Confused about why my projection matrix works My projection matrix was buggy, I'm not great at mathematics, but I checked it against the the songho tutorial, and the broken one seems correct to me but switching nearplane to farplane seems to have fixed it. What am I missing? My nearplane and farplane values are positive, nearplane is small about 0.01, 1.0f last time i ran against both farplane is usually relatively large about 1000.0f, 500.0f the last time I ran it against both. f32 l left f32 r right f32 t top f32 b bottom f32 n nearplane f32 f farplane m4x4 Result TODO why did changing n to f in 0 and 5 fix it? and make sure it is fixed if 0 works 2 f (r l), 0, (r l) (r l), 0, 0, 2 f (t b), (t b) (t b), 0, 0, 0, (f n) (f n), 2 f n (f n), 0, 0, 1, 0, else doesn't (2 n) (r l), 0, (r l) (r l), 0, 0, (2 n) (t b), (t b) (t b), 0, 0, 0, (f n) (f n), ( 2 f n) (f n), 0, 0, 1, 0, endif


How to implement weighted blended order independent transparency in OpenGL? I want to implement weighted blended OIT in my C OpenGL 3D game, but I didn't find any C examples about weighted blended order independent transparency. Paper How to clear accumTexture(framebuffer attachment) to vec4(0)? How to clear revealageTexture(framebuffer attachment) to float(1)?


"Highlighting" Faces Edges Corners How would I "highlight" faces edges corners? I would prefer an explanation OpenGL if possible. Here's an example


Order of render with transparency opengl I tried to render using different render configurations (GL BLEND FUNC()) but I couldn't get the back object to render in certain angles. The first screenshot here shows one angle where the back object is not visible through the front one. In th second screenshot, I looked at the blocks from 180 degrees. Is there a way I could render them through? Or would I have to implement a sorting algorithm?


How to store shader output to VRAM? This is really ungrateful question to Google. Basically, I would like to know, regarding openGL, what are various methods to do some kind of computation in one of the shaders and have the results stored in VRAM to be used and accessed at a later time?


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


Heightmap Physics Optimization Improvement I'm working on implementing the physics surrounding a player walking on a heightmap. A heightmap is a grid of points which are evenly spaced on the x and z axes, with varying heights. The physical representation of my player (what is exposed to my physics engine manager) is simply a point mass where his feet are, rather than complicating the problem by treating him as a sphere or a box. This image should help further explain heightmaps and show how triangles are generated from the points. This picture would be looking straight down on a heightmap, and each intersection would be a vertex that has some height. Feel free to move this over to math, physics, or stack overflow, but I'm pretty sure this is where it belongs as it is a programming question related to games. Here's my current algorithm Calculate the player's velocity from input gravity previous velocity etc Move the player's position (nextPos prevPos velocity timeSinceLastFrame) Figure out which triangle (all graphics is done in triangles!) of my heightmap the player's new position is vertically aligned with Use the three vertices of that triangle to calculate the equation for the plane which that triangle lies in Plug in the player's x and z coordinates into the plane's equation to get the y coordinate for the player's position on that plane Set the y coordinate of the player's position to this (if newPos.y lt y) This is all fine and dandy, but I'm wondering if there's anything that I can optimize. For example, my first thought is to store the plane's equation with the triangle's vertex information. This way all I have to do is plug in the x and z values to the equation to get the y. However, this would require adding 4 floats to every vertex of the heightmap which is a little ridiculous memory wise. Also, my heightmaps are dynamic (meaning the heights will change at runtime), which would mean changing the plane equations every time a vertex's height changes. Is there a faster way to calculate that point than digging up the plane's equation and then plugging in x and z? Should I store the plane equations and update them on vertex height change or should I just regenerate the plane equations for every triangle every time the player moves on that triangle? Is there a better way to do heightmap physics that maintains this simplicity? (this seems very simple to me as far as physics engines go)


How to make a triangle pixellated with GLFW? How can one make a triangle look pixelated without modifying the size of the window in GLFW3? Preferably, I'd like to accomplish this without the use of shaders. For example, by setting the size of the frame buffer to be 1 8th the size of the window. I've created an Xcode test project for this and tried setting a small window size to create a small framebuffer, then changing the window size to be big afterwards, but the framebuffer size always changes to match the window size. Example project output Desired output


How can I implement "cut outs" for lighting in OpenGL? So, I'm working with OpenGL (I'm not exactly sure of the version), and I want to do an old style lighting setup by essentially drawing a black rectangle over the screen, and drawing white circles over the areas that should be lit. I already have the rectangle and the circles, but I can't figure out how to make it so that the white circles are transparent when applied to the black areas. Any ideas? I tried to use blending modes, but it still evades me... EDIT Here's the code that I'm using (Python). view buf Buffer(GL INT, 4) glGetIntegerv(GL VIEWPORT, view buf) view view buf.to list() if hasattr(view buf, "to list") else view buf.list glDisable(GL DEPTH TEST) glDisable(GL LIGHTING) glEnable(GL BLEND) if logic.lights 'smooth' glEnable(GL LINE SMOOTH) Make sure we're using smooth shading instead of flat glShadeModel(GL SMOOTH) Setup the matrices glMatrixMode(GL PROJECTION) glPushMatrix() glLoadIdentity() gluOrtho2D(0, view 2 , 0, view 3 ) glMatrixMode(GL MODELVIEW) glPushMatrix() glLoadIdentity() glAlphaFunc(GL GREATER, 0.5) glColor4f(0.0, 0, 0, 0.75) glBegin(GL QUADS) Draw Black screen glVertex2d(0.0, 0.0) glVertex2d(view 2 , 0.0) glVertex2d(view 2 , view 3 ) glVertex2d(0.0, view 3 ) glEnd() glColor4f(1, 1, 1, 1) degtorad 3.14159 180.0 glBlendFunc(GL ZERO, GL SRC ALPHA) def DrawCircle(x, y, radius, fill 1, step 11) glVertex2f(x, y) if fill glBegin(GL TRIANGLE FAN) else glBegin(GL LINE LOOP) for a in range(0, 360, step) angle degtorad a glVertex2f(x (sin(angle) radius), y (cos(angle) radius)) glEnd() for layer in range(len(logic.lights 'layers' )) size for light in logic.lights 'points' DrawCircle(light 0 0 view 2 , (1 light 0 1 ) view 3 , light 1 , step light 2 ) if logic.lights 'smooth' DrawCircle(light 0 0 view 2 , (1 light 0 1 ) view 3 , light 1 , 0, light 2 ) Reset the state glPopMatrix() glMatrixMode(GL PROJECTION) glPopMatrix()


Is learning OpenGL 2.1 useless today? I'm new to 3D OpenGL DirectX world and I found out that OpenGL 4.1 and GLSL specifications were just released today. A friend of mine gave me the Red Book for OGL v2.1 but, as far as I've read, 3.x and 4.x differ a lot from 2.x and a lot of things are deprecated now. Can I use the book to start learning the basics of 3D and CG or is it better to find a newer copy?


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 to render portals in OpenGL? I am making RPG in OpenGl and I need to make some portals. How should I render it if I want to see through the portal on the other side?


SDL AddTimer SDL GL MakeCurrent not working on Windows I'm messing around with C , OpenGL and SDL doing a game that should be able to run in Windows and Mac OS X. I have a problem that only happens on Windows. Let me describe the scenario. First I create an OpenGL renderer and get the current context this gt renderer SDL CreateRenderer(this gt window, rendererIndex, SDL RENDERER ACCELERATED SDL RENDERER PRESENTVSYNC) this gt context SDL GL GetCurrentContext() Complete code here In my scene I add a timer to create some asteroids this gt timer.Start(INTERVAL CREATE ASTEROID, SpaceshipScene CreateAsteroidTimer, this) Internally this timer uses SDL AddTimer and keeps the current window and context for itself this gt window SDL GL GetCurrentWindow() this gt context SDL GL GetCurrentContext() this gt callback callback this gt param param this gt timerId SDL AddTimer(interval, Timer ExecuteCallback, this) When the callback executes I use MakeCurrent to make sure that OpenGL will run in the right context (the window and context from the main thread) bool hasContext timer gt window ! NULL amp amp timer gt context ! NULL if (hasContext) SDL GL MakeCurrent(timer gt window, timer gt context) Uint32 result timer gt callback(interval, timer gt param) if (hasContext) SDL GL MakeCurrent(timer gt window, NULL) Complete code here On Mac OS X this code is working perfectly, but on Windows it isn't drawing the asteroids on the window neither throwing any error. What am I doing wrong?


Getting choppy, jumpy animation Hey I'm trying to get a smooth animation for my player movement. Earlier I changed my frames to render at fixed time(1 60 sec). Well that makes my player now run at a constant speed but the animation now appear to be choppy and it seems like the player jumps from one point to another instead of smoothly transitioning between them. Below is my code and an gif animation of player movement. How do I make the animation appear smooth? float deltaTime 0 float oldTime 0 The direction in which the player will move int playerX 0 int playerY 0 callback method for keyboard events void keyboard callback(GLFWwindow window, int key, int scancode, int action, int mods) if (key GLFW KEY W amp amp action GLFW REPEAT) playerX 0 playerY 1 if (key GLFW KEY S amp amp action GLFW REPEAT) playerX 0 playerY 1 if (key GLFW KEY D amp amp action GLFW REPEAT) playerX 1 playerY 0 if (key GLFW KEY A amp amp action GLFW REPEAT) playerX 1 playerY 0 update player's position void update() player gt move(playerX, playerY, TIME PER FRAME) set up glfw keyboard callback function and other stuff void init() glClearColor(0, 0, 0, 0) player gt bindVertexAttributes(shader.getAttributeLocation("position")) glfwSetKeyCallback(window gt getGLFWWindow(), keyboard callback) wait logic float expected frame end glfwGetTime() TIME PER FRAME void wait() while (glfwGetTime() lt expected frame end) expected frame end TIME PER FRAME playerX playerY 0 rendering function void render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) player gt setUniformMatrixLocation(shader.getUniformLocation("projectionMatrix"), shader.getUniformLocation("transformationMatrix")) shader.useProgram() update() player gt render() wait() shader.stopProgram() main function int main(int argc, char argv) init() main loop while (!glfwWindowShouldClose(window gt getGLFWWindow())) render() window gt swapBuffers() glfwPollEvents() glfwTerminate() return 0


Order independent transparency in particle system I'm writing a particle system and would like to find a trick to achieve proper alpha blending without sorting particles because Each particle is a point sprite in a single mesh and I can't use scene graph ability to sort transparent nodes. The system node should be properly sorted, though. Particle position is computed on shader from initial velocity, acceleration and time. In order to sort the system I would have to perform all this computations on CPU, which is something I want to avoid. Sorting hundreds of particles against camera position and uploading it on GPU each frame seams to be quiet heavy operation. Alpha testing seems to be fast enough on GLES 2.0 and works fine for non transparent but "masked" textures. Still, it's not enough for semi transparent particles. How would you handle this?


How to implement a pannini projection in opengl? I have read about the pannini projection, which involves (I think) projecting a scene onto a cyclinder instead of a rectangle. How can I implement this projection in a vertex shader? Blinky is using lenses and globes, but I don't think it's what I am looking for. The lua script for the pannini projection is not commented https github.com shaunlebron blinky blob master game lua scripts lenses panini.lua As explained on http tksharpless.net vedutismo Pannini the projection works (if I understand it well), by projecting geometry on a cylinder, and then unrolling that cylinder on screen.


LWJGL texture bleeding fix won't work I tried a lot of things to fix texture bleeding, but nothing works. I don't want to add a transparent border around my textures, because I already got too many and it would take too much time and I can't do it with code because I'm loading textures with slick. My textures are seperate textures and they seem to wrap on the other side (texture bleeding). Here are the textures that are "bleeding" The head, body, arm and leg are seperate textures. Here's the code I'm using to draw a texture public static void drawTextureN(Texture texture, Vector2f position, Vector2f translation, Vector2f origin,Vector2f scale,float rotation, Color color, FlipState flipState) texture.setTextureFilter(GL11.GL NEAREST) color.bind() texture.bind() GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE WRAP S, GL12.GL CLAMP TO EDGE) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE WRAP T, GL12.GL CLAMP TO EDGE) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE MAG FILTER, GL11.GL NEAREST) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE MIN FILTER, GL11.GL NEAREST) GL11.glTranslatef((int)position.x, (int)position.y, 0) GL11.glTranslatef( (int)translation.x, (int)translation.y, 0) GL11.glRotated(rotation, 0f, 0f, 1f) GL11.glScalef(scale.x, scale.y, 1) GL11.glTranslatef( (int)origin.x, (int)origin.y, 0) float pixelCorrection 0f GL11.glBegin(GL11.GL QUADS) GL11.glTexCoord2f(0,0) GL11.glVertex2f(0,0) GL11.glTexCoord2f(1,0) GL11.glVertex2f(texture.getTextureWidth(),0) GL11.glTexCoord2f(1,1) GL11.glVertex2f(texture.getTextureWidth(),texture.getTextureHeight()) GL11.glTexCoord2f(0,1) GL11.glVertex2f(0,texture.getTextureHeight()) GL11.glEnd() GL11.glLoadIdentity() I tried a half pixel correction but it didn't make any sense because GL12.GL CLAMP TO EDGE. I set pixelCorrection to 0, but it still wont work.


Creating polygons with separate outline fill colors in OpenGL Subject I am creating a terrain map with triangle strips and I would like to make the bodies of the triangles black, but have their outlines be colored. Problem The solution appears to be to draw the triangles twice, once in solid black, using GL FILL and once in color using GL LINE. The problem with this approach is that, since I am using depth testing and the vertices are at the same position each time, my color lines end up blending with the black lines Attempted Solution According to the OpenGL docs, and other sources, it looks like I should be able to utilize the glPolygonOffset() function to give polygons that are drawn with GL LINE "precedence" in the depth buffer by offsetting their comparison value by the argument to the function. (so I would think 1.0 would be sufficient) This, however, does not appear to be working for me. My Code I have placed glEnable(GL POLYGON OFFSET LINE) in my init function. Here is the code in my draw loop where I do the actual rendering. col is the array that hods the real colors, col2 is filled with black. Please excuse the mess. glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glPolygonOffset(1.0,0.0) glDeleteBuffers(1, amp vertex buffer) vertex buffer createBuffer(GL ARRAY BUFFER, vert, sizeof(GLfloat) (buffer size), GL STATIC DRAW) attributeBind(vertex buffer, 0, 3) glDeleteBuffers(1, amp color buffer) color buffer createBuffer(GL ARRAY BUFFER, col2, sizeof(GLfloat) (buffer size), GL STATIC DRAW) attributeBind(color buffer, 1, 3) glPolygonMode(GL FRONT AND BACK,GL FILL) glDrawArrays(GL TRIANGLE STRIP,0,s) glDeleteBuffers(1, amp color buffer) color buffer createBuffer(GL ARRAY BUFFER, col, sizeof(GLfloat) (buffer size), GL STATIC DRAW) attributeBind(color buffer, 1, 3) glPolygonMode(GL FRONT AND BACK,GL LINE) glDrawArrays(GL TRIANGLE STRIP,0,s) I'm not sure if I need to call glPolygonOffset() each frame or not. These are the attributeBind() and createbuffer() functions void attributeBind(GLuint buffer, int index, int points) glBindBuffer(GL ARRAY BUFFER, buffer) glVertexAttribPointer( index, position or color points, how many dimensions? GL FLOAT, type GL FALSE, normalized? 0, stride (void )0 array buffer offset ) GLuint createBuffer(GLenum target, const void buffer data, GLsizei buffer size, GLenum usageHint) GLuint buffer glGenBuffers(1, amp buffer) glBindBuffer(target, buffer) glBufferData(target, buffer size, buffer data, usageHint) return buffer


Different shader programs but same buffer drawing I've setup 3 different instances of the same shader code (e.g. I've compiled the code into 3 separate programs) For each program, I've gone through the whole route of something like this Setup gl.useProgram(program) const buffer gl.createBuffer() const location gl.getAttribLocation(program, aName) Upload (each uses the buffer location it created in Setup gl.useProgram(program) gl.bindBuffer(gl.ARRAY BUFFER, buffer) gl.bufferData(gl.ARRAY BUFFER, data, usagePattern) gl.vertexAttribPointer(location, nComponents, dataType, false, 0, 0) gl.enableVertexAttribArray(location) Draw gl.useProgram(program) gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0) gl.drawArrays(gl.TRIANGLE STRIP, 0, 4) However, no matter what I pass into data e.g. different sized quads, all three are the same size. Notably, changes to other uniforms attributes like matrices and color do change per object How do I change this so that the changes to data per instance will be drawn properly? (I realize if they actually use the same shader I should maybe keep a reference to one program and use some sort of buffer pool but I'm not there yet, just getting started with WebGL)


Working towards going 3D I am a beginner intermediate C Java programmer and my long term goal is to be a game programmer. I have decided to start off with 2D and work my way towards 3D. I would like to use SDL to start off with, but I am wondering if it is maybe not such a great idea. Given the fact that I am working towards 3D, would it be advisable to use SDL or jump into OpenGL without the Z axis?


What is the purpose of glEdgeFlagv? I know that what both glEdgeFlagv and glEdgeFlag do is toggle boundary edge status, but my question is why does the v version exist when the documentation specifies that the only difference is that glEdgeFlagv takes (quoting from documentation) a pointer to an array that contains a single Boolean element, which replaces the current edge flag value. What's the point of having a special version that takes a pointer to an array of length one? I can't imagine its to let you toggle the pointed to bool to change the value later because the documentation would have to mention that to avoid inadvertent frees. I don't know of any platform where a pointer is smaller than a bool. When would one use glEdgeFlagv instead of glEdgeFlag?


Meaning of knots when drawing a NURBS curve? I'm using gluNurbsCurve to draw some curves with some control points. I've got the basic setup as described in the red book working correctly and I'm trying to expand on it. This sample looks like this float knots 8 0,0,0,0,1,1,1,1 float pnts 4 3 ... , ... , ... , ... GLUnurbsObj m gluNewNurbsRenderer() gluBeginCurve(n) gluNurbsCurve(n, 8, knots, 3, pnts, 4, GL MAP1 VERTEX 3) gluEndCurve(n) One thing I was wondering about is the meaning of the knots data. How does it affect the result? What other options can I experiment there? For some reason I could not find any tutorial which properly explains this.


Direction from the camera to the light source I'm currently writing a game using OpenGL and GLSL. For the shader I need the direction from the current camera to the light source. The lightsource is given by lightSource.position as a uniform as well as the ModelviewMatrix (mat4). The task is TODO compute the vectors from the current vertex towards the camera and towards the light source I need to fill two varyings with those information, but I'm not sure how to compute them. In addition I've the following information version 330 layout(location 0) in vec3 vertex layout(location 1) in vec3 vertex normal


Open Source Engine for RTS I must write a cross platform real time strategy game within 2 3 months. I want use C and OpenGL and am looking for an engine. The engine must be open source and work under both Linux and Windows. Preferably it should work with 3ds Max models. I do not know the game engines. Which engine would you recommend?


Why is GL TEXTURE MAX ANISOTROPY EXT undefined? So I'm writing my texture class in my opengl game, I get to the part where I would normally set GL TEXTURE MAX ANISOTROPY EXT, and I'm shocked to discover that it's undefined! This exact same extensions worked perfectly in a different application, so I know it's not a typo or something. It's worth noting that I'm getting my extensions using glcorearb.h, instead of glext.h, because I have no intention of supporting the compatibility profile. Could this be my problem, and if so, how do I work around it?


Can I use the HD Graphics 3000's quad list primitive type via D3D? I was studying some technical documentation on the Intel HD Graphics 3000 GPU, which I'm using as a lower end reference for my 2D game engine. I noticed the hardware supports a nice "Quad List" topology, where every 4 vertices in a vert buffer are interpreted as an independent quad. My engine draws nothing but sprite quads, so that would be a nice optimization in my case, to eliminate the need for copying caching processing an accompanying index buffer with 12 bytes per quad of trivial triangle edge definitions (I'm using indexed TriangleList primitives at the moment). From what I can tell though, DirectX 9 doesn't expose quad list, and after some cursory peeking around in DX10 11 (which I don't plan to support at this point) it seems they don't expose this feature either. Does anyone know if there's a way to use Quad Lists in DirectX? I'd be curious about OpenGL also, if anyone has experience on that side.


Zooming to point of interest I have the following variables Point of interest which is the position(x,y) in pixels of the place to focus. Screen width,height which are the dimensions of the window. Zoom level which sets the zoom level of the camera. And this is the code I have so far. void Zoom(int pointOfInterestX,int pointOfInterstY,int screenWidth, int screenHeight,int zoomLevel) glScalef(1,1,1) glTranslatef( (pointOfInterestX 2) (screenWidth 2), (pointOfInterestY 2) (screenHeight 2),0) glScalef(zoomLevel,zoomLevel,1) And I want to do zoom in out but keep the point of interest in the middle of the screen. but so far all of my attempts have failed and I would like to ask for some help.


Rendering (rasterization ray tracing others) I'm completely new to this graphics and game development. I have read about Rendering (drawing a 3D graphic on a display 2D) and there are many ways of rendering, Rasterization, Ray tracing, radiosity, ray casting. And my doubt is if OpenGl implements one of these. I mean with OpenGL I can draw lines, circles and so on, so there should be a rendering algorithm on OpenGL, am I right? Which one is it? What if I want to implement a different rendering algorithm, does this mean I'm no longer using OpenGL?


Skybox OpenGL texCUBE vs a textured cube In OpenGL, the typical way that I've seen to set up a skybox using cubemapping is to create a cube in camera space, prepare a cubemap sampler with the appropriate six sided texture, and then in the pixel shader use the camera space direction of the pixel as the input to texCUBE. What I'm wondering is, if instead of this, I set up the same cube, but then simply textured each face of the cube with the appropriate face of the cubemap texture, and then rendered the cube with a standard shader, would it achieve the same visual effect?


(LWJGL) Pixel Unpack Buffer Object is Disabled? (glTextImage2D) I am trying to create a render target for my game so that I can re render at a different screen size. But I am receiving the following error Exception in thread "main" org.lwjgl.opengl.OpenGLException Cannot use offsets when Pixel Unpack Buffer Object is disabled Here is the source code for my Render method clear screen GL11.glClear(GL11.GL COLOR BUFFER BIT GL11.GL DEPTH BUFFER BIT) Start FBO Rendering Code The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. int FramebufferName GL30.glGenFramebuffers() GL30.glBindFramebuffer(GL30.GL FRAMEBUFFER, FramebufferName) The texture we're going to render to int renderedTexture glGenTextures() "Bind" the newly created texture all future texture functions will modify this texture glBindTexture(GL TEXTURE 2D, renderedTexture) Give an empty image to OpenGL ( the last "0" ) glTexImage2D(GL TEXTURE 2D, 0,GL RGB, 1024, 768, 0,GL RGB, GL UNSIGNED BYTE, 0) Poor filtering. Needed ! glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) Set "renderedTexture" as our colour attachement 0 GL32.glFramebufferTexture(GL30.GL FRAMEBUFFER, GL30.GL COLOR ATTACHMENT0, renderedTexture, 0) Set the list of draw buffers. IntBuffer drawBuffer BufferUtils.createIntBuffer(20 20) GL20.glDrawBuffers(drawBuffer) Always check that our framebuffer is ok if(GL30.glCheckFramebufferStatus(GL30.GL FRAMEBUFFER) ! GL30.GL FRAMEBUFFER COMPLETE) System.out.println("Framebuffer was not created successfully! Exiting!") return Resets the current viewport GL11.glViewport(0, 0, scaleWidth scale, scaleHeight scale) GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() let subsystem paint if (callback ! null) callback.frameRendering() update window contents Display.update() It is crashing on this line glTexImage2D(GL TEXTURE 2D, 0,GL RGB, 1024, 768, 0,GL RGB, GL UNSIGNED BYTE, 0) I am not really sure why it is crashing and looking around I have not been able to find out why. Any help or insight would be greatly welcome.


OpenGL shows a black screen I am new at OpenGL, I try this example https stackoverflow.com a 31524956 4564882 but I get only a black widget. The code is exactly the same. this is the code associated to the QopenGLWidget OGLWidget OGLWidget(QWidget parent) QOpenGLWidget(parent) OGLWidget OGLWidget() void OGLWidget initializeGL() glClearColor(0,0,0,1) glEnable(GL DEPTH TEST) glEnable(GL LIGHT0) glEnable(GL LIGHTING) glColorMaterial(GL FRONT AND BACK, GL AMBIENT AND DIFFUSE) glEnable(GL COLOR MATERIAL) void OGLWidget paintGL() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glBegin(GL TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex3f( 0.5, 0.5, 0) glColor3f(0.0, 1.0, 0.0) glVertex3f( 0.5, 0.5, 0) glColor3f(0.0, 0.0, 1.0) glVertex3f( 0.0, 0.5, 0) glEnd() void OGLWidget resizeGL(int w, int h) glViewport(0,0,w,h) glMatrixMode(GL PROJECTION) glLoadIdentity() gluPerspective(45, (float)w h, 0.01, 100.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() gluLookAt(0,0,5,0,0,0,0,1,0) I tried the example here https doc.qt.io archives qt 5.3 qtopengl 2dpainting example.html. It works fine (trying the both base class QGLWidget and QOpenGLWidget. this is the code associated to the Widget GLWidget GLWidget(Helper helper, QWidget parent) QGLWidget(QGLFormat(QGL SampleBuffers), parent), helper(helper) elapsed 0 setFixedSize(200, 200) setAutoFillBackground(false) void GLWidget animate() elapsed (elapsed qobject cast lt QTimer gt (sender()) gt interval()) 1000 repaint() void GLWidget paintEvent(QPaintEvent event) QPainter painter painter.begin(this) painter.setRenderHint(QPainter Antialiasing) helper gt paint( amp painter, event, elapsed) painter.end() I use Qt 5.5.1 binairies built on my machine. I let the Build Configuration by default, so it is based on Qt ANGLE not Desktop OpenGL. My Graphic card Driver is updated. What is the problem of such a behaviour?


Best way to detect if vec3 is between vec3(x) and vec3(y) in glsl As titled I am sampling from a texture and if the color is somehow gray vec3(.8), vec3(.9) and an uniform is 1 I need to substitute that color with another one I am not a glsl veteran but I am pretty sure there is a more elegant and compact (without mentioning faster) way than this vec3 textureColor texture(texture0, oUV) if(settings.w 1 amp amp textureColor.r gt .8 amp amp textureColor.r lt .9 amp amp textureColor.g gt .8 amp amp textureColor.g lt .9 amp amp textureColor.b gt .8 amp amp textureColor.b lt .9)


Custom complex body shape with cut feature I need to create sprites (or scene2d actors or whatever) with custom shape, preferably generated from a png image (marching squares?). I followed some Mesh tutorials but they all hardcode the triangularized shape vertices in an array, which is completely insane. I will later have to give my sprite a cut feature, like this game. so I'll have to regenerate and redraw a new shape several times. Some told me to review the Drawable classes as well as Mesh, and create my own MeshDrawable that renders using meshes. Do you have an idea of how to dynamically generate vertices and shapes instead of hardcoding coordinates? at what level will my Mesh be responding to touch events and reacting with the user? Any clarification will be welcome, I'm kind of lost.


Earth and sun How to make the sun revolve around the earth in the following code? I want to imitate the planetary system with Earth and Sun drawn as solid spheres on the same window. I have drawn the two the earth as the bigger sphere and the sun as the smaller sphere. Now I want the earth to revolve around the sun when I press key A and when I press key B the earth must rotate around its axes. How do I achieve this? Thanks. Here is the code so far include lt GL glut.h gt void init(void) glClearColor(0.0,0.0,0.0,0.0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) void display(void) glClearColor(0.05,0.05,0.5,0.0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glColor3f(0.03,0.05,0.09) glutSolidSphere(0.5,30,30) Earth glMatrixMode(GL MODELVIEW) glLoadIdentity() glTranslatef(.7,.7,.7) glColor3f(1.0,1.0,1.0) glutSolidSphere(0.2,50,50) Sun glLoadIdentity() glFlush() int main(int argc, char argv) glutInit( amp argc, argv) glutInitDisplayMode(GLUT SINGLE) glutInitWindowPosition(10,10) glutInitWindowSize(400,400) init() glutCreateWindow("Planets") glutDisplayFunc(display) glFlush() glutMainLoop()


Simple, casual open source OpenGL games to implement other things in I am looking for a simple casual game (open source) done in openGL. I need it to implement communication component i build this is not for learning opengl and to implement some other stuff into it. Where can I find one? (I am using C ) Thanks


OpenGL glDisable(GL TEXTURE 2D) vs glBindTexture(GL TEXTURE 2D,0) I would like to ask which one of these is better to use after I finished my texture rendering. glDisable(GL TEXTURE 2D) glBindTexture(GL TEXTURE 2D,0) Is there any difference performance wise?


How can I get my meshes to work with Bullet Physics? The problem is that I'm trying to use my meshes with Bullet Physics for the collision part of my game. When I attempted doing this method with my GLM(model loading library by nate robins) model, I get a segmentation fault in the debug, so I figured that it doesnt like the coordinate variables of the model. If i use blender to export my model as a collision file, what type of file should I use? I have heard of a .bullet exporter, but i dont know hot to integrate this python script into my Blender 2.5 program.


How to create realistic rainfall animation in modern OpenGL using shaders? I see many examples of particle system in old style OpenGL with falling raindrops. Examples of rainfall that can interact with environment lighting and look realistic are hard to find. How to create realistic rainfall animation in modern OpenGL using shaders?


Finding correct index of triangles I'm generating a basic terrain and it looks something like this Load the vertex and index array with the terrain data. for (j 0 j lt (m terrainHeight 1) j ) for (i 0 i lt (m terrainWidth 1) i ) index1 (m terrainHeight j) i Top left. index2 (m terrainHeight (j 1)) i Bottom left. index3 (m terrainHeight j) (i 1) Top right. index4 (m terrainHeight (j 1)) (i 1) Bottom right. Top left vertices index .position glm vec3(m heightMap index1 .x, m heightMap index1 .y, m heightMap index1 .z) vertices index .texture glm vec2(m heightMap index1 .tu 0.0f, m heightMap index1 .tv 0.0f) indices index index index Bottom left. vertices index .position glm vec3(m heightMap index2 .x, m heightMap index2 .y, m heightMap index2 .z) vertices index .texture glm vec2(m heightMap index2 .tu 0.0f, m heightMap index2 .tv 1.0f) indices index index index Top right. vertices index .position glm vec3(m heightMap index3 .x, m heightMap index3 .y, m heightMap index3 .z) vertices index .texture glm vec2(m heightMap index3 .tu 1.0f, m heightMap index3 .tv 0.0f) indices index index index Top right. vertices index .position glm vec3(m heightMap index3 .x, m heightMap index3 .y, m heightMap index3 .z) vertices index .texture glm vec2(m heightMap index3 .tu 1.0f, m heightMap index3 .tv 0.0f) indices index index index Bottom left. vertices index .position glm vec3(m heightMap index2 .x, m heightMap index2 .y, m heightMap index2 .z) vertices index .texture glm vec2(m heightMap index2 .tu 0.0f, m heightMap index2 .tv 1.0f) indices index index index Bottom right vertices index .position glm vec3(m heightMap index4 .x, m heightMap index4 .y, m heightMap index4 .z) vertices index .texture glm vec2(m heightMap index4 .tu 1.0f, m heightMap index4 .tv 1.0f) indices index index index Now If I wanted to find which grid square the player is on, we could simply (if the camera position is relative to the terrain) Grid square the camera is on int gridX (int)std floor(cameraX gridSquareSize) int gridZ (int)std floor(cameraZ gridSquareSize) Continuing, we know that each face consists of two triangles, and the top triangle is represented by three vertices which index corresponds to top left, bottom left and top right. The bottom triangle would then be top right, bottom left and bottom right. Now I'm having a hard time trying to find height values (y values) at these points because if I try to do Top left triangle glm vec3(0, vertices (m terrainHeight gridZ) gridX .position.y, 0) Top left glm vec3(0, vertices (m terrainHeight (gridZ) 1) gridX .position.y, 1) Bottom left glm vec3(1, vertices ((m terrainHeight gridZ)) (gridX 1) .position.y, 0) Top right we conclude that the top left and bottom left position will be okay, but the top right position won't get the correct index, because as it is now (if we say that gridX 0 and gridZ 0), the index will generate a value of 1, which is not the correct height value at that position because the index we want should be 2 (top right). So, is there a way I could write the code so I would get the correct index for the triangles of the terrain?


Compress 16 bit raw data in webgl I have a 3D volume where every voxel is 16 bits. Is there anyway I can use some kind of compression to store the data so I can use less video ram? Webgl supported different compressiosn if you enable them with extension, but can I use them for a one channel data? Like WEBGL compressed texture s3tc only supports rgb and rgba data COMPRESSED RGB S3TC DXT1 EXT COMPRESSED RGBA S3TC DXT1 EXT COMPRESSED RGBA S3TC DXT3 EXT COMPRESSED RGBA S3TC DXT5 EXT If its not possible in webgl, is it supported in OpenGL to compress a 16 bit values with one channel?


How to debug a GLSL shader? I cannot find any tutorial in Google and Youtube. I have a C program that uses OpenGL ES 2.0 API to render something on the screen. How can I debug my shaders? Any step by step guide? What is the easiest way to at least print variable values?


OpenGL shaders messed up So after a long attempt at DirectX I switched back to good old OpenGL. Now I'm running into this weird problem. My code involves shaders, of course, and drawing a basic cube. But I'm getting this weird shape. I've never seen this before. I was just wondering what could possibly be causing this? Thanks very much! Initialization lightingShader gt GenerateVAO() lightingShader gt GenerateVBO() lightingShader gt SetVertices(vertices, sizeof(vertices), GL STATIC DRAW) lightingShader gt BindVAO() lightingShader gt AddAttribute(0, 3, GL FLOAT, GL FALSE, 3, 0) lightingShader gt UnbindVAO() Rendering lightingShader gt Use() GLint objectColorLoc lightingShader gt GetUniformLocation("objectColor") GLint lightColorLoc lightingShader gt GetUniformLocation("lightColor") glUniform3f(objectColorLoc, 1, 0.5f, 0.31f) glUniform3f(lightColorLoc, 1, 0.5f, 1) GLint modelLoc lightingShader gt GetUniformLocation("model") GLint viewLoc lightingShader gt GetUniformLocation("view") GLint projLoc lightingShader gt GetUniformLocation("projection") glUniformMatrix4fv(viewLoc, 1, GL FALSE, glm value ptr(game gt GetCamera() gt View())) glUniformMatrix4fv(projLoc, 1, GL FALSE, glm value ptr(game gt GetCamera() gt Projection())) lightingShader gt BindVAO() glm mat4 model glUniformMatrix4fv(modelLoc, 1, GL FALSE, glm value ptr(model)) glDrawArrays(GL TRIANGLES, 0, 36) lightingShader gt UnbindVAO() Result As you can see, position and color is set fine, but I still get that weird shape.


glfwCreateWindow function returning NULL I am working on creating a game engine using GLFW. To begin, I set up a window class in C to test how making a window works. For some reason, when I call the glfwCreateWindow function, it returns NULL instead of GLFWwindow . Here is my code (I have a header file that defines the class and then the c file that defines the class) Here is the window.h header file pragma once include lt iostream gt include lt GLFW glfw3.h gt namespace harmony namespace graphics class Window private const char m Title int m Width, m Height GLFWwindow m Window bool m Closed public Window(const char name, int width, int height) Window() bool closed() const void update() const private bool init() And here is the c window.cpp file include "window.h" namespace harmony namespace graphics Window Window(const char title, int width, int height) m Title title m Width width m Height height if (!init()) glfwTerminate() Window Window() glfwTerminate() bool Window init() if (!glfwInit) std cout lt lt "Failed to initialized" lt lt std endl return false m Window glfwCreateWindow(m Width, m Height, m Title, NULL, NULL) if (!m Window) std cout lt lt "Failed to create window!" lt lt std endl return false glfwMakeContextCurrent(m Window) return true bool Window closed() const return glfwWindowShouldClose(m Window) void Window update() const glfwPollEvents() glfwSwapBuffers(m Window) And lastly here's my main.cpp include "window.h" int main() using namespace harmony using namespace graphics Window window("Yay it works!", 800, 600) while (!window.closed()) window.update() return 0 I looked it up and there are only a couple cases (in the source code of glfwCreateWindow) where it returns NULL, but I haven't found a good way to troubleshoot which one.


Chessboard colors with VBO I am trying to draw a chessboard pattern using VBO. Geometrywise, I have it implemented and working nicely. However, I have come to the point where I want to color up the board and I have realized that I cannot do it because vertices should be black and white at the same time, depending which square they are drawing. So, looks like I cannot create a color array the same way I create a vertex array. Any ideas how I can sort this out? Is there anyway to assign two colors to the same vertex, and select one or another depening on the actual square being rendered? This is the code I am using so far, which is generating a nice "white to black" diagonal pattern instead of the chessboards like. glGenBuffersARB(1, amp VBOfloorVerticesAndNormals) glBindBufferARB(GL ARRAY BUFFER ARB, VBOfloorVerticesAndNormals) glBufferDataARB(GL ARRAY BUFFER ARB, numVertices sizeof(float), vertices, GL STATIC DRAW ARB) glGenBuffersARB(1, amp VBOcolors) glBindBufferARB(GL ARRAY BUFFER ARB, VBOcolors) glBufferDataARB(GL ARRAY BUFFER ARB, numColors sizeof(float), colors, GL STATIC DRAW ARB) glGenBuffersARB(1, amp VBOfloorIndex) glBindBufferARB(GL ELEMENT ARRAY BUFFER ARB, VBOfloorIndex) glBufferDataARB(GL ELEMENT ARRAY BUFFER ARB, numIndices sizeof(int), indices, GL STATIC DRAW ARB) glEnableClientState(GL VERTEX ARRAY) glBindBufferARB(GL ARRAY BUFFER ARB, VBOfloorVerticesAndNormals) glVertexPointer(3, GL FLOAT, 0, 0) glEnableClientState(GL COLOR ARRAY) glBindBufferARB(GL ARRAY BUFFER ARB, VBOcolors) glColorPointer(4, GL FLOAT, 0, 0) glIndexPointer(GL UNSIGNED SHORT, 0, 0) glDrawElements(GL QUADS, numIndices, GL UNSIGNED INT, 0) glDisableClientState(GL VERTEX ARRAY) glDisableClientState(GL COLOR ARRAY) glBindBufferARB(GL ARRAY BUFFER ARB, 0) glBindBufferARB(GL ELEMENT ARRAY BUFFER ARB, 0) And this is the pattern I get


Animation of moving circle by square's outer surface I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like Main problem is that I can not figure out how to move by corner circle should smoothly move by corner, not to just jump to another side's begin position. import Blender from Blender import Draw,BGL from Blender.BGL import from math import sin,cos import time squareLength, squareX, squareY, circleRadius 200, 200, 200, 20 movingX, movingY 0, 0 def event(evt, val) if evt Draw.ESCKEY Draw.Exit() def gui() global movingX, movingY glClearColor(0.17, 0.24, 0.31, 1.0) glClear(BGL.GL COLOR BUFFER BIT) glLineWidth(1) glColor3f(0.74, 0.76, 0.78) glBegin(GL QUADS) glVertex2i(squareX, squareY) glVertex2i(squareX, squareY squareLength) glVertex2i(squareX squareLength, squareY squareLength) glVertex2i(squareX squareLength, squareY) glEnd() glColor3f(0.58, 0.65, 0.65) glPushMatrix() if movingX circleRadius if movingY lt squareLength movingY 1 else movingX 0 movingY squareLength circleRadius else if movingY squareLength circleRadius if movingX lt squareLength movingX 1 else movingX squareLength circleRadius movingY squareLength else if movingY lt 0 if movingX gt 0 movingX 1 else movingX circleRadius movingY 0 else if movingY gt 0 movingY 1 else movingX squareLength movingY circleRadius glTranslatef(movingX, movingY, 0) glBegin(GL LINE LOOP) for i in xrange(0, 360, 1) glVertex2f(squareX sin(i) circleRadius, squareY cos(i) circleRadius) glEnd() glPopMatrix() Draw.Redraw(1) Draw.Register(gui, event, None) Can you please say me, how can I optimize this code to make circle moving by corners? Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.


An API independent way of managing video memory? I'm developing a game. The game architecture is very modular. I have a "Graphics Engine", which uses either a Direct3D or OpenGL renderer. However the user does not have access to the renderers directly. Instead the "Graphics Engine" class is used, which uses a renderer interface. I also have a resource management system. As for now, the renderers are respoinsible for allocating and releasing video memory. That couples my design in a bad way, since the "Graphics Engine" has undesirable logic for transferring resources between the RAM and the VideoRam through sending signals to the "Renderer". I want the resource management system to be responsible for allocating video memory. I want to decouple the "Renderer" and "Graphics Engine" classes as much as possible, and make the renderer only responsible for rendering. Is there a way to obtain a universal pointer to a Video RAM buffer, and use it to render with both renderers? My problem is basically that I can only obtain OpenGL or Direct3D handles, which can be used only from the relevant API. And the "Graphics Engine" should not know which renderer it uses.


Why does my blur shader implementation produce this strange result? I tried to implement the blur shader shown here. Instead of having a simple 2D texture I use Unity's GrabPass function to capture what's behind the plane to have a transparent effect. Then I apply this on a 3D plane struct v2f float4 pos SV POSITION float4 screenPos TEXCOORD3 float3 uv v2f vert(appdata full v) v2f o o.pos mul(UNITY MATRIX MVP, v.vertex) o.screenPos ComputeScreenPos(o.pos) o.uv UNITY PROJ COORD(o.screenPos) return o In the frag part there is the shader blur computation but based on XYZ, with Z 0 Then I apply the blur and this leads to this when I zoom in Is there a way to avoid this effect?


How forward rendering done using OpenGL? Recently I come across the term forward rendering. I'm kind of curious how this could be done in OpenGL. I have done a lot of search on this, majority of the result I get are on theory but not code implementation. May I know is there any code implementation on OpenGL for this rendering technique?


How can I insert and remove blocks quickly in a Minecraft style world? I currently have volume data for the world stored as an array of booleans. I then check each empty block and if it has non empty neighbors the faces get drawn. This prevents me from sending a bunch of faces to the graphics card using OpenGL. I'm now working on inserting and removing blocks but I'm not sure how to do this quickly. It is simple enough to change the volume data but I don't want to recompute all the vertices from the volume data each time someone inserts or removes a block. It occurred to me just to add the block to the vertex buffer at the end of the existing vertex data but then I don't have a good way of destroying it as I have no way to correlate between the volume and vertex buffer data. Any thoughts on how I can fix the mess I'm in?


Improve bloom quality I'm trying to understang how can I improve bloom effect quality using all known to me optimizations. Currently I'm making it as follows Create new texture using some threshold to extracts areas which should glow Downsample that texture 4 times (using bilinear filtering GL LINEAR) Blur each texture horizontally using 5x5 gaussian blur. Blur each texture vertically using 5x5 gaussian blur. Composite each blurred texture with final image. I've implemented gaussian blur using Incremental Gaussian Algorithm and set radius to 5. However because of size of last texture after composition bloom has very low quality especially when moving camera It doesn't look clear here but you can see it near bunny tail. Simple workaround to that issue was increasing the radius for smaller textures but then image was more blurred. Similar effect is when I use solution presented by Philip Rideout. I get better results when I use blur shader presented here. However I still see some kind of vertical stripes. I also tried to improve the algorithm by blurring the image and then downsampling it. Then I repeated whole process for the rest of images. But I haven't spotted any difference. I'm also wonder how it is done in Unreal Engine. I mean how effective blur radius is computed. Documentation claims that each Bloom Size value is "the size in percent of the screen width" and each texture is smaller from previous one 2 times.


C Help with Separating Axis Theorem I am trying to detect collision between two triangles using Separating Axis Theorem however I am unaware what is wrong with my code. The CollisionHelper isTriangleIntersectingTriangle is called every frame and passes in the vertices of both triangles. It never returns true, however. I've been stuck on this for days now. Any help is appreciated. glm vec3 CalcSurfaceNormal(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3) Subtracts each coordinate respectively glm vec3 u tri2 tri1 glm vec3 v tri3 tri1 glm vec3 nrmcross glm cross(u, v) nrmcross glm normalize(nrmcross) return nrmcross bool SATTriangleCheck(glm vec3 axis, glm vec3 tri1vert1, glm vec3 tri1vert2, glm vec3 tri1vert3, glm vec3 tri2vert1, glm vec3 tri2vert2, glm vec3 tri2vert3) int t1v1 glm dot(axis, tri1vert1) int t1v2 glm dot(axis, tri1vert2) int t1v3 glm dot(axis, tri1vert3) int t2v1 glm dot(axis, tri2vert1) int t2v2 glm dot(axis, tri2vert2) int t2v3 glm dot(axis, tri2vert3) int t1min glm min(t1v1, glm min(t1v2, t1v3)) int t1max glm max(t1v1, glm max(t1v2, t1v3)) int t2min glm min(t2v1, glm min(t2v2, t2v3)) int t2max glm max(t2v1, glm max(t2v2, t2v3)) if ((t1min lt t2max amp amp t1min gt t2min) (t1max lt t2max amp amp t1max gt t2min)) return true if ((t2min lt t1max amp amp t2min gt t1min) (t2max lt t1max amp amp t2max gt t1min)) return true return false bool CollisionHelper isTriangleIntersectingTriangle(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3, glm vec3 otherTri1, glm vec3 otherTri2, glm vec3 otherTri3) Triangle surface normals, 2 axes to test glm vec3 tri1FaceNrml CalcSurfaceNormal(tri1, tri2, tri3) glm vec3 tri2FaceNrml CalcSurfaceNormal(otherTri1, otherTri2, otherTri3) glm vec3 tri1Edge1 tri2 tri1 glm vec3 tri1Edge2 tri3 tri1 glm vec3 tri1Edge3 tri3 tri2 glm vec3 tri2Edge1 otherTri2 otherTri1 glm vec3 tri2Edge2 otherTri3 otherTri1 glm vec3 tri2Edge3 otherTri3 otherTri2 axes TODO may need to (un)normalize the cross products glm vec3 axis1 tri1FaceNrml glm vec3 axis2 tri2FaceNrml glm vec3 axis3 glm normalize(glm cross(tri1Edge1, tri2Edge1)) glm vec3 axis4 glm normalize(glm cross(tri1Edge1, tri2Edge2)) glm vec3 axis5 glm normalize(glm cross(tri1Edge1, tri2Edge3)) glm vec3 axis6 glm normalize(glm cross(tri1Edge2, tri2Edge1)) glm vec3 axis7 glm normalize(glm cross(tri1Edge2, tri2Edge2)) glm vec3 axis8 glm normalize(glm cross(tri1Edge2, tri2Edge3)) glm vec3 axis9 glm normalize(glm cross(tri1Edge3, tri2Edge1)) glm vec3 axis10 glm normalize(glm cross(tri1Edge3, tri2Edge2)) glm vec3 axis11 glm normalize(glm cross(tri1Edge3, tri2Edge3)) Perform SAT if (SATTriangleCheck(axis1, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis2, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis3, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis4, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis5, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis6, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis7, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis8, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis9, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis10, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis11, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true return false


OpenGL float not working? I have a float array in my terrainFragmentShader to load render the biomes, however the code simply does not work. No errors are being cast and when I remove the code biomeMap int(pass textureCoordinates.x) int(pass textureCoordinates.y) by either deleting that section or manually setting it, it loads the appropriate texture. vec4 textureColour texture(backgroundTexture, pass textureCoordinates) float c biomeMap int(pass textureCoordinates.x) int(pass textureCoordinates.y) if(c lt 0) textureColour texture(sandTexture, pass textureCoordinates) else if(c lt 32) textureColour texture(stoneTexture, pass textureCoordinates) All three textures load just fine and are rendered when not using this method and the biomes are being properly loaded and initialized. Loading public void loadBiomes(float biomeMap) for(int x 0 x lt Terrain.VERTEX COUNT x ) for(int y 0 y lt Terrain.VERTEX COUNT y ) super.loadFloat(location biomeMap x y , biomeMap x y ) Initializing location biomeMap new int Terrain.VERTEX COUNT Terrain.VERTEX COUNT for(int x 0 x lt Terrain.VERTEX COUNT x ) for(int y 0 y lt Terrain.VERTEX COUNT y ) location biomeMap x y super.getUniformLocation("biomeMap " x " " y " ") And finally here is the entire terrainFragmentShader version 400 core in vec2 pass textureCoordinates in vec3 surfaceNormal in vec3 toLightVector in vec3 toCameraVector in int biomeSize out vec4 out Color uniform sampler2D backgroundTexture uniform sampler2D sandTexture uniform sampler2D stoneTexture uniform vec3 lightColour uniform float shineDamper uniform float reflectivity uniform float biomeMap 128 128 uniform float offsetX uniform float offsetZ const int levels 32 void main(void) vec4 textureColour texture(backgroundTexture, pass textureCoordinates) float c biomeMap int(pass textureCoordinates.x) int(pass textureCoordinates.y) if(c lt 0) textureColour texture(sandTexture, pass textureCoordinates) else if(c lt 32) textureColour texture(stoneTexture, pass textureCoordinates) vec3 unitNormal normalize(surfaceNormal) vec3 unitLightVector normalize(toLightVector) float nDotl dot(unitNormal,unitLightVector) float brightness max(nDotl, 0.25) vec3 unitVectorToCamera normalize(toCameraVector) vec3 lightDirection unitLightVector vec3 reflectedLightDirection reflect(lightDirection, unitNormal) vec3 totalDiffuse brightness lightColour out Color vec4(totalDiffuse,1.0) textureColour Why isn't the biome not loading? Is it an issue in me not getting the appropriate x y from the pass textureCoordinates?


Pixel perfect clickable picture in OpenGL C So I have a picture(for easier understanding of problem like this http www.lib.utexas.edu maps europe europe 95.jpg). My goal is to click on any of the countries and get what country I clicked. The picture is full of colors, not just simple lets say Germany is purple. Also if I hover above a country I could also do things, like highlight it, write some text in a bar, etc. What solutions popped in my mind Draw every slice into a mesh, and ray trace the click. (making lots of meshes is a lot of time) Draw a single quad with texture, make a pixelmap, and get the coordinates clicked, then look up in the table.(I have to make a map for every resolution) Is there any better way of doing this? Or are there any algorithms for it?


Font loads with artifacts I've recently come on to an error when loading fonts in my game, some letters show up perfect while others have artifacts around them. Here's an example of this While some letters are perfectly normal, others are being unstable. My options menu This is what my loader method looks like. (Yes i've tried other fonts) private static int loadTexture(BufferedImage image) int BYTES PER PIXEL 4 int pixels new int image.getWidth() image.getHeight() image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()) ByteBuffer buffer BufferUtils.createByteBuffer(image.getWidth() image.getHeight() BYTES PER PIXEL) for(int y 0 y lt image.getHeight() y ) for(int x 0 x lt image.getWidth() x ) int pixel pixels y image.getWidth() x buffer.put((byte) ((pixel gt gt 16) amp 0xFF)) Red component buffer.put((byte) ((pixel gt gt 8) amp 0xFF)) Green component buffer.put((byte) (pixel amp 0xFF)) Blue component buffer.put((byte) ((pixel gt gt 24) amp 0xFF)) Alpha component. Only for RGBA buffer.flip() int textureID glGenTextures() glBindTexture(GL TEXTURE 2D, textureID) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA8, image.getWidth(), image.getHeight(), 0, GL RGBA, GL UNSIGNED BYTE, buffer) return textureID


How can I implement beam effects like these? I am interested in the techniques I could use to create the following effects Can I accomplish this with a particle system or a series of texture quads, or what? You can see this effects in action here in this video.


Calculating the weights of matrices bones in opengl glsl I have a basic shape that I want to render. Nothing too complex, just a tall cube. And I want to attach 2 bones to it. Not only that, but I also want one of the bones matrices to influence the cube more than the other bone, say 60 40 ratio. Can someone show or explain how to do this? I've been trying to find an explanation for this the past few days without luck. How to calculate the weight of a bone matrix and how (much) effect it will have on the vertex transformation. Im just using basic c opengl for this, looking for an explanation about how weights are calculated in, especially if there are multiple bones.


How to draw realtime 3D amoebas in OpenGL? How would one draw 3D amoebas in real time in OpenGL? The key components I'm looking for are Curved closed surface that changes shape Generally transparent Something translucent inside showing the volume is occupied It has to be in real time, and be able to handle many (100's) of these moving and animating on screen simultaneously. What techniques might one use to accomplish this?


First Person Camera Target I have a camera at position P, and a normalized direction vector D (where the camera is facing). I want the target of the camera to be 5 units forward from the position. Here's my attempt F (0, 0, 5) forward target P (D F) The obvious problem is that D F can eventually reach (0, 0, 0), which would cause the target to be equal to the initial position. I feel like I'm missing something even more obvious than the problem here but, how would I properly have the target be 5 units forward?


How does this snippet of code create a ray direction vector? In the Minecraft source code, this code is used to create a direction vector for a ray from pitch and yaw ' float f1 MathHelper.cos( rotationYaw 0.01745329F 3.141593F) float f3 MathHelper.sin( rotationYaw 0.01745329F 3.141593F) float f5 MathHelper.cos( rotationPitch 0.01745329F) float f7 MathHelper.sin( rotationPitch 0.01745329F) return Vec3D.createVector(f3 f5, f7, f1 f5) I was wondering how it worked, and what is the constant 0.01745329F?


Optimization of rendering of cube world I have a world made of many cubes (like in Minecraft), they have only color (not texture). I am rendering them using OpenGL 3.3 core profile (GLFW3, GLAD, GLM). I am already have done some optimizations not rendering internal faces backface culling rendering faces using GL TRIANGLES and indexing But it's still a lot slower than Minecraft, but Minecraft is in Java and blocks have textures, there is bigger world (there are entities etc. too)! How can I optimize my program further? It may be something with pre computing. Player rarely change the world (only small part of ticks). I am currently filtering faces with this code for every block if (blocks x y z ! nullptr) nullptr means that block is air bool drawSides 6 if (world.GetBlockAt(BlockPos(x, y, z 1)) ! nullptr) drawSides 0 false internal face, culled else drawSides 0 true draw that side other 5 sides ... blocks x y z .draw(sides)


How to only render part of an image in lwjgl openGL I'm making a mining building game in java using slick2D and I want to make it so you can only see a few blocks in any direction while you are underground. The best example I could find of what I want to do is the game miner dig deep. One way I thought of doing it would be to have a large image and just draw transparent areas on it where you need to be able too see but even if that would be an efficient method I wouldn't be sure how to do that.


Not repeating background in platformer I need to make not repeating background for platformer. I can't find any description of implementation and I developed algorithm but I'm not sure that it's right. I can't load one big texture per level, because many devices don't support textures more than 2048x2048 pixels and my levels require 4096 pixels at least on the one side. Therefore I have to cut big texture into smalls(512x512, 1024x1024), load them using separate thread and render. Picture shows it Green rectangle is screen(for example Nexus S with display 800x480) Problems In case 2 layers I have to keep in memory 4 big textures. I have to constantly load and unload big textures. Additional thread. If it's not problems then ok ) But it seems that I'm doing something wrong.


Directional lights (not) rotating with camera (opposite problem) I am trying to implement a shader for directional lights correctly, but I am bit confused as to why it works when it shouldn't and vice versa. People usually encounter problem with lights changing direction with camera. This is corrected by multiplying normals with model(view) matrix. But my problem is opposite. When I don't multiply normals with model(view) matrix then it works and when I try to use (supposedly) correct version it is having that "lights rotating with camera" problem. Any ideas? Working vertex shader version 330 layout (location 0) in vec3 position layout (location 1) in vec2 texCoord layout (location 2) in vec3 normal out vec2 texCoord0 out vec3 normal0 uniform mat4 model uniform mat4 view uniform mat4 proj void main() normal0 normal gl Position proj view model vec4(position, 1.0) texCoord0 texCoord Fragment shader version 330 in vec2 texCoord0 in vec3 normal0 out vec4 outColor struct BaseLight vec3 color float intensity struct DirectionalLight BaseLight base vec3 direction uniform vec3 baseColor uniform vec3 ambientLight uniform sampler2D sampler uniform DirectionalLight directionalLight vec4 calcLight(BaseLight base, vec3 direction, vec3 normal) float diffuseFactor dot(normal, direction) vec4 diffuseColor vec4(0,0,0,0) if(diffuseFactor gt 0) diffuseColor vec4(base.color, 1.0) base.intensity diffuseFactor return diffuseColor vec4 calcDirectionalLight(DirectionalLight directionalLight, vec3 normal) return calcLight(directionalLight.base, directionalLight.direction, normal) void main() vec4 totalLight vec4(ambientLight,1) vec3 normal normalize(normal0) totalLight calcDirectionalLight(directionalLight, normal) outColor texture(sampler, texCoord0.xy) vec4(baseColor, 1) totalLight Draw method glBindBuffer(GL ARRAY BUFFER, vbo) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) glVertexAttribPointer(0, 3, GL FLOAT, false, Vertex SIZE 4, 0) glVertexAttribPointer(1, 2, GL FLOAT, false, Vertex SIZE 4, (const GLvoid )12) glVertexAttribPointer(2, 3, GL FLOAT, false, Vertex SIZE 4, (const GLvoid )20) glBindBuffer(GL ELEMENT ARRAY BUFFER, ibo) glDrawElements(GL TRIANGLES, size, GL UNSIGNED INT, 0) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) Matices ViewTranslate glm mat4(1.0f) cam gt control(windowHandle, 0.01, 0.3, true, amp ViewTranslate) cam gt updateCamera( amp ViewTranslate) glm mat4 Projection glm perspective(70.0f, 800.0f 600.0f, 0.1f, 10000.0f) glm mat4 view glm lookAt( glm vec3(0, 0, 1), glm vec3(0.0f, 0.0f, 0.0f), glm vec3(0.0f, 1.0f, 0.0f) ) shader gt bind() shader gt setUniform("model", glm value ptr(ViewTranslate)) shader gt setUniform("view", glm value ptr(view)) shader gt setUniform("proj", glm value ptr(Projection)) shader gt setUniform("ambientLight", ambientLight) Not working shader code void main() normal0 (model vec4(normal, 0.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (model view vec4(normal, 0.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (model view vec4(normal, 1.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (transpose(inverse(model view)) vec4(normal, 1.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord ... Any ideas how I should do this correctly?


How many texture units are available per shader stage when compared to the total number available on hardware? The answer to the question How many textures can usually I bind at once?, given here, explains that OpenGL 3.x defines the minimum number for the per stage limit to be 16... and that there can be a higher limit. This still leaves some ambiguity that I would like to clarify. If we calculate the total number of texture units to be, for e.g., 192 (see here for more details), then does this mean theoretically, that we have access to 192 texture units available for the pixel shader? OR we have access to 192 texture units across all stages, however that still doesn't mean we have access to 192 texture units on any particular stage. OR ? If 2 is correct, then how do we figure out how many maximum texture units are available on any given stage?


How to put the camera inside a cube in OpenGL I'm really new to OpenGL and can't seem to figure out how to put the "camera" inside the cube I've created so that I can move in an FPS like style. I tried to use gluLookAt and gluPerspective but I'm clearly missing some steps. What should I do before gluLookAt? Here's the code written so far int rotate Y used to rotate the cube about the Y axis int rotate X used to rotate the cube about the X axis the display function draws the scene and redraws it void display() clear the screen and the z buffer glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() resets the transformations glRotatef(rotate X, 1.0, 0.0, 0.0) glRotatef(rotate Y, 0.0, 1.0, 0.0) Front Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.0, 1.0, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Back Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(1.0, 0.0, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Right Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(1.0, 0.0, 1.0) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Left Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.7, 0.7, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glEnd() Upper Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.7, 0.7, 0.3) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Bottom Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.2, 0.2, 0.8) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() glFlush() glutSwapBuffers() send image to the screen int main(int argc, char argv ) initialize GLUT glutInit( amp argc, argv) request double buffering, RGB colors window and a z buffer glutInitDisplayMode(GLUT DOUBLE GLUT RGB GLUT DEPTH) create a window glutInitWindowSize(600, 600) glutInitWindowPosition(100, 100) glutCreateWindow("Space") enable depth glEnable(GL DEPTH TEST) callback functions glutDisplayFunc(display) display redraws the scene glutSpecialFunc(specialKeys) special allows interaction with specialkeys pass control to GLUT for events glutMainLoop() return 0 this line is never reached Feel free to ask more about what I'm trying to achieve if I wasn't clear enough. Thanks for your help.


WebGL immediate mode I know that WebGL is based on OpenGL ES 2.0 and that glBegin and glEnd have been removed and replaced with vertex buffer objects. I understand that VBOs are faster and use less code but is there a library or add on for JavaScript WebGL that re implements these functions? After more research, I have discovered that this functionality is called immediate mode.


Keep 2d GUI shape through rotation I've been working on creating the GUI system for a 3d game I've been working on, and have hit a bit of an obstacle in trying to rotate GUI elements (Google searching did not yield what I was looking for). This is how the screen looks without any rotation. As of now, rotating each element distorts the GUI elements, like this, whereas I want an effect closer to this, without any stretch or skewing. My code, using glm, looks like this void GUI NewGUIBase rebuildMatrix() glm vec3 newModel glm vec3(absoluteTopLeft.x, absoluteTopLeft.y, 1.0f) glm mat4 rotate glm rotate(glm mat4(1.0f), glm radians(this gt rotation), glm vec3(0, 0, 1)) glm mat4 trans glm translate(glm mat4(1.0f), newModel) this gt setModel(trans rotate) I believe that the issue is due to the fact that my game window is not a square given that OpenGL uses window coordinates from 1 to 1. However, I can't figure out how I would take this into account to achieve the desired effect of rotation without any stretch. In case it helps, a GUI element knows its own top left corner and its own dimensions (in OpenGL coordinates), and the game window's width and height in pixels.


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?


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?


How do I find the 2D direction to a 3D location? I'm writing a 3D space flightsim, and I'm trying to display a 2D arrow on screen that points to the player's selected target. To clarify, the arrow needs to point in the direction that the player has to turn to reach the target. I've tried several approaches but I can't seem to make this work for all cases. My current attempt involves constructing a plane from the player's local X Y, projecting the target position onto it (to make the calculation 2D) then calculating the angle between the player's up and the vector to the projected target position. I can't help but think I'm over thinking this and there must be a better, simpler way. Anyone have any suggestions? UPDATE Based on Sam's answer, I've tried the following code Find the direction to the target, and normalize it kglt Vec3 target dir (target pos ship pos) target dir.normalize() kglt Vec3 v1, v2 v1 ship up.cross(ship dir) v2 ship up.cross(target dir) v1.normalize() v2.normalize() Get the angle of rotation for the arrow float angle kmRadiansToDegrees(atan2(ship up.dot(v1.cross(v2)), v1.dot(v2))) But the returned angle is always around 180.0 (although normally 179.xx). Is there any obvious error somewhere? I'll continue debugging and update if I figure it out! UPDATE2 Nevermind, the bug isn't in this section of code. My bad!


What happens if I don't call glNormal for some vertices? Let's say I have an object where some vertices will have the same normal and some won't. Are these two equivalent? Note I'm working with an old OpenGL version (2.3 I think). Option 1 glNormal3f(0.0, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.1, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.2, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.3, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) Option 2 glNormal3f(0.0, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.0, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.0, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.0, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.1, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.2, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glNormal3f(0.3, 0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0)


How do I change a shape without affecting the rest of the screen? I have drawn a shape like this in OpenGL glColor4f(red,green,blue) glBegin(GL QUADS) glVertex2f(x1,y1) glVertex2f(x2,y2) glVertex2f(x3,y3) glVertex2f(x4,y4) glEnd() glFlush() and I want change one the vertices like glVertex2f(x delta,y delta) But how do I redraw the shape without altering the other components of the screen?


Specular Light not working Phong shading I want to implement Phong Shading using GLSL. I also want to calulate all values using uniforms in the shaders. Nearly everything works fine, but there is an error with the specular term of the equation. Here is my vertex shader version 330 layout(location 0) in vec3 vertex layout(location 1) in vec3 vertex normal uniform vec3 light ambient color uniform vec3 light diffuse color uniform vec3 light specular color uniform vec3 light position uniform vec3 material ambient color uniform vec3 material diffuse color uniform vec3 material specular color uniform float material specular shininess out vec3 vNormal out vec3 camVec out vec3 lightVec out vec3 diffuse out vec3 ambient out vec3 specular out float shininess uniform mat4 view uniform mat4 modelview uniform mat4 projection void main() diffuse material diffuse color.rgb light diffuse color.rgb ambient material ambient color.rgb light ambient color.rgb specular material specular color.rgb light specular color.rgb shininess material specular shininess mat4 normalMat transpose(inverse(modelview)) vNormal vec3(normalMat vec4(vertex normal,0.0)) vec4 pos projection modelview vec4(vertex,1.0) camVec pos.xyz lightVec (1) (light position.xyz pos.xyz) gl Position pos And this is my fragment shader version 330 in vec3 vNormal in vec3 camVec in vec3 lightVec in vec3 diffuse in vec3 ambient in vec3 specular in float shininess this defines the fragment output out vec4 color void main() vec3 normal normalize(vNormal) vec3 viewDir normalize(camVec) vec3 lightDir normalize(lightVec) vec3 myDiffuse normalize(diffuse) vec3 myAmbient normalize(ambient) vec3 mySpecular normalize(specular) vec3 finalColor ambient float lambert dot(normal,lightDir) vec3 specColor if(lambert lt 0.0) specColor vec3(0.0,0.0,0.0) else finalColor myDiffuse lambert vec3 h (viewDir lightDir ) length(viewDir lightDir) float beta dot(h, normal) finalColor mySpecular pow(beta, shininess) color vec4(finalColor,0) All uniforms are set correctly. Here is what it looks like without the specular term And this happens when I add the specular term (which is not working) Edit Another screenshot with changing pos.xyz to pos.xyz in the vertex shader


How do animation works with mesh? I'm currently developing a game using OpenGL and my dev has run into a small problem. I'm having some problems understanding how "array of vectices works with animated object". For example, if we have a 3D object is there a different array for each frame of the animation or is there an instruction which does the animation ? So, does a 3D objet file look like this Idle Frame 1 mouvement animation Frame 2 mouvement animation Frame 3 mouvement animation All of the above being big array containing vertices and texture coords ? Thank you for the answer and explaning this thing to me !


OpenGL managing many textures smoothly I'm working on a game right now and running into some noticeable performance issues and limitations. Basically, I have this A few QGLWidgets, all sharing contexts with eachother (probably irrelevant that I'm using Qt also Windows, fwiw ). About 216000 total frames of 128x128 videos (with alpha, internal format GL RGBA, data format GL BGRA GL UNSIGNED INT 8 8 8 8 REV, video codec is Quicktime RLE, decoded with libav), spread into approximately 120 videos of 1800 frame average length. This translates to roughly 216000 128 128 4 14.2 GB of raw data, not including overhead. The game behaves as follows There are many "modes". At any given time only one mode is active. Each mode uses a very small known subset of the available videos, say 5 10 videos ( about 9000 18000 frames) tops. There's a bunch of 2D quads flying around the screen, each displaying whatever videos depending on the current mode. Objects don't all display the same frame, the video time offsets are random. The videos loop. Every few minutes, the mode changes. Objects cross fade to their new videos, so there is some overlap regarding when various sets of videos are needed. It is critical that this thing keep running smoothly, at 60 FPS, with no pauses for loading, etc. My problem is this My initial approach was to simply preload all videos off the disk and into textures, in video memory (via glTexImage2D and friends). I didn't mind the slow startup. This worked great early on, when I didn't have a lot of videos. The game could run smoothly because all the textures were already loaded. Now I have too many videos. I'm becoming extremely limited by available video memory, and the preload everything strategy is no longer working. I haven't become limited by system memory yet but that's also inevitable. I suspected this was going to be an issue and kept my fingers crossed, but alas. I hit the limit way sooner than I expected. I tried switching to a strategy where, every time a mode transition started I pre loaded the videos for that mode (and every time a transition ended I unloaded the videos for the previous mode). This works as far as memory goes but it pauses everything for a very long time while loading (as in 3 8 seconds depending on the number of videos and the graphics hardware). I've done the best searching that I know how to do, all of the texture memory management posts, blogs, tutorials etc. just talk about the basic technique of creating and destroying textures, rather than strategies for managing large numbers of them in an application. I went through every question in the auto search on here that had a relevant looking title. I did find out that OpenGL is definitely not thread safe, which kind of kills my asynchronous background loading idea, unless there's some other way to implement that. So my question is What's a good strategy to use for swapping out tons of textures (200000 , 128x128 typical size) when at any given time only a small portion of those are needed, while maintaining a smooth frame rate? How is this typically done?


Qt 5 QOpenGLWidget not updating the screen I'm creating a level editor for my game using Qt for gui and i'm in really early stages. Right now i'm trying to dynamically add objects ( entities ) on screen when i click a button. So far the objects are pushed into a stack but i can't see them on screen. When my widget inherits QGLWidget the screen is updated immediately and i can see the objects being drawn but since QGLWidget is deprecated i use QOpenGLWidget. Strangely this class does not auto update the screen. I have also connected update() to a timer and set the interval to 0 to update the screen in real time. connect( amp timer, SIGNAL(timeout()), this, SLOT(update())) timer.setInterval(0) timer.start() Am i missing something ?


GLSL to Cg why is the effect different? With reference to this question, where I was trying to make the shader compile, I am now trying to make an effect appear. The effect can be shown here, through a GLSL shader But when I use the equivalent Cg shader, the result becomes this Using the same images (color map normal map) and the same code (except the way to retrieve variables). Here is the original GLSL shader uniform sampler2D color texture uniform sampler2D normal texture void main() Extract the normal from the normal map vec3 normal normalize(texture2D(normal texture, gl TexCoord 0 .st).rgb 2.0 1.0) Determine where the light is positioned (this can be set however you like) vec3 light pos normalize(vec3(1.0, 1.0, 1.5)) Calculate the lighting diffuse value float diffuse max(dot(normal, light pos), 0.0) vec3 color diffuse texture2D(color texture, gl TexCoord 0 .st).rgb Set the output color of our current pixel gl FragColor vec4(color, 1.0) And here is the Cg shader I wrote struct fsOutput float4 color COLOR uniform sampler2D color texture TEXUNIT0 uniform sampler2D normal texture TEXUNIT1 fsOutput FS Main(float2 colorCoords TEXCOORD0, float2 normalCoords TEXCOORD1) fsOutput fragm float4 anorm tex2D(normal texture, normalCoords) float3 normal normalize(anorm.rgb 2.0f 1.0f) float3 light pos normalize(float3(1.0f, 1.0f, 1.5f)) float diffuse max(dot(normal, light pos), 0.0) float3 color diffuse tex2D(color texture, colorCoords).rgb fragm.color float4(color,1.0f) return fragm Please let me know if something needs to be changed in order to obtain the effect, or if you need the C code.


ATI driver bug and rendering to a texture 2d array in OpenGL I am trying to render to a texture2Darray in OpenGL, with a similar setup as descriped in this post. My question is, if anyone has gotten this to work on ATI hardware? Or is there still a bug in the driver, preventing multi layered rendering? The bug is also mentioned in the forum post.


Creating a 3D text mesh from a 2D glyph I have thought of three steps for doing this Acquire the vertex coordinates which will represent the glyph's form Extrude them Render Can you suggest a better method? Can you give me an insight on how to do the first and the second step? I use FreeType 2.4.10 for text managment.


Getting contour without the background I have a texture and vertex which are needed to create a set of closed polygons. For this purpose I use these functions Code for create texture CCSprite spr CCSprite spriteWithTexture(mShape gt getTexture()) spr gt setPosition(ccp(spr gt getTextureRect().size.width 2, spr gt getTextureRect().size.height 2)) spr gt setFlipY(true) CCRenderTexture texture CCRenderTexture renderTextureWithWidthAndHeight(mShape gt getTextureRect().size.width, mShape gt getTextureRect().size.height) texture gt beginWithClear(1, 1, 1, 0) spr gt visit() glColor4f(0, 0, 0, 1) glColorMask(GL TRUE, GL TRUE, GL TRUE, GL FALSE) for(int i 0 i lt innerBorders.size() i ) std vector lt Vector2d gt sitePoints innerBorders.at(i) for(int n 1 n lt sitePoints.size() n ) Vector2d origin sitePoints.at(n 1) Vector2d destination sitePoints.at(n) drawSmoothLine(ccp(origin.GetX(), origin.GetY()), ccp(destination.GetX(), destination.GetY()), 0.25f) glColorMask(GL TRUE, GL TRUE, GL TRUE, GL TRUE) glColor4f(1.0, 1.0, 1.0, 1.0) texture gt end() drawSmoothLine method drawSmoothLine(CCPoint pos1, CCPoint pos2, float width) GLfloat lineVertices 12 , curc 4 GLint ir, ig, ib, ia CCPoint dir, tan width width 8 dir.x pos2.x pos1.x dir.y pos2.y pos1.y float len sqrtf(dir.x dir.x dir.y dir.y) if(len lt 0.00001) return dir.x dir.x len dir.y dir.y len tan.x width dir.y tan.y width dir.x lineVertices 0 pos1.x tan.x lineVertices 1 pos1.y tan.y lineVertices 2 pos2.x tan.x lineVertices 3 pos2.y tan.y lineVertices 4 pos1.x lineVertices 5 pos1.y lineVertices 6 pos2.x lineVertices 7 pos2.y lineVertices 8 pos1.x tan.x lineVertices 9 pos1.y tan.y lineVertices 10 pos2.x tan.x lineVertices 11 pos2.y tan.y glGetFloatv(GL CURRENT COLOR,curc) ir 255.0 curc 0 ig 255.0 curc 1 ib 255.0 curc 2 ia 255.0 curc 3 const GLubyte lineColors ir, ig, ib, 0, ir, ig, ib, 0, ir, ig, ib, ia, ir, ig, ib, ia, ir, ig, ib, 0, ir, ig, ib, 0, glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glVertexPointer(2, GL FLOAT, 0, lineVertices) glColorPointer(4, GL UNSIGNED BYTE, 0, lineColors) glDisable(GL TEXTURE 2D) glDrawArrays(GL TRIANGLE STRIP, 0, 6) glEnable(GL TEXTURE 2D) glDisableClientState(GL COLOR ARRAY) glDisableClientState(GL VERTEX ARRAY) I need to get the texture of the contour (without the main texture on the background.) How can it be done using openGL ES 1.1?


Render to cubemap wrong Y values I'm currently trying to render to a cubemap in order to blur it. However the top and bottom faces appear much closer than they should be in the blurred version. I thought the problem came from my transformation matrices but they're just rotations. I'm beginning to believe that it's the way I'm handling the framebuffer that's causing this problem. Here's how I'm doing it unsigned fbo unsigned rt glViewport(0, 0, size, size) glGenFramebuffers(1, amp fbo) glGenRenderbuffers(1, amp rt) glBindFramebuffer(GL FRAMEBUFFER, fbo) glBindRenderbuffer(GL RENDERBUFFER, rt) glRenderbufferStorage(GL RENDERBUFFER, GL DEPTH COMPONENT24, size, size) glFramebufferRenderbuffer(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL RENDERBUFFER, rt) ... enable source cubemap, set projection ... for(int i 0 i lt 6 i) set rotation glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE CUBE MAP POSITIVE X i, target cubemap, 0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) draw cube (the images below are from the same corder)


Difference and interaction between Viewport and Camera I'm very very confused about some very basic concepts in game grafical developing. The interaction between the individual components (camera, viewport, window sizes, gameworld sizes, ...) when rendering graphical things are still confusing me. As far as I understand A camera "filming" viewing something as long it is between the near and the far clipping plane Camera has a Width and Height which defines the area of what will get "viewed"... ? The viewport can connect to an camera the viewport is the area which will get shown withing the window the cameras view will get projected onto the viewport so if the camera has a size of 1024x768 and the viewport ist only 300x400, the 1024 pixels will get upset on 300 "real" pixels As you may have have recognized Im very unsure about this. Maybe you can help me with that. I want to run the test app down bellow in a way, that the picture will not get stretched. Also Im wondering what "game coordinates" are in that context. For Demo Cases and learning I've just created a piece of src package com.mygdx.game import ... public class MyGdxGame extends ApplicationAdapter public PerspectiveCamera cam public Model model public ModelBatch modelBatch public ModelInstance instance private FitViewport viewport Override public void create() modelBatch new ModelBatch() creating a camera gets width and height from the window so it will "fit" best in the current window cam new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) cam.position.set(10f, 10f, 10f) cam.lookAt(0, 0, 0) cam.near 1f cam.far 300f cam.update() creating viewport width n height r not really necessary since it gets new values within the rezise() method correct? viewport new FitViewport(1920, 1080, cam) ModelBuilder modelBuilder new ModelBuilder() model modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position Usage.Normal) instance new ModelInstance(model) Override public void render() Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT GL20.GL DEPTH BUFFER BIT) what is happening here? cam.update() modelBatch.begin(cam) modelBatch.render(instance) modelBatch.end() Override public void dispose() model.dispose() Override public void resize(int w, int h) putting new values into the viewport and updating it will "resize" the camera ... ? float aspectRatio (float) w (float) h viewport.update((int) (h aspectRatio), h) viewport.update(1920, 1080) viewport.update(w, h)


Why is my OpenGL enabled Java game not detected by Fraps? Recently I found out that I could enable OpenGL hardware acceleration in my Java game with the line System.setProperty("sun.java2d.opengl", "True") Initial tests showed a big boost in performance. However, several days later I wanted to make a small test video using Fraps but I found out that it didn't recognize my application (as in the FPS counter did not show and I could not record anything). After I removed the earlier mentioned line of code (thus disabling OpenGL hardware acceleration) it recorded just fine. Is there any way to use Fraps while I have OpenGL enabled in my Java game?


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


Tangent on generated sphere I have difficulties understanding the tangent bitangent concept for normal mapping, or rather the calculations of them. I draw a sphere which is generated with the code in the OpenGL redbook http www.glprogramming.com red chapter05.html. I use cube mapping to texture the sphere. Now, pretty much everything in the web links to http www.terathon.com code tangent.html. But in that algorithm, they use the texture coords u and v, which I don't have like this because my texture mapping is 3D... Any pointers to how I can compute the tangents and bitangents with this setup? Also, aren't the tangents just vectors orthogonal to the normal of a point on the sphere? To me it seems there could be an easier way.. Edit As far as I understand I need those values to be able to "apply" the normal from the normal map to the point on the sphere. (I'm not sure what the correct mathematical terminologies are here). In other words, to deviate the normals of any point on the sphere based on the normal map. I calculated the normals as point on surface center of sphere (which, in modelspace, when the center is (0,0,0), is just point on surface)


Getting error GL FRAMEBUFFER INCOMPLETE ATTACHMENT I am getting error code GL FRAMEBUFFER INCOMPLETE ATTACHMENT when creating framebuffer on Mac (using glCheckFramebufferStatus). I am using same code for rendering on Mac and iOS both. Maybe problem is in the buffers initialization. On iOS I am doing it this way CAEAGLLayer eaglLayer (CAEAGLLayer ) super.layer eaglLayer.opaque YES EAGLRenderingAPI api kEAGLRenderingAPIOpenGLES2 m context EAGLContext alloc initWithAPI api if (!m context) self release return nil if (!m context ! EAGLContext setCurrentContext m context ) self release return nil self layoutIfNeeded NSLog( "Using OpenGL ES 2.0") m context renderbufferStorage GL RENDERBUFFER fromDrawable eaglLayer Variable m context is object EAGLContext On the Mac this way NSOpenGLPixelFormat nsglFormat NSOpenGLPixelFormatAttribute attr NSOpenGLPFADoubleBuffer, NSOpenGLPFAAccelerated, NSOpenGLPFAColorSize, m colorBits, 16 NSOpenGLPFADepthSize, m depthBits, 16 0 self setPostsFrameChangedNotifications YES lt Next, initialize the NSOpenGLPixelFormat itself nsglFormat NSOpenGLPixelFormat alloc initWithAttributes attr lt Check for errors in the creation of the NSOpenGLPixelFormat if(!nsglFormat) NSLog( "Invalid format... terminating.") return nil lt Now create the the CocoaGL instance, using initial frame and the NSOpenGLPixelFormat self super initWithFrame frame pixelFormat nsglFormat nsglFormat release lt If there was an error, we again should probably send an error message to the user if(!self) NSLog( "Self not created... terminating.") return nil lt Now set this context to the current context self openGLContext makeCurrentContext Maybe I am doing anything wrong when I initialize NSOpenGLContext. Can you see any error? Thankyou UPDATE Initialization of the OpenGL I am doing this way int m width, m height glGetRenderbufferParameteriv(GL RENDERBUFFER, GL RENDERBUFFER WIDTH, amp m width) glGetRenderbufferParameteriv(GL RENDERBUFFER, GL RENDERBUFFER HEIGHT, amp m height) Create the depth buffer. glGenRenderbuffers(1, amp m depthRenderbuffer) glBindRenderbuffer(GL RENDERBUFFER, m depthRenderbuffer) glRenderbufferStorage(GL RENDERBUFFER, GL DEPTH COMPONENT16, m width, m height) Create the framebuffer object attach the depth and color buffers. glGenFramebuffers(1, amp m framebuffer) glBindFramebuffer(GL FRAMEBUFFER, m framebuffer) glFramebufferRenderbuffer(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL RENDERBUFFER, m colorRenderbuffer) glFramebufferRenderbuffer(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL RENDERBUFFER, m depthRenderbuffer) Bind the color buffer for rendering. glBindRenderbuffer(GL RENDERBUFFER, m colorRenderbuffer) Set up some GL state. glViewport(0, 0, 640, 480) glEnable(GL DEPTH TEST)


How do I flip upside down fonts in FTGL I just use FTGL to use it in my app. I want to use the version FTBufferFont to render font but it renders in the wrong way. The font(texture?buffer?) is flipped in the wrong axis. I want to use this kind of orthographic settings void enable2D(int w, int h) winWidth w winHeight h glViewport(0, 0, w, h) glMatrixMode(GL PROJECTION) glLoadIdentity() I don't even want to swap the 3rd and 4th param because I like to retain the top left as the origin glOrtho(0, w, h, 0, 0, 1) glMatrixMode(GL MODELVIEW) I render the font like this No pushing and popping of matrices No translation font.Render("Hello World!", 1, position, spacing, FTGL RenderMode RENDER FRONT) On the other forums, they said, just scaled it down to 1, but it wont work in mine. Example font is above the screen I can't see relevant problem like in mine in google so I decide to ask this here again. How can I invert texture's v coordinate without modifying its source code ? (assume its read only)


Is Orthogonal in LWJGL 2D or 3D? I'm attempting to develop an orthogonal game with lwjgl 3 and OpenGL in Eclipse, but I can't find an answer for rendering objects in 2D or 3D. Are both applicable? And if so what are the advantages of either one? I would also like to rotate my camera if that changes your answer.


Loading multi texture 3ds c I have a question about loading 3ds using this tutorial. I want to use more than one texture on the model (because here all the models have more than one) but it seems that this library can't do that. Do you know any other alternatives or a way to edit this existing library to reach my aim?