Stencil buffer VS conditional discard in fragment shader I have a continuous height mapped mesh to represent landscape. I also have 1 to let's say 10 wells on this landscape represented by additional models. What I want to achieve is to create an illusion of an actual hole in landscape at the place where the well sits. I see the solution in two ways Draw holes to stencil buffer an then use it in fragment shader to discard landscape fragments. Send an array of uniforms (vec2) and then conditionally discard fragments if they are near those hole points. The question is what way should I prefer if I'm good with rectangular holes and want to get best performance?


Poor performance wth custom particle system in LibGDX I'm using a custom particle system for my LibGDX Java based game project (because I used Slick2D earlier on, need more parameters so I made my own and then ported). The system is fairly standard as far as I'm concerned, uses particle pooling (each emitter has its own fixed size particle pool) and renders each particle in a batch and uses one single (2048x1028) packed texture with all particle textures on it. Here is how I render the particles in semi pseudo code (because the entire code isn't relevant) ParticleSystem class Note ExtendedBatch is my custom sprite batch implementation, largely just the normal SpriteBatch with two additional vertices for grayscale factor and additive tinting void renderEmitter(ParticleEmitter emitter, ExtendedBatch batch) ParticlePool pool particlePools.get(emitter) if (emitter.shouldScissor) Renderer.pushScissor(emitter.scissor) for (Particle particle pool.particles) if (particle.inUse) particle.render(batch) if (emitter.shouldScissor) Renderer.popScissor() Particle class void render(ExtendedBatch batch) relativeX getRelativeX() relativeY getRelativeY() if (isInScreenBounds(relativeX, relativeY)) batch.setColor(myColor) batch.draw(myTexture, position, origin, size, scale, rotation) Now for some reason with only around 300 particles (split up into 10 emitters with varying sizes) the performance drops to awful 30FPS on my notebook's integrated GPU (Intel HD 4400) when I need want 60FPS at all times. I know iGPUs aren't great, but that one is one of the better ones out there and games like Ori or Braid which have thousands of similar particles run without any problems at 60FPS on that very chip. I also doubt (and hope) that it's not just Java vs C which is causing this huge performance drop here. Looking at in game profiling data The in game profiling data however shows a few things Particles aren't really taking that long to render and there is a lot of idle time. To me, that doesn't really make much sense. It looks like there would be enough resources to easily render everything at 200FPS or more, but it is stuck at a horrible 30FPS. There are a lot of things I already tried that didn't help Packing all particle textures into one (which is 2048x1024) Batching all particle draw calls Profiling to find out the cause (see above) VisualVM to find potential memory issues, didn't help Disabling vSync and FPS locks doesn't help For the record, here's a VisualVM CPU sample over a timespan of 2 minutes There must be something I'm doing wrong and I also want need more particles than just 300 so I definitely have to fix this but I don't know how. Update Using the default SpriteBatch implementation and default shaders doesn't improve performance either. Update Solution I forgot to turn off MSAA. I had it running at 2x sampling rate for smoother antialising, I completely forgot to check for that. In the meantime I improved performance in a lot of other parts, but that's what finally did it.


Wrong faces culled in OpenGL when drawing a rectangular prism I'm trying to learn opengl. I did some code for building a rectangular prism. I don't want to draw back faces so I used glCullFace(GL BACK), glEnable(GL CULL FACE) . But I keep getting back faces also when viewing from front and also sometimes when rotating sides are vanishing. Can someone point me in right direction? glPolygonMode(GL FRONT,GL LINE) draw wireframe polygons glColor3f(0,1,0) set color green glCullFace(GL BACK) don't draw back faces glEnable(GL CULL FACE) don't draw back faces glTranslatef( 10, 1, 0) position glBegin(GL QUADS) face 1 glVertex3f(0, 1,0) glVertex3f(0, 1,2) glVertex3f(2, 1,2) glVertex3f(2, 1,0) face 2 glVertex3f(2, 1,2) glVertex3f(2, 1,0) glVertex3f(2,5,0) glVertex3f(2,5,2) face 3 glVertex3f(0,5,0) glVertex3f(0,5,2) glVertex3f(2,5,2) glVertex3f(2,5,0) face 4 glVertex3f(0, 1,2) glVertex3f(2, 1,2) glVertex3f(2,5,2) glVertex3f(0,5,2) face 5 glVertex3f(0, 1,2) glVertex3f(0, 1,0) glVertex3f(0,5,0) glVertex3f(0,5,2) face 6 glVertex3f(0, 1,0) glVertex3f(2, 1,0) glVertex3f(2,5,0) glVertex3f(0,5,0) glEnd()


btRigidBody world transform and scale issue When I create a collision shape for rigid body (in this case box) I use vertices positions and scale from the opengl matrix, the code looks this way glm vec3 boxDim getBoxDim(verticesPositions, scale) collisionShape .reset(new btBoxShape(btVector3(boxDim.x, boxDim.y, boxDim.z))) When a simulation step is done I need to update opengl matrix for the object. I calculate a new model matrix this way btTransform transform rigidBody gt getWorldTransform() float openglMatrix 16 transform.getOpenGLMatrix(openglMatrix) glm mat4 newModelMatrix glm make mat4(openglMatrix) newModelMatrix glm scale(newModelMatrix, glTransform.getScale()) My code works but I wonder if there is any possibility to have already scale in the transform returned by getWorldTransform. Then I can ommit this line of the code newModelMatrix glm scale(newModelMatrix, glTransform.getScale())


Arbitrary number of VBO to Vertex Shader I am currently using standard modern OpenGL way to render a mesh via VBO and attributes glEnableVertexAttribArray(aVertexPosition) glBindBuffer(GL ARRAY BUFFER, VBO) glVertexAttribPointer(aVertexPosition, 3, GL FLOAT, GL FALSE, 0,0) glBindBuffer(GL ARRAY BUFFER, 0) and in the GLSL code also the standard way to received into as in vec3 aVertexPosition. However, I wonder if there is anyway to make this for a dynamic amount of VBOs. Let's say my software creates a number of VBOs that depend on the inputs, and I successfully create and allocate memory for all of them, how do I pass all of them to the shader? Does the number need to be constant? If so, what is the best way to do it?


How can I animate a portion of the textures on a model? I have a model to which I have attached multiple textures. Both textures are currently static, but if I want to move (or slide) the texture which is on the top (in UV space), is that possible? Maybe by moving the texture coordinates or something?


How can I extrude a regular, grid based 2D shape to 3D? I have a list of vertex coordinates which encircle several 2D areas. Orthogonal lines only, but not necessarily convex areas... similar to PCB traces of conductive copper areas. I want to draw them like solid objects in 3D using OpenGL, but I'm still very new to 3D and struggling. Please point me how to do this. I've managed to draw the outline only using GL LINE STRIP, but when I try GL QUAD STRIP or GL TRIANGLE STRIP, the list of coordinates is not properly ordered for triangle strip and the fact the areas are not convex prevent me from doing a simple triangular tessellation. These are the 2D shapes I'd like to render them like this


Accessing 3D texture data without normalized coordinates directly, but with filtering texelFetch() exists to access texture data with texture coordinates in "image dimensions", but texelFetch skips filtering. In case of 2D textures, it's possible to use a rectangle texture sampler to access textures without normalized coordinates with filtering, but the same equivalent doesn't seem to exist for 3D textures. Is this somehow possible with 3D textures?


draw two models changing the MVP matrix (android opengl) I'm newbie with opengl2 in android, and I'm making an app in which I'm testing some things. Now I was trying to duplicate a sphere object with a texture, so I thought it was enough to change my MVP matrix applying a small translation to the Model matrix, using same View Matrix and same projection matrix. int numIndices balon.getNumIndices() ShortBuffer indices balon.getIndices() GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0) for (int j 0 j lt numIndices.length j ) GLES20.glDrawElements(GLES20.GL TRIANGLES, numIndices j , GLES20.GL UNSIGNED SHORT, indices j ) GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix2, 0) for (int j 0 j lt numIndices.length j ) GLES20.glDrawElements(GLES20.GL TRIANGLES, numIndices j , GLES20.GL UNSIGNED SHORT, indices j ) balon is an object of type Sphere. mMVPMatrix and mMVPMatrix2 are the MVP matrices I was talking about. I simply changed the MVP matrix and did the drawing again. The result is that I have the two spheres, but one of them is behaving strangely, appears distorted, the position in which appears is right, the two spheres move along, but one of them changes it's shape. What I'm missing?, I guess I have to duplicate some things in my code before I do this, but what?, thought that being the same model, this was enough... This is how I changed the MVP matrix Matrix.setIdentityM(mModelMatrix, 0) Matrix.setIdentityM(mModelMatrix2, 0) Matrix.translateM(mModelMatrix, 0, posX, posY, posZ) Matrix.translateM(mModelMatrix2, 0, posX 0.5f, posY 0.5f, posZ) Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0) Matrix.multiplyMM(mMVPMatrix2, 0, mViewMatrix, 0, mModelMatrix2, 0) Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0) Matrix.multiplyMM(mMVPMatrix2, 0, mProjectionMatrix, 0, mMVPMatrix2, 0)


What is glViewport for and why it is not necessary sometimes? I develop my game most of time under ArchLinux. I have decided to try it on the Ubuntu 16.04 recently. The situation I came across was really strange No glGetError()s at all. No errors, warnings, anything bad in the gl debug output. All assertions that I made for all bad situations did not trigger. glClear successfully cleared the buffers I specified, but glDraw did not draw anything. Luckily I have found a solution which was to set glViewport. However, I don't quite understand, why is it necessary for drawing in Ubuntu but not necessary in ArchLinux? The also difference is between graphics adaptors on archlinux I use NVIDIA 1060, on Ubuntu I use integrated HD Graphics P530 (Skylake GT 2). If it is important, I use SDL2 with opengl 4.4.


orbit object around another object I am building 3D solar system containing (sun earth moon). I have difficult to add the part which the moon rotate around earth. I separated between "moon" and other stars. The problem is that the center of earth is not const like the sun. I know that earth is in starsList 1 so I thought to translate the moon to this place but got weird result.. Someone have an idea how to do this? mat4.identity(mvMatrix) mat4.translate(mvMatrix, 0, 0, z ) for (i 0 i lt starsList.length i ) mvPushMatrix() if (starsList i .name "moon") mat4.rotate(mvMatrix, degToRad(starsList i .angle), 0, 1, 0 ) mat4.translate(mvMatrix, starsList 1 .initPlace) mat4.rotate(mvMatrix, degToRad(starsList i .angle), 0, 1, 0 ) else mat4.rotate(mvMatrix, degToRad(starsList i .angle), 0, 1, 0 ) mat4.translate(mvMatrix, starsList i .initPlace) mat4.rotate(mvMatrix, degToRad(starsList i .angle), 0, 1, 0 ) mvPopMatrix()


Error OpenGL null Cocos 2D Visual Studio When I try to execute a game code fully functional on Visual Studio 2013, using Cocos 2D (3.8.1) library this error jumps on screen. (I'm working on a laptop) OpenGL 1.5 or higher is required (your version is (null)). Please upgrade the driver of your video card. And then this one My Graphic card is an AMD Radeon HD 7600M (OpenGL version 4.x), with de drivers fully updated. Neither my college teacher nor me know how to fix it. What can I do to fix it?


How can i port my OpenGL game to linux? I made a game with OpenGL 4.3(core profile) and C . I used GLFW3 for window and context management. I am also using bunch of third party library which are also available for linux. What things do i need to consider if i want to port the game and how can i make it support all windows and linux?


How can I disable dim the screen when I click the pause button? I am working in an android game using cocos2d. I want to dim the background screen when I click the pause button. How can I do this ?


camera movement along with model I am making a game in which a cube travels along a maze with the motive of crossing the maze safely. I have two problems in this. The cube needs to have a smooth movement like it is traveling on a frictionless surface. So could someone help me achieve this. I need to have this done in a event callback function I need to move the camera along with the cube. So could someone advice me a good tutorial about camera positions along with an object?


Got garbage when getting shader compile log I got garbage when trying to compile shader and get error log. I checked my code against some sample code, and could figure out where I did wrong. Below is my code bool LoadShader(GLuint ShaderType, char const ShaderFileName) os file ShaderFile OSReadFile(ShaderFileName) GLint ShaderHandle glCreateShader(ShaderType) DebugPrint("Shader source s n . s n", ShaderFileName, ShaderFile.Length, ShaderFile.Contents) GLchar ShaderSource (GLchar ) amp ShaderFile.Contents GLint ShaderSourceLength ShaderFile.Length glShaderSource(ShaderHandle, 1, amp ShaderSource, amp ShaderSourceLength) glCompileShader(ShaderHandle) OSFreeFile( amp ShaderFile) GLint Success glGetShaderiv(ShaderHandle, GL COMPILE STATUS, amp Success) if (!Success) GLchar CompileLog 512 glGetShaderInfoLog(ShaderType, 512, NULL, CompileLog) switch (ShaderType) define SHADER TYPE ERROR(ShaderType) case ShaderType DebugPrint( ShaderType " Compile error! n") break SHADER TYPE ERROR(GL VERTEX SHADER) SHADER TYPE ERROR(GL FRAGMENT SHADER) undef SHADER TYPE ERROR DebugPrint(" s n n", CompileLog) return false return true Below is some output Shader source shader fragment.glsl version 330 core out vec4 Colour void main() Colour vec4(1.0, 0.5, 0.2, 1.0) GL FRAGMENT SHADER Compile error! p R


glVertexAttribPointer stride GL INVALID VALUE opengl 3.3 I'm experiencing issues similar to described in this question, which was never answered. Basicly when I'm calling glVertexAttribPointer with stride greater than this exact value 640. OpenGL GL INVALID VALUE error is raised. According to documentation such an arror can be raised in one case GL INVALID VALUE is generated if stride is negative. Which is obviously not my case. In OpenGL 4.4 the maximum value is specified and set to GL MAX VERTEX ATTRIB STRIDE according to this site Is there a certain magic number in older versions of OpenGL (3.3 in my case) for a maximum vertex stride? Is there any other reason that this function can raise GL INVALID VALUE?


How can I achieve a good fire effect with alpha blending and particles? Using the following setting for the OpenGL particle effect SRC GL SRC ALPHA DST GL ONE Creates an additive blend, which looks spectacular on a black background but terrible on brighter colours, as it begines to fade to white. I then used alpha blending SRC GL SRC ALPHA DST GL ONE MINUS SRC ALPHA This allows other backgrounds to be used without affecting the color of the particles, but the particles themselves look dull compared to the additive blend. How can I achieve a good fire effect with alpha blending and particles? Additive Alpha UPDATE Following David's advice below, I created a separate texture and then used additive blend on the particle effect before drawing onto the texture. The problem with that is that drawing on an alpha 0 texture resulted in just the coloured parts of the particle appearing in front of my world map, since normally you have a black background instead. The trick was to use two textures. I created a black texture and then drew the particles on it. Then I removed the alpha layer of the particles from this texture, effectively removing all the surrounding solid black and fading out the partially visible particles, while leaving the underlying black as you'd expect when making additive blend particles on a black background. In short, a gruelling process, but I got there eventually Here's the thread where I posted my process http www.cocos2d iphone.org forum topic 28707?replies 8 post 141528 Video http www.youtube.com watch?v JptGbEO3b5E


Why does OpenGL 3 only allow VBOs? I see that OpenGL versions 3 and up eliminate the use of client side rendering. Immediate mode has been eliminated, and vertex arrays seem to be deprecated. Instead, if I understand correctly, VBOs are the main way of rendering vertices. While I see the logic behind having a uniform way of rendering everything, is it the case that VBOs have no major downsides over vertex arrays? I thought VBOs were supposed to be large buffers containing 1MB of data, generally. What if I have a scene that has a lot of smaller geometry? I have a scene graph with a large number of nodes, each of which needs its own transform, etc. Each node should also be able to be deleted separately, added to separately, etc. I was using vertex arrays before. So my first question is whether, if I switch to VBOs, there will be a greater overhead to my scene graph objects now because a VBO needs to be allocated for each object. Another concern is that the geometry I'm rendering can be highly dynamic. In the worst case, there may be times when all geometry needs to be resent every frame for some period of time. Will VBOs have worse performance than vertex arrays in this use case, or do VBOs at worst do just as much work as vertex arrays but no more? So, in more concise format, my questions are 1) Is there a substantial overhead to allocating deallocating VBOs (I mean the mere act of setting up a buffer)? 2) If I'm updating the data from the CPU every frame, can this be substantially worse than if I had used vertex arrays? And finally, I'd like to know 3) If the answer to either of the above questions is "yes", why deprecate other modes of rendering that could have advantages over VBOs? Is there something I'm missing here, like techniques I'm supposed to use to mitigate some of these potential allocation costs, etc.? 4) Do the answers to any of these questions change substantially depending on what OpenGL version I'm using? If I refactor my code to be OpenGL 3 or 4 forward compatible by using VBOs in a way that is performant, will the same techniques be likely to perform well with OpenGL 2, or is it likely that certain techniques are much faster with OpenGL 3 and others with OpenGL 2? I asked this question on stack overflow, but I am re posting here because I realized this site may be more appropriate for my question.


Texture filtering of look up table in post process shader I am doing post processing by drawing to an FBO and then applying a certain fragment shader when drawing the FBO's texture to the screen. I want to use a look up table texture to apply color grading. Since I am targeting OpenGL ES 2.0 and possibly older PCs, I cannot use 3D textures. Instead I can use a 2D texture as an atlas of the layers of my 3D look up table. What I'm concerned about is correctness and performance when the texture lookup is performed. My look up texture needs to have linear filtering so I don't have to have a full 256 3 sized look up table to cover all hues. My fragment shader would look something like this Round B up and down to get the two regions of the texture to sample from, add offsets accordingly to R G and sample the texture twice with the two offset .rg values. And finally linearly interpolate based on B. But I as I understand it, the when the GPU encounters a texture2D call on a texture with linear filtering, it will be calculating the input coordinates for those calls for neighboring pixels in parallel to get a derivative. This derivative is used to determine how to sample the texture pixels. Since this is a post process, I don't want two neighboring pixels to influence each other. It could be a black pixel from the edge of a sprite next to a bright blue sky pixel. In the look up table, these two would need to sample distant points. So is the GPU going to decide the derivative is huge (minification) and try to linearly sample and involve all the random in between texels on my look up table? Is there a way to get my linear filter to ignore neighboring pixels and only interpolate from the 4 nearest texels? Sort of like treating everything as magnification? The problem is similar to this question that was asked in regards to HLSL, but I'm targeting OpenGL 3.0 and OpenGL ES 2.0 Color grading, shaders and 3d textures


How do I convert my matrix from OpenGL to Marmalade? I am using a third party rendering API, Marmalade, on top of OpenGL code and I cannot get my matrices correct. One of the API's authors states this We're right handed by default, and we treat y as up by convention. Since IwGx's coordinate system has (0,0) as the top left, you typically need a 180 degree rotation around Z in your view matrix. I think the viewer does this by default. In my OpenGL app I have access to the view and projection matrices separately. How can I convert them to fit the criteria used by my third party rendering API? I don't understand what they mean to rotate 180 degrees around Z, is that in the view matrix itself or something in the camera before making the view matrix. Any code would be helpful, thanks.


Flickering tearing with glfwSwapBuffers I recently separated my logic and rendering threads to fix this problem GLFW window freezes on title bar hold drag This means the logic and rendering are no longer running in lock step as they were before, so it is possible that the logic has not finished executing by the time we are ready to render. To handle this case, the rendering thread will keep sleeping for 1ms until the logic has finished executing. Pseudo code Logic thread while (!exiting) timeBefore now() updateGame() renderingDue true timeElapsed now() timeBefore sleep(MS PER FRAME timeElapsed) Rendering thread while (!exiting) if (renderingDue) render() renderingDue false GLFW.glfwSwapBuffers(window) else Not yet ready to render, but try again in a short while sleep(1) This seems to work fine for me, at least with vsync disabled. When I tested with vsync enabled I encountered stuttering, which I suppose is because if we miss a rendering frame, we have to wait until the next monitor refresh interval before we can catch up. However, on some other systems, in particular low end laptops, there is a lot of flickering tearing during gameplay. I don't understand what would cause this, since we are always calling glfwSwapBuffers() after rendering, not during. Is there something fundamentally wrong with my approach? I know ideally the rendering thread should take a delta value so that it can render the state "between" logic threads (yes, I have read Fix Your Timestep!), but I am nonetheless curious about what is happening here.


Best way to do buttons for an OpenGL ES iPhone game I'm making a simple 2d game in OpenGL ES and I want to add movement buttons to it. What's the best way of going about this? In previous projects I've simply added UIButtons to the view but I hear there are performance implications in doing so with OpenGL ES so I'm wondering what the possible alternatives are if so.


Setting up OpenGL camera with off center perspective I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off center distance point. Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left hand side. The "main" part of the screen is on the right, but you still want to show whats in the view on the left. However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid x position in the screen. Here's the jist of how i set my viewport up where it is centered in the middle setup the camera glMatrixMode(GL PROJECTION) glLoadIdentity() const GLfloat zNear 0.1 const GLfloat zFar 1000.0 const GLfloat fieldOfView 90.0 can definitely adjust this to see more less of the scene GLfloat size zNear tanf(DEGREES TO RADIANS(fieldOfView) 2.0) CGRect rect rect.origin CGPointMake(0.0, 0.0) rect.size CGSizeMake(backingWidth, backingHeight) glFrustumf( size, size, size (rect.size.width rect.size.height), size (rect.size.width rect.size.height), zNear, zFar) glMatrixMode(GL MODELVIEW) rotate the whole scene by the tilt to face down on the dude const float tilt 0.3f const float yscale 0.8f const float zscale 4.0f glTranslatef(0.0, yscale, zscale) const int rotationMinDegree 0 const int rotationMaxDegree 180 glRotatef(tilt (rotationMaxDegree rotationMinDegree) 2, 1.0f, 0.0f, 0.0f) glTranslatef(0, yscale, zscale) static float b 25 0 static float c 0 rotate by to face in the direction of the dude float a RADIANS TO DEGREES( atan2f( gCamera.orientation.x, gCamera.orientation.z)) glRotatef(a, 0.0, 1.0, 0.0) and move to where it is glTranslatef( gCamera.pos.x, gCamera.pos.y, gCamera.pos.z) draw the rest of the scene ... I've tried a variety of things to make it appear as though "the dude" is off to the right do a translate after the frustum to the x direction do a rotation after the frustum about the up y axis move the camera with a biased lean to the left of the dude Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted. I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off center" these model views in OpenGL. Thanks!


Unexpectedly fast rotation after refactoring OpenGL code to add more abstraction I've been working on an OpenGL program that simply renders a square that rotates in 3D space. The square also has a texture applied to both sides. Here you can see an example screenshot of the program running I used very little abstraction in that project and most of the code was in main.cpp (apart from the shader loading and usage). After finishing this project, I wanted to improve it as much as I could with my current knowledge. I started abstracting away functionality. The final result was a very clean main.cpp file with multiple classes (Mesh, Shader, Resource Manager and Window classes). Apart from the texture, everything should functionally be the same, but I experienced the following after using the rotate function left is the abstracted version of the first project, right is the first project The square in the new project rotates at a much higher speed than in the previous project. The implementation is the same, as in, the degrees that the square should rotate around the y axis are the same in both projects the time the program has been running, which is gotten through GLFW's glfwGetTime(). I checked nearly everything. The .lib files are linked the same way between the projects. There are no differences between the vertex data. Both projects are running in DEBUG mode. The only difference I could think of is the texture not being applied in the second project, but I recall that the textureless version of the first project was still running with the same speed as it is currently. But rendering a 64x64 texture on a square shouldn't be that expensive to run. NOTE I'm using GLM for the matrices and for the rotation transformation. Does abstracting away all of OpenGL's initializing and buffer code improve performance by that much? I'm using GLFW for window and context creation, and thus using (float)glfwGetTime() for the angle of rotation along the y axis. The second project basically moves over all functionality into categorized classes. So everything to do with meshes was moved to a Mesh class, loading of GLSL shaders and textures was moved over to a ResourceManager class etc. So all functionality should be the same.


Limit Clamp camera movement using quaternions I'm making a camera object for rendering with OpenGL. However, instead of using the typical "LookAt" method I'm trying to use just a Quaternion for orientation and a Vector3 for position. Instead of messing with euler angles to rotate the Camera I use quaternions directly, like this glm vec3 up glm normalize(glm inverse(cam.Orientation) glm vec3(0, 1, 0)) glm vec3 right glm vec3( 1, 0, 0) cam.Orientation glm rotate(cam.Orientation, glm radians( xoffset), up) cam.Orientation glm rotate(cam.Orientation, glm radians( yoffset), right) xoffset and yoffset are just the amount the mouse has moved since the last frame. I create my view matrix from the inverse of the two variables. I've already got FPS style camera movement and rotation working. The problem I have now is that I want to prevent the camera from being able to flip over. I.E. moving the mouse up or down enough that the view becomes upside down. Is there a way to clamp the rotation using purely quaternions to prevent this?


OpenGL tile rendering Currently I'm trying to render a TileMap using OpenGL 2.1, GLSL 1.2. I would like to draw every tile in just one draw call. I use a single texture with all tiles, identifying each one by an index. The vertex data per tile is vec2 worldPos the position to transform the tile Quad in world coordinates vec2 texCoord the uv coordinates, calculated using the tile index, by CPU (top left corner). But I can't find a way to draw everything with one draw call The uv coordinates can't be calculated in shader because the vertex shader don't know which corner of the quad it is processing. Can't draw by element because my quad vertex data only contains 4 vertices, store repeated vertices is a memory waste. Only if I could use a separate element buffer just for the vertex (0, 1, 2, 3, 0, 1, ...). Does someone have any suggestion about how should I proceed? Thanks!


Why is my diffuse lighting changing with camera position? I am trying to do lighting in view space, but I am afraid I have an issue. I calculate the normals as N norm mat vec4(vert norm,0.0) where norm mat is the transpose(inverse(model view mat)). Then in the lighting shader (for a directional light) perform the following N normalize(N.xyz) vec4 view L pos vec4(lightPosition.xyz, 0.0) view mat vec3 L normalize(view L pos.xyz) out col vec3(dot(N,L)) However, moving the camera changes the floor's lighting What am I doing wrong?


What is the correct multiplication order for a 2D matrix? I'm currently trying to create a camera and entity model matrix for my 2D game similar to that of Unity3D. I've already tried to find answers to this question on stackoverflow gamedev but i couldn't find an answer that explains how to center the camera and image. Goal Have a camera matrix wich is centered at the position of the camera. Have a entity matrix wich draws everything centered Current implementation camera matrix Matrix.translation(Screen.width 0.5, Screen.height 0.5) Matrix.rotation(camera.rotation radians) Matrix.scale(camera.scale.x, camera.scale.y) Matrix.translation(camera.x, camera.y) entity matrix Matrix.rotation(entity.rotation radians) Matrix.scale(entity.scale.x, entity.scale.y) Matrix.translation(entity.x, entity.y) image component draw function setMatrix(camera.matrix entity.matrix) drawImage(x 0, y 0, image) position is already included in the entity matrix Results Image rotates around the upper left corner of the screen not around it's center Image is not centered. The image's origin is at its upper left corner. The camera matrix seems to be correct. Questions What is the correct multiplication order for the entity model matrix? Can i use a single matrix for all components of a entity or do i need to calculate in the width height of the image text animation component.


2D Tile based game Texture Atlas combining I am new to OpenGL and game dev, I have been to courses and trying to learing everything about this. My task is to implement a Texture Atlas in a 2D tile based game (very similar to Tibia) using OpenGL. Now the game have the sprite sheet loaded into memory and on each tile the program generates an image, load to a texture, bind and make a draw call. You can imagine how ineficcient it is. So what I have to do is to load this sprite sheet as a Texture Atlas and get the advantage that it has. The problem is that in the first step while generating an image, the program makes some combinations on the sprites. For example, the character has an outfit and player changes its colors (boots, pants, t shirt, hair) to do this there is a sprite for the base outfit, and a sprite for each element of the outfit, so the program apply a mask on color for each element and combine this five sprites into an image, then make the process that I mentioned above. This is an example that happens with outfit, but it happens to other things too, so this is not a special case with outfit only. My question is is there any way to make this combinations using OpenGL elements? Combining this multiple textures in my Texture Atlas into one draft and do it in a single draw call?


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.


GLSL Sphere from Vertex I am working on a particle simulation where we have a lot of spheres which can have different radii. Using this tutorial http mmmovania.blogspot.de 2011 01 point sprites as spheres in opengl33.html (see also code below) I was able to create a sphere from a point, but they all have the size from glPointSize(). Is it possible to extend this with a radius? version 330 out vec4 vFragColor uniform vec3 Color uniform vec3 lightDir void main(void) calculate normal from texture coordinates vec3 N N.xy gl PointCoord 2.0 vec2(1.0) float mag dot(N.xy, N.xy) if (mag gt 1.0) discard kill pixels outside circle N.z sqrt(1.0 mag) calculate lighting float diffuse max(0.0, dot(lightDir, N)) vFragColor vec4(Color,1) diffuse Maybe of interest I am using version 120 for my shaders. Or, is there a better way to do this? So, combining the two answers I now have void Draw setGeometry(float geometry, float velocity, float radius, GLuint size) this gt size size glGenBuffers(1, amp vertexData) glBindBuffer(GL ARRAY BUFFER, vertexData) glBufferData(GL ARRAY BUFFER, size 3 sizeof(float), geometry, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) glGenBuffers(1, amp velocityData) glBindBuffer(GL ARRAY BUFFER, velocityData) glBufferData(GL ARRAY BUFFER, size 3 sizeof(float), velocity, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) glGenBuffers(1, amp radiusData) glBindBuffer(GL ARRAY BUFFER, radiusData) glBufferData(GL ARRAY BUFFER, size sizeof(float), radius, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) And the drawing method void Draw paint(GLenum mode) glBindBuffer(GL ARRAY BUFFER, vertexData) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, 0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 0, 0) glEnableVertexAttribArray(2) glVertexAttribPointer(2, 1, GL FLOAT, GL FALSE, 0, 0) glDrawArrays(mode, 0, size 3 sizeof(float)) glDisableVertexAttribArray(0) And the Vertex Shader version 130 attribute vec3 position attribute vec3 velocity attribute float size uniform mat4 MVP uniform mat4 MV void main() gl PointSize size gl Position MVP vec4(position, 1.0) The problem is that when gl PointSize 15 is set, they are drawn well. When I make it equal with size, then it looks like this http picpaste.com Big particles daIBnJCG.png Works better now. Particles still getting bigger as they move along.


Replace glTranslatef and glRotatef with matrixes I'm not an opengl expert, and, as a novice, I prefer to practice a little bit with the old opengl just to be sure to understand correctly the basic concept of computer graphics before deal with shaders and modern opengl (3.x). I don't want to start a flame with this so I'll go through my question. I just know that what I'm using is deprecated. What I wanto to render is this and I'm drawing it using this piece of code draw grid drawGrid(10, 1) draw a teapot glPushMatrix() glTranslatef(modelPosition 0 , modelPosition 1 , modelPosition 2 ) glRotatef(modelAngle 0 , 1, 0, 0) glRotatef(modelAngle 1 , 0, 1, 0) glRotatef(modelAngle 2 , 0, 0, 1) drawAxis(4) drawTeapot() glPopMatrix() Now, I'd like to replace the last glTranslatef and glRotatef with matrixes, and I'm doing in this way Matrix4 matrixModel matrixModel.identity() matrixModel.translate(modelPosition 0 , modelPosition 1 , modelPosition 2 ) matrixModel.rotateX(modelAngle 0 ) matrixModel.rotateY(modelAngle 1 ) matrixModel.rotateZ(modelAngle 2 ) glLoadMatrixf( matrixModel.getTranspose()) And I don't see anymore the teapot. So I thought that this matrixModel is not complete because it is only the model matrix and I need a modelview so I have to multiply it with the projection matrix but.. this is what I get where am I wrong?


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.


Should texture regions sizes be power of two? Is it advisable for my individual texture regions inside this texture to be power of two, or that won't make any difference? I've read on several places that it's recommended to use power of two sized textures (e.g. Should I use textures not sized to a power of 2?).


Shader Color blending I would like to know how to blend colors in a specific way. Let's imagine that I have a color (A) and an other color (B). I would like to blend them in such a way that if I choose white for the (B) then the output color is (A) but if have any other color for (B) it outputs a blending of (A) and (B). I've tried the addition, but it doesn't give the expected result. I've tried the multiplicative blending it's quite good for the (B) white value but it fail for a blue (B) and red (A) colors. Any idea how to do that ? Thanks a lot.


"Render" unsigned integer values to texture without clamping to 0,1 I am trying to render to an unsigned integer texture, with a blending function enable, so that in the end, the value in each texel will be the number of objects rendered on the texel. So I assume I cannot use normalized integers. For example, if I have a 2x2 texture, and I render (0,0) (0,0) (0,1) (1,0) , the texture result should be, 2 1 1 0 . I am trying to set up the frameBuffer, but the call to glTexImage2D, causes the GL FRAMEBUFFER INCOMPLETE ATTACHMENT when I use the formats I assume I need. this works glTexImage2D(GL TEXTURE 2D, 0, GL RGB, 1024, 768, 0, GL RGB, GL UNSIGNED INT, 0) this causes GL FRAMEBUFFER INCOMPLETE ATTACHMENT glTexImage2D(GL TEXTURE 2D, 0, GL RGB32UI, width, height, 0, GL RGB INTEGER, GL UNSIGNED INT, 0 ) Is what I want to do even possible? If so, which settings do I need to use to accomplish this?


How can I consistently map mouse movements to camera rotation? I am writing a OpenGL game engine and also an editor for the engine. In my editor, I can import 3D models from FBX Collada as a scene graph. Now I want to implement the option for the user to rotate and the camera in the viewport using mouse. I found many links to rotate the camera by some angle based on the delta x and delta y of the mouse. This is fine. But my problem is selecting the axis for rotation. For example, if the user moves the mouse in the x axis, I am changing the camera's local rotation angle along y axis (the up axis). But this is not always working. In case if the camera node's parent node is rotated 90 degree in the x axis, when I change the camera's local y axis rotation angle, the scene is rotating in wrong direction. So in this case I have to rotate the camera's z axis angle. This is my problem. So how can I ensure the camera always finally rotate left and right (whatever the parent nodes' angles are rotated) when the user moves the mouse horizontally? Also I want to mention that when the user moves mouse up and down, I want the camera to rotate up and down always.


Rendering Performance num Draw Calls num Texture Bindings I'm making a game with Libgdx 1.6.4 and experience some lag issues on iPhone 4 and then discovered in the constructor GLProfiler.enable() ... in the render method Gdx.app.debug("draw calls " GLProfiler.drawCalls) Gdx.app.debug("texture bindings " GLProfiler.textureBindings) GLProfiler.reset() What the log shows is that the number of draw calls is always equal to the number of texture bindings. Do you know if this is ok? It seems strange because I have all images as TextureRegion in only one TextureAtlas with size 1024x512. Isn't it supposed to be that I will have for example 50 draw calls and only 1 2 texture binding instead of 50 draw calls and 50 texture bindings. Can this be the source of the lag? Another clue may be, that I use a SpriteBatch and Scene2d Stage at the same time, but they both use the same TextureAtlas. The Scene2d Skin is loading the TextureAtlas and SpriteBatch draws TextureRegions from the skins' regions. Thank you for any help. Update The main SpriteBatch (it's only one) is making 9 totalRenderCalls. The value of maxSpritesInBatch is 26. These values seem normal from what I read in the Docs and the FPS during rendering with the SpriteBatch is 60 FPS. Which is ok, no problem there. The problem with the lag is when I use a Scene2D Stage to display a Dialog above the GameScreen. The Stage has it's own batch which I don't manipulate directly. When the Dialog is displayed the frame rate drops to 49 50 and the Animations in the Dialog are crappy. I guess the problem has something to do with Texture Binding of the main SpriteBatch and the Stage's SpriteBatch.


Orthographic viewport zooming I'm a bit new in opengl so please bear with me. I have a viewport window like this I have implemented zoom in out features using the arrow keys. The problem is it zooms in and out with the whole image. Can anyone point me in the right direction as to how I can make the GUI on the sides stay in place while making my viewport (the white rectangle) zoom in and out? Thank you!


How to render apart blocks of a cone in OpenGL I want to render a cone in parts like on the image. My problem is to calculate the arc of each block in 3D space. has someone an idea how to handle this?


WebGL transparent gradient mask at edge I need to make a feature in WebGL, where I have horizontal list of meshes (example 20) and I want to show only 3 and 2 at edge are fade in fade out. And it slowly animates from one side no another (sliding to left or right). Here is a sample code, how it is done using CSS. (https jsfiddle.net jqsLh4vg 91 ) What would be possible options to have this kind of effect? My current approach, what I am trying (could be not the most perfomant solution) Calculate visible area Calculate how much visible area (in percentage) each mesh is visible in visible area on each render Draw gradient using frag shader at the edges (here it is were I stucked and can't figure out the solution) But maybe there is easier approach for this kind of effect? (Image if I have 100 elements and I need to manually calculate their visible area on each render time).


How do particle systems work? I want to implement a particle system in my game, but I've never programmed a particle system and don't know where to start. I only want to display pixels (GL POINTs) with different sizes in different places, something like Terraria or Minecraft when you hit a block, without the texture. Just a dead simple example. Google search results for this tend to be very complex, or don't explain the concepts, or are written in hard to read C without OOP I'm using Java and OpenGL.


OpenGL FBO to OpenCV image I am trying to figure out the best way to share an image between OpenGL and OpenCV libraries. I perform a render to texture on OpenGL, so I have and FBO texture that then I want to pass it OpenCV, where (ideally) I will be some GPU stuff with it. I know a naive way would be using glReadPixels, but this is obviously way to slow. It requires to copy the data from GPU memory to memory and then load it through cvLoadImage or similar in OpenCV. I am pretty sure there must be a way to bind or map the memory from OpenCV, so I can "load" an image by just accessing to its FBO pointer or something like that... but I cannot figure out how. I have goggled a lot about it, and so far I could just find this answer that I don't quite understand. What do they mean by glbuffer.bind() ? Any guess? Thanks.


Creating map files for a 3D game I've created plenty of 2D games and now that I've gotten my hands dirty working with 3D in opengl I want to start a game. The issue is I don't know how I can store all the map data. Not only the terrain but the textures and objects in the world, lighting, what's intractable etc. it seems that it'll get way to big if I don't have an efficient system for storing and loading maps. So what methods or articles can you guys suggest on this?


Tweening Colors in OpenGL I'm making a sky gradient in OpenGL by drawing with glColorPointer and glDrawArrays. I would like to be able to change the sky colour from morning to daytime to evening etc. I can either Make a number of sprites and fade them in with my framework Somehow tween the color vector in openGL over time and use a single sprite The second one seems like a more efficient option, but my framework doesn't pass the time delta into the draw method for me to decide how far I've progressed into fading. Here's my current code glDisable(GL BLEND) glDisable(GL DITHER) glDisable(GL FOG) glDisable(GL LIGHTING) glDisable(GL TEXTURE 2D) glShadeModel(GL SMOOTH) CGSize size CCDirector sharedDirector winSize float w size.width float h size.height const GLfloat vertices 0, 0, w, 0, 0, h 3, w, h 3, 0, h 2 3, w, h 2 3, 0, h, w, h, const GLubyte colors 254,255,134,255, 254,255,134,255, 230,157,0,255, 230,157,0,255, 230,60,0,255, 230,60,0,255, 167,0,86,255, 167,0,86,255, glVertexPointer(2, GL FLOAT, 0, vertices) glEnableClientState(GL VERTEX ARRAY) glColorPointer(4, GL UNSIGNED BYTE, 0, colors) glEnableClientState(GL COLOR ARRAY) glDrawArrays(GL TRIANGLE STRIP, 0, 8) glDisableClientState(GL COLOR ARRAY) glDisableClientState(GL VERTEX ARRAY) glEnable(GL TEXTURE 2D) Which gives me


How do I store an FBO'S as a cube map? As of late I've been trying to implement Cubemaps in my engine, and have managed to get the rendering side of them working. Currently, I'm trying to implement a function for creating them, but I somehow hit a road block. The way I'm trying to implement this is by rendering my scene once into an FBO from the perspective of the cubemap node (x6 times, one in each direction), and cycle the format of the texture bound to the color attachment as GL TEXTURE CUBE MAP POSITIVE X, GL TEXTURE CUBE MAP NEGATIVE X, etc For whatever reason, I haven't been getting any expected results. All I want to do is take snapshots from the camera's perspective, but I need them in texture units I can use multiple frames over. I've tried so many ways that I couldn't possibly recount them all here, but the general gist of how I've been trying to go about doing this, is this DTextureCubemapComponent cubemap getTexture() My Texture Component GLuint target cubemap gt textureObj() CUBEMAP texture handle glBindTexture(GL TEXTURE CUBE MAP, target) Make cubemap active for (int x 0 x lt 6 x ) Render from 6 different angles gbuffercube gt swapFinalFormat(GL TEXTURE CUBE MAP POSITIVE X x) gbuffercube gt StartFrame() my FBO Class, binds itself, etc ... RENDER SCENE ... Draw into my FBO, etc gbuffercube gt BindForFinalPass() Read buffer my FBO glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MIN FILTER, GL LINEAR) 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) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP R, GL CLAMP TO EDGE) Where "SwapFinalFormat()" is void GBuffer swapFinalFormat(GLuint format) format fmt glTexImage2D(format, 0, GL RGBA32F, size.width(), size.height(), 0, GL RGBA, GL UNSIGNED BYTE, NULL) glFramebufferTexture2D(GL DRAW FRAMEBUFFER, GL COLOR ATTACHMENT6, format, m finalTexture, 0) I know that my FBO class works (labeld GBufferCube above) , as it is the same class I use normally for my deferred shading system.


How to implement a pixelated screen transition shader? I am interested in creating a screen transition seen in a lot of retro games. The transition is just a kind of pixelated distortion that increases or decreases in granularity over time. The effect is present in Super Mario World, and can be seen recreated in this clip. Also, here is an image depicting the transition (ignore the gradual lightening of the screen) I want to achieve this by animating the uniforms of a GLSL shader. Unfortunately, I don't know how to design the shader. I know how to sample gradient textures to create various screen wipes, as well as how to sample noise textures to create simple distortion effects. But I can't figure out exactly how to create this effect. Any advice on how to set up a shader to achieve this effect?


Combining varying vertex variable and vertex variable in OpenGL. How to? Let's say I have 2 triangles sharing an edge defined by 4 vertices. Though the normals for these 2 triangles are unique for each triangle and are defined per vertex. So say I have 4 vertices, 6 normals (as shown in the figure below). I would like to know how this can be dealt with in OpenGL? I have been using glDrawElement so far, but I understand that this would only work if I had 4 normals (1 normal per vertex) and this it wouldn't allow me to define 3 normals per triangle. What's the best common most efficient of dealing with this case? Do I need to also duplicate the vertices (3 unique vertices per triangle or is there a more clever solution to this?) so that I have as many vertices than I have normals?


Loading screen OpenGL with glut API I'm trying to make a loading screen. My idea is to have two threads working one in the background loading the 'game' scene, one displaying 'load' scene. When building 'game' scene is finished, it's displayed instead of 'load' scene. Before threading I want to make it work the usual way first display 'load' scene, then 'game' scene. Both GameScene and LoadScene inherit from a virtual function Scene. Here's how my main looks like LoadScene load scene GameScene game scene Scene scene int main(int argc, char argv) Init GLUT and create window glutInit( amp argc, argv) glutInitDisplayMode(GLUT DEPTH GLUT DOUBLE GLUT RGBA GLUT STENCIL) glutInitWindowPosition(initWindowX, initWindowY) glutInitWindowSize(windowWidth, windowHeight) glutCreateWindow("OpenGL") Register callback functions for change in size and rendering. glutDisplayFunc(renderScene) glutReshapeFunc(changeSize) glutIdleFunc(renderScene) Register Input callback functions. 'Normal' keys processing glutKeyboardFunc(processNormalKeys) glutKeyboardUpFunc(processNormalKeysUp) Special keys processing glutSpecialFunc(processSpecialKeys) glutSpecialUpFunc(processSpecialKeysUp) Mouse callbacks glutMotionFunc(processActiveMouseMove) glutPassiveMotionFunc(processPassiveMouseMove) void glutMouseFunc(void( func)(int button, int state, int x, int y)) glutMouseFunc(processMouseButtons) glutMouseWheelFunc(processMouseWheel) Position mouse in centre of windows before main loop (window not resized yet) glutWarpPointer(windowWidth 2, windowHeight 2) Hide mouse cursor glutSetCursor(GLUT CURSOR NONE) warp Initialise input and scene objects. input new Input() scene new LoadingScene(input) load scene new LoadScene() game scene new GameScene(input) load scene Create GameScene() Create LoadingScene(GameScene ) delete LoadingScene() LoadingScene thread tells game to start loafing assetss Enter GLUT event processing cycle glutMainLoop() return 1 The game scene reassignment must be called in changeSize function. I thought it should be in the renderScene function but it's the only way it works. Here's how it looks like void changeSize(int w, int h) scene load scene scene gt resize(w, h) Any ideas how I could go on about it? So far if I assign to 'scene' pointer 'load scene' object it's displaying 'load' scene. Same goes for 'game' scene. Is it even possible to achieve a transition between scenes without threading?


Efficiently color a procedural mesh? I'm creating a procedural world with LWJGL and GLSL. I want to better visualize the biome map being produced and the height map it creates, but my attempts so far have been very inefficient. My first idea was to make a vec3 holding the biome color for each vertex, but that very quickly took the game from 150 fps to 10 15. The time to render a 512x512 chunk went from around 3 per second to one per five seconds. As you could expect, there was also a problem with it very quickly using up 12gb of ram. I then thought about making an int array for each vertex where each point of the mesh would be able to use as a dictionary to grab a vec3 for the color. So 512 512 integers in an array getting from an array of 15 colors intead of a single array of 512 512 vec3s. This seemed even worse somehow in both FPS and chunk rendering time. To summarize again, I'm trying to color each vertex with its own color to visually show the biomes. What is a more efficient way to do this?


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?


Do I lose gain performance for discarding pixels even if I don't use depth testing? When I first searched for discard instruction, I've found experts saying using discard will result in performance drain. They said discarding pixels will break GPU's ability to use zBuffer properly because GPU have to first run Fragment shader for both objects to check if the one nearer to camera is discarded or not. For a 2D game I'm currently working on, I've disabled both depth test and depth write. I'm drawing all objects sorted by their depth and that's all, no need for GPU to do fancy things. now I'm wondering is it still bad if I discard pixels in my fragment shader?


1D vs 2D vs 3D texture performance I'm working on a 3D game with large blocky untextured, but individually colored, voxels (similar to CubeWorld). For rendering, right now I naively convert online all visible faces ahead of time to triangles with the color information stored in the vertex attributes. The screenshot below is an example of what I'm currently doing. There's a lot of room to improve here and I want to switch to a system that uses fewer vertices and stores color information in a texture. What I'd like to do is combine adjacent triangles with the same normals and simplify the mesh so I'm left with a fraction of the vertices. My big hangup is color information. It's easy to add UVs, but the correct choice for texturing isn't obvious. I'm trying to figure out the relative performance of these options Use a 1D texture. This is compact but I'm concerned that large 1D textures won't play nicely with texture mapping units optimized for 2D textures. Use a 2D texture. Simple, but it'll end up with gaps. Use a 3D texture with the full set of voxels. Does anyone have insight as to the relative performance of these options? No mipmapping or other filtering is needed here, so all three options should be viable. For reference I'm making this in C using OpenGL on Windows. My target GPU architectures are GTX 780 Ti and higher or AMD equivalent.


GLSL Rewriting shaders from 330 to 130 I recently created a game (LD21) that uses a geometry shader to convert points into textured triangles culling. Since I was under the impression that the support for 330 was widespread I only wrote 330 shaders, but it seems that a lot of not so old hardware only support 130 (according to GLView) Now, since I'm only familiar with the 330 core functionality I am having trouble rewriting my shaders to 130. The fragment shader was quite trivial to rewrite, but I've only managed to get my vertex and geometry shader down to 150. So, is it possible to rewrite the shaders, or would it require a lot of changes in my rendering engine? Geometry shader version 150 layout(points) in layout(triangle strip, max vertices 4) out uniform mat4 oMatrix in VertexData vec4 position vec4 texcoord vec4 size vert out vec2 gTexCoord void main() if(vert.position.x gt 4f amp amp vert.position.x lt 4f amp amp vert.position.y gt 2f amp amp vert.position.y lt 2f) gTexCoord vec2(vert.texcoord.z,vert.texcoord.y) gl Position vert.position vec4(vert.size.x,vert.size.y,0,0) EmitVertex() gTexCoord vec2(vert.texcoord.x,vert.texcoord.y) gl Position vert.position vec4(0.0,vert.size.y,0,0) EmitVertex() gTexCoord vec2(vert.texcoord.z,vert.texcoord.w) gl Position vert.position vec4(vert.size.x,0.0,0,0) EmitVertex() gTexCoord vec2(vert.texcoord.x,vert.texcoord.w) gl Position vert.position EmitVertex() EndPrimitive() Vertex shader version 150 extension GL ARB explicit attrib location enable layout (location 0) in vec2 position layout (location 1) in vec4 textureCoord layout (location 2) in vec2 size uniform mat4 oMatrix uniform vec2 offset out VertexData vec4 position vec4 texcoord vec4 size outData void main() outData.position oMatrix vec4(position.x offset.x,position.y offset.y,0,1) outData.texcoord textureCoord outData.size oMatrix vec4(size.x,size.y,0,0)


calculate the offset between a quad and the mouse position Opengl I am working on a very simple "GUI framework" for my game. As you can see from the GIF, i have a window object that can be selected when the mouse is inside of it and dragged, when the left mouse button is being pressed. I tried to solve the problem this way Basically i calculate the x and y component of the distance between the center of the window and the mouse cursor. I then add the component values to the window function, which looks something like mousePosition is a Vector2() that stores the mouse position x component is a float, calculated by doing float x component mousePosition.x window.getPosition().x same for the y component variable. window.setPosition(Vector2(mousePosition.x x component, mousePosition.y y component)) set position takes in a Vector2 But for some reason, this is not working. I think that it's because we are not taking in consideration the fact that the x or y component could be negative, in relation to where we press the mouse inside the window. Can someone help me?


OpenGL ES screen to world coordinate I am currently attempting to convert my screen coordinates to world coordinates, to be able to interact with objects. I am using glm and unProject to try and achieve this, so far this is my code glm vec4 viewPort glm vec4(0.0f, 0.0f, width, height) glm mat4 tmpView sceneCamera gt updateView() glm mat4 tmpProj sceneCamera gt updateProjection() glm vec3 screenPos glm vec3(touchPosition.x, height touchPosition.y 1.0f, 1.0f) glm vec3 worldPos glm unProject(screenPos, tmpView, tmpProj, viewport) Renderer gt SceneObjects 120 gt translateX(worldPos.x) Renderer gt SceneObjects 120 gt translateY(worldPos.y) I am trying to get a sprite to equal the position where I tap. The issues is that the further I click going down the screen, the further the sprite overshoots, and the same horizontally. So if I click 2 3 the way down the screen, the sprite will overshoot the bottom of the screen.


How to pass array of dozens of floats to OpenGL 3.0 vertex shader? I use PyOpengl and Python 3. I have 50 thousand vertices. Position of each vertex could be calculated in vertex shader as version 300 es uniform v coefficients weights COEFFICIENTS AMOUNT in vec3 v coefficients COEFFICIENTS AMOUNT in vec3 v initial position out vec3 v position void main() v position v initial position v coefficients coefficients weights Amount of coefficients varies between 0 and 199 mdash it's not a problem for me to generate 200 vertex shaders to cover each situation. I need to change position of vertices tens of thousands times per application calls as fast as it's possible, so I cannot calculate them once on start. Though, I cannot provide arrays for each vertex because documentation says Attribute variables cannot be declared as arrays or structures. I see following solutions of this issue (will not work) hardcode suffices of variables names to emulate arrays use vectors with names like coefficients 000, coefficients 001, ..., coefficients 199 use matrices to have 4 vectors in each of variable mdash will it be better than previous solution with vectors (maybe performance of matrices product is faster than 4 products of vectors)? calculate vertices positions by myself using C NumPy calculate vertices positions by myself in parallel using OpenCL (will not work) store all coefficients in uniform int v coefficients COEFFICIENTS AMOUNT VERTICES AMOUNT and access needed ones according to vertex number, which will be stored in in int vertex id store coefficients in textures (proposed by HolyBlackCat). Are there any other solutions of my issue? Is there optimal solution in proposed above? Will I go out of memory if I will use 200 float 3 vectors for each vertex? I imagine the solution with hardcoded indices as version 300 es uniform v coefficients weights COEFFICIENTS AMOUNT in vec3 v coefficients 000 in vec3 v coefficients 001 ... in vec3 v coefficients 199 in vec3 v initial position out vec3 v position void main() v position v initial position v coefficients 0 coefficients weights 000 v coefficients 1 coefficients weights 001 ... v coefficients 199 coefficients weights 199


Unpacking Sprite Sheet Into 2D Texture Array I am using WebGL 2. A tag for it does not exist but it should. I have a 10x10 sprite sheet of squares that are 16x16 pixels in size (all in one PNG image). I'd like to create a 2D texture array out of them, where each 16x16 square gets its own, unique Z depth value. let texture gl.createTexture() let image new Image() image.onload function() gl.bindTexture(gl.TEXTURE 2D ARRAY, texture) gl.pixelStorei(gl.UNPACK FLIP Y WEBGL, false) gl.texStorage3D(gl.TEXTURE 2D ARRAY, 5, gl.RGBA, 16, 16, NUM IMAGES) Now what? gl.texSubImage3D doesn't let me copy in a section of the src image image.src "https source url.fake image.png" I know that gl.texSubImage3D exists but it only accepts an entire image as a source? glTexSubImage3D https www.khronos.org registry OpenGL Refpages gl2.1 xhtml glTexSubImage3D.xml


OpenGL VBO Additional Attributes If I have a buffer with my vertices, normals and texture coordinates, and I use glDrawArrays to draw the VBO to the screen, how can I send attributes per vertex that I placed in an array to the shader program? I'm making a voxel terrain, and every chunk is 1 VBO, this works all great, but I want to send the light value of each block (Just an array filled with int's) to the shader as well, how would I do that? Edit After reading some comments, here some clarification I'm trying to avoid the deprecated glVertexPointer etc, so I'm using Vertex Arrays. Here is the layout of my vertex array X, Y, Z, NX, NY, NZ, X, Y, Z, NX, NY, NZ,X, Y, Z, NX, NY, NZ I'm using this to draw it (ofcourse with the array buffer bound) glVertexAttribPointer(0, 3, GL FLOAT, false, 12, 0) glVertexAttribPointer(1, 3, GL FLOAT, false, 12, 12) glDrawArrays(GL TRIANGLES, 0, arraySize 6) However I get some weird shapes on my screen. Apart from the light problem, that is essentially the same thing, I don't get why this doesn't just work. When I remove the normals, and use just 1 vertexattribpointer it works fine. Yes, the attributes are bound to in position and in normal, and the vertex shader is nothing more than gl Position gl ModelViewProjectionMatrix vec4(in position, 1.0) Thanks! This is what I get (This are 6X6 chunks, so this code is called 6 6 times.)


OpenGL using gluSphere I have an OpenGL code that currently draws several spheres at different locations. I generate the vertex buffer data (and normal data) myself. However, to simplify the code and increase efficiency, I am now trying to use gluSphere instead. The problem is that if I want to draw several spheres at different locations, I think I will need several different model matrices, and thus several different MVP matrices (because I am using OpenGL 4.3 and there is no glTranslate). But if I want to rotate the whole scene, I will need to rotate all of these model matrices, instead of just one as before. Is there a workaround for this? Is there a simple way to draw several different things with gluQuadrics objects at different locations?


Any idea why my openGL camera is stuttering only on the X axis? and only when using nvidia drivers? As part of my assignment, I've been building a scene graph framework in C OpenGL. My camera works absolutely fine going backwards and forwards, but when I strafe move on the X axis, the camera just starts stuttering. It doesn't make much sense to me, because it's the same principle to move back forward as it is to move right left. Everything is also normalised and being applied by deltaTime, so that's not an issue. Interestingly, this didn't happen when I was using my intel built in gpu, but only started occurring when I forced my nvidia card to handle the program. Here is a video of the aforementioned stutter https www.youtube.com watch?v DyTIv0yiaP0 amp feature youtu.be My scene graph is available for viewing on my GitHub The repo https github.com charliegillies fullmetal. The camera https github.com charliegillies fullmetal blob master fullmetal.cpp (line 503 730, mostly get set methods.) The camera controller https github.com charliegillies fullmetal blob master fullmetal helpers.cpp (line 14 204) Please note that this framework is still in its early days. Let me know what you think, and I'll be sure to post a fix if I find it.


.md5mesh normals are not smooth I'm currently working on a project that requires me to load .md5mesh format and draw it. Following this link I've managed to load the mesh into the engine successfully, but a problem arises when calculating normals they just don't seem to smooth. To clarify that it was not my rendering or shader code that was the problem, I loaded a model of .OBJ format, and that lights smoothly. The mesh is calculated correctly too, as I am able to load in complex models with multiple joints and mesh parts. Here's a screenshot of the lighting. And here is how I currently calculate the normals (All normals are set to zero before computing) EDIT Amended the psuedo code to be more accurate to what I have. The original may have been confusing. for (unsigned int i 0 i lt NumberOfTriangles i ) Math3 vec3 r, s, result Math3 vec3 p1, p2, p3 p1 Triangle i .Vertex 0 p2 Triangle i .Vertex 1 p3 Triangle i .Vertex 2 r p2 p1 s p3 p1 result Math3 Cross(s, r) Add the triangles face normal to each vertex The Vertex's are not local to the triangles. Triangle i .Vertex j is just an index. Vertex Triangle i .Vertex 0 .normal result Vertex Triangle i .Vertex 1 .normal result Vertex Triangle i .Vertex 2 .normal result After the loop I normalise each vertex normal to find the average normal. EDIT Here is how I find the average normal for (unsigned int i 0 i lt NumberOfVerts i ) float nx Vertex i .normal.x float ny Vertex i .normal.y float nz Vertex i .normal.z float len sqrt(nx nx ny ny nz nz) Vertex i .normal.x len Vertex i .normal.y len Vertex i .normal.z len As you can see in the image the .md5mesh model is shading flat instead of shading smoothly like the .OBJ model. So what am I missing?


Loading Wavefront Data into VAO and Render It I have successfully loaded a triangulated Wavefront (.obj) into 6 vectors, the first 3 vectors contain the locations for vertices, UV coords, and normals. The last three have the indices stored for each of the faces. I have been looking into using VAO's and VBO's to render, and I'm not quite sure how to load and render the data. One of my biggest concerns is the fact that indexed rendering only allows you to have one array of indices, meaning I somehow have to make all of the first three vectors the same size, the only way I thought of doing this, is to make 3 new vertex's of equal size, and load in the data for each face, but that would completely defeat the purpose of indexing. Any help would be appreciated.


Running Slick2d outside of the IDE I am looking for advice how to solve an exception I am getting, I've looked around and seen people get the same error but most people whom had it seems to run on old graphics drivers and once they fixed that it seemed to work for most people. I doubt that's the reason causing it for me since I have the latest nVidia drivers and the game runs well from the IDE. I also did create a jar of the game before I implemented Slick2d and that ran without exceptions. I used to get another exception, that it couldn't find the right natives for lwjgl so I removed the natives from the build and made a fat jar with jarsplice and added them during that process and that's when I ended up at this point. I've tried and tried for days and it's probably something really stupid and easy to fix but I havn't built a lot of project to be ran from outside Eclipse so any help would be greatly appreciated. Some basic info on my rig OS Windows 7 Enterprise CPU Intel Core i7 2600K GPU nVidia GTX 980 RAM 8192MB (forgot the brand and make, it's old lol)


Dynamic VBO update possibly corrupting data? I want to draw a line between two vertices. On a mouseclick the vertex data will change and I want to update the line to use the new values. I am using a VBO for this and it looks like the update process is somehow corrupting the VBO data. The line is not drawing in a direction that I would expect given the values of the vertices. There are four lines in total and I am updating only the last two vertices. The vertex data is initialized as float vertLineBuffer 1.0f,0.0f,0.0f, right 0.0f,1.0f,0.0f, top 0.0f,0.0f,0.0f, center 1.0f,0.0f,0.0f, START 0.0f, 1.0f,0.0f END The init routine public void setLineVBOs(GL4 gl) throws Exception vboLineHandles new int 2 gl.glGenBuffers(2, vboLineHandles, 0) populate the position buffer FloatBuffer fbData Buffers.newDirectFloatBuffer(vertLineBuffer) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) the vertex data gl.glBufferData(GL4.GL ARRAY BUFFER, fbData.capacity() 4, fbData, GL4.GL STATIC DRAW) fbData.clear() don't need this anymore populate the color buffer FloatBuffer fbColor Buffers.newDirectFloatBuffer(vertLineColor) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINECOLOR IDX ) the vertex data gl.glBufferData(GL4.GL ARRAY BUFFER, fbColor.capacity() 4, fbColor, GL4.GL STATIC DRAW) fbColor.clear() don't need this anymore set vertex array index IntBuffer intBuffer BufferUtil.newIntBuffer(1) gl.glGenVertexArrays(1, intBuffer) iLineVao intBuffer.get(0) gl.glBindVertexArray(iLineVao) gl.glEnableVertexAttribArray(VERTICES LINE IDX) gl.glEnableVertexAttribArray(VERTICES LINECOLOR IDX) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) the vertex data Associate Vertex attribute 1 with the last bound VBO gl.glVertexAttribPointer(0,3, GL2ES2.GL FLOAT, false,0,0) color gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINECOLOR IDX ) the vertex data gl.glVertexAttribPointer(1,3, GL2ES2.GL FLOAT, false,0,0) And then I attempt to update the VBO on an event (mouseclick) like this public void updateLine(GL4 gl, float pos) pos contains the new vertex data vertLineBuffer 9 pos 0 vertLineBuffer 10 pos 1 vertLineBuffer 11 pos 2 vertLineBuffer 12 pos 3 vertLineBuffer 13 pos 4 vertLineBuffer 14 pos 5 FloatBuffer fbData Buffers.newDirectFloatBuffer(vertLineBuffer) gl.glBufferSubData(GL4.GL ARRAY BUFFER, 0, fbData.capacity() 4, fbData) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) fbData.clear() The vertex shader version 430 layout (location 0) in vec3 vertexPosition layout (location 1) in vec3 vertexColor out vec3 Color void main(void) Color vertexColor gl Position vec4(vertexPosition, 1.0) The frag shader version 430 in vec3 Color layout (location 0) out vec4 FragColor void main(void) FragColor vec4(Color, 1.0) Does this look right? Can anyone see where this might damage the contents of the VBO?


searching for "university kind" free online course about OPENGL I know there are a lot of free university courses, but I'm trying to find one about OpenGL. Do you know where can I find one, online?


What to do with unused vertices? Imagine yourself a vertex array in OpenGL representing blocks in a platform game. But some vertices may be not used. The environment is dynamic, so there always some vertex may suddenly become invisible. What is the best way to make them not draw? Graphic cards are complicated and it's hard to predict what is best approach. Few best ways I can think of delete and move all vertices after deleted one to fill freed space (sounds extremely inefficient) set positions to 0 set transparency to maximum I could of course benchmark, but what on my computer works faster doesn't have to on other.


3.3x OpenGL Camera how to do 3d rotation? I'm trying my hardest to understand what this code is doing so far I think the sin(theta) and cos(theta) of the code is representing a point with an angle. This point with an angle sin(theta) and cos(theta) will allow the xmouse 16 value and ymouse 16 value to rotate or translate on this point with an angle because of their layout representation in the GLM LookAt() function (view camera matrix). The result of doing this is that the view matrix rotates on the x axis left and right when I move the mouse left and right and the y axis up and down when I move the mouse up and down. Is this correct? It took a lot work to understand this and if I am correct does anyone know how to move the mouse left, right, up and down from the centre of the screen (as in the mouse cursor at centre of the screen when moved to the left, right, up and down will move the camera respectively) rather then from a small region of the top left hand corner thanks!. N.B. I'm using Model Matrix and Perspective Projection Matrix with this in the middle so Model View Perspective C OpenGL 3.3x GLSL 3.30 CORE Windows 10 Code GLuint OpenGL Engine SetupViewCamera(GLFWwindow RenderWindow, glm vec3 eyepos, glm vec3 originpos, glm vec3 viewrotationpos, GLuint program, GLfloat RotAng) double xmouse 0.0f, ymouse 0.0f glfwGetCursorPos(RenderWindow, amp xmouse, amp ymouse) double theta glm radians(RotAng) glm vec3 camera(cos(theta), 0.0f, sin(theta)) camera 5 glm mat4 ViewMatrix glm lookAt( camera, glm vec3(xmouse 16, ymouse 16, 0.0), glm vec3(0.0, 1.0, 0)) glm mat4 IViewMatrix glm inverse(ViewMatrix) GLint Viewmatrixloc glGetUniformLocation(program, "VM") glUniformMatrix4fv(Viewmatrixloc, 1, GL FALSE, amp IViewMatrix 0 0 ) return 80


Is it possible to get vertices after Primitive Assembly step (after face culling)? I would like to check which vertices will be rendered from direction A (with face culling enabled) and render it from another direction to visualize face culling effect. I have found information that using Transform Feedback I can received data from vertex or geometry shader. My question is if is it possible to get data from primitive assembly step and use it to render scene from another direction or should I calculate by myself which faces should not be rendered? Any help and information would be greatly appreciated


Issues with percentage closer filtering I'm trying to code a simple game via OpenGL C . I've implemented a point light, parallax effect with textures, objects from blender etc. but I seem to have an issue with my percentage closer filtering implementation. The shadows are casted on top of a floor which is just a rendered texture below my objects. Im pretty new with how shadows work in OpenGL. This is my attempt to achieve pcf in the fragment shader in vec4 shadowMapCoord layout(binding 10) uniform sampler2D shadowMapTex area around each fragment that will be sampled const int pcfCount 10 void main() float shadowFactor 0.0f for (int x pcfCount x lt pcfCount x ) x offset from inner pixel for (int y pcfCount y lt pcfCount y ) y offset from inner pixel shadowFactor textureProjOffset(shadowMapTex, shadowMapCoord, ivec2(x,y)) float visibility shadowFactor Does someone maybe spot any issue with my implementation of textureProjOffset() or can I achieve pcf with another type of implementation?


Rendering only a part of the screen in high detail If graphics are rendered for a large viewing angle (e.g. a very large TV or a VR headset), the viewer can't actually focus on the entire image, just a part of it. (Actually, this is the case for regular sized screens as well.) Combined with a way to track the viewer's eyes (which is mostly viable in VR I guess), you could theoretically exploit this and render the graphics away from the viewer's focus with progressively less details and resolution, gaining performance, without losing perceived quality. Are there any techniques for this available or under development today?


Does opengl performs Visibilty algorithms based on z index? Does OpenGL performs Visibilty algorithms based on z index? Or we have to write our own algorithms. Mainly I'm referring to z buffer algorithm. Is it in built?


Free camera rotation in 3D space I'm using a view matrix to do camera movement and rotation. viewMatrix new Matrix4f() viewMatrix.setIdentity() Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), viewMatrix, viewMatrix) Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), viewMatrix, viewMatrix) Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), viewMatrix, viewMatrix) Matrix4f.translate(new Vector3f(x ( 1), y ( 1), z ( 1)), viewMatrix, viewMatrix) I'm manipulating the rotation values around each axis here left and right public void rotateY(float amount) ry amount Up and down public void rotateUp(float amount) rx amount if(rx lt 90) rx 90 if(rx gt 90) rx 90 This all works fine. Now i'm trying to create a more "free" camera so that i always turn left an right and don't simply rotate around the Y Axis. For the rotation up you simply remove the if cause. But for the rotation sidewards you need to calculate the parts for the x and the z axis using sin and cos. That's where i get confused. How can i rotate sidewards correctly?


How do I generate a 3D race track from a spline? I want to generate a 3 dimensional race track around a spline that describes its shape. Here's an illustrative video. The track should be an endless tunnel that sweeps along a 3D spline, with some obstacles thrown in. My best idea so far has been to loft a circle shape along the spline. I would also like some pointers into how to manage the geometry i.e. how to create it from the loft operation, manage its 'lifecycle' in memory, collision and texturing.


Flipped model has wrong triangle order I have list of models and transform matrix for each of them. Some of models are flipped along X or Y or Z axis. This meshes will be rendered wrong, back face is rendered instead of front. I tried to use glFrontFace(GL CW) and that makes wrong models fixed but previous correct models are wrong. How can I fix this? Can I detect from transform matrix which models need glFrontFace switch? Right cube and sphere are normal and left are flipped


Trying to get the fragment shader to output a list I am trying to figure out a way to get the Fragment Shader to output a list of gl VertexID s. I want to use the GPU to get a list of vertices in the viewing frustum. Is there any way I can get a per fragment shader invocation variable or something else that is possible to use as a pointer to a texture? If it is not possible, is there a possibility to use a sparse texture to render to, using gl VertexID s as a pointer?. I will be rendering about a million or two vertices at a time (using GL POINTS), and the list should be tightly packed to be of use. Some work may be offloaded to the CPU, but this is part of a real time render engine so the execution times need to be under 10ms. I am using OpenGL 4.4.


Is it a good idea to perform all matrix operations on the GPU? I was wondering if it is a improvement to use OpenGL for matrix calculations instead of using the CPU. And if it is a improvement, is it worth it to change the math class to use OpenGL?


Any GL transformation not working Today I was trying to make a test camera, with a new method(I usually use gluLookAt) So I got a problem, void GameDraw() glPushMatrix() glMatrixMode(GL PROJECTION) glLoadIdentity() gluPerspective(90, WIDTH HEIGHT, 0.001, 10000.0) pitch 1 glRotatef(pitch, 1.0, 0.0, 0.0) glRotatef(yaw, 0.0, 1.0, 0.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() s gt bind() test gt drawMesh() glPopMatrix() And my draw function is glDrawElements(GL TRIANGLES, indices, GL UNSIGNED INT, nullptr) if it isn't working with glDrawElements is there any alternative to use? Edit Disabling shader it works fine, but how I can use this with Shader Please don't use glm examples, because I don't like to use it, I feel more comfortable by using the my math


Having problems with making a button class (checkIfClick) opengl Just basing how sfml does it, I get the globalbound of the object and then check if the mouseposition is within the object. I tried do something like that but I dont know exactly how to do it with opengl. I tried changing the projection from 1 to 1 coords to the size of the application in the hope I could just get the position of the object, but when doing std cout, it still shows the position in 1 to 1 coords. So my question is quot How would I convert my mouseposition to 1 to 1 or vi versa. quot Its actually 0 to 2 and not 1 to 1 So far i have this I dont know exactly how to get the top left right with opengl I know with sfml. I would use the position and subtract the half of the width and height to get it but like I said, idk how to do that in opengl. I tried doing that but the object position i still 1 to 1 even though I passed in the glm mat4 proj glm ortho(0,width, 0, height, 1,1) I know my projection is working, because when I enter any big number, my object gets really small. FYI, just because I see these types of answers alot I'm not asking you to write me a fully functional button class. I just want a general idea on how it would be done or some article that could help me do that (or a very basic example). void contain(glm vec2 position) if (position.x gt button.left amp amp position.x lt button.right amp amp position.y gt button.top amp amp position.y lt button.bottom) std cout lt lt quot True n quot else std cout lt lt quot False n quot


GLSL shader error on different computers I recently discovered a strange error with my fragment shader version 330 core in vec4 v color in vec2 v texCoords 10 out vec4 frag color uniform int actual textures uniform sampler2D u texture 10 void main() vec4 final color texture2D(u texture 0 , v texCoords 0 ) for(int i 1 i lt actual textures i ) vec4 tex texture2D(u texture i , v texCoords i ) final color tex tex.a final color (1 tex.a) frag color v color final color On my PC with a GTX 960 and OpenGL 4.5.1 there is no error at all. But on my laptop with an Intel HD 3000 and OpenGL 3.3, I get a compile error that the texture2D function is deprecated and that the sampler2D array size is too big because I only pass 3 textures at the moment and I want the array to be able to handle up to 10 textures. On any other computer I testedm the error didn't occur, but they all had nvidia or amd gpus. Why do I keep getting this error on my laptop?


3D sphere generation I have found a 3D sphere in a closed source game engine that I really like the look of and would like to have something similar in my own 3D engine. This is how the sphere looks like when it is created in the game engine, at program game start At program start, a function named CreateSphere is called and the user has the option to choose a 3D position and a radius of the sphere. That's all I know about the function since the engine is closed source. Anyone have any idea of how this sphere might be generated programmatically? I have checked other posts sites discussing spheres but none of them has the look of the sphere in the image. Edit removed some unnecessary information to get to the point of what I need help with.


Selection with region (when rendering with shaders and VAO) I am currently render my geometry using "Modern OpenGL" approach (with shaders and buffers). I have already implemented picking of single primitives using glReadPixels. Now I am faced with problem how to implement selection of multiple objects. I cannot use glReadPixels because maximum (and it seems meaningful for me) number of objects that I could select with 10x10 box is 100. But it is really necessary for my purposes to have ability to select thousands of objects in small selection area. I already read answer to similar question where was recommended to test each point against selection rectangle. But it gives new problems all my vertices are already stored in buffers and it looks like huge performance to test each point on CPU. Could someone help with such issue?


Issues with OpenGL rotation matricies and shaders I am having an issue with my rotations in my opengl shaders. My program works fine before I add in my rotation matrices. Here is an example, at YouTube. After I add rotations to my shaders, there are issues. Here is an example. Here is my vertex shader version 130 in vec3 position in vec4 color in vec2 texcoord uniform mat4 view array uniform mat4 end array uniform mat4 projection matrix uniform mat4 trans matrix uniform mat4 x rotation matrix uniform mat4 y rotation matrix uniform mat4 z rotation matrix out vec4 pos out vec2 texture coordinate out vec4 color value void main() mat4 vw matrix mat4(1.0) mat4 rotation matrix x rotation matrix y rotation matrix mat4 model matrix trans matrix rotation matrix pos projection matrix vw matrix model matrix vec4(position, 1.0) gl Position pos texture coordinate texcoord color value color Here are the values for my matrices rotation matrices x rotation matrix 0 1 x rotation matrix 1 0 x rotation matrix 2 0 x rotation matrix 3 0 x rotation matrix 4 (float) cos( yaw (PI 180)) x rotation matrix 5 (float) sin( yaw (PI 180)) x rotation matrix 6 0 x rotation matrix 7 (float) sin( yaw (PI 180)) x rotation matrix 8 (float) cos( yaw (PI 180)) x rotation matrix 9 0 x rotation matrix 10 1 x rotation matrix 11 0 x rotation matrix 12 0 x rotation matrix 13 0 x rotation matrix 14 0 x rotation matrix 15 1 y rotation matrix 0 (float) cos( pitch (PI 180)) y rotation matrix 1 0 y rotation matrix 2 (float) sin( pitch (PI 180)) y rotation matrix 3 0 y rotation matrix 4 0 y rotation matrix 5 1 y rotation matrix 6 (float) sin( pitch (PI 180)) y rotation matrix 7 0 y rotation matrix 8 (float) cos( pitch (PI 180)) y rotation matrix 9 0 y rotation matrix 10 1 y rotation matrix 11 0 y rotation matrix 12 0 y rotation matrix 13 0 y rotation matrix 14 0 y rotation matrix 15 1 z rotation matrix 0 (float) cos( pitch (PI 180)) z rotation matrix 1 (float) sin( pitch (PI 180)) z rotation matrix 2 0 z rotation matrix 3 (float) sin( pitch (PI 180)) z rotation matrix 4 (float) cos( pitch (PI 180)) z rotation matrix 5 1 z rotation matrix 6 0 z rotation matrix 7 0 z rotation matrix 8 0 z rotation matrix 9 0 z rotation matrix 10 1 z rotation matrix 11 0 z rotation matrix 12 0 z rotation matrix 13 0 z rotation matrix 14 0 z rotation matrix 15 1 GL20.glUniformMatrix4fv( GL20.glGetUniformLocation(programID, "x rotation matrix"), true, x rotation matrix) GL20.glUniformMatrix4fv( GL20.glGetUniformLocation(programID, "y rotation matrix"), true, y rotation matrix) GL20.glUniformMatrix4fv( GL20.glGetUniformLocation(programID, "z rotation matrix"), true, z rotation matrix) Here is my transformation matrix trans matrix 0 1 trans matrix 5 1 trans matrix 10 1 trans matrix 12 x trans matrix 13 y trans matrix 14 z trans matrix 15 1 What am I doing wrong?


OpenGL Filtering antialising textures in a 2D game I'm working on a 2D game using OpenGL 1.5 that uses rather large textures. I'm seeing aliasing effects and am wondering how to tackle those. I'm finding lots of material about antialiasing in 3D games, but I don't see how most of that applies to 2D games e.g. antisoptric filtering seems to make no sense, FSAA doesn't sound like the best bet either. I suppose this means texture filtering is my best option? Right now I'm using bilinear filtering, I think glTexParameterf(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) From what I've read, I'd have to use mipmaps to use trilinear filtering, which would drive memory usage up, so I'd rather not. I know the final sizes of all the textures when they are loaded, so can't I somehow size them correctly at that point? (Using some form of texture filtering).


Handling 3D perspective for different aspect ratio I have problem for supporting different aspect ratio in developing Mobile Game. I was developing on 2 3 screen which is iPhone 4 (Retina). When I use width and height for screen size and use fixed FOV, then most of cases look ok, but in 3 4 (which is iPad), the user can "See More" horizontally. If I force the aspect ratio to 2 3, then looks "squeezed". I am lost adjusting other values like moving camera, or changing FOV. Is there any proper way or tips?? Or, What is good FOV for portrait mobile device screen which can cover most of aspect ratio look ok? I am currently using 45 and force aspect ratio to 2 3


GLSL shader performance reduced by loop? I hav a fragment shader like this version 330 core in vec4 v color in vec2 v texCoords 10 out vec4 frag color uniform int actual textures uniform sampler2D u texture 10 void main() vec4 final color texture(u texture 0 , v texCoords 0 ) for(int i 1 i lt actual textures i ) vec4 tex texture(u texture i , v texCoords i ) final color tex tex.a final color (1 tex.a) frag color v color final color But somehow this slows my game down by 30 40fps in comparison to this approach version 330 core in vec4 v color in vec2 v texCoords 10 out vec4 frag color uniform sampler2D u texture 10 void main() vec4 final color texture(u texture 0 , v texCoords 0 ) vec4 tex texture(u texture 1 , v texCoords 1 ) final color tex tex.a final color (1 tex.a) tex texture(u texture 2 , v texCoords 2 ) final color tex tex.a final color (1 tex.a) ... frag color v color final color Why does a single loop slow the gpu down so much?


Do UV coordinates need correction for moving object? The image above is a static capture of a dynamic OpenGL project I created in which I wrapped a NASA albedo, i.e., sans clouds, image on an OpenGL generated sphere. In so doing, I also generated the UV coordinates associated with each vertex position. This was an incremental learning effort in which I had already applied model matrix corrections to the vertex positions for the rotating and translating (orbiting) "Earth". I was surprised to find that I did not have to apply a model matrix correction to the UV coordinates. I have tentatively concluded that once the jpg image coordinates are associated with the corresponding vertex positions with the UV coordinates in the range of 0, 1 , they are fixed and need no further correction. Does that sound correct, or is there more to the situation?


Texture rotation inside a quad How can I rotate a texture inside a quad without rotating the quad? Here's the code but I'm rotating the whole quad here. glBindTexture(GL TEXTURE 2D, texName5) glMatrixMode(GL TEXTURE) glLoadIdentity() glMatrixMode(GL MODELVIEW) glPushMatrix() glTranslatef(12.8, 10, 10) glRotatef(rotateAd, 1, 0, 0) glBegin(GL QUADS) glNormal3f(1, 0, 0) glTexCoord2f(0.0, 0.0) glVertex3f(0, 3, 3) glTexCoord2f(0.0, 1.0) glVertex3f(0, 3, 3) glTexCoord2f(1.0, 0.0) glVertex3f(0, 3, 3) glTexCoord2f(1.0, 1.0) glVertex3f(0, 3, 3) glEnd() glPopMatrix() Thanks.


What is the correct multiplication order for a 2D matrix? I'm currently trying to create a camera and entity model matrix for my 2D game similar to that of Unity3D. I've already tried to find answers to this question on stackoverflow gamedev but i couldn't find an answer that explains how to center the camera and image. Goal Have a camera matrix wich is centered at the position of the camera. Have a entity matrix wich draws everything centered Current implementation camera matrix Matrix.translation(Screen.width 0.5, Screen.height 0.5) Matrix.rotation(camera.rotation radians) Matrix.scale(camera.scale.x, camera.scale.y) Matrix.translation(camera.x, camera.y) entity matrix Matrix.rotation(entity.rotation radians) Matrix.scale(entity.scale.x, entity.scale.y) Matrix.translation(entity.x, entity.y) image component draw function setMatrix(camera.matrix entity.matrix) drawImage(x 0, y 0, image) position is already included in the entity matrix Results Image rotates around the upper left corner of the screen not around it's center Image is not centered. The image's origin is at its upper left corner. The camera matrix seems to be correct. Questions What is the correct multiplication order for the entity model matrix? Can i use a single matrix for all components of a entity or do i need to calculate in the width height of the image text animation component.


Pretty Sure I have Support for OpenGL 4, but it's not running. What can I do? Many Game Engines require OpenGL to run. I have one of those. I've confirmed that the program and any benchmarks for OpenGL above OpenGL 2 fail to run. Is there, like, a way to confirm I have dependencies or something to that effect? Is it installed or is it just a library included in other programs? Specifically using Ubuntu Linux 17.10, computer specs are fairly low but I've run the Engine on Windows on the same machine before. Linux should have more up to date graphics drivers, so I'm not sure what the root of the problem might be.


Using compressed(ETC1) textures in LibGDX I use standard android tool for compressing PNG texture and archiving it with gzip android sdks tools etc1tool texture.png encodeNoHeader gzip texture.pkm Then I try to load it FileHandle file ... ETC1.ETC1Data data new ETC1.ETC1Data(file) ETC1TextureData td new ETC1TextureData(data, false) Texture texture new Texture(td) But I get an java.nio.BufferOverflowException inside ETC1Data (FileHandle pkmFile) constructor in new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))) int fileSize in.readInt() compressedData BufferUtils.newUnsafeByteBuffer(fileSize) int readBytes 0 while ((readBytes in.read(buffer)) ! 1) compressedData.put(buffer, 0, readBytes) Exception occurs here compressedData.position(0) compressedData.limit(compressedData.capacity()) How to fix it? Thanks. ps if it's important unarchived pkm file size is 33KB


Creating a movable camera using glm lookAt() I came across this tutorial on how to create a movable camera in OpenGL using glm lookAt(glm vec3 position, glm vec3 target, glm vec3 up). In the tutorial, in order to keep the camera always facing in one direction while moving, the view matrix is created as such view glm lookAt(cameraPos, cameraPos cameraFront, cameraUp) , where cameraPos, cameraFront, and cameraUp are all glm vec3 type. What I would like to ask is why does the second argument have to be cameraPos cameraFront? If the camera position moved to the right without changing cameraFront, wouldn't cameraPos cameraFront have an effect of rotating to the right as opposed to staying in the same direction (which I think is what should be needed)?