Deferred rendering and gaussian blur artifacts I compute Gaussian blur in two passes (horizontally and vertically). Shaders look like this Horizontal blur fragment shader version 420 layout (location 0) out vec4 outColor in vec2 texCoord float PixOffset 5 float (0.0,1.0,2.0,3.0,4.0) float Weight 5 float ( 0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162 ) float scale 4.0 uniform sampler2D texture0 uniform vec2 screenSize void main(void) float dx 1.0 screenSize.x vec4 sum texture(texture0, texCoord) Weight 0 for( int i 1 i lt 5 i ) sum texture(texture0, texCoord vec2(PixOffset i , 0.0) scale dx ) Weight i sum texture(texture0, texCoord vec2(PixOffset i , 0.0) scale dx ) Weight i outColor sum I use deferred rendering and the following screens shows a diffuse material texture after blurring. I simplified a render loop for the sake of clarity(only one render target a diffuse material). A render loop first case bind fbo1 gbuffer stage unbind fbo1 bind fbo2 read a diffuse texture, render to a temporary texture (full screen quad) read a temporary texture, horizontal blur, render to a temporary texture (full screen quad) read a temporary texture, vertical blur, render to a temporary texture (full screen quad) unbind fbo2 read a temporary texture, render to the default framebuffer (full screen quad) The final image has artifacts(flickering pixels). Some of them are placed between two triangles which create the full screen quad. A render loop second case bind fbo1 gbuffer stage unbind fbo1 bind fbo2 read a diffuse texture, render to a temporary texture (full screen quad) read a temporary texture, horizontal blur, render to a temporary texture (full screen quad) unbind fbo2 read a temporary texture, vertical blur, render to the default framebuffer (full screen quad) Some artifacts may appear between triangles A render loop third case bind fbo1 gbuffer stage unbind fbo1 bind fbo2 read a diffuse texture, horizontal blur, render to a temporary texture (full screen quad) unbind fbo2 read a temporary texture, vertical blur, render to the default framebuffer (full screen quad) The final image doesn't contain artifacts. How to fix that ? The above code is simplified but normally the first case(render loop order) is most useful, for example I want to blur a glow texture and use it when shading.


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?


LWJGL 3 how to convert screen coordinate to world coordinate? I'm trying to convert screen coordinate to world coordinate on mouse click event. For LWJGL 3 there's not GLU utility class is available whereas LWJGL 2 has. I'm using JOML math classes and wrote following code, but its returning wrong world coordinate, I'm doing something wrong and couldn't figure out. On program init, I get viewProjMatrix and viewport viewProjMatrixUniform glGetUniformLocation(this.program, "viewProjMatrix") IntBuffer viewportBuffer BufferUtils.createIntBuffer(4) int viewport new int 4 glGetIntegerv(GL VIEWPORT, viewportBuffer) viewportBuffer.get(viewport) On render loop, I calculate viewProjMatrix viewProjMatrix .setPerspective((float) Math.toRadians(30), (float) width height, 0.01f, 500.0f) define min and max planes .lookAt(eye x, eye y, eye z, eye x, eye y, 0.0f, 0.0f, 2.0f, 0.0f) glUniformMatrix4fv(viewProjMatrixUniform, false, viewProjMatrix.get(matrixBuffer)) I convert screen coordinate to world coordinate with following code DoubleBuffer mouseXBuffer BufferUtils.createDoubleBuffer(1) DoubleBuffer mouseYBuffer BufferUtils.createDoubleBuffer(1) glfwGetCursorPos(window, mouseXBuffer, mouseYBuffer) double x mouseXBuffer.get(0) double y mouseYBuffer.get(0) System.out.println("clicked at " x " " y) Vector3f v3f new Vector3f() viewProjMatrix.unproject((float)x, (float)y, 0f, viewport, v3f) System.out.println("world coordinate " v3f.x " " v3f.y) Here's the full source code https gist.github.com digz6666 48bb433c83801ea4b82fa194f05b4f02


How to draw 2D pixel data with OpenGL I am fairly new to OpenGL. I have a 2D game in SDL2 that uses currently works by creating a SDL Surface from the pixel data, copying it into a SDL Texture, and rendering it to the screen with SDL Renderer. But rather than using SDL to render the pixels, I'd like to switch to OpenGL. The reason I'd like to switch is because I need to render some lines on top of the pixel data and SDL RenderDrawLine() just doesn't have all the features I need (like line thickness or glScissor). At first, I attempted to switch to OpenGL by using glDrawPixels() and I was happy with the results. However, I found out that glDrawPixels() does not seem to be available in OpenGL ES (mobile devices). I have looked through some tutorials, but they all use shaders and other fancy stuff that I don't think I really need. Is there a simple way (like glDrawPixels()) to just draw pixel data to the screen for a 2D game? The pixel data is in the format GL UNSIGNED BYTE and it contains everything that I want to draw on the screen (except for several 2D line segments that I plan on using GL to render on top).


What makes a game look "good"? I am working on a 3D space game using OpenGL and C and I am planning to focus on giving the game modern, eye catching graphics, but the more I think of it the more I realise I don't really know what makes graphics "good". Sure, I can go and play some well known AAA games and bask in the amazingly put together graphics, but I don't really know how the graphics looks good. (this is why I consider games to be an art!) This is what I can think of now High quality textures High quality models A good lighting model Bumpmapping specularity mapping High quality UI, if applicable A wealth of not overdone posteffects I'm asking here in the hope of an experienced game developer who has produced games and know how they work inside and out can explain some techniques that warrant a game's graphics to look "good", and some not well known quirky tips. That'd be awesome. Thanks!


Is glxinfo saying that the 980 GTX doesn't support a 32 bit depth buffer? I've been using the glxinfo command (glxinfo v) to explore the supported framebuffer configurations. There are two values relating to depth, "depth" and "depthsize." According the source, it appears that the "depth" value relates to the X config and the "depthsize" value relates to the OpenGL config. Assuming that is correct, would the lack of a "depthsize 32" entry suggest that 32 bit depth buffers aren't supported? Or is my understanding of the glxinfo output flawed?


View to normal calculation in GLSL Sorry for the terrible title, but I really cant think of anything better.. Suggestions welcome. I am trying to do something like showcased in this video http www.youtube.com watch?v CaTI2d0tQME So basically smoothly change the opacity when looked face on. This is my vertex shader so far, the fragment shader is simple as it just multiplies the lightColor with the texture version 430 core uniform mat4 MV uniform mat4 MVP layout(location 0) attribute vec3 vertexPosition layout(location 1) attribute vec2 vertexUV layout(location 2) attribute vec3 vertexNormal layout(location 3) attribute mat4 bufferMatrix For per instance translation varying vec2 UV varying vec4 lightColor flat varying int InstanceID void main() vec4 mcPosition MV bufferMatrix vec4(vertexPosition, 1.0) mcPosition mcPosition length(mcPosition) vec3 mcNormal vertexNormal vec3 ecNormal vec3(MV bufferMatrix vec4(mcNormal, 0.0)) ecNormal ecNormal length(ecNormal) float dotProduct dot(vec4(mcNormal, 1.0), mcPosition) lightColor vec4(dotProduct) gl Position MVP bufferMatrix vec4(vertexPosition, 1.0) UV vertexUV InstanceID gl InstanceID The base is copied code from a 'phong' shader that works!.. I have tried everything I could think of, as well as searched google for quite some time. I think I realize what I need to do mathematically, which is getting the dot product of the vertex normal on to the view to vertex vector. That is mathematically speaking, another is to do it in GLSL with matrices etc. I am bad at debugging GLSL code, but right now the lightColor is always 0, no matter where I look at the model from. Quick Bonus Question What is the technique in the video actually called if anything?


How do I draw a portion of a texture onscreen in OpenGL? I have a sprite sheet loaded as an OpenGL texture, and I'd like to draw a portion of that texture sequentially for animation. Is there an actual OpenGL command to draw part of a texture? I can get it done by modifying the U and V components when drawing the texture, but I'm not sure if there's a more elegant correct method of doing this.


OpenGL Transformations I'm not sure if I correctly understand 3D transformations in OpenGL. Let's assume I'm using the typical matrix stack. It seems like you move the world X units over, drop in a bag of verts (a mesh) and move the world back by popping the matrix off the stack, then you repeat the process to place another model? Say I wanted to place a model at (10, 0, 0) and another at (0, 10, 0). I think I would... PUSH move(10,0,0) DRAW model A POP PUSH move(0,10,0) DRAW model B POP Some questions come to mind, like for example what does loading an identity matrix do in the stack? Am I right to assume that these operations in effect move the world around, then you draw the mesh at 0,0,0 in world space when you've moved the world to your liking? Or is it the other way around, does GL "apply" the matrix stack to your mesh as you draw it? Thanks, Cody


What is the recommended way to output values to FBO targets? (OpenGL 3.3 GLSL 330) I'll begin by apologizing for any dumb assumptions you might find in the code below since I'm still pretty much green when it comes to OpenGL programming. I'm currently trying to implement deferred shading by using FBO's and their associated targets (textures in my case). I have a simple (I think P) geometry fragment shader program and I'd like to write its Fragment Shader stage output to three different render targets (previously bound by a call to glDrawBuffers()), like so version 330 in vec3 WorldPos0 in vec2 TexCoord0 in vec3 Normal0 in vec3 Tangent0 layout(location 0) out vec3 WorldPos layout(location 1) out vec3 Diffuse layout(location 2) out vec3 Normal uniform sampler2D gColorMap uniform sampler2D gNormalMap vec3 CalcBumpedNormal() vec3 Normal normalize(Normal0) vec3 Tangent normalize(Tangent0) Tangent normalize(Tangent dot(Tangent, Normal) Normal) vec3 Bitangent cross(Tangent, Normal) vec3 BumpMapNormal texture(gNormalMap, TexCoord0).xyz BumpMapNormal 2 BumpMapNormal vec3(1.0, 1.0, 1.0) vec3 NewNormal mat3 TBN mat3(Tangent, Bitangent, Normal) NewNormal TBN BumpMapNormal NewNormal normalize(NewNormal) return NewNormal void main() WorldPos WorldPos0 Diffuse texture(gColorMap, TexCoord0).xyz Normal CalcBumpedNormal() If my render target textures are configured as RT1 (GL RGB32F, GL RGB, GL FLOAT, GL TEXTURE0, GL COLOR ATTACHMENT0) RT2 (GL RGB32F, GL RGB, GL FLOAT, GL TEXTURE1, GL COLOR ATTACHMENT1) RT3 (GL RGB32F, GL RGB, GL FLOAT, GL TEXTURE2, GL COLOR ATTACHMENT2) And assuming that each texture has an internal format capable of contaning the incoming data, will the fragment shader write the corresponding values to the expected texture targets? On a related note, do the textures need to be bound to the OpenGL context when they are Multiple Render Targets? From some Googling, I think there are two other ways to output to MRTs 1 Output each component to gl FragData n . Some forum posts say this method is deprecated. However, looking at the latest OpenGL 3.3 and 4.0 specifications at opengl.org, the core profiles still mention this approach. 2 Use a typed output array variable for the expected type. In this case, I think it would be something like this out vec3 3 output void main() output 0 WorldPos0 output 1 texture(gColorMap, TexCoord0).xyz output 2 CalcBumpedNormal() So which is then the recommended approach? Is there a recommended approach at all if I plan to code on top of OpenGL 3.3? Thanks for your time and help!


How to fix texture edge artefacts? This issue has been annoying me for a long time now and even after reading a lot of articles about it, I am still unable to fix the issue. First, to my setup. I'm using LWJGL for a 2D project, rendering in immediate mode (yes, I know, FBOs, but I feel like it's too late to change it now). Textures can be scaled, rotated tinted and cropped in any way and are read from packed spritesheets that are multiples of 2 (the one in question is 512x1024 for example). The Problem Because there is no smoothing applied to the textures, scaled and rotated textures look quite ugly, showing jagged lines and black outlines. I tried improving it with using glEnable(GL POLYGON SMOOTH) (even though I know now that this is apparantly a bad practice, but I have no idea how to add multisampling to immediate mode rendering, other sites even state that multisampling is probably overkill for 2D games, which leaves me even more confused). This is what it looks like, with and without POLYGON SMOOTH Quite clearly, there are multiple issues visible With POLYGON SMOOTH disabled, there are horribly jagged lines and dark edges (that aren't there in the texture) With POLYGON SMOOTH enabled, the edges are no longer jagged, but the dark edges are still there and now there are those diagonal lines. After reading up on that a bit, I found out that it has something to do with how graphics cards render quads, which is as two triangles, and when smoothing is applied, this happens. To test that out, instead of drawing a single quad I draw two triangles which indeed moves the diagonal lines around. The dark edges seem to be caused by something like like pre multiplied alpha (according to this), but when I check the raw pixel data, it doesn't look pre multiplied to me. A completely white texture with 0.5f alpha for example is represented as (in ARGB) 0x80FFFFFF. So applying the "fix" (using glBlendFunc(GL ONE, GL ONE MINUS SRC ALPHA) instead of the default glBlendFunc(GL SRC, GL ONE MINUS SRC ALPHA)suggested in the article doesn't really work, because my textures aren't premultiplied alpha, so alpha components don't work anymore (same texture, black background) Texture without alpha I do use custom shaders, so I guess I probably could make alpha work in some way by passing it to the shader and then multiplying the color by it, would that fix the dark edges (which would enable me to use GL ONE, the "better" blend function)? That would still leave me with the issue of the diagonal lines though, which I seem to be able to move around, but not remove.


OpenGL and 3ds model loading Path of least resistance? Hey guys, im working on a final class project for a graphics class, and me and a teammate are making a simple 3d tower defense game. We're currently planning on using 3ds models and drawing them with OpenGL.However, niether of us have a lot of practice experience with loading drawing models. What is the fastest and or easiest (not neccesarily the best or most feature implemented) way to load a 3ds model and draw it with a OpenGL glut setup?


Applying different materials to an object I'm currently implementing an Object Loader for the Wavefront File Format ( .obj). When exporting a model (with associated materials) from blender, a material for a group of faces is specified like this usemtl MyMaterial s off f 2 1 1 4 2 1 3 3 1 f 1 4 1 2 1 1 3 3 1 Since each material consists of (at least) 3 components for each of ambient, diffuse specular color and also shininess (which totals up to 10 floats) I would consider it to be a tremendous waste of memory to store all of these values for each vertex. Does OpenGL provide us with a more elegant viable way to achieve the same result with a more reasonable memory consumption or do I have to swallow the bitter pill?


Multiple buffers and calling glBufferSubData Originally asked this on Computer Graphics, but it might fit in better here. In my project, for convenience I would like to use many buffers. Many buffers in my case means 50 100 terrain patches represented by buffers with vertex coordinates, normals, indices and maybe color. The magnitude of data would be, let's say 10 4 floats per buffer. Some of this data can be shared between each terrain patch, f.ex. xz coordinates and indices. During the rendering loop, some terrain patches will be updated. Which means that for certain buffers I call glBufferSubData() for the whole buffer. My question is are there any pros cons, performance wise between these two methods 1) Controlling my data in many buffers (50 100), thus letting me call glBufferSubData on a complete buffer when needed. 2) Controlling my data in fewer (5 20) buffers, with more data in each. But then having to set up a system where I need to call glBufferSubData on smaller portion of a buffer. (Which leads to a more complex design in my case).


No performance gain from instanced rendering? I recently worked through this tutorial about instanced rendering. At the end it promises to draw a huge amount of instances of one model without performance drops. So I tried some simple instanced rendering to see these effects. So I created a VBO containing four times xyz coordiantes, vertex color and texcoords. float backgroundData new float 1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1f,1f,1f,1f, 1.0f, 1.0f, 0.0f I also created a VAO and EBO containing the glVertexAttribPointers and indices int indices new int 0,1,2,1,2,3 . Now I draw everything with glDrawElementsInstanced(GL TRIANGLES, 6, GL UNSIGNED INT, 0, 10 000). But the Framerate drops as much as if I had the indices 10.000 times in my EBO. Why is the outcome so different? Did I do something wrong?


GLSL Shaders How to manage? As your game get's bigger and bigger, you will use more and more different shader effects. Let's take an easy example I have clouds in my voxel based world, and I want to give it a blue ish tint with a shader. Do I create a new shader, disable the default shader, enable the cloud shader, draw the cloud, disable the cloud shader and enable the default one again? If your game starts to get huge, how on earth can you use 300 shader effects enabled for 1 voxel and disabled for the other? I know the question may sound strange, but it really makes me think. I now have a Vertex and Fragmentshader, for the matrix calculations, and basic lighting. If I want to add a shading effect for for example water blocks, what to do? I hope someone can help me with this mystery.


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


Irradiance Map ( Irradiance environment map)? As irradiance map is generated for every possible normal for all the texels in environment map (as every texel act as a light source) so that we can look up irradiance map, based on normal of fragment to find out its resulting illumination. When Irradiance map is generated, does it get generated for every object in the scene to capture all possible normal and then eventually combined in a single texture? Is there any example code to create irradiance map and use it to light the scene? Any one has an example of CG shader for reading irradiance map? Thanks


Is it appropriate approach to simulate shadowing via occlusion culling of lights? I have own deferred renderer and a scene with both closed and open spaces. I want to prevent light passing though solid objects. For example, there can be a house with a lot of point lights inside. I want to prevent lighting of objects outside the house, but it is not always possible to adjust appropriate falloff distance. And it seems that creating shadows maps for each of them will require a lot of time and memory. So I could try another approach create some set of bounding primitives for each light source and perform occlusion culling with all of them to determine whether some space is affected by the source. Is this method appropriate for the described situation or maybe is there any other methods to simulate shadowing?


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


How do I load textures with SFML for OpenGL? I'm looking at NeHe's texture mapping tutorial. It looks overly complicated for just loading a texture. Is there a way to load a texture in SFML and then use it in Open GL? I use SFML for my windowing.


Is it possible to create a Facebook game that is a Windows executable? I'm thinking of trying to make a game, and I heard Facebook is good place to make it popular, but I don't want to make a sprite based Flash game, I want to use OpenGL for rendering to get nice graphics and good performance with it. I know there is Java which supports OpenGL (I think), but I would like to make my game closed source so that people cannot make their own mods for it like what happened with Minecraft. Another option I thought was to make OpenGL executable and a Flash version, but I think it might be too much work for one guy. Not to mention I have never done anything in Flash. So, is there any way to develop closed source game that can be also played through a browser? By closed source I mean the people have no way of getting the source code by decompiling it in any way.


Can frequent state changes decrease rendering performance? Can frequent texture and shader binding decrease rendering performance? "Frequent" binding example for object for material in object render part of object using that material "Low count" binding example for material for object in material render part of object using that material I'm planning to use an octree later and with this "low count" method of rendering it can drastically increase memory consumption. So is it good idea?


TBN Matrix Eye vs. World Space Conflict I am tired of misleading and insufficient articles making me more confused each time I read, I need a clarification that will solve my TBN matrix problem forever. Each article I read informs me differently about from which space TBN matrix converts to tangent space. One article says that it converts from eye space, other one says that it converts from world space to tangent space. As far as I know, world space is ModelMatrix vertex, eye space is ViewMatrix ModelMatrix vertex. Another article says that transpose of TBN Matrix actually does it. Can you please explain me how to use TBN matrix, does it (or transposed tbn) convert from eye or world to tangent ? Should I convert my lighting vectors from eye space to world and then apply TBN on them ?


What is the difference between Constant Vertex Attributes and Uniforms? According to the OpenGL ES 2.0 Programming Guide A constant vertex attribute is the same for all vertices of a primitive, and therefore only one value needs to be specified for all the vertices of a primitive. For uniforms the book states ...any parameter to a shader that is constant across either all vertices or fragments (but that is not known at compile time) should be passed in as a uniform. I've always used uniforms for data that is constant for a primitive but now it appears that attributes can also be used in the same way. Is there more to constant vertex attribute than simply 'they are the same as uniforms'?


One framebuffer for each light vs unique framebuffer per light Currently I have two ideas how to implement my lighting system 1) Use one framebuffer per light source no need to switch texture attachments of framebuffer may be faster bigger memory usage 2) Use one framebuffer for every light source some time may be wasted on attaching new textures to framebuffer less memory usage So could you please tell me which way is better and why? Or I'm totally wrong on my thoughts and there is no difference at all?


How to achieve rendering at huge distances? These days I was reading some information about the upcoming GTA V technology, in particular, how it is able to truly render all buildings you can see without a draw distance cap or any faking. Since I will soon be prototyping a big city environment, I wanted some advice on this topic. We're talking about a really big city, with simple geometry but fully lit and shadowed. My doubt comes in particular to the projection matrix, which imposes a maximum draw distance (the zFar parameter). Now, at the same time, I read everywhere that zFar should be as small as possible for better rendering results, in particular related to depth buffer issues etc, because of the floating point issues. So, assuming my computer can render this big city in a stable framerate, how should I approach the problem of rendering parts of the city which I can see REALLY far away, fully lit and shadowed? Shadow maps also seem to have problems with low depth buffer precision.. Thanks


Why does glGetString returns a NULL string I am trying my hands at GLFW library. I have written a basic program to get OpenGL renderer and vendor string. Here is the code include lt GL glew.h gt include lt GL glfw.h gt include lt cstdio gt include lt cstdlib gt include lt string gt using namespace std void shutDown(int returnCode) printf("There was an error in running the code with error d n",returnCode) GLenum res glGetError() const GLubyte errString gluErrorString(res) printf("Error is s n", errString) glfwTerminate() exit(returnCode) int main() start GL context and O S window using GLFW helper library if (glfwInit() ! GL TRUE) shutDown(1) if (glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW WINDOW) ! GL TRUE) shutDown(2) start GLEW extension handler glewInit() get version info const GLubyte renderer glGetString (GL RENDERER) get renderer string const GLubyte version glGetString (GL VERSION) version as a string printf("Renderer s n", renderer) printf("OpenGL version supported s n", version) close GL context and any other GLFW resources glfwTerminate() return 0 I googled this error and found out that we have to initialize the OpenGL context before calling glGetString(). Although I have initialized OpenGL context using glfwInit() but still the function returns a NULL string. Any ideas? Edit I have updated the code with error checking mechanisms. This code on running outputs the following There was an error in running the code with error 2 Error is no error


Generate screen space distance field from depth buffer I've been wanting to try out raymarching on real 3D scenes to implement effects like AO, soft shadows and such. I pretty much know how to use signed distance functions (as described by Inigo Quilez) to approximate a model and raymarch it, but I want to have way more precision and have the distance field of my scene. How would you go about generating a (un)signed distance field from the depth buffer in screen space ? Or would the usual depth buffer be usable as a distance field (I don't think so) ? Or there might be better ways that don't use the depth buffer ?


How to properly scale from natural coordinates to screen coordinate system in OpenGL? I am working on a Physics Engine, and I have been using opengl to visualize what it's doing. I think I have a scaling issue when going from natural coordinate system to the opengl screen coordinate system, which is between 1 and 1. I am saying that 1 is 150 meters and 1 is 150 meters. Therefore, to get to scale I should be able to take the natural coordinate system point say lt 0,100 , and scale to screen by doing lt 0,100 150 , which is approximately lt 0,.667 screen coordinates. When I watch a 1 kg ball fall from 100 meters, it seems too be falling to slow, as if it's falling under water (see https www.youtube.com watch?v KiZODHIvJ4A for reference). The physics engine seems to be correct. I think it has something to do with the coordinate system translation (just dividing by 150 scalar right now). Does anyone know if I am doing this correctly?


OpenGL vertex data per index Usually, vertex data is assigned to a particular vertex, like this data vertices 1.31 gt 1, 13, 5 84.3 gt 5, 8, 12 .095 gt 8, 3, 10 Then, you would typically have an array saying which order to draw the vertices in indices 0 2 1 2 Using this, the first vertex would be drawn first, then the third vertex, then the second one, then the third one again. My question is if it is possible to assign vertex data to the index array rather than to the vertex array, like this data indices 1.31 gt 0 84.3 gt 2 .095 gt 1 30.1 gt 2 So that when it draws each vertex from the index array, it uses that particular value. Please note that I am dealing with a lot more vertices than are shown here. (17 3 to be precise) The examples I shown above wouldn't be useful by themselves, but it would make a significant difference in performance in my program if this was possible.


Why is my depth buffer texture so bright? https www.youtube.com watch?v QuvAEqgHrMY amp feature youtu.be https www.youtube.com watch?v 5ob1JsPIGAs amp feature youtu.be gluPerspective(60, (float)CONTEXT WIDTH CONTEXT HEIGHT, 0.1f, 1.f) values used for first video gluPerspective(60, (float)CONTEXT WIDTH CONTEXT HEIGHT, 0.1f, 2000.f) values used for second video, the further z clip value seems to improve the depth rendered, but far from example images below. I set my projection matrix with gluPerspective. This seems to happen when I try gluPerspective when I set my projection matrix to first person. The type of image I would like to get is Is the visual result I am getting correct? Then are the listed examples of depth buffer images are merely a result of refining post rendering process, that are simply added in order for humans to see it better?


why is my OpenGL texture transparent? I have a terrain in OpenGL, and two textures which I am combining using GLSL mix() function. Here are the textures I am using. Now I am able to combine and mix these two textures, but for some reason, when I render the textures on the terrain, the terrain becomes transparent. I render the LHS texture first, and then I render the RHS texture with alpha channel, I don't understand why it is transparent. Here is an interesting fact, in the screenshot, you can see the result of the terrain when rendered on Nvidia GPU, when I render the same thing on interl HD 3k, I get different result. This result is how it is supposed to be, nothing is transparent in this following screenshot. Here is my fragment shader code.. void main() vec4 dryTex texture( u dryTex, vs texCoord 1 ) vec4 grassTex texture( u grassTex, vs texCoord 1 ) vec4 texColor1 mix(dryTex, grassTex , grassTex.a) out fragColor texColor1


Render on other render targets starting from one already rendered on I have to perform a double pass convolution on a texture that is actually the color attachment of another render target, and store it in the color attachment of ANOTHER render target. This must be done multiple time, but using the same texture as starting point What I do now is (a bit abstracted, but what I have abstract is guaranteed to work singularly) renderOnRT(firstTarget) This is working. for each other RT currRT glBindFramebuffer(GL FRAMEBUFFER, currRT.frameBufferID) programX.use() glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, firstTarget.colorAttachmentID) programX.setUniform1i("colourTexture",0) glActiveTexture(GL TEXTURE1) glBindTexture(GL TEXTURE 2D, firstTarget.depthAttachmentID) programX.setUniform1i("depthTexture",1) glBindBuffer(GL ARRAY BUFFER, quadBuffID) quadBuffID is a VBO for a screen aligned quad. It is fine. programX.vertexAttribPointer(POSITION ATTRIBUTE, 3, GL FLOAT, GL FALSE, 0, (void )0) glDrawArrays(GL QUADS,0,4) programY.use() glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, currRT.colorAttachmentID) The second pass is done on the previous pass programY.setUniform1i("colourTexture",0) glActiveTexture(GL TEXTURE1) glBindTexture(GL TEXTURE 2D, currRT.depthAttachmentID) programY.setUniform1i("depthTexture",1) glBindBuffer(GL ARRAY BUFFER, quadBuffID) programY.vertexAttribPointer(POSITION ATTRIBUTE, 3, GL FLOAT, GL FALSE, 0, (void )0) glDrawArrays(GL QUADS, 0, 4) The problem is that I end up with black textures and not the wanted result. The GLSL programs program(X,Y) works fine, already tested on single targets. Is there something stupid I am missing? Even an hint is much appreciated, thanks!


Disadvantages of using multiple versions of OpenGL in LWJGL? So, I'm trying to figure out LWJGL, and my goal is to use OpenGL 3.2 (because pretty shaders are pretty). But in every tutorial I can find for LWJGL, they import a bunch of different OpenGL versions and use them at the same time. For example, this one imports GL11, GL15, GL20, and GL30 and uses functions from all of them. This seems intuitively like it would be messy and generally a bad idea. Besides the normal disadvantages of using deprecated functions, is there any particular reason not to do this? Could it affect performance in any way? Is there a potential for errors and odd behavior to occur? Also, if possible, does anyone have an example of LWJGL written only using GL32? I've found C code samples that do this, but I'm not too familiar with C , so it's difficult for me to translate.


Inter Quake Model IQM render Directx9 I'm trying to render an Inter Quake Model(http lee.fov120.com iqm ) in DirectX9 that I exported from blender. I want to display animations which IQM supports and my model format does not. The model is a cylinder. It loads fine in the iqm sdk opengl viewer but when i try to render it in directx9 using for example(this is just to render the vertices) IDirect3DDevice9 device HRESULT hr S OK for(int i 0 i lt nummeshes i ) iqmmesh amp m meshes 0 hr device gt DrawIndexedPrimitiveUP(D3DPT TRIANGLELIST, 0, 3 m.num triangles, m.num triangles , amp tris m.first triangle ,D3DFMT INDEX32 ,inposition ,sizeof(unsigned int)) It renders like this Incorrect The light grey bit that looks like two triangles in the middle is what is rendered(ignore the other stuff). Whereas it is meant to look like this(using a custom importer which I designed which matches what is displayed in blender) Correct Anyone have any suggestions on what might be going wrong?


Wierd behaviour upon limiting rotation on Y axis Okay, this is the code that works for a FPS camera, except it allows the player to flip it over by going under over 90 rotation on Y axis transformation gt rotateObjectFromRight(glm radians(angleX), glm tvec3 lt GLfloat gt (0.0f, 1.0f, 0.0f)) transformation gt rotateObjectFromLeft(glm radians(angleY), glm tvec3 lt GLfloat gt (1.0f, 0.0f, 0.0f)) transformation object holds the data required to construct the view matrix, among others, a quaternion representing the rotation. The functions called will construct the quaternion with the given data and then multiply it with the rotation quaternion either from the left (relative to global axes) or the right (relative to local axes) side. angleX and angleY are mouse X and Y offsets representing the angles to rotate around. The first line yaws the camera around local Y axis, while the second then pitches it around global X axis, creating the characteristic FPS camera movement. Okay. So far so good. This is the code that should limit the pitch to never exceed the 90 boundaries transformation gt rotateObjectFromRight(glm radians(angleX), glm tvec3 lt GLfloat gt (0.0f, 1.0f, 0.0f)) glm tvec3 lt GLfloat gt forwardVector glm rotate(glm inverse(transformation gt getRotation()), glm tvec3 lt GLfloat gt (0.0f, 0.0f, 1.0f)) GLfloat pitchAngle forwardVector.y 90.0f angleY glm clamp(angleY, (pitchAngle 90.0f), (pitchAngle 90.0f)) transformation gt rotateObjectFromLeft(glm radians(angleY), glm tvec3 lt GLfloat gt (1.0f, 0.0f, 0.0f)) First and the last line are the same. What happens here? First I get the unit vector that lies on the Z axis and rotate it so that it represents the forward vector of the camera. I then take the Y component of that vector (ranging from 1 to 1) and multiply it with 90 to get the degrees. Then I clamp the angleY so that current rotation combined with the new one never exceeds the 90 boundary. If the rotation was about to flip the camera overhead, it would change the new rotation angle so the camera looks straight up. Similar thing for underfoot flipping. However, the camera acts weird. It's fastest at pitch angles close to 0 , but gets progressively slower as the pitch nears 90 . If I move my mouse slower, the camera is faster, if I move it faster, it's slower. It's as though it's discarding the too large small angleY values instead of clamping them to the appropriate values (but it's not, and I can confirm via the debugger all the calculated values look alright and are correct). What could be amiss here to cause such weird movement?


How to mitigate this strange pattern shown in Phong lighting? I am creating an entire lighting scene in OpenGL. The entire scene consist of only one point light. I noticed some strange z fighting like pattern. This flickers when I move the camera. Can anyone tell me what is the potential cause of the problem? How should I mitigate this problem? Thank you. EDIT The problem is solved. It was primarily caused by normal transform computation error and my ill made model might have been aggravated this speckle flickering effect.


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


Stencil buffer mask calculation I dont understand how exactly stencil buffer works in openGL. One aspect that confuses me is why do we use a bit operator there in glStencilFunc. Some text say that is is used to achieve multiple stencil planes but I am not sure how that can be done. Can anybody please explain the whole procedure of stencil buffer calculation during the rendering cycle. Thank you.


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


How can I render a shiny, metallic surface? I am creating a game for which I want to render a kind of shiny black metallic surface with some refection property in it. I know that there would be something related to masks involved with it. But somehow I am not able to get started on it. So could someone give me insight in the matter or give a link to a good tutorial?


OpenGL What's the best way to convert a screen coordinate to a world coordinate? For example, suppose I'm building a first person shooter and the player pulls the trigger. I want to convert the screen coordinate (x, y) into a world coordinate (x, y, z) to know what they've hit. I've seen some people mentioning a lookup using glReadPixels, but I've heard it's slow and those references were years old, so I'm not sure if this is the best way. I'm working with core OpenGL 3.3, not ES. gluUnProject is not part of the API I'm asking about. These types of answers would be most helpful An explanation of how to retrive a pixel's (x, y, z) value using glReadPixels and how to transform that into world coordinates. I know how to multiply by inverse matrices I don't know exactly what steps OpenGL takes to arrive at its depth buffer value. Or, an explantion of how to do something similar, perhaps more efficiently, with a pixel buffer object. Or some method that I don't even know about that's better than either of the above. For some context I have many months' worth of code into a game I'm developing in OpenGL using the core 3.3 profile. I'm using minimal libraries and not the old fixed function GL pipeline, which is why it does not make sense for me to use gluUnProject. I mention this to highlight why this question is not the duplicate of a currently linked older question. Note I previously mentioned a shader idea that did not add much to the question, so I removed it. I also edited the question to clarify the context and the type of answer I am looking for.


Efficient Dynamic Memory Management My world is procedurally generated. As the player moves, chunks behind them are unloaded and chunks in front of them are loaded. Each chunk has a mesh of triangles. At the moment, I create two VBOs for each chunk (vertices and colours), when the chunk is loaded. Once a mesh is created, it is only edited every few seconds. These buffers are deleted when the chunk is no longer visible. Am I leaking memory here by constantly creating and destroying buffers? I've heard somewhere that OpenGL (or WebGL in this case) doesn't do garbage collection until the program quits, due to it being slow. Is this right? Could I improve this system somehow?


What methods exist to implement a 2D looping world? I would like to know what other methods exist to implement a 2D wrapping world. I know the simple modulo solution (ObjectPosition MapSize) but that doesn't really fulfills my requirements. My issue with this easy solution that it only works on points and not on objects. I was trying to clone duplicate my objects and make them visible on both sides of the level that way but it doesn't really works out with box2d physics. So i am thinking if there is any other solution? I would like to make my game world a truly looping cylindrical world, but i don't know what other methods exist to implement such a thing in 2D.


"Normal" Blend Mode with OpenGL Trouble I've been having a lot of trouble trying to get a OpenGL blend function to work as I'd expect it to with like what I'd expect (or from any sensible image editing program). As an example, I'll use these two images to blend (bit difficult to see on white backgrounds so the colors are labeled) Images to be blended This is what I expect to happen (and what happens in paint.net) Expected Result Obviously opengl's default blend function makes it look like this (very wrong) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) After a ton of testing, this is the closest I could get to creating a "good" blend function glBlendFuncSeparate(GL SRC ALPHA, GL ONE MINUS SRC ALPHA, GL ONE, GL ONE MINUS SRC ALPHA) Looking back at the original expected result though, you'll notice that some of the colors are a bit dimmer than they should be (the middle left part). Specifically, they are premultiplied to half their color value (because of the .5 alpha), and I can't seem to make a function that does not do this (without causing odd blending issues with the barely visible red transparent part). Does anyone know a solution to this issue? One that I had was to use premultiplied alpha in the sources (while I dont want to do this because it requires extra work to convert every color I use in my game to premultiplied or just write some stuff in each shader) and do it like that glBlendFuncSeparate(GL ONE, GL ONE MINUS SRC ALPHA, GL ONE, GL ONE MINUS SRC ALPHA) (No premultiplication) Obviously thats wrong too, but this is actually the only correct result I've gotten so far glBlendFuncSeparate(GL ONE, GL ONE MINUS SRC ALPHA, GL ONE, GL ONE MINUS SRC ALPHA) (Premultiplied inputs) Only problem is, how would I get rid of the premultiplication to display it on the screen? It would probably require an additional render cycle for each thing I blend and that seems way too complex for this issue, so I'm still looking for an answer (its interesting that I cant find anything on this, because OpenGL is so widely used that I'd image someone else ran into this problem). Sources Online blend function testing http www.andersriggelsen.dk glblendfunc.php Bottom Layer Image http i.stack.imgur.com XjLNW.png Top Layer Image http i.stack.imgur.com 9CN6w.png


Problems with texture orientation in space I am currently drawing texture in 3D space and have some problems with it's orientation. I'd like me textures always to be oriented with front face to user. My desirable result looks like Note, that text size stay without changes when we rotating world and stay oriented with front face to user. Now I can draw text in 3D space, but it is not oriented with front but rotating with world. Such results I got with following shaders Vertex Shader uniform vec3 Position void main() gl Position vec4(Position, 1.0) Geometry Shader layout(points) in layout(triangle strip, max vertices 4) out out vec2 fsTextureCoordinates uniform mat4 projectionMatrix uniform mat4 modelViewMatrix uniform sampler2D og texture0 uniform float og highResolutionSnapScale uniform vec2 u originScale void main() vec2 halfSize vec2(textureSize(og texture0, 0)) 0.5 og highResolutionSnapScale vec4 center gl in 0 .gl Position center.xy (u originScale halfSize) vec4 v0 vec4(center.xy halfSize, center.z, 1.0) vec4 v1 vec4(center.xy vec2(halfSize.x, halfSize.y), center.z, 1.0) vec4 v2 vec4(center.xy vec2( halfSize.x, halfSize.y), center.z, 1.0) vec4 v3 vec4(center.xy halfSize, center.z, 1.0) gl Position projectionMatrix modelViewMatrix v0 fsTextureCoordinates vec2(0.0, 0.0) EmitVertex() gl Position projectionMatrix modelViewMatrix v1 fsTextureCoordinates vec2(1.0, 0.0) EmitVertex() gl Position projectionMatrix modelViewMatrix v2 fsTextureCoordinates vec2(0.0, 1.0) EmitVertex() gl Position projectionMatrix modelViewMatrix v3 fsTextureCoordinates vec2(1.0, 1.0) EmitVertex() Fragment Shader in vec2 fsTextureCoordinates out vec4 fragmentColor uniform sampler2D og texture0 uniform vec3 u color void main() vec4 color texture(og texture0, fsTextureCoordinates) if (color.a 0.0) discard fragmentColor vec4(color.rgb u color.rgb, color.a) Any ideas how to get my desirable result? EDIT 1 I make edit in my geometry shader and got part of lable drawn on screen at corner. But it is not rotating. .......... vec4 centerProjected projectionMatrix modelViewMatrix center centerProjected centerProjected.w vec4 v0 vec4(centerProjected.xy halfSize, 0.0, 1.0) vec4 v1 vec4(centerProjected.xy vec2(halfSize.x, halfSize.y), 0.0, 1.0) vec4 v2 vec4(centerProjected.xy vec2( halfSize.x, halfSize.y), 0.0, 1.0) vec4 v3 vec4(centerProjected.xy halfSize, 0.0, 1.0) gl Position og viewportOrthographicMatrix v0 ..........


How to position transform vertices for 2D UI in shaders? I am building a 3D engine and have a rendering abstraction that focuses on writing shaders. Most my 3D shaders have gl Position output like gl Position projection view model vec4(position, 1) I would like to draw some 2D UI on top of all the 3D draw calls. I am having a hard time understanding how to do this. Let's say I wanted to draw a HUD player life bar that is fixed to the bottom left corner of the screen. I can imagine drawing a quad. and maybe applying a texture to it. I would have 4 vertices for the quad to feed to the shader. How would I change the gl Position calculation to handle drawing only to 2D screen space? Would I update the transformation to only apply the projection matrix? gl Position projection vec4(position, 0, 1) How to determine the local coordinates of the quad verts? When the screen scales or resolution varies, How to ensure the quad stays positioned to the lower bottom screen? How to ensure the quad dimensions stay the same ratio?


Does gluLookAt add or set the view matrix variables? I'm trying to rotate the camera view in PyOpenGL, but it's not working well. The weirdest behavior I've noticed is that putting gluLookAt in a loop seems to change the camera view, even when I'm not changing the inputs as the loop continues. So while I'd expect something like gluLookAt(0,0,0, 0,0, 5, 0,0,1) to keep the camera constantly pointing downwards, it seems to rotate the view in some strange way, with the objects being rendered leaving the maximum clipping radius after a while. My question is, does gluLookAt take into account the previous camera settings, or do I need to look for something else wrong in my code?


Model gets distorted when rotating the camera I'm currently developing my own 3d graphics engine and I'm having a hard time figuring out why my 3D models gets distorted when rotating the camera around. This is my projection matrix. I'm following the OpenGL's Model. def get projection mat(aspect ratio, camera) fov camera.fov z near camera.z near z far camera.z far top math.tan(fov 0.5) z near bottom top right top aspect ratio left right projection mat np.identity(4, dtype float) projection mat 0, 0 2 z near (right left) projection mat 0, 2 (right left) (right left) projection mat 1, 1 2 z near (top bottom) projection mat 1, 2 (top bottom) (top bottom) projection mat 2, 2 (z far z near) (z far z near) projection mat 2, 3 2 z far z near (z far z near) projection mat 3, 2 1 projection mat 3, 3 0 return projection mat This is my view matrix def camera matrix(self) camera matrix np.identity(4, dtype float) camera matrix 3, 0 self.left camera matrix 3, 1 self.up camera matrix 3, 2 self.forward camera matrix 3, 3 self.pos return camera matrix This is how I get the ViewProjection matrix projection mat get projection mat(self.aspect ratio, self.camera) view mat self.camera.camera matrix() view mat np.linalg.inv(view mat) self.view projection mat np.dot(projection mat, view mat) And, finally, this is the ViewProjectionModel matrix view projection model mat np.dot(model.transform mat.T, self.view projection mat) This is the method that I use to rotate the camera def rotate(self, yaw, pitch, degress True) rotation mat y helper.rotate matrix y(yaw, degrees) rotation mat x helper.rotate matrix x(pitch, degrees) rotation mat np.dot(rotation mat y, rotation mat x) self.forward np.dot(np.insert(self.forward, 3, 1), rotation mat) self.forward helper.normalized((self.forward self.forward 3 ) 3 ) self.up np.dot(np.insert(self.up, 3, 1), rotation mat) self.up helper.normalized((self.up self.up 3 ) 3 ) self.left np.dot(np.insert(self.left, 3, 1), rotation mat) self.left helper.normalized((self.left self.left 3 ) 3 ) A video demo, showing the problem To summarize, the order of multiplication is ProjectionMat X ViewMat x ModelMat x ModelFaces. If it isn't clear by now, I'm using Python for this project. Any help would be greatly appreciated. With best regards, Jo o Pedro EDIT Like this? directions, r np.linalg.qr(np.array( self.forward, self.up, self.left )) self.forward directions 0 self.up directions 1 self.left directions 2


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


How does GL INT 2 10 10 10 REV work for color data? Can anybody tell me how exactly to use GL INT 2 10 10 10 REV as type parameter in glVertexAttribPointer()? I am trying to pass color values using this type. What is the significance of "REV" suffix in this type? Does it require any special treatment in the shaders?


How scanline rendering finds an intersection with an object I'm a newbie with graphics and after I read many articles on the web I still don't understand how in rasterizing from a pixel coordinate like (0 0) on the screen the intersection with an object (let's say a sphere) is found before determining its color and how the Z buffer comes into play. I know something about ray tracing.. is a ray shot from the 0 0 pixel and the intersection point thus determined by the equality between the ray equation with the sphere equation? If it works that way I don't see what the Z buffer is useful to. I don't know if I explained myself correctly, if not please let me know and I'll try to be as clear as I can on my doubt.


Camera rotation around point, but without centering Let's say i have the following Point somewhere in space Camera with position and orientation (up, right, forward) I want to rotate camera around the point, but also keep this point in same place on screen. So, if point was on (32, 32) on window, after rotation i want it to still be on (32, 32). I've seen How can I orbit a camera about it 39 s target point? , and it was somewhat helpful. I needed code to rotate point around arbitrary axis (camera's up and right), so i used this resource. Problem is, i got something like numerical errors and my camera started to wander weirdly when rotating around camera's both up and right (it seems fine when i rotate only around one of them). I tested my implementation with code Matrix m1 MatrixRotate(Vector( 1, 1, 1), 33) Matrix m2 MatrixRotate(Vector( 1, 1, 1), 33) Vector a Vector( 1, 1, 1) Vector c a c m1 c c m2 c printf(" f f f f n", c.x, c.y, c.z, c.w) And got 1.028036 0.960396 1.124331 0.000000 It worked fine when rotation axis was something 'normal' like (1, 0, 0) or (0, 0, 1). So, how else can i rotate camera around point, while keeping said point in same point on screen?


How can I add a parallax effect into my side scrolling game? How can I add a parallax effect into my side scrolling game? I read a lot about parallax scrolling so I know what the logic is and what parallax is but I can't create a dynamic parallax effect. I have draw and update functions like this void UpdateBackground(Background amp back) back.x back.velX back.dirX if(back.x back.width lt 0) back.x 0 void DrawBackground(Background amp back) draw bitmap(back.image, back.x, back.y, 0) if(back.x back.width lt WIDTH) draw bitmap(back.image, back.x back.width, back.y, 0) So this draws a parallax effect with two background objects but it draws it statically. I'm creating a 2D side scrolling game and I'm translating my character and my camera position along x axis. So I have to translate my parallax effect with my camera but when I add to background position.x it doesn't work. How can I solve this?


Render in a imGui Window How do i render my game scene into an imgui window? I want to get from this to this


Are there still advantages to using gl quads? OK, I understand that gl quads are deprecated, and thus we're not 'supposed' to use them anymore. I also understand that a modern PC when running a game using gl quads is actually drawing two triangles. Now, I've heard because of that a game should be written using triangles instead. But I'm wondering if, due to the specifics of how OpenGL makes that quad into two triangles, it is ever advantageous to use quads still? Specifically, I'm currently rendering many unconnected quads from rather large buffer objects. One of the areas I have to be careful is how large the vector of floats I'm using to make update these buffer objects get (I have quite a few extra float values per vertex, and a lot of vertices in a buffer the largest buffers are about 500KB). So it strikes me that if I change my buffer objects to draw triangles this vertex data is going to be 50 larger (six vertices to draw a square rather than 4), and take 50 longer for the CPU to generate. If gl quads still work, am I getting a benefit here, or is the 50 extra memory and CPU time still being used on OpenGL's automatic conversion to two triangles?


Pre or post multiplication for rotation between coordinate frames I have three 3D coordinate frames O, A and B, as shown below. I want to know the rotation matrix RAB between A and B, that is the rotation that is required, with respect to the frame A, to move from A to B. Let us imagine that all I know, is the rotation matrix RAO between A and O, and the rotation matrix ROB between O and B. So, what is the correct way to determine RAB? There are two suggestions that come to mind (1) RAB RAO ROB (2) RAB ROB RAO Now, my intuition is that (1) is correct, i.e. post multiplication. This is because I am multiplying everything with respect to the local coordinate frame (as discussed in http web.cse.ohio state.edu whmin courses cse5542 2013 spring 6 Transformation II.pdf). However, when I compute this, I get a different answer to that which I get by inspection of the diagram. The correct answer, I have noticed, is equal to the pre multiplication solution of (2). Please can somebody explain to me why (2) seems to be correct, rather than (1)? I was under the impression that if all your transformations are with respect to the current local frame, then post multiplication should be done, i.e. multiply the matrices from left to right as you move between each frame. However, when doing the maths, pre multiplication gives the expected answer.


glTextImage2D with GL UNSIGNED BYTE giving weird results while with GL FLOAT just works, driver bug? Update OK, not being able to see the textures loaded by FreeImage was just one of the common mistakes when using modern OpenGL. My texture loading code did not set GL TEXTURE WRAP S T and GL TEXTURE MIN MAG FILTER, and didn't have any mipmaps either Textures quot don 39 t work quot when I don 39 t specify any texture parameters. Is this a driver bug or intended behavior? May then the random colors I'm getting with the testing code be caused by the texture being too small? Maybe If I hardcode a 64x64 red square I will get same results in both cases. It is still weird that with float it works at 2x2 size. I hit a wall trying to rewrite old sprite rendering code based on SDL to use modern OpenGL directly. I'm loading images using FreeImage library and I already confirmed that the pixel data in memory is as expected. But at rendering I was getting no textures. So I harcoded a 2x2 image as a single dimensional array to pass to glTexImage2D and found something weird. When using float, result is as expected but when using char or uint8 t I get random colors. Test code with floats float pixels 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f glGenTextures(1, amp mRedSquareTex) glBindTexture(GL TEXTURE 2D, mRedSquareTex) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, 2, 2, 0, GL RGB, GL FLOAT, pixels) Test code with uint8 t uint8 t pixels 255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0 glGenTextures(1, amp mRedSquareTex) glBindTexture(GL TEXTURE 2D, mRedSquareTex) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, 2, 2, 0, GL RGB, GL UNSIGNED BYTE, pixels) I think that if I walk pixel by pixel the data I'm loading using FreeImage and write them to a float array, I can finally see the textures loaded from disk. But It would be nice to just be able to use them as they are. As I'm not sure about the channels ordering of images loaded with FreeImage I'm avoiding the alpha channel for now, until I confirm the channels order, but in theory, as long as I avoid the alpha channel, I must be able to see the texture drawn, maybe with the wrong colors. Shaders don't do anything special yet. The Vertex Shader just pass the textures coordinates as they are and the Fragment Shader just call texture(). I'm testing this in a machine with a NVidia GT 640, driver version 340.93, Ubuntu 14.04 64 bits.


Hardware Fragment Sorting? I'm writing a rendering engine in OpenGL. I Want to do order independent transparency. I had heard somewhere that some GPUs have support for actually sorting the fragments of all the objects in the scene based on depth and then drawing them. I then realized that this feature is likely very important to many people. Does OpenGL have a built in fragment sorting algorithm, or access to this hardware?


Aiming with a crosshair with a lot of polygons triangles I'm working on a 3d kindof game where I'll eventually be able to modify the shapes present in the environment by pulling their faces with a crosshair. The thing is that I don't know how to achieve ray quads or ray triangle collision. I did it once with a teacher at school, but he didn't have much time and it was not well constructed ( I lost this code). I was also wondering how I could check for theses collisions with thousands of shapes? Because I know this is quite resource demanding and doing this for 1000 spheres cube freeform shapes is not easy. If anyone could help me push my knowledge a bit further, it'd be very much appreciated! I also work in Java using LWJGL, so OpenGl.


Help understanding gluLookAt() I am fairly new to openGL( 3 months ) and am asking for assistance in understanding the fundamentals behind gluLookAt(). Currently I have spent most of my time with openGL modeling scenes with fixed views, and I wanted to begin using gluLookAt combined with keyboard and mouse callbacks to "explore" my scenes. I created a simple program to play around with the functionality of gluLookAt when I first realized I may not understand fully what is happening. My program creates a world using glOrtho( 4,4, 4,4, 4,4) confining my area somewhat around the origin (0,0,0) upon which I place the standard glutSolidTeapot(0.5). Then in an attempt to create a "camera" revolve around the teapot, in an idle callback function I write this glMatrixMode(GL MODELVIEW) glLoadIdentity() gluLookAt( cos(business), 0, sin(business), 0.0,0.0,0.0, 0.0,1.0,0.0 up vector ) glutPostRedisplay() Turns out, this worked. The view shows a revolving teapot. So I take another step and attempt to create an elliptical path around the teapot, multiplying either cos() or sin() (not both) by 2. This works as well but does not have the same effect I was expecting. The view rotates around the teapot, but I imagined along the path the teapot would "appear" to be closer at points, a zooming in effect of sorts. This leads to my question. What exactly do I not understand about this? or.. Why is this not doing what I am expecting?


Why does my simple OpenGL shadow map fail? I want to render a simple shadow map for grass, where closer looks brighter and further looks darker, from the view of the light point. I can't get it to work. Here is the relevant code setting up buffers gl.glGenFramebuffers(1, framebuff) gl.glBindFramebuffer(GL4.GL FRAMEBUFFER, framebuff.get(0)) gl.glGenTextures(2, textureBuff) gl.glBindTexture(GL4.GL TEXTURE 2D, textureBuff.get(0)) gl.glTexStorage2D(GL4.GL TEXTURE 2D, 1, GL4.GL R32F, displayWidth, displayHeight) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE MAG FILTER, GL4.GL LINEAR) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE MIN FILTER, GL4.GL LINEAR MIPMAP LINEAR) gl.glFramebufferTexture(GL4.GL FRAMEBUFFER, GL4.GL COLOR ATTACHMENT0, textureBuff.get(0), 0) gl.glBindTexture(GL4.GL TEXTURE 2D, textureBuff.get(1)) gl.glTexStorage2D(GL4.GL TEXTURE 2D, 1, GL4.GL DEPTH COMPONENT32F, displayWidth, displayHeight) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE MAG FILTER, GL4.GL LINEAR) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE MIN FILTER, GL4.GL LINEAR MIPMAP LINEAR) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE COMPARE MODE, GL4.GL COMPARE REF TO TEXTURE) gl.glTexParameteri(GL4.GL TEXTURE 2D, GL4.GL TEXTURE COMPARE FUNC, GL4.GL LEQUAL) gl.glFramebufferTexture(GL4.GL FRAMEBUFFER, GL4.GL DEPTH ATTACHMENT, textureBuff.get(1), 0) gl.glDrawBuffer(GL4.GL NONE) if(gl.glCheckFramebufferStatus(GL4.GL FRAMEBUFFER) ! GL4.GL FRAMEBUFFER COMPLETE) System.out.println(gl.glCheckFramebufferStatus(GL4.GL FRAMEBUFFER)) Drawing command (unsure if it's correct) gl.glBindFramebuffer(GL4.GL FRAMEBUFFER, framebuff.get(0)) gl.glViewport(0, 0, displayWidth, displayWidth) gl.glEnable(GL4.GL POLYGON OFFSET FILL) gl.glPolygonOffset(2.0f, 4.0f) gl.glClearBufferfv(GL4.GL COLOR, 0, new float 0, 0, 0 , 0) gl.glClearDepth(1.0f) gl.glClear(GL4.GL DEPTH BUFFER BIT) setupMVPMatrix() gl.glBindVertexArray(vaoBuff.get(0)) gl.glUseProgram(shaderProgram) gl.glDrawArraysInstanced(GL4.GL TRIANGLE STRIP, 0, 5, 512 512) gl.glDisable(GL4.GL POLYGON OFFSET FILL) gl.glBindFramebuffer(GL4.GL FRAMEBUFFER, 0) When I comment the glBindFramebuffer(), the grass appears correctly with the white color (from the light point of view, which shows the matrix should be correct) But if I call glBindFramebuffer() with the depth test enabled, everything just disappears. I have also checked the framebuffer status, yet it seems there is no error. What might cause this?


Can I make color data not render as gradient? I would like for the color between my vertices to not be rendered as a gradient, but as a hard break. Is there any way to accomplish this in OpenGL GLSL?


OpenGL slower than Canvas Up to 3 days ago I used a Canvas in a SurfaceView to do all the graphics operations but now I switched to OpenGL because my game went from 60FPS to 30 45 with the increase of the sprites in some levels. However, I find myself disappointed because OpenGL now reaches around 40 50 FPS at all levels. Surely (I hope) I'm doing something wrong. How can I increase the performance at stable 60FPS? My game is pretty simple and I can not believe that it is impossible to reach them. I use 2D sprite texture applied to a square for all the objects. I use a transparent GLSurfaceView, the real background is applied in a ImageView behind the GLSurfaceView. Some code public MyGLSurfaceView(Context context, AttributeSet attrs) super(context) setZOrderOnTop(true) setEGLConfigChooser(8, 8, 8, 8, 0, 0) getHolder().setFormat(PixelFormat.RGBA 8888) mRenderer new ClearRenderer(getContext()) setRenderer(mRenderer) setLongClickable(true) setFocusable(true) public void onSurfaceCreated(final GL10 gl, EGLConfig config) gl.glEnable(GL10.GL TEXTURE 2D) gl.glShadeModel(GL10.GL SMOOTH) gl.glDisable(GL10.GL DEPTH TEST) gl.glDepthMask(false) gl.glEnable(GL10.GL ALPHA TEST) gl.glAlphaFunc(GL10.GL GREATER, 0) gl.glEnable(GL10.GL BLEND) gl.glBlendFunc(GL10.GL ONE, GL10.GL ONE MINUS SRC ALPHA) gl.glHint(GL10.GL PERSPECTIVE CORRECTION HINT, GL10.GL NICEST) public void onSurfaceChanged(GL10 gl, int width, int height) gl.glViewport(0, 0, width, height) gl.glMatrixMode(GL10.GL PROJECTION) gl.glLoadIdentity() gl.glOrthof(0, width, height, 0, 1f, 1f) gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() public void onDrawFrame(GL10 gl) gl.glClear(GL10.GL COLOR BUFFER BIT) gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() gl.glEnableClientState(GL10.GL VERTEX ARRAY) gl.glEnableClientState(GL10.GL TEXTURE COORD ARRAY) Draw all the graphic object. for (byte i 0 i lt mGame.numberOfObjects() i ) mGame.getObject(i).draw(gl) Disable the client state before leaving gl.glDisableClientState(GL10.GL VERTEX ARRAY) gl.glDisableClientState(GL10.GL TEXTURE COORD ARRAY) mGame.getObject(i).draw(gl) is for all the objects like this HERE there is always a translatef and scalef transformation and sometimes rotatef gl.glBindTexture(GL10.GL TEXTURE 2D, mTexPointer 0 ) Point to our vertex buffer gl.glVertexPointer(3, GL10.GL FLOAT, 0, mVertexBuffer) gl.glTexCoordPointer(2, GL10.GL FLOAT, 0, mTextureBuffer) Draw the vertices as triangle strip gl.glDrawArrays(GL10.GL TRIANGLE STRIP, 0, mVertices.length 3) EDIT After some test it seems to be due to the transparent GLSurfaceView. If I delete this line of code setEGLConfigChooser(8, 8, 8, 8, 0, 0) the background becomes all black but I reach 60 fps. What can I do?


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?


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


Can instantiated objects have different material texture? While I have some experience with simple 2D games, I am new to more process demanding 3D games. One basic question that has been concerning me recently and for which I am having difficulties to find a proper detailed answer, is the following. I understand that when we instantiate an object, we are saving memory because the instantiated copy does not have to save mesh memory (like vertices' position, UV cood and normals). So, the instantiated copy only needs to save a transformation matrix in order to properly position, scale and rotate the mesh structure they share with the original mesh. But can the instantiated copies have different texture or material from the original mesh from which they were instantiated? If so, then it means the instantiated objects actually save with themselves more than transformation matrices. I would love to read more on that, so suggestions are welcome.


Practice openGL or learn a specific engine? Possible Duplicate Should I use Game Engines to learn to make 3D games? I am a university student. I want to work in the game industry. Now I am thinking about either practicing my openGL skills or learn a complete new game engine during my time in school. I will do this by developing a smartphone game. I am debating over using just openGL or using a game engine. If I learn a game engine, then if the company I want to work for does not use that game engine, then wouldn't it be a waste of time to learn that game engine now instead of solidifying my openGL skills? So, openGL or game engine? Thanks.


How can I render a single object that uses multiple textures? I'm looking for a technique to render an object with multiple texture sources. One texture is static, the other is generated dynamically (it's a render target). For example, say I was rendering a TV. The frame of the TV is a static texture and the image comes from a render to texture pass. It doesn't sound difficult but I've been unable to find a decent approach. Some of my ideas are Instead of rendering to a unique texture I render to a part of the other texture (so the part with the TV screen is overwritten, the frame remains). This doesn't work if I want to combine multiple textures (two TVs with different frames, same show playing) Create a two part object render the TV frame as one object then render the image as another. This would require leaving a hole in the one model, or putting the other model slightly on top. Is there a drawback to this approach? Is there another approach that works well?


Getting crash on glDrawElements Here is the code where I initialize the VAO, vertex attributes(also the main VBO) and EBO(im using my own wrapper class for these "databuffers" to hide some of the API features and make life easier so i dont think the problem will be in the generic class as it was working without problems) void initVAOManager(const bool amp ebo) if ( vaoID 0) glGenVertexArrays(1, amp vaoID) glBindVertexArray( vaoID) Here is the main data buffer (positions,colors,UVs) If it doesn t exist a new one is created if (! mainBuffer) mainBuffer new DataBuffer lt T gt (GL ARRAY BUFFER) mainBuffer gt bindBuffer() if (! eboBuffer amp amp ebo) eboBuffer new DataBuffer lt eboData gt (GL ELEMENT ARRAY BUFFER) eboBuffer gt bindBuffer() This is the position glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, sizeof(Vertex), (void )offsetof(Vertex, position)) Color attrib pointer glEnableVertexAttribArray(1) glVertexAttribPointer(1, 4, GL UNSIGNED BYTE, GL TRUE, sizeof(Vertex), (void )offsetof(Vertex, color)) UV glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL FLOAT, GL TRUE, sizeof(Vertex), (void )offsetof(Vertex, uv)) mainBuffer gt unbindBuffer() if (ebo) eboBuffer gt unbindBuffer() glBindVertexArray(0) Then the render function (dont mind the for loop, as i want to render multiple objects from the batch in one function) void renderBatchNormal() uploadData() glBindVertexArray( VAOManager gt getVAO()) std vector lt eboData gt for (std size t i 0 i lt DATA.size() i ) glDrawElements(GL TRIANGLES, 6, GL UNSIGNED INT, 0) glBindVertexArray(0) clearData() The upload data function send a data from the vectors to their buffers, I can send it too but as Im using my generic wrapper and it worked before with normal drawings I assume there is no problem. And finally a class eboData(if anyone wondered) (basically just a blank class with an array of 6 indices) class eboData public GLuint indices 6 However, this is causing crashes on the line where I try to execute the glDrawElements command, I read that it can be caused with no binded VAO while binding the ELEMENT BUFFER but as you can see from the code I m doing it right(at least I think that). However, if I change the following line with std vector lt eboData gt eboVector glDrawElements(GL TRIANGLES, 6, GL UNSIGNED INT, eboVector.data()) The code is working (problem is also that I don t know how to render second item in the buffer as it is showing only the first one). Do you have any ideas what can cause this crash? PS glGetError() returns 0.


GLSL to Cg fragment shader I have found very useful resource on the Swiftless website on OpenGL. Unfortunately, I cannot manage to adapt a GLSL fragment shader to my project, which uses Cg. Here it is uniform sampler2D color texture uniform sampler2D normal texture void main() Extract the normal from the normal map vec3 normal normalize(texture2D(normal texture, gl TexCoord 0 .st).rgb 2.0 1.0) Determine where the light is positioned (this can be set however you like) vec3 light pos normalize(vec3(1.0, 1.0, 1.5)) Calculate the lighting diffuse value float diffuse max(dot(normal, light pos), 0.0) vec3 color diffuse texture2D(color texture, gl TexCoord 0 .st).rgb Set the output color of our current pixel gl FragColor vec4(color, 1.0) I have tried something struct fsOutput vec4 color COLOR uniform sampler2D detailTexture TEXUNIT0 uniform sampler2D bumpTexture TEXUNIT1 fsOutput FS Main(float2 detailCoords TEXCOORD0, float2 bumpCoords TEXCOORD1) fsOutput fragm float4 anorm tex2D(bumpTexture, bumpCoords) vec3 normal normalize(anorm.rgb 2.0f 1.0f) vec3 light pos normalize(vec3(1.0f, 1.0f, 1.5f)) float diffuse max(dot(normal, light pos), 0.0) vec3 color diffuse texture2D(detailTexture, detailCoords).rgb fragm.color vec4(color, 1.0f) return fragm But it doesn't work. To debug, I have a function that catches Cg errors, and my program breaks at this point. I have identified the two texture IDs in the main program. Can you suggest any improvement for this Cg shader?


A few questions about Order Independent Transparency I've been looking through several different Order Independent Transparency algorithms. But very few of them seem to answer a few things. I understand that the idea of OIT is to not worry so much about ordering. But does it still matter in some cases? And is there a way to preserve it if a certain ordering is desired? For starters, does presorting impact OIT in any way? Such as speeding it up, or producing different visual results? And is lighting still handled per pixel as normal when you submit your geometry to be rendered. Or does it happen defacto? A few algorithms I have been looking at. Intel's OIT solution. This also seems to be fairly popular with AMD as well. AMD's Powerpoint Depth Peeling. Can't find a good link. And then Depth Weighted blending. Which seems to produce muddy results with layers. Linky I guess I should also ask how necessary, and how fast is this. My main issue isn't layer's of transparent objects with overlaps. Things like holograms and layers upon layers of glass are likely to be rare. But mostly with particles and their drawing order from different particle systems, and them interacting with other transparent objects correctly. Currently... the engine treats a particle engine like one complete object, and renders them directly to the backbuffer on the transparency pass. Though because the particles are volumes... it causes some graphical errors. For example if there was a huge explosion that covers a massive chunk of land... there will be a random stack of smoke that renders on top of it. And I don't want to break up all the particle instancing to batch them with the rest of the geometry... as it would likely massively raise the draw calls for every break. I currently can't provide any pictures right now. The engine is undergoing a serious rewrite to get it more usable. So a good portion of the code is slashed out. I'm just trying to solve problems I have noticed in my first right up.


Nvidia High Performance Processor Setting leads to graphical bug (Seizure Warning) with current lighting system, drawing completely in the shader code I followed the Lighting tutorial on learnopenGL, modifying some of the code to work in a 2D game engine. Everything was looking great and my team got our game done and the lights were quite simple for our designers to use. However we ran into a rare bug. as shown here https www.youtube.com watch?v to0mMP5I0cs one team member was able to recreate the bug by switching his Nvidia settings to use the "High Performance Processor" as opposed to "Integrated Graphics". Otherwise everything renders properly. The bug doesn't appear when there are no lights and everything is rendered in its full color. We have gone through alot of Ideas already but they haven't worked and now I am at a loss. Does anyone have any ideas about what is going on?


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


openGL Vertex Projection does not work as expected I try to render a simple grid using glBegin(GL LINES). I have a class Camera, which provides values like this float farPlane 100.0f float nearPlane 0.1f float screenRatio 1,42857 width height 1000 700 float frustum 70.0f glm vec3 position glm vec3(3.0f, 3.0f, 3.0f) glm vec3 UP glm vec3(0.0f, 1.0f, 0.0f) glm mat4 view glm lookAt(position, position glm normalize(position), UP) makes the lookAt vector always point towards (0, 0, 0) glm mat4 projection glm perspective(frustum, screenRatio, nearPlane, farPlane) using the view and projection matrices, i transform every vertex from my Grid model and render it. glm mat4 viewProjectionMatrix Graphic camera gt getViewProjectionMatrix() returns Camera projection Camera view glBegin(GL LINES) for (unsigned int i 0 i lt vertexNum i) glColor3f(vertexArray i .normal.x, vertexArray i .normal.y, vertexArray i .normal.z) normal vector is used for color in this case glm vec4 translatedPosition(viewProjectionMatrix gridTransformationMatrix (glm vec4(vertexArray i .position, 1.0f))) glVertex3f(translatedPosition.x, translatedPosition.y, translatedPosition.z) glEnd() but this is what i see when i move the camera along the line (0,0,0) u (1,1,1) http i.imgur.com PrcDcLs.gifv (you can see the camera cooridnates in the console)


interpolating frames in a vertex shader My models are stored as a set of meshes, each with a vertex list and normal list per key frame, and indices for GL TRIANGLES which is shared for all frames. Each frame I lerp between two adjacent key frames to generate the vertices for that frame on the CPU and then draw it. How can I move this into a GLSL vertex shader? Can a shader interpolate between two sets of vertices, and how can I store those vertices on the GPU?


How to render animated models via instanced rendering? I have an animated model with a maximum of 60 bones. That means i have an array of 60 matrices when i want to render the model. Previously i would just create a uniform with the fixed size (mat4 60 ), but now i want to render the model via instanced rendering, which means i need to write 60 matrices per instance into the VAO of the model. This would mean i have to create 240 vertex attributes each containing 4 floats because thats the maximum number of floats an attribute can have. This is obviously a ridiculous solution, besides the fact that i think it exceeds the maximum number of attributes a VAO can have. So how do i render animated models via instance rendering?


CubeRealm OpenGL rotation problems, need help. I'm totally new to OpenGL and I'm working on a Sandbox game called CubeRealm. My problem you see is rotation. I've got it in my head that to rotate the 'camera' I just rotate all the scene by the negative value of the camera's rotational values. However so far it seems to not be working. Here's the code snippets glPushMatrix() lighting() (640 2) (64 2) amount of cubes on one 640x640 plane(409,600,4,096) TODO fix z axis problem for translating glRotatef( player.camera.rotation.x,1.0,0.0,0.0) glRotatef( player.camera.rotation.y,0.0,1.0,0.0) glRotatef( player.camera.rotation.z,0.0,0.0,1.0) renderGrid() glPopMatrix() glutSwapBuffers() SNIPPET2... case LOOK UP if(player.camera.rotation.y! 90.0) if they are not looking up make them look up player.camera.rotation.y 90.0 TODO set direction the camera is facing in break case ROTATE LEFT if(player.camera.rotation.x! 0.0) player.camera.rotation.x 90.0 TODO set direction the camera is facing in else player.camera.rotation.x 360.0 player.camera.rotation.x 90.0 TODO set direction the camera is facing in break case LOOK DOWN if(player.camera.rotation.y! 90.0) if they are not looking down make them look down player.camera.rotation.y 90.0 TODO set direction the camera is facing in break case ROTATE RIGHT if(player.camera.rotation.x! 360.0) player.camera.rotation.x 90.0 TODO set direction the camera is facing in else player.camera.rotation.x 0 player.camera.rotation.x 90.0 TODO set direction the camera is facing in break When I press the right arrow key(rotate to the right) it doesn't rotate also when I rotate up(up arrow) it goes weird instead of allowing me to see the top of the skybox it still shows me my test cubes. So guys how do I fix the rotation, what am I doing wrong? Note the 'TODO set direction' stuff is for my local axis system. Those TODOs are irrelevant to the question.


How can I render text using the new(ish) JOGL GPU curve rendering classes? I'm fairly new to OpenGL JOGL, working through various tutorials and books and making steady progress. Text, however, is an area where I'm stuck. I figured out one way using BufferedImage and Graphics2D to draw strings and then swizzle the pixels and copy to an OpenGL texture, but the quality is low, it is resolution dependent, and it's not efficient. I found this http forum.jogamp.org GPU based Resolution Independent Curve Rendering td2764277.html. Unfortunately while there are some demos in the GitHub repo I can't quite get my head around them. The code I've tried to use is below In the init() method InputStream fontFile getClass().getResourceAsStream("media futura.ttf") try font FontFactory.get(fontFile, true) catch (IOException e) System.err.println("Couldn't open font!") e.printStackTrace() RenderState renderState RenderState.createRenderState(SVertex.factory()) renderState.setColorStatic(1, 1, 1, 1) renderState.setHintMask(RenderState.BITHINT GLOBAL DEPTH TEST ENABLED) renderer RegionRenderer.create(renderState, RegionRenderer.defaultBlendEnable, RegionRenderer.defaultBlendDisable) renderer.init(gl, Region.VBAA RENDERING BIT) util new TextRegionUtil(Region.VBAA RENDERING BIT) In the display() method PMVMatrix pmv renderer.getMatrix() pmv.glMatrixMode(GLMatrixFunc.GL MODELVIEW) pmv.glLoadIdentity() pmv.glTranslatef(0, 0, 300) float pixelSize font.getPixelSize(32, 96) util.drawString3D(gl, renderer, font, pixelSize, "Test", null, samples) I've searched and searched for a tutorial on this stuff or a simple, commented code example explaining how it works but to no avail. If anyone can help me I'd be extremely grateful!


Draw multiple times same object but translated and rotated I want to draw lots of spheres in different locations and orientations with Opengl4 and JOGL. As the vertexes and colours are the same for all of them, I have just one array for vertexes and another for colours. For the positions and orientations, I have another big matrix where I have all data for all spheres. In principle, drawing one with glDrawArrays is not a problem but for severals, I have read that I should use glDrawArraysInstanced instead. My problem is that I am a bit confused about how to apply each transformation for my particles. How should I introduce this array into the shader? Should I send the matrix model after doing the transformations in the cpu or should I send the positions and orientations and transform them inside the shader? How do I connect the data to the shader? How should the shader look like?


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


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


Can't get world position from reverse Z buffer I'm using this solution to render using a reversed Z buffer. This looks fine and completely fixes all my z fighting, but it breaks what I use in shader to derive the world position from the depth for various purposes such as deferred lighting and fog (it has worked for a regular projection matrix) vec4 screenSpacePosition vec4(texcoord 2.0 1.0, depth 2.0 1.0, 1) vec4 worldSpacePosition invProjView screenSpacePosition vec3 finalPosition worldSpacePosition.xyz worldSpacePosition.w return finalPosition I've thought that this was due to this using a single view projection matrix, so I've also tried this vec4 clipSpacePosition vec4(texcoord 2.0 1.0, depth 2.0 1.0, 1.0) vec4 viewSpacePosition invProj clipSpacePosition viewSpacePosition viewSpacePosition.w vec4 worldSpacePosition invView viewSpacePosition return worldSpacePosition.xyz That must be suboptimal performance wise, but it doesn't work either anyway. Any idea what I'm missing?


Is it possible to store diffuse and normal maps in the same texture area and preserve SRGB linear space? Usually, one would want to upload texture data to OpenGL with GL SRGB for the internalformat of a texture, and GL RGB (or some other linear format) for normal data or specular highlight maps. We can minimize context switches by using a texture array, but that forces all textures to have the same internalformat. Is there a way to store all needed textures in a single texture array, but preserve colour spaces? Or should I convert from SRGB to linear space when uploading texture data?


Texture coordinates for custom geometry in SceneKit ios9 I am trying to texture the a custom plane shape I created in scenekit on iOS9. I need the texture to spread out and stretch over the entire surface. I have a vertex and fragment shader on an SCNprogram. But it seems I am doing something wrong and fiddling with this all day, I have come to the conclusion that somehow the Texture coordinates I specify are not correct. My question is, when creating a geometry, does SceneKit create the texture coordinates automatically so when I specify CGpoint(0,0) for one corner of the texture, it automatically maps it to the bottom left corner of the geometry? Or do I have to manually specify the texture coordinates uv for the geometry I create? This problem is a part of a larger question posted here https stackoverflow.com questions 34104369 custom shader scnprogram ios 9 scenekit 34105050 34105050 Please help, I have spent all day tinkering but no success (


Processing through multiple shaders (LWJGL Java OpenGL) Very simple question Is it possible to process a vbo through different shaders? If so, how? What I want is sth like this reflectionShader.bind() starts shader reflectionShader.load(some values) loads uniform vars into shader process(vbo) "renders" vbo using bound shader reflectionShader.unbind() stops shader refractionShader.bind() refractionShader.load(some other values) process(vbo) refractionShader.unbind() render(vbo) output to screen


OpenGL C Rotate relative to shooting gun I'm trying to make a 2D game where I have a gun that i use to shot things in the direction of the mouse resulting in an angle that I can get. I have some problems with the trajectory of the bullet because I don't know what to put in the Transpose and Rotate function. For example Point 1 has x 20 and y 30. I want to shot in the direction of Point 2 at x 50 and y 50. To do that i get an angle 't' which I use in the rotate function. But the reality is that I get the animation that I presented in the photo. I increase the x coord of the bullet because I can only shot in right side so only positive x. The bullet is moving on the 0x axis rotated at an angle t but at the same y as the gun. What I want is something like I'm sorry if this is a duplicate I couldn't find a solution to my problem. I think the resulting Matrix should have the form Translate Rotate Translate but I can't find the right x and y. Sorry if this seemed dumb and thank you for your time!