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


Using multiple shaders in OpenGL3.3 guys, I got a question on how to use multiple shaders in my app. The app is simple I have a 3D scene, say, simple game and I want to show some 2D GUI in the scene. I was following this tutorial on how to add font rendering to my scene. One difference is that I am using Java and lwjgl, but everything is implemented as in the tutorial. So I have 2 sets of shaders (2 programs). 1st that handles the 3D models and scene at all. I added the second set of shaders, I just copied them from the tutorial. Here are they vertex version 330 in vec2 position in vec2 texcoord out vec2 TexCoords uniform mat4 projection void main() gl Position projection vec4(position, 0.0, 1.0) TexCoords texcoord and fragment version 330 in vec2 TexCoords out vec4 color uniform sampler2D text uniform vec3 textColor void main() vec4 sampled vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r) color vec4(textColor, 1.0) sampled I compile shaders, link them into a separate programs. (so I have modelProgram and fontProgram). However, when I run my application, I see errors in the console (however, the application runs fine) WARNING Output of vertex shader 'TexCoords' not read by fragment shader ERROR Input of fragment shader 'vNormal' not written by vertex shader ERROR Input of fragment shader 'vTexCoord' not written by vertex shader ERROR Input of fragment shader 'vPosition' not written by vertex shader As you can see TexCoords is an out variable in font.vs.glsl and the other 3 are in variables in model.fs.glsl. So they belong to the other set of shaders, other program. My question is why this happen? It looks like the pipeline tries to combine one program with another, although the application runs smoothly. The other problem I have is that I do not see any text rendered. I don't know whether this is caused by this or it happens because something else. Any help will be appreciated! Thank you


clamp a 2D coordinate to fit within an ellipse I need to clamp a 2D coordinate to fit within an ellipse. Call of Duty Modern Warfare 2 does something similar where capture points are translated from a 3D vector in the world to a 2D screen coordinate and then the 2D coordinates are clamped within an ellipse. When the capture points are in view they're within the bounds of the ellipse. When they're behind you they are clamped to be within the bounds of the ellipse. Given a 2D coordinate that could be off screen, etc, what is the math behind clamping it within an ellipse?


Calculate distance from the centre to the edge of a cube in OpenGL I'm trying to calculate the distance between a central point on a cube and anywhere on the surface of the cube, depending on the location of a second 3D point. I have two vertices in 3D Q and P. Q is the centre of the cube, P is a random point outside of the cube. I also have a known size of the cube, where distance across is d. If I have the normalised vector of u, which is Q gt P, how do I calculate the distance from the centre to where it hits the surface of the cube? I could not find the answer to this anywhere,on the Stack Exchange.


Protecting game assets through archiving I'm writing a game in C (with OpenGL) and am getting quite far into development. Currently I'm loading the data directly from different directories. (E.G. I load textures from a Data Textures ...png) This is fine, but not preferable. Ideally I would like to protect these assets without too much of a performance hit. I looked at other games that I own, both Indie and AAA and found that the majority of them archive the data. However, I am unable to access these archives with programs like Winrar Archiver which implies that they have some level of protection. I'm not particularly knowledgeable in the field of encryption and data storage, so I may be overlooking something obvious but I would like to know how exactly I could achieve something similar. (I am aware that competent individuals are able to use the GPU to gain access to the data but that's not preventable)


Make openGL program only update every 1 60 seconds I'm learning C and openGL and have this program as a result from tutorials and playing around. The problem is that the main loop is running at "full speed", making the program unnecessarily cpu intensive. I have managed to make it only perform rendering every 16.7 ms or so, but the outside loop that is waiting to render still is iterating as fast as my computer can handle. This is the full main.cpp http pastebin.com KaCW7wZw This is the main loop at line 95 while (!terminate) if (SDL GetTicks() gt time start frame rate) time start SDL GetTicks() while (SDL PollEvent( amp event)) if (event.type SDL QUIT) terminate true break glClearColor(0.1f, 0.1f, 0.1f, 1.0f) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) renderLoop(entities, amp counter) SDL GL SwapWindow(m window) counter 1.0f I've tried googling and haven't found anything concrete (obviously), except that using some kind of sleep is bad design for these loops. So how can I alter this to slow the whole thing down, and avoid having 100 cpu usage for a program that's not doing much at the moment?


OpenGL Understanding the relationship between Model, View and World Matrix I am having a bit of trouble understanding how these matrixes work and how to set them up in relation to one another to get a proper system running. In my understanding the Model Matrix is the matrix of a object, for example a cube or a sphere, there will be many of these in the application game. The World Matrix is the matrix which defines the origin of the 3D world. the starting point. And the View Matrix is the "camera" everything gets translated with this to make sure you have the illusion of an actual camera when in fact everything is moving instead of this matrix? I am a bit lost here. So I was hoping someone here could help me understand this properly. Does every modelMatrix get translated multiplied with the world matrix and the worldMatrix then with the viewMatrix? Or does every modelMatrix get translated multiplied with the viewMatrix and then that with the worldMatrix? How do all these matrixes relate and how do you set up a world with multiple objects and a "camera"? EDIT Thanks a lot for the feedback already. I did some googling aswel and I think I do understand it a bit better now, however would it be possible to get some pseudo code advice? projectionMatrix Matrix makePerspective(45, width, height, 0.1, 1000.0, projectionMatrix) modelMatrix Matrix identity(modelMatrix) translate(modelMatrix, 0.0, 0.0, 10.0 ) move back 10 on z axis viewMatrix Matrix identity(viewMatrix) do some translation based on input with viewMatrix Do I multiply or translate the viewMatrix with the modelMatrix or the other way around? and what then? I currently have a draw method up in such a way that it only needs 2 matrixes for arguments to draw. Here is my draw method draw(matrix1 matrix2) bindBuffer(ARRAY BUFFER, cubeVertexPositionBuffer) vertexAttribPointer(shaderProgram.getShaderProgram().vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, FLOAT, false, 0, 0) bindBuffer(ARRAY BUFFER, cubeVertexColorBuffer) vertexAttribPointer(shaderProgram.getShaderProgram().vertexColorAttribute, cubeVertexColorBuffer.itemSize, FLOAT, false, 0, 0) bindBuffer(ELEMENT ARRAY BUFFER, cubeVertexIndexBuffer) setMatrixUniforms(shaderProgram, matrix1, matrix2) drawElements(TRIANGLES, cubeVertexIndexBuffer.numItems, UNSIGNED SHORT, 0) What are those matrixes suppose to be? Thanks a lot in advance again guys.


Gamma Space and Linear Space with Shader I am using Unity and I can choose between two color space mode in the settings Gamma or Linear Space. I am trying to build a Custom Lighting Surface shader but I am facing some problems with those Color Space. Because the render is not the same depending of the Color Space. If I render the lightDir, Normal or viewDir I can see that they are different depending of the Color Space I use. I made some test and the result I have in Linear Space is great but how can I obtain the same result in Gamma Space ? Are there some transformations ? On what component should I apply those transformations ? Thank you very much !


client side array in the OpenGL 3.3. core It is possible the topic (not using VBO)? in the OpenGL 3.0 compatible profile I can to draw this way GLint position index attrib location get("VertexPosition") gl EnableVertexAttribArray(position index) gl VertexAttribPointer(position index, 3, gl FLOAT, false, 0, pos Data) gl DrawArrays(gl TRIANGLES, 0, count of vertices) Bat in the OpenGL 3.3 core profile it displays a blank screen. It is right?


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


Efficiently rendering to 3D texture I have an existing depth texture and some other color textures, and want to process the information in them by rendering to a 3D texture (based on the depth contained in the depth texture, i.e. a point at (x y) in the depth texture will be rendered to (x y texture(depth,uv)) in the 3D texture). Simply doing one manual draw call for each slice of the 3D texture (via glFramebufferTextureLayer) is terribly slow, since I don't know beforehand to what slice of the 3D texture a given texel from one of the color textures or the depth texture belongs. This means the entire process is effectively for each slice for each texel in depth texture process color textures and render to slice So I have to sample the depth texture completely per each slice, and I also have to go through the processing (at least until to discard ) for all texels in it. It would be much faster if I could rearrange the process to for each texel in depth texture figure out what slice it should end up in process color textures and render to slice Is this possible? If so, how? What I'm actually trying to do the color textures contain lighting information (as seen from light view, it's a reflective shadow map). I want to accumulate that information in the 3D texture and then later use it to light the scene. More specifically I'm trying to implement Cryteks Light Propagation Volumes algorithm.


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


How should I do 3D games through Java on a mac? I have been self teaching myself Java on the mac mostly because the language is cross platform. Recently, I have been only able to develop 2D games using the Graphics2D class. Now, I want to learn how to make 3D games in Java. I used to model and animate stuff in 3D, so my knowledge of 3 Dimensional stuff is okay. I have spent the last 3 hours using google to look up ways of making 3D games in java. Apparently the best one to use is OpenGL, so i looked up a tutorial on it and i cannot find a tutorial that shows how to (if there is a way) install JOGL on the Mac platform. Should i continue to use Java? How can i make 3D games using Java? What is the best way to make 3D games on a mac?


What is used for border parameter? I'm learning OpenGL and have a question. I read about Texturing and found border param in glCopyTexImage and glCompressedTexImage functions. In book "OpenGL Programming Guide" wrote that border is reserved and must be zero? If it reserved why they place it into parameter? P.S. I have one idea, is it used for border texture? Like don't read data below that border, isn't it?


Managing many draw calls for dynamic objects We are developing a game (cross platform) using Irrlicht. The game has many (around 200 500) dynamic objects flying around during the game. Most of these objects are static mesh and build from 20 50 unique Meshes. We created seperate scenenodes for each object and referring its mesh instance. But the output was very much unexpected. Menu screen (150 tris Just to show you the full speed rendering performance of 2 test computers) a) NVidia Quadro FX 3800 with 1GB 1600 FPS DirectX and 2600 FPS on OpenGL b) Mac Mini with Geforce 9400M 256mb 260 FPS in OpenGL Now inside the game in a test level (160 dynamic objects counting around 10K tris) a) NVidia Quadro FX 3800 with 1GB 45 FPS DirectX and 50 FPS on OpenGL b) Mac Mini with Geforce 9400M 256mb 45 FPS in OpenGL Obviously we don't have the option of mesh batch rendering as most of the objects are dynamic. And the one big static terrain is already in single mesh buffer. To add more information, we use one 2048 png for texture for most of the dynamic objects. And our collision detection hardly and other calculations hardly make any impact on FPS. So we understood its the draw calls we make that eats up all FPS. Is there a way we can optimize the rendering, or are we missing something?


RGB to xyY color space conversion and luminance The luminance calculated by following GLSL functions (fragment shaders tonemap) has different value float GetLuminance (vec3 rgb) return (0.2126 rgb.x) (0.7152 rgb.y) (0.0722 rgb.z) vec3 RGB2xyY (vec3 rgb) const mat3 RGB2XYZ mat3(0.4124, 0.3576, 0.1805, 0.2126, 0.7152, 0.0722, 0.0193, 0.1192, 0.9505) vec3 XYZ RGB2XYZ rgb return vec3(XYZ.x (XYZ.x XYZ.y XYZ.z), XYZ.y (XYZ.x XYZ.y XYZ.z), XYZ.y) I used a glm library to calculate an example result. For glm vec3(2.0f, 3.0f, 8.0f) GetLuminance returns 3.1484. RGB2xyY returns glm vec3 which z component is equal 3.8144. What is wrong ?


3D picking for mouse move event I implemented color picking recently and I would like to use it as kind of highlight when mouse is over an object but I am concerned about performance. Color picking requires whole frame to be drawn, loosing effectively up to half of performance (MouseMove can happen nearly every frame). Also, when mouse moves it is very likely to be nearly above previous point is there any way how to use this fact to improve performance of 3D picking? Or is my best chance to use some other technique of 3D picking or approximation of results? tl dr If I wanted to do "realtime" 3D picking on MouseMove, what is the best technique for doing so performance wise? EDIT the exact numbers are even worse, when rendering 1m triangles render time increase from 1.5ms to 2 6ms and in spikes up to 15ms.


How should I move 2D objects in OpenGL ES 2? I am a bit confused about what I need to move a basic square. Should I use a translation matrix or just change the object vertices? Which one is better? I use a simple vertex shader, gl Position myPMVMatrix a vertex, along with a VBO.


Software and Hardware Rendering From what I understand, the main difference between software rendering and hardware rendering is that in software rendering you use the CPU to determine what to color each pixel, and in hardware rendering you let the GPU take care of calculations and determine how to draw each pixel. However, in the end, isn't an API such as OpenGL still required to do the actual drawing no matter which method you pick? I saw a basic software rendering engine that someone built, and the person said he still used OpenGL to do the actual drawing after using the CPU to do the rendering. So is an API like OpenGL or DirectX still required in the end? And if so, is it true that a computer must at least have an integrated GPU or dedicated GPU to display anything at all?


BRDF Incorrect specular highlights I'm currently attempting to implement BRDF lighting, and am hitting a bit of a snag with my specular term the specular highlights aren't rendering correctly. To make things simple, I'm using a single directional light rendering down the Z axis only, and manually specify the gloss specularity of each of the following spheres. Glossyness increases left to right, and Specularity increases bottom to top. Notice how the highlights seem shifted nearly 90 degrees upwards Calculating the specular BRDF I use the generic Fresnel Shlick eq For the NDF, I use the GGX Trowbridge Reitz eq And for the Geometric Shadowing function, I use the Smith Shlick Beckmann eq vec3 BRDF Specular(vec3 F0, vec3 1minusF0, vec3 WorldPos, vec3 Normal) vec3 LightDirection vec3(0, 0, 1) vec3 ViewDirection normalize(EyePos WorldPos) vec3 HalfVec normalize(LightDirection ViewDirection) float NdotL clamp(dot(Normal, LightDirection), 0.0, 1.0) float NdotV clamp(dot(Normal, ViewDirection), 0.0, 1.0) float NdotH clamp(dot(Normal, HalfVec), 0.0, 1.0) float VdotH clamp(dot(ViewDirection, HalfVec), 0.0, 1.0) float Roughness max(1.0f Gloss, 0.0) Turn into roughness float Roughness 2 (Roughness Roughness) float NdotH 2 NdotH NdotH Normal Distribution Function GGX (Trowbridge Reitz) float D0 (NdotH 2 (a 2 1.0f) 1.0f) float D a 2 (M PI (D0 D0)) Fresnel Shlick vec3 Fs F0 1minusF0 pow(1.0 VdotH, 5.0) Geometric Shadowing Smith Shlick Beckmann float k a 2 sqrt(2.0 M PI) float GV NdotV (NdotV (1.0 k) k) float GL NdotL (NdotL (1.0 k) k) float G GV GL vec3 brdfspec vec3(max(( Fs D G ) (4.0f NdotL NdotV), 0.0)) return brdfspec I've been following so many different resources and mimicked many other implementations, and even reducing it down to this basic level I'm still having this issue. I don't know why I'm not getting proper results I'm using a deferred renderer, I derive the World position of each fragment from the depth buffer, and store my normals in viewspace. I don't use a "Metalness" map, but instead use a single rgb specular map, hense why my Fresnel calculation uses Vec3's instead of floats.


OpenGL Texture Loading I've been using OpenGL for a bit so I have a general idea of what I'm doing. Recently, I've been working on a framework to let me test stuff more easily. As part of the framework, I split up loading images into OpenGL into two parts, one where I load the data (ie from a file) and another part where I actually send the data to OpenGL. However, when I use the system I designed, only a black triangle is displayed. When I bypass the system I created and load the texture directly into OpenGL using SOIL's SOIL load OGL texture function, everything works with no other changes. Here's the relevant sections of code Main.cpp Section commented out to test loading a texture using SOIL instead Texture Texture2DSource texData texData.loadTextureFromFile("Background.png", Filesystem FOLDER TEXTURES) auto texture Texture Interface getSingleton().loadTexture(texData) Debugging function I added to access the texture ID directly GLuint textureID texture gt getTextureID() Load the texture using SOIL as opposed to my texture loading classes GLuint textureID SOIL load OGL texture( "C Users Username AppData Roaming Test Textures Background.png", SOIL LOAD RGBA, SOIL CREATE NEW ID, SOIL FLAG INVERT Y) glActiveTexture(GL TEXTURE0) This line is used when the SOIL texture loading is used glBindTexture(GL TEXTURE 2D, textureID) I hardcoded in 0 as the uniform ID just for testing normally I query the uniform ID and use that glUniform1i(uniformID, 0) Vertex Shader version 440 layout(location 0) in vec2 vertex layout(location 1) in vec2 uvData out vec2 uv void main() gl Position vec4(vertex, 0.0f, 1.0f) uv uvData Fragment Shader version 440 in vec2 uv out vec4 color uniform sampler2D textureSampler void main() color texture(textureSampler, uv) C code for loading a texture into memory Create variables to store the image dimensions and properties int width 0 int height 0 int channels 0 Load the image auto data SOIL load image(fileLocation.c str(), amp width, amp height, amp channels, SOIL LOAD RGBA) Resize the texture's vector to the same size as the array returned from SOIL m data.resize(width height) Copy the data from SOIL's array to the vector const uint32 t BYTES PER PIXEL 4 memcpy( amp m data 0 , data, width height BYTES PER PIXEL) Set the dimensions m x width m y height Flip the image Code omitted as irrelevant C code for loading the texture data into OpenGL Set up the texture storage GLuint textureID 1 glGenTextures(1, amp textureID) glBindTexture(GL TEXTURE 2D, textureID) Load the texture data glTexImage2D( GL TEXTURE 2D, Texture Target 0, Level of Detail level GL RGBA, Internal Format data.m x, Width data.m y, Height 0, Border (must be 0) GL RGBA, Pixel Data Format GL UNSIGNED BYTE, Data Type amp data.m data 0 Texture Data ) Set texture filtering options 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 MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST MIPMAP NEAREST) Create a Texture object and load the texture ID into it, then return it Texture lt GL TEXTURE 2D gt texture texture.m textureID textureID return texture Here's some more images This is what the window shows when using my texture loading process. This is what Nvidia NSight shows for the Fragment shader. This is what the window shows when bypassing my texture loading process. This is what Nvidia NSight shows when bypassing my texture loading process. NSight shows the texture as loaded properly for both texture loading processes, and everything else seems to be the same. Any ideas on what's causing the issue?


Efficient per frame constants in shaders I have some variables that stay the same during the entire frame and will be used by a large number of the various shaders I use (several dozens). These include things such as the various transforms of the camera, light source data, etc. The main options to provide this data to all the shaders (at least that I can think of) are Just give each shader uniforms for the data and set all uniforms manually when they're required Use buffers, such as Uniform Buffer Objects Shader Storage Buffer Objects Buffer Textures Which of these options is generally the most performance efficient, and why?


Noise when using SSLR (Screen Space Local Reflections) When I tried to apply reflections to my scene, I ran into the problem of noise My fragment shader code version 330 core uniform sampler2D normalMap in view space uniform sampler2D depthMap in view space uniform sampler2D colorMap uniform sampler2D reflectionStrengthMap uniform mat4 projection uniform mat4 inv projection in vec2 texCoord layout (location 0) out vec4 fragColor vec3 calcViewPosition(in vec2 texCoord) Combine UV amp depth into XY amp Z (NDC) vec3 rawPosition vec3(texCoord, texture(depthMap, texCoord).r) Convert from (0, 1) range to ( 1, 1) vec4 ScreenSpacePosition vec4(rawPosition 2 1, 1) Undo Perspective transformation to bring into view space vec4 ViewPosition inv projection ScreenSpacePosition Perform perspective divide and return return ViewPosition.xyz ViewPosition.w vec2 rayCast(vec3 dir, inout vec3 hitCoord, out float dDepth) dir 0.3f for (int i 0 i lt 20 i ) hitCoord dir vec4 projectedCoord projection vec4(hitCoord, 1.0) projectedCoord.xy projectedCoord.w projectedCoord.xy projectedCoord.xy 0.5 0.5 float depth calcViewPosition(projectedCoord.xy).z dDepth hitCoord.z depth if(dDepth lt 0.0) return projectedCoord.xy return vec2( 1.0f) void main() vec3 normal texture(normalMap, texCoord).xyz 2.0 1.0 float depth texture(depthMap, texCoord).r vec3 screenPos 2.0 vec3(texCoord, depth) 1.0 vec3 viewPos calcViewPosition(texCoord) Reflection vector vec3 reflected normalize(reflect(normalize(viewPos), normalize(normal))) Ray cast vec3 hitPos viewPos float dDepth float minRayStep 0.1f vec2 coords rayCast(reflected max(minRayStep, viewPos.z), hitPos, dDepth) if (coords ! vec2( 1.0)) fragColor mix(texture(colorMap, texCoord), texture(colorMap, coords), texture(reflectionStrengthMap, texCoord).r) else fragColor texture(colorMap, texCoord) Normal map Reflection strength map (only red chanel)


indices for surface of revolution I'd like to implement a surface of revolution. I already implemented creating Vertices based on a 2D line. I now want to get the indices to render the mesh with GL TRIANGLES Here's the code to create the 3D Vertices out of a 2D line void createVertices(vector lt Vector2 gt amp points,unsigned int iterations) int i int j unsigned int index vector lt Vertex gt newVertices vector lt unsigned int gt newIndices for(j 0 j lt points.size() j) for(i 0 i lt iterations i) Vector2 p points.at(j) float theta M PI 2.0 (float)i (float)iterations float x sinf(theta) p.x float z cosf(theta) p.x newVertices.push back(Vertex(x,p.y,z)) and here's the code that will be called to save the Vertices void addVertices(vector lt Vertex gt amp vertices,vector lt unsigned int gt amp indices) this gt vertices vertices this gt indices indices unsigned int verticesSize vertices.size() sizeof(Vertex) unsigned int indicesSize indices.size() sizeof(unsigned int) float vertexBuffer new float vertices.size() sizeof(Vertex) createBuffers(vertices,vertexBuffer) glGenVertexArrays(1, amp VAO) glBindVertexArray(VAO) glGenBuffers(1, amp verticesVBO) glBindBuffer(GL ARRAY BUFFER,verticesVBO) glBufferData(GL ARRAY BUFFER,verticesSize,vertexBuffer,GL STATIC DRAW) glGenBuffers(1, amp indicesVBO) glBindBuffer(GL ELEMENT ARRAY BUFFER,indicesVBO) glBufferData(GL ELEMENT ARRAY BUFFER,indicesSize, amp indices 0 ,GL STATIC DRAW) delete vertexBuffer someone has a basic idea?


Passing data into a vertex shader for perspective divide In OpenGL and GLSL, I am just learning about perspective projection and the vertex shader. However, I am a little confused about what data actually needs to be passed to the vertex shader, and what needs to be done in the shader code itself. I have two questions Suppose I have a triangle defined in 3D coordinates (x,y,z). Do I need to pass a 4D vector with values (x,y,z,w), where w z? Or do I just pass the 3D vector? The reason I ask is that I know that somewhere in the pipeline, the x and y coordinates are divided by the w component, in the perspective divide. In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically? Thanks!


Vector out of range (Batch rendering opengl) So ive (tried to) implement a batch rendering system, and at the for loop the error pops up and I'm not shure what ive done wrong. Any suggestions to improve the system would be much appreciated. (It's my first time trying to implement this) include "masterRenderer.h" masterRenderer masterRenderer() quad vector lt Quad gt (1000) numOf 0 void masterRenderer addQuad(Quad quad) masterRenderer quad numOf quad numOf void masterRenderer init(GLuint shader, string texPath) vector lt GLfloat gt vertex((3 4) (numOf 1)) vector lt GLfloat gt normals((3 4) (numOf 1)) vector lt GLfloat gt color((3 4) (numOf 1)) vector lt GLfloat gt uv((2 4) (numOf 1)) int nv 0, nn 0, nc 0, nu 0 GLfloat sizeV 0, sizeN 0, sizeC 0, sizeUv 0 for (int i 0 i lt numOf i ) The error seems to pop up over here. for (int j 0 j lt 3 4 j ) vertex nv quad i .g vertex buffer data j sizeV quad i .g vertex buffer data j nv normals nn quad i .g normal buffer bata j sizeN quad i .g normal buffer bata j nn color nc quad i .g color buffer data j sizeC quad i .g color buffer data j nc for (int j 0 j lt 2 4 j ) uv nc quad i .g uv buffer data j sizeUv quad i .g uv buffer data j nc TextureID glGetUniformLocation(shader, "textureSampler") texture handle Util loadTexture("test.png") glGenBuffers(1, amp normalbuffer) glBindBuffer(GL ARRAY BUFFER, normalbuffer) glBufferData(GL ARRAY BUFFER, sizeof(sizeN), amp normals 0 , GL STATIC DRAW) glGenBuffers(1, amp colorbuffer) glBindBuffer(GL ARRAY BUFFER, colorbuffer) glBufferData(GL ARRAY BUFFER, sizeof(sizeC), amp color 0 , GL STATIC DRAW) glGenBuffers(1, amp uvbuffer) glBindBuffer(GL ARRAY BUFFER, uvbuffer) glBufferData(GL ARRAY BUFFER, sizeof(sizeUv), amp uv 0 , GL STATIC DRAW) glGenBuffers(1, amp vertexbuffer) glBindBuffer(GL ARRAY BUFFER, vertexbuffer) glBufferData(GL ARRAY BUFFER, sizeof(sizeV), amp vertex 0 , GL STATIC DRAW) void masterRenderer draw(glm mat4 Model, glm mat4 View, glm mat4 Projection, GLuint MatrixID) glPushMatrix() glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, texture handle) glUniform1i(TextureID, 0) glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, vertexbuffer) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, (void )0) glEnableVertexAttribArray(1) glBindBuffer(GL ARRAY BUFFER, colorbuffer) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 0, (void )0) glEnableVertexAttribArray(2) glBindBuffer(GL ARRAY BUFFER, uvbuffer) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, 0, (void )0) glEnableVertexAttribArray(3) glBindBuffer(GL ARRAY BUFFER, normalbuffer) glVertexAttribPointer(3, 3, GL FLOAT, GL FALSE, 0, (void )0) for (int i 0 i lt numOf 1 i ) Model glm translate(glm mat4(1.0f), glm vec3(quad i 1 .pos.x, quad i 1 .pos.y, quad i 1 .pos.z)) Model glm rotate(Model, glm radians(quad i 1 .yrot), glm vec3(0.0f, 1.0f, 0.0f)) glm mat4 mvp Projection View Model glUniformMatrix4fv(MatrixID, 1, GL FALSE, amp mvp 0 0 ) glDrawArrays(GL QUADS, 4 i 1, 4 i) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) glDisableVertexAttribArray(3) glPopMatrix() masterRenderer masterRenderer()


How can I determine a budget for RAM used (LRU involving VRAM, in particular) After some profiling, I've determined that one of my most expensive functions involves drawing text. As a solution, I'd like to implement a LRU type of cache that will "remember" the vertices, tex coords (etc) for a given string. This is particularly complicated because some of the resources involved reside in VRAM (most do, actually I take a given string and convert it into a long sequence of vertices tex coords indices), while some reside in plain RAM. If I knew what my limits were (in both respects) I could write a decent LRU cache system and probably buy myself a substantial performance gain. The primary target for this app is the Android platform, and as I understand it, most such devices share RAM with the GPU. I'd appreciate any answers to this, whether they directly answer my question or not.


What Shading Rendering techniques are being used in this image? My previous question wasn't clear enough. From a rendering point of view what kind of techniques are used in this image as I would like to apply a similar style (I'm using OpenGL if that matters) http alexcpeterson.com My specific questions are How is that sun glare made? How does the planet look "cartoon" like? How does the space around the planet look warped misted? How does the water look that good? I'm a beginner so any information keywords on each question would be helpful so I can go off and learn more. Thanks


GLM conversion from euler angles to quaternion and back does not hold I am trying to convert the orientation of an OpenVR controller that I have stored as a glm vec3 of Euler angles into a glm fquat and back, but I get wildly different results and the in game behavior is just wrong (hard to explain, but the orientation of the object behaves normally for a small range of angles, then flips in weird axes). This is my conversion code get orientation from OpenVR controller sensor data const glm vec3 eulerAnglesInDegrees orientation PITCH , orientation YAW , orientation ROLL debugPrint(eulerAnglesInDegrees) const glm fquat quaternion glm radians(eulerAnglesInDegrees) const glm vec3 result glm degrees(glm eulerAngles(quaternion)) debugPrint(result) result should represent the same orientation as eulerAnglesInDegrees I would expect eulerAnglesInDegrees and result to either be the same or equivalent representations of the same orientation, but that is apparently not the case. These are some example values I get printed out 39.3851 5.17816 3.29104 39.3851 5.17816 3.29104 32.7636 144.849 44.3845 147.236 35.1512 135.616 39.3851 5.17816 3.29104 39.3851 5.17816 3.29104 32.0103 137.415 45.1592 147.99 42.5846 134.841 As you can see above, for some orientation ranges the conversion is correct, but for others it is completely different. What am I doing wrong? I've looked at existing questions and attempted a few things, including trying out every possible rotation order listed here, conjugating the quaternion, and other random things like flipping pitch yaw roll. Nothing gave me the expected result. How can I convert euler angles to quaternions and back, representing the original orientation, using glm? Some more examples of discrepancies original 4 175 26 computed 175 4 153 difference 179 171 179 original 6 173 32 computed 173 6 147 difference 179 167 179 original 9 268 46 computed 170 88 133 difference 179 356 179 original 27 73 266 computed 27 73 93 difference 0 0 359 original 33 111 205 computed 146 68 25 difference 179 43 180 I tried to find a pattern to fix the final computed results, but it doesn't seem like there's one easy to identify. GIF video of the behavior Full video on YouTube Visual representation of my intuition current understanding The above picture shows a sphere, and I'm in the center. When I aim the gun towards the green half of the sphere, the orientation is correct. When I aim the gun towards the red half of the sphere, it is incorrect it seems like every axis is inverted, but I am not 100 sure that is the case.


Transparent textures being handled oddly In OpenGL why is it that when rendering transparent textures it changes the color values of all the pixels? Ex. when this transparent texture is rendered it comes out as this. Also if I change the texture to not have transparency it still has the same problem of changing pixel values. What causes OpenGL to completely change a transparent texture when it is rendered? (Note the textures have been created in GIMP and the program is running on a mac (OSX 10.10.3)) EDIT Turns out this happens when you load a texture with transparency on the RGB color spectrum instead of the RGBA spectrum.


Started game development no idea of computer graphics. Should I learn tools or concepts? I am in 6th semester of my Computer science bachelor degree program, Working as Intern in a start up company. I started game development using AndEngine, things are going good because I have good hold on OOP and Java. But I don't have any experience in OpenGL programming and neither studied a course of computer graphics. I want to develop 3D games and there are tools available like Unity3d etc. My question is should I master tools or take online lectures of computer graphics to get started on basics. I want to continue game development as my profession. So what should I do? start learning from scratch or Learn already built tools and just dive into development? I see successful designers with no background of academic study, just did a photoshop course and now they are in the softwarehouse and making websites, sprites etc.


Textures not displaying. Problem with fragment and vertex shaders Hi i have newbe question. I am sending to gpu textures unit and they dont display. This is simple version of my fragment and vertexshader. (More complicated version also dont work with other textures than DDS but maybe simpler version will tell you what newbe mistake i made) for (unsigned int i 0 i lt textures.size() i ) glActiveTexture(GL TEXTURE0 i) glBindTexture(GL TEXTURE 2D, Textures i ) Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, i) This is my simple fragmentshader version 330 core Interpolated values from the vertex shaders in vec2 UV Ouput data out vec3 color Values that stay constant for the whole mesh. uniform sampler2D myTextureSampler void main() Output color color of the texture at the specified UV color texture2D( myTextureSampler, UV ).rgb This is my simple vertexshader version 330 core Input vertex data, different for all executions of this shader. layout(location 0) in vec3 vertexPosition modelspace layout(location 1) in vec2 vertexUV Output data will be interpolated for each fragment. out vec2 UV Values that stay constant for the whole mesh. uniform mat4 MVP void main() Output position of the vertex, in clip space MVP position gl Position MVP vec4(vertexPosition modelspace,1) UV of the vertex. No special space for this one. UV vertexUV EDIT this corrected version but still something dont work. If i had DDS everything was working OK but jpg textures all time i have problems. EDIT i have correct number of textures but they looks diffrent than original


How to not render what is behind object? I am working on a 3d project using openGL. I am looking for a way to optimize my renderings. Is there a way to tell if an object is behind another object and thus not visible to not waste time rendering it ? I am already working on a frustrum culling implementation to not display what is not visible because out of the viewing frustrum, but I didn't find a way to know if an object in located behind another object. Can any of you help me about this, please ?


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


How do you display non cutout transparent 2D textures with a depth buffer? (OpenGL) I've been able to get my 2D renderer to display transparent cutout textures by testing the alpha of a fragment and discarding if it is less than 1 (or any fraction really). The problem is I want to support using translucent textures. The current way I sort my sprites is by what texture they use, so that I can minimize texture changes. The only way I can think of getting this to work properly is by scrapping that and only sorting by z order. But I don't want to throw away the optimization I already did. Is there any way to do both? Does only rendering in 2D simplify the problem at all? I was hoping to support translucent sprites, but my font renderer makes translucent font textures, so I can't just only use cutouts. EDIT After doing some research, it seems there really is no easy way to do this. (depth peeling for a 2D renderer seems a little overkill) I'm going to compromise by having my renderer hold 2 different sets of sprites, cutouts and translucent. I can draw the cutouts first in whatever order I want, making full use of texture atlases. The translucent textures, however, will need to be in z order, ignoring atlases. If anyone can tell me a better way, I'm all ears.


How to draw a rectangle at x,y where x y are in pixel? Here is my code glMatrixMode(GL PROJECTION) glLoadIdentity() glViewport(0, 0, screen width, screen height) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0.0, screen width, 0.0, screen height, 1.0, 1.0) glMatrixMode(GL MODELVIEW MATRIX) glTranslatef(0, 0, 5) glColor4f(rect.color.R(), rect.color.G(), rect.color.B(), rect.color.A()) glClear(GL COLOR BUFFER BIT) glBegin(GL QUADS) glRectd(rect.transforms.position.x, rect.transforms.position.y, rect.transforms.size.width, rect.transforms.size.height) glEnd() glfwSwapBuffers(window) glFlush() Where rect.transforms.position.x is in pixel. Issue Nothing shows up. The color was tested before amp works on a rectangle that use opengl coordinates.


Octrees and Vertex Buffer Objects As many others I want to code a game with a voxel based terrain. The data is represented by voxels which are rendered using triangles. I head of two different approaches and want to combine them. First, I could once divide the space in chunks of a fixed size like many games do. What I could do now is to generate a polygon shape for each chunk and store that in a vertex buffer object (vbo). Each time a voxel changes, the polygon and vbo of its chunk is recreated. Additionally it is easy to dynamically load and reload parts of the terrain. Another approach would be to use octrees and divide the space in eight cubes which are divided again and again. So I could efficiently render the terrain because I don't have to go deeper in a solid cube and can draw that as a single one (with a repeated texture). What I like to use for my game is an octree datastructure. But I can't imagine how to use vbos with that. How is that done, or is this impossible?


OpenGL cube map is always black When creating and rendering a skybox with a cube map texture, the skybox is black. Here is how I create the cube map texture GLuint loadCubemap(std vector lt std string gt faces) GLuint textureID glGenTextures(1, amp textureID) glActiveTexture(GL TEXTURE0) int width,height unsigned char image glBindTexture(GL TEXTURE CUBE MAP, textureID) for(GLuint i 0 i lt faces.size() i ) image SOIL load image(faces i .c str(), amp width, amp height, 0, SOIL LOAD RGBA) glTexImage2D( GL TEXTURE CUBE MAP POSITIVE X i, 0, GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, image ) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP R, GL CLAMP TO EDGE) glBindTexture(GL TEXTURE CUBE MAP, 0) return textureID Here is how I draw the cube map void Skybox update() the sky box should be in the background glDepthMask(GL FALSE) set the position of the skybox around the camera pos Camera getCurrentlyBound() gt getPos() faces of the cube map std vector lt std string gt faces " home a Programming GameEngine Game Assets skybox px.png", x " home a Programming GameEngine Game Assets skybox nx.png", x " home a Programming GameEngine Game Assets skybox py.png", y " home a Programming GameEngine Game Assets skybox ny.png", y " home a Programming GameEngine Game Assets skybox pz.png", z " home a Programming GameEngine Game Assets skybox nz.png", z create the texture object GLuint cubeMap loadCubemap(faces) set up some matrices glm mat4 modelMatrix glm translate(glm mat4(), pos) glm mat4 cast(orien) glm mat4 mvpMatrix Camera getCurrentlyBound() gt getVP() modelMatrix you can ignore this part Program prog ProgramManager getProgram(msh.getProgramPath()) bind the program prog gt bind() set uniform data prog gt setUniformData(mvpMatrix, "MVP") bind the VAO msh.bind() bind the cube map texture glBindTexture(GL TEXTURE CUBE MAP, cubeMap) glDrawElements(GL TRIANGLES, msh.getNumVerts(), GL UNSIGNED INT, 0) draw msh.unbind() unbind the VAO prog gt unbind() glDepthMask(GL TRUE) And here are the shaders Vertex Shader version 330 core in vec3 pos uniform mat4 MVP out vec3 fragTexVector void main() gl Position MVP vec4(pos, 1) fragTexVector pos Fragment Shader version 330 core out vec4 finalColor in vec3 fragTexVector uniform samplerCube skybox void main() finalColor vec4(1,1,1,1) finalColor texture(skybox, fragTexVector) I have scanned over this piece of code and over my entire project many times to find what was wrong and could not find anything. The samplerCube seems to always get black pixels. Extra Information (might be helpful, I'm not sure) I have tried debugging the program with VOGL (Valve's opengl debugger) but when I try to capture a snapshot of a frame it crashes with an error Internal error KTX texture failed internal consistency check, texture 7 target GL TEXTURE CUBE MAP. This should not happen! I'm very new to OpenGL and if anybody with OpenGL experience could help me with issue it would be greatly appreciated. Thanks.


Project 2D texture onto a cubemap I'm looking to take a 2D texture (previously rendered from the user's perspective), and overlay it overtop of a cubemap. Since a cubemap has 6 textures, I need to run a shader over top of all 6, and use some formula for calculating the UV from a given view. I'm at a loss for how to calculate this. Here's an illustration If the user were to spin around in 1 spot, they would build up full panoramic cubemap. The intention is to reuse end of frame data to update a persistent cubemap that follows the user. I know how to build manual cubemaps by rendering a scene 6 times, once on all axes, however in this case I wish to take an already rendered view and transplant it onto the correct spots on a cubemap.


GLSL rewriting (geometry) shader from 330 to 130 version I'm having trouble running example from https raw.github.com progschj OpenGL Examples master 07geometry shader blending.cpp My graphics card supports only 130 shaders version so I have to rewrite shaders. I figured out how to fix vertex and fragment shaders. I removed layout(location 0) from layout(location 0) in vec4 vposition and added this into my source code glBindAttribLocation(shader program, 0, "vposition") However I have no idea how to rewrite geometry shader... version 130 uniform mat4 View uniform mat4 Projection layout (points) in layout (triangle strip, max vertices 4) out out vec2 txcoord void main() vec4 pos View gl PositionIn 0 .gl Position txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() The main problem is how to get rid of location here layout (points) in layout (triangle strip, max vertices 4) out Can someone help me? EDIT melak47 I edited shader, now I'm not getting any error, but window is black. version 130 extension GL EXT geometry shader4 enable precision mediump float uniform mat4 View uniform mat4 Projection out vec2 txcoord void main() vec4 pos View gl PositionIn 0 txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex() txcoord vec2( 1, 1) gl Position Projection (pos vec4(txcoord,0,0)) EmitVertex()


Knowing the size of a framebuffer when rendering transformed meshes to a texture I have a couple of 2D meshes that make a hierarchical animated model. I want to do some post processing on it, so I decided to render this model to a texture, so that I could do the post processing with a fragment shader while rendering it as a textured quad. But I don't suppose that it would be very smart to have the render texture's size as large as the entire screen for every layer that I'd like to compose it would be nicer if I could use a smaller render texture, just big enough to fit every element of my hierarchical model, right? But how am I supposed to know the size of the render target before I actually render it? Is there any way to figure out the bounding rectangle of a transformed mesh? (Keep in mind that the model is hierarchical, so there might be multiple meshes translated rotated scaled to their proper positions during rendering to make the final result.) I mean, sure, I could transform all the vertices of my meshes myself to get their world space screen space coordinates and then take their minima maxima in both directions to get the size of the image required. But isn't that what vertex shaders were supposed to to so that I wouldn't have to calculate that myself on the CPU? (I mean, if I have to transform everything myself anyway, what's the point of having a vertex shader in the first place? q ) It would be nice if I could just pass those meshes through the vertex shader first somehow without rasterizing it yet, just to let the vertex shader transform those vertices for me, then get their min max extents and create a render texture of that particular size, and only after that let the fragment shader rasterize those vertices into that texture. Is such thing possible to do though? If it isn't, then what would be a better way to do that? Is rendering the entire screen for each composition layer my only option?


Restart a 2D game OpenGL, GLUT I started learning OpenGL and GLUT by making a snake game. The problem I encountered is that when I press the "new game" in the menu, the window has to be resized so that the content of the window to be updated. From what I have read, it's because of the MainLoop that's waiting for an event, but I don't know how to fix it. I've tried with glutPostRedisplay, but it doesn't change anything maybe I'm placing it wrong. Here is the code associated with the restart of the game int main( int argc, char argv ) glutInit( amp argc, argv ) glutInitDisplayMode( GLUT DOUBLE GLUT RGB ) glutInitWindowSize( 800, 600 ) glutInitWindowPosition( 100, 100 ) glutCreateWindow( "Aarghhh! O ramaaa !" ) createMenu() glClearColor( 0.0, 0.0, 0.0, 0.0 ) init() glutReshapeFunc( reshape ) glutDisplayFunc( dreptunghi ) glutSpecialFunc( player ) glutMainLoop() return 0 void init( void ) glClearColor( 1.0, 1.0, 1.0, 0.0 ) glMatrixMode( GL PROJECTION ) gluOrtho2D( 0.0, 800.0, 0.0, 600.0 ) glShadeModel( GL FLAT ) void menu( int num ) if ( num 0 ) exit( 0 ) else if ( num 1 ) menu value num snake.clear() i 30.0 j 30.0 alpha 1.0 value 1 speed 3 eaten true collided food false collided self false createMenu() glClearColor( 0.0, 0.0, 0.0, 0.0 ) init() glutDisplayFunc( dreptunghi ) glutReshapeFunc( reshape ) glutSpecialFunc( player ) glutSwapBuffers() glutPostRedisplay() void createMenu( void ) glutCreateMenu( menu ) glutAddMenuEntry( "New game!", 1 ) glutAddMenuEntry( "Exit", 0 ) glutAttachMenu( GLUT RIGHT BUTTON ) I have also tried to write a function for the display of the menu, that's called using glutIdleFunc, but it didn't solve anything either. I have ran out of ideas.


Turning on Vertex Attribute Divisor With Instanced Rendering Renders Nothing When I render with glDrawArraysInstanced with the vertex attribute divisor set to zero, the triangle appears as expected. But when the divisor is set to any value other than zero, the triangle disappears. This is the code I am using to render static const u32 NUM TRIANGLES 1 struct Vertex f32 x f32 y static const Vertex g triangles NUM TRIANGLES 3 0.125f, 0.125f , 0.125f,0.125f , 0.125f, 0.125f , glGenVertexArrays(1, amp g vao) glBindVertexArray(g vao) glGenBuffers(1, amp g vbo) glBindBuffer(GL ARRAY BUFFER, g vbo) glBufferData(GL ARRAY BUFFER, sizeof(g triangles), nullptr, GL DYNAMIC DRAW) glBufferSubData(GL ARRAY BUFFER, 0, sizeof(g triangles), reinterpret cast lt const void gt ( amp g triangles)) glVertexAttribPointer(0, 2, GL FLOAT, GL FALSE, 0, reinterpret cast lt void gt (0)) glEnableVertexAttribArray(0) glVertexAttribDivisor(0, 1) Setting this to 0 renders the triangle This is the draw call glDrawArraysInstanced(GL TRIANGLES, 0, 3, NUM TRIANGLES) Here are my shaders version 420 core layout (location 0) in vec2 v void main() gl Position vec4(v, 0.0f, 1.0f) version 420 core out vec4 out color void main() out color vec4(1.0f,0.0f,0.0f,1.0f) My problem is similar to OpenGL 2D instancing glDrawArraysInstanced with a divisor renders nothing, but that question wasn't resolved.


Opengl Best VAO model for voxel engine I make a voxel engine on LWJGL 3 (OpenGL binding for JVM). I store all object data in world class. World is subdivided into 32 32 32 chunks. Chunks use octree storage. The main part of all my rendering is cubes that share one mesh but have different transformation matrices and some other data. To render those i use one VAO per chunk, it contains only one cube mesh instance and has all cubes data (like transformations) stored in its VBOs. I construct each chunk VAO once and render it fully in one call glDrawElementsInstanced. If i need to change some cube data in a chunk, i will reconstuct VAO from ground up or change individual buffer data. That should be pretty efficient, right ? But I need some other stuff to be rendered, like complex mesh objects or effects or some debug stuff. How should I render those objects ? Should I create a VAO for each mesh and then perform instanced rendering for each object with the same mesh ? Or should I batch all objects with their meshes into one VAO for each chunk and render it fully ? I was trying to create a VAO recently, that contained one instance of each mesh and all object data. But i could not render it correctly. Because each time I needed to somehow switch object data VBO while rendering an instanced mesh. It didn't work. Code for the last VAO http pastebin.com WanNsR5L


using heightmap to simulate 3d in an isometric 2d game I saw a video of an 2.5d engine that used heightmaps to do zbuffering. Is this hard to do? I have more or less no idea of Opengl(lwjgl) and that stuff. I could imagine, that you compare each pixel and its depthmap to the depthmap of the already drawn background to determine if it gets drawn or not. Are there any tutorials on how to do this, is this a common problem? It would already be awesome if somebody knows the names of the Opengl commands so that i can go through some general tutorials on that. greets! Great 2.5d engine with the needed effect, pls go to the last 30 seconds Edit, just realised, that my question wasn't quite clear expressed How can i tell Opengl to compare the existing depthbuffer with an grayscale texure, to determine if a pixel should get drawn or not?


How do I initialise levels sequentially? I have been learning opengl and I have made good progress over past few months. However I still struggle to understand game logic in C , I am new to C too. Say I have this program. include lt headers gt int main() Step 1 VAO VBO EBO inits() while(!glfwWindowShouldClose(window)) glClearColor(.2f, .2f, .3f, 1.f) glClear(GL COLOR BUFFER BIT) Step 2 DrawCalss() glfwPollEvents() glfwSwapBuffers(window) return 0 For OpenGL programmers this should be clear. With this structure, I have to load all levels and then draw part of them like so. Step 1 feeds the gpu the vertex data and its attributes. Step 2 binds shader programs and draws the vertices Say I have A, B, C, D levels, within VAO VBO EBO inits() function I have to load all A, B, C, D levels then within DrawCalss() function will draw only related levels. DrawCalss() function is dynamic but VAO VBO EBO inits() invoked only once. What I want to do is create separate game loops for each levels and be able to switch between levels, and as I switch levels preceding level should be unloaded and next level reloaded. Since I am new to C I don't know what way would be the most efficient, that's why I have not tried anything. How do I achieve it? what is the best practice for such scenarios?


Understanding ticksPerSecond and duration with skeletal animations That's my first question here so i hope to do all correctly. From various weeks i started surfing the net about Skeletal animation aiming to add a simple animation controller into my small game engine. After following a video tutorial by ThinMatrix, i successfully added skeletal animation into my engine (i used Assimp to load a .dae file from Blender with one animation in it). Once finished all the base stuff i started thinking about how to change animations speed by a factor (like x2 x3 etc...) and here i found some problems. As i think i understand every animation is measured by a duration field (in ticks) that, as i suppose, should be at least something like 25fps (to obtain some kind of smooth animation) times animation's length in seconds. Then for every animation there is also another field called ticksPerSecond that (as the name says) is the amount of ticks in every second. Into my engine i've a data structure called Animator that contains an array of Animation objects and for each one it has a ticks per second and duration array. The following code shows how i took data from assimp. animator gt ticks per second animation index scene gt mAnimations animation index gt mTicksPerSecond ! 0 ? scene gt mAnimations animation index gt mTicksPerSecond 25.f animator gt duration animation index scene gt mAnimations animation index gt mDuration If i print the two variables i get this result DEBUG ticks per sec 1.000000 DEBUG total ticks 0.833333 So here is my question Why do these variables take on these values? I am trying to explain it to myself and the idea I found is that if ticks is equal to 1 the animation would go at the same mainloop's frame rate but, at the end, I am not sure about it and I would appreciate your help.


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's matrix stack vs Hand multiplying Which is more efficient using OpenGL's transformation stack or applying the transformations by hand. I've often heard that you should minimize the number of state transitions in your graphics pipeline. Pushing and popping translation matrices seem like a big change. However, I wonder if the graphics card might be able to more than make up for pipeline hiccup by using its parallel execution hardware to bulk multiply the vertices. My specific case. I have font rendered to a sprite sheet. The coordinates of each character or a string are calculated and added to a vertex buffer. Now I need to move that string. Would it be better to iterate through the vertex buffer and adjust each of the vertices by hand or temporarily push a new translation matrix?


What is the convention for column major order matrix transformations? According to this cheat sheet for CG, if I want to use column major order for my matrix vector math I have to multiply from the left applying transformations from right to left, i.e. v' P V v I built my view and projection matrices like this Matrix44 view(right.x, right.y, right.z, position.x, up.x, up.y, up.z, position.y, forward.x, forward.y, forward.z, position.z, 0.0f, 0.0f, 0.0f, 1.0f) Matrix44 projection(Sx, 0.0f, 0.0f, 0.0f, 0.0f, Sy, 0.0f, 0.0f, 0.0f, 0.0f, Sz, Pz, 0.0f, 0.0f, 1.0f, 0.0f) However, when using them in the vertex shader gl Position projection view vec4(position, 1.0) I cannot see my geometry unless I swap the transformation to gl Position vec4(position, 1.0) view projection which means that I am using row major order instead of column order. So my question is if the pdf I'm following is correct in the notation for the column major order for view and projection matrices or what am I missing?


Blending vs Texture Sampling Lets say I want to blend two textures together A texture containing the result of the SSAO calculation. A texture containing the rendered scene. I could do it in two ways Use a shader that samples both the SSAO and scene textures, blends them together and outputs the final color to a render target. Render to the texture containing the scene and use a blending mode to blend the SSAO texture on top of it. Only the SSAO texture will be sampled inside the shader. Is it possible to give a general answer about which version is faster, or is it highly hardware dependent?


Input before or after update draw? This is how I understood the game loop, and I wanted to know if I'm correct or not 1) Draw render gt input CPU GPU Update Draw Input Rendering 2) Input gt Draw render CPU GPU Input Update Draw (nothing?) Rendering By rendering I mean updating the actual frame. What happens in the second case? Is the CPU doing nothing or is it checking input for the next frame already? Are there any differences from checking input before or after the update draw part?


Drawing many separate lines using mouse OpenGL(GLFW glad) So, in order to draw a line, I track the coordinates of the mouse, then I add them to the array and capture it as GL LINE STRIP ADJACENCY. However, for example, I completed drawing a line1 at P1 and decided to start drawing a different line at P2 as shown in the figure, but my two points P1 and P2 joined together, how to fix it? Need to clear the array after drawing at the point P1, actually it doesn't help if I use glClearColor and glClear(GL COLOR BUFFER BIT).. Is there any other way?


Missing any kind of lights? I am trying to make my first 3D game in OpenGL with Shaders (LWJGL3) I read and follow a lot of tutorials but can't figure it out what kind of light I am missing here? The wall doesn't get any effect from the light It is supposed to be like this one And my point light part in fragment vec4 calcLightColour(vec3 light colour, float light intensity, vec3 position, vec3 to light dir, vec3 normal) vec4 diffuseColour vec4(0, 0, 0, 0) vec4 specColour vec4(0, 0, 0, 0) Diffuse Light float diffuseFactor max(dot(normal, to light dir), 0.0) diffuseColour diffuseC vec4(light colour, 1.0) light intensity diffuseFactor Specular Light vec3 camera direction normalize( position) vec3 from light dir to light dir vec3 reflected light normalize(reflect(from light dir , normal)) float specularFactor max( dot(camera direction, reflected light), 0.0) specularFactor pow(specularFactor, specularPower) specColour speculrC light intensity specularFactor material.reflectance vec4(light colour, 1.0) return (diffuseColour specColour) vec4 calcPointLight(PointLight light, vec3 position, vec3 normal) vec3 light direction light.position position vec3 to light dir normalize(light direction) vec4 light colour calcLightColour(light.colour, light.intensity, position, to light dir, normal) Apply Attenuation float distance length(light direction) float attenuationInv light.att.constant light.att.linear distance light.att.exponent distance distance return light colour attenuationInv


How do I create a 2D tile map, and implement movement within it? How do I create a 2D tile map that I can use? How do I get the world coordinates of it so I can move something to that tile? I'm learning OpenGL, at the moment, but I'm having a lot of issues understanding how to create a 2D tile map. I have rendered tiles to the world, but I have no way of using them. For example, I'm trying to implement movement, where when clicking on a tile, I would move the player to that tile. To elaborate, I want a tiles coordinates when I click near on it, so I can use that position when implementing movement. Right now, I have no idea how to do that I am able to get the windows 2D coordinates on click, but I don't know how to turn that into a useful way of finding the coordinates I want based on where my tile is in the world.


3D position of an arbitrary UV coordinate I have a UV map for a 3D mesh that encodes "links" between pairs of UV coordinates. I have previously defined this links (or pairs), one to one. The links are enconded using the function rgb color(u1, v1) (u2, v2, 0.0). Therefore, in the fragment shader, given UV coordinates of the current fragment, I can get the UV coordinates of the fragment "linked" with the current one. What I want to do is to draw this links in the 3D space(i.e. draw a line between the current fragment with texture coordinates (u1, v1) and its "link" texture coordinate (u2,v2). As far as I know this is a hard problem to solve because in the fragment shader you cannot access to the 3D coordinates (u2,v2). Edit Notice that the UV map is fragmented, therefore you cannot just draw this lines in the UV domain. Do you have any idea how to approach this problem?


How can I avoid the precision loss when recentering objects on open terrain? For a better context this question is related to this one What 39 s the largest quot relative quot level I can make using float? When the player is moving too far away from the center, all the scene and objects are moved in the opposite direction, in order to bring the center closer to the player and avoid float precision issues. Recentering all objects makes me doubt a little, since it might still accumulate error since it's an addition. I also don't think I can tell a physics engine to just teleport all its object without causing weird behavior.


Do glColorMask and glDrawBuffer accomplish the same thing? I'm doing a shadowmap pass (only storing depth values) so I set glDrawBuffer(GL NONE) to disable color writing for the moment. Yet, I see some tutorials also do glColorMask(GL FALSE, GL FALSE, GL FALSE, GL FALSE). Is this really necessary, given glDrawBuffer(GL NONE)? Don't they accomplish the same thing?


Why are all OpenGL function calls prefixed with "q" in the Doom 3 source code? Why is every OpenGL call prefixed with a "q" in the Doom 3 source code? Are they custom functions or a different library, and if so, why use that over OpenGL? Any Google search comes up with the Qt OpenGL module, which I assume has nothing to do with it.


For deferred rendering and SSAO, what coordinate system are the normals actually in? So, I'm following the very helpful LearnOpenGL online tutorials, and I'm working on implementing SSAO. I don't have a deferred rendering pipeline, but I need to collect normals during my depth pass so that I can sample them for the SSAO effect. I'm following this tutorial https learnopengl.com Advanced Lighting SSAO, and referencing this one when needed https learnopengl.com Advanced Lighting Deferred Shading. However, neither of these tutorials really explain what's going on with the normals. What is the normalMatrix being used in the shader? mat3 normalMatrix transpose(inverse(mat3(view model))) Normal normalMatrix (invertedNormals ? aNormal aNormal) I'm not worried about the invertexNormals conditional, that's probably just something weird the author added for handling different conventions, but what the heck is going on with that normalMatrix? Why would we invert the view model matrix? If we're starting with aNormal in object space (whether it's coming directly from a vertex buffer or from a normal map TBN calculation), I can't for the life of me figure out what coordinate system that resulting normal is going to end up in! So, long story short, what coordinate frame should my normals be in if I'm to use them for SSAO? World space? View Space? Clip space? None of the above? If it's some weird coordinate system, can somebody help me get there? I'm probably more confused than I should be.


My model is drawn wrong in 3d I'm learning OpenGL and now after I made everything I needed, I started with 3D, my first problem is that my mesh doesn't draw like I intended... Here's my rectangle (uses GL TRIANGLES) std vector lt GLfloat gt Vpos 0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 0.5, 0.5, 0.0 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 comms are the 3d version And here I draw my array glDrawArrays(GL TRIANGLES, 0, verNum 2) it is binded with vertex array, I use shaders And my fragment shader is version 330 in vec2 passTextureCoords out vec4 outColor uniform sampler2D ourTexture void main() outColor vec4(0.0, 1.0, 0.5, 1.0) texture(ourTexture, passTextureCoords) I don't have a texture so I use a lightgreen for debug proposes Also my vertex shader version 330 layout (location 0) in vec3 inVertPos layout (location 1) in vec2 inTexCoords out vec2 passTextureCoords void main() gl Position vec4(inVertPos.x, inVertPos.y, inVertPos.z, 1.0) passTextureCoords inTexCoords Thanks for help by now, I pretty sure that I missed something small but important.


How can I render "two sided" clouds like in Minecraft? The clouds in Minecraft are semi transparent and are rendered on both sides. If you fly into the cloud you can see inside of the cloud. If I render clouds the inside faces would be visible on the outside. How can I prevent that? Z Ordering the faces and render near to far with depth test on? There must be a better, easier way. Could the accum or stencil buffers be used somehow? UPDATE I think the crucial point everyone is forgetting is that these clouds and semi transparent and "blended" into the scene as each face is rendered. If two faces are rendered on top of each other the "white" texture will double up which is undesired. The faces also seem to have slight lighting variations which would rule out using a stencil. UPDATE2 Just another note. Each cloud is 12x12x4 blocks (roughly). Larger clouds are just a group of the base clouds stuck together. Here's showing clouds from above. They are translucent and the chunks below can be seen. And here's the view from inside them.


First encounter with dynamic lighting I have a game idea with lots of pretty lights (literally) in mind that I would really love to implement, but I have essentially zero experience with shadow mapping, deferred rendering, the lot of it. I've done some research into 2D shadow casting, and I think I might try a method similar to this, but I haven't a fathom how to create a virtual rectangular manipulation of a polar image (from the point light's perspective on the map). My question How can I create a virtual rectangular manipulation of a polar image whose process is quick enough that it can be run twice per frame every time a light moves in game? I'd like to be able to handle at least 4 dynamic lights on screen at any time, but I'll take what I can get. I've started to learn OpenGL, so hopefully this isn't too high above my skill level.


Perspective Matrix doesn't work OpenGL 4 I tried to implement my own perspective matrix and it doesn't work. I don't understand why. With just with my view matrix (without Perspective Matrix) I can see my mesh. Here my view matrix Vec3f position(0.0,0.0, 5.0) Vec3f target(0.0,0.0,0.0) Mat4f Camera LookAt(Vec3f target, Vec3f position) ce dont j'ai besoin pour calculer les parametre de ma camera... Vec3f up world Vec3f(0.0,1.0,0.0) Vec3f forward (position target).normalize() Vec3f right up world.cross(forward).normalize() Vec3f up forward.cross(right).normalize() Mat3f R R.setCol(2,forward) R.setCol(0,right) R.setCol(1,up) R.transpose() Mat4f R4(R) Vec3f mp position 1.0f Mat4f P4 P4.setCol(3,mp) LookAt R4 P4 return LookAt And my Perspective Matrix Mat4f Camera perspective(float fovy, float aspect, float zNear, float zFar) float theta fovy 0.5f (180.f M PI) float range zFar zNear float invtan 1.f tanf(theta) Mat4f projMat(invtan aspect, 0.0f, 0.0f, 0.0f, 0.0f, invtan, 0.0f, 0.0f, 0.0f, 0.0f, (zFar zNear) range, 2 zNear zFar range, 0.0f, 0.0f, 1.0f, 0.0f) perspectiveCam projMat std cout lt lt perspectiveCam lt lt std endl return perspectiveCam Mat4f perspective(float fovy M PI 2, float aspect (1280.f 720.f) 1.f, float zNear 0.1f, float zFar 100.f) My shader is very simple so it can't be the problem.. version 410 core layout(location 0) in vec3 V position layout(location 1) in vec3 V color layout(location 2) in vec3 V normal uniform mat4 view matrix uniform mat4 proj matrix out vec3 color void main() color V color gl Position proj matrix view matrix vec4(V position, 1.) when I initialise perspectiveCam with the unit matrix 4x4 it displays my triangle.. but when I implement perspectiveCam like in the function it does not display my triangle Here my Set col function template lt typename TYPE gt void Mat4 lt TYPE gt setCol(int i, Vec4 lt TYPE gt amp vec4) for (size t k 0 k lt 4 k ) setElement(k,i, vec4.getElement(k)) void setElement(int i,int j, TYPE var) element i 4 j var TYPE getElement(int i, int j) const return element i 4 j


how to do partial updates in OpenGL? It is general wisdom that you redraw the entire viewport on each frame. I would like to use partial updates what are the various ways can do that, and what are their pros, cons and relative performance? (Using textures, FBOs, the accumulator buffer, any kind of scissors that can affect swapbuffers etc?) A scenario a scene with a fair few thousand visible trees although the textures are mipmapped and they are drawn via VBOs roughly front to back with so on, its still a lot of polys. Would streaming a single screen sized texture be better than throwing them at the screen every frame? You'd have to redraw and recapture them only on camera movement or as often as your wind model updates or whatever, which need not be every frame.


Does one need normals for a strictly 2d Game? I'm starting to learn OpenGL by creating a pure 2D game. I have to decide on the format of the Vertices. Do I need a normal component? Or is this for a 2d component not needed? My gut feeling says I won't need it since everything is flat. But perhaps I need it for some shader or other thing I don't see yet.


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


OpenGL App not setting cursor position appropriately I have written a small application using OpenGL, and have implemented some rudimentary camera controls. Unfortunately, I cannot get the application to set my cursor position correctly. The cursor is never set to where I tell it to go, so my application just reacts to where the cursor is on my entire screen. I first attempted to use GLFW, and when I saw that I couldn't set the cursor appropriately, I decided to try SFML. Neither one works. I'm on an Arch Linux install with a Gnome desktop. I've been trying to figure this out for a few days now to no avail. The relevant code is as follows sf Vector2i cursor pos sf Mouse getPosition( window) sf Mouse setPosition(sf Vector2i(1280 2, 720 2), window) This gets called every frame inside a function that messes with some matrices. I also set the cursor position at initialization. Any hints or advice would be greatly appreciated.


OpenGL Disable Anti Alias I can't find anything on how to hint to the driver to disable any antialias. I'm using a very minimal passthrough setup yet I notice my driver is still doing what looks like MSAA. I want to disable this, or at least give a strong hint to disable it, so to save performance. As I will be doing deferred rendering with my own SSAA.


physics model simulation I am building a game for which I want to simulate certain rigid body dynamics.Could someone suggest me some engines which work on Ubuntu.Also as I have dont have much time to implement it,so it would be helpful if it is a easy one to work with. I have some across one namely ODE.Am looking for others which would help me simulate collisions and angular movements.


Are buffers in OpenGL associated with GLSL programs? I have two different shader programs in my OpenGL code. 1 renders simple font using freetype 2 simple shader which draw primitive shapes. I sent both of them some data using buffers, I understood that they are stored on server side, but are they associated with different programs? or any program can use any buffer data by just using gBindBuffer() ?


How can I use ARB debug output with SDL on Windows? I'm trying to port a small GL program that I've been working on from Linux to Windows. I have the following window SDL CreateWindow(...) SDL GL SetAttribute(SDL GL CONTEXT FLAGS, SDL GL CONTEXT DEBUG FLAG) glContext SDL GL CreateContext(window ) glewInit() if (GLEW ARB debug output) glDebugMessageCallbackARB( amp DebugCallback, nullptr) I was surprised to find out that GLEW ARB debug output evaluates to false. Could it be that ARB debug output not supported on Windows, with the latest drivers for my video card (an older Radeon HD540v)? Am I doing anything wrong? I thought this extension was rather old, and it would probably be supported everywhere by now. Update I added my SDL initialization code, as I needed to pass SDL GL CONTEXT DEBUG FLAG. Unfortunately, ARB debug output is still not supported. Update After initializing the context with the debug flag through SDL, I manually queried the available extensions (bypassing GLEW) and ARB debug output is not available! Again, could this not be supported on my implementation?


OpenGL multiple mesh management I've been working on coding a new 3D engine in Java. For the moment at least I'm sticking to openGL... Currently I'm reworking how meshes get transformed and then drawn. ATM each mesh created has its own VBO and IBO along with its own draw method so if I wanted to draw multiple meshes it would look like this mesh1 MeshLoader.loadMesh("cube.obj") mesh2 MeshLoader.loadMesh("pyramid.obj") mesh1.addToBuffers() adds vertex and index data to vbo and ibo mesh2.addToBuffers() mesh1.draw() mesh2.draw() The draw method defined in class Mesh enables vertex attribute arrays, binds the bufffers, and then draws elements based on the ibo. Then I send my projection matrix (transformation and perspective) as a uniform to the vertex shader. QUESTION Games are made of many many meshes and each has to be identified so that transformation can be applied. I want to be able to apply transformations (translate, rotate, scale) directly to a given mesh, independent of the other meshes. In other words I want to move mesh1 and only mesh1 5 units to the right (on its own axis) without it affecting mesh2. How do I do all this without making a million draw calls to the gpu? Any advice appreciated.


I want to render some surfaces in GLSL with normal maps, and some without I have normal mapping working in my game, but I want to only use normal mapping for some surfaces, and not others. Right now, as far as I can tell, my shader is applying an incorrect normal of (0, 0, 0) in tangent space to my non normal mapped surfaces, since no textures are bound to the sampler. Is there a suitable way of detecting that nothing is bound to a sampler in GLSL and then using a flat normal instead? I've also found old posts around the web recommending the following Using a dummy 1x1 texture with the color (128, 128, 255) this will lose Phong interpolation. Switching shader programs for normal mapped and non normal mapped surfaces I get the feeling that I'd end up duplicating a lot of code this way, especially when I start implementing specular maps, parallax displacement maps, etc. Are either of these still recommended or is there a new feature to query the sampler that I could make use of? Should I be doing it one way over another for performance reasons? Here is my fragment shader version 330 core in vec2 UV in vec3 tangentSpaceLightDir out vec4 outColor uniform sampler2D diffuseMap, normalMap void main (void) vec4 texel texture(diffuseMap, UV) vec4 ntexel texture(normalMap, UV) I want to use vertex normal here, if nothing is bound. vec3 N normalize(ntexel.xyz 2.0 1.0) vec3 L normalize(tangentSpaceLightDir) float lambertTerm dot(N, L) vec4 finalColor vec4(0.0) if (lambertTerm gt 0.0) finalColor vec4(lambertTerm, 1.0) outColor finalColor texel


Process of writing to the depth texture In openGL, let's say I output one single point from the vertex shader with this value gl Position vec4(2.0,3.0,5.0,7.0) what exact math operations happen to "z" after leaving the vertex shader? what will be the end value of that depth texel?


Providing texture coordinates and using indexed drawing at the same time Please consider the following vertex structure struct vertex vec3 posL, normalL Using this vertex layout, we can provide the vertex data in an interleaved way, i.e. (posL,normalL),(posL',normalL'),... This works pretty fine in combination with indexed drawing via glDrawElements(). However, if we add texture coordinates to our vertex structure, i.e. consider struct vertex vec3 posL, normalL vec2 tex things get more complicated. Since one and the same vertex (meaning it's position) may participate in a variety of different faces with varying texture coordinates, I wondered how one would provide such vertex data to the vertex buffer. One solution would be to quit storing the data interleaved and provide it a linear way, i.e. (posL,posL',...),(normalL,normalL',...),(tex,tex',...) where each tuple has the same length. Doing so, we would hold related things together (i.e. the k th element of each tuple forms exactly one input the vertex shader sees). But we would push much more data to the pipeline than necessary. So, what's the "ideal" solution to this problem? If one suggests to use different buffers, how does the vertex shader know, that texture coordinate tex at position i in Buffer 2 corresponds to the tuple (posL,normalL) at position j in Buffer 1?


OpenGL first person camera orientation issues I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function private void camera() glRotatef(xrot, 1.0f, 0.0f, 0.0f) glRotatef(yrot, 0.0f, 1.0f, 0.0f) The keyboard function if (Keyboard.isKeyDown(Keyboard.KEY D)) xpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY A)) xpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY W)) zpos 0.03f delta if (Keyboard.isKeyDown(Keyboard.KEY S)) zpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY UP)) xrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY DOWN)) xrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY RIGHT)) yrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY LEFT)) yrot 0.035 if (xrot gt 360) xrot 360 And my translate function glTranslated(xpos, ypos, zpos 30) any ideas on how to solve this? I would be very grateful


Getting the number of fragments which passed the depth test In "modern" environments, the "NV Occlusion Query" extension provides a method to get the number of fragments which passed the depth test. However, on the iPad iPhone using OpenGL ES, the extension is not available. What is the most performant approach to implement a similar behaviour in the fragment shader? Some of my ideas Render the object completely in white, then count all the colors together using a two pass shader where first a vertical line is rendered and for each fragment the shader computes the sum over the whole row. Then, a single vertex is rendered whose fragment sums all the partial sums of the first pass. Doesn't seem to be very efficient. Render the object completely in white over a black background. Downsample recursively, abusing the hardware linear interpolation between textures until being at a reasonably small resolution. This leads to fragments which have a greyscale level depending on the number of white pixels where in their corresponding region. Is this even accurate enough? Use mipmaps and simply read the pixel on the 1x1 level. Again the question of accuracy and if it is even possible using non power of two textures. The problem wit these approaches is, that the pipeline gets stalled which results in major performance issues. Therefore, I'm looking for a more performant way to accomplish my goal. Using the EXT OCCLUSION QUERY BOOLEAN extension Apple introduced EXT OCCLUSION QUERY BOOLEAN in iOS 5.0 for iPad 2. "4.1.6 Occlusion Queries Occlusion queries use query objects to track the number of fragments or samples that pass the depth test. An occlusion query can be started and finished by calling BeginQueryEXT and EndQueryEXT, respectively, with a target of ANY SAMPLES PASSED EXT or ANY SAMPLES PASSED CONSERVATIVE EXT. When an occlusion query is started with the target ANY SAMPLES PASSED EXT, the samples boolean state maintained by the GL is set to FALSE. While that occlusion query is active, the samples boolean state is set to TRUE if any fragment or sample passes the depth test. When the occlusion query finishes, the samples boolean state of FALSE or TRUE is written to the corresponding query object as the query result value, and the query result for that object is marked as available. If the target of the query is ANY SAMPLES PASSED CONSERVATIVE EXT, an implementation may choose to use a less precise version of the test which can additionally set the samples boolean state to TRUE in some other implementation dependent cases." The first sentence hints on a behavior which is exactly what I'm looking for getting the number of pixels which passed the depth test in an asynchronous manner without much performance loss. However, the rest of the document describes only how to get boolean results. Is it possible to exploit this extension to get the pixel count? Does the hardware support it so that there may be hidden API to get access to the pixel count? Other extensions which could be exploitable would be debugging features like the number of times the fragment shader was invoked (PSInvocations in DirectX not sure if something simila is available in OpenGL ES). However, this would also result in a pipeline stall.


What happen if I try to run OpenGL 4.4 code on an unsupported graphic card? I'm learning OpenGL because I'd like to build my own engine. I'd like to know what happens if I try to run OpenGL 4.4 code (the latest version at the moment of writing) on an unsupported graphic card ? (I mean for example a graphic card that support up to 4.1 OpenGL). Does it fails even to start ? or, it start but fails to render ? Thank you very much.


Is FreeGLUT still a good choice? I recently decided to utilize the C library called FreeGLUT to have a window be managed from my program, where I can draw things via OpenGL. But at the same time I saw some people telling that it is an old library, not that much reliable and so on... Should I keep using that or move to another one?


How do I convert from Cartesian to spherical coordinates? This seems like a fairly basic and common problem. Is there a builtin way to achieve it or do I have to write the algorithm on my own? If I do, how should it work?


Is linear filtering possible on depth textures in OpenGL? I'm working on shadow maps in OpenGL (using C ). First, I've created a framebuffer and attached a depth texture as follows Generate the framebuffer. var framebuffer 0u glGenFramebuffers(1, amp framebuffer) glBindFramebuffer(GL FRAMEBUFFER, framebuffer) Generate the depth texture. var shadowMap 0u glGenTextures(1, amp shadowMap) glBindTexture(GL TEXTURE 2D, shadowMap) glTexImage2D(GL TEXTURE 2D, 0, GL DEPTH COMPONENT24, 1024, 1024, 0, GL DEPTH COMPONENT, GL FLOAT, null) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glFramebufferTexture2D(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL TEXTURE 2D, shadowMap, 0) Set the read and draw buffers. glDrawBuffer(GL NONE) glReadBuffer(GL NONE) Later (after rendering to the shadow map and preparing the main scene), I sample from the shadow map in a GLSL fragment shader as follows float shadow texture(shadowMap, shadowCoords.xy).r Where vec3 shadowCoords is the coordinates of the fragment from the perspective of the global directional light source (the one used to create the shadow map). The result is shown below. As expected, shadow edges are jagged due to using GL NEAREST filtering. To improve smoothness, I tried replaced the shadow map's filtering with GL LINEAR, but the results haven't changed. I understand there are other avenues I could take (like Percentage Closer Filtering), but I'd like to answer this question first, if only for my sanity. I've also noticed that other texture parameters (like GL CLAMP TO EDGE rather than GL REPEAT for wrapping) don't function for the shadow map, which hints that this may be a limitation of depth textures in general. To reiterate Is linear filtering possible using depth textures in OpenGL?


Textures "don't work" when I don't specify any texture parameters. Is this a driver bug or intended behavior? Whenever I try to use textures, I have to at least specify the sample filtering parameters (GL TEXTURE MAG FILTER, GL TEXTURE MIN FILTER) for textures to work at all. If I don't, sampling the textures in a shader will usually just return a value of 0 for all texels in the texture, even though glReadPixels return the correct values, and rendering to the textures actually works. Debugging tools like Nsight and gDebugger confirm this. I tested this on two NVIDIA GPUs (GTX 970, GT 555m) with the latest driver versions (347.09), and the behavior is the same. However, I can't find any reference to this in docs like this or this I assumed that not specifying these parameters just made them take on their default values. So is this actually intended standard behavior (probably meaning "undefined behavior") or can I assume this is a driver bug?


draw fog of war using shaders I am making a RTS game, and I'd like some advice on how to best render fog of wars, given what I'm already doing. You can imagine this game as being a classic RTS like Age of Empires 2, where the fog of war will basically be handled by a 2D array telling if a given "tile" is explored or not. The specific things to consider here are 1) I'm only doing a few draw calls to draw the whole screen, using shaders, and I'm not drawing "tile by tile" in a 2D loop 2) The whole map is much bigger than the screen, and the screen can move every frame or so In that case, how could I draw the fog of war ? I have no issue maintaining on the CPU side a 2D array giving the fog of war for each tile, but what would be the best way to actually display it dynamically ? thanks!


Engine and level of detail for maze labyrinth dungeon scene? My question is similar to these Algorithm for generating a 2d maze To scene graph or not to scene graph? I.e. in this case should I use jME3 or some other engine (I heard Unreal offers a free engine) for a 3D dungeon game and when I build up the dungeon, should I use an algorithm for a new dungeon every time or should I use a static scene? I've code to build a small wall that adds it to my scene which is mostly programmaticly achieved with less 3D modelling and more algorithmic solutions This loop builds a wall out of individual bricks. public void initWall() float startpt brickLength 4 float height 0 for (int j 0 j lt 15 j ) for (int i 0 i lt 6 i ) Vector3f vt new Vector3f(i brickLength 2 startpt, brickHeight height, 10) makeBrick(vt) startpt startpt height 2 brickHeight This method creates one individual physical brick. public void makeBrick(Vector3f loc) Create a brick geometry and attach to scene graph. Geometry brick geo new Geometry("brick", box) brick geo.setMaterial(wall mat) rootNode.attachChild(brick geo) Position the brick geometry brick geo.setLocalTranslation(loc) Make brick physical with a mass gt 0.0f. brick phy new RigidBodyControl(2f) Add physical brick to physics space. brick geo.addControl(brick phy) bulletAppState.getPhysicsSpace().add(brick phy)