• Advertisement
Sign in to follow this  

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

This topic is 4005 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 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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by riruilo
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

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 riruilo
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.

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 riruilo
Well, 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 riruilo
Thank you very much for your time.

You're welcome [smile]

Share this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
Quote:
Original post by riruilo
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);
}

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 Sphet
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(); }.

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 this post


Link to post
Share on other sites
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)

I followed this toturial about MFC threads:
http://www.codeproject.com/threads/memberthread.asp

And I added this code to my thread:

UINT CColladaLoaderView::StartThread (LPVOID param) {
THREADSTRUCT* ts = (THREADSTRUCT*)param;
while (true)
{
ts->_this->Render(ts->_this->m_pDC);
}
return 1;
}



And I add this code after opengl initialization, on OnCreate:
THREADSTRUCT *_param = new THREADSTRUCT;
_param->m_pDC=m_pDC;
_param->_this=this;
AfxBeginThread (StartThread, _param);

But my screen is black.


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



Thank you for your help.

Share this post


Link to post
Share on other sites
Quote:
Original post by iNsAn1tY
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.


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]

Share this post


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

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      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
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement