• Advertisement
Sign in to follow this  

OpenGL Dealing with bind-to-edit in OpenGL

This topic is 1849 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all,

 

I'm looking for an elegant way to design a rendering API abstraction layer, but I keeping running into problems because of OpenGL's bind-to-edit model.  For example, one thing I want to do is cache/shadow the current render state to avoid redundant state changes, but bind-to-edit makes this especially difficult.

 

Here's some pseudocode (I'm pretending there is only one texture unit, for the sake of simplicity):

class Texture {
public:
    void Create()
    {
        glBindTexture(GL_TEXTURE_2D, m_name); // the wrong texture is now bound
        ... // code to create texture
    }
    GLuint GetGLName() const { return m_name; }
private:
    GLuint m_name;
};

class GraphicsDevice {
public:
    void SetTexture(Texture* texture)
    {
        if (texture != m_texture) {
            glBindTexture(GL_TEXTURE_2D, texture->GetGLName());
            m_texture = texture;
        }
    }
private:
    Texture* m_texture;
};

 

As you can see, the texture class needs to bind itself in order to create the OpenGL texture object, and so the the GraphicsDevice class now thinks a different texture is bound than the one that actually is.

 

The obvious way to fix this problem is to add a glGet(GL_TEXTURE_BINDING_2D) call in Texture::Create so that the previous texture can be bound afterwards, but glGet() calls are supposed to be avoided, right?

 

The only other solutions I can think of involve various ugly techniques such as circular dependencies, global variables, etc.

 

Is there a better way of solving this problem?

 

 

Share this post


Link to post
Share on other sites
Advertisement

It's probable that the value for this particular glGet will be cached by the driver and so won't need a round-trip to the GPU - as a general rule, if it doesn't rely on a previous draw call having completed in order to fetch the result, then you can assume that the driver may be able to do something intelligent with it (but do back up this assumption with some benchmarking first!)

 

On the other hand, you're still left with the annoyance of bind-to-modify.  One possible solution, if you're prepared to bump your hardware requirements appropriately, is to have a look at GL_EXT_direct_state_access - it may be just what you need.

Share this post


Link to post
Share on other sites
As mhagain pointed out, direct state access is a great solution to your problem.

However, you have alternatives. It really depends on the GL version you're aiming to support. Suppose it's 4, then you can force your textures to be created only once (let's say in the constructor), and from there on they can only be modified by ARB_copy_image, or casted by ARB_texture_view. Also, the only entity that can create textures is the device. With this design you'll have less problems, and it also resembles the D3D design.

Also, what mhagain said about the state being cached in the driver is true. Generally the driver stores the current state in a local copy. It's just less pretty to have all those glGet in your code. A rule of thumb is that if you have to resort to glGet to query the state, then your design has flaws. Edited by max343

Share this post


Link to post
Share on other sites

Direct state access does indeed look like a great solution, but I think the hardware requirements might be a bit high.  Interesting point about whether glGet values will be cached -- I'll remember that.

 

 

It really depends on the GL version you're aiming to support. Suppose it's 4...

 

 

That technique looks excellent, but unfortunately I need to support Mac OS X versions earlier than Lion, so I only have OpenGL 2.1 available.  If you have any suggestions that could work for OpenGL 2.1, that would be great.  I'm interested in your idea about having the device create the textures.  How would you implement this?  Would you just create the OpenGL texture object in a function in the GraphicsDevice class and then pass the GLuint into the Texture constructor? Or something else?

 

 

if you have to resort to glGet to query the state, then your design has flaws

 

 

Yeah, that's what I thought.  Do you have any pointers on how I could approach re-designing this so that I wouldn't need to use glGet?

 

Thanks!

Edited by IncidentRay

Share this post


Link to post
Share on other sites
It seems that in your case there are no shortcuts available, so you'll just have to do it the hard way.

You can do exactly what D3D11 does. This is pretty much like you suggested. Instead of having the method "Create" in the "Texture" class, move it to the "GraphicsDevice" class and rename it to something like "CreateTexture2D". This method will create the GL texture, create an object of "Texture", initialize its name (possibly through the constructor), restore the previously bounded texture correctly, and finally return the texture object. You'll have to do the same for copying (and probably a few more things). Your "Texture" class will essentially become a resource interface which will be able to do only simple things (like return its name, and delete itself).
Just keep in mind that if you're going to follow D3D11 on this, don't copy it exactly as it also supports views. This is way beyond the scope of 2.1 context. Not that it's impossible to emulate it (pretty much what FL9 does), but you'll just have to write a lot more code. Edited by max343

Share this post


Link to post
Share on other sites

Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

Also, what's FL9?  I googled it but I can't seem to find anything.

Edited by IncidentRay

Share this post


Link to post
Share on other sites

I have most of my resources pointed to as shared_ptr's. I know it is not the best solution but it works for now.

Also why do you need to cache the rendering state? In my code, a list is prepared containing all things to be rendered this frame. Then it is sorted to reduce state changes

and then rendered in a single function removing the need to store a global cache.

Share this post


Link to post
Share on other sites
Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

As a general rule, anything responsible for allocating memory should be responsible for deleting it: void GraphicsDevice::DestroyTexture(Texture t) { ... }

Share this post


Link to post
Share on other sites
Ok, that solution sounds good.
 
However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.
 
Do you have any ideas on how to fix this issue?
 
Also, what's FL9?  I googled it but I can't seem to find anything.

FL9 is feature level 9 mode of D3D11.

As for your first question, then yes it could potentially cause a problem, though this problem is much easier to identify with a simple assert during bind, just check whether the texture name seems valid (for instance, you can keep track on how many textures you've allocated).
This way of deletion is just how D3D does things, you don't have to do the same. As Aldacron already said, your GraphicsDevice can handle the deletion (and check if what you're deleting is currently bound). However, as far as the state goes textures can delete themselves because for that you don't need to bind them (you don't alter the state).

Share this post


Link to post
Share on other sites

Thanks for the replies!

 

I have most of my resources pointed to as shared_ptr's. I know it is not the best solution but it works for now.

Also why do you need to cache the rendering state? In my code, a list is prepared containing all things to be rendered this frame. Then it is sorted to reduce state changes

and then rendered in a single function removing the need to store a global cache.

 

This would definitely work, but I just prefer it if the caching is implemented in the graphics API layer, so that the user doesn't have to worry about it.  It seems to me that you might end up implementing render state caching multiple times, for each type of graphics you need to draw; e.g., the actual game world, the UI, etc.  I also think this could pose a problem if you are dynamically generating geometry -- i.e., filling a vertex buffer with data, then drawing it, filling it with new data, and so on.  How would you have a list of objects in this case?

 

 

Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

As a general rule, anything responsible for allocating memory should be responsible for deleting it: void GraphicsDevice::DestroyTexture(Texture t) { ... }

 

This is a good idea.  What's interesting though, is the texture class doesn't really do anything in this case -- it just stores a texture name and returns it.  Also, if you need an instance of GraphicsDevice to destroy a texture, it would then be necessary to pass a pointer/reference to it around more.  For example, if an object creates a texture in its constructor, and destroys it in its destructor, it would need to maintain either a pointer or a reference to the GraphicsDevice, so that it could call DestroyTexture.  This wouldn't be needed if you could delete a texture without needing the device, but I'm not quite sure how to get around this.

 

 

[quote name='max343' timestamp='1356428689' post='5014135']
FL9 is feature level 9 mode of D3D11.
[/quote]

 

Ah ok, I'm not too familiar with D3D terminology.

 

[quote name='max343' timestamp='1356428689' post='5014135']
As for your first question, then yes it could potentially cause a problem, though this problem is much easier to identify with a simple assert during bind, just check whether the texture name seems valid (for instance, you can keep track on how many textures you've allocated).
This way of deletion is just how D3D does things, you don't have to do the same. As Aldacron already said, your GraphicsDevice can handle the deletion (and check if what you're deleting is currently bound). However, as far as the state goes textures can delete themselves because for that you don't need to bind them (you don't alter the state).
[/quote]

 

I'm having trouble understanding how this would be implemented.  How would you get the texture name without calling a function of the Texture object (which might have been deleted)?  I'm also not sure how keeping a count of the number of textures allocated would help you determine whether a texture name is valid.  I thought OpenGL wasn't required to return a contiguous range of texture names.  I do like the idea of being able to model D3D on this -- could you maybe give a simple example of some code for this?  Many thanks.

Share this post


Link to post
Share on other sites
As opposed to general rendering errors (binding invalid textures), controlled crashes (asserts) are good! They're much easier to debug.

Suppose your GraphicsDevice object holds an already deleted pointer to some Texture. While running in debug mode, when an object is being deleted its associated memory is being overwritten with something like BAADF00D. So you just call the method GetName of your invalid Texture object, and in almost all cases one of the two will happen, either you'll get an exception for trying to read an unallocated memory, or you'll get the magic number. Those magic numbers are big, I mean really big, there's no way you're going to allocate billion textures. So you can just make your assert like this (in SetTexture or directly in GetName):
assert(glIsTexture(texture->GetName()) == GL_TRUE);

glIsTexture is not a cheap call, but it's in the assert, so it'll run only in debug mode. If you want to do something similar in release mode, then you can make the check less costly (but also much less precise) by first overwriting the value of m_texture in the destructor with something big and by changing the check to:
if(texture->GetName() > 1<<20) // Or some other magic number
  throw TextureException;
Although a GL implementation isn't obligated to use contiguous numbers, all implementations I've worked with, do it.

As for your other questions. If GraphicsDevice is going to be responsible for deletion, then yes, you'll probably need to hold the object in many places. Though I think it's reasonable enough, because in 99% of cases there should be exactly one object of GraphicsDevice.
Also, planning to match D3D is good, but you need to know what version to target (10 or 11) and where to draw the line. What you want to do is probably closer to 10 than to 11. Targeting for 11 will require more abstraction in some layers, most notably separating the Device from RenderingContext. For instance, creating a texture is a Device operation, while binding a texture is a RenderingContext operation.
I really cannot summarize D3D10/11 in a few lines of text here, but you can use MSDN and the SDK for pointers on how to do it best. Edited by max343

Share this post


Link to post
Share on other sites

That looks useful for debugging, but how would you rewrite this code so that it doesn't cause the assert to fail?

GraphicsDevice device;
Texture* texture1 = device.CreateTexture(...);
device.SetTexture(texture1);
delete texture1;
Texture* texture2 = device.CreateTexture(...); // device dereferences dangling pointer; crash

 

 

Should I just just add a device.SetTexture(NULL) call before deleting the texture1 object?  This could become quite tedious in the generic case, with multiple texture units, though.  For example, before deleting any texture you would have to do,

for (unsigned i = 0; i < device.GetNumTextureUnits(); ++i) {
    if (device.GetTexture(i) == texture) {
        device.SetTexture(i, NULL);
    }
}
Edited by IncidentRay

Share this post


Link to post
Share on other sites

Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

If the resources get created first (CreateTexture), then a render starts with SetTexture serving as a bind that protects against a re-bind,

the GraphicsDevice doesn't need to have any knowledge about whether a texture object exists or not. Might want to have a reset method in GraphicsDevice that sets m_texture to NULL, as well as do that in the swapBuffer/Present method of GraphicsDevice and you're good to go.

Share this post


Link to post
Share on other sites

That looks useful for debugging, but how would you rewrite this code so that it doesn't cause the assert to fail?



GraphicsDevice device;
Texture* texture1 = device.CreateTexture(...);
device.SetTexture(texture1);
delete texture1;
Texture* texture2 = device.CreateTexture(...); // device dereferences dangling pointer; crash

 
 



This is problematic. Best way to deal with this is to let GraphicsDevice to deallocate the texture (instead of leaving it to Texture). If deallocating currently bound texture, then just reset the texture pointer to NULL.
There's also the option of using one texture unit as a temporary unit for all those things like creating textures. This is less pretty, and leaves you with one unit less, but it'll help minimize the amount of rebinds.

Share this post


Link to post
Share on other sites
Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

 

In theory this is a valid line of questioning.

 

In practice you may need to update a texture (or buffer object) at any point in time, and you may also have a state filtering system set up (to catch redundant glBind* calls) which would also be messed up.  Things are never quite so clean in the real world, unfortunately.

Share this post


Link to post
Share on other sites

[quote name='max343' timestamp='1356516002' post='5014372']
This is problematic. Best way to deal with this is to let GraphicsDevice to deallocate the texture (instead of leaving it to Texture). If deallocating currently bound texture, then just reset the texture pointer to NULL.
There's also the option of using one texture unit as a temporary unit for all those things like creating textures. This is less pretty, and leaves you with one unit less, but it'll help minimize the amount of rebinds.
[/quote]

 

Yeah, moving the deallocation function into the GraphicsDevice class is probably the best solution.  Reserving one texture unit for modifying/creating textures would work fairly well, but I don't think it's worth losing the extra texture unit, and this approach doesn't extend to other resource types (buffer objects, shaders, FBOs, etc.)

 

 

[quote name='beans222' timestamp='1356498994' post='5014334']

Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

[/quote]

 

This is a good point, but as mhagain says, there likely are some cases where you may need to modify or create resources in the middle of rendering.  In any case, I'd prefer a system where you can create resources whenever you want; I think it's exposing an implementation detail if you restrict users to only doing so at the start of a frame.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By khawk
      We've just released all of the source code for the NeHe OpenGL lessons on our Github page at https://github.com/gamedev-net/nehe-opengl. code - 43 total platforms, configurations, and languages are included.
      Now operated by GameDev.net, NeHe is located at http://nehe.gamedev.net where it has been a valuable resource for developers wanting to learn OpenGL and graphics programming.

      View full story
    • By TheChubu
      The Khronos™ Group, an open consortium of leading hardware and software companies, announces from the SIGGRAPH 2017 Conference the immediate public availability of the OpenGL® 4.6 specification. OpenGL 4.6 integrates the functionality of numerous ARB and EXT extensions created by Khronos members AMD, Intel, and NVIDIA into core, including the capability to ingest SPIR-V™ shaders.
      SPIR-V is a Khronos-defined standard intermediate language for parallel compute and graphics, which enables content creators to simplify their shader authoring and management pipelines while providing significant source shading language flexibility. OpenGL 4.6 adds support for ingesting SPIR-V shaders to the core specification, guaranteeing that SPIR-V shaders will be widely supported by OpenGL implementations.
      OpenGL 4.6 adds the functionality of these ARB extensions to OpenGL’s core specification:
      GL_ARB_gl_spirv and GL_ARB_spirv_extensions to standardize SPIR-V support for OpenGL GL_ARB_indirect_parameters and GL_ARB_shader_draw_parameters for reducing the CPU overhead associated with rendering batches of geometry GL_ARB_pipeline_statistics_query and GL_ARB_transform_feedback_overflow_querystandardize OpenGL support for features available in Direct3D GL_ARB_texture_filter_anisotropic (based on GL_EXT_texture_filter_anisotropic) brings previously IP encumbered functionality into OpenGL to improve the visual quality of textured scenes GL_ARB_polygon_offset_clamp (based on GL_EXT_polygon_offset_clamp) suppresses a common visual artifact known as a “light leak” associated with rendering shadows GL_ARB_shader_atomic_counter_ops and GL_ARB_shader_group_vote add shader intrinsics supported by all desktop vendors to improve functionality and performance GL_KHR_no_error reduces driver overhead by allowing the application to indicate that it expects error-free operation so errors need not be generated In addition to the above features being added to OpenGL 4.6, the following are being released as extensions:
      GL_KHR_parallel_shader_compile allows applications to launch multiple shader compile threads to improve shader compile throughput WGL_ARB_create_context_no_error and GXL_ARB_create_context_no_error allow no error contexts to be created with WGL or GLX that support the GL_KHR_no_error extension “I’m proud to announce OpenGL 4.6 as the most feature-rich version of OpenGL yet. We've brought together the most popular, widely-supported extensions into a new core specification to give OpenGL developers and end users an improved baseline feature set. This includes resolving previous intellectual property roadblocks to bringing anisotropic texture filtering and polygon offset clamping into the core specification to enable widespread implementation and usage,” said Piers Daniell, chair of the OpenGL Working Group at Khronos. “The OpenGL working group will continue to respond to market needs and work with GPU vendors to ensure OpenGL remains a viable and evolving graphics API for all its customers and users across many vital industries.“
      The OpenGL 4.6 specification can be found at https://khronos.org/registry/OpenGL/index_gl.php. The GLSL to SPIR-V compiler glslang has been updated with GLSL 4.60 support, and can be found at https://github.com/KhronosGroup/glslang.
      Sophisticated graphics applications will also benefit from a set of newly released extensions for both OpenGL and OpenGL ES to enable interoperability with Vulkan and Direct3D. These extensions are named:
      GL_EXT_memory_object GL_EXT_memory_object_fd GL_EXT_memory_object_win32 GL_EXT_semaphore GL_EXT_semaphore_fd GL_EXT_semaphore_win32 GL_EXT_win32_keyed_mutex They can be found at: https://khronos.org/registry/OpenGL/index_gl.php
      Industry Support for OpenGL 4.6
      “With OpenGL 4.6 our customers have an improved set of core features available on our full range of OpenGL 4.x capable GPUs. These features provide improved rendering quality, performance and functionality. As the graphics industry’s most popular API, we fully support OpenGL and will continue to work closely with the Khronos Group on the development of new OpenGL specifications and extensions for our customers. NVIDIA has released beta OpenGL 4.6 drivers today at https://developer.nvidia.com/opengl-driver so developers can use these new features right away,” said Bob Pette, vice president, Professional Graphics at NVIDIA.
      "OpenGL 4.6 will be the first OpenGL release where conformant open source implementations based on the Mesa project will be deliverable in a reasonable timeframe after release. The open sourcing of the OpenGL conformance test suite and ongoing work between Khronos and X.org will also allow for non-vendor led open source implementations to achieve conformance in the near future," said David Airlie, senior principal engineer at Red Hat, and developer on Mesa/X.org projects.

      View full story
    • By _OskaR
      Hi,
      I have an OpenGL application but without possibility to wite own shaders.
      I need to perform small VS modification - is possible to do it in an alternative way? Do we have apps or driver modifictions which will catch the shader sent to GPU and override it?
    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
  • Advertisement