OpenGL poor performace with instanced drawing I'm just started learning OpenGL and this is my first project besides tutorials. I'm trying to load a huge enginering model The data is structured in a way that I thought I could use instancing for very good performance, because many items are simple primitives (cylinder, torus, cones, etc) with different transformation matrices. So I structured my data this way Primitive 1 VAO VBO gt vertices VBO gt indices Instance 1.1 VBO gt object color VBO gt transformation matrix Instance 1.2 VBO gt object color VBO gt transformation matrix Instance 1.n VBO gt object color VBO gt transformation matrix Primitive n VAO VBO gt vertices VBO gt indices Instance n.1 VBO gt object color VBO gt transformation matrix Instance n.n VBO gt object color VBO gt transformation matrix The model has 50k unique primitives and 120k instances, so in general each primitive has 2 instances. But in practice, some have 10 and some have only 1. I end up with 50k VAOs and then call dlDrawElementsInstanced for each VAO. The model is being draw at only 3 fps. I gues it's because of the number of glDraw calls (50k for the triangles and 50k for the outlines). The shaders are very simple, not even lightning is being applied. To be sure of that I changed the way I organize the buffers I put everything in a single buffer, but to do that I had to pass the color and transformations matrices as vertex attributes to each vertex. I know this isn't right but I had to test if the problem was the number of glDraw calls. I couldn't even load the model this way because the buffers get way to big and I get out of memory. So I tested this theory on a smaller model that was taking 50ms to render in the instanced way. With a single VAO for everything and only a single glDrawElements call the model is taking less than 1ms to render. I know that putting everything in a single VAO and passing the trasnformations for every vertex is not the correct way of doing this. Now I also know that instancing isn't the tool for this due the very few intances for each mesh. So the question is, what would be the correct way to setup the buffers to minimize the number of glDraw calls? I think that it would be perfect to store all in a single VAO (so I could call glDrawElements a single time) but use something like the glVertexAttribDivisor used in instancing to inform the shaders when to use the next shaders. But not exactly because I had to manually inform when to use the next matrix, in way like glPrimitiveRestartIndex works. I'm using OpenGL 3.3


How to implement OpenGL triple buffering of buffer objects to avoid stalls? I'm trying to implement the triple buffering described here. The intent is to gain higher frame rate by avoiding waiting for glBufferSubData() to finish. My understanding is that this is how to implement triple buffer make 3 buffers with glGenBuffers() Current frame bind to buffer3 draw last frame bind to buffer1 glBufferSubData for all the vertices, keep track of their texture vertex count,blend function, etc Next frame bind to buffer 1 draw last frame (bind texture, blend func, glDrawArrays) and so on There doesn't seem to be any performance gain between this and doing glBufferSubData() and then immediately calling glDrawArrays(). Am I missing something or misunderstand how triple buffer should work? Also is there a way to know when glDrawArrays() stalls due to glBufferSubData() still not being finished?


LibGDX Shader files in assets Access is Denied I stored the glsl files in android gt assets gt shaders directory, but when I run the app, an error is displayed Error Gradle Execution failed for task ' android mergeDebugAssets'. Error java.io.FileNotFoundException ...android assets shaders (Access is denied) But the problem goes away if I put those files in assets root folder. Can I not store shader files in asset subdirectories? Using Gdx v1.9.3. EDIT The issue is not there when running on Desktop, but only on Android. Didn't check others. UPDATE Apparently the issue got resolved today. I didn't make any changes but it's working now!


Simplifying Camera Strafing I have a camera that follows the position and direction of the player. These are updated using spin and velocity. The velocity is updated like so auto velocity get velocity() velocity get acceleration().x get right() velocity get acceleration().y get up() velocity get acceleration().z get forward() set velocity(velocity) ... where acceleration is relative to the object, not the world. This is the first time I have used OpenGL and I am not sure if this is the best solution, but it does what I want. I was wondering if there is a better way to do this using OpenGL Mathematics (GLM). Additionally, this method works like a rocket, which is good for what I am trying to do, but if I want something more like a human, I have to change it to auto velocity get velocity() auto const y velocity.y get acceleration().y velocity get acceleration().x get right() velocity get acceleration().z get forward() velocity.y y set velocity(velocity) ... to prevent the player from being able to fly by looking up. Is there a way of simplifying this case, too? Acceleration is defined as switch (dir) case left return glm vec3( 1, 0, 0) case right return glm vec3( 1, 0, 0) case front return glm vec3( 0, 0, 1) case back return glm vec3( 0, 0, 1) case up return glm vec3( 0, 1, 0) case down return glm vec3( 0, 1, 0) default assert(false)


How to reduce image size without pixelation? I see lots of games with smooth edges characters and high res images, however when I try to reduce images to say 64x64 for my character I just get a pixelated mess. even if I start with a 64x64 canvas I get pixelated edges. Should I be scaling with OpenGL? or is there some technique perhaps with photoshop or pixen that I am unaware of?


JWJGL Multi threading to separate update and render Introduction I am currently designing a game in Java using the LWJGL 3.0, with Gradle. I have quite an advanced knowledge on multi threading, and I am aware how GLFW does doesn't implement multi threading from this guide. Currently, I have one class Updater with a loop for updating, and another class Renderer for rendering, each extending Runnable with their own loops and time calculations. Below is a diagram showing the structure of the classes and update and render methods. I have also set up a lock system, using the Java Lock class (again below). My Problem Despite setting each thread as the current context before each loop executes its window call, and setting the current context to null at the end, I still get the error Exception in thread "RENDERER" java.lang.IllegalStateException GLFW error 0x10008 WGL Failed to make context current The requested resource is in use. Any idea as to why? Been at this for a few hours now. Loop class private void threadLoop() try lock.lock() locked true loop() TPS catch (InterruptedException e) e.printStackTrace() finally lock.unlock() locked false Override public void run() init() long lastTime System.nanoTime() double ns SECOND (MAX TPS 2) double delta 0 long timer System.currentTimeMillis() while (running) long now System.nanoTime() delta (now lastTime) ns lastTime now while(delta gt 1) threadLoop() TPS delta if(System.currentTimeMillis() timer gt 1000) finalTPS TPS timer 1000 TPS 0 stop() Thread Manager public void update() if (window null) return window.setThread() window.update() window.nullThread() public void render() if (window null) return window.setThread() window.render() window.nullThread() Renderer Override protected void loop() if (state ! null) state.render() threadManager.intermediateCode() threadManager.render() Updater Override protected void loop() if (state ! null) state.update() threadManager.intermediateCode() threadManager.update() Window public void setThread() glfwMakeContextCurrent(getID()) public void nullThread() glfwMakeContextCurrent(NULL) public void render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glClearColor(0.0f, 0.3f, 0.8f, 0.0f) glfwSwapBuffers(ID) System.out.println("Rendered window") public void update() glfwPollEvents() System.out.println("Updated window")


Linear filter problem with diagonal lines on adjecent tiles I am quite new at using OpenGL GLSL. Basically, the project I am working on is my first 'real' experience with it. I do not know whether this is relevant, but I use libgdx for my project. Currently, I am trying to use the GL LINEAR filters to draw tile of my (tile) map (before I was using GL NEAREST without problems). My map contains diagonal roads (just simple lines in this example). A partial overview example of my map (using the nearest filter without corrections) With the GL NEAREST filter, initially I added a 1 pixel border, so the tiles were slightly overlapping and the diagonal roads were draw without the small gaps at the edges of the tiles. This does not work with the GL LINEAR filter, because I suppose that the overlapping parts are drawn twice, resulting in a darker 'blob' I tried to get rid of the blobs, by making the horizontal lines shorter, but there is always an irregularity, either a blob or an 'decrease of line width' (as seen in the diagonal part of the line). So I removed the 1 pixel additional border and have this as a result Now I am trying to fill in the 'gaps' by drawing the two triangular fillers like this but I can't get it completely right (this is the best I managed to get) I suppose it is virtually impossible to get this perfectly right by 'manually' drawing these triangles. Also, when looking at the third image, the lines at the 'edges' (that need to be filled) are very sharp. I suppose this is problematic..? So, my question is how does one solve this problem? Do I need to prepare modify my textures for this? Can I use a shader to fill the gaps automatically? Is manually filling the gaps with the triangles the way to go? Or is there some entirely different technique to have smooth diagonal lines that span multiple tiles?


Geometry shader questions? I had some questions on geometry shaders. Do directx geometry shaders offer anything over the opengl ones? What advantages does the official geometry shader implementation on opengl 3.2 have over the plug in for 2.0? Is the official one faster? What are the oldest cards which support opengl 3.2 and the geometry shaders on there? What are the oldest cards which support opengl 2.0 and the geometry shader plugin?


OpenGL Black rectangle in rendering texture I create textures (for example, I just fill the texture color), and render their. But, for some reason, to the upper edge added black rectangle. Screenshot var Textures array of GLuint procedure LoadTexture(const TextureID Byte var Texture GLuint) var w, h Cardinal Data PByteArray begin if TextureID 0 then begin w 512 h 512 end else begin w 128 h 64 end GetMem(Data, w h 3) if TextureID 0 then FillChar(Data , w h 3, 204) else FillChar(Data , w h 3, 102) glBindTexture(GL TEXTURE 2D, Texture) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexImage2D(GL TEXTURE 2D, 0, GL RGB8, w, h, 0, GL RGB, GL UNSIGNED BYTE, Data) FreeMem(Data, w h 3) Data nil end procedure glInit begin glEnable(GL TEXTURE 2D) SetLength(Textures, 2) glGenTextures(1, Textures 0 ) LoadTexture(0, Textures 0 ) glGenTextures(1, Textures 1 ) LoadTexture(1, Textures 1 ) glClearColor(1, 1, 1, 0) glShadeModel(GL SMOOTH) glClearDepth(1) glDisable(GL DEPTH TEST) glHint(GL PERSPECTIVE CORRECTION HINT, GL NICEST) glViewport(0, 0, 800, 600) glMatrixMode(GL PROJECTION) glLoadIdentity glOrtho(0, 800, 600, 0, 0, 1) glMatrixMode(GL MODELVIEW) glLoadIdentity end procedure glDraw begin glClearColor(1, 1, 1, 0) glClear(GL COLOR BUFFER BIT or GL DEPTH BUFFER BIT) glBindTexture(GL TEXTURE 2D, Textures 0 ) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f(0, 0) glTexCoord2f(1, 0) glVertex2f(512, 0) glTexCoord2f(1, 1) glVertex2f(512, 512) glTexCoord2f(0, 1) glVertex2f(0, 512) glEnd glBindTexture(GL TEXTURE 2D, Textures 1 ) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f(128, 64) glTexCoord2f(1, 0) glVertex2f(256, 64) glTexCoord2f(1, 1) glVertex2f(256, 128) glTexCoord2f(0, 1) glVertex2f(128, 128) glEnd end


Wireframe shader sometimes won't render parts depending on camera rotation I'm trying to make a stylized wireframe shader for a game using this method, but it seems to be conflicting with my character controller. Here's some images to better show what's going on https imgur.com a f48F3lN Basically, as I look around, some lines will disappear and reappear. It might have something to do with culling but the face is still visible, so theoretically shouldn't all the vertices still be rendered? It would also help if you knew of a better method for doing this as well. If it helps, I'm using OpenGL with c , and my shader code is functionally the same as what I linked to.


How can I efficiently render lots of 2D quads? I have lots of 2D quads. I write their local vertex position info to a buffer (accompanied with a world transform matrix) which gets sent to the render thread. I then pass the world transform matrix as a uniform into the vertex shader which applies itself to each vertex and works fine. I however have to make a call to glDrawElements() for each quad I want to render because each one has a different world transform. What is the most efficient way for me to render all of these quads? Should I do what I'm already doing, or should I calculate the world position for each vertex on the CPU before I write them to the buffer, so I can attempt to batch more quads into a single glDrawElements() call? Or is there another approach?


Qt opengl glTexImage2D in a widget I was doing an OpenGL display, where I render in an opengl context (GLUT). But now I would like to integrate it into a big project that does not use the Qt OpenGL API at all (QGLWidget, QOpenGLWidget, ). So I would have to display on QWidget for example using the function glTexImage2D () because it can take a Qimage input ((GLvoid ) Qimage.bits ())


How to use modern OpenGL for 2D games? I've found a plethora of "modern" OpenGL (3.0 ) tutorials for 3D, but I have found next to nothing when looking for information on how to use it for 2D game development. How can I get started using OpenGL for 2D gamedev? Specifically, I'm interested in getting answers to the following topics How should I set up my various matrices for orthographic projection? Are shaders as heavily used in 2D applications as in 3D ones? If so, what is their purpose in the 2D setting? How should I handle the massive number of textures obviously required for a 2D game? I apologize for the relatively broad question, but I've spent a long time searching and I've found very little useful information that applies to modern OpenGL.


OpenGL picking performance ray casting vs. color picking I am curious of how the performance of color picking compares to ray casting. I am looking at the scenario when the mouse is clicked which means only then the scene is rendered in a backbuffer for color picking or ray cating has to be applied. Note I have found this question which unfortunatly does not give any indication.


What is actually drawn when glDrawArrays and glDrawElements are called? In my journey out of immediate mode I've come across a snag that I haven't been able to find a decent answer for in any tutorial or API, namely Which data structures are actually invoked when I make a call to a glDraw function in OpenGL3.3 ? For example, if I want to draw two 3D models and I've put their vertex data in two different VBO's, does invoking glDrawArrays draw everything set under the current VAO? Or does it only draw the currently bound VBO sampling from the currently bound texture? I basically understand VAO's and VBO's conceptually but its down to implementation that I'm running into problems, it's a big jump to go from the "stability" of immediate mode to the a synchronicity of modern OpenGL.


rotating 3D object around the center I have object moving from A to B on x axis and there is no translation of object apart from it. Now, while moving, i want to rotate it around y axis and the motion should change accordingly, i mean if i rotate it right when moving from x to x axis, it should move towards near plane. I have variable in gltranslatef which is modified in the loop after that i have glscalef to scale whole object which is made of hierarchical structure. Now i tried following code to achieve the expected result but its not working properly glTranslatef(move, 0, 0) If I comment these 3 lines, it does not affect the output glTranslatef( move, 0, 0) glRotatef(rotate,0,1,0) glTranslatef(move, 0, 0) glScalef(0.2, 0.2, 1.0)


Skybox texture artifact on edge I have strange problem with drawing skybox texture on Mac. On iPhone everything is going fine. I have tried to change near and far planes value with no success. It is a skybox of six textures, and for every texture I set this glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) What could be the problem? Screenshot EDIT I have tried to set background color to red, to ensure if it is bleeding through the texture I have also tried to change coords of the texture to this float err corr 0.5 TEXTURE SIZE GLfloat vertices 24 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, And the box is drawn in this order GLubyte indices 14 0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1 SOLUTION The solution is to set GL CLAMP TO EDGE for the cubemap itself! glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE)


How can I make a transparent hole with shaperenderer using stencil masking in libgdx? I'm making a 2d game, where I need a resizeable, moveable rectangle outline. I'm trying to use stencil masking to do it by cutting a hole in a solid rectangle, and I thought this would help How can I add a transparent overlay to a UI in libGDX? But all I get is a solid box. Here's my code Gdx.gl.glClear(GL STENCIL BUFFER BIT) Gdx.gl.glColorMask(false, false, false, false) Gdx.gl.glDepthMask(false) Gdx.gl.glEnable(GL20.GL STENCIL TEST) Gdx.gl.glStencilFunc(GL20.GL ALWAYS, 0x1, 0xffffffff) Gdx.gl.glStencilOp(GL REPLACE, GL REPLACE, GL REPLACE) shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.box(cubby.xpos 5 , cubby.ypos 5, 0, cubby.size 10, cubby.size 10, 0) shapeRenderer.end() shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) Gdx.gl.glColorMask(true, true, true, true) Gdx.gl.glDepthMask(true) Gdx.gl.glStencilFunc(GL NOTEQUAL, 0x1, 0xffffffff) Gdx.gl.glStencilOp(GL KEEP, GL KEEP, GL KEEP) shapeRenderer.box(cubby.xpos, cubby.ypos,0,cubby.size, cubby.size, 0) shapeRenderer.end() Gdx.gl.glDisable(GL20.GL STENCIL TEST)


What resources are available for Mac OS game development? Are there are any modern resources on how to develop games for Mac OS? I suppose this would include objective c, cocoa and opengl 3 . The book Beginning Mac OS X Game Development with Cocoa looks very promising but isn't out until early next year.


glRotatef rotation never applied to 3d cube I have a floating cube that I want to rotate around the Y axis. The cube renders fine, the proper size, the proper coordinate, the proper texture faces, etc. However, the rotation is never applied. My update logic calculates a new rotation value, between 0 and 360. Set the coordinates, rotate Y axis GL11.glTranslatef(x,y,z) GL11.glRotatef(rotation, 0, 1f, 0) Each cube face rendered, etc... GL11.glColor3f( ... GL11.glTexCoord2f( .. GL11.glVertex3f .. No matter what combination I've tried, the cube never changes it's rotation. Update Per a comment, I was using glBegin outside the glRotatef and the comment advised that I use glPush Pop GL11.glPushMatrix() GL11.glTranslatef(x,adjY,z) GL11.glRotatef(rotation, 0f, 1f, 0) GL11.glPopMatrix() GL11.glBegin(GL11.GL QUADS) block.renderVertex(x,adjY,z,1,null,0.1f) GL11.glEnd()


Using depth texture for depth testing I was wondering if it is possible to render my scene onto a depth texture then using that texture for depth testing in another pass. I have an idea to that in shaders, but is that possible hardware side?


Synchronization between several glDispatchCompute with same SSBOs Let's say I have one compute shader A which writes to an SSBO, and then a second compute shader B which reads from the same SSBO. Do I need to do anything special to ensure that A has finished executing before B starts?


How do I implement a quaternion based camera? UPDATE The error here was a pretty simple one. I have missed a radian to degrees conversion. No need to read the whole thing if you have some other problem. I looked at several tutorials about this and when I thought I understood I tried to implement a quaternion based camera. The problem is it doesn't work correctly, after rotating for approx. 10 degrees it jumps back to 10 degrees. I have no idea what's wrong. I'm using openTK and it already has a quaternion class. I'm a noob at opengl, I'm doing this just for fun, and don't really understand quaternions, so probably I'm doing something stupid here. Here is some code (Actually almost all the code except the methods that load and draw a vbo (it is taken from an OpenTK sample that demonstrates vbo s)) I load a cube into a vbo and initialize the quaternion for the camera protected override void OnLoad(EventArgs e) base.OnLoad(e) cameraPos new Vector3(0, 0, 7) cameraRot Quaternion.FromAxisAngle(new Vector3(0,0, 1), 0) GL.ClearColor(System.Drawing.Color.MidnightBlue) GL.Enable(EnableCap.DepthTest) vbo LoadVBO(CubeVertices, CubeElements) I load a perspective projection here. This is loaded at the beginning and every time I resize the window. protected override void OnResize(EventArgs e) base.OnResize(e) GL.Viewport(0, 0, Width, Height) float aspect ratio Width (float)Height Matrix4 perpective Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect ratio, 1, 64) GL.MatrixMode(MatrixMode.Projection) GL.LoadMatrix(ref perpective) Here I get the last rotation value and create a new quaternion that represents only the last rotation and multiply it with the camera quaternion. After this I transform this into axis angle so that opengl can use it. (This is how I understood it from several online quaternion tutorials) protected override void OnRenderFrame(FrameEventArgs e) base.OnRenderFrame(e) GL.Clear(ClearBufferMask.ColorBufferBit ClearBufferMask.DepthBufferBit) double speed 1 double rx 0, ry 0 if (Keyboard Key.A ) ry speed e.Time if (Keyboard Key.D ) ry speed e.Time if (Keyboard Key.W ) rx speed e.Time if (Keyboard Key.S ) rx speed e.Time Quaternion tmpQuat Quaternion.FromAxisAngle(new Vector3(0,1,0), (float)ry) cameraRot tmpQuat cameraRot cameraRot.Normalize() GL.MatrixMode(MatrixMode.Modelview) GL.LoadIdentity() Vector3 axis float angle cameraRot.ToAxisAngle(out axis, out angle) THIS IS WHAT I DID WRONG I NEED TO CONVERT FROM RADIANS TO DEGREES BEFORE GL.Rotate(angle, axis) AFTER GL.Rotate(angle (float)180.0 (float)Math.PI, axis) GL.Translate( cameraPos) Draw(vbo) SwapBuffers() Here are 2 images to explain better I rotate a while and from this it jumps into this Any help is appreciated. Update1 I add these to a streamwriter that writes into a file sw.WriteLine("camerarot X 0 Y 1 Z 2 W 3 L 4 ", cameraRot.X, cameraRot.Y, cameraRot.Z, cameraRot.W, cameraRot.Length) sw.WriteLine("ry 0 ", ry) The log is available here http www.pasteall.org 26133 text. At line 770 the cube jumps from right to left, when camerarot.Y changes signs. I don't know if this is normal. Update2 Here is the complete project.


Looking for specific "textured quad" openGL tutorial in c I'm new to openGL and I've been googling around for the old and simple textured quad tutorial in openGL but I haven't been able to find one that suits my needs. OpenGL3.X compatible OpenGL ES 2.0 compatible AND Only uses core openGL library (no GLUT, GLEW...) I'm creating the window and the openGL context with SDL2. I only need the most basic stuff to draw quads. I'm not interested in any of the new OpenGL features, just in compatibility and cross platformness (Windows, OSX, Linux, Android and iOS).


What are the alternatives to OpenGL arrays for deferred rendering? I'm trying to build a deferred rendering technique in an OpenGL engine, but I can't figure how I could get more than the limit of 32 lights. I use an array in my shader, feed light properties into this array then loop through it and compute lightning, but I can't get more than 32 items into my array. What is a better alternative to this?


Batching and Z order with Alpha blending in a 3D world I'm working on a game in a 3D world with 2D sprites only (like Don't Starve game). (OpenGL ES2 with C ) Currently, I'm ordering elements back to front before drawing them without batch (so 1 element 1 drawcall). I would like to implement batching in my framework to decrease draw calls. Here is what I've got for the moment Order all elements of my scene back to front. Send order list of elements to the Renderer. Renderer look in his batch manager if a batch exist for the given element with his Material. Batch didn't exist create a new one. Batch exist for element with this Material Add sprite to the batch. Compute big mesh with all sprite for each batch (1 material type 1 batch). When all batches are ok, the batch manager compute draw commands for the renderer. Renderer process draw commands (bind shader, bind textures, bind buffers, draw element) Image with my problem here But I've got some problems because objects can be behind another objects inside another batch. How can I do something like that?


Quaternion rotation around center, undefined behavior Here's my code vec4 qx, qy, qz mat4 mx, my, mz rotating using quaternions glm quat(qx, to radians(a gt rx), 1.0f, 0.0f, 0.0f) glm quat(qy, to radians(a gt ry), 0.0f, 1.0f, 0.0f) glm quat(qz, to radians(a gt rz), 0.0f, 0.0f, 1.0f) turning the quaternions into matrices glm quat mat4(qx, mx) glm quat mat4(qy, my) glm quat mat4(qz, mz) mat4 trans 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 mat4 rot 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 mat4 final combining the rotations into one. glm mat4 mulN((mat4 ) amp mx, amp my, amp mz , 3, rot) translating the trans matrix. glm translate(trans, (vec3) a gt x, a gt y, a gt z ) finally combining the translation with the rotation into one. glm mat4 mul(trans, rot, final) My desired behavior is that the object rotates around its center, but here is what happens instead So , it seems that my object is rotating around some weird other undefined point. I have no idea why this happens. Any ideas? Thank you.


Combine textures with coordinates Is it possible to add one texture to another texture, at specific coordinates? Like if I want to add a small texture(16x16) to big texture (1368 x 768) with coordinates ( 100, 100) so the small texture goes to specific coordinates (100, 100 ).


3D Studio MAX dxf model to OpenGL and DirectX Main Question I saw this Loading and Animating MD5 Models with OpenGL an old post explaining .md5mesh .md5anim files. Is there any similar alternate mechanisms? Additional Questions 1.) Is there an open source tool or a Plug in for 3ds max to convert a .DXF file to such files which can be used in 3D OpenGL DirectX game programming. 2.) If I am developing a game in this approach how to make these model files encrypted and make big single file which contains all this file, so that the user cannot crack hack it? 3.) If I am providing an update via an online gaming server, then how to I update this models and keep it encrypted again?


How to calculate normal from normal map in world space? (OpenGL) I'm trying to do normal mapping in a deferred renderer and I'm stuck on how to implement normal maps. I have a bool that passes whether or not to use a normal mapped value and thus, whether to calculate the TBN matrix. My vertex code for the geometry pass looks as follows version 410 core layout (location 0) in vec3 aPos layout (location 1) in vec3 aNormal layout (location 2) in vec2 aTexCoords layout (location 3) in vec3 aTangent Optional Texture coordinates layout (location 4) in vec3 aBitangent Optional Texture coordinates out vec3 FragPos out vec2 TexCoords out vec3 Normal out mat3 TBN uniform mat4 model uniform mat4 view uniform mat4 projection uniform bool hasNormalMap void main() vec4 worldPos model vec4(aPos, 1.0) FragPos worldPos.xyz TexCoords aTexCoords Normal transpose(inverse(mat3(model))) aNormal if(hasNormalMap) vec3 T normalize(vec3(model vec4(aTangent, 0.0))) vec3 N normalize(vec3(model vec4(aNormal, 0.0))) re orthogonalize T with respect to N T normalize(T dot(T, N) N) then retrieve perpendicular vector B with the cross product of T and N vec3 B cross(N, T) mat3 TBN mat3(T, B, N) gl Position projection view worldPos Here is where I am confused In my calculation, I multiplied T and N by the model matrix which should have moved it into world space. Now transposing (T,B,N) should move me back into model space (I think, I'm not sure). In the fragment shader how do I use the TBN to calculate the normal in world space? If there are better approaches, they are welcome. Thank you. Update I removed the transposing of the TBN as there's no reason to transform into tangent space if we want to pass it in world space. Now that we have the TBN matrix in the fragment shader, how do we apply it so that the normal is the correct value for lighting? Currently I've done version 410 core layout (location 0) out vec3 gPosition layout (location 1) out vec3 gNormal layout (location 2) out vec4 gAlbedoSpec in vec2 TexCoords in vec3 FragPos in vec3 Normal in mat3 TBN struct Material sampler2D diffuseMap sampler2D specularMap sampler2D normalMap float shininess uniform Material material uniform bool hasNormalMap void main() store the fragment position vector in the first gbuffer texture gPosition FragPos also store the per fragment normals into the gbuffer gNormal normalize(Normal) if(hasNormalMap) gNormal texture(material.normalMap, TexCoords).rgb TBN gNormal normalize(gNormal) and the diffuse per fragment color gAlbedoSpec.rgb texture(material.diffuseMap, TexCoords).rgb store specular intensity in gAlbedoSpec's alpha component gAlbedoSpec.a texture(material.specularMap, TexCoords).r but that doesn't feel right. I imagine that I would transform the sampled value from the normal map by the TBN matrix to get it in world space. Am I missing something?


OpenGL lighting with dynamic geometry I'm currently thinking hard about how to implement lighting in my game. The geometry is quite dynamic (fixed 3D grid with custom geometry in each cell) and needs some light to get more depth and in general look nicer. A scene in my game always contains sunlight and local light sources like lamps (point lights). One can move underground, so sunlight must be able to illuminate as far as it can get. Here's a render of a typical situation The lamp is positioned behind the wall to the top, and in the hollow cube there's a hole in the back, so that light can shine through. (I don't want soft shadows, this is just for illustration) While spending the whole day searching through Google, I stumbled on some keywords like deferred rendering, forward rendering, ambient occlusion, screen space ambient occlusion etc. Some articles tutorials even refer to "normal shading", but to be honest I don't really have an idea to even do simple shading. OpenGL of course has a fixed lighting pipeline with 8 possible light sources. However they just illuminate all vertices without checking for occluding geometry. I'd be very thankful if someone could give me some pointers into the right direction. I don't need complete solutions or similar, just good sources with information understandable for someone with nearly no lighting experience (preferably with OpenGL).


2D pixels change size when scrolling I'm working on a 2D side scroller, OpenGL, pixel art. And I'm having trouble getting the pixels to remain square when scrolling the camera. By that I mean, when scrolling the camera at low speed when you have tile pixels being draw at 2x2 scale, you can see some pixels become 3x2 in size rather than 2x2. I've tried different ways of calculating the size of the orthographic projection in order to get the pixels sized correctly, and while they do usually appear correct when stationary, they always wobble while scrolling. Here is my latest attempt at calculating window size for the orthographic projection define TILE SIZE 32 Each tile is 32x32 define TILE MIN HEIGHT 10 Adjust pixel size to fit at east 10 tiles vertically in the window float windowRatio (float)window gt width (float)window gt height int pixelSize window gt height TILE SIZE TILE MIN HEIGHT float tileHeight (float)window gt height (pixelSize TILE SIZE) gameState gt windowTileWidth tileHeight windowRatio TILE SIZE gameState gt windowTileHeight tileHeight TILE SIZE window gt orthoProjection matrix44 createOrthographic2D( gameState gt windowTileWidth, gameState gt windowTileHeight ) So far, I've tried all of these in an attempt to eliminate the wobble Calculate orthographic projection as above, to fix at least 10 tiles vertically, adjusting projection size to fit window ratio. Calculate orthographic projection to exactly fit a 20x10 tile scene, scaling pixels to fit window. Render the scene to a 1 1 scale framebuffer, then blit that buffer to the window to scale it up to desired pixel size. Disable offsetting of texture coordinates (I draw tiles from a texture atlas, and so offset the coordinates by 0.001 inside each quad to eliminate bleed from surrounding textures). None of these have eliminated the wobbling. Sometimes it is extremely subtle, but still present when examining the movement closely. What is the correct way to draw a 2D image to the scree with perfect square pixel accuracy, at a given pixel size?


Can't use SFML sprite drawing and OpenGL rendering at the same time I'm using some SFML built in functions to draw sprites and text as an overlay on top of some OpenGL rending in an SFML RenderWindow. The opengl rendering appears fine until I add the code to draw the sprites or text. The sprite or text drawing causes the OpenGL stuff to disappear. The follow code show what I'm trying to do sf RenderWindow window(sf VideoMode(viewport.width,viewport.height,32), "SFML Window") glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0,viewport.width,0,viewport.height,0,1) while (window.pollEvent(Event)) event handling... begin drawing glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glBegin(GL TRIANGLES) glColor3f(col.x,col.y,col.z) for(int i 0 i lt 3 i ) glVertex2f(pos.x verts i .x,pos.y verts i .y) glEnd() adding this line causes all the previous opengl triangles not to appear window.draw("Sometext") window.display()


How to only render fragments with Z from 0 to 1 in OpenGL? I have been using OpenGL for a year now, but I just recently found out that OpenGL only clips vertices when the absolute value of the x,y or z coordinate is less than the absolute value of w coordinate. Previously I had assumed that the z coordinate would have to be 0 lt z lt w to be rendered. Is there any way to clip vertices with z less than 0, without a performance hit? I am using OpenGL 4.4


How to create a 2D overlay over a 3D game? (LWJGL OpenGL) GameDev! I would like to create a 2D overlay over a 3D world, using LWJGL (Java version of OpenGL), to show information to the player, for example, a chat box, health bar, selected cannonball type, etc. Currently the code I have is this (Taken from several sources on the internet) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glEnable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() glOrtho(0.0f, Display.getWidth(), Display.getHeight(), 0.0f, 0.0f, 1.0f) GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() glDisable(GL DEPTH TEST) glDisable(GL CULL FACE) glDisable(GL TEXTURE 2D) glDisable(GL LIGHTING) glDisable(GL DEPTH TEST) glDisable(GL CULL FACE) glDisable(GL BLEND) glDisable(GL TEXTURE 2D) glDisable(GL LIGHTING) glBegin(GL QUADS) glColor3f(1, 1, 1) glVertex2f(0, 0) glVertex2f(1, 1) glVertex2f(1, 0) glVertex2f(0, 1) glEnd() GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() glPopMatrix() glEnable(GL DEPTH TEST) glEnable(GL CULL FACE) glEnable(GL BLEND) glEnable(GL TEXTURE 2D) glEnable(GL LIGHTING) glEnable(GL DEPTH TEST) glEnable(GL CULL FACE) glEnable(GL TEXTURE 2D) glEnable(GL LIGHTING) glDisable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() Reset The Projection Matrix GLU.gluPerspective(45.0f, ((float) Display.getWidth() (float) Display.getHeight()), 0.1f, 5000.0f) Calculate The Aspect Ratio Of The Window GL11.glMatrixMode(GL11.GL MODELVIEW) glLoadIdentity() However this does not show a 2D scene at all! I would appreciate it if anybody could help me. Thanks!


C Freetype advance X problem I'm currently working on a font rendering system for my OpenGL based engine. I sure got something to work, but the only thing I still have problems with, is the horizontal advance! This is what it spits out, obviously not correct. If I understood correct from the documentation and some other threads, this is the procedure to draw a string set current drawing position to (0, 0) draw first character move drawing position in the x for advance.x draw second character move drawing position in the x for next face glyph advance.x ... repeat Is that correct? If not, what am I doing wrong? I think its worth to say that I render every character as a texture!


Why doesn't the y Axis work with SuperBible frame reference or GluLookAt I'm currently trying to understand how to use the GLFrame Class in the superbible book, and acording to the 4th edition of the book, the camera matrix derived from the Frame of reference class should work the same as GluLookAt When I add these lines cameraFrame.SetForwardVector( 0.5f, 0.0f, 0.5f) cameraFrame.Normalize() The camera looks in the correct direction, yaw at 45 Degrees (Am I doing that right!) However when I add this cameraFrame.SetForwardVector(0.0f, 0.5f, 0.5f) The camera just looks as if it was set to (0.0f, 0.0f, 1.0f) Why is this! It's been driving me mad for three days. Maybe I'm not passing in the vectors correctly, but I'm not sure how to pass in x,y 360 degrees for the look at (forward) location vector. Do the vectors have to be normalized before passing them in? Eventually I hope to do full mouse look (FPS style) , but for now just understanding why I can't make the camera simply pitch up would be a good start. Thansk! Here is the code in situ. Called to draw scene void RenderScene(void) Color values static GLfloat vFloorColor 0.0f, 1.0f, 0.0f, 1.0f static GLfloat vTorusColor 1.0f, 0.0f, 0.0f, 1.0f static GLfloat vSphereColor 0.0f, 0.0f, 1.0f, 1.0f Time Based animation static CStopWatch rotTimer float yRot rotTimer.GetElapsedSeconds() 60.0f Clear the color and depth buffers glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) Save the current modelview matrix (the identity matrix) modelViewMatrix.PushMatrix() M3DMatrix44f mCamera My Code cameraFrame.SetForwardVector( 0.5f, 0.5f, 0.5f) cameraFrame.Normalize() End of my code cameraFrame.GetCameraMatrix(mCamera) modelViewMatrix.PushMatrix(mCamera) Transform the light position into eye coordinates M3DVector4f vLightPos 0.0f, 10.0f, 5.0f, 1.0f M3DVector4f vLightEyePos m3dTransformVector4(vLightEyePos, vLightPos, mCamera) Draw the ground shaderManager.UseStockShader(GLT SHADER FLAT, transformPipeline.GetModelViewProjectionMatrix(), vFloorColor) floorBatch.Draw() for(int i 0 i lt NUM SPHERES i ) modelViewMatrix.PushMatrix() modelViewMatrix.MultMatrix(spheres i ) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor) sphereBatch.Draw() modelViewMatrix.PopMatrix() Draw the spinning Torus modelViewMatrix.Translate(0.0f, 0.0f, 2.5f) Save the Translation modelViewMatrix.PushMatrix() Apply a rotation and draw the torus modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vTorusColor) torusBatch.Draw() modelViewMatrix.PopMatrix() "Erase" the Rotation from before Apply another rotation, followed by a translation, then draw the sphere modelViewMatrix.Rotate(yRot 2.0f, 0.0f, 1.0f, 0.0f) modelViewMatrix.Translate(0.8f, 0.0f, 0.0f) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor) sphereBatch.Draw() Restore the previous modleview matrix (the identity matrix) modelViewMatrix.PopMatrix() modelViewMatrix.PopMatrix() Do the buffer Swap glutSwapBuffers() Tell GLUT to do it again glutPostRedisplay()


Using full resolution of depth buffer for 2D rendering I'm working on a front to back renderer for a 2D engine using an orthographic projection. I want to use the depth buffer to avoid overdraw. I have a 16 bit depth buffer, a camera at Z 100 looking at Z 0, zNear is 1, and zFar is 1000. Each sprite rendered sets its Z co ordinates to increasingly distant values, allowing depth test to skip rendering anything which is underneath. However I'm aware the way Z positions end up with Z buffer values is non linear. I want to make use of the full resolution of the 16 bit depth buffer, i.e. allowing 65536 unique values. So for every sprite rendered, I want to increment the Z position to the next position to correlate to the next unique depth buffer value. In other words I want to turn an incrementing index (0, 1, 2, 3...) of the sprite being drawn in to the appropriate Z position for each sprite to have a unique depth buffer value. I'm not sure of the maths behind this. What is the calculation to do this? Note I'm working in WebGL (basically OpenGL ES 2), and I need to support a wide range of hardware, so while extensions like gl FragDepth might make this easier, I can't use it for compatibility reasons.


What is the difference between OpenGL, SDL, DirectX, GLFW, GLUE? I have not work with graphics yet but I'd like to know its concepts at some high level overview. I was told that OpenGL and DirectX are somehow programmed into my graphics card, and I can use GLFW, SDL etc. to get access to those and manipulate them, by creating kind of different graphics objects. Analogy OpenGL programming language SDL framework Please, correct me politely.


Changing player color without multiple player bitmaps Possible Duplicate How to colorize certain parts of a model like RTS games have those team colors? Ok, so here is my current situation. I have a player model, fully UV mapped, and textured. At first I made multiple bitmaps for the character representing multiple colors for each team in the game. (red, blue, green, yellow, etc) Well, as my player count build up, space lowers. So I needed to make a new method of keeping the game effecient, clean, and fast. So I thought of the idea of having a color mask (alpha map covering the areas to be colored). I am using OpenGL, and I just have NO idea on where to begin! So I ask you, are there any libraries? methods? anything that could help me do this?


Would it perform faster to split calculation between vertex and fragment shaders? Assuming the total amount of computation would be the same (at least as far as my code goes), would there be any performance increase in splitting the calculation and using separate vertex and fragment shaders vs. doing all the calculations in just a fragment shader? In my use case, I would not be using vertex shaders as they are typically intended (so, not processing actual vertices). I just thought if the GPU hardware is set up such that the pipeline is expected to be used, would it be better to take advantage of that, or would it be just as fast to put it all in a fragment shader. Conceptually, it would be simpler to just use the fragment shader. Note, that I do need a lot of data going to the fragment shader that is updated every frame (eg. texture buffer object).


GLSL, all in one or many shader programs? I am doing some 3D demos using OpenGL and I noticed that GLSL is somewhat "limited" (or is it just me?). Anyway I have many different types of materials. Some materials have ambient and diffuse color, some materials have ambient occlusion map, some have specular map and bump map etc. Is it better to support everything in one vertex fragment shader pair or is it better to create many vertex fragment shaders and select them based on currently selected material? What is the usual shader strategy in OpenGL or D3D?


Bind render result to texture id I want to save the result screen of the rendering and then apply another shader on that result, the typical way is to read the screen using glReadPixels and then buffer that image to gpu and then apply my effect, so is there a way to bind the screen result to a texture id directory in gpu, instead of retrieving it back to CPU and then buffer it to GPU ?


How would I setup fog to follow a players coordinates? I'm wondering if its possible to setup a fog to a player's coordinates (where there is fog around the player to make it more third person) the main reason I ask this is because I have my player more towards the top right corner of the screen Here's some code that can give you a guide on what im doing glEnable(GL FOG) GLfloat FogColor 0.8,0.8,0.8,1.0 glFogfv(GL FOG COLOR,FogColor) glFogi(GL FOG MODE,GL LINEAR) glFogf(GL FOG START,30) glFogf(GL FOG END,) glHint(GL FOG HINT,GL NICEST) and I want the fog to follow a player with a position as said in posX,posY,posZ If anyone can turn this into some example code that would be very helpful, thanks If this is not possible then how would I setup the fog to be around a certain position of the camera, like show on the top right corner of the camera instead of the center? Here's a picture of the game screen so you can see what im talking about


Speed of procedural geometries I'm evaluating solutions for creating a VR videogame that should run on cellphones. The assets will be streamed from our servers and that could be a problem on limited capabilities devices. Since the geometries are not going to be too complex (mostly boxes and wardrobes) I was thinking about procedurally generating them. Is generating geometries procedurally usually faster or slower than just streaming a bunch of vertex data?


How to properly delete unwanted models I am implementing bullets into my game, and each bullet has a lifetime. Whenever the bullet has existed for a set amount of time or collides with an object, the bullet should be deleted. I implemented the timer properly and whenever the bullet reaches the end of its life, it gets deleted. The problem occurs whenever I shoot another bullet. This instantly causes a crash with the code Exception thrown at 0x044765D7 (nvoglv32.dll) in gravityGame.exe 0xC0000005 Access violation reading location 0x00000000. After some research, I've found that this usually means that I am trying to render something that is a nullptr. My thinking is that I am not deleting the previous bullet properly and this affects the new one. A single bullet object is created on startup, and every new bullet is copied using the following line of code std shared ptr lt Bullet gt bullet std make shared lt Bullet gt ( std dynamic pointer cast lt Bullet gt (modelsLoaded.at(i))) The reason for the dynamic pointer cast is because it is in a vector of its base class that it inherits from. Whenever the bullet needs to get deleted, it is erased from the bullets vector using bullets.erase(bullets.begin() index) and the object it is pointing to should go out of scope, there is nothing else pointing to it. I feel like somehow having that object getting deleted has an adverse effect on the other bullets in the vector, but I do not know how. A new object is created and all the data from the original bullet gets copied over. How could deleting a copy of an object mess with the other copied objects? The functions to create, and render the models are below. Generate Model Function binds id glGenBuffers(1, amp VBO) glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp EBO) glGenTextures(1, amp texture) glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, verticesSizeTexture 8 sizeof(float), verticesTexture, GL STATIC DRAW) position attribute glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )0) glEnableVertexAttribArray(0) color attribute glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(3 sizeof(float))) glEnableVertexAttribArray(1) glBindBuffer(GL ELEMENT ARRAY BUFFER, EBO) glBufferData(GL ELEMENT ARRAY BUFFER, indicesSizeTexture 4, indicesTexture, GL STATIC DRAW) texture glBindTexture(GL TEXTURE 2D, texture) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(6 sizeof(float))) glEnableVertexAttribArray(2) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) Rendering Function unsigned int transformLoc glGetUniformLocation(shader gt ID, quot location quot ) glUniformMatrix4fv(transformLoc, 1, GL FALSE, glm value ptr(trans)) glBindTexture(GL TEXTURE 2D, texture) glBindVertexArray(VAO) glDrawElements(GL TRIANGLES, indicesSizeTexture, GL UNSIGNED INT, 0) glBindVertexArray(0) Destructor glDeleteVertexArrays(1, amp VAO) glDeleteBuffers(1, amp VBO) glDeleteBuffers(1, amp EBO) Update After removing the contents of the destructor, the problem goes away. However, I would like to have some sort of destructor to allow for the proper freeing of memory.


Create a white background for the texture and then blend using GLSL I have a transparent png texture and I'd like to create a white background and then blend this on top of that. Is this possible using just GLSL? I can't multiply, add or mix colors because I don't want to overlay the color white. I want it to be in the background of the texture. I can achieve what I want by creating 2 objects with the exact same dimensions and position, set the color of the object behind to white and the object in the front to the transparent texture. But this seems less than ideal to me. Any suggestions will be much appreciated!


Local shape color blending I am trying to implement this in Unity 4 Pro. But I am stuck in the blending part. I don't understand how you could blend multiples textures colors using multiples volumes on an object. How could you access those volumes in the shader and check for "collision"? It's seems to be very similar to vertex pixel lighting. But maybe I am wrong. Here is the simple effect I am trying to create.


Converting normalized device coordinates to world space coordinates flipping my sprites I'm trying to convert my game's camera system to use world space coordinates rather than OpenGL's default normalized device coordinates, however in doing so my sprites are being rendered improperly as you will see in the image below. Using GLM as my math library I have created a 4x4 orthographic matrix with the following code m orthoMatrix glm ortho(0.0f, (float) m screenWidth, (float) m screenHeight, 0.0f) I am then performing some translations (and scaling if by chance that is messing with anything) with the following code (m cameraMatrix is a 4x4 matrix) vec3 translation( m position.x, m position.y, 0.0f) m cameraMatrix glm translate(m orthoMatrix, translation) vec3 scale(m scale, m scale, 0.0f) m cameraMatrix glm scale(mat4(1.0f), scale) m cameraMatrix m scale is a float currently with my testing at value 1.0f. m position is a vec2 where in the image, the sprite on the right has values (0, 0) and the sprite on the left as values (screen width 2, 20). The issue, as you will notice, is that the sprites are rendered upside down, and I can't seem to fix it without getting rid of my translation math and going back to normalized coordinates.


Beginner question about vertex arrays in OpenGL Is there a special order in which vertices are entered into a vertex array? Currently I'm drawing single textures like this glBindTexture(GL TEXTURE 2D, texName) glVertexPointer(2, GL FLOAT, 0, vertices) glTexCoordPointer(2, GL FLOAT, 0, coordinates) glDrawArrays(GL TRIANGLE STRIP, 0, 4) where vertices has four "xy pairs". This is working fine. As a test I doubled the sizes of the vertices and coordinates arrays and changed the last line above to glDrawArrays(GL TRIANGLE STRIP, 0, 8) since vertices now contains eight "xy pairs". I do see two textures (the second is intentionally offset from the first). However the textures are now distorted. I've tried passing GL TRIANGLES to glDrawArrays instead of GL TRIANGLE STRIP but this doesn't work either. I'm so new to OpenGL that I thought it's best to just ask here ) Cheers!


Rotate an image and get back to its original position opengles glkit I need to rotate an image in opengles GLkit and get it back to its original position in GLkit. rotation 5 modelViewMatrix GLKMatrix4Rotate( modelViewMatrix, GLKMathDegreesToRadians(5), 1, 0, 0) modelViewMatrix GLKMatrix4Rotate( modelViewMatrix, GLKMathDegreesToRadians(rotation), 1,0,0) I need to move it in x axis for certain amount and getting back to its original position from where it started. How should i do it?


Optimizing texture fetches with higher mip levels Let's say I have some shader program in DirectX or OpenGL rendering a full screen quad. And in a pixel fragment shader I sample some huge textures at random texture coordinates. That is one same texture coordinate for all texture samplings in one shader invocation, but it is various among different shader invocations. These fetch operations produce performance drop, I even think that due to the size of the textures the GPU texture cache is not big enough and is used not efficiently. Now I have a theoretical question can I optimize the performance by using some low resolution like 32x32 mask textures, which are built by mipmapping the large textures, and if a value in a mask texture at given texture coordinate at some higher mip level is not appropriate, then I don't need to perform texture fetches at full size level 0? Something like this in HLSL (GLSL code is pretty similar, but there is no branch attribute) float2 tc calculateTexCoordinates() bool performHeavyComputations testValue(largeMipmappedTexture.SampleLevel(sampler, tc, 5)) float result 0 branch if (performHeavyComputations) result largeMipmappedTexture.SampleLevel(sampler, tc, 0) About 50 of texels at mip level 5 will not pass the test. And so a lot of shader invocations should not sample the full size textures. But I am introducing branching in the code. May this branching hurt the performance even worse than sampling the full size texture even if that is not needed? Different GPUs may behave differently, some may not even support branching, will they perform two fetches instead of one? I can test this code on some machines, but my question is theoretical. And can you suggest another optimizations, if this won't work properly ?


glVertexAttribPointer stride ambiguity As a hobbyist junior game programmer, I have done multiple small OpenGL projects just to have fun with 3D. I've tested VBOs in C and in Java and I found something or rather understood Java tutorials differently than the C ones. When using the glVertexAttribPointer function in Java, it is told that the parameter stride (second from the end) is the size of an entire vertex. void glVertexAttribPointer( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid pointer) Considering the following my interpretation of the Java OpenGL tutorial, this is what should be done (as example) in C glVertexAttribPointer(vertexLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(0)) glVertexAttribPointer(normalLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(sizeof(float) 3)) glVertexAttribPointer(texCoord0Loc, 2, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(sizeof(float) 6)) struct MyVertex float x, y, z float nx, ny, nz float s0, t0 Now I'm really confused because this works in my Java code. However, in my old C code, I was something like this glVertexAttribPointer(vertexLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aPosition), BUFFER OFFSET(0)) glVertexAttribPointer(normalLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aNormal), BUFFER OFFSET(sizeof(float) 3)) glVertexAttribPointer(texCoord0Loc, 2, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aTextCoord), BUFFER OFFSET(sizeof(float) 6)) My question is should the stride parameter be the size of an entire vertex in bytes or should it be the number of bytes separating another vertex attribute of the same type, i.e. the size between two normals, positions, texture coordinates, ect?


Time to render each frame is proportional to the amount of models in the scene This question is deliberately written in a "High Level" manor to avoid screeds and screeds of code snippets, hopefully I can get my point across, I am using C and OpenGL. I have a game engine, and in the engine I have my "game loop" that is called every frame, one of the things in this game loop is my call to Render(), before a call to SwapBuffers(), nothing new there. Essentially my engine draws the scene using a scene graph, that is I have GameObject's and each object has a GameComponent. So when the Render() is called in the "game loop" I get the root GameObject and render its GameComponent and then move onto the next GameObject and render its GameComponent, etc. until all GameObject's and each of their GameComponent's are drawn using glDrawElements(...). One of the GameComponent's a GameObject can have is a MeshRenderer, that is a Mesh paired with a Texture. In my scene I want to add loads of tree models, therefore I create for example 50 GameObject's that each have a MeshRenderer component (a tree) that will eventually in the game loop described above be drawn. The issue with this is that the time it takes to render a frame is directly proportional to the number of tree models I have (O(N) I think is how you word it). For example with 100 trees the render time is 23ms, with 200 trees it is 46ms, with 400 trees it is 90ms so on and so forth. This is terrible, I need at least 1000 trees in my "game world" and even at around 400 my game is "laggy". Because the time to draw a frame is proportional to the number of tees I know that each frame it is re drawing each mesh essentially (every frame drawing 100 trees, and then 200 and so on, and the time to draw scales with it) My question is this How can I store the mesh data so that I don't need to draw them from scratch every frame, I can just draw them once, and then re use that data for the next frame, but don't re draw it all? is there a way to firstly use glDrawElements(...), then store that mesh data(all the vertices etc.) and then every frame after call something like for example glDrawExcistingElements() instead of glDrawElements(...). Ultimately meaning that for consecutive frame draws the time is the exact same wether I have 1 tree or 1000 trees because the system is simply saying "here is the scene I already drew", instead of "lets draw it all again from scratch".


OpenGL How can I make the edges of this textured circle smoother? I'm building a game and I've applied a certain texture (RAW file) to a circle (GL POLYGON) in OpenGL. It loads correctly, with the right size and all, but the edges seem a bit jagged and I would prefer them smooth (without any evidence of a polygon being underneath). GLuint loadTex(int wrap) GLuint texture int width, height BYTE data FILE file file fopen( "tex.raw", "rb" ) if (file NULL) std cerr lt lt "O ficheiro da textura n o foi encontrado" lt lt std endl return 0 width 128 height 128 data (BYTE )malloc( width height 3 ) Aloca o do buffer fread( data, width height 3, 1, file ) Ler dados da textura fclose( file ) glGenTextures( 1, amp texture ) Nome da textura glBindTexture( GL TEXTURE 2D, texture ) Selec o da textura actual glTexEnvf( GL TEXTURE ENV, GL TEXTURE ENV MODE, GL MODULATE ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP NEAREST ) Par metros da Textura glTexParameterf( GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE WRAP S, wrap ? GL REPEAT GL CLAMP ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE WRAP T, wrap ? GL REPEAT GL CLAMP ) gluBuild2DMipmaps( GL TEXTURE 2D, 3, width, height, GL RGB, GL UNSIGNED BYTE, data ) free(data) return texture void drawCircle(float cx, float cy, float r, float aspectRatio) GLuint t loadTex(1) float angle, radian, x, y, tx, ty, xcos, ysin glEnable(GL TEXTURE 2D) glBindTexture(GL TEXTURE 2D, t) glBegin(GL POLYGON) for (angle 0.0 angle lt 360.0 angle 2.0) radian angle (M PI 180.0f) xcos (float)cos(radian) ysin (float)sin(radian) x xcos r cx y ysin r aspectRatio cy tx xcos 0.5 0.5 ty ysin 0.5 0.5 glTexCoord2f(tx, ty) glVertex2f(x, y) glEnd() glDisable(GL TEXTURE 2D) Is this a problem from my texture file? Or is it from my code? I apply Line Smoothing before drawing anything (and it is being applied correctly in my lines I believe)


C OpenGL SDL2 VBO Depth problem Transparency I got a problem with my VBO. When having textures. The far blocks overlay the near ones. I tried editing the alpha, depth buffer, the VBO byte allocation. Nothing works for me... The FAR plane is overlapping the NEAR plane. Alpha glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glEnable(GL CULL FACE) glDisable(GL MULTISAMPLE) glDepthMask(GL TRUE)


SDL 2.0 OpenGL not drawing anything except background My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code main.cpp include "src App.h" int main( int argc, char args ) App app(600, 400, false) app.Run() return 0 App.h ifndef APP H define APP H include lt SDL.h gt class App public explicit App(size t win width, size t win height, bool fullscreen mode) m window width(win width), m window height(win height), m fullscreen(fullscreen mode) void Run() private void Draw() void Update(double dt) void Resize(size t width, size t height) void ProcessEvents() private size t m window width size t m window height bool m fullscreen bool is done SDL Window m window SDL GLContext m glcontext endif APP H App.cpp include ".. App.h" include lt SDL opengl.h gt include lt cassert gt void App Run() SDL Init(SDL INIT VIDEO) m window SDL CreateWindow("Okno gry", SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, m window width, m window height, SDL WINDOW OPENGL (m fullscreen?SDL WINDOW FULLSCREEN SDL WINDOW RESIZABLE)) m glcontext SDL GL CreateContext(m window) Resize(m window width, m window height) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL CONTEXT PROFILE MASK, SDL GL CONTEXT PROFILE COMPATIBILITY) glClearColor(0, 0, 1, 0) glEnable(GL DEPTH TEST) glDepthFunc(GL EQUAL) is done false size t last ticks SDL GetTicks() while(!is done) ProcessEvents() size t ticks SDL GetTicks() double delta time (ticks last ticks) 1000 last ticks ticks if (delta time gt 0 ) Update(delta time) Draw() SDL Quit() void App Draw() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() glBegin(GL TRIANGLES) glColor3f(1, 1, 0) glVertex2f(1, 1) glVertex2f(0, 1) glVertex2f(0, 0) glEnd() SDL GL SwapWindow(m window) void App ProcessEvents() if (is done) return SDL Event event while (SDL PollEvent( amp event)) if (event.type SDL WINDOWEVENT amp amp event.window.event SDL WINDOWEVENT SIZE CHANGED) Resize(event.window.data1, event.window.data2) else if (event.type SDL QUIT) is done true break void App Resize(size t width, size t height) m window width width m window height height glViewport(0, 0, static cast lt int gt (width), static cast lt int gt (height)) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, 1, 0, 1, 1, 10) glMatrixMode(GL MODELVIEW) glLoadIdentity() void App Update(double dt) printf(" d", dt) Can anyone help? I don't know why it's not running.


Texture coordinate discontinuity with mipmaps creates seams I just started learning openGL and I am getting this artifact when texturing a sphere with mipmaps. Basically when the fragment samples the edge of my texture, it detects the discontinuity (say from 1 to 0) and picks the smallest mipmap, which creates this ugly seam ugly seam http cdn.imghack.se images 6bbe0ad0173cac003cd5dddc94bd43c7.png So I tried to manually override the gradients using textureGrad fragVert is the original vertex from the vertex shader vec2 ll vec2((atan(fragVert.y, fragVert.x) 3.1415926 1.0) 0.5, (asin(fragVert.z) 3.1415926 0.5)) vec2 ll2 ll if (ll.x lt 0.01 ll.x gt 0.99) ll2.x .5 vec4 surfaceColor textureGrad(material.tex, ll, dFdx(ll2), dFdy(ll2)) Now I get two seams instead of one. How can I get rid of them? And why does the code above generate 2 seams? 2 eams http cdn.imghack.se images 44a38ef13cc2cdd801967c9223fdd2d3.png You can't tell from the two images but the 2 seams are on either side of the original seam.


Which code is faster to convert 1 to 0 and 1 to 1? I'm writing a shader for rendering the sides of triangles with different colors. I have a value mediump float back dot(V, N) which is positive if the normal faces away from the camera and negative if towards the camera. To correctly select which diffuse color to shade a particular fragment, I need something like this lowp vec4 color max(0.0, sign( back)) frontdiffuse max(0.0, sign(back)) back diffuse It's more or less an "unrolled conditional"... Which code produces faster instructions? x 0.5 0.5, or max(0.0, x) ? The former may be better mathematically behaved than the latter, but maybe min max clamping is super efficient in hardware


How do I render using VBOs? I'm trying to render a hemisphere in OpenGL, the problem that the hemisphere isn't rendered at all, only part of it. I initialize it, then at each frame I draw it using the following code. I'm trying to use a VBO for drawing it. void Jellyfish Init HemiSphere(const float radius, const int segments ) m iSegements segments m fVerts new float (segments 1) 2 3 m fNormals new float (segments 1) 2 3 m fTexCoords new float (segments 1) 2 2 for( int j 0 j lt segments 2 j ) float theta1 j 2 3.14159f segments ( 3.14159f ) float theta2 (j 1) 2 3.14159f segments ( 3.14159f ) for( int i 0 i lt segments i ) Vec3f e, p float theta3 i 2 3.14159f segments e.x math lt float gt cos( theta1 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta1 ) e.z math lt float gt cos( theta1 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 0 e.x m fNormals i 3 2 1 e.y m fNormals i 3 2 2 e.z m fTexCoords i 2 2 0 0.999f i (float)segments m fTexCoords i 2 2 1 0.999f 2 j (float)segments m fVerts i 3 2 0 p.x m fVerts i 3 2 1 p.y m fVerts i 3 2 2 p.z e.x math lt float gt cos( theta2 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta2 ) e.z math lt float gt cos( theta2 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 3 e.x m fNormals i 3 2 4 e.y m fNormals i 3 2 5 e.z m fTexCoords i 2 2 2 0.999f i (float)segments m fTexCoords i 2 2 3 0.999f 2 ( j 1 ) (float)segments m fVerts i 3 2 3 p.x m fVerts i 3 2 4 p.y m fVerts i 3 2 5 p.z glGenBuffers(3, amp SVboId 0 ) Vertex glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glBufferData(GL ARRAY BUFFER,sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts,GL DYNAMIC DRAW) Normals glBindBuffer(GL ARRAY BUFFER,SVboId 1 ) glBufferData(GL ARRAY BUFFER,sizeof( m fNormals) (m iSegements 1) 2 3, m fNormals,GL DYNAMIC DRAW) void Jellyfish drawHemiSphere( ) glEnableClientState( GL VERTEX ARRAY ) glVertexPointer( 3, GL FLOAT, sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts ) glEnableClientState( GL VERTEX ARRAY ) glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glVertexPointer( 3, GL FLOAT, 0, 0 ) glEnableClientState( GL NORMAL ARRAY ) glBindBuffer(GL NORMAL ARRAY,SVboId 1 ) glNormalPointer( GL FLOAT, 0,0 ) glEnableClientState( GL TEXTURE COORD ARRAY ) glTexCoordPointer( 2, GL FLOAT, sizeof( m fTexCoords) (m iSegements 1) 2 3, m fTexCoords ) glEnableClientState( GL NORMAL ARRAY ) glNormalPointer( GL FLOAT, sizeof( m fNormals) (m iSegements 1) 2 2, m fNormals ) for( int j 0 j lt m iSegements 2 j ) for( int i 0 i lt m iSegements i ) glDrawArrays( GL TRIANGLES, 0, (m iSegements 1) 2 ) glDisableClientState( GL VERTEX ARRAY ) glDisableClientState( GL TEXTURE COORD ARRAY ) glDisableClientState( GL NORMAL ARRAY )


Skeletal Animation with UV seams I have a UV mapped model that I am about to animate and load into my game. Like most unwrapped models, I have several UV seams. In order to render the model correctly, I split each vertex along the seam into two vertices whose positions and normals are the same but whose UV coordinates differ. I do the same thing when I have more than one normal associated with a vertex. This works fine for static models, but now I'm getting into the realm of animation. Technically since the two seam vertices occupy the same position in space they should use the same joint weights and joint IDs. Right now the simple way to do this is to just give them the same joint weights and joint IDs and then skin them separately. But to me this seems very wasteful because there are so many vertices along seams and so there will be many duplicate computations. It gets even worse since I need to render the animated model into the shadow map too. Does anyone have any thoughts about improving this process? I've considered using something involving OpenGL transform feedback to save the results of the transformed vertices. This would at least help with computing transformed positions once and using the same results in the main render pass and shadow pass, but I still can't think of an elegant way to handle the duplicate computation along UV seams.


OpenGL Interpole keyframes of animated 3d object inside vertex shader Lets say I have N vertex buffers that hold the N key frames of an animated 3d object, that was created by an application like blender. To smoothly interpolate these frames, I would like to bind two buffers to render the object with a vertex shader like this in vec4 inPos0 in vec4 inPos1 in vec3 inNormal0 in vec3 inNormal1 ... other attributes... uniform float time void main() vec4 currentPos mix(inPos0,inPos1,time) ... other calculations ... To do this, the two buffers must be bound simultaneously, so I'd need to call glVertexAttribPointer every time, that a new keyframe should be used. This way buffer I can be bound to inPos0 and buffer I 1 to inPos1. My question Is this a good way to interpolate key frames? Or is there any builtin function to handle this scenario?


Blending for multiple lighting passes I am attempting to perform shadow mapping with deferred shading, using the following code for (auto light m ShadowDirs) render shadow map shadowDirPass(m ShadowBuffer, light) glEnable(GL BLEND) glBlendFunc(GL ONE, GL ONE) activate shader for non shadow casting lights m ShadowDirLightShader.activate() m FrameBuffer.LightingPass(m ShadowDirLightShader) m ShadowDirLightShader.setUniform(("WSCamPos"), m ActiveCamera gt getPosition()) m ShadowDirLightShader.setDirLight(("dirLight"), static cast lt DirLightData amp gt (light gt getLightData())) m ShadowDirLightShader.setUniform(("ShadowTransform"), m ShadowDirMatrix) bind depth map m ShadowDirLightShader.bindTexture(("shadowMap"),5, m ShadowBuffer.getDepthTexture()) render renderQuad() glDisable(GL BLEND) shadowDirPass(m ShadowBuffer, light) Simply renders the geometry to the shadow map. m FrameBuffer.LightingPass(m ShadowDirLightShader) Just binds the Gbuffer textures. I have two directional lights in the scene, one with red colour (1,0,0), and one with blue colour (0,0,1) One would think that the scene would be coloured purple, but no. Every time I render (for each) light, the image in the target framebuffer is overwritten completely, instead of blended together. To illustrate this, see the following images Above is the scene with a single red light. Above is the same scene, with a single blue light, but from a different direction. (See shadows). When I enable both lights, the result is as if the first light was never used, though by stepping through the code, I can confirm that it is definitely going through a render cycle. I'm pretty sure than I've messed up the blending somehow, but I could use some guidance.


rendering rolling hills I want to render very pretty smooth undulating hills. There are objects snuggled between these hills, so I can't really use naive bump mapping. I am currently rendering using a very detailed mesh that I generate myself. Its a lot of very small triangles. Are there other approaches? What is the current viability of displacement mapping, for example? I would like to run on mainstream hardware, including integrated graphics, and possibly even one day across to tablets and such.


How to detect GLSL warnings? After compiling a shader with glCompileShader, I can call glGetShaderiv with GL COMPILE STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified. In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL COMPILE STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved?


OpenGl indices array I have a class terrain which create a grid of Quads. I do it like this for(int z 0 z lt length z ) for(int x 0 x lt width x ) vertices.push back(vec3((float)x 250, 0.f, (float)z 250)) for(int z 0 z lt ( length 1) z) for(int x 0 x lt ( width 1) x) int index z width x Vertex vertices Vertex(vertices.at(index),vec3(0, 0, 0)), Vertex(vertices.at(index 1),vec3(0, 0, 0)), Vertex(vertices.at(index width),vec3(0, 0, 0)), Vertex(vertices.at(index 1 width),vec3(0,0,0)) unsigned short indices index,index 1,index width,index 1,index width,index width 1 Quad quad( vertices, 4, indices, 6) squares.push back(quad) i The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code But when I change this indices to this unsigned short indices 0,1,2,1,2,3 It works great The problem is I don't understand why this line unsigned short indices index,index 1,index width,index 1,index width,index width 1 doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code class Quad public Quad(Vertex vertices, int n, unsigned short indices, unsigned short numIndices) for(int i 0 i lt numIndices i ) indices.push back( indices i ) for(int i 0 i lt n i ) vec3 v vec3( vertices i .position, lengthPower) position.push back(v) glGenVertexArrays(1, amp mVertexArray) glBindVertexArray(mVertexArray) glGenBuffers(1, amp mPositionBuffer) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glBufferData(GL ARRAY BUFFER, sizeof(vec3) position.size(), position.data(), GL STATIC DRAW) glGenBuffers(1, amp mIndicesBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(unsigned short) indices.size(), indices.data(), GL STATIC DRAW) void draw() glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glVertexAttribPointer(0, 4, GL FLOAT, GL FALSE, 0, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glDrawElements(GL TRIANGLES, indices.size(), GL UNSIGNED SHORT, 0) glDisableVertexAttribArray(0) Quad() private std vector lt unsigned short gt indices std vector lt vec3 gt position GLuint mVertexArray GLuint mPositionBuffer GLuint mIndicesBuffer I'm using, OpenGL, glm, glfw etc.


Generating geometry when using VBO Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads. I am doing this by storing a STD Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays. I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader VBO approach


Why are some of my normals facing away from the camera? I'm trying to use WebGL to render some simple models, and I'm running into issues where pixels near the edge of my model are passing normals to my fragment shader that point away from the camera. This is of course messing with my attempts to use physically based shading, because BRDFs are only defined in the hemisphere around the normal vector. These normals aren't just slightly pointing away from the screen if that was the case, I would chalk it up to floating point error and clamp to acceptable values. But some of my pixels have v dot n values of 0.5 or less. This happens on pretty much any mesh I try to render. I have verified that my vertex normals point away from the mesh. I have backface culling turned on. This happens with both perspective and orthographic projections. I have tested in both Firefox and Chrome. Everything else about my render looks fine. My vertex shader looks like this precision mediump float uniform mat4 M uniform mat4 V uniform mat4 P attribute vec3 vertexPos model attribute vec3 vertexNormal model varying vec3 pos world varying vec3 normal world void main() gl Position P V M vec4(vertexPos model, 1.0) pos world (M vec4(vertexPos model, 1.0)).xyz We can use M here instead of its inverse transpose because it does not scale the model. normal world mat3(M) vertexNormal model And my fragment shader looks like this precision mediump float uniform vec3 cameraPos world varying vec3 pos world varying vec3 normal world void main() vec3 n normalize(normal world) vec3 v normalize(cameraPos world pos world) float vAngleCos dot(n, v) This will highlight pixels whose view vectors are outside of the hemisphere around n. gl FragColor vec4(vec3(clamp( vAngleCos, 0.0, 1.0)), 1.0) Rendering with the fragment shader above gives me results like this Apologies if I'm missing something obvious!


Fastest way to draw quads in OpenGL ES? I am using OpenGL ES 2.0 I have a bunch a quads to be drawn, would love to be able to have to pass only 4 vertices per quad as if I were using GL QUADS, but basically I just want to know the best way of drawing a bunch of separate quads. So far what I've found I could do GL TRIANGLES(6 vertices per quad) Degenerate GL TRIANGLE STRIP(6 vertices per quad) Possibilities I've found GL TRIANGLE STRIPS with a special index value that resets quad strip(this would mean 5 indexes per quad, but I don't think this is possible is OpenGL ES 2.0)


Panorama from cube map without geometry Is it possible to achieve effect equivalent to looking on the cube textured from cube map from its center, but without creation of its faces (6 quads or 12 triangles)? Say, one needed a skybox, but without the "box". There is no anything except skybox and there is no need to calculate depth of something all the points of that skybox are always visible.


OpenGL Water reflection seems to follow camera yaw and pitch I'm attempting to add reflective water to my procedural terrain. I've got it to a point which seems like it's reflecting however when I move the camera left right up down the reflections move with it. I believe the problem has something to do with the way I convert from world space to clip space for the projective texture mapping. Here is a gif of what is happening. http i.imgur.com PDta5Qu.gifv Vertex Shader version 400 in vec4 vPosition out vec4 clipSpace uniform mat4 model uniform mat4 view uniform mat4 projection void main () clipSpace projection view model vec4(vPosition.x, 0.0, vPosition.z, 1.0) gl Position clipSpace Fragment Shader version 400 in vec4 clipSpace out vec4 frag colour uniform sampler2D reflectionTexture void main () vec2 ndc (clipSpace.xy clipSpace.z) 2.0 0.5 vec2 reflectTexCoords vec2(ndc.x, ndc.y) vec4 reflectColour texture(reflectionTexture, reflectTexCoords) frag colour reflectColour I'm using this code to move the camera under the water's surface to get the reflection float distance 2 (m camera gt GetPosition().y m water gt GetHeight()) m camera gt m cameraPosition.y distance m camera gt m cameraPitch m camera gt m cameraPitch If this is insufficient code to diagnose the problem, I'll post more. I tried to keep it to what I thought could be the problem.


Data Organization in Custom 3D Mesh File Format After careful consideration to use middleware, I have decided on creating my own 3d file format format to export meshes from 3D authoring application (Softimage) into my game. I will need to export the following Vertices Indices Normals UVs Material Information Animation information (no clue, how to import it) Collision mesh Game Properties defined within 3D authoring tool (object intelligence, aggressivity, etc..) ..another assets.. Can I kindly ask for a hint, how to construct my custom file format. How to organize data within my files, please? Does anoybody have a good adivce on exporting animation information, especially when the mesh changes its geometry? I would be thankful for advices that could point me into right direction. It would be nice to save some time instead of wasting it on incorrect approaches. I use Softimage as my 3D authoring tool. Target platform is OpenGL ES 2.0 running on mobile devices (iOS, Android). Programming language C .


Making a weapon stay with a first person camera I was looking all over the internet for any information on how to get a gun to stay with a camera as done in FPS games. I am using OpenGL and GLSL to carry this out. I knew a way of how to do this in earlier OpenGL versions, but I could never figure it out in the newer versions. The type of camera that I am trying to get is something similar to this With the view matrix and everything else, I should be able to figure out the movement of the hand and the shooting. Here is some of the code that I have so far Copyright(c) 2019 Ryan Hall All Rights Reserved I do not permit any of this code to be used elsewhere by anyone else except me for commercial purposes. The gun has two defining variables one that actually creates the gun and another that moves it around in object space weaponOfChoice glm translate(weaponOfChoice, glm vec3(camera.GetPosition().x 0.15, camera.GetPosition().y 0.15, camera.GetPosition().z 0.3)) weaponOfChoice glm rotate(gun, angle, glm vec3(0.0f, 1.0f, 0.0f)) weaponOfChoice glm scale(gun, glm vec3(0.005f, 0.005f, 0.005f)) glUniformMatrix4fv(glGetUniformLocation(shader.Program, "gun"), 1, GL FALSE, glm value ptr(weaponOfChoice)) I have spent quite some time working on how to fix the code so that it will render the gun correctly and have not been able to find any great sources online that will help solve my problem. How could I do this? Do I need an identity matrix as used by me in older versions of OpenGL? If so, how do I create a mimicking function of glLoadIdentity() that will help me with this problem? Thanks, rjhwinner03


What am I supposed to pass shaders to? I don't think I fully understand how rendering shaders work. I get that you give a shader to an object sprite when drawing it, and it applies the shader to it. But I don't think I'm doing it right. For example, I wrote a shader for when the player is underwater. It makes the player sway side to side, but the problem is I'm not sure how to tell when I can use it. Do I loop through all the water blocks, and If the player intersects, run the shader on the player? This brings up the problem where all of the player would wave instead of just the part of him below the water. I'm not sure what else I could do, and I apologize if this sounds confusing, I'm very confused myself and am not sure how to explain it. Do I run the shader on the water and somehow get it to run on all the pixels intersecting the water? What do I do? Also, just to make sure, I am using 2D.


glScalef game math issue I can't get my head wrapped around this issue. The issue is my latest code is making the camera zoom in and out really quickly. My approach is built on http www.zdnet.com blog burnette how to use multi touch in android 2 part 6 implementing the pinch zoom gesture 1847?tag content siu container The opengl scale will be getting the variable scale. gl.glScalef(scale, scale, 1) the distance is obtained by between two fingers, old distance (initial touch points), and new distance (dragging touch points). The zooming in and out works well. However, it would reset glScalef each time the user start using pinch zoom. scale newDistance oldDistance I tried calculating by additive ratio. The oldtscale handles the previous distance, if it is same, then it doesn't need to add up anything to scale. The zooming is really quick, I moved the fingers closer by mere 1 cm to 5 cm, zoom goes down or up fast. I think additive ratio is a bad solution. I think it might be incomplete solution. I'm trying to figure out what's wrong with it. additive ratio tscale (newDistance oldDistance) 1 if(oldtscale tscale) oldtscale tscale tscale 0 else oldtscale tscale adding up the additive ratio and scale tscale scale tscale checking tscale for limiting the maximum minimum scale if(tscale gt 2) tscale 2 else if(tscale lt 1) tscale 1 supply scale scale tscale


Normals showing unexpected results I am making a game in c with opengl and glm and was working on my terrain when this happend as it appears it is renderering just the way i planned it, but my question was, how do i make it appear so that the their are not as many shadows? i have no idea of how i can fix this. Here is the normal code glm vec3 calculateNormal(int x, int z) float heightL getHeight(x 1, z) float heightR getHeight(x 1, z) float heightD getHeight(x, z 1) float heightU getHeight(x, z 1) glm vec3 normal(heightL heightR, 2.0f, heightD heightU) glm vec3 result glm normalize(normal) return result and here is the terrain normal generation code for (int i 0 i lt vertex count i ) for (int j 0 j lt vertex count j ) float height getHeight(j, i) vert vertexPointer 3 (float)j ((float)vertex count 1) size vert vertexPointer 3 1 height vert vertexPointer 3 2 (float)i ((float)vertex count 1) size glm vec3 normal calculateNormal(j, i) norm vertexPointer 3 normal.x norm vertexPointer 3 1 normal.y norm vertexPointer 3 2 normal.z ... here is the terrain generation code float getNoise(int x, int z) int seed x z (std rand() (0 15)) return seed 2.0f 1.0f float generateheight(int x, int z) return getIntoplatedNoise(x 16.0f, z 16.0f) float getSmoothNoise(int x, int z) float corners (getNoise(x 1, z 1) getNoise(x 1, z 1) getNoise(x 1, z 1) getNoise(x 1, z 1)) 16.0f float sides (getNoise(x 1, z) getNoise(x 1, z) getNoise(x, z 1) getNoise(x, z 1)) 8.0f float center getNoise(x, z) 4.0f return corners sides center float getIntoplatedNoise(float x, float z) int intX (int)x int intZ (int)z float fracX x intX float fracZ z intZ float v1 getSmoothNoise(intX, intZ) float v2 getSmoothNoise(intX 1, intZ) float v3 getSmoothNoise(intX, intZ 1) float v4 getSmoothNoise(intX 1, intZ 1) float i1 interplate(v1, v2, fracX) float i2 interplate(v3, v4, fracX) return interplate(i1, i2, fracZ) float interplate(float a, float b, float blend) double theta blend M PI float f ((float) 1.0f cos(theta)) 0.5f return a (1.0f f) b f float getHeight(int x, int z) return generateheight(x, z) Thank you very much for you time


Detect collision with bullet physics, to make a character controller I inherited from btCollisionWorld ContactResultCallback but I really have no idea how to use this virtual function btScalar addSingleResult(btManifoldPoint amp cp, const btCollisionObjectWrapper colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper colObj1Wrap, int partId1, int index1) I thought about using btCollisionWorld ConvexResultCallback instead but there is no method in btCollisionWorld to use it. For now my only goal is to move a btCollisionObject around and detect collision with walls, to adjust the position and movement. I would just need the collision normal, some collision point, or anything else...


(GLSL) Lighting code outputting a black quad So, ive been transitioning to modern opengl recently and it's going rather well. But alas, something must go wrong. As the titel says, all I'm getting is a completely black quad. (Ive double checked my C code and I'm pretty sure it has nothing to do with that.) version 330 core Vertex shader layout(location 0) in vec3 vertexPosition modelspace layout(location 1) in vec3 vertexColor layout(location 2) in vec2 vertexUV layout(location 3) in vec3 vertexNormal out vec3 vertNorm out vec3 fragmentColor out vec3 vertPos out vec2 UV uniform mat4 MVP void main() gl Position MVP vec4(vertexPosition modelspace,1.0f) UV vertexUV fragmentColor vertexColor vertPos vertexPosition modelspace vertNorm vertexNormal Fragment shader version 330 core in vec3 Normal in vec3 fragmentColor in vec3 vertPos in vec2 UV out vec3 color uniform sampler2D textureSampler uniform mat4 Model void main() vec3 lightPos vec3(0, 0, 0) mat3 normalMatrix transpose(inverse(mat3(Model))) vec3 normal normalize(normalMatrix Normal) vec3 fragPosition vec3(Model vec4(vertPos, 1)) vec3 surfaceToLight lightPos fragPosition float brightness dot(normal, surfaceToLight) (length(surfaceToLight) length(normal)) brightness clamp(brightness, 0, 1) color vec3(brightness 1 (texture(textureSampler, UV).rgb fragmentColor)) But if you require my c code, say so and ill edit.


What is UVIndex and how do I use it on OpenGL? I am a noob in OpenGL ES 2.0 (for WebGL) and I'm trying to draw a simple model I've made with a 3D tool and exported to .fbx format. I've been able to draw some models that only have A vertex buffer, a index buffer for the vertices, a normal buffer and a texture coordinate buffer, but this model now has a "UVIndex" and I'm not sure where am I supposed to put this UVIndex. My code looks like this GL.bindBuffer(GL.ARRAY BUFFER, this.Model.House.VertexBuffer) GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute "vPosition" ,3,GL.FLOAT, false, 0, 0) GL.bindBuffer(GL.ARRAY BUFFER, this.Model.House.NormalBuffer) GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute "vNormal" , 3, GL.FLOAT, false, 0, 0) GL.bindBuffer(GL.ARRAY BUFFER, this.Model.House.TexCoordBuffer) GL.vertexAttribPointer(this.Shader.TextureAndLighting.Attribute "TexCoord" , 2, GL.FLOAT, false, 0, 0) GL.bindBuffer(GL.ELEMENT ARRAY BUFFER, this.Model.House.IndexBuffer) GL.bindTexture(GL.TEXTURE 2D, this.Texture.HTex1) GL.activeTexture(GL.TEXTURE0) GL.drawElements(GL.TRIANGLES, this.Model.House.IndexBuffer.Length, GL.UNSIGNED SHORT, 0) But my model renders totally incorrect and I think it has to do with the fact that I am ignoring this "UVIndex" in the .fbx file, since I've never drawn any model that uses this UVIndex I really have no clue on what to do with it. This is the json file containing the model's data http pastebin.com raw.php?i G294TVmz


GLSL, all in one or many shader programs? I am doing some 3D demos using OpenGL and I noticed that GLSL is somewhat "limited" (or is it just me?). Anyway I have many different types of materials. Some materials have ambient and diffuse color, some materials have ambient occlusion map, some have specular map and bump map etc. Is it better to support everything in one vertex fragment shader pair or is it better to create many vertex fragment shaders and select them based on currently selected material? What is the usual shader strategy in OpenGL or D3D?


How to rotate a direction I'm working a spotlight for my deferred renderer and I'm having trouble with matching the mesh to the visual representation of the light. Right now my mesh is a cone, the apex of the cone is at (0,0,0), it has a height of 1 and a radius of 1. The direction of this cone is (0, 1,0) when the rotation is (0,0,0). The relevant GLSL code float spot alpha dot( l,normalize(vec3(0, 1,0) )) lt float inner alpha cos(light.falloff) float outer alpha cos(light.radius) float spot clamp((spot alpha outer alpha) (inner alpha outer alpha),0.,1.) As you can see, the GLSL code uses a direction to define the area to be lit, so I could get this direction as a uniform, but I would need to find a rotation from that for the mesh to follow, or I can get the rotation and find a direction, but I don't know how to do either of these things. Can I rotate a direction? How do I do it? If I can't, is there another solution for this problem?


Geometry instancing in OpenGL ES 2.0 I am planning to do geometry instancing in OpenGL ES 2.0 Basically I plan to render the same geometry(a chair) maybe 1000 times in my scene. What is the best way to do this in OpenGL ES 2.0? I am considering passing model view mat4 as an attribute. Since attributes are per vertex data do I need to pass this same mat4, three times for each vertex of the same triangle(since modelview remains constant across vertices of the triangle). That would amount to a lot of extra data sent to the GPU( 2 extra vertices 16 floats (Number of triangles) amount of extra data). Or should I be sending the mat4 only once per triangle?But how is that possible using attributes since attributes are defined as "per vertex" data? What is the best and efficient way to do instancing in OpenGL ES 2.0?


OpenGL can an Element Array Buffer points to only one VBO I'm making a Minecraft style game and currently storing 36 vertices and texture coordinates per cube. Could I make an EBO for only the position and leave the texture coordinates as they are? OK i think thsi is how i will do it. I would have an array of 24 vertices(3 GLfloat) and 24 texture coordinates(2 GLfloat) for the corners then i would have an EBO pointing to the corners with 36 indices So memory total 24 3 4 24 2 4 36 4 624 bytes instead of 36 3 4 36 2 4 720 bytes


Linear filter problem with diagonal lines on adjecent tiles I am quite new at using OpenGL GLSL. Basically, the project I am working on is my first 'real' experience with it. I do not know whether this is relevant, but I use libgdx for my project. Currently, I am trying to use the GL LINEAR filters to draw tile of my (tile) map (before I was using GL NEAREST without problems). My map contains diagonal roads (just simple lines in this example). A partial overview example of my map (using the nearest filter without corrections) With the GL NEAREST filter, initially I added a 1 pixel border, so the tiles were slightly overlapping and the diagonal roads were draw without the small gaps at the edges of the tiles. This does not work with the GL LINEAR filter, because I suppose that the overlapping parts are drawn twice, resulting in a darker 'blob' I tried to get rid of the blobs, by making the horizontal lines shorter, but there is always an irregularity, either a blob or an 'decrease of line width' (as seen in the diagonal part of the line). So I removed the 1 pixel additional border and have this as a result Now I am trying to fill in the 'gaps' by drawing the two triangular fillers like this but I can't get it completely right (this is the best I managed to get) I suppose it is virtually impossible to get this perfectly right by 'manually' drawing these triangles. Also, when looking at the third image, the lines at the 'edges' (that need to be filled) are very sharp. I suppose this is problematic..? So, my question is how does one solve this problem? Do I need to prepare modify my textures for this? Can I use a shader to fill the gaps automatically? Is manually filling the gaps with the triangles the way to go? Or is there some entirely different technique to have smooth diagonal lines that span multiple tiles?


Modern shadow rendering techniques? What is the state of the art in terms of shadow rendering? My target is OpenGL 3.2, using a deferred rendering pipeline, if that matters. It's been years since I looked into shadow rendering, and at that time there were numerous techniques available, from stencils to the various shadow mapping methods. At that time, rendering shadows required separate rendering passes, controlled by the CPU. But then recently I saw a demo where a scene was rendered entirely on the GPU, including shadows. I have no idea how that would have been accomplished, or if it is even a reasonable thing to do (beyond a tech demo). Given the large amount of old info on the internet, I'd like to learn what methods people are using these days, and how much of it can be pushed to the GPU (assuming my target OpenGL version supports it).


State of art shadowing technique for OpenGL on isometric terrain? What's the most efficient way of creating shadows for object on a isometric terrain with OpenGL and JOGL? Note that this terrain is not flat and is not heightmap generated. Think it as another model. However objects' shadows on other objects is just nice to have.Objects must drop shadows just on the terrain.


Where to start learning OpenGL with C ? Possible Duplicate What are some good learning resources for OpenGL? I have learnt C and made some cool text based games and such but I would love to start graphical programming. I'm a decent artist (I will have some of my work below) I know the basics of C but I really would like to get into OpenGL. I need someone to show me some good tutorials for OpenGL with C so I can really get into game development. My goal is to be able to program a simple 2D game by the end of the year and I have lots of time to do so. I'm en rolled in a game development course next year and really need some help with starting off.


glBlendFunc transparency in cocos2d? GL ONE, GL ONE This makes the flamingoes transparent on http www.andersriggelsen.dk glblendfunc.php but not in cocos2d using sprite.blendFunc (ccBlendFunc) GL ONE, GL ONE How can I achieve a similar effect in cocos2d? Thank you.


Shader Transmittance or Absorption I am trying to create a transmittance or absorption shader (glsl, hlsl, cg, etc...) in realtime but I don't find any good tutorial or white paper about this subject. I only find offline rendering references. Is it possible to achieve this kind of effect in realtime using standard rasterisation of a 3D mesh ? How ?