How to properly transform vertices for a model loaded using Assimp? When I try to load a DAE model then vertices are not placed correctly. Here's the code snippet I use to load 3D models using Assimp aiNode CGameObject findNode(aiNode rootNode, const char name) if (!strcmp(name, rootNode gt mName.data)) return rootNode for (int i 0 i lt rootNode gt mNumChildren i ) aiNode found findNode(rootNode gt mChildren i , name) if (found) return found return NULL void CGameObject transformNode(aiMatrix4x4 result, aiNode rootNode) if (rootNode gt mParent) transformNode(result, rootNode gt mParent) aiMultiplyMatrix4(result, amp rootNode gt mTransformation) else result rootNode gt mTransformation Assimp Importer importer const aiScene scene importer.ReadFileFromMemory(buffer, size, aiProcess CalcTangentSpace aiProcess Triangulate aiProcess JoinIdenticalVertices aiProcess GenUVCoords aiProcess TransformUVCoords aiProcess FlipUVs aiProcess SortByPType) if (!scene) return false const int iVertexTotalSize sizeof(aiVector3D) 2 sizeof(aiVector2D) int iTotalVertices 0 for(int i 0 i lt scene gt mNumMeshes i ) Mesh m new Mesh aiMesh mesh scene gt mMeshes i aiNode node findNode(scene gt mRootNode, mesh gt mName.data) transformNode( amp node gt mTransformation, node) aiTransposeMatrix4( amp node gt mTransformation) int iMeshFaces mesh gt mNumFaces for (int f 0 f lt iMeshFaces f ) const aiFace face amp mesh gt mFaces f for (int k 0 k lt 3 k ) int vertexIndex face gt mIndices k iTotalVertices aiVector3D pos mesh gt mVertices vertexIndex aiTransformVecByMatrix4( amp pos, amp node gt mTransformation) m gt vertices.push back(pos.x) m gt vertices.push back(pos.y) m gt vertices.push back(pos.z) ... What am I doing wrong ? I will create a VBO for all the vertex positions later and render them. When I load an OBJ model everything loads fine and there is no need for applying per node transformations. Also, I noticed that Assimp renames node names from "Cube.001" to "Cube 001", is this behavior normal expected. I'm using Assimp 3.1.1.


Using PyOpenGL, can I rotate raw data rather than the current matrix? I'm trying to create a sort of PyOpenGL renderer for the Bullet physics engine, and at the moment I'm rotating my basic cubes with math in Python. However, if I do the math in Python that's going to take more time than doing the math with OpenGL. OpenGL has the ability to rotate a matrix using glRotatef(), but it only rotates the "current matrix". I'm not really interested in convoluting my render loop with an individual check for each object's rotation and position if I don't have to. So my question is, is there a way I can, for example, load a matrix of points into OpenGL, rotate this matrix and then read it back and give it to my render loop? Or should I instead look for an alternative 3D math library? (Or for that matter, is running the code in python really all that laggy?)


How to mix pixel colors in Shader? I have a pixel that have a colour RGB. This color is calculated by the shader and can be anything. How can I override this color by a colour I choose. If my pixel is white it's simple, I can do this half3 original half3(1, 1, 1) half3 mycolor half3(1, 0, 0) half3 result original mycolor But what can I do if half3 original half3(0.36, 0.74, 0.18) half3 mycolor half3(1, 0, 0) half3 result ? What operation or function should I apply to my original pixel color to override it ?


LWJGL 3 Random Sprites Don't Blend Some of my sprites don't quot Blend quot in with tiles behind them Z wise. glEnable(GL DEPTH TEST) Depth testing is enabled and works. glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) The blend function is above. Below is a picture of four different instances of the application. As you can see, blending works on random sprites. Why aren't some of the sprites blending? An observation that I made is that when I move the sprites (layers 0 and 1) below (Z wise) the button, you can see the sprites from the gaps left by letters (layer 10), yet the button itself (layer 9) doesn't show in that area. This is what I find the strangest.


OpenGL ES wrong orientation I'm writing a little Android game in OpenGL ES. My game graphics are not appearing in the right orientation. In fact everything is drawn in reverse vertically. Can someone please comment on my understanding of how OpenGL works below please? My understanding is that OpenGL works in a right handed coordinate system, e.g. y( ) o x( ) z( ) So, I set my orthographic projection matrix using Matrix.orthoM(..., 2, 2, 2, 2, 1, 15) for example, so if I were to draw a line from ( 2, 2, 0) to (2, 2, 0) I should be drawing a line in the X Y plane from ( 2, 2) top (2, 2). Near and far planes are 1 and 15 respectively. In addition I am setting up my view matrix using Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 10, 0, 0, 0, 0, 1, 0) so I'm standing on the positive Z axis at 10 units, looking towards the origin with the Y axis as the upwards vector. But when I come to draw stuff, everything is flipped in the X axis. So a point at (1, 1) would appear at (1, 1). Does anyone see what might be wrong here?


How to "hot reload" a glsl shader I am wondering if its possible to dynamically change shaders while the code is running. In my game, I want to have a development mode in which users can change the shader source and dynamically see their changes like so https www.youtube.com watch?v hlSG iVC6xc this is my current reload method Shader is my shader class and shader is the current shader delete all resources of previous shader if (shader gt GetProgram() ! 0) glDeleteProgram(shader gt GetProgram()) if (inShader gt GetVert() ! 0) glDeleteShader(inShader gt GetVert()) if (inShader gt GetGeom() ! 0) glDeleteShader(inShader gt GetGeom()) if (inShader gt GetFrag() ! 0) glDeleteShader(inShader gt GetFrag()) GLuint vertex shader glCreateShader(GL VERTEX SHADER) GLuint fragment shader glCreateShader(GL FRAGMENT SHADER) GLuint geometry shader glCreateShader(GL GEOMETRY SHADER) create vertex shader glShaderSource(vertex shader, 1, (const GLchar )vertSource, NULL) glCompileShader(vertex shader) create fragment shader glShaderSource(fragment shader, 1, (const GLchar )fragSource, NULL) glCompileShader(fragment shader) GLuint program glCreateProgram() glAttachShader(program, vertex shader) glAttachShader(program, fragment shader) glLinkProgram(program) Shader theResult new Shader(context) theResult gt SetVertShader(vertex shader) theResult gt SetFragShader(fragment shader) theResult gt SetGeomShader(geometry shader) theResult gt SetProgram(program) replace the shader we created with the old one shader theResult delete theResult return shader The above code does one of two things when called, it either gives some undefined graphical behaviour or doesn't seem to reload the shader and use the previous ones. Is there something I'm missing regarding how I'm linking the new shaders, or is this even the right approach? As requested i will add the shader class information shader.h protected Shader properties unsigned int m VertexShader unsigned int m GeometricShader unsigned int m FragmentShader unsigned int m Program OpenGL mContext public Constructor Shader(OpenGL context) Shader() Getter setters shader properties inline unsigned int GetVert() return m VertexShader inline unsigned int GetGeom() return m GeometricShader inline unsigned int GetFrag() return m FragmentShader inline unsigned int GetProgram() return m Program inline void SetVertShader(unsigned int inValue) m VertexShader inValue inline void SetGeomShader(unsigned int inValue) m GeometricShader inValue inline void SetFragShader(unsigned int inValue) m FragmentShader inValue inline void SetProgram(unsigned int inValue) m Program inValue shader.cpp Shader Shader(OpenGL context) m VertexShader(0), m GeometricShader(0), m FragmentShader(0), m Program(0), mContext(context) Shader Shader()


opengl rotations for a human I currently can rotate around a pivot point by first translating to the pivot point then performing the rotation and finally translating back to the origin. I do that easily enough for the shoulder in my example. However I cannot figure out how to also add in a rotation around the elbow for the forearm. I've tried the following for the forearm rotation around the elbow translate to shoulder, rotate, translate to origin, translate to forearm, rotate, translate to origin translate to shoulder, rotate, translate to forearm, rotate, translate to shoulder, translate to origin Neither work for me. Any suggestions? I'm really stuck on this one.


Is glDrawArraysInstanced in OpenGL parallel when drawing those instances? Is glDrawArraysInstanced in OpenGL parallel when drawing those instances? I cannot figure out by referring to its reference and numerous online tutorials. Update To be more clear, I mean, for example, we have 100 instances. Are the drawing of those 100 instances parallel? For example, we have the 100 commands "glDrawArrays(mode, first, count) "? Is execution of those 100 commands sequential or parallel? I think it should be sequential. GPU begins to draw the second instance, only AFTER the first instance drawing finished. Or glDrawArraysInstanced just save the time for "giving your GPU the commands"? Update 2 The reason I wanted to know the answer, is that If it is sequential, personally I think drawing thousands of tree leaves in this way is time consuming. I may draw them in one shader program with some algorithm tweak.


Does the order of vertex buffer data when rendering indexed primitives matter? I'm building a 3d object's triangles. If I can write them to the buffer in the order they are calculated it will simplify the CPU code. The vertices for the triangles will not be contiguous. Is there any performance penalty for writing them out of order?


OpenGL Textures not sitting right on model I have been trying to get textures loading properly onto my models but to no avail. I'm using picopng to load my images. Here is my code. Texture code std vector lt unsigned char gt buffer, image, aaa std ifstream file(location.c str(), std ios in std ios binary std ios ate) std streamsize size 0 if (file.seekg(0, std ios end).good()) size file.tellg() if (file.seekg(0, std ios beg).good()) size file.tellg() if (size gt 0) buffer.resize((size t)size) file.read((char )( amp buffer 0 ), size) else buffer.clear() unsigned long w, h int error decodePNG(image, w, h, buffer.empty() ? 0 amp buffer 0 , (unsigned long)buffer.size()) if (error ! 0) std cout lt lt "error " lt lt error lt lt std endl glEnable(GL TEXTURE 2D) GLuint id glGenTextures(1, amp id) glBindTexture(GL TEXTURE 2D, id) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, w, h, 0, GL RGBA, GL UNSIGNED BYTE, amp image 0 ) glBindTexture(GL TEXTURE 2D, 0) glGenerateMipmap(GL TEXTURE 2D) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP LINEAR) float mipMapingAffectivness 0.4f glTexParameterf(GL TEXTURE 2D, GL TEXTURE LOD BIAS, mipMapingAffectivness) Any advice? Update I have tried flipping the image but to no avail, I have tried all 8 orientation variations and non seem to work.


SDL Image and typical SDL BMP loading fails completely been messing with OpenGL and SDL for a pair of weeks. The thing is quite weird. I have been loading a texture from a BMP and using a really easy shader to make it work, and so far it has worked very well. Now, i've refractored my code and made a heightmap loader, with is pretty cool and works nice. I have a ResourceManager class which successfully loads shaders but fails at loading textures. The structure of that class is simple Constructor (empty) Destructor (empty) AddTexture (const char FileName, const char indexName) GetTexture (const char indexName) typedef map TextureMap typedef TextureMap iterator TextureIt TextureMap Textures I tried using SDL Load BMP function and SDL img Load IMG function. The first one makes this weird result Close Up When the real image is a simple BMP in 32bit format, as always Real Texture And the second method, using SDL image, simply doesn't show the image. The 'AddTexture' function bool TEXTURE TextureManager AddTexture(const char fileName, const char indexName) SDL Surface img SDL LoadBMP(fileName) unsigned int id glGenTextures(1, amp id) glBindTexture(GL TEXTURE 2D, id) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, img gt w, img gt h, 0, GL RGB, GL UNSIGNED SHORT 5 6 5, img gt pixels) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) SDL FreeSurface(img) Textures indexName id return true And the 'AddTexture' SDL image version GLuint id 0 SDL Surface Surface IMG Load(fileName) glGenTextures(1, amp id) glBindTexture(GL TEXTURE 2D, id) int Mode NULL if(Surface gt format gt BytesPerPixel 4) Mode GL RGBA else Mode GL RGB glTexImage2D(GL TEXTURE 2D, 0, Mode, Surface gt w, Surface gt h, 0, Mode, GL UNSIGNED BYTE, Surface gt pixels) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glBindTexture(GL TEXTURE 2D, 0) std cout lt lt "The ID of the tex is " lt lt id lt lt std endl Textures indexName id return true I create the texture here Res gt TexManager gt AddTextureAlt("res sum.bmp", "Brick") And the following code is used to bind the texture GLuint TEX Res gt TexManager gt GetTexture("Brick") glBindTexture(GL TEXTURE 2D, TEX) The normals and tex coords are alright, i've been using it all the time and it was displaying the tex and light perfectly well before. I can't find the problem. I just can't. Is someone able to help a poor noob?


Texturing in OpenGL, Should texture coordinates be assigned to vertices in the shader? I attempting to texture 3D models (a cube for example) using ibo s, with OpenGL in Java. Currently, my textures are distorted. I believe this is because only a single texture coordinate is being assigned to each vertex, as the meshes are loaded from wave front (.obj) files. As each vertex should correspond to multiple texture coordinates, should I be assigning texture coordinates to vertices as the data is loaded from file or would it be better to assign texture coordinates to vertices in the shader? I would appreciate example code.


How to modify VBO data I am learning LWJGL so i can start working on my game. In order to learn LWJGL I got the idea to implement the map builder so I can get comfortable with graphics programming. Now, for the map creation tool I need to draw new elements or draw the old one's with different coordinates. Let me explain this My game will be a 2D scroller. The map will be consisting of multiple rectangles ( 2 strip triangles). When I click my left mouse button i want to start the rectangle and when I release it I want to stop the rectangle bottom right at that position. As I want to use VBOs I want to know how to modify data inside the VBO based on user input. Should i have a copy of a vertex array and then add the whole array to the VBO at each user input? How is usually implemented the VBO update?


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 ?


JNI Error when Wrapping Jar with JOGL using Launch4j I have been trying to wrap my fat JAR file into an EXE using Launch4j, but I have been running into problems when I try to execute the EXE. Here is the error log I get from Launch4j Executing E Downloads CasualCaving.exe JNILibLoaderBase Caught IllegalArgumentException No Jar name in lt jar file E Downloads CasualCaving.exe! jogamp common Debug.class gt Exception in thread "main" java.lang.UnsatisfiedLinkError Can't load library E Downloads natives windows amd64 gluegen rt.dll at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.load0(Unknown Source) at java.lang.System.load(Unknown Source) at com.jogamp.common.jvm.JNILibLoaderBase.loadLibraryInternal(JNILibLoaderBase.java 624) at com.jogamp.common.jvm.JNILibLoaderBase.access 000(JNILibLoaderBase.java 63) at com.jogamp.common.jvm.JNILibLoaderBase DefaultAction.loadLibrary(JNILibLoaderBase.java 106) at com.jogamp.common.jvm.JNILibLoaderBase.loadLibrary(JNILibLoaderBase.java 487) at com.jogamp.common.os.DynamicLibraryBundle GlueJNILibLoader.loadLibrary(DynamicLibraryBundle.java 421) at com.jogamp.common.os.Platform 1.run(Platform.java 317) at java.security.AccessController.doPrivileged(Native Method) at com.jogamp.common.os.Platform. lt clinit gt (Platform.java 287) at com.jogamp.opengl.GLProfile. lt clinit gt (GLProfile.java 147) at org.graphics.Render. lt init gt (Render.java 20) at org.engine.Main.main(Main.java 18) I am using JOGL 2.3.2 imported through Maven, with the assembly plugin to compile it to a fat JAR. Here is a picture of my library configuration I am not sure what is wrong, as the JAR file works fine.


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


Java OpenGl Rotating Cube Problem! OK, so I successfully learned how to bind textures to quads and display this cool looking crate. However, when I rotate the cube something goes wrong. During rotation the back face of the cube overlays the front face and appears in front of the front face. This is also the case with the right and left faces. They overlay each other giving a weird perception. I'm not sure why this happens. Here is the code where I draw only four face of the quad (front, back right, left). gl.glClear(GL2.GL COLOR BUFFER BIT GL2.GL DEPTH BUFFER BIT) clear the screen and depth buffers gl.glLoadIdentity() reset the current modelview matrix draw quad gl.glTranslatef(0.0f, 0.0f, 6.0f) translate to the left and into the screen gl.glRotatef(rotateAngle, 0.0f, 1.0f, 0.0f) rotate triangle around the y axis gl.glBindTexture(GL2.GL TEXTURE 2D, textures 2 ) bind the texture you want to use to gl texture 2d gl.glBegin(GL2.GL QUADS) front face gl.glTexCoord2f(0.0f, 1.0f) bottom left gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 1.0f) bottom right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 0.0f) top right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(0.0f, 0.0f) top left gl.glVertex3f( 1.0f, 1.0f, 1.0f) right face gl.glTexCoord2f(0.0f, 1.0f) bottom left gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 1.0f) bottom right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 0.0f) top right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(0.0f, 0.0f) top left gl.glVertex3f(1.0f, 1.0f, 1.0f) left face gl.glTexCoord2f(0.0f, 1.0f) bottom left gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 1.0f) bottom right gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 0.0f) top right gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glTexCoord2f(0.0f, 0.0f) top left gl.glVertex3f( 1.0f, 1.0f, 1.0f) back face gl.glTexCoord2f(0.0f, 1.0f) bottom left gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 1.0f) bottom right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(1.0f, 0.0f) top right gl.glVertex3f(1.0f, 1.0f, 1.0f) gl.glTexCoord2f(0.0f, 0.0f) top left gl.glVertex3f( 1.0f, 1.0f, 1.0f) gl.glEnd() Moreover, the way I draw textures and then vertices is not yet clear to me. According to what I've read the bottom left corner (0, 0) is where the textures start drawing, so I should also start drawing my quad from bottom left accordingly. I tried that but it didn't work. The texture was drawn, but up side down. So I had to go through some trial and error till I got the texture drawn correctly. I wish I could attach a picture to this post so I can show you how the back face of the cube overlays the front one during rotation, but I think this facility isn't provided in stack exchange. Thanks.


Does interleaving in VBOs speed up performance when using VAOs You usually get a speed up when you use interleaved VBOs instead of using multiple VBOs. Is this also valid when using VAOs? Because it's much more convenient to have a VBO for the positions, and one for the normals etc. And you can use one VBO in multiple VAOs.


Run OpenGL shader on part of a texture How do I run an OpenGL shader on just a portion of an off screen texture and leave the rest of the texture unmodified? Are there any calls that restrict the sampled pixels to just a rectangle or do I have to filter out the rectangle in the shader code?


OpenGL Index buffers problem I have a custom file format that has all the needed information for a 3D mesh (exported from 3ds Max). I've extracted the data for vertices, vertex indices and normals. I pass to OpenGL the vertex data, vertex indices and normals data and I render the mesh with a call to glDrawElements(GL TRIANGLES,...) Everything looks right but the normals. The problem is that the normals have different indices. And because OpenGL can use only one index buffer, it uses that index buffer for both the vertices and the normals. I would be really grateful if you could suggest me how to go about that problem. Important thing to note is that the vertex normal data is not "sorted" and therefore I am unable to use the functionality of glDrawArrays(GL TRIANGLES,...) the mesh doesn't render correctly. Is there a way algorithm that I can use to sort the data so the mesh can be drawn correctly with glDrawArrays(GL TRIANGLES,..) ? But even if there is an algorithm, there is one more problem I will have to duplicate some vertices (because my vertex buffer consists of unique vertices for example if you have cube my buffer will only have 8 vertices) and I am not sure how to do that.


What is the "main" implementation of OpenGL? What is the main implementation of OpenGL? I see GLUT everywhere, but I want to use whatever is closest to an official implementation, or what ever I will have the most control over. I might not be asking this right since it's contributed to by different parties. Which is why I have been looking at DirectX, but I see more people using OpenGl so I'd like to use that instead.


Constant size geometries for glDrawArraysInstanced calls In my application I can keep the objects constant sized const Graphics VectorDouble diffVec(dTranslateX m CameraTransformOffset.x, dTranslateY m CameraTransformOffset.y, dTranslateZ m CameraTransformOffset.z) camScaleInv Graphics Lenght(diffVec) 2.0f tan(fov 0.5f PI 180.0f) Than I scale my view matrix with camScaleInv and I think that is very common to do but , I have some objects which I draw with glDrawArraysInstanced. I pass the parent surface only once and another array for duplicating the parent surface in different positions. That causes my quot diffVec quot to be different and causes me to not being able to use keep same distance logic in CPU side. Is there any way for me to keep the objects which are being drawn with glDrawArraysInstanced same size either in CPU or GPU(glsl) side.


Store static environment in chunks I have terrain separated by chunks and I would like to put environment (For example, rocks, trees, etc..) in each chunk randomly. My question is related to how to implement such system in OpenGL. What I have tried Solution Draw the environment with instancing once for all the terrain (not a specific chunk) Problem I except the chunk to sometimes take a bit to load and because I am using threads the environment will appear as floating. Solution Draw the environment with instancing for each chunk. Problem To draw each chunk, I will need to bind the VBO for the chunk, draw the chunk, bind the VBO for the environment (and the VAO probably) and draw it. I don't want to put so many glBindBuffer functions because I heard it is slow (Please correct me if I am wrong) (Not tried) Solution Somehow merge the vertices of the terrain with its environment and draw them together. Problem My terrain is drawn with GL TRIANGLE STRIP so this is a first problem, the second problem(?) is that I don't know how well it will function (talking speed). I tried looking up solutions on the internet but didn't seem to find any that relate to chunks. Anyone know how other games that uses chunks do that? Is there a way to do it without causing a lot of speed decrease?


OpenGL Keeping alpha in a render buffer In my current task, i need to render a texture into a render buffer, in order to work on it (apply special filters) there. The result is then considered a "new texture", which is later displayed. This works fine, except when the texture contains some transparent semi transparent parts. My current guess it that, within the render buffer, the texture is "merged" with a kind of "grey background". In this case, it obviously impacts the R,G,B color components of transparent pixels. I've yet to find a way around this. Even manually assigning alpha after the rendering process doesn't save the day for semi transparent pixels, which RGB are "tainted" by the grey background.


OpenGL ES indices optimization I am using OpenGL ES 1.x 2.x I have 2 attributes to be passed to the GPU(one is colors, one is vertices, one color per vertex). I use indices. Both attributes will use the same indices array This is not a big issue but I was wondering if there is a way to tell the GPU that both attributes use the same indices array so that it is not transfered to the gpu twice, or maybe it does not matter because the GPU uses the RAM?


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


Shaders and Performance I'm coding my first Shader in my little game engine, and I have some questions about it's performance and common approaches. Is the Shader code processed by the video card instead of the PC processor? Just so I know if it's possible to share some calculations to save some processor power. Generally, should I do the math calculations in my code or the Shader? I could calculate them all (lightning for example) and just send the final values to be multiplied used to the Shader, but what's the best approach? Shaders as far as I could understand are the main party responsible for visual effects, so for example, if I want to add a "blur" effect to only one object on screen, should I use an if switch statement in the Shader or should I have different Shader ProgramIDs and I just switch the call glUseProgram(programID)? Sorry if some questions seems stupid, and thanks for your time!


Shadow map shimmering, indexing outside the shadow map I have tried to reduce the shadow shimmering flickering using the technique described here http msdn.microsoft.com en us library windows desktop ee416324 28v vs.85 29.aspx It works as I want and shimmering is reduced but sometimes I have artifacts. It looks like my code tries to index space outside the shadow map. The article above writes about it but I didn't find a solution. When I played with the code I also got black strips on the corners. Code reduce shadow shimmering flickering Vector2 vecWorldUnitsPerTexel Vector2(D.x() (float)D.shadowMapSize(), D.y() (float)D.shadowMapSize()) get only x and y dimensions Vector2 min2D min.vector2(), max2D max.vector2() min2D vecWorldUnitsPerTexel min2D Round(min2D) min2D vecWorldUnitsPerTexel max2D vecWorldUnitsPerTexel max2D Round(max2D) max2D vecWorldUnitsPerTexel min.set(min2D, min.z) max.set(max2D, max.z) crop matrix based on this article https developer.nvidia.com gpugems GPUGems3 gpugems3 ch10.html Vector scale Vector offset scale.x 2.0f (max.x min.x) scale.y 2.0f (max.y min.y) scale.z 1.0f (max.z min.z) offset.x 0.5f (max.x min.x) scale.x offset.y 0.5f (max.y min.y) scale.y offset.z min.z scale.z Matrix4 m m.x Vector4(scale.x, 0, 0, 0) m.y Vector4(0, scale.y, 0, 0) m.z Vector4(0, 0, scale.z, 0) m.w Vector4(offset.x, offset.y, offset.z, 1.0f) I think that I should store in the depth map a slightly larger area but I'm not sure how to do this. I tried to change the scale of the crop matrix but it doesn't help. EDIT It seems I've found a solution. When I'm rounding (or flooring) min and max values I subtract one from the min value and add one to the max value. This makes the shadow map contain a slightly larger area and I don't see any artifacts.


Draw contour around object in Opengl I need to draw contour around 2d objects in 3d space. I tried drawing lines around object( points to fill the gap), but due to line width, some part of it( 50 ) was covering object. I tried to use stencil buffer, to eliminate this problem, but I got sth like this(contour is green) http goo.gl OI5uc (sorry I can't post images, due to my reputation) You can see(where arrow points), that some parts of line are behind object, and some are above. This changes when I move camera, but always there is some part, that is covering it. Here is code, that I use for drawing object glColorMask(1,1,1,1) std list lt CObjectOnScene gt iterator objIter ptr gt objects.begin(),objEnd ptr gt objects.end() int countStencilBit 1 while(objIter! objEnd) glColorMask(1,1,1,1) glStencilFunc(GL ALWAYS,countStencilBit,countStencilBit) glStencilOp(GL REPLACE,GL KEEP,GL REPLACE ) ( objIter) gt DrawYourVertices() glStencilFunc(GL NOTEQUAL,countStencilBit,countStencilBit) glStencilOp(GL KEEP,GL KEEP,GL REPLACE) ( objIter) gt DrawYourBorder() objIter countStencilBit I've tried different settings of stencil buffer, but always I was getting sth like that. Here is question 1.Am I setting stencil buffer wrong? 2. Are there any other simple ways to create contour on such objects? Thanks in advance. EDIT 1. I don't have normals of objects. 2. Object can be concave. 3. I can't use shaders(see below why).


Problem with bullet movement I'm trying to draw quot bullets quot in my game, but I think something is wrong with velocity computation. Sometimes the quot bullets quot are going in the right way, but sometimes they won't. The CameraFront is constructed with euler angles. Can you help? Thanks in advance So this is how I create bullets Bullet tracer makeBulletTracer(v3 cameraFront,v3 startP, v3 endP) Bullet tracer result assert((gTracersCount 1) lt MAX BULLET TRACERS) mat4 model indentity() model scale(model, v3(.5f,.5f,1.5f)) v3 up v3(0.0f,1.0f,0.0f) v3 right normalize(cross(cameraFront,up)) mat4 M rows3x3(right,up,cameraFront) model model M model translate(model, startP v3(0.0f,3.0f,0.0f)) result.model model result.velocity cameraFront gTracersCount return result This is how I draw them for (u32 tracerIndex 0 tracerIndex lt gTracersCount tracerIndex ) Bullet tracer tracer gameState gt tracers tracerIndex v3 p getTranslationPart(tracer gt model) v3 offset (p tracer gt velocity) input gt dtForFrame 0.01f tracer gt model translate(tracer gt model, offset) passUniformMatrix(opengl.shaderProgram,tracer gt model,false, quot model quot ) glDrawArrays(GL TRIANGLES, 0, 36)


What does glBlendFunc do when given an incorrect enumeration value? In cocos2d x, I am using particle system from plist with blend values dst 1, and src 100 which is wrong enum for gl blend. Although app logged "OpenGL error 0x0500" but it still run and showed a good blend effect. And i can not find the right pairs of dst and src to recreate that effect. So i hope someone can tell me how BlendFunc gl blend will work when it having bad src value. Base on that i hope i can recreate that effect without using wrong src value. Thanks


OpenGL can an Element Array Buffer points to only one VBO I'm making a Minecraft style game and currently storing 36 vertices and texture coordinates per cube. Could I make an EBO for only the position and leave the texture coordinates as they are? OK i think thsi is how i will do it. I would have an array of 24 vertices(3 GLfloat) and 24 texture coordinates(2 GLfloat) for the corners then i would have an EBO pointing to the corners with 36 indices So memory total 24 3 4 24 2 4 36 4 624 bytes instead of 36 3 4 36 2 4 720 bytes


OpenGL GLSL vector of sampler2D If im trying to create an obj. file loader in c and draw it with opengl i need to use multiple textures in the fragment shader.I know i can just use uniform sampler2D Texture1 uniform sampler2D Texture2 uniform sampler2D Texture3 uniform sampler2D Texture4 But i think there must be an elegant way to do it.Like a vector of samplers or something.Im asking this because i dont want to declare n textures in my fragment shader and type n if's where i test which texture i should use for the current fragment.It just looks ugly.


How to properly transform vertices for a model loaded using Assimp? When I try to load a DAE model then vertices are not placed correctly. Here's the code snippet I use to load 3D models using Assimp aiNode CGameObject findNode(aiNode rootNode, const char name) if (!strcmp(name, rootNode gt mName.data)) return rootNode for (int i 0 i lt rootNode gt mNumChildren i ) aiNode found findNode(rootNode gt mChildren i , name) if (found) return found return NULL void CGameObject transformNode(aiMatrix4x4 result, aiNode rootNode) if (rootNode gt mParent) transformNode(result, rootNode gt mParent) aiMultiplyMatrix4(result, amp rootNode gt mTransformation) else result rootNode gt mTransformation Assimp Importer importer const aiScene scene importer.ReadFileFromMemory(buffer, size, aiProcess CalcTangentSpace aiProcess Triangulate aiProcess JoinIdenticalVertices aiProcess GenUVCoords aiProcess TransformUVCoords aiProcess FlipUVs aiProcess SortByPType) if (!scene) return false const int iVertexTotalSize sizeof(aiVector3D) 2 sizeof(aiVector2D) int iTotalVertices 0 for(int i 0 i lt scene gt mNumMeshes i ) Mesh m new Mesh aiMesh mesh scene gt mMeshes i aiNode node findNode(scene gt mRootNode, mesh gt mName.data) transformNode( amp node gt mTransformation, node) aiTransposeMatrix4( amp node gt mTransformation) int iMeshFaces mesh gt mNumFaces for (int f 0 f lt iMeshFaces f ) const aiFace face amp mesh gt mFaces f for (int k 0 k lt 3 k ) int vertexIndex face gt mIndices k iTotalVertices aiVector3D pos mesh gt mVertices vertexIndex aiTransformVecByMatrix4( amp pos, amp node gt mTransformation) m gt vertices.push back(pos.x) m gt vertices.push back(pos.y) m gt vertices.push back(pos.z) ... What am I doing wrong ? I will create a VBO for all the vertex positions later and render them. When I load an OBJ model everything loads fine and there is no need for applying per node transformations. Also, I noticed that Assimp renames node names from "Cube.001" to "Cube 001", is this behavior normal expected. I'm using Assimp 3.1.1.


OpenGL Fragment Shader Interpolation Vs Inverse Calculation I have found openGL fragment shader tutorials on the web, some that use use inverse calculations to revert the fragment coordinate back to the world space and others that interpolate the position. With that said... Is there a difference between interpolated world space position and the actual world space position calculated using inverse matrices and the fragment window space coordinates? Does anyone know of any resources that would help me understand the mathematical differences between these two things, if they are different? If they aren't different, then why would anyone use inverse matrices instead of interpolating, which seems less expensive? I wrote a shader to test 1, but I cannot tell if rounding errors are to blame for the differences or not. Thanks!


How do I implement camera axis aligned billboards? I am trying to make an axis aligned billboard with Pyglet. I have looked at several tutorials, but they only show me how to get the up, right, and look vectors. So far this is what I have target cam.pos look norm(target billboard.pos) right norm(Vector3(0,1,0) look) up look right gluLookAt( look.x, look.y, look.z, self.pos.x, self.pos.y, self.pos.z, up.x, up.y, up.z ) This does nothing for me visibly. Any idea what I'm doing wrong?


Deferred shadow mapping Question What am i doing wrong in the CalcShadowFactor method? It looks like the depth check is not working correctly. Body I'm using deferred rendering in my engine and i have generated the following shadow map Which is draw by the following fragment void main() gl FragColor vec4(texture(gColorMap, TexCoord0).x) The position texture is generated like this WorldPos0 (gWorld vec4(Position, 1.0)).xyz Where gWorld is the transformation of the object being draw(translation rotation scale) Finally, in the light pass, i want to generate the shadow produced from this spotlight with the following code float CalcShadowFactor(vec3 WorldPos) vec4 ShadowCoord gLightWVP vec4(WorldPos,1) ShadowCoord ShadowCoord.w vec2 UVCoords UVCoords.x 0.5 ShadowCoord.x 0.5 UVCoords.y 0.5 ShadowCoord.y 0.5 float z 0.5 ShadowCoord.z 0.5 float Depth texture(gShadowMap, UVCoords).x if (Depth lt z 0.00001) return 0 else return 1.0 It returns a float which multiplicates the color output. I know, im just returning 0 to set the color to complete transparent, it is intensional. The variables used were gLightWVP It is the ProjectionView of the camare set at the light Projection LightCameraRotation LightCameraTranslation WorldPos It is the position got from the Position Texture vec3 WorldPos texture2D( gPositionMap, TextCoord0 ).xyz gShadowMap It is the shadow map texture sampler. This is what is displayed(notice how the spotlight looks at the first image) The engine passes are Shadow pass Render the scene for every light using a alternative camera which is placed in their position with their orientation. It generates the shadow maps for every light. Currently i just have one shadow map for that spot light. Render pass It renders all the scene using the main camera. It generates the position map, normal map, diffuse map and a specular map. Light pass It uses all the textures generated to place the illumination. Here is where the shadow map is being checked for generate the shadows. EDIT I'll also leave here the shadow map texture definition. glGenTextures(1, amp m shadowMap) glBindTexture(GL TEXTURE 2D, m shadowMap) glTexImage2D(GL TEXTURE 2D, 0, GL DEPTH COMPONENT32, WindowWidth, WindowHeight, 0, GL DEPTH COMPONENT, GL FLOAT, NULL) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE COMPARE MODE, GL NONE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glBindFramebuffer(GL FRAMEBUFFER, m fbo) glFramebufferTexture2D(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL TEXTURE 2D, m shadowMap, 0)


How to spin a 2D quad in place using only matrices? In short, I have a textured 2D quad (a sprite). I would like to rotate spin it about the z axis (coming out of the screen) using nothing but matrices. If I do the following to a transform with scale in it already, the object spins, but also follows a circular path around the origin. As a test, if I first undo the scale, then this works fine (the object spins in place). But I'm not normally keeping scale, orientation and translation separate and then computing the matrix every frame in this case. I'm mutating the matrix all the time. So this isn't workable. Can this be done without first undoing the scale? self is the current transformation matrix (4x4) pivot is the "center" of the quad's AABB (recomputed immediately before this) eulerAngles is a vec3 containing 0.0, 0.0, z angle translate to the origin translate(self, pivot) rotate rotate(self, eulerAngles) go back translate(self, pivot) (I'm using OpenGL, but that probably doesn't matter much here) There are other related articles, but I didn't get to a solution. I'm linking for reference Combining rotation,scaling around a pivot with translation into a matrix How can I rotate about an arbitrary point in 3D (instead of the origin)?


How can I reduce a frustum to the subset that passes through a portal AABB? I'm trying to implement portal based occlusion culling There are sectors and portals. When a portal is visible, the sector it is connected to is rendered. The sector is made of polygons and portals. The sector is sealed by a portal to the next sector. The portal has an axis aligned bounding box. The view frustum has an array of mathematical planes in it. There is top, bottom, left, right, near and far. The view frustum planes change shape when in contact with a wall. When the view frustum planes are in contact with the portal's AABB, the sector get rendered. Then an array of mathematical planes are added behind the portal to create a reduced view frustum. Reduced frustums are made from other portals in contact with the view frustum until there are no more portals in view. How can I perform the bolded step, where I find a new collection of frustum planes representing the portion of the original frustum that continues through the portal's AABB?


FBX Importer Vertex Color I imported vertex positions, indices and normals successfully in OpenGL using fbx sdk, but I just can't figure out how to import vertex colors. I tried to fetch the pointer to array of colors trough mesh layer but it returns null. Can anyone help me with this one please?


Getting the Ray position from View and Projection Matrix I'm having some trouble calculating the direction and position of the ray from my matrices. I have tried some things such as private Vec3 getPick(Mat4 projection, Mat4 view) Mat4 inverseProject projection.copy().inverse() Mat4 pick inverseProject.mul(view.copy()) Vec3 pos new Vec3(pick.m10, pick.m11, pick.m12) return pos I am using custom math classes and I'm pretty sure they work. Also, would it be better to perform this math in my shader? For better performance etc..? I contacted Notch (creator of Minecraft) on this issue and he told me to inverse the view Matrix and multiply by the projection, then multiply by the mouse coordinates. I tried that, it didn't do much. EDIT Tried normalising the screen space. It seems to do the job except in negative directions. Plus its a little off. Vec3 getPick(double w, double h, double ar) double sx ((Mouse.getX() w 2.0) 1.0) ar double sw 1.0 (2 ((h Mouse.getY()) h)) Mat4 viewProjInv view.copy().mul(projection).inverse() Vec3 mouseNormal new Vec3(sx, sw, 1.0) Vec3 dir viewProjInv.mul(mouseNormal) return dir.mul(1)


Font loads with artifacts I've recently come on to an error when loading fonts in my game, some letters show up perfect while others have artifacts around them. Here's an example of this While some letters are perfectly normal, others are being unstable. My options menu This is what my loader method looks like. (Yes i've tried other fonts) private static int loadTexture(BufferedImage image) int BYTES PER PIXEL 4 int pixels new int image.getWidth() image.getHeight() image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()) ByteBuffer buffer BufferUtils.createByteBuffer(image.getWidth() image.getHeight() BYTES PER PIXEL) for(int y 0 y lt image.getHeight() y ) for(int x 0 x lt image.getWidth() x ) int pixel pixels y image.getWidth() x buffer.put((byte) ((pixel gt gt 16) amp 0xFF)) Red component buffer.put((byte) ((pixel gt gt 8) amp 0xFF)) Green component buffer.put((byte) (pixel amp 0xFF)) Blue component buffer.put((byte) ((pixel gt gt 24) amp 0xFF)) Alpha component. Only for RGBA buffer.flip() int textureID glGenTextures() glBindTexture(GL TEXTURE 2D, textureID) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA8, image.getWidth(), image.getHeight(), 0, GL RGBA, GL UNSIGNED BYTE, buffer) return textureID


Beginner question about vertex arrays in OpenGL Is there a special order in which vertices are entered into a vertex array? Currently I'm drawing single textures like this glBindTexture(GL TEXTURE 2D, texName) glVertexPointer(2, GL FLOAT, 0, vertices) glTexCoordPointer(2, GL FLOAT, 0, coordinates) glDrawArrays(GL TRIANGLE STRIP, 0, 4) where vertices has four "xy pairs". This is working fine. As a test I doubled the sizes of the vertices and coordinates arrays and changed the last line above to glDrawArrays(GL TRIANGLE STRIP, 0, 8) since vertices now contains eight "xy pairs". I do see two textures (the second is intentionally offset from the first). However the textures are now distorted. I've tried passing GL TRIANGLES to glDrawArrays instead of GL TRIANGLE STRIP but this doesn't work either. I'm so new to OpenGL that I thought it's best to just ask here ) Cheers!


How to 'point' an arrow in the direction that it's going? I am relatively new to OpenGL and 3D environments and am having trouble creating a rotation matrix that will rotate an arrow model so it 'points' in the direction that it is going. I am using GLM as a math library. My current approach is to predict the position the arrow will be at next frame and try to rotate the arrow to face that position. double nextVelY velocity.y (gravity (((glfwGetTime() dt) clock) 1000.0)) glm vec3 nextVelocity velocity nextVelocity.y pos.y 0.5 gt 3 ? nextVelY velocity.y glm vec3 lookat glm vec3((nextVelocity glm vec3(20) glm vec3(dt))) glm vec3 pos2 glm vec3(0) And then try to calculate angles between the current position and the predicted position model glm translate(model, pos) model glm scale(model, glm vec3(0.05)) float angleX atan(nextVelocity.y nextVelocity.z) float angleY atan(nextVelocity.x nextVelocity.z) float angleZ atan(nextVelocity.x nextVelocity.y) glm vec3 zAxis glm normalize(lookat pos2) glm vec3 xAxis glm normalize(glm cross(up, zAxis)) glm vec3 yAxis glm cross(zAxis, yAxis) model glm rotate(model, angleX, xAxis) model glm rotate(model, angleY, yAxis) model glm rotate(model, angleZ, zAxis) I'm not at all sure if this is a good way to try and achieve this. I've also tried using glm lookAt model glm transpose(glm lookAt(pos2, lookat, glm vec3(0, 1, 0))) and various other methods I've found with no success.


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


OpenGL object load in reverse I am trying to load a model and it is loading it in reverse. When I am trying to rotate it 180 degrees it changes the lightning as well. I am not sure what I need to do to change the position that eh model is facing when is being loaded. This is the object loader if (!submarineShader gt load("BasicView", "glslfiles basicTransformations.vert", "glslfiles basicTransformations.frag")) cout lt lt "failed to load shader" lt lt endl glUseProgram(submarineShader gt handle()) use the shader glEnable(GL TEXTURE 2D) cout lt lt " loading model " lt lt endl if (objLoader.loadModel("submarine submarine v2 submarine5.obj", model)) returns true if the model is loaded, puts the model in the model parameter cout lt lt " model loaded " lt lt endl model.calcVertNormalsUsingOctree() model.initDrawElements() model.initVBO(submarineShader) model.deleteVertexFaceData() else cout lt lt " model failed to load " lt lt endl


shadow mapping and linear depth I'm implementing ominidirectional shadow mapping for point lights. I want to use a linear depth which will be stored in the color textures (cube map). A program will contain two filtering techniques software pcf (because hardware pcf works only with depth textures) and variance shadow mapping. I found two ways of storing linear depth const float linearDepthConstant 1.0 (zFar zNear) first float moment1 viewSpace.z linearDepthConstant float moment2 moment1 moment1 outColor vec2(moment1, moment2) second float moment1 length(viewSpace) linearDepthConstant float moment2 moment1 moment1 outColor vec2(moment1, moment2) What are differences between them ? Are both ways correct ? For the standard shadow mapping with software pcf a shadow test will depend on the linear depth format. What about variance shadow mapping ? I implemented omnidirectional shadow mapping for points light using a non linear depth and hardware pcf. In that case a shadow test looks like this vec3 lightToPixel worldSpacePos worldSpaceLightPos vec3 aPos abs(lightToPixel) float fZ max(aPos.x, max(aPos.y, aPos.z)) vec4 clip pLightProjection vec4(0.0, 0.0, fZ, 1.0) float depth (clip.z clip.w) 0.5 0.5 float shadow texture(ShadowMapCube, vec4(normalize(lightToPixel), depth)) I also implemented standard shadow mapping without pcf which using second format of linear depth (Edit 1 i.e. distance to the light some offset to fix shadow acne) vec3 lightToPixel worldSpacePos worldSpaceLightPos const float linearDepthConstant 1.0 (zFar zNear) float fZ length(lightToPixel) linearDepthConstant float depth texture(ShadowMapCube, normalize(lightToPixel)).x if(depth lt fZ) shadow 0.0 else shadow 1.0 but I have no idea how to do that for the first format of linear depth. Is it possible ? Edit 2 For non linear depth I used glPolygonOffset to fix shadow acne. For linear depth and distance to the light some offset should be add in the shader. I'm trying to implement standard shadow mapping without pcf using a linear depth ( viewSpace.z linearDepthConstant offset) but following shadow test doesn't produce correct results vec3 lightToPixel worldSpacePos worldSpaceLightPos vec3 aPos abs(lightToPixel) float fZ max(aPos.x, max(aPos.y, aPos.z)) vec4 clip pLightProjection vec4(0.0, 0.0, fZ, 1.0) float fDepth (clip.z clip.w) 0.5 0.5 float depth texture(ShadowMapCube, normalize(lightToPixel)).x if(depth lt fDepth) shadow 0.0 else shadow 1.0 How to fix that ?


Can we flip znear and zfar so that positive z values increase away from the viewer? I am confused about the projection matrix in OpenGL. i have a habit of writing the code as follows. glViewport(0,0,w,h) glMatrixMode(GL PROJECTION) glLoadIdentity() if(w lt h) glOrtho(0.0f,250.0f,0.0f,250.0f h w,1.0, 1.0) else glOrtho(0.0f,250.0f w h,0.0f,250.0f,1.0, 1.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() Simple, This code sets the viewing clipping region that maintains the equal width and height. negative z value points away from the viewer. as z value extends from 1 to 1. anything that lies outside this value wont be visible to the user. But i have seen the code like this. glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(left,right,bottom,top,1.0, 500.0) how???? glMatrixMode(GL MODELVIEW) glLoadIdentity() glTranslatef(0.0f, 0.0f, 250.0f) ????? glutSolidSphere(15.0f,15,15) how is this visible on the screen Please help me understand this code. As from my point of view the z value is totally flipped near is 1.0 its okay but zfar is 500 and following that code there is a translation of z value to 250. and drawing that sphere will be visible on the screen how? My question is can we flip znear and zfar so that positive z value will go away from the viewer.


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


OpenGl Error, The loaded object takes the same colors and style of the Texture? I'm new to OpenGl Faced this problem Draw function void Renderer Draw() glUseProgram(programID) shader.UseProgram() mat4 view mat4(mat3(myCamera gt GetViewMatrix())) glm mat4 VP myCamera gt GetProjectionMatrix() myCamera gt GetViewMatrix() shader.BindVPMatrix( amp VP 0 0 ) glm mat4 VP2 myCamera gt GetProjectionMatrix() myCamera gt GetViewMatrix() floorM model13D gt Render( amp shader, scale(100.0f, 100.0f, 100.0f)) scaling the skybox t2 gt Bind() model3D gt Render( amp shader, scale(2.0f, 2.0f, 2.0f)) scaling aircraft glUniformMatrix4fv(VPID, 1, GL FALSE, amp VP2 0 0 ) mySquare gt Draw() The code of loaded shader.LoadProgram() model3D new Model3D() model3D gt LoadFromFile("data models obj Galaxy galaxy.obj", true) model3D gt Initialize() myCamera gt SetPerspectiveProjection(90.0f, 4.0f 3.0f, 0.1f, 10000000.0f) model13D new Model3D() model13D gt LoadFromFile("data models obj skybox Skybox.obj", true) model13D gt Initialize() Projection matrix shader.LoadProgram() View matrix myCamera gt Reset( 0.0f, 0.0f, 5.0f, Camera Position 0.0f, 0.0f, 0.0f, Look at Point 0.0f, 1.0f, 0.0f Up Vector ) std string Images names 6 Images names 0 "right.png" Images names 1 "left.png" Images names 2 "top.png" Images names 3 "bottom.png" Images names 4 "back.png" Images names 5 "front.png" t new Texture(Images names, 0) t2 new Texture("arrakisday dn.tga", 1)


How to implement HUD I'm wondering how one could implement an HUD in LWJGL. I've seen tutorials on this, but they don't seem to work. I know the basic structure goes like this init3d() 3d code init2d() HUD To which, of course, init3d and init2d are the GL Initialization codes. And also, how would you draw the images for the HUD (or should I ask that in a separate question)? If this is too vague, let me know and I'll update the question.


Weird problem with advect program in fluid simulator I implemented 2d fluid simulator. Solver runs entirely on GPU. All works fine... on my work PC. But on home PC I have some awful glitches, and I can t understand how to fix them. Empirically I discovered that problem is localized somewhere in advect program. This is very strange cause at work I have integrated video, and at home NVIDIA GeForce 9800 GT. Here is the GLSL source of advect program (some lines were dropped for clearness) version 130 out vec3 value uniform sampler2D q uniform sampler2D velocity uniform float dt uniform float inverseSize void main() vec2 p gl FragCoord.xy inverseSize vec2 np p dt texture(velocity, p).xy value texture(q, np).xyz And some screenshots. Work PC Home PC


Opengl texture rendered as solid color,why? her is my vertex array and texture coordinate.. float POS 0.5, 0.5, 1.0, 0.5, 0.5, 1.0, 0.5,0.5, 1.0, 0.5,0.5, 1.0 float texCoords 0.0,0.0, 1.0,0.0, 1.0,1.0, 0.0,1.0 here is my texture creation stbi set flip vertically on load(1) openglTexBuff stbi load("lena.jpg", amp w, amp h, amp c,0) glGenTextures(1, amp TexID) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D,TexID) glTexImage2D(GL TEXTURE 2D,0,GL RGB,w,h,GL FALSE,GL RGB,GL UNSIGNED BYTE,openglTexBuff) glGenerateMipmap(GL TEXTURE 2D) glTexParameteri(GL TEXTURE 2D,GL TEXTURE WRAP S,GL REPEAT) glTexParameteri(GL TEXTURE 2D,GL TEXTURE WRAP T,GL REPEAT) glTexParameteri(GL TEXTURE 2D,GL TEXTURE MAG FILTER,GL NEAREST) glTexParameteri(GL TEXTURE 2D,GL TEXTURE MIN FILTER,GL NEAREST) glBindTexture(GL TEXTURE 2D,0) stbi image free(openglTexBuff) ' and these are my shaders shader vertex version 330 core layout(location 0) in vec4 positions layout(location 1) in vec2 texCoords uniform mat4 translation matrix inactive shader variables.. uniform mat4 rotation matrix mat4 model matrix mat4 projection matrix out vec4 pos out vec2 frag TexCoord void main() rotation matrix gl Position rotation matrix translation matrix positions translation matrix operated with POS vector.. pos positions frag TexCoord texCoords translation matrix shader fragment version 330 core layout(location 0) out vec4 color in vec4 pos in vec2 frag TexCoord rag TexCoord uniform float col uniform sampler2D a texture void main() col a texture color texture(a texture,frag TexCoord) when i use (solid)color instead of texture in shader..everything works fine but when i use shader it gives solid color instead of texture..It seems like my whole tex is super zoomed to output single color here is draw call glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) box.shader.setUniformat4x4("translation matrix",translation) box.shader.setUniformat4x4("rotation matrix",rotation arr) box.shader.setUniform1f("col",1.0) glBindTexture(GL TEXTURE 2D,TexID) box.shader.setUniform1i("a texture",0) box.render() box.render void render() vertices.bind() indices.bind() shader.bind() glDrawElements(render As,vertices.getSize(),GL UNSIGNED INT,NULL) vertices.unbind() indices.unbind()


Difference between the terms Material Effect I'm making an effect system right now (I think, because it may be a material system... or both!). The effects system follows the common (e.g. COLLADA, DirectX) effect framework abstraction of Effects have Techniques, Techniques have Passes, Passes have States amp Shader Programs. An effect, according to COLLADA, defines the equations necessary for the visual appearance of geometry and screen space image processing. Keeping with the abstraction, effects contain techniques. Each effect can contain one or many techniques (i.e. ways to generate the effect), each of which describes a different method for rendering that effect. The technique could be relate to quality (e.g. high precision, high LOD, etc.), or in game situation (e.g. night day, power up mode, etc.). Techniques hold a description of the textures, samplers, shaders, parameters, amp passes necessary for rendering this effect using one method. Some algorithms require several passes to render the effect. Pipeline descriptions are broken into an ordered collection of Pass objects. A pass provides a static declaration of all the render states, shaders, amp settings for "one rendering pipeline" (i.e. one pass). Meshes usually contain a series of materials that define the model. According to the COLLADA spec (again), a material instantiates an effect, fills its parameters with values, amp selects a technique. But I see material defined differently in other places, such as just the Lambert, Blinn, Phong "material types shaded surfaces", or as Metal, Plastic, Wood, etc. In game dev forums, people often talk about implementing a "material effect system". Is the material not an instance of an effect? Ergo, if I had effect objects, stored in a collection, amp each effect instance object with there own parameter setting, then there is no need for the concept of a material... Or am I interpreting it wrong? Please help by contributing your interpretations as I want to be clear on a distinction (if any), amp don't want to miss out on the concept of a material if it should be implemented to follow the abstraction of the DirectX FX framework amp COLLADA definitions closely.


What is causing this problem with my object rotation? I'm having an issue here with rotation in OpenGL. Before I changed my rendering function the rotation I had for my object worked fine, but now it seems to be messed up. I changed my rendering function because I wanted to be able to clip the image (render frames of the image), whereas before I was just rendering things on a 1 object, 1 image basis. The rendering is fine, just the rotation to clarify that. Here's my current rendering code void DrawRotateAdv(int x, int y, int width, int height, float sourceX, float sourceY, float imageWidth, float imageHeight, GLuint texture, float angle, bool blendFlag) glTranslatef((GLfloat) x (width 2), (GLfloat) y (height 2), 0.0) glRotatef(angle, 0.0, 0.0, 1.0) if (blendFlag) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glBindTexture(GL TEXTURE 2D, texture) float texscaleX 1.0f (float)(imageWidth width) float texscaleY 1.0f (float)(imageHeight height) sourceX sourceX (float)imageWidth sourceY sourceY (float)imageHeight glBegin(GL QUADS) Top left vertex (corner) glTexCoord2f(sourceX, sourceY) glVertex2i( ( width 2), ( height 2)) Bottom left vertex (corner) glTexCoord2f(sourceX, sourceY texscaleY) glVertex2i( (width 2), ( height 2)) Bottom right vertex (corner) glTexCoord2f(sourceX texscaleX, sourceY texscaleY) glVertex2i( (width 2), (height 2)) Top right vertex (corner) glTexCoord2f( sourceX texscaleX, sourceY) glVertex2i( ( width 2) , (height 2)) glEnd() glLoadIdentity() I think that perhaps my translation is wrong? Unsure though, guess that's a stab in the dark on my part. As for the getting the angle angle atan2((cEnemy gt position.y (float)position.y), cEnemy gt position.x (float)position.x) 3.14159265f 180 But I don't think that's the issue, like I said it worked before hand perfectly. Screenshot of the output


LWJGL loading textures of various types I googled around a bit and nobody seems to have asked this question. I have images in multiple color formats (all of them are PNGs). Most of them are ARGB but my bitmap fonts are gray scale, and I would like them to stay that way. All I want to do is find out what format BufferedImage uses to store my pixel data and then use that information with glTexImage2D. Java, in all its wisdom, seems to be determined to hide that information from me at all costs... I also need to know how BufferedImage aligns its pixel data in both of these formats (glTexImage2D cares). Could someone please tell me how to Determine the pixel format of my BufferedImage. If it is ARGB32, I'm going to have to reorder the bytes and use GL RGBA. If it's grayscale, I will be using GL INTENSITY. Extract the actual bytes from the image. I have seen a few examples on the web that use BufferedImage.getRaster().getDataBuffer(). This is nonsensical. Why are there different types of buffers like DataBufferInt? Because of Java's strong typing, I need DataBufferByte. If this is the only way, could somebody give me specific directions to use the different type of buffers with glTexImage2D? Figure out how the aforementioned image data is aligned. I will use this information with glPixelStorei. In addition, I come from C and C programming. In C this was 100 lines of simple libPNG and GL calls. Should I expect more trouble like this in the future?


Why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix? I'm working on a 2D game engine project, and I want to implement matrices for my transformations. I'm going to use the GLM library. Since my game is only 2D, I figured I only need a 3x3 matrix to combine the translation, rotation and scale operations. However, glm translation is only overloaded to return a 4x4 matrix, and never a 3x3. I thought a translation could be performed by using a 3x3 matrix why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?


JME3 Fragment Shader not compiling Here is the fragment shader code (MyShaders Shader1.frag) void main() gl FragColor vec4(1.0,1.0,1.0,1.0) And the vertex shader code (MyShaders Shader1.vert) void main(void) gl Position vec4(1.0,1.0,1.0,0.0) And the .j3md material code MaterialDef Shader1 MaterialParameters Technique VertexShader GLSL100 GLSL150 MyShaders Shader1.frag FragmentShader GLSL100 GLSL150 MyShaders Shader1.vert The error stack trace is WARNING Bad compile of 1 version 110 2 define FRAGMENT SHADER 1 3 void main(void) 4 5 6 gl Position vec4(1.0,1.0,1.0,0.0) 7 8 May 01, 2018 3 35 57 PM com.jme3.app.LegacyApplication handleError SEVERE Uncaught exception thrown in Thread jME3 Main,5,main com.jme3.renderer.RendererException compile error in ShaderSource name MyShaders Shader1.vert, defines, type Fragment, language GLSL100 ERROR 0 6 Use of undeclared identifier 'gl Position' And here is the code for instantiating the material Material mat new Material(assetManager,"MyShaders Shader1.j3md") I think that the bug is somewhere in me not passing any gl Position parameters into the shader, but how do I do that? I am using JME3 and Java.


Taking cube from camera space to clip space, error in my math? watching Ken Joy's Computer Graphics lectures on youtube. One thing I'm confused about is after he gets the cube from the camera space to clip space, from my calculations the cube doesn't look like that. I expected the cube to look like that pink parallelogram in my picture, if we assume the Z of the front face of the cube to be 4 3 and the back face to be 2 then the Ws come out to be 4 3 and 2 respectively. So can someone explain how after multiplying by the viewing matrix, the cube comes out to look like how Ken has it. Ken's view matrix After view matrix has been applied What I think the side of the cube should look like(the pink parallelogram) after view matrix has been applied my reasoning is, after the perspective divide by W, the blue and green vectors should get truncated to create that pink parallelogram. So I'm struggling to understand this. Thanks in advance.


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


How to save am image of a screen using JOGL Hope this is a better place to ask things like this. I have a 2D scene with some sprites drawn in Swing frame. I need them to be saved as an image. The problem is every tutorial I found seem to be obsolete. I found using glReadPixels and putting result to a BufferedImage should help but all those snippets look stale, API has changed. I'm using JOGL 2.1.5 that is current at the moment. I have a feeling this should be a widely known use case for professionals. Any help would be appreciated! Updated I adopted some stale snippets (please, don't tell me API hasn't changed significantly, there're dozens of movings and renamings) No the problem is I'm getting black screen in png file. It comes from byte buffer being read to with zeros only. public static void main(String args) TestPNGSaver saver new TestPNGSaver() saver.run() private void writeBufferToFile(GLAutoDrawable drawable, File outputFile) int width drawable.getWidth() int height drawable.getHeight() ByteBuffer pixelsRGB Buffers.newDirectByteBuffer(width height 3) GL2 gl drawable.getGL().getGL2() gl.glReadBuffer(GL.GL BACK) gl.glPixelStorei(GL.GL PACK ALIGNMENT, 1) gl.glReadPixels(0, 0, width, height, GL.GL RGB, GL.GL UNSIGNED BYTE, pixelsRGB) int pixels new int width height int firstByte width height 3 int sourceIndex int targetIndex 0 int rowBytesNumber width 3 for (int row 0 row lt height row ) firstByte rowBytesNumber sourceIndex firstByte for (int col 0 col lt width col ) if (pixelsRGB.get(sourceIndex) ! 0) System.out.println(sourceIndex) int iR pixelsRGB.get(sourceIndex ) int iG pixelsRGB.get(sourceIndex ) int iB pixelsRGB.get(sourceIndex ) pixels targetIndex 0xFF000000 ((iR amp 0x000000FF) lt lt 16) ((iG amp 0x000000FF) lt lt 8) (iB amp 0x000000FF) BufferedImage bufferedImage new BufferedImage(width, height, BufferedImage.TYPE INT ARGB) bufferedImage.setRGB(0, 0, width, height, pixels, 0, width) try ImageIO.write(bufferedImage, "PNG", outputFile) catch (Exception e) e.printStackTrace() Override public void display(GLAutoDrawable drawable) GL2 gl drawable.getGL().getGL2() gl.glClear(GL.GL COLOR BUFFER BIT) gl.glBegin(GL.GL TRIANGLES) gl.glColor3f(1, 0, 0) gl.glVertex2f( 1, 1) gl.glColor3f(0, 1, 0) gl.glVertex2f(0, 1) gl.glColor3f(0, 0, 1) gl.glVertex2f(1, 1) gl.glEnd() private void run() GLProfile.initSingleton() GLProfile glp GLProfile.getDefault() GLCapabilities caps new GLCapabilities(glp) final GLCanvas canvas new GLCanvas(caps) canvas.addGLEventListener(this) Frame frame new Frame() frame.setSize(400, 400) frame.add(canvas) frame.setVisible(true) frame.addWindowListener(new WindowAdapter() public void windowClosing(WindowEvent e) writeBufferToFile(canvas, new File(" whatever text.png")) System.exit(0) )


How do I apply skeletal animation from a .x (Direct X) file? Using the .x format to export a model from Blender, I can load a mesh, armature and animation. I have no problems generating the mesh and viewing models in game. Additionally, I have animations and the armature properly loaded into appropriate data structures. My problem is properly applying the animation to the models. I have the framework for applying the models and the code for selecting animations and stepping through frames. From what I understand, the AnimationKeys inside the AnimationSet supplies the transformations to transform the bind pose to the pose in the animated frame. As small example Animation Armature 001 Bone AnimationKey 2 Position 121 number of frames 0 3 0.000000, 0.000000, 0.000000 , 1 3 0.000000, 0.000000, 0.005524 , 2 3 0.000000, 0.000000, 0.022217 , ... AnimationKey 0 Quaternion Rotation 121 0 4 0.707107, 0.707107, 0.000000, 0.000000 , 1 4 0.697332, 0.697332, 0.015710, 0.015710 , 2 4 0.684805, 0.684805, 0.035442, 0.035442 , ... AnimationKey 1 Scale 121 0 3 1.000000, 1.000000, 1.000000 , 1 3 1.000000, 1.000000, 1.000000 , 2 3 1.000000, 1.000000, 1.000000 , ... So, to apply frame 2, I would take the position, rotation and scale from frame 2, create a transformation matrix (call it Transform A) from them and apply that matrix the vertices controlled by Armature 001 Bone at their weights. So I'd stuff TransformA into my shader and transform the vertex. Something like vertexPos vertexPos bones int(bfs BoneIndices.x) bfs BoneWeights.x Where bfs BoneIndices and bfs BoneWeights are values specific to the current vertex. When loading in the mesh vertices, I transform them by the rootTransform and the meshTransform. This ensures they're oriented and scaled correctly for viewing the bind pose. The problem is when I create that transformation matrix (using the position, rotation and scale from the animation), it doesn't properly transform the vertex. There's likely more to it than just using the animation data. I also tried applying the bone transform hierarchies, still no dice. Basically I end up with some twisted models. It should also be noted that I'm working in openGL, so any matrix transposes that might need to be applied should be considered. What data do I need and how do I combine it for applying .x animations to models? I've made some mock ups of what this looks like, in case that's useful. First I wanted to just test the translation, this is a bobbing head, what it looks like in Blender http i.stack.imgur.com NAc4B.gif And what it looks like in game (don't mind the colors) http i.stack.imgur.com nj2du.gif Then for just rotation, the animation was the head rotating 360 degrees around the vertical axis. This is what that looks like in game http i.stack.imgur.com gVyUW.gif Note, there should be no tilt, only rotation like a merry go round. Update I have the translation part of the animation working. But it feels kind of hacky and I don't see how to apply it to the rotation. The translation works by taking these steps Take the position from the animation frame and swap the y and z values Translate the transformation matrix by the altered position Transpose the transformation matrix Apply the transformation matrix to the vertices So that's how it can work, but how is it supposed to work generally for position, scale and rotation?


glDrawElements not acting as expected code Vertices are created by an .obj file. (loading OBJFile.java) I draw a cube perfectly fine with glDrawArrays. (VertexModel.java) created like this new VertexModel(square.getIndexedVertexBuffer()) However, when I try to do the same with glDrawElements i get a distorted cube.. (IndexedVertexModel.java) The IndexedVertexModel is created like this new IndexedVertexModel(square.getVertexBuffer(), square.getVertexIndecies()) The result can be seen here. I've tried to figure out what's wrong, but i really have no idea what causes it to behave this way. The OBJ file I'm using looks like this v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 v 1.00000000000000 1.00000000000000 1.00000000000000 f 1 4 1 2 3 1 4 2 1 f 3 4 3 4 3 3 6 2 3 f 5 4 4 6 3 5 8 2 4 f 7 4 6 8 3 6 2 2 6 f 2 4 7 8 3 7 6 2 7 f 7 4 8 1 3 8 3 2 8 f 1 4 1 4 4 1 3 3 1 f 3 4 3 6 4 3 5 3 3 f 5 4 4 8 4 4 7 3 4 f 7 4 6 2 4 6 1 3 6 f 2 4 7 6 4 7 4 3 7 f 7 4 8 3 4 8 5 3 8


Looking for literature about graphics pipeline optimization I am looking for some books, articles or tutorials about graphics architecture and graphics pipeline optimizations. It shouldn't be too old (2008 or newer) the newer, the better. I have found something in Optimising the Graphics Pipeline, NVIDIA, Koji Ashida too old, Real time rendering, Akenine Moller , OpenGL Bindless Extensions, NVIDIA, Jeff Bolz , Efficient multifragment effects on graphics processing units, Louis Frederic Bavoil and some internet discussions. But there is not too much information and I want to read more. It should contain something about application, driver, memory and shader units communication and data transfers. About vertices and attributes. Also pre and post T amp L cache (if they still exist in nowadays architectures) etc. I don't need anything about textures, frame buffers and rasterization. It can also be about OpenGL (not about DirecX) and optimizing extensions (not old extensions like VBOs, but newer like vertex buffer unified memory).


How do I get GLEW to use my Nvidia GPU instead of an integrated Intel card? I'm new to graphics programming, though not to coding generally. I've been learning opengl from the OpenGL Superbible, 6th Edition. I was trying out the shader examples from the book but couldn't get them to work. The logged error says approximately "incorrect version". The book uses GLSL 4.3 core. I ran glewinfo.exe and the generated text file said that the core OpenGL version on my system was OpenGL 4.0, but it was the stats of my integrated Intel GPU, not my Nvidia GT720m GPU. I'm pretty sure the nvidia gpu supports a higher opengl version. How do I get GLEW to detect the high performance GPU and make calls to the Nvidia drivers instead of the integrated Intel HD GPU? A similar question has been asked there, but it concerned only running the program on the gpu. How do I tell which version of OpenGL the Nvidia GPU supports?


Texture not visible on particles This is the first time I am working with particles (GL POINTS) I am using kinematic equations and controlling their movement in vertex shader. I am following an example given in OpenGL 4.0 Cookbook by David Wolff. I am not able to see the texture which I am loading in the particle. However, I can see the texture if I put it to some other object, say quad. I have increased the size of POINT using glPointSize just so I can see if the texture is really visible. In the image above you can that I am loading and rendering the same texture for quad, but when I use the same texture for particles, I get different results. PS The color which you're seeing for the particles is from the texture itself. If i choose a texture having white color, the same is seen for the particles. Here is a code from my fragment shader. I figured if the texture is being displayed correctly for quad, then the issue may not be with the loading of the texture. if(rendPlane false) vs fragColor vec4(.3f,.3f,0.6f,1.00f) vs fragColor texture(u particlesTex, gl PointCoord) vs fragColor.a vs transp else plane... vs fragColor texture(u particlesTex, vs texCoord)


Does glScissor affect stencil and depth buffer operations? I know glScissor() affects glColorMask() and glDepthMask(), but does it affect the stencil and depth buffers? For example glEnable(GL DEPTH TEST) glEnable(GL SCISSOR TEST) glEnable(GL STENCIL TEST) glScissor(X,Y,W,H) Is this color mask set only for the scissor area? glColorMask(TRUE,TRUE,TRUE,TRUE) Does this stencil function only work within the scissor area? glstencilfunc(GL ALWAYS) Does the stencil function only work within scissor area? glstencilop(GL KEEP,GL KEEP,GL KEEP) Is this depth mask set only for the scissor area? glDepthMask(GL TRUE) Does this depth function only work within the scissor area? glDepthFunc(GL ALWAYS)


How does Windows GDI work compared to DirectX OpenGL? OpenGL and DirectX, if we are talking about graphics, are somehow built into a graphics card and you can access them using appropriate environment and draw some graphics. After reading wiki, I came to a thought that even though GDI doesn't use hardware directly as DirectX OpenGL, it still get its access to a graphics card after some manipulations. What is GDI and how does it work in compare to these two?


Is it ok to use polymorphism as a way of "interfacing" with objects in a scene? I'm designing a class that holds values representing a 3D scene. This includes lights, cameras, meshes, materials, etc. The way how I'm setting it up is that each "thing" has a name. A camera has a name, a light has a name, etc. But they also have an "interface" to access the object via pointer instead of having to name it each time something needs to be changed. For example Light light scene.getLight("light2") light gt setBrightness(2.0f) The problems is what Light is. Ideally, it's "proper C " where it's a pointer directly to the internal object. However, these classes are closely tied to how the scene class works, which makes maintainability a mess. It's seems much easier to just have private implementations that do all the dirty work and only let the user receive pointers to an interface. What I want to do is make Light an interface (struct with virtual functions, no data, no non virtual functions except empty constructor) and implement the internal details as a private class inside the scene class. While this makes it more maintainable, it comes at the cost of using polymorphism where I'm not dealing with more than one implementation. Any thoughts or ideas are helpful.


Some maths about camera in 3D So after finishing a 2d game for my school project, I decided to dive into 3d world by using raylib instead of Unity. Raylib does provide a simple implementation of 3d camera without you doing maths, but instead I want to challenge myself to understand trigonometry in 3d.Here, I am trying to make the camera rotate upside down and left right(like it's orbiting). After implementing the math, it seems like it only works when the target is at Vector3 0.0f, 0.0f, 0.0f position. If the target position gets further and further, the rotation gets weird. Here is the demonstration video that I uploaded to youtube. https www.youtube.com watch?v MpXkhGy60HA amp feature youtu.be And below is my code for math Vector3 cubePosition 0.0f, 0.5f, 0.0f Camera3D camera 0 camera.position 0.0f, 10.0f, 10.0f Camera position camera.target 0.0f, 0.0f, 0.0f Camera looking at point camera.up 0.0f,2.0f, 0.0f Camera up vector (rotation towards target) camera.fovy 45.0f Camera field of view Y float distance 15.0f Set the distance from camera.target to camera.position float verticalAngle 45.0f The Y XZ angle float horizontalAngle 90.0f The X Z angle, y is considered as 0 float horizontalDistance distance cosf(verticalAngle PI 180.0f) Horizontal distance, the magnitude camera.position.x horizontalDistance cosf(horizontalAngle PI 180.0f) Calculate the position of camera.position x based on distance etc.. camera.position.z horizontalDistance sinf(horizontalAngle PI 180.0f) camera.position.y distance sinf(verticalAngle PI 180.0f) Vector3 selectedTarget cubePosition And for the main loop if (IsKeyDown(KEY A)) camera.position.x horizontalDistance cosf(horizontalAngle PI 180.0f) camera.position.z horizontalDistance sinf(horizontalAngle PI 180.0f) horizontalAngle 1.0f else if (IsKeyDown(KEY D)) camera.position.x horizontalDistance cosf(horizontalAngle PI 180.0f) camera.position.z horizontalDistance sinf(horizontalAngle PI 180.0f) horizontalAngle 1.0f else if (IsKeyDown(KEY W) amp amp verticalAngle lt 88.0f) horizontalDistance distance cosf(verticalAngle PI 180.0f) camera.position.x horizontalDistance cosf(horizontalAngle PI 180.0f) camera.position.z horizontalDistance sinf(horizontalAngle PI 180.0f) camera.position.y distance sinf(verticalAngle PI 180.0f) verticalAngle 1.0f else if (IsKeyDown(KEY S) amp amp verticalAngle gt 2.0f) horizontalDistance distance cosf(verticalAngle PI 180.0f) camera.position.x horizontalDistance cosf(horizontalAngle PI 180.0f) camera.position.z horizontalDistance sinf(horizontalAngle PI 180.0f) camera.position.y distance sinf(verticalAngle PI 180.0f) verticalAngle 1.0f if (IsKeyPressed(KEY RIGHT)) camera.position.x 1.0f selectedTarget.x 1.0f else if (IsKeyPressed(KEY LEFT)) camera.position.x 1.0f selectedTarget.x 1.0f if (IsKeyPressed(KEY UP)) camera.position.z 1.0f selectedTarget.z 1.0f else if (IsKeyPressed(KEY DOWN)) camera.position.z 1.0f selectedTarget.z 1.0f if (IsKeyPressed(KEY SPACE)) cubeList.push back(selectedTarget) camera.target selectedTarget Since raylib is using opengl so i tried to use the following link and picture to understand the camera system. https learnopengl.com Getting started Camera This is the picture I used to calculate my camera position. https uploads.disquscdn.com images 58fa1f1a3dd8d736a9345b3b168dd55caf0f14d485e9dae7e06b8e185348a42a.png Any help would be appreciated. Thank you..


Why would OpenGL ignore GL DEPTH TEST setting? I cannot figure out why some of my objects are being rendered on top of each other. I have Depth testing on. glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) Do I need to draw by order of what is closest to the camera? (I thought OpenGL did that for you.) Setup code private void setUpStates() glShadeModel(GL SMOOTH) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glEnable(GL LIGHTING) glEnable(GL LIGHT0) glLightModel(GL LIGHT MODEL AMBIENT, BufferTools.asFlippedFloatBuffer(new float 0, 0f, 0f, 1f )) glLight(GL LIGHT0, GL CONSTANT ATTENUATION,BufferTools.asFlippedFloatBuffer(new float 1, 1, 1, 1 ) ) glEnable(GL COLOR MATERIAL) glColorMaterial(GL FRONT, GL DIFFUSE) glMaterialf(GL FRONT, GL SHININESS, 50f) camera.applyOptimalStates() glEnable(GL CULL FACE) glCullFace(GL BACK) glEnable(GL TEXTURE 2D) glClearColor(0.0f, 0.0f, 0.0f, 0.0f) glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glEnableClientState(GL NORMAL ARRAY) glHint(GL PERSPECTIVE CORRECTION HINT, GL NICEST) Render Code private void render() Clear the pixels on the screen and clear the contents of the depth buffer (3D contents of the scene) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) Reset any translations the camera made last frame update glLoadIdentity() Apply the camera position and orientation to the scene camera.applyTranslations() glLight(GL LIGHT0, GL POSITION, BufferTools.asFlippedFloatBuffer(500f, 100f, 500f, 1)) glPolygonMode(GL FRONT AND BACK, GL LINE) for(ChunkBatch cb InterthreadHolder.getInstance().getBatches()) cb.draw(camera.x(), camera.y(), camera.z()) The draw method in ChunkBatch public void draw(float x, float y, float z) shader.bind() shader.setUniform("cameraPosition", x,y,z) for(ChunkVBO c VBOs) glBindBuffer(GL ARRAY BUFFER, c.vertexid) glVertexPointer(3, GL FLOAT, 0, 0L) glBindBuffer(GL ARRAY BUFFER, c.colorid) glColorPointer(3, GL FLOAT, 0, 0L) glBindBuffer(GL ARRAY BUFFER, c.normalid) glNormalPointer(GL FLOAT, 0, 0L) glDrawArrays(GL QUADS, 0, c.visibleFaces 6) ShaderProgram.unbind()


Do game engines put all interpolation onto the GPU? Is it considered standard to push all the vertices and an interpolation of the next position onto the GPU? Suppose a sector is moving up every game tick at 50 units per second. You could put on the shader something like (good old parametric equation like formulas) pos.x a x1 (1 a) x0 Where you'd calculate a as a uniform and only send this value to the GPU in an uncapped fashion, like so while (true) a percentage of the way between frames in range from 0.0 to 1.0 updateGLUniform(..., a) render() Rest of stuff delay() The other way of doing it was to manually set each entity and sector every single time you loop, but then you might have to update the position of a lot of things every game cycle. Just setting one value seems way more efficient. However, I don't know if there's any downsides to this. Are there any negatives to shoving interpolation off to the GPU to save computation time in the game? Or is there something that I'm missing? What do major games do?


How to create an OpenGL texture using primitives? I'm currently rendering a large proportion of the graphics of my game using custom OpenGL primitive functions (e.g. DrawCircleFilled(), DrawPolygonFilled(), etc) drawing procedurally generated objects (e.g. trees). Typically the core of these functions is a glBegin and glEnd loop, and use GL TRIANGLE FAN, GL LINE LOOP, GL LINES, or GL POLYGON. While this generally works, I'm seeing some performance issues if I have too many objects using these functions on screen at once. For instance, I could render a brick wall by drawing 128 small brick coloured rectangles with an outline. Alternatively I could render a single OpenGL texture with these bricks pre drawn, which takes up more video memory but seems to be less processor intensive. With this in mind, my question is how do I take the output of the primitive functions and store them in an OpenGL texture at runtime? I'm aware of how to do with with an SDL Surface, but I don't have access to the primitive drawing functions in SDL and SDL primitive drawing is very slow (one of the reasons why I switched to raw OpenGL in the first place). Advice appreciated. Thanks, Nathan


Black Area in skybox in opengl Hi I am using opengl and I am having a problem if I go further from the skybox with the camera I get black areas, a smaller radius of the skybox will make the camera too close to the object to stay inside the skybox and increasing it obviously doesn't help. Here is the code for the skybox glEnable(GL TEXTURE 2D) glPushMatrix() qobj gluNewQuadric() glTranslated(50,0,0) glBindTexture(GL TEXTURE 2D, underwater) gluQuadricTexture(qobj,true) gluQuadricNormals(qobj,GL SMOOTH) gluSphere(qobj,100,100,100) glPopMatrix()


How do I render a word in the middle of the screen using FreeType and OpenGL? I'm following this tutorial series on making a simple 2D clone of the classic Breakout game, but its author doesn't mention how to render a whole word or sentence in the middle of the screen. He simply uses hard coded X and Y coordinates that obviously work for his screen, but not for mine (hence why the mere suggestion of using hard coded values for something like this makes my skin crawl). For more details on how he accomplishes the task, see this page of the aforementioned tutorial. My version of his game has two major differences I am rendering the GLFW window in fullscreen mode instead of a 800x600 window. I suspect that even if I were to use a 800x600 window, things still wouldn't look consistent across every device. As such I have made many changes to hard coded values across the entire code base. I'm a perfectionist so even though no one else will probably ever run my game, I'm trying to eliminate the possibility of different results on different resolutions. But to do that has turned out to be a massive undertaking! Here is the code that I'm having particular trouble with void TextRenderer RenderText(string text, GLfloat x, GLfloat y, GLfloat scale, vec3 color) Activate corresponding render state shader.Use() shader.SetVector3f("textColor", color) glActiveTexture(GL TEXTURE0) glBindVertexArray(vao) Iterate through all characters for (auto c text.begin() c ! text.end() c ) auto ch characters c auto xPos x ch.bearing.x scale auto yPos y (characters 'H' .bearing. y ch.bearing.y) scale auto w ch.size.x scale auto h ch.size.y scale Update VBO for each character GLfloat vertices 6 4 xPos, yPos h, 0.0, 1.0 , xPos w, yPos, 1.0, 0.0 , xPos, yPos, 0.0, 0.0 , xPos, yPos h, 0.0, 1.0 , xPos w, yPos h, 1.0, 1.0 , xPos w, yPos, 1.0, 0.0 Render glyph texture over quad glBindTexture(GL TEXTURE 2D, ch.textureID) Update content of VBO memory glBindBuffer(GL ARRAY BUFFER, vbo) glBufferSubData(GL ARRAY BUFFER, 0, sizeof(vertices), vertices) glBindBuffer(GL ARRAY BUFFER, 0) Render quad and advance cursors for next glyph glDrawArrays(GL TRIANGLES, 0, 6) Bitshift by 6 to get value in pixels (1 64th times 2 6 64) x (ch.advance gt gt 6) scale glBindVertexArray(0) glBindTexture(GL TEXTURE 2D, 0) I have tried adding a bool centreX and bool centreY param to the function, as well as another for loop before the main one like this if (centreX centreY) auto textWidth 0.0f auto textHeight 0.0f for (auto c text.begin() c ! text.end() c ) auto ch characters c if (centreX) textWidth (ch.bearing.x scale) (ch.size. x scale) ((ch.advance gt gt 6) scale) if (centreY) textHeight (y (characters 'H' .bearing.y ch.bearing.y) scale) (ch.size.y scale) if (centreX) auto lastCh text.end() 1 textWidth (characters lastCh .advance gt gt 6) scale But for the sentence, font and font size used I'm getting a textWidth value of 1952 while a screenshot of the rendered text is 1143 px wide S Where has my math or understanding of the original code gone wrong? My display is a high DPI one and I have my Windows scaling settings at 200 could either of those things be the culprit? MTIA!


How can I simulate a limited (256) color palette in OpenGL? On Twitter, I found this screenshot of a game in development The image on top seems to be without any color limitation. But the two other pictures at the bottom have a 256 color palette. I want to achieve a similar effect in my game (I am using OpenGL). How can I do so?


How do I better organise rendering in an entity component system? I'm developing an isometric RPG, with 3D characters in 2D level. I was using a standard object orientated programming paradigm, but was faced with a lot of issues. Recently, I learned about entity component systems, and am currently rewriting my engine using this paradigm. I use OpenGL, and have two rendering systems one for drawing in 2D, and one for drawing in 3D. Each system consists of one VBO id, with the appropriate geometry, shader program id, id of texture unit binded to the texture atlas (which accommodates all tilesets or all model textures) and other information like that. The alternate systems provide different logic for drawing in 2D and 3D. When it comes to the components for these systems, I am stuck. Say I have component, defined by the buffer offset from the beginning of VBO buffer and the primitive count that needs to be rendered. Let's pretend that I have two instances of these components. The first instance belongs to the level floor entity, and describes the bunch of quad tiles. The second instance is a character mesh that belongs to the player entity. The first component instance should use the 2D rendering system, and second instance should use the 3D rendering system, but the data structure of these instances are identical. It must be said that I use EntityX and the components gets in the systems, automatically depending on their type. Both systems require position and craphics components, so both systems will take both component instances, and one of these component will be processed improperly, what with a 2D graphics component in a 3D rendering system, and vice versa. I'm thinking about creating the "hollow" components, like sprite and model, which will indicate what graphics components in the entity mean. Since these component will not contain any properties, and would be used only as flags, this solution seems clumsy. How do I better organise rendering in an entity component system?


How do I align the cube in which shadows are computed with the view frustrum? ("View Space aligned frustum") Short and concise Given 8 world space positions that form a cube of arbitrary size, position and orientation and given an arbitrary light direction. How do I compute the View and Projection matrix for a directional light, such that the shadows are computed in exactly and only this cube? Edit Clarification I want to create Shadow Maps, in the way, that Crytek calls "View Space aligned" (http www.crytek.com download Playing 20with 20Real Time 20Shadows.pdf page 54 55), so I want that the cube in which shadows are computed is aligned with the view frustrum. How do I achieve that, when I have already have the 8 world space positions of a cube, around the view frustrum?