Followers 0

# OpenGL Starting with GL Instancing, advice?

## 4 posts in this topic

Hey, I'm thinking about implementing Instancing, but before doing so, I need some general advice.

So far, most of the rendering is done by looping through (sorted) lists and call a VBO for each object. In some other cases, like drawing a simple sprite, I still use the good old "glVertex3f(...) <4 times>) method. And then for particles, I use a VBO containing many particles that can be updated with OpenGL Transform Feedback.

It makes sense that using Instancing helps when rendering lots of the same object (but at a different position, or with slight differences). But in practice, most of my objects only come in small numbers. 3 boxex, 5 decals, 1 barrel, et cetera. Does it still make sense to implement instancing, or does it actually slow down things with overhead? Or to put it different, when rendering a single quad, is instancing equal or faster than doing it the old 4x glVertex3f way?

Second, some of my objects are animated, and use Transform Feedback to let a Vertex Shader calculate the skinned vertex positions. Each animated model would have its own secundary VBO to write back the transformed vertices. This takes extra memory of course, then again the amount of animated objects is very small compared to the rest. I'm guessing this technique does not co-operate with instancing in any way right?

Third. My meshes use a LOD system. So when getting further away from the camera, they toggle to a simplified mesh. Is it possible to put all LOD models (usually I have 3 to 5 variants) in a single buffer and let the Instancing somehow pick the right variant depending on the distance? Or would using LOD's being less needed anyway?

Any other things I should keep in mind when working with Instancing?

Merci beaucoup

Rick

Edited by spek
1

##### Share on other sites

I'm still developing on OGL2.0+extensions, though here are my experiences/knowledge:

1. I draw gui elements (including letters for text!!) the old way (glVertex..,glColor, etc.), not using any buffers or lists and still the performance is remarkable (300-500 + few thousand letters,this will slow down the game, but most often only half the FPS on my nvidia8800).

2. Particles and decals are in a VBO (dynamic), no CPU update once they have been spawned (they move along a spline which is calculated on the GPU alone).

3. Static ad-hoc batching for grass, stones,small plants.

4. Every other object is rendered as single VBO call.

In my pipeline the most significant impact has the post-processing effects (screensize-bottleneck). I see it like that, that we (hobby-indie) devs have so much GPU/CPU power at hands, that up-front over-optimization is seldom necessary , your game will most likely benefit more from maintainable code.

Best to check, if you are pixel shader bound (screensize test), then try to check, if some state changes (texture switches etc.) are limiting your performance and eventually check if really draw calls are a limiting factor. I.e. most of my models don't have less then 1000 vertices, I never use LOD after seening no performances improvements.

But it depends on your hardware target and what you render (200 zombies  or 10 enemies ? A forest ? ).

If you want to optimize I would take a look at the particle system. The geometry shader could be used to improve the particle throughput (one vertex expanded to 4), though particles are most likely although pixel-bound.

Edited by Ashaman73
1

##### Share on other sites

Your approaches look pretty much like the techniques I also uses. Manual drawn stuff for quadlike HUD stuff, VBO's with transform feedback for decals, and 1 VBO call per object.

The amount of objects is most likely not a performance killer in my case indeed. Asides from particles, enities are rarely duplicates more than 10 times. Yet the goal now is not to make things faster, but just to be prepared in case we do actually need a high number of the same objects or decals. Which is not unrealistic when thinking about scenes with a lot of rubble, or foliage.

So, if Instancing comes for "free" even if you don't really make good use of it, it wouldn't hurt either to implement it, just in case. I'm not really worried about the code getting more stiff, as most of the objects to draw are grouped and sorted for batching already anyway.

Greets

0

##### Share on other sites

I haven't used VBOs much, but if you're building a sprite system, I would recommend a "sprite batch". You'd have two classes: Sprite and SpriteBatch. SpriteBatch holds an STL vector of vertices and an STL list of Sprite objects (could go with pointers and allocate too, and that would cut down on copy operations when manipulating the Sprite list). Then, each group of vertices in that vector correspond a sprite object. That sprite object would contain your sprite's properties list its transform matrix, position, dimensions, blit parameters, etc. the Sprite class would have a pointer to its "parent" SpriteBatch it belongs to so that it has access to the vertices it's manipulating. You could also add animation and physics properties to Sprite.

Sprite batch would also contain the texture you're using, and handle all rendering. The pros are that you draw all of your objects using that texture in one call. The drawback is that your'd software-transform each sprite using matrix math on the CPU. Still, you only transform the vertices when a change occurs instead of each frame. This could be costly for particle systems, but then again, you'd want point sprites for that!

EDIT: I forgot to mention models.

I would say it's a good idea to use VBOs with static models. Again, you'd have two classes similar to my sprite example about: Model and ModelObject. The model is in charge of loading the 3D model data from your file, and storing a copy of the data. Then, each ModelObject would be allocated to store a "parent" pointer to the loaded "Model" object it wants to take the form of, and hold world-space properties like a transform matrix, attachment matrix, physics properties, bounding volumes for frustum checks, etc. Model will contain an STL list of ModelObjects, all of whom can be positioned, rotated, attached, scaled, targeting other objects, etc. Then, run Model through your Update and Render loops. Model's Update() and Render() methods will set the shader that model uses, and call each ModelObject's corresponding Update() and Render() methods respectively. The Object's Update() and Render() properties will render the model's data using it's transform data, physics, etc. You can even add an "isRendering" property to ModelObject and check if it's TRUE each frame before rendering.

The same can go for dynamic models, but you'll be running vertex skinning code on its vertices for each ModelObject's Render() call so the vertices are temporarily transformed for that instance. Additional animation data would be required such as an Animation class that holds all animation data once (you can store a list of Animation objects in Model), and each ModelObject instance will only hold the animation(s) being applied to it and current frame so the vertices can be skinned either on the GPU via vertex shader, or in real-time on the CPU each frame per Render() call.

Edited by Vincent_M
0

##### Share on other sites

Well, particles, objects and skinned characters are already optimized in terms of using VBO's, and letting the GPU do all the work (converting vertices to sprite quads, moving the particles, and storing skinned vertices back into a second VBO). The real question is, would it hurt (performance wise) to apply instancing (like shown here http://sol.gfxile.net/instancing.html) even if the majority of entities doesn't come in huge numbers?

The question arised when I was spawning bullet cases, which tend to come in big numbers when shooting machine guns. So far, these are rendered like any other object in my engine, which comes down to this:

loop through sorted list // sorted on material
{
sortedList[x].referenceObject..material.apply; // applies shaders, textures and parameters
for each object in sortedList[x].objects
{
object.applyMatrix;
sortedList[x].referenceObject.vbo.draw;
}
}


But since these particular bullet cases come in larger numbers, it could be done with instancing, which changes the code "slightly" into something like this

loop through sorted list // sorted on material
{
sortedList[x].referenceObject..material.apply; // applies shaders, textures and parameters
pushMatrices( sortedList[x].objects.allMatrices );
sortedList[x].vbo.drawMultipleTimes( sortedList[x].objects.count );
}


It might make the bullets being drawn a bit faster, though most other types of objects may not benefit. Yet, if it doesn't harm either, I prefer to write the drawing approach in a single way, rather than having to split the instanced objects from the non-instanced objects and do things in two different ways...

0

## Create an account

Register a new account

Followers 0

• ### Similar Content

• So it's been a while since I took a break from my whole creating a planet in DX11. Last time around I got stuck on fixing a nice LOD.
A week back or so I got help to find this:
https://github.com/sp4cerat/Planet-LOD
In general this is what I'm trying to recreate in DX11, he that made that planet LOD uses OpenGL but that is a minor issue and something I can solve. But I have a question regarding the code
He gets the position using this row
vec4d pos = b.var.vec4d["position"]; Which is then used further down when he sends the variable "center" into the drawing function:
if (pos.len() < 1) pos.norm(); world::draw(vec3d(pos.x, pos.y, pos.z));
Inside the draw function this happens:
draw_recursive(p3[0], p3[1], p3[2], center); Basically the 3 vertices of the triangle and the center of details that he sent as a parameter earlier: vec3d(pos.x, pos.y, pos.z)
Now onto my real question, he does vec3d edge_center[3] = { (p1 + p2) / 2, (p2 + p3) / 2, (p3 + p1) / 2 }; to get the edge center of each edge, nothing weird there.
But this is used later on with:
vec3d d = center + edge_center[i]; edge_test[i] = d.len() > ratio_size; edge_test is then used to evaluate if there should be a triangle drawn or if it should be split up into 3 new triangles instead. Why is it working for him? shouldn't it be like center - edge_center or something like that? Why adding them togheter? I asume here that the center is the center of details for the LOD. the position of the camera if stood on the ground of the planet and not up int he air like it is now.

Full code can be seen here:
https://github.com/sp4cerat/Planet-LOD/blob/master/src.simple/Main.cpp
If anyone would like to take a look and try to help me understand this code I would love this person. I'm running out of ideas on how to solve this in my own head, most likely twisted it one time to many up in my head
Toastmastern

• I googled around but are unable to find source code or details of implementation.
What keywords should I search for this topic?
Things I would like to know:
A. How to ensure that partially covered pixels are rasterized?
Apparently by expanding each triangle by 1 pixel or so, rasterization problem is almost solved.
But it will result in an unindexable triangle list without tons of overlaps. Will it incur a large performance penalty?
How to ensure proper synchronizations in GLSL?
GLSL seems to only allow int32 atomics on image.
C. Is there some simple ways to estimate coverage on-the-fly?
In case I am to draw 2D shapes onto an exisitng target:
1. A multi-pass whatever-buffer seems overkill.
2. Multisampling could cost a lot memory though all I need is better coverage.
Besides, I have to blit twice, if draw target is not multisampled.

• By mapra99
Hello

I am working on a recent project and I have been learning how to code in C# using OpenGL libraries for some graphics. I have achieved some quite interesting things using TAO Framework writing in Console Applications, creating a GLUT Window. But my problem now is that I need to incorporate the Graphics in a Windows Form so I can relate the objects that I render with some .NET Controls.

To deal with this problem, I have seen in some forums that it's better to use OpenTK instead of TAO Framework, so I can use the glControl that OpenTK libraries offer. However, I haven't found complete articles, tutorials or source codes that help using the glControl or that may insert me into de OpenTK functions. Would somebody please share in this forum some links or files where I can find good documentation about this topic? Or may I use another library different of OpenTK?

Thanks!

• Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
• By KarimIO
EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
Update: No crash occurs if I don't draw, just clear and swap.
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));

• 10
• 11
• 19
• 14
• 23