How do I wrap textures inside shader GLSL? I'm trying out GLSL and one of the problems I'm facing is wrapping a random texture sampler in the shader. Searching for answers on the web first, this leads me to using these glTexParameter() GL TEXTURE WRAP S GL REPEAT GL TEXTURE WRAP T GL REPEAT I'm not sure where to put this or how to use it. I'm using a custom engine for this shader and I would assume I could wrap the texture in the shader. My main concern on this is my final output render having left and bottom artifacts. I got some previous advise it has to do with wrapping a random texture that is used for noise if that helps in my case.


How to know when graphics driver or card changes I'm about to start work on implementing GLSL binary shader compilation and I was curious how to handle the cases when the shaders need to be recompiled, such as when the driver (or perhaps even the graphics card itself) changes. Are there any mechanisms out there to do these types of things, or is this just a "delete the shader cache folder if you update your driver" type of thing? I did a quick search on here and Google and didn't see anything that looked promising. Edit or am I just ignorant and GL will let me know when a recompile is necessary?


3D Camera Rotation (Unwanted Roll) Space Flight Cam I am working on a camera class that will have full range of motion (pitch, yaw, and roll). When only altering pitch and yaw, I am getting a large amount of roll. I understand that the issue is related to I 39 m rotating an object on two axes, so why does it keep twisting around the third axis? However, I have not been able to come up with a solution. I would like the camera to have all motion (i.e. like a spaceship). Here is the relevant code void Camera3D update(const glm vec2 amp current mouse coords) if (m mouse first movement) if (current mouse coords.x ! 0 current mouse coords.y ! 0) m mouse first movement false else const glm vec2 mouse delta (current mouse coords m old mouse coords) mouse sensitivity pitch( mouse delta.y) yaw( mouse delta.x) m old mouse coords current mouse coords void Camera3D pitch(const float angle) Pitch Rotation const glm quat pitch quaternion glm angleAxis( angle, m camera right) Update Vectors m camera up glm normalize(glm rotate(pitch quaternion, m camera up)) m camera forward glm normalize(glm rotate(pitch quaternion, m camera forward)) void Camera3D yaw(const float angle) Yaw Rotation const glm quat yaw quaternion glm angleAxis(angle, m camera up) Update Vectors m camera right glm normalize(glm rotate(yaw quaternion, m camera right)) m camera forward glm normalize(glm rotate(yaw quaternion, m camera forward)) glm mat4 Camera3D get view matrix() m view matrix glm lookAt( m camera position, m camera position m camera forward, m camera up ) return m view matrix I would like the movement of the camera to be based on local coordinates so the controls (up down left right vertical up vertical down) move the camera along its own local axis. Additional clarification based on the comment below If I look up 60 degrees and then left, I would like the horizon to stay level (essentially adding roll in the opposite direction to keep the horizon level) Any help is appreciated. Thank you!


What is the fastest way of drawing simple, textured geomtries and keeping the depth test? I'm looking for a fast way to draw simple 3D geometries that will consist of up to 10 vertices. Each of them will have a texture (though varying between geometries). I also want to store the fragment depth for depth testing. There will be no lighting and only very simple transformations (this actually is for isometric game). So far what I did was trying to achieve top performance using OpenGL for drawing simple quads (what the problem actually boils down to). For my machine (from around 2008), I had the following results Using immediate mode 4800 quads took 120ms Using vertex arrays and VBOs this took around 40 ms What I see as a problem is the bottleneck of glDraw calls. I want to somehow get below 4 5 ms , as there will be really a lot of objects on the screen. Any ideas about how could (or perhaps couldn't) achieve that?


GLM Euler Angles to Quaternion I hope you know GL Mathematics (GLM) because I've got a problem, I can not break I have a set of Euler Angles and I need to perform smooth interpolation between them. The best way is converting them to Quaternions and applying SLERP alrogirthm. The issue I have is how to initialize glm quaternion with Euler Angles, please? I read GLM Documentation over and over, but I can not find appropriate Quaternion constructor signature, that would take three Euler Angles. The closest one I found is angleAxis() function, taking angle value and an axis for that angle. Note, please, what I am looking for si a way, how to parse RotX, RotY, RotZ. For your information, this is the above metnioned angleAxis() function signature detail tquat lt valType gt angleAxis (valType const amp angle, valType const amp x, valType const amp y, valType const amp z)


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


OpenGL textures look poor I'm having some issues loading in textures in OpenGL, as my textures keep rendering incorrectly or coming out looking muddy. For instance, here I tried to load a 256x256 color spectrum image. On the left is how it looks in OpenGL and on the right is how it looks in an image viewing program As you can see, while the left image resembles the right image, the left image appears to squish the blues, and greens, and extend the pinks. I also tried loading in this 512x512 image of a dog and the result came out like this (again, left is OpenGL, right is image viewer) For this image, the image looks like it has lost a lot of its color, resulting in something that looks white washed and like it came out of a 1970s camera. (the fact that is flipped is fine however since the cube that I am drawing this on has some texture coordinates flipped to accommodate for a different image). I load in these .BMP textures using SOIL, as such glEnable(GL TEXTURE 2D) GLuint texID 0 glGenTextures(1, amp texID) int height 0, width 0 unsigned char imgData SOIL load image(filePath.c str(), amp width, amp height, 0, SOIL LOAD AUTO) glBindTexture(GL TEXTURE 2D, texID) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, width, height, 0, GL RGB, imgData) set texture filtering, gen mip map Then in my fragment shader I do the following to apply the texture version 330 core in vec2 TexCoord uniform sampler2D textureSampler void main() gl FragColor texture2D(textureSampler, TexCoord)


Efficient way to output display debugging data in a window I'm writing a program in Visual Studio, C with OpenGL and for the first time, I think it will be beneficial to see some live data on top of my display render window. To give some scope, I'm developing a 3D world with a ball bouncing and it would be nice to see things like the current velocity and y positions of various objects, amongst other things. What method is a nice effective way to display this type of information to a window? Is there any libraries, vs settings or third party implementations that can be useful? (please excuse my naivety, I'm used to just cout lt lt some info, on a console).


Best strategy to track object hierarchy using groups and obj files I am making a 3D game in OpenGL from scratch. In this game I have a ship with stuff inside it. How can I attach the stuff to the ship in the CAD program and maintain that hierarchy in my own game? For example say I have a fire extinguisher in my ship that mounts on the wall. There are two approaches both with problems. Solution 1 Save fire extinguisher and ship as separate obj files. Problem How can I place the fire extinguisher in the proper place inside my ship in my game? With hundreds of objects manually placing them is completely infeasible. I want to arrange stuff in my CAD and load it into the game and be done. Solution 2 Save fire extinguisher as its own group inside the ship obj file. Problem Now I can't reuse the fire extinguisher in other ships. The obj files for game assets will balloon out of control in size with new instances of reused sub objects. Is there some way I can specify the position of an external object? A 3d point in my ship obj file representing the origin of another obj model?


opengl matrix multiplication Can someone provide some type of example of multiplying a 4x4 matrix without using loops? typedef struct matrix4 data 16 m4 can someone provide a sample of how you you'd multiply two of these in the opengl column major way?


(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.


Orthographic Projection Issue I have a problem with my Ortho Matrix. The engine uses the perspective projection fine but for some reason the Ortho matrix is messed up. (See screenshots below). Can anyone understand what is happening here? At the min I am taking the Projection matrix Transform (Translate, rotate, scale) and passing to the Vertex shader to multiply the Vertices by it. VIDEO Shows the same scene, rotating on the Y axis. http youtu.be 2feiZAIM9Y0 void Matrix4f InitOrthoProjTransform(float left, float right, float top, float bottom, float zNear, float zFar) m 0 0 2 (right left) m 0 1 0 m 0 2 0 m 0 3 0 m 1 0 0 m 1 1 2 (top bottom) m 1 2 0 m 1 3 0 m 2 0 0 m 2 1 0 m 2 2 1 (zFar zNear) m 2 3 0 m 3 0 (right left) (right left) m 3 1 (top bottom) (top bottom) m 3 2 zNear (zFar zNear) m 3 3 1 This is what happens with Ortho Matrix This is the Perspective Matrix


Texture artifacts depending on texture size I get some strange artifacting with textures depending on their size. I run OpenGL 3.3 with an GTX 580 so it should definitely support non power of two textures. I've narrowed down the problem specifically to the texture's size, I've tried checking if transparency had anything to do with it, color channels etc. As you can see, the 512x512 and 300x300 textures look just fine but the 437x437 is all distorted. What could be the cause of this and how can it be fixed? I could of course just stick to power of two textures which seem to work fine but since this is an personal educational project I really want to understand what's going on.


Deferred rendering camera inside point light's sphere of effect I'm trying out deferred rendering and I'm using the tutorials at http ogldev.atspace.co.uk. I've got the basics working and I'm currently trying to implement the final step from tutorial 37 (http ogldev.atspace.co.uk www tutorial37 tutorial37.html). In the previous tutorial, the author explains how to render point lights as spheres in a second render pass, combing the effect of the lights with the data generated in the geometry buffers in the first pass, and I've got this working already. In tutorial 37, he explains how to use the stencil buffer to limit the influence of the lighting to only light up objects actually inside the light sphere. He describes how the stencil buffer is set up to decrease the stencil value when the depth test fails for front facing polygons and increase it for back facing polygons, resulting in the stencil buffer containing zeroes for all pixels belonging to objects outside the light sphere (as these will either be in front of the light sphere, leading to the depth test failing both for the front facing and the back facing polygons of the lights sphere, causing the stencil value to first decrease by one and then increase by one, or behind it, leading to neither front facing nor back facing polygons of the light sphere failing the test so the stencil value remains unchanged). Objects inside the sphere though cause the depth test to fail only for back facing polygons, leading to the stencil value being not zero. This will later be used to only render the light sphere on pixels for which the stencil value is not zero. So far, so good. But then there is a remark saying that the case when the camera is inside the light sphere is left as an exercise for the reader, and this comment puzzles me. Won't it still work the same way? If the camera is inside the light sphere, then objects in front of the light sphere will not be rendered at all (since they are behind the camera). Objects behind it will still not cause the depth test to fail for the back facing polygons of the light sphere (and the front facing polygons will of course not be rendered) so the stencil values for those pixels will still be zero. As for objects inside the light sphere, the depth test for the back facing polygons will fail, causing the stencil value to be different from zero. It seems to me that no special consideration will need to be taken for the case when the camera is inside the light sphere, but maybe I'm missing something. Can someone please help me figure this out?


How can I reduce the data sent to the GPU for a voxel? I'm making a minecraft style game where each chunk each chunk has buffers holding the position of all visible blocks and texture atlas coordinates of the 36 vertices that are needed to draw the triangles. I have 8 vertices and an EBO that I use for the triangles so it takes up sizeof(GLfloat) 3 8 sizeof(GLuint) 36 sizeof(Glfloat) 2 36 so 528 bytes. that seems like a lot per block meaning that if I am rendering around 16 16 chunks(I use an stl map not an array) 16 16 256 chunks that have around 300 visible blocks that means I am sending about 40 mb of data to the GPU each frame. It runs smoothly now but could this end up being a problem? or is there a way to reduce this? one other thing, I tried to change my program from using gldraw arrays and having 720 bytes for each block to using an EBO for just the position. how can you control what vbo the ebo operates on? for example the EBO would have indices to the points of the cube and texture coordinates but still have an instance array for the position


OpenGL why do I have to set a normal with glNormal? I'm learning some basics of OpenGL but I'm wondering why there is a call glNormal to set the normal of vertices. If I create a simple triangle like this glBegin(GL TRIANGLES) glVertex3f(0,0,0) glVertex3f(1,0,0) glVertex3f(0,1,0) glEnd() Shouldn't the normals be defined implicitly by the type of the geometric primitive? If I don't set a normal will OpenGL calculate it?


Problem with 2d rotation in OpenGL I have a function to perform sprite rotation void Sprite rotateSprite(float angle) Making an array of vertices 6 for 2 triangles Vector2 lt gamePos gt halfDims( rect.w 2, rect.h 2) Vector2 lt gamePos gt bl( halfDims.x, halfDims.y) Vector2 lt gamePos gt tl( halfDims.x,halfDims.y) Vector2 lt gamePos gt br(halfDims.x, halfDims.y) Vector2 lt gamePos gt tr(halfDims.x,halfDims.y) bl rotatePoint(bl,angle) halfDims br rotatePoint(br,angle) halfDims tl rotatePoint(tl,angle) halfDims tr rotatePoint(tr,angle) halfDims 1st triangle Top right dataPointer.vertices 0 .setPosition( rect.x tr.x, rect.y tr.y) Top left dataPointer.vertices 1 .setPosition( rect.x tl.x, rect.y tl.y) Bottom left dataPointer.vertices 2 .setPosition( rect.x bl.x, rect.y bl.y) 2nd triangle Bottom left dataPointer.vertices 3 .setPosition( rect.x bl.x, rect.y bl.y) Bottom right dataPointer.vertices 4 .setPosition( rect.x br.x, rect.y br.y) Top right dataPointer.vertices 5 .setPosition( rect.x tr.x, rect.y tr.y) Vector2 lt gamePos gt Sprite rotatePoint(Vector2 lt gamePos gt pos, float amp angle) Vector2 lt gamePos gt newv newv.x pos.x cos(angle) pos.y sin(angle) newv.y pos.y cos(angle) pos.x sin(angle) return newv And the result is Am i doing something wrong ? It happens also when i put small angle (even if i put here angle 1 ) Thanks for help.


Creating a glitch effect similar to Watch Dogs I'm currently working on a LibGDX game. When a user does something wrong, I would like all the graphics on the screen to jitter very similar to the glitch distort effect seen in the game Watch Dogs (See Below). My question is this can this effect be achieved in real time by writing a shader? If so are there any references online on how to do this? (I've had a quick Google but all I could find is how to achieve this effect in Photoshop After Effects). Thank you for your help. Screen jitter https www.youtube.com watch?v EYkqC9uI8Nc Text glitch effect https www.youtube.com watch?v Wj26Wp2AH U


Move Camera Freely Around Object While Looking at It I've got a 3D model loaded (a planet) and I have a camera that I want to allow the user to move freely around it. I have no problem getting the camera to orbit the planet around either the x or y axis. My problem is when I try to move the camera on a different axis I have no idea how to go about doing it. I am using OpenGL on Android with the libGDX library. I want the camera to orbit the planet in the direction that the user swipes their finger on the screen.


Stencil buffer appears to not be decrementing values correctly I'm attempting to use the stencil buffer as a clipper for my UI system, but I'm having trouble debugging a problem I'm running in to. This is what I'm doing A widget can pass a rectangle to the the stencil clipper functions, which will increment the stencil buffer values that it covers. Then it will draw its children, which will only get drawn in the stencilled area (so that if they extend outside they'll be clipped). After a widget is done drawing its children, it pops that rectangle from the stack and in the process decrements the values in the stencil buffer that it has previously incremented. The slightly simplified code is below static void drawStencil(Rect amp rect, unsigned int ref) Save previous values of the color and depth masks GLboolean colorMask 4 GLboolean depthMask glGetBooleanv(GL COLOR WRITEMASK, colorMask) glGetBooleanv(GL DEPTH WRITEMASK, amp depthMask) Turn off drawing glColorMask(0, 0, 0, 0) glDepthMask(0) Draw vertices here ... Turn everything back on glColorMask(colorMask 0 , colorMask 1 , colorMask 2 , colorMask 3 ) glDepthMask(depthMask) Only render pixels in areas where the stencil buffer value ref glStencilFunc(GL EQUAL, ref, 0xFF) glStencilOp(GL KEEP, GL KEEP, GL KEEP) void pushScissor(Rect rect) increment things only at the current stencil stack level glStencilFunc(GL ALWAYS, s scissorStack.size(), 0xFF) glStencilOp(GL INCR, GL INCR, GL INCR) s scissorStack.push back(rect) drawStencil(rect, s ScissorStack.size()) void popScissor() undo what was done in the previous push, decrement things only at the current stencil stack level glStencilFunc(GL ALWAYS, s scissorStack.size(), 0xFF) glStencilOp(GL DECR, GL DECR, GL DECR) Rect rect s scissorStack.back() s scissorStack.pop back() drawStencil(rect, s scissorStack.size()) And this is how it's being used by the Widgets if (m clip) pushScissor(m rect) drawInternal(target, states) for (auto child m children) target.draw( child, states) if (m clip) popScissor() This is the result of the above code There are two things on the screen, a giant test button, and a window with some buttons and text areas on it. The text area scroll box is set to clip its children (so that the text doesn't extend outside the scroll box). The button is drawn after the window and should be on top of it completely. However, for some reason the text area is appearing on top of the button. The only reason I can think of that this would happen is if the stencil values were not getting decremented in the pop, and when it comes time to render the button, since those pixels don't have the right stencil value it doesn't draw over. But I can't figure out whats wrong with my code that would cause that to happen.


OpenGL behaviour depending on the graphics card? This is something that never happened to me before. I have an OpenGL code that uses GLSL shaders to texture a 3D model. The code involves a lot of GPU texture processing, blending, etc... I wanted to check how the performance of my code improves using a faster graphics card (both new and old are NVIDIA, using always the NVIDIA development drivers). But now I have found that once I run the code using the new graphics card, it behaves completely different (the final render looks wrong), probably because some blending effect is not performed correctly. I haven't really look into what has changed, but I am guessing that some OpenGL states are, by default, set different. Is this possible? Have you ever found different OpenGL GLSL behaviour using different graphics cards? Any "fast" solution? (So far I've thought of plugging back the old one, push all OpenGL default states, and compare with the ones I initially get using the new card..) Edit 1 The graphics cards are NVIDIA Quadro GX7300 (in which my code works OK) and NVIDIA GeForce GTX 560 Ti (in which the results changes fails) Edit 2 I have commented out a lot of my code, and apparently the strange behaviour has nothing to do with texture handling. A simple chessboard like floor looks differents. The diagonal white lines did not appear using the old NVIDIA Quadro GX7300. Any guess what OpenGL related thing could be causing this? Figure 1 Edit 3 I have now fixed the issue commented on the previous edit, regarding the weird unwanted diagonal thin whit lines. As I commented below, I had to remove the glEnable(GL POLYGON SMOOTH) , which was affecting the NVIDIA GeForce GTX 560 for whatever reason (probably due to reasons explained by mh01 in his answer. However, I am still facing a "texture blending" problem when using the NVIDIA GeForce GTX 560. I have a 3D model that is being textured using a shader that blends 8 different images to compute the right texture, depending on where the camera is at that particular moment. The resulting texture is then a combination of different images, and ideally they were blended nicely, using a set of blending weights computed each time the camera moves. The blending weights are still well computed, but the resulting texture is wrong. I am guessing that the GL BLEND function is somehow behaving different, but I have checked it in both graphics cards and it is actually the same one. I have no idea what else can be involved in getting this wrong result As you can imagine, the black line is where two original textures are being blended in order to get a seamless texture. If I use the exact some code and a NVIDIA Quadro GX730, the shader works as expected. However, when I use the NVIDIA GeForce GTX 560, the texture blending goes wrong. Any guess? This is the GLSL shader I am using.


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?


Calculate normal angle in screen space I'm working on adding billboarded sprites to a game engine, but the engine allows for walking on curved terrain, like spheres. In order to look like the player is walking on the terrain, I want to start with the billboard, then rotate it around its origin (bottom centre) so that its up vector matches the screenspace normal of the terrain. Here's a diagram of the general idea The billboarding works fine passed the camera's rotation matrix to the sprite, and the poly quad's 0,0,0 is at the bottom centre of the canvas. How can I get the angle between the normal and screenspace up? I think it's a matter of projecting the normal with the MVP matrix, to get it as a 2D screenspace vector to calculate the angle from. But I'm not having much luck attempting to implement it. The sprites take their positioning from the centre of the tiles, along with the normal. I'd also like to move the sprites down in the rotated axis, so that they cover the tile they're standing on. Any other methods are welcome too.


glOrthof not being applied I have had a problem with OpenGL where glOrthof is not being applied, leading to my frame having the default 1 1 1 ratio. Here is the code initializing it public void reshape(GLAutoDrawable glAutoDrawable, int i, int i1, int i2, int i3) GL2 gl glAutoDrawable.getGL().getGL2() if(window.getWidth()! screenWidth window.getHeight()! screenHeight)window.setSize(screenWidth,screenHeight) unitsTall window.getHeight() (window.getWidth() unitsTall) gl.glMatrixMode(GL2.GL PROJECTION) gl.glLoadIdentity() gl.glOrthof(0.0f, unitsWide, 0.0f, unitsTall, 0.0f, 1.0f) gl.glMatrixMode(GL2.GL MODELVIEW) unitsWide is equal to 100. Here is the code for drawing the rectangle public static void drawRect(float x,float y,float width,float height) GL2 gl Render.getGL2() gl.glRotatef( rotation,0,0,1) Rotation needed to be reversed gl.glColor4f(red,green,blue,alpha) gl.glBegin(GL2.GL QUADS) gl.glVertex2f(x,y) gl.glVertex2f(x width,y) gl.glVertex2f(x width,y height) gl.glVertex2f(x,y height) gl.glEnd() gl.glFlush() gl.glRotatef(rotation,0,0,1) The "Render" class is the class with all of the main methods for OpenGL. Here is the code that I used for drawing the rectangle Graphics.drawRect(0,0,0.5f,1) Finally, here is a screenshot of what it looks like when this code executes I have looked around and have not found any other problems like this. Please tell me what I might be doing wrong.


Texture with transparency not rendered correctly in LibGDX The title might be a bit misleading but I'm having a hard time to explain the problem so I'll try with pictures Same tree from opposite site I'm trying to create a voxel game and at the moment I try to get textures with transparency working. The mesh is generated for each chunk individually so that every chunk has its own ModelInstance that is rendered. And the result should be like in the second picture (almost) so that every block is rendered behind the transparent textures but thats not the case for every side. The relevant code for the transparent textures Mesh mesh new Mesh(true, meshDataBlended.sizeEstimate, (int)Math.round(meshDataBlended.sizeEstimate 1.5), new VertexAttribute(VertexAttributes.Usage.Position, 3, ShaderProgram.POSITION ATTRIBUTE), new VertexAttribute(VertexAttributes.Usage.Normal, 3, ShaderProgram.NORMAL ATTRIBUTE), new VertexAttribute(VertexAttributes.Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD ATTRIBUTE "0")) BlendingAttribute blendingAttribute new BlendingAttribute() blendingAttribute.blended false blendingAttribute.sourceFunction GL20.GL SRC ALPHA blendingAttribute.destFunction GL20.GL ONE MINUS SRC ALPHA mesh.setVertices(meshDataBlended.vertices) mesh.setIndices(meshDataBlended.indices) Node terrainNode modelBuilder.node() terrainNode.id "terrain blended" modelBuilder.part( "terrain blended", mesh, GL20.GL TRIANGLES, new Material(TextureAttribute.createDiffuse(World.TEXTURE), blendingAttribute) ) I'm pretty new to OpenGL, so I'm totally lost with this problem. No idea why it behaves like this and I even don't know where I could find the needed informations. So far i just know that it depends on what is rendered first (that's why it works from one side but not the opposite side) Sorry for using Minecraft textures it's just for testing purposes. Let me know if some additional information is needed I'll add them then. Thanks Blakk EDIT setting blended to true will make everything visible behind the leaves except other leaves (still only from specific sides).


Why do most game devs prefer OGL for OS X and D3D for Windows? Today I decided to check what Diablo 3 developers used to do graphics OpenGL or Direct3D? My mind was completely blown For Windows, they've used D3D and for OS X they've used OGL. I did some research and found that most game developers prefer the same method. This choice doesn't make sense to me. Writing one game engine with OpenGL for OS X and then rewriting same for Windows with D3D seems a lot of unnecessary work. Wouldn't it be easier to just take OpenGL and make a game engine that works on both operating systems?


How to draw 2d above 3d scene? I have an OpenGL(3.3) GLEW application. I want to draw a black vertical rectangle at the left side of the window for writing some information on it, like fps (I use GLEW function for drawing text). I have a common pipeline, like this m transformation PersProjTrans CameraRotateTrans CameraTranslationTrans TranslationTrans RotateTrans ScaleTrans I know how it works, but I can't figure out how to draw a projection of the rectangle on the window, like 2d. I would be glad to any advise.


What is the practical use of IBOs degenerate vertex in OpenGL? Vertices in 3D models CAN get cut in the process of optimizing 3D geometry, (degenerate vertices) by 3D graphics software (Blender, ...) when exporting because they aren't needed when reusing a vertex for multiple triangles. (In the current case 3D data is exported from Blender as .ply and read by a simple application that displays the 3D model) Every vertex has a few attributes like position, color, normal, tangent,... But the data for each vertex that is cut through the vertex sharing is lost and is missing in the vertex shader. Modern shader techniques like Bump or Normal mapping require normals tangents per vertex which are also cut. To use complex shader techniques IBOs must not be used? Or is there a way to use IBOs and retain the data per vertex that was origionally lost?


How to reconcile depth ordering with minimal shader context changes? We generally want to minimise shader program switches (glUseProgram and all associated context changes) for the sake of performance. AFAIK it is not uncommon to render by shader program, i.e. group draw calls of all mesh instances that use the same set of shaders or vertex shader at least (i.e. that have the same set of vertex attributes), for this reason. How then do we go about doing both depth ordering and shader program changes, quickly? Because it seems to me one either orders primarily by program (thus minimal program context changes), or primarily by depth (frequent context changes), and that they're mutually exclusive in terms of maximising performance. PS. In my current work I'm not using the hardware Z buffer, instead I'm using the painter's algorithm prior to making all draw calls... If this affects the answer to the question at all, I'd be happy to hear solutions for both sorts of depth ordering.


Reduce texture switches in UI I'm working on game which uses LibGDX's Stage2d for GUI. All textures for UI are packed into one texture atlas. Fonts (BitmapFont) are generated in runtime by gdx freetype for different locales and font sizes (at least 6 locales and 4 font sizes for each locale) and then placed into separate texture. Game UI contains much different elements (strategy game with lots of numbers) buttons, icons, text labels, which usually alternate between each other and trigger many texture switches when drawn. I wonder if there's any way to reduce the number of texture switches as it sometimes takes up to 5ms per frame for stage.draw(). The only way I see is to draw fonts only when all UI textures are drawn, when it is possible, but it will produce awful code and will harm the hierarchy of elements in stage. I didn't merge textures (but thought of it), because Textures use different filtering (MipMapLinearNearest for UI textures, Linear for fonts) and it will require manual texture filtering switches or mess with stage2d overriden Label class. UI texture already has a size of 2048x2048px, and I can't add all font size textures to it as it will require higher texture sizes, which are not supported by many old devices. Is there any good way of solving this issue?


THREE.ShaderMaterial cannot perform antialiasing I created a ShaderMaterial to draw a box in three.js using the following key code magnetic orientation let magnetMaterial new THREE.ShaderMaterial( uniforms orientation value new THREE.Vector3(1) , vertexShader varying vec3 vPos void main() vPos position gl Position projectionMatrix modelViewMatrix vec4(position,1.0) , https stackoverflow.com questions 15688232 check which side of a plane points are on fragmentShader extension GL OES standard derivatives enable varying vec3 vPos uniform vec3 orientation void main() float a dot(orientation, vPos) gl FragColor vec4(step(a, 0.), 0, step(0., a), 1.0) ) See also online Demo. Even if I set WebGLRenderer.antialias to true, there's a heavy aliasing if the box is not axis aligned. I found Point Sampled AA and How do I implement anti aliasing in OpenGL?, but I didn't how to do? In addition, the custom shader cannot work with the light if any. In order to make custom color work with the built in effect (light). I want to try post processing via EffectComposer. Can anyone help me out? Related Add scene lights to custom vertex fragment shaders and shader materials? the last shader I added point lights threejs Adding lighting to ShaderMaterial How do you combine a ShaderMaterial and LambertMaterial?


Is there a way to use other fonts, besides the default ones in OpenGLUT? I'm using OpenGLUT functions like glutBitmapString to render sentences and words in a game. However, there is a limited set of fonts to use and I need some bigger size fonts. Is there a way to add new fonts to these functions API? Thanks


Projection Matrix Breaks My Rectangle This is my vertex shader, shown below. version 330 core in vec3 a position in vec4 a colour FOV 70, near plane 0.1, far plane 1000 const mat4 u projection mat4( 1.428148, 0.0, 0.0, 0.0, 0.0, 1.428148, 0.0, 0.0, 0.0, 0.0, 1.0001999, 0.20002, 0.0, 0.0, 1.0, 0.0 ) uniform mat4 u projection uniform mat4 u view uniform mat4 u transformation out vec4 v colour void main() gl Position u projection u transformation vec4(a position, 1) v colour a colour Whenever I take out u projection, my square appears. When I add it back, the square is malformed. The vertices of my square are as follows, aka the contents of a position. float vertices 0, 0, 0.5f, 0.5f, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0, 0.5f, 0f, 0.5f, 0.5f, 0, 0.5f, 0.5f The position of the square is (0, 0, 0), the rotation is (0, 0, 0) and the scale is 1. These are computed into u transformation and uploaded. This works perfectly. If I change the 1.0001999 and the last 0 to 1 part to 1 then the square is not hidden. void bindAttribute(int index, String name) GL20.glBindAttribLocation(program, index, name) bindAttribute(0, "a position") bindAttribute(1, "a colour")


How do I draw an animated object in OpenGL ES? I have a VBO, which I initialise like this (just an example) (void)setupVBOs GLuint vertexBuffer glGenBuffers(1, amp vertexBuffer) glBindBuffer(GL ARRAY BUFFER, vertexBuffer) glBufferData(GL ARRAY BUFFER, sizeof(Vertices), Vertices, GL STATIC DRAW) GLuint indexBuffer glGenBuffers(1, amp indexBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(Indices), Indices, GL STATIC DRAW) As you can see, I'm using GL STATIC DRAW, which is good for visually unchanging objects (not including translations and such). How do I draw animated objects though? I mean things that might be changed by user interaction. This video is a good example. It is obvious OpenGL is being used, as the vertices are manipulated by gestures. How is it done? by changing the x y z coordinates on every touch? Are they using GL DYNAMIC DRAW? Is this hard?


Depth Stencil Buffer In OpenGL, what is the difference between GL DEPTH COMPONENT and GL DEPTH STENCIL? I have looked around and have been unable to find a clear explanation. Information on their usage with GLSL would also be appreciated (mainly DEPTH STENCIL). Thanks for any help.


How are walkable regions determined, and movements handled on a 3D map? I've created a 3D scene with both indoor and outdoor parts. The outdoor part has bridges and caves also. How is it possible to handle player movements on it? My intuition is To determine the walkable regions, I could create a large grid. If the normal under the segment is not too steep, then it is walkable. If the difference between the heights of two neighboring segments in not large, then the player can move between them. My solution is far from optimal. It would consume a lot of memory, and it can't handle situations, when there are multiple walkable regions on the same XZ position (for example a bridge over a valley) How to manage movements effectively? How is it solved in game engines like Unreal or Unity?


fragment shader directional light positioning with camera Im trying to set up directional lighting in the fragment shader. So the direction of my light moves with the camera position. version 150 core uniform sampler2D diffuseTex uniform vec4 lightColour uniform vec3 lightDirection vec3 LNorm normalize(lightDirection) vec3 normal normalize(IN.normal) vec3 calColour lightColour i .rgb intensity gl FragColor vec4(diffuse.rbg calColour, diffuse.a) It lights the entire scene.


Parts of 3D model disappear during animation I'm trying to properly play an animation done in Blender 2.8 inside my OpenGL application. When the animation is running, it happens that at some particular frames, some parts of the 3D model "disappear", by "disappear" I mean that they obviously get relocated at some incorrect position and rotation in the 3D scene. The model is an FBX file. Has anyone got an idea about what could be the possible reasons for that? Maybe some wrong settings in Blender? Thanks in advance!


Calculating Per Vertex Normal in Geometry Shader I am able to calculate normals per face in my Geometry Shader but i want to calculate per vertex normal for smooth shading. My Geometry shader is version 430 core layout ( triangles ) in layout ( triangle strip, max vertices 3 ) out out vec3 normal out uniform mat4 projectionMatrix uniform mat4 viewMatrix uniform mat4 modelTranslationMatrix uniform mat4 modelRotationXMatrix uniform mat4 modelRotationYMatrix uniform mat4 modelRotationZMatrix uniform mat4 modelScaleMatrix void main(void) Please ignore my modelMatrix and NormalMatrix calculation here mat4 modelMatrix modelTranslationMatrix modelScaleMatrix modelRotationXMatrix modelRotationYMatrix modelRotationZMatrix mat4 modelViewMatrix viewMatrix modelMatrix mat4 mvp projectionMatrix modelViewMatrix vec3 A gl in 2 .gl Position.xyz gl in 0 .gl Position.xyz vec3 B gl in 1 .gl Position.xyz gl in 0 .gl Position.xyz mat4 normalMatrix transpose(inverse(modelViewMatrix)) normal out mat3(normalMatrix) normalize(cross(A,B)) gl Position mvp gl in 0 .gl Position EmitVertex() gl Position mvp gl in 1 .gl Position EmitVertex() gl Position mvp gl in 2 .gl Position EmitVertex() EndPrimitive() Since i don't have access to adjacent faces here, i cannot calculate per vertex normals. How can i calculate per vertex normals in my Geometry Shader?


How can rotate a 2D textured quad in legacy OpenGL immediate mode? I have a texture of a tank, and I want to it appearance on the screen depends on its current direction, so I decided to use rotating texture functions of OpenGL. I followed some advices through Google and received unsuccessful results. Anyone can help me with this problem? This is my render() function define UP 0 define DOWN 1 define LEFT 2 define RIGHT 3 void GameObject render() glBindTexture(GL TEXTURE 2D, textureID) glLoadIdentity() glTranslatef((GLfloat)coord.getX(), (GLfloat)coord.getY(), 0.0f) glDrawArrays(GL QUADS, 0, 4)


Sprite quickly disappears after rendering I'm currently making space invaders and I'm using the game loop pattern as described here. I have an entity class from which there is a spaceship derived class. The base entity class contains all of the general entity data such as the x y position, speed, etc... Currently, I have the X and Y positions initialized to (0,0) so the spaceship is rendered in the center of the screen. I tried initializing the y position to a different coordinate corresponding to a position, but for some reason, the spaceship just keep moving vertically as if the y position is just being accumulated at each frame. I think the problem is caused by the fact that in my render() method of the spaceship class, I'm translating the modelmatrix with the x and y position of the spaceship as that would explain why there isn't vertical movement when the coordinates are (0,0). I'm not sure exactly if this is the proper way to structure the render() method but I couldn't think of another way to change the object's position. Below is the relevant code Spaceship class definition class Spaceship public Entity public Spaceship(float xDirect, float yDirect, float xPosition, float yPosition, float speed, float rState, ShaderProgram program, SheetSprite newSprite, bool movingLeft, bool movingRight) Entity(xDirect, yDirect, xPosition, yPosition, speed, rState, program, newSprite), movingLeft(movingLeft), movingRight(movingRight) posY 0.1 virtual void Update(float elapsed) move stuff and check for collisions if (movingLeft) posX elapsed 0.001 else if (movingRight) posX elapsed 0.001 virtual void Render() setOrthoProj() setObjMatrices() translateObj(posX, posY, 0.0) mySprite.Draw() bool movingLeft bool movingRight Initialization Code in main Spaceship spaceship new Spaceship( 1.0f, 1.0f, 5.1f, 0.0f, 3.0f, 0.0f, program,mySprite, false, false) spaceship gt Render() Game Loop movement code const Uint8 keys SDL GetKeyboardState(NULL) if (keys SDL SCANCODE LEFT ) spaceship gt movingRight false spaceship gt movingLeft true spaceship gt Update(elapsed) else if (keys SDL SCANCODE RIGHT ) spaceship gt movingLeft false spaceship gt movingRight true spaceship gt Update(elapsed) spaceship gt Render() For some reason, the first render() call outside of the loop isn't rendering the spaceship, only the one inside the loop works. Given the structure of the program, what could be causing the problem? EDIT Translate method from Entity base class void translateObj(float x, float y, float z) posX x posY y modelMatrix.Translate(posX, posY, 0.0) void setObjMatrices() glUseProgram(program gt programID) program gt setModelMatrix(modelMatrix) program gt setProjectionMatrix(projectionMatrix) program gt setViewMatrix(viewMatrix)


How can I organize render and transformation data in a scalable fashion? I am writing for OpenGL 2.0 and in the future porting to OpenGL ES 2.0. I only use VBOs and shaders (no immediate mode, no vertex arrays). I already have working solutions, they just... feel wrong. All my calls related to OpenGL are tucked away in a separate class called RenderManager (this includes creation of VBOs and IBOs, texture IDs and shader programs) and rendering. I called the creation of OpenGL objects logging in and out, so majority of this action is invoked from the ResourceManager object upon loading of data. However, a lot of geometry (level) is generated dynamically and therefore some RenderManager calls to create the VBOs IBOs is scattered throughout the level class. Now, I have a Renderable interface which returns the (single) transformation matrix and a RenderOp object when it is time for rendering. RenderOps is an object that has Vertex Index Buffer pointers (has actual geom. data which in turn has VBO IBO indices) and some parameters such as whether to use the index buffer and if the RenderOp needs blending and stuff. There is also the RenderView object it has the viewport parameters, projection matrix and view matrix (camera). The game objects reside in the World class (single dimension arrays). These game objects are added upon their creation, and are derived from Entity interface. Entity is able to return the number of Renderable type objects within as well as the actual pointer to a Renderable at a given index. The magic happens when the main loop traverses the World. First it collects all Light objects visible from within Frustum. Then it collects Entity object that's within Frustum (it gets added to std vector inside RenderView if it is), and then it checks that same object to see if it is inside any of the visible Light's bounding volumes (and gets added into Light's std vector). Then the RenderView is passed onto the RenderManager class, which extracts appropriate Renderables from each Entity, applies Renderable's shader, then applies Renderable's textures, then stores the transforms inside itself and promptly shoves them down the programmable pipeline's throat along with attributes stored inside the RenderOperation (that gets extracted from Renderable as well). Last note I have NO way to render debug data, which is extremely annoying. A lot of what I am doing feels wrong. My question is, how do you organize all your Renderable and Transformation data to facilitate your rendering needs? I am burning out thinking of semi flexible ways of managing this data and I want to hear your ways. I am not a big fan of scene graphs, and consequently don't really want to implement one as I feel there are no real hierarchies inside the game, but I feel like I'm running myself into a corner. Please throw me a bone here, how do you manage all this data? And if you suggest an event based rendering system, how would you design it?


making a game in 2D(C ). SDL or openGL? Or, why not both? I'm trying to make a platform game in 2D and I want to know what tool should I use to make it happen. I understand that I can use SDL with openGL. However, if I want to make a solid 2D platform game, should I use SDL? Or, openGL?


How to make shadows softer as distance increases? I'm trying to make shadows become more blurry as the distance between the caster and receiver, so they look a little more realistic. What method can I use to achieve this?


2D Sidescroller camera I'm using OpenGL. For my tiles, I'm using a display list and I'm just using immediate more for my player (for now). When I move the player, I want to center him in the center of the window, but allow him to jump around on the y axis and not have the camera follow him. But the problem is, is that I can't figure out how to center the player in the viewport! Here is the player update method public void update() if (Keyboard.isKeyDown(Keyboard.KEY D)) World.scrollx Constants.scrollSpeed setCurrentSprite(Sprite.PLAYER RIGHT) if (Keyboard.isKeyDown(Keyboard.KEY A)) World.scrollx Constants.scrollSpeed setCurrentSprite(Sprite.PLAYER LEFT) move((Constants.WIDTH) 2 World.scrollx, getY()) World.scrollx and World.scrolly are variables that I increase decrease to move the tiles. move() is just a method that sets the player position, nothing else. I render the player at his current coordinates like this public void render() glBegin(GL QUADS) Shape.renderSprite(getX(), getY(), getCurrentSprite()) glEnd() Shape.renderSprite is this public static void renderSprite(float x, float y, Sprite sprite) glTexCoord2f(sprite.x, sprite.y Spritesheet.tiles.uniformSize()) glVertex2f(x, y) glTexCoord2f(sprite.x Spritesheet.tiles.uniformSize() , sprite.y Spritesheet.tiles.uniformSize()) glVertex2f(x Constants.PLAYER WIDTH, y) glTexCoord2f(sprite.x Spritesheet.tiles.uniformSize(), sprite.y) glVertex2f(x Constants.PLAYER WIDTH, y Constants.PLAYER HEIGHT) glTexCoord2f(sprite.x, sprite.y) glVertex2f(x, y Constants.PLAYER HEIGHT) Pretty simple, I just render the quad at the current player's position. This is how I actually render everything public void render(float scrollx, float scrolly) Spritesheet.tiles.bind() glPushMatrix() glTranslatef(scrollx, scrolly, 0) glCallList(tileID) glPopMatrix() player.render() This is the part I'm confused on. I translate the tiles according to the scrollx and scrolly variables, and then I render the player at his current position. But the player moves faster than the tiles scroll, and he can escape out the side of the screen! How do I center the player with moving tiles? Thanks for any help!


Camera movement with slerp I have 3 spots, I would like to move my camera to using slerp. Just As seen in the image below. My question is how I can connect my camera to the first spot? I should be able to move between other spots after I connect my camera to the first spot. Maybe a better way to ask is how can I make the camera location my first quaternion spot?


How can I render a JBox2D ParticleGroup? I want to render a ParticleGroup from JBox2d using OpenGL. I've managed to define a particle group area, but I'm unsure how to draw the individual particles. Here's how I create the ParticleGroup m world.setParticleRadius(0.15f) m world.setParticleDamping(0.2f) PolygonShape shape new PolygonShape() shape.setAsBox(8, 10, new Vec2( 12, 10.1f), 0) ParticleGroupDef pd new ParticleGroupDef() pd.shape shape m world.createParticleGroup(pd) This is how I draw a normal Square (which I don't know how to apply to groups of particles) public void draw(GLAutoDrawable gLDrawable, Vec3 position, float angle) gLDrawable.getGL().getGL2().glEnable(GL.GL BLEND) gLDrawable.getGL().getGL2().glEnable(GL.GL TEXTURE 2D) gLDrawable.getGL().getGL2().glBlendFunc(GL.GL SRC ALPHA, GL.GL ONE MINUS SRC ALPHA) gLDrawable.getGL().getGL2().glBindTexture(GL2.GL TEXTURE 2D, TextureFactory.getTextureIndex(TextureCollection.valueOf(getTextureSelection()))) gLDrawable.getGL().getGL2().glPushMatrix() gLDrawable.getGL().getGL2().glTranslatef(position.x getP2M(), position.y getP2M(), position.z) gLDrawable.getGL().getGL2().glRotated(Math.toDegrees(angle), 0, 0, 1) gLDrawable.getGL().getGL2().glBegin(GL2.GL QUADS) gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 0.0f) gLDrawable.getGL().getGL2().glVertex3f( getWidth() 2 getP2M(), getHeight() 2 getP2M(), 0.0f) gLDrawable.getGL().getGL2().glTexCoord2f(0.0f, 1.0f) gLDrawable.getGL().getGL2().glVertex3f( getWidth() 2 getP2M(), getHeight() 2 getP2M(), 0.0f) gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 1.0f) gLDrawable.getGL().getGL2().glVertex3f(getWidth() 2 getP2M(), getHeight() 2 getP2M(), 0.0f) gLDrawable.getGL().getGL2().glTexCoord2f(1.0f, 0.0f) gLDrawable.getGL().getGL2().glVertex3f(getWidth() 2 getP2M(), getHeight() 2 getP2M(), 0.0f) gLDrawable.getGL().getGL2().glEnd() gLDrawable.getGL().getGL2().glFlush() gLDrawable.getGL().getGL2().glPopMatrix() gLDrawable.getGL().getGL2().glDisable(GL.GL TEXTURE 2D) gLDrawable.getGL().getGL2().glDisable(GL.GL BLEND) How should I do this? (Example code would be great.)


VBO and shaders confusion, what's their connection? Considering OpenGL 2.1 VBOs and 1.20 GLSL shaders When creating an entity like "Zombie", is it good to initialize just the VBO buffer with the data once and do N glDrawArrays() calls per each N zombies? Is there a more efficient way? (With a single call we cannot pass different uniforms to the shader to calculate an offset, see point 3) When dealing with logical object (player, tree, cube etc), should I always use the same shader or should I customize (or be able to customize) the shaders per each object? Considering an entity class, should I create and define the shader at object initialization? When having a movable object such as a human, is there any more powerful way to deal with its coordinates than to initialize its VBO object at 0,0 and define an uniform offset to pass to the shader to calculate its real position?


MSAA CSAA FXAA How to set the mode in OpenGL? I'm learning OpenGL and something I am stuck with is AA. Specially when I want to turn it on and off at runtime. I know that I can set the samplecount when I create a FBO and blit it over to the final window. When I want to change the mode I switch the FBO and everything is fine. The question I am completely stuck with is, how do I change the mode and also important, how do I query the modes that the card supports. With mode I mean CSAA,MSAA,.. .I can't find a lot. At least I know that it is vendor specific. Hope anyone can point me in the right direction. Thanks


How can I render a font in C with OpenGL? What I tried I was testing some things in order to render text with stb truetype.h and OpenGL in C. I took as a reference the example that appears here. Basically, this example, loads a .ttf file and returns the raw information in bytes, that can be used to generate a texture in OpenGL. I adapted the example, mentioned before, into modern OpenGL, because, the example uses OpenGL deprecated functions, like glVertex2f. The only thing I get to output on screen was this kind of noise of strange colors The code I use texture t fnt texture GLuint fnt shader unsigned char ttf buffer 1 lt lt 20 unsigned char temp bitmap 512 512 stbtt bakedchar cdata 96 ASCII 32..126 is 95 glyphs define FONT VS quot version 330 core n quot quot layout(location 0) in vec3 m Position quot quot layout(location 1) in vec2 m TexCoords quot quot out vec2 TexCoords n quot quot void main() n quot quot TexCoords m TexCoords n quot quot gl Position vec4(m Position, 1.0) n quot quot n quot define FONT FS quot version 330 core n quot quot in vec2 TexCoords n quot quot uniform sampler2D Texture n quot quot void main() n quot quot gl FragColor texture(Texture, TexCoords) n quot quot n quot void font init(void) fread(ttf buffer, 1, 1 lt lt 20, fopen( quot c windows fonts times.ttf quot , quot rb quot )) stbtt BakeFontBitmap(ttf buffer, 0, 32.0, temp bitmap, 512, 512, 32, 96, cdata) no guarantee this fits! glGenTextures(1, amp fnt texture 3 ) My texture type, is an array that saves the texture on the 3rd position. glBindTexture(GL TEXTURE 2D, fnt texture 3 ) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA8, 512, 512, 0, GL RGBA, GL UNSIGNED BYTE, temp bitmap) glGenerateMipmap(GL TEXTURE 2D) can free temp bitmap at this point glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glBindTexture(GL TEXTURE 2D, 0) fnt shader shader init(FONT VS, FONT FS) void font render(model t model) shader bind(fnt shader) texture bind(fnt texture, 0) model begin(model) model draw(model, GL TRIANGLES) The model (vao, vbo, ibo) is rendering the whole buffer, not individual glyphs model end() texture unbind() shader unbind() Can someone tell me what I'm doing wrong, and, how I'm suposed to render correctly text, with modern OpenGL, with textures and buffers, in order to read the .ttf file and create the necessary information with stb truetype.h and, then, render the text?


OpenGL can't use glew 3.0 I've been trying to follow a tutorial of glew, but i can't run this glGenVertexArrays, it always leads to a memmory access violation!... I tried glExperimental GL TRUE too, also updated my video card driver 2 times, but it doesn't run. Btw, there's my code (to TRY to generate a simple triangle) include lt stdio.h gt include lt stdlib.h gt include lt iostream gt using namespace std include lt glew.h gt include lt glfw.h gt include lt glm glm.hpp gt using namespace glm define GLFW DLL pragma comment(linker, " SUBSYSTEM WINDOWS") pragma comment(linker, " ENTRY mainCRTStartup") int main() glewExperimental GL TRUE if(!glfwInit()) cout lt lt "Failed to load graphics... " lt lt endl return 1 GLuint VertexArrayID glGenVertexArrays(1, amp VertexArrayID) glBindVertexArray(VertexArrayID) static const GLfloat g vertex buffer data 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, GLuint vertexbuffer glGenBuffers(1, amp vertexbuffer) glBindBuffer(GL ARRAY BUFFER, vertexbuffer) glBufferData(GL ARRAY BUFFER, sizeof(g vertex buffer data), g vertex buffer data, GL STATIC DRAW) glfwOpenWindowHint(GLFW FSAA SAMPLES, 4) glfwOpenWindowHint(GLFW VERSION MAJOR, 3) glfwOpenWindowHint(GLFW VERSION MINOR, 1) glfwOpenWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) glfwOpenWindowHint(GLFW OPENGL PROFILE, 0) if(!glfwOpenWindow(1024, 768, 0, 0, 0, 0, 32, 0, GLFW WINDOW)) cout lt lt "Failed to open window" glfwTerminate() return 2 glfwSetWindowTitle("IfUSeeingThisMsgTheShitWorked") glfwEnable(GLFW STICKY KEYS) Main loop do cout lt lt "happaned" glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, vertexbuffer) glVertexAttribPointer(0,3, GL FLOAT, GL FALSE, 0, (void ) 0) glDrawArrays(GL TRIANGLES, 0, 3) glDisableVertexAttribArray(0) glfwSwapBuffers() while(glfwGetKey(GLFW KEY ESC) ! GLFW PRESS amp amp glfwGetWindowParam(GLFW OPENED)) return 0 Also, I want to point out that this function doesn't work glfwOpenWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) so I had to change it to glfwOpenWindowHint(GLFW OPENGL PROFILE, 0) Does it have anything to do with my error? hm. I'm posting it here, just to make sure that there's no other thing I can do, other than buy a new video card. I really want to use the modern OpenGL, it is pointless to learn the old one.


When I add in Java transformationMatrix I can't see images? When I add in Java transformationMatrix I can't see images moving but when I remove it I can see why and how to fix it? Any ideas how to fix it? My Renderer class public class Renderer private static final float FOV 70 private static final float NEAR PLANE 0.1f private static final float FAR PLANE 1000 private Matrix4f projectionMatrix public Renderer(StaticShader shader) createProjectionMatrix() shader.start() shader.loadProjectionMatrix(projectionMatrix) shader.stop() public void prepare() GL11.glClear(GL11.GL COLOR BUFFER BIT) GL11.glClearColor(1, 0, 0, 1) public void render(Entity entity,StaticShader shader) TexturedModel model entity.getModel() RawModel rawModel model.getRawModel() GL30.glBindVertexArray(rawModel.getVaoID()) GL20.glEnableVertexAttribArray(0) GL20.glEnableVertexAttribArray(1) Matrix4f transformationMatrix Maths.createTransformationMatrix(entity.getPosition(), entity.getRotX(), entity.getRotY(), entity.getRotZ(), entity.getScale()) shader.loadTransformationMatrix(transformationMatrix) GL13.glActiveTexture(GL13.GL TEXTURE0) GL11.glBindTexture(GL11.GL TEXTURE 2D, model.getTexture().getID()) GL11.glDrawElements(GL11.GL TRIANGLES, rawModel.getVertexCount(), GL11.GL UNSIGNED INT, 0) GL20.glDisableVertexAttribArray(0) GL20.glDisableVertexAttribArray(1) GL30.glBindVertexArray(0) private void createProjectionMatrix() float aspectRatio (float) Display.getWidth() (float) Display.getHeight() float y scale (float) ((1f Math.tan(Math.toRadians(FOV 2f))) aspectRatio) float x scale y scale aspectRatio float frustum length FAR PLANE NEAR PLANE projectionMatrix new Matrix4f() projectionMatrix.m00 x scale projectionMatrix.m11 y scale projectionMatrix.m22 ((FAR PLANE NEAR PLANE) frustum length) projectionMatrix.m23 1 projectionMatrix.m32 ((2 NEAR PLANE FAR PLANE) frustum length) projectionMatrix.m33 0 Edit added StaticShader class package shader import org.lwjgl.util.vector.Matrix4f public class StaticShader extends ShaderProgram private static final String VERTEX FILE "src shader vertexShader.txt" private static final String FRAGMENT FILE "src shader fragmentShader.txt" private int location transformationMatrix private int location projectionMatrix public StaticShader() super(VERTEX FILE, FRAGMENT FILE) Override protected void bindAttributes() super.bindAttribute(0, "position") super.bindAttribute(1, "textureCoords") Override protected void getAllUniformLocations() location transformationMatrix super.getUniformLocation("transformationMatrix") location projectionMatrix super.getUniformLocation("projectionMatrix") public void loadTransformationMatrix(Matrix4f matrix) super.loadMatrix(location transformationMatrix, matrix) public void loadProjectionMatrix(Matrix4f projection) super.loadMatrix(location projectionMatrix, projection) Edit vertexShader.txt version 400 core in vec3 position in vec2 textureCoords out vec3 colour out vec2 pass textureCoords uniform mat4 transformationMatrix uniform mat4 projectionMatrix void main(void) gl Position projectionMatrix transformationMatrix vec4(position,1.0) pass textureCoords textureCoords colour vec3(position.x 0.5,0.0,position.y 0.5)


Why does this work in the fragment shader but not in the vertex shader? I'm doing some model view and projection transforms in the vertex shader and I want to determine whether the current vertex will end up on the viewport or not. After searching a bit I found that after the projection transform the coordinates have not been "normalized". So the criteria for a vertex (after the transforms) to appear in the final viewport is the following w lt x lt w w lt y lt w 0 lt z lt w where w is the 4th coordinate of the vertex after the transforms Performing this check I had a great amount of vertices passing the test without being in the viewport and this caused many sorts of problems in whatever I was trying to implement. However, passing the vertices in their local coordinates to the fragment shader and then doing the exact same process with the transforms and the tests everything worked out fine. Why?


input arrays in OpenGL vertex Shader would something like this be valid as an input to a vertex shader? layout (location 0) in float 6 faceTextureOffsets I know you can use things like vec3s but for this situation I need an array of 6 floats. I am using a texture atlas and I would like for different sides of the cubes i'm rendering to have different textures and I need a way to be able to change the position in the texture atlas.


Textures created with Photoshop show up with a white border All of a sudden, I started having this problem. I've used libGDX Photoshop before and never had this problem. One of my textures is showing up with a white border glow around. The texture is the black blob on the middle, which is a 256 pixels png with a few black brushstrokes I created with Photoshop, just to test it. Everything in libGDX is on default. I haven't changed the blending function, I'm just using a SpriteBatch to render the image without any changes. The weird thing is, some other textures I created with Photoshop, same size, RBG 8 bit color mode (just like my blob image), look fine. These are temporary textures I created by downloading a png from the web, pasting it into Photoshop, applying a solid color overlay effect to it and saving it back as a png. Any idea what's causing this? Edit Here's how I'm loading my textures private static Texture createTexture(String fileName, boolean maxQuality, Texture.TextureWrap textureWrap) Texture result new Texture(Gdx.files.internal(fileName), true) result.setFilter(maxQuality ? Texture.TextureFilter.MipMapLinearLinear Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear) TODO Are these the best? if(textureWrap ! null) result.setWrap(textureWrap, textureWrap) return result texture new TextureRegion(createTexture("data blob.png")) I just found out using this technique that the transparent pixels in my texture are white (1, 1, 1, 0). So I'm pretty sure the cause is a combination of this, the linear resizing and probably the blending function. Not sure what's the right way to fix it though. Don't want to change the resizing to nearest.


Minecraft OpenGL Create Multiple viewports I'm working on a project for the game and i have been trying to draw a second smaller "window" that would act like a second camera, independent from the player. I have looked into glViewport however i keep running into issues where the second viewport is the only one being drawn (the first one gets covered by the second and has a blank screen where the first viewport should be So i guess the question is How can i have multiple windows on screen and make it so it plays nice with the game's default rendering system? I know it is possible since the game uses OpenGL, and maybe its just a simple case of putting the code in the right class.


Quaternion precision problems Each entity and camera have a Transformation object that holds position info as vec3, rotation info as quat and scale info as vec3. When I need a matrix (that being either model or view matrix), I construct the matrix out of given data. That gives me the freedom to change any of transformation info without having to worry about order of change. Now, I'm trying to implement it in a fly camera. The two constraints are pitch that has to be limited from 90 to 90 and roll which should not occur. While rotating the camera along X and Y axis, a sort of drift happens along the Z axis. In order to combat that, after all changes to rotation are applied, I get the angle of rotation around the Z axis and then rotate it by angle, effectively resetting the Z rotation to 0. That all works nicely in theory, but not so much in practice. You see, when I go over 55ish both in the positive or negative Y rotation, the camera starts freaking out and fluctuating. It seems that every frame it switches from some negative z rotation, to positive z rotation of the same value. It looks like this (moving camera to the left, negative Y rotation) Of course, since the object is only in the one place at one time, I had to edit the screenshot in paint to give you a better idea of what's going on. It really does look like there are two objects at the same time, both flickering as crazy. Also note that if I were to move camera further to the left, the Z rotation offset would increase, moving both objects further from the horizontal plane. At this point, the Y rotation would also start to fluctuate ever so slightly. You couldn't see it on screen, but printing out angle each frame would show that it's fluctuating at about 3rd digit after the dot (0.00 ). Once I get far enough, the camera would just give up and just show the object rapidly changing it's Z rotation with no apparent pattern. My guess is that quaternion rotation is imprecise for some reason. You can tell by the fact that my strict Z rotation starts to influence the Y rotation after the Z drift gets severe enough. Here's a snippet of code, for what it's worth transformation gt rotateAroundY(angleY) GLfloat roll transformation gt getRoll() transformation gt rotateAroundZ( roll) angleY is delta Y of mouse position between this and previous frame. rotateAround (angle) calls this code rotation glm tquat lt GLfloat gt (glm angleAxis(glm radians(angle), axis)) where rotation is the quaternion, while axis is tvec3 lt GLfloat gt representing the axis around which the rotation takes place. How do I combat this? How can I consistently reverse unintentional Z drift without making the camera freak out?


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?


Proper way to maintain Vertex Buffer Objects I've started learning WebGL, currently I'm building a 2D lighting system, but there is some confusion going on inside my head. How the lighting works is based on this tutorial http archive.gamedev.net archive reference programming features 2dsoftshadow default.html (probably the most linked article of the genre). My question is about the proper way to store create update the Vertex Buffer Objects of the polygons. Currently I have something like during initialization of each polygon build vertices from the provided points ... create the VBO this. VBO gl.createBuffer() gl.bindBuffer( gl.ARRAY BUFFER, this. VBO ) gl.bufferData( gl.ARRAY BUFFER, vertices, gl.DYNAMIC DRAW ) during rendering of each polygon gl.bindBuffer( gl.ARRAY BUFFER, this. VBO ) gl.enableVertexAttribArray( program.aVertexPosLoc ) gl.vertexAttribPointer( program.aVertexPosLoc, 3, gl.FLOAT, false, 0, 0 ) The vertices array is created only one time at the top of the file, and reused for each new polygon, the motive to do that is to avoid the creation of various Float32Arrays per object. top of file var vertices new Float32Array( 20 3 ) maximum of 20 points It's okay to have one VBO for each object? I was thinking about the possibility of a single VBO, but I don't understand how I can make it work with only one. The number of vertices can vary between one polygon and another, so how I'm going to store that? Currently I'm not taking into consideration textures, however, answers that already take they into account are welcome.


How can I use ImGui to render simple text instead of using stb truetype directly? Since ImGui builds on top of stb truetype for its font rendering, I thought it could be nicer to use its already built font processing capabilities (ImGui GetIO().Fonts), and render with those, instead of using stb truetype directly. However, I've been having trouble figuring out how to do this, specifically how to get quad position texture coordinates for a given string to use with the preloaded texture at ImGui GetIO().Fonts gt TexID. I'm not looking to draw buttons text inside ImGui windows, all I want to do is to use ImGui to build vertex data for a given string so that I can render it anywhere.


Consistent Shadow Map Filtering I want to filter my shadow map generated by PSSM, but the problem is that I have a inconsistent filter size. The problem is that the shadow map sources rotate to find the best fit for the camera frustum, and thus sampling with a constant offset (e.g. 10.0 resolution) produces inconsistent results. A gif shows it probably best (same shadow and sun position, just different view angles) GIF showing the issue My idea was to, instead of using a fixed filter offset, compute the filter offset by projecting 2 world space points to light space and taking the difference of both, like this vec4 find filter size(mat4 projection, vec3 light, float sample radius) Find an arbitrary tangent and bitangent to the light vector vec3 v0 abs(light.z) lt 0.99 ? vec3(0, 0, 1) vec3(1, 0, 0) vec3 tangent normalize(cross(v0, light)) vec3 binormal normalize(cross(light, tangent)) Project everything vec2 proj origin project(projection, vec3(0)).xy vec2 dx proj tangent project(projection, tangent).xy proj origin vec2 dx proj binormal project(projection, binormal).xy proj origin return vec4(dx proj tangent, dx proj binormal) sample radius However that didn't quite work out, and, in fact, produces even more artifacts. Any suggestions how I could fix this? I just need a basic idea, then I can figure out the implementation by myself.


Architecture to draw many different objects in OpenGL I have some objects that I want to draw. I am not sure how I can create my architecture in a way where I can draw everything as fast as possible. As example class MyObject float vertices float colors float textures public MyObject() fill every buffer with data public void Draw() set shader set shader uniforms etc. foreach buffer BindBuffer() VertexAttribPointer() DrawArrays() In this way, I can draw every object like myObject.Draw after it is constructed. The problem would be, that if I have 5000 objects, I have 5000 draw calls. I need to set the shader every time even if I loop over the 5000 objects because I don't know if they use the same shaders. Another way class MyObject bool needsToBeChanged public MyObject() set my edge points needsToBeChanged true void ChangeMyObject() e.g. I changed the height of my object needsToBeChanged true class GLWindow float vertices float colors float textures GameLoop() foreach(MyObject myObj in allMyObjects) if(myObj.needsToBeChanged) get objects points for drawing it and set the global buffers up myObj.needsToBeChanged false DrawArrays() draw only once (because every data is in the buffer) Only 1 draw call for everything. I guess this will be faster than first method. The problem on this code is the big buffer that contains everything. Let's imagine we have inherited from MyObject and want to draw objects in different shapes. Now the Loop gets more complicated. You may have to split it because you need another shader for example for text. Now you have 2 arrays... And with other changes the Loop becomes more and more complicated and harder to maintain. What solutions (beside the both) are available for this kind of problem? Can I use the first way or is there a better way where I can reduce the draw calls? How is it solved in other applications?


Why do I have to switch T(v) texture coordinates while importing OpenGL to Direct3D? I am importing my code from OpenGL to Direct3D. My D3DTS PROJECTION uses D3DXMatrixPerspectiveFovRH, and my D3DTS VIEW uses D3DXMatrixLookAtRH to set a view equal to OpenGL's view. My question is why do I have to switch all of my 1.0000 Tex(v) texture coordinates to "minus value" in D3D to get equal texture mapping as in OpenGL. OpenGL T(u) T(v) 1.0000, 1.0000, 0.0000, 1.0000, 1.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, ... Direct3D T(u) T(v) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) ... Is it because Direct3D's origin (0.0) of texture coordinates lies in different place than in OpenGL?


Using gluLookAt to move camera in 2D iPhone game? I'm trying to use gluLookAt to move the camera in my iPhone game, but every time I've tried to use gluLookAt my screen just goes "blank" ( grey in this case ) I'm trying to render a simple triangle and to move the camera, this is my code to setup my scene I do glViewport(0, 0, backingWidth, backingHeight) glMatrixMode(GL PROJECTION) glLoadIdentity() glRotatef( 90.0, 0.0, 0.0, 1.0) using iPhone in horizontal mode glOrthof( 240, 240, 160, 160, 1, 1) glMatrixMode(GL MODELVIEW) then my "triangle rendering" code looks like GLfloat triangle 0, 100, 100, 0, 100, 0, glClearColor(0.7, 0.7, 0.7, 1.0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glEnableClientState(GL VERTEX ARRAY) glColor4f(1.0, 0.0, 0.0, 1.0) glVertexPointer(2, GL FLOAT, 0, amp triangle) glDrawArrays(GL TRIANGLES, 0, 6) glDisableClientState(GL VERTEX ARRAY) This draws a red triangle in the middle of the screen, when I try to apply gluLookAt ( I got the implementation of the function from Cocos2D so I asume it's correct ), i do glMatrixMode(GL MODELVIEW) glLoadIdentity() gluLookAt(0,0,1,0,0,0,0,0,1) try to move the camera a bit ? GLfloat triangle 0, 100, 100, 0, 100, 0, glClearColor(0.7, 0.7, 0.7, 1.0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glEnableClientState(GL VERTEX ARRAY) glColor4f(1.0, 0.0, 0.0, 1.0) glVertexPointer(2, GL FLOAT, 0, amp triangle) glDrawArrays(GL TRIANGLES, 0, 6) glDisableClientState(GL VERTEX ARRAY) This leads me to grey screen (glClearColor is grey), I've tried all sort of things and read what I've found about gluLookAt on the net, but no luck (, if someone could explain me or show me how to move to move the camera in a top down fashion ( zelda, etc ), I would really appreciate it. Thanks!


Should I use the X Y plane when using an orthographic projection in OpenGL? I'm currently at a loss rendering a tile based 3D map with an orthographic projection in OpenGL. Imagine any isometric 3D game (using actual geometry instead of sprites). Internally, the tiles of my map have x and y coordinates (for column and row position within the map respectively). The tile with x 0 and y 0 is the one in the "top left", the one with y 0 and x 1 the one to the right of the first tile and so on. Since in OpenGL, the coordinate system is so that the X Z plane is the "ground" plane, I create the model matrix for each tile by using the tile's y coordinate for the matrix' (or position vector's) z component. I then set up an orthographic "camera" by using glm ortho(). This seems to work fine at first, but I quickly ran into clipping issues when trying to render larger parts of the map. I assume this is due to the fact that the orthographic projection clips on z. A quick and dirty attempt of having the map in the X Y plane confirmed this, as I didn't have clipping issues then. Now, I'm not sure what's the best approach here? Change the code so the tiles are being layed out in the X Y plane? In that case, it seems as if I would have to remember to rotate every single object around x accordingly, which seems wrong. Do I need to set up the orthographic projection manually to use Y as the clipping plane? Is that even possible? I think OpenGL always uses z for clipping, right? Some other approach? I think I'm lost in coordinates and matrices, really. I assume this is a common problem with a well known solution, so I'm hoping to learn about that before I go ahead, change a lot and then learn I did it the wrong way...


Simplest way of skeletal animation in openGL I am not interested in using easy libraries like assimp which will import collada files with ease to get skeleton animation done. I wanna know what is the minimal requirement to get the animation done. What I understand is that a bone is a 3 3 rotation matrix which is associated with each group of vertex. We have to augment it with the model matrix to animate anything How would I play a sequential animation with my existing bone system. What's the workflow to process the bones. Sending bones through Uniform block is slow but I would consider doing it. What's the simplest file format to store rig and animation data. Collada is unnecessarily advanced and complex. Or how would I write my own file format for animation. I am using blender to model and rig. How would I even manage to get an exporter for my format in blender


What are the different attributes of a vertex array object (VAO)? What are the 16 attributes of a VAO? 0. vertex position 1. vertex colours 2. normal vector 3. texture coords 4. ??? 5. ??? 6. ??? 7. ??? 8. ??? 9. ??? 10. ??? 11. ??? 12. ??? 13. ??? 14. ??? 15. ???


How to animate a model in WebGL? I created a human model in Blender, exported the vertices and indices into a JSON file and render the model in a browser using WebGL. Now I created a walk and jump animation in Blender and would like to do the same with WebGL. I saw examples that use a list of vertices for every frame of the animation. Is this the way to go? Do I need to export the vertices for every frame for every animation?


Creating a retro style palette swapping effect in OpenGL I'm working on a Megaman like game where I need to change the color of certain pixels at runtime. For reference in Megaman when you change your selected weapon then main character's palette changes to reflect the selected weapon. Not all of the sprite's colors change, only certain ones do. This kind of effect was common and quite easy to do on the NES since the programmer had access to the palette and the logical mapping between pixels and palette indices. On modern hardware, though, this is a bit more challenging because the concept of palettes is not the same. All of my textures are 32 bit and do not use palettes. There are two ways I know of to achieve the effect I want, but I'm curious if there are better ways to achieve this effect easily. The two options I know of are Use a shader and write some GLSL to perform the "palette swapping" behavior. If shaders are not available (say, because the graphics card doesn't support them) then it is possible to clone the "original" textures and generate different versions with the color changes pre applied. Ideally I would like to use a shader since it seems straightforward and requires little additional work opposed to the duplicated texture method. I worry that duplicating textures just to change a color in them is wasting VRAM should I not worry about that? Edit I ended up using the accepted answer's technique and here is my shader for reference. uniform sampler2D texture uniform sampler2D colorTable uniform float paletteIndex void main() vec2 pos gl TexCoord 0 .xy vec4 color texture2D(texture, pos) vec2 index vec2(color.r paletteIndex, 0) vec4 indexedColor texture2D(colorTable, index) gl FragColor indexedColor Both textures are 32 bit, one texture is used as lookup table containing several palettes which are all the same size (in my case 6 colors). I use the source pixel's red channel as an index to the color table. This worked like a charm for achieving Megaman like palette swapping!


How to properly repeat a texture on a quad in OpenGL? I'm drawing a quad and binding a texture to this quad like this define TERRAIN WIDTH 2000 define TERRAIN LENGTH 2000 define TERRAIN WIDTH 2 (TERRAIN WIDTH 2) define TERRAIN LENGTH 2 (TERRAIN LENGTH 2) glBindTexture(GL TEXTURE 2D, gameTextures.terrain) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex3f( TERRAIN WIDTH 2, 0.0f, TERRAIN LENGTH 2) glTexCoord2f(X, 0) glVertex3f( TERRAIN WIDTH 2, 0.0f, TERRAIN LENGTH 2) glTexCoord2f(X, X) glVertex3f( TERRAIN WIDTH 2, 0.0f, TERRAIN LENGTH 2) glTexCoord2f(0, X) glVertex3f( TERRAIN WIDTH 2, 0.0f, TERRAIN LENGTH 2) glEnd() glBindTexture(GL TEXTURE 2D, 0) Normally, X would be equal to 1 but this will stretch the texture because the quad is very large. The idea is to increase that value so the texture is repeated (the texture was generated with GL REPEAT of course). But how should I find the best value for X? I have a few 512x512 textures which look nice if I replace X 512. Then I have another 1024x1024 texture which looks good to with X 512 but doesn't start to look so good with a higher lower value. Another texture is 2048x2048 and now I need to go down to X 256, otherwise it won't look so good. What's confusing me even more is the fact that both 512x512 and 1024x1024 textures look good with X 512. The way I see it, the lower the texture resolution, the more times I need to repeat it. How should I calculate the value of X then?


OpenGL fixed function WASD 2D movement I need to make a simple object (like a turtle) move on a 2D scene. The keys w, s, a and d, respectively, make a positive and negative translate on x axis (move to forward and backward), and rotate 1 degree (a and d). The problem is the simple object, will initially rotate and translate correctly (because initially the object is at the origin). But after that the commands don't work like I intend them to. Which are the best practices to make this? Anyone can help me? To compile (assuming this code is saved in a file named movement2D.cpp) g movement2D.cpp o movement2D lGL lglut To execute, use . movement2D 500 500 Here's the code include lt GL glut.h gt struct point int x int y typedef struct point t point struct object int width int height t point pose float angle typedef struct object t object void display(void) void keyPress(unsigned char, int, int) void initialize(int, int) void exit(void) void draw(void) t object head, body int main(int argc, char argv) glutInit( amp argc, argv) glutInitDisplayMode(GLUT SINGLE GLUT RGB) glutInitWindowSize(atoi(argv 1 ), atoi(argv 2 )) glutInitWindowPosition(10, 10) glutCreateWindow( quot Movement quot ) initialize(atoi(argv 1 ), atoi(argv 2 )) glutDisplayFunc(display) glutKeyboardFunc(keyPress) atexit(exit) glutMainLoop() void display(void) glClear(GL COLOR BUFFER BIT) glPushMatrix() glLoadIdentity() glRotatef(body gt angle, 0.0f, 0.0f, 1.0f) glTranslatef(body gt pose.x, body gt pose.y, 0.0f) draw() glPopMatrix() glutSwapBuffers() void keyPress(unsigned char key, int x, int y) switch (key) case 'a' case 'A' body gt angle 1 break case 'd' case 'D' body gt angle 1 break case 'w' case 'W' body gt pose.x 5 break case 's' case 'S' body gt pose.x 5 break case 27 exit(1) glutPostRedisplay() void initialize(int width, int height) head (t object ) calloc(1, sizeof(t object)) body (t object ) calloc(1, sizeof(t object)) body gt width body gt height 100 head gt width head gt height 20 body gt pose.x body gt pose.y 0 glClearColor(0.0f, 0.0f, 0.0f, 1.0f) glMatrixMode(GL PROJECTION) glOrtho( width 2, width 2, height 2, height 2, 100, 100) glMatrixMode(GL MODELVIEW) void exit(void) free(head) free(body) void draw(void) glColor3f(1.0f, 0.0f, 0.0f) glBegin(GL QUADS) glVertex2i( body gt width 2, body gt height 2) glVertex2i( body gt width 2, body gt height 2) glVertex2i(body gt width 2, body gt height 2) glVertex2i(body gt width 2, body gt height 2) glEnd() glTranslatef(body gt width 2 head gt width 2, 0.0f, 0.0f) glColor3f(0.0f, 0.0f, 1.0f) glBegin(GL QUADS) glVertex2i( head gt width 2, head gt height 2) glVertex2i( head gt width 2, head gt height 2) glVertex2i(head gt width 2, head gt height 2) glVertex2i(head gt width 2, head gt height 2) glEnd()


Is there any reason not to save skinning animation data in texture? I have thought about saving animation data in texture. I think I can save shader parameter setting and interpolation cost in CPU, and also enable animated instancing. But I couldn't find no text mentioning about this, so I think there's some obvious reason people don't do this. Which I'm missing. Can I know what I missed? Or is this just widely known technique?


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 ?


Opengl scrolling world guidance I'm looking for a tutorial about how to implement a horizontally scrolling background with various objects that auto scrolls as your character player moves just like various car motorbikes games. I'll have images for various obstacles, objects along the path. I'm concerned if I load everything on start of game. i would want these to be loaded for visible area as the player moves (or appears to move). Though I'm looking for a tutorial in android and I'm new to opengl, but I welcome any sort of help.


Problems with rendering a SkyBox At the moment I'm writing an Android OpenGL ES 2.0 game but now I get stuck on rendering a SkyBox. Here is my (a bit simplified) code for the SkyBox float vertices 1,1,1,1,1,1, 1, 1,1,1, 1,1, 1,1, 1,1,1, 1, 1, 1, 1,1, 1, 1 byte drawOrder 1,3,0,0,3,2,4,6,5,5,6,7,0,2,4,4,2,6,5,7,1,1,7,3,5,1,4,4,1,0,6,2,7,7,2,3 private final void bindTexture() int shaderTextureUnit GLES20.glGetUniformLocation(shaderProgram, "u TextureUnit") GLES20.glActiveTexture(GLES20.GL TEXTURE0) GLES20.glBindTexture(GLES20.GL TEXTURE CUBE MAP, texture) GLES20.glUniform1i(shaderTextureUnit, 0) public void draw(float viewMatrix) viewMatrix Camera data array GLES20.glUseProgram(shaderProgram) bindTexture() Load Texture shaderPosition GLES20.glGetAttribLocation(shaderProgram, "a Position") shaderMatrix GLES20.glGetUniformLocation(shaderProgram, "u Matrix") get handle to shape's transformation matrix GLES20.glUniformMatrix4fv(shaderMatrix, 1, false, vpMatrix, 0) Prepare the triangle coordinate data GLES20.glEnableVertexAttribArray(shaderPosition) GLES20.glVertexAttribPointer(shaderPosition, 3, GLES20.GL FLOAT, false, 0, vertexBuffer) Draw the object to the screen GL UNSIGNED BYTE GLES20.glDrawElements(GLES20.GL TRIANGLES, orderBuffer.capacity(), GLES20.GL UNSIGNED BYTE, orderBuffer) GLES20.glDisableVertexAttribArray(shaderPosition) Free the position in shader I think this code should be perfect because I got it from an OpenGL for beginners book. My problem now is that it looks like this if I render the SkyBox to the screen. I initialize my Camera with this code and here you have also the code for my touch event. If my considerations are right this should produce a circle around the origin so I can see all sides of the SkyBox. private float angle 90 Matrix.setLookAtM(data, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0) the viewMatrix Z out of screen Z in screen public void onTouch() angle 2 float s (float) Math.sin(angle Math.PI 180) float c (float) Math.cos(angle Math.PI 180) Matrix.setLookAtM(data, 0, 0, 0, 0, c, 0, s, 0, 1, 0) the viewMatrix The draw Method from the SkyBox is called with the data Matrix from the camera (ViewMatrix) and with disabled depthBuffer. Do you have any ideas why the SkyBox is rendered so strange? What is wrong with my code? Only to be sure that all is right with my shaders here is the code from them FragmentShader precision mediump float uniform samplerCube u TextureUnit varying vec3 v Position void main() gl FragColor textureCube(u TextureUnit, v Position) VertexShader uniform mat4 u Matrix attribute vec3 a Position varying vec3 v Position void main() v Position a Position v Position.z v Position.z gl Position u Matrix vec4(a Position, 1.0) gl Position gl Position.xyww


How can I blend up to 3 textures on a polygon without blend maps? For my voxel game I need to blend up to 3 textures in the same polygon. It would be preferable if I could specify a texture id for each vertex, but other solutions are accepted as well. Here's an illustration of what I want. How can I achieve this type of blending? Multi texturing with blend maps is NOT a solution. Also please notice that there will be a lot of different textures.


What is the best way to draw outline of object using OpenGL I want to select the best way to draw outline of 3d human like object and what would be the best way to draw outline for this kind of objects. I found about stencil buffer based methods, geometric shader based methods and toon shader based methods is one if this is good if so which method. or is there any other best way to draw a outline.


Using large textures on limited hardware I've run into a problem where some of the models that I'm loading can have very large textures (2000x2000 for example). While my desktop computer can load them just fine, my laptop gets a segfault at the glTexImage call. I've thought of a couple of things I can do in this situation Before giving the image to OpenGL, I could downscale it so it's below the max texture size, but I'm not sure how to then stretch the image to its original width and height I could also outright refuse to load the texture, and replace it with a generic repeating texture, like Valve's black and purple grid, but this isn't at all reliable or desired Are these two options viable? How is it done with game engines like Unity or Source? Are there any other options that are better than my ideas?


Ray Picking how can I find which copy of model to pick, if they share the same vertices, but each one is translated before being drawn? I have a scene, in which I am drawing few different objects each one has the same vertices and each one is translated to proper place before being drawn. While using libgdx (but I think that this question should be generic enough to work with other libraries), I try to do ray picking, casting ray and trying to find intersections of given ray with triangles, from meshes of each object. My problem is, that because they all share the same set of vertices, how should I find which one exactly was pointed by user? As I have no experience in this, I was thinking about translating the vertices for each object and getting rid of glTranslate(x, y, z) called before each one, but in that situation I won't be able to use one copy of mesh to work with all objects. May I ask for a few hints links to articles how this should be done?


if a desktop machine supports OpenGL 3.0 I can assume that it supports OpenGL ES 2.0 too? This isn't clear for me, if i use the drivers from the GPU manufacturer and they support OpenGL 3.0 and or above, i can always make an OpenGL ES 2.0 application work?


Matrix loading problems with jbullet and lwjgl The following code does not load the matrix correctly from jbullet. box is a RigidBody Transform trans new Transform() trans box.getMotionState().getWorldTransform(trans) float matrix new float 16 trans.getOpenGLMatrix(matrix) pass that matrix to OpenGL and render the cube FloatBuffer buffer ByteBuffer.allocateDirect(4 16).asFloatBuffer().put(matrix) buffer.rewind() glPushMatrix() glMultMatrix(buffer) glBegin(GL POINTS) glVertex3f(0,0,0) glEnd() glPopMatrix() the jbullet is configured as so CollisionConfiguration new DefaultCollisionConfiguration() dispatcher new CollisionDispatcher(collisionConfiguration) Vector3f worldAabbMin new Vector3f( 10000, 10000, 10000) Vector3f worldAabbMax new Vector3f(10000,10000,10000) AxisSweep3 overlappingPairCache new AxisSweep3(worldAabbMin, worldAabbMax) SequentialImpulseConstraintSolver solver new SequentialImpulseConstraintSolver() dynamicWorld new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration) dynamicWorld.setGravity(new Vector3f(0, 10,0)) dynamicWorld.getDispatchInfo().allowedCcdPenetration 0f CollisionShape groundShape new BoxShape(new Vector3f(1000.f, 50.f, 1000.f)) Transform groundTransform new Transform() groundTransform.setIdentity() groundTransform.origin.set(new Vector3f(0.f, 60.f, 0.f)) float mass 0f Vector3f localInertia new Vector3f(0, 0, 0) DefaultMotionState myMotionState new DefaultMotionState(groundTransform) RigidBodyConstructionInfo rbInfo new RigidBodyConstructionInfo(mass, myMotionState, groundShape, localInertia) RigidBody body new RigidBody(rbInfo) dynamicWorld.addRigidBody(body) dynamicWorld.clearForces() Nothing is rendered on the screen. What am I doing wrong?