Linking error at tessellation shaders in GLSL I'm testing the triangle tessellation from the link http prideout.net blog ?p 48 shaders . All the shader are compiled correctly, but when I try to link the program using the command glLinkProgram(programID) I got the following error Tessellation control info (0) error C6029 No input primitive type Tessellation evaluation info (0) error c7005 No tessellation primitive mode specified Geometry info (0) error C6022 No input primitive type (0) error C6029 No ouput primitive type Not valid It's so strange I declare output for TC Shader using command layout(vertices 3) out And input layout for TE shader using command layout(triangles, equal spacing, cw) in Why I still got this error? I hope to see you answer about it. I put my shaders in below Vertex shader version 410 core in vec4 Position out vec3 vPosition void main() vPosition Position.xyz TC shader version 410 core layout(vertices 3) out in vec3 vPosition out vec3 tcPosition define ID gl InvocationID void main() float TessLevelInner 3 float TessLevelOuter 2 tcPosition ID vPosition ID if (ID 0) gl TessLevelInner 0 TessLevelInner gl TessLevelOuter 0 TessLevelOuter gl TessLevelOuter 1 TessLevelOuter gl TessLevelOuter 2 TessLevelOuter TE Shader version 410 core TessEval layout(triangles, equal spacing, cw) in in vec3 tcPosition out vec3 tePosition out vec3 tePatchDistance uniform mat4 Projection uniform mat4 Modelview void main() vec3 p0 gl TessCoord.x tcPosition 0 vec3 p1 gl TessCoord.y tcPosition 1 vec3 p2 gl TessCoord.z tcPosition 2 tePatchDistance gl TessCoord tePosition normalize(p0 p1 p2) gl Position Projection Modelview vec4(tePosition, 1) Geometry shader version 410 core geometry shader layout(triangles) in layout(triangle strip, max vertices 3) out in vec3 tePosition 3 in vec3 tePatchDistance 3 out vec3 gFacetNormal out vec3 gPatchDistance out vec3 gTriDistance uniform mat4 Modelview uniform mat3 NormalMatrix void main() vec3 A tePosition 2 tePosition 0 vec3 B tePosition 1 tePosition 0 gFacetNormal NormalMatrix normalize(cross(A, B)) gPatchDistance tePatchDistance 0 gTriDistance vec3(1, 0, 0) gl Position gl in 0 .gl Position EmitVertex() gPatchDistance tePatchDistance 1 gTriDistance vec3(0, 1, 0) gl Position gl in 1 .gl Position EmitVertex() gPatchDistance tePatchDistance 2 gTriDistance vec3(0, 0, 1) gl Position gl in 2 .gl Position EmitVertex() EndPrimitive() Fragment Shader version 410 core fragment shader out vec4 FragColor in vec3 gFacetNormal in vec3 gTriDistance in vec3 gPatchDistance in float gPrimitive uniform vec3 LightPosition float amplify(float d, float scale, float offset) d scale d offset d clamp(d, 0, 1) d 1 exp2( 2 d d) return d void main() vec3 AmbientMaterial vec3(0.04f, 0.04f, 0.04f) vec3 DiffuseMaterial vec3(0, 0.75, 0.75) vec3 LightPosition vec3(0.25, 0.25, 1) vec3 N normalize(gFacetNormal) vec3 L LightPosition float df abs(dot(N, L)) vec3 color AmbientMaterial df DiffuseMaterial float d1 min(min(gTriDistance.x, gTriDistance.y), gTriDistance.z) float d2 min(min(gPatchDistance.x, gPatchDistance.y), gPatchDistance.z) color amplify(d1, 40, 0.5) amplify(d2, 60, 0.5) color FragColor vec4(color, 1.0)


Uniforms stop working when loading multiple programs via glUseProgram() The rendering keeps happening, and the debugger shows my camera is getting its position updated properly, but for some reason the camera doesn't appear to have its position updated. I'm not sure what I'm doing wrong. Can uniforms fail to get set when swapping between different programs shaders?


Why is Minecraft's default resolution (seemingly) non standard? Background I'm writing some articles on Minecraft in an attempt to introduce 10 year olds to development through modding. I know very little about the game itself, though ) I'm trying to understand why Minecraft appears to run in an "odd" default resolution. Grabbing a screenshot, I think it's rendering at 550x310 but that doesn't seem to match any of the "common" aspect ratios (although it's close to 16 9), nor is it evenly divisible by 16, which appears to be what the texture packs use. Is it actually running at 550x310 in its default windowed mode? If not, what is the resolution? Depending on the answer to the first question, why isn't it using one of the standard aspect ratios? I'm not familiar with OpenGL programming either so perhaps there is a common resolution close to what I'm guessing at that would make perfect sense.


What are the benefits of capping frames per second? (If any) I am working on a simple game in OpenGL, using SDL for display initialization and input, and it appears in terms of timing I have two options available to me. Number one being just sleeping for the optimalTimePerFrame theTimeTakenToRender, when the optimalTimePerFrame in seconds 1 theFramerateCap. (I'm not entirely sure if this is necessary, as it is equivalent to using vsync, which may be more accurate. If my assumption is correct then please tell me wheter or not SDL OpenGL has vsync by default, and if not how to enable it.) The other is to measure the time since the last frame was rendered, and merely adjust movement accordingly. (The shorter time taken to render a frame, the less far entities move in that frame). In terms of performance, and decreasing flicker etc, what are the advantages and disadvantages of these two methods?


Is Ada suitable for game development? Would Ada be a practical language for game development (at least for the PC I understand there aren't compilers for PlayStation and other consoles)? It has bindings to OpenGL, it has decent performance, and it's less error prone than C . Please feel encouraged to support your point with relevant example projects you know about.


OpenGL large tile map rendering I want to be able to have a big tilemap (e.g. like Terraria, or an infinite procedural generated one), with only a handful of tiles on my screen. This means that I have a texture atlas (i.e. spritesheet) which contains the textures for the tiles. For the sake of simplicity, let's assume that I have a huge internal 2D array, containing the tileIDs and a lookup tablel hasmap for the UV coords for each tile type. All the tiles have the same dimension (the texture AND the onscreen tiles). I know a couple of methods to render such a 2D grid tilemap, but I don't know which one of them is a solid foundation for a game which heavily relies on modifiable tiles. Additionally, I want to be able to dynamically change the tilesize (i.e. zooming in out), modifying the tiles tilemap (e.g. destroying, building) and fast loading (fast paced player actions). Using a single draw call. I create a VBO with all the quads to fill the screen (multiple overlapping vertices, because each quad needs a different texture) and have a persistent buffer to modify the texture buffer object. As soon as the camera moves, I update the UV coordinates in the TBO. I can use attributeless rendering. I make a glDrawArrays call on an empty VAO, and use gl VertexID 6 and gl VertexID 6 to get the vertex ID and the tileID. To map the UV coordinates, I pass a TBO, which is updated at every camera move. I don't know how expensive this calculation is for the GPU. Hoping on the train of attributeless rendering, I can pass a uniform or create a const array to hold the UV offsets of every tile type, and only pass at every camera move the updated tile type IDs to the shader (with a uniform?). With gl VertexID 6 I know which index holds the current tiles type information, and then with this type, I can access my constant array to lookup the UV coordinates. Either using triangle strips, or indices to reduce the vertex count, and use provoking vertices to correctly map the UV coordinates (this can be combined with attributeless rendering). The vertices are all fixed for the window, and only the textures change. Here, once again, I have to map the TBO to a persistent buffer and update it at every camera move. Every tile gets a separate draw call (thus a separate VBO, IBO, TBO) and I can therefore render only the tiles which are seen by the camera. Because of the low amount of onscreen tiles, those separate draw calls shouldn't be too expensive. I put the whole map at the start of the game in the VAO and TBO, and modify the indices buffer, to only render the onscreen tiles (the IBO only holds enough indices to render the onscreen quads). My problem here is that I send too much data to the GPU every frame, and I have a really bad cache locality, because the information has to be accessed from different parts of the buffer objects. There might also be a way to use a geometric shader, although I have never used one. My concrete question is, is there a "state of the art" method to render big tilemaps, is any of my above mentioned ideas a good solution, and, does it really matter which option I use? Thank you!


c most used libraries I'm trying to find out whether or not I want to switch from Java to c for my OpenGL game programming. I now have setup a test project in VS 11 professional, with GLUT. I created my windows with GLUT, and I can render OpenGL primitives without any problems. Now my question What library(s) is are used mostly in the indie semi professional industry for using OpenGL in c ? With 'using OpenGL' I mean Creating and managing an OpenGL window Actually using the OpenGL API Handling user input (keyboard mouse)


View matrix in opengl Sorry for my clumsy question. But I don't know where I am wrong at creating view matrix. I have the following code createMatrix(vec4f(xAxis.x, xAxis.y, xAxis.z, dot(xAxis,eye)), vec4f( yAxis.x , yAxis.y , yAxis.z , dot(yAxis,eye)), vec4f( zAxis.x , zAxis.y , zAxis.z , dot(zAxis,eye)), vec4f(0, 0, 0, 1)) column1, column2,... I have tried to transpose it, but with no success. I have also tried to use gluLookAt(...) with success. At the reference page, I watched the remarks about the to be created matrix, and it seems the same as mine. Where I am wrong?


How to correctly specify the offset in a call to glVertexAttribPointer()? I'm trying to draw a simple triangle using the following vertices std vector lt VertexFormat gt vertices vertices.push back(VertexFormat(glm vec3(0.25, 0.25, 0.0), glm vec4(1, 0, 0, 1))) vertices.push back(VertexFormat(glm vec3( 0.25, 0.25, 0.0), glm vec4(0, 1, 0, 1))) vertices.push back(VertexFormat(glm vec3(0.25, 0.25, 0.0), glm vec4(0, 0, 1, 1))) The corresponding Vertex format is given by the following struct struct VertexFormat glm vec3 position glm vec4 color VertexFormat(const glm vec3 amp iPos, const glm vec4 amp iColor) position iPos color iColor The first call to glVertexAttribPointer() is easy since the position vector appears first in the struct, the call is as follows glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )0) The second call to glVertexAttribPointer() should be made specifying a suitable offset for the color attribute of a vertex. Since the color vector appears after the position, then such offset should be given by sizeof(glm vec3). The corresponding call is glVertexAttribPointer(1, 4, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )(sizeof(glm vec3))) The output of the program using these parameters is This output is wrong. There are only two colors (green and blue) and the colors are in the wrong position, note that the bottom left vertex is blue, but according to the code the vertex should be green. If the offset is changed to sizeof(glm vec4) the call is glVertexAttribPointer(1, 4, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )(sizeof(glm vec4))) And the triangle is rendered correctly So, Is my understanding of the offset parameter wrong? Why using an offset with the size of a vec4 gives the right output? Any help would be appreciated. P.S. Sorry for the bad english. Edit After reading the answer of Fibbles, and the comments of Fuzz Logic, I checked the size of the VertexFormat struct. A sizeof() gives a size of 32 bytes for a 32 bit executable. So padding is indeed the problem here. Using the macro suggested by Fibbles solves the problem. Thanks for everything guys!


Atmospheric scattering and sky geometry I'm trying to implement an atmospheric scattering in my graphics (game) engine based on the GPU Gems article link. An example implementation from that article uses a skydome. My scene is different I don't render a whole earth with an atmosphere which can be also visible from the space but some finite flat (rectangle) area with objects, for example a race track. In fact this is the most common scenario in many games. Now I wonder how to render a sky in such case What kind of geometry I should use skydome, skybox or a full screen quad then I have to move almost all calculations to the fragment shader, but I don't know if it makes sense in terms quality performance ? How to place sky geometry on the scene ? My idea I have a hemisphere (skydome) geometry with radius 1 and center in vec3(0, 0, 0) in object space. Those vertices are sent to the atmospheric scattering vertex shader layout(location 0) in vec3 inPosition Next, In the vertex shader I transform vertex this way v3Pos inPosition 0.25f 10.0f Uniform v3CameraPos vec3(0.0f, 10.0f, 0.0f), uniform fInnerRadius 10.0f, uniform fCameraHeight 10.0f Then I have correct an inner outer radius propotion (10 10.25),right? I also send to the vertex shader a model matrix which sets a position of the hemisphere to the postion of the mobile camera vec3(myCamera.x, myCamera.y, myCamera.z) vec4 position ProjectionMatrix ViewMatrix ModelMatrix vec4(inPosition, 1.0) gl Position position.xyww always fails depth test. The hemisphere moves together with the camera (encloses only some space around camera with radius 1, but it also always fails a depth test.) Unfortunately a sky color which I get is not correct What about a "sky curve"? Here is a picture which demonstrate what I mean How should I set a sky curve? Edit1 debugging In the vertex shader I assigned to v3Pos position of the "highest" vertex in the hemisphere vec3 v3Pos vec3(0.0f, 10.25f, 0.0f) Now the whole sky contains a color of that vertex


OpenGl indices array I have a class terrain which create a grid of Quads. I do it like this for(int z 0 z lt length z ) for(int x 0 x lt width x ) vertices.push back(vec3((float)x 250, 0.f, (float)z 250)) for(int z 0 z lt ( length 1) z) for(int x 0 x lt ( width 1) x) int index z width x Vertex vertices Vertex(vertices.at(index),vec3(0, 0, 0)), Vertex(vertices.at(index 1),vec3(0, 0, 0)), Vertex(vertices.at(index width),vec3(0, 0, 0)), Vertex(vertices.at(index 1 width),vec3(0,0,0)) unsigned short indices index,index 1,index width,index 1,index width,index width 1 Quad quad( vertices, 4, indices, 6) squares.push back(quad) i The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code But when I change this indices to this unsigned short indices 0,1,2,1,2,3 It works great The problem is I don't understand why this line unsigned short indices index,index 1,index width,index 1,index width,index width 1 doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code class Quad public Quad(Vertex vertices, int n, unsigned short indices, unsigned short numIndices) for(int i 0 i lt numIndices i ) indices.push back( indices i ) for(int i 0 i lt n i ) vec3 v vec3( vertices i .position, lengthPower) position.push back(v) glGenVertexArrays(1, amp mVertexArray) glBindVertexArray(mVertexArray) glGenBuffers(1, amp mPositionBuffer) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glBufferData(GL ARRAY BUFFER, sizeof(vec3) position.size(), position.data(), GL STATIC DRAW) glGenBuffers(1, amp mIndicesBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(unsigned short) indices.size(), indices.data(), GL STATIC DRAW) void draw() glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glVertexAttribPointer(0, 4, GL FLOAT, GL FALSE, 0, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glDrawElements(GL TRIANGLES, indices.size(), GL UNSIGNED SHORT, 0) glDisableVertexAttribArray(0) Quad() private std vector lt unsigned short gt indices std vector lt vec3 gt position GLuint mVertexArray GLuint mPositionBuffer GLuint mIndicesBuffer I'm using, OpenGL, glm, glfw etc.


OpenGL pitching problem I've been trying to implement several camera movements for my application. So far yawing, rolling, strafing, walking has been working properly, but I can't get my pitching to work properly. If I continue pitching upwards, it doesn't rotate back 360 degree, and instead gets stuck looking at the top of the screen. Here's my code for Camera class class Camera float m 16 Vector dirForward, dirUp, dirRight void loadCameraDirections() glGetFloatv(GL MODELVIEW MATRIX, m) dirForward Vector(m 2 , m 6 , m 10 ).unitVector() dirUp Vector(m 1 , m 5 , m 9 ).unitVector() dirRight Vector(m 0 , m 4 , m 8 ).unitVector() public Vector position Vector lookAt Vector up Camera() position Vector(300, 0, 100) lookAt Vector(0, 0, 100) up Vector(0, 0, 1) void rotatePitch(double rotationAngle) glPushMatrix() glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z) loadCameraDirections() glPopMatrix() lookAt position.repositionBy(dirForward.reverseVector()) cam I call the gluLookAt funtion by gluLookAt(cam.position.x, cam.position.y, cam.position.z, cam.lookAt.x, cam.lookAt.y, cam.lookAt.z, cam.up.x, cam.up.y, cam.up.z)


OpenGL Maximal amount of debug string reached I was trying to check my current openGL code in gDEBugger, everything works fine. But, I get these messages Debug String gt gt gt gt gt gt gt gt gt 1 Debug String gt gt gt gt gt gt gt gt gt 2 Debug String gt gt gt gt gt gt gt gt gt 3 ... Debug String gt gt gt gt gt gt gt gt gt 497 Debug String Maximal amount of debug string reached (500 strings). Additional debug strings will be ignored What are these messages, everything in my code runs fine. But its troubling to see these debug strings.


How to determine what color will be written into single pixel framebuffer? I thinking about rendering into single pixel (1x1) framebuffer. For example we have two triangles which covers whole NDC area, one is green second red. What color will be written to 1x1 framebuffer? As far as I understend graphic API (no matter which) tries to put whole scene in to given framebuffer, in our example, into single pixel. But I can't figure how GPU will choose what should be written into that pixel.


Game development for high school with C and OpenGL I've been teaching high school students (12th grade) game programming in the last 2 years. The way I did this till now, was first to give them "half made" classes (for Point, Polygon, etc.) and they've completed them with my help their friends themselves, and then they were free to design their models, and write their game logic. The programming language was C and I used GLUT. I gave the students the base class that does all inits for OpenGL so they didn't work on it (except some high motivated students that wanted to extend their graphics). My goal was to teach them the fundamentals of C using OOP, by implementing their own classes rather than teaching them methods from OpenGL GLUT API. It's also important to notice that most of those students never programmed in their life and all they knowledge comes from theory in high school computer science. I write this post here to get your opinions about the way I handled this class until now, do you think I've done wrong not teaching the OpenGL GLUT API? do you think I need to utilize OpenGL power to implement basic models, or it's good practice to let them implement models by themselves? Maybe I don't need to use GLUT anymore because there are modern libraries these days that does better work, or it doesn't matter as long as it's for learning purposes? I really want to give the students motivation by demonstrating what they can do in modern game programming, but I still got my limits which I wrote here, and also time limit (the class is one year, one lesson each week). Thanks for your help!


OpenGL Array Texture generates black texture I am creating a game using OpenGL that has many textured cubes. I am trying to use an Array Texture to load multiple textures from one file. I tried to setup my texture atlas however, all that renders is a black texture. I'm not sure what exactly I am doing wrong. Here is the texture loading code Load image stbi set flip vertically on load(true) unsigned char data stbi load(path, amp width, amp height, amp nrChannels, 0) Generate texture object glActiveTexture(GL TEXTURE0) glGenTextures(1, amp textureId) glBindTexture(GL TEXTURE 2D ARRAY, textureId) Actually load texture if (data) glTexImage3D(GL TEXTURE 2D ARRAY, 0, GL RGBA, width, height, 0, 0, GL RGB, GL UNSIGNED BYTE, data) glGenerateMipmap(GL TEXTURE 2D ARRAY) else std cout lt lt "Failed to load " lt lt path lt lt " texture" lt lt std endl set texture filtering parameters glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MAG FILTER, GL NEAREST) Free memory stbi image free(data) Here is my fragment shader version 330 core out vec4 FragColor in vec2 TexCoord uniform sampler2DArray my sampler void main() FragColor texture(my sampler, vec3(0, 0, 1)) vec4(1.0f) Here is my texture file Does anyone know how I can solve my issue?


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


Rotating a scene around a fixed axis I am looking for a way to move my scene so that when I translate forward back left right it moves directly up down left right on the screen. Currently it does do that until I rotate (by anything other than 360...). After rotation the up down left right moves in the direction of the rotation. I need it to move directly up down left right on screen. I've been racking my brains trying all kinds of different matrix rotations and multiplication but I can't get it. MOST IMPORTANTLY I need it to maintain a single rotation axis of 0,0,0 so the centre of rotation is always near the middle of the screen regardless of how far I scroll. I can easily rotate on the centre of the scene itself and have it translate how I want (translate to co ord, rotate, translate back, go to position) but I need that axis to remain fixed. Otherwise the centre of rotation could be somewhere way off screen. Fig 1. Shows the starting position of the model(scene). Fig 2. The modelview is rotated 45deg. Fig 3. Decrementing the z value causes the model to move out along z which I do not want. Fig 4 I need the model to move straight back (between z and x). I have tried using sin cos rule in an attempt to translate the vertices back along the arc between the undesired position (Fig 3) and the desired one (Fig 4) but the math is off and the process is messy. I just know there has to be a clean simple solution out there. I am coding this in Java (JOGL) and passing modelview and projection matrices to a vertex shader. Also, I am not using deprecated functions (no begin end glRotate etc). Does anyone know of a matrix multiplication that will accomplish this?


GLSL "varying" interpolation component wise? Reference in the spec? Probably a dumb question, but I can't find (or am not understanding) a conclusive answer in the spec or in other questions (e.g., this one). For smoothly interpolated varying vec and mat vertex shader outputs fragment shader inputs, is each element of the vector or matrix interpolated individually? GL spec sec. 13.5.1 (clipping) describes linear clip space interpolation of the "output values associated with a vertex." It also says that those are componentwise for vectors, but doesn't mention matrices. Similarly, sec. 14.5.1 (rasterizing lines) and sec 14.6 (rasterizing polygons) describe interpolation of an "associated datum f for the fragment". Is each element of a vector or matrix considered an individual "associated datum" and interpolated independently from the other elements of the vector or matrix? Secs. 11.1.3.10 (shader outputs) and 15.1 (fragment shader variables) mention interpolation but refer elsewhere for the details. Similarly, in the GLSL spec, sec. 4.5 (interpolation qualifiers) says that interpolation happens but does not distinguish scalars from multi component variables. I am looking for a definitive statement about how vecs and mats are interpolated, if there is one. Or let me know if there isn't! Thank you! (Note answers can be for any OpenGL version.)


opengl storing multiple indices into indices buffer After parsing collada files I found out that we have to load two(or more) indices each pointing to say a vertex or normal etc. like this ( lt p 3 0 2 0 0 0 lt p ) Is there a way to load (and use)these indices to indices buffer(ELEMENT ARRAY BUFFER) like this (vnvnvn...) where v is vertex pointer, n is normal pointer from the above. with vertices loaded to VBO1 like (vvvv...) and in VBO2 like (nnnn...). So that we dont have to repeat the normals in VBO2. VBO like (vnvnvn...) is also ok. (and not something like this https stackoverflow.com questions 11148567 rendering meshes with multiple indices), I'm not trying to use multiple indices buffer. I'm trying to put all the given indices into one index buffer and use them alternately. (If I wasnt clear i will try for more clarification.)


Moving a camera without rolling (tumble not arcball rotation) I'm trying to move my camera around using mouse keyboard. I'm looking for specific camera behaviour however, and I cant figure out how to get it right. What I've found, is that to get a maya tumble style camera, I need to multiply my xrotation in world space then my yrotation. Reversing the order it looks like this view cam move wasd in cam space, this works correctly yrot before world to camera space view xrot after model to world space This means my xrot(world) doesn't interfere with my yrot(eye), which avoids unwanted roll induced by regular cam space x rotation. My problem however, is that I want the xrotation to happen around a point (as if done in eye space) but without creating unwanted roll. I do not know how to get that result. According to my sources It should be as easy as translating inversely before xrotating, then translating back after, but its just not working. Perhaps someone knows how I can get my cam to spin (yaw) around a point, without causing the unwanted roll? SOLUTION Keeping track of pitch yaw (mouse move.xy) seperately, as well as the camera location, and making sure to multiply the yaw before the pitch. Pitching will create unwanted roll, but yawing wont create unwanted pitch, so its a matter of which you do first here. To move the camera in eye space, I do this make a mat3 rotation matrix and multiply it with current movement if (keys 'A' keys 'D' keys 'W' keys 'S' ) camlocation rotated then moved (glm normalize(vec3(keys 'A' keys 'D' , 0, keys 'W' keys 'S' )) move speed) mat3(glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0))) mat3(glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0))) which will be a value to add in world space Then under camera update, or where I build the view matrix, I do this view glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0)) pitch radian float glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0)) yaw also in radian glm translate(mat4(1.0f), camlocation) Just remember that in OpenGL GLM the matrix transformations are reverse order, due to how OpenGL does column row matrix computations. (Compared to directx it saves a transpose operation in the shader (apparently)) Making sure to yaw before pitching, and both after translating (reversed on paper) avoids the unwanted roll, wich yields the desired tumble maya effect!


How to load a spherical planet and its regions? I'm designing a game partially composed of planets exploration. I want to use pseudo random generation for them, regenerating from a defined seed when I have to load them rather than store every detail, which would be too heavy. So I will just store in a file the random seed and modifications done by the player if any. The player must be able to see the planet from orbit (with very low level of details, then go down to the ground, increasing slowly the level of details of the region where he she is landing, and unloading the ones on the other sides of the planet, which go outside the player's field of view. If I had to do it on a plane ground, I would do it easily with a square chunk system. But the problem here is that planets are almost spheres. So what would be the best way to load ground details (relief and grounded objects) around a precise point ? I already though on two solutions, but both have a weak point 1. Cutting the sphere in square chunks. Once the player is close enough of the ground, I just have to improve details of closest squares from his her position. If it is not enough, I still can cut each square in sub squares to load when the players is on or really close of the ground. But as you can see on the picture, there is a problem if the player try to land on a pole squares become very slim rectangles, or even triangles for the last line, and additionally to the fact that they would be many to load, generation would appear distorted. 2. Starting from an icosahedron. Here, I could just increase triangle tessellation around player's position when he she is getting close. But I don't know how to locate triangles close than player's position. I heard Cartesian coordinates could be usefull in that case, but I don't know how to use them. I'm using C OpenGL for it, so the main thing to generate and load here are vertices representing the surface relief and color texture.


OpenGL glTexImage3D not working? I'm trying to use arrax textures with opengl 3.3 since this the target version for my application. So I have to use the glTexImage3D() method instead of glTexStorage3D(). The problem is, if I use glTexImage3D() instead of glTexStorage3D() the screen is always black. The other way round, everything works. Here is how I create the array texture public ArrayTexture(int width, int height) this.width width this.height height this.arrayTextureHandle GL11.glGenTextures() GL13.glActiveTexture(GL13.GL TEXTURE0) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, arrayTextureHandle) Works perfect GL42.glTexStorage3D(GL30.GL TEXTURE 2D ARRAY, 1, GL11.GL RGBA8, width, height, 10) Doesn't work with these parameters GL12.glTexImage3D(GL30.GL TEXTURE 2D ARRAY, 0, GL11.GL RGBA8, width, height, 10, 0, GL11.GL RGBA, GL11.GL UNSIGNED BYTE, (ByteBuffer)null) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, 0) public void addTexture(ScrollingSprite... sprites) if(zLayerCounter sprites.length lt MAX LAYERS) GL13.glActiveTexture(GL13.GL TEXTURE0) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, arrayTextureHandle) Arrays.asList(sprites).forEach(sprite gt sprite.getTexture().getTextureData().prepare() GL12.glTexSubImage3D(GL30.GL TEXTURE 2D ARRAY, 0, Mipmap number 0, 0, zLayerCounter , xoffset, yoffset, zoffset width, height, 1, width, height, depth GL11.GL RGBA, format GL11.GL UNSIGNED BYTE, type sprite.getTexture().getTextureData().consumePixmap().getPixels()) pointer to data GL11.glTexParameteri(GL30.GL TEXTURE 2D ARRAY, GL11.GL TEXTURE WRAP S, sprite.getTextureWrapS()) GL11.glTexParameteri(GL30.GL TEXTURE 2D ARRAY, GL11.GL TEXTURE WRAP T, sprite.getTextureWrapT()) ) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, 0) else throw new IllegalArgumentException("Maximum number of textures reached!")


What advantages does bare OpenGL provide over frameworks engines to small developers? I've noticed a trend of indie developers steering away from frameworks and engines, and moving towards using bare OpenGL, or using it combined with SDL SFML2. As an indie developer, I can't see what low level OpenGL can offer over separate engines or frameworks. Most decent engines and frameworks give the functionality that you need, and never get in your way. They might also open the option to deal with OpenGL directly. Some even offer the functionality to compile cross platform! I understand the aspiration to learn what is happening below the hood, but I can't see any upsides that OpenGL might offer to indie developers over engines or frameworks. Could you explain the reasoning behind building games from scratch using OpenGL?


How to select a vertex by mouse clicking in OpenGL? I'm programming a simple graph game and so far I'm still doing a few tests in OpenGL. Right now, let's say I defined a GL POINT with the glVertex2f(20.0f, 0.0f). I have this function to calculate the coordinates from the mouse input to world coordinates void converterCoords(GLfloat winX, GLfloat winY) GLint viewport 4 GLdouble modelview 16 GLdouble projection 16 GLfloat winZ 0 glGetDoublev( GL MODELVIEW MATRIX, modelview ) glGetDoublev( GL PROJECTION MATRIX, projection ) glGetIntegerv( GL VIEWPORT, viewport ) winX (float)winX winY (float)viewport 3 (float)winY winZ 0 gluUnProject( winX, winY, winZ, modelview, projection, viewport, amp worldX, amp worldY, amp worldZ) After this I have a function to check if the mouse click coordinates are the same as one of the GL POINTS I defined int determinaPosicao(double x, double y) int i for(i 0 i lt nPontos i ) if(pontos i .vX x pontos i .vY y) pontos i .seleccionado 1 glutSetWindow(window) glutPostRedisplay() return 0 I can check just fine if the mouse click is the same as the if condition with the " " function, however, if I have two points with the same x or y value, then it will declare the mouse has hit both points. However, if I use the " amp amp " function it never seems to go into the if condition and never declares any point as having been hit. This certainly isn't the best way to achieve my goal and I would really like to ask for some opinions on how to do this. Solution I found with help from user concept3d int determinaPosicao(double x, double y) const double maxDist (1e0) int i printf(" f n", x) Escala no rato ap s convers o 5510 x (x xMaxRef) 10000 y (y yMaxRef) 10000 for(i 0 i lt nPontos i ) if(pow((pontos i .vX x), 2) lt maxDist amp amp pow((pontos i .vY y), 2) lt maxDist) pontos i .seleccionado 1 glutSetWindow(window) glutPostRedisplay() return 0 The operations I used in x (x xMaxRef) 10000 is a simple rule to scale the mouse coordinates (that range from 0 to approx 5510) from the max ortho referencial scale which is x and y 100, 100


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


Is Windows window creation faster more efficient than GLFW window creation? Are there any benefits to using Windows window for OpenGL or Vulkan rendering, rather than using GLFW window? Is there any performance hits when using C Window creation over GLFW since it provides OpenGL and Vulkan interface?


Finding the Dimension of OBJ objects I am having a Three OBJ file , Cone , Sphere and Cube. How can i find the dimension of these objects , so that i can use it in my collision detection class. i.e How can i find Radius , Length of Cube and Radius and Height of cone. Or is there any better way for collision detection , I have Hundreds of random particle in my game which may or maynot collide with these objects.


How to map trapezoid image to rectangle cubemap face? I am writing a 360 video application on oculus mobile SDK. My video frame has a trapezoid region and I need to map it into a rectangle region. In the above figure, trapezoid ABDC is part of my video frame. I need to map it into a rectangle A'B'D'C'. The rectangle is part of a face of a cube. At the video frame generation side, the trapezoid region is generated from a rectangle region. The bigger side of the trapezoid (AC in the abovefigure) is same as the height of rectangle (side A'C') and smaller side of trapezoid (side BD) is smaller than the height of the rectangle. I know I am loosing some details in this process and I am fine with it. At rendering side for mapping, I need to provide the region as combination of triangles. So I gave two triangles, ABC and CBD. But sice the triangle sizes are not equal, mapping was not proper. The triangle region CBD expands more compare to triangle region ABC. I also tried drawing diagonals to trapezoid ABDC and mapped using four triangles. Even with that logic I observed same issue. Update 1 Please refer to image3(https i.stack.imgur.com yRy9W.jpg) and image1(https i.stack.imgur.com dwOuI.jpg) of this question (https stackoverflow.com questions 15141039 transform rectangle to trapezoid for perspective). Please note, in my application decoded image will be like image3 and I need to render it such that it appears like image1. Can anyone suggest me the right way to map trapezoid to rectangle?


samplerCubeShadow and texture offset I use sampler2DShadow when accessing a single shadow map. I create PCF in this way result textureProjOffset(ShadowSampler, ShadowCoord, ivec2( 1, 1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2( 1,1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1, 1)) result result 0.25 For a cube map I use samplerCubeShadow result texture(ShadowCubeSampler, vec4(normalize(position), depth)) How to adopt above PCF when accessing a cube map ?


Combine a light and water shader in libgdx glsl I am trying to combine a light shader with a water shader in libgdx. Shader programming is not one of my strengths at all. This is the water effect rendering nicely And when I have added the flickering light code I am getting this The light is meant to be a flickering white circle and the water should show up. It doesn't. What I have done so far is try to re arrange texture binding, combine drawing in one pass. I can render the other scene content on top of the water but the water has to be the top most item. That is what I am failing to do, Here is my wall of code (just the render function) public void render() float dt Gdx.graphics.getDeltaTime() water time dt float angle time (2 MathUtils.PI) if (angle gt (2 MathUtils.PI)) angle (2 MathUtils.PI) light zAngle dt zSpeed while (zAngle gt PI2) zAngle PI2 fbo.begin() batch.setProjectionMatrix(cam.combined) batch.setShader(defaultShader) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.begin() float lightSize 140.75f 0.25f (float) Math.sin(zAngle) 27.2f MathUtils.random() batch.draw(lighttex, 400 lightSize 0.5f 0.5f, 300 0.5f lightSize 0.5f, lightSize, lightSize) batch.end() fbo.end() draw the actual scene Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) batch.setShader(finalShader) batch.begin() fbo.getColorBufferTexture().bind(1) lighttex.bind(0) batch.draw(map1BgTex, 0, 0, 960, 540) batch.setShader(waterShader) waterShader.setUniformMatrix("u worldView", cam.combined) batch.end() Gdx.gl20.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) Gdx.gl20.glEnable(GL20.GL BLEND) watertex.bind(1) waterdisptex.bind(2) defWaterShader.begin() defWaterShader.setUniformMatrix("u worldView", matrix) defWaterShader.setUniformi("u texture", 2) defWaterShader.setUniformi("u texture2", 3) defWaterShader.setUniformf("timedelta", angle) waterMesh.render(defWaterShader, GL20.GL TRIANGLE FAN) defWaterShader.end() I uploaded a more complete source file and the shaders to my server, I hope it's not too inconvenient http agexdev.com files shaders.tar.xz


Calling opengl32.DLL from java? I don't like LWJGL in some cases, so I prefer to use Swing. The thing is that Swing doesn't have OpenGL. I have tried JOGL and it's a mess to install, needs external jars, and I have yet to get it working. So I was wondering if I could just make an OpenGL class that uses opengl32.DLL and put the graphics into a window made with Swing? Also, is opengl32.DLL able to be called with a 64 bit Java program?


Two UBO's end up containing the same data I have two separate UBO's for different types of lights (for a light stage in a deferred rendering system). These are defined as follows Pointlight UBO m pointLightBlockIndex glGetUniformBlockIndex(shader.getShaderHandle(), "PointLights") glGetActiveUniformBlockiv(shader.getShaderHandle(), m pointLightBlockIndex, GL UNIFORM BLOCK DATA SIZE, amp m PointLightBlockSize) glUniformBlockBinding(shader.getShaderHandle(), m pointLightBlockIndex, 0) Spotlight UBO m splBlockIndex glGetUniformBlockIndex(shader.getShaderHandle(), "SpotLights") glGetActiveUniformBlockiv(shader.getShaderHandle(), m splBlockIndex, GL UNIFORM BLOCK DATA SIZE, amp m SpotLightBlockSize) glUniformBlockBinding(shader.getShaderHandle(), m splBlockIndex, 0) create the buffers glGenBuffers(1, amp m SLBuffer) glGenBuffers(1, amp m PLBuffer) glBindBuffer(GL UNIFORM BUFFER, m SLBuffer) glBufferData(GL UNIFORM BUFFER, sizeof(SpotLightData) m MaxSpots, nullptr, GL DYNAMIC DRAW) glBindBuffer(GL UNIFORM BUFFER, m PLBuffer) glBufferData(GL UNIFORM BUFFER, sizeof(LightData) m MaxPoints, nullptr, GL DYNAMIC DRAW) glBindBuffer(GL UNIFORM BUFFER, 0) To populate the UBO's I use the following void LightUniformBuffer updatePointLights(int numLights, const LightData data) glBindBuffer(GL UNIFORM BUFFER, m PLBuffer) glBufferSubData(GL UNIFORM BUFFER, 0, sizeof(LightData) numLights, data) glBindBuffer(GL UNIFORM BUFFER, 0) void LightUniformBuffer updateSpotLights(int numLights, const SpotLightData data) glBindBuffer(GL UNIFORM BUFFER, m SLBuffer) glBufferSubData(GL UNIFORM BUFFER, 0, sizeof(SpotLightData) numLights, data) glBindBuffer(GL UNIFORM BUFFER, 0) And finally to bind them void LightUniformBuffer bindPointLights() glBindBufferBase(GL UNIFORM BUFFER, m pointLightBlockIndex, m PLBuffer) void LightUniformBuffer bindSpotLights() glBindBufferBase(GL UNIFORM BUFFER, m splBlockIndex, m SLBuffer) These buffers are represented as arrays of lights in GLSL, like so layout (std140) uniform PointLights LightData points MAX NUM POINT LIGHTS layout (std140) uniform SpotLights SpotLightData spots MAX NUM POINT LIGHTS Now, when I populate the buffers and use the shader, I found, through using Nsight, that both buffers are using the same set of data, i.e. the spotlight buffer is filled with point light data, and so is useless. Why is this happening, and how can I fix it?


Texture Mapping to procedurally generated geometry How can I calculate texture coordinates of such geometry? The angle shown in the image (89.90 degree) may vary, therefore the geometry figure is changing and is not always such uniform.(maybe like geometry in the bottom of image) and red dots are generated procedurally depends on degree of smoothness given.


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


Can I change the order of these OpenGL Win32 calls? I've been adapting the NeHe OpenGL Win32 code to be more object oriented and I don't like the way some of the calls are structured. The example has the following pseudo structure Register window class Change display settings with a DEVMODE Adjust window rect Create window Get DC Find closest matching pixel format Set the pixel format to closest match Create rendering context Make that context current Show the window Set it to foreground Set it to having focus Resize the GL scene Init GL The points in bold are what I want to move into a rendering class (the rest are what I see being pure Win32 calls) but I'm not sure if I can call them after the Win32 calls. Essentially what I'm aiming for is to encapsulate the Win32 calls into a Platform Initiate() type method and the rest into a sort of Renderer Initiate() method. So my question essentially boils down to quot Would OpenGL allow these methods to be called in this order? quot Register window class Adjust window rect Create window Get DC Show the window Set it to foreground Set it to having focus Change display settings with a DEVMODE Find closest matching pixel format Set the pixel format to closest match Create rendering context Make that context current Resize the GL scene Init GL (obviously passing through the appropriate window handles and device contexts) Thanks in advance.


Opengl binding shaders vs binding buffers performance Quick question for an opengl guru, I'm in the process of building a render queue and can either reduce the number of shader binding or the number of vertex buffer binding. I just want to know which one is more expensive on newer graphics cards (IE)(opengl 3.2)?


Errors when loading Assimp meshes I am experiencing some oddities when loading meshes in Assimp. Some models render perfectly, while others are complete jumbles of triangles. Some Example Images Teapot Correct Teapot Actual Flower Correct Flower Actual OBJ download links Teapot.obj Flower.obj I've searched far and wide, and I cant seem to pin down the cause of this. I have noticed while debugging that the value of ai mesh gt mNumVertices differs from what Assimp Viewer or Blender display. ai mesh gt mNumVertices is smaller in the Teapot example by 156 vertices, and larger in the Flower example by 20 vertices. I've considered that Assimp post processing may be causing the difference here. However, I'm using the EXACT same post processing flags used in Assimp Viewer, copied directly from the source code. Here is my Mesh Loader mesh mesh(aiMesh ai mesh, model parent model) mesh() name ai mesh gt mName.length ! 0 ? ai mesh gt mName.C Str() "" Get Vertices if (ai mesh gt mNumVertices gt 0) for (int ii 0 ii lt ai mesh gt mNumVertices ii ) aiVector3D ai ai mesh gt mVertices ii glm vec3 vec glm vec3(ai.x, ai.y, ai.z) vertices .push back(vec) Get Normals if (ai mesh gt HasNormals()) for (int ii 0 ii lt ai mesh gt mNumVertices ii ) aiVector3D ai ai mesh gt mNormals ii glm vec3 vec glm vec3(ai.x, ai.y, ai.z) normals .push back(vec) Get mesh indexes for (int t 0 t lt ai mesh gt mNumFaces t ) aiFace face amp ai mesh gt mFaces t if (face gt mNumIndices ! 3) std cout lt lt " ?? Mesh face with not exactly 3 indices, ignoring this primitive. n" continue indices .push back(face gt mIndices 0 ) indices .push back(face gt mIndices 1 ) indices .push back(face gt mIndices 2 ) material parent model gt getMaterial(ai mesh gt mMaterialIndex) And render function, just in case. void mesh render() material gt bind() glVertexPointer(3, GL FLOAT, 0, amp vertices 0 ) glNormalPointer(GL FLOAT, 0, amp normals 0 ) glDrawElements(GL TRIANGLES, indices .size(), GL UNSIGNED BYTE, amp indices 0 ) Thanks ahead.


What does glBlendFunc(GL DST COLOR, GL ZERO) mean? I need to write a description about a filter method I made but I don't know what glBlendFunc(GL DST COLOR, GL ZERO) means.


Unpacking Sprite Sheet Into 2D Texture Array I am using WebGL 2. A tag for it does not exist but it should. I have a 10x10 sprite sheet of squares that are 16x16 pixels in size (all in one PNG image). I'd like to create a 2D texture array out of them, where each 16x16 square gets its own, unique Z depth value. let texture gl.createTexture() let image new Image() image.onload function() gl.bindTexture(gl.TEXTURE 2D ARRAY, texture) gl.pixelStorei(gl.UNPACK FLIP Y WEBGL, false) gl.texStorage3D(gl.TEXTURE 2D ARRAY, 5, gl.RGBA, 16, 16, NUM IMAGES) Now what? gl.texSubImage3D doesn't let me copy in a section of the src image image.src "https source url.fake image.png" I know that gl.texSubImage3D exists but it only accepts an entire image as a source? glTexSubImage3D https www.khronos.org registry OpenGL Refpages gl2.1 xhtml glTexSubImage3D.xml


Creating a DPI and Resolution Independant GUI How would one best go about it? Assuming I'm using OpenGL to do all the drawing. It seems like the best approach is to have the GUI elements maintain the same physical size regardless of the screen it is displayed on.It seems that Windows will act as if you had a screen with 72 DPI regardless of its actual size unless you specifically request tell it that you handle high DPI cases. Which would greatly simplify things, does this hold for Linux as well? Does things change between running things in Windowed mode versus fullscreen? It seems like it should, as the Window changes size depending on resultion while in fullscreen the image is always the same size, just with less or more density!


How to use continious collision detection in a dynamic AABB tree I am currently writing a game in c using openGL, and I am currently using a kinetic sweep and prune algorithm for the broad phase and then using GJK Raycast GJK amp EPA for the narrow phase. However I have realized that kinetic sweep and prune may not be the best choice because there are many objects in the scene that are just static and cause a lot of swapping when an object moves. So basically I would like to implement a dynamic AABB tree for the broad phase knowing there will be only a few objects requiring continuous collision detection (but these objects are essential). However for these fast moving objects what is the best way to detect a possible collision with other objects in the broad phase? I am thinking about using an AABB that contains the object trajectory from one frame to another, is this a good idea? Or will this a lot of overhead due to many false positives? Also I haven't read to much about dynamic AABB trees but I think I understand the idea, the idea is for each object that moved check if it's AABB if overlapping with the tree node, if it is do the same check with it's children and do so until we are at the leaves of the tree. All help is greatly appreciated


How to enable geometry shader in OpenGL 4.2? I'm porting my Direct3D based engine to OpenGL and I'm using geometry shaders for rendering text characters (basically, textured billboards). D3D version works fine, but in OpenGL mode it gives only a flickering point right in the center of the screen. It seems that somehow the geometry shader stage is not enabled (in AMD GPUPerfStudio the box, representing GS stage, is grayed out). I tripple checked the OpenGL back end and the shader code but couldn't find any mistakes. Maybe, I'm missing something. Below is the source code of the relevant shaders Vertex shader in vec4 in xy wh in vec4 in tl br UVs for top left and bottom right corners out vec4 v xy wh out vec4 v tl br void main() v xy wh in xy wh v tl br in tl br Geometry shader layout(points) in layout(triangle strip, max vertices 4) out in vec4 v xy wh in vec4 v tl br UVs for top left and bottom right corners out vec2 v uv void main() vec2 pos v xy wh 0 .xy float width v xy wh 0 .z float height v xy wh 0 .w vec2 tl v tl br 0 .xy vec2 br v tl br 0 .zw gl Position vec4( pos.x, pos.y, 0.0f, 1.0f ) v uv vec2( tl.x, tl.y ) EmitVertex() gl Position vec4( pos.x width, pos.y, 0.0f, 1.0f ) v uv vec2( br.x, tl.y ) EmitVertex() gl Position vec4( pos.x, pos.y height, 0.0f, 1.0f ) v uv vec2( tl.x, br.y ) EmitVertex() gl Position vec4( pos.x width, pos.y height, 0.0f, 1.0f ) v uv vec2( br.x, br.y ) EmitVertex() EndPrimitive() Fragment shader in vec2 v uv out vec4 v color uniform sampler2D s font void main() vec4 color texture( s font, v uv ).rgba if( color.w lt 1.0 255.0 ) discard v color color I've added the " version 420 core" preamble to each shader. I know I shouldn't use the glProgramParameteriEXT function to define GL GEOMETRY INPUT TYPE EXT, GL GEOMETRY OUTPUT TYPE EXT, GL GEOMETRY VERTICES OUT EXT, because these parameters are specified in the geometry shader (which is core in OpenGL 4.2). EDIT My mistake was incorrect usage of glVertexAttribPointer (wrong value of the the last parameter). Thanks for all the answers and sorry for your wasted time!


How do I change a sprite's color? In my rhythm game, I have a note object which can be of a different color depending on the note chart. I could use a sprite sheet with all the different color variations I use, but I would prefer to parametrize this. (Each note sprite is made of different shades of a hue. For example a red note has only red, light red and dark red.) How can I colourise a sprite anew? I'm working with OpenGL, but any algorithm or math explanation will do. )


Can you trilinear sample a non volume texture? Let's say that i have a regular 2d texture (not a volume texture). Is it possible to do trilinear texture sampling of that texture even though it isn't a volume texture in opengl or directx? Specifically, if i had a 2x4 texture laid out like below where A through H are pixels A B C D E F G H What I'd like to get is a trilinear sample being the result of linearly interpolating the bilinear sampling of (A,B,C,D) and (E,F,G,H). I know i could take two bilinear texture samples and lerp them to get what I want, but is there a hardware supported way to do this?


360 degree video of my OpenGL game I want to make a 360 degree video of my OpenGL game. Concerning the rendering Is it enough to render it in OpenGL with a specific projection matrix? If yes, which one? Or can I render it into a cube map, and then encode it? (Which will require much more rendering power and be more complicated, which I want to avoid) And how do I encode a 360 degree video with FFMPEG?


Easy way to set face colors with indexed VBOs? I'm loading OBJs, which lend themselves well to setting up as indexed VBOs, since each vertex is only defined once and then a face definition will reference the same vertex more than once when they share an edge. I want to define face colors based on the materials loaded from the OBJ. This is quite easy in immediate mode, but I've realized that using VBOs will require me to duplicate each vertex in order to have two adjacent faces with different colors. What's the best way to go about solving this without duplicating vertices? EDIT Code (LWJGL) Get the VBO from the GPU glBindBuffer(GL ARRAY BUFFER, vbo) Tell OpenGL what to expect from the VBO glVertexAttribPointer(0, 3, GL FLOAT, false, Vertex.SIZE 4, 0) Location glVertexAttribPointer(1, 2, GL FLOAT, false, Vertex.SIZE 4, 4 3) Texture Coord glVertexAttribPointer(2, 3, GL FLOAT, false, Vertex.SIZE 4, 4 3 4 2) Normal glBindBuffer(GL ELEMENT ARRAY BUFFER, ibo) glDrawElements(GL TRIANGLES, size, GL UNSIGNED INT, 0)


LibGDX Draw multiple textures with different positions with one shader? currently I'm optimizing my render calls by drawing multiple textures with one shader. The background textures who all share the same position are no problem. But now I want to draw some Textures with different positions with one shader. I think it isn't possible, because the textures don't have the same geometry. But maybe there is a possible way to do this? I never worked with the geometry shader for example. For example, draw a 512x512 texture to position (100, 50), draw a 256x256 texture to position (500, 300)... , like in this picture


C OpenGL More textured objects equals less FPS So I'm creating a game engine with many features, last time I focused on textures. When I finished implementing some new code (Made by myself) I created new Entity with texture, and it was working really nice. But If I create 2 or more textured objects game starts lagging.. 1 Cube without texture 60 FPS 1 Cube with texture 60 FPS 2 Cubes without texture 60 FPS 2 Cubes with texture 40 50 FPS 10 Cubes without texture 60 FPS 10 Cubes with texture 20 FPS 100 Cubes without Texture 60 FPS 100 Cubes with Texture lt 1 FPS 10000 Cubes without Texture 60 FPS I'm using GLSL sampler2D, texture UV from VBO, here is my renderer code bool textured false if(entity gt hasComponent("MaterialComponent")) MaterialComponent materialComponent (MaterialComponent ) entity gt getComponent("MaterialComponent") if(materialComponent gt material ! NULL amp amp materialComponent gt material gt texture ! NULL) textured true if(component gt cullFaces) glEnable(GL CULL FACE) glCullFace(GL BACK) if(textured) glEnable(GL TEXTURE 2D) glBindVertexArray(component gt model gt vaoID) glEnableVertexAttribArray(0) if(textured) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) glDrawElements(GL TRIANGLES, component gt model gt getVertexCount(), GL UNSIGNED INT, 0) if(textured) MaterialComponent materialComponent (MaterialComponent ) entity gt getComponent("MaterialComponent") if(materialComponent gt material gt texture gt textureID 0) glGenTextures(1, amp materialComponent gt material gt texture gt textureID) glBindTexture(GL TEXTURE 2D, materialComponent gt material gt texture gt textureID) SDL Surface surface IMG Load(materialComponent gt material gt texture gt textureFile gt getPath().c str()) if(!surface) Error throwError("Cannot load texture file!") S32 colorMode GL RGB if(surface gt format gt BytesPerPixel 4) colorMode GL RGBA glTexImage2D(GL TEXTURE 2D, 0, colorMode, surface gt w, surface gt h, 0, colorMode, GL UNSIGNED BYTE, surface gt pixels) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP LINEAR) glGenerateMipmap(GL TEXTURE 2D) glActiveTexture(GL TEXTURE0) glUniform1i(baseShader gt loc sampler, 0) SDL FreeSurface(surface) glDrawElements(GL TRIANGLES, component gt model gt getVertexCount(), GL UNSIGNED INT, 0) if(textured) glBindTexture(GL TEXTURE 2D, 0) glDisable(GL TEXTURE 2D) glDisableVertexAttribArray(0) if(textured) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) glBindVertexArray(0) if(textured) glDisable(GL TEXTURE 2D) if(component gt cullFaces) glDisable(GL CULL FACE) So I can create new TextureAsset for each cube or I can use one TextureAsset for each cube, it makes no difference about FPS. I'm creating new TextureAsset like this TextureAsset textureAsset new TextureAsset(new FilePath("PATH TO TEXTURE")) Then putting it inside Entity' MaterialComponent MaterialComponent materialC (MaterialComponent ) cube1 gt getComponent("MaterialComponent") materialC gt materialAsset gt texture textureAsset I think there is something bad inside my renderer method, it happens only if there is more than 1 textured object. Maybe I have to clean up texture in different way? I'm using SDL2, SDL2 image and GLEW. If you need more code just tell me.


Animating a jellyfish hardcoding? I have drew a hemi sphere by myself, and would like to do basic jellyfish animation by animating the vertices of the hemi sphere. I tried a lot of experiments but it seems I'm doing it wrong. I need hints or idea on about doing it. This is the code on how to draw a hemi sphere. I don't know what values actually to play with to animate the sphere as a jellyfish. for(float phi 0.0 phi lt 1.567 phi factor) glBegin(GL QUAD STRIP) for(float theta 0.0 theta lt 2 3.14 factor theta factor) x rh sin(phi) cos(theta) z rh sin(phi) sin(theta) y rh cos(phi) gl vertex(Vec3f(x, y, z)) x rh sin(phi factor) cos(theta) z rh sin(phi factor) sin(theta) y rh cos(phi factor) gl vertex(Vec3f(x, y, z)) glEnd()


Do OpenGL buffers overflow to CPU memory? This is a question about OpenGL buffers and memory. My game world is mid sized, one contiguous space, unchanging, and only partially visible from any position. Will modern OpenGL overflow buffers into CPU memory? And if so, can I just allocate buffers (vertex and texture) for all of it, and adjust my draw calls to skip non visible areas, and let OpenGL pull buffers into GPU as needed, hopefully minimizing thrashing? (Or does OpenGL just fail on the allocate after a while?) EDIT The above was ambiguous. But maybe both variations are interesting. Could I just allocate one huge vertex buffer and a few giant textures, and hope that OpenGL moves parts of it in and out of the GPU as needed, and maybe enough early depth testing lets it skip some of the texture drawing... Could I have a handful, or maybe a lot, of "sensibly sized" vertex and texture buffers, but only glDrawXxx() some of them on each frame? In that case, would OpenGL move them up and down from the GPU, maybe in a least recently used sort of way?


How to free the GPU from a long task? I'm developing an application that uses the GPU. Some tasks might be rather long (like a fragment shader with a loop). I have the impression that I can make the entire OS visually freeze by asking the GPU to perform a job that doesn't end. Of course, I'm not doing this on purpose, but when that accidentally happens, I have to force power off my machine and this is very difficult to debug. Some questions Is this behaviour normal? Or could this be a bug in the hardware or driver? Is there a technique to recover from this without force stopping my machine? Since the OS is still functioning (only not rendering), I could try to ssh into my machine and kill the process. Would that free the GPU from its job? Update I tried to ssh into my machine and sudo kill 9 pid , but didn't work. I would like to know if there is an OS independent answer for this. If there isn't, my setup is macOS, with OpenGL (running on Intel HD Graphics 3000).


How do i set up 9 slicing in Opengl? What is the ideal way to set up 9 slicing? (for the people who don't know what 9 slicing is) Let's say we have a quad, with a texture applied to it. 9 slicing is basically a way of dividing a texture in 9 parts. The reason why we do this is to have a quad with a texture, that can be resized without the issue of having the texture all warped. we divide the edges, the corners, and the main body of the texture As can be seen in the pictures, we have a quad that can be scaled without warping the texture which would look something like this(no 9 slicing) Now, to come back to my question How should i set up 9 slicing? should i have a multiple quads(one for the center part, one for the right edge, one for the left edge....) but then how do i specify the different texture coordinates for each quad? Another way would be to just create the quads with their texture coordinates and relative textures and then move them all toghether like a whole object. I hope someone explain me a little more about this "9 slicing" approach, since I've never used it before. Thanks everyone for the help EDIT (to answer HolyBlackCat) "Another way would be to just create the quads with their texture coordinates and relative textures and then move them all toghether like a whole object." What i wanted to say is this I create separate quads, attach separate textures to them, render and move them at the same time This is, in my opinion, the most logical way to do this. Despite that, I still want to know what would be a better, faster way to do this, without having to have too many vertices for a quad


Best way to do buttons for an OpenGL ES iPhone game I'm making a simple 2d game in OpenGL ES and I want to add movement buttons to it. What's the best way of going about this? In previous projects I've simply added UIButtons to the view but I hear there are performance implications in doing so with OpenGL ES so I'm wondering what the possible alternatives are if so.


Point Light shows black box rect (PointLight not working) libgdx 3D I am creating a 3d scene currently a box and rect, and trying to enable lighting. When i create a PointLight and add it to Environment everything turns to black color? all i want to do is create a 3d scene and enable point light, like a sun or rays coming from a point and shading the objects. Code environment new Environment() environment.add(new PointLight().set(1f, 1f, 1f, 0, 0, 20f, 100f)) modelBatch new ModelBatch() .. square new ModelBuilder().createBox(300,300,300,new Material(ColorAttribute.createDiffuse(Color.GREEN)), VertexAttributes.Usage.Position VertexAttributes.Usage.Normal) squareinst new ModelInstance(square) squareinst.transform.setTranslation( 500,0,0) sprites.get(0).setRotationY(sprites.get(0).getRotationY() 1f) sprites.get(1).setRotationY(sprites.get(1).getRotationY() 1f) squareinst.transform.rotate(1,0,0,1) modelBatch.begin(camera) for(Sprite3D sp sprites) has 3d rect models sp.draw(modelBatch,environment) modelBatch.render(squareinst,environment) modelBatch.end() PointLight turning everything black Without using environment or lights as per my investigation, here if pointlight is not working then everything should be black as currently, because the environment needs light, it works fine with Directional light (only the backface of rect is black even after rotations, i don't know why) libgdx version 1.6.1 android studio i checked it on both android device and desktop please i really need to get this PointLight working, i don't know if it will take a custom shader, if so please guide me to some links because i am not experienced in shaders. I also read about PointLight not working on some device or not working in opengl 2.0 enabled, but i am not sure.


Transferring my OpenGL PC game to PS4 and or XBox One I want to transfer my OpenGL PC game to consoles, PS4 and or XBox One. It's a complex application, where many calculations (incl. fast fourier transformations) via FBOs and Transformfeedback are performed within OpenGL. What is the best way to bring it to the PS4? Or is it easier to implement the game in an engine like Unity or Unreal. As far as I know they have console support? An advantage would be that we could offer our methods as plugin asset. We are planning to do this too. There are a lot of glsl shaders and OpenGL Api Calls. Is it possible at all to "translate" that into an engine like unreal? Or would we have to use the engines "predefined" rendnering mechanisms? We basically need shaders operating on floating point textures, changing render targets frequently and transform feedback if possible. We also need low level acces to shading attributes like changing pointsize in the vertex shader etc. And I really would like to know which is less work. I could image that it is possible to absctract all the Api Calls in classes functions and then where first all the OpenGL calls are implemted and then we would do an implemetation for the console api. Is this realistic on the PS4 Api? I know that Direct X will have a different design and therefore abstraction itself won't be enough. I believe porting to an engine might be even more work as you have to respect its structures.


glDrawElements draws nothing As the title says . ( nothing is drawn on screen is there something I'm missing? Mesh Mesh Create(GLfloat vertices , GLuint indices , GLfloat uvs , GLfloat colors ) Mesh mesh (Mesh )malloc(sizeof(Mesh)) mesh gt vertices (GLfloat )malloc(sizeof(vertices)) memcpy(mesh gt vertices, vertices, sizeof(vertices)) mesh gt indices (GLuint )malloc(sizeof(indices)) memcpy(mesh gt indices, indices, sizeof(indices)) mesh gt elementCount sizeof(indices) sizeof(GLuint) glGenVertexArrays(1, amp mesh gt vao) glBindVertexArray(mesh gt vao) glGenBuffers(1, amp mesh gt vbo VERTEXBUFFER ) glBindBuffer(GL ARRAY BUFFER, mesh gt vbo VERTEXBUFFER ) glBufferData(GL ARRAY BUFFER, sizeof(mesh gt vertices), amp mesh gt vertices, GL STATIC DRAW) glVertexAttribPointer(0, 2, GL FLOAT, false, 0, 0) glEnableVertexAttribArray(0) glGenBuffers(1, amp mesh gt vbo TEXTUREBUFFER ) glBindBuffer(GL ARRAY BUFFER, mesh gt vbo TEXTUREBUFFER ) glBufferData(GL ARRAY BUFFER, sizeof(uvs), uvs, GL STATIC DRAW) glVertexAttribPointer(1, 2, GL FLOAT, false, 0, 0) glEnableVertexAttribArray(1) glGenBuffers(1, amp mesh gt vbo INDICESBUFFER ) glBindBuffer(GL ELEMENT ARRAY BUFFER, mesh gt vbo INDICESBUFFER ) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(mesh gt indices), amp mesh gt indices, GL STATIC DRAW) glGenBuffers(1, amp mesh gt vbo COLORBUFFER ) glBindBuffer(GL ARRAY BUFFER, mesh gt vbo COLORBUFFER ) glBufferData(GL ARRAY BUFFER, sizeof(colors), colors, GL STATIC DRAW) glVertexAttribPointer(3, 4, GL FLOAT, false, 4 sizeof(GLfloat), NULL) glEnableVertexAttribArray(3) glBindVertexArray(0) glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) glBindBuffer(GL ARRAY BUFFER, 0) return mesh Mesh Mesh CreateQuad() GLfloat vertices 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5 GLuint indices 0,1,2, 0,2,3 GLfloat uvs 0 , 1, 1, 1, 1, 0, 0, 0 GLfloat colors 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 return Mesh Create(vertices, indices, uvs, colors) void Mesh Render(Mesh mesh) glBindVertexArray(mesh gt vao) glDrawElements(GL TRIANGLES, mesh gt elementCount, GL UNSIGNED INT, amp mesh gt indices)


Bones Animation Matrices and calculations We are 'on final' when it comes to finishing the project, but just before implementing the animation system. Our Client decided to choose "Bones Animation" which is that I should export each Transformation Matrix ( matrix4x4 rotation translation ) for every frame and for every bone that this animated object has. Objects in our game are animated with 3DS Max Physique Modifier, so we will have bones weighting data per vertex. But I will simplify things here just to get a bit of light on this subject. I would like to split this post into 2 points, where Exporting bones matrices for every frame treats about the correct method of exporting the bones positions for later animation purposes, where i have to 'move' and 'rotate' every vertex influenced by this bone to bone position at frame X. Calculating final vertex position treats about proper matrices operations to calculate new vertex position according to bone transformation in frame X. 1. EXPORTING BONES MATRICES FOR EVERY FRAME Do I understand correctly that while exporting the animated object I should Grab BONE transformation matrix at frame 0 and Invert this matrix Grab BONE transformation matrix at FRAMEx Multiply 1 2 to get the transformation offset of the BONE at FRAMEx pseudocode Animation export For each frame, export bone transformation offset for(int iFrame 0 iFrame lt vFrames.size() iFrame ) For every bone in the object for(int iBone 0 iBone lt vBones.size() iBone ) Grab transformation matrix for this bone at frame 0 and inverse it Matrix3 matBoneMatrixAtStart pNode gt GetObjectTMAfterWSM( 0 ) matBoneMatrixAtStart.Inverse() Grab transformation matrix for this bone at frame iFrame Matrix3 matBoneMatrixAtCurrentFrame pNode gt GetObjectTMAfterWSM( iFrame ) Multiply Inversed Transformation Matrix of this bone at frame 0 with current frame transformation matrix Matrix3 matBoneTransformationOffset matBoneMatrixAtStart matBoneMatrixAtCurrentFrame Save matBoneTransformationOffset vertex will be multiplied by this matrix for animation purposes fwrite(.....) pseudocode Will that be enough ? Or there is something I am missing here? 2. CALCULATING NEW VERTICES POSITIONS ( FINAL VERTEX POSITION AT FRAME X) Later on, when rendering, object vertices are going to be multiplied by exported bone transformation matrix for actual animation frame, and then multiplied by this whole model transformation matrix to place the object in correct position inside the level pseudocode Update() The model transformation matrix describing the position of the model in the level matModelTransformationMatrix Calculate new vertex position according to it's bone transformation offset NewVertexPosition (OriginalVertexPosition matBoneTransformationOffset iFrame ) matModelTransformationMatrix Increment the frame for testing purposes iFrame pseudocode Am I thinking correct here? So, Having bone transformation offset for frame X, multiplying every vertex affected by this bone by this offset should result in a vertex transformed exactly as this bone right?


Handling multiple lights of different types in GLSL I want to be able to support multiple lights of different types (point, spot amp directional). Note that I also want to be able to render transparent translucent objects, which rules out deferred rendering. This means that I will need a fixed upper limit on the number of lights. All of the implementations I have seen use a uniform array, for example struct PointLight vec3 color float intensity float radius uniform PointLight pointLights 8 How can I best extend this to multiple types of lights? Two possible options are Create multiple uniform arrays, one for each type of light. Define a struct that can be used for all three types of light and then have some way of differentiating the types of lights in the array (e.g. using start index and count uniforms or adding some kind of type flag to the struct). Both have disadvantages. Both waste memory (although the first more so than the second) and the second either requires additional uniforms or flag checking. What is the usual method for handling multiple lights of various types?


Rotate an object given only by its points? I was recently writing a simple 3D maze FPP game. Once I was done fiddling with planes in OpenGL, I wanted to add support for importing Blender objects. The approach I used was triangulization of the object, then using Three.js to export the points to plaintext and then parsing the result JSON in my app. The example file can be seen here https github.com d33tah tinyfpp blob master Data Models cross.txt The numbers represent x,y,z,u,v of a single vertex, which combined in three make a triangle. Then I rendered such an object triangle by triangle and played with it. I could move it back and forth and sideways, but I still have no idea how to rotate it by some axis. Let's say I'd like to rotate all the points by five degrees to the left, how would a code doing it look like?


How to draw a rotatable and zoomable sphere? My game is a sort of business simulation game of Earth, and I want the main interface to be just like a google earth view. Is there a way to do this with built in OpenGL features or do I have to implement the engine myself.


How can I forward GLFW's keyboard input to another object? I'm having trouble trying to execute keyboard events in a another class with GLFW3. The problem I'm having is that GLFW3 uses a static function for input as shown static UI u ... ... static void key callback(GLFWwindow window, int key, int scancode, int action, int mods) u.controls(window, key, action) u is also static and controls holds the the input for WSAD keys (the only way I could get get key events). From here, pressing a key works displaying which key is pressed in the console window. The trouble I'm having is trying to used the key pressed to manipulate a variable in another class. I have another class called MainMenu that has the function update(). Is there a way I can use my UI class within this function?


How do I create a view matrix that does not contain the camera translation? I'm looking at this tutorial https capnramses.github.io opengl cubemaps.html about half way down the webpage, there is a description of a vertex shader version 400 in vec3 vp uniform mat4 P, V out vec3 texcoords void main() texcoords vp gl Position P V vec4(vp, 1.0) The P and V matrices are my camera's projection, and view matrices, respectively. The view matrix here is a special version of the camera's view matrix that does not contain the camera translation. Inside my main loop I check if the camera has moved. If so I build a very simple view matrix and update its uniform for the cube map shader. This camera only can only rotate on the Y Axis, but you might use a quaternion to generate a matrix for a free look camera. Remember that view matrices use negated orientations so that the scene is rotated around the camera. Of course if you are using a different maths library then you will have different matrix functions here. I'm having difficulty figuring out how to construct this matrix in my program. How would I construct it from a projection matrix, view matrix, or camera matrix? (These are the matrices already within my program)


Texturing a PyOpenGL 3D Cube with PySDL2 So, I've just started learning OpenGL with PySDL2, and I've created a class that will create a cube to the window that I've created with PySDL2. What I'd like to do now, is to figure out a way to texture the cube. I don't believe that the actual texturing part is the problem, but actually loading the image. I've tried to do this with PySDL's image loader, but this causes an error from the OpenGL texture creator. Here is my code to load an texture and bind it to OpenGL def LoadTexture(self, filename) """Loads a texture for the cube""" surface SDL LoadBMP(filename) Checks if the loading succeeded if surface Translate the LP SDL Surface pointer got from SDL LoadBMP() to a real SDL Surface texture surface surface.contents texture format GL.GL RGBA GL TEXTURE ID GL.glGenTextures(1) GL.glBindTexture(GL.GL TEXTURE 2D, GL TEXTURE ID) GL.glPixelStorei(GL.GL UNPACK ALIGNMENT, 1) GL.glTexImage2D(GL.GL TEXTURE 2D, 0, 3, texture surface.w, texture surface.h, 0, texture format, GL.GL UNSIGNED BYTE, texture surface) return GL TEXTURE ID return None And the error that gives looks like this TypeError ("No array type handler for type lt class 'sdl2.surface.SDL Surface' gt (value lt sdl2.surface.SDL Surface object at 0x030762B0 gt ) registered", lt OpenGL.GL.images.ImageInputConverter object at 0x02EC49F0 gt ) I'm using Python 3 so using something like PIL won't work for me. Any ideas how to get the texture loaded, preferably with PySDL2?


Opengl es picking object I saw a lot of picking code opengl es, but nothing worked. Can someone give me what am I missing? My code is (from tutorials forums) Vec3 far Camera.getPosition() Vec3 near Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0) Vec3 direction far.sub(near) direction.normalize() Log.e("direction", direction.x " " direction.y " " direction.z) Ray mouseRay new Ray(near, direction) for (int n 0 n lt ObjectFactory.objects.size() n ) if (ObjectFactory.objects.get(n)! null) IObject obj ObjectFactory.objects.get(n) float discriminant, b float radius 0.1f b mouseRay.getOrigin().dot(mouseRay.getDirection()) discriminant b b mouseRay.getOrigin().dot(mouseRay.getOrigin()) radius radius discriminant FloatMath.sqrt(discriminant) double x1 b discriminant double x2 b discriminant Log.e("asd", obj.getName() " " discriminant " " x1 " " x2) my camera vectors cam Vec3 position new Vec3( obj.getPosX() x, obj.getPosZ() 0.3f, obj.getPosY() z) Vec3 direction new Vec3( obj.getPosX(), obj.getPosZ(), obj.getPosY()) Vec3 up new Vec3(0.0f, 1.0f, 0.0f) Camera.set(position, direction, up) and my picking code public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) int viewport getViewport() float modelview getModelView() float projection getProjection() float winX, winY float position new float 4 winX (float)mouseX winY (float)Shared.screen.width (float)mouseY GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0) return new Vec3(position 0 , position 1 , position 2 ) My camera moving all the time in 3d space. and my actors modells moving too. my camera is following one actor modell and the user can move the camera on a circle on this model. How can I change the above code to working?


How can I identify loaded models so I can efficiently avoid loading them twice? I'm making a fairly basic OpenGL 3D engine, at the moment. In this engine, when you load an object, you would write manager gt LoadObjFile("cube.obj") manager gt AddParent("uvmap.bmp", "cube.obj", "cube", glm vec3(10.0f, 1.0f, 0.0f)) "uvmap.bmp" being the texture, "cube.obj" is the .obj file path, "cube" being the ID for the object. My question is, at the moment, when it loads an object, it stores the object in a struct with all of the buffer data and an ID, the ID being the path of the obj file, so when I load an .obj, it runs through all of the already loaded files and compared the ID of each using strcmp, which obviously when there's thousands of items, is going to start to get a bit slow.... it does the same for AddParent, and most of my other methods (different vector of data than where the obj data is stored). What would be best in terms of identifying items, an integer? I really don't know, I want this to be as high level, user friendly as possible, but want to keep it as optimized and as efficient as possible.


Assimp, Blender and model rotating There is something I can't figure out. I have two models grass.blend and tower.blend. grass.blend tower.blend Note X, Y and Z axises. The problem is that when I load these models using Assimp the scene looks like this The tower should be placed vertically, but for some reason it is placed horizontally. I didn't rotate it this way. Why is it happening? Project example is here (tower was rotated in Blender right way for now). Tower model could be downloaded from blendswap.com.


How can I deal with vertex precision errors between terrain chunks? I am using OpenGL to render the following scene, using vertex data from one of the map files of a popular MMORPG. The data is chunked and the pictured scene is made up of 256 (16x16) chunks. However between the chunks I am seeing what I believe to be glitches due to the float precision. Yet I am not doing any large translations and rendering very close to the origin, should I be seeing this problem? The glitches very noticeable as you fly over the scene with it flickering different points along the chunk edges. I was wondering if I was overlooking something simple or there are tricks other games use to mask this problem. I guess the source data could be the reason for this problem but I am not aware of it happening in the original game. View screenshots in a new window to see the issue.


GLFW mouselook under OSX I'm continuing to port an OpenGL app from Visual Studio 2012 to XCode 5. The only major issue I'm having is mouselook. It "doesn't work" under OSX (Mavericks). Here's the (pseudocode) Pre update, executed at the start of the frame void Dispatcher PreUpdate(GameTime amp time) m currentKeyboardState m nextKeyboardState m previousMousePosition m currentMousePosition GetMousePosition(m currentMousePosition) Post update, executed, well, after input processing, at the end of the frame void Dispatcher PostUpdate(GameTime amp time) m previousKeyboardState m currentKeyboardState if (m captureMouse) RecenterMouse() Method to recenter the mouse void Dispatcher RecenterMouse() glfwSetCursorPos(m window, m windowSize.x 2.f, m windowSize.y 2.f) GetMousePosition(m currentMousePosition) if (m previousMousePosition ! m currentMousePosition) cout lt lt "Mouse " lt lt m currentMousePosition.x lt lt "," lt lt m currentMousePosition.y lt lt endl m previousMousePosition m currentMousePosition And, jut for completeness void Dispatcher GetMouseMotion(Vector2 amp movedBy) if(m captureMouse) movedBy.x (m currentMousePosition.x m previousMousePosition.x) movedBy.y (m currentMousePosition.y m previousMousePosition.y) else movedBy.x movedBy.y 0 If m captureMouse is true, and m previousMousePosition ! m currentMousePosition, the y delta is always 1, no matter how far I've moved the mouse. (Actually, using the trackpad, but should be indentical.) This code works perfectly under Win7, but never returns anything other motion than (0,1) under OSX. Suggestions? I've seen other questions regarding glfw and osx, but no solutions. EDIT It's worth noting if I turn off mouse capture (which basically does everything but recenter the mouse at the end of the frame), mouselook works correctly but, of course, the cursor is free to wander outside of the window, which doesn't really work for a first person app.


OpenGL, Blender and model optimization I'm learning OpenGL and there is something I don't understand regarding model loading. Lets say I found a free .blend model of a tree. The problem is currently in my program all models have only one texture. But this model use two textures, one for trunk and another for branches and leaves. Actually trunk and leaves are two separated models on one scene. What to do in this situation? Editing model manually could take a long time (I'm not an expert in Blender). I could join two textures in one and correct UV's automatically. But most likely a lot of space will be wasted on such an automatically created texture. I could also modify my model format (it's more like memory dump header actually) so I could store N models with N textures as one object. But using N times more VBOs and textures when you actually need only one is inefficient. I'm wondering maybe there is a well known tool for automatically joining multiple objects in one? Or maybe some good practice for this case? Or something like this.


Is there a way to start with OpenGL 3.0 without need to write my own shaders? I'm starting with OpenGL and found out that after OpenGL 3.x you must write your own shaders (think it's obligatory). Am I right here? I have made some research but I can't seem to find the answer. If it's necessary to write the shaders for OpenGL 3 the I still can use 2.x right? Just because I'm just starting and OpenGL seems a little bit more level than I'm accustomed to. So I think I'll have a really hard time writing a shader myself. P.S. My GPU only supports up to OpenGL 3.0. I think it's because of the drivers, I'm running a Linux distro that only has FLOSS (no proprietary software).


LWJGL Mixing 2D and 3D I'm trying to mix 2D and 3D using LWJGL. I have wrote 2D little method that allow me to easily switch between 2D and 3D. protected static void make2D() glEnable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() glOrtho(0.0f, SCREEN WIDTH, SCREEN HEIGHT, 0.0f, 0.0f, 1.0f) GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() protected static void make3D() glDisable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() Reset The Projection Matrix GLU.gluPerspective(45.0f, ((float) SCREEN WIDTH (float) SCREEN HEIGHT), 0.1f, 100.0f) Calculate The Aspect Ratio Of The Window GL11.glMatrixMode(GL11.GL MODELVIEW) glLoadIdentity() The in my rendering code i would do something like make2D() draw 2D stuffs here make3D() draw 3D stuffs here What i'm trying to do is to draw a 3D shape (in my case a quad) and i 2D image. I found this example and i took the code from TextureLoader, Texture and Sprite to load and render a 2D image. Here is how i load the image. TextureLoader loader new TextureLoader() Sprite s new Sprite(loader, "player.png") And how i render it make2D() s.draw(0, 0) It works great. Here is how i render my quad glTranslatef(0.0f, 0.0f, 30.0f) glScalef(12.0f, 9.0f, 1.0f) DrawUtils.drawQuad() Once again, no problem, the quad is properly rendered. DrawUtils is a simple class i wrote containing utility method to draw primitives shapes. Now my problem is when i want to mix both of the above, loading rendering the 2D image, rendering the quad. When i try to load my 2D image with the following s new Sprite(loader, "player.png) My quad is not rendered anymore (i'm not even trying to render the 2D image at this point). Only the fact of creating the texture create the issue. After looking a bit at the code of Sprite and TextureLoader i found that the problem appears after the call of the glTexImage2d. In the TextureLoader class glTexImage2D(target, 0, dstPixelFormat, get2Fold(bufferedImage.getWidth()), get2Fold(bufferedImage.getHeight()), 0, srcPixelFormat, GL UNSIGNED BYTE, textureBuffer) Commenting this like make the problem disappear. My question is then why? Is there anything special to do after calling this function to do 3D? Does this function alter the render part, the projection matrix?


Rotating between two coordinate frames I have two coordinate frames, A and B. I want to create the rotation matrix RAB which takes you from A to B. A is a right handed system, and B is a left handed system. Furthermore, after moving from a right to a left handed system, there is a further rotation. These two coordinate frames are illustrated in the image below. As can be seen, it appears that the axes in B are simply the negative of the axes in A. So, my first attempt was to simply make these negative in the rotation matrix RAB 1 0 0, 0 1 0, 0 0 1 (sorry I don't know how to write matrices properly here...) However, after working through some examples, this did not work out. Please could somebody answer either (or both!) these questions? (a) Why does my above solution not hold? (b) what is the correct rotation matrix RAB?


Why does accessing a uniform float make my shader more than twice as slow? My fragment shader was significantly slowed down by a recent change, and I've been trying to understand why. I isolated the main slow down to accessing a single particular uniform float. If I include this line float not used my uniform then the shader runs more than twice as slowly as it does without this line. The not used float is never referenced again. Why would this be happening? I hope to understand it so that I can try to come up with a workaround that runs more quickly. I'm running this on a mac with Intel HD Graphics 3000. I'm measuring the performance by making OpenGL timestamp queries before and after executing my glDraw calls and looking at the ms intervals. I can provide more specs details if it would be helpful in diagnosing the problem.


Texture is black when manually building mipmap I am trying to manually build a mipmap from a series of images. For the sake of brevity, let's assume the file containing the images I want (from 256x256 to 32x32) have paths file 1...4. What I do to load the texture is GLuint textureID glGenTextures(1, amp textureID) glBindTexture(GL TEXTURE 2D, textureID) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri (GL TEXTURE 2D, GL TEXTURE MAX LEVEL, 4) for i from 1 to 4 unsigned char image stbi load from file(file i, amp width, amp height, amp comp, 3) glTexImage2D(GL TEXTURE 2D, (i 1), GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, image) stbi free image(image) When I go and try to use this created texture in a render all I got is a black result. Using singularly each texture works properly, so I excluded they're malformed. What can it be?


Spherical harmonics lighting interpolation I want to use hardware filtering to smooth out colors in texels of a texture when I'm accessing texels at coordinates that are not directly at the center of the texel, the catch being that the texels store 2 bands of spherical harmonics coefficients ( 4 coefficients), not RGBA intensity values. Can I just use hardware filtering like that (GL LINEAR with and without mip mapping) without any considerations? In other terms If I were to first convert the coefficients back to intensity representations, than manually interpolate between two intensities, would the resulting intensity be the same as if I interpolated between the coefficient vectors directly and then converted the interpolated result to intensities?


Sprite with alpha Blending in 3D world I'm working on a game in a 3D world with elements 2D only (Like Don't starve game) for Android and IOS. Currently, I've managed "Sprite" without alpha blending, I've just put a condition in the pixel shader to test if pixel alpha channel is null if ( texture.a lt 0.5 ) discard Everything working here. (On old devies like an HTC desire mobile, this condition destroy framerate but it's another problem ) But recently, I've tried to had another Sprite with AlphaBlending activated glCheck( glEnable(GL BLEND) ) glCheck( glBlendFunc( GL ONE, GL ONE MINUS SRC ALPHA ) ) glCheck( glDisable(GL DEPTH TEST) ) My sprite transparency is ok but it is now in front of everything in the scene. (Probably due to glDisable(GL DEPTH TEST)). How can I handle depth with alpha blending activated? EDIT A video to show the problem http www.youtube.com watch?v W0gpBekEwW8 amp feature youtu.be


Managing Game Entity coordinates In my Game I'm currently have "Scene Coordinates" which are the X,Y coordinates relative to a Game Scene. In that Scene there are Game Entities, let's say there's a GameEntity A in x 100.0, y 100.0 ( scene coordinates ) Which is the best way to have "Entity Coordinates" so that from GameEntity A point of view, he's standing at x 0.0, y 0.0 with OpenGL transformations? In that way if I apply something like glRotatef(angle, 0, 0, 1) The entity will rotate around it's own origin and not the scene "global" origin.


How can I draw multiple lines connected via "nodes" in libgdx Scene2D? I have two Vectors which indicate the ending points of each line. I am trying to draw similar lines to football formation lines like these My main problem using ShapeRenderer is ShapeRenderer coordinates are relative to screen coordinates and not Scene Table Stack. This creates varying coordinate points in different screen sizes. Although I can fix it, I still experience get varying line width in different screen sizes. ShapeRenderer performance issues as it is mainly intended for debugging. ShapeRenderer draws over all Actors. I have tried drawing the lines as a Pixmap and adding them to the scene as an image. This is part of the constructor to my custom class which extends Group. pixmap new Pixmap( 16, 16, Pixmap.Format.RGBA8888 ) pixmap.setColor(Color.RED) pixmap.drawLine(Ax, Ay, Bx, By) Texture pixmaptex new Texture(pixmap, Pixmap.Format.RGB888, false) Image pixmapimg new Image(pixmaptex) pixmapimg.setPosition(x, y) this.addActor(new Image(pixmaptex)) pixmap.dispose() I am trying to draw using this but it just draws a square with the pixmap width and height at (0,0) of the stack. Which is the best class to extend to draw this lines? I am expecting to write a custom class if this doesn't work.


What state is stored in an OpenGL Vertex Array Object (VAO) and how do I use the VAO correctly? I was wondering what state is stored in an OpenGL VAO. I've understood that a VAO contains state related to the vertex specifications of buffered vertices (what attributes are in the buffers, and what buffers are bound, ... ). To better understand the correct usage of VAO's, I'd like to know exactly what state they hold. How I assume VAO's should be used From simple examples, I've understood that correct usage of VAO's is as follows Setup Generate VAO BindVAO Specify vertex attributes Generate VBO's BindVBO's Buffer vertex data in VBO's Unbind VBO's Unbind VAO Rendering Bind VAO Draw Unbind VAO From this, I assume that at least the vertex buffer bindings and the vertex attribute specifications are stored in the VAO. I'm unsure however how this usage pattern extends to situations where (multiple) textures and (multiple) shader programs come into play. Is the active shader program stored in the VAO? And are the texture bindings (with their sampling wrapping settings) stored in the VAO as well? Ditto for uniforms? Therefore, my questions are What exact state is stored in an OpenGL VAO? (VBO bindings, attribute specifications, active shader program, texture bindings, texture sampling wrapping settings, uniforms ... ?) How do I correctly use VAO's in a more complex rendering setup where (multiple) textures with associated sampling wrapping settings, (multiple) shader programs and uniforms are involved?


OpenGL depth problem I am drawing two cubes, first a red one and then a green one in front of the red one. When I rotate the camera I can see the green cube through the red cube. I have enabled depth test and I clear depth buffer. I'm using OpenGL 4.4 core profile and a simple diffuse shader by the way.