views:

642

answers:

1

I'm new to U/I programming, and I'm trying to get started with OpenGL. When I run an example program which creates a new OpenGL window with GLUT, it works fine. Good. However, in the context of another program, where I have to respond to Draw events (on Windows), with a device context passed to me - and where I might not have GLUT available - my confusion is this:

  1. When is a device context created and destroyed? Can I draw to any device context given to me, or only some of them (and how do I know)?

  2. Do I have to create my own OpenGL context and use that to draw to, or can I use a "current" OpenGL context? Do I have to re-create the context every time a draw event is sent?

Basically my question is, given a situation where I am sent "Draw" events, how often do I attempt to create OpenGL contexts and how does this relate to the creation/destruction cycle of device contexts?

+4  A: 

In general, it's usually safe to think of a single OpenGL context as a window, especially on windows.

A device context will (typically) map to an Window Handle (HWND). It's actually a DC (HDC is the handle), but normally you associate one HDC with a single HWND. In Windows, you'll create a window to use based off the window on screen where you want to render.

Typically, you'll reuse this device context for the entire runtime of your application. If you want to render into a different window, you'll need to generate a device context (HDC) for the new window handle. Also, offscreen rendering is a bit different, since you'd create a compatible device context for that, as well.

As for your questions:

1) When you create the window where you want to do the rendering, you'll grab a device context, and use it for the lifetime of that window.

2) You'll want to always use the device context created for the window where you are rendering.

Reed Copsey
Great - I think this answers my question. Then the OpenGL context will pretty much be associated 1-1 with the DC, right? I remember reading about having only one context per thread too. I am supposing, then, that different threads will have different DC's then too?
The threading issue is different - when you make a DC, you need to always use that thread for all calls into that DC. In general, this means one graphics/rendering thread per device context (ie: per window).
Reed Copsey