Rotate OpenGL quad around its center Sorry, I searched it but couldn't figure how to apply it to my code reading the other answers to similar questions. I what to rotate a quad, my code is the following glEnable(GL TEXTURE 2D) glBindTexture(GL TEXTURE 2D, player texture) glBegin(GL QUADS) glColor4ub(255, 255, 255, 255) glTexCoord2d(0,0) glVertex2f(hero.xValue(), hero.yValue()) glTexCoord2d(1,0) glVertex2f(hero.xValue() hero.lValue(), hero.yValue()) glTexCoord2d(1,1) glVertex2f(hero.xValue() hero.lValue(), hero.yValue() hero.hValue()) glTexCoord2d(0,1) glVertex2f(hero.xValue(), hero.yValue() hero.hValue()) glEnd() glDisable(GL TEXTURE 2D) I'm not sure about how to use the glTranslatef function, I tell it what is the center of my object? In that case it would be hero.xValue() hero.lValue() 2 (x) and hero.yValue() hero.hValue() 2 (y) I know I have to use both glTranslatef and glRotate, by the way. When I try, setting glTranslatef with the values I mentioned above, I get a texture floating far from where the hero actually is. Any help on this matter will be appreciated, thank you. Obs hValue height, lValue lenght Edit New information to show the changes I made after user55564's comment I call init() once, on there I set basic openGL and SDL stuff, among them glViewport(0, 0, WIDTH, HEIGHT) glMatrixMode(GL MODELVIEW) then I call my draw function, it has in it while (running) glLoadIdentity() . . stuff non related to drawing . glClear(GL COLOR BUFFER BIT) glClearColor(0, 0, 0, 0) glPushMatrix() glOrtho(0, WIDTH, HEIGHT, 0, 1, 1) draws the player glEnable(GL TEXTURE 2D) glBindTexture(GL TEXTURE 2D, player texture) glTranslatef(hero.xValue(), hero.yValue(), 0) glRotatef(0, 0, 0, 1) glTranslatef( (hero.xValue() hero.lValue() 2), (hero.yValue() hero.hValue() 2), 0) glBegin(GL QUADS) glColor4ub(255, 255, 255, 255) glTexCoord2d(0,0) glVertex2f(hero.xValue(), hero.yValue()) glTexCoord2d(1,0) glVertex2f(hero.xValue() hero.lValue(), hero.yValue()) glTexCoord2d(1,1) glVertex2f(hero.xValue() hero.lValue(), hero.yValue() hero.hValue()) glTexCoord2d(0,1) glVertex2f(hero.xValue(), hero.yValue() hero.hValue()) glEnd() glDisable(GL TEXTURE 2D) glPopMatrix() then I use pushmatrix again to draw the enemies and the health bars of both enemies and player (these don't need rotation) glPushMatrix() glOrtho(0, WIDTH, HEIGHT, 0, 1, 1) . . .


How to access an uniform array with a float as index in GLSL? I'm trying to do basic multitexturing of terrain in OpenGL. Im building the terrain with an image representing different elements (beach, water, jungle...) Im trying to map each color of this image with a texture in my game green color means grassTexture (id 0), blue color means waterTexture (id 1), etc... My fragment shader contains an uniform array containing all textures that I use (grass, water, ...) Terrain.frag uniform sampler2D terrainTextures 50 For each vertex of the terrain, I pass a float in TextureId corresponding to a texture id Terrain.vert layout (location 0) in vec3 in Vertex layout (location 1) in vec4 in Color layout (location 2) in vec3 in Normal layout (location 3) in vec2 in TexCoord layout (location 4) in float in TextureId Then im trying to display the correct texture for a vertex with this textureId in the fragment shader outputColor texture(terrainTextures int(textureId) , texCoord) With this line, I have this result If I modify the code of the fragment shader with the following code highp int tid int(textureId) if(tid 2) outputColor texture(terrainTextures int(textureId) , texCoord) else if(tid 1) outputColor texture(terrainTextures int(textureId) , texCoord) else outputColor texture(terrainTextures int(textureId) , texCoord) It works better I can't understand why it's working with this code, i'm doing exactly the same thing in the first example. Maybe it's not the good way to access an uniform array ?


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


Failed to understand how to use glm unProject (OpenGL 4.3) Situation I use OpenGL 4.3, FreeGLUT 3.0, and GLM library. Let say i have a simple 2D object (a ball) and it moves accordingly to the simple equations x x 0 v 0 t cosf(alpha) y y 0 v 0 t sinf(alpha) 0.5 g t t So i can be sure what are x and y in every time step. My GLUT mouse callback is void onMouse(int button, int state, int mx, int my) if (state ! GLUT DOWN) return view glm lookAt(glm vec3(0.0, 0.0, 10.0), glm vec3(0.0, 0.0, 0.0), glm vec3(0, 1, 0) projection glm perspective(45.0f, 1.0f 640 480, 0.1f, 10.0f) glm vec4 viewport glm vec4(0, 0, 640, 480) glm vec3 wincoord glm vec3(mx, 480 my, 0.0f) glm vec3 objcoord glm unProject(wincoord, view, projection, viewport) So, when the ball moves and i click on it, i suppose to get (objcoord.x, objcoord.y) very close to the center of the ball (x,y). Coordinates of the ball itself (x,y) are calculated correctly. But when i click on the ball, (objcoord.x, objcoord.y) are not even close to the (x,y). I always get very small values like (0.0012, 0.099) wherever i click on the screen. I feel that it might be due to some Z (depth) issues, but i don't have enough knowledge here and ask for help now.


Multisampled Texture i have some doubts with multisampled textures. In fragment shader, how to pass multiple samples? We use glTexImage2DMultisample instead of glTeximage2D. so, how to upload texture data? I want to use default FBO for this.


Simple OpenGL program major slow down at high resolution I have created a small OpenGL 3.3 (Core) program using freeglut. The whole geometry is two boxes and one plane with some textures. I can move around like in an FPS and that's it. The problem is I face a big slow down of fps when I make my window large (i.e. above 1920x1080). I have monitors GPU usage when in full screen and it shows GPU load of nearly 100 and Memory Controller load of 85 . When at 600x600, these numbers are at about 45 , my CPU is also at full load. I use deferred rendering at the moment but even when forward rendering, the slow down was nearly as severe. I can't imagine my GPU is not powerful enough for something this simple when I play many games at 1080p (I have a GeForce GT 120M btw). Below are my shaders, First Pass VS version 330 core uniform mat4 ModelViewMatrix uniform mat3 NormalMatrix uniform mat4 MVPMatrix uniform float scale layout(location 0) in vec3 in Position layout(location 1) in vec3 in Normal layout(location 2) in vec2 in TexCoord smooth out vec3 pass Normal smooth out vec3 pass Position smooth out vec2 TexCoord void main(void) pass Position (ModelViewMatrix vec4(scale in Position, 1.0)).xyz pass Normal NormalMatrix in Normal TexCoord in TexCoord gl Position MVPMatrix vec4(scale in Position, 1.0) FS version 330 core uniform sampler2D inSampler smooth in vec3 pass Normal smooth in vec3 pass Position smooth in vec2 TexCoord layout(location 0) out vec3 outPosition layout(location 1) out vec3 outDiffuse layout(location 2) out vec3 outNormal void main(void) outPosition pass Position outDiffuse texture(inSampler, TexCoord).xyz outNormal pass Normal Second Pass VS version 330 core uniform float scale layout(location 0) in vec3 in Position void main(void) gl Position mat4(1.0) vec4(scale in Position, 1.0) FS version 330 core struct Light vec3 direction uniform ivec2 ScreenSize uniform Light light uniform sampler2D PositionMap uniform sampler2D ColorMap uniform sampler2D NormalMap out vec4 out Color vec2 CalcTexCoord(void) return gl FragCoord.xy ScreenSize vec4 CalcLight(vec3 position, vec3 normal) vec4 DiffuseColor vec4(0.0) vec4 SpecularColor vec4(0.0) vec3 light Direction normalize(light.direction) float diffuse max(0.0, dot(normal, light Direction)) if(diffuse 0.0) DiffuseColor diffuse vec4(1.0) vec3 camera Direction normalize( position) vec3 half vector normalize(camera Direction light Direction) float specular max(0.0, dot(normal, half vector)) float fspecular pow(specular, 128.0) SpecularColor fspecular vec4(1.0) return DiffuseColor SpecularColor vec4(0.1) void main(void) vec2 TexCoord CalcTexCoord() vec3 Position texture(PositionMap, TexCoord).xyz vec3 Color texture(ColorMap, TexCoord).xyz vec3 Normal normalize(texture(NormalMap, TexCoord).xyz) out Color vec4(Color, 1.0) CalcLight(Position, Normal) Is it normal for the GPU to be used that much under the described circumstances? Is it due to poor performance of freeglut? I understand that the problem could be specific to my code, but I can't paste the whole code here, if you need more info, please tell me.


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.


Making a HUD GUI with OpenGL (LWJGL) I'm at the stage in my game development where I need to make a HUD or GUI. I've never gotten to this part, so I don't know how its done. I tried rendering a simple quad at a fixed position on the screen, but there's a problem. To make my camera work with orthographic, I use this public void lookThrough() GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() GL11.glOrtho(position.x, position.x Display.getDisplayMode().getWidth() zoom, position.y Display.getDisplayMode().getHeight() zoom, position.y, 1, 1) GL11.glMatrixMode(GL11.GL MODELVIEW) I don't see how I would be able to make something fixed on the screen using this method? Any way around this? Thanks )


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


Am I allowed to make my Minecraft clone open source? I'm developing in my spare time a game like Minecraft. In fact, it isn't "like Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL. So, my question is am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch. A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft). If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this http www.minecraft.net terms Edit There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.


std map for storing static const Objects I am making a game similar to Minecraft, and I am trying to fine a way to keep a map of Block objects sorted by their id. This is almost identical to the way that Minecraft does it, in that they declare a bunch of static final Block objects and initialize them, and then the constructor of each block puts a reference of that block into whatever the Java equivalent of a std map is, so there is a central place to get ids and the Blocks with those ids. The problem is, that I am making my game in C , and trying to do the exact same thing. In Block.h, I am declaring the Blocks like so Block.h public static const Block Vacuum static const Block Test And in Block.cpp I am initializing them like so Block.cpp const Block Block Vacuum Block("Vacuum", 0, 0) const Block Block Test Block("Test", 1, 0) The block constructor looks like this Block Block(std string name, uint16 id, uint8 tex) Check for repeat ids if (IdInUse(id)) fprintf(stderr, "Block id u is already in use!", (uint32)id) throw std runtime error("You cannot reuse block ids!") id id Check for repeat names if (NameInUse(name)) fprintf(stderr, "Block name s is already in use!", name) throw std runtime error("You cannot reuse block names!") name name tex tex fprintf(stdout, "Using texture u n", tex) transparent false solidity 1.0f idMap id this nameMap name this And finally, the maps that I'm using to store references of Blocks in relation to their names and ids are declared as such std map lt uint16, Block gt Block idMap std map lt uint16, Block gt () The map of block ids std map lt std string, Block gt Block nameMap std map lt std string, Block gt () The map of block names The problem comes when I try to get the Blocks in the maps using a method called const Block GetBlock(uint16 id), where the last line is return idMap.at(id) . This line returns a Block with completely random values like visibility 0xcccc and such like that, found out through debugging. So my question is, is there something wrong with the blocks being declared as const obejcts, and then stored at pointers and accessed later on? The reason I cant store them as Block amp is because that makes a copy of the Block when it is entered, so the block wouldn't have any of the attributes that could be set afterwards in the constructor of any child class, so I think I need to store them as a pointer. Any help is greatly appreciated, as I don't fully understand pointers yet. Just ask if you need to see any other parts of the code.


Just how expensive is it to bind textures in OpenGL? (LibGDX) I'm using LibGDX on top of OpenGL and currently my game engine does something along the lines of the following per frame Bind a terrain texture sprite atlas and a set of transparency masks in another texture atlas Render terrain tiles using the 2 bound textures to a FBO Bind a character and item texture sprite atlas Render characters over the terrain to the same FBO Bind the same transparency mask atlas and a normal map texture for the terrain Draw the same terrain tiles' normal map version to a different FBO Bind the character and item normal map texture atlas Render character normal maps over the terrain normal map FBO Bind this normal map FBO as a texture Render lighting information to a different FBO using the normal map texture information Bind the diffuse and lighting FBOs as textures Use these to render the combined final image to the main display So in summary, each frame I'm binding a total of 9 different textures, one or two at a time. Should I look into changing my code so all 9 textures are always bound, and the correct one is referenced at the right time? Or is this a reasonable amount of texture binds per frame that isn't going to impact overall performance to a noticable effect? Assume I'm aiming for 60fps and there's a fair amount of other calculations going on per frame.


Is "pure" OpenGL productive enough? I know that this is a difficult question and I hope I can convey my meaning. Over time I've used many different engines from XNA over Unity to Panda3d and even tried native directX once. My final impression is that an engine basically serves to do this implement a scene graph offer classes like actor to add them to the scene graph implement an asset pipeline that exports to actors or something similar allow for custom logic scripts that hook onto the engine and are called at the right times. In Unity you can override update() in panda3d you can add methods to the taskmanager that are then called repeatedly. In Jmonkey they are called controls. It's basically the same. Additionally you can listen to physics events and the like. then there's work done under the hood physics, rendering and networking. I appreciate all of these points very much and acknowledge the comfort a good engine can offer. The problem is I'd like to create a game in a comparably young language (Google's Go) and there's no engine out there yet. Bindings for OpenGL exist and I figure I could easily hack a little engine of my own together. The points one, two and four are not too difficult. I'd do the rendering with custom shaders anyways so that's work that has to be done in any case. For now I don't need complex physics and the standard raycast and collision check wouldn't be too hard for me. The only problem is an asset pipeline because I've got no experience in processing 3d data at all. I've only lived on the programmatical side up to now and the 3d models I've used were admittedly ugly. In the end it will probably add up to a weekend of coding and ongoing maintaining work. The bottom line is I don't have to use go but then again there's no deadline for the project and I figured it might be fun to use this language. Is anyone out there still using "pure" OpenGL and can tell me about the work that lies ahead? Have you ever done this before? Do you think that low level OpenGL is a too complex choice for a one man team or does the work to hack together something of my own pay off in the end ? EDIT You might want to read the comments below Nicol Bolas post since they explain the question a little better.


Do Java and Actionscript use OpenGL? As far as I know there are only 3 base graphics libraries on Windows, the GDI, OpenGL and DirectX, is that correct, so that means that Java, Actionscript and all language use one of these 3 libraries if they are to display graphics, or maybe Java has it's own graphics library API?


What is Vulkan and how does it differ from OpenGL? Khronos Group (the standards body behind OpenGL) has just announced Vulkan Vulkan is the new generation, open standard API for high efficiency access to graphics and compute on modern GPUs. This ground up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability. Their page is quite marketese jargon heavy, as is the press release In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.) What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement. Update The Vulkan 1.0 spec was released on 16 02 2016.


alpha test shader 'discard' operation not working GLES2 I wrote this shader to illustare alpha test action in GLES2 (Galaxy S6). I think is not working at all cause I don't see any change with or without it. Is there anything Im missing? Any syntax error? I know its better not using if in shader but for now this is the solution I need. precision highp float precision highp int precision lowp sampler2D precision lowp samplerCube 0 CMPF ALWAYS FAIL, 1 CMPF ALWAYS PASS, 2 CMPF LESS, 3 CMPF LESS EQUAL, 4 CMPF EQUAL, 5 CMPF NOT EQUAL, 6 CMPF GREATER EQUAL, 7 CMPF GREATER bool Is Alpha Pass(int func,float alphaRef, float alphaValue) bool result true if (func 0) result false break if (func 1) result true break if (func 2) result alphaValue lt alphaRef break if (func 3) result alphaValue lt alphaRef break if (func 4) result alphaValue alphaRef break if (func 5) result alphaValue ! alphaRef break if (func 6) result alphaValue gt alphaRef break if (func 7) result alphaValue gt alphaRef break return result void FFP Alpha Test(in float func, in float alphaRef, in vec4 texel) if (!Is Alpha Pass(int(func), alphaRef, texel.a)) discard


How can I set the attribute index location? I am trying to set up a shader which takes three input parameters. I have the following code GLuint vert glCreateShader(GL VERTEX SHADER) GLuint frag glCreateShader(GL FRAGMENT SHADER) const GLchar vertsrc src.vertex.c str() const GLchar fragsrc src.fragment.c str() glShaderSource(vert, 1, amp vertsrc, NULL) glShaderSource(frag, 1, amp fragsrc, NULL) glCompileShader(vert) glCompileShader(frag) GLuint program glCreateProgram() glAttachShader(program, vert) glAttachShader(program, frag) glBindAttribLocation(program, 0, "position") if (glGetError() ! GL NO ERROR) ... glBindAttribLocation(program, 1, "normal") if (glGetError() ! GL NO ERROR) ... glBindAttribLocation(program, 2, "texcoord") if (glGetError() ! GL NO ERROR) ... glLinkProgram(program) ...check linking errors auto p glGetAttribLocation(program, "position") auto n glGetAttribLocation(program, "normal") auto t glGetAttribLocation(program, "texcoord") GL MAX VERTEX ATTRIBS is 16. I don't understand why, after this code executes, the values I get from glGetAttribLocation are as follows p 0 n 1 t 1 Needless to say, I am unable to pass anything beyond vertex attrib array no. 0 to my shader. What am I doing wrong?


Anti Aliasing in OpenGL C I'm trying to make anti aliasing work inside of OpenGL, here's what I've tried glEnable(GL POINT SMOOTH) glHint(GL POINT SMOOTH HINT, GL NICEST) glEnable(GL LINE SMOOTH) glHint(GL LINE SMOOTH HINT, GL NICEST) glEnable(GL POLYGON SMOOTH) glHint(GL POLYGON SMOOTH HINT, GL NICEST) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) But so far none of these have worked. I have gotten antialiasing to work by enabling it on the control panel for my video card (Catalyst Control Center in my case), but I would like to get it working inside my program instead. This is what the rendering looks like with 4x antialiasing enabled via the video card control panel And this is what it looks like when I do it with my program How do I get antialiasing to work?


Problems when rendering code on Nvidia GPU I am following OpenGL GLSL cookbook 4.0, I have rendered a tesselated quad, as you see in the screenshot below, and i am moving Y coordinate of every vertex using a time based sin function as given in the code in the book. This program, as you see on the text in the image, runs perfectly on built in Intel HD graphics of my processor, but i have Nvidia GT 555m graphics in my laptop, (which by the way has switchable graphics) when I run the program on the graphic card, the OpenGL shader compilation fails. It fails on following instruction.. pos.y sin.waveAmp sin(u) giving error Error C1105 Cannot call a non function I know this error is coming on the sin(u) function which you see in the instruction. I am not able to understand why? When i removed sin(u) from the code, the program ran fine on Nvidia card. Its running with sin(u) fine on Intel HD 3000 graphics. Also, if you notice the program is almost unusable with intel HD 3000 graphics, I am getting only 9FPS, which is not enough. Its too much load for intel HD 3000. So, sin(X) function is not defined in the OpenGL specification given by Nvidia drivers or something else??


Can I directly pass a Boost ptr vector list to glBufferData? I have a data structure like this typedef struct vertex float x float y float z float s float t vertex Then I add to a list called boost ptr vector lt vector gt vertices Is there a way to use vertices to provide the parameters for glBufferData?


moving glDepthMask into a shader Can a fragment shader make per fragment decisions on whether the fragment updates the depth buffer or not, even if the fragment is not discarded and the color is written?


gl VertexID values when calling glDrawElements I am struggling a bit to understand the values that gl VertexID primitive contains when the vertex shader is executed. I have the standard modern rendering pipeline, in which after setting up shaders, buffers, etc I call the code below to render a mesh glBindBuffer(GL ELEMENT ARRAY BUFFER, auxMesh gt indicesBuffer) glDrawElements(GL TRIANGLES, auxMesh gt numIndices, GL UNSIGNED INT, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) In the vertex shader I want to manually access to the current vertex being rendered retrieving it from the original buffer (I know this sounds nonsense, but I need to do this for a reason), therefore I pass the vertex buffer as the texture buffer u tbo tex and I access to the actual coordinates as follows vec3 vertex 1 texelFetch(u tbo tex, gl VertexID 0).xyz vec3 vertex 2 texelFetch(u tbo tex, gl VertexID 1).xyz vec3 vertex 3 texelFetch(u tbo tex, gl VertexID 2).xyz And the values of these vertex vertex 1, vertex 2, vertex 3 make perfect sense. However, I can't really understand what values gl VertexID got in each iteration. Is gl VertexID sequentially assigned following the range of 0...auxMesh gt numIndices . Or are the values increased 3 at every iteration because I am drawing triangles? I need to understand this because I am interested in calling textureFetch(u tbo tex, i) where i is a arbitrary triangle in my mesh (or whatever i needs to be to access an arbitrary triangle), but I can't find the right way to access to it.


OpenGL draw functions and multi threading. How they work together? I want to apply multi thread in a simple way to control and draw 4000 objects. I am using SDL and OpenGL. control locations, collisions, calculations ... etc draw OpenGL draw functions glDrawArrays,glDrawElements etc For 4000 objects i think like this do you think it works ?


Why nearby triangles tend to disappear? I've just enabled back face culling and I'm noticing a weird behavior when all vertices of my triangle is outside the view and 2 of them is behind me (I think) the triangle disappears. So to see it, here is a GIF. I suspect the projection matrix reverses the order of the two vertices when they fall behind me, and changes the winding of my triangle. But it's unclear why does the triangles disappear only if all vertices out of view... How can I work around this problem, if possible? I develop on Linux if that matters. UPDATE It's pointed out it might not be due to the back face culling. I disabled it and I can indeed reproduce it. The cubes are 20 20 and the vertical field view is 90 . Its vertical apparent size roughly fills the window. UPDATE 2 Ok I'll post the relevant part of the code, projection and view matrixes are set up using my own functions void createViewMatrix( GLfloat matrix 16 , const Vector3 forward, const Vector3 up, const Vector3 pos ) Setting up perpendicular axes Vector3 rright Vector3 rup up Vector3 rforward forward vbonorm( amp rright, amp rup, amp rforward) Orthonormalization (right is computed from scratch) Filling the matrix matrix 0 rright.x matrix 1 rup.x matrix 2 rforward.x matrix 3 0 matrix 4 rright.y matrix 5 rup.y matrix 6 rforward.y matrix 7 0 matrix 8 rright.z matrix 9 rup.z matrix 10 rforward.z matrix 11 0 matrix 12 vdp(pos, amp rright) matrix 13 vdp(pos, amp rup) matrix 14 vdp(pos, amp rforward) matrix 15 1 void createProjectionMatrix( GLfloat matrix 16 , GLfloat vfov, GLfloat aspect, GLfloat near, GLfloat far ) GLfloat vfovtan 1 tan(RAD(vfov 0.5)) memset(matrix, 0, sizeof( matrix) 16) matrix 0 vfovtan aspect matrix 5 vfovtan matrix 10 (near far) (near far) matrix 11 1 matrix 14 (2 near far) (near far) Projection matrix set up with this call createProjectionMatrix(projMatrix, VERTICAL FOV, ASPECT RATIO, Z NEAR, 10000) (VERTICAL FOV 90, ASPECT RATIO 4.0 3, Z NEAR 1) Level drawing is simply void drawStuff() GLfloat projectView 16 glClearColor(0, 0, 0, 1) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) createViewMatrix(viewMatrix, amp camera.forward, amp camera.up, amp camera.pos) multiplyMatrix(projectView, viewMatrix, projMatrix) lt Row mayor multiplication. glUniformMatrix4fv(renderingMatrixId, 1, GL FALSE, projectView) bailOnGlError( FILE , LINE ) renderLevel( amp testLevel) Cubes are rendered wall by wall (optimizing this will be another story) for (j 0 j lt 6 j ) glBindTexture(GL TEXTURE 2D, cube gt wallTextureIds j ) bailOnGlError( FILE , LINE ) glDrawElements(GL TRIANGLE FAN, 4, GL UNSIGNED INT, (void )(sizeof(GLuint) 4 j)) bailOnGlError( FILE , LINE ) glUniform4f(extraColorId, 1, 1, 1, 1) bailOnGlError( FILE , LINE ) Vertex shader version 110 attribute vec3 position attribute vec3 color attribute vec2 texCoord varying vec4 f color varying vec2 f texCoord uniform mat4 renderingMatrix void main() gl Position renderingMatrix vec4(position, 1) f color vec4(color, 1) f texCoord texCoord Fragment shader version 110 varying vec4 f color varying vec2 f texCoord uniform sampler2D tex uniform vec4 extraColor void main() gl FragColor texture2D(tex, f texCoord) vec4(f color) extraColor The depth buffer simply set up by enabling it.


Opengl mutiple texture in a shader Im using modern opengl and c . How do I draw a number of triangles each one having a different texture in one draw call when I only have 32 texture units on my graphics card and the max texture size is 1024? My video card has 2gb of memory yet it can only hold 32 texture at a time? Why do graphics cards have this limitation? I'm a c programmer and in c you don't have restrictions like that. The only restriction that you have is how much RAM you have which is fine.


OpenGL never reverts to default FrameBuffer So I'm trying to change the texture using FBOs, When I run it, The whole game gets drawn in the new FBO that I created then deleted, Here's the function public void ChangeTextureBuffer(int width, int height, ByteBuffer newBuffer) int frameID glGenFramebuffers() glBindFramebuffer(GL FRAMEBUFFER BINDING, frameID) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, ID, 0) glViewport(0, 0, width, height) Texture texture new Texture(width, height, newBuffer) glBindTexture(GL TEXTURE 2D, texture.ID) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f( 1, 1) glTexCoord2f(1, 0) glVertex2f(1, 1) glTexCoord2f(1, 1) glVertex2f(1, 1) glTexCoord2f(0, 1) glVertex2f( 1, 1) glEnd() texture.Delete() glDeleteFramebuffers(frameID) glBindTexture(GL TEXTURE 2D, 0) glBindFramebuffer(GL FRAMEBUFFER BINDING, 0) And here's what I'm getting It's getting drawn where I want it to be with the size that I want, I just don't want everything to be drawn there. Also when I delete a texture or framebuffer, OpenGL isn't reusing the id, I don't know if that's a feature or a bug. EDIT Here's how its supposed to look, Everything getting drawn in its place, I just want to change the text on the bottom left side to show the FPS


physically based shading, how to combine specular diffuse parts? After writing 'standard' phong amp blinn shaders for a while, I recently started to dabble in physically based shading. A resource that helped me a lot are these course notes, especially this paper it explains how to make blinn more shading physically plausible. I implemted the blinn model propsed in the paper, and I really like how it looks. The most significant change proposed ( imo ) is the inclusion of the fresnel reflectance, and this is also the part that gives me problems. Unfortunately, the author chose to focus on the specular part only, omitting diffuse reflectance. Given e.g. a lambertian diffuse reflection, I just don't know how to combine it with the 'improved' blinn because just adding diffuse amp specular parts does not seem to be right any more. In some shaders I've seen a floating point 'fresnel term' in range 0 1 being used, based on the indices of refraction of the participating media. Schlick's approximation is used every time float schlick( in vec3 v0, in vec3 v1, in float n1, in float n2 ) float f0 ( n1 n2 ) ( n1 n2 ) f0 f0 return f0 ( 1 f0 ) pow( dot( v0, v1 ), 5 ) Doing it like this, one can then linearly interpolate between diffuse and specular contribution based on the fresnel term, e.g. float fresnel schlick( L, H, 1.0002926 air , 1.5191 other material ) vec3 color mix( diffuseContrib, specularContrib, fresnel ) In the paper, the author states that this approach is incorrect because it basically just darkens the specular color whenever L is parallel or nearly parallel to H and that instead of computing a f0 based on the indices of refraction, you should treat the specular color itself as f0 and have your schlick approximation compute a vec3, like this vec3 schlick( in vec3 v0, in vec3 v1, in vec3 spec ) return spec ( vec3( 1.0 ) spec ) pow( dot( v0, v1 ), 5 ) This results in the specular color going towards white at glancing angles. Now my question is, how would I introduce a diffuse component into this? At 90 the specular contribution is fully white, this means all incoming light is reflected, so there can't be a diffuse contribution. For incidence angles lt 90 , can I just multiply the whole diffuse part with ( vec3( 1 ) schlick ), i.e. the proportion of light that isn't reflected? vec3 diffuseContrib max( dot( N, L ), 0.0 ) kDiffuse ( vec3( 1.0 ) schlick( L, H, kSpec ) ) Or do I need a completely different approach?


OpenGL SFML GLFW3 I'am maybe asking a stupid question, but can we mix OpenGl SMFL and add to it some GLFW in the same SFML window ?


How to use multiple custom vertex attributes in OpenGL My code currently uses glBindAttribLocation and glVertexAttribPointer to specify two custom vertex attributes in indices 6 and 7. This seems to work fine, but I wish to add another attribute and no index other than 6 or 7 will work the shader instead acts like the attribute is always set to a value of 0. I'm using gl Vertex, gl Normal, gl Color and gl MultiTexCoord0, and apparently some nVidia thing means indices 0, 2, 3 and 8 are off limits, but that should still leave other indices. I don't use gl SecondaryColor or gl FogCoord anywhere in my code or shaders for example, but indices 4 and 5 still don't work. If I change graphics cards for an ATI one which supports more than 16 attributes, then indices 16 work fine, but I want to support cards with only 16 attributes.


OpenGL concatenate vertex data into one big VBO I successfully can render two triangles (with a texture) that looks like the side of a crate and also "walk" around it. Also, a small .obj file parser is available which gives me a float array of the vertices, texture coords and an unsigned int array of the indices (of a simple cube). The vertices and texture coords look like the following float vertices positions texture coords 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f And the indices unsigned int indices 0, 1, 3, first triangle 1, 2, 3 second triangle To assign the vertices and tex coords I use the following unsigned int VBO glGenBuffers( 1, amp VBO ) glBindBuffer( GL ARRAY BUFFER, VBO ) glBufferData( GL ARRAY BUFFER, 5 4 sizeof( float ), vertices, GL STATIC DRAW ) Creating an IBO call glEnableVertexAttribArray() glVertexAttribPointer() Creating a shader, a texture etc.. and draw it with glDrawElements(). This works all very well, I just can't wrap my head around how to use just a single VBO with the "split" data that my .obj parser gives back. I now (when using the .obj parser) have the vertices and texture coords separated how do I put that two arrays into one VBO? The picture I have in mind is to have fewer draw calls and also prevent redundant code if I, for example, use the same model for 100 times.


Frame Buffer Object (FBO) is not working. What is the right way to use? I am trying to use FBO but i am living some problems. I will show you my steps but first i will show my running screen ,so we can compare them. Like before fbo after fbo. My running screen and Draw() function code glClearColor(0.5,0.5,0.5,1.0) glLoadIdentity() glTranslatef(0.0,0.0, 3.0) glRotatef(0,0.0,1.0,0.0) glUniform3f(glGetUniformLocation(mainShader gt getProgramId(),"lightPos"),0,1,2) mainShader gt useShader() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) scene gt draw(mainShader gt getProgramId()) mainShader gt delShader() After I tried to add FBO Create FBO texture function unsigned int createTexture(int w,int h,bool isDepth false) unsigned int textureId glGenTextures(1, amp textureId) glBindTexture(GL TEXTURE 2D,textureId) glTexImage2D(GL TEXTURE 2D,0,(!isDepth ? GL RGBA8 GL DEPTH COMPONENT),w,h,0,isDepth ? GL DEPTH COMPONENT GL RGBA,GL FLOAT,NULL) glTexParameteri(GL TEXTURE 2D,GL TEXTURE MAG FILTER,GL NEAREST) glTexParameteri(GL TEXTURE 2D,GL TEXTURE MIN FILTER,GL NEAREST) glTexParameteri(GL TEXTURE 2D,GL TEXTURE WRAP S,GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D,GL TEXTURE WRAP T,GL CLAMP TO EDGE) int i i glGetError() if(i! 0) std cout lt lt "Error happened while loading the texture " lt lt i lt lt std endl glBindTexture(GL TEXTURE 2D,0) return textureId Init() function void init() glClearColor(0,0,0,1) glMatrixMode(GL PROJECTION) glLoadIdentity() gluPerspective(50,640.0 480.0,1,1000) glMatrixMode(GL MODELVIEW) glEnable(GL DEPTH TEST) mainShader new shader("vertex.vs","fragment.frag") quadRenderShader new shader("quadRender.vs","quadRender.frag") scene new meshLoader("test.blend") renderTexture createTexture(640,480) depthTexture createTexture(640,480,true) glGenFramebuffers(1, amp FBO) glBindFramebuffer(GL FRAMEBUFFER,FBO) GL COLOR ATTACHMENT0 GL DEPTH ATTACHMENT glFramebufferTexture2D(GL FRAMEBUFFER,GL COLOR ATTACHMENT0,GL TEXTURE 2D,renderTexture,0) glFramebufferTexture2D(GL FRAMEBUFFER,GL DEPTH ATTACHMENT,GL TEXTURE 2D,depthTexture,0) int i glCheckFramebufferStatus(GL FRAMEBUFFER) if(i! GL FRAMEBUFFER COMPLETE) std cout lt lt "Framebuffer is not OK, status " lt lt i lt lt std endl glBindFramebuffer(GL FRAMEBUFFER,0) And Draw() function void display() rendering to texture... glClearColor(0.5,0.5,0.5,1.0) glLoadIdentity() glTranslatef(0.0,0.0, 3.0) glRotatef(0,0.0,1.0,0.0) glUniform3f(glGetUniformLocation(mainShader gt getProgramId(),"lightPos"),0,1,2) mainShader gt useShader() glBindFramebuffer(GL FRAMEBUFFER,FBO) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) scene gt draw(mainShader gt getProgramId()) glBindFramebuffer(GL FRAMEBUFFER,0) mainShader gt delShader() glClearColor(0.0,0.0,0.0,1.0) render texture to screen glLoadIdentity() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) quadRenderShader gt useShader() glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D,depthTexture) glUniform1i(glGetUniformLocation(quadRenderShader gt getProgramId(),"texture"),0) quad gt draw(quadRenderShader gt getProgramId()) quadRenderShader gt delShader() and Result only drawing last setup color (glClearColor) so black Result should be like in tutorial Note I know tutorial monkey is purple but it is not problem.


HDR Tone Mapping choosing parameters I implement HDR in my graphics engine (deferred rendering) based on this document link I save a luminance in a texture (RGBA16F) this way const float delta 1e 6 vec3 color texture(texture0, texCoord).xyz float luminance dot(color, vec3(0.2125, 0.7154, 0.0721)) float logLuminance log(delta luminance) fragColor vec4(logLuminance, logLuminance, 0.0, 0.0) first channel stores max luminance during a minification process Then I can calculate an average luminance and find a max luminance. The delta 1e 6. Is that a good choice ? Can I calculate "a" (equation 2) dynamically to achieve better results ?


Is it possible to access vertex values of an object created using display lists? I wanted to learn to develop games so started with tetris. I encountered a problem right in the beginning. My game is 20 ready. There are five types of shapes viz YELL, BOX, LINE, TEE, YEL which are shapes of different kinds. I created five display lists like this define YELL 1 define BOX 2 define LINE 3 define TEE 4 define YEL 5 int bs 20 void defineshapes() glNewList(YELL,GL COMPILE) glPushMatrix() glTranslated( bs,0,0) glColor3fv(color color1 ) glBegin(GL POLYGON) glVertex2i(0,0) glVertex2i(bs,0) glVertex2i(bs, bs) glVertex2i(0, bs) glEnd() glTranslated(bs,0,0) glColor3fv(color color2 ) glBegin(GL POLYGON) glVertex2i(0,0) glVertex2i(bs,0) glVertex2i(bs, bs) glVertex2i(0, bs) glEnd() glTranslated(bs,0,0) glColor3fv(color color3 ) glBegin(GL POLYGON) glVertex2i(0,0) glVertex2i(bs,0) glVertex2i(bs, bs) glVertex2i(0, bs) glEnd() glTranslated( 2 bs, bs,0) glColor3fv(color color4 ) glBegin(GL POLYGON) glVertex2i(0,0) glVertex2i(bs,0) glVertex2i(bs, bs) glVertex2i(0, bs) glEnd() glPopMatrix() glEndList() glNewList(BOX,GL COMPILE) glPushMatrix() ..... and randomly picking one like this srand(time(NULL)) color1 rand() 6 color2 rand() 6 color3 rand() 6 color4 rand() 6 defineshapes() randshape rand() 5 1 and drawing in display function like this void display() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glPushMatrix() glTranslated(x2,y2,0) glCallList(randshape) glPopMatrix() glFlush() I expected problem in the beginning itself when i used the display lists because i had to access the vertex values(x,y) of the shapes to check if they might overlap with another block below before moving them down. Is there a way of knowing the vertex values of objects drawn using display lists. I encountered the same problem once before when i needed to create a tyre of a car. I wanted the tyre to be painted with colors so created a mesh by rotating a circle again using display lists. Then i needed to know the values of the intersection points of longitudes and latitudes which i didnt know how to get so i abandoned that task. A YELL looks like this What is the easiest method of getting around this problem. I am sure OpenGL has a way of getting this done but i am new to it.


Does Java support OpenGL by itself? Note This is long but I explaining everything that you need to know. Don't read half way through it and say "What's the question?". It's simple but long and I need help as soon as possible. So I asked a question not long ago that was similar but it wasn't my best work. What I'm trying to do is make a small jar with no other files but the jar (maybe natives if needed) that handles a window and graphics for games. I'm making this for some people I know who don't want to get into advanced graphics and stuff to make games, plus I figure it would be easier to stick everything they need into one jar that they know how to use. Anyway I found JOGL but after like the past 3 hours or so all I got with JOGL was the memory to never use it because it's a pain to install (at least for me) and everyone says a different way to install it and I need like 100 files along with my jar to get it to work. So since I'm not dealing with JOGL i figured that it's best to try and find something else. So does anyway know any way to get OpenGL into java without libraries that add more files and if so just like 1 file? I'm trying to get it so it's just that jar and nothing else. I just want this done but I'm very confused. I would also like it to be able to run on Windows, Linux and Mac. I only have a Windows machine although I can get Linux to test it on and I know someone who has a Mac but keep in mind I'm building it on a Windows machine. So my question really is how would I be able to stick OpenGL (I would like OpenAL and maybe OpenCL too) in a single jar and nothing else? I have a few exceptions such as I'm kinda ok if I need a few natives but I don't want 10 jars and 50 natives and I need it to work on all kind of machines, and also I would like to be able to use swing to handle the window.


OpenGL have object follow mouse I want to have an object follow around my mouse on the screen in OpenGL. (I am also using GLEW, GLFW, and GLM). The best idea I've come up with is Get the coordinates within the window with glfwGetCursorPos. The window was created with window glfwCreateWindow( 1024, 768, "Test", NULL, NULL) and the code to get coordinates is double xpos, ypos glfwGetCursorPos(window, amp xpos, amp ypos) Next, I use GLM unproject, to get the coordinates in "object space" glm vec4 viewport glm vec4(0.0f, 0.0f, 1024.0f, 768.0f) glm vec3 pos glm vec3(xpos, ypos, 0.0f) glm vec3 un glm unProject(pos, View Model, Projection, viewport) There are two potential problems I can already see. The viewport is fine, as the initial x,y, coordinates of the lower left are indeed 0,0, and it's indeed a 1024 768 window. However, the position vector I create doesn't seem right. The Z coordinate should probably not be zero. However, glfwGetCursorPos returns 2D coordinates, and I don't know how to go from there to the 3D window coordinates, especially since I am not sure what the 3rd dimension of the window coordinates even means (since computer screens are 2D). Then, I am not sure if I am using unproject correctly. Assume the View, Model, Projection matrices are all OK. If I passed in the correct position vector in Window coordinates, does the unproject call give me the coordinates in Object coordinates? I think it does, but the documentation is not clear. Finally, to each vertex of the object I want to follow the mouse around, I just increment the x coordinate by un 0 , the y coordinate by un 1 , and the z coordinate by un 2 . However, since my position vector that is being unprojected is likely wrong, this is not giving good results the object does move as my mouse moves, but it is offset quite a bit (i.e. moving the mouse a lot doesn't move the object that much, and the z coordinate is very large). I actually found that the z coordinate un 2 is always the same value no matter where my mouse is, probably because the position vector I pass into unproject always has a value of 0.0 for z. Edit The (incorrectly) unprojected x values range from about 0.552 to 0.552, and the y values from about 0.411 to 0.411.


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


How to adapt a webgl shader using mouse position to have symmetrical behaviour I'm trying to create a particular kind of effect for the background of my SpriteKit game, and I've found some shaders on shadertoy that are close to what I want, but I'm struggling to adapt them to do exactly what I want.. There are a few shaders that simulate the sun with atmospheric scattering based on its xy position. here are some examples https www.shadertoy.com view MsVSWt https www.shadertoy.com view MdtXD2 I want something similar to this effect but I want the glow to be symmetrical, so that when the 'sun' reaches close to bottom or top edge the glow effect is at a maximum, and when it is in the centre it is at a minimum. I've been playing with these shaders trying to get this effect but my understanding of webgl is clearly lacking as I'm struggling to achieve this. What I've tried playing with is replacing variables such as sunPosition.y with abs(sunPosition.y) my logic being that the y axis ranges from 1 to 1 so I should be able to get symmetry by making everything positive.. but this in fact has no effect. If someone can nudge me in the right direction would be greatly appreciated as I'm now thoroughly confused by webgl!


How to generate a RGB a texture for a glow effect in GLSL? I would like to create a glow effect in GLSL, there is a tutorial that explains how we multiply RGB a I have some questions is it an operation that is in a fragment shader, where RGBa is calculated each frame, and then we apply the blur at the end of the shader? The whole process in the same shader, called each frame? Or can we multiply RGBa in a separate process at the beginning of the game and send this texture to the fragment that will blur the result? I have tried to translate the informations I found, but I am a beginner with the shaders, could someone put me on the right track here? Should we use a "buffer"? Here is my starting code GLuint CreateBufferForMixAB() unsigned char data GLuint bindingPoint 1, mixTex, buffer glGenTextures( 1, amp mixTex ) glBindTexture( GL TEXTURE 2D, mixTex ) data (unsigned char )malloc( width height ) ...imageTex.rgb alphaTex.rgb... glGenBuffers(1, amp buffer) glBindBuffer(GL UNIFORM BUFFER, buffer) glBufferData(GL UNIFORM BUFFER, sizeof(mixTex), mixTex, GL DYNAMIC DRAW) glBindBufferBase(GL UNIFORM BUFFER, bindingPoint, buffer) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, data) Thanks


OpenGL VBO or glBegin() glEnd()? I recently was given this link to a tutorial site from someone who I gave the original OGL Redbook to. The third header down says distinctly to forget glBegin() amp glEnd() as the typical render method. I learned via the Redbook's method, but I see some benefit in VBOs. Is this really the way to go, and if so, is there a way to easily convert the render code, and subsequent shaders, into VBOs and subsequent datatypes?


Queries regarding Geometry Shaders I am dealing with geometry shaders using GL ARB geometry shader4 extension. My code goes like GLfloat vertices 0.5,0.25,1.0, 0.5,0.75,1.0, 0.5,0.75,1.0, 0.5,0.25,1.0, 0.6,0.35,1.0, 0.6,0.85,1.0, 0.6,0.85,1.0, 0.6,0.35,1.0 glProgramParameteriEXT(psId, GL GEOMETRY INPUT TYPE EXT, GL TRIANGLES) glProgramParameteriEXT(psId, GL GEOMETRY OUTPUT TYPE EXT, GL TRIANGLE STRIP) glLinkProgram(psId) glBindAttribLocation(psId,0,"Position") glEnableVertexAttribArray (0) glVertexAttribPointer(0, 3, GL FLOAT, 0, 0, vertices) glDrawArrays(GL TRIANGLE STRIP,0,4) My vertex shader is version 150 in vec3 Position void main() gl Position vec4(Position,1.0) Geometry shader is version 150 extension GL EXT geometry shader4 enable in vec4 pos 3 void main() int i vec4 vertex gl Position pos 0 EmitVertex() gl Position pos 1 EmitVertex() gl Position pos 2 EmitVertex() gl Position pos 0 vec4(0.3,0.0,0.0,0.0) EmitVertex() EndPrimitive() Nothing is rendered with this code. What exactly should be the mode in glDrawArrays() ? How does the GL GEOMETRY OUTPUT TYPE EXT parameter will affect glDrawArrays() ? What I expect is 3 vertices will be passed on to Geometry Shader and using those we construct a primitive of size 4 (assuming GL TRIANGLE STRIP requires 4 vertices). Can somebody please throw some light on this ?


C OpenGL Game Timer Possible Duplicate Tips for writing the main game loop? I am attempting to make a game using OpenGL and C but i haven't been able to find any good tutorials..or anything that could assist me in setting up my main game loop with some kind of timer tick system...i would prefer to use as little external libraries as possible...i am using Win32 any help would be appreciated


Combining and drawing 2D lights in OpenGL I have progressed to the lighting portion of my little framework and I managed to solve a few initial problems so now I'm left with the subtle weirdnesses. At this stage I just have 2 lights the ambient daylight and a hard coded example light in my fragment shader (ultimately, I want to have multiple lights that I loop through adding together, and shadows would be nice too, but 1 step at a time!) uniform sampler2D u image varying vec2 v texCoords varying vec4 v position uniform vec3 ambient light set as (0.3, 0.3, 0.3), night! vec2 point light pos vec2( 0.4, 0.3) vec3 point light col vec3(0.999, 0.999, 0.999) float point light intensity 0.4 void main() vec4 frag color texture2D(u image, v texCoords) if(frag color.a lt 1.0) discard float distance distance(point light pos, v position.xy) float diffuse 0.0 if (distance lt point light intensity) diffuse 1.0 abs(distance point light intensity) gl FragColor vec4(min(frag color.rgb ((point light col diffuse) ambient light), frag color.rgb), 1.0) Which almost does what I want, but there are 2 problems The light has a bright ring in it and the light is squashed on the y axis. I actually like how it looks squashed at this ratio, but I'd much rather do it deliberately. I the y axis squashing is down to the window aspect ratio if the window is square, the light is circular, but I don't know how to fix this in the fragment shader. I don't know where the bright ring is coming from.


Performance issues with different types of uniform buffer I've tested different buffer layouts, because I'm confused about some performance issues. That are my test buffer (OpenGL 4.1, GLSL 410, GT 750M, MacBook Pro) Test 1 Using fixed struct buffer with unused variables inside struct SPerFrameUniformBufferVS vec4 m UnusedButPlaned1 vec4 m SometimesInUse2 vec4 m UnusedButPlaned3 vec4 m Used4 mat4 m Used5 mat4 m Used6 layout(row major, std140) uniform UPerFrameUniformBufferVS SPerFrameUniformBufferVS m PerFrameUniformBufferVS Test 2 Same buffer without unused variables struct SPerFrameUniformBufferVS vec4 m Used4 mat4 m Used5 mat4 m Used6 layout(row major, std140) uniform UPerFrameUniformBufferVS SPerFrameUniformBufferVS m PerFrameUniformBufferVS Test 3 Using fixed buffer with unused variables inside layout(row major, std140) uniform UPerFrameUniformBufferVS vec4 m UnusedButPlaned1VS vec4 m SometimesInUse2VS vec4 m UnusedButPlaned3VS vec4 m Used4VS mat4 m Used5VS mat4 m Used6VS Test 4 Same buffer without unused variables layout(row major, std140) uniform UPerFrameUniformBufferVS vec4 m Used4VS mat4 m Used5VS mat4 m Used6VS In my case i've the following performance results Test 1 40 FPS Test 2 55 FPS Test 3 46 FPS Test 4 60 FPS My application do 1558 draw and 2341 glGetUniformBlockIndex calls. glGetUniformBlockIndex seems to be the bottle neck, because it is much higher in Test 1 and Test 3.


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


Making a button that spawn objects in the world? I want to make a button that can spawn an object that I've already created. Though I have no clue how to actually do this where to start. Has anyone ever done something similar?


How to update vertices and indices in OpenGL I want to change and update the vertices and indices of the 3D object. I am new to openGL and I do not know if this the right place to ask this question. I searched and read about that, and I found that I should bind the VAO and VBO and make that, but nothing changed in vertices and indices. The vertices vector class type has the position, normal and uv coords and the vertices vector class type is int. I wonder how I can make changes to these two vectors when I translate or scale the model. here is the code Create buffers arrays glGenVertexArrays(1, amp this gt VAO) glGenBuffers(1, amp this gt VBO) glGenBuffers(1, amp this gt EBO) glBindVertexArray(this gt VAO) Load data into vertex buffers glBindBuffer(GL ARRAY BUFFER, this gt VBO) A great thing about structs is that their memory layout is sequential for all its items. The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm vec3 2 array which again translates to 3 2 floats which translates to a byte array. glBufferData(GL ARRAY BUFFER,this gt vertices.size() sizeof(vertex), amp this gt vertices 0 , GL STATIC DRAW) glBindBuffer(GL ELEMENT ARRAY BUFFER, this gt EBO) glBufferData(GL ELEMENT ARRAY BUFFER, this gt indices.size() sizeof(int), amp this gt indices 0 , GL STATIC DRAW) Set the vertex attribute pointers Vertex Positions glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )0) Vertex Normals glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )offsetof(vertex, normal)) Vertex Texture Coords glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )offsetof(vertex, uv)) glBindVertexArray(0)


What is the benefit of a sparse bindless texture array over just bindless textures? I've seen the talks on AZDO, and they tend to suggest moving towards an architecture where you have one texture array per texture "shape". This is sparse, so you allocate loads of layers for potential future texture loads, and then commit each layer as you load a texture to it. You then make the whole thing bindless, and you can now pass a handle amp layer to your shaders for texturing. This is great, but what has it bought me above just using bindless textures? With bindless textures I seem to have to do exactly the same amount of work in fact, a little less I just pass in the texture handle (or sampler handle) to my shader. So why the push for sparse bindless texture arrays?


How can I efficiently render a tile based map with many Z levels, where the levels act like hollowed out voxels? My map setup is a little different to what you normally have with tilemaps. The map itself is a rectangular prism, with a width, height, and depth being variable. In my case, width is the x axis horizontally across the screen, height is the y axis vertically across the screen and depth is the z level, or how quot deep quot the map goes into out of the screen. In my map you could consider the rectangular prism as quot solid quot . Many most of these voxels could be considered as occluders to the voxels below them. Some voxels are hollowed out to make rooms and corridors. The map is viewed at a specific z level, from 0, the quot bottom quot of the rectangular prism, to n, the top. A quot hollowed out quot voxel, if viewed from it's level, would result in me rendering a floor texture in that tile. If there were 4 voxels above it hollowed out, then that floor texture would be rendered when the map is viewed from each of these z levels, but each z level above the quot floor quot would have a semi transparent black rect rendered on top of the tile (so it gets successively darker the further quot up quot you are). This occurs until you're on a z level above the tallest voxel that is hollowed out to make the room at which point you can't see it any longer, because this non hollowed out voxel blocks your view to the room below. The problem I have is that there are many z levels to render and most of the hollowed out sections criss cross around in the different layers to make a very complex network of little rooms and tunnels. This results in me naively rendering a floor texture, followed by several layers of semi transparent black rects, followed by a fully opaque black rect and potentially repeated for any additional overlapping rooms for every x,y tile on the screen. I'm trying to wrap my head around a way to render this more efficiently but I'm having trouble. Currently, for every render loop, I'm attempting to step through the z layers, from the current viewed z level down to 0, and finding the z level that is occluded first (or all the way to the 0 level), so that when rendering, I can skip z layers for that tile that are below this value. This isn't really giving me much of a performance increase. I'm looking for ideas on how to better perform these series of draw calls. I'm using OpenGL3.3 directly, so I'm not restricted by any library or engine constraints. Currently, I'm rendering each quot tile quot on each layer seperately and would prefer to keep it that way for simplicity.


How does the following code generate a full screen quad? How does this struct Output float4 position cs SV POSITION float2 texcoord TEXCOORD Output main(uint id SV VertexID) Output output output.texcoord float2((id lt lt 1) amp 2, id amp 2) output.position cs float4(output.texcoord float2(2, 2) float2( 1, 1), 0, 1) return output and this pImmediateContext gt VSSetShader(fxaaVS, ..., ...) pImmediateContext gt IASetPrimitiveTopology(D3D11 PRIMITIVE TOPOLOGY TRIANGLELIST) pImmediateContext gt Draw(3, 0) generate a Full Screen Quad? It has only three vertices b(provided quad has 4 vertices) the positions produced are also not like a (half of a) quad. Looking at this, i might be confused between a quad and a full screen triangle.


How can I change the camera to work from an Y up system to a Z up I am following the tutorial from learnopengl.com but it uses a Y up system, but I would like to change it for a Z up system because I'm more used to it. I tried changing the up vector to be 1.0 on the last coordinate but and inverting the pitch And the Yaw, but when having the camera face the positive y axis the mouse movement breaks and starts to move slower and opposite to the way I move the mouse. The Axis system I'm trying to achieve That is the same as the Blender one. This is the function of the camera class which handles the Pitch and Yaw (offset is the mouse movement on the x axis and y axis) void Camera updateCameraVectors() Calculate the new Front vector glm vec3 front front.x cos(glm radians(Yaw)) cos(glm radians(Pitch)) front.y sin(glm radians(Pitch)) front.z sin(glm radians(Yaw)) cos(glm radians(Pitch)) Front glm normalize(front) Also re calculate the Right and Up vector Right glm normalize(glm cross(Front, WorldUp)) Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. Up glm normalize(glm cross(Right, Front)) Up is the vector that I initialized as (0.0f, 0.0f 1.0f) Are there any resources available online that explain how to make the switch from a Y up to Z up system?


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


Why doesn't glBindVertexArray work in this case? From my understanding of what glBindVertexArray does and how it works, the following code should work fine First init glGenVertexArraysOES(1, amp vertexArray) glBindVertexArrayOES( vertexArray) glGenBuffers(1, amp buffer) glBindBuffer(GL ARRAY BUFFER, buffer) glBufferData(GL ARRAY BUFFER, kMaxDrawingVerticesCount sizeof(GLKVector3), NULL, GL DYNAMIC DRAW) glGenBuffers(1, amp indexBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, kMaxDrawingVerticesCount 1.5 sizeof(GLuint), NULL, GL DYNAMIC DRAW) glEnableVertexAttribArray(GLKVertexAttribPosition) glVertexAttribPointer(GLKVertexAttribPosition, 3, GL FLOAT, GL FALSE, sizeof(GLKVector3), BUFFER OFFSET(0)) glBindVertexArrayOES(0) And later add new geometry glBindVertexArrayOES( vertexArray) glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) However, it doesn't work (there is screen output, but it looks like the buffers were changed between each other). Binding the vertex array is not enough for the vertex indices buffer to get bound? Because, if I do this glBindVertexArrayOES( vertexArray) glBindBuffer(GL ARRAY BUFFER, buffer) lt note this line glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) lt note this line glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) Everything works looks as expected. I find it strange, since the vertex array should have taken care of the buffer binding. Otherwise, what's the purpose to have a vertex array if you still have to bind all the buffers?


How do I follow this glsl1.2 lights shadows tutorial? I am following this great tutorial but I have many questions. Let's see if I understand the basic idea. 1. I must create the same number of FBOs that lights (maximum 8). 2. I must create the same number of depth textures (shadow maps) that FBOs. 3. For every FBO I must perform offscreen render (render to texture, drawing the scene from the point of view of each of the lights, maximum 8 times). Is this correct or can I use just a texture with multiple FBOs, or fbo with various textures or how? Assuming you use the idea above, how should the final render of the scene? glUseProgram(programa) glUniformli(shadowM0,4) glActivateTexture(GL TEXTURE4) glBindTexture(GL TEXTURE 2D,depthT0) Draw Escene? glUniformli(shadowM1,5) glActivateTexture(GL TEXTURE5) glBindTexture(GL TEXTURE 2D,depthT1) Draw Escene? glUniformli(shadowM2,6) glActivateTexture(GL TEXTURE6) glBindTexture(GL TEXTURE 2D,depthT2) Draw Escene? ... glUseProgram(0) Is this okay? I think not, because it uses a lot of resources and the scene would have to be drawn up to 7 times. (One per light source and shadow mapping). Well but then how should the render scene with multiple light sources and shadows?


How to rotate a sprite in 2D with LWJGL3 and GLSL I have all the basic rendering already set up, with translation, scaling etc. What matrix(s) and or vector(s) do I need to multiply add with my existing code to rotate an object. Preferably around a point given by a vector2fa, also only in degrees because quaternions aren't implemented and its only 2D not 3D. Snippet of the vertex shader gl Position transformation vec4(position, 1.0) translation Where transformation is done in java as (Note not actual code as is replaced with .mul()) Matrix4f transformation ortho scale And translation is given by a method Vector4f translation new Vector4f(x , y , 0f, 0f).mul(gc.getOrtho()) All the code listed before works as expected. It is just lacking the rotation feature mentioned at the top. How can I add rotation to my code?


Prevent tile layout gaps I'm making a map viewer where you can specify where tiles go in a map and then see it on the screen, translate it, and zoom in and out. Here's a picture showing the tiles used to make my example map Here's the tiles connected together, more or less my desired result. The problem is that at particular combinations of translations and zoom levels the spacing is off. Here's an example picture of the problem. In order to arrange the tiles I'm using a Perspective projection matrix parametrized by the zoom level, a camera matrix which just translates the scene based the camera's 2d position, and finally each tile is translated using another matrix derived from its x and y position. tile camera projection How can I avoid this weird spacing issue at particular positions? I'm guessing this is some kind of floating point precision issue, but I'm not sure. (for those interested, the tiles I'm using are from this collection) EDIT I was using the following parameters for the standard openGL perspective projection matrix let near 0.5 let far 1024.0 let scale zoom near let top scale let bottom top let right aspect ratio scale let left right where aspect ratio is the window width divided by the window height, (in pixels,) and zoom in the error case above was set to 8.0. I read some more on perspective projection and floating point errors but couldn't find anything sensible to change so I resorted to adjusting the parameters. Specifically I tried setting near to 1.0 and now I can't replicate the weird spacing. So I guess my problem is solved? But this is a mysterious and unsatisfying answer, so I would still appreciate it if someone could explain what went wrong, and how I can avoid it in the future without fiddling with numbers until it "magically" works! EDIT responding to amitp Here's a screenshot from the same version as above (with near still set to 0.5), with the background set to red as suggested. This seems to indicate that it's something wrong with the tile layout, not image bleed.


Rendering a model with transparent or translucent uv map applied doesn't work Before I try to make anything transparent, the model renders nicely. When I change the uv layout so that one piece of the model will be transparent, it renders horribly. This is the result with a translucent green texture I did transparency with OpenGL when I did 2D games and everything worked nicely because of these two lines glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) Now, I fear, this won't be enough, right? Or maybe I should use some other technique?


Is this process for generating an OpenGL perspective projection correct? I have been programming OpenGL for a while now and I have successfully created a perspective camera, however, I can't help but shake the feeling that I am doing it wrong. The code I am using is below, is there something wrong with how I am constructing the perspective projection? int MainWindow SDL execute(QCoreApplication amp app) SDL Init(SDL INIT EVERYTHING) glewInit() ... glLoadIdentity() glEnable(GL TEXTURE 2D) glEnable(GL DEPTH TEST) glMatrixMode(GL MODELVIEW) glDisable(GL LIGHTING) gluPerspective(50, 1.33, 1, 1000) gluLookAt(3, m xAxisLocation, 4, 0, 0, 0, 0, 1, 0) glewExperimental GL TRUE ... GameStart() app.exit() return 0 I also set it up in the game loop void MainWindow SDL GameLoop() OpenGLRenderer t renderer t renderer.PreGameRender() while (m state GameState RUNNING) glPushMatrix() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() processInput() glMatrixMode(GL MODELVIEW) glEnable(GL TEXTURE 2D) glEnable(GL DEPTH TEST) gluPerspective(50, 1.33, 1, 1000) gluLookAt(m xAxisLocation, m yAxisLocation, m zAxisLocation, 0, 0, 0, 0, 1, 0) t renderer.DuringGameRender() SDL GL SwapWindow(m window) glPopMatrix() t renderer.PostGameRender() GameEnd()


Using same buffer for vertex and index data? Is it possible to use the same buffer for both GL ARRAY BUFFER and GL ELEMENT ARRAY BUFFER? I load both vertex data and index data into a big slab of memory, so it would be easier for me to just load it all into a single buffer. So naturally, I do like this glBindBuffer(GL ARRAY BUFFER, vboId) glBufferData(GL ARRAY BUFFER, dataSize, data, usage) glBindBuffer(GL ARRAY BUFFER, 0) Is it legal to ndash during rendering ndash simply use it as both? glBindBuffer(GL ARRAY BUFFER, vboId) glBindBuffer(GL ELEMENT ARRAY BUFFER, vboId) glVertexAttribPointer(...) ... glDrawElements(mode, count, dataType, (void )indexOffset) I can't find anything in the spec saying it's ok to do so, but I can't find anything that says that I can't either. Googling doesn't turn up much either, but I might be looking in the wrong places.


Uniform arrays do not work on every GPU I am trying to implement instanced rendering for objects that repeat, so I came up with idea I could simply group objects that loaded same model files, create array with their Model matrices and so on, and finally pass this array as uniform array to shaders, which will be indexed by gl instanceID to get correct model matrix for given objects. C implementation looks pretty much like this std vector RelativePositions, Scales std vector Models int ctr 0 bool first true int isz 0 obj gt getIndices(isz) pDrawData gt refObjects holds all Object3D instances which share same model geometry for (std list lt IObject3D gt iterator pObj pDrawData gt refObjects.begin() pObj ! pDrawData gt refObjects.end() pObj ) IObject3D obj pObj int render prepareForRender(obj, flags, isShadow, offset) if (!render) continue if (first) this is gonna be same for all objects of this class setUniform(Type, (int)obj gt getType()) setUniform(Flags, (int)obj gt getFlags()) first false Scales.push back(obj gt getScale()) RelativePositions.push back(obj gt getPos()) Models.push back(obj gt getModel()) ctr if (ctr) int Rem 0 const int Step MAX OBJ PER INST 64 for (size t i 0, j Scales.size() i lt j i Step) Rem Scales.size() i if (Rem gt Step) Rem Step following functions set uniform array of specified length setUniform(Scale, Scales.data() i, Rem) setUniform(RelativePosition, RelativePositions.data() i, Rem) setUniform(Model, Models.data() i, Rem) glDrawElementsInstanced(GL TRIANGLES, (GLsizei)isz, GL UNSIGNED INT, 0, Rem) Rendering object is done via Vertex Shader Tess Control Shader Tess Eval Shader Geom Shader FragmentShader. Instance ID is being passed using flat out in int InstanceID from shader to shader while being once set in Vertex shader as gl InstanceID. Tessellation Evaluation Shader logics look like this version 430 layout(triangles) in in vec3 tcPosition in vec3 tcTexCoord in vec3 tcNormal flat in int tcInstanceID out vec3 tePosition out vec3 teDistance out vec3 teTexCoord out vec3 teNormal flat out int teInstanceID define MAX OBJ PER INST 64 uniform mat4 Model MAX OBJ PER INST uniform vec3 Scale MAX OBJ PER INST uniform vec3 RelativePosition MAX OBJ PER INST ... other uniforms void main(void) vec3 p0 gl TessCoord.x tcPosition 0 vec3 p1 gl TessCoord.y tcPosition 1 vec3 p2 gl TessCoord.z tcPosition 2 ... other stuff ... teDistance gl TessCoord tePosition (p0 p1 p2) teInstanceID tcInstanceID 0 switch(Type) ... other types ... default tePosition (vec4(tePosition,1) Model teInstanceID ).xyz Scale teInstanceID RelativePosition teInstanceID break This works fine when I run it on any nVidia GPU when on laptop, but when I try to run it on AMD GPU or Intel Integrated Graphics, it suddenly doesn't work and I only get blank screen. But if I remove uniform arrays and pass only single variable for uniform, so all instances would suddenly have same model matrix, position and scale, it works even on other GPUs, so problem is definitely with arrays... Is there any solution to this?


Cannot Draw a triangle without VAO on MacOS So I was watching Cherno's Video on Vertex attributes and he was successful in drawing a triangle without a VAO, but in tutorials from learnopengl.com they specifically say they we need a VAO to draw VBO and I tested it and it works fine. Here is my snippet glGenVertexArrays(1, amp VAO) glBindVertexArray(VAO) glGenBuffers(1, amp VBO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, sizeof(triangleVertices), triangleVertices, GL STATIC DRAW) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(GLfloat), (GLvoid )0) glEnableVertexAttribArray(0) Game Loop Loop until the user closes the window while (!glfwWindowShouldClose(window)) Poll for and process events glfwPollEvents() Render here glClearColor(0.2f, 0.3f, 0.3f, 1.0f) RGBA glClear(GL COLOR BUFFER BIT) glUseProgram(shaderProgram) glBindVertexArray(VAO) we did not unbind it so it's still binded to the assigned VAO glDrawArrays(GL TRIANGLES, 0, 3) Swap front and back buffers glfwSwapBuffers(window) This only works if I uncomment the VAO which is understandable, what I can't get my head around is how did Cherno got it working without a VAO and just using a VBO? Is it a MacOS specific thing?


UnrealEngine4 "backwards compatilibility" Can I view a site that uses Unreal Engine4 on a very old laptop and still see in high definition? Backwards compatible? The project I want to render a high definition model on my personal website such that it'll be rendered in the highest definition possible on any device, from a 20 year old Gateway PC running Windows 95 to an iPhoneX. It's particularly important that it's real pretty on mobile (whatever Android and iPhone models are big these days) The question I was thinking I'd buy an expensive desktop with GPUs to make sure I can make the app really fancy for users on a high end desktop with nice monitors. But I'm not going to do that if the high definition I get on my new expensive screen doesn't make it out to the app my employer is building. How does this work? Does OpenGL display the highest definition render it can on the mobile device?


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.


OpenGL gradient banding on Samsung Galaxy S2 Android phone I've got a live wallpaper out on the market which uses OpenGL to render some basic shapes and a flat plane. The simple lighting creates a gradient effect across the plane, which looks fine on most devices. The Samsung Galaxy S2 series seems to have some trouble rendering the gradient, though, as you can see in this screen shot The color banding looks awful, especially compared to this screen shot from an Incredible I'm using a 565 EGL config in both cases, so I believe this is just a display issue with the GS2 devices. Can anyone confirm this suspicion? Is there any solution to the banding?


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


Help finding coordinate for left of screen in this frustum I have a frustum with l 2, r 2, n 0.5, f 10, corresponding to left, right, near, far respectively. I also define top and bottom too. I've set the camera eye up at (0, 0, 2.5), looking directly at (0, 0, 0) with up (0, 1, 0). Suppose I want to position an object centred at z 1. I want to find the x coordinate so that under this frustum it appears exactly centred on the left edge of the screen. I set up the following diagram to help me z x lt gt x x 1 l near dist n 0.5 a 2.5 z So to find x I can use simple trig. Since tan a l n and tan a x 1.5 then the formula for x is x l n 1.5 2 0.5 1.5 6, where . is the absolute value. But when I use this x value to draw an object left of the centre, it does not appear centred at the edge of the screen. I can see the object but it's not on the edge. Moreover, if I increase n then the gap between the object and the left edge increases. What am I doing wrong? UPDATE Empirically I have discovered that if I compute x l n 2.5 then my object is correctly centred on the left edge of the device screen, and works for any n value I choose. Not sure why 2.5 works... SOLUTION Not really worthy of an answer, but I found in some legacy code that the renderer was set up to transalte the z forward by 1 unit, so this was undoing my 1 z value, hence why multiplying by 2.5 worked and not 1.5. Despite this annoying fact, I'm now confident I fully understand how the frustum fits into OpenGL.


Is it ok to use NPOT textures with OpenGL in this situation? I drew some icons to use on orthographic projection and instead of loading each icon file individually as a texture I thought of putting them all together in one single file. Now I have a file 72x36 which is not a power of two. This texture is divide in two icons, both with 36px wide. I didn't remember about this restriction when designing the texture but I eventually noticed it when the texture didn't load because I have an if statement checking if the texture is a power of two, if it's not, than the texture is not loaded. I commented that code to see if the texture loaded anyway and it did. The texture was loaded and properly applied to the area I wanted. To draw the first icon I do this glBindTexture(GL TEXTURE 2D, gameTextures.hudKeys) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f(0, 36) glTexCoord2f(0.5, 0) glVertex2f(36, 36) glTexCoord2f(0.5, 1) glVertex2f(36, 0) glTexCoord2f(0, 1) glVertex2f(0, 0) glEnd() And for the second this glBindTexture(GL TEXTURE 2D, gameTextures.hudKeys) glBegin(GL QUADS) glTexCoord2f(0.5, 0) glVertex2f(0, 36) glTexCoord2f(1, 0) glVertex2f(36, 36) glTexCoord2f(1, 1) glVertex2f(36, 0) glTexCoord2f(0.5, 1) glVertex2f(0, 0) glEnd() Which is easy to understand, I only use half of the texture depending on which icon I want. I don't want my icons to be distorted or stretched, the icons were designed with 36x36 in mind. If I use a power of 2 texture, for instance 128x64 (that's the lowest possible to fit a 72x36 texture), how do I properly map the 36x36 texture area I want to the quad? Or maybe I can keep doing using this NPOT texture or should I still really create a power of 2 texture? How to fix the problem above then?


OpenGL ES 2 Developing snowfall particle system I've recently begun OpenGL ES 2 and I'm trying to implement a snowfall (on Android), but I'm not sure what's the best approach. I would like to develop it myself rather than use a library. It really helps a lot in understanding OpenGL. What I'm doing at the moment is I have an array of, say, 1000 particles, each with its own lifetime ( number of frames it will live). It works fine if a particle "dies" and starts all over when it already left the screen, but if it is still on the screen and it has to die, the user will notice that the particle suddenly disappeared. The problem is very noticeable if this happens very often. I need a way to kill a particle only when it left the screen. Is there a way to improve my approach or maybe I should change it completely?


How to render a model that consists of individually transformable parts? Consider a 3D model for a spider that consists of a body and eight legs. The legs can be transformed (rotated) relative to the body. I am not sure what the common ways of rendering such a scene are, at a low level. Two ways I could think of Render the body and legs separately, using different VBOs (or different indices) (one for the body, one for the leg) and separate draw calls. Encode in each vertex which body part it belongs to, and decide based on this information how to transform the vertex in the vertex shader. I searched a bit and could find some tutorials on skeletal animation and similar techniques, but they still boil down to this question.


Learning OpenGL Red and Blue book still relevant? I've recently purchased the Orange book( GLSL ) and am wondering if it is important at all to read through the red and blue books as well? Any thoughts?


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


Texture dimensions guidelines I have 3 related questions What are the main optimizations related to power of 2 dimensions for 1D 2D 3D textures? This question gives some answers like mipmapping, but are not well explained and the list of optimizations does not seem to be complete. I want a complete ordered list from most important to less of the optimizations with complete explanations, with references replacing full explanations only where full explanation would overwhelming, and proper references (paper graphics official page OpenGL Vulkan CUDA ) for every statement about explained optimization. When the comparation is not direct, take a guess based on the one that would improve overall performance most in majority of computer graphics applications. Furthermore I want to specify which of this optimizations are available at least for OpenGL and CUDA. More specifications would be acclaimed. What benefits exists for divisible by 8 dimensions? This article states the rule as an alternative complement to the power of 2 one but does not give explanations nor references. Is there any benefit for divisibility by a larger number? This article uses divisible by 32 dimensions. I know that CUDA has a warp size of 32 and that blocks should be multiple of 32 to have a good overall average utilization, but I do not know if this could be related to texture sizes and would like to know if the answer is no. In many places posibilities for texture optimization are loosely stated and not properly documentated. This question aims at solving this issue.


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


Texture being rendered to main frame buffer? I'm using Ogre 1.10.12 (openglES2 as render system) to create a manual texture like this rtt texture Ogre TextureManager getSingleton().createManual("RttTex", Ogre ResourceGroupManager DEFAULT RESOURCE GROUP NAME, Ogre TEX TYPE 2D, m size.width(), m size.height(), 0, Ogre PF A1R5G5B5, Ogre TU RENDERTARGET) m renderTexture static cast lt Ogre GLES2FBORenderTexture gt (rtt texture gt getBuffer() gt getRenderTarget()) m renderTexture gt addViewport(m camera) m renderTexture gt getViewport(0) gt setClearEveryFrame(true) m renderTexture gt getViewport(0) gt setBackgroundColour(Ogre ColourValue Red) m renderTexture gt getViewport(0) gt setOverlaysEnabled(false) then, I bind the texture to the FBO and retrieve the FBO's ID like Ogre GLES2FrameBufferObject ogreFbo 0 m renderTexture gt getCustomAttribute("FBO", amp ogreFbo) Ogre GLES2FBOManager manager ogreFbo gt getManager() manager gt bind(m renderTexture) GLint id glGetIntegerv(GL FRAMEBUFFER BINDING, amp id) My concern is that id is 0 so I cannot render this texture outside my display, it's getting visible which I don't want it to be. Shouldn't be ogre creating an unused frame buffer object when creating a manual texture with the TU RENDERTARGET parameter?


Sprite batching in OpenGL I've got a JAVA based game with an OpenGL rendering front that is drawing a large amount of sprites every frame (during testing it peaked at 700). Now this game is completely unoptimized. There is no spatial partitioning (so a sprite is drawn even if it isn't on screen) and every sprite is drawn separately like this graphics.glPushMatrix() graphics.glTranslated(x, y, 0.0) graphics.glRotated(degrees, 0, 0, 1) graphics.glBegin(GL2.GL QUADS) graphics.glTexCoord2f (1.0f, 0.0f) graphics.glVertex2d(half size , half size) upper right same for upper left, lower left, lower right graphics.glEnd() graphics.glPopMatrix() Currently the game is running at 25FPS and is CPU bound. I would like to improve performance by adding spatial partitioning (which I know how to do) and sprite batching. Not drawing sprites that aren't on screen will help a lot, however since players can zoom out it won't help enough, hence the need for batching. However sprite batching in OpenGL is a bit of mystery to me. I usually work with XNA where a few classes to do this are built in. But in OpenGL I don't know what to do. As for further optimization, the game I'm working on as a few interesting characteristics. A lot of sprites have the same texture and all the sprites are square. Maybe these characteristics will help determine an efficient batching technique?


What causes some computers to have no or slow OpenGL, and how to fix it? I am using Java with JOGL to create OpenGL enhanced 2D graphics. The graphics operations I use are nothing fancy, and should be supported by almost any recent graphics card. For example, my game runs great on a Netbook. I was hoping the game would run on most computers. It runs fine on my own computers. However, I found some computers have very slow performance (apparently software fallback, yielding about 2 frames per second). I ran a LWJGL app on one such computer. It doesn't run at all (it reports something like org.lwjgl.LWJGLException Pixel format not accelerated, you can find various forum threads complaining about this but no apparent solutions, except the suggestion that it is a driver problem). Other OpenGL software does not seem to work, either. I also found that my Flash version of the game with exactly the same graphical effects performs pretty well full screen on that same computer. The computer in question has a recent ATI card but unfortunately I have no access to the driver manager. The problem appears fairly widespread. I think it is very unfortunate that OpenGL does not always provide access to graphics features found on most computers. This makes it less attractive for casual 2D games, which I expect to run on any computer. Did any of you run into this problem and manage to fix it? AFAIK, both NVidia and ATI provide OpenGL as part of their standard driver sets, but maybe there are some exceptions? Is this problem caused by third party drivers not supporting OpenGL, and can the problem be fixed by installing better drivers? How many other graphics cards are out there without OpenGL drivers? EDIT As a final note, I can conclude that OpenGL is just not well supported on Windows machines. Microsoft seems to have been doing their best to keep it off their platform, for example by deliberately leaving out OpenGL drivers in some Windows driver bundles. Get the vendor drivers, and you get OpenGL get the standard drivers that Windows downloads for you, and you don't. This has been causing no end of trouble for others as well. For example, for implementing WebGL, Web browsers use Angle, which is an OpenGL ES emulator for DirectX. So, what we'd really need is something like Angle, only for full OpenGL.