# OpenGL Optimize drawing lots of objects

## Recommended Posts

Hi, I'm working on a 2D project in OpenGL and now trying to optimize it, and basically I wondered if you could take a look at the code and tell me if there are any faster ways of doing it. I think it's the drawing that is time consuming and that's why I posted it here in the OpenGL department. The part that I am interested in handles the units, I have a chain where every unit knows the adress to the previous and the next unit, and one controller that knows the adress to the first and last unit. Every frame the controller tells the first unit to update itself, then the first unit tells the next unit to update, etc etc. For example I tried removing the glLoadIdentity() and positioning the unit relative to the last unit, but that was no success. Here is the code that every unit executes:
void unit::Update()
{

//calculate the direction to the target

if (TC.tank1->getX() > x)
dir = atanf((y - TC.tank1->getY()) / (TC.tank1->getX() - x));
else
dir = pi - atanf((y - TC.tank1->getY()) / (x - TC.tank1->getX()));

x += v*cosf(dir);
y -= v*sinf(dir);

//////////////////////////////////////
//	Perform collision detection //
//////////////////////////////////////
float r=18.0f;
if ((TC.tank1->getX() - x) < r && (TC.tank1->getX() - x) > -r)
if (TC.tank1->getY() - y < r && TC.tank1->getY() - y > -r)
{
//the unit is inside the tank quad
}

//////////////////////////////////////
//         Draw the unit	    //
//////////////////////////////////////
glTranslatef(x,y,-1.0f);

glRotatef(-dir*57.29577, 0, 0, 1);

//	glNormal3f( 0.0f, 0.0f, 1.0f);

glTexCoord2f(0.0f, 0.0f); glVertex3f(-16.0f, -16.0f,  0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(16.0f, -16.0f,  0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(16.0f, 16.0f,  0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-16.0f, 16.0f,  0.0f);

glEnd();

// if there are more units, update them too
if (unit_next != 0)
unit_next->Update();

delete this;
}


Here is the class declaration (not really important?):
class unit
{
public:
float getX();
float getY();
unit *unit_next;		//keeps the adress to the next unit, creates one big chain of units
unit *unit_previous;	//keeps the adresss to the previous....

void Update();
private:
float x;
float y;
float dir;		//the current direction to target
float v;		//velocity

};



##### Share on other sites
You could use a Display list to draw the quad. That is if you are drawing a lot of them.

##### Share on other sites
Quote:
 Original post by nefthyYou could use a Display list to draw the quad. That is if you are drawing a lot of them.

Every unit consists of one textured quad so I guess display lists wont help much.

##### Share on other sites
This may be a little too common sense, but sometimes it is overlooked, just make sure you aren't rendering units you can't see. Back when I was using OpenGL for 2d, I just brute force drew everything and got a FPS of 50ish, which is passable, but when I culled out everything that isn't visible, I was got an FPS of 500.

The one thing that also could be slowing down your rendering is using OpenGL's immediate mode. You could dump the units into a VB and render from that, that could give you a boost.

##### Share on other sites
Quote:
 Original post by PureWHi, I'm working on a 2D project in OpenGL and now trying to optimize it, and basically I wondered if you could take a look at the code and tell me if there are any faster ways of doing it. I think it's the drawing that is time consuming and that's why I posted it here in the OpenGLdepartment.

dont guess, profile.
Also, what kind of speeds are you getting right now on what kind of machine?

##### Share on other sites
JohnnyCasil: The units are visible at all times so that wont work.

_the_phantom_: I acctually tried drawing the units in one frame out of ten, wich resulted in higher speeds and a flickering screen.
At the moment I can draw approximately 4000 units on the screen with 100fps (I think it's 100fps, since my monitor runs with 100hz and v-sync seems to be enabled) before the cpu reaches 100%.

##### Share on other sites
confirm the fps first without vsync on, then use some kind of profiler (either a proper external program or your own in built code to time different sections of the game), both with and without vsync.
If the rendering isnt the bottle neck all the improvememts in the world wont help you

##### Share on other sites
OpenGL has a relatively low overhead for draw calls. But assuming that you are being limited by draw calls, try doing this,

//called 1000+ times
draw(unit);

draw(Unit* u)
{
}

At the end of all your draw calls,
call something like submitBuffer();

submitBuffer()
{
glVertexPointer(...);
glTexCoordPointer(...);
glDrawArrays(.., vertexArray.data);
}

Basically the idea is to buffer all your quads and draw them throught 1 big vertex array to minimise draw calls. this is the approach i use for my fonts. Also i am assuming that all your units are using the same texture. Otherwise you will have to make seperate buffers for different textures. To minimise this, you should try to use 1 big texture containing all your sprites instead of 1 small texture for each sprite.

##### Share on other sites
One thing you can do to reduce your CPU overhead is to make a sin/cos/atan table. I noticed you're doing a lot of trig on each unit every frame, and these are pretty expensive calls. Especially since today's memory is so big, it's worthwhile to make a table of all sin/cos/atan values. You'll probably want to experiment with the step size to find something that gives you good results, then all you have to do each frame is round to the nearest step and look it up in a table...much faster.

If you were just computing a new camera position, this wouldn't be an issue, but since you're doing trig on each of 4000 objects, it really adds up.

You may not see a significant framerate increase, but I promise you'll be clearing up CPU cycles for the rest of your engine that you'll need later!

##### Share on other sites
the only time u would want to maybe use the tables is inside a tight loop that uses those functions, the above doesnt adhere to that.

to the OP the best way to speed it up would be to do all the math yourself, ie loop first through all the units and workout the 4 corners of the quad. and then once u have all the units sussed draw them in one fell swoop

itll save in calling the following commands for every unit
glTranslatef(x,y,-1.0f);
glRotatef(-dir*57.29577, 0, 0, 1);

##### Share on other sites
now adays its probably faster to perform the maths than use lookup tables, the biggest source of latancy on anything past a P2 is more likely to be memory than a cos/sin operation, latancy on a memory lookup is in 100s of intructions, a sin/cos instruction is going to take much less time over all (factor in out of order execution and pipelining and instructions are going to win 99 times out of 100)

##### Share on other sites
Quote:
 Original post by GamerSgOpenGL has a relatively low overhead for draw calls. But assuming that you are being limited by draw calls, try doing this,//called 1000+ timesdraw(unit);draw(Unit* u){vertexArray.addVerticesFrom(u);}At the end of all your draw calls,call something like submitBuffer();submitBuffer(){glVertexPointer(...);glTexCoordPointer(...);glDrawArrays(.., vertexArray.data);}Hope this is helpful.

Quote:
 Original post by zedzeekthe only time u would want to maybe use the tables is inside a tight loop that uses those functions, the above doesnt adhere to that.to the OP the best way to speed it up would be to do all the math yourself, ie loop first through all the units and workout the 4 corners of the quad. and then once u have all the units sussed draw them in one fell swoopitll save in calling the following commands for every unitglLoadIdentity();glTranslatef(x,y,-1.0f);glRotatef(-dir*57.29577, 0, 0, 1);glBegin(GL_QUADS);

Is this the same thing?

##### Share on other sites
If you want to get rid of the glLoadIdentity then you can rotate and translate after drawing the quad to restore yourself to the initial position. ie:

glTranslatef(x,y,-1.0f);
glRotatef(-dir*57.29577, 0, 0, 1);

; draw polies

glRotatef(dir*57.29577, 0, 0, 1);
glTranslatef(-x,-y,1.0f);

And obviously if you introduce scaling then you'll need to scale by 1/x,1/y afterwards. This is what I do in my 2D opengl program and I get decent speed. Another thing is obviously to minimise texture changes, so I pre-sort all my units and place those with different textures at different z-depths so that when I draw them in order I have the bare minimum texture changes and that helps speed things up a lot.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628350
• Total Posts
2982211
• ### Similar Content

• 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?

• 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.

• 10
• 9
• 24
• 11
• 9