_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
1 | Octree Frustrum Culling times came when i had to implement some culling into my engine. I started by reading some stuff and so far so good. I managed to create an octree which can effectivly divide my geometry's vertices (per mesh) into an octree. But here i have some Questions Currently i am using immediate mode to test if the culling works. And it does work, i am recursivly traversing the tree's nodes and testing against the node's bounding box if the frustum intersects with it. Repeat untill leaf is found and render that leaf's geometry (with immediate mode for testing) But now i would like to use VBO VAO's to render the geometry in the leaves and here i see two options 1.Each time the i traverse the tree push the leaves that intersect with the frustrum into a list then get the vertices out of them and construct a VBO and send it to be rendered. 2.Pre build a VBO for each leaf then just rebind for each visible leaf and render. Anyway, which is the better option rebuilding a new vbo each time the frustum changes, or just rebinding multiple vbos (which is also expensive). Also is this even the right approach , maybe i am missing something. bool view Culling(CFrustum amp frusrum, COctree node) if (!node) return false if (frusrum.CubeInFrustum(node gt GetCenter().x, node gt GetCenter().y, node gt GetCenter().z,(node gt GetWidth() 2.0f))) if (node gt IsSubDivided()) view Culling(frusrum, node gt OctreeNodes() TOP LEFT FRONT ) view Culling(frusrum, node gt OctreeNodes() TOP LEFT BACK ) view Culling(frusrum, node gt OctreeNodes() TOP RIGHT BACK ) view Culling(frusrum, node gt OctreeNodes() TOP RIGHT FRONT ) view Culling(frusrum, node gt OctreeNodes() BOTTOM LEFT FRONT ) view Culling(frusrum, node gt OctreeNodes() BOTTOM LEFT BACK ) view Culling(frusrum, node gt OctreeNodes() BOTTOM RIGHT BACK ) view Culling(frusrum, node gt OctreeNodes() BOTTOM RIGHT FRONT ) else use prebuilded vbo here or push these vertices here in a list later build a dynamic vbo from them node gt DrawOctree(node) return true return false |
1 | multiply matrix4x4 with vec4 I'm developing a game and I'd like to make model pos4 calc (that's usual in glsl vertex shader) in cpu instead of doing it in gpu. I'm using LWJGL and for the math impl I use JOML. Anyone know how to multiply a vec4 with a matrix 4x4? It would be nice showing me the JOML code but also the way to mul the mat values with the vec4 values is fine! |
1 | Dynamic VBO update possibly corrupting data? I want to draw a line between two vertices. On a mouseclick the vertex data will change and I want to update the line to use the new values. I am using a VBO for this and it looks like the update process is somehow corrupting the VBO data. The line is not drawing in a direction that I would expect given the values of the vertices. There are four lines in total and I am updating only the last two vertices. The vertex data is initialized as float vertLineBuffer 1.0f,0.0f,0.0f, right 0.0f,1.0f,0.0f, top 0.0f,0.0f,0.0f, center 1.0f,0.0f,0.0f, START 0.0f, 1.0f,0.0f END The init routine public void setLineVBOs(GL4 gl) throws Exception vboLineHandles new int 2 gl.glGenBuffers(2, vboLineHandles, 0) populate the position buffer FloatBuffer fbData Buffers.newDirectFloatBuffer(vertLineBuffer) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) the vertex data gl.glBufferData(GL4.GL ARRAY BUFFER, fbData.capacity() 4, fbData, GL4.GL STATIC DRAW) fbData.clear() don't need this anymore populate the color buffer FloatBuffer fbColor Buffers.newDirectFloatBuffer(vertLineColor) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINECOLOR IDX ) the vertex data gl.glBufferData(GL4.GL ARRAY BUFFER, fbColor.capacity() 4, fbColor, GL4.GL STATIC DRAW) fbColor.clear() don't need this anymore set vertex array index IntBuffer intBuffer BufferUtil.newIntBuffer(1) gl.glGenVertexArrays(1, intBuffer) iLineVao intBuffer.get(0) gl.glBindVertexArray(iLineVao) gl.glEnableVertexAttribArray(VERTICES LINE IDX) gl.glEnableVertexAttribArray(VERTICES LINECOLOR IDX) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) the vertex data Associate Vertex attribute 1 with the last bound VBO gl.glVertexAttribPointer(0,3, GL2ES2.GL FLOAT, false,0,0) color gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINECOLOR IDX ) the vertex data gl.glVertexAttribPointer(1,3, GL2ES2.GL FLOAT, false,0,0) And then I attempt to update the VBO on an event (mouseclick) like this public void updateLine(GL4 gl, float pos) pos contains the new vertex data vertLineBuffer 9 pos 0 vertLineBuffer 10 pos 1 vertLineBuffer 11 pos 2 vertLineBuffer 12 pos 3 vertLineBuffer 13 pos 4 vertLineBuffer 14 pos 5 FloatBuffer fbData Buffers.newDirectFloatBuffer(vertLineBuffer) gl.glBufferSubData(GL4.GL ARRAY BUFFER, 0, fbData.capacity() 4, fbData) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboLineHandles VERTICES LINE IDX ) fbData.clear() The vertex shader version 430 layout (location 0) in vec3 vertexPosition layout (location 1) in vec3 vertexColor out vec3 Color void main(void) Color vertexColor gl Position vec4(vertexPosition, 1.0) The frag shader version 430 in vec3 Color layout (location 0) out vec4 FragColor void main(void) FragColor vec4(Color, 1.0) Does this look right? Can anyone see where this might damage the contents of the VBO? |
1 | Correct Rotation and Translation with a 4x4 matrix I am using a 4x4 matrix to transform verts in a shader. I multiply an identity matrix by a rotation matrix by a translation matrix. I am trying to first rotate the verts and then translate them, however in my result, it appears that the verts are being transformed and then rotated. My matrix looks something like this m00 m01 m02 tx m10 m11 m12 ty m20 m21 m22 tz 1 I am not using OpenGL's fixed function pipeline, I am multiplying matrices on the client side, and uploading the matrix to a GLSL shader. If it helps, I am using my own matrix multiplication code, but I have recreated this problem using matrices on my graphing calculator, so I don't believe my matrix code has errors.. I'll include a visual aid if needed. |
1 | Tessellation won't render I am starting to work with tessellation and have some problems right in the beginning. I try to render a quad made of two triangles with tessellation, but nothing appears on the screen. But as soon as I remove the tessellation shaders and change GL PATCHES to GL TRIANGLESagain, it starts working again, without tessellation obviously. So here is my code to setup the tessellation shaders glPatchParameteri(GL PATCH VERTICES, 3) shaderID glCreateProgram() vertex GraphicsUtilities loadShader("D vert.glsl", GL VERTEX SHADER) glAttachShader(shaderID, vertex) fragment GraphicsUtilities loadShader("D frag.glsl", GL FRAGMENT SHADER) glAttachShader(shaderID, fragment) tcs GraphicsUtilities loadShader("D tcs.glsl", GL TESS CONTROL SHADER) glAttachShader(shaderID, tcs) tes GraphicsUtilities loadShader("D tes.glsl", GL TESS EVALUATION SHADER) glAttachShader(shaderID, tes) glLinkProgram(shaderID) This is the vertex shader version 400 layout(location 0) in vec4 vertPosition layout(location 1) in vec2 vertUV layout(location 2) in vec3 vertNormal void main(void) gl Position vertPosition The TCS version 400 layout (vertices 3) out void main() gl out gl InvocationID .gl Position gl in gl InvocationID .gl Position gl TessLevelOuter 0 3.0 gl TessLevelOuter 1 3.0 gl TessLevelOuter 2 3.0 gl TessLevelInner 0 3.0 And the TES version 400 layout(triangles, equal spacing, cw) in void main() gl Position (gl TessCoord.x gl in 0 .gl Position gl TessCoord.y gl in 1 .gl Position gl TessCoord.z gl in 2 .gl Position) And this is how I draw the quad glPolygonMode( GL FRONT AND BACK, GL LINE ) glUseProgram(shaderID) glBindVertexArray(quad gt getVboID()) glDrawElements(GL PATCHES, 6, GL UNSIGNED INT, (GLvoid )0) glBindVertexArray(0) glUseProgram(0) glPolygonMode( GL FRONT AND BACK, GL FILL ) I tried using in and out variables instead of gl in out, but that doesn't work either. I also tried it without the TCS. I was also using Apitrace to look up any errors, but nothing. The function loadShader() looks for compile errors. So what could cause this problem? I really have no idea how to debug this thing any further. |
1 | OpenGL shader program per shape or model I have a program which imports models from .obj files and then draws them with OpenGL. I have a model which contains many shapes (meshes?). Not every shape has texcoords defined inside .obj file (it looks like 1 1 instead of 1 1 1) and I try to use one shader program which depends on texcoords. What would be the best solution for that problem? Should I use separate programs for shapes that have texcoords and another for shape without texcoords defined? Maybe there is a way to check if some attributes were passed to shader program? This is the gist with .obj, .mtl and shader files, maybe that will help you to understand my problem. |
1 | C from LWJGL to C with OpenGL I've been trying my best on porting my 3D game from Java to C , but to no avail. I use only LWJGL with OpenGL but I cannot find any other library in C that supports as much as LWJGL does for Java. Especially on the math part. For instance. I'm trying to port this TransformationMatrix maker to C . public static Matrix4f createTransformMatrix(Vector3f translation, float rx, float ry, float rz, float scale) Matrix4f newMatrix new Matrix4f() newMatrix.setIdentity() Matrix4f.translate(translation, newMatrix, newMatrix) Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), newMatrix, newMatrix) Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), newMatrix, newMatrix) Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), newMatrix, newMatrix) Matrix4f.scale(new Vector3f(scale,scale,scale), newMatrix, newMatrix) return newMatrix I've tried using Eigen and GLM, but none of them work the same like LWJGL. Now I wouldn't mind this, but the lack of actual 3D tutorials on OpenGL in C is just abysmal. Any tips or help with even converting this piece of code would be greatly appreciated. |
1 | Versions of GL and its device that don't display or required powers of 2 for the sprites From this question aside from identifying possibilities of displaying images that don't needed to require powers of 2, what are the versions of GL that can actually display images even if don't needed the power of 2 size? |
1 | Game (X Plane) boot startup time performance I use X Plane for my question but it also concerns probably every other flight simulator or simulation game in general. When developing a plugin what bothers me most is the startup time of the application to test my plugin functionality so I was wondering how I can improve the startup speed of the simulator. First I removed all additional scenery and reduced the loaded files to a minimum which gave me a startup time of 34 seconds which is quite fast already. To improve the time even further I thought it would make sense to run the whole application from memory and I installed ubuntu 64 bit and created a 2GB tempfs filesystem in memory (ram disk). When starting x plane from this memory file system it still takes 30 seconds. Can anyone explain what the application does during startup which needs so much processing time? I assume that the graphic bitmaps for the object and the environment are compressed on disk and therefore they have to be decompressed in memory first before they can be used in opengl. This would explain the time spent on startup. If it is true that the bitmaps need to be decompressed first would it be possible to improve the time by using multiple cores? If the application is multithreaded and there are four cores would the time be divided by four or does this processing happen on the GPU? Any explanation which helps me to better understand the startup process of a computer game is really appreciated because I'm interested in improving the overall performance of the system and therefore I need a better understanding of the bottlenecks (RAM, CPU, GPU, Disks (SSD Raid), OS, libraries, ...). |
1 | Inter Quake Model IQM render Directx9 I'm trying to render an Inter Quake Model(http lee.fov120.com iqm ) in DirectX9 that I exported from blender. I want to display animations which IQM supports and my model format does not. The model is a cylinder. It loads fine in the iqm sdk opengl viewer but when i try to render it in directx9 using for example(this is just to render the vertices) IDirect3DDevice9 device HRESULT hr S OK for(int i 0 i lt nummeshes i ) iqmmesh amp m meshes 0 hr device gt DrawIndexedPrimitiveUP(D3DPT TRIANGLELIST, 0, 3 m.num triangles, m.num triangles , amp tris m.first triangle ,D3DFMT INDEX32 ,inposition ,sizeof(unsigned int)) It renders like this Incorrect The light grey bit that looks like two triangles in the middle is what is rendered(ignore the other stuff). Whereas it is meant to look like this(using a custom importer which I designed which matches what is displayed in blender) Correct Anyone have any suggestions on what might be going wrong? |
1 | clip space, normalized device coordinate space and window space in OpenGL I am learning OpenGL. Clip space, normalized device coordinate space and window space are confusing. I searched but still don't understand them clearly. So, the question is what are differences between them and how are they converted from one to another? And what coordinate do the built in OpenGL functions (e.g. glBufferData) take as input? |
1 | Everything turning black when pitching down Just a quick questions about something that's occurring in my world. Every time I pitch my camera downward, everything starts turning black, and if I pitch upward, everything sort of intensifies. I'm multiplying my normals by the normal matrix in the shader, and I'm multiplying my lights direction by the model view matrix. If I leave the normal and light dir in world space everything ends up fine. I thought putting them both in view space would not cause those weird things to happen? |
1 | How can i draw a curve in modern Opengl? OpenGl is capable of rendering points, lines, triangles and quads but what if i want to draw a bezier curve? I read online you should use something called GL STRIP, but the solutions were using either legacy Opengl, or they were not explaining well the process. The question is How can i render bezier curves in Modern Opengl? I'm using C . |
1 | A little bit confused on how to set normals in this case I'm learning how to use VBOs and I'm following up on the tutorial at the bottom of this page. So I went ahead and created a structure Vertex to hold vertex data.(coordinates and normals). struct Vertex GLfloat x, y, z GLfloat nx, ny, nz GLfloat r, g, b GLfloat padding 7 For the moment I'm trying to draw a cube.So I created an array with 8 vertices. My question is how do I set the normals? When I used immediate rendering, I would just do a glNormal3f and proceeded to draw the vertices for that face. Now that the normals are defined on a per vertex basis, and a vertex practically belongs to 3 faces, I'm somewhat confused as what I should do here. Have I taken a wrong approach on making that structure, or I am missing something else. I would also like to note that I want to make something more generic, so I don't want it to be limited to just drawing cubes. Thanks. |
1 | How Extract Frustum Planes from Clip Coordinates? I'm having some problems with my Frustum Culling and I want to debug it, so I'm trying to render it's planes, to see exatly the Frustum. But I'm using the Clip Coordinates to do the culling (like OpenGL pipeline do), but I dont know how to render a frustum, in another words, I dont know how to convert a frustum in Clip Coordinates to a "Frustum Mesh". Actually to calculate the frustum I use this function glm vec3 point MVP glm vec4( radius, radius, radius, 1.0f)) leftTopPoint return (point.x gt point.w) amp amp Inside left clipping pane (point.x lt point.w) amp amp Inside right clipping pane (point.y gt point.w) amp amp Inside bottom clipping pane (point.y lt point.w) amp amp Inside top clipping pane (point.z gt point.w) amp amp Inside near clipping pane (point.z lt point.w) Inside far clipping pane Where MVP is a glm mat4 of Projection View Model matrices. This function is activated only when I press the left click of mouse, so I want to render the Frustum and see how it is. Also I dont use a "lookAt" function to rotate the camera, I'm using Quaternions (dont know if that matters). Sorry if it is a bit confusing, it's hard to explain. So I just need a tip or a orientation example of how achive this. Thanks for your attention. |
1 | How to draw textured tile map in opengl I am trying to create a textured hexagonal tile map in opengl. I have the VBO and respective index buffer. Additionally I have a texture atlas for texturing individual tiles. I'm attempting to create a distinct texture for each hex without mixing the textures. I understood that one should use a pair of (U,V) texture coordinates for each vertex. Now if the tile map would not be indexed and have the overlapping vertices, I could just set the texture coordinates for each vertex and get each hex rendering the correct texture. However, with indexing the overlapping vertices are gone and I can only set single pair of texture coordinates for each vertex which results in the textures mixing inside the hexes. Is there a way to texture tiles with indexing or another alternative approach to creating hex maps with different textures? |
1 | Simple GLSL example to render a 2d textured quad? I would really love to add shader support in my game , although i can't seem to find a SIMPLE example on how to setup opengl for using shaders. So i would like to ask Does anyone knows if there are any SIMPLE examples for beginners ? (ie Rendering a simple 2d quad or something like that) |
1 | 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) |
1 | Why is the light following my camera around? I have implemented a simple Phong shader without specular highlights for now (just ambient diffuse components) The problem however, is that the calculations seem to be done in camera space as I move the camera around, the light source seems to move along with it. This is evident by me not being able to see the dark side of the models (Note Image is a gif, if it is not animating, open in a new tab) My light is a point light, that I would like to have fixed somewhere in the world. It has a defined position. To my shader, I also pass in the M, V, P matrices, as well as the normal matrix, which is the inverse transpose of the MV matrix cameraPosition glm vec3(8,8,8) cameraTarget glm vec3(0,0,0) cameraUp glm vec3(0,0,1) glm vec3 cameraDirection glm normalize(cameraPosition cameraTarget) cameraRight glm cross(cameraDirection, cameraUp) view glm lookAt(cameraPosition, cameraTarget, cameraUp) glm mat4 model view view modelMatrix glm mat4 normal matrix glm transpose(glm inverse(model view)) The following is my shader code attribute vec3 vertex position attribute vec3 vertex colour in attribute vec3 vertex normal uniform mat4 model uniform mat4 view uniform mat4 projection uniform mat4 normal matrix uniform vec3 ambient light colour in uniform vec3 light position in varying vec4 fragment colour void main(void) position gl Position projection view model vec4(vertex position, 1.0) ambient colour vec3 ambient colour ambient light colour in vertex colour in diffuse colour vec3 normal normalize(vec3(normal matrix vec4(vertex normal, 0.0))) vec4 pos4 view model vec4(vertex position, 1.0) vec4 lightPos4 vec4(light position in, 1.0) vec3 lightDirection normalize((lightPos4 pos4).xyz) vec3 diffuse colour vertex colour in max(0.0, dot(normal, lightDirection)) fragment colour.rgb ambient colour diffuse colour As far as I understand, the problem is that these lighting calculations are done in Camera space, and hence change when the camera changes position. So, my question is How would I change that to get the light to be at a fixed position, ie do the light calculations in World space |
1 | glGenArrays This functionality is not available Whenever I call glGenVertexArrays(), I get the following exception Exception in thread "main" java.lang.IllegalStateException This functionality is not available. at org.lwjgl.system.Checks.checkFunctionality(Checks.java 36) at org.lwjgl.opengl.GL30.getInstance(GL30.java 651) at org.lwjgl.opengl.GL30.nglGenVertexArrays(GL30.java 3101) at org.lwjgl.opengl.GL30.glGenVertexArrays(GL30.java 3128) at me.package.name.ClassName.methodName(ClassName.java ANY LINE NUMBER) The operating system is OS X Yosemite 10.10.2, Java 7. I think that this problem is OS X specific. Immediate mode drawing does work. I am using LWJGL 3. |
1 | How to create class for storing different types of vertex? I am writing graphics engine for educational pursoses and have some problems. I need to have ability to use different vertex formats (for example position normal uv or position normal uv bones weights). I have different structs for these formats and have a class HardwareBuffer that stores OpenGL vertex and index buffers. The problem is to give this class the ability to work with different types of vertices. There are a way to make this class template and use like this HardwareBuffer lt VertexPosNormUV gt buffer buffer.addVertex(VertexPosNormUV(vector3(1, 1, 1), vector3(1, 0, 0), vector2(1, 0))) But in my engine there is an interface IRenderer that have virtual method drawDataFromHardwaveBuffer. Also there is a class OpenGLRenderer that is inherited from it. And now I can't pass my hardware buffer object to this method because there isn't a way to use template virtual methods. Renderer renderer createRenderer(GraphicsDriver OpenGL3) renderer gt drawDataFromHardwaveBuffer(buffer) can't make this method template I can write functions for every type of vertex but this is not a solution. How can I solve the problem? |
1 | Software and Hardware Rendering From what I understand, the main difference between software rendering and hardware rendering is that in software rendering you use the CPU to determine what to color each pixel, and in hardware rendering you let the GPU take care of calculations and determine how to draw each pixel. However, in the end, isn't an API such as OpenGL still required to do the actual drawing no matter which method you pick? I saw a basic software rendering engine that someone built, and the person said he still used OpenGL to do the actual drawing after using the CPU to do the rendering. So is an API like OpenGL or DirectX still required in the end? And if so, is it true that a computer must at least have an integrated GPU or dedicated GPU to display anything at all? |
1 | How to bind more texture array objects into shader? I can't find information if it is posiible, to bind few texture array objects into shader. Any searches for "array of texture arrays" or "multiple texture arrays" end with how to use texture array object. I'm creating a texture array object in this way glGenTextures(1, amp array texture object A) glBindTexture(GL TEXTURE 2D ARRAY, array texture object A) ... glBindTexture(GL TEXTURE 2D ARRAY, 0) unbind Texture array object is distinguishable by texture width, height and bits per pixel. When I want to load texture with different size I create anoter texture array object glGenTextures(1, amp array texture object B) glBindTexture(GL TEXTURE 2D ARRAY, array texture object B) ... glBindTexture(GL TEXTURE 2D ARRAY, 0) unbind And my question is how to bind array texture object A and array texture object B into shader. (For example I have diffuse map in array texture object A and specular map in array texture object B). For binding function (glBindTexture) first argument target, has only GL TEXTURE 2D ARRAY enum, there is no something like GL TEXTURE 2D ARRAY 0, GL TEXTURE 2D ARRAY 1 etc. End now I'm stuck at this point. Many thanks for any help. |
1 | How to make TMXTiledMap responsive? I've been struggling with Cocos2d x (C ) and finally I got to the point I feel more or less comfortable with that. My game is a 2D car based one, with a straight infinite map where I've finally been able to add some random obstacles. There are only 3 positions the car can be at, and everything is working fine. The point is that I've recently noticed that it is not responsive, and tried to make it responsive by adding a line like these one to the AppDelegate.cpp glview gt setDesignResolutionSize(1024.0, 600.0, kResolutionFixedWidth) I've tried to use kResolutionFixedWidth, kResolutionFixedHeight and all others 5 variables you can put there, but I only got black lines along the screen and every single screen breakdown you can imagine . ' I can figure out I need to resize my TMXTiledMap manually because of the nature of tiles (I did it with Tiled), but I don't know how to face this problem. Note that I'm currently developing for a 1024x600 Android device but I would want to support at least the most common resolutions for both tablets and smartphones. Thanks in advance to anyone who can help me in some way. |
1 | Trying to Rotate terrain I'm new to OpenGL and don't really know how to rotate a terrain. For my graphics class, I have a project I need to do that is making a tire using OpenGL and work that we done in class (my framework is one of the labs that we did that introduced us to heightmaps and terrains). I have this tire tread terrain (see picture) that I made and how I'm going to make the tire is by making lots of these tire terrains and rotate them to make the tire shape. I'm sure there is better ways to accomplish this but my professor recommended I do this. So I was wondering how I can rotate it. The code below is my code for the terrain that is shown in the picture. Thank you in advance for the help! void TerrainScene() glClear(GL DEPTH BUFFER BIT GL COLOR BUFFER BIT) glLoadIdentity() gluLookAt(0,g.moveup,g.movedown, 0,0,0, 0,1,0) gluLookAt(g.movedown 50,8,g.moveup, g.movedown 50, 2,g.moveup 40, 0,1,0) gluLookAt(g.movedown 50,70,g.moveup, g.movedown 50, 2,g.moveup 40, 0,1,0) glLightfv(GL LIGHT0, GL POSITION, g.lightPosition) glColor3f(1.0f, 1.0f, 0.0f) glBegin(GL TRIANGLES) glNormal3f(1.0f, 1.0f, 0.0f) float x 25.0 float z 25.0 float inc 0.2 glColor3f(0.8f, 0.8f, 0.8f) for (int i 0 i lt 256 i ) for (int j 0 j lt 256 j ) float scale 5.0 int tmp1 (int) (img 0 .data (i img 0 .width 3 j 3)) int tmp2 (int) (img 0 .data ((i 1) img 0 .width 3 j 3)) int tmp3 (int) (img 0 .data (i img 0 .width 3 (j 1) 3)) int tmp4 (int) (img 0 .data ((i 1) img 0 .width 3 (j 1) 3)) float e1 10.0 ((float)tmp1 255.0) scale float e2 10.0 ((float)tmp2 255.0) scale float e3 10.0 ((float)tmp3 255.0) scale float e4 10.0 ((float)tmp4 255.0) scale unsigned char rgb 3 getTerrainColor(i,j,1,rgb) glColor3ubv(rgb) Vec v1, v2, v3, norm vecMake(x, e2, z inc, v1) vecMake(x inc, e4, z inc, v2) vecMake(x, e1, z, v3) getTriangleNormal(v1,v2,v3,norm) glNormal3fv(norm) glVertex3f(x, e2, z inc) glVertex3f(x inc, e4, z inc) glVertex3f(x, e1, z) vecMake(x inc, e4, z inc, v1) vecMake(x inc, e3, z, v2) vecMake(x, e1, z, v3) getTriangleNormal(v1,v2,v3,norm) glNormal3fv(norm) glVertex3f(x inc, e4, z inc) glVertex3f(x inc, e3, z) glVertex3f(x, e1, z) x inc x 25.0f z inc glEnd() |
1 | 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? |
1 | Is Orthogonal in LWJGL 2D or 3D? I'm attempting to develop an orthogonal game with lwjgl 3 and OpenGL in Eclipse, but I can't find an answer for rendering objects in 2D or 3D. Are both applicable? And if so what are the advantages of either one? I would also like to rotate my camera if that changes your answer. |
1 | Is there any opengl cel shading tutorial out there (without GLAUX)? I want to implement cel shading into my opengl game. I have only found a nehe tutorial that uses glaux (old as hell). I'm looking into it, but I wanna avoid the pain of learning how to translate those old glaux functions variables. Is there any cel shading tutorial out there that uses glut sdl? http nehe.gamedev.net data lessons lesson.asp?lesson 37 |
1 | Use different values for Depth Test and Depth Write in OpenGL Is there a way to use something similar to PolygonOffset to make a depth test more permissive (move fragment depth towards eye) but still write the original depth value to the depth buffer? The only thing I can come up with is a tricky two pass solution using a stencil buffer, but I'd like to avoid that if possible. Context of my question We have an entity with a particle based smoke plume that is often in front of a semi transparent building. Do to some constraints with batching, the building gets drawn after the smoke plume. Originally the smoke plume particles were rendered with a depth test but no depth write. This caused the building to be drawn on top of the smoke. Turning the depth write on for the smoke particles fixes the building, but now the smoke particles interfere with each other. Ideally, I'd like to find a way for them to stop interfering while still writing to the depth buffer. |
1 | What is the relationship between glVertexAttribPointer index and GLSL location? I've been getting some strange results when trying to implement a normals buffer for the purpose of rendering lighting. It seems to be related to the indexes for glEnableVertexAttribArray, glVertexAttribPointer and the location value in the vertex shader. Take a look at the following code for example gl.glEnableVertexAttribArray(1) gl.glEnableVertexAttribArray(0) bind vertex data why does the index have to be 1? gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboHandles VERTICES IDX ) the vertex data gl.glVertexAttribPointer(1,3,GL4.GL FLOAT, false, 0,0) Select the VBO, GPU memory data, to use for colors why doe the index have to be 0?? gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboHandles COLOR IDX ) gl.glVertexAttribPointer(0, 3, GL4.GL FLOAT, false, 0, 0) bind IBO gl.glBindBuffer(GL4.GL ELEMENT ARRAY BUFFER, vboHandles 2 ) Where do the values for the indexes used in the above functions come from? If I were to switch them and make the color buffer 1 and the vertex buffer 0, nothing renders. It seems logical to me that the vertices should be applied first and then the colors? My confusion is compounded when I try to pass the data to a shader. I thought the location value in the shader program referred to the index in glVertexAttribPointer but that doesn't seem to be the case. In fact it looks like location is being completely ignored (targeting GLSL 430). Have a look at this From the shader layout (location 0) in vec3 vertexPosition layout (location 1) in vec3 vertexNormal The Java code with glEnableVertexAttribArray 0 and 1 enabled all of the cubes render but they are individually lighted ie the shading doesn't propagate over the whole scene, only over each cube. if i rem 1, the scene looks lighted properly. So only 1 vertex array enabled and it still works? gl.glEnableVertexAttribArray(0) gl.glEnableVertexAttribArray(1) gl.glEnableVertexAttribArray(2) gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboHandles VERTICES IDX ) with the index set to 5 (doesn't relate to any other index) the scene still renders... gl.glVertexAttribPointer(5,3,GL4.GL FLOAT, false, 0,0) normals gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboHandles 3 ) gl.glVertexAttribPointer(1, 3, GL4.GL FLOAT, false, 0, 0) Select the VBO, GPU memory data, to use for colors almost strangest of all. If I remove colors the program crashes. I don't even use this buffer.. gl.glBindBuffer(GL4.GL ARRAY BUFFER, vboHandles COLOR IDX ) gl.glVertexAttribPointer(0, 3, GL4.GL FLOAT, false, 0, 0) bind IBO gl.glBindBuffer(GL4.GL ELEMENT ARRAY BUFFER, vboHandles 2 ) There is obviously something fundamental here that I am not understanding. I would think that by setting the glVertexAttribPointer index for the vertices to 5 it would unlink from the shader in variable as its location is 0. I need to know what is going on here especially now that I am implementing lighting. So, what is the relationship between the glVertexAttribPointer index and the shader location value? Also, why does the index have to be certain value (eg 0 for color, 1 for vertex)? |
1 | I would like to know how an OpenGL driver will be implemented to learn opengl internals? I'm learning OpenGL and really like to know how the interaction with the Graphics card will be. I feel understanding how it was implemented in the Graphics driver, will let me know complete internals of the opengl(With this I can know what stages factors influence my decisions regarding performance in opengl). Are there any ways for this path to proceed.Does exploring the 'Mesa lib' will help me in this aspect? Am I in the right path? I posted this question in SOF but it seems here is the right place for this Question. |
1 | OpenGL Make two images blend together I have 2 images that are .png and they mix together, The problem is that one overwrite the other. I know that the draw order matters, but In that case I should redraw the icons 2 times ( there is a lot of them) the black is in fact transparent and drawing a star on top of the other "cuts" a part of the underlying one, In other words, it overwrites with transparency How I see it now How I want to see it My blending code GLES20.glActiveTexture(GLES20.GL TEXTURE0) GLES20.glBindTexture(GLES20.GL TEXTURE 2D, mMarcaDataHandle) GLES20.glEnable(GLES20.GL BLEND) GLES20.glBlendFunc(GLES20.GL SRC ALPHA, GLES20.GL ONE MINUS SRC ALPHA) Matrix.setIdentityM(mModelMatrix, 0) aplicarRotacion() Matrix.translateM(mModelMatrix, 0, marcador.posX, marcador.posY, marcador.posZ) drawMarca() GLES20.glDisable(GLES20.GL BLEND) private void drawMarca() coordinate.drawMarca(mPositionHandle, mNormalHandle, mTextureCoordinateHandle) This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix (which currently contains model view). Matrix.multiplyMM(mMVMatrix, 0, mViewMatrix, 0, mModelMatrix, 0) GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mMVMatrix, 0) Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVMatrix, 0) GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0) GLES20.glDrawArrays(GLES20.GL TRIANGLES, 0, 6) |
1 | Android Opengl Alternate values for gl FragColor I'm writing an Android application that utilizes opengl to perform some changes to the camera output. I've written my code in such a way that I finally figured out what is causing the performance issue. extension GL OES EGL image external require precision mediump float uniform samplerExternalOES sTexture uniform vec4 vColor const int MAX COLORS 6 uniform float vHues MAX COLORS uniform float vOffsets MAX COLORS varying vec2 v CamTexCoordinate float rgb2hue(vec4 c) vec4 K vec4(0.0, 1.0 3.0, 2.0 3.0, 1.0) vec4 p mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)) vec4 q mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)) float d q.x min(q.w, q.y) float e 1.0e 10 return abs(q.z (q.w q.y) (6.0 d e)) bool isInRange(float a1,float a2, float vOffset) if(a2 lt 0.0) return false else if(abs(a1 a2) lt vOffset) return true else if( a1 gt a2) return (1.0 a1 a2) lt vOffset else return (1.0 a1 a2) lt vOffset vec4 getGrey(vec4 c) float grey (c.r c.g c.b) 3.0 return vec4(grey, grey, grey, c.a) void main() vec4 c texture2D(sTexture, v CamTexCoordinate) bool hasColor vHues 0 gt 0.0 float hue rgb2hue(c) vec4 test getGrey(c) for(int i 0 i lt MAX COLORS i ) if(isInRange(hue, vHues i , vOffsets i )) If I uncomment this line the performance gets terrible test c gl FragColor test There is a significant hit to performance (a lot of frames are skipped) when I uncomment the line above. I basically want to use the original color sometimes and a different color depending on some condition. It works but is there a more efficient way to do this? Also, why does this perform so poorly? |
1 | Entity Component System data duplicate I've read some articles about Entity Component System and I like this idea of "entities" having lots of "components" to define them, so I tried to implement it. Here is an simple overview of what i've got so far I've a template class that will hold a list for each component type that exit That allows me to have a collection of components by its type Which is good because in memory components will be contiguous Then I've a component manager that hold all these collections and allows me to retrieve a collection at any time Also, each entity keeps tack of all components it has with a bitset So in the final result, each index of all component containers belongs to an entity I know that this causes a problem than, not all entities have all components, so it causes a waste of space... But for now, I can (saldy) live with it But the real issue for me here is that some components will have same data, and if each entity have a component for that data, this data will be duplicated unnecessary Even worst, it would require OpenGL to have different objects in memory that are exactly equal and having to enable those objects and disable them many times is not desirable at all. I've been scratching my head to figure out a solution for this issue but I can't find any. Could someone give me an advice please? If you've read this far, Thank You! |
1 | Rendering artifacts at a large scale I'm a new to OpenGL or graphics in general. Trying to write a game with realistic scale. I had a perfectly fine rendering of earth at a small scale, but when I try to scale it up to 1 1 I get this artifact. Any ideas what this could be? I suspect it's because I am using floats, but I would rather avoid using doubles in the shader for performance reasons. |
1 | Most efficient way of drawing a lot of cubes OpenGL ES I have to draw a lot of cubes in my OpenGL programme for android. All the cubes have the same size but different colors. I know that calling glDrawArrays is expensive operation so I should call it less as possible. But as I know I have to call it 6 times (one per each side) and since I have more than 500 cubes it's not efficient at all. Does anyone have the idea what to do? Btw, I am using OpenGL ES 1.0. I saw that I can use one big VBO but I don't know how to do that. |
1 | How to process multiple shadow maps in deferred shading I'm attempting to implement shadow mapping in an OpenGL deferred shading system. I know how to handle a single shadow map in the lighting stage, but I want my rendering system to be able to support multiple shadow maps. At present, My lighting shader is capable of supporting up to 128 point and spotlights in a single pass. I'd like to know how to modify the shader to handle an indeterminate number of shadow maps of each type (ortho for directional, cube for pointlights, projection for spotlights). Normally, when I define a sampler in GLSL, i simply use uniform sampler2D shadowMap But I think it would be cumbersome to define up to 256 individual sampler uniforms, if it were even possible (which I am far from convinced about). Is there a way to define an array of samplers which I can iterate through on a 1 1 ratio for each light, and if so, how would I do this? For instance, I know that I can use UBO's to send the data for many lights to the shader, so can I do the same to populate an array of samplers, like so shadowMaps MAX SHADOWMAPS Or uniform sampler2D shadowMaps MAX SHADOWMAPS |
1 | How to properly delete unwanted models I am implementing bullets into my game, and each bullet has a lifetime. Whenever the bullet has existed for a set amount of time or collides with an object, the bullet should be deleted. I implemented the timer properly and whenever the bullet reaches the end of its life, it gets deleted. The problem occurs whenever I shoot another bullet. This instantly causes a crash with the code Exception thrown at 0x044765D7 (nvoglv32.dll) in gravityGame.exe 0xC0000005 Access violation reading location 0x00000000. After some research, I've found that this usually means that I am trying to render something that is a nullptr. My thinking is that I am not deleting the previous bullet properly and this affects the new one. A single bullet object is created on startup, and every new bullet is copied using the following line of code std shared ptr lt Bullet gt bullet std make shared lt Bullet gt ( std dynamic pointer cast lt Bullet gt (modelsLoaded.at(i))) The reason for the dynamic pointer cast is because it is in a vector of its base class that it inherits from. Whenever the bullet needs to get deleted, it is erased from the bullets vector using bullets.erase(bullets.begin() index) and the object it is pointing to should go out of scope, there is nothing else pointing to it. I feel like somehow having that object getting deleted has an adverse effect on the other bullets in the vector, but I do not know how. A new object is created and all the data from the original bullet gets copied over. How could deleting a copy of an object mess with the other copied objects? The functions to create, and render the models are below. Generate Model Function binds id glGenBuffers(1, amp VBO) glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp EBO) glGenTextures(1, amp texture) glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, verticesSizeTexture 8 sizeof(float), verticesTexture, GL STATIC DRAW) position attribute glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )0) glEnableVertexAttribArray(0) color attribute glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(3 sizeof(float))) glEnableVertexAttribArray(1) glBindBuffer(GL ELEMENT ARRAY BUFFER, EBO) glBufferData(GL ELEMENT ARRAY BUFFER, indicesSizeTexture 4, indicesTexture, GL STATIC DRAW) texture glBindTexture(GL TEXTURE 2D, texture) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(6 sizeof(float))) glEnableVertexAttribArray(2) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) Rendering Function unsigned int transformLoc glGetUniformLocation(shader gt ID, quot location quot ) glUniformMatrix4fv(transformLoc, 1, GL FALSE, glm value ptr(trans)) glBindTexture(GL TEXTURE 2D, texture) glBindVertexArray(VAO) glDrawElements(GL TRIANGLES, indicesSizeTexture, GL UNSIGNED INT, 0) glBindVertexArray(0) Destructor glDeleteVertexArrays(1, amp VAO) glDeleteBuffers(1, amp VBO) glDeleteBuffers(1, amp EBO) Update After removing the contents of the destructor, the problem goes away. However, I would like to have some sort of destructor to allow for the proper freeing of memory. |
1 | OpenGL object movement is not smooth and vibrating In my android NDK OpenGL C project, I have a render method which executes every frame on draw event so this is the algorithm void Engine render() deltaTime GetCurrentTime() lastFrame glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) update() renderDepthMaps() renderMeshes() if (skybox ! nullptr) shaders.drawSkyBox(skybox, camera, width, height) lastFrame GetCurrentTime() first I calculate the delta time between the last frame and the current frame, then I update all transformation and view matrices from input then render the scene so the game loop depends on the android draw frames, I have an object which moves over a terrain and a third person camera moves with it and rotates around it, so after the object moves for some distance it begins to flicker forward and backward, the update function for the object is double amp delta engine.getDeltaTime() GLfloat velocity delta movementSpeed glm vec3 t(glm vec3(0, 0, 1) velocity 3.0f) matrix glm translate(matrix, t) glm vec3 f(matrix 2 0 , matrix 2 1 , matrix 2 2 ) f glm normalize(f) velocity 3.0f camera gt translate(f) If it is an interpolation issue I don't know how to make interpolation with using translate matrix to its forward vector. |
1 | Do I have to use vertexArray in opengl GLuint VertexArrayID glGenVertexArrays(1, amp VertexArrayID) glBindVertexArray(VertexArrayID) As you can see from the above code, some tutorials use this before using opengl. But a tutorial that I am following, directly uses glGenBuffers method and it works just fine. Hence I am totally confused what glGenVertexArrays. It is sad that it defines how buffer is used, but noone says in what way. Can you help me understand ? |
1 | How Extract Frustum Planes from Clip Coordinates? I'm having some problems with my Frustum Culling and I want to debug it, so I'm trying to render it's planes, to see exatly the Frustum. But I'm using the Clip Coordinates to do the culling (like OpenGL pipeline do), but I dont know how to render a frustum, in another words, I dont know how to convert a frustum in Clip Coordinates to a "Frustum Mesh". Actually to calculate the frustum I use this function glm vec3 point MVP glm vec4( radius, radius, radius, 1.0f)) leftTopPoint return (point.x gt point.w) amp amp Inside left clipping pane (point.x lt point.w) amp amp Inside right clipping pane (point.y gt point.w) amp amp Inside bottom clipping pane (point.y lt point.w) amp amp Inside top clipping pane (point.z gt point.w) amp amp Inside near clipping pane (point.z lt point.w) Inside far clipping pane Where MVP is a glm mat4 of Projection View Model matrices. This function is activated only when I press the left click of mouse, so I want to render the Frustum and see how it is. Also I dont use a "lookAt" function to rotate the camera, I'm using Quaternions (dont know if that matters). Sorry if it is a bit confusing, it's hard to explain. So I just need a tip or a orientation example of how achive this. Thanks for your attention. |
1 | What are the semantics of glRotate and glTranslate's parameters? I have been trying to play with OpenGL after watching some tutorials and I don't understand how the glTranslatef and glRotatef functions work. I believe a simple picture would help me. I understand that glTranslatef changes the position of the "camera" (but does it change the position in wich the shapes are getting drawn)? However, I don't understand the rotation concept at all. If I do glRotatef(1,0,0,1) it makes my quad spin around. If I just do glRotatef(1,0,0,0) it makes the quad smaller (further away) but if I try to rotate around the X or Y axis, I get a black screen. I don't understand the angle either. Help would be appreciated. |
1 | Java OpenGL Perspective matrix not working I'm trying to render a simple triangle with OpenGL in Java using LWJGL3. Everything is working great, but the projection matrix (perspective) is not working. In C I just used to apply the glm perspective() method which works just great. But in Java, I implemented it myself since there are no libraries like GLM handling it. So here the code for the perspective in Java public mat4 perspective(float fov, float aspectRatio, float zNear, float zFar) mat4 perspective new mat4() float halfTanFov (float) Math.tan(Math.toRadians(fov 2)) float range zNear zFar perspective.m00 1f halfTanFov aspectRatio perspective.m11 1f halfTanFov perspective.m22 (zFar zNear) range perspective.m23 1 perspective.m32 (2f zFar zNear) range return perspective Of course I tested this multiplication and a compared a result with my TI output, and it worked great. Other information, the default constructor for the mat4 class is putting all the values to 0. here is the code public void setZero() m00 0 m01 0 m02 0 m03 0 m10 0 m11 0 m12 0 m13 0 m20 0 m21 0 m22 0 m23 0 m30 0 m31 0 m32 0 m33 0 the viewMatrix() in the other hand is working great. It's a simple implementation of the lookAt() method. So when it's lookAtMatrix modelMatrix position where the position is a vec4 the result is good. But when I try to add the projection matrix for the MVP perspective lookatMatrix model position the result is nothing. Here where I do it in the code public mat4 getViewProjection() mViewProjection MatrixTransform.getInstance().lookAt(mPosition, mPosition.add(mDirection), mUp) return mViewProjection public mat4 getMVP(mat4 model) return mPerspective.mult(getViewProjection()).mult(model) And here is my simple GLSL shader (for the vertex shader ) version 430 layout(location 0) in vec3 position uniform mat4 MVP void main(void) gl Position MVP vec4(position, 1) I tried other implementation of the perspective without success, so I guess my mistake is somewhere else, but sadly enough, I can't figure out where. If someone could help, it'd be great ! thank you. If you other informations, please ask me and I'll post it. EDIT Here is how I put a mat4 into a uniform public void uniform(String variableName, mat4 matrix) int loc glGetUniformLocation(mId, variableName) FloatBuffer buffer BufferUtils.createFloatBuffer(16) matrix.putIntoBuffer(buffer) buffer.flip() glUniformMatrix4(loc, false, buffer) and the method putIntoBuffer() public void putIntoBuffer(FloatBuffer buffer) buffer.put(m00) buffer.put(m01) buffer.put(m02) buffer.put(m03) buffer.put(m10) buffer.put(m11) buffer.put(m12) buffer.put(m13) buffer.put(m20) buffer.put(m21) buffer.put(m22) buffer.put(m23) buffer.put(m30) buffer.put(m31) buffer.put(m32) buffer.put(m33) |
1 | Is it acceptable to buffer no data OpenGL? Correct me if I am wrong, but if you call "glBufferData(...)" upon an existing buffer, it will resize the buffer to whatever data you upload. Does that mean if I call something like glBufferData(GL ARRAY BUFFER, 0, NULL, GL DYNAMIC DRAW) it will keep the buffer in existence, but it will have size and no data? In the description of glBufferData, it says it is acceptable to pass NULL as a data parameter, but it mentions nothing of the size parameter. |
1 | Sprite framework binding multiple textures In an attempt to batch render as many quads (sprites) as possible, I'm instance rendering a single unit sized quad and passing in a buffer of per instance data that includes width height, texture coordinates, color, texture Id, etc. Offline, I have a tool that constructs texture atlases based on any particular sprite animation, so the output is flexible in terms of texture atlas width height, which sprites reference which texture atlas, and so on. The end result is that I may have many texture atlases, and sprites which reference any one of those atlases for their current frame. I need a robust solution that'll allow me to draw these sprites in any order while reducing texture binding as much as possible. After some research there are two options combine multiple 2D textures into a 2D array texture (up to GL MAX ARRAY TEXTURE LAYERS EXT) bind multiple textures in array of samplers (up to MAX TEXTURE IMAGE UNITS) The first solution I believe requires all textures to be the same height width. The second solution seems to have a limitation that requires a constant index to access the array of samplers in the fragment shader. I think I want to go with the second solution, but I'm worried I won't be able to properly write a fragment shader if I have to use a constant index, as I'd be getting the index via per instance data input. Are my above suspicions correct? Is there a known work a round for the second solution? Or is there a better way to do this than what I presented. |
1 | Straightforward guidelines for converting OpenGL to OpenGL ES? Is there a straightforward list of finite steps that I need to follow to convert an OpenGL program into an OpenGL ES that's used on the iPhone and iPad? I'd be using GLKit. I've seen some similar API functions but I gather that triangles have to be presented differently. |
1 | Achieving Retro Resolution with HD I couldn't really find any tips on this (or perhaps I just lack the proper words once again), but I'm thinking about how to get some retro looks (SNES 16 Bit, specifially) using a modern system. Basically, the game still runs with the native resolution, however, vertially and horizontally we're limited to 256x224 (512x448). The colour palette is not an issue nowadays. So I basically came up with this idea and am wondering if it's a smart approach (using OpenGL) Create Orthogonal Projection Matrix with 256 units width and 224 units wide. Use a fragment shader that doesn't do anti aliasing on the textures, so the textures are upscaled to look pixel y. Since I couldn't really find a shader for 2), I also came up with a plan b) Same as 1a) Don't use textures at all, replace pixels with 1x1 coloured quads, convert spritesheets to 3D models made of quads. I think plan a) seems more realistic, however. But I do wonder how other games (Shovel Knight, Freedom Planet) approach a pixel y, retro look that stays true to the systems of 20 years ago. |
1 | LWJGL MouseY Coordinates are flipped So I'm very new to using OpenGL and LWJGL, although I am proficient in Java itself. One of the first things I read in the documentation of the Display class was that it maps the origin to the bottom left as opposed to how most other programs map it to the top left. I was ready to take this into account until I discovered that the OpenGL libraries in LWJGL still map everything to the top left. It would also appear that the two spaces (window coordinates and game OpenGL space) do not correspond to each other. ie. if I set a quads position to 10 x 10 via a mouse click in the lower left corner of the screen, it will move to what looks more like (windowWidth 100, windowHeight 100) or (100,100) using a standard top left origin. I am attempting to write a 2D game using quads to draw my sprites, and I was wondering if there was a way to get the screen and game space to correspond. Any help would be greatly appreciated, Thanks! Peter Just in case it helps, here's how I'm creating a window and initializing OpenGL Display Display.setResizable(true) Display.setDisplayMode(new DisplayMode(WIDTH,HEIGHT)) Display.setVSyncEnabled(VSYNC) Display.setFullscreen(FULLSCREEN) Display.create() OpenGL glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0,Display.getWidth(),Display.getHeight(),0,1, 1) glMatrixMode(GL MODELVIEW) glClearColor(0,0,0,1) glDisable(GL DEPTH TEST) glEnable(GL BLEND) glBlendFunc(GL11.GL SRC ALPHA, GL11.GL ONE MINUS SRC ALPHA) |
1 | Cursor position to a 3D ray using angles I've been stuck for a month trying to get gluUnProject working. After my attempts to use gluUnProject failed (as well as attempts to implement gluUnProject functionality manually) I implemented method to get ray using angles. float RadToDeg 180.0f (float)M PI conversion coefficient to degree float DegToRad 1 RadToDeg conversion coefficient to radians float DeltaX tan(fovy 2 DegToRad) 2 (Width 2 winX) zNear Height float DeltaY tan(fovy 2 DegToRad) 2 (Height 2 winY) zNear Height float AngleX atan(DeltaX zNear) RadToDeg float AngleY atan(DeltaY zNear) RadToDeg float DeltaXY sqrt(DeltaX DeltaX DeltaY DeltaY) float AngleXY atan(DeltaXY zNear) RadToDeg float AxisAngle atan(DeltaX DeltaY) RadToDeg vec3 RotationAxis rotate(Camera gt X, AxisAngle, Camera gt Z) if (DeltaY lt 0) RotationAxis RotationAxis vec3 ray rotate( (Camera gt Z), AngleXY, RotationAxis) getting ray direction ray vec3(ray.x scale, ray.y scale, ray.z scale) scale ray if needed vec3 RayEndPoint Camera gt Position ray The main idea behind my method is to rotate ray pointing perpendicularly from the middle of the screen (like in first person shooters) to position where you clicked. Necessary values are fovy angle (field of view in vertical direction), zNear (distance from Camera to near plane) and Camera Transformation Matrix(Camera X, Camera Y, Camera Z, Camera Position 1st, 2nd, 3rd and 4th columns). Difference between Camera Transformation Matrix and View Matrix here. Besides we need some method rotate(vec3 vector,float angle,vec3 axis) that will rotate any vector at any angle around any arbitrary axis. Explanation how it works will consume too many lines (check photo of my calculations). Q Is any easier or better way to do it? Any information or links welcomed. |
1 | OpenGL light not shining quad I've constructed a scene using OpenGL GLUT with a spot light but I'm getting troubles with light shining some of the walls what is going on and how to solve? |
1 | What are valid ranges of space dimensions used in OpenGL? I want to know what the valid ranges of all the spaces in OpenGL are. Specifically Maximum and Minimum Clip space X, Y, and Z (gl Position) Maximum and Minimum gl FragCoord X, Y, and Z Maximum and Minimum gl FragDepth value |
1 | Fastest visibility calculation towards all possible directions I am searching for your advice. I have a massive voxelized model, like the one in the picture (but with a few million voxels more..). To reduce the total number of the model s triangulations, I can remove the shared faces among the voxels, nevertheless, the triangles will indeed remain MANY. What I need to do is create an index that will hold a boolean list (of visible not visible) information, coming from the following procedure Define a set of points, like the centroids of the 3 yellow voxels in the picture (but, this set might again contain millions of points) and for each point calculate which voxels (except their corresponding containers) can be seen (direct and unblocked line of site) towards ALL directions (something like a global illumination concept). If the ray source (coming from a given point) can reach even at the minimum a target voxel, it means we have a "true" condition for that voxel. For example, if we assume that the ray source point in the picture is the light source, then all voxels in the blue circle are "true" for the specific point. This has nothing to do with game development, so I am sorry if my post should be somewhere else. I just felt I should better ask here, because most of my searches conclude to ray casting, hard shadows, visible surface determination, OpenGL, etc which are quite relevant here. I do not need to see any graphics (or have high fps D), just store the results for future usage into a 3rd simulation process. I get the feeling that if I go with implementing simply geometric calculations this indexing will run for too long (even though this can be parallelized quite easily I believe). Nonetheless, can I take advantage somehow of OpenGL and GPU maybe? Will this boost significantly my task? How should I approach the problem? I am working on an ASUS ROG G752VY. I only have to construct and store this index (which I would not be surprised if it would turn out to be tens of GBytes). The rest of the simulation runs on a cluster continuously. This indexing calculation operation will run more or less only once. I just don't know what execution time to expect (days weeks years) with this amount of ray source points that I am mentioning along with a "brute" check towards all directions and voxels (with or without the use of OpenGL and GPU). Yet, I can predict that the max number of visible voxels every time will be just a few thousand. That, because (sorry for not mentioning it) there is a life termination logic of this ray when the distance of its travel exceeds "x" units ("x" will be much much smaller than the size of the total model). Hence, for a ray further than "x" the searching process should break every time. Thank you so much already for your time!!! |
1 | How do I follow this glsl1.2 lights shadows tutorial? I am following this great tutorial but I have many questions. Let's see if I understand the basic idea. 1. I must create the same number of FBOs that lights (maximum 8). 2. I must create the same number of depth textures (shadow maps) that FBOs. 3. For every FBO I must perform offscreen render (render to texture, drawing the scene from the point of view of each of the lights, maximum 8 times). Is this correct or can I use just a texture with multiple FBOs, or fbo with various textures or how? Assuming you use the idea above, how should the final render of the scene? glUseProgram(programa) glUniformli(shadowM0,4) glActivateTexture(GL TEXTURE4) glBindTexture(GL TEXTURE 2D,depthT0) Draw Escene? glUniformli(shadowM1,5) glActivateTexture(GL TEXTURE5) glBindTexture(GL TEXTURE 2D,depthT1) Draw Escene? glUniformli(shadowM2,6) glActivateTexture(GL TEXTURE6) glBindTexture(GL TEXTURE 2D,depthT2) Draw Escene? ... glUseProgram(0) Is this okay? I think not, because it uses a lot of resources and the scene would have to be drawn up to 7 times. (One per light source and shadow mapping). Well but then how should the render scene with multiple light sources and shadows? |
1 | How to put the camera inside a cube in OpenGL I'm really new to OpenGL and can't seem to figure out how to put the "camera" inside the cube I've created so that I can move in an FPS like style. I tried to use gluLookAt and gluPerspective but I'm clearly missing some steps. What should I do before gluLookAt? Here's the code written so far int rotate Y used to rotate the cube about the Y axis int rotate X used to rotate the cube about the X axis the display function draws the scene and redraws it void display() clear the screen and the z buffer glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() resets the transformations glRotatef(rotate X, 1.0, 0.0, 0.0) glRotatef(rotate Y, 0.0, 1.0, 0.0) Front Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.0, 1.0, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Back Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(1.0, 0.0, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Right Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(1.0, 0.0, 1.0) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Left Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.7, 0.7, 0.0) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glEnd() Upper Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.7, 0.7, 0.3) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() Bottom Face of the cube vertex definition glBegin(GL POLYGON) glColor3f(0.2, 0.2, 0.8) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f( 0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glVertex3f(0.5f, 0.5f, 0.5f) glEnd() glFlush() glutSwapBuffers() send image to the screen int main(int argc, char argv ) initialize GLUT glutInit( amp argc, argv) request double buffering, RGB colors window and a z buffer glutInitDisplayMode(GLUT DOUBLE GLUT RGB GLUT DEPTH) create a window glutInitWindowSize(600, 600) glutInitWindowPosition(100, 100) glutCreateWindow("Space") enable depth glEnable(GL DEPTH TEST) callback functions glutDisplayFunc(display) display redraws the scene glutSpecialFunc(specialKeys) special allows interaction with specialkeys pass control to GLUT for events glutMainLoop() return 0 this line is never reached Feel free to ask more about what I'm trying to achieve if I wasn't clear enough. Thanks for your help. |
1 | Directional lights (not) rotating with camera (opposite problem) I am trying to implement a shader for directional lights correctly, but I am bit confused as to why it works when it shouldn't and vice versa. People usually encounter problem with lights changing direction with camera. This is corrected by multiplying normals with model(view) matrix. But my problem is opposite. When I don't multiply normals with model(view) matrix then it works and when I try to use (supposedly) correct version it is having that "lights rotating with camera" problem. Any ideas? Working vertex shader version 330 layout (location 0) in vec3 position layout (location 1) in vec2 texCoord layout (location 2) in vec3 normal out vec2 texCoord0 out vec3 normal0 uniform mat4 model uniform mat4 view uniform mat4 proj void main() normal0 normal gl Position proj view model vec4(position, 1.0) texCoord0 texCoord Fragment shader version 330 in vec2 texCoord0 in vec3 normal0 out vec4 outColor struct BaseLight vec3 color float intensity struct DirectionalLight BaseLight base vec3 direction uniform vec3 baseColor uniform vec3 ambientLight uniform sampler2D sampler uniform DirectionalLight directionalLight vec4 calcLight(BaseLight base, vec3 direction, vec3 normal) float diffuseFactor dot(normal, direction) vec4 diffuseColor vec4(0,0,0,0) if(diffuseFactor gt 0) diffuseColor vec4(base.color, 1.0) base.intensity diffuseFactor return diffuseColor vec4 calcDirectionalLight(DirectionalLight directionalLight, vec3 normal) return calcLight(directionalLight.base, directionalLight.direction, normal) void main() vec4 totalLight vec4(ambientLight,1) vec3 normal normalize(normal0) totalLight calcDirectionalLight(directionalLight, normal) outColor texture(sampler, texCoord0.xy) vec4(baseColor, 1) totalLight Draw method glBindBuffer(GL ARRAY BUFFER, vbo) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glEnableVertexAttribArray(2) glVertexAttribPointer(0, 3, GL FLOAT, false, Vertex SIZE 4, 0) glVertexAttribPointer(1, 2, GL FLOAT, false, Vertex SIZE 4, (const GLvoid )12) glVertexAttribPointer(2, 3, GL FLOAT, false, Vertex SIZE 4, (const GLvoid )20) glBindBuffer(GL ELEMENT ARRAY BUFFER, ibo) glDrawElements(GL TRIANGLES, size, GL UNSIGNED INT, 0) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) Matices ViewTranslate glm mat4(1.0f) cam gt control(windowHandle, 0.01, 0.3, true, amp ViewTranslate) cam gt updateCamera( amp ViewTranslate) glm mat4 Projection glm perspective(70.0f, 800.0f 600.0f, 0.1f, 10000.0f) glm mat4 view glm lookAt( glm vec3(0, 0, 1), glm vec3(0.0f, 0.0f, 0.0f), glm vec3(0.0f, 1.0f, 0.0f) ) shader gt bind() shader gt setUniform("model", glm value ptr(ViewTranslate)) shader gt setUniform("view", glm value ptr(view)) shader gt setUniform("proj", glm value ptr(Projection)) shader gt setUniform("ambientLight", ambientLight) Not working shader code void main() normal0 (model vec4(normal, 0.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (model view vec4(normal, 0.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (model view vec4(normal, 1.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord or void main() normal0 (transpose(inverse(model view)) vec4(normal, 1.0)).xzy gl Position proj view model vec4(position, 1.0) texCoord0 texCoord ... Any ideas how I should do this correctly? |
1 | What are some good learning resources for OpenGL? I have been using the OpenGL ES on the iPhone for a while now and basically I feel pretty lost outside to the small set of commands I've seen in examples and adopted as my own. I would love to use OpenGL on other platforms and have a good understanding of it. Every time I search for a book I find this HUGE bibles that seem uninteresting and very hard for a beginner. If I had a couple of weekends to spend on learning OpenGL what would be the best way to spend my time (and money)? |
1 | GLFW OpenGL location and size in pixels I'm using GLFW to create a little game. (and by little, I mean small, nonprofit) After a while of puzzling, I found out that this draws a texture (from an image, for instance) to the screen (the syntax is in Go, but the library is the same as the C C version) gl.BindTexture(gl.TEXTURE 2D, tex) gl.Color4f(1, 1, 1, 1) gl.Begin(gl.QUADS) gl.Normal3f(0, 0, 0) gl.TexCoord2f(1, 1) top right gl.Vertex3f(1, 1, 0) gl.TexCoord2f(0, 1) bottom right gl.Vertex3f( 1, 1, 0) location gl.TexCoord2f(0, 0) bottom left gl.Vertex3f( 1, 1, 0) gl.TexCoord2f(1, 0) top left gl.Vertex3f(1, 1, 0) gl.End() This draws the texture perfectly. There is just one downside as my screen is 16 9, the texture also gets rendered displayed as 16 9. But as this is a square image (32 by 32 pixels), how do I get it to draw just those pixels, instead of defining it relative to the screen ratio? (values between 1 and 1) My first assumption was that I can compute what the values should be, by comparing it with the actual screen size, but this feels like it's not the way to go. |
1 | How do I find the 2D direction to a 3D location? I'm writing a 3D space flightsim, and I'm trying to display a 2D arrow on screen that points to the player's selected target. To clarify, the arrow needs to point in the direction that the player has to turn to reach the target. I've tried several approaches but I can't seem to make this work for all cases. My current attempt involves constructing a plane from the player's local X Y, projecting the target position onto it (to make the calculation 2D) then calculating the angle between the player's up and the vector to the projected target position. I can't help but think I'm over thinking this and there must be a better, simpler way. Anyone have any suggestions? UPDATE Based on Sam's answer, I've tried the following code Find the direction to the target, and normalize it kglt Vec3 target dir (target pos ship pos) target dir.normalize() kglt Vec3 v1, v2 v1 ship up.cross(ship dir) v2 ship up.cross(target dir) v1.normalize() v2.normalize() Get the angle of rotation for the arrow float angle kmRadiansToDegrees(atan2(ship up.dot(v1.cross(v2)), v1.dot(v2))) But the returned angle is always around 180.0 (although normally 179.xx). Is there any obvious error somewhere? I'll continue debugging and update if I figure it out! UPDATE2 Nevermind, the bug isn't in this section of code. My bad! |
1 | OpenGL rendering to multiple windows, having 1 main loop for each window I have written a little OpenGL framework in the past year that i would like to extend to support multiple windows in the near future. I have an idea about what I would like to do but I am not sure if that is possible so far. I a nutshell the inner working of my framework is as following A window is created. A render context for that window is created. An application deriving from an interface is created. window.run() is called, passing the application running in the window and the render context used as parameter. sglr W32Window w(nCmdShow) w.create(L"DemoApp", sglr DISPLAY MODE ENUM WINDOWED, sglr Resolution(800, 800)) sglr W32Rendercontext r r.create(w, 4, 0, sglr CONTEXT TYPE ENUM DEBUG) TestApp app return w.run(app, r) The run method on the Win32 implementation looks like following (just some of the code) mRunningApp gt onInit() start message loop while (1) while (PeekMessage( amp msg, NULL, 0, 0, PM REMOVE)) TranslateMessage( amp msg) DispatchMessage( amp msg) if message is WM QUIT, exit loop if (msg.message WM QUIT) break mRunningApp gt onUpdate(mDt) mRenderContext gt setAsCurrent() mRunningApp gt onRender() mRenderContext gt disableAsCurrent() What I would like to do is to create a seperate window, rendercontext and application and start a seperate main loop by calling run() just like with the first window. I already have a seperate rendercontext for each window and know about setting it active before rendering to each window. What possible solutions would exist to do that? Just running each run() method in a seperate threads sound like a kinda naive approach to me. (I admit I already tried it with failure D) |
1 | android game using bullet and libgdx i'm developing a android project for school and i'm currently using libgdx for rendering. It performs quite well, but it lacks a 3d physics library. So i searched and found that Bullet physics engine was ported to android through NDK (c ). Did anyone try to connect this two libs together? I've never used a physics engine library before (i've mainly developed 2d games so i've made one my self) and wanted to ask if any one had any previous experiences with implementing bullet and libgdx? To be more precise i need to simulate a jump and implement physics like wind drag, friction, lift, gravity during the jump. Does bullet calculate the gravity and other forces by it self (if so can i implement other forces easily?) or can i control which element gets updated (mainly re transformed) and when? How does collision detection work (is there some kind of collision world collection)? Can i handle collision detection on my own or does bullet take care of this as well? Thanks for the reply's! |
1 | OpenGL Core 3.2 framebuffer rendering black on Mac OSX I'm trying to get a 2 pass post processing system going in OpenGL in a cross platform manor using FBOs. I'm starting the dev on mac OSX (since in the past I've found it the most finicky to get working of windows linux osx), I have a toggle to toggle between using the FBO(post processing) and not. The shaders are working, but it seems the FBO didn't load the texture unit bound to it. The following is the init code for the FBO and it's texture glGenTextures(1, amp fboimg) glBindTexture(GL TEXTURE 2D,fboimg) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA8, 512, 512, 0, GL RGBA, GL UNSIGNED BYTE, 0) glBindTexture(GL TEXTURE 2D, 0) glGenFramebuffers(1, amp fboHandle) glBindFramebuffer(GL FRAMEBUFFER,fboHandle) glFramebufferTexture2D(GL FRAMEBUFFER,GL COLOR ATTACHMENT0,GL TEXTURE 2D,fboimg,0) GLenum status glCheckFramebufferStatus(GL FRAMEBUFFER) switch(status) case GL FRAMEBUFFER COMPLETE cout lt lt "The fbo is complete n" lt lt endl break case GL FRAMEBUFFER INCOMPLETE ATTACHMENT cout lt lt "GL FRAMEBUFFER INCOMPLETE ATTACHMENT EXT n" lt lt endl break case GL FRAMEBUFFER INCOMPLETE MISSING ATTACHMENT cout lt lt "GL FRAMEBUFFER INCOMPLETE MISSING ATTACHMENT EXT n" lt lt endl break case GL FRAMEBUFFER INCOMPLETE DRAW BUFFER cout lt lt "GL FRAMEBUFFER INCOMPLETE DRAW BUFFER" lt lt endl break case GL FRAMEBUFFER INCOMPLETE READ BUFFER cout lt lt "GL FRAMEBUFFER INCOMPLETE READ BUFFER" lt lt endl break if(status ! GL FRAMEBUFFER COMPLETE) cout lt lt "status ! GL FRAMEBUFFER COMPLETE" lt lt endl GLUtils checkForOpenGLError( FILE , LINE ) else shader and VAO setup for post fboSetup true Here is the render code start rendering to FBO if(postFlag amp amp fboSetup) glBindFramebuffer(GL FRAMEBUFFER, fboHandle) glUseProgram(programHandle) start rendering scene one way or another glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glUniformMatrix4fv(mats.projHandle,1,GL FALSE, glm value ptr(mats.projMatrix)) glUniformMatrix4fv(mats.mvHandle,1,GL FALSE,glm value ptr(mats.modelViewMatrix)) bind to vertex array object glBindVertexArray(vaoHandle) render scene glDrawArrays(GL TRIANGLES, 0, 240 3 ) do post processing if we have it enabled if(postFlag amp amp fboSetup) glFlush() glBindFramebuffer(GL FRAMEBUFFER, 0) glUseProgram(fboProgram) glClear(GL COLOR BUFFER BIT) glBindTexture(GL TEXTURE 2D,fboimg) glUniform1i(glGetUniformLocation(fboProgram,"sampler0"),fboimg) glUniform2f(glGetUniformLocation(fboProgram,"resolution"),512,512) glBindVertexArray(vaoFBO) glDrawArrays(GL TRIANGLES, 0, 6) glBindTexture(GL TEXTURE 2D, 0) Tried everything I can think of or find in a FBO tutorial or have read about. I don't get any errors and it returns as complete. (Also I can't seem to get it glTexImage2d a image of size width and height. says invalid values, and if I try to use GL TEXTURE RECTANGLE it says invalid enum but that's for a different question after I just get it working to begin with ) |
1 | How do I move the camera in 2D LWJGL openGL? I am making a top down rpg game with the LWJGL but I can't figure out how to make the camera follow the player. I've tryed using GLU.gluLookAt() but it seems to be designed for 3D and when I try it with my game everything currently on the screen disappears. I have no idea where the camera gets moved to. Please explain simply how to use GLU.gluLookAt() or a better alternative to move the camera. public class Camera public float x 0 public float y 0 public void moveCamera(float toX, float toY) GLU.gluLookAt(x toX, y toY, 0.0f, 0.0f, 0.0f, 0.0f, 0f, 1f, 0f) |
1 | Practice openGL or learn a specific engine? Possible Duplicate Should I use Game Engines to learn to make 3D games? I am a university student. I want to work in the game industry. Now I am thinking about either practicing my openGL skills or learn a complete new game engine during my time in school. I will do this by developing a smartphone game. I am debating over using just openGL or using a game engine. If I learn a game engine, then if the company I want to work for does not use that game engine, then wouldn't it be a waste of time to learn that game engine now instead of solidifying my openGL skills? So, openGL or game engine? Thanks. |
1 | How to draw a Minecraft like world with Open GL I recently completed the this Open GL tutorial. The tutorial shows how to set up a window and shaders, and teaches you how to draw a single cube in the middle of the screen, which all makes sense to me (I think). I'd like to make just a simple flat world made of cubes like Minecraft, but I have no idea how to turn my single giant cube into a bunch of smaller cubes, or how to get the smaller cubes to be arranged in the proper way. Mostly what doesn't make sense to me is the coordinate system being from 1 to 1 and trying to draw a bunch of cubes in that space. Is there a way to adjust that coordinate space to be more world like, where each unit of coordinate space is roughly equivalent to a meter or something? |
1 | Is it possible to gain performance by omitting vertex normals in the GPU pipe? I am working on a rendering problem where I want to render as many raw triangles to the screen as I can with either OpenGL or DirectX with the absolute fastest performance possible. I wondered about omitting vertex normals completely and only transforming vertex positions during the vertex shader stage. 1) Is this possible? 2) Is it actually going to increase performance or is the "bare metal" of the GPU designed in such a way that trying to omit normals won't gain any more throughput? p.s. Yes, I realize that omitting normals will leave you with the problem of how to shade the triangle during the shader stage, but I could at least render a solid color to the screen (no shading). At this point, all I'm wondering about is how much data I can eliminate from the typical pipeline to increase the pipeline throughput to the absolute maximum. |
1 | 2D Outline shader in GLSL I have a simple prototype with 2D worms like destructible terrain. I use a trivial shader to discard pixels based on a mask. varying vec2 v texCoords uniform sampler2D u texture uniform sampler2D u mask void main() vec4 colour texture2D(u texture, v texCoords) vec4 mask texture2D(u mask, v texCoords) if (mask.a gt 0) discard else gl FragColor colour What would be a good and simple way to add few pixels thick black outlines to the terrain to make the carved parts look better? I've researched something about edge detection algorithms, but my hunch says that such a fullblown thing would be kind of an overkill for this task? I'm not after quality or high performance, but simplicity. Thanks for any ideas. |
1 | Best way of writing pixel manipuliting intensive applications with OpenGL Direct3D Recently I have been making little experiments with engines similar to old Wolfenstein 3D, Doom and Build, engines where the 3D rendering is entirely done in software and therefore you need full access to the screen buffers at pixel level. In the days of DOS and before we had current GPUs it was relatively straightforward to get a surface to plot pixels. You had to devise the fastest way to do your calculations and the fastest way of updating the framebuffer. In fact, it is still possible by using libraries like SDL, which still give you a reasonable speed when you manipulate surfaces at pixel level. So I wonder which would be the best way of dealing with pixel intensive applications like the ones I suggest using current GPUs, by using OpenGL or Direct3D. I understand this sounds absurd, but I have been looking at API documentation and it seems that it is a feature that we have somewhat lost in current hardware. I see suggestions as using glDrawPixels or using pixel shaders, but no solid explanation or theory which can help me to make the right decisions. |
1 | Screen Space Reflections Artifacts problem I'm trying to implement a simple (so far) screen space reflections shader. Below is my code const int numBinarySearchSteps 100 const int maxSteps 400 const float rayStep 0.01 25 const float minRayStep rayStep 2.5 vec3 BinarySearch(vec3 dir, inout vec3 hitCoord, out float dDepth, out int hit) float depth for(int i 0 i lt numBinarySearchSteps i ) vec4 projectedCoord projectionMatrix vec4(hitCoord, 1.0) projectedCoord.xyz projectedCoord.w projectedCoord.xyz projectedCoord.xyz 0.5 0.5 depth texture2D(depthMapTex, projectedCoord.xy).x vec4 viewSpaceDepth inverse(projectionMatrix) vec4(projectedCoord.xy, depth 2.0 1.0, 1.0) viewSpaceDepth.xyz viewSpaceDepth.w dDepth viewSpaceDepth.z hitCoord.z if(dDepth lt 0.0) hitCoord dir dir 0.5 hitCoord dir vec4 projectedCoord projectionMatrix vec4(hitCoord, 1.0) projectedCoord.xyz projectedCoord.w projectedCoord.xyz projectedCoord.xyz 0.5 0.5 hit 1 return vec3(projectedCoord.xy, depth) vec4 RayCast(vec3 dir, inout vec3 hitCoord, out float dDepth, out int hit) dir rayStep float depth vec4 projectedCoord projectionMatrix vec4(hitCoord, 1.0) projectedCoord.xyz projectedCoord.w projectedCoord.xyz projectedCoord.xyz 0.5 0.5 depth texture2D(depthMapTex, projectedCoord.xy).x return vec4(vec3(depth),1.0) for(int i 0 i lt maxSteps i ) hitCoord dir vec4 projectedCoord projectionMatrix vec4(hitCoord, 1.0) projectedCoord.xyz projectedCoord.w projectedCoord.xyz projectedCoord.xyz 0.5 0.5 depth texture2D(depthMapTex, projectedCoord.xy).x float zNear 5.0 float zFar 2000.0 float z n 2.0 depth 1.0 float z e 2.0 zNear zFar (zFar zNear z n (zFar zNear)) vec4 viewSpaceDepth inverse(projectionMatrix) vec4(projectedCoord.xy, depth 2.0 1.0, 1.0) viewSpaceDepth.xyz viewSpaceDepth.w dDepth hitCoord.z z e if(dDepth gt 0.0) if (dDepth gt length(dir)) Inconclusive hit 2 return vec4(0.0) return vec4(BinarySearch(dir, hitCoord, dDepth, hit), 1.0) hit 0 return vec4(0.0, 0.0, 0.0, 0.0) vec3 ssr() Reflection vector vec3 reflected normalize(reflect(normalize(viewSpacePosition), normalize(viewSpaceNormal))) Ray cast vec3 hitPos viewSpacePosition float dDepth int hit 0 no hit, 1 good hit, 2 nonsense hit vec4 coords RayCast(reflected max(minRayStep, viewSpacePosition.z) , hitPos, dDepth, hit) vec3 color if (hit 1) color texture2D(colorMapTex, coords.xy).rgb else color vec3(0.0) return color So far, all it does is just return the color of every pixels purely specular reflection, or black if there is no reflection on the screen or if the reflection ray passes behind an object. My issue is that I get these bizarre artifacts where the pixel gets a color (dDepth length(dir)), even though dDepth is supposed to be way larger than length(dir). I've been stuck on debugging this for ages now and I'm wondering if anyone can see the mistake? This is the scene using just a simple shader (to the right), and the scene running only the SSR shader (on the left) Extremely thankful for any help!!! Simon |
1 | Mesh manipulation on GPU vs CPU Just a bit curious where do you perform mesh manipulations, on the CPU or in the shader? I've been doing everything on the CPU and a friend suggested moving things on to the GPU side. If you're doing things like bone animations... on the GPU, how do you get back the mesh? (since I'm doing collision detection...) |
1 | Order of render with transparency opengl I tried to render using different render configurations (GL BLEND FUNC()) but I couldn't get the back object to render in certain angles. The first screenshot here shows one angle where the back object is not visible through the front one. In th second screenshot, I looked at the blocks from 180 degrees. Is there a way I could render them through? Or would I have to implement a sorting algorithm? |
1 | Indirect indexing (uv coords read from texture) In the vertex shader, I need to make a texture fetch, where the texture coordinate itself is read from some other texture. vec2 uv texture(someTexture,coords).xy vec4 val texture(otherTexture,uv).xyzw As far as I know, the second sample has undefined results, because the value of uv is outside of uniform flow control. Is there any way to efficiently (i.e., not copy back the contents of the texture and upload it as a uniform to the shader or something) do what I want to do? |
1 | Simplst possible TBN Matrix giving weird results I'm implementing normal mapping and was trying different techniques of doing that. All seemed not to give me a correct result (e.g. the normals point in weird directions). To find the problem, I broke everything down to the simplest possible solution, but I cant find the problem. Here is a picture of my scene outputting only the world space normals And here is the scene outputting the transformed normals with the normal map As you can see, the normals are not pointed the way they should be (green should be to the right, for example). Here is the way I caluclate the TBN Matrix (I know, its not the correct way of doing that, but I tried the "correct" ways too). vec3 tangent cross(worldspaceNormal, vec3(0,0,1)) vec3 biTangent cross(tangent, worldspaceNormal) mat3 tbn mat3(tangent, biTangent, worldspaceNormal) vec3 map texture(normal, texCoord).rgb map 2 map vec3(1) outNormal vec4(tbn map, 0.0) The worldspaceNormal is just the normal of the surface multiplied by the model matrix, with w component 0.0, of course. |
1 | Depth to World Space Position problem I am having a problem with turning depth to world space position. I am using GLSL. What could go wrong? Here is the code float x (uv.x 2.0) 1.0 float y (uv.y 2.0) 1.0 float z (depth 2.0) 1.0 vec4 pos clip vec4(x, y, z 1.0) vec4 inverse pos view InvCamProjMatrix pos clip inverse pos view.xyz inverse pos view.w vec4 pos ws InvCamViewMatrix inverse pos view return pos ws.xyz Thanks. |
1 | How to implement OpenGL triple buffering of buffer objects to avoid stalls? I'm trying to implement the triple buffering described here. The intent is to gain higher frame rate by avoiding waiting for glBufferSubData() to finish. My understanding is that this is how to implement triple buffer make 3 buffers with glGenBuffers() Current frame bind to buffer3 draw last frame bind to buffer1 glBufferSubData for all the vertices, keep track of their texture vertex count,blend function, etc Next frame bind to buffer 1 draw last frame (bind texture, blend func, glDrawArrays) and so on There doesn't seem to be any performance gain between this and doing glBufferSubData() and then immediately calling glDrawArrays(). Am I missing something or misunderstand how triple buffer should work? Also is there a way to know when glDrawArrays() stalls due to glBufferSubData() still not being finished? |
1 | Opengl shader questions I'm currently building a shader that takes a 2D texture sampler and uses UV coordinates to map it. This works fine for all textured objects. However, I'm having a bit of a problem as I'm trying to render a Mesh with no texture and the shader objects just keeps sampling based on the parameters of the last object I rendered. What is a good way to make sure whenever no texture is available it will just treat it as a white texture or something? One thing I've thought of was creating and binding a white 1x1 texture but that seems overkill. Related question I've been wondering about this and I've yet to find an answer Is it best to make a multi purpose shader or constantly change the shader program for different objects in the same render update? For instance, should I have just created a shader for non textured objects? |
1 | 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? |
1 | How to draw lines round selected objects and lights? I need two things to draw in Modern OpenGL. Please see the image Draw lines to represent light's position and direction Draw xyz axises at the origin of a selected objects How do I draw these? should I use fragment shader or what? |
1 | Reduce texture switches in UI I'm working on game which uses LibGDX's Stage2d for GUI. All textures for UI are packed into one texture atlas. Fonts (BitmapFont) are generated in runtime by gdx freetype for different locales and font sizes (at least 6 locales and 4 font sizes for each locale) and then placed into separate texture. Game UI contains much different elements (strategy game with lots of numbers) buttons, icons, text labels, which usually alternate between each other and trigger many texture switches when drawn. I wonder if there's any way to reduce the number of texture switches as it sometimes takes up to 5ms per frame for stage.draw(). The only way I see is to draw fonts only when all UI textures are drawn, when it is possible, but it will produce awful code and will harm the hierarchy of elements in stage. I didn't merge textures (but thought of it), because Textures use different filtering (MipMapLinearNearest for UI textures, Linear for fonts) and it will require manual texture filtering switches or mess with stage2d overriden Label class. UI texture already has a size of 2048x2048px, and I can't add all font size textures to it as it will require higher texture sizes, which are not supported by many old devices. Is there any good way of solving this issue? |
1 | Projecting onto different size screens by cropping I am building a phone application which will display a shape on screen. The shape should look the same on different screen sizes. I Decided the best way to do this is to show more of the background on larger screen keeping the shapes proportion the same on all screens. My problem is I am not sure how to achieve this, I can query the screen size at runtime and calculate how different it is from the six is designed for but I am not sure what to do with this value. What kind of projection should I use for my orthographic matrix an hour will I display more on larger screens and not loose information on smaller screens? |
1 | How to rotate a sprite in 2D with LWJGL3 and GLSL I have all the basic rendering already set up, with translation, scaling etc. What matrix(s) and or vector(s) do I need to multiply add with my existing code to rotate an object. Preferably around a point given by a vector2fa, also only in degrees because quaternions aren't implemented and its only 2D not 3D. Snippet of the vertex shader gl Position transformation vec4(position, 1.0) translation Where transformation is done in java as (Note not actual code as is replaced with .mul()) Matrix4f transformation ortho scale And translation is given by a method Vector4f translation new Vector4f(x , y , 0f, 0f).mul(gc.getOrtho()) All the code listed before works as expected. It is just lacking the rotation feature mentioned at the top. How can I add rotation to my code? |
1 | Binding and unbinding, what would you do? Let's assume the following example creation glBindVertexArray(vao) glBindBuffer(GL ARRAY BUFFER, vbo) glBindBuffer(GL ELEMENT ARRAY BUFFER, indices) Filling up buffers glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) Unbinding vertex array This looks great from a code beauty perspective. Each bind unbind pair is like parenthesis, so () (I am also actually using these indentions) But it also results in a more code for rendering, because the buffers are unbound in the vao, they need to be rebound during rendering, which kind of defeats the purpose of a vao which represents a certain state you can just use whenever you need to. Rendering would need to look like glBindVertexArray(vao) glBindBuffer(GL ARRAY BUFFER, vbo) glBindBuffer(GL ELEMENT ARRAY BUFFER, indices) Do your drawing glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) so it would be better to glBindVertexArray(vao) glBindBuffer(GL ARRAY BUFFER, vbo) glBindBuffer(GL ELEMENT ARRAY BUFFER, indices) Filling up buffers glBindVertexArray(0) Unbinding vertex array glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) glBindBuffer(GL ARRAY BUFFER, 0) Just to make sure the buffers are not bound for another write or anything. Code wise this looks kind of ugly. But rendering then is just glBindVertexArray(vao) Do your drawing glBindVertexArray(0) Regarding the cost, the second one uses less (un)bindings, but also it could happen that the vao is already unbound (during rendering) but the vbo and element buffer is not, so one could write messy data in there. Am I missing something? Which way is more error prone? Are the costs for un binding neglect able and is the beauty of code worth it? |
1 | Why is it Important to have render targets with the same bit size? I am currently thinking of what type of GBuffer I'll need for deferred shading, hence I tried also to document myself online about the most common ones and their format. Most of the GBuffer that I've seen used the same bit size for each render target, leading also often to unused channels. However, as first guess for my GBuffer, on paper, I need two 24 bit targets and two 32 ones or three 24 and one 32. I understand that having the same "size" each attachment can be aligned better, but practically speaking is it better to waste channels (or reserve them for future use) and having all the RTs of the same size or I should use just what needed? In the former case, why it is such advantage, will the 24 bit ones be padded to 32 anyway? |
1 | OpenGL 3.3 Core Compatibility with OpenGL 4.x Are all OpenGL calls in 3.3 Core and GLSL 330 core shaders valid and functionally equivalent in OpenGL 4.0 through 4.5 core? I can't seem to find a clear and definitive answer both in specification and the real world, is code written for 3.3 core going to function in a 4.5 core context? I've currently kept all of my OpenGL renderer code strictly to 3.3 core profile, but I'd like to take advantage of some features that are only available in 4.0 and 4.4 if the user's environment supports those contexts. The change logs of OpenGL seem fairly simple and it doesn't look like anything in 3.3 core has been deprecated in 4. Are there new requirements OpenGL 4.0 or 4.4 that makes 3.3 core code used in conjunction with new features like tessellation shaders incompatible? |
1 | OpenGL Camera causes spatial distortion I'm trying to implement a 3D camera of the "Orbit around the origin" variety in a game engine I'm developing in order to learn about 3D graphics and game programming. I have a basic handle on the required math, and have implemented my own crude 3D math library and matrix stack (functionally similar to the one in OpenGL's compatibility profile). My first attempts at a camera failed miserably, until I decided that I should use quaternions to represent rotation. Once I'd done that, I had a camera that moved in the direction I expected it to at about the right speed and fairly smoothly, but there is an odd spatial distortion effect that I can't seem to get rid of. I have posted a brief video on YouTube showing exactly what is happening. I honestly don't know what could be causing this issue, the magnitude of the distortion appears to reach a maximum at certain angles, but beyond that I'm not sure what I should be looking at. Right now my chief suspect is my quaternion math code, because the matrix stack appears to be behaving itself and if something was wrong with my matrix math code I would be having more serious issues than this. I'm not sure what information or code I can provide that would be of any use, so I'll start with the code that handles quaternion math. public class Quaternion private float w private float x private float y private float z public Quaternion() this(1.0f,0.0f,0.0f,0.0f) public Quaternion(float W, float X, float Y, float Z) w W x X y Y z Z public void loadIdentity() w 1.0f x 0.0f y 0.0f z 0.0f public float magnitude() AKA the "norm" return (float) Math.sqrt(w w x x y y z z) public void qNormalize() float mag this.magnitude() w mag x mag y mag z mag public void qMultiply(Quaternion q) this.qMultiply(q.w, q.x, q.y, q.z) private void qMultiply(float w2, float x2, float y2, float z2) Performs A B, where this Quaternion is A this.w w w2 x x2 y y2 z z2 this.x w x2 x w2 y z2 z y2 this.y w y2 y w2 z x2 x z2 this.z w z2 z w2 x y2 y x2 public float qMatrix() Return a 4x4 matrix representation of this Quaternion, column major like OpenGL prefers float w2 w w float x2 x x float y2 y y float z2 z z if(Math.abs(w2 x2 y2 z2 1.0) gt 0.000001) this.qNormalize() return this.qMatrix() return new float 1.0f 2.0f y2 2.0f z2, 2.0f x y 2.0f w z, 2.0f x z 2.0f w y, 0.0f, 2.0f x y 2.0f w z, 1.0f 2.0f x2 2.0f z2, 2.0f y z 2.0f w x,0.0f, 2.0f x z 2.0f w y, 2.0f y z 2.0f w x, 1.0f 2.0f x2 2.0f y2,0.0f, 0.0f,0.0f,0.0f,1.0f public void qFromAA(float angle, float axis) create a Quaternion from an axis angle representation if(Vector.magnitude(axis) 0.0f) this.loadIdentity() return float theta angle 2.0f axis Vector.scale((float)Math.sin(theta), Vector.normalize(axis)) w (float)Math.cos(theta) x axis 0 y axis 1 z axis 2 public String toString() return "w " w " tx " x " ty " y " tz " z " tmag " (x x y y z z w w) Any ideas about where I should start? |
1 | opengl texture clamping not working I'm having a problem with post processing in my deferred renderer. When I'm applying an effect like bloom on top of my scene, the bottom of the bloom effect texture leaks into the top of my screen, the top of the texture leaks into the bottom of the screen, the left into the right of the screen and so on. Looks like the uv coords don't get clamped correctly, although I thought I'd have set that all correctly. The bloom effect in this case is created in a lower resolution and the gets upsampled using linear filtering. This image shows the problem I render the postprocessing effects using a simple quad glm vec3( 1.f, 1.f, 0.f), glm vec3(1.f, 1.f, 0.f), glm vec3(1.f, 1.f, 0.f), glm vec3( 1.f, 1.f, 0.f) This is the vertex shader I use to render the quad version 430 core layout(location 0) in vec3 POSITION noperspective out vec2 tex coord void main(void) tex coord POSITION.xy 0.5 0.5 gl Position vec4(POSITION.xy, 0.0, 1.0) And of course in the fragment shader I'm doing something like this version 430 core uniform sampler2D uTexture noperspective in vec2 tex coord out vec4 frag color void main(void) frag color texture(uTexture, tex coord) The effect got rendered into a frame buffer object which got set up like this glGenFramebuffers(1, amp filterFbo) glBindFramebuffer(GL FRAMEBUFFER, filterFbo) filter texture glGenTextures(1, amp filterTexture) glBindTexture(GL TEXTURE 2D, filterTexture) glTexImage2D(GL TEXTURE 2D, 0, GL RGB16F, effectWidth, effectHeight, 0, GL RGB, 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 ARRAY, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, filterTexture, 0) I really don't know what's the problem here, I hope anyone got an idea. Thanks in advance |
1 | .md5mesh normals are not smooth I'm currently working on a project that requires me to load .md5mesh format and draw it. Following this link I've managed to load the mesh into the engine successfully, but a problem arises when calculating normals they just don't seem to smooth. To clarify that it was not my rendering or shader code that was the problem, I loaded a model of .OBJ format, and that lights smoothly. The mesh is calculated correctly too, as I am able to load in complex models with multiple joints and mesh parts. Here's a screenshot of the lighting. And here is how I currently calculate the normals (All normals are set to zero before computing) EDIT Amended the psuedo code to be more accurate to what I have. The original may have been confusing. for (unsigned int i 0 i lt NumberOfTriangles i ) Math3 vec3 r, s, result Math3 vec3 p1, p2, p3 p1 Triangle i .Vertex 0 p2 Triangle i .Vertex 1 p3 Triangle i .Vertex 2 r p2 p1 s p3 p1 result Math3 Cross(s, r) Add the triangles face normal to each vertex The Vertex's are not local to the triangles. Triangle i .Vertex j is just an index. Vertex Triangle i .Vertex 0 .normal result Vertex Triangle i .Vertex 1 .normal result Vertex Triangle i .Vertex 2 .normal result After the loop I normalise each vertex normal to find the average normal. EDIT Here is how I find the average normal for (unsigned int i 0 i lt NumberOfVerts i ) float nx Vertex i .normal.x float ny Vertex i .normal.y float nz Vertex i .normal.z float len sqrt(nx nx ny ny nz nz) Vertex i .normal.x len Vertex i .normal.y len Vertex i .normal.z len As you can see in the image the .md5mesh model is shading flat instead of shading smoothly like the .OBJ model. So what am I missing? |
1 | handling buffers in OpenGL I'm reading through the OpenGL documentation for version 3.3 core. I'm having issues understanding proper buffer deletion. At the moment I have an object that loads itself into OpenGL memory in the constructor and only exposes a VAO with the attribute pointers and a bound element array ready for rendering. When it stops existing it deletes all the buffers and sets pointers to NULL. How do I properly delete OpenGL data? I'm going to assume that the object doesn't stop existing while it's being rendered. Do I have to do something more than just delete the VAO and then delete the buffer objects? Does that leave anything out? Should I bind the VAO disable the attributes, unbind it and then delete it? |
1 | How can I position framebuffer objects on the screen in OpenGL? I currently have two framebuffers which are drawn using glBlitFramebuffer(0, 0, 1920, 1080, 0, 0, 1920, 1080, GL COLOR BUFFER BIT, GL NEAREST) But the texture does not take up the whole screen, and I would like to position it at a certain x,y on the screen. The images by default start from 0,0 and then span the width height provided, however I would like the image to start at say, 100, 100 and span the width height provided. How would I do this? |
1 | Animate multiple entities I'm trying to animate multiple(3) entities using one model(IQM format). It's working but performance is really bad because I'm calling animate function for each entity in my game loop (I think problem is there). What's the best way to animate multiple entities (with different animation ofc) in OpenGL? I think I can try build one VBO entity for better performances but I don't think it's the best way to do it. |
1 | Do I need to "use" the shader program when buffering and defining VBO data? I'm trying to wrap my head around the relation between a GL "program", and the VAOs, buffers, textures, etc. I don't quite understand when I need to "use" my shader program, and when (if ever) I need to "un use" it? So when do I need to use the shader program (i.e. invoke glUseProgram), exactly? Does my shader program need to be in "use" when Creating and binding VAOs? Creating and binding VBOs? Buffering data to VBOs? Defining vertex attributes (i.e. invoking glVertexAttribPointer)? |
1 | Update single entry in GLSL array I have an array in my vertex shader like this uniform mat4 MeshTransforms 20 At the moment I'm just updating the entire array of matrices like so int meshTransforms ARBShaderObjects.glGetUniformLocationARB(shader, "MeshTransforms") ARBShaderObjects.glUniformMatrix4ARB(meshTransforms, false, UnitTransformMatrices) Where UnitTransformMatrices is a float buffer containing the transform matrices of some units. I'd like to just update a single matrix in the array (just update one unit transform matrix). So how can I overwrite a single matrix in the middle of the matrix array? This is using the LWJGL, so I'm limited to the functionality it provides. |
1 | Include deprecated OpenGl "immediate mode" context in OpenGl 4? I'm working on an app that uses immediate mode in all of it's draw routines and I'd like to keep those functions intact when updating our graphics drivers to OpenGl 4. My intention is to get the app functioning on 4.x and then convert the code to use VBOs. I've read there's a way to load a more "full" context that includes deprecated libraries but I have not found an actual implementation to base mine off of. |
1 | Difference between Spherical Harmonics and Spherical Harmonics Lighting What is the difference between Spherical Harmonics and Spherical Harmonics Lighting in OpenGL? |
1 | How should I go about creating a generic Scene object for managing VBO data? To simplify managing multiple types of data with different shaders and textures, I thought about creating a generic Scene object (is there a name for this?) which would allow me to pre configure how I want to render something, and how the data changes. Let me give an example Everything below is in the context of a 2D top down game Some parts are completely static, e.g. the background, and their geometry never changes. Then there'd be a "NPC" layer, which can change on almost every single frame, uses different shaders. Last but not least, there's a UI layer, which sits on top of everything else. Some of these parts would probably be split into multiple subparts, such as parts rendered as GL TRIANGLE FAN, and other parts rendered as GL LINE STRIP, etc. To avoid duplicating lots of setup generate geometry render phases, it would seem logical to wrap this in something that can be configured, such as Scene s Batch b1 s.create batch(somehow specify shaders etc) generate background geometry(b1) Batch b2 s.create batch(somehow specify other shaders and VAO) game loop while (true) this would generate update the NPC geometry on the fly b2.process input(gather user input()) for (Batch b s) b.render() Now what if I wanted to specify different texture bindings for each batch? Or different shaders? Is there a general pattern for managing geometry data like this? |
1 | Terrain collision detection How should I go about making terrain collision system without hightmap ? What I have tried is building a heightmap from a blender model, but that works only if the vertices are evenly spaced. Mine are not and I am not sure how to proceed from here. How do i store the mesh info ? Do I store a Plane object for every triangle in the mesh and then plug those in some kind of grid quad tree etc ? Is that the best thing to do ? My terrain has around 2000 faces, wouldn't that be too much ? |
1 | 2D Outline shader in GLSL I have a simple prototype with 2D worms like destructible terrain. I use a trivial shader to discard pixels based on a mask. varying vec2 v texCoords uniform sampler2D u texture uniform sampler2D u mask void main() vec4 colour texture2D(u texture, v texCoords) vec4 mask texture2D(u mask, v texCoords) if (mask.a gt 0) discard else gl FragColor colour What would be a good and simple way to add few pixels thick black outlines to the terrain to make the carved parts look better? I've researched something about edge detection algorithms, but my hunch says that such a fullblown thing would be kind of an overkill for this task? I'm not after quality or high performance, but simplicity. Thanks for any ideas. |
1 | How do I fill a shape with a texture in Libgdx? I am making a 2D racing game. I want to fill the area of the ground object with a texture. I have the shapes of the ground (a Box2D shape). If I make images of the ground with textures, it uses a lot of RAM, so I instead want to fill the shapes with copies of a small texture. |
1 | Do rendered to textures need to be bound when being drawn to? In OpenGL, if I'm rendering to a texture using a framebuffer, do I have to have that texture bound while I'm rendering to it? In code glBindTexture(...) glTexImage2D(...) glBindFramebuffer(...) glFrameBufferTexture2D(...) START DRAWING HERE does the texture I'm rendering to need to be bound here? |
1 | The view matrix finally explained I must say that I am really confused by how a view matrix is constructed and works. First, there are 3 terms view matrix, lookat matrix, and camera transformation matrix. Are those 3 the same, or different things. From what I undestand, the camera transformation matrix is basically the model matrix of the camera, and the view matrix is the inverse of that. The lookat matrix is basically for going from world space to view space, and I think I undestand how it works (doing dot products for projecting a point into another coordinate system). I am also confused by the fact that sometimes, it seems like the view matrix is built by translation and dot products, and some other times, it is built with translation and rotation (with cos and sin). There are also quaternions. When you convert a quaternion to a matrix, what kind of matrix is this? Can someone explain to me how it really works, or point me towards a good resource. Thank you. |
1 | How do I check for collision between transparent textures? I am creating a 2D game using OpenGL. For sprites, I use textured quads (actually two triangles). The texures contain transparent pixels, since objects are not always perfectly rectangular. How do I do collision detection on the objects, not the quads? I was thinking to first check the quads for collision and if they match, check the textures. But how can I check if two non transparent pixels are on top of each other (or next to each other) for the two objects? Or is there a completely different way of how this is done best? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.