Visual C++中OpenGL编程入门
opengl作图非常方便,故日益流行,但对许多人来说,是在微机上进行的,首先碰到的问题是,如何适应微机环境。这往往是最关键的一步,虽然也是最初级的。一般的,我不建议使用glut 包.那样难以充分发挥 windows 的界面上的功能.
下面介绍如何在 vc++ 上进行 opengl 编程。 opengl 绘图的一般过程可以看作这样的,先用 opengl 语句在 opengl 的绘图环境 rendercontext (rc)中画好图, 然后再通过一个 swap buffer 的过程把图传给操作系统的绘图环境 devicecontext (dc)中,实实在在地画出到屏幕上.
下面以画一条 bezier 曲线为例,详细介绍vc++ 上 opengl编程的方法。文中给出了详细注释,以便给初学者明确的指引。一步一步地按所述去做,你将顺利地画出第一个 opengl 平台上的图形来。
一、产生程序框架 test.dsw
new project | mfc application wizard (exe) | "test" | ok
*注* : 加“”者指要手工敲入的字串
二、导入 bezier 曲线类的文件
用下面方法产生 beziercurve.h beziercurve.cpp 两个文件:
workspace | classview | test classes| <右击弹出> new class | generic class(不用mfc类) | "cbeziercurve" | ok
三、编辑好 bezier 曲线类的定义与实现
写好下面两个文件:
beziercurve.h beziercurve.cpp
四、设置编译环境:
1. 在 beziercurve.h 和 testview.h 内各加上:
#include <gl/gl.h>
#include <gl/glu.h>
#include <gl/glaux.h>
2. 在集成环境中
project | settings | link | object/library module | "opengl32.lib glu32.lib glaux.lib" | ok
五、设置 opengl 工作环境:(下面各个操作,均针对 testview.cpp )
1. 处理 precreatewindow(): 设置 opengl 绘图窗口的风格
(来源 www.iocblog.net)
cs.style |= ws_clipsiblings | ws_clipchildren | cs_owndc;
2. 处理 oncreate():创建 opengl 的绘图设备。
opengl 绘图的机制是: 先用 opengl 的绘图上下文 rendering context (简称为 rc )把图画好,再把所绘结果通过 swapbuffer() 函数传给 window 的 绘图上下文 device context (简记为 dc).要注意的是,程序运行过程中,可以有多个 dc,但只能有一个 rc。因此当一个 dc 画完图后,要立即释放 rc,以便其它的 dc 也使用。在后面的代码中,将有详细注释。
int ctestview::oncreate(lpcreatestruct lpcreatestruct)
{
if (cview::oncreate(lpcreatestruct) == -1)
return -1;
myinitopengl();
return 0;
}
void ctestview::myinitopengl()
{
m_pdc = new cclientdc(this); //创建 dc
assert(m_pdc != null);
if (!mysetuppixelformat()) //设定绘图的位图格式,函数下面列出
return;
m_hrc = wglcreatecontext(m_pdc->m_hdc);//创建 rc
wglmakecurrent(m_pdc->m_hdc, m_hrc); //rc 与当前 dc 相关联
} //cclient * m_pdc; hglrc m_hrc; 是 ctestview 的成员变量
bool ctestview::mysetuppixelformat()
{//我们暂时不管格式的具体内容是什么,以后熟悉了再改变格式
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, // rgba type
24, // 24-bit color depth
0, 0, 0, 0, 0, 0, // color bits ignored
0, // no alpha buffer
0, // shift bit ignored
0, // no accumulation buffer
0, 0, 0, 0, // accum bits ignored
32, // 32-bit z-buffer
0, // no stencil buffer
0, // no auxiliary buffer
pfd_main_plane, // main layer
0, // reserved
0, 0, 0 // layer masks ignored
};
int pixelformat;
if ( (pixelformat = choosepixelformat(m_pdc->m_hdc, &pfd)) == 0 )
{
messagebox("choosepixelformat failed");
return false;
}
if (setpixelformat(m_pdc->m_hdc, pixelformat, &pfd) == false)
{
messagebox("setpixelformat failed");
return false;
}
return true;
}
Tag: OpenGL
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。