# OpenGL Animation in a MFC application and OPENGL (again, sorry)

## Recommended Posts

riruilo    218
Hi friends! First all, sorry for my english. My questions are about animations in MFC (doc/view arquitecture) and OPENGL. I know there are some articles and threads about this topic, but actually I don´t have clear this subject. My questions is: What is the most correct way to do that? I found these: Overwrite Idle function: There is an article about this in gamedev but I think (it is my opinion, nothing else) this approach is not elegant and intrusive. http://www.gamedev.net/reference/articles/article2204.asp SetTimer: My teacher at university this is horrible and this function has a bad resolution http://www.gamedev.net/community/forums/topic.asp?topic_id=212576 AfxBeginThread, QueryPerformanceCounter... or some While loop... After read some information I will suggest (me) this: (and maybe I´m wrong) Add to my engine a funtion like this: Render(fElapsedTime); So everything will be rendered depending of the value of fElapsedTime. If an animation has a 3 seconds animation, fElapsedTime will be from 0.0 to 3.0 in a variable frame rate (or fixed), but I prefer to draw all frames that my computer can able to do it. So when I will press PLAY, will occur this: starttime=QueryPerformanceCounter; and after this a thread will be launched with this code: while (true) { fElapsedTime=QueryPerformanceCounter-starttime; Render(fElapsedTime); } (Actually, until you press STOP) Is my approach elegant or very difficult? Will I have problems with MFC model? Will I block message waiting line? How can I add this on OnDraw function? or MFC view/doc paradigm. I think with my approach can give me the maximum amount of FPS of my system, not like SetTimer, which give me a constant FPS. Well, I will apreciate all opinions, I would just like to know WHICH is the best and easy way to do it. Thank you very much for your time.

##### Share on other sites
iNsAn1tY    476
Quote:
 Original post by riruiloOverwrite Idle function: There is an article about this in gamedev but I think (it is my opinion, nothing else) this approach is not elegant and intrusive.http://www.gamedev.net/reference/articles/article2204.asp

Yeah, it is intrusive, and a bit of a hack in truth [grin]

Thing is though, it's a quick and reliable way of continuously updating an MFC application. As you already mention, using a timer is a very poor solution, and just using the OnIdle and OnDraw functions on their own won't give you what you want.

Quote:
 Original post by riruiloAfter read some information I will suggest (me) this: (and maybe I´m wrong)Add to my engine a funtion like this:Render(fElapsedTime);So everything will be rendered depending of the value of fElapsedTime.If an animation has a 3 seconds animation, fElapsedTime will be from 0.0 to 3.0 in a variable frame rate (or fixed), but I prefer to draw all frames that my computer can able to do it.So when I will press PLAY, will occur this:starttime=QueryPerformanceCounter;and after this a thread will be launched with this code:while (true) { fElapsedTime=QueryPerformanceCounter-starttime; Render(fElapsedTime);}(Actually, until you press STOP)Is my approach elegant or very difficult? Will I have problems with MFC model? Will I block message waiting line?How can I add this on OnDraw function? or MFC view/doc paradigm.I think with my approach can give me the maximum amount of FPS of my system, not like SetTimer, which give me a constant FPS.

The other solution, as you suggest, is to use another thread to control rendering. This is a better (and arguably more elegant) way of doing your rendering, but you need to be aware of all the problems which can occur with a multi-threaded solution, such as the potential for deadlock and mutually-exclusive access to data which is shared among threads.

If you're using a different thread, you won't be blocking the message queue; the parent (main) thread will continue to run after launching the child (rendering) thread.

How you integrate your child (rendering) thread with the rest of your application will vary. If your child (rendering) thread is running continuously calling your Render function as often as it can, you won't actually need to do anything in OnDraw (all of your views will presumably be updated by your Render function). All you'll need to do is update the scene data which is displayed by your Render function (and it's here that problems could occur with both threads trying to read/write to shared data).

To prevent all of your views being updated every cycle by the child thread (which might really slow your app down), you can flag that a view is "dirty" (in need of redrawing) in the OnDraw function, and only redraw views in your Render function which have that dirty flag set. Alternatively, you could give the user the option to specify the update (5fps by default, say). 3ds max allows you to do this; basically, you just lock the frame-rate to the user-specified value (which would be a trivial change to your child thread).

Quote:
 Original post by riruiloWell, I will apreciate all opinions, I would just like to know WHICH is the best and easy way to do it.

The method outlined in my article of overriding the Run and OnIdle functions is a quick and relatively hacky way of getting an MFC application to update continuously. The better solution is to create a child thread which runs continuously, and frees your main thread to run the MFC app.

Quote:
 Original post by riruiloThank you very much for your time.

You're welcome [smile]

##### Share on other sites
riruilo    218
Thanks a lot iNsAn1tY.

Right now I´m going to try to implement it using AfxBeginThread. I´m doing a COLLADA loader and I need that for animations.

By the way, is this a proper way to control animations? (time, I mean)

starttime=QueryPerformanceCounter;
and after this a thread will be launched with this code:

while (true) {
fElapsedTime=QueryPerformanceCounter-starttime;
Render(fElapsedTime);
}

Thanks!

##### Share on other sites
Sphet    631
iNsAn1tY posts a lot of good information. I can't add much but I can tell you the experience I had trying to write an animation viewer with MFC & a render viewport. I've tried all kinds of techniques and the best solution I came up with was using the OnIdle() method. It simplifies the process greatly and isn't really a hack if you stop and think about how MFC applications work. Multi threading was really a hassle and made the application much more complicated than it needed to be.

Most applications are event driven - they wait until they receive a message to perform some task. In an animation viewer it is the same - play this animation, load this animation, start, stop. The only difference is that you want to continue to do something while waiting for messages. MFC provides that mechanism in the idle call. You can make it hacky if you don't code it up to make sense ie OnIdle() { DrawSomething(); }.

In our MFC framework there can be multiple viewports. Some of these are updated always and some of them are not.

Every view is derived from CRenderView. This class, on creation, registers itself with the RenderViewManager. It's automatic in the constructor so client code does not even know it's happenening.

Every application derives not from CWinApp but CRenderApp. This application base class in turn derives from CWinApp. What does it do? It contains the RenderViewManager and overloads OnIdle. Every time OnIdle is called, the time delta is determined and the list of CRenderView classes is iterated over, and the Render function is called with the time delta. We also have a virtual function in CRenderApp called OnFrameUpdate() which also gets the delta. This is called first so that objects are updated before they are rendered. The nice thing about this framework is that people can create MFC render applications without having to worry about the guts of the framework. Additionally, we can switch views between being live updated or not - our CRenderView() overrides the paint message and paints the screen if it is 'dirty update' instead of 'live update' mode. In a quad-view with three wireframe views and one live update view this works really well.

If you are trying to use MFC I would avoid multi-threading it; MFC provides the hooks you need to do the work. You'll be thankful you are working on the application's good points instead of working on critical sections and mutexes.

##### Share on other sites
iNsAn1tY    476
Quote:
 Original post by riruiloBy the way, is this a proper way to control animations? (time, I mean)starttime=QueryPerformanceCounter;and after this a thread will be launched with this code:while (true) {fElapsedTime=QueryPerformanceCounter-starttime;Render(fElapsedTime);}

Yeah, that's how performance counters work in outline. You need to divide by the timer frequency, though:

// During initalization...QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER *>( &miTimerFreq ) );QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>( &miStartTime ) );// When updating...__int64 liEndTime;float lfTime;QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER *>( &liEndTime ) );lfTime = static_cast<float>( liEndTime - miStartTime ) / static_cast<float>( miTimerFreq );miStartTime = liEndTime;return lfTime;

Also, every time your while loop executes, you need a non-blocking rendezvous with the parent thread, so that the parent can stop the child thread when it needs to.

Quote:
 Original post by SphetMost applications are event driven - they wait until they receive a message to perform some task. In an animation viewer it is the same - play this animation, load this animation, start, stop. The only difference is that you want to continue to do something while waiting for messages. MFC provides that mechanism in the idle call. You can make it hacky if you don't code it up to make sense ie OnIdle() { DrawSomething(); }.

True. This is the rationale the article works to; it's the simple modification of an application from one which is event-driven to on which is both event-driven and updates continuously. Did your animation viewer only use the OnIdle function? I found that I had to override Run as well to get the kind of reliable updating I expected.

##### Share on other sites
riruilo    218
Hi!

Sorry for this post, but actually I dont know so much threads in MFC.
My first experiment was a failure.

I moved my code from OnDraw to my thread and my screen is black right now (black like my future)

while (true)
{
ts->_this->Render(ts->_this->m_pDC);
}
return 1;
}

And I add this code after opengl initialization, on OnCreate:
_param->m_pDC=m_pDC;
_param->_this=this;

But my screen is black.

Any idea? by the way StartThread is a static funtion.

##### Share on other sites
Sphet    631
Quote:
 Original post by iNsAn1tYTrue. This is the rationale the article works to; it's the simple modification of an application from one which is event-driven to on which is both event-driven and updates continuously. Did your animation viewer only use the OnIdle function? I found that I had to override Run as well to get the kind of reliable updating I expected.

Only OnIdle I believe - I'll check when I am in the office - I think you just need to make sure your OnIdle() kick returns TRUE - this forces the application to keep firing OnIdle() until you return FALSE or there are messages to handle. Once the messages are handled it goes back to OnIdle() calls. It's in OnIdle() tha the time delta was calculated, so I don't know how widely variable the frame-times slices were but none of our engineers or artists complain about it. Maybe I'll put a profile graph in today to see. I do know that when a menu item is being selected, or a modal loop is entered, the screen no longer refreshes ( OnIdle() not called ) but what I did was make it that if WM_Paint is received and the last-render time is quite old ( > 50ms ) to redraw from the view invalidation - this has the effect of 'time stopping' while modal but still rendering what you need to.

What were you doing in Run()?

I justed checked and there's no call to Run at all.

[Edited by - Sphet on March 5, 2007 11:31:20 AM]

## Create an account

Register a new account

• ### Similar Content

• There are studios selling applications which is just copying any 3Dgraphic content and regenerating into another new window. especially for CAVE Virtual reality experience. so that the user opens REvite or CAD or any other 3D applications and opens a model. then when the user selects the rendered window the VR application copies the 3D model information from the OpenGL window.
I got the clue that the VR application replaces the windows opengl32.dll file. how this is possible ... how can we copy the 3d content from the current OpenGL window.

Thanks
• By cebugdev
hi all,

i am trying to build an OpenGL 2D GUI system, (yeah yeah, i know i should not be re inventing the wheel, but this is for educational and some other purpose only),
i have built GUI system before using 2D systems such as that of HTML/JS canvas, but in 2D system, i can directly match a mouse coordinates to the actual graphic coordinates with additional computation for screen size/ratio/scale ofcourse.
now i want to port it to OpenGL, i know that to render a 2D object in OpenGL we specify coordiantes in Clip space or use the orthographic projection, now heres what i need help about.
1. what is the right way of rendering the GUI? is it thru drawing in clip space or switching to ortho projection?
2. from screen coordinates (top left is 0,0 nd bottom right is width height), how can i map the mouse coordinates to OpenGL 2D so that mouse events such as button click works? In consideration ofcourse to the current screen/size dimension.
3. when let say if the screen size/dimension is different, how to handle this? in my previous javascript 2D engine using canvas, i just have my working coordinates and then just perform the bitblk or copying my working canvas to screen canvas and scale the mouse coordinates from there, in OpenGL how to work on a multiple screen sizes (more like an OpenGL ES question).
lastly, if you guys know any books, resources, links or tutorials that handle or discuss this, i found one with marekknows opengl game engine website but its not free,
Just let me know. Did not have any luck finding resource in google for writing our own OpenGL GUI framework.
IF there are no any available online, just let me know, what things do i need to look into for OpenGL and i will study them one by one to make it work.
thank you, and looking forward to positive replies.

• I have a few beginner questions about tesselation that I really have no clue.
The opengl wiki doesn't seem to talk anything about the details.

What is the relationship between TCS layout out and TES layout in?
How does the tesselator know how control points are organized?
e.g. If TES input requests triangles, but TCS can output N vertices.
What happens in this case?
http://www.informit.com/articles/article.aspx?p=2120983
the isoline example TCS out=4, but TES in=isoline.
And gl_TessCoord is only a single one.
So which ones are the control points?
How are tesselator building primitives?
• By Orella
I've been developing a 2D Engine using SFML + ImGui.
Here you can see an image
The editor is rendered using ImGui and the scene window is a sf::RenderTexture where I draw the GameObjects and then is converted to ImGui::Image to render it in the editor.
Now I need to create a 3D Engine during this year in my Bachelor Degree but using SDL2 + ImGui and I want to recreate what I did with the 2D Engine.
I've managed to render the editor like I did in the 2D Engine using this example that comes with ImGui.
3D Editor preview
But I don't know how to create an equivalent of sf::RenderTexture in SDL2, so I can draw the 3D scene there and convert it to ImGui::Image to show it in the editor.
If you can provide code will be better. And if you want me to provide any specific code tell me.
Thanks!

• Hi
I'm new to learning OpenGL and still learning C. I'm using SDL2, glew, OpenGL 3.3, linmath and stb_image.
I started following through learnopengl.com and got through it until I had to load models. The problem is, it uses Assimp for loading models. Assimp is C++ and uses things I don't want in my program (boost for example) and C support doesn't seem that good.
Things like glVertexAttribPointer and shaders are still confusing to me, but I have to start somewhere right?
I can't seem to find any good loading/rendering tutorials or source code that is simple to use and easy to understand.
I have tried this for over a week by myself, searching for solutions but so far no luck. With tinyobjloader-c and project that uses it, FantasyGolfSimulator, I was able to actually load the model with plain color (always the same color no matter what I do) on screen and move it around, but cannot figure out how to use textures or use its multiple textures with it.
I don't ask much: I just want to load models with textures in them, maybe have lights affect them (directional spotlight etc). Also, some models have multiple parts and multiple textures in them, how can I handle those?
Are there solutions anywhere?
Thank you for your time. Sorry if this is a bit confusing, English isn't my native language

• 17
• 13
• 28
• 10
• 13