1. MFC-based OpenGL program

Source: Internet
Author: User

First, the libraries used are glut and glaux, download both, add find path, and link

One, single text fileEngineering OPENGLMFC 1. Create a single text file 2. Add path, linkmethod as shown in the previous chapter, the link library is opengl32.lib; glu32.lib; glut32.lib; glaux.lib 3. header fileAdd the following statement to the stdafx.h:
OpenGL Required header file # include <gl/gl.h> #include <gl/glu.h> #include <gl/glut.h> #include <gl/glaux.h >
4. Set the window styleSet the window style to Ws_clipchildrenAnd ws_clipsiblingsto avoid OpenGL drawing to other windows. These should be placed in the PreCreateWindow () .
BOOL Copenglmfcview::P Recreatewindow (createstruct& cs) {    //todo:modify the Window class or styles here by Modifyi Ng    //The  CREATESTRUCT cs    cs.style |= ws_clipsiblings | Ws_clipchildren;    Return CView::P Recreatewindow (CS);}

5. Variables, function declarationsInitialize GL, considering the use of device context, drawing context, first declare the required variables and functions in OpenGLMFCView.h
HGLRC M_HRC;    RC drawing Context cdc* M_PDC;        DC Device context bool Initializeopengl ();    Initialize Openglbool Setuppixelformat ();    Create a pixel format for a DC
6. Create a message response functionInitialization needs to trigger resource release at wm_create when Wm_destroy trigger window size changesWm_size trigger, need to adjust the drawingDue to the use of OpenGL to draw the background, it does not need the window itself in the drawing background, need to rewriteWm_erasebackground event triggered by a messageTherefore, open ClassWizard, add the above four message response functions in the Openglmfcview class

OnCreate OnDestroy OnSize Onerasebkground

7. Initialize

OpenGL is initialized by establishing the pixel format and drawing context. A Device context (DC) is created in Initializeopengl (), a pixel format is selected for the DC, the drawing context (RC) associated with the DC is created, and the RC is selected. This function calls Setuppixelformat () To create a pixel format.

int copenglmfcview::oncreate (lpcreatestruct lpcreatestruct) {if (cview::oncreate (lpcreatestruct) = =-1) return-    1;    Todo:add your specialized creation code here Initializeopengl (); return 0;}    BOOL Copenglmfcview::initializeopengl () {//client area get DC M_PDC = new CClientDC (this);        Failure to Get DC if (M_PDC = = NULL) {MessageBox (L "Error obtaining DC");    return FALSE; }//Create a pixel format for the DC if (!    Setuppixelformat ()) {return FALSE;    }//Create RC M_HRC =:: Wglcreatecontext (M_PDC-&GT;GETSAFEHDC ());        Failure to Create Rendering Context if (M_HRC = = 0) {MessageBox (L "Error Creating RC");    return FALSE;    }//Set the rendering environment for the current thread of OpenGL.    All OpenGL calls for this thread later are drawn on the device identified by this HDC.        if (:: Wglmakecurrent (M_pdc->getsafehdc (), M_HRC) = = FALSE) {MessageBox (L "Error making RC current");    return FALSE;    }//Background color:: Glclearcolor (0.0f, 0.0f, 0.0f, 0.0f);  Depth Cache 1 Max, so that anything can be displayed: Glcleardepth (1.0f);  If the depth value changes after comparison, the operation of the depth buffer is updated: glenable (gl_depth_test); return TRUE;} To create a pixel format/////////////////////////////////////////////////////////////////////////////bool CopenGLMFCView::        Setuppixelformat () {static Pixelformatdescriptor PFD = {sizeof (pixelformatdescriptor),//size of this PFD            1,//version number Pfd_draw_to_window |            Support Window Pfd_support_opengl | Support OpenGL Pfd_doublebuffer,//Double buffered Pfd_type_rgba,//RGB A type,//24-bit color depth 0, 0, 0, 0, 0, 0,//color bits I gnored 0,//No alpha buffer 0,//shift bit Ignor Ed 0,//No accumulation buffer 0, 0, 0, 0,//accum bits I gnored 16,//16-bit Z-buffer 0,//no stencil buffer 0,//no aux        Iliary buffer Pfd_main_plane,//MAIN layer 0,//reserved    0, 0, 0//layer masks ignored};    int M_npixelformat =:: Choosepixelformat (M_pdc->getsafehdc (), &AMP;PFD);    if (M_npixelformat = = 0) {return FALSE;    } if (:: Setpixelformat (M_pdc->getsafehdc (), M_npixelformat, &pfd) = = False) {return false; } return TRUE;

8. Draw the scenewhen you draw a scene, you typically include the following steps: 1) empty the cache. 2) Draw the scene. 3) flush out the rendering line. 4) If double buffering is set, swap the front and back buffers.
void Copenglmfcview::ondraw (cdc*/*pdc*/) {    copenglmfcdoc* PDoc = GetDocument ();    Assert_valid (PDOC);    if (!pdoc)        return;    Todo:add draw code for native data here    //clear color, Depth cache    :: Glclear (Gl_color_buffer_bit | Gl_depth_buffer_bit);    Can add render function    //flush off render line    :: Glfinish ();    Buffer before and after swap    :: Swapbuffers (M_PDC->GETSAFEHDC ());}

9. Background Drawing modification

Try changing the size of the window, you will see a very serious flicker, and after closing the program will report a memory leak, so we will solve these two problems.

The reason for the flicker is that Windows draws the background first, and then OpenGL draws, because we've made OpenGL responsible for emptying the background color, so we don't need windows to clear the background.

BOOL copenglmfcview::onerasebkgnd (cdc* pDC) {    //todo:add your message handler code here and/or call default    retur n True;//cview::onerasebkgnd (PDC);}

the reason for the memory leaks is that we The new operator is used in Initializeopengl () to allocate memory for the CClientDC object, so you need to display the delete drop.

void Copenglmfcview::ondestroy () {    Cview::ondestroy ();     Todo:add your message Handler code here    if (:: Wglmakecurrent (0, 0) = = FALSE)    {        MessageBox (L "Could not MA Ke RC non-current ");    }     Delete the rendering context    if (:: Wgldeletecontext (M_HRC) = = FALSE)    {        MessageBox (L "Could not delete RC ");    }    Delete the DC    if (M_PDC)    {        delete m_pdc;    }    Set it to null    M_PDC = null;}
10. Size AdjustmentIn OnSize (), it is generally used to set viewports and cones, as these are related to window size. Basic operations include setting the viewport, selecting the projection matrix, and setting the Model view matrix.
void Copenglmfcview::onsize (UINT nType, int cx, int cy) {    cview::onsize (NType, CX, CY);    Todo:add your message Handler code here    gldouble aspect_ratio;//Width/height ratio    if (0 >= cx | | 0 >= CY)    {        return;    }    Select the full client area    :: Glviewport (0, 0, CX, CY);    Compute the aspect ratio    //This would keep all dimension scales equal    Aspect_ratio = (gldouble) CX/(gldouble ) Cy;    Select the projection matrix and clear it    :: Glmatrixmode (Gl_projection);    :: Glloadidentity ();    Select the viewing volume    :: Gluperspective (45.0f, Aspect_ratio,. 01f, 200.0f);    Switch back to the Modelview matrix and clear it    :: Glmatrixmode (Gl_modelview);:    : Glloadidentity ();}

Get the result of the operation above:

Second, based on the dialog box

Project: Openglmfcdialog1-3 step 4, variable function declaration in the OpenGLMFCDialogDlg.h file, declaration as above. The rest of the steps above, the difference is that you need to write inside the OnDraw into the OnPaint function, where Isiconic () is the judgment is minimized, you can put in the else inside. Get results

1. MFC-based OpenGL program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.