How do I pick tiles from an isometric map with slopes? I'm looking for a way to convert mouse screen coordinates to isometric map coordinates, with the addition that the world has slopes and cliffs, and I have to be able to tell which quadrant of the tile is being pointed at by the mouse. The textures are handled by OpenGL, so I can't (easily) pick directly based on the tile sprite. I've found several similar solutions, (e.g. Isometric Tiles Math, XNA Resources amp Mouse Maps for Isometric Height Maps with the latter looking most promising) but none of them seem to quite fit my requirements. My tiles look like this What algorithm or technique could I use here?


Better texture downscaling at 9xMSAA than at 8xMSAA I'm drawing my game on a render to texture FBO with multisampling. The multisampling works as expected, except for one thing No MSAA 8xMSAA 9xMSAA (left is a untextured quad, right is a textured quad the texture is much larger than the quad, the cross in the center of the texture is 2 line primitives) As you can see, textures seem to suddenly have better downscaling at 9 samples. Im trying to figure out why this is, because I'd prefer to have this quality of downscaling all the time (even if I'm at, say, 4 samples). The artefacting in the first two images is pretty ugly. I'm not using any mipmapping here, but I did try that as an alternative to this, and it does look much better. However, mipmapping looks a bit blurry compared to the third image, and is still not preferable in comparison. This was rendered with an NVIDIA GeForce 980M, and it appeared to have the same behavior on other nvidia cards.


GL SPOT CUTOFF not working properly I'm new to OpenGL. I'm studying OpenGL 2.1 and I'm trying to make a little program to test the GL SPOT CUTOFF property, but when I set a value between 0.0 90.0, the light doesn't work and everything is dark. The code void lightInit(void) GLfloat light0Position 0.0,0.0,2.0,1.0 glEnable(GL LIGHTING) glEnable(GL LIGHT0) glLightf(GL LIGHT0, GL SPOT CUTOFF, 45.0) glLightfv(GL LIGHT0, GL POSITION, light0Position) void reshapeFunc(int w, int h) glViewport(0, 0, (GLsizei) w, (GLsizei) h) glMatrixMode(GL PROJECTION) glLoadIdentity() if (w lt h) glOrtho( 4, 4, 4 (GLfloat)h (GLfloat)w, 4 (GLfloat)h (GLfloat)w, 4.0, 4.0) else glOrtho( 4 (GLfloat)w (GLfloat)h,4 (GLfloat)w (GLfloat)h, 4, 4, 4, 4.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() gluLookAt(0,0,0,0,0, 1,0,1,0) void displayFunc(void) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) center sphere glutSolidSphere(1, 100,100) right sphere glPushMatrix() glTranslatef(3,0,0) glutSolidSphere(1, 100,100) glPopMatrix() left sphere glPushMatrix() glTranslatef( 3,0,0) glutSolidSphere(1, 100,100) glPopMatrix() glutSwapBuffers() void keyboardFunc(unsigned char key, int x, int y) if (key 27) exit(EXIT SUCCESS) int main(int argc, char argv) freeglut init and windows creation glutInit( amp argc, argv) glutInitDisplayMode(GLUT DOUBLE GLUT RGB GLUT DEPTH) glutInitWindowSize(600, 500) glutInitWindowPosition(300, 100) glutCreateWindow("OpenGL") glew init and errors check GLenum err glewInit() if (GLEW OK ! err) fprintf(stderr, "Error s n", glewGetErrorString(err)) return 1 fprintf(stdout, " GLEW s n n", glewGetString(GLEW VERSION)) general settings glClearColor(0.0, 0.0, 0.0, 0.0) glShadeModel(GL SMOOTH) glEnable(GL DEPTH TEST) light settings lightInit() callback functions glutDisplayFunc(displayFunc) glutReshapeFunc(reshapeFunc) glutKeyboardFunc(keyboardFunc) glutMainLoop() return 0 This code produces this image If I delete glLightf(GL LIGHT0, GL SPOT CUTOFF, 45.0) , the next image is produced Is there some kind of bug ?


Know if you're fully utilizing the GPU I render 17.000 VAOs each frame. 2.840.386 triangles. Only applying texture, nothing else. I have three computers and the performance across them is not as expected. Cheap laptop(i3 4010U amp Intel HD 4400) runs at 20 fps. Desktop1(FX 9590 amp GT 630) runs at 65 fps. Desktop2(i7 5820k amp GTX 970) runs at 105 fps. As the game is in a pretty early stage, the only CPU task each frame is to loop through a 3 Dimensional map containing VAO ids, and then render them. When I look at the CPU Benchmarks and the GPU Benchmarks of my systems, I would expect a much bigger difference between my Desktop2 and the two other systems. The GTX 970's 3D score(8662) is more than 15 times better than the Intel HD 4400's (546), though it only run 5 times as fast. Even more ridiculous the GTX 970's 3D score is 11 times better than the GT 630's (797), but run 1.6 times faster. Even without taking the benchmarks into consideration I would still expect bigger difference. When I compare the performance differences in other games(Like GTA V) across my systems, there's a much bigger difference. Therefore I know the problem is my game, and not a hardware driver related issue. Am I right that I would expect larger differences between the different systems, if yes How may I find the issue and how can I solve it? Edit I've read that GTX 590 is capable of 3.2 Billion triangles second, where as my game is only able to squeeze 300 million of a GTX 970. Edit 2 I've tested my desktop1(GT 630) that runs 1080p at 65fps and if I change the resolution to 1 1, I only get a performance boost of 20fps(85fps).


Painter algorithm vs. 3D rendering with Z buffer when drawing 2D Sprites I'm currently developing a tile base engine. I want it to look like your average old school tilebased RPG like Zelda Link to the past (orthographic projection, squared tile texture, textures overlapping each other, alpha channels, etc.). The twist is that the world is internally 3d meaning that every tile has an elevation and entities are moving in a 3d space. Reason for this is beyond the scope of this question but I'm struggling on comparing the follow two ideas for the rendering. I'm using OpenGL with libGDX in Java but wouldn't mind writing my own code to interface OpenGL. That's also why I didn't tag it. A screenshot of quot Zelda Link to the past quot in case you don't know what it looks like. Painter algorithm Disable Z Buffer and use painter algorithm to draw from back to front in the appropriate order with some overdraw and a lot of texture rebinding. I know a texture atlas can minimize the texture rebinding but the engine is supposed to act more like a sandbox so I don't want to rely too heavily on assumptions like a efficient texture atlas that I might not have all the time. Pro Easy to implement and very straight forward. Con I've no idea how big the impact will be since almost every sprite will cause a texture rebinding. And I don't know how to predict the performance costs of that many texture bind calls. Full blown 3D Rotate the camera 45 degrees up around the x axis with an orthographic projection matrix. Then use the 3d information from the game world to draw the tile textures with billboarding at the real position in the worlds 3d space. Same for entities and such. This way I can gather all sprites and then render them sorted by their texture which means one texture bind per texture and reduced overdraw due to usage of the Z buffer Pro I can use a freecam to debug render problems. I assume it's significantly faster that the painter algorithm. Con Some sprites might share the same place which could lead to Z fighting. I'm thinking about how to use multiple layers on a tile. For instance you may have a bridge tile with a railing where the railing is always overlapping an entity on the bridge but the floor of it is always overlapped by the entity. So I would have to add a little offset to different layers in the 3d space. I'm not really sure how that would work out and to be honest had a hard time figuring out how old games did it so maybe I'm overthinking it. I guess I have a very rough idea of how each method will work out but I don't know how much the texture rebinding (or sorting and preparing the sprites for the 3d approach) is affecting the performance and while it's easy to find information regarding large 3D scenes I found it difficult to get information about 2D scenes with way less polygons.I hope this question is not too much a subject of personal preference. I know that Premature optimization is the root of all evil but due to how the decision is affecting almost the entire rendering process I don't want to make the wrong call. I deliberately didn't mention any OpenGL functions mainly because I've mostly used the libGDX API which hides the function calls behind it's wrappers but generally I know how the internals work and just got into the internals and how the OpenGL API works. I don't think specific OpenGL calls do matter for the question but feel free to use them for your answer I'll just look them up.


Linear search vs Octree (Frustum cull) I am wondering whether I should look into implementing an octree of some kind. I have a very simple game which consists of a 3d plane for the floor. There are multiple objects scattered around on the ground, each one has an aabb in world space. Currently I just do a loop through the list of all these objects and check if its bounding box intersects with the frustum, it works great but I am wondering if if it would be a good investment in an octree. I only have max 512 of these objects on the map and they all contain bounding boxes. I am not sure if an octree would make it faster since I have so little objects in the scene.


Terminology for the way Transformation Matrix Data is treated I recently asked a question at math stack exchange and realize a similar questions is more suited for this forum, but the original is here https math.stackexchange.com questions 1526601 terminology for transformation matrices update or rigid body transform I'm attempting to describe transformation matrix operations within Sketchup's Ruby scripts, and I need some terminology. Sketchup allows the selection of a group of "loose" drawing objects (i.e. edges and faces), and provides options to create a grouped object from them. The drawing elements inside the group have position data relative to the group's local coordinate system. The grouped objects respond to a getter "transformation" method that returns a transformation object that contains data representing the orientation, scale, and position of the group. Sketchup's "world space" supports multiple grouped objects, and typically there are numerous grouped entities in the outer level entities, as well as loose drawing objects. Each grouped object has a separate transformation that determines their position, orientation, and scaling in world space. The transformation can be altered or replaced with methods that include a) The "transform" method Applies a transformation (i.e. like a rotation) to rotate the group and b) The "transformation " setter method Replaces the existing transformation with the supplied argument. Lets say I have a grouped object called "entity1" and rotation transformation object called "rotation". To provide the same rotation effect I could perform either of the following in Sketchup's Ruby programming entity1.transform!( rotation ) OR entity1.transformation rotation entity1.transformation Only groups and components support the "transformation " setter method, while fundamental Point3d amp Vector3d object provide "transform!" kind of methods. It is obvious, at least from within Sketchup (which uses OpenGL internally), that transformation matrix internal data can be treated as either Relative A transformation performs an incremental operation (Example "entity1.transform! identity" does not have an affect on the grouped model) or Absolute The data inside a transformation is treated as absolute position, orientation, and scaling of the grouped object. (Example "entity1.transformation IDENTITY" sets the model to Sketchup's origin position, the model is de rotated to the orientation it was when first grouped, and it is descaled) Questions 1) What is the terminology for the type of transformation that is supplied to the "transform!" method? I was calling it an "affine", now want to call it an "update transformation". 2) What is the terminology for the type of transformation that is the argument to the setter "transformation "? I have been calling it a "rigid body transformation", and sometimes "absolute transform". It appears that OpenGL is calling this the "model matrix". 3) If I call it "model matrix", is more than one model matrix transform allowed in world space? A previous english stack exchange article for a word to mean "position and orientation" is at https english.stackexchange.com questions 119883 word for position and orientation The article responses recommend to use "pose matrix".


An odd performance problem rendering a simple scene (less than 14k vertices) in OpenGL using two vbos with LWJGL Problem I have been having a strange degrading performance issue rendering a simple scene containing two "chunks" of 4x4x4 cubes each. Video of problem This is a screen capture showing my console output, look specifically at the FPS dropping (which is the issue). http assets.cognitive.io bugconsole.swf Details about problem My machine (a mid 2009 mbp 15") is on average using something like 10 cpu, but the machine is getting very hot to touch so I believe the graphics card is working very hard. Someone else tested this code on another machine and experienced 100 cpu usage on a quad core AMD cpu (on one core) and the same kind of performance problem. I can't quite figure out what's going on, multiple people have looked at this and we are not getting any smarter. Currently there is no frustum culling or any other sort of culling. I do not think that is the problem, I should be able to render a much much higher number of vertices without experiencing problems. I have a list of chunks (ArrayList) that is created on start, not within the render loop, that generates a vbo and all that. In my renderer I loop through the list of chunks and for each one I bind the vbo, setup some uniform variables and such before calling glDrawArrays(). I have a version of this where I only have one vbo (but then also only one cube per vbo glDrawArrays call, very inefficient) where everything is working fine. Thoughts and ideas I believe the problem is something related to either VRAM filling up or me doing something incredibly wrong. I've tried looking at my project with OSX's OpenGL profiler application, which has given me two different results First I was just using glBufferData each frame to pass the data, which resulted in 90 of the gl time spent being spent on CGLFlushDrawable(). After some advice from someone on opengl on Freenode, it was suggested I should setup the vbo once with glBufferData, and then call glMapBuffer to pass the data after that. This results in the same performance problem but 99 of the gl time being spent on glMapBuffer(). I was hoping someone had some advice for me, I would really like to just be able to continue learning opengl instead of being stuck debugging this performance issue for weeks. Code on GitHub The code is available at https github.com flexd Game tree chunkrenderer (specifically the chunkrenderer branch!, you can see that the lighting2 branch works without the same performance issue). The main game class is Game.java which contains the main method and it's also where I setup OpenGL. Chunk.java, Cube.java, Renderable.java and ChunkRenderer.java are also of interest. Shader.java is where the shader class lives, but I doubt that has anything to do with the issues, it's basically the same shader as before. Thanks in advance, I hope to be able to find the issue soon ) Looking forward to being able to learn more of this. PS Let me know if I am posting this in the wrong place, I don't know if there's a opengl category that's better suited for this.


How to draw or translate into world space? I've been hacking around with OpenGL, but there's a few concepts which I can not find the answer on. I want to draw three GL QUADS next to eachoter like so 1 2 3 I know GL QUADS are deprecated, but for this question i'd like to use them nonetheless. Each quad will have its own color, the first being red, second green and the third blue. r g b my code void display() glClear(GL COLOR BUFFER BIT) GLfloat vertices 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 3, 1, 5, 1, 5, 1, 3, 1 GLfloat colors 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1 glLoadIdentity() glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glVertexPointer(2, GL FLOAT, 0, vertices) glColorPointer(3, GL FLOAT, 0, colors) glMatrixMode(GL PROJECTION) glTranslatef( 1, 0, 0) glDrawArrays(GL QUADS, 0, 12) glDisableClientState(GL COLOR ARRAY) glDisableClientState(GL VERTEX ARRAY) glFlush() result being I'm confused as which to which matrix I should apply the translation matrix and in which order. I'm almost certain I should not use glMatrixMode(GL PROJECTION) What are the initial values of a matrix? I'm not certain which coords to pass in the vertex array at this point, model space or world space? I hope you can shed some light in my confusion.


OpenGL SDL2 How to resize the render area with the window? After calling SDL SetWindowSize, the area being rendered to doesn't change with the window, so if the window gets bigger, it leaves a black area on the top and right sides. I am adjusting the OpenGL viewport to the new window dimentions. Everything I'm drawing scales correctly but is cut off when the window is bigger. I've been searching for the solution all day and all I've found is creating a new OpenGL context, but that causes crashes unless I reload all my graphics data which seems ridiculous just to resize the window. Is it the default framebuffer that needs to be resized? According to the OpenGL wiki, All default framebuffer images are automatically resized to the size of the output window, as it is resized. So if the default framebuffer is being resized, why is it only rendering to the same small area? I could initialize it to the largest possible resolution and then shrink it, but wouldn't that cause OpenGL to process a bunch of fragments outside the window?


OpenGL glRotatef cause performance drop while rotating x and y I have made a rotating cube and I got some performance drops while using two glRotatef calls. So basically this code is giving me 80FPS code 1 GLrotate x 0.4f GLrotate y 0.4f glPushMatrix() glRotatef( GLrotate y, 0.0f, 1.0f, 0.0f ) glRotatef( GLrotate x, 1.0f, 0.0f, 0.0f ) glTranslatef(multiplxGL 0.5f spaceGL 2, multiplyGL 0.5f spaceGL 2, multiplzGL 0.5f spaceGL 2) glDrawElements(GL TRIANGLES, 36, GL UNSIGNED SHORT, BUFFER OFFSET(0)) glPopMatrix() While this one is giving me 100FPS code 2 GLrotate y 0.4f glPushMatrix() glRotatef( GLrotate y, 1.0f, 1.0f, 0.0f ) glTranslatef(multiplxGL 0.5f spaceGL 2, multiplyGL 0.5f spaceGL 2, multiplzGL 0.5f spaceGL 2) glDrawElements(GL TRIANGLES, 36, GL UNSIGNED SHORT, BUFFER OFFSET(0)) glPopMatrix() The rotate results from the rotation code 1 and code 2 are not the same (cube rotates different).I know that the code 1 is the most proper way here for the rotation but why the performance drops? Any chance of updating my code 1 to the performance of code 2? On the other side in DirectX I use D3DXMatrixRotationYawPitchRoll( amp matDXRotate, D3DXToRadian(DXrotate y), D3DXToRadian(DXrotate x), D3DXToRadian(0.0f)) and then matDXStack gt Push() D3DXMatrixTranslation( amp matDXmove, multiplxDX 0.5f spaceDX 2, multiplyDX 0.5f spaceDX 2, multiplzDX 0.5f spaceDX 2) matDXStack gt LoadMatrix( amp (matDXmove matDXRotate)) d3ddev gt SetTransform(D3DTS WORLD, matDXStack gt GetTop()) d3ddev gt DrawIndexedPrimitive(D3DPT TRIANGLELIST, 0, 0, 36, 0, 12) matDXStack gt Pop() Which gives me 100 FPS and rotate results same as code 1.


How can I implement a camera like the one in RotMG? RotMG, an MMO top down shooter, takes on a unique 2d 3d style, and has an intriguing camera The game is obviously 3d, not simply isometric, and if you play the game and turn on camera rotation you will notice the effect the game produces, like so. RotMG is made using flash, and I am currently experimenting with libgdx (which uses lwjgl opengl). How should I go about implementing a RotMG like camera?


I add a straight big plane over terrain(3d). Vibrations are happening when i move camera I have this problem in my OpenGL project but i will show you the same thing over blender3d with video. So I believe that I will better explain the problem. it is just 30 seconds. Take a look. Youtube LINK How can i fix these problem ?


Accesing depth buffer from shader I read this presentation and on 6th slide I found that is not need to use multiple render targets and depth can be taken directly from depth buffer. From which version of DirectX or OpenGL can be the feature used? How to do that?


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


How detect which OpenGL texture formats are natively supported? For example, how detect if my videocard doesn t support "bgr8" and convert it to another format, such as "rgba8" in software mode. UPDATE Sorry for the confusion. This question more about situation when I set internalFormat in glTexImage2D to something like "bgra8" but videodriver internally convert data to another format, like "rgba8".


Keep rasterized pixel amount constant I have a scene that is rendered from the point of view of the light using an orthographic projection matrix. For an arbitrarily shaped and oriented object that doesn't change its shape or size in any way, the amount of pixels that get rasterized change with its position. I guess it's better to explain this with an images The depth of the quads (their y coordinates) are constant. Their x and z coordinates are slightly different. However, since it's an orthographic projection matrix, their "world space" floating point sizes are the same as seen from the camera. Just in one case, one additional lines of pixels is rasterized (I drew the two white lines with mspaint to illustrate their size difference). This is highly undesirable for my application. Is there a way to keep the amount of rasterized pixels consistent? How would I go about implementing it using OpenGL?


Design question best way to model and visualize a long grid of data Perhaps some noob questions for a scientific application that you can assist with I am trying to render a large, evenly spaced grid of data in 2D. The full data set dimensions could be anywhere from 48x250,000 to 1000x15,000,000 points pixels. The data is evenly spaced, but I need to change the aspect ratio, and then render only a section of that data on the screen at a time. I need the users to be able to smoothly scroll forward or backward along the long dimension with user input, or press the "play" button and have it move forward or backward at certain speed. I am looking for advice on how to handle this via DirecX or OpenGL (probably using SharpDX or OpenTK). The basic approach I am considering is to use textures that the application generates on the fly from the data and then map them to a very simple model. I would keep the graphics card supplied with a large enough scene so that as the user scrolls or moves around that they don't have to wait for the application. Questions I have are 1) does this approach make sense? i am presuming this is way more efficient and faster than creating a bunch of primitives with discrete colors. true? 2) is there a particular texture format that is good to use and easy to create (or do i create it directly)? I have the data in application memory as large arrays and it loads unloads from disk as needed. I would map the scalar values to a color as I create the image texture blocks. 3) would mipmaps be useful? i could have an aspect ratio (or small enough window) that there are fewer screen pixels than data in the viewable range. Or, would it just automatically subsample? 4) if mipmaps are used, most of the scaling is along the long dimension, so could i uses non square subsamples? 4) does creating compressed images make sense? or, would the compression overhead yield much benefit (or how might i determine this) 5) how would i go about finding an optimal texture size? Any other general advice? Hopefully this is a straightforward problem for the cool stuff y'all do in games!


Efficient Rendering for multiple light sources I'm building a 3D rendering engine using C and OpenGL. Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods. I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources. The straight forward approach would be something like this for every object to be rendered closestLights for every light in the scene if (light closer than all lights in closestLights) swap furthest light from closestLights with current light loadLightSourcesToShader(closestLights) renderObject(object) However, I'm afraid the performance of this rendering loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker. 1) Is there any way to circumvent this? 2) How is this implemented in 'real' engines? 3) How can I find the closest K lightsources to an object efficiently? I've heard about kd trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now. 4) I could keep an octree and a kd tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?). Is this a good approach? I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game program reaches a certain complexity size.


OpenGL, Offset and Camera Space I was reading chapter 4 of the Arcsyntesis OpenGL tutorial when I came across this line in the GLSL shader. vec4 cameraPos position vec4(offset.x, offset.y, 0.0, 0.0) About it, the tutorial says The first statement simply applies the offset to get the camera space positions of the vertices. I understand what cameraPos is but I don't get what the offset is. It's defined as a uniform and it's passed to the shader by the main program like this glUniform2f(offsetUniform, 1.5f, 0.5f) So offset.x 1.5f and offset.y 0.5f. But I see no mention of that offset in the rest of the tutorial and its values seem quite random to me. I know that the offset from the projection plane to the eye is always 1 but that refers to a value of Z. Where do X and Y come from? Are they arbitrary values? What they mean, what they do? I understood everything up to the point but I can find no reference to said offset in the tutorial and I'd like to know if someone can explain it to me, please. Edit the last line I posted was probably forgotten by the author of the tutorial and can be find in the book's source distribution here.


Graphical mesh lags behind collision shape in BulletPhysics debug drawing In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape. m DynamicsWorld gt stepSimulation(1 60.0f, 10) btTransform trans, trans2 trans2 m RigidBodies.at("CubeMesh") gt m Body gt getWorldTransform() m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) using m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) causes the graphical mesh to lag behind the collision shape in DebugDraw call Checking with debugger shows that the lag error keeps on increasing glm mat4 M trans.getOpenGLMatrix(glm value ptr(M)) m RigidBodies.at("CubeMesh") gt GetGraphicalObject() gt Model M if (m DebugDraw) m DynamicsWorld gt debugDrawWorld() If I use the OpenGL matrix from trans2 then debug drawing is perferct. But with trans the graphical mesh lags behind the collision shape in debug draw. I am using btDefaultMotionState when setting the CubeMesh rigid body. btTransform tr tr.setIdentity() tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f)) cubeMesh gt m PhysicsBody gt m MotionState new btDefaultMotionState(tr) Can anyone explain reason for this lag?


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


Stars coming out of screen I am pretty new to Graphics Programming. I am currently using OpenGL. I have got some hands on in last few days. I have knowledge of Texture Mapping, Cubemap, Multitexturing. But somehow I am not able to bridge the gap between my understanding and actual coding What I am trying to do is create a demo of a stars coming out of screen. It should look realistic. Now, my questions are 1. Is Cubemap capable of doing this? 2. Do I need to write particle engine for this?(Really, don't want to at this stage) 3. This is kinda most needed for me. May I See some code..? In some tutorial just code would also do.. but i think if its similar to my requirement then only it will Help


Help me understand this vbo rotation, and how its done opengl c Im pretty new to opengl, and I just cant figure out how to rotate this vbo vao in 2d space. This is how I bind my coordinates float points 0.0f, 0.10f, 0.0f, 0.10f, 0.10f, 0.0f, 0.10f, 0.10f, 0.0f glGenBuffers(1, amp points vbo) glBindBuffer(GL ARRAY BUFFER, points vbo) glBufferData(GL ARRAY BUFFER, 9 sizeof(float), points, GL STATIC DRAW) I place the vbo at vao 0 glBindBuffer(GL ARRAY BUFFER, points vbo) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, NULL) And I enable the array glEnableVertexAttribArray(0) and call to draw in the cpu, with glDrawArrays(GL TRIANGLES, 0, 3) In my shader, I load the array by glsl shader layout ( location 0 ) in vec3 vertex position void main() gl Position vec4(vertex position, 1.0) Ive edited out the coloring fragment to save space, but this is my problem I can make a uniform to move my triangle around, but idk how to apply a transformation matrix to a vec4. It seems the shader reads my vertex position VAO one vec element at a time, and trying to apply any matrix just gives an error. How do you make or apply a rotation matrix on vao, am I inputting it wrong? All the uniforms I apply seem to only stretch, zoom, or move the overall triangle. Sorry if the question is bad, or partially confused, shading is new to me overall, so thanks in advance.' my shader version 410 core layout ( location 0 ) in vec3 vertex position layout ( location 1 ) in vec3 vertex colour out vec3 colour uniform vec3 fade vec3(0.0,0.0,0.0) fade uniform float zoom 1.0 uniform mat4 transform mat4(vec4(1.0,0.0,0.0,0.0), vec4(0.0,1.0,0.0,0.0), vec4(0.0,0.0,1.0,0.0), vec4(0.0,0.0,0.0,1.0)) void main() colour vertex colour fade gl Position transform vec4(vertex position,1.0) this example https open.gl transformations and the answer made it doable.


Opengl drawing a section of a texture stretched over a quad Current Situation I have a spritesheet loaded in for a texture when drawing the specific portions of the sheet that I'd like to have on my quads I do some simple math to get their location on the sheet and normalize it. My texture is setup like this glTexParameterf(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameterf(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) The Problem Where I'm facing the problem is that because I'm using a "chunk" of the total texture I can't take advantage of using 1.0 for the mapping of values to glTexCoordPointer to cause the texture to stretch over the entire face. Looked Into I've looked for a glTexParameterf option for scaling options but I failed to find anything. Question Is it possible with my current methods to stretch the texture over the face of the quad without having to load a separate image for every "sprite" of the texture? Or am I just doing everything completely wrong? Picture that hopefully sort of clarifies Thanks for any help. edit The problem was another issue all together Turns out it was another issue all together, I thought this didn't make sense cause it was mapping it to the vertices so it should stretch regardless and infact it does work right I was assigning the wrong the width and height values to the drawing routines calculations. And now I feel really stupid, thanks for the help Byte56. Sorry for taking up your time. The GL CLAMP solution would be the correct answer if I hadn't made a huge fail.


Which one have to use Canvas or Open GL for 2D game in Android I am compleatly new to android gaming.I want to develop a 2D game with some physics in it.I want to know which one i have to use Open GL or Canvas and the reason for selection I want to include a physics engine i dont know anything about that too It will be very help full if anyone can share any idea's and suggections. Advanced thanks to all ...


Best way to initialize values on 32 bit FP framebuffer in OpenGL I have a framebuffer bound to 32 bit FP texture glGenTextures(1, amp texColor) glBindTexture(GL TEXTURE 2D, texColor) glTexImage2D(GL TEXTURE 2D, 0, GL R32F, w, h, 0, GL RGBA, GL FLOAT, (GLvoid )NULL) glBindTexture(GL TEXTURE 2D, 0) glGenFramebuffers(1, amp fbo) glBindFramebuffer(GL FRAMEBUFFER, fbo) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, texColor, 0) What's the best way to initialize framebuffer to a value 1000.0? The problem is that glClearColor(1000.0f, 0.0f, 0.0f, 0.0f) glClear(GL COLOR BUFFER BIT) clamps values to 0,1 interval, and clearing the texture texColor would require memory allocation of w h sizeof(float) bytes of memory and manual filling of that buffer with value 1000.0 which is slow (I would inject it using glTexImage2D). I'm using OpenGL 3.2 Core profile. Thanks, Josip


How to calculate spherical harmonic coefficients for indirect diffuse? After reading the article "An Efficient Representation for Irradiance Environment Maps", I'm a bit confused as how to calculate the spherical harmonic coefficients. I'd like to generate these coefficients given a cube map that I've generate dynamically in engine. I'm currently using DirectX 11, but I have some familiarity with OpenGl. Some tips on calculating these coefficients would be greatly appreciated!


Getting world coordinates from mouse position I am drawing a 2D mesh imported from CAD. The mesh vertex coordinates are in feet from some arbitrary origin and Z is always 0. I am supplying the coordinates to my shader program and using projection matrix, view matrix and model matrix to display everything. I am also using the view matrix and the model matrix to pan and zoom my 2D scene. I am trying to get the coordinates in feet from my mouse cursor coordinates. Should be a straightforward solution. A matrix multiplied by it's inverse will give you an identity matrix but something is very wrong. Here is my code (don't lough at the vb, I took over an old project) Private Sub openGLControl1 MouseMove(sender As Object, e As MouseEventArgs) Handles openGLControl1.MouseMove Dim UnprojectMat As mat4 glm.inverse(scene.projectionMatrix scene.viewMatrix scene.modelMatrix) Dim wCoordsVec As vec4 UnprojectMat New vec4(2 e.X openGLControl1.Width 1, (2 e.Y openGLControl1.Height 1), 0, 1) wCoordsVec wCoordsVec wCoordsVec.w wCoordsLabel.Text wCoordsVec.x.ToString ", " wCoordsVec.y.ToString End Sub And this is my vertex shader version 150 in vec3 in Position uniform mat4 projectionMatrix uniform mat4 viewMatrix uniform mat4 modelMatrix void main(void) gl Position projectionMatrix viewMatrix modelMatrix vec4(in Position, 1.0) pass Color in Color The in Position vector is what I'm trying to get. As you see, I normalized the mouse coordinates for the 1, 1 coordinate system. I don't have a viewport. I'm just using the entire gl control window. Please help me pinpoint what I'm doing wrong.


OpenGL VBO Additional Attributes If I have a buffer with my vertices, normals and texture coordinates, and I use glDrawArrays to draw the VBO to the screen, how can I send attributes per vertex that I placed in an array to the shader program? I'm making a voxel terrain, and every chunk is 1 VBO, this works all great, but I want to send the light value of each block (Just an array filled with int's) to the shader as well, how would I do that? Edit After reading some comments, here some clarification I'm trying to avoid the deprecated glVertexPointer etc, so I'm using Vertex Arrays. Here is the layout of my vertex array X, Y, Z, NX, NY, NZ, X, Y, Z, NX, NY, NZ,X, Y, Z, NX, NY, NZ I'm using this to draw it (ofcourse with the array buffer bound) glVertexAttribPointer(0, 3, GL FLOAT, false, 12, 0) glVertexAttribPointer(1, 3, GL FLOAT, false, 12, 12) glDrawArrays(GL TRIANGLES, 0, arraySize 6) However I get some weird shapes on my screen. Apart from the light problem, that is essentially the same thing, I don't get why this doesn't just work. When I remove the normals, and use just 1 vertexattribpointer it works fine. Yes, the attributes are bound to in position and in normal, and the vertex shader is nothing more than gl Position gl ModelViewProjectionMatrix vec4(in position, 1.0) Thanks! This is what I get (This are 6X6 chunks, so this code is called 6 6 times.)


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


What is the difference between OpenGL 1.x and 2.x? Is there a good tutorial that shows the difference between OpenGL 1. and 2. ? It would be very helpful to know which functions I should not be calling (like glBegin(), I assume).


How can I improve rendering speeds of a Voxel Minecraft type game? I'm writing my own clone of Minecraft (also written in Java). It works great right now. With a viewing distance of 40 meters I can easily hit 60 FPS on my MacBook Pro 8,1. (Intel i5 Intel HD Graphics 3000). But if I put the viewing distance on 70 meters, I only reach 15 25 FPS. In the real Minecraft, I can put the viewing disntance on far ( 256m) without a problem. So my question is what should I do to make my game better? The optimisations I implemented Only keep local chunks in memory (depending on the player's viewing distance) Frustum culling (First on the chunks, then on the blocks) Only drawing really visible faces of the blocks Using lists per chunk that contain the visible blocks. Chunks that become visible will add itself to this list. If they become invisible, they are automatically removed from this list. Blocks become (in)visible by building or destroying a neighbour block. Using lists per chunk that contain the updating blocks. Same mechanism as the visible block lists. Use nearly no new statements inside the game loop. (My game runs about 20 seconds until the Garbage Collector is invoked) I'm using OpenGL call lists at the moment. (glNewList(), glEndList(), glCallList()) for each side of a kind of block. Currently I'm even not using any sort of lighting system. I heard already about VBO's. But I don't know exactly what it is. However, I'll do some research about them. Will they improve performance? Before implementing VBO's, I want to try to use glCallLists() and pass a list of call lists. Instead using thousand times glCallList(). (I want to try this, because I think that the real MineCraft doesn't use VBO's. Correct?) Are there other tricks to improve performance? VisualVM profiling showed me this (profiling for only 33 frames, with a viewing distance of 70 meters) Profiling with 40 meters (246 frames) Note I'm synchronising a lot of methods and code blocks, because I'm generating chunks in another thread. I think that acquiring a lock for an object is a performance issue when doing this much in a game loop (of course, I'm talking about the time when there is only the game loop and no new chunks are generated). Is this right? Edit After removing some synchronised blocks and some other little improvements. The performance is already much better. Here are my new profiling results with 70 meters I think it is pretty clear that selectVisibleBlocks is the issue here. Thanks in advance! Martijn Update After some extra improvements (like using for loops in stead of for each, buffering variables outside loops, etc...), I now can run viewing distance 60 pretty good. I think I'm going to implement VBO's as soon as possible. PS All source code is available on GitHub https github.com mcourteaux CraftMania


Does cube map texturing works only for objects which vertices are is in 1,1 range? Im attempting to texture an .obj file that is not a skybox. So the question is, every tutorial about cubemap creates their hardcoded cubes with vertices ranging from 1, 1 . Probably not, but is it necessary to scale my .obj model to be in that range? Also, to map my fragments with the right texel I saw people online telling that I should take a point p then subtract it with the model center c in the shader. Some said that I should normalize them? normalize(p c) I hope you can help me deliver a brief explanation.


SDL 2.0 OpenGL not drawing anything except background My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code main.cpp include "src App.h" int main( int argc, char args ) App app(600, 400, false) app.Run() return 0 App.h ifndef APP H define APP H include lt SDL.h gt class App public explicit App(size t win width, size t win height, bool fullscreen mode) m window width(win width), m window height(win height), m fullscreen(fullscreen mode) void Run() private void Draw() void Update(double dt) void Resize(size t width, size t height) void ProcessEvents() private size t m window width size t m window height bool m fullscreen bool is done SDL Window m window SDL GLContext m glcontext endif APP H App.cpp include ".. App.h" include lt SDL opengl.h gt include lt cassert gt void App Run() SDL Init(SDL INIT VIDEO) m window SDL CreateWindow("Okno gry", SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, m window width, m window height, SDL WINDOW OPENGL (m fullscreen?SDL WINDOW FULLSCREEN SDL WINDOW RESIZABLE)) m glcontext SDL GL CreateContext(m window) Resize(m window width, m window height) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL CONTEXT PROFILE MASK, SDL GL CONTEXT PROFILE COMPATIBILITY) glClearColor(0, 0, 1, 0) glEnable(GL DEPTH TEST) glDepthFunc(GL EQUAL) is done false size t last ticks SDL GetTicks() while(!is done) ProcessEvents() size t ticks SDL GetTicks() double delta time (ticks last ticks) 1000 last ticks ticks if (delta time gt 0 ) Update(delta time) Draw() SDL Quit() void App Draw() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() glBegin(GL TRIANGLES) glColor3f(1, 1, 0) glVertex2f(1, 1) glVertex2f(0, 1) glVertex2f(0, 0) glEnd() SDL GL SwapWindow(m window) void App ProcessEvents() if (is done) return SDL Event event while (SDL PollEvent( amp event)) if (event.type SDL WINDOWEVENT amp amp event.window.event SDL WINDOWEVENT SIZE CHANGED) Resize(event.window.data1, event.window.data2) else if (event.type SDL QUIT) is done true break void App Resize(size t width, size t height) m window width width m window height height glViewport(0, 0, static cast lt int gt (width), static cast lt int gt (height)) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, 1, 0, 1, 1, 10) glMatrixMode(GL MODELVIEW) glLoadIdentity() void App Update(double dt) printf(" d", dt) Can anyone help? I don't know why it's not running.


What does glTranslatef function is translating in this code? I understand translation from mathematics view where we can have a triangle with a certain coordinates. We can translate this triangle by multiplying the coordinates of the triangle (expressed in the form of a matrix) by a translation vector. In the code below, I could not see what glTranslate () is translating since we havent drawn anything yet. What are we translating? Are we applying the translation to some default objects or something? void display(void) glClear (GL COLOR BUFFER BIT) glPushMatrix() glTranslatef ( 1.0, 0.0, 0.0) glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0) glTranslatef (1.0, 0.0, 0.0) glPushMatrix() glScalef (2.0, 0.5, 1.0) glutWireCube (1.0) glPopMatrix() glTranslatef (1.0, 0.0, 0.0) glRotatef ((GLfloat) elbow, 0.0, 0.0, 1.0) glTranslatef (1.0, 0.0, 0.0) glPushMatrix() glScalef (2.0, 0.5, 1.0) glutWireCube (1.0) glPopMatrix() glPushMatrix() glTranslatef(1.6, 0.22, 0.0) glRotatef ((GLfloat) finger, 0.0, 0.0, 1.0) glScalef (0.6, 0.1, 0.08) glutWireCube (1.0) glPopMatrix() glPopMatrix() glutSwapBuffers()


Alpha blending, transparence and z ordering I'm making some tests with alpha blending in a projet and I don't understand something. In my tests I've done something like that and everything look good Draw blue box first (depth test true, blend alpha none, color 1, 1, 1, 1) Draw left Mario (depth test false, blend alpha true, color 1, 1, 1, 0.8) Draw red box (depth test true, blend alpha none, color 1, 1, 1, 1) Draw right Mario (depth test false, blend alpha true, color 1, 1, 1, 0.8) Every tutorial say that we should Draw opaque object first Order transparent object back to front then draw them. Here is the result So, I'm not sure to understand how it work what is wrong (I've read this document). Thanks!


What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? The refer graphic entities have glUseProgram( shader program id ) glDrawArrays(GL XXXX, x) One of my ideas is to have a camera object that manages the current view and projection matrix. Then, I pass a reference of that camera object to all the entities. However, my issue with that approach is syncing the current camera across all the entities objects when switching views. I could make the Camera global, however, that could have many issues.


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.


How do you create a fractal cube map? I want to create a map similar to how Mincraft and other related games do. I just haven't the faintest clue on how to do so. Can anyone point me to a decent tutorial or give me a decent run through? I program in java and use openGL.


OpenGL flickerinng near the edges I am trying to simulate particles moving around the scene with OpenCL for computation and OpenGL for rendering with GLUT. There is no OpenCL OpenGL interop yet, so the drawing is done in the older fixed pipeline way. Whenever circles get close to the edges, they start to flicker. The drawing should draw a part of the circle on the top of the scene and a part on the bottom. The effect is the following The balls you see on the bottom should be one part on the bottom and one part on the top. Wrapping around the scene, so to say, but they constantly flicker. The code for drawing them is void Scene drawCircle(GLuint index) glMatrixMode(GL MODELVIEW) glLoadIdentity() glTranslatef(pos.at(2 index),pos.at(2 index 1), 0.0f) glBegin(GL TRIANGLE FAN) GLfloat incr (2.0 M PI) (GLfloat) slices glColor3f(0.8f, 0.255f, 0.26f) glVertex2f(0.0f, 0.0f) glColor3f(1.0f, 0.0f, 0.0f) for(GLint i 0 i lt slices i) GLfloat x radius sin((GLfloat) i incr) GLfloat y radius cos((GLfloat) i incr) glVertex2f(x, y) glEnd() If it helps, this is the reshape method void Scene reshape(GLint width, GLint height) if(0 height) height 1 Prevent division by zero glViewport(0, 0, width, height) glMatrixMode(GL PROJECTION) glLoadIdentity() gluOrtho2D(xmin, xmax, ymin, ymax) std cout lt lt xmin lt lt " " lt lt xmax lt lt " " lt lt ymin lt lt " " lt lt ymax lt lt std endl


OpenGL camera moves faster than player I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it cameraX Width 2 TileSize playerPosX cameraY Height 2 TileSize playerPosY However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen. Some code, this is how I translate the camera public Camera() public void update(Player p) glTranslatef( p.getPos().x Main.WIDTH 64 2, p.getPos().y Main.HEIGHT 64 2, 1) Here's how I move the player public void update() if(Keyboard.isKeyDown(Keyboard.KEY D)) this.move(MOVESPEED, 0) if(Keyboard.isKeyDown(Keyboard.KEY A)) this.move( MOVESPEED, 0) The move method public void move(float x, float y) this.getPos().set(this.getPos().x x, this.getPos().y y) And then after I move the player, I update the player's geometry, which shouldn't matter. What am I doing wrong here, this seems like such a simple problem, yet it doesn't work!


Get world position in Vertex shader I'm wondering how I can get the final position of a vertex. I use glTranslate in my render code, and I'm not getting the world coordinates correct. My world is devided in chunks and my position get's screwed up. I have tried multiplying the position with the 3 built in matrices, but no success.


Cheap ways to do scaling ops in shader? I've got an extensive world terrain that uses vec3 for the vertex position attribute. That's good, because the terrain has endless gradations due to the use of floating point. But I'm thinking about how to reduce the amount of data uploaded to the GPU. For my terrain, which uses discrete grid based vertex positions in x and z, it's pretty clear that I can replace my vec3s (floats, really) with shorts, halving the per vertex position attribute cost from 12 bytes each to 6 bytes. Considering I've got little enough other vertex data, and an enormous amount of terrain data to push into the world, it's a major gain. Currently in my code, one unit in GLSL shaders is equal to 1m in the world. I like that scale. If I move over to using shorts, though, I won't be able to use the same scale, as I would then have a very blocky world where every step in height is an entire metre. So I see these potential solutions to scale the positional data correctly once it arrives at the vertex shader stage Use 10 1 scaling, i.e. 1 short unit 1 decimetre in CPU side code. Do a division by 10 in the vertex shader to scale incoming decimetre values back to metres. Arbirary (non PoT) divisions tend to be slow, however. Use (some power of two) 1 scaling (eg. 8 1), which enables the use of a bitshift (eg. val gt gt 3) to do the division... not sure how performant this is in shaders, though. Not as intuitive to read values, but possibly quite a bit faster than div by a non PoT value. Use a texture as lookup table to convert the value from decimetres to metres. I've heard that this is really fast. Or whatever solutions others can offer to achieve the same results minimal vertex data with sensible scaling.


Special Texture Stretching without deformation I am trying to achieve a special texture stretching effect in my shader. Here is how I define my uv before sampling my texture, nothing really special. uv ST contains the tiling and offset values uv.xy uv.xy uv ST.xy uv ST.zw This gives the standard tiling stretching and offset behaviour when you tile stretche a clamped texture as you can see in the image below. First is normal, second is offset and last is stretching. But I want to avoid the deformation behaviour when stretching, I want to keep margins when stretching my texture or simply cut it in the middle and stretching it. Here is an illustration below. How could I do that inside my shader when defining my uvs before sampling the texture ?


What happens when a texture is too large for a device The question is two fold What happens on a device when a texture is too large for it to handle? Will it crash or simply downsize it? In Unity if I use texture atlases of size 4k and then set Texture Quality in the Quality settings as half res will it run normally on devices with maximum texture size of 2k?


Why does OpenGL seem to ignore my glBindTexture call? I'm having problems making a simple sprite rendering. I load 2 different textures. Then, I bind these textures and draw 2 squares, one with each texture. But only the texture of the first rendered object is drawn in both squares. Its like if I'd only use a texture or as if glBindTexture don't work properly. I know that GL is a state machine, but I think that you only need to change active texture with glBindTexture. I load texture with this method bool CTexture generate( utils CImageBuff img ) assert(img) m image img CHECKGL(glGenTextures(1, amp m textureID)) CHECKGL(glBindTexture(GL TEXTURE 2D,m textureID)) CHECKGL(glTexParameteri(GL TEXTURE 2D,GL TEXTURE MIN FILTER,GL LINEAR)) CHECKGL(glTexParameteri(GL TEXTURE 2D,GL TEXTURE MAG FILTER,GL LINEAR)) CHECKGL(glTexImage2D(GL TEXTURE 2D,0,img gt getBpp(),img gt getWitdh(),img gt getHeight(),0,img gt getFormat(),GL UNSIGNED BYTE,img gt getImgData())) CHECKGL(glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, img gt getWitdh(), img gt getHeight(), 0, GL RGBA, GL UNSIGNED BYTE, img gt getImgData())) return true And I bind textures with this function void CTexture bind() CHECKGL(glBindTexture(GL TEXTURE 2D,m textureID)) Also, I draw sprites with this method void CSprite2D render() CHECKGL(glLoadIdentity()) CHECKGL(glEnable(GL TEXTURE 2D)) CHECKGL(glEnable(GL BLEND)) CHECKGL(glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA)) m texture gt bind() CHECKGL(glPushMatrix()) CHECKGL(glBegin(GL QUADS)) CHECKGL(glTexCoord2f(m textureAreaStart.s,m textureAreaStart.t)) 0,0 by default CHECKGL(glVertex3i(m position.x,m position.y,0)) CHECKGL(glTexCoord2f(m textureAreaEnd.s,m textureAreaStart.t)) 1,0 by default CHECKGL(glVertex3i( m position.x m dimensions.x, m position.y, 0)) CHECKGL(glTexCoord2f(m textureAreaEnd.s, m textureAreaEnd.t)) 1,1 by default CHECKGL(glVertex3i( m position.x m dimensions.x, m position.y m dimensions.y, 0)) CHECKGL(glTexCoord2f(m textureAreaStart.s, m textureAreaEnd.t)) 0,1 by default CHECKGL(glVertex3i( m position.x, m position.y m dimensions.y,0)) CHECKGL(glPopMatrix()) CHECKGL(glDisable(GL BLEND)) Edit I bring also the check error code int CheckGLError(const char GLcall, const char file, int line) GLenum errCode avoids infinite loop int errorCount 0 while ( (errCode glGetError()) ! GL NO ERROR amp amp errorCount lt 3000) utils globalLogPtr log utils CGLogFactory getLogInstance() const GLubyte errString errString gluErrorString(errCode) std stringstream ss ss lt lt "In " lt lt FILE lt lt "(" lt lt LINE lt lt ") " lt lt "GL error with code " lt lt errCode lt lt " at file " lt lt file lt lt ", line " lt lt line lt lt " with message " lt lt errString lt lt " n" log gt addMessage(ss.str(),ZEL APPENDER GL,utils LOGLEVEL ERROR) return 0


Masking OpenGL texture by a pattern Tiled terrain. User wants to build a structure. He presses build and for each tile there is an "allow" or "disallow" tile sprite added to the scene. FPS drops right away, since there are 600 tiles added to the screen. Since map equals screen, there is no scrolling. I came to an idea to make an allow grid covering the whole map and mask the disallow fields. Approach 1 Create allow and disallow grid textures. Draw a polygon on screen. Pass both textures to the fragment shader. Determine the position inside the polygon and use color from allowTexture if the fragment belongs to the allow field, disallow otherwise Problem How do I know if I'm on the field that isn't allowed if I cannot pass the matrix representing the map (enum FieldStatus (Allow Disallow)) to the shader? Therefore, inside the shader I don't know which fragments should be masked. Approach 2 Create allow texture. Create an empty texture buffer same size as the allow texture Memset the pixels of the empty texture to desired color for each pixel that doesn't allow building. Draw a polygon on screen. Pass both textures to the fragment shader. Use texture2 color if alpha 0, texture1 color otherwise. Problem I'm not sure what is the right way to manipulate pixels on a texture. Do I just make a buffer with width height 4 size and memcpy the color to desired coordinates or is there anything else to it? Would I have to call glTexImage2D after every change to the texture? Another problem with this approach is that it takes a lot more work to get a prettier effect since I'm manipulating the color pixels instead of just masking two textures. varying vec2 TexCoordOut uniform sampler2D Texture1 uniform sampler2D Texture2 void main(void) vec4 allowColor texture2D(Texture1, TexCoordOut) vec4 disallowColor texture2D(Texture2, TexCoordOut) if(disallowColor.a gt 0) gl FragColor disallowColor else gl FragColor allowColor I'm working with OpenGL on Windows. Any other suggestion is welcome.


Cube world rendering optimizations I'm making a Minecraft like game and I would like to apply some optimizations. Firstly I didn't and I rendered the world using a vbo in which I stored a cube model and I drow all blocks of the worlds and off course it caused lag if there were too many blocks. Then I decided to draw the world face by face and check if a face is hidden from another one. This concept is simple if I have the world made only by cubes of the same size, like this Blue and black block are two blocks of the same size and the red face is the face to ignore since is hidden (overlapped) by another opaque face. As I said if I want to make blocks of different sizes (scale) position rotation but by always drawing them from faces, the matter is different since I can't know if a face is completely visible or not. Here's an image of a normal block with a "custom" block on it Blue block is the custom block, the black a "normal" block and the red is the face overlapped by the biggest one (then it should be ignored during rendering). Here the rotation is null but if there's no way to check rotated faces I can simply ignore it and draws all rotated blocks by default (I don't rotate all the world lol)... that's not what I'd like to do but if there's no way or the way is too difficult... Anyway, finally, how can I check (using GL functions or doing it in my code) if a face is hidden and to ignore it on rendering? I forgot to say that another optimization I did is if a block is hidden (has a block relative to each face) by other blocks I don't draw it.


Ray picking get direction from pitch and yaw I am attempting to cast a ray from the center of the screen and check for collisions with objects. When rendering, I use these calls to set up the camera GL11.glRotated(mPitch, 1, 0, 0) GL11.glRotated(mYaw, 0, 1, 0) GL11.glTranslated(mPositionX, mPositionY, mPositionZ) I am having trouble creating the ray, however. This is the code I have so far ray.origin new Vector(mPositionX, mPositionY, mPositionZ) ray.direction new Vector(?, ?, ?) My question is what should I put in the question mark spots? I.e. how can I create the ray direction from the pitch and roll? Any help would be much appreciated!


How to handle hitboxes hurtboxes in animations? I'm curious how I should go about structuring hitboxes and hurtboxes for my actors. For context, I'm developing a game engine in OpenGL, using C and OpenTK. I have developed a working skeletal animation system, which loads animations using Assimp, and then passes BoneIDs, BoneWeights, and Transform matrices to the Vertex shader, which calculates all vertex deforms appropriately for the current animation keyframe (or current interpolation between keyframes). Is there a set standard for calculating collision in animations? I'd prefer to continue using Assimp, which means using standard, recognizable animation formats that my engine can load in, so I'd rather not store any collision data in the animation files, unless there is a precedent for this or room for metadata or something. My current thoughts One option would be to calculate the hitboxes and hurtboxes upon loading an animation, and have a mapping that determines which meshes are hitboxes and which are hurtboxes. The second option would be to create a new file format where I store my hitboxes and hurtboxes in a way that is similar to animation files (minus bone weights, since I'll just be transforming the scale position of axis aligned rectangles), where I can determine keyframes for hitboxes and hurtboxes, then interpolate based off of these to get the current collision box for each frame. I could combine the two options by automatically generating these files from the animations, then editing them manually until they are reasonable. Am I on the right track, or are there smarter ways of going about this? I don't want to reinvent the wheel if there are better options available.


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


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


Should I batch up debug primitives for rendering in modern OpenGL? I've recently started porting some old rendering demos I did to modern OpenGL. I had a debug drawing class in my old code which used immediate mode glBegin(), glEnd() etc. for rendering debug objects such as triangles, cubes and spheres etc. Originally I replaced the code in these functions with code to generate the VAO and VBOs (for position and colour), bind them, assign the vertex data, render, then disable and delete the VBOs and VAO. Is there anything wrong with this? I've been thinking about modifying the class so that every time it gets a draw primitive call it generates the VAO and VBOs and assigns the vertex data but doesn't actually do the rendering until after all the other rendering has been completed. Then it renders all the debug prims that have been stored at once. I'm not sure of the benefits of either way of doing this and was just wondering what people thought.


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


OpenGL drawElements 2D imposible z sorting (textured) I am creating a 2D program in OpenGL 3.2 Now to render what I do is have a VBO for each texture and add the elements of the objects that use that texture to this vbo. Now as you know the order you render objects will be the (fliped) order you see them on the screen. Here is the problem, as you know its possible to sort objects by their Z value in the same VBO (by inserting them to the vbo according to their Z value). But when you want to sort them between VBOs thats impossible because they have to be in the correct VBO to have the correct texture, Meaning the VBOs that are drawn last will have positive Z value priority over VBOs that are drawn first. This causes the Z value to transfer from the actual objects, to their textures and makes the Z value be grouped for all objects that use the same texture. That was kinda confusing so to recap, because of the way VBOs work this is what is going to happen Turtule texture id 1 Box texture id 2 (Each textures has its own VBO) There is one turtle and one box, the turtle (z 1) is behind the box (z 0) . if I render the box VBO then the Turtle VBO What will happen is we will see the turtle over the box even though it has a z value that is less then the box. Here is some art I drew to help you visualize the problem That makes the Z value of the actual turtle meaning less compared to the " Z " value of the VBO. This can be worked around by having a Z value for each VBO but that limits the program because if the Z of the boxes is bigger than turtles no matter what every turtles is gonna be hidden behind every box. And its a stupid way of doing it. So finally to the question What can I do to fix this, to have a meaning full Z value to each OBJECT. Notes I cannot draw the object individually because I use drawElements and because I add them to texture coresponding VBOs to reduce the VBO count and texture binding count. Stuff I have tried I have tried using the actual opengl Z buffer, but I cannot blend layers because of that so its not a solution.


Reading mesh data back from OpenGL vs storing two copies I'm wondering if whether it's a good idea or not to keep a copy of vertex data in the main memory or just read it back via glGetBufferSubData (or glMapBuffer glMapBufferRange). The reason why I'd do this is so that I can keep only what's needed in the VRAM (and resource which may be needed very soon in the main memory) but not have to go back and load the resource from the disk again. The concern that I have is that, with the draw optimized flags (GL XXXX DRAW) is that they aren't optimized for reading back (since there's a seperate flag for that). So if it's not very fast, it kinda defeats the whole purpose. The other option is storing a second copy and just delete the VBO when I'm done (no reading it back), but I dislike this because it requires more memory usage than might be necessary. Which option is preferred? Is there another way? Maybe something I'm missing?


Expected OpenGL performance I'm benchmarking some simple code for drawing using OpenGL. In the following code, the number of indices being drawn is 4,644 (or 1,548 triangles per frame 60fps 92,880 Triangles per second). glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, screenSize.width, screenSize.height, 0, 0, 1) glMatrixMode(GL MODELVIEW) glLoadIdentity() glDisable(GL DEPTH TEST) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glEnableClientState(GL TEXTURE COORD ARRAY) glEnable(GL TEXTURE 2D) glColorPointer(4, GL UNSIGNED BYTE, sizeof(venomGLAttribute), ,drawingTexturedList.attrib 0 .color) glVertexPointer(2, GL SHORT, sizeof(venomGLAttribute), amp drawingTexturedList.attrib 0 .pos 0 ) glTexCoordPointer(2, GL FLOAT, sizeof(venomGLAttribute), amp drawingTexturedList.attrib 0 .UV 0 ) glDrawElements(GL TRIANGLES, drawingTexturedList cnt .currentIndice 4644 , GL UNSIGNED INT, drawingTexturedList cnt .Indices) This takes 100 of one of my CPU's. If I take out the call to glDrawElements but still perform all the other steps (geometry preperation, gl Pointer setup) I see my CPU stay at 3 . Is this expected behaviour? The machine I'm running on has a GeForce 8800GTX and a Dual Core 2.66Ghz. Using fps as a measurement (which isn't perfect I realise) and using gDEBugger to confirm my findings, rendering 27,904 triangles a frame in a single call to glDrawElements brings my frame rate down to 35fps (or 977,640 triangles a second). Is there a better way to pack my data than I'm doing or perhaps a better way to send the data than glDrawElements? I don't think using a VBO will help as the data being sent changes every frame. Any idea's would be appreciated!


Would it perform faster to split calculation between vertex and fragment shaders? Assuming the total amount of computation would be the same (at least as far as my code goes), would there be any performance increase in splitting the calculation and using separate vertex and fragment shaders vs. doing all the calculations in just a fragment shader? In my use case, I would not be using vertex shaders as they are typically intended (so, not processing actual vertices). I just thought if the GPU hardware is set up such that the pipeline is expected to be used, would it be better to take advantage of that, or would it be just as fast to put it all in a fragment shader. Conceptually, it would be simpler to just use the fragment shader. Note, that I do need a lot of data going to the fragment shader that is updated every frame (eg. texture buffer object).


Deforming a lip mesh to match face tracking points I'm creating a lipstick filter. I have a basic mesh for the lip shape ( 140 vertices ) which I am able to render on screen. I need the mesh since I have my own lighting system, and hence need the normal info. Plus I don't want to create a model at runtime since if I load an obj file I have the flexibility of rendering high quality meshes. The problem that I am now facing is that when a user is going to use it, their face will be moving around in the video frame, and I will be getting the lips' positions accordingly. Hence at each frame the mesh will be rendered differently ( in one frame he might be smiling, the other he might be frowning etc), in different places in the screen. How can I set the OpenGL vertices to match the positions of the tracked feature points, and interpolate the rest? I have only 20 ish detection landmark points for each of the upper and lower lip.


OpenGL Is it efficient ok to glPushMatrix, plMultMatrix, plPopMatrix for every object in my scene? I'm very new to opengl, and I might not fully understand the openGL matrix projection stack thing. So, I have about 300 'objects' in my scene, each with their own position rotation, and I want to draw them all (ignore culling and overdrawing for now). Would it be efficient enough to for each object glPushMatrix() glMultMatrix(object pose) do object drawing glPopMatrix() or is there a better way to draw each object?


Perspective Projection Far Plane Not Clipping? I've just discovered that far away objects in my world don't seem to clip like they should with a perspective projection matrix. When I fly far away from my main landscape, so that I am much more than 10 units (if not hundreds) away, it won't disappear. This is weird, because I thought objects should clip disappear once they hit the far plane. Here's a photo that demonstrates the issue I have defined the projection with my own custom function. The field of view is 60 degrees and the aspect ratio is 1.3333 (although those shouldn't matter), the near plane is 0.1 and the far plane is 10. I have experimented with adjusting the far plane and even when it is 0.2 nothing is ever clipped. When it is 0.1 or below I get a blank screen. (which makes sense) The matrix is calculated like so projectionMatrix.setIdentity() float yScale MathHelper.coTangent((float) Math.toRadians(fieldOfView 2f)) float xScale yScale aspectRatio float frustumLength farPlane nearPlane projectionMatrix.m00 xScale projectionMatrix.m11 yScale projectionMatrix.m22 ((farPlane nearPlane) frustumLength) projectionMatrix.m23 1 projectionMatrix.m32 ((2 nearPlane farPlane) frustumLength) projectionMatrix.m33 0 This produces a perspective projection like so 1.299038 0.0 0.0 0.0 0.0 1.7320508 0.0 0.0 0.0 0.0 1.0 0.20202021 0.0 0.0 1.0 0.0 Thanks very much if you could help with this annoying issue benefit.


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


Rendering issues in Monogame when using shaders I am currently fiddling with Monogame, trying to work with Shaders and I have encountered a really weird issue. If the first ever draw in the application's lifetime is with a custom shader all further draws without a custom shader get this red tint (as if blue and green channels were set to 0) (A is the correct one, the sprite is white and black) The following code produced these spriteBatch.Begin() Use this for A spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, Gfx.MyShader) Use this for B spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(10, 10)) spriteBatch.End() spriteBatch.Begin() spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(50, 50)) spriteBatch.End() spriteBatch.Begin() spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(80, 80)) spriteBatch.End() And this is the shader sampler TextureSampler register(s0) float4 PixelShaderFunction(float2 texCoord TEXCOORD0) COLOR0 return tex2D(TextureSampler, texCoord) technique Shader1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() It all depends on the first draw if I replace the first two lines with this counter Starts at 0 if (counter 1) Run only on the first draw spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, Gfx.GaussianBlur) else spriteBatch.Begin() They all become red. If I replace with ! they all display correctly. I am using OpenGL for rendering. I am aware I could circumvent this problem by always using a custom shader but I fear that this is but a symptom of a greater issue that will come later to bite my bottom. Or hopefully something completely trivial that I missed. Update I tried to reproduce it in DirectX version and in this case the batch with the shader does not render, but the other sprites are not red. I also tried to compile the files via Monogame Pipeline with the same effect.


Collision Detection Tips I need collision detection for my 3D racing game but it isn't going well right now. I think I understand the concept of testing boxes and generating a response, however implementation part is a nightmare for me. OpenGL makes everything more complicated than it has to be. How can I use a shape that is constructed with glVertex ? Should I create the bounding boxes with some Vector3D class?


How to work with smaller intermediate textures in OpenGL and GLSL? I'm working on a project rendering water simulated through smoothed particle hydrodynamics (SPH) with a non photorealistic look to use in games. In the actual stage of the project everything about this rendering is done through OpenGL and GLSL in C , with many shader steps that stores intermediate textures in FBOs, which are later used in a final shader that brings everything together. Everything is working fine, except for the framerate, which lies below between 25 and 30 FPS in the better case, rendering everything, including the intermediate textures, in 1024x768 pixels. So, since some of these intermediate steps involve image smoothing algorithms that are time consuming, I thought of reducing the dimensions of the textures generated in intermediate steps to make them faster, trying to find a sweet spot between the level of reduction performance (divided by 2, 4, 8...) and the rendering final visual. My question lies precisely here How can I work with smaller textures in intermediate steps and use them on a final shader step to render to a image in a bigger dimension?


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


Is OpenGL 1.x deprecated? I'm familiar with OpenGL 1.x. I typically use SDL with OpenGL 1.4 on Linux, and I've never run into problems, even on my modern system. I've read on the OpenGL site about deprecation and compatibility contexts, but I'm still unclear as to whether it's safe to continue to use old versions of OpenGL, as opposed to using old features in newer versions. When functionality is marked deprecated ... future versions of OpenGL may remove it. Does deprecation simply imply that those functions can't be used alongside newer features? More specifically, are there any systems today (other than embedded) where OpenGL 1.x isn't available? The old skool stuff like, glBegin, glEnd, glDrawPixels, etc. Note I'm not a professional games developer, so you'll have to excuse my ignorance. I'm working on a mostly 2D game that I would like to keep multi platform, supporting at least Linux, Mac, and Windows.


Opengl lighting not working I have rendered a spinning model in LWJGL. I have calculated normals and enabled lighting. Now I make a light float lightpos 0, 0, 0, 0 FloatBuffer lightposb BufferUtils.createFloatBuffer(8) lightposb.put(lightpos) glLight(GL LIGHT0, GL POSITION, lightposb) float light 10, 10, 10, 1 FloatBuffer lightb BufferUtils.createFloatBuffer(8) lightb.put(light) glLight(GL LIGHT0, GL SPECULAR, lightb) glLight(GL LIGHT0, GL DIFFUSE, lightb) glLight(GL LIGHT0, GL AMBIENT, lightb) The model, instead of being lit up, is a dark gray. Also, no color appears on the model, even though I set its color to cyan float color 0,1,1,1 FloatBuffer colorb BufferUtils.createFloatBuffer(8) colorb.put(color) glMaterial(GL FRONT, GL AMBIENT, colorb) UPDATE Even though I have calculated normals and set them with glNormal3f, the model still appears to be shaded flat. UPDATE I HAVE done glEnable(GL LIGHTING) and glEnable(GL LIGHT0) that is NOT the problem. UPDATE I reversed the order of the light code and the model code and now the model flashes white, then goes dark grey and stays there.


OpenGL height map accuracy for planetary rendering I am trying to implement planetary rendering and I am trying to use OpenGL tessellation to model the terrain. Here is an overview picture using cube faces projected onto a sphere If I use the following code for the tessellation evaluation shader, I get a smooth sphere even when rendering a near view. version 410 core layout(quads, equal spacing, ccw) in in mediump vec2 texcoord tes out mediump vec2 texcoord geo uniform mat4 projection uniform mat4 transform void main() vec2 c mix(texcoord tes 0 , texcoord tes 1 , gl TessCoord.x) vec2 d mix(texcoord tes 3 , texcoord tes 2 , gl TessCoord.x) texcoord geo mix(c, d, gl TessCoord.y) vec4 a mix(gl in 0 .gl Position, gl in 1 .gl Position, gl TessCoord.x) vec4 b mix(gl in 3 .gl Position, gl in 2 .gl Position, gl TessCoord.x) vec4 p mix(a, b, gl TessCoord.y) float s 1.0 sqrt(p.x p.x p.y p.y p.z p.z) gl Position projection transform vec4(p.xyz s 6388000, 1) Here is a near view using the computed scaling factor (float s 1.0 sqrt(p.x ...)) However if I take the scale factors from a floating point texture, I can see quantisation artifacts. The scale factors (or heightmap values) are extracted from the texture using float s texture(hf, texcoord geo).r. The code for the tessellation evaluation shader in this case is as follows version 410 core layout(quads, equal spacing, ccw) in in mediump vec2 texcoord tes out mediump vec2 texcoord geo uniform sampler2D hf uniform mat4 projection uniform mat4 transform void main() vec2 c mix(texcoord tes 0 , texcoord tes 1 , gl TessCoord.x) vec2 d mix(texcoord tes 3 , texcoord tes 2 , gl TessCoord.x) texcoord geo mix(c, d, gl TessCoord.y) float s texture(hf, texcoord geo).r vec4 a mix(gl in 0 .gl Position, gl in 1 .gl Position, gl TessCoord.x) vec4 b mix(gl in 3 .gl Position, gl in 2 .gl Position, gl TessCoord.x) vec4 p mix(a, b, gl TessCoord.y) gl Position projection transform vec4(p.xyz s 6388000, 1) In this case the near view looks like this and shows artifacts My question is, what am I doing wrong? Or is it normal that OpenGL textures are less accurate than 4 byte floating point numbers? Any help is appreciated.


What OpenCL video cards (or FPGAs) features are needed for high speed multiplication? I'm benchmarking some cryptographic related software and am looking for video cards that are better at parallel multiplication vs parallel addition. Is there any prior work that would graph video card performance against math operations (calculating large digits like 256 2048, calculating the modulus etc.) What GPU features should I look for?


Why does my depth test fail on Nvidia cards? I sent a test version of my in development game to some friends, and they found out that the Depth Test in OpenGL does not work on Nvidia cards. I'm using LWJGL. I use my own matrices and send them to the shader, and at the start of evey game loop I use glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT ) clear the display On an Nvidia card, you can see mountains through other mountains and stuff. On my Radeon HD 6650M it works perfectly fine. Any ideas? I don't have anything special in the shaders just some basic lighting calculations. I dont touch the gl FragDepth. Here's a screenshot (with placeholder textures) I use these calculations for the Projection Matrix public Matrix4f getProjectionMatrix() Setup projection matrix Matrix4f projectionMatrix new Matrix4f() float fieldOfView 40.0f float aspectRatio (float)Display.getWidth() (float)Display.getHeight() float near plane 0.1f float far plane 1000f float y scale coTangent((float) Math.toRadians(fieldOfView 2f)) float x scale y scale aspectRatio float frustum length far plane near plane projectionMatrix.m00 x scale projectionMatrix.m11 y scale projectionMatrix.m22 ((far plane near plane) frustum length) projectionMatrix.m23 1 projectionMatrix.m32 ((2 near plane far plane) frustum length) projectionMatrix.m33 0 return projectionMatrix


Shadow maps, reducing "shimmering" I'm doing shadow maps, and my shadows move around, "shimmer", when I move around the camera. It is difficult to spot on still images but very much noticable in motion. I read an MSDN article describing the very same problem http msdn.microsoft.com en us library windows desktop ee416324(v vs.85).aspx but even with their fix, the problem still very much persists in fact, I hardly see any difference at all. Here's how I construct view projection for my directional light source, and the measures I take to combat "shimmering" yet which does not work why? Mat4 CreateDirLightVPMatrix(const Vec3 amp lightDirection, const Mat4 amp viewProjectionMatrix, const float shadowMapResolution) const Vec3 lightDir glm normalize(lightDirection) const Vec3 perpVec1 glm normalize(glm cross(lightDir, Vec3(0.0f, 0.0f, 1.0f))) const Vec3 perpVec2 glm normalize(glm cross(lightDir, perpVec1)) Mat4 rotationMatrix(Vec4(perpVec1, 0.0f), Vec4(perpVec2, 0.0f), Vec4(lightDir, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f)) Vec4 corners 8 Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f) const Mat4 inverseVPMatrix glm inverse(viewProjectionMatrix) for (uint32 t i 0 i lt 8 i ) corners i inverseVPMatrix corners i corners i corners i .w corners i corners i rotationMatrix float minX corners 0 .x, minY corners 0 .y, minZ corners 0 .z, maxX corners 0 .x, maxY corners 0 .y, maxZ corners 0 .z for (uint32 t i 0 i lt 8 i ) if (corners i .x lt minX) minX corners i .x if (corners i .x gt maxX) maxX corners i .x if (corners i .y lt minY) minY corners i .y if (corners i .y gt maxY) maxY corners i .y if (corners i .z lt minZ) minZ corners i .z if (corners i .z gt maxZ) maxZ corners i .z Mat4 viewMatrix(rotationMatrix) viewMatrix 3 0 (minX maxX) 0.5f viewMatrix 3 1 (minY maxY) 0.5f viewMatrix 3 2 (minZ maxZ) 0.5f viewMatrix 0 3 0.0f viewMatrix 1 3 0.0f viewMatrix 2 3 0.0f viewMatrix 3 3 1.0f Vec3 halfExtents((maxX minX) 0.5, (maxY minY) 0.5, (maxZ minZ) 0.5) supposed fix from MSDN article does not have any effect at all float texelSize 1.0f shadowMapResolution halfExtents.x texelSize halfExtents.y texelSize halfExtents glm floor(halfExtents) halfExtents.x texelSize halfExtents.y texelSize return glm ortho( halfExtents.x, halfExtents.x, halfExtents.y, halfExtents.y, halfExtents.z, halfExtents.y) viewMatrix


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


How to draw a Minecraft like world with Open GL I recently completed the this Open GL tutorial. The tutorial shows how to set up a window and shaders, and teaches you how to draw a single cube in the middle of the screen, which all makes sense to me (I think). I'd like to make just a simple flat world made of cubes like Minecraft, but I have no idea how to turn my single giant cube into a bunch of smaller cubes, or how to get the smaller cubes to be arranged in the proper way. Mostly what doesn't make sense to me is the coordinate system being from 1 to 1 and trying to draw a bunch of cubes in that space. Is there a way to adjust that coordinate space to be more world like, where each unit of coordinate space is roughly equivalent to a meter or something?


What is the order less rendering technique that allows partial transparency? I've seen somewhere rendering technique that allows order less rendering of partially transparent sprites objects. Though I can't remember what the technique is called, so I'm having trouble Googling it.


Shader value remap Blend Falloff I would like to know if there's a way to remap a value that goes from 0 to 1 constantly like this. Into those values (those are examples). This might be some function transformation but I can't find the way to do that. I've tried using a lookup texture but in my opinion this is not the best solution. Thank you very much.


Soft Body rendering from OBJ model As part of my master thesis I have to do an softbody simulation. I 'm using Bullet Physics engine. I'm trying to render softbody, create from Meshes, with Shaders in OpenGL but the object doesnt seem to be rendered (it doesnt appear in the window). I'm not sure if the problem is because of the way I created the sobtbody or the way I render it. Thank you in advance. I'm using this function for creating a softBody from my OBJ Liver model btScalar verti new btScalar 3 (Liver.getMeshes() 0 .vertices.size()) for (int i 0 i lt Liver.getMeshes() 0 .vertices.size() i ) verti 3 i Liver.getMeshes() 0 .vertices i .Position.x verti 3 i 1 Liver.getMeshes() 0 .vertices i .Position.y verti 3 i 2 Liver.getMeshes() 0 .vertices i .Position.z int indi new int Liver.getMeshes() 0 .indices.size() for (int i 0 i lt Liver.getMeshes() 0 .indices.size() i ) indi i Liver.getMeshes() 0 .indices i btSoftBody LiverSBody btSoftBodyHelpers CreateFromTriMesh(softBodyWorldInfo, verti, amp indi 0 , int(Liver.getMeshes() 0 .indices.size()) 3) LiverSBody gt m cfg.kVC 0.5 btSoftBody Material pSpMat LiverSBody gt appendMaterial() LiverSBody gt m materials 0 gt m kLST 0.5 pSpMat gt m kLST 1.0 LiverSBody gt setPose(false, true) btTransform trans trans.setIdentity() trans.setOrigin(btVector3(0,0,0)) LiverSBody gt transform(trans) LiverSBody gt generateBendingConstraints(2, pSpMat) LiverSBody gt m cfg.piterations 2 LiverSBody gt m cfg.kDF 1.0 LiverSBody gt m cfg.kSRHR CL 1 LiverSBody gt m cfg.kSR SPLT CL 0 LiverSBody gt setTotalMass(10, true) LiverSBody gt scale(btVector3(0.02, 0.02, 0.02)) LiverSBody gt getCollisionShape() gt setMargin(0.1) float Friction 0.9 float Restitution 0.5 LiverSBody gt setFriction(Friction) LiverSBody gt setRestitution(Restitution) m pSoftBodyWorld gt addSoftBody(LiverSBody) I'm using this class for loading and visualizing model https learnopengl.com code viewer gh.php?code includes learnopengl model.h I need to extract from the softBody some data (Position, normal, texCoords, tangent and bitangent) to fill the vertex buffer objects but i don't know where to find most of it... I know that the position and the normals are in the softbody nodes but i can't find the other information needed (texCoords, ..). btSoftbody.h struct Node Feature btVector3 m x Position btVector3 m q Previous step position btVector3 m v Velocity btVector3 m f Force accumulator btVector3 m n Normal btScalar m im 1 mass btScalar m area Area btDbvtNode m leaf Leaf data int m battach 1 Attached


Simple mouseray picking in openGL Ive been looking at tutorials and trying to figure out how to do basic ray picking. But I'm stuck at figuring out what space to do the distance calculations in. What space does glm unproject() lead to exactly? This is what I'm doing first I get the mouse unprojected, like so mouse ray start vec3 m uproj glm unProject( vec3(mouse xy .x glutGet(GLUT WINDOW WIDTH), mouse xy .y glutGet(GLUT WINDOW HEIGHT),0.0f), workshop.access gui() gt view mat(), workshop.access gui() gt proj mat(), glm ivec4(0, 0, glutGet(GLUT WINDOW WIDTH), glutGet(GLUT WINDOW HEIGHT))) end of ray vec3 m uproj2 glm unProject( vec3(mouse xy.x glutGet(GLUT WINDOW WIDTH), mouse xy.y glutGet(GLUT WINDOW HEIGHT), 1.0f), workshop.access gui() gt view mat(), workshop.access gui() gt proj mat(), ivec4(0, 0, glutGet(GLUT WINDOW WIDTH), glutGet(GLUT WINDOW HEIGHT))) Then I find its direction, mray, like so vec3 mouse ray normalize(m uproj2 m uproj) get mray direction And Im expecting to find the closest point to some object by using this calculation vec3 closest point mouse ray glm dot(locations i , mouse ray) closest point But locations seems to be in the wrong space? Or am I thinking about this the wrong way? Ive been looking around, but I cant find anywhere that explains just this part that I must be misunderstanding. the idea is to compare the distance between closest point and locations i , but the results are incorrect. Im getting something like this Where it should be red only if the cursor is over the square. What space does glm unproj() put my ray in anyway? And in what space should I put the objects that I want to pick highlight?