Sign in to follow this  
NicoG

OpenGL Only 5.000 Sprites

Recommended Posts

NicoG    172
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
NicoG    172
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
karwosts    840
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
NicoG    172
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
Ezbez    1164
[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
Danny02    279
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
NicoG    172
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
Danny02    279
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
haegarr    7372
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
NicoG    172
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
Danny02    279
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
mhagain    13430
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
NicoG    172
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  

  • Similar Content

    • By cebugdev
      hi all,

      i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
      i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
      now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
      1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
      2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
      3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
      lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
      Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
      IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
      thank you, and looking forward to positive replies.
    • By fllwr0491
      I have a few beginner questions about tesselation that I really have no clue.
      The opengl wiki doesn't seem to talk anything about the details.
       
      What is the relationship between TCS layout out and TES layout in?
      How does the tesselator know how control points are organized?
          e.g. If TES input requests triangles, but TCS can output N vertices.
             What happens in this case?
      In this article,
      http://www.informit.com/articles/article.aspx?p=2120983
      the isoline example TCS out=4, but TES in=isoline.
      And gl_TessCoord is only a single one.
      So which ones are the control points?
      How are tesselator building primitives?
    • By Orella
      I've been developing a 2D Engine using SFML + ImGui.
      Here you can see an image
      The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
      Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine. 
      I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui. 
      3D Editor preview
      But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
      If you can provide code will be better. And if you want me to provide any specific code tell me.
      Thanks!
    • By Picpenguin
      Hi
      I'm new to learning OpenGL and still learning C. I'm using SDL2, glew, OpenGL 3.3, linmath and stb_image.
      I started following through learnopengl.com and got through it until I had to load models. The problem is, it uses Assimp for loading models. Assimp is C++ and uses things I don't want in my program (boost for example) and C support doesn't seem that good.
      Things like glVertexAttribPointer and shaders are still confusing to me, but I have to start somewhere right?
      I can't seem to find any good loading/rendering tutorials or source code that is simple to use and easy to understand.
      I have tried this for over a week by myself, searching for solutions but so far no luck. With tinyobjloader-c and project that uses it, FantasyGolfSimulator, I was able to actually load the model with plain color (always the same color no matter what I do) on screen and move it around, but cannot figure out how to use textures or use its multiple textures with it.
      I don't ask much: I just want to load models with textures in them, maybe have lights affect them (directional spotlight etc). Also, some models have multiple parts and multiple textures in them, how can I handle those?
      Are there solutions anywhere?
      Thank you for your time. Sorry if this is a bit confusing, English isn't my native language
    • By dpadam450
      FINALLY, upgrading my engine to openGL 4. I was having some trouble so I started with a stripped down application and was wondering if VAO's are required, because I have a sample working, but if I remove the VAO then it doesn't seem to like drawing my triangle.
  • Popular Now