_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
1 | I add a straight big plane over terrain(3d). Vibrations are happening when i move camera I have this problem in my OpenGL project but i will show you the same thing over blender3d with video. So I believe that I will better explain the problem. it is just 30 seconds. Take a look. Youtube LINK How can i fix these problem ? |
1 | Accesing depth buffer from shader I read this presentation and on 6th slide I found that is not need to use multiple render targets and depth can be taken directly from depth buffer. From which version of DirectX or OpenGL can be the feature used? How to do that? |
1 | Rendering a model with transparent or translucent uv map applied doesn't work Before I try to make anything transparent, the model renders nicely. When I change the uv layout so that one piece of the model will be transparent, it renders horribly. This is the result with a translucent green texture I did transparency with OpenGL when I did 2D games and everything worked nicely because of these two lines glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) Now, I fear, this won't be enough, right? Or maybe I should use some other technique? |
1 | How detect which OpenGL texture formats are natively supported? For example, how detect if my videocard doesn t support "bgr8" and convert it to another format, such as "rgba8" in software mode. UPDATE Sorry for the confusion. This question more about situation when I set internalFormat in glTexImage2D to something like "bgra8" but videodriver internally convert data to another format, like "rgba8". |
1 | Keep rasterized pixel amount constant I have a scene that is rendered from the point of view of the light using an orthographic projection matrix. For an arbitrarily shaped and oriented object that doesn't change its shape or size in any way, the amount of pixels that get rasterized change with its position. I guess it's better to explain this with an images The depth of the quads (their y coordinates) are constant. Their x and z coordinates are slightly different. However, since it's an orthographic projection matrix, their "world space" floating point sizes are the same as seen from the camera. Just in one case, one additional lines of pixels is rasterized (I drew the two white lines with mspaint to illustrate their size difference). This is highly undesirable for my application. Is there a way to keep the amount of rasterized pixels consistent? How would I go about implementing it using OpenGL? |
1 | Design question best way to model and visualize a long grid of data Perhaps some noob questions for a scientific application that you can assist with I am trying to render a large, evenly spaced grid of data in 2D. The full data set dimensions could be anywhere from 48x250,000 to 1000x15,000,000 points pixels. The data is evenly spaced, but I need to change the aspect ratio, and then render only a section of that data on the screen at a time. I need the users to be able to smoothly scroll forward or backward along the long dimension with user input, or press the "play" button and have it move forward or backward at certain speed. I am looking for advice on how to handle this via DirecX or OpenGL (probably using SharpDX or OpenTK). The basic approach I am considering is to use textures that the application generates on the fly from the data and then map them to a very simple model. I would keep the graphics card supplied with a large enough scene so that as the user scrolls or moves around that they don't have to wait for the application. Questions I have are 1) does this approach make sense? i am presuming this is way more efficient and faster than creating a bunch of primitives with discrete colors. true? 2) is there a particular texture format that is good to use and easy to create (or do i create it directly)? I have the data in application memory as large arrays and it loads unloads from disk as needed. I would map the scalar values to a color as I create the image texture blocks. 3) would mipmaps be useful? i could have an aspect ratio (or small enough window) that there are fewer screen pixels than data in the viewable range. Or, would it just automatically subsample? 4) if mipmaps are used, most of the scaling is along the long dimension, so could i uses non square subsamples? 4) does creating compressed images make sense? or, would the compression overhead yield much benefit (or how might i determine this) 5) how would i go about finding an optimal texture size? Any other general advice? Hopefully this is a straightforward problem for the cool stuff y'all do in games! |
1 | Efficient Rendering for multiple light sources I'm building a 3D rendering engine using C and OpenGL. Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods. I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources. The straight forward approach would be something like this for every object to be rendered closestLights for every light in the scene if (light closer than all lights in closestLights) swap furthest light from closestLights with current light loadLightSourcesToShader(closestLights) renderObject(object) However, I'm afraid the performance of this rendering loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker. 1) Is there any way to circumvent this? 2) How is this implemented in 'real' engines? 3) How can I find the closest K lightsources to an object efficiently? I've heard about kd trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now. 4) I could keep an octree and a kd tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?). Is this a good approach? I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game program reaches a certain complexity size. |
1 | OpenGL, Offset and Camera Space I was reading chapter 4 of the Arcsyntesis OpenGL tutorial when I came across this line in the GLSL shader. vec4 cameraPos position vec4(offset.x, offset.y, 0.0, 0.0) About it, the tutorial says The first statement simply applies the offset to get the camera space positions of the vertices. I understand what cameraPos is but I don't get what the offset is. It's defined as a uniform and it's passed to the shader by the main program like this glUniform2f(offsetUniform, 1.5f, 0.5f) So offset.x 1.5f and offset.y 0.5f. But I see no mention of that offset in the rest of the tutorial and its values seem quite random to me. I know that the offset from the projection plane to the eye is always 1 but that refers to a value of Z. Where do X and Y come from? Are they arbitrary values? What they mean, what they do? I understood everything up to the point but I can find no reference to said offset in the tutorial and I'd like to know if someone can explain it to me, please. Edit the last line I posted was probably forgotten by the author of the tutorial and can be find in the book's source distribution here. |
1 | Graphical mesh lags behind collision shape in BulletPhysics debug drawing In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape. m DynamicsWorld gt stepSimulation(1 60.0f, 10) btTransform trans, trans2 trans2 m RigidBodies.at("CubeMesh") gt m Body gt getWorldTransform() m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) using m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) causes the graphical mesh to lag behind the collision shape in DebugDraw call Checking with debugger shows that the lag error keeps on increasing glm mat4 M trans.getOpenGLMatrix(glm value ptr(M)) m RigidBodies.at("CubeMesh") gt GetGraphicalObject() gt Model M if (m DebugDraw) m DynamicsWorld gt debugDrawWorld() If I use the OpenGL matrix from trans2 then debug drawing is perferct. But with trans the graphical mesh lags behind the collision shape in debug draw. I am using btDefaultMotionState when setting the CubeMesh rigid body. btTransform tr tr.setIdentity() tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f)) cubeMesh gt m PhysicsBody gt m MotionState new btDefaultMotionState(tr) Can anyone explain reason for this lag? |
1 | How to update vertices and indices in OpenGL I want to change and update the vertices and indices of the 3D object. I am new to openGL and I do not know if this the right place to ask this question. I searched and read about that, and I found that I should bind the VAO and VBO and make that, but nothing changed in vertices and indices. The vertices vector class type has the position, normal and uv coords and the vertices vector class type is int. I wonder how I can make changes to these two vectors when I translate or scale the model. here is the code Create buffers arrays glGenVertexArrays(1, amp this gt VAO) glGenBuffers(1, amp this gt VBO) glGenBuffers(1, amp this gt EBO) glBindVertexArray(this gt VAO) Load data into vertex buffers glBindBuffer(GL ARRAY BUFFER, this gt VBO) A great thing about structs is that their memory layout is sequential for all its items. The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm vec3 2 array which again translates to 3 2 floats which translates to a byte array. glBufferData(GL ARRAY BUFFER,this gt vertices.size() sizeof(vertex), amp this gt vertices 0 , GL STATIC DRAW) glBindBuffer(GL ELEMENT ARRAY BUFFER, this gt EBO) glBufferData(GL ELEMENT ARRAY BUFFER, this gt indices.size() sizeof(int), amp this gt indices 0 , GL STATIC DRAW) Set the vertex attribute pointers Vertex Positions glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )0) Vertex Normals glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )offsetof(vertex, normal)) Vertex Texture Coords glEnableVertexAttribArray(2) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, sizeof(vertex), (GLvoid )offsetof(vertex, uv)) glBindVertexArray(0) |
1 | Stars coming out of screen I am pretty new to Graphics Programming. I am currently using OpenGL. I have got some hands on in last few days. I have knowledge of Texture Mapping, Cubemap, Multitexturing. But somehow I am not able to bridge the gap between my understanding and actual coding What I am trying to do is create a demo of a stars coming out of screen. It should look realistic. Now, my questions are 1. Is Cubemap capable of doing this? 2. Do I need to write particle engine for this?(Really, don't want to at this stage) 3. This is kinda most needed for me. May I See some code..? In some tutorial just code would also do.. but i think if its similar to my requirement then only it will Help |
1 | Help me understand this vbo rotation, and how its done opengl c Im pretty new to opengl, and I just cant figure out how to rotate this vbo vao in 2d space. This is how I bind my coordinates float points 0.0f, 0.10f, 0.0f, 0.10f, 0.10f, 0.0f, 0.10f, 0.10f, 0.0f glGenBuffers(1, amp points vbo) glBindBuffer(GL ARRAY BUFFER, points vbo) glBufferData(GL ARRAY BUFFER, 9 sizeof(float), points, GL STATIC DRAW) I place the vbo at vao 0 glBindBuffer(GL ARRAY BUFFER, points vbo) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, NULL) And I enable the array glEnableVertexAttribArray(0) and call to draw in the cpu, with glDrawArrays(GL TRIANGLES, 0, 3) In my shader, I load the array by glsl shader layout ( location 0 ) in vec3 vertex position void main() gl Position vec4(vertex position, 1.0) Ive edited out the coloring fragment to save space, but this is my problem I can make a uniform to move my triangle around, but idk how to apply a transformation matrix to a vec4. It seems the shader reads my vertex position VAO one vec element at a time, and trying to apply any matrix just gives an error. How do you make or apply a rotation matrix on vao, am I inputting it wrong? All the uniforms I apply seem to only stretch, zoom, or move the overall triangle. Sorry if the question is bad, or partially confused, shading is new to me overall, so thanks in advance.' my shader version 410 core layout ( location 0 ) in vec3 vertex position layout ( location 1 ) in vec3 vertex colour out vec3 colour uniform vec3 fade vec3(0.0,0.0,0.0) fade uniform float zoom 1.0 uniform mat4 transform mat4(vec4(1.0,0.0,0.0,0.0), vec4(0.0,1.0,0.0,0.0), vec4(0.0,0.0,1.0,0.0), vec4(0.0,0.0,0.0,1.0)) void main() colour vertex colour fade gl Position transform vec4(vertex position,1.0) this example https open.gl transformations and the answer made it doable. |
1 | Opengl drawing a section of a texture stretched over a quad Current Situation I have a spritesheet loaded in for a texture when drawing the specific portions of the sheet that I'd like to have on my quads I do some simple math to get their location on the sheet and normalize it. My texture is setup like this glTexParameterf(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) The Problem Where I'm facing the problem is that because I'm using a "chunk" of the total texture I can't take advantage of using 1.0 for the mapping of values to glTexCoordPointer to cause the texture to stretch over the entire face. Looked Into I've looked for a glTexParameterf option for scaling options but I failed to find anything. Question Is it possible with my current methods to stretch the texture over the face of the quad without having to load a separate image for every "sprite" of the texture? Or am I just doing everything completely wrong? Picture that hopefully sort of clarifies Thanks for any help. edit The problem was another issue all together Turns out it was another issue all together, I thought this didn't make sense cause it was mapping it to the vertices so it should stretch regardless and infact it does work right I was assigning the wrong the width and height values to the drawing routines calculations. And now I feel really stupid, thanks for the help Byte56. Sorry for taking up your time. The GL CLAMP solution would be the correct answer if I hadn't made a huge fail. |
1 | Which one have to use Canvas or Open GL for 2D game in Android I am compleatly new to android gaming.I want to develop a 2D game with some physics in it.I want to know which one i have to use Open GL or Canvas and the reason for selection I want to include a physics engine i dont know anything about that too It will be very help full if anyone can share any idea's and suggections. Advanced thanks to all ... |
1 | Best way to initialize values on 32 bit FP framebuffer in OpenGL I have a framebuffer bound to 32 bit FP texture glGenTextures(1, amp texColor) glBindTexture(GL TEXTURE 2D, texColor) glTexImage2D(GL TEXTURE 2D, 0, GL R32F, w, h, 0, GL RGBA, GL FLOAT, (GLvoid )NULL) glBindTexture(GL TEXTURE 2D, 0) glGenFramebuffers(1, amp fbo) glBindFramebuffer(GL FRAMEBUFFER, fbo) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, texColor, 0) What's the best way to initialize framebuffer to a value 1000.0? The problem is that glClearColor(1000.0f, 0.0f, 0.0f, 0.0f) glClear(GL COLOR BUFFER BIT) clamps values to 0,1 interval, and clearing the texture texColor would require memory allocation of w h sizeof(float) bytes of memory and manual filling of that buffer with value 1000.0 which is slow (I would inject it using glTexImage2D). I'm using OpenGL 3.2 Core profile. Thanks, Josip |
1 | How to calculate spherical harmonic coefficients for indirect diffuse? After reading the article "An Efficient Representation for Irradiance Environment Maps", I'm a bit confused as how to calculate the spherical harmonic coefficients. I'd like to generate these coefficients given a cube map that I've generate dynamically in engine. I'm currently using DirectX 11, but I have some familiarity with OpenGl. Some tips on calculating these coefficients would be greatly appreciated! |
1 | Getting world coordinates from mouse position I am drawing a 2D mesh imported from CAD. The mesh vertex coordinates are in feet from some arbitrary origin and Z is always 0. I am supplying the coordinates to my shader program and using projection matrix, view matrix and model matrix to display everything. I am also using the view matrix and the model matrix to pan and zoom my 2D scene. I am trying to get the coordinates in feet from my mouse cursor coordinates. Should be a straightforward solution. A matrix multiplied by it's inverse will give you an identity matrix but something is very wrong. Here is my code (don't lough at the vb, I took over an old project) Private Sub openGLControl1 MouseMove(sender As Object, e As MouseEventArgs) Handles openGLControl1.MouseMove Dim UnprojectMat As mat4 glm.inverse(scene.projectionMatrix scene.viewMatrix scene.modelMatrix) Dim wCoordsVec As vec4 UnprojectMat New vec4(2 e.X openGLControl1.Width 1, (2 e.Y openGLControl1.Height 1), 0, 1) wCoordsVec wCoordsVec wCoordsVec.w wCoordsLabel.Text wCoordsVec.x.ToString ", " wCoordsVec.y.ToString End Sub And this is my vertex shader version 150 in vec3 in Position uniform mat4 projectionMatrix uniform mat4 viewMatrix uniform mat4 modelMatrix void main(void) gl Position projectionMatrix viewMatrix modelMatrix vec4(in Position, 1.0) pass Color in Color The in Position vector is what I'm trying to get. As you see, I normalized the mouse coordinates for the 1, 1 coordinate system. I don't have a viewport. I'm just using the entire gl control window. Please help me pinpoint what I'm doing wrong. |
1 | OpenGL VBO Additional Attributes If I have a buffer with my vertices, normals and texture coordinates, and I use glDrawArrays to draw the VBO to the screen, how can I send attributes per vertex that I placed in an array to the shader program? I'm making a voxel terrain, and every chunk is 1 VBO, this works all great, but I want to send the light value of each block (Just an array filled with int's) to the shader as well, how would I do that? Edit After reading some comments, here some clarification I'm trying to avoid the deprecated glVertexPointer etc, so I'm using Vertex Arrays. Here is the layout of my vertex array X, Y, Z, NX, NY, NZ, X, Y, Z, NX, NY, NZ,X, Y, Z, NX, NY, NZ I'm using this to draw it (ofcourse with the array buffer bound) glVertexAttribPointer(0, 3, GL FLOAT, false, 12, 0) glVertexAttribPointer(1, 3, GL FLOAT, false, 12, 12) glDrawArrays(GL TRIANGLES, 0, arraySize 6) However I get some weird shapes on my screen. Apart from the light problem, that is essentially the same thing, I don't get why this doesn't just work. When I remove the normals, and use just 1 vertexattribpointer it works fine. Yes, the attributes are bound to in position and in normal, and the vertex shader is nothing more than gl Position gl ModelViewProjectionMatrix vec4(in position, 1.0) Thanks! This is what I get (This are 6X6 chunks, so this code is called 6 6 times.) |
1 | How can I render "two sided" clouds like in Minecraft? The clouds in Minecraft are semi transparent and are rendered on both sides. If you fly into the cloud you can see inside of the cloud. If I render clouds the inside faces would be visible on the outside. How can I prevent that? Z Ordering the faces and render near to far with depth test on? There must be a better, easier way. Could the accum or stencil buffers be used somehow? UPDATE I think the crucial point everyone is forgetting is that these clouds and semi transparent and "blended" into the scene as each face is rendered. If two faces are rendered on top of each other the "white" texture will double up which is undesired. The faces also seem to have slight lighting variations which would rule out using a stencil. UPDATE2 Just another note. Each cloud is 12x12x4 blocks (roughly). Larger clouds are just a group of the base clouds stuck together. Here's showing clouds from above. They are translucent and the chunks below can be seen. And here's the view from inside them. |
1 | What is the difference between OpenGL 1.x and 2.x? Is there a good tutorial that shows the difference between OpenGL 1. and 2. ? It would be very helpful to know which functions I should not be calling (like glBegin(), I assume). |
1 | How can I improve rendering speeds of a Voxel Minecraft type game? I'm writing my own clone of Minecraft (also written in Java). It works great right now. With a viewing distance of 40 meters I can easily hit 60 FPS on my MacBook Pro 8,1. (Intel i5 Intel HD Graphics 3000). But if I put the viewing distance on 70 meters, I only reach 15 25 FPS. In the real Minecraft, I can put the viewing disntance on far ( 256m) without a problem. So my question is what should I do to make my game better? The optimisations I implemented Only keep local chunks in memory (depending on the player's viewing distance) Frustum culling (First on the chunks, then on the blocks) Only drawing really visible faces of the blocks Using lists per chunk that contain the visible blocks. Chunks that become visible will add itself to this list. If they become invisible, they are automatically removed from this list. Blocks become (in)visible by building or destroying a neighbour block. Using lists per chunk that contain the updating blocks. Same mechanism as the visible block lists. Use nearly no new statements inside the game loop. (My game runs about 20 seconds until the Garbage Collector is invoked) I'm using OpenGL call lists at the moment. (glNewList(), glEndList(), glCallList()) for each side of a kind of block. Currently I'm even not using any sort of lighting system. I heard already about VBO's. But I don't know exactly what it is. However, I'll do some research about them. Will they improve performance? Before implementing VBO's, I want to try to use glCallLists() and pass a list of call lists. Instead using thousand times glCallList(). (I want to try this, because I think that the real MineCraft doesn't use VBO's. Correct?) Are there other tricks to improve performance? VisualVM profiling showed me this (profiling for only 33 frames, with a viewing distance of 70 meters) Profiling with 40 meters (246 frames) Note I'm synchronising a lot of methods and code blocks, because I'm generating chunks in another thread. I think that acquiring a lock for an object is a performance issue when doing this much in a game loop (of course, I'm talking about the time when there is only the game loop and no new chunks are generated). Is this right? Edit After removing some synchronised blocks and some other little improvements. The performance is already much better. Here are my new profiling results with 70 meters I think it is pretty clear that selectVisibleBlocks is the issue here. Thanks in advance! Martijn Update After some extra improvements (like using for loops in stead of for each, buffering variables outside loops, etc...), I now can run viewing distance 60 pretty good. I think I'm going to implement VBO's as soon as possible. PS All source code is available on GitHub https github.com mcourteaux CraftMania |
1 | Does cube map texturing works only for objects which vertices are is in 1,1 range? Im attempting to texture an .obj file that is not a skybox. So the question is, every tutorial about cubemap creates their hardcoded cubes with vertices ranging from 1, 1 . Probably not, but is it necessary to scale my .obj model to be in that range? Also, to map my fragments with the right texel I saw people online telling that I should take a point p then subtract it with the model center c in the shader. Some said that I should normalize them? normalize(p c) I hope you can help me deliver a brief explanation. |
1 | SDL 2.0 OpenGL not drawing anything except background My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code main.cpp include "src App.h" int main( int argc, char args ) App app(600, 400, false) app.Run() return 0 App.h ifndef APP H define APP H include lt SDL.h gt class App public explicit App(size t win width, size t win height, bool fullscreen mode) m window width(win width), m window height(win height), m fullscreen(fullscreen mode) void Run() private void Draw() void Update(double dt) void Resize(size t width, size t height) void ProcessEvents() private size t m window width size t m window height bool m fullscreen bool is done SDL Window m window SDL GLContext m glcontext endif APP H App.cpp include ".. App.h" include lt SDL opengl.h gt include lt cassert gt void App Run() SDL Init(SDL INIT VIDEO) m window SDL CreateWindow("Okno gry", SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, m window width, m window height, SDL WINDOW OPENGL (m fullscreen?SDL WINDOW FULLSCREEN SDL WINDOW RESIZABLE)) m glcontext SDL GL CreateContext(m window) Resize(m window width, m window height) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL CONTEXT PROFILE MASK, SDL GL CONTEXT PROFILE COMPATIBILITY) glClearColor(0, 0, 1, 0) glEnable(GL DEPTH TEST) glDepthFunc(GL EQUAL) is done false size t last ticks SDL GetTicks() while(!is done) ProcessEvents() size t ticks SDL GetTicks() double delta time (ticks last ticks) 1000 last ticks ticks if (delta time gt 0 ) Update(delta time) Draw() SDL Quit() void App Draw() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() glBegin(GL TRIANGLES) glColor3f(1, 1, 0) glVertex2f(1, 1) glVertex2f(0, 1) glVertex2f(0, 0) glEnd() SDL GL SwapWindow(m window) void App ProcessEvents() if (is done) return SDL Event event while (SDL PollEvent( amp event)) if (event.type SDL WINDOWEVENT amp amp event.window.event SDL WINDOWEVENT SIZE CHANGED) Resize(event.window.data1, event.window.data2) else if (event.type SDL QUIT) is done true break void App Resize(size t width, size t height) m window width width m window height height glViewport(0, 0, static cast lt int gt (width), static cast lt int gt (height)) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, 1, 0, 1, 1, 10) glMatrixMode(GL MODELVIEW) glLoadIdentity() void App Update(double dt) printf(" d", dt) Can anyone help? I don't know why it's not running. |
1 | What does glTranslatef function is translating in this code? I understand translation from mathematics view where we can have a triangle with a certain coordinates. We can translate this triangle by multiplying the coordinates of the triangle (expressed in the form of a matrix) by a translation vector. In the code below, I could not see what glTranslate () is translating since we havent drawn anything yet. What are we translating? Are we applying the translation to some default objects or something? void display(void) glClear (GL COLOR BUFFER BIT) glPushMatrix() glTranslatef ( 1.0, 0.0, 0.0) glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0) glTranslatef (1.0, 0.0, 0.0) glPushMatrix() glScalef (2.0, 0.5, 1.0) glutWireCube (1.0) glPopMatrix() glTranslatef (1.0, 0.0, 0.0) glRotatef ((GLfloat) elbow, 0.0, 0.0, 1.0) glTranslatef (1.0, 0.0, 0.0) glPushMatrix() glScalef (2.0, 0.5, 1.0) glutWireCube (1.0) glPopMatrix() glPushMatrix() glTranslatef(1.6, 0.22, 0.0) glRotatef ((GLfloat) finger, 0.0, 0.0, 1.0) glScalef (0.6, 0.1, 0.08) glutWireCube (1.0) glPopMatrix() glPopMatrix() glutSwapBuffers() |
1 | Alpha blending, transparence and z ordering I'm making some tests with alpha blending in a projet and I don't understand something. In my tests I've done something like that and everything look good Draw blue box first (depth test true, blend alpha none, color 1, 1, 1, 1) Draw left Mario (depth test false, blend alpha true, color 1, 1, 1, 0.8) Draw red box (depth test true, blend alpha none, color 1, 1, 1, 1) Draw right Mario (depth test false, blend alpha true, color 1, 1, 1, 0.8) Every tutorial say that we should Draw opaque object first Order transparent object back to front then draw them. Here is the result So, I'm not sure to understand how it work what is wrong (I've read this document). Thanks! |
1 | What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? What is the best method to share the projection matrix and view matrix with all graphic entity shaders in a custom game engine? The refer graphic entities have glUseProgram( shader program id ) glDrawArrays(GL XXXX, x) One of my ideas is to have a camera object that manages the current view and projection matrix. Then, I pass a reference of that camera object to all the entities. However, my issue with that approach is syncing the current camera across all the entities objects when switching views. I could make the Camera global, however, that could have many issues. |
1 | How can I identify loaded models so I can efficiently avoid loading them twice? I'm making a fairly basic OpenGL 3D engine, at the moment. In this engine, when you load an object, you would write manager gt LoadObjFile("cube.obj") manager gt AddParent("uvmap.bmp", "cube.obj", "cube", glm vec3(10.0f, 1.0f, 0.0f)) "uvmap.bmp" being the texture, "cube.obj" is the .obj file path, "cube" being the ID for the object. My question is, at the moment, when it loads an object, it stores the object in a struct with all of the buffer data and an ID, the ID being the path of the obj file, so when I load an .obj, it runs through all of the already loaded files and compared the ID of each using strcmp, which obviously when there's thousands of items, is going to start to get a bit slow.... it does the same for AddParent, and most of my other methods (different vector of data than where the obj data is stored). What would be best in terms of identifying items, an integer? I really don't know, I want this to be as high level, user friendly as possible, but want to keep it as optimized and as efficient as possible. |
1 | How do you create a fractal cube map? I want to create a map similar to how Mincraft and other related games do. I just haven't the faintest clue on how to do so. Can anyone point me to a decent tutorial or give me a decent run through? I program in java and use openGL. |
1 | OpenGL flickerinng near the edges I am trying to simulate particles moving around the scene with OpenCL for computation and OpenGL for rendering with GLUT. There is no OpenCL OpenGL interop yet, so the drawing is done in the older fixed pipeline way. Whenever circles get close to the edges, they start to flicker. The drawing should draw a part of the circle on the top of the scene and a part on the bottom. The effect is the following The balls you see on the bottom should be one part on the bottom and one part on the top. Wrapping around the scene, so to say, but they constantly flicker. The code for drawing them is void Scene drawCircle(GLuint index) glMatrixMode(GL MODELVIEW) glLoadIdentity() glTranslatef(pos.at(2 index),pos.at(2 index 1), 0.0f) glBegin(GL TRIANGLE FAN) GLfloat incr (2.0 M PI) (GLfloat) slices glColor3f(0.8f, 0.255f, 0.26f) glVertex2f(0.0f, 0.0f) glColor3f(1.0f, 0.0f, 0.0f) for(GLint i 0 i lt slices i) GLfloat x radius sin((GLfloat) i incr) GLfloat y radius cos((GLfloat) i incr) glVertex2f(x, y) glEnd() If it helps, this is the reshape method void Scene reshape(GLint width, GLint height) if(0 height) height 1 Prevent division by zero glViewport(0, 0, width, height) glMatrixMode(GL PROJECTION) glLoadIdentity() gluOrtho2D(xmin, xmax, ymin, ymax) std cout lt lt xmin lt lt " " lt lt xmax lt lt " " lt lt ymin lt lt " " lt lt ymax lt lt std endl |
1 | OpenGL camera moves faster than player I have a side scroller game made in OpenGL, and I'm trying to center the player in the viewport when he moves. I know how to do it cameraX Width 2 TileSize playerPosX cameraY Height 2 TileSize playerPosY However, I have a problem. The player and "camera" move, but the player moves faster than the "camera" scrolls. So, the player can actually move out of the screen. Some code, this is how I translate the camera public Camera() public void update(Player p) glTranslatef( p.getPos().x Main.WIDTH 64 2, p.getPos().y Main.HEIGHT 64 2, 1) Here's how I move the player public void update() if(Keyboard.isKeyDown(Keyboard.KEY D)) this.move(MOVESPEED, 0) if(Keyboard.isKeyDown(Keyboard.KEY A)) this.move( MOVESPEED, 0) The move method public void move(float x, float y) this.getPos().set(this.getPos().x x, this.getPos().y y) And then after I move the player, I update the player's geometry, which shouldn't matter. What am I doing wrong here, this seems like such a simple problem, yet it doesn't work! |
1 | Get world position in Vertex shader I'm wondering how I can get the final position of a vertex. I use glTranslate in my render code, and I'm not getting the world coordinates correct. My world is devided in chunks and my position get's screwed up. I have tried multiplying the position with the 3 built in matrices, but no success. |
1 | Cheap ways to do scaling ops in shader? I've got an extensive world terrain that uses vec3 for the vertex position attribute. That's good, because the terrain has endless gradations due to the use of floating point. But I'm thinking about how to reduce the amount of data uploaded to the GPU. For my terrain, which uses discrete grid based vertex positions in x and z, it's pretty clear that I can replace my vec3s (floats, really) with shorts, halving the per vertex position attribute cost from 12 bytes each to 6 bytes. Considering I've got little enough other vertex data, and an enormous amount of terrain data to push into the world, it's a major gain. Currently in my code, one unit in GLSL shaders is equal to 1m in the world. I like that scale. If I move over to using shorts, though, I won't be able to use the same scale, as I would then have a very blocky world where every step in height is an entire metre. So I see these potential solutions to scale the positional data correctly once it arrives at the vertex shader stage Use 10 1 scaling, i.e. 1 short unit 1 decimetre in CPU side code. Do a division by 10 in the vertex shader to scale incoming decimetre values back to metres. Arbirary (non PoT) divisions tend to be slow, however. Use (some power of two) 1 scaling (eg. 8 1), which enables the use of a bitshift (eg. val gt gt 3) to do the division... not sure how performant this is in shaders, though. Not as intuitive to read values, but possibly quite a bit faster than div by a non PoT value. Use a texture as lookup table to convert the value from decimetres to metres. I've heard that this is really fast. Or whatever solutions others can offer to achieve the same results minimal vertex data with sensible scaling. |
1 | Special Texture Stretching without deformation I am trying to achieve a special texture stretching effect in my shader. Here is how I define my uv before sampling my texture, nothing really special. uv ST contains the tiling and offset values uv.xy uv.xy uv ST.xy uv ST.zw This gives the standard tiling stretching and offset behaviour when you tile stretche a clamped texture as you can see in the image below. First is normal, second is offset and last is stretching. But I want to avoid the deformation behaviour when stretching, I want to keep margins when stretching my texture or simply cut it in the middle and stretching it. Here is an illustration below. How could I do that inside my shader when defining my uvs before sampling the texture ? |
1 | What happens when a texture is too large for a device The question is two fold What happens on a device when a texture is too large for it to handle? Will it crash or simply downsize it? In Unity if I use texture atlases of size 4k and then set Texture Quality in the Quality settings as half res will it run normally on devices with maximum texture size of 2k? |
1 | Why does OpenGL seem to ignore my glBindTexture call? I'm having problems making a simple sprite rendering. I load 2 different textures. Then, I bind these textures and draw 2 squares, one with each texture. But only the texture of the first rendered object is drawn in both squares. Its like if I'd only use a texture or as if glBindTexture don't work properly. I know that GL is a state machine, but I think that you only need to change active texture with glBindTexture. I load texture with this method bool CTexture generate( utils CImageBuff img ) assert(img) m image img CHECKGL(glGenTextures(1, amp m textureID)) CHECKGL(glBindTexture(GL TEXTURE 2D,m textureID)) CHECKGL(glTexParameteri(GL TEXTURE 2D,GL TEXTURE MIN FILTER,GL LINEAR)) CHECKGL(glTexParameteri(GL TEXTURE 2D,GL TEXTURE MAG FILTER,GL LINEAR)) CHECKGL(glTexImage2D(GL TEXTURE 2D,0,img gt getBpp(),img gt getWitdh(),img gt getHeight(),0,img gt getFormat(),GL UNSIGNED BYTE,img gt getImgData())) CHECKGL(glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, img gt getWitdh(), img gt getHeight(), 0, GL RGBA, GL UNSIGNED BYTE, img gt getImgData())) return true And I bind textures with this function void CTexture bind() CHECKGL(glBindTexture(GL TEXTURE 2D,m textureID)) Also, I draw sprites with this method void CSprite2D render() CHECKGL(glLoadIdentity()) CHECKGL(glEnable(GL TEXTURE 2D)) CHECKGL(glEnable(GL BLEND)) CHECKGL(glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA)) m texture gt bind() CHECKGL(glPushMatrix()) CHECKGL(glBegin(GL QUADS)) CHECKGL(glTexCoord2f(m textureAreaStart.s,m textureAreaStart.t)) 0,0 by default CHECKGL(glVertex3i(m position.x,m position.y,0)) CHECKGL(glTexCoord2f(m textureAreaEnd.s,m textureAreaStart.t)) 1,0 by default CHECKGL(glVertex3i( m position.x m dimensions.x, m position.y, 0)) CHECKGL(glTexCoord2f(m textureAreaEnd.s, m textureAreaEnd.t)) 1,1 by default CHECKGL(glVertex3i( m position.x m dimensions.x, m position.y m dimensions.y, 0)) CHECKGL(glTexCoord2f(m textureAreaStart.s, m textureAreaEnd.t)) 0,1 by default CHECKGL(glVertex3i( m position.x, m position.y m dimensions.y,0)) CHECKGL(glPopMatrix()) CHECKGL(glDisable(GL BLEND)) Edit I bring also the check error code int CheckGLError(const char GLcall, const char file, int line) GLenum errCode avoids infinite loop int errorCount 0 while ( (errCode glGetError()) ! GL NO ERROR amp amp errorCount lt 3000) utils globalLogPtr log utils CGLogFactory getLogInstance() const GLubyte errString errString gluErrorString(errCode) std stringstream ss ss lt lt "In " lt lt FILE lt lt "(" lt lt LINE lt lt ") " lt lt "GL error with code " lt lt errCode lt lt " at file " lt lt file lt lt ", line " lt lt line lt lt " with message " lt lt errString lt lt " n" log gt addMessage(ss.str(),ZEL APPENDER GL,utils LOGLEVEL ERROR) return 0 |
1 | Masking OpenGL texture by a pattern Tiled terrain. User wants to build a structure. He presses build and for each tile there is an "allow" or "disallow" tile sprite added to the scene. FPS drops right away, since there are 600 tiles added to the screen. Since map equals screen, there is no scrolling. I came to an idea to make an allow grid covering the whole map and mask the disallow fields. Approach 1 Create allow and disallow grid textures. Draw a polygon on screen. Pass both textures to the fragment shader. Determine the position inside the polygon and use color from allowTexture if the fragment belongs to the allow field, disallow otherwise Problem How do I know if I'm on the field that isn't allowed if I cannot pass the matrix representing the map (enum FieldStatus (Allow Disallow)) to the shader? Therefore, inside the shader I don't know which fragments should be masked. Approach 2 Create allow texture. Create an empty texture buffer same size as the allow texture Memset the pixels of the empty texture to desired color for each pixel that doesn't allow building. Draw a polygon on screen. Pass both textures to the fragment shader. Use texture2 color if alpha 0, texture1 color otherwise. Problem I'm not sure what is the right way to manipulate pixels on a texture. Do I just make a buffer with width height 4 size and memcpy the color to desired coordinates or is there anything else to it? Would I have to call glTexImage2D after every change to the texture? Another problem with this approach is that it takes a lot more work to get a prettier effect since I'm manipulating the color pixels instead of just masking two textures. varying vec2 TexCoordOut uniform sampler2D Texture1 uniform sampler2D Texture2 void main(void) vec4 allowColor texture2D(Texture1, TexCoordOut) vec4 disallowColor texture2D(Texture2, TexCoordOut) if(disallowColor.a gt 0) gl FragColor disallowColor else gl FragColor allowColor I'm working with OpenGL on Windows. Any other suggestion is welcome. |
1 | Cube world rendering optimizations I'm making a Minecraft like game and I would like to apply some optimizations. Firstly I didn't and I rendered the world using a vbo in which I stored a cube model and I drow all blocks of the worlds and off course it caused lag if there were too many blocks. Then I decided to draw the world face by face and check if a face is hidden from another one. This concept is simple if I have the world made only by cubes of the same size, like this Blue and black block are two blocks of the same size and the red face is the face to ignore since is hidden (overlapped) by another opaque face. As I said if I want to make blocks of different sizes (scale) position rotation but by always drawing them from faces, the matter is different since I can't know if a face is completely visible or not. Here's an image of a normal block with a "custom" block on it Blue block is the custom block, the black a "normal" block and the red is the face overlapped by the biggest one (then it should be ignored during rendering). Here the rotation is null but if there's no way to check rotated faces I can simply ignore it and draws all rotated blocks by default (I don't rotate all the world lol)... that's not what I'd like to do but if there's no way or the way is too difficult... Anyway, finally, how can I check (using GL functions or doing it in my code) if a face is hidden and to ignore it on rendering? I forgot to say that another optimization I did is if a block is hidden (has a block relative to each face) by other blocks I don't draw it. |
1 | Ray picking get direction from pitch and yaw I am attempting to cast a ray from the center of the screen and check for collisions with objects. When rendering, I use these calls to set up the camera GL11.glRotated(mPitch, 1, 0, 0) GL11.glRotated(mYaw, 0, 1, 0) GL11.glTranslated(mPositionX, mPositionY, mPositionZ) I am having trouble creating the ray, however. This is the code I have so far ray.origin new Vector(mPositionX, mPositionY, mPositionZ) ray.direction new Vector(?, ?, ?) My question is what should I put in the question mark spots? I.e. how can I create the ray direction from the pitch and roll? Any help would be much appreciated! |
1 | How to handle hitboxes hurtboxes in animations? I'm curious how I should go about structuring hitboxes and hurtboxes for my actors. For context, I'm developing a game engine in OpenGL, using C and OpenTK. I have developed a working skeletal animation system, which loads animations using Assimp, and then passes BoneIDs, BoneWeights, and Transform matrices to the Vertex shader, which calculates all vertex deforms appropriately for the current animation keyframe (or current interpolation between keyframes). Is there a set standard for calculating collision in animations? I'd prefer to continue using Assimp, which means using standard, recognizable animation formats that my engine can load in, so I'd rather not store any collision data in the animation files, unless there is a precedent for this or room for metadata or something. My current thoughts One option would be to calculate the hitboxes and hurtboxes upon loading an animation, and have a mapping that determines which meshes are hitboxes and which are hurtboxes. The second option would be to create a new file format where I store my hitboxes and hurtboxes in a way that is similar to animation files (minus bone weights, since I'll just be transforming the scale position of axis aligned rectangles), where I can determine keyframes for hitboxes and hurtboxes, then interpolate based off of these to get the current collision box for each frame. I could combine the two options by automatically generating these files from the animations, then editing them manually until they are reasonable. Am I on the right track, or are there smarter ways of going about this? I don't want to reinvent the wheel if there are better options available. |
1 | Can I directly pass a Boost ptr vector list to glBufferData? I have a data structure like this typedef struct vertex float x float y float z float s float t vertex Then I add to a list called boost ptr vector lt vector gt vertices Is there a way to use vertices to provide the parameters for glBufferData? |
1 | What is Vulkan and how does it differ from OpenGL? Khronos Group (the standards body behind OpenGL) has just announced Vulkan Vulkan is the new generation, open standard API for high efficiency access to graphics and compute on modern GPUs. This ground up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability. Their page is quite marketese jargon heavy, as is the press release In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.) What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement. Update The Vulkan 1.0 spec was released on 16 02 2016. |
1 | Should I batch up debug primitives for rendering in modern OpenGL? I've recently started porting some old rendering demos I did to modern OpenGL. I had a debug drawing class in my old code which used immediate mode glBegin(), glEnd() etc. for rendering debug objects such as triangles, cubes and spheres etc. Originally I replaced the code in these functions with code to generate the VAO and VBOs (for position and colour), bind them, assign the vertex data, render, then disable and delete the VBOs and VAO. Is there anything wrong with this? I've been thinking about modifying the class so that every time it gets a draw primitive call it generates the VAO and VBOs and assigns the vertex data but doesn't actually do the rendering until after all the other rendering has been completed. Then it renders all the debug prims that have been stored at once. I'm not sure of the benefits of either way of doing this and was just wondering what people thought. |
1 | Help finding coordinate for left of screen in this frustum I have a frustum with l 2, r 2, n 0.5, f 10, corresponding to left, right, near, far respectively. I also define top and bottom too. I've set the camera eye up at (0, 0, 2.5), looking directly at (0, 0, 0) with up (0, 1, 0). Suppose I want to position an object centred at z 1. I want to find the x coordinate so that under this frustum it appears exactly centred on the left edge of the screen. I set up the following diagram to help me z x lt gt x x 1 l near dist n 0.5 a 2.5 z So to find x I can use simple trig. Since tan a l n and tan a x 1.5 then the formula for x is x l n 1.5 2 0.5 1.5 6, where . is the absolute value. But when I use this x value to draw an object left of the centre, it does not appear centred at the edge of the screen. I can see the object but it's not on the edge. Moreover, if I increase n then the gap between the object and the left edge increases. What am I doing wrong? UPDATE Empirically I have discovered that if I compute x l n 2.5 then my object is correctly centred on the left edge of the device screen, and works for any n value I choose. Not sure why 2.5 works... SOLUTION Not really worthy of an answer, but I found in some legacy code that the renderer was set up to transalte the z forward by 1 unit, so this was undoing my 1 z value, hence why multiplying by 2.5 worked and not 1.5. Despite this annoying fact, I'm now confident I fully understand how the frustum fits into OpenGL. |
1 | OpenGL drawElements 2D imposible z sorting (textured) I am creating a 2D program in OpenGL 3.2 Now to render what I do is have a VBO for each texture and add the elements of the objects that use that texture to this vbo. Now as you know the order you render objects will be the (fliped) order you see them on the screen. Here is the problem, as you know its possible to sort objects by their Z value in the same VBO (by inserting them to the vbo according to their Z value). But when you want to sort them between VBOs thats impossible because they have to be in the correct VBO to have the correct texture, Meaning the VBOs that are drawn last will have positive Z value priority over VBOs that are drawn first. This causes the Z value to transfer from the actual objects, to their textures and makes the Z value be grouped for all objects that use the same texture. That was kinda confusing so to recap, because of the way VBOs work this is what is going to happen Turtule texture id 1 Box texture id 2 (Each textures has its own VBO) There is one turtle and one box, the turtle (z 1) is behind the box (z 0) . if I render the box VBO then the Turtle VBO What will happen is we will see the turtle over the box even though it has a z value that is less then the box. Here is some art I drew to help you visualize the problem That makes the Z value of the actual turtle meaning less compared to the " Z " value of the VBO. This can be worked around by having a Z value for each VBO but that limits the program because if the Z of the boxes is bigger than turtles no matter what every turtles is gonna be hidden behind every box. And its a stupid way of doing it. So finally to the question What can I do to fix this, to have a meaning full Z value to each OBJECT. Notes I cannot draw the object individually because I use drawElements and because I add them to texture coresponding VBOs to reduce the VBO count and texture binding count. Stuff I have tried I have tried using the actual opengl Z buffer, but I cannot blend layers because of that so its not a solution. |
1 | Reading mesh data back from OpenGL vs storing two copies I'm wondering if whether it's a good idea or not to keep a copy of vertex data in the main memory or just read it back via glGetBufferSubData (or glMapBuffer glMapBufferRange). The reason why I'd do this is so that I can keep only what's needed in the VRAM (and resource which may be needed very soon in the main memory) but not have to go back and load the resource from the disk again. The concern that I have is that, with the draw optimized flags (GL XXXX DRAW) is that they aren't optimized for reading back (since there's a seperate flag for that). So if it's not very fast, it kinda defeats the whole purpose. The other option is storing a second copy and just delete the VBO when I'm done (no reading it back), but I dislike this because it requires more memory usage than might be necessary. Which option is preferred? Is there another way? Maybe something I'm missing? |
1 | Expected OpenGL performance I'm benchmarking some simple code for drawing using OpenGL. In the following code, the number of indices being drawn is 4,644 (or 1,548 triangles per frame 60fps 92,880 Triangles per second). glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, screenSize.width, screenSize.height, 0, 0, 1) glMatrixMode(GL MODELVIEW) glLoadIdentity() glDisable(GL DEPTH TEST) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glEnableClientState(GL TEXTURE COORD ARRAY) glEnable(GL TEXTURE 2D) glColorPointer(4, GL UNSIGNED BYTE, sizeof(venomGLAttribute), ,drawingTexturedList.attrib 0 .color) glVertexPointer(2, GL SHORT, sizeof(venomGLAttribute), amp drawingTexturedList.attrib 0 .pos 0 ) glTexCoordPointer(2, GL FLOAT, sizeof(venomGLAttribute), amp drawingTexturedList.attrib 0 .UV 0 ) glDrawElements(GL TRIANGLES, drawingTexturedList cnt .currentIndice 4644 , GL UNSIGNED INT, drawingTexturedList cnt .Indices) This takes 100 of one of my CPU's. If I take out the call to glDrawElements but still perform all the other steps (geometry preperation, gl Pointer setup) I see my CPU stay at 3 . Is this expected behaviour? The machine I'm running on has a GeForce 8800GTX and a Dual Core 2.66Ghz. Using fps as a measurement (which isn't perfect I realise) and using gDEBugger to confirm my findings, rendering 27,904 triangles a frame in a single call to glDrawElements brings my frame rate down to 35fps (or 977,640 triangles a second). Is there a better way to pack my data than I'm doing or perhaps a better way to send the data than glDrawElements? I don't think using a VBO will help as the data being sent changes every frame. Any idea's would be appreciated! |
1 | Would it perform faster to split calculation between vertex and fragment shaders? Assuming the total amount of computation would be the same (at least as far as my code goes), would there be any performance increase in splitting the calculation and using separate vertex and fragment shaders vs. doing all the calculations in just a fragment shader? In my use case, I would not be using vertex shaders as they are typically intended (so, not processing actual vertices). I just thought if the GPU hardware is set up such that the pipeline is expected to be used, would it be better to take advantage of that, or would it be just as fast to put it all in a fragment shader. Conceptually, it would be simpler to just use the fragment shader. Note, that I do need a lot of data going to the fragment shader that is updated every frame (eg. texture buffer object). |
1 | Deforming a lip mesh to match face tracking points I'm creating a lipstick filter. I have a basic mesh for the lip shape ( 140 vertices ) which I am able to render on screen. I need the mesh since I have my own lighting system, and hence need the normal info. Plus I don't want to create a model at runtime since if I load an obj file I have the flexibility of rendering high quality meshes. The problem that I am now facing is that when a user is going to use it, their face will be moving around in the video frame, and I will be getting the lips' positions accordingly. Hence at each frame the mesh will be rendered differently ( in one frame he might be smiling, the other he might be frowning etc), in different places in the screen. How can I set the OpenGL vertices to match the positions of the tracked feature points, and interpolate the rest? I have only 20 ish detection landmark points for each of the upper and lower lip. |
1 | OpenGL Is it efficient ok to glPushMatrix, plMultMatrix, plPopMatrix for every object in my scene? I'm very new to opengl, and I might not fully understand the openGL matrix projection stack thing. So, I have about 300 'objects' in my scene, each with their own position rotation, and I want to draw them all (ignore culling and overdrawing for now). Would it be efficient enough to for each object glPushMatrix() glMultMatrix(object pose) do object drawing glPopMatrix() or is there a better way to draw each object? |
1 | Perspective Projection Far Plane Not Clipping? I've just discovered that far away objects in my world don't seem to clip like they should with a perspective projection matrix. When I fly far away from my main landscape, so that I am much more than 10 units (if not hundreds) away, it won't disappear. This is weird, because I thought objects should clip disappear once they hit the far plane. Here's a photo that demonstrates the issue I have defined the projection with my own custom function. The field of view is 60 degrees and the aspect ratio is 1.3333 (although those shouldn't matter), the near plane is 0.1 and the far plane is 10. I have experimented with adjusting the far plane and even when it is 0.2 nothing is ever clipped. When it is 0.1 or below I get a blank screen. (which makes sense) The matrix is calculated like so projectionMatrix.setIdentity() float yScale MathHelper.coTangent((float) Math.toRadians(fieldOfView 2f)) float xScale yScale aspectRatio float frustumLength farPlane nearPlane projectionMatrix.m00 xScale projectionMatrix.m11 yScale projectionMatrix.m22 ((farPlane nearPlane) frustumLength) projectionMatrix.m23 1 projectionMatrix.m32 ((2 nearPlane farPlane) frustumLength) projectionMatrix.m33 0 This produces a perspective projection like so 1.299038 0.0 0.0 0.0 0.0 1.7320508 0.0 0.0 0.0 0.0 1.0 0.20202021 0.0 0.0 1.0 0.0 Thanks very much if you could help with this annoying issue benefit. |
1 | Learning OpenGL Red and Blue book still relevant? I've recently purchased the Orange book( GLSL ) and am wondering if it is important at all to read through the red and blue books as well? Any thoughts? |
1 | Rendering issues in Monogame when using shaders I am currently fiddling with Monogame, trying to work with Shaders and I have encountered a really weird issue. If the first ever draw in the application's lifetime is with a custom shader all further draws without a custom shader get this red tint (as if blue and green channels were set to 0) (A is the correct one, the sprite is white and black) The following code produced these spriteBatch.Begin() Use this for A spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, Gfx.MyShader) Use this for B spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(10, 10)) spriteBatch.End() spriteBatch.Begin() spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(50, 50)) spriteBatch.End() spriteBatch.Begin() spriteBatch.Draw(Gfx.PlayerStand2, new Vector2(80, 80)) spriteBatch.End() And this is the shader sampler TextureSampler register(s0) float4 PixelShaderFunction(float2 texCoord TEXCOORD0) COLOR0 return tex2D(TextureSampler, texCoord) technique Shader1 pass Pass1 PixelShader compile ps 2 0 PixelShaderFunction() It all depends on the first draw if I replace the first two lines with this counter Starts at 0 if (counter 1) Run only on the first draw spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, Gfx.GaussianBlur) else spriteBatch.Begin() They all become red. If I replace with ! they all display correctly. I am using OpenGL for rendering. I am aware I could circumvent this problem by always using a custom shader but I fear that this is but a symptom of a greater issue that will come later to bite my bottom. Or hopefully something completely trivial that I missed. Update I tried to reproduce it in DirectX version and in this case the batch with the shader does not render, but the other sprites are not red. I also tried to compile the files via Monogame Pipeline with the same effect. |
1 | Collision Detection Tips I need collision detection for my 3D racing game but it isn't going well right now. I think I understand the concept of testing boxes and generating a response, however implementation part is a nightmare for me. OpenGL makes everything more complicated than it has to be. How can I use a shape that is constructed with glVertex ? Should I create the bounding boxes with some Vector3D class? |
1 | How to work with smaller intermediate textures in OpenGL and GLSL? I'm working on a project rendering water simulated through smoothed particle hydrodynamics (SPH) with a non photorealistic look to use in games. In the actual stage of the project everything about this rendering is done through OpenGL and GLSL in C , with many shader steps that stores intermediate textures in FBOs, which are later used in a final shader that brings everything together. Everything is working fine, except for the framerate, which lies below between 25 and 30 FPS in the better case, rendering everything, including the intermediate textures, in 1024x768 pixels. So, since some of these intermediate steps involve image smoothing algorithms that are time consuming, I thought of reducing the dimensions of the textures generated in intermediate steps to make them faster, trying to find a sweet spot between the level of reduction performance (divided by 2, 4, 8...) and the rendering final visual. My question lies precisely here How can I work with smaller textures in intermediate steps and use them on a final shader step to render to a image in a bigger dimension? |
1 | Wierd behaviour upon limiting rotation on Y axis Okay, this is the code that works for a FPS camera, except it allows the player to flip it over by going under over 90 rotation on Y axis transformation gt rotateObjectFromRight(glm radians(angleX), glm tvec3 lt GLfloat gt (0.0f, 1.0f, 0.0f)) transformation gt rotateObjectFromLeft(glm radians(angleY), glm tvec3 lt GLfloat gt (1.0f, 0.0f, 0.0f)) transformation object holds the data required to construct the view matrix, among others, a quaternion representing the rotation. The functions called will construct the quaternion with the given data and then multiply it with the rotation quaternion either from the left (relative to global axes) or the right (relative to local axes) side. angleX and angleY are mouse X and Y offsets representing the angles to rotate around. The first line yaws the camera around local Y axis, while the second then pitches it around global X axis, creating the characteristic FPS camera movement. Okay. So far so good. This is the code that should limit the pitch to never exceed the 90 boundaries transformation gt rotateObjectFromRight(glm radians(angleX), glm tvec3 lt GLfloat gt (0.0f, 1.0f, 0.0f)) glm tvec3 lt GLfloat gt forwardVector glm rotate(glm inverse(transformation gt getRotation()), glm tvec3 lt GLfloat gt (0.0f, 0.0f, 1.0f)) GLfloat pitchAngle forwardVector.y 90.0f angleY glm clamp(angleY, (pitchAngle 90.0f), (pitchAngle 90.0f)) transformation gt rotateObjectFromLeft(glm radians(angleY), glm tvec3 lt GLfloat gt (1.0f, 0.0f, 0.0f)) First and the last line are the same. What happens here? First I get the unit vector that lies on the Z axis and rotate it so that it represents the forward vector of the camera. I then take the Y component of that vector (ranging from 1 to 1) and multiply it with 90 to get the degrees. Then I clamp the angleY so that current rotation combined with the new one never exceeds the 90 boundary. If the rotation was about to flip the camera overhead, it would change the new rotation angle so the camera looks straight up. Similar thing for underfoot flipping. However, the camera acts weird. It's fastest at pitch angles close to 0 , but gets progressively slower as the pitch nears 90 . If I move my mouse slower, the camera is faster, if I move it faster, it's slower. It's as though it's discarding the too large small angleY values instead of clamping them to the appropriate values (but it's not, and I can confirm via the debugger all the calculated values look alright and are correct). What could be amiss here to cause such weird movement? |
1 | Is OpenGL 1.x deprecated? I'm familiar with OpenGL 1.x. I typically use SDL with OpenGL 1.4 on Linux, and I've never run into problems, even on my modern system. I've read on the OpenGL site about deprecation and compatibility contexts, but I'm still unclear as to whether it's safe to continue to use old versions of OpenGL, as opposed to using old features in newer versions. When functionality is marked deprecated ... future versions of OpenGL may remove it. Does deprecation simply imply that those functions can't be used alongside newer features? More specifically, are there any systems today (other than embedded) where OpenGL 1.x isn't available? The old skool stuff like, glBegin, glEnd, glDrawPixels, etc. Note I'm not a professional games developer, so you'll have to excuse my ignorance. I'm working on a mostly 2D game that I would like to keep multi platform, supporting at least Linux, Mac, and Windows. |
1 | Opengl lighting not working I have rendered a spinning model in LWJGL. I have calculated normals and enabled lighting. Now I make a light float lightpos 0, 0, 0, 0 FloatBuffer lightposb BufferUtils.createFloatBuffer(8) lightposb.put(lightpos) glLight(GL LIGHT0, GL POSITION, lightposb) float light 10, 10, 10, 1 FloatBuffer lightb BufferUtils.createFloatBuffer(8) lightb.put(light) glLight(GL LIGHT0, GL SPECULAR, lightb) glLight(GL LIGHT0, GL DIFFUSE, lightb) glLight(GL LIGHT0, GL AMBIENT, lightb) The model, instead of being lit up, is a dark gray. Also, no color appears on the model, even though I set its color to cyan float color 0,1,1,1 FloatBuffer colorb BufferUtils.createFloatBuffer(8) colorb.put(color) glMaterial(GL FRONT, GL AMBIENT, colorb) UPDATE Even though I have calculated normals and set them with glNormal3f, the model still appears to be shaded flat. UPDATE I HAVE done glEnable(GL LIGHTING) and glEnable(GL LIGHT0) that is NOT the problem. UPDATE I reversed the order of the light code and the model code and now the model flashes white, then goes dark grey and stays there. |
1 | OpenGL height map accuracy for planetary rendering I am trying to implement planetary rendering and I am trying to use OpenGL tessellation to model the terrain. Here is an overview picture using cube faces projected onto a sphere If I use the following code for the tessellation evaluation shader, I get a smooth sphere even when rendering a near view. version 410 core layout(quads, equal spacing, ccw) in in mediump vec2 texcoord tes out mediump vec2 texcoord geo uniform mat4 projection uniform mat4 transform void main() vec2 c mix(texcoord tes 0 , texcoord tes 1 , gl TessCoord.x) vec2 d mix(texcoord tes 3 , texcoord tes 2 , gl TessCoord.x) texcoord geo mix(c, d, gl TessCoord.y) vec4 a mix(gl in 0 .gl Position, gl in 1 .gl Position, gl TessCoord.x) vec4 b mix(gl in 3 .gl Position, gl in 2 .gl Position, gl TessCoord.x) vec4 p mix(a, b, gl TessCoord.y) float s 1.0 sqrt(p.x p.x p.y p.y p.z p.z) gl Position projection transform vec4(p.xyz s 6388000, 1) Here is a near view using the computed scaling factor (float s 1.0 sqrt(p.x ...)) However if I take the scale factors from a floating point texture, I can see quantisation artifacts. The scale factors (or heightmap values) are extracted from the texture using float s texture(hf, texcoord geo).r. The code for the tessellation evaluation shader in this case is as follows version 410 core layout(quads, equal spacing, ccw) in in mediump vec2 texcoord tes out mediump vec2 texcoord geo uniform sampler2D hf uniform mat4 projection uniform mat4 transform void main() vec2 c mix(texcoord tes 0 , texcoord tes 1 , gl TessCoord.x) vec2 d mix(texcoord tes 3 , texcoord tes 2 , gl TessCoord.x) texcoord geo mix(c, d, gl TessCoord.y) float s texture(hf, texcoord geo).r vec4 a mix(gl in 0 .gl Position, gl in 1 .gl Position, gl TessCoord.x) vec4 b mix(gl in 3 .gl Position, gl in 2 .gl Position, gl TessCoord.x) vec4 p mix(a, b, gl TessCoord.y) gl Position projection transform vec4(p.xyz s 6388000, 1) In this case the near view looks like this and shows artifacts My question is, what am I doing wrong? Or is it normal that OpenGL textures are less accurate than 4 byte floating point numbers? Any help is appreciated. |
1 | What OpenCL video cards (or FPGAs) features are needed for high speed multiplication? I'm benchmarking some cryptographic related software and am looking for video cards that are better at parallel multiplication vs parallel addition. Is there any prior work that would graph video card performance against math operations (calculating large digits like 256 2048, calculating the modulus etc.) What GPU features should I look for? |
1 | Why does my depth test fail on Nvidia cards? I sent a test version of my in development game to some friends, and they found out that the Depth Test in OpenGL does not work on Nvidia cards. I'm using LWJGL. I use my own matrices and send them to the shader, and at the start of evey game loop I use glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT ) clear the display On an Nvidia card, you can see mountains through other mountains and stuff. On my Radeon HD 6650M it works perfectly fine. Any ideas? I don't have anything special in the shaders just some basic lighting calculations. I dont touch the gl FragDepth. Here's a screenshot (with placeholder textures) I use these calculations for the Projection Matrix public Matrix4f getProjectionMatrix() Setup projection matrix Matrix4f projectionMatrix new Matrix4f() float fieldOfView 40.0f float aspectRatio (float)Display.getWidth() (float)Display.getHeight() float near plane 0.1f float far plane 1000f float y scale coTangent((float) Math.toRadians(fieldOfView 2f)) float x scale y scale aspectRatio float frustum length far plane near plane projectionMatrix.m00 x scale projectionMatrix.m11 y scale projectionMatrix.m22 ((far plane near plane) frustum length) projectionMatrix.m23 1 projectionMatrix.m32 ((2 near plane far plane) frustum length) projectionMatrix.m33 0 return projectionMatrix |
1 | Shadow maps, reducing "shimmering" I'm doing shadow maps, and my shadows move around, "shimmer", when I move around the camera. It is difficult to spot on still images but very much noticable in motion. I read an MSDN article describing the very same problem http msdn.microsoft.com en us library windows desktop ee416324(v vs.85).aspx but even with their fix, the problem still very much persists in fact, I hardly see any difference at all. Here's how I construct view projection for my directional light source, and the measures I take to combat "shimmering" yet which does not work why? Mat4 CreateDirLightVPMatrix(const Vec3 amp lightDirection, const Mat4 amp viewProjectionMatrix, const float shadowMapResolution) const Vec3 lightDir glm normalize(lightDirection) const Vec3 perpVec1 glm normalize(glm cross(lightDir, Vec3(0.0f, 0.0f, 1.0f))) const Vec3 perpVec2 glm normalize(glm cross(lightDir, perpVec1)) Mat4 rotationMatrix(Vec4(perpVec1, 0.0f), Vec4(perpVec2, 0.0f), Vec4(lightDir, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f)) Vec4 corners 8 Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4( 1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f), Vec4(1.0f, 1.0f, 1.0f, 1.0f) const Mat4 inverseVPMatrix glm inverse(viewProjectionMatrix) for (uint32 t i 0 i lt 8 i ) corners i inverseVPMatrix corners i corners i corners i .w corners i corners i rotationMatrix float minX corners 0 .x, minY corners 0 .y, minZ corners 0 .z, maxX corners 0 .x, maxY corners 0 .y, maxZ corners 0 .z for (uint32 t i 0 i lt 8 i ) if (corners i .x lt minX) minX corners i .x if (corners i .x gt maxX) maxX corners i .x if (corners i .y lt minY) minY corners i .y if (corners i .y gt maxY) maxY corners i .y if (corners i .z lt minZ) minZ corners i .z if (corners i .z gt maxZ) maxZ corners i .z Mat4 viewMatrix(rotationMatrix) viewMatrix 3 0 (minX maxX) 0.5f viewMatrix 3 1 (minY maxY) 0.5f viewMatrix 3 2 (minZ maxZ) 0.5f viewMatrix 0 3 0.0f viewMatrix 1 3 0.0f viewMatrix 2 3 0.0f viewMatrix 3 3 1.0f Vec3 halfExtents((maxX minX) 0.5, (maxY minY) 0.5, (maxZ minZ) 0.5) supposed fix from MSDN article does not have any effect at all float texelSize 1.0f shadowMapResolution halfExtents.x texelSize halfExtents.y texelSize halfExtents glm floor(halfExtents) halfExtents.x texelSize halfExtents.y texelSize return glm ortho( halfExtents.x, halfExtents.x, halfExtents.y, halfExtents.y, halfExtents.z, halfExtents.y) viewMatrix |
1 | Why doesn't glBindVertexArray work in this case? From my understanding of what glBindVertexArray does and how it works, the following code should work fine First init glGenVertexArraysOES(1, amp vertexArray) glBindVertexArrayOES( vertexArray) glGenBuffers(1, amp buffer) glBindBuffer(GL ARRAY BUFFER, buffer) glBufferData(GL ARRAY BUFFER, kMaxDrawingVerticesCount sizeof(GLKVector3), NULL, GL DYNAMIC DRAW) glGenBuffers(1, amp indexBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, kMaxDrawingVerticesCount 1.5 sizeof(GLuint), NULL, GL DYNAMIC DRAW) glEnableVertexAttribArray(GLKVertexAttribPosition) glVertexAttribPointer(GLKVertexAttribPosition, 3, GL FLOAT, GL FALSE, sizeof(GLKVector3), BUFFER OFFSET(0)) glBindVertexArrayOES(0) And later add new geometry glBindVertexArrayOES( vertexArray) glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) However, it doesn't work (there is screen output, but it looks like the buffers were changed between each other). Binding the vertex array is not enough for the vertex indices buffer to get bound? Because, if I do this glBindVertexArrayOES( vertexArray) glBindBuffer(GL ARRAY BUFFER, buffer) lt note this line glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) lt note this line glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) Everything works looks as expected. I find it strange, since the vertex array should have taken care of the buffer binding. Otherwise, what's the purpose to have a vertex array if you still have to bind all the buffers? |
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 | What is the order less rendering technique that allows partial transparency? I've seen somewhere rendering technique that allows order less rendering of partially transparent sprites objects. Though I can't remember what the technique is called, so I'm having trouble Googling it. |
1 | Shader value remap Blend Falloff I would like to know if there's a way to remap a value that goes from 0 to 1 constantly like this. Into those values (those are examples). This might be some function transformation but I can't find the way to do that. I've tried using a lookup texture but in my opinion this is not the best solution. Thank you very much. |
1 | Soft Body rendering from OBJ model As part of my master thesis I have to do an softbody simulation. I 'm using Bullet Physics engine. I'm trying to render softbody, create from Meshes, with Shaders in OpenGL but the object doesnt seem to be rendered (it doesnt appear in the window). I'm not sure if the problem is because of the way I created the sobtbody or the way I render it. Thank you in advance. I'm using this function for creating a softBody from my OBJ Liver model btScalar verti new btScalar 3 (Liver.getMeshes() 0 .vertices.size()) for (int i 0 i lt Liver.getMeshes() 0 .vertices.size() i ) verti 3 i Liver.getMeshes() 0 .vertices i .Position.x verti 3 i 1 Liver.getMeshes() 0 .vertices i .Position.y verti 3 i 2 Liver.getMeshes() 0 .vertices i .Position.z int indi new int Liver.getMeshes() 0 .indices.size() for (int i 0 i lt Liver.getMeshes() 0 .indices.size() i ) indi i Liver.getMeshes() 0 .indices i btSoftBody LiverSBody btSoftBodyHelpers CreateFromTriMesh(softBodyWorldInfo, verti, amp indi 0 , int(Liver.getMeshes() 0 .indices.size()) 3) LiverSBody gt m cfg.kVC 0.5 btSoftBody Material pSpMat LiverSBody gt appendMaterial() LiverSBody gt m materials 0 gt m kLST 0.5 pSpMat gt m kLST 1.0 LiverSBody gt setPose(false, true) btTransform trans trans.setIdentity() trans.setOrigin(btVector3(0,0,0)) LiverSBody gt transform(trans) LiverSBody gt generateBendingConstraints(2, pSpMat) LiverSBody gt m cfg.piterations 2 LiverSBody gt m cfg.kDF 1.0 LiverSBody gt m cfg.kSRHR CL 1 LiverSBody gt m cfg.kSR SPLT CL 0 LiverSBody gt setTotalMass(10, true) LiverSBody gt scale(btVector3(0.02, 0.02, 0.02)) LiverSBody gt getCollisionShape() gt setMargin(0.1) float Friction 0.9 float Restitution 0.5 LiverSBody gt setFriction(Friction) LiverSBody gt setRestitution(Restitution) m pSoftBodyWorld gt addSoftBody(LiverSBody) I'm using this class for loading and visualizing model https learnopengl.com code viewer gh.php?code includes learnopengl model.h I need to extract from the softBody some data (Position, normal, texCoords, tangent and bitangent) to fill the vertex buffer objects but i don't know where to find most of it... I know that the position and the normals are in the softbody nodes but i can't find the other information needed (texCoords, ..). btSoftbody.h struct Node Feature btVector3 m x Position btVector3 m q Previous step position btVector3 m v Velocity btVector3 m f Force accumulator btVector3 m n Normal btScalar m im 1 mass btScalar m area Area btDbvtNode m leaf Leaf data int m battach 1 Attached |
1 | Simple mouseray picking in openGL Ive been looking at tutorials and trying to figure out how to do basic ray picking. But I'm stuck at figuring out what space to do the distance calculations in. What space does glm unproject() lead to exactly? This is what I'm doing first I get the mouse unprojected, like so mouse ray start vec3 m uproj glm unProject( vec3(mouse xy .x glutGet(GLUT WINDOW WIDTH), mouse xy .y glutGet(GLUT WINDOW HEIGHT),0.0f), workshop.access gui() gt view mat(), workshop.access gui() gt proj mat(), glm ivec4(0, 0, glutGet(GLUT WINDOW WIDTH), glutGet(GLUT WINDOW HEIGHT))) end of ray vec3 m uproj2 glm unProject( vec3(mouse xy.x glutGet(GLUT WINDOW WIDTH), mouse xy.y glutGet(GLUT WINDOW HEIGHT), 1.0f), workshop.access gui() gt view mat(), workshop.access gui() gt proj mat(), ivec4(0, 0, glutGet(GLUT WINDOW WIDTH), glutGet(GLUT WINDOW HEIGHT))) Then I find its direction, mray, like so vec3 mouse ray normalize(m uproj2 m uproj) get mray direction And Im expecting to find the closest point to some object by using this calculation vec3 closest point mouse ray glm dot(locations i , mouse ray) closest point But locations seems to be in the wrong space? Or am I thinking about this the wrong way? Ive been looking around, but I cant find anywhere that explains just this part that I must be misunderstanding. the idea is to compare the distance between closest point and locations i , but the results are incorrect. Im getting something like this Where it should be red only if the cursor is over the square. What space does glm unproj() put my ray in anyway? And in what space should I put the objects that I want to pick highlight? |
1 | opengl z index changing does not zoom in I am making a simple opengl application where I have a cube and I want to move forward to it with the glTranslate3d function, where I change the z index. One would expect the object to get bigger because of the view but it does not My code glClearColor(0, 0, 0, 1) glClearDepth(1.0) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glViewport(0, 0, width, height) glMatrixMode(GL PROJECTION) glOrtho(30, width, 0, height, 100, 100) glMatrixMode(GL MODELVIEW) I have tried many things also I have been told that gluPerspective is out dated and should not be used.... EDIT it works when I rotate the object you can see how 3d it is p |
1 | What are the possible techniques to optimize the lighting pass in a deferred shading renderer? I am toying around with "modern" OpenGL (this is my first attempt, I am new to this) and I have been developping my own deferred shading renderer as an exercise. I am using an FBO with the following attachments DS Depth Stencil (GL DEPTH32F STENCIL8) RT0 Position (GL RGB16F) RT1 Normal (GL RGB16F) RT2 Albedo (GL RGB16F) RT3 Postprocessing buffer 0 RT4 Postprocessing buffer 1 Depth RT0, 1, 2 are filled first in one single geometry pass. Then for each light source (point lights only for now, spheres are used as light volumes) Stencil pass to limit light calculation to where it actually has an effect Light pass light contribution is accumulated in RT3 From this point on, I am only rendering a quad the size of the screen and fragment shaders are used to compute the next image. Albedo (RT2) and Light (RT3) are blended into RT4 I now have my lit image. I can enable more postprocessng shaders (FXAA, Depth of field, ...), in which case RT3 and RT4 are used for ping ponging. The thing is, even with no postprocessing, not that many lights (around 10) and a very simple scene (roughly 5k vertices), my frame rate drops like significantly as soon as I increase resolution or add more lights. It looks like my light pass is responsible for most of this but how can I track down what exactly is slowing everything down? Are there any tricks to optimize it? Is there anything I am missing? Thanks! Light Fragment Shader for reference uniform sampler2D position uniform sampler2D normal uniform float screenw uniform float screenh uniform vec3 light pos uniform vec3 camera pos uniform vec4 diffuse uniform vec4 ambient uniform vec4 specular uniform float outer radius uniform float inner radius float specular hardness 100.0 vec4 calc point light(vec3 p, vec3 n) vec3 light dir light pos p float d to light length(light dir) light dir normalize(light dir) vec3 eye dir normalize(camera pos p) vec3 half vec normalize(light dir eye dir) float attenuation (outer radius d to light) (outer radius inner radius) attenuation max(min(attenuation, 1.0), 0.0) vec3 c ambient.rgb ambient.a c diffuse.rgb max(dot(n, light dir), 0.0) diffuse.a c specular.rgb pow(max(dot(n, half vec), 0), specular hardness) specular.a return vec4(clamp(c, 0.0, 1.0) attenuation, 1.0) void main(void) vec2 texcoord gl FragCoord.xy vec2(screenw, screenh) vec3 p texture2D(position, texcoord).xyz vec3 n texture2D(normal, texcoord).xyz gl FragColor calc point light(p, n) |
1 | OpenGL Fragment Shader Interpolation Vs Inverse Calculation I have found openGL fragment shader tutorials on the web, some that use use inverse calculations to revert the fragment coordinate back to the world space and others that interpolate the position. With that said... Is there a difference between interpolated world space position and the actual world space position calculated using inverse matrices and the fragment window space coordinates? Does anyone know of any resources that would help me understand the mathematical differences between these two things, if they are different? If they aren't different, then why would anyone use inverse matrices instead of interpolating, which seems less expensive? I wrote a shader to test 1, but I cannot tell if rounding errors are to blame for the differences or not. Thanks! |
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 | How can I get my meshes to work with Bullet Physics? The problem is that I'm trying to use my meshes with Bullet Physics for the collision part of my game. When I attempted doing this method with my GLM(model loading library by nate robins) model, I get a segmentation fault in the debug, so I figured that it doesnt like the coordinate variables of the model. If i use blender to export my model as a collision file, what type of file should I use? I have heard of a .bullet exporter, but i dont know hot to integrate this python script into my Blender 2.5 program. |
1 | How to detect GLSL warnings? After compiling a shader with glCompileShader, I can call glGetShaderiv with GL COMPILE STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified. In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL COMPILE STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved? |
1 | Rendering a black and white image in OpenGL 1.1 Is there is any way that I can simple disable the color in OpenGL 1.1? Or can I "grey out" textures in LWJGL? |
1 | LWJGL Determining whether or not a polygon is on screen Not sure whether this is an LWJGL or math question. I want to check whether a shape is on screen, so that I don't have to render it if it isn't. First of all, is there any simple way to do this that I am overlooking? Like some method or something that I haven't found? I'm going to assume there isn't. I tried using my trigonometry skills, but it is hard to do this because of how glRotate also distorts the image a little for perspective and realism. Or, is there any way to easily determine if a ray starting from the camera, and going outward in a straight line intersects a shape? (I can probably do it with my math skillz, but is there an easier way?) By the way, I can easily determine the angle at which the camera is facing around the x and y axis. EDIT Or, possibly, I could get the angles of a vector from the camera to the object, and compare those angles to my camera angles. But I have a feeling that the distorts from glRotate and glTranslate would be an issue. I'll try it though. |
1 | OpenGL Positional 2D Texture Masking I have a simple 2D java game engine running using LWJGL. I have my own vertex and fragment shaders, and I'm able to render quads with textures. I want to be able to mask one quad using the texture from another quad. Example I have two quads with two different textures mapped to them. Quad A has a red circle texture. Quad B has a blue square texture. I want to use Quad A's red circle texture as a mask such that Quad B will only be visible if it is within Quad A's red circle texture. Here's an image showing what I want to do The problem is that I am always seeing the 'full overlap' no matter the position of the quads. I can never get that partial masking that I'm looking for. My shader logic is close to this version 150 core uniform sampler2D texture uniform sampler2D maskTexture in vec2 pass TextureCoord in vec2 pass MaskTextureCoord out vec4 out Color void main(void) other logic here to determine out Color if(pass MaskTextureCoord.x ! 1 amp amp pass MaskTextureCoord.y ! 1) if we have valid mask texture coordinates, we are masking vec4 maskColor texture(maskTexture, pass MaskTextureCoord) get the rgba values of the mask texture if(maskColor.a 0) if mask texture has no alpha, discard discard Do I need to pass location data of the masking quad into the shader? If so, how do I do that? EDIT ilmale's method using the stencil buffer worked for me! All I needed to add was a uniform boolean value to tell the shader if I was drawing a mask or not. Here's the relevant shader code if(isMask) if this is a mask, discard where texture alpha is 0 if(texColor.a 0) discard else out Color vec4(0, 0, 0, 0) make the rest transparent, so we don't see the mask texture |
1 | Only one triangle drawn I am trying to render a quad with gl render mode GL TRIANGLES with using element array buffer. Here is some code to explain process. Only the first 3 elements of indices array are drawn as expected. But following indices doesn't drawn at all. Mesh Creation glm vec3 vertices glm vec3( 1, 1, 0), glm vec3( 1, 1, 0), glm vec3(1, 1, 0), glm vec3(1, 1, 0) glm vec2 textures glm vec2(1, 0), glm vec2(0, 0), glm vec2(0, 1), glm vec2(1, 1) unsigned int indices 0, 1, 3, 3, 1, 2 Mesh mesh new Mesh(vertices, sizeof(vertices) sizeof(glm vec3), textures, sizeof(textures) sizeof(glm vec2), indices, sizeof(indices) sizeof(unsigned int), texture) Mesh Class Mesh Mesh(...) InitMesh(...) void Mesh InitMesh(vec3 vertices, unsigned int numVertices, vec2 textureCoords, unsigned int numTextureCoords, unsigned int indices, unsigned int numIndices) this gt numIndices numIndices Generate VAO and bind glGenVertexArrays(1, amp vaoID) glBindVertexArray(vaoID) Generate VBOs glGenBuffers(3, vboIDs) Bind Position Buffer, Buffer Position Data glBindBuffer(GL ARRAY BUFFER, vboIDs 0 ) glBufferData(GL ARRAY BUFFER, numVertices sizeof(vec3), vertices, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, 0) Buffer TextureCoord Data glBindBuffer(GL ARRAY BUFFER, vboIDs 1 ) glBufferData(GL ARRAY BUFFER, numTextureCoords sizeof(vec2), textureCoords, GL STATIC DRAW) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL FLOAT, GL FALSE, 0, 0) Buffer Indices Data glBindBuffer(GL ELEMENT ARRAY BUFFER, vboIDs 2 ) glBufferData(GL ELEMENT ARRAY BUFFER, numIndices sizeof(unsigned int), indices, GL STATIC DRAW) Unbind VAO glBindVertexArray(0) void Mesh Draw() glBindVertexArray(vaoID) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glDrawElements(GL TRIANGLES, numIndices, GL UNSIGNED INT, 0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(0) glBindVertexArray(0) |
1 | GL INVALID OPERATION in glGenerateMipmap(incomplete cube map) I'm trying to learn OpenGL and i'm using SOIL to load images. I have the following piece of code GLuint texID 0 bool loadCubeMap(const char baseFileName) glActiveTexture(GL TEXTURE0) glGenTextures(1, amp texID) glBindTexture(GL TEXTURE CUBE MAP, texID) const char suffixes "posx", "negx", "posy", "negy", "posz", "negz" GLuint targets GL TEXTURE CUBE MAP POSITIVE X, GL TEXTURE CUBE MAP NEGATIVE X, GL TEXTURE CUBE MAP POSITIVE Y, GL TEXTURE CUBE MAP NEGATIVE Y, GL TEXTURE CUBE MAP POSITIVE Z, GL TEXTURE CUBE MAP NEGATIVE Z for (int i 0 i lt 6 i ) int width, height std string fileName std string(baseFileName) " " suffixes i ".png" std cout lt lt "Loading " lt lt fileName lt lt std endl unsigned char image SOIL load image(fileName.c str(), amp width, amp height, 0, SOIL LOAD RGB) if (!image) std cerr lt lt FUNCTION lt lt " cannot load image " lt lt fileName lt lt " (" lt lt SOIL last result() lt lt ")" lt lt std endl return false glTexImage2D(GL TEXTURE 2D, 0, GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, image) SOIL free image data(image) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP R, GL CLAMP TO EDGE) glGenerateMipmap(GL TEXTURE CUBE MAP) glBindTexture(GL TEXTURE CUBE MAP, 0) return true When i call this, the images load successfully, but then i get an error in console OGL DEBUG message lt 1 gt 'API' reported 'Error' with 'High' severity GL INVALID OPERATION in glGenerateMipmap(incomplete cube map) BACKTRACE and no cubemap is displaying at all. Do you see any mistake in this code? |
1 | How can I clip my sprite as it passes through a portal in a 2D scenario, using OpenGL? This is a very simple question, but after a brief search and reading through the "similar questions" I could not yet find an answer. I'm creating a 2D game using OpenGL and came across a problem Let's say I wanted to create portals. An Entity can move into a portal A and come out of the corresponding portal B. Transforming the coordinates and velocity of the entity is easy, but this would create "hard" texture teleportation. Which means while half of the entity is in the A portal, it won't be rendered on the corresponding B side. How would I create a smooth transition? My first Idea was I define "exit" and "entry" zones containing the transformation function (Matrix). Now when an Entity enteres the exit zone the entity is also drawn at the entry zone using the transformation matrix relative the the entry exit zones. But drawing it twice would still give me the difficulty, that I need to clip the entity on the portals "backside". (The entity shall vanish behind portal A when entering). So my second thought was, that there should be a solution using (vertex?) shader? But how would such a shader look like? (Example code would be nice, but not neccessary. I'd rather want to have a "what the shader would do" answer). Would I define Uniforms (exit and entry zones) which the shader would clip transform ("move") the vertexes from? How does a typical solution for this clipping look like? Or where could I read some information about these kind of problems? I only found some to 3D versions, where the view of portal B should be rendered in portal A. But this does not solve the object moving through it problem...I think In my opinion changing the draw order, or rendering something above the backside of the portals is not the right way to go, since this could create strange behavior in certain situations. (Portal B is just behind portal A for example. One of both would be overdrawn I think.) |
1 | How to free the GPU from a long task? I'm developing an application that uses the GPU. Some tasks might be rather long (like a fragment shader with a loop). I have the impression that I can make the entire OS visually freeze by asking the GPU to perform a job that doesn't end. Of course, I'm not doing this on purpose, but when that accidentally happens, I have to force power off my machine and this is very difficult to debug. Some questions Is this behaviour normal? Or could this be a bug in the hardware or driver? Is there a technique to recover from this without force stopping my machine? Since the OS is still functioning (only not rendering), I could try to ssh into my machine and kill the process. Would that free the GPU from its job? Update I tried to ssh into my machine and sudo kill 9 pid , but didn't work. I would like to know if there is an OS independent answer for this. If there isn't, my setup is macOS, with OpenGL (running on Intel HD Graphics 3000). |
1 | OpenGL Maximal amount of debug string reached I was trying to check my current openGL code in gDEBugger, everything works fine. But, I get these messages Debug String gt gt gt gt gt gt gt gt gt 1 Debug String gt gt gt gt gt gt gt gt gt 2 Debug String gt gt gt gt gt gt gt gt gt 3 ... Debug String gt gt gt gt gt gt gt gt gt 497 Debug String Maximal amount of debug string reached (500 strings). Additional debug strings will be ignored What are these messages, everything in my code runs fine. But its troubling to see these debug strings. |
1 | OpenGL 4D textures with bilinear interpolation I want to use and interpolated 4D texture in OpenGL, i.e. a texture that is accessed with a texture coordinate vector (s, t, p, q) and interpolated linearly in every texture coordinate. The extension GL SGIS texture4D does exactly this. However, it is unsupported on literally every GPU I have access to. If the was a GL TEXTURE 3D ARRAY, I guess I could sample the appropriate 2 layers of a 3D array texture with the (s, t, p) coordinates and then manually interpolate in the q coordinate. However, there are only "ordinary" GL TEXTURE 2D ARRAY texture arrays. A possible solution is to treat the texture array as 2D array of 2D texture, sample the appropriate 4 layers with (s, t) and then manually interpolate in p and q. This method is somewhat constrained by GL MAX ARRAY TEXTURE LAYERS . I am also afraid of the relatively large number of 2D texture fetches required to fetch a single 4D texture value. Is there a simpler way of achieving 4D interpolated textures? |
1 | Model gets distorted when rotating the camera I'm currently developing my own 3d graphics engine and I'm having a hard time figuring out why my 3D models gets distorted when rotating the camera around. This is my projection matrix. I'm following the OpenGL's Model. def get projection mat(aspect ratio, camera) fov camera.fov z near camera.z near z far camera.z far top math.tan(fov 0.5) z near bottom top right top aspect ratio left right projection mat np.identity(4, dtype float) projection mat 0, 0 2 z near (right left) projection mat 0, 2 (right left) (right left) projection mat 1, 1 2 z near (top bottom) projection mat 1, 2 (top bottom) (top bottom) projection mat 2, 2 (z far z near) (z far z near) projection mat 2, 3 2 z far z near (z far z near) projection mat 3, 2 1 projection mat 3, 3 0 return projection mat This is my view matrix def camera matrix(self) camera matrix np.identity(4, dtype float) camera matrix 3, 0 self.left camera matrix 3, 1 self.up camera matrix 3, 2 self.forward camera matrix 3, 3 self.pos return camera matrix This is how I get the ViewProjection matrix projection mat get projection mat(self.aspect ratio, self.camera) view mat self.camera.camera matrix() view mat np.linalg.inv(view mat) self.view projection mat np.dot(projection mat, view mat) And, finally, this is the ViewProjectionModel matrix view projection model mat np.dot(model.transform mat.T, self.view projection mat) This is the method that I use to rotate the camera def rotate(self, yaw, pitch, degress True) rotation mat y helper.rotate matrix y(yaw, degrees) rotation mat x helper.rotate matrix x(pitch, degrees) rotation mat np.dot(rotation mat y, rotation mat x) self.forward np.dot(np.insert(self.forward, 3, 1), rotation mat) self.forward helper.normalized((self.forward self.forward 3 ) 3 ) self.up np.dot(np.insert(self.up, 3, 1), rotation mat) self.up helper.normalized((self.up self.up 3 ) 3 ) self.left np.dot(np.insert(self.left, 3, 1), rotation mat) self.left helper.normalized((self.left self.left 3 ) 3 ) A video demo, showing the problem To summarize, the order of multiplication is ProjectionMat X ViewMat x ModelMat x ModelFaces. If it isn't clear by now, I'm using Python for this project. Any help would be greatly appreciated. With best regards, Jo o Pedro EDIT Like this? directions, r np.linalg.qr(np.array( self.forward, self.up, self.left )) self.forward directions 0 self.up directions 1 self.left directions 2 |
1 | How can I improve the performance of this rendering code? I've created a practice application for rendering triangles squares cubes using VBOs. This is mainly so I can get it right before upgrading a 3D block world game I've written that currently is using display lists to cache block rendering. I have a 3D cube rendering with an interleaved VBO and I recreated a basic chunk block system that does the following Loads chunks in a 10x10 area Each chunk creates its own float buffer and adds 16x16x16 cube vertices, colors, texture coordinates. Each chunk then is rendered via its own VBO. The VBO rendering code, called per chunk, looks like this interleavedBuffer.flip() glGenBuffersARB(ib) int vHandle ib.get(0) glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glEnableClientState(GL TEXTURE COORD ARRAY) glBindBufferARB(GL ARRAY BUFFER ARB, vHandle) glBufferDataARB(GL ARRAY BUFFER ARB, interleavedBuffer, GL STATIC DRAW ARB) glVertexPointer(3, GL FLOAT, 32, 0) glColorPointer(3, GL FLOAT, 32, 12) glTexCoordPointer(3, GL FLOAT, 32, 24) glDrawArrays(GL QUADS, 0, vertexCount) glBindBufferARB(GL ARRAY BUFFER ARB, 0) glDisableClientState(GL COLOR ARRAY) glDisableClientState(GL VERTEX ARRAY) glDisableClientState(GL TEXTURE COORD ARRAY) ib.put(0, vHandle) glDeleteBuffersARB(ib) clear() This method renders everything perfectly, however it suffers from performance problems. A few chunks of 16x5x16 are fine, 60 fps. Increasing them to 16 3 and loading 10x10 chunks, the performance drops to 8fps. I'm preparing to use VBOs on a game that loads at most 20x20 chunks of 16x128x16 dimensions so I need resolve this performance issue. What are my choices? I have yet to look into interfaced indexed VBOs. I've heard those are good choices when rendering many of the same thing? My game currently uses display lists to cache chunk rendering, and I only refresh that cache when a block change is made that requires it. Is there something similar I can do with VBOs? For reference, my code for the chunk loading and chunk rendering can be perused. |
1 | Loading PNG textures for use in Android OpenGL ES1 I'm very new to Android and OpenGL coding (I have previously used ogre3d). I am trying to find an efficient way to load PNG textures. It is currently taking around 8 secs to load 3 512x512 textures on a fairly fast phone (Motorola Defy) There seems to be a problem with the texture being upside down (I used a Matrix to flip it below). Secondly, the order of the colour channels are incompatible, therefore each pixel needs changed. This (I believe) is the cause of the slowness, is there a way to make the BitmapFactory load it in a channel order that is compatible with opengl? Is there a better approach here? Here is the code Will load a texture out of a drawable resource file, and return an OpenGL texture ID private int loadTexture(GL10 gl, Context context, int resource, boolean loadMipMaps) We need to flip the textures vertically Matrix flip new Matrix() flip.postScale(1f, 1f) This will tell the BitmapFactory to not scale based on the device's pixel density BitmapFactory.Options opts new BitmapFactory.Options() opts.inScaled false Load up, and flip the texture Bitmap temp BitmapFactory.decodeResource(context.getResources(), resource, opts) Bitmap bmp Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true) temp.recycle() int id loadTextureFromBmp(gl,bmp, true) bmp.recycle() return id protected static int loadTextureFromBmp(GL10 gl, Bitmap bmp, boolean reverseRGB) ByteBuffer bb ByteBuffer.allocateDirect(bmp.getHeight() bmp.getWidth() 4) bb.order(ByteOrder.nativeOrder()) IntBuffer ib bb.asIntBuffer() for (int y bmp.getHeight() 1 y gt 1 y ) for (int x 0 x lt bmp.getWidth() x ) if (reverseRGB) int px bmp.getPixel(x,y) int alpha (px amp 0xFF000000) gt gt 24 int red (px amp 0xFF0000) gt gt 16 int green (px amp 0xFF00) gt gt 8 int blue (px amp 0xFF) ib.put((alpha lt lt 24) (blue lt lt 16) (green lt lt 8) (red)) ib.put(Integer.reverseBytes(bmp.getPixel(x, y))) else ib.put(bmp.getPixel(x,y)) ib.position(0) bb.position(0) int tmp tex new int 1 gl.glGenTextures(1, tmp tex, 0) int tex tmp tex 0 gl.glBindTexture(GL10.GL TEXTURE 2D, tex) gl.glTexImage2D(GL10.GL TEXTURE 2D, 0, GL10.GL RGBA, bmp.getWidth(), bmp.getHeight(), 0, GL10.GL RGBA, GL10.GL UNSIGNED BYTE, bb) gl.glTexParameterf(GL10.GL TEXTURE 2D, GL10.GL TEXTURE MIN FILTER, GL10.GL LINEAR) gl.glTexParameterf(GL10.GL TEXTURE 2D, GL10.GL TEXTURE MAG FILTER, GL10.GL LINEAR) return tex |
1 | Libgdx, TiledMap, and tearing My TiledMap tears when the window is specific sizes, resized, or the camera moves. The tileset is padded by 2px and have tried as high as 10px. Each tile is 70x70. Here are the pack.json settings, paddingX 2, paddingY 2, bleed true, edgePadding true, duplicatePadding true, maxWidth 4096, maxHeight 4096, filterMin Nearest, filterMag Nearest, ignoreBlankImages true, wrapX ClampToEdge, wrapY ClampToEdge, grid true, fast false Here is the code. Parameters params new Parameters() params.textureMinFilter TextureFilter.Nearest params.textureMagFilter TextureFilter.Nearest TileMap map new TmxMapLoader().load(file.getAbsolutePath(),params) So what am I doing wrong? If nothing, does that mean libgdx absolutely cannot handle TileMaps of any sort? |
1 | what happens with missing vertices in geometry shader I am relatively new to GLSL shader programming, and the documentation I found is unfortunately often inscrutable. I am having trouble understanding a few things with how geometry shaders fit into the pipeline. I am trying to implement silhouette detection by detecting boundary triangles in a geometry shader. A triangle is a boundary triangle if it is front facing and an adjacent triangle is back facing. The idea then is to emit additional camera facing triangles to outline them. For this purpose, I am looking at GL TRIANGLE ADJACENCY shaders, since they seem to fit the bill. Let's assume for the moment that I have already got the data loaded properly into the buffer. For clarity I plan on doing skinning and the Model View transform in the vertex shader, but to hold off on the perspective projection until I decide what to do in the geometry shader (this seems reasonable, but maybe I am wrong). Here is where the uncertainties start to come in. First of all, am I expected to manually perform backface culling at some shader stage? Second, if a triangle has incomplete adjacency information(only 2 out of three triangles for example), how is this conveyed to the shader? Does it just have a length less than 6 vertices? Third, what does the pass through shader (the one that does nothing special) have to perform? Do I emit every vertex in the input list, or just 3 from the first triangle? And again, am I supposed to allowed to cull backfaces? And last, if I decide to emit additional geometry, is there anyway to distinguish that from the (passed through) input geometry from the point of view of the fragment shader? I'd like to be able to texture map them separately if it is possible. If I am on the wrong path on any of this, of course feel free to let me know. In case it is important, I am using OpenGL 3.3. Based on my understanding and Nathan's answer, I could start with a passthrough shader that looks something like this layout(triangle adjacency) in layout(triangle strip, max vertices 14) out flat out float is border void main() gl Position gl in 0 .gl Position is border 0.0 EmitVertex() gl Position gl in 2 .gl Position is border 0.0 EmitVertex() gl Position gl in 4 .gl Position is border 0.0 EmitVertex() EndPrimitive() And then when if I add triangle strips for outlines, I will set is border 1.0 for each of those vertices. |
1 | Difference between Spherical Harmonics and Spherical Harmonics Lighting What is the difference between Spherical Harmonics and Spherical Harmonics Lighting in OpenGL? |
1 | OpenGL 4.4 LWJGL How can i render text to the screen I have been told that you need to create a texture atlas for the font, and individually assign each character to a texture and add them up to create the string you want to produce. This seems a little more difficult than it should be. Is there another way? If not there must be documentation or a library someone wrote to do this. Can someone help me out? |
1 | Beginning on animations I am clueless with regards to animations. I have a simple rendering engine that renders models, sprites, skyboxes and whatnot but everything is simply static with no animations whatsoever. With my engine written in C and OpenGL I will have to learn how to implement animations accordingly but any OpenGL book or tutorial I look for doesn't explain animations. It's probably one of those topics which being so complex requires its own book or something. Does anyone know any great resources to explain how I can programme animations? I'm not interested in learning how to design them, rather just the technical side of it, you know bones and all. I would also welcome tips as to the general concept of modern animations in OpenGL. If it also means much, I use assimp as my model loader. Suffice it to say, how does a programmer animate a model to 'run' or 'jump'? |
1 | How do I fix this access violation when I exit my custom OpenGL game engine? I'm writing an game engine, where the engine is written in a project and exports a .dll file. In another project, in the same solution as the engine, there is a sandbox project which uses the engine. However, there is a bug. I run the sandbox project in debug mode with the engine dll. When I spam my mouse and keyboard for a few seconds, and close the program via the exit button, the program crashes with an error Exception thrown at 0x00000043 in phantom sandbox.exe 0xC0000005 Access violation executing location 0x00000043.If there is a handler for this exception, the program may be safely continued. I found the source of the bug. Since I'm currently writing the engine for OpenGL, I have to initialize GLEW, and I need to create a HGLRC. If I don't initialize this HGLRC, everything works. This is not the ideal solution, since I need to use OpenGL for my engine. I went forth without exporting the .dll from the engine, making the engine an application, instead. I made a main.cpp, and wrote it to use the engine, enabling OpenGL rendering. I tried to recreate the bug, but everything works! I thought it might OpenGL, but then now I'm thinking it might be my engine. How do I fix this? Here is my code, where it errors int const main result invoke main() telemetry main return trigger(nullptr) if(! scrt is managed app()) exit(main result)l if(!has actor) lt this is the line being sent to the call stack cexit() scrt unititialize crt(true, false) return main result except ( seh filter exe(GetExceptionCode(), GetExceptionInformation())) int const main result GetExceptionCode() if(! scrt is managed app()) exit(main result) Here is the call stack |
1 | Problems with Rotation Matrices on Certain Axes Here is what my rotation matrix looks like public Matrix4f initRotation(float x, float y, float z) Matrix4f rx new Matrix4f() Matrix4f ry new Matrix4f() Matrix4f rz new Matrix4f() x (float)Math.toRadians(x) y (float)Math.toRadians(y) z (float)Math.toRadians(z) rz.m 0 0 (float)Math.cos(z) rz.m 0 1 (float)Math.sin(z) rz.m 0 2 0 rz.m 0 3 0 rz.m 1 0 (float)Math.sin(z) rz.m 1 1 (float)Math.cos(z) rz.m 1 2 0 rz.m 1 3 0 rz.m 2 0 0 rz.m 2 1 0 rz.m 2 2 1 rz.m 2 3 0 rz.m 3 0 0 rz.m 3 1 0 rz.m 3 2 0 rz.m 3 3 1 rx.m 0 0 1 rx.m 0 1 0 rx.m 0 2 0 rx.m 0 3 0 rx.m 1 0 0 rx.m 1 1 (float)Math.cos(x) rx.m 1 2 (float)Math.sin(x) rx.m 1 3 0 rx.m 2 0 0 rx.m 2 1 (float)Math.sin(x) rx.m 2 2 (float)Math.cos(x) rx.m 2 3 0 rx.m 3 0 0 rx.m 3 1 0 rx.m 3 2 0 rx.m 3 3 1 ry.m 0 0 (float)Math.cos(y) ry.m 0 1 0 ry.m 0 2 (float)Math.sin(y) ry.m 0 3 0 ry.m 1 0 0 ry.m 1 1 1 ry.m 1 2 0 ry.m 1 3 0 ry.m 2 0 (float)Math.sin(y) ry.m 2 1 0 ry.m 2 2 (float)Math.cos(y) ry.m 2 3 0 ry.m 3 0 0 ry.m 3 1 0 ry.m 3 2 0 ry.m 3 3 1 m rz.mult(ry.mult(rx)).getM() return this And here is how I've been implementing it for tests (using default orthographic perspective) public class Renderer private WorldMesh mesh private Mesh mesh private Matrix4f transform private Shader shader public Renderer() Setup Meshes mesh new WorldMesh() mesh ResLoader.loadMesh("pyramid.obj") mesh.addToBuffers( mesh) setup Shader shader new Shader() shader.addVertexShader(ResLoader.loadShader("basicVertex.vs")) shader.addFragmentShader(ResLoader.loadShader("basicFragment.fs")) shader.compileShader() shader.addUniform("transformation") temporary transformation matrix Matrix4f tran new Matrix4f().initTranslation(0, 0, 0) Matrix4f rot new Matrix4f().initRotation(0, 0, 0) problem is definitely with the rotation matrix Matrix4f scale new Matrix4f().initScale(1, 1, 1) transform tran.mult(rot.mult(scale)) public void update() public void render() RenderUtils.clearScreen() shader.setUniform("transformation", transform) shader.bind() mesh.draw(true) and finally here is my vertex shader version 330 layout (location 0) in vec3 position uniform mat4 transformation void main() gl Position transformation vec4(position, 1.0) The problem is that setting a rotation on any other axis other than Z (for some reason z axis rotation is working fine) does not function properly. An X axis rotation seems to be doing both an x and y rotation at the same time, causing a weird stretching affect. A Y axis rotation causes the mesh to completely disappear. The funny thing is that I've used this code over and over again and some projects don't give me a problem. The order of multiplication seems in order, and I made sure that OpenGL knows to transpose the matrix I give it when setting the uniform. Any ideas as to what could be causing the x and y axis rotations to completely fail? |
1 | how to calculate smooth normals for 10,000,000 vertices? I am trying to calculate smooth normals with angle weight for a huge mesh with 10 million vertices. Currently, i am using map dictionary to store the traingles connected to a vertex. That is, for each vertex, I loop through the entire mesh to find triangles connected to a single vertex and store them in a map for that vertex. I am doing this for 10 million triangles. So, i iterate 10 million x 10 million times to calculate normals for the whole mesh. It takes around 8 seconds to create the map itself. I also have to animate this mesh dynamically calculating the normals for 10 instances. Is there a possibility to move these computations to shaders? |
1 | Why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix? I'm working on a 2D game engine project, and I want to implement matrices for my transformations. I'm going to use the GLM library. Since my game is only 2D, I figured I only need a 3x3 matrix to combine the translation, rotation and scale operations. However, glm translation is only overloaded to return a 4x4 matrix, and never a 3x3. I thought a translation could be performed by using a 3x3 matrix why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix? |
1 | Can you specify which VBO EBO to use with glDrawElements? I'm creating a voxel like game. I'm not sure if I am using VBO EBO's correctly. I am creating a new VBO amp EBO for every chunk. This is done once, but chunks call a render function in every block inside, and the block calls glDrawElements (Is there a more efficient way?). How can I specify which VBO amp EBO each is supposed to use? Is this possible? Thank you! |
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 | Multithreaded Game Loop I'm trying to implement a multithreaded game loop. I already did that but had to use a few locks for that, which ruined the performance. After researching a bit I came up with this idea Instead of splitting the engines subsystems into different threads (e.g. physics, animation), all subsystems run on all threads. So when we got four CPUs, four threads are created, with each thread having one loop for all subsystems. So the single core game loop is copied on all four threads. These game loops are controlled by one other loop, which sends messages (or 'jobs', 'tasks') to one of these threads (depending on their usage) according to user input or scripts. This could be done with a double buffered command buffer. Only the rendering loop is alone in a thread for maximum rendering performance. Now I'm thinking of the best way to communicate with the rendering loop. The best idea I could come up with is to again use a command buffer and swap it when the rendering loop is complete. That way the rendering loop doesn't have to wait for any of the loops and can go on rendering. If the game loop hasn't finished when the rendering loop swapped the buffer, all commands after that will be executed in the next frame of the rendering loop. To make sure that all objects will be drawn even if the game loop hasn't finished, the rendering loop holds all objects that will be drawn and draws them until it gets the command to stop drawing them. My goal is to make the engine scalable to cpu numbers and make it to use all cores. Is this a way to do that? What is the best approach to this and how are modern engines handling this? |
1 | How can I add 3D animation to my Pygame window? I've developed a quiz game using Pygame but now I'm being asked to implement a 3D animation element (a game show host) to the game. I used Pygame as I was told it would be an easy enough language to learn and make something simple, however I see now that it seems very limited in terms of 3D animation. I've seen OpenGL being used with Pygame and what I need is for my game to run exactly as it is, but with the 3D element (game show host) added on the corner of the window for example. How can I use OpenGL in Pygame in order to do this? |
1 | Generating 3D like effect I'm making a 2D sidescroller game and want to give the blocks a 3D like effect. This way it looks like the player is walking on 3D blocks while walking on a 2D plane (thus having only x,y coordinates). I have already written the code to generate the terrain in 2D, but the 3D effect is now baked in. It looks like this At this moment the 3D effect is baked into the blocks, but I want to try to generate it. Is there a common way to achieve this 3D like effect while still staying 2D? Do I have to convert from 2D to 3D or is it also possible to do this with calculations shaders? EDIT The reason I want the top texture of the block separate of the block is because when the camera would go up, the top should get bigger as the camera sees more of the top of the block and the other way around when the camera goes down. |
1 | Maximum tile and texture size for tiled maps I'm currently making a game using libGDX and Tiled. Everything was running fine until I changed the tile size from 96x96 to 300x300. Most layers are still displayed correctly but the tiles of a single layer are just black. I guess that there may be a problem with the large tiles (as there are some tiles together in one tileset bitmap the texure is 2100x2100 large). Are there any upper limits for tiles and or tilesets regarding the bitmap and texture size? GL MAX TEXTURE SIZE returns 3379 on this machine. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.