OpenGL usage in MFC (2) -- derived OpenGL class, mfcopengl

Source: Internet
Author: User

OpenGL usage in MFC (2) -- derived OpenGL class, mfcopengl

Sometimes OpenGL needs to be configured every time, which is a little troublesome. You can directly derive an OpenGL Class Based on CWND and use it directly when necessary. The following is an example of this class, which deletes some specific items of my project. If any error occurs, contact me ~~~

H file:

# If! Defined (success _) # define success _ # if _ MSC_VER> 1000 # pragma once # endif // _ MSC_VER> 1000 // OpenGL. h: header file # include <gl/glu. h> # inclede <gl/gl. h> ////////////////////////////////////// //////////////////////////////////////// /COpenGL windowclass COpenGL: public CWnd {// Constructionpublic: COpenGL (); // Overrides // ClassWizard generated virtual function overrides // {AFX_VIRTUAL (COpenGL) //} AFX_VIRTUAL // Implementationpublic: virtual void RenderGLScene (); void Create (CRect rect, CWnd * parent); virtual ~ COpenGL (); // Generated message map functionsprotected: CRect m_rect; CWnd * m_parent; DEVMODE m_DMsaved; public: // add or delete BOOL m_bInit as needed; HDC m_hDC; HGLRC m_hRC; // read data int DrawXXX (); int InitGL (); void KillGLWindow (); // {AFX_MSG (COpenGL) afx_msg int OnCreate (maid ); afx_msg void OnPaint (); afx_msg void OnSize (UINT nType, int cx, int cy); //} AFX_MSGDECLARE_MESSAGE_MAP ()}; ////////////////// //////////////////////////////////////// /// {AFX_INSERT_LOCATION} // Microsoft Visual C ++ will insert additional declarations immediately before the previous line. # endif //! Defined (afx_opengl_h000038b5d1c8_2dff_4a7d_9a99_3ac401c19d7200000000ded _)

CPP file:

# Include "stdafx. h "# include" OpenGL. h "# include" math. h "# ifdef _ DEBUG # define new DEBUG_NEW # undef THIS_FILEstatic char THIS_FILE [] = _ FILE __; # endif ////////////////////////////////////// /// // COpenGL:: COpenGL (): m_bInit (FALSE), m_hDC (NULL), m_hRC (NULL), m_parent (NULL) {} COpenGL ::~ COpenGL () {KillGLWindow (); // Shutdown} BEGIN_MESSAGE_MAP (COpenGL, CWnd) // {AFX_MSG_MAP (COpenGL) ON_WM_CREATE () ON_WM_PAINT () ON_WM_SIZE () //} AFX_MSG_MAPON_WM_ERASEBKGND () END_MESSAGE_MAP () //////////////////////////////////////// /// // COpenGL message handlersvoid COpenGL:: Create (CRect rect, CWnd * parent) {if (m_bInit) return; ASSERT (rect); ASSERT (parent); m_rect = rect; m_par Ent = parent; CString className = AfxRegisterWndClass (CS_HREDRAW | CS_VREDRAW | CS_OWNDC, NULL, (HBRUSH) GetStockObject (BLACK_BRUSH), NULL); CreateEx (callback, className, _ T ("OpenGL"), WS_CHILD | WS_VISIBLE | visible | WS_CLIPCHILDREN, rect, parent, 0);} int COpenGL: OnCreate (maid) {if (CWnd :: onCreate (lpCreateStruct) =-1) return-1; // TODO: Add your specialized creatio N code hereEnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, & m_DMsaved); GLuint PixelFormat; // Holds The Results After Searching For A Matchstatic PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be {sizeof (PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor1, // Version NumberPFD_DRAW_TO_WINDOW | // Format Must Support WindowPFD_SUPPORT_OPENGL | // Format Must Sup Port OpenGLPFD_DOUBLEBUFFER, // Must Support Double BufferingPFD_TYPE_RGBA, // Request An RGBA success, // Select Our Color Depth0, 0, 0, 0, 0, 0, // Color Bits noriged0, // No Alpha Buffer0, // Shift Bit Ignored0, // No Accumulation Buffer0, 0, 0, 0, // Accumulation Bits Ignored16, // 16Bit Z-Buffer (Depth Buffer) 0, // No stencel Buffer0, // No Auxiliary BufferPFD_MAIN_PLANE, // Main Drawing Layer0, // Reserved0, 0, 0 // Layer Masks Ignored}; if (! (M_hDC =: GetDC (m_hWnd) {// Did We Get A Device Context? KillGLWindow (); // Reset The DisplayTRACE ("Can't Create a gl Device Context."); return FALSE;} if (! (PixelFormat = ChoosePixelFormat (m_hDC, & pfd) {// Did Windows Find A Matching Pixel Format? KillGLWindow (); // Reset The DisplayTRACE ("Can't Find A Suitable PixelFormat."); return FALSE;} if (! SetPixelFormat (m_hDC, PixelFormat, & pfd) {// Are We Able To Set The Pixel Format? KillGLWindow (); // Reset The DisplayTRACE ("Can't Set The PixelFormat."); return FALSE;} if (! (M_hRC = wglCreateContext (m_hDC) {// Are We Able To Get A Rendering Context? KillGLWindow (); // Reset The DisplayTRACE ("Can't Create a gl Rendering Context."); return FALSE;} if (! WglMakeCurrent (m_hDC, m_hRC) {// Try To Activate The Rendering Context KillGLWindow (); // Reset The DisplayTRACE ("Can't Activate The GL Rendering Context. "); return FALSE;} if (! InitGL () {// Initialize Our Newly Created GL Window KillGLWindow (); // Reset The DisplayTRACE ("Initialization Failed. "); return FALSE;} m_bInit = TRUE; return 0;} void COpenGL: KillGLWindow () {if (m_hRC) {// Do We Have A Rendering Context? If (! WglMakeCurrent (NULL, NULL) {// Are We Able To Release The DC And RC Contexts? TRACE ("Release Of DC And RC Failed.");} if (! WglDeleteContext (m_hRC) {// Are We Able To Delete The RC? TRACE ("Release Rendering Context Failed.");} m_hRC = NULL; // Set RC To NULL} if (m_hDC &&!: ReleaseDC (m_hWnd, m_hDC) {// Are We Able To Release The DCTRACE ("Release Device Context Failed. "); m_hDC = NULL; // Set DC To NULL} if (m_hWnd &&!: DestroyWindow (m_hWnd) {// Are We Able To Destroy The Window? TRACE ("cocould Not Release m_hWnd. "); m_hWnd = NULL; // Set m_hWnd To NULL} int COpenGL: InitGL () {glShadeModel (GL_SMOOTH); // Enable Smooth ShadingglClearColor (0.0f, 0.0f, 0.0f, 0.0f); // Black BackgroundglClearDepth (1.0f); // Depth Buffer setupglable (GL_DEPTH_TEST); // Enables Depth TestingglDepthFunc (GL_LEQUAL ); // The Type Of Depth Testing To DoglHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // Really Nice Perspective CalculationsglEnable (GL_TEXTURE_2D); // Enable Texture Mappingreturn TRUE; // Initialization Went OK} void COpenGL: RenderGLScene () {if (! M_bInit) return; glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw the model DrawXXX (); SwapBuffers (m_hDC);} void COpenGL: OnPaint () {// CPaintDC dc (this); // device context for painting // TODO: Add your message handler code here: ValidateRect (m_hWnd, NULL); RenderGLScene (); // Do not call CWnd: OnPaint () for painting messages} void COpenGL: OnSize (UINT nType, int cx, int cy) {CWnd: OnSize (nType, cx, cy); // TODO: Add your message handler code hereif (cy = 0) {// Prevent A Divide By Zero By cy = 1; // Making Height Equal One} glViewport (, cx, cy); // Reset The Current ViewportglMatrixMode (GL_PROJECTION); // set The projection matrix glLoadIdentity (); // initialize gluPerspective (45.0f, (GLfloat) cx/(GLfloat) cy, 0.1f, 100366f); // set the viewpoint glMatrixMode (GL_MODELVIEW); // set the model matrix glLoadIdentity (); // initialization} int COpenGL: DrawXXX () {// The specific painting return 1 ;}




Use opengl for plotting in MFC

The MFC program is too large and there are too many files. You can check this address and learn Opengl. I started from here: nehe.gamedev.net.

The program part of an MFC is as follows:
# Include "stdafx. h"
# Include "NeheMFC. h"
# Include "NeheWindow. h"
# Include "Main. h"

# Ifdef _ DEBUG
# Undef THIS_FILE
Static char THIS_FILE [] =__ FILE __;
# Define new DEBUG_NEW
# Endif

Static float angle = 0, rot1, rot2;

CMain: CMain ()
{
// Start Of User Initialization
}

CMain ::~ CMain ()
{

}

BOOL CMain: KeyPressed (int nCode)
{
If (nCode> = 0 & nCode <= 255)
{
Return theApp. keyDown [nCode];
}
Return FALSE;
}

BOOL CMain: Initialize ()
{
Angle = 0.0f; // Set Starting Angle To Zero

GlClearColor (0.0f, 0.0f, 0.0f, 0.5f); // Black Background
GlClearDepth (1.0f); // Depth Buffer Setup
GlDepthFunc (GL_LEQUAL); // The Type Of Depth Testing (Less Or Equal)
Glable (GL_DEPTH_TEST); // Enable Depth Testing
GlShadeModel (GL_SMOOTH); // Select Smooth Shading
GlHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Set Perspective Calculations To Most Accurate

Return TRUE;
}

Void CMain: Deinitialize ()
{

}

Void CMain: Update (DWORD milliseconds)
{
If (KeyPressed (VK_ESCAPE) = TRUE) // Is ESC Being Pressed?
{
TheApp. TerminateApplication (); // Terminate The Program
}

If (KeyPressed (VK_F1) = TRUE) // Is F1 Bei ...... the remaining full text>

In the MFC architecture, how does opengl compile animation effects? It turns out that opengl has glutIdlefunc and cannot be used now.

Add OnTimer and OnCreate messages to the View class, add Invalidate (); To the OnTimer function, and add SetTimer (, NULL) to the OnCreate function );

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.