[置顶] 《基于MFC的OpenGL编程》Part 0 基于MFC的OpenGL基本框架

《基于MFC的OpenGL编程》Part 0 基于MFC的OpenGL基本框架                                                                                                         


OpenGL环境配置


1.各种库的配置

(1)glew

下载:https://sourceforge.net/projects/glew/files/glew/1.7.0/glew-1.7.0.zip/download

将include文件夹下的.h文件拷贝到C:\Program Files\Microsoft Visual Studio 9.0\VC\include\GL目录中(没有GL目录就自己创建一个,这里的具体路径视电脑上VS2008安装的位置而定)
将lib文件夹下的.lib文件拷贝到C:\Program Files\Microsoft Visual Studio 9.0\VC\lib目录中
将bin文件夹下的.dll文件拷贝到C:\Windows\System32目录(64位目录C:\Windows\SysWOW64

(2)glut

下载OpenGL的glut类库:http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip

将.h文件拷贝到C:\Program Files\Microsoft Visual Studio 9.0\VC\include\GL目录中(没有GL目录就自己创建一个,这里的具体路径视电脑上VS2008安装的位置而定)
将.lib文件拷贝到C:\Program Files\Microsoft Visual Studio 9.0\VC\lib目录中
将.dll文件拷贝到C:\Windows\System32目录(64位目录C:\Windows\SysWOW64)中

环境变量配置好后不必每个新建项目都按照下面这样配置。下面步骤仅限没有进行上述配置的用户。


2.配置项目环境

在需要用到openGL的每个项目中都需要执行以下步骤:

项目——项目属性——配置属性——链接器——输入——附加依赖项,添加

    opengl32.lib glu32.lib glut.lib glaux.lib glew32.lib




3.OpenGL的MFC基本框架程序


环境配置:VC++6.0、win7 64位

OpenGL库配置: 首先下载需要的GLUT头文件,DLLLib文件,下载链接glutdlls37beta.zip (149 kilobytes),解压缩后把gltu.h放到"VC98/Include/GL"下,把glut.libglut32.lib放到"VC9/Lib" 下glut32.dllglut.dll放到你创建的应用程序的运行目录下


1、工程—>设置—>链接—>输入:对象/库模块中添加(暂时用不上glew32.lib):opengl32.lib glu32.lib glut.lib glaux.lib

2、源文件栏中的stdafx.h中加入:

#include <windows.h>
#include <GL/glut.h>
3、CMy2OpenGLView.h中添加:
#include "GL/gl.h"
#include "GL/glaux.h"
#include "GL/glu.h"
#include "GL/glut.h"
4、贴出整个 CMy2OpenGLView.h的代码:

// 2OpenGLView.h : interface of the CMy2OpenGLView class
//
/////////////////////////////////////////////////////////////////////////////

#if !defined(AFX_2OPENGLVIEW_H__093AEC68_AF1D_4180_B7AE_BE30F4E3A904__INCLUDED_)
#define AFX_2OPENGLVIEW_H__093AEC68_AF1D_4180_B7AE_BE30F4E3A904__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "GL/gl.h"
#include "GL/glaux.h"
#include "GL/glu.h"
#include "GL/glut.h"

class CMy2OpenGLView : public CView
{
protected: // create from serialization only
	CMy2OpenGLView();
	DECLARE_DYNCREATE(CMy2OpenGLView)

// Attributes
public:
	CMy2OpenGLDoc* GetDocument();

// Operations
public:

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CMy2OpenGLView)
	public:
	virtual void OnDraw(CDC* pDC);  // overridden to draw this view
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
	protected:
	virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
	virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
	virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
	//}}AFX_VIRTUAL

// Implementation
public:
	virtual ~CMy2OpenGLView();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

protected:

// Generated message map functions
protected:
		void RenderScene();
	   BOOL SetWindowPixelFormat(HDC hDC);//设置像素格式
	   BOOL CreateViewGLContext(HDC hDC);//创建绘制环境(RC)并使之成为当前绘制环境
	   BOOL InitGL(GLvoid);//初始化openGL
	   int DrawGLScene(GLvoid);//绘图代码区
	   int m_GLPixelIndex;
	   HGLRC m_hGLContext;//绘制环境
	//{{AFX_MSG(CMy2OpenGLView)
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	afx_msg void OnDestroy();
	afx_msg void OnSize(UINT nType, int cx, int cy);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

#ifndef _DEBUG  // debug version in 2OpenGLView.cpp
inline CMy2OpenGLDoc* CMy2OpenGLView::GetDocument()
   { return (CMy2OpenGLDoc*)m_pDocument; }
#endif

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_2OPENGLVIEW_H__093AEC68_AF1D_4180_B7AE_BE30F4E3A904__INCLUDED_)
5、 贴出整个 CMy2OpenGLView.cpp的代码:
// 2OpenGLView.cpp : implementation of the CMy2OpenGLView class
//

#include "stdafx.h"
#include "2OpenGL.h"

#include "2OpenGLDoc.h"
#include "2OpenGLView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView

IMPLEMENT_DYNCREATE(CMy2OpenGLView, CView)

BEGIN_MESSAGE_MAP(CMy2OpenGLView, CView)
	//{{AFX_MSG_MAP(CMy2OpenGLView)
	ON_WM_CREATE()
	ON_WM_DESTROY()
	ON_WM_SIZE()
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView construction/destruction

CMy2OpenGLView::CMy2OpenGLView()
{
	// TODO: add construction code here
    this->m_GLPixelIndex = 0;
    this->m_hGLContext = NULL;
}

CMy2OpenGLView::~CMy2OpenGLView()
{
}

BOOL CMy2OpenGLView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
    cs.style |= (WS_CLIPCHILDREN | WS_CLIPSIBLINGS);//openGL必需的
	return CView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView drawing

void CMy2OpenGLView::OnDraw(CDC* pDC)
{
	CMy2OpenGLDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	   // Clear out the color & depth buffers
    ::glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    RenderScene();
    // Tell OpenGL to flush its pipeline
    ::glFinish();
    // Now Swap the buffers
    ::SwapBuffers( pDC->GetSafeHdc() );
}

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView printing

BOOL CMy2OpenGLView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CMy2OpenGLView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CMy2OpenGLView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView diagnostics

#ifdef _DEBUG
void CMy2OpenGLView::AssertValid() const
{
	CView::AssertValid();
}

void CMy2OpenGLView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CMy2OpenGLDoc* CMy2OpenGLView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMy2OpenGLDoc)));
	return (CMy2OpenGLDoc*)m_pDocument;
}
BOOL CMy2OpenGLView::SetWindowPixelFormat(HDC hDC)
{
//定义窗口的像素格式
    PIXELFORMATDESCRIPTOR pixelDesc=
    {
        sizeof(PIXELFORMATDESCRIPTOR),
			1,
			PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|
			PFD_DOUBLEBUFFER|PFD_SUPPORT_GDI,
			PFD_TYPE_RGBA,
			24,
			0,0,0,0,0,0,
			0,
			0,
			0,
			0,0,0,0,
			32,
			0,
			0,
			PFD_MAIN_PLANE,
			0,
			0,0,0
    };
	
    this->m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);//选择最相近的像素格式
    if(this->m_GLPixelIndex==0)
    {//选择失败
        this->m_GLPixelIndex = 1;//默认的像素格式
        if(DescribePixelFormat(hDC,this->m_GLPixelIndex,sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)
        {//用默认的像素格式进行设置
            return FALSE;
        }
    }
	
    if(SetPixelFormat(hDC,this->m_GLPixelIndex,&pixelDesc)==FALSE)
    {
        return FALSE;
    }
    return TRUE;
}

BOOL CMy2OpenGLView::InitGL(GLvoid)                                        // All Setup For OpenGL Goes Here
{
    glShadeModel(GL_SMOOTH);                            // Enable Smooth Shading
	glClearColor(0.0,0.0,0.0,0.0);// Black Background
    glClearDepth(1.0f);                                    // Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);                            // Enables Depth Testing
    glDepthFunc(GL_LEQUAL);                                // The Type Of Depth Testing To Do
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);    // Really Nice Perspective Calculations
    return TRUE;                                        // Initialization Went OK
}
BOOL CMy2OpenGLView::CreateViewGLContext(HDC hDC)
{
    this->m_hGLContext = wglCreateContext(hDC);//创建RC
    if(this->m_hGLContext==NULL)
    {//创建失败
        return FALSE;
    }
	
    if(wglMakeCurrent(hDC,this->m_hGLContext)==FALSE)
    {//选为当前RC失败
        return FALSE;
    }
    return TRUE;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMy2OpenGLView message handlers

int CMy2OpenGLView::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// TODO: Add your specialized creation code here
	HWND hWnd = this->GetSafeHwnd();    
	HDC hDC = ::GetDC(hWnd);

	if(this->SetWindowPixelFormat(hDC)==FALSE)
	{//设置像素格式
		return 0;
	}
	if(this->CreateViewGLContext(hDC)==FALSE)
	{//创建RC并选为所用
		return 0;
	}
	if(!this->InitGL())
	{//初始化openGL
		return 0;
}
    return 0;
}

void CMy2OpenGLView::OnDestroy() 
{
	CView::OnDestroy();
	
	// TODO: Add your message handler code here
     if(wglGetCurrentContext()!=NULL)
    {
        wglMakeCurrent(NULL,NULL);
    }
    if(this->m_hGLContext!=NULL)
    {
        wglDeleteContext(this->m_hGLContext);
        this->m_hGLContext = NULL;
    }
}

void CMy2OpenGLView::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 will 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
//	gluOrtho2D(-10.0f,10.0f,-10.0f,10.0f);
    ::gluPerspective(45.0f, aspect_ratio, 0.01f, 200.0f);
    
    // switch back to the modelview matrix and clear it
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadIdentity();                              // Reset The Modelview Matrix
}


void CMy2OpenGLView::RenderScene()
{
	// Here's Where We Do All The Drawing
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    // Clear Screen And Depth Buffer
    glLoadIdentity();                                    // Reset The Current Modelview Matrix
    glTranslatef(-1.5f,0.0f,-6.0f);//物体左移1.5,向内移6,相当于移动镜头一样,让物体进入镜头中
    glBegin(GL_TRIANGLES);                            // 绘制三角形
	glColor3f(255.0f,0.0f,0.0f);
	glVertex3f( 0.0f, 1.0f, 0.0f);                    // 上顶点
	glColor3f(0.0f,255.0f,0.0f);
	glVertex3f(-1.0f,-1.0f, 0.0f);                    // 左下
	glColor3f(0.0f,0.0f,255.0f);
	glVertex3f( 1.0f,-1.0f, 0.0f);                    // 右下
    glEnd();                                // 三角形绘制结束
	glTranslatef(3.0f,0.0f,0.0f);
	glBegin(GL_QUADS);                            //  绘制正方形
	glColor3f(255.0f,0.0f,0.0f);
	glVertex3f(-1.0f, 1.0f, 0.0f);                    // 左上
	glColor3f(0.0f,255.0f,0.0f);
	glVertex3f( 1.0f, 1.0f, 0.0f);                    // 右上
	glColor3f(0.0f,0.0f,255.0f);
	glVertex3f( 1.0f,-1.0f, 0.0f);                    // 左下
	glColor3f(255.255f,255.0f,255.0f);
	glVertex3f(-1.0f,-1.0f, 0.0f);                    // 右下
    glEnd();                                // 正方形绘制结束
    glFlush();

}

运行结果:

[置顶] 《基于MFC的OpenGL编程》Part 0 基于MFC的OpenGL基本框架_第1张图片




你可能感兴趣的:(编程,mfc,3D,图形,OpenGL)