_id
int64
0
49
text
stringlengths
71
4.19k
1
Best approach to render text in OpenGL 4.5 I have tried to implement text rendering in OpenGL from several tutorials and guides but I am unable to implement any of them successfully. The latest one I have attempted is Here but it seems to be incompatible with GL 4.5. My end goal is to implement the ability to load TTF files into OpenGL and render them. If someone could give me a hand with a sample code snippet of how to implement this myself, or even to reconfigure the free type library, that would be appreciated!
1
Transformed Vertices have wrong Z Axis For quite some time I've been working on my open 3D game engine, to learn how this stuff works. You can see the full codebase relating to my problem here on GitHub. I'm using an OpenGL 3.3 Core Profile Context on Mac OS X 10.10.3 and a GeForce GTX 760, if this matters. Everything seems to work fine when submitting my vertices and MVP matrix to the Pipeline. But at two different points I try to transform vertices on my CPU, which leads to problems. To simplify rendering the debug bounding boxes in a single frame, I transform the vertices by their MVP matrix and later submit them all to OpenGL with an identity matrix as transformation matrix for (auto amp c corner) glm vec4 t VP glm vec4(c, 1.0f) vertices.emplace back(glm vec3(t) t.w) ... Shader drawGL(vertices, colorsLine, indicesLine, glm mat4(1.0f), gl GL LINES) Most of the time, this seems to work fine. But when some vertices of a bounding box lie behind the camera, they will be "mirrored" and extend into empty space, as you can see in this screenshot Something similar happens with my portal based rendering approach, as described in Portals and Mirrors Simple, Fast Evaluation of Potentially Visible Sets. Basically, I'm looking for a visible portal, and then for more portals that are visible through the already found portal. The relevant code for (int c 0 c lt 4 c ) glm vec3 port portal.getVertex(c) glm vec4 result VP glm vec4(port, 1.0f) glm vec3 vert glm vec3(result) result.w ... This basically works as expected, as you can see in the following screenshot However, as before, there is a problem with vertices behind the camera. I would expect the transformed vertices Z axis to be in the range 0 1 and vertices behind the camera should be outside of that range. What I'm really seeing, however, is that the Z part is always 1, as you can see in this screenshot (the first line is the world vector, the second is the vector multiplied with the matrix, the third is the multiplied vector divided by w) To give you the full picture, this is how I create my projection matrix projection glm perspective(45.0f, size.x size.y, 0.1f, 75000.0f) And my view matrix is created using the quaternion of my camera glm mat4 translate glm translate(glm mat4(1.0f), pos) glm mat4 rotate glm toMat4(quaternion) view glm inverse(translate rotate) According to every description I've read of the OpenGL transformation pipeline, I've done everything to have my world coordinates now in clipping space. But, looking at the Z axis, this seems to be false. I'm sure I'm missing something obvious with my math here. Please help me out ) Best Regards, Thomas PS English is not my native language, please excuse any mistakes.
1
Questions related to rendering to texture and rendering to buffer (OpenGL) I am experimenting with off screen rendering. I understand there is two solutions to this rendering to texture (you attach a texture to one of the FBO's attachment point which can be a color, depth, etc.) use a render buffer. Question 1 I first experimented with using render buffers. I have a FBO and 2 RBOs, one for color (attached to COLOR0) and one for depth (attached to DEPTH). When I want to visualise the content of what I rendered to the render buffer, I use the glBlitFramebuffer function to copy the content from the FBO to the Window frame buffer (index 0). glBindFramebuffer(GL READ FRAMEBUFFER, fboId) glBindFramebuffer(GL DRAW FRAMEBUFFER, 0) glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL COLOR BUFFER BIT, GL LINEAR) First I would like to know if this the best way? (of passing the image from the a render buffer back to the window buffer). Question 2 My second question. The method I described above works but I can only see the "color" buffer of the FBO, not the depth buffer (I would also like to visualise the depth buffer). So I was wondering how if this was possible using this approach? I tried to use the index of the depth render buffer in place of the fboIdx in glBindFramebuffer but it didn't change anything. Can I make it work without using render to texture approach? Question 3 My end goal is to render two images using an off screen approach and blend them together. The result of the mix between the two rendered images is what I want to display to the screen. To keep things fast, I understand this can be done in hardware. What's the best way for doing this? Can it be done using the render buffer approach or do I need to go the render to texture approach (aka render to two textures and then blend these textures using a fragment shader when I do my final pass in which I render a quad stretched over the surface of the screen?
1
Mapping rectangular texture on trapezoid like shape I have a problem with rendering rectangular textures on non rectangular surfaces. While googling, I found a thread with person having a pretty similar problem http www.gamedev.net topic 419296 skewedsheared texture mapping in opengl But in my case, I cannot be sure about surface's exact properties. It's not regular trapezoid, it can be slightly bent. Which means, that I cannot just calculate correct texture matrix, or at least I don't know how. I've tried to render triangle fan like shape, but it just changed the characteristics of final distortion.
1
Efficient Rendering for multiple light sources I'm building a 3D rendering engine using C and OpenGL. Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods. I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources. The straight forward approach would be something like this for every object to be rendered closestLights for every light in the scene if (light closer than all lights in closestLights) swap furthest light from closestLights with current light loadLightSourcesToShader(closestLights) renderObject(object) However, I'm afraid the performance of this rendering loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker. 1) Is there any way to circumvent this? 2) How is this implemented in 'real' engines? 3) How can I find the closest K lightsources to an object efficiently? I've heard about kd trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now. 4) I could keep an octree and a kd tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?). Is this a good approach? I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game program reaches a certain complexity size.
1
Am I allowed to make my Minecraft clone open source? I'm developing in my spare time a game like Minecraft. In fact, it isn't "like Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL. So, my question is am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch. A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft). If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this http www.minecraft.net terms Edit There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.
1
How to get rid of half pixel artifacts? I've been having a bit of trouble using OpenGL to make 2D games. I am using a traditional ortho perspective with just some sprites being rendered and moved around. It all works perfectly but there is a little graphical artifact that I would like to get rid of. As the sprites move, their edges jitter a little bit I assume this happens as the position of the sprite goes from a half pixel coordinate to a nicely rounded up coordinate, and then back again, causing the artifact to intermittently show up. I also had the exact same problem with text rendering (textured quads technique), when it was sitting at half pixel coordinates, where it would get blurry and ugly, while at strict integer positions it would show immaculate. I could force my sprites to integer positions before rendering, which would probably fix the artifact, but at the same time ruin the movement smoothness. So, does anyone know what is the state of the art solution for this problem? How to handle sprite positioning without artifacts?
1
2D Sprite batching in OpenGL How to send transformation data to GPU OpenGL newbie here. So I'm trying to implement sprite batching to draw 100 sprites per draw call. I've created a VBO that contains texture coordinates, vertex coordinates, color data (for tinting), and a mat4 matrix for transforms. So far, so good, right? Well, everything is working but the transform portion of my VBO. My theory is that I could push a mat4 with all of the rotation, scaling, flipping, and world location data applied to it, so that it gets multiplied in with viewports (see glsl code below). version 130 Vertex position attribute in vec2 vertexPos Texture coordinate attribute in vec2 texCoordIn out vec2 texCoord Vertex color in vec4 textureColorIn out vec4 textureColor Matrix transformations for the sprite in mat4 transformation void main() Process texCoord texCoord texCoordIn Process texture color textureColor textureColorIn Process vertex gl Position gl ProjectionMatrix gl ModelViewMatrix vec4( vertexPos.x, vertexPos.y, 0.0, 1.0 ) transformation So here's my question, if you were to send transform data to the GPU, how would you do it? Sending a mat4 over the wire per vertex seems like overkill.
1
A good way to build a game loop in OpenGL I'm currently beginning to learn OpenGL at school, and I've started making a simple game the other day (on my own, not for school). I'm using freeglut, and am building it in C, so for my game loop I had really just been using a function I made passed to glutIdleFunc to update all the drawing and physics in one pass. This was fine for simple animations that I didn't care too much about the frame rate, but since the game is mostly physics based, I really want to (need to) tie down how fast it's updating. So my first attempt was to have my function I pass to glutIdleFunc (myIdle()) to keep track of how much time has passed since the previous call to it, and update the physics (and currently graphics) every so many milliseconds. I used timeGetTime() to do this (by using lt windows.h gt ). And this got me to thinking, is using the idle function really a good way of going about the game loop? My question is, what is a better way to implement the game loop in OpenGL? Should I avoid using the idle function?
1
What is Vulkan and how does it differ from OpenGL? Khronos Group (the standards body behind OpenGL) has just announced Vulkan Vulkan is the new generation, open standard API for high efficiency access to graphics and compute on modern GPUs. This ground up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability. Their page is quite marketese jargon heavy, as is the press release In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.) What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement. Update The Vulkan 1.0 spec was released on 16 02 2016.
1
D3D OpenGL Question about shaders in larger projects I'm a game dev student and last semester we had a '3D programming' course, in which we did some basic stuff such as rendering a textured quad spinning around in the "scene". We used quite basic vertex , geometry , and fragment shaders to do this. My question is, how are shaders "managed" in a larger projects? For example, I might have a sphere in the scene that uses a shader to generate some effect on it, some VS or FS to generate water ripples or waves on a water 'model', etc. How would all these different shaders be combined in the same project? Do we just create new shader programs for the different shaders(as you can do in OpenGL)? Do you use some kind of condition statement in the shader and use only one program? Some other approach? I've heard you really want to minimize API calls, especially for realtime apps (Multiple shader programs would need at least 2 calls to set the shader programs, EVERY frame.) I'm really confused about this part, and our next course involves making a small game so this will be quite important I'd imagine. (also im personally very paranoid when it comes to performance I want to do things right from the start when possible) Sorry if the question is poorly formulated, hope it makes some sense. ' An example would be great, HLSL D3D or GLSL OpenGL doesnt matter, I've fiddled with both.
1
How expensive is OpenGL Texture Binding I'm currently working on a renderer for Tiled's .tmx maps. Among one of the features there is that layers and tilesets are independent, so that a layer can use any tile set on any tile. It's not so much of a problem, though, as my Image type is basically data Image Image imageTexture TextureObject , imageMinTex2 TexCoord2 , imageMaxTex2 TexCoord2 deriving (Show, Eq) Drawing an image is therefore Bind texture Render Quad using min max texture coords A quite simple implementation. However, if every Tile is an Image, in my implementation, then this would mean that on every tile, a texture is bound. Often times it will be the same, and quite often just a few tiles have entirely different texture. So how expensive is a texture binding in OpenGL? Do I have to sort the Tiles by texture or will the OpenGL drivers do that for me?
1
OpenGL Shadow Mapping from directional light I have read this tutorial http www.opengl tutorial.org intermediate tutorials tutorial 16 shadow mapping I wonder, is this the current best technique for generating shadows in an arbitrary 3D scene? Is it the way current modern games implements directional light shadows or are they using some other better way of calculating shadows on the fly? What I mean is if you know your geometry so good that you know exactly every impact a shadow can have on an objects colors, it must be better to use that information instead of rendering a Shadow map? For example, if we have a 3D grid world with all perfect cubes at perfect offset (think minecraft) and the directional light if exactly 45 degree in all dimensions, that leave us with a situation where a cube closer to the light will also cast shadow on the entire cubes at position offset 1, 1, 1 from that cube, and so on. The shadows always go diagonal and put other equally sized cubes sides in 1 of three states all shadow, all light or 50 in shadow. If we know our geometry so good, then using that information must be much faster than rendering shadow maps right? Even when most of such calculation is done on the CPU instead of the GPU.
1
Translate operation is rotating? cube 1. 0. 0. 6. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. view 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. final 1. 0. 0. 6. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. Hello! I have a cube and I'm trying to move it around. The above are the calculated matricies for the cube, viewport, and the combined matrix after multiplication. The result is this I'm not sure why it's being warped like this instead of scooting over a bit. Any idea?
1
Effect of vertex winding on normals and shading I have implemented a Phong and Gourand shader for a triangle mesh that is being imported from an STL file. It appears to be working fairly allright but some triangles seem to be what I can only describe as upside down due to lack of better wording. This effect is visible in both shading models albeit a bit smoother in Phong. Here is an example On something basic like a cube the rendering is perfect. I am no expert but from what I have read, I am lead to suspect that perhaps the winding of the vertices in the mesh might be causing normals that are somewhat incorrect. Could this be possible and if so, how does one correct for that? The effect of interpolating the normals by either division or by area weight does not really make too much of a difference. I can also confirm that the normals that I am calculating are basically the same as those that come with the STL as calculated by FreeCAD. The manually calculated normals are slightly better though because they are area weighed. They are calculated as follows glm vec3 e1 vecs 1 vecs 0 glm vec3 e2 vecs 2 vecs 0 faceNorms i glm cross(e1, e2) with "vecs" being the 3 points of my vertices. I then sum up all these area weighed normals for each face that uses a normal and finally normalize that. PS. FreeCAD renders the mesh in a "flat" fashion and I guess thereby avoids this issue but unfortunately rendering "flat" with GLES 2.0 is a bit of a performance waste from what I have read.
1
Android Opengl Alternate values for gl FragColor I'm writing an Android application that utilizes opengl to perform some changes to the camera output. I've written my code in such a way that I finally figured out what is causing the performance issue. extension GL OES EGL image external require precision mediump float uniform samplerExternalOES sTexture uniform vec4 vColor const int MAX COLORS 6 uniform float vHues MAX COLORS uniform float vOffsets MAX COLORS varying vec2 v CamTexCoordinate float rgb2hue(vec4 c) vec4 K vec4(0.0, 1.0 3.0, 2.0 3.0, 1.0) vec4 p mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)) vec4 q mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)) float d q.x min(q.w, q.y) float e 1.0e 10 return abs(q.z (q.w q.y) (6.0 d e)) bool isInRange(float a1,float a2, float vOffset) if(a2 lt 0.0) return false else if(abs(a1 a2) lt vOffset) return true else if( a1 gt a2) return (1.0 a1 a2) lt vOffset else return (1.0 a1 a2) lt vOffset vec4 getGrey(vec4 c) float grey (c.r c.g c.b) 3.0 return vec4(grey, grey, grey, c.a) void main() vec4 c texture2D(sTexture, v CamTexCoordinate) bool hasColor vHues 0 gt 0.0 float hue rgb2hue(c) vec4 test getGrey(c) for(int i 0 i lt MAX COLORS i ) if(isInRange(hue, vHues i , vOffsets i )) If I uncomment this line the performance gets terrible test c gl FragColor test There is a significant hit to performance (a lot of frames are skipped) when I uncomment the line above. I basically want to use the original color sometimes and a different color depending on some condition. It works but is there a more efficient way to do this? Also, why does this perform so poorly?
1
How can I improve the performance of texture switching without resorting to atlasing? I'd like to use texture images that are not a sprite sheet or other form of texture atlas, mainly because I'll be consistently adding and swapping textures while I figure out the direction my game takes. In Java, I'm using slick2d's TextureLoader to load a texture, and then I bind it with an unique id. However, when not using a spritesheet I have many more images to bind, which causes a potential performance problem. I've noticed that calling glBindTexture for every block I'm drawing is bad, it drops my FPS to 1. I'm already rendering blocks with glCallList so I've found a middle ground. I bind a single block texture and then render all blocks of that type in the chunk, and repeat for each unique block type. However, that's still less than preferable. Is there a better way to efficiently use multiple textures without an atlas or sprite sheet?
1
Get world position in Vertex shader I'm wondering how I can get the final position of a vertex. I use glTranslate in my render code, and I'm not getting the world coordinates correct. My world is devided in chunks and my position get's screwed up. I have tried multiplying the position with the 3 built in matrices, but no success.
1
GraphicsAdapter.Adapters on openGL won t return secondary monitor I have been searching for this everywhere and never found the answer. I am developing a feature to allow the user to select which monitor to run the game. I have two monitors, primary and secondary. I tried to use "GraphicsAdapter.Adapters" but it always retrieves only 1 monitor (the one I am running the Visual Studio which is the default one). Is this a bug? How can I retrieve all the monitors available? Thanks MONOGAME 3.6 OPENGL (cross platform) Visual Studio 2015 Windows 10 Pro 64bits
1
How to fix model matrices colliding in vertex shader? I am new to OpenGL programming and I'm writing some basic code to display a few objects onto a screen. I have a pyramid shape that I'm displaying, as well as a box shape that I am displaying. The pyramid shape is a class (C ), and each pyramid object creates it's own VBO (storing the points colours). The same thing goes for the box. The problem I'm having is that I have two shapes, and the shapes use the same vertex shader. Since I apply a model matrix for each object in the shader, the model matrix gets set for one object, but then when the other object goes to display itself it overwrites the model matrix for the previous object with it's own. So only one object has the correct model matrix after they are all done their display method. I am also using hierarchical transformations to attach objects to each other. I have the root object storing the view projection matrices, and the children of the hierarchy tree storing their individual model transformations. When a child wants to display itself, it walks up the tree to compute all the transformations it needs to do to itself. The problem also applies here, since the last child to be displayed will be the one whose model matrix is applied in the vertex shader. I can't seem to figure out how to differentiate in the shader which MVP matrix to apply to which vertex. I think I'm missing something very basic here but I can't seem to figure it out... Any help would make my life a lot easier! Edit Is it possible that the shader is overwriting the MVP matrix in between glDrawArrays() glDrawElements() calls?
1
Smooth matrix rotation I have a coded a simple example for a matrix rotation. The example rotates a sphere around its center. The problem is that the rotation is not running perfectly smooth and I'm wondering why. Here is a minimal code sample float totalMs 0.0f int animationDuration 5000 void update(float deltaMs) totalMs deltaMs float degrees (totalMs animationDuration) animationDuration 360.0f glm mat4 rotation glm rotate(glm mat4(), radians(degrees), rotationAxis) multiply modelViewMatrix by rotation matrix and use the resulting matrix in shader to transform points I'm programming in C , using GLM Library for Maths, SDL2 for rendering context and OpenGL for the rendering. Any hints what could cause the rendering to not look totally smooth? Edit Ok I found out that the time needed for SDL GL SwapWindow() at the end of my gameLoop varies between lt 1ms and 30ms. What could be causing this?
1
OpenglGL Render two scenes with one draw call I need to draw a normal vector scene and default scene. I could achieve this my having two programs with different fragment shader to produce the following images. It will require me to draw twice. somethinglike useProgram(normal vector rendering program) render bunny() useProgram(just default scene program) render bunny() However when I am rendering the default scene, I am already passing normal vector information to achieve the lighting. So it got me curious, can I produce two different scenes with one program(a program that has two color buffer attaches) and one draw call somehow? I think if such is possible then I am saving lots of computer resource by not having to draw multiple times for different images.
1
Am I allowed to make my Minecraft clone open source? I'm developing in my spare time a game like Minecraft. In fact, it isn't "like Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL. So, my question is am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch. A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft). If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this http www.minecraft.net terms Edit There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.
1
Is it possible to run GLFW eventhough my graphic card(Nvidia) supports Direct3d API? I have Nvidia 820M GPU installed in my windows 7 machine. In nvidia control panel it is showing it supports Direct3d API version 11. Am I able to run OpenGL applications(using GLUT,GLFW) on my machine with this configuration? see the below screenshot for configuration details.
1
Using compressed(ETC1) textures in LibGDX I use standard android tool for compressing PNG texture and archiving it with gzip android sdks tools etc1tool texture.png encodeNoHeader gzip texture.pkm Then I try to load it FileHandle file ... ETC1.ETC1Data data new ETC1.ETC1Data(file) ETC1TextureData td new ETC1TextureData(data, false) Texture texture new Texture(td) But I get an java.nio.BufferOverflowException inside ETC1Data (FileHandle pkmFile) constructor in new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))) int fileSize in.readInt() compressedData BufferUtils.newUnsafeByteBuffer(fileSize) int readBytes 0 while ((readBytes in.read(buffer)) ! 1) compressedData.put(buffer, 0, readBytes) Exception occurs here compressedData.position(0) compressedData.limit(compressedData.capacity()) How to fix it? Thanks. ps if it's important unarchived pkm file size is 33KB
1
Problems with Rotation Matrices on Certain Axes Here is what my rotation matrix looks like public Matrix4f initRotation(float x, float y, float z) Matrix4f rx new Matrix4f() Matrix4f ry new Matrix4f() Matrix4f rz new Matrix4f() x (float)Math.toRadians(x) y (float)Math.toRadians(y) z (float)Math.toRadians(z) rz.m 0 0 (float)Math.cos(z) rz.m 0 1 (float)Math.sin(z) rz.m 0 2 0 rz.m 0 3 0 rz.m 1 0 (float)Math.sin(z) rz.m 1 1 (float)Math.cos(z) rz.m 1 2 0 rz.m 1 3 0 rz.m 2 0 0 rz.m 2 1 0 rz.m 2 2 1 rz.m 2 3 0 rz.m 3 0 0 rz.m 3 1 0 rz.m 3 2 0 rz.m 3 3 1 rx.m 0 0 1 rx.m 0 1 0 rx.m 0 2 0 rx.m 0 3 0 rx.m 1 0 0 rx.m 1 1 (float)Math.cos(x) rx.m 1 2 (float)Math.sin(x) rx.m 1 3 0 rx.m 2 0 0 rx.m 2 1 (float)Math.sin(x) rx.m 2 2 (float)Math.cos(x) rx.m 2 3 0 rx.m 3 0 0 rx.m 3 1 0 rx.m 3 2 0 rx.m 3 3 1 ry.m 0 0 (float)Math.cos(y) ry.m 0 1 0 ry.m 0 2 (float)Math.sin(y) ry.m 0 3 0 ry.m 1 0 0 ry.m 1 1 1 ry.m 1 2 0 ry.m 1 3 0 ry.m 2 0 (float)Math.sin(y) ry.m 2 1 0 ry.m 2 2 (float)Math.cos(y) ry.m 2 3 0 ry.m 3 0 0 ry.m 3 1 0 ry.m 3 2 0 ry.m 3 3 1 m rz.mult(ry.mult(rx)).getM() return this And here is how I've been implementing it for tests (using default orthographic perspective) public class Renderer private WorldMesh mesh private Mesh mesh private Matrix4f transform private Shader shader public Renderer() Setup Meshes mesh new WorldMesh() mesh ResLoader.loadMesh("pyramid.obj") mesh.addToBuffers( mesh) setup Shader shader new Shader() shader.addVertexShader(ResLoader.loadShader("basicVertex.vs")) shader.addFragmentShader(ResLoader.loadShader("basicFragment.fs")) shader.compileShader() shader.addUniform("transformation") temporary transformation matrix Matrix4f tran new Matrix4f().initTranslation(0, 0, 0) Matrix4f rot new Matrix4f().initRotation(0, 0, 0) problem is definitely with the rotation matrix Matrix4f scale new Matrix4f().initScale(1, 1, 1) transform tran.mult(rot.mult(scale)) public void update() public void render() RenderUtils.clearScreen() shader.setUniform("transformation", transform) shader.bind() mesh.draw(true) and finally here is my vertex shader version 330 layout (location 0) in vec3 position uniform mat4 transformation void main() gl Position transformation vec4(position, 1.0) The problem is that setting a rotation on any other axis other than Z (for some reason z axis rotation is working fine) does not function properly. An X axis rotation seems to be doing both an x and y rotation at the same time, causing a weird stretching affect. A Y axis rotation causes the mesh to completely disappear. The funny thing is that I've used this code over and over again and some projects don't give me a problem. The order of multiplication seems in order, and I made sure that OpenGL knows to transpose the matrix I give it when setting the uniform. Any ideas as to what could be causing the x and y axis rotations to completely fail?
1
How can I set up a pixel perfect camera using OpenGL and orthographic projection? I am creating a 2D game using OpenGL and orthographic projection. For sprites, I use textured quads (actually two triangles). I want the pixel art textures for the sprites to be displayed in a multiple of the original size to avoid blurry textures. How can I set up a pixel perfect camera using OpenGL and orthographic projection? After doing so, how do I size the qauds?
1
How do I apply 2 rotations about different points to a single primitive using OpenGL I'm working on a 2D top down shooter game that has a rotation feature like Realm Of The Mad God such that if you press e the camera rotates around the character in a clockwise direction and q rotates the camera around the character in a counterclockwise direction. I have this working with my floors and walls by translating to the character, doing the screen rotation, and drawing everything with the character as the origin. The problem arises when I shoot projectiles which need to both rotate around the character and rotate around themselves (shooting uses the mouse cursor so I can shoot at any angle). For example, if the screen is not rotated and I'm shooting rectangular projectiles, I want them to face in the direction I'm shooting (rotation around themselves). However if I only do this rotation, when I then rotate the screen the projectiles will always shoot at the same position because my cursor position does not change. Therefore I need to also either rotate the projectiles around the character or rotate the mouse cursor position to get the correct position (which would then totally screw up all of the collision detection). Likewise if I only do the screen rotation on projectiles, the rectangles will always be facing the same way and they would only look correct if I were shooting straight up or straight down. So my question is, how can I perform 2 rotations on a primitive around 2 different points? The only way I can think of is to translate to the character and do the screen rotation, then somehow calculate the translation required to move back to the middle of the projectile (seeing as how my axes are now rotated) and do its rotation. Or am I thinking about this in the wrong way and there is a different solution to accomplishing this effect?
1
Rotate heading relative to agent's local space I'm having a little trouble translating a point in my game's world space to an object's local space. I have a cannon in my game with a normalized heading vector that's always supposed to point in the direction of a target. The target is set by an incoming screen touch event. My problem is that the coordinates I get from the incoming touch events are relative to the game world's axis centered at the world's origin, not relative to the cannon's position like I need. The angle I calculate to rotate the heading is relative to the world's X axis, not the cannon's local X axis, this means I can never rotate the heading by anything outside of 0 lt x lt 90. I hope my crude drawing conveys what I mean. In the picture below, A is the cannon's position (with the blue heading vector), and B is the target's location (set by an event). The green line represents the angle the game is giving me, and the angle between red line and the heading is what I need to find (the little curved blue arrow). Here's the code I use to calculate the heading float xDistance target.x position.x float yDistance target.y position.y float angleToTurn (float) Math.atan2(yDistance, xDistance) vec2RotateAroundOrigin(heading, angleToTurn) Thanks in advance. Any help is greatly appreciated.
1
How to remove fragment from VAO? I have the OpenGL VAO object ( 40K) to draw the 3D scene glBindVertexArray(VAO) glDrawElements(GL TRIANGLES, 4, GL UNSIGNED BYTE, nullptr) glBindVertexArray(0) To add some data I can use glMapBuffer GLuint buffer glGenBuffers(1, amp buffer) glBindBuffer(GL ARRAY BUFFER, buffer) glBufferData(GL ARRAY BUFFER, (2 steps) sizeof(float), NULL, GL STATIC DRAW) float data (float ) glMapBuffer(GL ARRAY BUFFER, GL WRITE ONLY) myFuncAddingData(data, 2.4f, 40.0f, 19.0f ) glUnmapBuffer(GL ARRAY BUFFER) Can I to remove (hide mask) some verteces (3 from 40K) directly from the located in the grafical memory VAO without full complete replacement all of the 40K?
1
vec4 for vec3 multiplication while calculating the specular value I'm following this tutorial to calculate the specular color of a vertex. I use OpenGL 2.1 with GLSL version 120. This is the formula that I apply spec (R eye) s Ls Lm With L direction vector light vertex N vector normal eye direction vector vertex eye R 2N (L N) L Now the problem is that following this way I need to multiply a vec3 for a vec4. This is what I tried to do vec4 L normalize(gl LightSource 0 .position gl Position) vec3 N normalize (gl NormalMatrix gl Normal) vec4 eye normalize( gl Position) vec4 R 2.0 N (L N) L Syntax error N is a vec3 vec4 spec (R eye) gl LightSource 0 .specular I wouldn't get a vec3 result when calculating the specular value, this value I would be ignoring the alpha value. How do I go around this?
1
Cannot Draw a triangle without VAO on MacOS So I was watching Cherno's Video on Vertex attributes and he was successful in drawing a triangle without a VAO, but in tutorials from learnopengl.com they specifically say they we need a VAO to draw VBO and I tested it and it works fine. Here is my snippet glGenVertexArrays(1, amp VAO) glBindVertexArray(VAO) glGenBuffers(1, amp VBO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, sizeof(triangleVertices), triangleVertices, GL STATIC DRAW) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(GLfloat), (GLvoid )0) glEnableVertexAttribArray(0) Game Loop Loop until the user closes the window while (!glfwWindowShouldClose(window)) Poll for and process events glfwPollEvents() Render here glClearColor(0.2f, 0.3f, 0.3f, 1.0f) RGBA glClear(GL COLOR BUFFER BIT) glUseProgram(shaderProgram) glBindVertexArray(VAO) we did not unbind it so it's still binded to the assigned VAO glDrawArrays(GL TRIANGLES, 0, 3) Swap front and back buffers glfwSwapBuffers(window) This only works if I uncomment the VAO which is understandable, what I can't get my head around is how did Cherno got it working without a VAO and just using a VBO? Is it a MacOS specific thing?
1
Working towards going 3D I am a beginner intermediate C Java programmer and my long term goal is to be a game programmer. I have decided to start off with 2D and work my way towards 3D. I would like to use SDL to start off with, but I am wondering if it is maybe not such a great idea. Given the fact that I am working towards 3D, would it be advisable to use SDL or jump into OpenGL without the Z axis?
1
Why do I have to switch T(v) texture coordinates while importing OpenGL to Direct3D? I am importing my code from OpenGL to Direct3D. My D3DTS PROJECTION uses D3DXMatrixPerspectiveFovRH, and my D3DTS VIEW uses D3DXMatrixLookAtRH to set a view equal to OpenGL's view. My question is why do I have to switch all of my 1.0000 Tex(v) texture coordinates to "minus value" in D3D to get equal texture mapping as in OpenGL. OpenGL T(u) T(v) 1.0000, 1.0000, 0.0000, 1.0000, 1.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, ... Direct3D T(u) T(v) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) ... Is it because Direct3D's origin (0.0) of texture coordinates lies in different place than in OpenGL?
1
Storing rendering data for voxel game 1 VAO and VBO or 1 for every chunk I have a minecraft style voxel game with placing and digging blocks. it runs at 400 fps on my computer but when I added semi transparent water it started running at 40 fps. so a time per frame increase of 0.0175s or 8 times what is used to be. What I am currently doing is having a VAO and VBO for each chunk and every time a chunk is changed or loaded it finds all of the non occluded blocks and puts their positions into another buffer in the chunk. then I use instancing to render the whole chunk in one draw call so every frame I am doing 300 draw calls. Once I added the water(using order independent transparency http www.openglsuperbible.com 2013 08 20 is order independent transparency really necessary ) I was individually calling gldrawelements() for every visible water block so around 9000 if half the visible area is ocean. I know using instancing with these blocks would help but then I have 2 VAOs for every chunk and 600 draw calls of buffers with only a couple hundred blocks in them. would there be a better way to organize these things.
1
OpenGL only rendering 4 tris of cube? I'm on Win10, OpenGL 4.5 I wrote some code that takes mesh data from an OBJ file and puts it into a vertex buffer. I used this code to import a cube OBJ and render it in OpenGL. For some reason, although the importer output shows that all tris (broken down into vert components) were put into the buffer, the actual rendered cube only has 4 tris showing. What could be happening here? Here is my relevant code Before the main loop Import mesh data OBJ amp cube ImportOBJ( quot meshes cube.obj quot ) Bind mesh data GLuint vertexArrID glGenVertexArrays(1, amp vertexArrID) glBindVertexArray(vertexArrID) GLuint vertexBufferID glGenBuffers(1, amp vertexBufferID) glBindBuffer(GL ARRAY BUFFER, vertexBufferID) glBufferData(GL ARRAY BUFFER, cube.vertBufferSize, cube.vertBuffer, GL STATIC DRAW) Inside the main loop Draw cube glDrawArrays(GL TRIANGLES, 0, cube.vertCount) glDisableVertexAttribArray(0) Here is what it looks like and here is the importer output broken down like face index vert index (x, y, z) 0 0 ( 0.5, 0.5, 0.5) 0 1 (0.5, 0.5, 0.5) 0 2 (0.5, 0.5, 0.5) 1 3 (0.5, 0.5, 0.5) 1 4 ( 0.5, 0.5, 0.5) 1 5 (0.5, 0.5, 0.5) 2 6 ( 0.5, 0.5, 0.5) 2 7 ( 0.5, 0.5, 0.5) 2 8 ( 0.5, 0.5, 0.5) 3 9 (0.5, 0.5, 0.5) 3 10 ( 0.5, 0.5, 0.5) 3 11 ( 0.5, 0.5, 0.5) 4 12 (0.5, 0.5, 0.5) 4 13 (0.5, 0.5, 0.5) 4 14 (0.5, 0.5, 0.5) 5 15 ( 0.5, 0.5, 0.5) 5 16 (0.5, 0.5, 0.5) 5 17 ( 0.5, 0.5, 0.5) 6 18 ( 0.5, 0.5, 0.5) 6 19 ( 0.5, 0.5, 0.5) 6 20 (0.5, 0.5, 0.5) 7 21 (0.5, 0.5, 0.5) 7 22 ( 0.5, 0.5, 0.5) 7 23 ( 0.5, 0.5, 0.5) 8 24 ( 0.5, 0.5, 0.5) 8 25 ( 0.5, 0.5, 0.5) 8 26 ( 0.5, 0.5, 0.5) 9 27 (0.5, 0.5, 0.5) 9 28 (0.5, 0.5, 0.5) 9 29 ( 0.5, 0.5, 0.5) 10 30 (0.5, 0.5, 0.5) 10 31 (0.5, 0.5, 0.5) 10 32 (0.5, 0.5, 0.5) 11 33 ( 0.5, 0.5, 0.5) 11 34 (0.5, 0.5, 0.5) 11 35 (0.5, 0.5, 0.5)
1
Improve opengl drawing with less calls as possible I'm looking to render rectangle primitives as performant as possible, here's what I did so far int main() Window window("OpenGL", 800, 600) Shader shader(". file.shader") float vertices 8 glGenVertices(vertices, 200, 150, 400, 300) return coords for a square const GLshort indices 6 0, 1, 2, 2, 3, 0 GLuint vao, vbo, ebo glGenVertexArrays(1, amp vao) glBindVertexArray(vao) glGenBuffers(1, amp vbo) glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, sizeof(vertices), vertices, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 2, GL FLOAT, GL FALSE, 0, 0) glGenBuffers(1, amp ebo) glBindBuffer(GL ELEMENT ARRAY BUFFER, ebo) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(indices), indices, GL STATIC DRAW) while(window.isOpen()) window.clear() shader.use() glDrawElements(GL TRIANGLES, 6, GL UNSIGNED SHORT, NULL) shader.setUniforms(..) glDrawElements(GL TRIANGLES, 6, GL UNSIGNED SHORT, NULL) window.update() glDeleteBuffers(1, amp vbo) glDeleteBuffers(1, amp ebo) glDeleteVertexArrays(1, amp vao) return 0 So far what I'm doing to fix my problem and seems to work Created vao, vbo and ebo to make a basic indexed rectangle. Made a function that will returns vertices coordinates based position and sizes(x, y, w, h) Create one single shader and set uniforms like position offsets, sizes and eventualy colors textures after every draw call to be able to render shapes in different places ( that makes the coordinates function useless) I'm pretty sure that's not the way to do it, but can't find something else, so this is what I'm thinking. Heard that switching shaders is expensive, but I'll require shapes that won't share the same shader.. Also heard that setting uniforms is slower than switching shaders, so probalby switching shaders will be better here, need to profile the code to see. Currently drawing one by one with glDrawElements seems hardcoded and inefficient to me, need something like a vao that could store multiple rectangular like indexedvbo all preloaded before drawing and when it goes to drawing, draw all the data with one call. Not sure if I can load shaders between drawing, some of them will require changing while drawing like a hover or click effect, maybe there's better practices here too. At the end, if you've been through this issue or having some tips docs source codes to read, it'll be excellent, thanks! BIG NOTE Mostly looking for 2d support, no 3d needed in case this could make it harder.
1
How to obtain touch events from a GL Viewport, not the whole screen? Background I'm implementing viewport resizing in order for my game to maintain the same display ratio on all devices. However, I've found an issue with getting touch events. Basically, if my viewport, for example, uses the whole of the physical screen's width and height then there is no issue. However, if it is resized say in the vertical, then my touch events are thrown off, because touch events are registered from the top of the physical screen. Hence if I put a sprite at say position 50 in the Y direction then it put's the sprite 50 pixels down from the top of the viewport, not the top of the actual screen. Do I have to manage this myself by adding my viewport's offset to my touch events or is there a way to tell Android to register 0, as the top of the viewport as opposed to the actual screen. Here is a graphic to illistrate what I mean, any help would be appreciated
1
Modern opengl for direct3d programmers I don't think this is quite the same questions as this one but if you disagree feel free to close this ) With SteamOS being announced yesterday I can see that it's entirely possible that opengl will get a big boost in usage in the near future. Now I already know direct3d11 quite well but I think maybe it's time to learn opengl too. Are there any good resource for learning modern opengl that are aimed at programmers who already know direct3d11 pretty well. So don't need any education on the concepts and math, just on how to use the API and any important differences?
1
Front Face Culling with Shadowmapping To avoid shadow acne I usualy use front face culling which works great. But for my current implementation the mesh is a quite complex terrain (depending on the lod level) and than the shading (dot product of the normals face with the negative light direction) is not always correct as some normals are actually facing the light. But still there is no information in the shadowmap to shadow these fragments in the shadowmap because of the front face culling ( like it is not exact enough). What I end up with, is that there are some bright spots in the shadowed area. I am not really sure why this does not work, because that would mean, that the front face culling is also culling some back faces, if the mesh has a very high level of detail, right? In the Image with Front Face Culling (top picture) you can see these bright lines in the shadowed area where as without FF Culling (bottom image) the shadowed area is completely black. My current workaround is, that I check the highest LOD level that is currently displaying and than according to that switch back an forth between ff culling and bias. I use OpenGL The front face culling glEnable(GL CULL FACE) glCullFace(GL FRONT) The shading in the fragment shader float shading max(dot(normal, lightDir), 0.0)
1
Soft Body rendering from OBJ model As part of my master thesis I have to do an softbody simulation. I 'm using Bullet Physics engine. I'm trying to render softbody, create from Meshes, with Shaders in OpenGL but the object doesnt seem to be rendered (it doesnt appear in the window). I'm not sure if the problem is because of the way I created the sobtbody or the way I render it. Thank you in advance. I'm using this function for creating a softBody from my OBJ Liver model btScalar verti new btScalar 3 (Liver.getMeshes() 0 .vertices.size()) for (int i 0 i lt Liver.getMeshes() 0 .vertices.size() i ) verti 3 i Liver.getMeshes() 0 .vertices i .Position.x verti 3 i 1 Liver.getMeshes() 0 .vertices i .Position.y verti 3 i 2 Liver.getMeshes() 0 .vertices i .Position.z int indi new int Liver.getMeshes() 0 .indices.size() for (int i 0 i lt Liver.getMeshes() 0 .indices.size() i ) indi i Liver.getMeshes() 0 .indices i btSoftBody LiverSBody btSoftBodyHelpers CreateFromTriMesh(softBodyWorldInfo, verti, amp indi 0 , int(Liver.getMeshes() 0 .indices.size()) 3) LiverSBody gt m cfg.kVC 0.5 btSoftBody Material pSpMat LiverSBody gt appendMaterial() LiverSBody gt m materials 0 gt m kLST 0.5 pSpMat gt m kLST 1.0 LiverSBody gt setPose(false, true) btTransform trans trans.setIdentity() trans.setOrigin(btVector3(0,0,0)) LiverSBody gt transform(trans) LiverSBody gt generateBendingConstraints(2, pSpMat) LiverSBody gt m cfg.piterations 2 LiverSBody gt m cfg.kDF 1.0 LiverSBody gt m cfg.kSRHR CL 1 LiverSBody gt m cfg.kSR SPLT CL 0 LiverSBody gt setTotalMass(10, true) LiverSBody gt scale(btVector3(0.02, 0.02, 0.02)) LiverSBody gt getCollisionShape() gt setMargin(0.1) float Friction 0.9 float Restitution 0.5 LiverSBody gt setFriction(Friction) LiverSBody gt setRestitution(Restitution) m pSoftBodyWorld gt addSoftBody(LiverSBody) I'm using this class for loading and visualizing model https learnopengl.com code viewer gh.php?code includes learnopengl model.h I need to extract from the softBody some data (Position, normal, texCoords, tangent and bitangent) to fill the vertex buffer objects but i don't know where to find most of it... I know that the position and the normals are in the softbody nodes but i can't find the other information needed (texCoords, ..). btSoftbody.h struct Node Feature btVector3 m x Position btVector3 m q Previous step position btVector3 m v Velocity btVector3 m f Force accumulator btVector3 m n Normal btScalar m im 1 mass btScalar m area Area btDbvtNode m leaf Leaf data int m battach 1 Attached
1
Why does my terrain texture fail to load? (OpenGL) I'm currently using a vertex shader and a fragment shader for loading my texture onto the terrain I made. Here is my vertex shader version 330 core layout (location 0) in vec3 aPos layout (location 1) in vec3 aNormal uniform mat4 model uniform mat4 view uniform mat4 projection float scale 0.5 out vec2 TexX out vec2 TexY out vec2 TexZ out vec3 blend weights void main() vec3 blend weights abs(aNormal.xyz) blend weights (blend weights 0.2) 0.7 blend weights max(blend weights, 0) blend weights (blend weights.x blend weights.y blend weights.z) TexX aPos.yz scale TexY aPos.zx scale TexZ aPos.xy scale gl Position projection view model vec4(aPos, 1.0) And here is my fragment shader. version 330 core out vec4 FragColor uniform sampler2D terrainTexture in vec2 TexX in vec2 TexY in vec2 TexZ in vec3 blend weights void main() FragColor texture(terrainTexture, TexX) blend weights.x texture(terrainTexture, TexY) blend weights.y texture(terrainTexture, TexZ) blend weights.z I was trying to implement 3D texture planar projections, based on section 1.5 of this link https developer.nvidia.com gpugems GPUGems3 gpugems3 ch01.html If I just try to implement the texture in a very simple way, it works (which looks terribly stretched on the mountanous terrains, of course). But if I implement it this way, the texture does not load. What could be the possible reason? Just in case anyone is wondering, the following is my VAO, VBO, EBO configuration VAO, VBO configuration unsigned int VAO, VBO, EBO glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp VBO) glGenBuffers(1, amp EBO) glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, positions.size() sizeof(glm vec3) normals.size() sizeof(glm vec3) , NULL, GL STATIC DRAW) glBufferSubData(GL ARRAY BUFFER, 0, positions.size() sizeof(glm vec3), amp positions 0 ) glBufferSubData(GL ARRAY BUFFER, positions.size() sizeof(glm vec3), normals.size() sizeof(glm vec3), amp normals 0 ) glBindBuffer(GL ELEMENT ARRAY BUFFER, EBO) glBufferData(GL ELEMENT ARRAY BUFFER, indices.size() sizeof(int), amp indices 0 , GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(float), 0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 3 sizeof(float), (void )(positions.size() sizeof(glm vec3))) This is my draw function Inside the render loop void drawScene(Shader amp shader, unsigned int VAO, unsigned int numIndices, unsigned int texture1) draw the scene with the parameter data. glm mat4 model model glm translate(model, glm vec3( (int)(gridXNum) 2, 0.0f, (int)(gridZNum) 2)) glm mat4 view camera.GetViewMatrix() glm mat4 projection glm perspective(glm radians(camera.Zoom), (float)SCR WIDTH (float)SCR HEIGHT, 0.1f, 100.0f) shader.use() shader.setMat4("model", model) shader.setMat4("view", view) shader.setMat4("projection", projection) shader.setFloat("TERRAIN WIDTH",gridXNum) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, texture1) glBindVertexArray(VAO) glDrawElements(GL TRIANGLE STRIP, numIndices, GL UNSIGNED INT, 0) glBindVertexArray(0) However, I really don't think this is the problem because as I said, if I change the shader codes into a really basic one, the texture successfully loads. There is definitely something wrong with my shader program. Any help would be appreciated. Thanks in advance!
1
Nvidia RTX ray tracing OpenGL extension I can't seem to find any OpenGL headers for the RTX ray tracing extension, seems like they only want you to use Vulkan and optix with RTX
1
i need suggestion animation technique for 3d? firstly you need to now i am beginner ) i am using opengl and for display vertex buffer object(vbo). i made 2000 frames animation model with blender and i export with (.obj) files and i upload all these 2000 obj files to my opengl project. But upload process is taking too much time. like 7 8min and this method use too much vram around 2 3gb. Despite all this i'm glad draw performance because when i draw 100 animation(same model) at the same time my pc using 1 2 cpu and 70 80gpu. Now i want to learn is there another method of good draw performance and low system consumption ? (i want to draw 100 and much more animation model at the same time)
1
does glBindAttribLocation silently ignore names not found in a shader? Does glBindAttribLocation silently ignore names that are not found? For example, in a shader Some vertex shader in vec3 position in vec3 normal ... And in some set up code While setting up shader GLuint program glCreateProgram() glBindAttribLocation(program, 0, "position") glBindAttribLocation(program, 1, "normal") glBindAttribLocation(program, 2, "color") What about this one? glLinkProgram(program)
1
For voxel rendering, what is more efficient pre made VBO or a geometry shader? Given a fairly static voxel array, what is more efficient using the CPU to pre generate a VBO to render the voxel faces (ignoring more advanced forms of rendering like marching cubes for now) or using a geometry shader on the GPU to generate the faces on the fly? I'm not that worried about updating changing voxels but of course that is a benefit of the GPU version since you don't have to rebuild the VBOs. Also, the GS approach feels a bit more modern ) On the other hand, I haven't looked at the details on how a GS actually works with the rasterization pipeline in modern GPUs. Does it output the vertices into a sort of stream cache or is the vertices written to the normal GPU memory in between? If it's the latter, then on the fly generating could reduce the available bandwidth and processing power from the rest of the GPU tasks I guess and then it would be more beneficial to do it on the CPU..
1
How to correctly setup latest LWJGL libraries to Eclipse? A year ago, I understood how to setup an LWJGL project in Eclipse IDE. Now LWJGL has a lot of changes including a different file structure. I downloaded the latest release, LWJGL 3.1.0 Build 40 from the official site. There's also a page explaining how to get started, but it does not help me to set it up in Eclipse. When I extract the downloaded .zip file, I only get .jar files (and .txt licences). I see nowadays there are no .dll natives for a specific operating system. Instead of that, I see jars like lwjgl glfw natives windows.jar. I expect these are now the files that were previously .dll files. Can someone explain to me how to set it all up correctly?
1
Having issue's with a confusing access violation? C , OpenGL 3.3 , SDL 2.0 Hello this code seems so well done and yet I'm getting this weird access violation error when I use anything but 0 in glShaderSources 2nd argument glShaderSource( fragshader, 0, fragfilebuff, NULL ) If I use lenofstr or any other number then 0 it calls up an error like this I have no idea for the life of me why this is happpening I've updated my drivers , I've even tried messing around with glewInit() too see if it's something to do with that but no luck what so ever. This nvidia dll has some problem with my code and I don't know why?... void LoadShaders(const char fragshaderfn, const char vertshaderfn) FILE fragfile const GLchar fragfilebuff 256 0 fopen s( amp fragfile, fragshaderfn, "r") fread(fragfilebuff, sizeof(char), sizeof(char) 256, fragfile) printf(fragfilebuff) GLsizei lenofstr strlen(fragfilebuff) printf("this is the length gt d", lenofstr) GLuint fragshader glCreateShader(GL FRAGMENT SHADER) glShaderSource(fragshader, 0, fragfilebuff, NULL) glCompileShader(fragshader) Here's the complete source include lt SDL.h gt include lt GL glew.h gt include lt SDL opengl.h gt include lt stdio.h gt include lt conio.h gt define SCREEN HEIGHT 480 define SCREEN WIDTH 640 SDL Renderer mainrenderer SDL Window mainwindow SDL Event event bool running true void LoadShaders(const char fragshaderfn, const char vertshaderfn) FILE fragfile const GLchar fragfilebuff 256 0 fopen s( amp fragfile, fragshaderfn, "r") fread(fragfilebuff, sizeof(char), sizeof(char) 256, fragfile) printf(fragfilebuff) GLsizei lenofstr strlen(fragfilebuff) printf("this is the length gt d", lenofstr) GLuint fragshader glCreateShader(GL FRAGMENT SHADER) glShaderSource(fragshader, lenofstr, fragfilebuff, NULL) glCompileShader(fragshader) int main(int argc , char argv) SDL Init(SDL INIT EVERYTHING) mainwindow SDL CreateWindow( "C OpenGL Engine", 300, 300, 640, 480, SDL WINDOW SHOWN SDL WINDOW OPENGL ) SDL GLContext maincontext SDL GL CreateContext(mainwindow) SDL GL MakeCurrent(mainwindow, maincontext) glewExperimental GL TRUE GLenum err glewInit() if (GLEW OK ! err) Problem glewInit failed, something is seriously wrong. fprintf(stderr, "Error s n", glewGetErrorString(err)) fprintf(stdout, "Status Using GLEW s n", glewGetString(GLEW VERSION)) if (SDL GL SetSwapInterval(1) lt 0) printf("Warning Unable to set VSync! SDL Error s n", SDL GetError()) LoadShaders("ffile.frag", "") glClearColor(0.0, 0.0, 0.0, 1.0) while (running true) while (SDL PollEvent( amp event)) switch (event.type) case SDL QUIT SDL GL DeleteContext(maincontext) SDL Quit() return 0 break glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT ) SDL GL SwapWindow(mainwindow) SDL GL DeleteContext(maincontext) SDL DestroyWindow(mainwindow) SDL Quit() return 0 All help would be appreciated I am using C , SDL 2.0 and OpenGL 3.3 , MSVC 2015 , Win10 64bit
1
SFML Segmentation Fault when using VBOs? I'm trying to follow along with the gltut tutorials and for some reason when I call GLDrawArrays my program segmentation faults. I've been looking at the state of my application with the Mac OpenGL Profiler and Googling and I can't seem to figure out why it isn't working. I may have missed setting some OpenGL state somewhere. My code is here, it segfaults on line 32. If I don't call glEnableClientState(GL VERTEX ARRAY) and the respective glDisableClientState(GL VERTEX ARRAY) it compiles and runs, but I get no rendering, which is what I would expect given my limited OpenGL knowledge.
1
glDrawElements vs glDrawArrays for polygons that do not reuse vertices Is it better to use glDrawElements or glDrawArrays when not reusing vertices? There must be some difference, otherwise people would always use glDrawElements? I suppose the question could be reworded as the following Does glDrawElements function the same as glDrawArrays if it is passed a blank indices table?
1
How to scale to fit OGL viewport to GLFW window? Say my window is 1280x720. I want to render my stuff to lower resolution and then stretch it to window. I've tried this glViewport(0, 0, 1280 2, 720 2) When I call glViewport and pass lesser width and height than window, I get all my OpenGL rendering in left bottom 1 4 of window. I need to scale it (linear filtering preferably) back to window size so I would get a pixelated effect. I wonder if there is such possibility within glad glfw API.
1
Frustum culling only working at certain angles So how I'm doing this is a little sketchy but I plan on changing it to either AABBs or spheres once I get it working. So the problem I'm having right now is that the frustum culling I've implemented is only working at certain angles and is not even close to accurate, personally I believe that the problem is at a calculation level. I am fairly new to 3D game development so I just whipped up this class fairly quickly based on some thread I read. My ViewFrustum class can be found here https www.dropbox.com s 3b97bgcwoyh2oq8 ViewFrustum.java?dl 0 So all I'm doing outside this class is calling the update method from my renderer class and I have an ungodly amount of if statements checking if an entity's xyz is within the min and max xyz of the frustum (This is temporary). So my main question is, am I calculating the frustum right or did I make any mistakes? Values (when game starts, rotation matrix is a identity matrix) centerNear 134.49167, 7.3502045, 271.4365 centerFar 134.49167, 7.3502045, 1170.7365 points 0 7 0 2607.2214 1714.3507 621.8992 1.0 1 2338.238 1714.3507 621.8992 1.0 2 2607.2214 899.70605 1573.3379 1.0 3 2338.238 899.70605 1573.3379 1.0 4 136.4149 100.760254 252.18294 1.0 5 132.56844 100.760254 252.18294 1.0 6 136.4149 98.727104 252.92294 1.0 7 132.56844 98.727104 252.92294 1.0
1
JOGL KeyListener not functioning properly I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't). Here is the relevant code in the class import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.KeyListener import java.util.HashSet import java.util.Set public class KeyInput implements KeyListener private static Set lt Short gt key new HashSet lt Short gt () public void keyPressed(KeyEvent keyEvent) key.add(keyEvent.getKeyCode()) System.out.println("added " keyEvent.getKeyChar()) public void keyReleased(KeyEvent keyEvent) key.remove(keyEvent.getKeyCode()) System.out.println("removed " keyEvent.getKeyChar()) public static boolean getKey(short k) return key.contains(k) I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.
1
Quaternion Rotation after performing previous rotations Have Quaternion Q which is rotated on the X axis 90 degrees. Q is now (0.707106, 0.707106, 0, 0) . I want to rotate Q another 90 degrees by a different pivot P so i will calculate Q P Q 1 , save the x,y,z coordinates in res(x,y,z) and then res res P . This should give me the offset between the new coordinates and the old ones, however in my case i get a big translation on the Y axis. Example 1 Here i do both rotations around the same pivot, compared to first center then pivot. Example 2 i do both rotations around the same point C( 0.5,0.5,0.5) if it matters, for the second rotation i first rotate the pivot with the current rotation to get actual coordinates of the pivot. I do all calculations in object space where the object center is at 0,0,0 EDIT CODE Before i start a rotation i calculate where the pivot should be at the current rotation like this, it only happens when there are no active rotations, i choose to rotate by vertices 3 state.currentPivot state.rotation vertices 3 this is the part of the update function that gets executed during rotations for (auto amp rotationRule v rotationRules) if (deltaTime gt rotationRule.startTime amp amp deltaTime lt rotationRule.endTime) state.rotation glm rotate(state.rotation, glm radians(rotationRule.degrees), rotationRule.axis) state.rotateAroundPivotWithQuat() TranslationMatrix glm translate(glm mat4(1.0f), state.rotatedPosition()) ModelMatrix TranslationMatrix glm mat4 cast(state.rotation) ScaleMatrix glm vec3 ObjectState rotatedPosition() return position rotationOffSet void ObjectState rotateAroundPivotWithQuat() glm vec3 negp currentPivot glm vec3 res rotation negp rotationOffSet res currentPivot When a rotation is over i add position rotationOffSet, happens at the end of it, and make it equal to (0,0,0) again. in the gifs, the first value of rotationOffSet has the high offset on y axis, as i checked in debugger.
1
JOGL KeyListener not functioning properly I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't). Here is the relevant code in the class import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.KeyListener import java.util.HashSet import java.util.Set public class KeyInput implements KeyListener private static Set lt Short gt key new HashSet lt Short gt () public void keyPressed(KeyEvent keyEvent) key.add(keyEvent.getKeyCode()) System.out.println("added " keyEvent.getKeyChar()) public void keyReleased(KeyEvent keyEvent) key.remove(keyEvent.getKeyCode()) System.out.println("removed " keyEvent.getKeyChar()) public static boolean getKey(short k) return key.contains(k) I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.
1
OpenGL Colour Issues I am using a single VBO to store vertices in the follow format v1X, v1Y, v1Z, v1R, v1G, v1B, v2A, v2X, ... Vertex positioning is fine, shapes show up where expected, however instead of using the colour provided, all shapes show up red. The code given below simply draws two triangles to form one square ground shape. Buffer data preparation method public void prepare(float data) glBindBuffer(GL ARRAY BUFFER, vboID) FloatBuffer dataBuffer RenderUtils.fArrayToBuffer(data) if(dataLength ! data.length) glBufferData(GL ARRAY BUFFER, dataBuffer, GL STATIC DRAW) dataLength data.length else glBufferSubData(GL ARRAY BUFFER, 0, dataBuffer) glVertexAttribPointer(0, 3, GL FLOAT, false, 7 4, 0) glVertexAttribPointer(3, 4, GL FLOAT, false, 7 4, 3 4) Render code floorObj.prepare(new float 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, ) glDrawArrays(GL TRIANGLES, 0, 6) Vertex shader version 330 core in vec3 position in vec4 i color out vec4 color uniform mat4 transform void main() gl Position transform vec4(position, 1) color i color Fragment shader version 330 core in vec4 color out vec4 f color void main() f color color As previously stated, vertex positions work fine, however colour does not. Just ask if any other code would be useful to determine the problem. Thanks, Jasper
1
What is the best way of storing transformations for an object and then applying them with OpenGL? First some background info... I have been working on a platformer game, which I draw with OpenGL. The platforms are cubes and the player is a cube. The platforms and the player (both cubes) are given a position, from which the vertices should be drawn. However, the first cube is at position 0, 0, 0 and I would like the player to be on top of this cube. The size of the cubes and player is 0.5, 0.5, 0.5 initially. However, I didn't manage to get the player on 0, 1, 0 (cubes are drawn from their center point I remembered), because the scaling didn't seem to work, which led me to believe the method I'm using to store the translations and scaling is inherently bad. I am currently storing the translations and scaling in a matrix, which is part of the object. The object also holds the vertices and the VBO. Let's call it class Cube, which thus holds glm mat4 m transform. I expose m transform and pass it with glUniformMatrix4fv(shader.GetUniformLocation("model"), 1, GL FALSE, glm value ptr(m transform)) And at some point I call glDrawArrays(GL TRIANGLES, 0, 36) to draw the platform player cube. So to alter the position of such a cube, I would alter m transform. Such as m transform glm translate(m transform, vec) where glm vec3 vec is the desired translation to apply. However, the issues arise when u wish to scale a cube as well, so if we scale with vec3(0, 2, 0), the translations will be twice as large. And I'm unsure where to go from here. I've read that having different matrices for translation, rotation and scaling is the way to go, which I will try, however, I would like to know what the best practices are surrounding this subject. Any suggestions are much appreciated!
1
Most efficient way of brighten and darken sprites with OpenGL 2.0 So I have been shading (brighten darken adding color) my sprites by using glTexEnvf with GL MODULATE and GL ADD and a vertex color. I only had to rebind the batch every time I needed to change from modulate to add and vice versa. it was not perfect but worked well enough. However libGDX 1.0 dropped support for OpenGL1.1 and the only way I see is to use shaders. I want to stay up to date and therefore want to update. I am new to shaders but I found some code that works to brighten a sprite. However as far as I understood I need to rebind the batch every time I want another value for my brightness batch binding on every sprite I render. That is not very performant. Is there a way to change values between the bindings? (I don't think it's possible because shaders get compiled afaik). Or do you have another idea how to archive this effect with openGL2.0 (like I did before)? Or is rebinding every sprite the most efficient way with OpenGL2.0?
1
glsl directional light specular seems to be relative to origin not camera I've been using the LearnOpenGL tutorials to calculate directional light. The diffuse works perfectly fine but the specular seems only work properly when the camera is near the origin and the specular is applied the same to all objects. When I look at the second to last object i expect the specular to be the same as the object around the origin but instead it seems reacts to the origin and not the camera. My guess is it's something to do with converting something to model space instead of camera space but as i'm new to glsl i'm lost as to where to look first. Vertex shader version 330 core layout (location 0) in vec3 vertexPosition layout (location 1) in vec2 vertexUV layout (location 2) in vec3 vertexNormal out vec3 VectorWorldPosition out vec2 UV out vec3 Normal cameraspace uniform mat4 MVP uniform mat4 V uniform mat4 M void main() gl Position MVP vec4(vertexPosition, 1.0f) VectorWorldPosition (M vec4(vertexPosition, 1.0f)).xyz Normal cameraspace vertexNormal (M V vec4(vertexNormal, 1.0f)).xyz UV vertexUV Fragment Shader version 330 core in vec3 vertexWorldPosition in vec2 UV in vec3 Normal cameraspace out vec4 color struct DirectionalLight vec3 position vec3 ambient vec3 diffuse vec3 specular struct Material sampler2D diffuse sampler2D specular float shininess uniform DirectionalLight dirLight uniform Material material uniform vec3 viewPos vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir) void main() vec3 output vec3(0.0f) vec3 norm normalize(Normal cameraspace) vec3 viewDir normalize(viewPos vertexWorldPosition) output CalcDirectionalLight(dirLight, norm, viewDir) color vec4(output, 1.0f) vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir) vec3 lightDirection normalize(light.position) float diff clamp(dot(normal, lightDirection), 0.0, 1.0) vec3 reflectDir reflect( lightDirection, normal) float spec pow(max(dot(viewDir, reflectDir), 0.0), material.shininess) vec3 ambient light.ambient vec3(texture(material.diffuse, UV)) vec3 diffuse light.diffuse diff vec3(texture(material.diffuse, UV)) vec3 specular light.specular spec vec3(texture(material.specular, UV)) return (ambient diffuse specular) I'm using light position here when the tutorial asks to use direction. My thinking is that relative to the origin, position will be equal to direction. This works fine for diffuse so it should it work for specular.
1
Modifying GLFW callbacks I'm currently using Imgui for the GUI part of my OpenGL C engine with the GLFW binding. The problem is though that this binding has encapsulated the input callbacks in a global .cpp file which makes it impossible to access for other classes. Now I could always use the regular routine to handle input without the callbacks like if(glfwGetKey(m window, GLFW KEY A) GLFW PRESS) ... but yet this won't give me the one to one mapping like the key callback provides as the conditional code is processed more than once. I have tried using static booleans without success to see if I could overcome the problem by setting the boolean to true when the key is pressed in the callback and then handling the outcome elsewhere. I also know that you can override callbacks with different ones but that would not make any sence in this case. Does anyone know how to solve this problem?
1
Is GL DEPTH COMPONENT32 deprecated in OpenGL 4.5? I'm in the process of migrating our object oriented OpenGL wrapper from 3.3 core to 4.5 core. Some OpenGL implementations are notoriously permissive on what inputs they'll accept which can make tracking down bugs difficult. Wherever possible the inputs to our wrapper are validated with asserts to keep them in line with the spec. While setting up the asserts for glTextureStorage3D I've noticed that according to this page on the Khronos website it only accepts the following sized depth types GL DEPTH COMPONENT32F, GL DEPTH COMPONENT24, GL DEPTH COMPONENT16, GL DEPTH32F STENCIL8 or GL DEPTH24 STENCIL8. Non floating point 32bit depth types seem to be missing from that list which leads me to believe they're no longer supported (or at least actively discouraged). There's also this answer to another question which states that GL DEPTH COMPONENT32 is probably overkill, and as of 4.5, isn't a required format for OpenGL implementations to support (though 16 and 24 bit ones are). I have tried to find some reference to this in the 4.5 core spec but turned up nothing. Is GL DEPTH COMPONENT32 a deprecated size type? If so, why?
1
OpenGL Insanely Slow I'm learning C , and I'm writing my first OpenGL program. Unfortunately, it seems to be defaulting to Software Rendering (CPU uses bounces, GPU uses stays at 1 ). I'm using SDL as the Windowing system. I've got no idea why, but when there is significant scaling, the program grinds to a halt. My PC should be able to handle it I'm using an 8800GTX. My texture is 1024x1024, 32 bit RGBA and loaded with DevIL, and glGetString(GL VENDOR) is returning "NVidia Corporation". Any ideas? I'm sorry to be dumping all the code, but I've got absolutely no idea at all what is doing it. I'm very new to OpenGL. pragma once include "SDL.h" include "SDL opengl.h"7 include "IL il.h" include "IL ilut.h" include lt math.h gt const int SCREEN WIDTH 1024 const int SCREEN HEIGHT 768 const int SCREEN BPP 32 const int FPS 60 const int XSIZE 1024 const int YSIZE 768 int main( int argc, char argv ) bool quit false SDL Init(SDL INIT EVERYTHING) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL RED SIZE, 8) SDL GL SetAttribute(SDL GL GREEN SIZE, 8) SDL GL SetAttribute(SDL GL BLUE SIZE, 8) SDL GL SetAttribute(SDL GL ALPHA SIZE, 8) SDL SetVideoMode(SCREEN WIDTH, SCREEN HEIGHT, SCREEN BPP, SDL HWSURFACE SDL OPENGL) glEnable(GL TEXTURE 2D) const GLubyte Vendor glGetString(GL VENDOR) glClearColor(0.0f, 0.0f, 0.0f, 1.0f) Clear the background of our window to red glMatrixMode (GL PROJECTION) glLoadIdentity () glOrtho(0, XSIZE, YSIZE, 0, 0, 1) glMatrixMode (GL MODELVIEW) glDisable(GL DEPTH TEST) GLuint image ilInit() ilutRenderer(ILUT OPENGL) ILuint texid ILboolean success ilGenImages(1, amp texid) ilBindImage(texid) success ilLoadImage("Textures.png") if (success) success ilConvertImage(IL RGBA, IL UNSIGNED BYTE) if (!success) SDL Quit() return 1 glGenTextures(1, amp image) glBindTexture(GL TEXTURE 2D, image) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, ilGetInteger(IL IMAGE BPP), ilGetInteger(IL IMAGE WIDTH), ilGetInteger(IL IMAGE HEIGHT), 0, ilGetInteger(IL IMAGE FORMAT), GL UNSIGNED BYTE, ilGetData()) ilDeleteImages(1, amp texid) else SDL Quit() return 2 SDL Event event float x 0.0f while (!quit) while ( SDL PollEvent( amp event) ) switch (event.type) case SDL QUIT quit true break glClear(GL COLOR BUFFER BIT) glLoadIdentity() glTranslatef(200.0f, 200.0f, 0.0f) glRotatef(x,0.0f,0.0f, 1.0f) glScalef(1.0f x, 1.0f x, 1.0f x) glBegin(GL QUADS) glTexCoord2f(0.0f, 0.0f) glVertex2f( 100, 100) glTexCoord2f(0.0f, 0.119140f) glVertex2f( 100, 100) glTexCoord2f(0.091797f, 0.119140f) glVertex2f(100, 100) glTexCoord2f(0.091797f, 0.0f) glVertex2f(100, 100) glEnd() x 0.1f SDL GL SwapBuffers() glFlush return 0 Edit (24 04 2011 9.22 PM AEST) When run on an ancient card, on an ancient computer, it maintains 60FPS.
1
C Help with Separating Axis Theorem I am trying to detect collision between two triangles using Separating Axis Theorem however I am unaware what is wrong with my code. The CollisionHelper isTriangleIntersectingTriangle is called every frame and passes in the vertices of both triangles. It never returns true, however. I've been stuck on this for days now. Any help is appreciated. glm vec3 CalcSurfaceNormal(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3) Subtracts each coordinate respectively glm vec3 u tri2 tri1 glm vec3 v tri3 tri1 glm vec3 nrmcross glm cross(u, v) nrmcross glm normalize(nrmcross) return nrmcross bool SATTriangleCheck(glm vec3 axis, glm vec3 tri1vert1, glm vec3 tri1vert2, glm vec3 tri1vert3, glm vec3 tri2vert1, glm vec3 tri2vert2, glm vec3 tri2vert3) int t1v1 glm dot(axis, tri1vert1) int t1v2 glm dot(axis, tri1vert2) int t1v3 glm dot(axis, tri1vert3) int t2v1 glm dot(axis, tri2vert1) int t2v2 glm dot(axis, tri2vert2) int t2v3 glm dot(axis, tri2vert3) int t1min glm min(t1v1, glm min(t1v2, t1v3)) int t1max glm max(t1v1, glm max(t1v2, t1v3)) int t2min glm min(t2v1, glm min(t2v2, t2v3)) int t2max glm max(t2v1, glm max(t2v2, t2v3)) if ((t1min lt t2max amp amp t1min gt t2min) (t1max lt t2max amp amp t1max gt t2min)) return true if ((t2min lt t1max amp amp t2min gt t1min) (t2max lt t1max amp amp t2max gt t1min)) return true return false bool CollisionHelper isTriangleIntersectingTriangle(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3, glm vec3 otherTri1, glm vec3 otherTri2, glm vec3 otherTri3) Triangle surface normals, 2 axes to test glm vec3 tri1FaceNrml CalcSurfaceNormal(tri1, tri2, tri3) glm vec3 tri2FaceNrml CalcSurfaceNormal(otherTri1, otherTri2, otherTri3) glm vec3 tri1Edge1 tri2 tri1 glm vec3 tri1Edge2 tri3 tri1 glm vec3 tri1Edge3 tri3 tri2 glm vec3 tri2Edge1 otherTri2 otherTri1 glm vec3 tri2Edge2 otherTri3 otherTri1 glm vec3 tri2Edge3 otherTri3 otherTri2 axes TODO may need to (un)normalize the cross products glm vec3 axis1 tri1FaceNrml glm vec3 axis2 tri2FaceNrml glm vec3 axis3 glm normalize(glm cross(tri1Edge1, tri2Edge1)) glm vec3 axis4 glm normalize(glm cross(tri1Edge1, tri2Edge2)) glm vec3 axis5 glm normalize(glm cross(tri1Edge1, tri2Edge3)) glm vec3 axis6 glm normalize(glm cross(tri1Edge2, tri2Edge1)) glm vec3 axis7 glm normalize(glm cross(tri1Edge2, tri2Edge2)) glm vec3 axis8 glm normalize(glm cross(tri1Edge2, tri2Edge3)) glm vec3 axis9 glm normalize(glm cross(tri1Edge3, tri2Edge1)) glm vec3 axis10 glm normalize(glm cross(tri1Edge3, tri2Edge2)) glm vec3 axis11 glm normalize(glm cross(tri1Edge3, tri2Edge3)) Perform SAT if (SATTriangleCheck(axis1, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis2, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis3, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis4, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis5, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis6, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis7, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis8, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis9, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis10, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis11, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true return false
1
Linking error at tessellation shaders in GLSL I'm testing the triangle tessellation from the link http prideout.net blog ?p 48 shaders . All the shader are compiled correctly, but when I try to link the program using the command glLinkProgram(programID) I got the following error Tessellation control info (0) error C6029 No input primitive type Tessellation evaluation info (0) error c7005 No tessellation primitive mode specified Geometry info (0) error C6022 No input primitive type (0) error C6029 No ouput primitive type Not valid It's so strange I declare output for TC Shader using command layout(vertices 3) out And input layout for TE shader using command layout(triangles, equal spacing, cw) in Why I still got this error? I hope to see you answer about it. I put my shaders in below Vertex shader version 410 core in vec4 Position out vec3 vPosition void main() vPosition Position.xyz TC shader version 410 core layout(vertices 3) out in vec3 vPosition out vec3 tcPosition define ID gl InvocationID void main() float TessLevelInner 3 float TessLevelOuter 2 tcPosition ID vPosition ID if (ID 0) gl TessLevelInner 0 TessLevelInner gl TessLevelOuter 0 TessLevelOuter gl TessLevelOuter 1 TessLevelOuter gl TessLevelOuter 2 TessLevelOuter TE Shader version 410 core TessEval layout(triangles, equal spacing, cw) in in vec3 tcPosition out vec3 tePosition out vec3 tePatchDistance uniform mat4 Projection uniform mat4 Modelview void main() vec3 p0 gl TessCoord.x tcPosition 0 vec3 p1 gl TessCoord.y tcPosition 1 vec3 p2 gl TessCoord.z tcPosition 2 tePatchDistance gl TessCoord tePosition normalize(p0 p1 p2) gl Position Projection Modelview vec4(tePosition, 1) Geometry shader version 410 core geometry shader layout(triangles) in layout(triangle strip, max vertices 3) out in vec3 tePosition 3 in vec3 tePatchDistance 3 out vec3 gFacetNormal out vec3 gPatchDistance out vec3 gTriDistance uniform mat4 Modelview uniform mat3 NormalMatrix void main() vec3 A tePosition 2 tePosition 0 vec3 B tePosition 1 tePosition 0 gFacetNormal NormalMatrix normalize(cross(A, B)) gPatchDistance tePatchDistance 0 gTriDistance vec3(1, 0, 0) gl Position gl in 0 .gl Position EmitVertex() gPatchDistance tePatchDistance 1 gTriDistance vec3(0, 1, 0) gl Position gl in 1 .gl Position EmitVertex() gPatchDistance tePatchDistance 2 gTriDistance vec3(0, 0, 1) gl Position gl in 2 .gl Position EmitVertex() EndPrimitive() Fragment Shader version 410 core fragment shader out vec4 FragColor in vec3 gFacetNormal in vec3 gTriDistance in vec3 gPatchDistance in float gPrimitive uniform vec3 LightPosition float amplify(float d, float scale, float offset) d scale d offset d clamp(d, 0, 1) d 1 exp2( 2 d d) return d void main() vec3 AmbientMaterial vec3(0.04f, 0.04f, 0.04f) vec3 DiffuseMaterial vec3(0, 0.75, 0.75) vec3 LightPosition vec3(0.25, 0.25, 1) vec3 N normalize(gFacetNormal) vec3 L LightPosition float df abs(dot(N, L)) vec3 color AmbientMaterial df DiffuseMaterial float d1 min(min(gTriDistance.x, gTriDistance.y), gTriDistance.z) float d2 min(min(gPatchDistance.x, gPatchDistance.y), gPatchDistance.z) color amplify(d1, 40, 0.5) amplify(d2, 60, 0.5) color FragColor vec4(color, 1.0)
1
Uniforms stop working when loading multiple programs via glUseProgram() The rendering keeps happening, and the debugger shows my camera is getting its position updated properly, but for some reason the camera doesn't appear to have its position updated. I'm not sure what I'm doing wrong. Can uniforms fail to get set when swapping between different programs shaders?
1
Why is Minecraft's default resolution (seemingly) non standard? Background I'm writing some articles on Minecraft in an attempt to introduce 10 year olds to development through modding. I know very little about the game itself, though ) I'm trying to understand why Minecraft appears to run in an "odd" default resolution. Grabbing a screenshot, I think it's rendering at 550x310 but that doesn't seem to match any of the "common" aspect ratios (although it's close to 16 9), nor is it evenly divisible by 16, which appears to be what the texture packs use. Is it actually running at 550x310 in its default windowed mode? If not, what is the resolution? Depending on the answer to the first question, why isn't it using one of the standard aspect ratios? I'm not familiar with OpenGL programming either so perhaps there is a common resolution close to what I'm guessing at that would make perfect sense.
1
What are the benefits of capping frames per second? (If any) I am working on a simple game in OpenGL, using SDL for display initialization and input, and it appears in terms of timing I have two options available to me. Number one being just sleeping for the optimalTimePerFrame theTimeTakenToRender, when the optimalTimePerFrame in seconds 1 theFramerateCap. (I'm not entirely sure if this is necessary, as it is equivalent to using vsync, which may be more accurate. If my assumption is correct then please tell me wheter or not SDL OpenGL has vsync by default, and if not how to enable it.) The other is to measure the time since the last frame was rendered, and merely adjust movement accordingly. (The shorter time taken to render a frame, the less far entities move in that frame). In terms of performance, and decreasing flicker etc, what are the advantages and disadvantages of these two methods?
1
Is Ada suitable for game development? Would Ada be a practical language for game development (at least for the PC I understand there aren't compilers for PlayStation and other consoles)? It has bindings to OpenGL, it has decent performance, and it's less error prone than C . Please feel encouraged to support your point with relevant example projects you know about.
1
OpenGL large tile map rendering I want to be able to have a big tilemap (e.g. like Terraria, or an infinite procedural generated one), with only a handful of tiles on my screen. This means that I have a texture atlas (i.e. spritesheet) which contains the textures for the tiles. For the sake of simplicity, let's assume that I have a huge internal 2D array, containing the tileIDs and a lookup tablel hasmap for the UV coords for each tile type. All the tiles have the same dimension (the texture AND the onscreen tiles). I know a couple of methods to render such a 2D grid tilemap, but I don't know which one of them is a solid foundation for a game which heavily relies on modifiable tiles. Additionally, I want to be able to dynamically change the tilesize (i.e. zooming in out), modifying the tiles tilemap (e.g. destroying, building) and fast loading (fast paced player actions). Using a single draw call. I create a VBO with all the quads to fill the screen (multiple overlapping vertices, because each quad needs a different texture) and have a persistent buffer to modify the texture buffer object. As soon as the camera moves, I update the UV coordinates in the TBO. I can use attributeless rendering. I make a glDrawArrays call on an empty VAO, and use gl VertexID 6 and gl VertexID 6 to get the vertex ID and the tileID. To map the UV coordinates, I pass a TBO, which is updated at every camera move. I don't know how expensive this calculation is for the GPU. Hoping on the train of attributeless rendering, I can pass a uniform or create a const array to hold the UV offsets of every tile type, and only pass at every camera move the updated tile type IDs to the shader (with a uniform?). With gl VertexID 6 I know which index holds the current tiles type information, and then with this type, I can access my constant array to lookup the UV coordinates. Either using triangle strips, or indices to reduce the vertex count, and use provoking vertices to correctly map the UV coordinates (this can be combined with attributeless rendering). The vertices are all fixed for the window, and only the textures change. Here, once again, I have to map the TBO to a persistent buffer and update it at every camera move. Every tile gets a separate draw call (thus a separate VBO, IBO, TBO) and I can therefore render only the tiles which are seen by the camera. Because of the low amount of onscreen tiles, those separate draw calls shouldn't be too expensive. I put the whole map at the start of the game in the VAO and TBO, and modify the indices buffer, to only render the onscreen tiles (the IBO only holds enough indices to render the onscreen quads). My problem here is that I send too much data to the GPU every frame, and I have a really bad cache locality, because the information has to be accessed from different parts of the buffer objects. There might also be a way to use a geometric shader, although I have never used one. My concrete question is, is there a "state of the art" method to render big tilemaps, is any of my above mentioned ideas a good solution, and, does it really matter which option I use? Thank you!
1
c most used libraries I'm trying to find out whether or not I want to switch from Java to c for my OpenGL game programming. I now have setup a test project in VS 11 professional, with GLUT. I created my windows with GLUT, and I can render OpenGL primitives without any problems. Now my question What library(s) is are used mostly in the indie semi professional industry for using OpenGL in c ? With 'using OpenGL' I mean Creating and managing an OpenGL window Actually using the OpenGL API Handling user input (keyboard mouse)
1
View matrix in opengl Sorry for my clumsy question. But I don't know where I am wrong at creating view matrix. I have the following code createMatrix(vec4f(xAxis.x, xAxis.y, xAxis.z, dot(xAxis,eye)), vec4f( yAxis.x , yAxis.y , yAxis.z , dot(yAxis,eye)), vec4f( zAxis.x , zAxis.y , zAxis.z , dot(zAxis,eye)), vec4f(0, 0, 0, 1)) column1, column2,... I have tried to transpose it, but with no success. I have also tried to use gluLookAt(...) with success. At the reference page, I watched the remarks about the to be created matrix, and it seems the same as mine. Where I am wrong?
1
How to correctly specify the offset in a call to glVertexAttribPointer()? I'm trying to draw a simple triangle using the following vertices std vector lt VertexFormat gt vertices vertices.push back(VertexFormat(glm vec3(0.25, 0.25, 0.0), glm vec4(1, 0, 0, 1))) vertices.push back(VertexFormat(glm vec3( 0.25, 0.25, 0.0), glm vec4(0, 1, 0, 1))) vertices.push back(VertexFormat(glm vec3(0.25, 0.25, 0.0), glm vec4(0, 0, 1, 1))) The corresponding Vertex format is given by the following struct struct VertexFormat glm vec3 position glm vec4 color VertexFormat(const glm vec3 amp iPos, const glm vec4 amp iColor) position iPos color iColor The first call to glVertexAttribPointer() is easy since the position vector appears first in the struct, the call is as follows glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )0) The second call to glVertexAttribPointer() should be made specifying a suitable offset for the color attribute of a vertex. Since the color vector appears after the position, then such offset should be given by sizeof(glm vec3). The corresponding call is glVertexAttribPointer(1, 4, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )(sizeof(glm vec3))) The output of the program using these parameters is This output is wrong. There are only two colors (green and blue) and the colors are in the wrong position, note that the bottom left vertex is blue, but according to the code the vertex should be green. If the offset is changed to sizeof(glm vec4) the call is glVertexAttribPointer(1, 4, GL FLOAT, GL FALSE, sizeof(VertexFormat), (void )(sizeof(glm vec4))) And the triangle is rendered correctly So, Is my understanding of the offset parameter wrong? Why using an offset with the size of a vec4 gives the right output? Any help would be appreciated. P.S. Sorry for the bad english. Edit After reading the answer of Fibbles, and the comments of Fuzz Logic, I checked the size of the VertexFormat struct. A sizeof() gives a size of 32 bytes for a 32 bit executable. So padding is indeed the problem here. Using the macro suggested by Fibbles solves the problem. Thanks for everything guys!
1
Atmospheric scattering and sky geometry I'm trying to implement an atmospheric scattering in my graphics (game) engine based on the GPU Gems article link. An example implementation from that article uses a skydome. My scene is different I don't render a whole earth with an atmosphere which can be also visible from the space but some finite flat (rectangle) area with objects, for example a race track. In fact this is the most common scenario in many games. Now I wonder how to render a sky in such case What kind of geometry I should use skydome, skybox or a full screen quad then I have to move almost all calculations to the fragment shader, but I don't know if it makes sense in terms quality performance ? How to place sky geometry on the scene ? My idea I have a hemisphere (skydome) geometry with radius 1 and center in vec3(0, 0, 0) in object space. Those vertices are sent to the atmospheric scattering vertex shader layout(location 0) in vec3 inPosition Next, In the vertex shader I transform vertex this way v3Pos inPosition 0.25f 10.0f Uniform v3CameraPos vec3(0.0f, 10.0f, 0.0f), uniform fInnerRadius 10.0f, uniform fCameraHeight 10.0f Then I have correct an inner outer radius propotion (10 10.25),right? I also send to the vertex shader a model matrix which sets a position of the hemisphere to the postion of the mobile camera vec3(myCamera.x, myCamera.y, myCamera.z) vec4 position ProjectionMatrix ViewMatrix ModelMatrix vec4(inPosition, 1.0) gl Position position.xyww always fails depth test. The hemisphere moves together with the camera (encloses only some space around camera with radius 1, but it also always fails a depth test.) Unfortunately a sky color which I get is not correct What about a "sky curve"? Here is a picture which demonstrate what I mean How should I set a sky curve? Edit1 debugging In the vertex shader I assigned to v3Pos position of the "highest" vertex in the hemisphere vec3 v3Pos vec3(0.0f, 10.25f, 0.0f) Now the whole sky contains a color of that vertex
1
OpenGl indices array I have a class terrain which create a grid of Quads. I do it like this for(int z 0 z lt length z ) for(int x 0 x lt width x ) vertices.push back(vec3((float)x 250, 0.f, (float)z 250)) for(int z 0 z lt ( length 1) z) for(int x 0 x lt ( width 1) x) int index z width x Vertex vertices Vertex(vertices.at(index),vec3(0, 0, 0)), Vertex(vertices.at(index 1),vec3(0, 0, 0)), Vertex(vertices.at(index width),vec3(0, 0, 0)), Vertex(vertices.at(index 1 width),vec3(0,0,0)) unsigned short indices index,index 1,index width,index 1,index width,index width 1 Quad quad( vertices, 4, indices, 6) squares.push back(quad) i The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code But when I change this indices to this unsigned short indices 0,1,2,1,2,3 It works great The problem is I don't understand why this line unsigned short indices index,index 1,index width,index 1,index width,index width 1 doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code class Quad public Quad(Vertex vertices, int n, unsigned short indices, unsigned short numIndices) for(int i 0 i lt numIndices i ) indices.push back( indices i ) for(int i 0 i lt n i ) vec3 v vec3( vertices i .position, lengthPower) position.push back(v) glGenVertexArrays(1, amp mVertexArray) glBindVertexArray(mVertexArray) glGenBuffers(1, amp mPositionBuffer) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glBufferData(GL ARRAY BUFFER, sizeof(vec3) position.size(), position.data(), GL STATIC DRAW) glGenBuffers(1, amp mIndicesBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(unsigned short) indices.size(), indices.data(), GL STATIC DRAW) void draw() glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glVertexAttribPointer(0, 4, GL FLOAT, GL FALSE, 0, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glDrawElements(GL TRIANGLES, indices.size(), GL UNSIGNED SHORT, 0) glDisableVertexAttribArray(0) Quad() private std vector lt unsigned short gt indices std vector lt vec3 gt position GLuint mVertexArray GLuint mPositionBuffer GLuint mIndicesBuffer I'm using, OpenGL, glm, glfw etc.
1
OpenGL pitching problem I've been trying to implement several camera movements for my application. So far yawing, rolling, strafing, walking has been working properly, but I can't get my pitching to work properly. If I continue pitching upwards, it doesn't rotate back 360 degree, and instead gets stuck looking at the top of the screen. Here's my code for Camera class class Camera float m 16 Vector dirForward, dirUp, dirRight void loadCameraDirections() glGetFloatv(GL MODELVIEW MATRIX, m) dirForward Vector(m 2 , m 6 , m 10 ).unitVector() dirUp Vector(m 1 , m 5 , m 9 ).unitVector() dirRight Vector(m 0 , m 4 , m 8 ).unitVector() public Vector position Vector lookAt Vector up Camera() position Vector(300, 0, 100) lookAt Vector(0, 0, 100) up Vector(0, 0, 1) void rotatePitch(double rotationAngle) glPushMatrix() glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z) loadCameraDirections() glPopMatrix() lookAt position.repositionBy(dirForward.reverseVector()) cam I call the gluLookAt funtion by gluLookAt(cam.position.x, cam.position.y, cam.position.z, cam.lookAt.x, cam.lookAt.y, cam.lookAt.z, cam.up.x, cam.up.y, cam.up.z)
1
OpenGL Maximal amount of debug string reached I was trying to check my current openGL code in gDEBugger, everything works fine. But, I get these messages Debug String gt gt gt gt gt gt gt gt gt 1 Debug String gt gt gt gt gt gt gt gt gt 2 Debug String gt gt gt gt gt gt gt gt gt 3 ... Debug String gt gt gt gt gt gt gt gt gt 497 Debug String Maximal amount of debug string reached (500 strings). Additional debug strings will be ignored What are these messages, everything in my code runs fine. But its troubling to see these debug strings.
1
How to determine what color will be written into single pixel framebuffer? I thinking about rendering into single pixel (1x1) framebuffer. For example we have two triangles which covers whole NDC area, one is green second red. What color will be written to 1x1 framebuffer? As far as I understend graphic API (no matter which) tries to put whole scene in to given framebuffer, in our example, into single pixel. But I can't figure how GPU will choose what should be written into that pixel.
1
Game development for high school with C and OpenGL I've been teaching high school students (12th grade) game programming in the last 2 years. The way I did this till now, was first to give them "half made" classes (for Point, Polygon, etc.) and they've completed them with my help their friends themselves, and then they were free to design their models, and write their game logic. The programming language was C and I used GLUT. I gave the students the base class that does all inits for OpenGL so they didn't work on it (except some high motivated students that wanted to extend their graphics). My goal was to teach them the fundamentals of C using OOP, by implementing their own classes rather than teaching them methods from OpenGL GLUT API. It's also important to notice that most of those students never programmed in their life and all they knowledge comes from theory in high school computer science. I write this post here to get your opinions about the way I handled this class until now, do you think I've done wrong not teaching the OpenGL GLUT API? do you think I need to utilize OpenGL power to implement basic models, or it's good practice to let them implement models by themselves? Maybe I don't need to use GLUT anymore because there are modern libraries these days that does better work, or it doesn't matter as long as it's for learning purposes? I really want to give the students motivation by demonstrating what they can do in modern game programming, but I still got my limits which I wrote here, and also time limit (the class is one year, one lesson each week). Thanks for your help!
1
OpenGL Array Texture generates black texture I am creating a game using OpenGL that has many textured cubes. I am trying to use an Array Texture to load multiple textures from one file. I tried to setup my texture atlas however, all that renders is a black texture. I'm not sure what exactly I am doing wrong. Here is the texture loading code Load image stbi set flip vertically on load(true) unsigned char data stbi load(path, amp width, amp height, amp nrChannels, 0) Generate texture object glActiveTexture(GL TEXTURE0) glGenTextures(1, amp textureId) glBindTexture(GL TEXTURE 2D ARRAY, textureId) Actually load texture if (data) glTexImage3D(GL TEXTURE 2D ARRAY, 0, GL RGBA, width, height, 0, 0, GL RGB, GL UNSIGNED BYTE, data) glGenerateMipmap(GL TEXTURE 2D ARRAY) else std cout lt lt "Failed to load " lt lt path lt lt " texture" lt lt std endl set texture filtering parameters glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MAG FILTER, GL NEAREST) Free memory stbi image free(data) Here is my fragment shader version 330 core out vec4 FragColor in vec2 TexCoord uniform sampler2DArray my sampler void main() FragColor texture(my sampler, vec3(0, 0, 1)) vec4(1.0f) Here is my texture file Does anyone know how I can solve my issue?
1
Make openGL program only update every 1 60 seconds I'm learning C and openGL and have this program as a result from tutorials and playing around. The problem is that the main loop is running at "full speed", making the program unnecessarily cpu intensive. I have managed to make it only perform rendering every 16.7 ms or so, but the outside loop that is waiting to render still is iterating as fast as my computer can handle. This is the full main.cpp http pastebin.com KaCW7wZw This is the main loop at line 95 while (!terminate) if (SDL GetTicks() gt time start frame rate) time start SDL GetTicks() while (SDL PollEvent( amp event)) if (event.type SDL QUIT) terminate true break glClearColor(0.1f, 0.1f, 0.1f, 1.0f) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) renderLoop(entities, amp counter) SDL GL SwapWindow(m window) counter 1.0f I've tried googling and haven't found anything concrete (obviously), except that using some kind of sleep is bad design for these loops. So how can I alter this to slow the whole thing down, and avoid having 100 cpu usage for a program that's not doing much at the moment?
1
Rotating a scene around a fixed axis I am looking for a way to move my scene so that when I translate forward back left right it moves directly up down left right on the screen. Currently it does do that until I rotate (by anything other than 360...). After rotation the up down left right moves in the direction of the rotation. I need it to move directly up down left right on screen. I've been racking my brains trying all kinds of different matrix rotations and multiplication but I can't get it. MOST IMPORTANTLY I need it to maintain a single rotation axis of 0,0,0 so the centre of rotation is always near the middle of the screen regardless of how far I scroll. I can easily rotate on the centre of the scene itself and have it translate how I want (translate to co ord, rotate, translate back, go to position) but I need that axis to remain fixed. Otherwise the centre of rotation could be somewhere way off screen. Fig 1. Shows the starting position of the model(scene). Fig 2. The modelview is rotated 45deg. Fig 3. Decrementing the z value causes the model to move out along z which I do not want. Fig 4 I need the model to move straight back (between z and x). I have tried using sin cos rule in an attempt to translate the vertices back along the arc between the undesired position (Fig 3) and the desired one (Fig 4) but the math is off and the process is messy. I just know there has to be a clean simple solution out there. I am coding this in Java (JOGL) and passing modelview and projection matrices to a vertex shader. Also, I am not using deprecated functions (no begin end glRotate etc). Does anyone know of a matrix multiplication that will accomplish this?
1
GLSL "varying" interpolation component wise? Reference in the spec? Probably a dumb question, but I can't find (or am not understanding) a conclusive answer in the spec or in other questions (e.g., this one). For smoothly interpolated varying vec and mat vertex shader outputs fragment shader inputs, is each element of the vector or matrix interpolated individually? GL spec sec. 13.5.1 (clipping) describes linear clip space interpolation of the "output values associated with a vertex." It also says that those are componentwise for vectors, but doesn't mention matrices. Similarly, sec. 14.5.1 (rasterizing lines) and sec 14.6 (rasterizing polygons) describe interpolation of an "associated datum f for the fragment". Is each element of a vector or matrix considered an individual "associated datum" and interpolated independently from the other elements of the vector or matrix? Secs. 11.1.3.10 (shader outputs) and 15.1 (fragment shader variables) mention interpolation but refer elsewhere for the details. Similarly, in the GLSL spec, sec. 4.5 (interpolation qualifiers) says that interpolation happens but does not distinguish scalars from multi component variables. I am looking for a definitive statement about how vecs and mats are interpolated, if there is one. Or let me know if there isn't! Thank you! (Note answers can be for any OpenGL version.)
1
opengl storing multiple indices into indices buffer After parsing collada files I found out that we have to load two(or more) indices each pointing to say a vertex or normal etc. like this ( lt p 3 0 2 0 0 0 lt p ) Is there a way to load (and use)these indices to indices buffer(ELEMENT ARRAY BUFFER) like this (vnvnvn...) where v is vertex pointer, n is normal pointer from the above. with vertices loaded to VBO1 like (vvvv...) and in VBO2 like (nnnn...). So that we dont have to repeat the normals in VBO2. VBO like (vnvnvn...) is also ok. (and not something like this https stackoverflow.com questions 11148567 rendering meshes with multiple indices), I'm not trying to use multiple indices buffer. I'm trying to put all the given indices into one index buffer and use them alternately. (If I wasnt clear i will try for more clarification.)
1
Moving a camera without rolling (tumble not arcball rotation) I'm trying to move my camera around using mouse keyboard. I'm looking for specific camera behaviour however, and I cant figure out how to get it right. What I've found, is that to get a maya tumble style camera, I need to multiply my xrotation in world space then my yrotation. Reversing the order it looks like this view cam move wasd in cam space, this works correctly yrot before world to camera space view xrot after model to world space This means my xrot(world) doesn't interfere with my yrot(eye), which avoids unwanted roll induced by regular cam space x rotation. My problem however, is that I want the xrotation to happen around a point (as if done in eye space) but without creating unwanted roll. I do not know how to get that result. According to my sources It should be as easy as translating inversely before xrotating, then translating back after, but its just not working. Perhaps someone knows how I can get my cam to spin (yaw) around a point, without causing the unwanted roll? SOLUTION Keeping track of pitch yaw (mouse move.xy) seperately, as well as the camera location, and making sure to multiply the yaw before the pitch. Pitching will create unwanted roll, but yawing wont create unwanted pitch, so its a matter of which you do first here. To move the camera in eye space, I do this make a mat3 rotation matrix and multiply it with current movement if (keys 'A' keys 'D' keys 'W' keys 'S' ) camlocation rotated then moved (glm normalize(vec3(keys 'A' keys 'D' , 0, keys 'W' keys 'S' )) move speed) mat3(glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0))) mat3(glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0))) which will be a value to add in world space Then under camera update, or where I build the view matrix, I do this view glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0)) pitch radian float glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0)) yaw also in radian glm translate(mat4(1.0f), camlocation) Just remember that in OpenGL GLM the matrix transformations are reverse order, due to how OpenGL does column row matrix computations. (Compared to directx it saves a transpose operation in the shader (apparently)) Making sure to yaw before pitching, and both after translating (reversed on paper) avoids the unwanted roll, wich yields the desired tumble maya effect!
1
How to load a spherical planet and its regions? I'm designing a game partially composed of planets exploration. I want to use pseudo random generation for them, regenerating from a defined seed when I have to load them rather than store every detail, which would be too heavy. So I will just store in a file the random seed and modifications done by the player if any. The player must be able to see the planet from orbit (with very low level of details, then go down to the ground, increasing slowly the level of details of the region where he she is landing, and unloading the ones on the other sides of the planet, which go outside the player's field of view. If I had to do it on a plane ground, I would do it easily with a square chunk system. But the problem here is that planets are almost spheres. So what would be the best way to load ground details (relief and grounded objects) around a precise point ? I already though on two solutions, but both have a weak point 1. Cutting the sphere in square chunks. Once the player is close enough of the ground, I just have to improve details of closest squares from his her position. If it is not enough, I still can cut each square in sub squares to load when the players is on or really close of the ground. But as you can see on the picture, there is a problem if the player try to land on a pole squares become very slim rectangles, or even triangles for the last line, and additionally to the fact that they would be many to load, generation would appear distorted. 2. Starting from an icosahedron. Here, I could just increase triangle tessellation around player's position when he she is getting close. But I don't know how to locate triangles close than player's position. I heard Cartesian coordinates could be usefull in that case, but I don't know how to use them. I'm using C OpenGL for it, so the main thing to generate and load here are vertices representing the surface relief and color texture.
1
OpenGL glTexImage3D not working? I'm trying to use arrax textures with opengl 3.3 since this the target version for my application. So I have to use the glTexImage3D() method instead of glTexStorage3D(). The problem is, if I use glTexImage3D() instead of glTexStorage3D() the screen is always black. The other way round, everything works. Here is how I create the array texture public ArrayTexture(int width, int height) this.width width this.height height this.arrayTextureHandle GL11.glGenTextures() GL13.glActiveTexture(GL13.GL TEXTURE0) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, arrayTextureHandle) Works perfect GL42.glTexStorage3D(GL30.GL TEXTURE 2D ARRAY, 1, GL11.GL RGBA8, width, height, 10) Doesn't work with these parameters GL12.glTexImage3D(GL30.GL TEXTURE 2D ARRAY, 0, GL11.GL RGBA8, width, height, 10, 0, GL11.GL RGBA, GL11.GL UNSIGNED BYTE, (ByteBuffer)null) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, 0) public void addTexture(ScrollingSprite... sprites) if(zLayerCounter sprites.length lt MAX LAYERS) GL13.glActiveTexture(GL13.GL TEXTURE0) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, arrayTextureHandle) Arrays.asList(sprites).forEach(sprite gt sprite.getTexture().getTextureData().prepare() GL12.glTexSubImage3D(GL30.GL TEXTURE 2D ARRAY, 0, Mipmap number 0, 0, zLayerCounter , xoffset, yoffset, zoffset width, height, 1, width, height, depth GL11.GL RGBA, format GL11.GL UNSIGNED BYTE, type sprite.getTexture().getTextureData().consumePixmap().getPixels()) pointer to data GL11.glTexParameteri(GL30.GL TEXTURE 2D ARRAY, GL11.GL TEXTURE WRAP S, sprite.getTextureWrapS()) GL11.glTexParameteri(GL30.GL TEXTURE 2D ARRAY, GL11.GL TEXTURE WRAP T, sprite.getTextureWrapT()) ) GL11.glBindTexture(GL30.GL TEXTURE 2D ARRAY, 0) else throw new IllegalArgumentException("Maximum number of textures reached!")
1
What advantages does bare OpenGL provide over frameworks engines to small developers? I've noticed a trend of indie developers steering away from frameworks and engines, and moving towards using bare OpenGL, or using it combined with SDL SFML2. As an indie developer, I can't see what low level OpenGL can offer over separate engines or frameworks. Most decent engines and frameworks give the functionality that you need, and never get in your way. They might also open the option to deal with OpenGL directly. Some even offer the functionality to compile cross platform! I understand the aspiration to learn what is happening below the hood, but I can't see any upsides that OpenGL might offer to indie developers over engines or frameworks. Could you explain the reasoning behind building games from scratch using OpenGL?
1
How to select a vertex by mouse clicking in OpenGL? I'm programming a simple graph game and so far I'm still doing a few tests in OpenGL. Right now, let's say I defined a GL POINT with the glVertex2f(20.0f, 0.0f). I have this function to calculate the coordinates from the mouse input to world coordinates void converterCoords(GLfloat winX, GLfloat winY) GLint viewport 4 GLdouble modelview 16 GLdouble projection 16 GLfloat winZ 0 glGetDoublev( GL MODELVIEW MATRIX, modelview ) glGetDoublev( GL PROJECTION MATRIX, projection ) glGetIntegerv( GL VIEWPORT, viewport ) winX (float)winX winY (float)viewport 3 (float)winY winZ 0 gluUnProject( winX, winY, winZ, modelview, projection, viewport, amp worldX, amp worldY, amp worldZ) After this I have a function to check if the mouse click coordinates are the same as one of the GL POINTS I defined int determinaPosicao(double x, double y) int i for(i 0 i lt nPontos i ) if(pontos i .vX x pontos i .vY y) pontos i .seleccionado 1 glutSetWindow(window) glutPostRedisplay() return 0 I can check just fine if the mouse click is the same as the if condition with the " " function, however, if I have two points with the same x or y value, then it will declare the mouse has hit both points. However, if I use the " amp amp " function it never seems to go into the if condition and never declares any point as having been hit. This certainly isn't the best way to achieve my goal and I would really like to ask for some opinions on how to do this. Solution I found with help from user concept3d int determinaPosicao(double x, double y) const double maxDist (1e0) int i printf(" f n", x) Escala no rato ap s convers o 5510 x (x xMaxRef) 10000 y (y yMaxRef) 10000 for(i 0 i lt nPontos i ) if(pow((pontos i .vX x), 2) lt maxDist amp amp pow((pontos i .vY y), 2) lt maxDist) pontos i .seleccionado 1 glutSetWindow(window) glutPostRedisplay() return 0 The operations I used in x (x xMaxRef) 10000 is a simple rule to scale the mouse coordinates (that range from 0 to approx 5510) from the max ortho referencial scale which is x and y 100, 100
1
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
1
Is Windows window creation faster more efficient than GLFW window creation? Are there any benefits to using Windows window for OpenGL or Vulkan rendering, rather than using GLFW window? Is there any performance hits when using C Window creation over GLFW since it provides OpenGL and Vulkan interface?
1
Finding the Dimension of OBJ objects I am having a Three OBJ file , Cone , Sphere and Cube. How can i find the dimension of these objects , so that i can use it in my collision detection class. i.e How can i find Radius , Length of Cube and Radius and Height of cone. Or is there any better way for collision detection , I have Hundreds of random particle in my game which may or maynot collide with these objects.
1
How to map trapezoid image to rectangle cubemap face? I am writing a 360 video application on oculus mobile SDK. My video frame has a trapezoid region and I need to map it into a rectangle region. In the above figure, trapezoid ABDC is part of my video frame. I need to map it into a rectangle A'B'D'C'. The rectangle is part of a face of a cube. At the video frame generation side, the trapezoid region is generated from a rectangle region. The bigger side of the trapezoid (AC in the abovefigure) is same as the height of rectangle (side A'C') and smaller side of trapezoid (side BD) is smaller than the height of the rectangle. I know I am loosing some details in this process and I am fine with it. At rendering side for mapping, I need to provide the region as combination of triangles. So I gave two triangles, ABC and CBD. But sice the triangle sizes are not equal, mapping was not proper. The triangle region CBD expands more compare to triangle region ABC. I also tried drawing diagonals to trapezoid ABDC and mapped using four triangles. Even with that logic I observed same issue. Update 1 Please refer to image3(https i.stack.imgur.com yRy9W.jpg) and image1(https i.stack.imgur.com dwOuI.jpg) of this question (https stackoverflow.com questions 15141039 transform rectangle to trapezoid for perspective). Please note, in my application decoded image will be like image3 and I need to render it such that it appears like image1. Can anyone suggest me the right way to map trapezoid to rectangle?
1
samplerCubeShadow and texture offset I use sampler2DShadow when accessing a single shadow map. I create PCF in this way result textureProjOffset(ShadowSampler, ShadowCoord, ivec2( 1, 1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2( 1,1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1,1)) result textureProjOffset(ShadowSampler, ShadowCoord, ivec2(1, 1)) result result 0.25 For a cube map I use samplerCubeShadow result texture(ShadowCubeSampler, vec4(normalize(position), depth)) How to adopt above PCF when accessing a cube map ?
1
Combine a light and water shader in libgdx glsl I am trying to combine a light shader with a water shader in libgdx. Shader programming is not one of my strengths at all. This is the water effect rendering nicely And when I have added the flickering light code I am getting this The light is meant to be a flickering white circle and the water should show up. It doesn't. What I have done so far is try to re arrange texture binding, combine drawing in one pass. I can render the other scene content on top of the water but the water has to be the top most item. That is what I am failing to do, Here is my wall of code (just the render function) public void render() float dt Gdx.graphics.getDeltaTime() water time dt float angle time (2 MathUtils.PI) if (angle gt (2 MathUtils.PI)) angle (2 MathUtils.PI) light zAngle dt zSpeed while (zAngle gt PI2) zAngle PI2 fbo.begin() batch.setProjectionMatrix(cam.combined) batch.setShader(defaultShader) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.begin() float lightSize 140.75f 0.25f (float) Math.sin(zAngle) 27.2f MathUtils.random() batch.draw(lighttex, 400 lightSize 0.5f 0.5f, 300 0.5f lightSize 0.5f, lightSize, lightSize) batch.end() fbo.end() draw the actual scene Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) batch.setProjectionMatrix(cam.combined) batch.setShader(finalShader) batch.begin() fbo.getColorBufferTexture().bind(1) lighttex.bind(0) batch.draw(map1BgTex, 0, 0, 960, 540) batch.setShader(waterShader) waterShader.setUniformMatrix("u worldView", cam.combined) batch.end() Gdx.gl20.glBlendFunc(GL20.GL SRC ALPHA, GL20.GL ONE MINUS SRC ALPHA) Gdx.gl20.glEnable(GL20.GL BLEND) watertex.bind(1) waterdisptex.bind(2) defWaterShader.begin() defWaterShader.setUniformMatrix("u worldView", matrix) defWaterShader.setUniformi("u texture", 2) defWaterShader.setUniformi("u texture2", 3) defWaterShader.setUniformf("timedelta", angle) waterMesh.render(defWaterShader, GL20.GL TRIANGLE FAN) defWaterShader.end() I uploaded a more complete source file and the shaders to my server, I hope it's not too inconvenient http agexdev.com files shaders.tar.xz
1
Calling opengl32.DLL from java? I don't like LWJGL in some cases, so I prefer to use Swing. The thing is that Swing doesn't have OpenGL. I have tried JOGL and it's a mess to install, needs external jars, and I have yet to get it working. So I was wondering if I could just make an OpenGL class that uses opengl32.DLL and put the graphics into a window made with Swing? Also, is opengl32.DLL able to be called with a 64 bit Java program?
1
Two UBO's end up containing the same data I have two separate UBO's for different types of lights (for a light stage in a deferred rendering system). These are defined as follows Pointlight UBO m pointLightBlockIndex glGetUniformBlockIndex(shader.getShaderHandle(), "PointLights") glGetActiveUniformBlockiv(shader.getShaderHandle(), m pointLightBlockIndex, GL UNIFORM BLOCK DATA SIZE, amp m PointLightBlockSize) glUniformBlockBinding(shader.getShaderHandle(), m pointLightBlockIndex, 0) Spotlight UBO m splBlockIndex glGetUniformBlockIndex(shader.getShaderHandle(), "SpotLights") glGetActiveUniformBlockiv(shader.getShaderHandle(), m splBlockIndex, GL UNIFORM BLOCK DATA SIZE, amp m SpotLightBlockSize) glUniformBlockBinding(shader.getShaderHandle(), m splBlockIndex, 0) create the buffers glGenBuffers(1, amp m SLBuffer) glGenBuffers(1, amp m PLBuffer) glBindBuffer(GL UNIFORM BUFFER, m SLBuffer) glBufferData(GL UNIFORM BUFFER, sizeof(SpotLightData) m MaxSpots, nullptr, GL DYNAMIC DRAW) glBindBuffer(GL UNIFORM BUFFER, m PLBuffer) glBufferData(GL UNIFORM BUFFER, sizeof(LightData) m MaxPoints, nullptr, GL DYNAMIC DRAW) glBindBuffer(GL UNIFORM BUFFER, 0) To populate the UBO's I use the following void LightUniformBuffer updatePointLights(int numLights, const LightData data) glBindBuffer(GL UNIFORM BUFFER, m PLBuffer) glBufferSubData(GL UNIFORM BUFFER, 0, sizeof(LightData) numLights, data) glBindBuffer(GL UNIFORM BUFFER, 0) void LightUniformBuffer updateSpotLights(int numLights, const SpotLightData data) glBindBuffer(GL UNIFORM BUFFER, m SLBuffer) glBufferSubData(GL UNIFORM BUFFER, 0, sizeof(SpotLightData) numLights, data) glBindBuffer(GL UNIFORM BUFFER, 0) And finally to bind them void LightUniformBuffer bindPointLights() glBindBufferBase(GL UNIFORM BUFFER, m pointLightBlockIndex, m PLBuffer) void LightUniformBuffer bindSpotLights() glBindBufferBase(GL UNIFORM BUFFER, m splBlockIndex, m SLBuffer) These buffers are represented as arrays of lights in GLSL, like so layout (std140) uniform PointLights LightData points MAX NUM POINT LIGHTS layout (std140) uniform SpotLights SpotLightData spots MAX NUM POINT LIGHTS Now, when I populate the buffers and use the shader, I found, through using Nsight, that both buffers are using the same set of data, i.e. the spotlight buffer is filled with point light data, and so is useless. Why is this happening, and how can I fix it?
1
Texture Mapping to procedurally generated geometry How can I calculate texture coordinates of such geometry? The angle shown in the image (89.90 degree) may vary, therefore the geometry figure is changing and is not always such uniform.(maybe like geometry in the bottom of image) and red dots are generated procedurally depends on degree of smoothness given.
1
Why does my blur shader implementation produce this strange result? I tried to implement the blur shader shown here. Instead of having a simple 2D texture I use Unity's GrabPass function to capture what's behind the plane to have a transparent effect. Then I apply this on a 3D plane struct v2f float4 pos SV POSITION float4 screenPos TEXCOORD3 float3 uv v2f vert(appdata full v) v2f o o.pos mul(UNITY MATRIX MVP, v.vertex) o.screenPos ComputeScreenPos(o.pos) o.uv UNITY PROJ COORD(o.screenPos) return o In the frag part there is the shader blur computation but based on XYZ, with Z 0 Then I apply the blur and this leads to this when I zoom in Is there a way to avoid this effect?
1
Can I change the order of these OpenGL Win32 calls? I've been adapting the NeHe OpenGL Win32 code to be more object oriented and I don't like the way some of the calls are structured. The example has the following pseudo structure Register window class Change display settings with a DEVMODE Adjust window rect Create window Get DC Find closest matching pixel format Set the pixel format to closest match Create rendering context Make that context current Show the window Set it to foreground Set it to having focus Resize the GL scene Init GL The points in bold are what I want to move into a rendering class (the rest are what I see being pure Win32 calls) but I'm not sure if I can call them after the Win32 calls. Essentially what I'm aiming for is to encapsulate the Win32 calls into a Platform Initiate() type method and the rest into a sort of Renderer Initiate() method. So my question essentially boils down to quot Would OpenGL allow these methods to be called in this order? quot Register window class Adjust window rect Create window Get DC Show the window Set it to foreground Set it to having focus Change display settings with a DEVMODE Find closest matching pixel format Set the pixel format to closest match Create rendering context Make that context current Resize the GL scene Init GL (obviously passing through the appropriate window handles and device contexts) Thanks in advance.
1
Opengl binding shaders vs binding buffers performance Quick question for an opengl guru, I'm in the process of building a render queue and can either reduce the number of shader binding or the number of vertex buffer binding. I just want to know which one is more expensive on newer graphics cards (IE)(opengl 3.2)?