Archived

This topic is now archived and is closed to further replies.

burnseh

OpenGL what do think of this ? (opengl states)

Recommended Posts

hello, right, from what I understand using glEnable()/glDisable() is expensive (right ?) so I started writing a few "state manager" functions, well 2 actually...:
// all states a false by default 
bool bState_Texture2D=false;
bool bState_DepthTest=false;
bool bState_Blend=false;

// enables a state unless its already enabled 
void mglEnable(int state)
{
	switch(state)
	{
		case GL_TEXTURE_2D: if(!bState_Texture2D) 
							{
								glEnable(GL_TEXTURE_2D);
								bState_Texture2D = true;
							}
							break;

		case GL_DEPTH_TEST:	if(!bState_DepthTest)
							{
								glEnable(GL_DEPTH_TEST);
								bState_DepthTest = true;
							}
							break;

		case GL_BLEND:		if(!bState_Blend)
							{
								glEnable(GL_BLEND);
								bState_Blend = true;
							}
							break;
	};
}

// disables a state unless already disabled
void mglDisable(int state)
{
	switch(state)
	{
		case GL_TEXTURE_2D: if(bState_Texture2D)
							{
								glDisable(GL_TEXTURE_2D);
								bState_Texture2D = false;
							}
							break;

		case GL_DEPTH_TEST:	if(bState_DepthTest)
							{
								glDisable(GL_DEPTH_TEST);
								bState_DepthTest = false;
							}
							break;

		case GL_BLEND:		if(bState_Blend)
							{
								glDisable(GL_BLEND);
								bState_Blend = false;
							}
							break;
	};
}
  
Would this result in a speed increase at all or is this a complete waste of time ? or is there a different/better way of doing this ? cheers, rich Edit: code formattings a bit wonky, ah well Edited by - burnseh on December 30, 2001 6:44:09 PM Edited by - burnseh on December 30, 2001 6:44:55 PM

Share this post


Link to post
Share on other sites
zedzeek,

Would you mind elaborating on what you do, I am interested in building my own state manager.

Also, would a rendering manager by similar to a state manager? For example, to reduce state changes, I WOULD build a tree. Each node would be a state change and a linked list of data to render under that state. Then, rendering would traverse this tree of state nodes with data associated with each. Would this idea be the same as what is being discussed here??

Edited by - GalaxyQuest on January 2, 2002 8:31:52 PM

Share this post


Link to post
Share on other sites
It''s faster than just calling glEnable everytime, but that switch is a bottleneck, especially if you have a lot of cases. An easy way to avoid this is just writing some functions like mglEnableTexture2D and so on. Or define them as macros what''ll save you the function''s overhead. I use some trick of mine to optimize my code where I would need a switch, making the code as fast as seperate functions, but it needs special values for all cases and a lot of assembler, making it only usable if you may define all constants by yourself.

Share this post


Link to post
Share on other sites
my opengl statemanager
*handles sorting of states (for optimal performance).
*it will also LOG out all current states (so i can see if something is enabled which shouldnt be)
*a lot of error checking etc

btw its 3000+ LOC so its not a short piece of code

http://uk.geocities.com/sloppyturds/gotterdammerung.html

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
There was an interesting discussion about redundant state changed on opengl.org''s forums and the thing that came out was that the redundant state changes should be avoided at any cost(well, almost at any cost). NVIDIA driver does not ignore them, while the driver _could_ check for redundant state changes they do not do it to favor well-written applications over badly-written(this was one of the points, search the advanced forum for more details).

While with many cases the state-manager could be a little slow, its still faster than a redundant state change in 99%. To speed up one could use macros, or, which I prefer, inline functions.

-Lev

Share this post


Link to post
Share on other sites
as lev saiz its a bad think if the driver checked. if it checked its gonna be slower so no drivers will do this for statechanges

shag - i havent been working much on gotterdammerung lately (been staying in a tent 5 days out of seven 4 the last couple of months whilst im away picking fruit thus no access to a computer) though the bright side is ive saved up enuf cash to buy me a geforce2mx if i can just make it to a decent sized town ill grab one (the nearest is 300km distance



http://uk.geocities.com/sloppyturds/gotterdammerung.html

Share this post


Link to post
Share on other sites
I posted my idea of using a tree with state "nodes" where at each node has a linked list of data to render. At render time the tree is traversed, therby it should minimize state changes to what is needed....but no one really had any comments on whether this "sounds" good. Ive heard of this idea elsewhere. Sound good??

Share this post


Link to post
Share on other sites
Hi,

I think that the switch method is "too slow" because it costs a lot of "if" instructions.
I had implement the state management through flag.

- to enable a state you wrote :
Enable (CF_CULL_FACE);
- CF_CULL_FACE is a flag define like below
#define CF_CULL_FACE 0 //cull is the 0-th bit
- a flag with the value of the state is declared:
long states;
- All render state are in an array :
GLenum allGLstates[] = { GL_CULL_FACE, ... };
- and enable code is like this :
void Enable (const ulong flag)
{
if ( GetFlagValue (states, (1< {
glEnable ( *(allGLstates+flag) );
SetFlag (states, (1< }
}
I think that this method could be faster that the switch. But there are a lot of methods to do it.

Vko

Share this post


Link to post
Share on other sites
Shag, even if certain drivers did actually ignore redundancy, there''s no guarantee of such a thing in the OpenGL specification. Therefore, if you were to make that assumption, your app might break somewhere. Never make assumptions.

Share this post


Link to post
Share on other sites
To Galaxy Quest , i ''ve heard too this kind of tree for opengl state switching but i think it has to deal with a lot of precomputing, in fact before rnedering you should check which of you actual calls to the opengl api are more expensive than other and thus put in the tree, then render it, i think its a good idea coupling with a sort of list of the slowest state change
done during initialization , but after some struggle i preferred to write an opengl state manager with inlined function and the speed gain is neat at the cost of some if , moreover i don''t think that some driver does a redundant check, at least at my actual knowledge

Share this post


Link to post
Share on other sites
I should know by now never to post when pissed!!! I was bound to get it the wrong way round!

*quietly deleting above post*

Sorry for the misinformation!

Edited by - Shag on January 3, 2002 11:38:37 AM

Share this post


Link to post
Share on other sites
The faster way is to take the shader description from a file (Quake3 uses text plain files). While interpreting the shader, make an OpenGL Display List. To activate the shader you must call the glCallList function. I thought that''s the faster way.



"If you''''re gonna die, die with your boots on"

Share this post


Link to post
Share on other sites
Im sorta new to 3d, so I am unfamiliar with this term "SHADER" thrown around??

I also notice it referenced to quake(3). Did carmack coin this or is it specific to quake? I dont understand how this "shader" refers to states....

Share this post


Link to post
Share on other sites
Shaders allow to define a lot of triangles properties such as if the depth test is enble, the culling, textures stage (envmode, gentex...), rgb color ...

So all of that use states in OpenGL so to set up a shader system, you must have a good states switching manager.

For the glList it is a excellent methods to improve the speed !

Vko

Share this post


Link to post
Share on other sites
I haven't read any of the above replies yet so this may have already been said, but you can enumerate the names or place them in an array of some sort

instead of calls like

glEnable(GL_TEXTURE_2D);
bState_Texture2D = true;

use stuff something like

Sorry, had to edit this. the source call doesn't understand the define statement or the // comments very well, or breaks either.

// following line not really necessary but makes it neat
#define Statements_Number 3
// texturing on by default
#define Statements_Default_1 TRUE
// depthtest on by default
#define Statements_Default_2 TRUE
// blend off by default
#define Statements_Default_3 FALSE

typedef struct __mglState
{
long int enable;
char flag;
}_mglState;

_mglState mglState[Statements_Number]={
{ GL_TEXTURE_2D,Statements_Default_1 },
{ GL_DEPTH_TEST,Statements_Default_2 },
{ GL_BLEND,Statements_Default_3 }
};

#define mglEnable(x)\
{\
if(mglState[x].flag==FALSE)\
{\
glEnable(mglState[x].enable);\
mglState[x].flag=TRUE;\
}\
}

#define mglDisable(x)\
{\
if(mglState[x].flag==TRUE)\
{\
glDisable(mglState[x].enable);\
mglState[x].flag=FALSE;\
}\
}




Beer - the love catalyst
good ol' homepage



PS - check if it is long int or what for glEnable/glDisable. I forgot. Make sure it is the same (pososibly glint) as it will save on converting the number format.

Edited by - Dredge-Master on January 5, 2002 11:59:44 AM

Share this post


Link to post
Share on other sites

  • Announcements

  • Forum Statistics

    • Total Topics
      628401
    • Total Posts
      2982462
  • 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