State tracker.
acdemiralp opened this issue · comments
State leaking is a common problem in OpenGL. Many free functions set a global state which often has to be unset at the end of render calls. Find a way to "track" this state and unset it on scope exits, perhaps similar to a std::lock_guard
.
Example:
{
gl::state_guard sg;
gl::set_depth_test_enabled(false);
gl::set_depth_function(GL_EQUAL);
gl::set_front_face(GL_CCW);
gl::set_cull_face(GL_BACK);
}
// Depth test, depth function, front face and cull face are reverted to the defaults here.
Two implementation options:
- Create a gl::state_guard which stores ALL OpenGL state at its time of construction and reverts to it at its time of destruction.
- Pro: Requires no intrusion to existing code.
- Con: Might be slow to store/revert all states each time.
- Create a gl::state_guard which holds an internally managed list of previous states. Modify each global state changing function to register its previous state to this list when a gl::state_guard is in order. Revert to the registered states upon destruction.
- Pro: Works only with the changed states. May be faster.
- Con: Requires intrusion to existing code.
Since this functionality is auxiliary and the library is intended to be a thin wrapper, I would rather not pollute the existing global state functions with state tracking code, and go with the first approach.