Sign in to follow this  
NicoG

OpenGL Only 5.000 Sprites

Recommended Posts

Topic says it.
I tried to get the maximum out of my Library and just created insane amounts of sprites wandering over the screen.
With 5000 Sprites I got down to 15-20fps which is the bottom line of a playable Game.
So, I need some performance Tipps.

Here is the drawing Code:

[code]

void NLSpriteList::renderObject()
{
m_texture->attach();
m_shader->attach();

glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

// Enable Attribute Sets
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

// Draw
glDrawArrays(GL_TRIANGLES, 0, m_list.size()*6);

// Disable Attribute Sets
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

// Unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

m_shader->detach();
m_texture->detach();
}

void NLSpriteList::update(u32 delta, u32 time)
{
if ( m_vao == 0 || m_vbo == 0 )
this->createBatch();

//m_list.sort(NLBatchedSprite::OrderByZ());

// Update data
NLVertexData* data = createData(delta, time);

// Bind
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

// Enable Attribute Sets
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

// Send Vertex data
glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

// Disable Attribute Sets
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

// Unbind
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// Delete buffer
delete [] data;
}

NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
NLVertexData* buffer = new NLVertexData[m_list.size()*6];
memset(buffer, 0, sizeof(buffer));
TSpriteList::iterator it = m_list.begin();

int i = 0;
for ( it; it != m_list.end(); it++ )
{
NLBatchedSprite& s = *it;
s.update(delta, time);
memcpy(&buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
i += 6;
}

return buffer;
}
[/code]
As you can see, I send the vertices each frame. Okay, in this case it is needed since I have transformations every frame and I do transforms on the cpu.
Any hints? :)
Oh and there are no texture-/shaderchanges during the rendering, OpenGL Calls are constant 31 per Frame and no glGet/Redundant state changes.
Picture was taken on an AMD 2600+ DualCore with ATI HD4890 with 11.4 drivers.

[img]http://h-6.abload.de/img/gdebugh71p.png[/img]

Share this post


Link to post
Share on other sites
Okay, I was dumb enough to do this with a debug executable.
In Release Mode I can get up to 30.000 Sprites.
But if anyone sees some Room for improvements, I am open to suggestions.

Share this post


Link to post
Share on other sites
How about an image of your game, so that we may see in what way you are using the sprites?

Not that it will make your game run much faster, but this is pointless, you have no need to modify attribArrays to send bufferdata.

// Enable Attribute Sets
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

// Send Vertex data
glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

// Disable Attribute Sets
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

You probably don't need to bind/unbind VAO either, but I don't work with VAO that much so I can't be sure.

Share this post


Link to post
Share on other sites
Thanks for the reply. Well, in this case it is only a lot of sprite wandering from left to right and back. Nothing fancy. I just stress test my code.
Removing the Attribute Sets was fine and gave me maybe 1-2 fps.
About the binds: I bind/unbind at the end of every function because I want to leave the OpenGL StateMachine in the state it was before.
Maybe this is a bad strategy?
The class used here is a batcher class which does nothing but batching the sprites you feed to it. One batcher is required per SpriteSheet.
There are also sprites which take a single texture, they cannot be batched. So I am nevery sure if my objects are still bound. A glGet is probably
more expensive than binding it? Or would you buffer the OGL State here?

On the other Hand: Who makes 2D Games with more than 200 Sprites visible at once... and I still have to do Point Sprites for a Leightweight Particle-Engine, so that goes extra.
The current Sprites are 2 Triangles which are making up a quad.
Maybe I get lost in micro-optimisations here?

And here is the requested image:
[url="http://www.abload.de/img/sample47kb.png"]http://www.abload.de.../sample47kb.png[/url]

Share this post


Link to post
Share on other sites
[quote name='NicoG' timestamp='1302308896' post='4796159']
On the other Hand: Who makes 2D Games with more than 200 Sprites visible at once... and I still have to do Point Sprites for a Leightweight Particle-Engine, so that goes extra.
[/quote]

More to the point, are [i]you[/i] making such a game? "You ain't gunna need it" is the rule of thumb to follow here.

Share this post


Link to post
Share on other sites
First of,
you using VAOs wrong, making them useless in your case.
1. in the render function, get rid of all the client state en/disables and the buffer binds.
You need this only while initialization.
2. in the update function, you don't need to bind the VAO just the buffer.

when a VAO is bound all of these specific OpenGL stats are stored in the VAO instead of the "standard" context(VAO, glBindVertexArray(0);)

also, it don't make any sens to "unbind" a shader, its just extra work. In many case also true for the textures.


Finaly there is something what u can optimize, in your update function.
Instead of your simple [color="#1C2837"][size="2"]glBufferData use this[/size][/color]
[size="2"] [/size][code]glBufferData(GL_ARRAY_BUFFER, size, null, GL_STREAM_DRAW);
glSubBufferData(GL_ARRAY_BUFFER, 0, size, data);[/code]

this lets the driver optimize the upload better and can reduce stalls

Share this post


Link to post
Share on other sites
Thanks for all the replies.

@Ezbez
I am developing a multi purpose Library and just trying to make it as good as I can.
But I feel already pretty comfortable with this drawable amount of sprites.

@Danny02

Could go into detail with the VAO? I have the OpenGL Superbible and some Tutorials on OpenGL3, but Articles about it are really rare and reading the specs is not a good documentation for me. "Too technical" if you can understand what I mean.
If I get rid of all the glEnableVertexAttrib()-binds in the render function, nothing is displayed at all. Thats not the only place I am using a VAO/VBO.
About glBufferSubData:
Does not yield any performance gain. I already tell OpenGL that I will throw away the content of the VBO by using GL_STREAM_DRAW. glBufferSubData yields some problems regarding updating the sprites, esp. dynamic Text like FPS Display.

But well, I think 30.000 Sprites at once are pretty good in Release Mode. But that there is such a huge difference in performance of 25.000 Sprites between Debug and Release is astounding.

Here is my updated code so far:

[code]

void NLSpriteList::renderObject()
{
m_texture->attach();
m_shader->attach();

glBindVertexArray(m_vao);

// Enable Attribute Sets
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);

// Draw
glDrawArrays(GL_TRIANGLES, 0, m_list.size()*6);

// Disable Attribute Sets
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);

// Unbind
glBindVertexArray(0);

m_shader->detach();
m_texture->detach();
}

void NLSpriteList::update(u32 delta, u32 time)
{
if ( m_vao == 0 || m_vbo == 0 )
this->createBatch();

//m_list.sort(NLBatchedSprite::OrderByZ());

// Update data
NLVertexData* data = createData(delta, time);

// Bind
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

// Send Vertex data
glBufferData(GL_ARRAY_BUFFER, 6*m_list.size()*sizeof(NLVertexData), data, GL_STREAM_DRAW);

// Unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);

// Delete buffer
delete [] data;
}

NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
NLVertexData* buffer = new NLVertexData[m_list.size()*6];
memset(buffer, 0, sizeof(buffer));
TSpriteList::iterator it = m_list.begin();

int i = 0;
for ( it; it != m_list.end(); it++ )
{
(*it).update(delta, time);
memcpy(&buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
i += 6;
}

return buffer;
}

[/code]

Share this post


Link to post
Share on other sites
Ok, VAOs are a special kind of OpenGL object. Instead of saving data they save state.
In order to draw something with BOs u normally have to set up a lot of state, like enabling vertex attributes, setting the attribute settings and specifying an element buffer.

These states are set through the following OpenGL commands:
[list][*]glEnableClientState , glDisableClientState[*]all the [font=sans-serif][size=2]gl*Pointer functions[/size][/font][*][font=sans-serif][size=2]binding the [/size][/font][font=sans-serif][size=2]GL_ELEMENT_ARRAY_BUFFER buffer[/size][/font][/list]
[font="sans-serif"][size="2"]good overview over the data structure [/size][url="http://www.opengl.org/wiki/Vertex_Array_Object"]http://www.opengl.org/wiki/Vertex_Array_Object[/url][/font]
[font="sans-serif"][size="2"]
[/size][/font]
[font="sans-serif"][size="2"][/size][/font][color=#1C2837][size=2][color=#000000][size=3][font=sans-serif][size=2][quote][/size][/font][/size][/color]If I get rid of all the glEnableVertexAttrib()-binds in the render function, nothing is displayed at all. Thats not the only place I am using a VAO/VBO. [/size][/color][font=sans-serif][size=2][/quote][/size][/font]
[font="sans-serif"][size="2"]Have u put that code in your VAO initialization? The same spot where u set up all the Attribute info.[/size][/font]
[font=sans-serif][size=2]
[/size][/font]

Share this post


Link to post
Share on other sites
Although you're right that 30.000 sprites should be enough, here are some points for discussion:

[quote name='NicoG' timestamp='1302311975' post='4796174']
About glBufferSubData:
Does not yield any performance gain. I already tell OpenGL that I will throw away the content of the VBO by using GL_STREAM_DRAW. glBufferSubData yields some problems regarding updating the sprites, esp. dynamic Text like FPS Display.
[/quote]
When OpenGL enqueues commands for later execution, you don't know whether the VBO is already available (i.e. there is no commands pending that requires access to that VBO). You would know if you do synchronization, but that obviously wastes some time. If you "blindly" write to the VBO memory the driver may defer your routine until no pending command requires the VBO anymore. Hence the trick is to do double buffering for vertices, and that is why

[code]
glBufferData(GL_ARRAY_BUFFER, size, null, GL_STREAM_DRAW);
glSubBufferData(GL_ARRAY_BUFFER, 0, size, data);
[/code]
is used, because that "null" allows the driver to allocate a second memory area, leaving the 1st memory area until no pending commands require it anymore while you are writing to the 2nd one. So using GL_STREAM_DRAW by itself isn't sufficient to gain advantage from double buffering.

There is no guarantee though that the driver behaves this way, but it is the best you can do in situations where you need to be compatible. In OpenGL 3 / the ARB_map_buffer_range extension there is glMapBufferRange which allows an explicit double buffering.


Moreover, how looks your vertex layout? It is probably best if multiples of vertex data boundaries lie on 32 byte boundaries. E.g. a vertex occupying 16 bytes would be fine. My current development uses 3 floats for position and 2 shorts for (u,v) with auto-normalizing the (u,v) pair in the input pipeline. But I have no performance comparisons made yet.


At least, using vertex indices may be of benefit. Assuming you need 16 bytes per vertex and each sprite is mapped on a quad (i.e. 2 triangles), then you need
6 * sizeof(Vertex) = 6 * 16 bytes = 96 bytes
for each sprite. If you use INT indices (at least for the stress test), then you need
6 * sizeof(INT) + 4 * sizeof(Vertex) = 6 * 4 bytes + 4 * 16 bytes = 88 bytes
for each sprite. If you use SHORT indices (obviously allowing for >10.000 sprites), then you need
6 * sizeof(SHORT) + 4 * sizeof(Vertex) = 6 * 4 bytes + 4 * 16 bytes = 76 bytes
for each sprite. It may be that the sprites all together live long enough so that the index buffer need not be rebuild every frame, reducing the transfer amount asymptotically to 64 bytes.

Advantages are:
1. Using less bandwidth (okay, the difference between 96 and 88 may be eaten by the additional mapping; you have to try).
2. Allowing the GPU to use the vertex cache for 2 of the 6 vertices of a sprite.

Share this post


Link to post
Share on other sites
My Vertex Layout is:

[code]

#pragma pack(push, 1)
/**
* \brief Vertex coords for storage in OpenGL
*
*
* A normal user does not need to care about them.
*/
struct NLVertexData
{
/// \brief Constructor
NLVertexData()
: x(0), y(0), z(0),
r(1), g(1), b(1), a(1),
s(0), t(0)
{}

/// \brief X
f32 x;

/// \brief Y
f32 y;

/// \brief Z
f32 z;

/// \brief Red
f32 r;

/// \brief Green
f32 g;

/// \brief Blue
f32 b;

/// \brief Alpha
f32 a;

/// \brief t
f32 s;

/// \brief t
f32 t;
};

#pragma pack(pop)
[/code]

And when I use glBufferData(NULL) and then glBufferSubData, I loose around 5 Frames. At least on my ATI.

Share this post


Link to post
Share on other sites
some thoughts
1. frames doesn't tell u anything, use ms to compare stuff.
2. try to test if u are filtrate bound, render the particles without updating them every frame.
3. try to shrink your vertex size
4. can u use point spirits instead of your quads? possible if u don't rotate the particles and they face the camera
4.1. experiment with geometrie shaders
5. use instancing, for particles a texture or with OGL3 transform feedback is probably the best

Share this post


Link to post
Share on other sites
Your update function is doing a lot of memory allocation and releasing - are you calling this every frame? If so it's going to be a potential bottleneck as the numbers get higher.

I wouldn't use C++ new and delete for this kind of thing at all to be honest. On Windows I'd VirtualAlloc (with MEM_RESERVE) a large-ish pool (16-64 MB, but it depends on how many you want to draw really) and VirtualAlloc (with MEM_COMMIT) as needed, but never release memory so that I could reuse previous allocations from frame to frame. Otherwise I'd create an initial static pool of objects that's large enough to cover most common uses, and only allocate/release when the size needs to change (and even then only when it needs to go up). The key however is to always be able to reuse previously allocated memory instead of having to allocate fresh memory every frame. Memory is cheap and plentiful, performance is not.

I wouldn't use a class either (or even a struct with a constructor) for something that I need to dynamically allocate 10s of 1000s of every frame. Here you're allocating a buffer, you're memset-0'ing, it, you're updating the data, you're memcpy'ing it, then you're glBufferSubData'ing it. This actually needs to update data for each vertex [i]five[/i] times - constructor, memset-0, update for real, memcpy, and glBufferSubData. That's a lot of walking over the same data,and a lot of unnecessary value-storing (are the constructor and the memset-0 even necessary?), all for a chunk of data that you just end up throwing away. Just use a simple lightweight C style struct and maintain the count of items for it separately.

The point though is that too much OO at too fine a level can really hurt performance, and that if you want your rendering to really fly you may need to start doing things that you consider less "clean".

Share this post


Link to post
Share on other sites
Thanks for all the good suggestions.
I have eliminated the memset, but I still need the memcpy.
I also eliminated the renundant OpenGL Calls.
I have also eliminated the allocation of the buffer for sending the data to OpenGL and replaced it with a lightweight, but "safe" solution:
[code]
NLVertexData* NLSpriteList::createData(u32 delta, u32 time)
{
TSpriteList::iterator it = m_list.begin();
u32 size = m_list.size()*6;
u32 i = 0;

// Alloc more space only if there is a need to do so.
if ( m_buffer_size < size )
{
delete [] m_buffer;
m_buffer_size = size;
m_buffer = new NLVertexData[m_buffer_size];
}

// Create
for ( it; it != m_list.end(); it++ )
{
(*it).update(delta, time);
memcpy(&m_buffer[i], &it->m_vertices, sizeof(NLVertexData)*6);
i += 6;
}
return m_buffer;
}
[/code]
This reduces the usage of the new operator greatly, since normally the size of a batcher rarely changes atm. This is dependant of the usage of my library though, but every lib has its "good practice" section in the docs huh? :D

However, I will examine "placement new" to allocate memory ahead for the batcher and also the created sprites on client side. This way I could save some considerable performance. And it is not Platform dependant like VirtualAlloc().
I just don't know yet how to implement it in detail.
Btw I am up to 75.000 objects in release mode with logic update @ 20 FPS and good timings.
So thanks for all the good hints :). I really apreciate it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628356
    • Total Posts
      2982251
  • Similar Content

    • By test opty
      Hi all,
       
      I'm starting OpenGL using a tut on the Web. But at this point I would like to know the primitives needed for creating a window using OpenGL. So on Windows and using MS VS 2017, what is the simplest code required to render a window with the title of "First Rectangle", please?
       
       
    • By DejayHextrix
      Hi, New here. 
      I need some help. My fiance and I like to play this mobile game online that goes by real time. Her and I are always working but when we have free time we like to play this game. We don't always got time throughout the day to Queue Buildings, troops, Upgrades....etc.... 
      I was told to look into DLL Injection and OpenGL/DirectX Hooking. Is this true? Is this what I need to learn? 
      How do I read the Android files, or modify the files, or get the in-game tags/variables for the game I want? 
      Any assistance on this would be most appreciated. I been everywhere and seems no one knows or is to lazy to help me out. It would be nice to have assistance for once. I don't know what I need to learn. 
      So links of topics I need to learn within the comment section would be SOOOOO.....Helpful. Anything to just get me started. 
      Thanks, 
      Dejay Hextrix 
    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
  • Popular Now