# OpenGL wglShareLists and multiple render windows

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

## Recommended Posts

MSDN is the only crediable source on wiggle (that I know of) and it's pretty much outdated with plenty of missing functions so there's usually some sort of dark magic involved if one is about to step outside the cozy shelter and enter the dark realm of lesser-used functions. wglShareLists() is one member of this family. MSDN states that this function informs OpenGL server to share the diplay-list space between several rendering contexts but it never talks about other server-side resources. I'm assuming that other server-side resources such as textures and VBOs are also shared, but to my experience server-side states are not. I've been playing around with wglShareLists() for a few days now so my knowledge on the subject is limitted. My interpretation might also be completely wrong, especially considering the scarce documentaion that's available but my experience is that server-side states (states that are set by glEnable/glDisable for instance) are not shared between the rendering contexts so they must be explicitly set for every single rendering context that's available, which is a pain in the rear end in applications with multiple render window setups. These states tend to get out of synch and cause headaches in the long run. So my first question is this: Do you have any experience with wglShareLists()? What's your take on the aforementioned dilemma? As far as I'm concerned, D3D's architecture is a whole lot cleaner in this regard. In D3D, pipeline states are stored inside the device object, which, as far as I know, is not directly related or bound to a window. These states are shared among all windows which in turn, are represented by swap chains. There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created. In OpenGL, rendering contexts are bound to windows (rendering contexts are bound to device contexts which in turn are bound to windows, to be exact), which makes sharing them non-trivial considering the set of functions that are available. I even went as far as creating a dummy rendering context that's attached to a dummy window and used that as a hub to share other states, but you see, wglShareLists doesn't allow sharing of states. So, do you know of a workaround? Did you find this issue problematic? Thanks

##### Share on other sites
Yes, MSDN is outdated. It will soon be updated *

wglShareLists is not such a great name for the function, but essentially it shares objects between 2 or more GL contexts :
- display lists (essentially replaced by VBO/IBO)
- VBO/IBO
- textures
- FBO
- PBO

* just kidding

Quote:
 I even went as far as creating a dummy rendering context that's attached to a dummy window and used that as a hub to share other states, but you see, wglShareLists doesn't allow sharing of states.

Try just making 1 GL context and use them for both windows.

##### Share on other sites
Quote:
 Original post by V-manYes, MSDN is outdated. It will soon be updated *wglShareLists is not such a great name for the function, but essentially it shares objects between 2 or more GL contexts :- display lists (essentially replaced by VBO/IBO)- VBO/IBO- shaders- textures- FBO- PBO* just kidding

You certainly got me for a moment [smile] I thought you work for microsoft or something [grin]

Quote:

Quote:
 I even went as far as creating a dummy rendering context that's attached to a dummy window and used that as a hub to share other states, but you see, wglShareLists doesn't allow sharing of states.

Try just making 1 GL context and use them for both windows.

But how?! Each rendering context must be associated with a device context (wglCreateContext needs that) and each window has a device context of its own. So, I think the question boils down to this: how can several windows share a device context? Or am I missing something? A code snippet might help clarify these points.

Any help is greatly appreciated.

##### Share on other sites
Yes, wglCreateContext takes a HDC as a parameter but I think the driver doesn't care as other people seem to be doing this for a long time. I don't know what things you must respect. Perhaps both windows must be created from the same process. It shouldn't matter if both windows are created in the same thread or not. I think both windows must be on the same graphics card. If 2 graphics cards are used (like 2 nvidia's), the driver would do some management so it would work.
The pixelformat you give to SetPixelFormat should be the same.

##### Share on other sites
Quote:
 ....server-side states (states that are set by glEnable/glDisable for instance) are not shared between the rendering contexts so they must be explicitly set for every single rendering context that's available, which is a pain in the rear end in applications with multiple render window setups. These states tend to get out of synch and cause headaches in the long run. So my first question is this: Do you have any experience with wglShareLists()? What's your take on the aforementioned dilemma?

First, the most important question I have is:
What are you using multiple windows for?

Then the others:
Can you give an example of "states get out of sync"?

My thinking is quite different (maybe I am just stuck with thinking of making the best of what apis have to offer to date?): I cannot see a real dilemma(until you answer the "states get out of sync" and other question above perhaps).

Quote:
 ...experience with wglShareLists()?

wglShareLists() can actually be well suited to mfc or forms applications(once you get over its undocumented idiosyncracies): windows manages the err..windows, and each window's contents is managed (or rather rendered) by the graphics api of choice..(obviously opengl, in this case). However, this depends on your specific application too really. The example application I have in mind is something like 3ds max: in so far has having multiple views of the same scene, and even numerous other windows that may display other things such as materials/texures.

The only real disadvantage of not being able to share state changes with wglShareLists I can see is:
You have already mentioned-> making unneccessary server-side state calls(e.g. having to Re-glEnable()/Re-glDisable() etc..of the same state after a context change). Ultimately, you could minimize the number of server-side state change calls which is apparently always good (some would say critical) for max performance. And it's even better if you do not need to change any more states after that!

See any others?

From the point of view that states do change and each window has the option of rendering its contents differently:
I would still want to manage/keep track of my state changes.
Whether they are 'global' to all(or more than 1) contexts or only 'local' to each context. Interestingly, let's just say I could share state changes among contexts via wglShareLists() and I still want to manage/keep track of state changes for what gets rendered in each window. I would hope for increased performance, but managing those state changes could become a little more complex as I may need to then consider which states I am dealing with, the 'global' ones(where more than one window currently shares it) or the 'local' ones(one window's current state). A minor price to pay if the performance increase is worth it. So, in a way, in this case, if you have a lot of state changes happening, your task of managing them becomes more complex, unless each state change applies to every window all the time (i.e. not only multiple windows, but duplicate windows? for what purpose?)

I imagine possible performance enhancements may be had by a programmer actually implementing such a similar scheme even in a one windowed app to avoid the notorious redundant state change?(By the by, non-pure directx devices can be more forgiving, filtering out redundant state changes)

So, after all that, I would presume that you are really searching for a better way to manage your server-side state changes(Your "states get out of sync" remark is indicative of this to me) instead of assuming server-state sharing may be a solution to your pain?
Yes? No?

Terrible, aren't I, answering the question I wish you had asked, instead of answering the question you actually asked? Maybe I should become a politician (but it pays too much and I am not a very good liar).

Or maybe I am barking up the wrong tree? woof. It's easy to do.

Quote:
 ....So, do you know of a workaround? Did you find this issue problematic?

Since when is programming not problematic! ;)
I think I know what you mean: realtively speaking, no: You may just need to be more (boringly) systematic in your approach as the size of your state changes
grow. It depends how many state changes per frame you have to manage.
Again, with your "states out of sync" problem you either have hundreds/thousands or you are finding it difficult to manage the few you have.

Tell us. Who knows, maybe "Try just making 1 GL context and use them for both windows" may just be more suitable. There's nothing wrong with throwing it out there as an option, but I see no evidence to presume it happens to be the most suitable one?

RE: wglShareLists() undocumented idiosyncracies. e.g. I have found that in a forms application the contexts of 4 views works appropriately only before any context is actually made current (i.e. call wglShareLists() before any calls to
wglMakeCurrent()....go figure ( the cause could be elsewhere?...but this was a solution).

##### Share on other sites
OK, maybe I went too far with my "states get out of synch" statement, or maybe you just based too much of your arguments on that [smile]. Anyway, all I meant was that having to manage a different set of states for every single window is sure too much work to do. My argument was mainly a result of comparing OpenGL's unintuitive approach and D3D's more elegant method of handling things in this regard (that's just my opinion).

I haven't yet experimented with V-man's approach (i.e. having a single rendering context for multiple windows), but as there seems to be quite a few people suggesting that approach (I asked the same question at OpenGL.org forums and got the same answer; greedy me!), I'm going to assume that it works well which as far as I'm conrened is miles better than using wglShareLists, but the downside to both of these approaches (i.e. 1- having one rendering context for multiple windows and 2- using wglShareLists to share server-side resources), is that all DCs must have the same pixel format, which is even a greater concern compared to the aforementioned state management issue. What if I want to enable anti-aliasing for one of my windows and disable that on all others? What if I want to have several windows with different depth percisions? Should I load all server-side resource several times? You've gotta admit that this really sucks.

Quote:
 Tell us. Who knows, maybe "Try just making 1 GL context and use them for both windows" may just be more suitable. There's nothing wrong with throwing it out there as an option, but I see no evidence to presume it happens to be the most suitable one?

So why do you prefer using wglShareLists()?

Quote:
 RE: wglShareLists() undocumented idiosyncracies. e.g. I have found that in a forms application the contexts of 4 views works appropriately only before any context is actually made current (i.e. call wglShareLists() before any calls towglMakeCurrent()....go figure ( the cause could be elsewhere?...but this was a solution).

You mean one should call wglShareLists() before ANY calls to wglMakeCurrent() or only before wglMakeCurrent() calls that take place on the rendering context that's to be shared?

##### Share on other sites
Quote:
 OK, maybe I went too far with my "states get out of synch" statement, or maybe you just based too much of your arguments on that .

No problem. If I had to enter a plea it would be: guilty as charged.
I kept on thinking "how do you do that"? So I invented my little "server state mis-management" agenda. sorry.

So, are you now saying your states do not get out of sync? Did you try to go for a more dramatic effect or something? Well... it worked!

Quote:
 My argument was mainly a result of comparing OpenGL's unintuitive approach and D3D's more elegant method of handling things in this regard (that's just my opinion).

That is easily evident from your orginal D3D comments. And I would slightly tend to agree (if I forced myself).

Quote:
 ..but the downside to both of these approaches (i.e. 1- having one rendering context for multiple windows and 2- using wglShareLists to share server-side resources), is that all DCs must have the same pixel format, which is even a greater concern compared to the aforementioned state management issue. What if I want to enable anti-aliasing for one of my windows and disable that on all others? What if I want to have several windows with different depth percisions? Should I load all server-side resource several times? You've gotta admit that this really sucks.

fair enough. Being in a pragmatic state of mind, I guess the majority of what's left of the opengl graphics programming community has bitten the bullet(waiting...and waiting..and waiting...for..what is it..that new thing...Opengl 3.0?) and tolerated it to date, if they haven't already moved over exclusively to Directx. If there was an actual specific problem you are trying to present, maybe I could respond in a better way (I'll assume you just need to express your frustration).

Quote:
 So why do you prefer using wglShareLists()?

I cannot really give you any compelling reasons why. It's the first thing I found that allowed me to share those resources listed above in as many windows as I want. Pretty simple really, and it's worked fine ever since. Now I guess if someone gave me a compelling reason to simply change to one rendering context for multiple windows(e.g. increase my current 260fps in 4 views to say ...I dunno..300fps) I might consider not using it any longer(and go with the flow?..hoping as little as possible server state-changing/management code would need to be reorganised to make it worth it...now that would be a dilemma!).

Quote:
 I'm going to assume that it works well which as far as I'm conrened is miles better than using wglShareLists

I'd like to hear how it goes. Give me a compelling reason to do likewise and I won't be able to resist joining you.

Quote:
 You mean one should call wglShareLists() before ANY calls to wglMakeCurrent() or only before wglMakeCurrent() calls that take place on the rendering context that's to be shared?

Call wglShareLists() on shared contexts before any of those shared contexts are made current with wglMakeCurrent(). So that implies wglMakeCurrent() can be called before wglShareLists() as long as it is called on a context you do not intend to be a sharer/sharee (hope that's better - it only occurs in C++ forms applications. No such problem in mfc apps). (incidently, you should view this problem for what it is: an isolated incident...until it is/has been shown to be repeatable by others - as you said - since not much info around about wglShareLists() ).

##### Share on other sites
Quote:
 What if I want to enable anti-aliasing for one of my windows and disable that on all others? What if I want to have several windows with different depth percisions? Should I load all server-side resource several times? You've gotta admit that this really sucks.

Yes, that is correct.
In general, like the previous person said it's better to just have 1 window with multiple views just like 3dS max does andmany other CAD and content creation software.

##### Share on other sites
Quote:
 Yes, that is correct.In general, like the previous person said it's better to just have 1 window with multiple views just like 3dS max does andmany other CAD and content creation software.

now you are confusing me.

apparently, 3ds max used to be a slightly different beast again:

"Since MAX is highly multi-threaded, it is absolutely imperative that the OpenGL driver be thread safe. In particular, MAX maintains one "draw thread" per viewport (four total), and these threads create and hold on to their own OpenGL rendering contexts (OGLRC) for the entire run of MAX. In more detail, the contexts are created and made current at the beginning of the MAX session (one context per each of the four drawing threads), and the four contexts remain current in their respective threads until MAX is terminated. "

if this ancient history is to be believed from here Some pertinent questions would be:

(1)would said opengl contexts have been shared?(an almost rhetorical question?)

(2)Does it apply to the latest 3dsmax today?
Another almost rhetorical question, but more unanswerable than rhetorical.

##### Share on other sites
Thank you both of you guys.

Quote:

Quote:
 My argument was mainly a result of comparing OpenGL's unintuitive approach and D3D's more elegant method of handling things in this regard (that's just my opinion).

That is easily evident from your orginal D3D comments. And I would slightly tend to agree (if I forced myself).

I'd like to add that I'm not bashing OpenGL in anyway... and not that you implied that I'm influenced by such mentality. Far from it. I just wanted to clarify that I like both APIs the same and my only purpose is to get myself acquianted with the quirks. D3D has its own weaknesses too.

Quote:

Quote:
 ..but the downside to both of these approaches (i.e. 1- having one rendering context for multiple windows and 2- using wglShareLists to share server-side resources), is that all DCs must have the same pixel format, which is even a greater concern compared to the aforementioned state management issue. What if I want to enable anti-aliasing for one of my windows and disable that on all others? What if I want to have several windows with different depth percisions? Should I load all server-side resource several times? You've gotta admit that this really sucks.

fair enough. Being in a pragmatic state of mind, I guess the majority of what's left of the opengl graphics programming community has bitten the bullet(waiting...and waiting..and waiting...for..what is it..that new thing...Opengl 3.0?) and tolerated it to date, if they haven't already moved over exclusively to Directx. If there was an actual specific problem you are trying to present, maybe I could respond in a better way (I'll assume you just need to express your frustration).

It seems that the community has been waiting for OpenGL 3.0 forever...

Back to our discussion, to reiterate my earlier question, do you know of an approach that allows several windows to have different pixel formats while the server-side resources are still shared?

Quote:

Quote:
 So why do you prefer using wglShareLists()?

I cannot really give you any compelling reasons why. It's the first thing I found that allowed me to share those resources listed above in as many windows as I want. Pretty simple really, and it's worked fine ever since. Now I guess if someone gave me a compelling reason to simply change to one rendering context for multiple windows(e.g. increase my current 260fps in 4 views to say ...I dunno..300fps) I might consider not using it any longer(and go with the flow?..hoping as little as possible server state-changing/management code would need to be reorganised to make it worth it...now that would be a dilemma!).

Quote:
 I'm going to assume that it works well which as far as I'm conrened is miles better than using wglShareLists

I'd like to hear how it goes. Give me a compelling reason to do likewise and I won't be able to resist joining you.

It addresses the first issue: state management. You won't be needing to keep track of states for different rendering contexts since all states reside in a single context. It simplifies the design to some extent. Of course, you'd be needing some form of state management to cull redundant states.

Quote:

Quote:
 You mean one should call wglShareLists() before ANY calls to wglMakeCurrent() or only before wglMakeCurrent() calls that take place on the rendering context that's to be shared?

Call wglShareLists() on shared contexts before any of those shared contexts are made current with wglMakeCurrent(). So that implies wglMakeCurrent() can be called before wglShareLists() as long as it is called on a context you do not intend to be a sharer/sharee (hope that's better - it only occurs in C++ forms applications. No such problem in mfc apps). (incidently, you should view this problem for what it is: an isolated incident...until it is/has been shown to be repeatable by others - as you said - since not much info around about wglShareLists() ).

Thanks for the tip.

##### Share on other sites
Quote:
Original post by steven katic
Quote:
 Yes, that is correct.In general, like the previous person said it's better to just have 1 window with multiple views just like 3dS max does and many other CAD and content creation software.

now you are confusing me.

apparently, 3ds max used to be a slightly different beast again:

Sorry for using 3dS max as an example since you seemed to have read some in depth material about it and it is rather lengthy.

All I'm saying is that instead of having 2 windows, just make 1, use half of the window for 1 thing and the other half for something else.

If that is not possible for you then I think the previous answers here cover all your questions.

##### Share on other sites
Quote:
 It addresses the first issue: state management. You won't be needing to keep track of states for different rendering contexts since all states reside in a single context. It simplifies the design to some extent. Of course, you'd be needing some form of state management to cull redundant states.

come on now...you should be careful...it sounds like you are clutching at straws to justify its use to me - there is no need to justify any of your actions. I am here to discuss...not to convince..or to otherwise be convinced of anything.

Having said that I'lI continue to be blunt:
I fail to see any reason in that statement, let alone a compelling one to cease the use of wglShareLists() the way I do.

All I see there is a statement that applies equally to the shared contexts implementation I have. The major difference being that I have a context switch statement as the first statement in my viewport rendering function. In fact it is probably the only code wise difference to be had (I guess my implementation just happens to be organised in such a way by chance that allows me to say that i.e. point is it depends on you application implementation).OOps - should be real easy to just change it over to the one context multiple window method then!!! I put my foot in it now hey?

I can give you an example of how simple it works if you like?

In the meantime, if I were to try and convince you of anything..it would be to go with the 1 context with multiple windows - I actually want to know how it compares - but I'm to lazy to do the research! (But you have to be kind enough to share what you have learnt from it with us....*gulp*

V-man
Quote:
 Sorry for using 3dS max as an example since you seemed to have read some in depth material about it and it is rather lengthy.

I found it in a galaxy far, far away,... long ago, and the haze is temporarily lifting from my memory, so I have to type quickly...before it returns!(this is now a memory... of a memory...of a memeory...of a mem.. unfortunately). It is probably ONE of the real reasons that prompted me to go with the multiple shared contexts concept. I had a soft spot for 3dsMax long ago and had to find out everything I could about how they implemented there multitude of windows. Being such a powerful premium product of choice was compelling enough a reason to attempt to emulate bits of it; Perhaps not much empirical rigor in that logic at all hey? Then the little boy grew up a little, hopefully.
Rather lengthy you say? Nah... Hey what do you think I read that stuff? It's reference material, scan it for info like I do, don't read it!

Quote:
 All I'm saying is that instead of having 2 windows, just make 1, use half of the window for 1 thing and the other half for something else.Multithreading not required.

yeah well....its not the contents(it may be dated info?) of that 3dsMax document that is important, it is its possible level of credibility that is important compared to your statement about 3dsMax.

[Edited by - steven katic on May 10, 2008 4:37:48 PM]

##### Share on other sites
Quote:
Original post by steven katic
Quote:
 It addresses the first issue: state management. You won't be needing to keep track of states for different rendering contexts since all states reside in a single context. It simplifies the design to some extent. Of course, you'd be needing some form of state management to cull redundant states.

come on now...you should be careful...it sounds like you are clutching at straws to justify its use to me - there is no need to justify any of your actions. I am here to discuss...not to convince..or to otherwise be convinced of anything.

It's not like I'll win a free trip to moon if I manage to convince you?! I can't believe how you started getting so defensive all of a sudden after being so helpful all the way. I was just expressing my opinion for the sake of discussion and I don't see any reason to start getting hostile. If you're not convinced that managing one rendering context instead of several is both easier and more convinient, so be it. We have different opinions, big deal. Even if I was blindly insisting on a falacy, which I was *not*... well, it's my loss if I want to act blindly and there's no need for you to get defensive over it.

Thank you both of you guys for sharing your knowledge with me.

##### Share on other sites
Something you may find interesting Ashkan:
I thought I would start a little investigating into the notorious expense of opengl render context switching vs 1 context + multiple device contexts.

I also said:
Quote:
 OOps - should be real easy to just change it over to the one context multiple window method then!!! I put my foot in it now hey?

And it is true: All I did is the following:
private: System::Void ShareGLContexts(){   /**** (A)changed this ***********************/   // get the contexts to share resources   HGLRC c1 = m_OpenglViewports[0]->GetContext();   HGLRC c2 = m_OpenglViewports[1]->GetContext();   HGLRC c3 = m_OpenglViewports[2]->GetContext();   HGLRC c4 = m_OpenglViewports[3]->GetContext();   // whats with the going overboard with sharing both ways?: could be a problem.   if(!wglShareLists( c1,c2  ) || !wglShareLists( c3,c2  ) ||       !wglShareLists( c4,c2  ) || !wglShareLists( c2,c1  ) ||      !wglShareLists( c2,c3  ) || !wglShareLists( c2,c4  ) )   {      bGLContextShared = false;   }   /* (B)to this: *************************/   // 4 devices sharing one render context test   		    HGLRC c1 = m_OpenglViewports[0]->GetContext();			   m_OpenglViewports[1]->SetContext(c1);   m_OpenglViewports[2]->SetContext(c1);   m_OpenglViewports[3]->SetContext(c1);}

So far in testing nothing has changed: not even my fps metric of 260(or so I thought).
I tried out gDebugger for more reliable metrics and it records the following:
Option (A) 4 shared render contexts: 130 fps.[edited: 15th may 08 only 2 contexts where mesured!]
(Edit 15th may 08: Option(A) 4 shared contexts where all 4 where measured (65 fps per context)
Option (B) 1 render context shared among 4 DCs 260 fps.

Now that might be potentially compelling (so far). But something is not right (e.g. My fps counter?, or the way I use gDebugger is not right?). I need to continue testing, but with more rigor before making conclusions just yet. I must say gDebugger's metrics/testing options are very impressive (and very quick and easy to use).

Something of maybe more interest Ashkan, may be talk from here:
Quote:
 ...today with FBOs, there's no reason to use more than one context per GPU. You either just don't need it(no Pbuffers anymore) or got something else wrong (there' s no point in talking to the same gfx cards from two threads concurrently)....

FBO specs (and other docs) do mention FBO superiority to and substitution for context switching. Apparently different precision depths(you mention) can be achieved if you delve further into the use of FBOs. However, I have my doubts about FBO as suitable for multi windows (could it be a square peg for a round whole?): meaning "try it see" tests are required (there are 2 typical uses of FBOs, mutli windows is not one of them, as far as I can tell so far).

Hope this tentative speculation has been of interest.

[Edited by - steven katic on May 15, 2008 5:59:04 AM]

• 12
• 11
• 17
• 11
• 13
• ### Similar Content

• Hello Everyone,
I have been going over a number of books and examples that deal with GLSL. It's common after viewing the source code to have something like this...
class Model{ public: Model(); void render(); private: GLSL glsl_program; }; ////// .cpp Model::Model(){ glsl_program.compileAndLinkShaders() } void Model::render(){ glsl_program.use() //render something glsl_program.unUse(); } Is this how a shader program should be used in real time applications? For example, if I have a particle class, for every particle that's created, do I want to compiling and linking a vertex, frag shader? It seems to a noob such as myself this might not be the best approach to real time applications.
If I am correct, what is the best work around?
Thanks so much for all the help,

Mike

• I'm having some difficulty understanding how data would flow or get inserted into a multi-threaded opengl renderer where there is a thread pool and a render thread and an update thread (possibly main). My understanding is that the threadpool will continually execute jobs, assemble these and when done send them off to be rendered where I can further sort these and achieve some cheap form of statelessness. I don't want anything overly complicated or too fine grained,  fibers,  job stealing etc. My end goal is to simply have my renderer isolated in its own thread and only concerned with drawing and swapping buffers.
My questions are:
1. At what point in this pipeline are resources created?
Say I have a
class CCommandList { void SetVertexBuffer(...); void SetIndexBuffer(...); void SetVertexShader(...); void SetPixelShader(...); } borrowed from an existing post here. I would need to generate a VAO at some point and call glGenBuffers etc especially if I start with an empty scene. If my context lives on another thread, how do I call these commands if the command list is only supposed to be a collection of state and what command to use. I don't think that the render thread should do this and somehow add a task to the queue or am I wrong?
Or could I do some variation where I do the loading in a thread with shared context and from there generate a command that has the handle to the resources needed.

2. How do I know all my jobs are done.
I'm working with C++, is this as simple as knowing how many objects there are in the scene, for every task that gets added increment a counter and when it matches aforementioned count I signal the renderer that the command list is ready? I was thinking a condition_variable or something would suffice to alert the renderthread that work is ready.

3. Does all work come from a singular queue that the thread pool constantly cycles over?
With the notion of jobs, we are basically sending the same work repeatedly right? Do all jobs need to be added to a single persistent queue to be submitted over and over again?

4. Are resources destroyed with commands?
Likewise with initializing and assuming #3 is correct, removing an item from the scene would mean removing it from the job queue, no? Would I need to send a onetime command to the renderer to cleanup?

• I am starting to get into linux X11/GLX programming, but from every C example i found - there is this XVisualInfo thing parameter passed to XCreateWindow always.
Can i control this parameter later on - when the window is already created? What i want it to change my own non GLX window to be a GLX window - without recreating. Is that possible?

On win32 this works just fine to create a rendering context later on, i simply find and setup the pixel format from a pixel format descriptor and create the context and are ready to go.

I am asking, because if that doesent work - i need to change a few things to support both worlds (Create a context from a existing window, create a context for a new window).

• This article uses material originally posted on Diligent Graphics web site.
Introduction
Graphics APIs have come a long way from small set of basic commands allowing limited control of configurable stages of early 3D accelerators to very low-level programming interfaces exposing almost every aspect of the underlying graphics hardware. Next-generation APIs, Direct3D12 by Microsoft and Vulkan by Khronos are relatively new and have only started getting widespread adoption and support from hardware vendors, while Direct3D11 and OpenGL are still considered industry standard. New APIs can provide substantial performance and functional improvements, but may not be supported by older hardware. An application targeting wide range of platforms needs to support Direct3D11 and OpenGL. New APIs will not give any advantage when used with old paradigms. It is totally possible to add Direct3D12 support to an existing renderer by implementing Direct3D11 interface through Direct3D12, but this will give zero benefits. Instead, new approaches and rendering architectures that leverage flexibility provided by the next-generation APIs are expected to be developed.
There are at least four APIs (Direct3D11, Direct3D12, OpenGL/GLES, Vulkan, plus Apple's Metal for iOS and osX platforms) that a cross-platform 3D application may need to support. Writing separate code paths for all APIs is clearly not an option for any real-world application and the need for a cross-platform graphics abstraction layer is evident. The following is the list of requirements that I believe such layer needs to satisfy:
Lightweight abstractions: the API should be as close to the underlying native APIs as possible to allow an application leverage all available low-level functionality. In many cases this requirement is difficult to achieve because specific features exposed by different APIs may vary considerably. Low performance overhead: the abstraction layer needs to be efficient from performance point of view. If it introduces considerable amount of overhead, there is no point in using it. Convenience: the API needs to be convenient to use. It needs to assist developers in achieving their goals not limiting their control of the graphics hardware. Multithreading: ability to efficiently parallelize work is in the core of Direct3D12 and Vulkan and one of the main selling points of the new APIs. Support for multithreading in a cross-platform layer is a must. Extensibility: no matter how well the API is designed, it still introduces some level of abstraction. In some cases the most efficient way to implement certain functionality is to directly use native API. The abstraction layer needs to provide seamless interoperability with the underlying native APIs to provide a way for the app to add features that may be missing. Diligent Engine is designed to solve these problems. Its main goal is to take advantages of the next-generation APIs such as Direct3D12 and Vulkan, but at the same time provide support for older platforms via Direct3D11, OpenGL and OpenGLES. Diligent Engine exposes common C++ front-end for all supported platforms and provides interoperability with underlying native APIs. It also supports integration with Unity and is designed to be used as graphics subsystem in a standalone game engine, Unity native plugin or any other 3D application. Full source code is available for download at GitHub and is free to use.
Overview
Diligent Engine API takes some features from Direct3D11 and Direct3D12 as well as introduces new concepts to hide certain platform-specific details and make the system easy to use. It contains the following main components:
Render device (IRenderDevice  interface) is responsible for creating all other objects (textures, buffers, shaders, pipeline states, etc.).
Device context (IDeviceContext interface) is the main interface for recording rendering commands. Similar to Direct3D11, there are immediate context and deferred contexts (which in Direct3D11 implementation map directly to the corresponding context types). Immediate context combines command queue and command list recording functionality. It records commands and submits the command list for execution when it contains sufficient number of commands. Deferred contexts are designed to only record command lists that can be submitted for execution through the immediate context.
An alternative way to design the API would be to expose command queue and command lists directly. This approach however does not map well to Direct3D11 and OpenGL. Besides, some functionality (such as dynamic descriptor allocation) can be much more efficiently implemented when it is known that a command list is recorded by a certain deferred context from some thread.
The approach taken in the engine does not limit scalability as the application is expected to create one deferred context per thread, and internally every deferred context records a command list in lock-free fashion. At the same time this approach maps well to older APIs.
In current implementation, only one immediate context that uses default graphics command queue is created. To support multiple GPUs or multiple command queue types (compute, copy, etc.), it is natural to have one immediate contexts per queue. Cross-context synchronization utilities will be necessary.
Swap Chain (ISwapChain interface). Swap chain interface represents a chain of back buffers and is responsible for showing the final rendered image on the screen.
Render device, device contexts and swap chain are created during the engine initialization.
Resources (ITexture and IBuffer interfaces). There are two types of resources - textures and buffers. There are many different texture types (2D textures, 3D textures, texture array, cubmepas, etc.) that can all be represented by ITexture interface.
Resources Views (ITextureView and IBufferView interfaces). While textures and buffers are mere data containers, texture views and buffer views describe how the data should be interpreted. For instance, a 2D texture can be used as a render target for rendering commands or as a shader resource.
Pipeline State (IPipelineState interface). GPU pipeline contains many configurable stages (depth-stencil, rasterizer and blend states, different shader stage, etc.). Direct3D11 uses coarse-grain objects to set all stage parameters at once (for instance, a rasterizer object encompasses all rasterizer attributes), while OpenGL contains myriad functions to fine-grain control every individual attribute of every stage. Both methods do not map very well to modern graphics hardware that combines all states into one monolithic state under the hood. Direct3D12 directly exposes pipeline state object in the API, and Diligent Engine uses the same approach.
Shader Resource Binding (IShaderResourceBinding interface). Shaders are programs that run on the GPU. Shaders may access various resources (textures and buffers), and setting correspondence between shader variables and actual resources is called resource binding. Resource binding implementation varies considerably between different API. Diligent Engine introduces a new object called shader resource binding that encompasses all resources needed by all shaders in a certain pipeline state.
API Basics
Creating Resources
Device resources are created by the render device. The two main resource types are buffers, which represent linear memory, and textures, which use memory layouts optimized for fast filtering. Graphics APIs usually have a native object that represents linear buffer. Diligent Engine uses IBuffer interface as an abstraction for a native buffer. To create a buffer, one needs to populate BufferDesc structure and call IRenderDevice::CreateBuffer() method as in the following example:
BufferDesc BuffDesc; BufferDesc.Name = "Uniform buffer"; BuffDesc.BindFlags = BIND_UNIFORM_BUFFER; BuffDesc.Usage = USAGE_DYNAMIC; BuffDesc.uiSizeInBytes = sizeof(ShaderConstants); BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE; m_pDevice->CreateBuffer( BuffDesc, BufferData(), &m_pConstantBuffer ); While there is usually just one buffer object, different APIs use very different approaches to represent textures. For instance, in Direct3D11, there are ID3D11Texture1D, ID3D11Texture2D, and ID3D11Texture3D objects. In OpenGL, there is individual object for every texture dimension (1D, 2D, 3D, Cube), which may be a texture array, which may also be multisampled (i.e. GL_TEXTURE_2D_MULTISAMPLE_ARRAY). As a result there are nine different GL texture types that Diligent Engine may create under the hood. In Direct3D12, there is only one resource interface. Diligent Engine hides all these details in ITexture interface. There is only one  IRenderDevice::CreateTexture() method that is capable of creating all texture types. Dimension, format, array size and all other parameters are specified by the members of the TextureDesc structure:
TextureDesc TexDesc; TexDesc.Name = "My texture 2D"; TexDesc.Type = TEXTURE_TYPE_2D; TexDesc.Width = 1024; TexDesc.Height = 1024; TexDesc.Format = TEX_FORMAT_RGBA8_UNORM; TexDesc.Usage = USAGE_DEFAULT; TexDesc.BindFlags = BIND_SHADER_RESOURCE | BIND_RENDER_TARGET | BIND_UNORDERED_ACCESS; TexDesc.Name = "Sample 2D Texture"; m_pRenderDevice->CreateTexture( TexDesc, TextureData(), &m_pTestTex ); If native API supports multithreaded resource creation, textures and buffers can be created by multiple threads simultaneously.
Interoperability with native API provides access to the native buffer/texture objects and also allows creating Diligent Engine objects from native handles. It allows applications seamlessly integrate native API-specific code with Diligent Engine.
Next-generation APIs allow fine level-control over how resources are allocated. Diligent Engine does not currently expose this functionality, but it can be added by implementing IResourceAllocator interface that encapsulates specifics of resource allocation and providing this interface to CreateBuffer() or CreateTexture() methods. If null is provided, default allocator should be used.
Initializing the Pipeline State
As it was mentioned earlier, Diligent Engine follows next-gen APIs to configure the graphics/compute pipeline. One big Pipelines State Object (PSO) encompasses all required states (all shader stages, input layout description, depth stencil, rasterizer and blend state descriptions etc.). This approach maps directly to Direct3D12/Vulkan, but is also beneficial for older APIs as it eliminates pipeline misconfiguration errors. With many individual calls tweaking various GPU pipeline settings it is very easy to forget to set one of the states or assume the stage is already properly configured when in fact it is not. Using pipeline state object helps avoid these problems as all stages are configured at once.
While in earlier APIs shaders were bound separately, in the next-generation APIs as well as in Diligent Engine shaders are part of the pipeline state object. The biggest challenge when authoring shaders is that Direct3D and OpenGL/Vulkan use different shader languages (while Apple uses yet another language in their Metal API). Maintaining two versions of every shader is not an option for real applications and Diligent Engine implements shader source code converter that allows shaders authored in HLSL to be translated to GLSL. To create a shader, one needs to populate ShaderCreationAttribs structure. SourceLanguage member of this structure tells the system which language the shader is authored in:
When sampling a texture in a shader, the texture sampler was traditionally specified as separate object that was bound to the pipeline at run time or set as part of the texture object itself. However, in most cases it is known beforehand what kind of sampler will be used in the shader. Next-generation APIs expose new type of sampler called static sampler that can be initialized directly in the pipeline state. Diligent Engine exposes this functionality: when creating a shader, textures can be assigned static samplers. If static sampler is assigned, it will always be used instead of the one initialized in the texture shader resource view. To initialize static samplers, prepare an array of StaticSamplerDesc structures and initialize StaticSamplers and NumStaticSamplers members. Static samplers are more efficient and it is highly recommended to use them whenever possible. On older APIs, static samplers are emulated via generic sampler objects.
The following is an example of shader initialization:
Creating the Pipeline State Object
After all required shaders are created, the rest of the fields of the PipelineStateDesc structure provide depth-stencil, rasterizer, and blend state descriptions, the number and format of render targets, input layout format, etc. For instance, rasterizer state can be described as follows:
PipelineStateDesc PSODesc; RasterizerStateDesc &RasterizerDesc = PSODesc.GraphicsPipeline.RasterizerDesc; RasterizerDesc.FillMode = FILL_MODE_SOLID; RasterizerDesc.CullMode = CULL_MODE_NONE; RasterizerDesc.FrontCounterClockwise = True; RasterizerDesc.ScissorEnable = True; RasterizerDesc.AntialiasedLineEnable = False; Depth-stencil and blend states are defined in a similar fashion.
Another important thing that pipeline state object encompasses is the input layout description that defines how inputs to the vertex shader, which is the very first shader stage, should be read from the memory. Input layout may define several vertex streams that contain values of different formats and sizes:
// Define input layout InputLayoutDesc &Layout = PSODesc.GraphicsPipeline.InputLayout; LayoutElement TextLayoutElems[] = {     LayoutElement( 0, 0, 3, VT_FLOAT32, False ),     LayoutElement( 1, 0, 4, VT_UINT8, True ),     LayoutElement( 2, 0, 2, VT_FLOAT32, False ), }; Layout.LayoutElements = TextLayoutElems; Layout.NumElements = _countof( TextLayoutElems ); Finally, pipeline state defines primitive topology type. When all required members are initialized, a pipeline state object can be created by IRenderDevice::CreatePipelineState() method:
// Define shader and primitive topology PSODesc.GraphicsPipeline.PrimitiveTopologyType = PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; PSODesc.GraphicsPipeline.pVS = pVertexShader; PSODesc.GraphicsPipeline.pPS = pPixelShader; PSODesc.Name = "My pipeline state"; m_pDev->CreatePipelineState(PSODesc, &m_pPSO); When PSO object is bound to the pipeline, the engine invokes all API-specific commands to set all states specified by the object. In case of Direct3D12 this maps directly to setting the D3D12 PSO object. In case of Direct3D11, this involves setting individual state objects (such as rasterizer and blend states), shaders, input layout etc. In case of OpenGL, this requires a number of fine-grain state tweaking calls. Diligent Engine keeps track of currently bound states and only calls functions to update these states that have actually changed.
Direct3D11 and OpenGL utilize fine-grain resource binding models, where an application binds individual buffers and textures to certain shader or program resource binding slots. Direct3D12 uses a very different approach, where resource descriptors are grouped into tables, and an application can bind all resources in the table at once by setting the table in the command list. Resource binding model in Diligent Engine is designed to leverage this new method. It introduces a new object called shader resource binding that encapsulates all resource bindings required for all shaders in a certain pipeline state. It also introduces the classification of shader variables based on the frequency of expected change that helps the engine group them into tables under the hood:
Static variables (SHADER_VARIABLE_TYPE_STATIC) are variables that are expected to be set only once. They may not be changed once a resource is bound to the variable. Such variables are intended to hold global constants such as camera attributes or global light attributes constant buffers. Mutable variables (SHADER_VARIABLE_TYPE_MUTABLE) define resources that are expected to change on a per-material frequency. Examples may include diffuse textures, normal maps etc. Dynamic variables (SHADER_VARIABLE_TYPE_DYNAMIC) are expected to change frequently and randomly. Shader variable type must be specified during shader creation by populating an array of ShaderVariableDesc structures and initializing ShaderCreationAttribs::Desc::VariableDesc and ShaderCreationAttribs::Desc::NumVariables members (see example of shader creation above).
Static variables cannot be changed once a resource is bound to the variable. They are bound directly to the shader object. For instance, a shadow map texture is not expected to change after it is created, so it can be bound directly to the shader:
m_pPSO->CreateShaderResourceBinding(&m_pSRB); Note that an SRB is only compatible with the pipeline state it was created from. SRB object inherits all static bindings from shaders in the pipeline, but is not allowed to change them.
Mutable resources can only be set once for every instance of a shader resource binding. Such resources are intended to define specific material properties. For instance, a diffuse texture for a specific material is not expected to change once the material is defined and can be set right after the SRB object has been created:
m_pSRB->GetVariable(SHADER_TYPE_PIXEL, "tex2DDiffuse")->Set(pDiffuseTexSRV); In some cases it is necessary to bind a new resource to a variable every time a draw command is invoked. Such variables should be labeled as dynamic, which will allow setting them multiple times through the same SRB object:
m_pSRB->GetVariable(SHADER_TYPE_VERTEX, "cbRandomAttribs")->Set(pRandomAttrsCB); Under the hood, the engine pre-allocates descriptor tables for static and mutable resources when an SRB objcet is created. Space for dynamic resources is dynamically allocated at run time. Static and mutable resources are thus more efficient and should be used whenever possible.
As you can see, Diligent Engine does not expose low-level details of how resources are bound to shader variables. One reason for this is that these details are very different for various APIs. The other reason is that using low-level binding methods is extremely error-prone: it is very easy to forget to bind some resource, or bind incorrect resource such as bind a buffer to the variable that is in fact a texture, especially during shader development when everything changes fast. Diligent Engine instead relies on shader reflection system to automatically query the list of all shader variables. Grouping variables based on three types mentioned above allows the engine to create optimized layout and take heavy lifting of matching resources to API-specific resource location, register or descriptor in the table.
This post gives more details about the resource binding model in Diligent Engine.
Setting the Pipeline State and Committing Shader Resources
Before any draw or compute command can be invoked, the pipeline state needs to be bound to the context:
m_pContext->SetPipelineState(m_pPSO); Under the hood, the engine sets the internal PSO object in the command list or calls all the required native API functions to properly configure all pipeline stages.
The next step is to bind all required shader resources to the GPU pipeline, which is accomplished by IDeviceContext::CommitShaderResources() method:
m_pContext->CommitShaderResources(m_pSRB, COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES); The method takes a pointer to the shader resource binding object and makes all resources the object holds available for the shaders. In the case of D3D12, this only requires setting appropriate descriptor tables in the command list. For older APIs, this typically requires setting all resources individually.
Next-generation APIs require the application to track the state of every resource and explicitly inform the system about all state transitions. For instance, if a texture was used as render target before, while the next draw command is going to use it as shader resource, a transition barrier needs to be executed. Diligent Engine does the heavy lifting of state tracking.  When CommitShaderResources() method is called with COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES flag, the engine commits and transitions resources to correct states at the same time. Note that transitioning resources does introduce some overhead. The engine tracks state of every resource and it will not issue the barrier if the state is already correct. But checking resource state is an overhead that can sometimes be avoided. The engine provides IDeviceContext::TransitionShaderResources() method that only transitions resources:
m_pContext->TransitionShaderResources(m_pPSO, m_pSRB); In some scenarios it is more efficient to transition resources once and then only commit them.
Invoking Draw Command
The final step is to set states that are not part of the PSO, such as render targets, vertex and index buffers. Diligent Engine uses Direct3D11-syle API that is translated to other native API calls under the hood:
ITextureView *pRTVs[] = {m_pRTV}; m_pContext->SetRenderTargets(_countof( pRTVs ), pRTVs, m_pDSV); // Clear render target and depth buffer const float zero[4] = {0, 0, 0, 0}; m_pContext->ClearRenderTarget(nullptr, zero); m_pContext->ClearDepthStencil(nullptr, CLEAR_DEPTH_FLAG, 1.f); // Set vertex and index buffers IBuffer *buffer[] = {m_pVertexBuffer}; Uint32 offsets[] = {0}; Uint32 strides[] = {sizeof(MyVertex)}; m_pContext->SetVertexBuffers(0, 1, buffer, strides, offsets, SET_VERTEX_BUFFERS_FLAG_RESET); m_pContext->SetIndexBuffer(m_pIndexBuffer, 0); Different native APIs use various set of function to execute draw commands depending on command details (if the command is indexed, instanced or both, what offsets in the source buffers are used etc.). For instance, there are 5 draw commands in Direct3D11 and more than 9 commands in OpenGL with something like glDrawElementsInstancedBaseVertexBaseInstance not uncommon. Diligent Engine hides all details with single IDeviceContext::Draw() method that takes takes DrawAttribs structure as an argument. The structure members define all attributes required to perform the command (primitive topology, number of vertices or indices, if draw call is indexed or not, if draw call is instanced or not, if draw call is indirect or not, etc.). For example:
DrawAttribs attrs; attrs.IsIndexed = true; attrs.IndexType = VT_UINT16; attrs.NumIndices = 36; attrs.Topology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; pContext->Draw(attrs); For compute commands, there is IDeviceContext::DispatchCompute() method that takes DispatchComputeAttribs structure that defines compute grid dimension.
Source Code
Full engine source code is available on GitHub and is free to use. The repository contains tutorials, sample applications, asteroids performance benchmark and an example Unity project that uses Diligent Engine in native plugin.
Atmospheric scattering sample demonstrates how Diligent Engine can be used to implement various rendering tasks: loading textures from files, using complex shaders, rendering to multiple render targets, using compute shaders and unordered access views, etc.

Asteroids performance benchmark is based on this demo developed by Intel. It renders 50,000 unique textured asteroids and allows comparing performance of Direct3D11 and Direct3D12 implementations. Every asteroid is a combination of one of 1000 unique meshes and one of 10 unique textures.

Finally, there is an example project that shows how Diligent Engine can be integrated with Unity.

Future Work
The engine is under active development. It currently supports Windows desktop, Universal Windows, Linux, Android, MacOS, and iOS platforms. Direct3D11, Direct3D12, OpenGL/GLES backends are now feature complete. Vulkan backend is coming next, and Metal backend is in the plan.

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist