OpenGLHow to fit a texture to a curved plane with GL CLAMP I'm trying to fit a texture on a curved plane made from some triangles with GL CLAMP, because GL CLAMP TO EDGE is not available in my OpenGL version, but the texture (512 x 512 pixels) appears so small when render glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP) If the u,v coordinates overflow the range 0,1 the image is repeated glTexParameterf(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) The magnification function ( quot linear quot produces better results) glTexParameterf(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) The minifying function glTexGeni(GL S, GL TEXTURE GEN MODE, GL OBJECT LINEAR) glTexGeni(GL T, GL TEXTURE GEN MODE, GL OBJECT LINEAR) glEnable(GL TEXTURE GEN S) glEnable(GL TEXTURE GEN T) I load the texture like this glTexEnvf(GL TEXTURE ENV, GL TEXTURE ENV MODE, GL DECR ) glTexImage2D(GL TEXTURE 2D, 0, 4, infoheader.biWidth, infoheader.biHeight, 0, GL RGBA, GL UNSIGNED BYTE, l texture) gluBuild2DMipmaps(GL TEXTURE 2D, 4, infoheader.biWidth, infoheader.biHeight, GL RGBA, GL UNSIGNED BYTE, l texture)


Light Attenuation Formula Derivation I understand that when sampling the brightness of a given point on the surface, a certain cutoff needs to be taken into consideration. Other words, when the light is further away, the intensity decreases. I came across the following formula that is used to compute the aforementioned attenuation 1.0 (1.0 a dist b dist dist) However, I have not been able to find out why and how this formula is derived. From the formula what I can understand is that as the distance get larger, the result will become smaller but how it is derived is beyond me. If distance takes an important role in the above formula, which helps determine the intensity, could we simply ignore a and b from the formula and simply use attenuation 1.0 (1.0 dist) ? Does anyone know how the formula is derived and the importance the values a and b play within the formula? Thanks.


Achieving a fixed frame rate with varying scenes I am working on an OpenGL 3D model viewer app for iOS. I have to load, view and navigate extra detailled 3D models on an iPad. I hardly achieve 2 fps, if i load and navigate a very complex model. I tried some optimizations like view frustum culling, area in pixel space, back face culling etc but still i am unable to improve the frame rate. I would like to set fixed frame rate to some X fps for my app and drop out all the objects which don't have enough time to render at run time. I would like to know if there is any algorithm to achieve this fixed frame rate. I would appreciate any ideas.


Stretching a tetragonal shape in a texture to a square object I'd like to write a fragment shader that stretches a tetragonal shape in a texture to a square shaped game object of mine. My problem is best described with a picture, seen below. The shader receives a texture and the four corners of the red tetragon, and I'd like to stretch the tetragon as such that that's the only thing that'll appear on my square object, nothing outside of it. In this example, the texture coordinates u and v (0, 0) would be transformed into (x1, y1), and in a similar fashion, (1, 1) would become (x4, y4). I don't know how I should go about this though. I've done my research, I believe bilinear interpolation could be what I'm looking for, but from what I can see, it would only work if my red tetragon was a rectangle, in other words if its four corners where (x1, y1), (x1, x2), (x2, y1) and (x2, y2), which is clearly not the case here as all my four coordinates are different. Any help from a little hint to a complete code solution would be welcome. Edit I did try implementing bilinear interpolation, however it did not work. Here are the equations from the wikipedia article that I tried modifying to my specific case What R1 and R2 correspond to can be also seen on the image on wikipedia, my math notation may not entirely be correct but I tried to make it as understandable as possible. This did not give me the result I was looking for, however. I tried setting the red tetragon to be a triangle by setting (x1, y1) to (0.5, 0.5) while the remaining three coordinates went in their corresponding corners), and while I was expecting the texture to be stretched in some way, the end result still was a crystal clear, non stretched picture (due to my testing circumstances, I can't tell the exact difference to when I set (x1, y1) to (0, 0), but the results were extremely similar). Edit 2 I'll also include the code from my fragment shader, for good measure. in vec4 tex in vec3 normal out vec4 fragmentColor uniform struct sampler2D colorTexture vec2 p1 vec2 p2 vec2 p3 vec2 p4 material void main(void) float x tex.x tex.w float y tex.y tex.w float x1 material.p1.x float x2 material.p2.x float x3 material.p3.x float x4 material.p4.x float y1 material.p1.y float y2 material.p2.y float y3 material.p3.y float y4 material.p4.y vec2 R1 (x3 x) (x3 x1) material.p1 (x x1) (x3 x1) material.p3 vec2 R2 (x4 x) (x4 x2) material.p2 (x x2) (x4 x2) material.p4 vec2 interpolatedPoint (R2.y y) (R2.y R1.y) R1 (y R1.y) (R2.y R1.y) R2 fragmentColor texture(material.colorTexture, interpolatedPoint) Here's what I see when I set p1 to (0, 0), p2 to (0, 1), p3 to (1, 0) and p4 to (1, 1) And here's the same image but with p1 set to (0.5, 0.5) The slight differences are only there because I had to position my camera manually, the two results are identical, even though in the second case I would expect to see an image that's clearly been stretched in some way.


TBN matrix for normal and parallax mapping I'd like to refer to this question because I didn't completely answer to my problem. I've implemented normal and parallax mapping but because of some assumptions I have to use two different TBN matrices for each effect. One of the most important assumptions is that I have deferred renderer with normals encoding and light calculations in view space. This implies that I have to convert data from normal maps (which are in tangent space) to view space using below TBN matrix mat3 NormalMatrix transpose(inverse(mat3(ModelViewMatrix))) vec3 T normalize(NormalMatrix Tangent) vec3 N normalize(NormalMatrix Normal) vec3 B normalize(NormalMatrix Bitangent) mat3 TBN mat3(T, B, N) On the other hand parallax mapping required view direction vector in tangent space. To compute that I use camera position and fragment position (in world space) multiplied by following TBN matrix to move this vectors from world space to tangent space T normalize(mat3(ModelMatrix) Tangent) N normalize(mat3(ModelMatrix) Normal) B normalize(mat3(ModelMatrix) Bitangent) mat3 TBN transpose(mat3(T, B, N)) I'm looking for a way to optimize that. Is it possible to make it better?


First person camera with Bullet Physics Before integrating the Bullet Physics, the camera worked fine. But instead of using my own simple struct for transform data, I use rigid body structs provided by the physics library now. There are two issue with the first person camera at the moment. First, it is stuck in the ground and when I try to move it, it slips back to it's position. Second, When I get the camera out of the ground, which sometimes happens, The applied rotation isn't in the way I move the mouse. When I move the mouse straight, the camera is moved in circles. This is how the rigid body it set up. float mass 1.0f btCollisionShape shape new btBoxShape(btVector3(0.5f, 0.5f, 0.5f)) btDefaultMotionState state new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, mass), btVector3(0, 0, 0))) btVector3 inertia shape gt calculateLocalInertia(mass, inertia) Body new btRigidBody(mass, state, shape, inertia) This is how I get and set rotations and positions of rigid bodies. vec3 Position() btVector3 pos Body gt getWorldTransform().getOrigin() return vec3(pos.getX(), pos.getY(), pos.getZ()) void Position(vec3 Position) btTransform transform Body gt getCenterOfMassTransform() transform.setOrigin(btVector3(Position.x, Position.y, Position.z)) Body gt setCenterOfMassTransform(transform) vec3 Rotation() vec3 rot Body gt getWorldTransform().getBasis().getEulerZYX(rot.z, rot.y, rot.x) return rot void Rotation(vec3 Rotation) btTransform transform Shape gt getCenterOfMassTransform() transform.setRotation(btQuaternion(Rotation.y, Rotation.x, Rotation.z)) Shape gt setCenterOfMassTransform(transform) And this is how I calculate the view matrix of the camera. const float pi glm pi lt float gt () if (Rotation().x lt pi) Rotation(vec3(Rotation().x pi 2, Rotation().y, Rotation().z)) else if (Rotation().x gt pi) Rotation(vec3(Rotation().x pi 2, Rotation().y, Rotation().z)) const float margin 0.2f if (Rotation().y lt pi 2 margin) Rotation(vec3(Rotation().x, pi 2 margin, Rotation().z)) else if (Rotation().y gt pi 2 margin) Rotation(vec3(Rotation().x, pi 2 margin, Rotation().z)) vec3 lookat( sinf(Rotation().x) cosf(Rotation().y), sinf(Rotation().y), cosf(Rotation().x) cosf(Rotation().y) ) cam gt View lookAt(Position(), Position() lookat, vec3(0, 1, 0)) How can I move and rotate a rigid body to use it as camera?


Drawing many separate lines using mouse OpenGL(GLFW glad) So, in order to draw a line, I track the coordinates of the mouse, then I add them to the array and capture it as GL LINE STRIP ADJACENCY. However, for example, I completed drawing a line1 at P1 and decided to start drawing a different line at P2 as shown in the figure, but my two points P1 and P2 joined together, how to fix it? Need to clear the array after drawing at the point P1, actually it doesn't help if I use glClearColor and glClear(GL COLOR BUFFER BIT).. Is there any other way?


Libgdx storing rendered frames quickly to use them later I have implemented a gif button for my libgdx game that allows the player to store the last few seconds of gameplay as a gif. It works by storing frames in memory, and encoding them into a gif if the player presses a Button. The problem is, that my method of storing the frames takes around 20ms, far to slow for my 60fps game. This leads to stuttering. Currently im storing the frames like this private static LinkedList lt Pixmap gt frames new LinkedList lt gt () private static float delay 0 static Pixmap pixmap static int width Gdx.graphics.getWidth() static int height Gdx.graphics.getHeight() called every frame public static void act(float delta) delay delta if (delay lt 0f) the actual storing of the frame. 20ms Gdx.gl.glPixelStorei(GL20.GL PACK ALIGNMENT, 1) pixmap new Pixmap(width, height, Pixmap.Format.RGBA8888) Gdx.gl.glReadPixels(0, 0, width, height, GL20.GL RGBA, GL20.GL UNSIGNED BYTE, pixmap.getPixels()) frames.add(pixmap) remove old frames and reset delay I have tried to allocate as little memory as possible but its still way to slow. Concurrency is not an option for this approach since the gl methods need to be called on the rendering thread. I would be very thankful for a solution or ideas for other possible ways to achieve my goal.


Creating and Destroying OpenGl objects dynamically I was trying to build a game like this and i want to create and destroy these ships at runtime , I have used GL QUADS and used an image to plot over the QUAD, how can I dynamically create multiple Quads,paste (ship) image over them and destroy them when they collide with the canon ball, thanks here is a chunk of code ship SOIL load OGL texture( "ship2.png", SOIL LOAD RGBA, SOIL CREATE NEW ID, SOIL FLAG INVERT Y ) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glColor3f(1, 1, 1) glBindTexture(GL TEXTURE 2D, ship) glBegin(GL QUADS) glTexCoord2d(0, 0) glVertex2d(450 x, 0) glTexCoord2d(1, 0) glVertex2d(500 x, 0) glTexCoord2d(1, 1) glVertex2d(500 x, 100) glTexCoord2d(0, 1) glVertex2d(450 x, 100) glEnd()


Is there a need to set the parameters again when updating a texture? Suppose that I'm developing the class COpenGLControl here in code guru to use it for showing a 2D texture in an MFC CPictureControl. and after applying some filters on the image, I will update the texture to show the filtered image on the picture control. I have set a rule for the clients of my class as follows Call function setImageWidthHeightType just first time of calling OnTimer and after setting pImage pImage is the rastetr data that will be provided by another classes that have been developed using OpenCV and GDAL libraries for the next calls of OnTimer and when updating pImage there's no need to call this function. If you do so, your client code slows down because the function InitializeTextureObject() is called in the setImageWidthHeightType function For second and more calls of OnTimer you should call updataTextureObject() function after setting pImage. In the first call of OnTimer and before calling setImageWidthHeightType, the function updataTextureObject() should not be called and if so, the program will encounter an unhandled exception because there you still don't have any texture object to be updated. any way I have used the following codes for the functions that are mentioned above OpenGLControl.h allocate texture name which will be an unsigned integer GLuint texture OpenGLControl.cpp Generate just one texture and bind it to the target void COpenGLControl InitializeTextureObject() wglMakeCurrent(hdc, hrc) glEnable(target) glGenTextures(1, amp texture) glBindTexture(target,texture) glTexParameteri(target,GL TEXTURE WRAP S,GL REPEAT) glTexParameteri(target,GL TEXTURE WRAP T,GL REPEAT) glTexParameteri(target,GL TEXTURE MAG FILTER,GL NEAREST) glTexParameteri(target,GL TEXTURE MIN FILTER,GL NEAREST) glTexEnvf(GL TEXTURE ENV,GL TEXTURE ENV MODE,GL REPLACE) glPixelStorei(GL UNPACK ALIGNMENT,1) glTexImage2D(target,level,internalformat,ImageWidth,ImageHeight,border,format,type, amp pImage 0 ) wglMakeCurrent(NULL, NULL) the question that roses up is that Is there a need to set the parameters again when updating texture because of using wglMakeCurrent(NULL,NULL) at the end of the function above? In other words should I write the function updataTextureObject() as this void COpenGLControl updataTextureObject() wglMakeCurrent(hdc, hrc) glEnable(target) glBindTexture(target,texture) glTexParameteri(target,GL TEXTURE WRAP S,GL REPEAT) glTexParameteri(target,GL TEXTURE WRAP T,GL REPEAT) glTexParameteri(target,GL TEXTURE MAG FILTER,GL NEAREST) glTexParameteri(target,GL TEXTURE MIN FILTER,GL NEAREST) glTexEnvf(GL TEXTURE ENV,GL TEXTURE ENV MODE,GL REPLACE) glPixelStorei(GL UNPACK ALIGNMENT,1) glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type, amp pImage 0 ) wglMakeCurrent(NULL, NULL) Or just as this void COpenGLControl updataTextureObject() wglMakeCurrent(hdc, hrc) glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type, amp pImage 0 ) wglMakeCurrent(NULL, NULL) What way is the correct one?


OpenGL white edges on cubes In a minecraft like game I'm making, I get white edges on my cubes It is much more noticeable in darker textures. The textures are being setup like this glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) Any help?


Running OpenGL app on Windows XP x86 produces incorrect texture colors I'm working with the Cen64 emulator and I compiled from source a x86 version that operates fine on Windows 10 x64. As soon as I run it on a Windows XP x86 machine the colors are then all incorrect. Here are some screenshots Running on Win 10 Running on Win XP SP3 The color format is set to GL UNSIGNED SHORT 5 5 5 1 and the internal format is GL RGBA glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, hres hskip, vres, 0, GL RGBA, GL UNSIGNED SHORT 5 5 5 1, buffer) I'm pretty new to configuring color packing formats but it appears like some color channels are getting swapped? Maybe some sort of endianness issue going from an x64 to an x86 architecture? Please let me know if I need to show more of my code to help debug the issue. Thanks for any help!


Reading from depth textures always returns 1 I create a packed depth stencil texture and attach it to a framebuffer like this glGenTextures(1, amp depthStencilTexture) glBindTexture(GL TEXTURE 2D, depthStencilTexture) set filtering to gl nearest, not shown cause not important glTexImage2D(GL TEXTURE 2D,0,GL DEPTH24 STENCIL8,width,height,0,GL DEPTH STENCIL,GL UNSIGNED INT 24 8,nullptr) ... create framebuffer and attach some color attachments glFramebufferTexture(GL FRAMEBUFFER,GL DEPTH STENCIL ATTACHMENT, depthStencilTexture,0) The creation of the framebuffer causes no OpenGL status errors. In terms of usage for depth and stencil testing, the texture attachment seems to work correctly. If I disable depth testing, I get the usual artifacts of objects in the back being drawn over objects in the front if they are drawn in the wrong order. If I disable stencil testing, the effects I'm using related to that don't work anymore (I'm masking out areas that shouldn't be lit by the lighting pass). Also, if I simply don't attach the depth stencil buffer to the framebuffer, the related tests stop working (as expected). However, reading from that texture in a shader always returns 1 if I read the depth part, and 0 if I read from the stencil part. I confirmed this via glReadBuffer(GL DEPTH STENCIL ATTACHMENT) and glReadPixels. All integers read show up as 0xffffff00, directly after clearing them via glClear and a black clearcolor and also after the screen is drawn full of stuff. Drawing to and reading from the rest of the attached textures (four color buffers for now) works fine. I have to note that I'm not actually manually drawing anything to the depth stencil attachment in the fragment shader when rendering I'm assuming OpenGL automatically draws depth and stencil values to the correct buffer. What could be the cause of these incorrect values showing up when reading from the texture?


sfml opengl, two objects of same class are sharing variables whenever I use the none default constructor, it only adds to the coordinates of the previous class(in an array) wall 1x1 wall 2 wall 1x1(0, 2, 0), first argument is x, second z, and third ry wall 1x1(1, 2, 0) the second object in the array will be behind the first object(by 2 z) and if I give the first object an ry of 90, all the other objects will have the same rotation. pragma once ifndef WALL 1X1 H include lt GL glew.h gt include lt SFML Graphics.hpp gt class wall 1x1 public wall 1x1() wall 1x1(float x, float z, float ry) wall 1x1() void up() private float m x float m z float m ry GLuint tex sf Image data endif and the .cpp class include "wall 1x1.h" GLfloat verts 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 GLfloat coords 0, 0, 2, 0, 2, 2, 0, 2 wall 1x1 wall 1x1() m ry 0 m x 0 m z 0 wall 1x1 wall 1x1(float x, float z, float ry) m ry 0 m x 0 m z 0 m x x m z z m ry ry data.loadFromFile("wall1.png") glGenTextures(1, amp tex) glBindTexture(GL TEXTURE 2D, tex) glTexImage2D( GL TEXTURE 2D, 0, GL RGBA, data.getSize().x, data.getSize().y, 0, GL RGBA, GL UNSIGNED BYTE, data.getPixelsPtr()) wall 1x1 wall 1x1() void wall 1x1 up() glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL TEXTURE COORD ARRAY) glVertexPointer(3, GL FLOAT, 0, verts) glTexCoordPointer(2, GL FLOAT, 0, coords) glBindTexture(GL TEXTURE 2D, tex) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTranslatef(m x, 0, m z) glRotatef(m ry, 0, 1, 0) glDrawArrays(GL QUADS, 0, 4) glDisableClientState(GL VERTEX ARRAY) glDisableClientState(GL TEXTURE COORD ARRAY) and the important parts in main wall 1x1 wall 2 wall 1x1(0, 2, 0), wall 1x1(1, 2, 0) .... wall 0 .up() wall 1 .up()


Drawing multiple objects from one Vertex Buffer Object in OpenGL OpenTK I am trying to experimenting drawing method using VBO in OpenGL. Many people normally use 1 vbo to store one object data array. I was trying to do something quite opposite which is storing multiple object data into 1 vbo then drawing it. There is story behind why i want to do this. I want to group many of objects as a single object sometime. However my code doesn't do the justice. Following is my pseudo code Data int vBO new int 1 vertex buffer objects triangleVertices new float 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, first triangle lineloop, positions in the middle of the screen. 3.0f, 1.0f, 0.0f, 2.0f, 1.0f, 0.0f, 4.0f, 1.0f, 0.0f, second triangle lineloop, positions on the left side of the first triangle. 3.0f, 1.0f, 0.0f, 4.0f, 1.0f, 0.0f, 2.0f, 1.0f, 0.0f third triangle lineloop, positions on the right side of the first triangle. Setting Up void init() GL.GenBuffers(1, vBO) GL.BindBuffer(BufferTarget.ArrayBuffer, vBO 0 ) GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) triangleVertices.Length), triangleVertices, BufferUsageHint.StaticDraw) GL.VertexPointer(3, VertexPointerType.Float, 0, 0) GL.EnableClientState(Array.VertexArray) Drawing void display() GL.Clear(ClearBufferMask.ColorBufferBit) GL.Clear(ClearBufferMask.DepthBufferBit) setting up camera and projection. float eyes 0.0f, 0.0f, 10.0f float target 0.0f, 0.0f, 0.0f Matrix4 projection Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f 3.0f, 0.1f, 100f) 45 degree 0.785398163 rads Matrix4 view Matrix4.LookAt(eyes 0 , eyes 1 , eyes 2 , target 0 , target 1 , target 2 , 0, 1, 0) Matrix4 model Matrix4.Identity Matrix4 MV view model GL.MatrixMode(MatrixMode.Projection) GL.LoadIdentity() GL.LoadMatrix(ref projection) GL.MatrixMode(MatrixMode.Modelview) GL.LoadIdentity() GL.LoadMatrix(ref MV) GL.Viewport(0, 0, glControlWindow.Width, glControlWindow.Height) GL.Enable(EnableCap.DepthTest) Enable correct Z Drawings GL.DepthFunc(DepthFunction.Less) Enable correct Z Drawings GL.MatrixMode(MatrixMode.Modelview) Draw drawTriangleLineLoops() Finally... GraphicsContext.CurrentContext.VSync true Caps frame rate as to not over run GPU glControlWindow.SwapBuffers() Takes from the 'GL' and puts into control void drawTriangleLineLoops() GL.BindBuffer(BufferTarget.ArrayBuffer, vBO 0 ) GL.VertexPointer(3, VertexPointerType.Float, 0, 0) GL.EnableClientState(ArrayCap.VertexArray) GL.DrawArrays(BeginMode.LineLoop, 0, 3) drawing first triangle lineloop, first vertex starts at index 0. GL.DrawArrays(BeginMode.LineLoop, 9, 3) drawing second triangle lineloop, first vertex starts at index 9. GL.DrawArrays(BeginMode.LineLoop, 18, 3) drawing third triangle lineloop, first vertex starts at index 18. GL.DisableClientState(ArrayCap.VertexArray) I expect 3 different triangles to be drawn, but only one was drawn. I don't know what went wrong.


Issues with the camera following the spline I am trying to make a roller coaster and currently I have created a spline class which loads a spline from a text file . So I have all the points and I have a Catmull Rom Spline function but I have trouble figuring how a proper track can be created from those points. Anyone done anything similar? edit Ok i think i will make it more clear now. I was working on it yesterday that's why i didn't reply sooner. First problem is that my camera is going off tracks. This is the path generated http prntscr.com ci9sud drawing it as GL LINE STRIP. I have a cameraUpdate function float t (float)TrackPointIndex (float)1000 TrackPointIndex point viewPoint tr gt over gt getInterpolatedSplinePoint(t) t (float)TrackPointIndex (float)1000 TrackPointIndex point nextPoint tr gt over gt getInterpolatedSplinePoint(t) std cout lt lt "viewPoint " lt lt glm to string(viewPoint) lt lt std endl std cout lt lt "nextPoint " lt lt glm to string(nextPoint) lt lt std endl if (TrackPointIndex 1000) TrackPointIndex 0 control gt bodyTranslation viewPoint control gt bodyRotation nextPoint which with the use of getInterpolatedSplinePoint(t) returns the viewPoint and the nextPoint which are points on the spline. Printing them proves they are indeed on the line. But since i am using GLM i update my camera with the glm lookAt function . So i thought that the first argument which is the camera position should be the viewPoint and the second one which is where the camera should be pointing at should be nextPoint . But that just doesn't work . cameraUpdate is called every 250ms or so but it is off tracks . Do i have to do any extra calculations to define where the camera should be or be looking at? That's my first problem. The second one is not really a problem because i have not started working on it yet. I want to know how can somebody generate from the path a fairly good looking rail track. Thanks. Edit2 I put a sphere to travel through the tracks and it seems to be working fine . Still if i try moving the camera along the path it does not . Anyone knows any way around this?


How to initialize OpenGL context with PyGame instead of GLUT I'm trying to start with OpenGL, using Python and PyGame. I'm going to use PyGame instead of GLUT to do all the initializing, windows opening, input handling, etc. However, my shaders are failing to compile, unless I specify exactly the version of OpenGL and profile. They do compile with GLUT initialization from the book glutInit() glutInitDisplayMode(GLUT RGBA) glutInitWindowSize(400, 400) this is what I need glutInitContextVersion(3, 3) glutInitContextProfile(GLUT CORE PROFILE) glutCreateWindow("main") But, with simple PyGame initialization like this pygame.init() display (400, 400) pygame.display.set mode(display, pygame.DOUBLEBUF pygame.OPENGL) which doesn't specify exact OpenGL version 3.3 and CORE PROFILE, the same program would fail when trying to compile shaders RuntimeError ('Shader compile failure (0) 0 2(10) error GLSL 3.30 is not supported. Supported versions are 1.10, 1.20, 1.30, 1.00 ES, and 3.00 ES n', ' n version 330 core n layout(location 0) in vec4 position n void main() n n gl Position position n n ' , GL VERTEX SHADER) My question is how do I do this initialization with PyGame?


How can I generate a view or projection matrix for OpenGL 3. I'm transitioning from OpenGL 2 to OpenGL 3. and to GLSL 1.5. I'm trying to avoid using the deprecated features. My question how do we now generate the view or projection matrix. I was using the matrix stack to calculate the projection matrix for me GLfloat ptr 16 gluPerspective(...) glGetFloatv(GL MODELVIEW MATRIX, ptr) then pass ptr via a uniform to the shader But obviously the matrix stack is deprecated. So this approach is not the best an option going forward. I have the 'Red Book', 7th ed, which covers 3.0 amp 3.1 and it still uses the deprecated matrix functions in it's examples. I could write some utility code myself to generate the matrices. But I don't want to re invent this particular wheel, especially when this functionality is required for every 3D graphics program. What is the accepted way to generate world,view amp projection matrices for OpenGL? Is there an emerging 'standard' library for this? Or is there some other hidden (to me) functionality in OpenGL GLSL which I have overlooked?


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


How to manage shaders? I've done some shader programming some time ago but only simple stuff. I'm especially interested in how do you manage shaders? Do you just write one of each kind, or do you need more of them? If so, how exactly do you split and managed them? Also I've recently read that all the transformation matrix operations I used in OpenGL(glPushMatrix, etc) are now deprecated and you need to manage your own matrices.Is that something you do in a vertex shader and how would I go about doing it correctly? Suggestions for books about this topic will be highly appreciated. Thank you.


Help in understanding atmospheric scattering shading I have a made a planet and wanted to make an atmosphere around it. So I was referring to this site Click to visit site I don't understand this As with the lookup table proposed in Nishita et al. 1993, we can get the optical depth for the ray to the sun from any sample point in the atmosphere. All we need is the height of the sample point (x) and the angle from vertical to the sun (y), and we look up (x, y) in the table. This eliminates the need to calculate one of the out scattering integrals. In addition, the optical depth for the ray to the camera can be figured out in the same way, right? Well, almost. It works the same way when the camera is in space, but not when the camera is in the atmosphere. That's because the sample rays used in the lookup table go from some point at height x all the way to the top of the atmosphere. They don't stop at some point in the middle of the atmosphere, as they would need to when the camera is inside the atmosphere. Fortunately, the solution to this is very simple. First we do a lookup from sample point P to the camera to get the optical depth of the ray passing through the camera to the top of the atmosphere. Then we do a second lookup for the same ray, but starting at the camera instead of starting at P. This will give us the optical depth for the part of the ray that we don't want, and we can subtract it from the result of the first lookup. Examine the rays starting from the ground vertex (B 1) in Figure 16 3 for a graphical representation of this. First Question isn't optical depth dependent on how you see that is, on the viewing angle? If yes, the table just gives me the optical depth of the rays going from land to the top of the atmosphere in a straight line. How to find the optical depth in the case where the ray pierces the atmosphere and goes through it to the camera? Second Question What is the vertical angle it is talking about...like, is it the same as the angle with the z axis as we use in polar coordinates? (I am having a very hard time understanding this angle) Third Question The article talks about scattering of the rays going to the sun..shouldn't it be the other way around? like coming from the sun to a point? Any explanation on the article or on my questions will help a lot. Thanks in advance!


Geometry Struct and glDrawElements currently I re write my codes and change them to make they are better. I have vertex struct like this struct SVertex float X, Y, Z struct STexCoord float U, V And I re wrote it like this struct SVertex int Flag, BoneID float Pos 3 float UV 2 When it comes to the render function, I just need to change it from glVertexPointer(3, GL FLOAT, 0, amp (Mesh i .Vertex 0 )) glTexCoordPointer(2, GL FLOAT, 0, amp (Mesh i .TexCoord 0 )) to glVertexPointer(3, GL FLOAT, sizeof (SVertex), amp (Mesh i .Vertex 0 .Pos)) glTexCoordPointer(2, GL FLOAT, sizeof (SVertex), amp (Mesh i .Vertex 0 .UV)) The problem comes from the triangle struct. I re wrote the Triangle from struct STriangle int X, Y, Z to struct STriangle int Flag, Group int V 3 , N 3 and I changed the glDrawElements from glDrawElements(GL TRIANGLES, Mesh i .TriangleTotal 3, GL UNSIGNED INT, amp (Mesh i .Triangle 0 )) to glDrawElements(GL TRIANGLES, Mesh i .TriangleTotal 3, GL UNSIGNED INT, amp (Mesh i .Triangle 0 .V)) And I got messed vertex with the new triangle struct. If I use the old ones, it is correct. How to pass the new triangle struct to the glDrawElements?


How to make natural looking voxel I'm developing a voxel game, but I think I use the wrong technique. I currently use flat tiles, to make blocks, and I think theres a better and more efficient way. I have seen a voxel game, which have naturally looking terrain. By that I mean non blocky. The game have 4 4 4 blocks per cubic meter, and blocks like dirt, sand and stone, have round edges, and kind of melt together (Like in ordinary games). Heres a screenshot How is this achieved?


Rotating a circle on its axis I have a circular shape object, which I want to rotate like a fan along it's own axis. I can change the rotation in any direction i.e. dx, dy, dz using my transformation matrix. The following it's the code Matrix4f matrix new Matrix4f() matrix.setIdentity() Matrix4f.translate(translation, matrix, matrix) Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix) Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix) Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix) Matrix4f.scale(new Vector3f(scale,scale,scale), matrix, matrix) My vertex code vec4 worldPosition transformationMatrix vec4(position,1.0) vec4 positionRelativeToCam viewMatrix worldPosition gl Position projectionMatrix positionRelativeToCam But, it's not rotating along its own axis, it is flipping like a coin instead. What am I missing here?


Environment mapping cube mapping using OpenGL I'm trying to do cube mapping. Problem is that I'm getting this This is what I get when I rotate it But it should look like this Here is code for vertex shader varying vec2 tex coord void main() vec3 v vec3(gl ModelViewMatrix gl Vertex) gl TexCoord 0 .stp normalize(gl Vertex.xyz) gl Position gl ModelViewProjectionMatrix gl Vertex gl ModelViewMatrix gl Vertex fragment shader uniform samplerCube tex void main() gl FragColor vec4(1.0, 1.0, 1.0, 1.0) gl FragColor textureCube( tex, gl TexCoord 0 .stp) Could you please tell me what am I doing wrong?


Shadowmapping with multiple light sources I am using shadow mapping to add shadows to my world. Currently, I use one lightsource, which means I have to draw my world twice once in the lightview, once in the camera view. I want to add more light sources to the world, I want at least 2 sources, maybe 3 or 4. My world geometry is large, roughly 1M triangles, so drawing them comes at a large cost. Are there any shortcuts I can take to avoid drawing the geometry for every light source? Would it be possible to write to multiple depth textures in a single pass? E.g. pass several lightview matrices to a vertex shader and somehow write several framebuffers in one go? I am using OpenGL core profile. What I've tried I looked at Multiple Render Targets, but it seems that every attached buffer will share the same vertex transformation, which would not help in my situation every light view has a different transformation.


Making a house in jogl java eclipse? here's what I'm trying to do One house, with 3 rooms, a window in two rooms, doors in the front and back of the house and into each room (the back door has to be through one of the rooms). I've added a picture as an example I'm using JOGL 2.0, in eclipse. Clarification my question is how do I code it in java using jogl? This is what I have so far glBegin(GL QUADS) Floor glVertex3f( 1, 1, 1) glVertex3f(1, 1, 1) glVertex3f(1, 1,1) glVertex3f( 1, 1,1) Ceiling glVertex3f( 1,1, 1) glVertex3f(1,1, 1) glVertex3f(1,1,1) glVertex3f( 1,1,1) Walls glVertex3f( 1, 1,1) glVertex3f(1, 1,1) glVertex3f(1,1,1) glVertex3f( 1,1,1) glVertex3f( 1, 1, 1) glVertex3f(1, 1, 1) glVertex3f(1,1, 1) glVertex3f( 1,1, 1) glVertex3f(1,1,1) glVertex3f(1, 1,1) glVertex3f(1, 1, 1) glVertex3f(1,1, 1) glVertex3f( 1,1,1) glVertex3f( 1, 1,1) glVertex3f( 1, 1, 1) glVertex3f( 1,1, 1) glEnd()


Implementing Valve's checkerboard rendering technique I've been trying to implement Valve's VR checkerboard rendering technique (original document) and was wondering which way would be the best to proceed. The thing is that I need to "abort" the execution of 2x2 blocks of fragments in a checkerboard pattern considering how GPUs work in blocks of pixels. I've thought of several approaches which are the following Discard fragments in the fragment shader using a condition like this one float mod2 gl FragCoord.x gl FragCoord.y float res mod(mod2, 2.0f) if (res 0.0f) discard Use the stencil buffer and write a checkerboard pattern on it using an image or such. Use some kind of clipping method where I have several quads in front of the camera forming a checkerboard pattern. The first approach seems to be the worse because I have to branch and after, discard fragments. And considering the fact that GPUs work in blocks of 2x2 pixels, I need to find a way to abort block by block so that I don't get the fragment shader processed anyway (even with a discard). And I'm not even sure this would force a block to abort and skip the fragment shader. The second method seems OK, but I'm not sure if there's a better way to do it. Would the fragment shader be processed anyway ? The third seems to need to process more polygons which is not really a good idea I guess even though it does not require a lot of processing considering they would be simple quads. What would be the most efficient method (listed here or not) for skipping these blocks ?


Problem with scrolling background in one OpenGL loop I have 960x3000 map image in png and I'm scrolling it in a loop like this (it's called in 60 FPS loop) glPushMatrix() glBindTexture( GL TEXTURE 2D, mapTex iBgImg ) glBegin(GL QUADS) double mtstart 0.0f fBgVPos (double)BgSize double mtend mtstart mtsize glTexCoord2d(0.0, mtstart) glVertex2f(fBgX, TOP MARGIN) glTexCoord2d(1.0, mtstart) glVertex2f(fBgX MAP WIDTH, TOP MARGIN) glTexCoord2d(1.0, mtend) glVertex2f(fBgX MAP WIDTH, BOTTOM MARGIN) glTexCoord2d(0.0, mtend) glVertex2f(fBgX, BOTTOM MARGIN) glEnd() glPopMatrix() unfortunately it isn't smooth when the game is in windowed mode. However, it is smooth in full screen mode. I'm using GLFW for windows. Maybe there is something wrong with my method? Is there anything better? Or could this be hardware problem? Edit Window is created using glfwOpenWindowHint(GLFW WINDOW NO RESIZE, GL TRUE) glfwOpenWindowHint(GLFW REFRESH RATE, 60) and main loop is using glfwSwapInterval(1) to ensure 60 FPS


Any idea why my openGL camera is stuttering only on the X axis? and only when using nvidia drivers? As part of my assignment, I've been building a scene graph framework in C OpenGL. My camera works absolutely fine going backwards and forwards, but when I strafe move on the X axis, the camera just starts stuttering. It doesn't make much sense to me, because it's the same principle to move back forward as it is to move right left. Everything is also normalised and being applied by deltaTime, so that's not an issue. Interestingly, this didn't happen when I was using my intel built in gpu, but only started occurring when I forced my nvidia card to handle the program. Here is a video of the aforementioned stutter https www.youtube.com watch?v DyTIv0yiaP0 amp feature youtu.be My scene graph is available for viewing on my GitHub The repo https github.com charliegillies fullmetal. The camera https github.com charliegillies fullmetal blob master fullmetal.cpp (line 503 730, mostly get set methods.) The camera controller https github.com charliegillies fullmetal blob master fullmetal helpers.cpp (line 14 204) Please note that this framework is still in its early days. Let me know what you think, and I'll be sure to post a fix if I find it.


SDL, SFML, OpenGL, or just move to Java I recently started a new project, and I'm wondering if I should change the technology now before it's too late. I'm using SDL with C , I have around 6 classes, and the game is going alright, but I got to this point where I have to rotate my sprite to make it point to the coordinates of the mouse. It's a 2D topdown game, so if I pre cached the images, I'd have to load 360 images, which is bad for memory. If I used SDL glx, I could do the rotation real time, but I heard it'd drop my frame rate very drastically, and I don't want my game to be slow. I also read I could use OpenGL, which is faster at these things. The problem is, how much would I have to change my code if I moved to OpenGL with SDL. So, I considered moving to a completely different language Java which is much simpler, and would allow me to focus on the game and handle networking much more easily than with C . I am very confused, and would like to hear your opinion thank you!


How to draw the simplest grid map OpenGL 1.0 I want to draw a simple black amp white grid map, like that I have been searching for a way to generate tile, a tile map and tho and I want to draw this map and thats all. I mean that I want to draw it only once so it should be easy. I use OpenGL 1.0. How can I draw that and how should I draw should I draw an Image and place it like a map, should I draw a tile and multiple it ?


Fixing T Junction artifacts in a BSP Editor I'm starting a little BSP engine, and have begun implementing Brush CSG. Currently I represent my brushes as the enclosed volume of surface planes (like old idTech 3 maps), with a cache for each face that is generated on rendering the brush for the first time. Now, I subtract a cube from another cube to cut a hole into it, yielding 5 brushes. Instantly, t junctions! As you can see below, visible cracks appear This isn't particularly surprising, and obviously moving onto the BSP compilation process I will have to fix up all the t junctions in the scene. However, I notice that in e.g. GtkRadiant, if I perform the same operation, these artifacts don't show up (or at least, I don't notice them), despite the fact the new brushes ARE separate and can even be moved apart and back together in the scene. How do I remove this rendering issue at map design time?


model view projection multiplication order I'm debugging a lighting problem where the camera position is effecting the diffused lighting component on my 3d model. In researching my problem I went back and am reading over all the how to documents. I found that one of my old sources (where I learned open gl 2.0) said this (summarized) When creating the modelViewProjection matrix you can't change the order or you'll get unexpected results. First take the View Matrix and post multiply it by the projection matrix to create a viewProjection matrix. Then post multiply the model matrix to get the modelViewProjection matrix. Looking at my code, all this time I haven't been doing this matrixMultiply(mView, thisItem gt objModel, mModelView) matrixMultiply(mProjection, mModelView, mModelViewProjection) As a test I tried changing it to this matrixMultiply(mView, thisItem gt objModel, mModelView) matrixMultiply(mProjection, mView, mViewProjection) matrixMultiply(mViewProjection, thisItem gt objModel, mModelViewProjection) ...but the result appears the same. EDIT To answer a question about what the matrices contain. A snapshot of the matrix values EDIT2 As a test I did the math both ways to compare the results and even with moving the camera and model around and rotating the model I'm getting the same results for the final ModelViewProjection.


How can I extract the RGB color data from a TGA image? I am working in OpenGL, and I am trying to create terrains using height maps. I am using my own functions to load a TGA image, and in order to pass data to heightmap vertex shader I need to retrieve RGB components from the TGA image. I am not quite sure how to do that, I saw in one tutorial that SDL library can be used to retrieve RGB component from a TGA image, but I do not want to use any such libraries because I am already able to load a TGA. So, how do I recover RGB information per pixel from a TGA that we loaded?


equirectangular panorama rendering? I want to render my scenes as equirectangular panorama frames. I can get the angular fisheye which is what I actually need by applying the rendered frame as a texture to a correctly UV mapped circle. But how can the scene be rendered as equirectangular panorama? I'm using a 3d engine which uses OpenGL and GLSL.


3Ds Max is exporting model with more normals than vertices I made a simple teapot with the "Create Standard Primitives" option and exported it as a collada file, ended up with this lt float array id "Teapot001 POSITION array" count "1590" lt float array id "Teapot001 Normal0 array" count "9216" For what I know there should be only one normal per vertex, am I wrong? What am I supposed to do with that much normals? Just put them on the normal buffer all at once normally?


Graphics API abstraction architecture I'm developing a 3D game engine in C and I was just wondering what are the different ways I can approach designing a graphics API abstraction. My original design was going to be something like this public interface IVertexBuffer IDisposable void Bind() if DRIVER TYPE OPENGL 45 public sealed class OpenGLVertexBuffer IVertexBuffer public void Bind() Bind buffer... public void Dispose() Delete buffer... endif if DRIVER TYPE OPENGL ES30 public sealed class OpenGLESVertexBuffer IVertexBuffer public void Bind() Bind buffer... public void Dispose() Delete buffer... endif In C , sadly pre processors don't work the same way they do in C , so I would have to compile two versions of my project, but that just seems hacky and I would much rather be able to switch between drivers types. So, I had another idea to do something like this public interface IRenderDevice IVertexBuffer CreateVertexBuffer(float vertexData, int sizeInBytes) void DestroyVertexBuffer(IVertexBuffer vertexBuffer) public sealed class OpenGLRenderDevice IRenderDevice public IVertexBuffer CreateVertexBuffer(float vertexData, int sizeInBytes) Create vertex buffer public void DestroyVertexBuffer(IVertexBuffer vertexBuffer) Destroy vertex buffer, or should I just call vertexBuffer.Dispose()? and then just use an enum to determine which render device to create, but I know this solution will quickly get out of hand when I begin to introduce other things like vertex arrays, index buffers, frame buffers, etc. What other options do I have that will still maintain readable code and look native to C ?


Intel GPU running faster than Nvidia GTX 1060 My app in its current state renders only 2 triangles to the screen using OpenGL. I am using std chrono steady clock for frame counting. With Intel graphics, I hit 1000fps and with my GTX 1060(6GB) I am getting an absurd frame rate of 480fps. I have used the Nvidia Optimus Enablement method to force renders on my GPU(reference http developer.download.nvidia.com devzone devcenter gamegraphics files OptimusRenderingPolicies.pdf) Why could this be happening? My shaders are under 60 lines of code, there seems to be nothing that is lagging my GPU from my CPU performance.


How do I know if memory isn't being handled right? My (2D) game's memory footprint seems to increase any time I load a texture, e.g. when I start my game it uses 30 mb private RAM, after transversing a 367mb background file, so it's all in RAM at some point, it increases to 54 mb private RAM. The same thing happens after going the same distance but going back and forth between two points repeatedly. However, my readouts are showing that the program is correctly calling glDeleteTextures about a second after textures go off screen and valgrind isn't finding any leaks. How do I know if I should be worried about this, or if it's just a quirk of how the OS pages memory?


Reset Camera view webgl I have camera rotating by dragging mouse. Im trying to add reset button that restart the scene to initial view. The rotating camera works as expected but I can't figure out how to reset it. The scene rotating in weird directions, not as expected. I have 2 vars absX, absY which hold the overall change angle value from the init mode. when reset applied mat4.rotate(getRotationCameraMat, degToRad( absX 10), 0, 1, 0 ) mat4.rotate(getRotationCameraMat, degToRad( absY 10), 1, 0, 0 ) absX 0 absY 0 apply the rotate mat4.multiply(mvMatrix, cameraRotationMat) the camera code var mouseDown false var prevMouseX null var prevMouseY null var cameraRotationMat mat4.create() mat4.identity(cameraRotationMat) function handleMouseDown(event) mouseDown true prevMouseX event.clientX prevMouseY event.clientY function handleMouseUp(event) mouseDown false var absX 0 var absY 0 function handleMouseMove(event) if (!mouseDown) return var currentX event.clientX var currentY event.clientY var deltaX currentX prevMouseX absX deltaX var newRotationMatrix mat4.create() mat4.identity(newRotationMatrix) mat4.rotate(newRotationMatrix, degToRad(deltaX 10), 0, 1, 0 ) var deltaY currentY prevMouseY absY deltaY mat4.rotate(newRotationMatrix, degToRad(deltaY 10), 1, 0, 0 ) mat4.multiply(newRotationMatrix, cameraRotationMat,cameraRotationMat) prevMouseX currentX prevMouseY currentY


Compress 16 bit raw data in webgl I have a 3D volume where every voxel is 16 bits. Is there anyway I can use some kind of compression to store the data so I can use less video ram? Webgl supported different compressiosn if you enable them with extension, but can I use them for a one channel data? Like WEBGL compressed texture s3tc only supports rgb and rgba data COMPRESSED RGB S3TC DXT1 EXT COMPRESSED RGBA S3TC DXT1 EXT COMPRESSED RGBA S3TC DXT3 EXT COMPRESSED RGBA S3TC DXT5 EXT If its not possible in webgl, is it supported in OpenGL to compress a 16 bit values with one channel?


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


Perspective Matrix doesn't work OpenGL 4 I tried to implement my own perspective matrix and it doesn't work. I don't understand why. With just with my view matrix (without Perspective Matrix) I can see my mesh. Here my view matrix Vec3f position(0.0,0.0, 5.0) Vec3f target(0.0,0.0,0.0) Mat4f Camera LookAt(Vec3f target, Vec3f position) ce dont j'ai besoin pour calculer les parametre de ma camera... Vec3f up world Vec3f(0.0,1.0,0.0) Vec3f forward (position target).normalize() Vec3f right up world.cross(forward).normalize() Vec3f up forward.cross(right).normalize() Mat3f R R.setCol(2,forward) R.setCol(0,right) R.setCol(1,up) R.transpose() Mat4f R4(R) Vec3f mp position 1.0f Mat4f P4 P4.setCol(3,mp) LookAt R4 P4 return LookAt And my Perspective Matrix Mat4f Camera perspective(float fovy, float aspect, float zNear, float zFar) float theta fovy 0.5f (180.f M PI) float range zFar zNear float invtan 1.f tanf(theta) Mat4f projMat(invtan aspect, 0.0f, 0.0f, 0.0f, 0.0f, invtan, 0.0f, 0.0f, 0.0f, 0.0f, (zFar zNear) range, 2 zNear zFar range, 0.0f, 0.0f, 1.0f, 0.0f) perspectiveCam projMat std cout lt lt perspectiveCam lt lt std endl return perspectiveCam Mat4f perspective(float fovy M PI 2, float aspect (1280.f 720.f) 1.f, float zNear 0.1f, float zFar 100.f) My shader is very simple so it can't be the problem.. version 410 core layout(location 0) in vec3 V position layout(location 1) in vec3 V color layout(location 2) in vec3 V normal uniform mat4 view matrix uniform mat4 proj matrix out vec3 color void main() color V color gl Position proj matrix view matrix vec4(V position, 1.) when I initialise perspectiveCam with the unit matrix 4x4 it displays my triangle.. but when I implement perspectiveCam like in the function it does not display my triangle Here my Set col function template lt typename TYPE gt void Mat4 lt TYPE gt setCol(int i, Vec4 lt TYPE gt amp vec4) for (size t k 0 k lt 4 k ) setElement(k,i, vec4.getElement(k)) void setElement(int i,int j, TYPE var) element i 4 j var TYPE getElement(int i, int j) const return element i 4 j


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


Handling metallic roughness maps colour channels I'm trying to use a metalness roughness workflow and I'm not sure how to translate the colour channels into the different metalness and roughness attributes. I'm not sure if there's a standard on how to encode that information and I can't find any online resources on how to treat the colour channels so I'm guessing that there is no standard. I have had materials which have used only the R and B channels and having the B channel set as 0 and I have had materials that somehow use all the RGB channels and I'm confused as to why they would need a third channel to determine metallness and roughness. My question is, how should I determine the format that the map is in and which channel corresponds to which attribute? Update I've already come to terms that I'll probably have to compile new shaders for different materials but I'm trying to figure out a way of identifying the format that a map is in. It would appear that for one of the models I'm using, it stores its bump map in the R channel. I didn't even know that was an option Update 2 I imagine I'll have to just delegate this to the asset pipeline and have the user select which channels to sample from. That or have a hardcoded format and make sure that any PBR materials imported follow that format


OpenGL dynamic font glyph cache library I have begun work on an OpenGL application (all on my own and with little knowledge) and started with FTGL, rendering true type fonts, which, with alot of text has a great impact on frames per second. I believe that to overcome this limitation one needs to generate a font atlas and save glyphs to opengl textures which are then drawn by shaders. I have done a search of github for such a library and found several, a few of which are incomplete (and by their own admission have memory leaks) I am looking for, and hoping that one of you can recommend, the most stable opengl font library that you preffer and does the aforementioned. I also need unicode support. Or a guide to help a noob like me achieve this Thankyou for reading


Why does texture sampling only work at (0,0,0)? I want to save the color of every point of one object in the RWTexture3D(UAV Resource) and transfer them to another object in its shader. I made a test in the two shaders. Both in the fragment shader. In first shader, I gave RWTexture3D lt float4 gt gUAVColor gUAVColor uint3(0,0,0) float4(1.0f,0.0f,0.0f,1.0f) In second shader Texture3D lt float4 gt gVoxelList float4 output gVoxelList.SampleLevel(SVOFilter, uint3(0,0,0),0) The result is correct, I got red as the result. But when I change the code, the texture cant be sampled correctly. In first shader, I gave RWTexture3D lt float4 gt gUAVColor gUAVColor uint3(1,0,0) float4(1.0f,0.0f,0.0f,1.0f) In second shader Texture3D lt float4 gt gVoxelList float4 output gVoxelList.SampleLevel(SVOFilter, uint3(1,0,0),0) I only changed the pos which save the red color from uint(0,0,0) to uint(1,0,0), but what I got changed to black, which means it's uncorrect. If I use gVoxelList uint(1,0,0) .xyz ,it works. I have no idea where the mistake will be.


Memory leak with glfwSetWindowTitle? I am using GLFW for a game, and I have a function which allows me to set the window title. PROBLEM WITH INCREASING MEMORY USAGE void WindowSystem setTitle( const string amp title ) glfwSetWindowTitle( window, title.c str() ) This function is called once during every iteration of the main program loop, so that I can have a basic FPS counter. Under Xcode the program memory usage increases faster and faster. If I replace title.c str() with a literal, the problem does not happen, i.e., the following does not cause the same memory usage growth. DOESN'T CAUSE PROBLEM void WindowSystem setTitle( const string amp title ) glfwSetWindowTitle( window, "Hello world!" ) This where the function is called. int SystemControl update() double time glfwGetTime() double timeStep time control gt lastUpdate control gt lastUpdate time float frameRate 1.0f timeStep string windowTitle std to string( frameRate ) control gt windowSystem gt setTitle( windowTitle ) control gt physicsSystem gt update( timeStep ) return OK The string title is allocated on the stack, and should be freed at the end of update. Could there possibly be a memory leak? I understand that the pointer for c str() is internally managed, and does not need to be freed.


Can instantiated objects have different material texture? While I have some experience with simple 2D games, I am new to more process demanding 3D games. One basic question that has been concerning me recently and for which I am having difficulties to find a proper detailed answer, is the following. I understand that when we instantiate an object, we are saving memory because the instantiated copy does not have to save mesh memory (like vertices' position, UV cood and normals). So, the instantiated copy only needs to save a transformation matrix in order to properly position, scale and rotate the mesh structure they share with the original mesh. But can the instantiated copies have different texture or material from the original mesh from which they were instantiated? If so, then it means the instantiated objects actually save with themselves more than transformation matrices. I would love to read more on that, so suggestions are welcome.


Ways to "invert Z axis" in shader based core profile OpenGL? In my hobbyist shader based (non FFP) GL (3.2 core) "engine", everything in world space and model space is by design "left handed" (and to stay that way), so X axis goes from 1 ("left") to 1 ("right"), Y from 1 ("bottom") to 1 ("top") and Z from 1 ("near") to 1 ("far"). Now, by default in OpenGL the NDC space works the same but the clip space doesn't, from what I gather, here z extends from 1 ("near") to 1 ("far"). At the same time I want to ideally keep using the "kinda sorta inofficial quasi standard" matrix functions for lookat and perspective, currently defined as func (me Mat4) Lookat(eyePos, lookTarget, upVec Vec3) l lookTarget.Sub(eyePos) l.Normalize() s l.Cross(upVec) s.Normalize() u s.Cross(l) me 0 , me 4 , me 8 , me 12 s.X, u.X, l.X, eyePos.X me 1 , me 5 , me 9 , me 13 s.Y, u.Y, l.Y, eyePos.Y me 2 , me 6 , me 10 , me 14 s.Z, u.Z, l.Z, eyePos.Z me 3 , me 7 , me 11 , me 15 0, 0, 0, 1 a aspect ratio. n near plane. f far plane. func (me Mat4) Perspective(fovY, a, n, f float64) s 1 math.Tan(DegToRad(fovY) 2) scaling me 0 , me 4 , me 8 , me 12 s a, 0, 0, 0 me 1 , me 5 , me 9 , me 13 0, s, 0, 0 me 2 , me 6 , me 10 , me 14 0, 0, (f n) (n f), (2 f n) (n f) me 3 , me 7 , me 11 , me 15 0, 0, 1, 0 So, for the lookat part to have my world space camera (positive Z) work with lookat (negative Z) as per this pseudocode world space position camPos cam.Pos normalized direction vector, up right forward are 1 not 1 camTarget cam.Dir lookat target camTarget.Add( amp camPos) invert both Z camPos.Z, camTarget.Z camPos.Z, camTarget.Z compute lookat matrix cam.mat.Lookat( amp camPos, amp camTarget, amp Vec3 0, 1, 0 ) That works well. Moving the camera in all 6 degrees of freedom produces correct on screen movement and correct new camera world space coords. But geometry is still inverted on the Z axis. When I position two boxes, A at ( 2, 1, 2), to appear near left and B (2, 1, 2) to appear far right, then A appears far left and B appears near right. Z is still inverted here. Now, these nodes have their own world space coords and update from those their own model to world matrices. I shouldn't invert posZ there as they form a hierarchy of sub nodes multiplying with their parents transforms and all that. They're still in model or world space, which as per my decree is to remain left handed. Their world to camera calculation happens on the CPU at my end, not in a vertex shader which just gets a single final (mvp clip space) matrix. When that happens multiplication of world space object matrix with clip space lookat and projection matrix at that point I need to somehow invert Z. What's the best way to do this? Or, more generally speaking, what's a common way that works? Do I have to modify the projection to accept left handed but output to GL right handed? If so, how? And then wouldn't I also have to modify lookat? Is there a smart way to do all this without having to modify the somewhat standard lookat projection matrices while also keeping model transform matrices in left handed coords?


Water effect using DuDv Map weird look I'm trying to apply a DuDv Map effect (distortions) on my water. My texture is 512x512 in size. I'm using the following code (Vertex Shader) out vec2 texCoord0 void main()... texCoord0 vec2(position.x 2.0 0.5, position.y 2.0 0.5) 6.0 (Fragment Shader) in vec2 texCoord0 void main() ... vec3 ndc (clipSpace.xyz clipSpace.w) 2.0 0.5 vec2 reflectTexCoords vec2(ndc.x, ndc.y) vec2 refractTexCoords vec2(ndc.x, ndc.y) vec2 distorsion1 (texture(dudvMap, vec2(texCoord0.x, texCoord0.y)).rg 2.0 1.0) waveStrength waveStrength 0.02 refractTexCoords distorsion1 reflectTexCoords distorsion1 vec4 reflectColor texture(reflectionTexture, reflectTexCoords) vec4 refractionColor texture(refractionTexture, refractTexCoords) outColor mix(reflectColor, refractionColor, 0.5) As you can see when I add my distortion to my reflection and refraction texture coordinates, it seems that something is wrong and can't figure what, because I get this effect Do any of you have any idea how can I fix this? Thanks for your time!


WinAPI SwapBuffers and Threads I'm trying to use a different Thread for the whole WinAPI Message Loop stuff, so the window always keeps being responsive. Of course I'm using the main thread as the "window thread", because I need a context before loading textures etc. and I can't just call Get PeekMessage for a different thread. Now there are a few things I'm wondering about though Can I use the OpenGL context handle from a different thread? I'm relatively sure I can since otherwise there would be no way to do multi threaded rendering, but maybe there's more to it. At some point I have to call SwapBuffers() from inside the render loop that means in this case, from a different thread. Can I just use the HDC I usually use? Is this handle thread safe? I'm not so sure about that, but I can't really find a definitive answer on the subject. If the answer is no, what would be a good method to deal with the issue? Maybe I can send a message from the render thread?


How can I determine a budget for RAM used (LRU involving VRAM, in particular) After some profiling, I've determined that one of my most expensive functions involves drawing text. As a solution, I'd like to implement a LRU type of cache that will "remember" the vertices, tex coords (etc) for a given string. This is particularly complicated because some of the resources involved reside in VRAM (most do, actually I take a given string and convert it into a long sequence of vertices tex coords indices), while some reside in plain RAM. If I knew what my limits were (in both respects) I could write a decent LRU cache system and probably buy myself a substantial performance gain. The primary target for this app is the Android platform, and as I understand it, most such devices share RAM with the GPU. I'd appreciate any answers to this, whether they directly answer my question or not.


How to pass array of dozens of floats to OpenGL 3.0 vertex shader? I use PyOpengl and Python 3. I have 50 thousand vertices. Position of each vertex could be calculated in vertex shader as version 300 es uniform v coefficients weights COEFFICIENTS AMOUNT in vec3 v coefficients COEFFICIENTS AMOUNT in vec3 v initial position out vec3 v position void main() v position v initial position v coefficients coefficients weights Amount of coefficients varies between 0 and 199 mdash it's not a problem for me to generate 200 vertex shaders to cover each situation. I need to change position of vertices tens of thousands times per application calls as fast as it's possible, so I cannot calculate them once on start. Though, I cannot provide arrays for each vertex because documentation says Attribute variables cannot be declared as arrays or structures. I see following solutions of this issue (will not work) hardcode suffices of variables names to emulate arrays use vectors with names like coefficients 000, coefficients 001, ..., coefficients 199 use matrices to have 4 vectors in each of variable mdash will it be better than previous solution with vectors (maybe performance of matrices product is faster than 4 products of vectors)? calculate vertices positions by myself using C NumPy calculate vertices positions by myself in parallel using OpenCL (will not work) store all coefficients in uniform int v coefficients COEFFICIENTS AMOUNT VERTICES AMOUNT and access needed ones according to vertex number, which will be stored in in int vertex id store coefficients in textures (proposed by HolyBlackCat). Are there any other solutions of my issue? Is there optimal solution in proposed above? Will I go out of memory if I will use 200 float 3 vectors for each vertex? I imagine the solution with hardcoded indices as version 300 es uniform v coefficients weights COEFFICIENTS AMOUNT in vec3 v coefficients 000 in vec3 v coefficients 001 ... in vec3 v coefficients 199 in vec3 v initial position out vec3 v position void main() v position v initial position v coefficients 0 coefficients weights 000 v coefficients 1 coefficients weights 001 ... v coefficients 199 coefficients weights 199


How do I pass textures into a fragment shader in Slick? I've written a shader that uses three different textures, tex0, tex1, and tex2. I can load it into Slick and successfully display it, but I can't figure out how to set the three different textures. Whichever texture I last load or set is the one used for all three. My code if (sp null) try sp ShaderProgram.loadProgram("passthrough.vert", "planet.frag") planet TextureLoader.getTexture("png", new FileInputStream("earth.png")) clouds TextureLoader.getTexture("png", new FileInputStream("clouds.png")) lights TextureLoader.getTexture("png", new FileInputStream("lights.png")) catch (Exception e) e.printStackTrace() System.exit(0) sp.bind() Attempt to set tex0 tex2. This fails and just sets everything to tex2. glUniform1i(sp.getUniform1i("tex0"), 0) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, planet.getTextureID()) glUniform1i(sp.getUniform1i("tex1"), 1) glActiveTexture(GL TEXTURE1) glBindTexture(GL TEXTURE 2D, clouds.getTextureID()) glUniform1i(sp.getUniform1i("tex2"), 0) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, lights.getTextureID()) sp.setUniform1f("time", tick 0.03f) sp.setUniform2f("resolution", 400f, 400f) Render a quad. This works, except that the textures are all the same. glBegin(GL QUADS) glVertex2i(0, 0) glVertex2i(0, 400) glVertex2i(400, 400) glVertex2i(400, 0) glEnd()


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.


Process of writing to the depth texture In openGL, let's say I output one single point from the vertex shader with this value gl Position vec4(2.0,3.0,5.0,7.0) what exact math operations happen to "z" after leaving the vertex shader? what will be the end value of that depth texel?


How to share values between different shader programs? I am using Unity but this might concerns all type of shaders. I would like to know if this is possible to share values between different shader pass.Let's imagine that I am computing something in the first pass and I would like to use this value in a second pass, is it possible ? If this is possible, how can I do that ?


Different way to pass uniforms to seperate draws in glMultiDrawElementsIndirect Given OpenGL version 4.3 and GLSL 430, what would be the best way to pass a matrix to each model in a draw call to glMultiDrawElementsIndirect? I am thinking of going the way of a TBO and indexing it based on my own attribute passed in to each model that tells the shader which draw call it is currently on. That technique is not my favourite as I have to create another buffer for something that should be basic functionality for the type of draw call (think gl DrawID), so I have come here to ask what I could do instead. (gl DrawID is not supported on my current system. Although it really should be AMD catalyst 14.4 with OpenGL 4.4 support)


Getting choppy, jumpy animation Hey I'm trying to get a smooth animation for my player movement. Earlier I changed my frames to render at fixed time(1 60 sec). Well that makes my player now run at a constant speed but the animation now appear to be choppy and it seems like the player jumps from one point to another instead of smoothly transitioning between them. Below is my code and an gif animation of player movement. How do I make the animation appear smooth? float deltaTime 0 float oldTime 0 The direction in which the player will move int playerX 0 int playerY 0 callback method for keyboard events void keyboard callback(GLFWwindow window, int key, int scancode, int action, int mods) if (key GLFW KEY W amp amp action GLFW REPEAT) playerX 0 playerY 1 if (key GLFW KEY S amp amp action GLFW REPEAT) playerX 0 playerY 1 if (key GLFW KEY D amp amp action GLFW REPEAT) playerX 1 playerY 0 if (key GLFW KEY A amp amp action GLFW REPEAT) playerX 1 playerY 0 update player's position void update() player gt move(playerX, playerY, TIME PER FRAME) set up glfw keyboard callback function and other stuff void init() glClearColor(0, 0, 0, 0) player gt bindVertexAttributes(shader.getAttributeLocation("position")) glfwSetKeyCallback(window gt getGLFWWindow(), keyboard callback) wait logic float expected frame end glfwGetTime() TIME PER FRAME void wait() while (glfwGetTime() lt expected frame end) expected frame end TIME PER FRAME playerX playerY 0 rendering function void render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) player gt setUniformMatrixLocation(shader.getUniformLocation("projectionMatrix"), shader.getUniformLocation("transformationMatrix")) shader.useProgram() update() player gt render() wait() shader.stopProgram() main function int main(int argc, char argv) init() main loop while (!glfwWindowShouldClose(window gt getGLFWWindow())) render() window gt swapBuffers() glfwPollEvents() glfwTerminate() return 0


Fragment shader working so strange the fragment shader is working so strange, can someone explain me whats going on. this one compiles fine but crashes when i use it version 330 core const float PI 3.14159265359 out vec4 coloroutfinal in vec3 fragpos uniform vec3 lightpos uniform vec3 camerapos vec3 wi vec3 normal float cosT uniform vec3 lightcolor vec3 incidentlight uniform float metallic uniform float roughness uniform vec3 albedo uniform float ao vec3 fresnel(float cosT,vec3 Fo) float ND(vec3 H,vec3 N,float roughness) float G(vec3 L,vec3 N,vec3 V,float roughness) void main() coloroutfinal vec4(1.0) vec3 fresnel(float cosT,vec3 Fo) return Fo (1.0 Fo) pow((1 cosT),5) float ND(vec3 H,vec3 N,float roughness) float roughness4 pow(roughness,4) float cosT max(dot(N,H),0.0) float cosT2 cosT cosT float num roughness4 float denom cosT2 (1.0 roughness4) 1.0 return num denom float GP(float cosT,float roughness) roughness 1.0 float r2 roughness roughness float k r2 8 float num cosT float denom cosT (1.0 k) k return num denom float G(vec3 L,vec3 N,vec3 V,float roughness) float cosTL max(dot(N,L),0.0) float cosTV max(dot(N,V),0.0) float GL GP(cosTL,roughness) float GV GP(cosTV,roughness) return GL GV but this one is just the same as above but no function definitions but works fine(renders my object in white) version 330 core const float PI 3.14159265359 out vec4 coloroutfinal in vec3 fragpos uniform vec3 lightpos uniform vec3 camerapos vec3 wi vec3 normal float cosT uniform vec3 lightcolor vec3 incidentlight uniform float metallic uniform float roughness uniform vec3 albedo uniform float ao vec3 fresnel(float cosT,vec3 Fo) float ND(vec3 H,vec3 N,float roughness) float G(vec3 L,vec3 N,vec3 V,float roughness) void main() coloroutfinal vec4(1.0) I never call the function so how are they interfearing. also both the shaders compile and link fine. can someone point me to the mistake?


How do I implement GPU based dynamic geometry LOD in OpenGL? I'm trying to implement LOD to boost my game's performance. I found a very nice tutorial. The basic concept that I think I understand is Get the distance from the camera to the object, check for the right LOD level and then render the object with the "right amount of instances". How do I implement that? The provided example code is a mystery to me... Some questions Is this a good method to implement LOD? Can someone please explain me detailed, how I have to implement it, with the queries and so on... I'm rendering all of my objects with GL11.glDrawElements(GL11.GL TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL UNSIGNED INT, 0) The example code uses GL POINTS. Can I implement it also with GL TRIANGLES?


Fixed Function vs Shaders Which for beginner? I'm currently going to college for computer science. Although I do plan on utilizing an existing engine at some point to create a small game, my aim right now is towards learning the fundamentals namely, 3D programming. I've already done some research regarding the choice between DirectX and OpenGL, and the general sentiment that came out of that was that whether you choose OpenGL or DirectX as your training wheels platform, a lot of the knowledge is transferrable to the other platform. Therefore, since OpenGL is supported by more systems (probably a silly reason to choose what to learn), I decided that I'm going to learn OpenGL first. After I made this decision to learn OpenGL, I did some more research and found out about a dichotomy that I was somehow unaware of all this time fixed function OpenGL vs. modern programmable shader based OpenGL. At first, I thought it was an obvious choice that I should choose to learn shader based OpenGL since that's what's most commonly used in the industry today. However, I then stumbled upon the very popular Learning Modern 3D Graphics Programming by Jason L. McKesson, located here http www.arcsynthesis.org gltut I read through the introductory bits, and in the "About This Book" section, the author states "First, much of what is learned with this approach must be inevitably abandoned when the user encounters a graphics problem that must be solved with programmability. Programmability wipes out almost all of the fixed function pipeline, so the knowledge does not easily transfer." yet at the same time also makes the case that fixed functionality provides an easier, more immediate learning curve for beginners by stating "It is generally considered easiest to teach neophyte graphics programmers using the fixed function pipeline." Naturally, you can see why I might be conflicted about which paradigm to learn Do I spend a lot of time learning (and then later unlearning) the ways of fixed functionality, or do I choose to start out with shaders? My primary concern is that modern programmable shaders somehow require the programmer to already understand the fixed function pipeline, but I doubt that's the case. TL DR As an aspiring game graphics programmer, is it in my best interest to learn 3D programming through fixed functionality or modern shader based programming?


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


OpenGL Attempt to allocate a texture too big for the current hardware I'm getting the following error java.io.IOException Attempt to allocate a texture to big for the current hardware at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java 320) at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java 254) at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java 200) at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java 64) at org.newdawn.slick.opengl.TextureLoader.getTexture(TextureLoader.java 24) The image I'm trying to use is 128x128. System.out.println(GL11.glGetInteger(GL11.GL MAX TEXTURE SIZE)) I get 32. 32??!! My graphics card is AMD Radeon HD 7970M with 2048 MB GDDR5 RAM, I can run all the latest games in 1080p and 60fps with no problem, and those textures sure as hell doesn't look like they are 32x32 pixels to me! How can I fix this? Edit Here's the chaos code I use to init OpenGL Display.setDisplayMode(new DisplayMode(500,500)) Display.create() if (!GLContext.getCapabilities().OpenGL11) throw new Exception("OpenGL 1.1 not supported.") Display.setTitle("Game") glMatrixMode(GL PROJECTION) glLoadIdentity() GLU.gluPerspective(45, 1, 0.1f, 5000) Mouse.setGrabbed(true) glMatrixMode(GL MODELVIEW) glLoadIdentity() glEnable(GL TEXTURE 2D) glClearColor(0, 0, 0, 0) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glHint(GL PERSPECTIVE CORRECTION HINT, GL NICEST) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnable(GL BLEND) glEnable(GL POINT SMOOTH) glEnable(GL LINE SMOOTH) glEnable(GL POLYGON SMOOTH) glEnable(GL POLYGON OFFSET FILL) glShadeModel(GL SMOOTH) Display is a LWJGL thing, it makes the OpenGL context and the window. Anyway, I don't think there's anything in the init code that can help me but you never know...


How to efficiently change VBO size? I have created a menu class and now I'm working on getting it to render using OpenGL's VBO's. The menu is fairly simple, it has a number of buttons, the user can press up and down to highlight the desired button and then press ENTER to go to the selected buttons sub menu which is just another instance of my menu. It should be noted that it doesn't need to have the same amount of buttons as the previous one. Pretty basic. What I've come up so far is this setting up the buffers and variables int amountOfVerticesButtons this.menu.getCurMenu().getNoButtons() ShapeRenderUtils2D.VERTICES RECT FloatBuffer vertexBufferButtons BufferUtils.createFloatBuffer(amountOfVerticesButtons VERTEX SIZE) FloatBuffer colorBufferButtons RenderUtils.createColorBuffer(0.5f, 0f, 0.5f, amountOfVerticesButtons) int amountOfVerticesBorders this.menu.getCurMenu().getNoButtons() ShapeRenderUtils2D.VERTICES FRAME FloatBuffer vertexBufferBorders BufferUtils.createFloatBuffer(amountOfVerticesBorders VERTEX SIZE) FloatBuffer colorBufferBorders RenderUtils.createColorBuffer(0.3f, 0f, 0.45f, amountOfVerticesBorders) filling up the buffers for (int i 0 i lt MAX BUTTONS PER PAGE amp amp i lt menu.getCurMenu().getNoButtons() i ) buttons vertexBufferButtons.put(ShapeRenderUtils2D.getRectVertices(new Point(point.x, point.y (i (BUTTON HEIGHT BUTTON SPACING))), MENU WIDTH, BUTTON HEIGHT)) button borders vertexBufferBorders.put(ShapeRenderUtils2D.getFrameRectangle(new Point(point.x, point.y (i (BUTTON HEIGHT BUTTON SPACING))), MENU WIDTH, BUTTON HEIGHT)) vertexBufferButtons.flip() buttons handles RenderUtils.createHandles(vertexBufferButtons, null, colorBufferButtons, amountOfVerticesButtons) vertexBufferBorders.flip() borders handles RenderUtils.createHandles(vertexBufferBorders, null, colorBufferBorders, amountOfVerticesBorders) This code is run once in the constructor and it sets up the VBO for my buttons, and creates a color array with one color for each button. My question is When the user presses ENTER, a new menu becomes active. The new menu doesn't have to have as many buttons as the previous one, so the old VBO is worthless, because it is of different size. I detect that the menu changes and what I basically do is to run the above code again, for the new menu, but at the end before I flip and create Handles I first do RenderUtils.deleteHandles(buttons handles) RenderUtils.deleteHandles(borders handles) Which removes the handles to the old VBO's. And then I create new ones just like I did the first time, but this time with correct size. This seems very ineffective. Is there a better way to do it? Is there a better way to change an existing VBO's size? EDIT Please note that I've got everything else done with the menu. I only have problems with the VBO rendering. Also, there may be a very large amount of buttons, with many sub menus that also contain large amounts of buttons, so creating a separate VBO for each case is not possible.


LWJGL texture bleeding fix won't work I tried a lot of things to fix texture bleeding, but nothing works. I don't want to add a transparent border around my textures, because I already got too many and it would take too much time and I can't do it with code because I'm loading textures with slick. My textures are seperate textures and they seem to wrap on the other side (texture bleeding). Here are the textures that are "bleeding" The head, body, arm and leg are seperate textures. Here's the code I'm using to draw a texture public static void drawTextureN(Texture texture, Vector2f position, Vector2f translation, Vector2f origin,Vector2f scale,float rotation, Color color, FlipState flipState) texture.setTextureFilter(GL11.GL NEAREST) color.bind() texture.bind() GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE WRAP S, GL12.GL CLAMP TO EDGE) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE WRAP T, GL12.GL CLAMP TO EDGE) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE MAG FILTER, GL11.GL NEAREST) GL11.glTexParameteri(GL11.GL TEXTURE 2D, GL11.GL TEXTURE MIN FILTER, GL11.GL NEAREST) GL11.glTranslatef((int)position.x, (int)position.y, 0) GL11.glTranslatef( (int)translation.x, (int)translation.y, 0) GL11.glRotated(rotation, 0f, 0f, 1f) GL11.glScalef(scale.x, scale.y, 1) GL11.glTranslatef( (int)origin.x, (int)origin.y, 0) float pixelCorrection 0f GL11.glBegin(GL11.GL QUADS) GL11.glTexCoord2f(0,0) GL11.glVertex2f(0,0) GL11.glTexCoord2f(1,0) GL11.glVertex2f(texture.getTextureWidth(),0) GL11.glTexCoord2f(1,1) GL11.glVertex2f(texture.getTextureWidth(),texture.getTextureHeight()) GL11.glTexCoord2f(0,1) GL11.glVertex2f(0,texture.getTextureHeight()) GL11.glEnd() GL11.glLoadIdentity() I tried a half pixel correction but it didn't make any sense because GL12.GL CLAMP TO EDGE. I set pixelCorrection to 0, but it still wont work.


Deferred lighting and point light volumes I'm doing deferred point light shadow mapping and I am drawing my point lights using light volumes. Normally I access the position diffuse texture normals using this in the fragment shaders vec2 texcoord gl FragCoord.xy UnifPointLightPass.mScreenSize vec3 worldPos texture(unifPositionTexture, texcoord).xyz vec3 normal texture(unifNormalTexture, texcoord).xyz vec3 diffuse texture(unifDiffuseTexture, texcoord).xyz When doing directional lights, I just draw a fullscreen rectangle, but when doing point lights I use light volumes drawing a 3d sphere from the cameras point of view to limit the amount of fragments processed. Does light volumes change the way I get the texcoord?


How can I create a pixellated, limited palette appearance in modern OpenGL? I wanna get some old art style (256 color, dithering, etc) in modern OpenGL in an effective way. Maybe using a low resolution (320x240) rendered at a bigger space so that the pixels looks "bigger?" I'd just like to fake this old style on modern GPUs.


Passing data into a vertex shader for perspective divide In OpenGL and GLSL, I am just learning about perspective projection and the vertex shader. However, I am a little confused about what data actually needs to be passed to the vertex shader, and what needs to be done in the shader code itself. I have two questions Suppose I have a triangle defined in 3D coordinates (x,y,z). Do I need to pass a 4D vector with values (x,y,z,w), where w z? Or do I just pass the 3D vector? The reason I ask is that I know that somewhere in the pipeline, the x and y coordinates are divided by the w component, in the perspective divide. In the vertex shader code, do I need to manually divide the x and y components by the w component myself? Or is this taken care of automatically? Thanks!


Can't render to FBO using a shader I've added functionality so that I can render to a framebuffer (for post processing and stuff). I can successfully render to my framebuffer and then render that framebuffer, but anything with a shader does not render to my framebuffer. Rendering with the same shader worked before I added the framebuffer step. Here's how I create my framebuffer create the color texture colorBuffer GL.GenTexture() GL.BindTexture(TextureTarget.Texture2D, colorBuffer) GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, width, height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero) GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear) GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear) create the depth texture depthBuffer GL.GenTexture() GL.BindTexture(TextureTarget.Texture2D, depthBuffer) GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Depth24Stencil8, width, height, 0, PixelFormat.DepthStencil, PixelType.UnsignedInt, IntPtr.Zero) GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear) GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear) create the fbo GL.GenFramebuffers(1, out fbo) GL.BindFramebuffer(FramebufferTarget.Framebuffer, fbo) GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, colorBuffer, 0) GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, TextureTarget.Texture2D, depthBuffer, 0) GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0) And this is my shader code VERTEX SHADER version 330 uniform mat4 world uniform mat3 worldIT uniform mat4 view uniform mat4 projection uniform mat4 textureTransformation in vec3 rPosition in vec3 rNormal in vec2 rTexCoord in vec3 rColor out vec3 vWorldPosition out vec3 vNormal out vec2 vTexCoord out vec3 vColor void main(void) vec4 tempWorld world vec4(rPosition, 1.0f) gl Position projection view tempWorld vWorldPosition tempWorld.xyz mat3 normalSpace mat3(world) vNormal normalize(normalSpace rNormal) vTexCoord (textureTransformation vec4(rTexCoord, 0.0f, 1.0f)).xy vColor rColor FRAGMENT SHADER version 330 uniform sampler2D colorMap in vec3 vWorldPosition in vec3 vNormal in vec2 vTexCoord in vec3 vColor out vec4 fColor const vec3 ambientLight vec3(0.1f, 0.1f, 0.1f) const vec3 lightDir vec3(0.0f, 1.0f, 1.0f) const vec3 lightColor vec3(1.0f, 1.0f, 1.0f) void main(void) vec4 texel texture(colorMap, vTexCoord) vec3 n normalize(vNormal) vec3 l normalize(lightDir) float nDotL max(dot(n, l), 0.0f) vec4 diffuse vec4((ambientLight nDotL lightColor) vColor, 1.0f) texel vec4 specular vec4(0.0f, 0.0f, 0.0f, 0.0f) fColor diffuse specular EDIT It seems to be that, for some odd reason, my shader stopped outputting at all when I added the framebuffer support.


OpenGLES 2.0 batching method and do not draw inactive object I am researching about "batching" objects for one big VBO and reduce draw call. These are what I am doing now Create interleaved VBO based on texture or render state (like Blending) So, for example, there will be two separate VBO and draw call if I want only some object has blending For more batching, add unused vertex data. eg) Object "A" doesn't need to have color data, but I added white empty color, so can be batched in interleaved array For hiding object, set vertex positions to 0.0. So, stay on the array, but cannot see. eg) if it is quad, set to 0.0, 0.0, 0.0, 0.0 These are my questions Should I create one Giant VBO, and use draw call based on offset?? If I do that, then is there any limitation on glbufferData?? (or performance drop, if too much data in) Is there any method that vbo can contain different types of interleaved vertex? Is multiple "offset" draw call not affect performance unlike single draw call? Should I bind multiple texture atlas to each unit, and use uniform? Currently, I am only binding one texture per draw. Is there correct way for above 3 method?? (Feels like not correct) I am updating "All" vertices every frame, even though some object doesn't need to be updated. (glBufferData) Should I do multiple update call?? Sorry for my wording, but please point me anything that I am doing something wrong. Thank you.


When drawing transparent object in OpenGL it cuts some sides of other object? I am making some OpenGL program, and I have a lost of cubes next to each other like this When I am making this hole, I am just skipping those cubes, just don't draw them. for (int i 0 i lt NUM OF CUBES i ) for (int j 0 j lt NUM OF CUBES j ) if ((i 3 amp amp j 3) (i 4 amp amp j 3) (i 3 amp amp j 4) (i 4 amp amp j 4)) continue cubes i j .draw(true) The result is But when I make those cubes invisible, by setting alpha to 0, the result is The code is for (int i 0 i lt NUM OF CUBES i ) for (int j 0 j lt NUM OF CUBES j ) if ((i 3 amp amp j 3) (i 4 amp amp j 3) (i 3 amp amp j 4) (i 4 amp amp j 4)) cubes i j .draw(true) else cubes i j .draw(false) true false fleg which I send to draw function just sets alpha to 0 or 1, if true alpha coordinate of glColor4f is set to 0, and if false is sent alpha coordinate is set to 1. Does anyone have idea why it looks like some sides of the other cubes are cut? Like they don't exist.


How do I crop a camera's viewport? I'm making an Android game using LibGDX. I would like to render a cropped version of the camera's viewport. Here's an original camera view (in 3ds max) I can get the same view in LibGDX without any problems, with this code perspCam new PerspectiveCamera(40, screenHeight, screenWidth h w) perspCam.position.set(1, 6, 18f) perspCam.lookAt(1, 3, 1f) perspCam.update() Now the tricky part I actually want to see this view in game It's basically just a crop of the camera viewport, keeping the original perspective and other camera properties. Could someone explain the general concept? (No need for working code.)


GLSL Efficient Point inside Box Check I'm attempting to improve the performance of a shader that changes the colour of a region of the world that is inside a "zone". I am using a deferred lighting system, so the colour and world space position of each pixel on the screen are stored in two separate textures, gColor and gPosition. The zonePos uniform stores the two corners of each zone. The zoneColor uniform stores the colour of each zone. The totalZones uniform stores the amount of zones in the current game. Here is the fragment shader out vec4 FragColor in vec2 texCoords layout (binding 0) uniform sampler2D gColor layout (binding 1) uniform sampler2D gPosition uniform vec3 zonePos 10 uniform vec3 zoneColor 5 uniform int totalZones void main() vec3 FragPos texture(gPosition, texCoords).rgb vec3 Albedo texture(gColor, texCoords).rgb vec3 j vec3 k for (int i totalZones i gt 0 i ) j zonePos i 2 k zonePos i 2 1 if (FragPos.x gt j.x amp amp FragPos.x lt k.x amp amp FragPos.y gt j.y amp amp FragPos.y lt k.y amp amp FragPos.z gt j.z amp amp FragPos.z lt k.z) Albedo zoneColor i FragColor vec4(Albedo, 1.0) The changes I have made so far are Using j and k, rather than accessing zonePos 6 times in the if statement Looping down from totalZones to 0, as a comparison against 0 is faster Any suggestions are greatly appreciated.


Bullet physics with OpenGL I have got some problem implementing bullet physics into my opengl game. The thing is that it doesn't want to update my translatef value continously but only at the end. The code for bullet looks like this void CGL initPhysics( void ) broadphase new btDbvtBroadphase() collisionConfiguration new btDefaultCollisionConfiguration() dispatcher new btCollisionDispatcher(collisionConfiguration) solver new btSequentialImpulseConstraintSolver dynamicsWorld new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration) dynamicsWorld gt setGravity(btVector3(0, 10,0)) ballShape new btSphereShape(1) pinShape new btCylinderShape(btVector3(1,1,1)) pinShape gt setMargin(0.04) fallMotionState new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0))) btScalar mass 1 btVector3 fallInertia(0,0,0) ballShape gt calculateLocalInertia(mass,fallInertia) btCollisionShape groundShape new btStaticPlaneShape(btVector3(0,1,0),1) btDefaultMotionState groundMotionState new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0, 1,0))) btRigidBody btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0)) btRigidBody groundRigidBody new btRigidBody(groundRigidBodyCI) dynamicsWorld gt addRigidBody(groundRigidBody) btRigidBody btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia) btRigidBody fallRigidBody new btRigidBody(fallRigidBodyCI) dynamicsWorld gt addRigidBody(fallRigidBody) for (int i 0 i lt 300 i ) dynamicsWorld gt stepSimulation(1 60.f,10) btTransform trans fallRigidBody gt getMotionState() gt getWorldTransform(trans) fallY trans.getOrigin().getY() state list.remove( STATE FALL BALL ) printf("stoped n") And the drawing function which is called at the beginning looks like this void CGL fallingBall( void ) glPushMatrix() float colBall2 4 0.0f, 0.0f, 1.0f, 1.0f glMaterialfv( GL FRONT, GL AMBIENT, colBall2) glTranslatef(0.0f,fallY,0.0f) printf("fallY f n",fallY) glutSolidSphere(1.0f,20,20) glPopMatrix() The thing is that it shows correct value in this function's printf but translation is called only at the beginning I mean I can only see the last state. Can anyone help me, please?


Difference between two perspective projection representations When researching perspective projections on the web, I've come across two different representations. One is unrelated to OpenGL and the other is strictly associated with it. What is the relation of these two projections? Both are called the same but the matrices are quite different. The first one seems to project unto the xy plane (z 0), the OpenGL one to the z near plane.


3Ds Max is exporting model with more normals than vertices I made a simple teapot with the "Create Standard Primitives" option and exported it as a collada file, ended up with this lt float array id "Teapot001 POSITION array" count "1590" lt float array id "Teapot001 Normal0 array" count "9216" For what I know there should be only one normal per vertex, am I wrong? What am I supposed to do with that much normals? Just put them on the normal buffer all at once normally?