研究生计算机图形学课程室内场景OpenGL--实验报告

合集下载

opengl实验报告

opengl实验报告

opengl实验报告OpenGL实验报告引言:OpenGL(Open Graphics Library)是一种跨平台的图形编程接口,被广泛应用于计算机图形学、游戏开发和科学可视化等领域。

本实验报告将介绍我对OpenGL的实验研究和学习成果。

一、实验目的本次实验的主要目的是掌握OpenGL的基本概念和使用方法,了解图形渲染的原理和过程,以及学习如何在OpenGL中创建和操作图形对象。

二、实验环境本次实验使用的是OpenGL的最新版本,并在Windows操作系统下进行开发。

使用的开发工具是Visual Studio和OpenGL的开发库。

三、实验过程1. 熟悉OpenGL的基本概念在开始实验之前,我先学习了OpenGL的基本概念,包括OpenGL的坐标系统、图形渲染管线、着色器等。

了解这些概念对于后续的实验非常重要。

2. 创建窗口和上下文在OpenGL中,我们需要先创建一个窗口和一个OpenGL上下文,以便进行图形渲染。

通过调用相关的OpenGL函数,我成功创建了一个窗口,并初始化了OpenGL的上下文。

3. 绘制基本图形接下来,我开始尝试绘制一些基本的图形,比如点、线和三角形。

通过设置顶点坐标和颜色,我成功绘制出了这些基本图形,并在窗口中显示出来。

4. 添加纹理为了使图形更加逼真和丰富,我学习了如何在OpenGL中添加纹理。

通过加载图片并设置纹理坐标,我成功将纹理贴在了绘制的图形上,使其具有了更加真实的效果。

5. 光照和阴影效果为了增加图形的立体感和真实感,我学习了如何在OpenGL中添加光照和阴影效果。

通过设置光源的位置和属性,以及材质的属性,我成功实现了光照和阴影的效果,使图形看起来更加逼真。

6. 动画效果为了使图形具有动态效果,我学习了如何在OpenGL中实现简单的动画效果。

通过每帧更新顶点的位置和纹理坐标,我成功实现了图形的旋转和平移动画,使其具有了动态的效果。

四、实验结果和分析通过以上的实验过程,我成功掌握了OpenGL的基本概念和使用方法,并实现了一些基本的图形渲染效果。

计算机图形学实验报告

计算机图形学实验报告

计算机图形学实验报告
在计算机图形学课程中,实验是不可或缺的一部分。

通过实验,我们可以更好地理解课程中所学的知识,并且在实践中掌握这些
知识。

在本次实验中,我学习了如何使用OpenGL绘制三维图形,并了解了一些基本的图形变换和视图变换。

首先,我们需要通过OpenGL的基本命令来绘制基本图形,例
如线段、矩形、圆等。

这些基本的绘制命令需要首先设置OpenGL 的状态,例如绘制颜色、线段宽度等,才能正确地绘制出所需的
图形。

然后,在实验中我们学习了图形的变换。

变换是指通过一定的
规则将图形的形状、位置、大小等进行改变。

我们可以通过平移、旋转、缩放等变换来改变图形。

变换需要按照一定的顺序进行,
例如先进行旋转再进行平移等。

在OpenGL中,我们可以通过设
置变换矩阵来完成图形的变换。

变换矩阵包含了平移、旋转、缩
放等信息,通过矩阵乘法可以完成图形的复合变换。

最后,视图变换是指将三维场景中的图形投影到二维平面上,
成为我们所见到的图形。

在实验中,我们学习了透视投影和正交
投影两种方式。

透视投影是指将场景中的图形按照视点不同而产
生不同的远近缩放,使得图形呈现出三维感。

而正交投影则是简单地将场景中的图形按照平行投影的方式呈现在屏幕上。

在OpenGL中,我们可以通过设置视图矩阵和投影矩阵来完成视图变换。

通过本次实验,我对于计算机图形学有了更深入的了解,并掌握了一些基本的图形绘制和变换知识。

在今后的学习中,我将继续学习更高级的图形绘制技术,并应用于实际的项目中。

计算机形学实训课程学习总结利用OpenGL进行三维渲染与动设计

计算机形学实训课程学习总结利用OpenGL进行三维渲染与动设计

计算机形学实训课程学习总结利用OpenGL进行三维渲染与动设计计算机形学实训课程学习总结——利用OpenGL进行三维渲染与动设计在计算机形学实训课程中,我们学习了如何利用OpenGL进行三维渲染与动设计。

通过这门课程的学习,我对计算机图形学和OpenGL有了更深入的了解,并且掌握了一些基本的三维渲染和动画设计技术。

在本文中,我将总结我在这门课程中的学习和体会。

首先,在课程中我们学习了计算机图形学的基础知识。

我们了解了计算机图形学的基本概念、渲染管线的工作原理以及一些基本的数学知识。

这些基础知识为我们后续的学习和实践打下了坚实的基础。

接着,我们学习了OpenGL的基本用法。

OpenGL是一套跨平台、高性能的图形库,广泛应用于计算机图形学和游戏开发领域。

通过学习OpenGL,我们能够使用它提供的接口函数绘制基本的图形和渲染效果。

我们学习了OpenGL的初始化过程、绘制基本图形的方法以及纹理贴图等高级特性的使用方法。

通过编写代码实践,我们能够将所学的知识应用到实际的图形渲染中,达到自己预期的效果。

在实践环节中,我们进行了三维渲染和动画设计的项目实践。

我们学习了如何使用OpenGL绘制三维模型并进行渲染。

通过导入模型文件、设置材质和光照等参数,我们能够让模型呈现逼真的效果。

同时,我们也学习了如何添加动画效果,让模型在场景中运动起来。

通过控制模型的变换矩阵和设置关键帧,我们能够制作出流畅的动画效果。

除了基本的三维渲染和动画设计,我们还学习了一些高级的图形效果和技术。

例如,我们学习了阴影的渲染方法,包括平面阴影和体积阴影的实现。

我们还学习了粒子系统的设计和实现,通过控制粒子的参数和行为,可以制作出各种特效,如烟雾、火焰等。

在整个实践过程中,我不仅学到了很多有关计算机图形学和OpenGL的知识,还提高了编程能力和问题解决能力。

在实现特定效果的过程中,我们经常会遇到各种各样的问题,如渲染错误、性能问题等。

通过查阅资料和与同学讨论,我学会了如何解决这些问题,并且能够修复错误并改进我的代码。

计算机图形学实验报告

计算机图形学实验报告

计算机图形学实验报告计算机图形学实验 (一) – OpenGL 基础用OPENGL画直线\圆\曲线等二维图1.1 综述这次试验的目的主要是使大家初步熟悉OpenGL 这一图形系统的用法,编程平台是Visual C++,它对OpenGL 提供了完备的支持。

OpenGL 提供了一系列的辅助函数,用于简化Windows 操作系统的窗口操作,使我们能把注意力集中到图形编程上,这次试验的程序就采用这些辅助函数。

本次实验不涉及面向对象编程,不涉及MFC。

1.2 在 VC 中新建项目1.2.1 新建一个项目选择菜单File 中的New 选项,弹出一个分页的对话框,选中页Projects 中的Win32Console Application 项,然后填入你自己的Project name,如Test,回车即可。

VC 为你创建一个工作区(WorkSpace ),你的项目Test 就放在这个工作区里。

1.2.2 为项目添加文件为了使用OpenGL,我们需要在项目中加入三个相关的Lib 文件:glu32.lib、glaux.lib、opengl32.lib,这三个文件位于c:\programfiles\microsoft visualstudio\vc98\lib 目录中。

选中菜单Project->Add To Project->Files 项(或用鼠标右键),把这三个文件加入项目,在FileView 中会有显示。

这三个文件请务必加入,否则编译时会出错。

或者将这三个文件名添加到Project->Setting->Link->Object/library Modules 即可。

点击工具条中New Text File 按钮,新建一个文本文件,存盘为Test.c 作为你的源程序文件,再把它加入到项目中,然后就可以开始编程了。

1.3 一个 OpenGL 的例子及说明1.3.1 源程序请将下面的程序写入源文件Test.c,这个程序很简单,只是在屏幕上画两根线。

实验1,opengl的基本语法实验报告心得体会

实验1,opengl的基本语法实验报告心得体会

实验1,opengl的基本语法实验报告心得体会实验1,opengl的基本语法实验报告心得体会篇一:图形学实验报告openGL的基本语法《计算机图形学基础》实验1 OpenGL的基本语法一、实验目的及要求1. 了解OpenGL的主要功能2. 了解OpenGL的绘制流程3. 掌握OpenGL的基本语法4. 通过以上内容,掌握 OpenGL的编程框架,实现简单的图形绘制二、实验环境主要是软件开发环境:VC三、实验内容OpenGL绘制矩形的简单例子。

四、实验结果五、程序代码#includevoid Initial(void){}void Display(void){glClear(GL_COLOR_BUFFER_BIT); //用当前背景色填充窗口glColor3f(, , );//设置当前的绘图颜色为红色glRectf(, , , ); //绘制一个矩形glFlush();//处理所有的OpenGL程序}int main(int argc, char* argv[]){glutInit(&argc, argv); glutInitDisplayMo(转载于: 小龙文档网:实验1,opengl的基本语法实验报告心得体会)de(GLUT_SINGLE | GLUT_RGB); //初始化glClearColor(, , , ); //设置窗口背景颜色为白色glMatrixMode(GL_PROJECTION);//设置投影参数gluOrtho2D(,,,); 窗口的显示模式glutInitWindowSize(400,300); //设置窗口的尺寸glutInitWindowPosition(100,120); //设置窗口的位置}glutCreateWindow("矩形"); //创建一个名为矩形的窗口glutDisplayFunc(Display); //设置当前窗口的显示回调函数Initial(); //完成窗口初始化glutMainLoop(); //启动主GLUT事件处理循环return 0;六、心得体会。

研究生计算机图形学课程室内场景OpenGL--实验报告

研究生计算机图形学课程室内场景OpenGL--实验报告

《高级计算机图形学》实验报告姓名:学号:班级:【实验报告要求】实验名称:高级计算机图形学室内场景实验目的:掌握使用OpenGL生成真实感复杂对象的方法,进一步熟练掌握构造实体几何表示法、扫描表示法、八叉树法、BSP树法等建模方法。

实验要求:要求利用OpenGL生成一个真实感的复杂对象及其周围场景,并显示观测点变化时的几何变换,要具备在一个纹理复杂的场景中漫游功能。

要求使用到光线跟踪算法、纹理映射技术以及实时绘制技术。

一、实验效果图图1:正面效果图图2:背面效果图图4:背面效果图图4:室内场景细节效果图图5:场景角度转换效果图二、源文件数据代码:共6个文件,其实现代码如下:1、DlgAbout.cpp#include "StdAfx.h"#include "DlgAbout.h"CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) {}void CAboutDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()2、FormCommandView.cpp#include "stdafx.h"#include "Tool.h"#include "MainFrm.h"#include "FormCommandView.h"#include "ToolDoc.h"#include "RenderView.h"// Download by #ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CFormCommandViewIMPLEMENT_DYNCREATE(CFormCommandView, CFormView)CFormCommandView::CFormCommandView(): CFormView(CFormCommandView::IDD){//{{AFX_DATA_INIT(CFormCommandView)m_Smooth = FALSE;m_Antialias = FALSE;//}}AFX_DATA_INIT}CFormCommandView::~CFormCommandView(){}void CFormCommandView::DoDataExchange(CDataExchange* pDX){CFormView::DoDataExchange(pDX);//{{AFX_DATA_MAP(CFormCommandView)DDX_Control(pDX, IDC_FRAME_COLOR_BACK, m_ControlBackColor);DDX_Check(pDX, IDC_CHECK_SMOOTH, m_Smooth);DDX_Check(pDX, IDC_CHECK_ANTIALIAS, m_Antialias);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CFormCommandView, CFormView)//{{AFX_MSG_MAP(CFormCommandView)ON_WM_PAINT()ON_WM_LBUTTONUP()ON_BN_CLICKED(IDC_RADIO_MODEL_1, OnRadioModel1)ON_BN_CLICKED(IDC_RADIO_MODEL_2, OnRadioModel2)ON_BN_CLICKED(IDC_CHECK_SMOOTH, OnCheckSmooth)ON_BN_CLICKED(IDC_CHECK_ANTIALIAS, OnCheckAntialias)//}}AFX_MSG_MAPEND_MESSAGE_MAP()///////////////////////////////////////////////////////////////////////// ////// CFormCommandView diagnostics#ifdef _DEBUGvoid CFormCommandView::AssertValid() const{CFormView::AssertValid();}void CFormCommandView::Dump(CDumpContext& dc) const{CFormView::Dump(dc);}CToolDoc* CFormCommandView::GetDocument() // non-debug version is inline {ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CToolDoc)));return (CToolDoc*)m_pDocument;}#endif //_DEBUG// OnPaintvoid CFormCommandView::OnPaint(){// Device context for paintingCPaintDC dc(this);// Options are stored in ApplicationCToolApp *pApp = (CToolApp *)AfxGetApp();CRect rect;// Color backm_ControlBackColor.GetWindowRect(&rect);ScreenToClient(&rect);CBrush BrushBack(pApp->m_OptionColorGlBack);dc.FillRect(&rect,&BrushBack);}// OnLButtonUpvoid CFormCommandView::OnLButtonUp(UINT nFlags,CPoint point){CRect rect;CToolApp *pApp = (CToolApp *)AfxGetApp();// Option back colorm_ControlBackColor.GetWindowRect(&rect);ScreenToClient(&rect);if(rect.PtInRect(point)){CColorDialog dlg(pApp->m_OptionColorGlBack);if(dlg.DoModal()==IDOK){pApp->m_OptionColorGlBack = dlg.GetColor();CRenderView *pView = (CRenderView *)GetRenderView();pView->m_ClearColorRed = (float)GetRValue(pApp->m_OptionColorGlBack) / 255.0f;pView->m_ClearColorGreen = (float)GetGValue(pApp->m_OptionColorGlBack) / 255.0f;pView->m_ClearColorBlue = (float)GetBValue(pApp->m_OptionColorGlBack) / 255.0f;this->InvalidateRect(&rect,FALSE);pView->InvalidateRect(NULL,FALSE);}}CFormView::OnLButtonUp(nFlags, point);}// GetRenderViewCView *CFormCommandView::GetRenderView(){CToolApp *pApp = (CToolApp *)AfxGetApp();CMainFrame *pFrame = (CMainFrame *)pApp->m_pMainWnd;CView *pView = (CView *)pFrame->m_wndSplitter.GetPane(0,1);return pView;}// Modelvoid CFormCommandView::OnRadioModel1(){glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);this->GetRenderView()->InvalidateRect(NULL,FALSE);}void CFormCommandView::OnRadioModel2(){glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);this->GetRenderView()->InvalidateRect(NULL,FALSE); }// OnCheckSmoothvoid CFormCommandView::OnCheckSmooth(){m_Smooth = !m_Smooth;if(m_Smooth)glShadeModel(GL_SMOOTH);elseglShadeModel(GL_FLAT);this->GetRenderView()->InvalidateRect(NULL,FALSE);}// OnCheckAntialias// Toggle antialiased linesvoid CFormCommandView::OnCheckAntialias(){m_Antialias = !m_Antialias;if(m_Antialias){glEnable(GL_LINE_SMOOTH);glEnable(GL_BLEND);glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);glLineWidth(1.5f);}else{glDisable(GL_LINE_SMOOTH);glDisable(GL_BLEND);glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);glLineWidth(1.0f);}GetRenderView()->InvalidateRect(NULL,FALSE);}3、MainFrm.cpp#include "stdafx.h"#include "Tool.h"// Download by #include "MainFrm.h"#include "FormCommandView.h"#include "RenderView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CMainFrameIMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd)BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)//{{AFX_MSG_MAP(CMainFrame)ON_WM_CREATE()ON_WM_PAINT()//}}AFX_MSG_MAPEND_MESSAGE_MAP()static UINT indicators[] ={ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS,ID_INDICATOR_NUM,ID_INDICATOR_SCRL,};// CMainFrame construction/destruction CMainFrame::CMainFrame(){}CMainFrame::~CMainFrame(){}int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {if (CFrameWnd::OnCreate(lpCreateStruct) == -1)return -1;if (!m_wndToolBar.Create(this) ||!m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) {TRACE0("Failed to create toolbar\n");return -1; // fail to create}if (!m_wndStatusBar.Create(this) ||!m_wndStatusBar.SetIndicators(indicators,sizeof(indicators)/sizeof(UINT))){TRACE0("Failed to create status bar\n");return -1; // fail to create}m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);return 0;}BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs){cs.cx = 600; cs.cy = 500;return CFrameWnd::PreCreateWindow(cs);}// CMainFrame diagnostics#ifdef _DEBUGvoid CMainFrame::AssertValid() const{CFrameWnd::AssertValid();}void CMainFrame::Dump(CDumpContext& dc) const{CFrameWnd::Dump(dc);}#endif //_DEBUG// CMainFrame message handlersvoid CMainFrame::OnPaint(){CPaintDC dc(this); // device context for painting}BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) {if (!m_wndSplitter.CreateStatic(this, 1, 2,WS_CHILD | WS_VISIBLE)){TRACE("Failed to CreateStaticSplitter\n");return FALSE;}// First splitter paneif (!m_wndSplitter.CreateView(0, 0,RUNTIME_CLASS(CRenderView), CSize(600,500), pContext)){TRACE("Failed to create command view pane\n");return FALSE;}if (!m_wndSplitter.CreateView(0, 1,RUNTIME_CLASS(CFormCommandView), CSize(0,0), pContext)){TRACE("Failed to create command view pane\n");return FALSE;}// Second splitter panereturn TRUE;}4、RenderView.cpp#include "stdafx.h"#include "Tool.h"#include <string.h>#include <time.h>#include <math.h>#include "ToolDoc.h"#include "RenderView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifextern void Render(void);// This is the holding space for the landscape colours.int WinWidth, WinHeigth;unsigned short int comp = 32; // Scale modifier.unsigned short int temp, texture_mapping = FALSE,land_fogging = TRUE, flat_shading = TRUE; float angle, Near, ex, ey, ez, cx, cy, cz;// Initial eye position and vector of sight.static GLfloat speed = 0;// The following code for mouse routines was contributed.// These are used for the motion function.#define FORWARD 1#define UP 2#define TURNLEFT 3#define LOOKUP 5// Mouse position and button.int oldmx = 0, oldmy = 0, mb;// CRenderViewIMPLEMENT_DYNCREATE(CRenderView, CView)BEGIN_MESSAGE_MAP(CRenderView, CView)//{{AFX_MSG_MAP(CRenderView)ON_WM_DESTROY()ON_WM_SIZE()ON_WM_LBUTTONDOWN()ON_WM_LBUTTONUP()ON_WM_MOUSEMOVE()ON_WM_PAINT()ON_WM_CREATE()//}}AFX_MSG_MAP// Standard printing commandsON_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()// CRenderView construction/destructionCRenderView::CRenderView(){// OpenGLm_hGLContext = NULL;m_GLPixelIndex = 0;// Mousem_LeftButtonDown = FALSE;m_RightButtonDown = FALSE;m_CursorRotation = AfxGetApp()->LoadCursor(IDC_CURSOR_ROTATION);// ColorsCToolApp *pApp = (CToolApp *)AfxGetApp();m_ClearColorRed = GetRValue(pApp->m_OptionColorGlBack);m_ClearColorGreen = GetGValue(pApp->m_OptionColorGlBack);m_ClearColorBlue = GetBValue(pApp->m_OptionColorGlBack); ReadData();WinWidth=1000;WinHeigth=800;LoadAllTexture();InitLookAt();}//============================================// InitGeometry//============================================void CRenderView::InitGeometry(void){GLfloat fogColor[4] = {0.75, 0.75, 1.0, 1.0};speed = 0;srand(224);srand((unsigned)time(NULL));glPixelStorei(GL_UNPACK_ALIGNMENT, 1);glEnable(GL_DEPTH_TEST);glShadeModel(GL_FLAT);glFogi(GL_FOG_MODE, GL_LINEAR);glFogfv(GL_FOG_COLOR, fogColor);glFogf(GL_FOG_DENSITY, 0.8f);glFogf(GL_FOG_START, 400.0f);glFogf(GL_FOG_END, 500.0f);glClearColor(0.75f, 0.75f, 1.0f, 1.0f);}CRenderView::~CRenderView(){FreeAllTexture();freelist();}BOOL CRenderView::PreCreateWindow(CREATESTRUCT& cs){return CView::PreCreateWindow(cs);}// CRenderView drawingvoid CRenderView::OnDraw(CDC* pDC){}BOOL CRenderView::OnPreparePrinting(CPrintInfo* pInfo){return DoPreparePrinting(pInfo);}void CRenderView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) {}void CRenderView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) {}// CRenderView diagnostics#ifdef _DEBUGvoid CRenderView::AssertValid() const{CView::AssertValid();}void CRenderView::Dump(CDumpContext& dc) const{CView::Dump(dc);}CToolDoc* CRenderView::GetDocument() // non-debug version is inline{if (m_pDocument){ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CToolDoc)));return (CToolDoc*)m_pDocument;}else return NULL;}#endif //_DEBUG// Create OpenGL rendering contextint CRenderView::OnCreate(LPCREATESTRUCT lpCreateStruct) {if (CView::OnCreate(lpCreateStruct) == -1)return -1;HWND hWnd = GetSafeHwnd();HDC hDC = ::GetDC(hWnd);if(SetWindowPixelFormat(hDC)==FALSE)return 0;if(CreateViewGLContext(hDC)==FALSE)return 0;// Default modeglPolygonMode(GL_FRONT,GL_FILL);glPolygonMode(GL_BACK,GL_FILL);glShadeModel(GL_FLAT);// light must be disabled// while rendering the terrain// because it has no normal definitionInitGeometry();glEnable(GL_TEXTURE_2D);glDisable(GL_LIGHTING);return 0;}BOOL CRenderView::SetWindowPixelFormat(HDC hDC){PIXELFORMATDESCRIPTOR pixelDesc;pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);pixelDesc.nVersion = 1;pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE;pixelDesc.iPixelType = PFD_TYPE_RGBA;olorBits = 32;pixelDesc.cRedBits = 8;pixelDesc.cRedShift = 16;pixelDesc.cGreenBits = 8;pixelDesc.cGreenShift = 8;pixelDesc.cBlueBits = 8;pixelDesc.cBlueShift = 0;pixelDesc.cAlphaBits = 0;pixelDesc.cAlphaShift = 0;pixelDesc.cAccumBits = 64;pixelDesc.cAccumRedBits = 16;pixelDesc.cAccumGreenBits = 16;pixelDesc.cAccumBlueBits = 16;pixelDesc.cAccumAlphaBits = 0;pixelDesc.cDepthBits = 32;pixelDesc.cStencilBits = 8;pixelDesc.cAuxBuffers = 0;pixelDesc.iLayerType = PFD_MAIN_PLANE;pixelDesc.bReserved = 0;pixelDesc.dwLayerMask = 0;pixelDesc.dwVisibleMask = 0;pixelDesc.dwDamageMask = 0;m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);if(m_GLPixelIndex == 0) // Choose default{m_GLPixelIndex = 1;if(DescribePixelFormat(hDC,m_GLPixelIndex,sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)return FALSE;}if(!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc))return FALSE;return TRUE;}// Create an OpenGL rendering contextBOOL CRenderView::CreateViewGLContext(HDC hDC){m_hGLContext = wglCreateContext(hDC);if(m_hGLContext==NULL)return FALSE;if(wglMakeCurrent(hDC,m_hGLContext)==FALSE)return FALSE;return TRUE;}// Cleanup every OpenGL rendering contextvoid CRenderView::OnDestroy(){if(wglGetCurrentContext() != NULL)wglMakeCurrent(NULL,NULL);if(m_hGLContext != NULL){wglDeleteContext(m_hGLContext);m_hGLContext = NULL;}CView::OnDestroy();}void CRenderView::OnSize(UINT nType, int cx, int cy) {CView::OnSize(nType, cx, cy);// Set OpenGL perspective, viewport and modeCSize size(cx,cy);double aspect;aspect = (cy == 0) ? (double)size.cx : (double)size.cx/(double)size.cy;glViewport(0, 0, (GLsizei) cx, (GLsizei) cy);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(60.0, (GLfloat) cx/(GLfloat) cy, 1.0f, 500.0f);glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt (ex, ey, ez, cx, cy, cz, 0.0f, 1.0f, 0.0f);}void CRenderView::OnLButtonDown(UINT nFlags, CPoint point){m_LeftButtonDown = TRUE;m_LeftDownPos = point;CView::OnLButtonDown(nFlags, point);}void CRenderView::OnLButtonUp(UINT nFlags,CPoint point){m_LeftButtonDown = FALSE;CView::OnLButtonUp(nFlags, point);}void CRenderView::OnMouseMove(UINT nFlags, CPoint point){switch(nFlags){case(MK_LBUTTON):MoveEye(FORWARD,(GLfloat)(oldmy-point.y)/5.0f,1);break;case(MK_RBUTTON):MoveEye(TURNLEFT, (GLfloat)(oldmx-point.x), 1);break;}oldmy = point.y;oldmx = point.x;Invalidate(FALSE);CView::OnMouseMove(nFlags, point);}void CRenderView::OnPaint(){// Device context for paintingCPaintDC dc(this);// Useful in singledoc templatesHWND hWnd = GetSafeHwnd();HDC hDC = ::GetDC(hWnd);wglMakeCurrent(hDC,m_hGLContext);glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glClearColor(m_ClearColorRed,m_ClearColorGreen,m_ClearColorBlue,1.0f); glPushMatrix();glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);InitRenderWin();Render();// Double buffersSwapBuffers(hDC);}// Function that moves the eye or turns the angle of sight.// Updates scene if update != 0.void CRenderView::MoveEye(int type, GLfloat amount, int update){GLfloat a;switch(type){case FORWARD:a = sqrt((cx-ex)*(cx-ex)+(cz-ez)*(cz-ez));ex = (amount*(cx-ex)+a*ex) / a;ez = (amount*(cz-ez)+a*ez) / a;cx = (amount*(cx-ex)+a*cx) / a;cz = (amount*(cz-ez)+a*cz) / a;break;case TURNLEFT:cx = (cx-ex)*(float)cos(amount/360.0f) + (cz-ez)*(float)sin(amount/360.0f)+ex;cz = (cz-ez)*(float)cos(amount/360.0f) - (cx-ex)*(float)sin(amount/360.0f)+ez;break;case UP:ey += amount;break;case LOOKUP:cy += amount;break;}if (update){glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt(ex, ey, ez, cx, cy, cz, 0.0f,1.0f,0.0f);}}TEXTURE_2D **TextureList;OBJECT *ObjectList; /* ObjectList[0]:isolated surfaces*/INT4S ObjectNum;char gEnergyFile[30];char sLookAtFN[100];char ImageName[30];void CRenderView::ReadData(){int i,j,l;FILE *fp;char stemp[100];POINT3D *plist;INT4U nAllVertexNum;INT4U *pchlist;strcpy(gEnergyFile,"room.ed");fp = fopen( gEnergyFile, "r" );if ( fp == NULL ){printf( "\n Can not open energy data file:%s\n", gEnergyFile); exit(0);}fseek( fp, 0, SEEK_SET);/****** read texture list ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"texnum" ) != 0) fscanf( fp, "%s", stemp);fscanf( fp, "%d", &texnum );TextureList = (TEXTURE_2D **)malloc( sizeof(TEXTURE_2D)*(texnum+1)); for(i=1; i<=texnum; i++){TextureList[i] = (TEXTURE_2D *)malloc( sizeof(TEXTURE_2D));fscanf( fp, "%s%s", TextureList[i]->fname, stemp );if ( strcmp( stemp,"REPEAT_TEXTURE" ) == 0)TextureList[i]->type = 1;else if ( strcmp( stemp,"CLAMP_TEXTURE" ) == 0)TextureList[i]->type = 0;}/****** Read object list ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"ObjectNum" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%ld", &ObjectNum);ObjectList = (OBJECT *)malloc( sizeof(OBJECT ) * ObjectNum);for(i = 0; i < ObjectNum; i ++ ){f scanf( fp, "%s", stemp);w hile( strcmp( stemp,"SurfaceNum" ) != 0) fscanf(fp,"%s",stemp);f scanf( fp, "%ld", &(ObjectList[i].SurfNum) );ObjectList[i].surflist = (SURFACE *)malloc( sizeof(SURFACE) * ObjectList[i].SurfNum);for(j = 0; j < ObjectList[i].SurfNum; j ++ ){/****** Read surface infor ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"TextureId" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].texId) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"pointnum" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].pointn) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"triangle" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].triangle) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"quadrangle" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].quadric) );/****** Read point list ******/ObjectList[i].surflist[j].pointlist = (POINT3D*)malloc(sizeof(POINT3D) *ObjectList[i].surflist[j].pointn);plist = ObjectList[i].surflist[j].pointlist;for( l = 0; l < ObjectList[i].surflist[j].pointn ; l ++ )fscanf( fp, "%f%f%f%f%f%f%f%f",&(plist[l].r), &(plist[l].g), &(plist[l].b),&(plist[l].u), &(plist[l].v),&(plist[l].x), &(plist[l].y), &(plist[l].z) );/****** Read patchlist ******/nAllVertexNum = ObjectList[i].surflist[j].triangle * 3 +ObjectList[i].surflist[j].quadric *4 ;ObjectList[i].surflist[j].patchlist = (INT4U *)malloc( sizeof(INT4U) * nAllVertexNum);pchlist = ObjectList[i].surflist[j].patchlist;for( l = 0; l < nAllVertexNum; l ++ )fscanf( fp, "%ld", &(pchlist[l]) );}}fclose(fp);}void CRenderView::InitLookAt(){FILE *fp;strcpy(sLookAtFN,"room.lk");fp = fopen(sLookAtFN, "rb");if (fp == NULL){ex = ey = ez =1.0f;cx = cy = cz =0.0f;Near = 0.1f;angle = 30.0f;}else fscanf(fp, "%f%f%f%f%f%f%f%f", &angle, &Near, &ex, &ey, &ez, &cx, &cy, &cz);fclose(fp);}void C RenderView::InitRenderWin(){glShadeModel ( GL_SMOOTH );glDepthFunc ( GL_LESS );glEnable ( GL_DEPTH_TEST );glMatrixMode ( GL_PROJECTION );glLoadIdentity();glMatrixMode ( GL_MODELVIEW );glLoadIdentity();gluPerspective ( angle, (float)WinWidth/(float)WinHeigth, Near, 1000000000.0); gluLookAt( ex, ey, ez, cx, cy, cz, 0.0, 1.0, 0.0);}void C RenderView::Render(void){int i, j, k, l, m, TexIndex;POINT3D *plist;INT4U *pchlist;glClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);for(i = 0; i < ObjectNum; i ++ )for(j = 0; j < ObjectList[i].SurfNum; j ++ ){TexIndex = ObjectList[i].surflist[j].texId;if( TexIndex > 0 )InitTex( TexIndex );plist = ObjectList[i].surflist[j].pointlist;pchlist = ObjectList[i].surflist[j].patchlist;l = 0;for ( k = 0; k < ObjectList[i].surflist[j].triangle; k ++){glBegin( GL_TRIANGLES );for( m = 0; m < 3; m ++ ){glColor3f ( plist[pchlist[l]].r,plist[pchlist[l]].g,plist[pchlist[l]].b );glTexCoord2f( plist[pchlist[l]].u,plist[pchlist[l]].v );glVertex3f( plist[pchlist[l]].x,plist[pchlist[l]].y,plist[pchlist[l]].z );l ++;}/* m */glEnd();}/* k */for ( k = 0; k < ObjectList[i].surflist[j].quadric; k ++){glBegin( GL_QUADS );for( m = 0; m < 4; m ++ ){glColor3f ( plist[pchlist[l]].r,plist[pchlist[l]].g,plist[pchlist[l]].b );glTexCoord2f( plist[pchlist[l]].u,plist[pchlist[l]].v );glVertex3f( plist[pchlist[l]].x,plist[pchlist[l]].y,plist[pchlist[l]].z );l ++;}/* m */glEnd();}/* k */glFlush();CloseTex();}}void CRenderView::freelist(){int i, j;for( i=0; i<ObjectNum; i++){for( j=0; j<ObjectList[i].SurfNum; j++){free(ObjectList[i].surflist[j].pointlist);free(ObjectList[i].surflist[j].patchlist);}free( ObjectList[i].surflist );}free(ObjectList);for(i=1; i<=texnum; i++)free(TextureList[i]);free(TextureList);}extern TEXTURE_2D **TextureList;/********************************//* function : OpenTexImage *//********************************/unsigned char *CRenderView::OpenTexImage( INT2U TexIndex, INT2U *rslx, INT2U *rsly ){unsigned char *image;FILE *fp;INT2U srcx, srcy;INT4U i, j;char ImageName[30];unsigned char *SImageData;int rc;int width, height;strcpy( ImageName, TextureList[TexIndex]->fname);/* load a image */fp = fopen(ImageName,"rb");if(!fp) return 0;fseek(fp,18L,0);rc=fread(&width,sizeof(long),1,fp);rc=fread(&height,sizeof(long),1,fp);*rslx=srcx=width; *rsly=srcy=height;fseek(fp,54L,0);image = (unsigned char *)malloc(width*height*3);rc=fread(image,width*height*3,1,fp);fclose(fp);SImageData = (unsigned char *)malloc(srcx*srcy*3);for(i=0; i<srcx; i++) {for(j=0; j<srcy; j++) {(unsigned char)*(SImageData+i*srcx*3+j*3+0) = (unsignedchar)*(image+i*srcx*3+j*3+2);(unsigned char)*(SImageData+i*srcx*3+j*3+1) = (unsigned char)*(image+i*srcx*3+j*3+1);(unsigned char)*(SImageData+i*srcx*3+j*3+2) = (unsigned char)*(image+i*srcx*3+j*3+0);}}free(image);printf("%s : %ld=%ld\n", ImageName, srcx*srcy*3,i*j*3);return( SImageData );}/********************************//* function : InitTex *//********************************/void C RenderView::InitTex( int TexIndex ){INT2U TextType;unsigned char *ImageData;static int OldIndex = -1;if(TexIndex<=0) return;if(TexIndex == OldIndex){glEnable(GL_TEXTURE_2D);return;}ImageData = ImageDatas[TexIndex-1];TextType = TextureList[TexIndex]->type;glPixelStorei(GL_UNPACK_ALIGNMENT, 1);glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);if( TextType == CLAMP_TEXTURE ){glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);}else{glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);}glTexImage2D( GL_TEXTURE_2D, 0, 3, rslxs[TexIndex-1], rslys[TexIndex-1], 0,GL_RGB, GL_UNSIGNED_BYTE, ImageData );glEnable(GL_TEXTURE_2D);OldIndex = TexIndex;}/********************************//* function : CloseTex *//********************************/void C RenderView::CloseTex(){glDisable(GL_TEXTURE_2D);}void CRenderView::LoadAllTexture(){int i;for (i=0; i <texnum ; i++)ImageDatas[i] = OpenTexImage( i+1, &rslxs[i], &rslys[i] );}void CRenderView::FreeAllTexture(){int i;for (i=0; i <texnum ; i++)free(ImageDatas[i]);}5、StdAfx.cpp#include "stdafx.h"6、Tool.cpp#include "stdafx.h"#include "Tool.h"#include "DlgAbout.h"#include "MainFrm.h"#include "ToolDoc.h"#include "RenderView.h"// Download by #ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CToolAppCToolDoc *MyDocument;BEGIN_MESSAGE_MAP(CToolApp, CWinApp)//{{AFX_MSG_MAP(CToolApp)ON_COMMAND(ID_APP_ABOUT, OnAppAbout)//}}AFX_MSG_MAP// Standard file based document commands// Standard print setup commandON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP()// CToolApp constructionCToolApp::CToolApp(){// Optionsm_OptionColorGlBack = RGB(0,0,255);}// The one and only CToolApp objectCToolApp theApp;// CToolApp initializationBOOL CToolApp::InitInstance(){AfxEnableControlContainer();// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL#elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endif// Change the registry key under which our settings are stored.// You should modify this string to be something appropriate// such as the name of your company or organization.SetRegistryKey(_T("3D Toolbox"));LoadStdProfileSettings(10); // Load standard INI file options (including MRU)// Register the application's document templates. Document templates// serve as the connection between documents, frame windows and views.CSingleDocTemplate* pDocTemplate;// create main SDI Frame windowCMainFrame* pMainFrame = new CMainFrame;if (!pMainFrame->LoadFrame(IDR_MAINFRAME))return FALSE;m_pMainWnd = pMainFrame;pDocTemplate = new CSingleDocTemplate(IDR_MODELTYPE,RUNTIME_CLASS(CToolDoc),RUNTIME_CLASS(CMainFrame),RUNTIME_CLASS(CRenderView));AddDocTemplate(pDocTemplate);// The main window has been initialized, so show and update it.//pMainFrame->ShowWindow(SW_SHOWMAXIMIZED);pMainFrame->ShowWindow(SW_SHOW);pMainFrame->UpdateWindow();return TRUE;}// App command to run the dialogvoid CToolApp::OnAppAbout(){CAboutDlg aboutDlg;aboutDlg.DoModal();}6、ToolDoc.cpp#include "stdafx.h"#include "math.h"#include "Tool.h"#include "ToolDoc.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifIMPLEMENT_DYNCREATE(CToolDoc, CDocument)BEGIN_MESSAGE_MAP(CToolDoc, CDocument)//{{AFX_MSG_MAP(CToolDoc)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAPEND_MESSAGE_MAP()extern CToolApp theApp;// CToolDoc construction/destruction。

图形学实验报告 OpenGL中的实体模型与层次模型

图形学实验报告 OpenGL中的实体模型与层次模型

《计算机图形学基础》实验3OpenGL中的实体模型与层次模型一、实验目的及要求1.掌握GLUT库中的多面体函数的绘制方法;2.掌握GLUT库中的二、三次曲面的绘制方法;3.掌握绘制实体或线框模型的绘制方法;4.掌握显示列表的用法;二、实验环境主要是软件开发环境:VC 6.0三、实验内容1.利用OpenGL绘制简单多面体、二次及三次曲线的例子。

2.利用OpenGL绘制奥运五环标志。

四、实验结果1、利用OpenGL绘制简单多面体、二次及三次曲线的例子。

2、利用OpenGL绘制奥运五环标志五、程序代码1、利用OpenGL绘制简单多面体、二次及三次曲线#include <gl/glut.h>static GLsizei iMode = 1;static GLfloat xRot = 0.0f; //x方向旋转参数static GLfloat yRot = 0.0f; //y方向旋转参数GLUquadricObj *obj; //二次曲面对象void Initial(void){glClearColor(1.0f, 1.0f, 1.0f, 1.0f);glColor3f(0.0f, 0.0f, 0.0f);obj = gluNewQuadric( );gluQuadricDrawStyle(obj, GLU_LINE); //以线框方式绘制二次曲面对象}void ChangeSize(int w, int h){glViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D (-1.5f, 1.5f, -1.5f, 1.5f);}void Display(void){glClear(GL_COLOR_BUFFER_BIT);glMatrixMode(GL_MODELVIEW);glLoadIdentity();glRotatef(xRot, 1.0f, 0.0f, 0.0f); //旋转图形glRotatef(yRot, 0.0f, 1.0f, 0.0f); //旋转图形//指定需要绘制的图元switch(iMode) {case 1:glutWireTetrahedron(); break;case 2:glutSolidTetrahedron(); break;case 3:glutWireOctahedron(); break;case 4:glutSolidOctahedron(); break;case 5:glutWireSphere(1.0f,15,15); break;case 6:glutSolidSphere(1.0f,15,15); break;case 7:glutWireTeapot(1.0f); break;case 8:glutSolidTeapot(1.0f); break;case 9:gluSphere(obj, 1.0f, 15, 15); break;case 10:gluCylinder(obj,1.0f,0.0f,1.0f,15,15);break;case 11:gluPartialDisk(obj,0.3f,0.8f,15,15,30.0f,260.0f); break;default: break;}glFlush();}void ProcessMenu(int value){iMode = value;glutPostRedisplay();}void SpecialKeys(int key, int x, int y){if(key == GLUT_KEY_UP) xRot-= 5.0f;if(key == GLUT_KEY_DOWN) xRot += 5.0f;if(key == GLUT_KEY_LEFT) yRot -= 5.0f;if(key == GLUT_KEY_RIGHT) yRot += 5.0f;if(xRot > 356.0f) xRot = 0.0f;if(xRot < -1.0f) xRot = 355.0f;if(yRot > 356.0f) yRot = 0.0f;if(yRot < -1.0f) yRot = 355.0f;glutPostRedisplay();}int main(int argc, char* argv[]){glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(400,400);glutInitWindowPosition(100,100);glutCreateWindow("OpenGL模型绘制函数示例");//创建菜单并定义菜单回调函数int nGlutPolyMenu = glutCreateMenu(ProcessMenu);glutAddMenuEntry("线框正四面体",1); //创建GLUT多面体绘制菜单glutAddMenuEntry("实体正四面体",2);glutAddMenuEntry("线框正八面体",3);glutAddMenuEntry("实体正八面体",4);int nGlutCurveMenu = glutCreateMenu(ProcessMenu); //创建GLUT曲面绘制菜单glutAddMenuEntry("线框球面",5);glutAddMenuEntry("实体球面",6);glutAddMenuEntry("线框茶壶",7);glutAddMenuEntry("实体茶壶",8);int nGluCurveMenu = glutCreateMenu(ProcessMenu); //创建GLU曲面绘制菜单glutAddMenuEntry("线框球面",9);glutAddMenuEntry("线框圆锥面",10);glutAddMenuEntry("线框圆环面",11);int nMainMenu = glutCreateMenu(ProcessMenu); //创建主菜单glutAddSubMenu("GLUT多面体", nGlutPolyMenu);glutAddSubMenu("GLUT曲面", nGlutCurveMenu);glutAddSubMenu("GLU曲面", nGluCurveMenu);glutAttachMenu(GLUT_RIGHT_BUTTON);glutDisplayFunc(Display);glutReshapeFunc(ChangeSize);glutSpecialFunc(SpecialKeys);Initial();glutMainLoop();return 0;}2、利用OpenGL绘制奥运五环标志#include <gl/glut.h>GLuint OlympicRings;void Initial(void){glClearColor(1.0f, 1.0f, 1.0f, 1.0f);OlympicRings = glGenLists(1);glNewList(OlympicRings, GL_COMPILE);glColor3f(1.0, 1.0, 0.0);glTranslatef(-22.0, 0.0, 0.0);glutSolidTorus(0.5, 20.0, 15, 50); //绘制黄色环glColor3f(0.0, 1.0, 0.0);glTranslatef(44.0, 0.0, 0.0);glutSolidTorus(0.5, 20.0, 15, 50); //绘制绿色环glColor3f(0.0, 0.0, 0.0);glTranslatef(-22.0, 30.0, 0.0);glutSolidTorus(0.5, 20.0, 15, 50); //绘制黑色环glColor3f(0.0, 0.0, 1.0);glTranslatef(-42.0, 0.0, 0.0);glutSolidTorus(0.5, 20.0, 15, 50); //绘制蓝色环glColor3f(1.0, 0.0, 0.0);glTranslatef(84.0, 0.0, 0.0);glutSolidTorus(0.5, 20.0, 15, 50); //绘制红色环glEndList();}void ChangeSize(int w, int h){glViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluOrtho2D (-70.0f, 70.0f, -70.0f, 70.0f);}void Display(void){glClear(GL_COLOR_BUFFER_BIT);glMatrixMode(GL_MODELVIEW);glLoadIdentity();glCallList(OlympicRings); //调用显示列表glFlush();}int main(int argc, char* argv[]){glutInit(&argc, argv);glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);glutInitWindowSize(400,400);glutInitWindowPosition(100,100);glutCreateWindow("OpenGL模型绘制函数示例");glutDisplayFunc(Display);glutReshapeFunc(ChangeSize);Initial();glutMainLoop();return 0;}六、心得体会多面体画出来,如果函数引用缺少一部分,那么会很小。

计算机图形学OpenGL版实验1-4

计算机图形学OpenGL版实验1-4

实验1 OpenGL初识一、实验目的:熟悉编程环境;了解光栅图形显示器的特点;了解计算机绘图的特点;利用VC+OpenGL作为开发平台设计程序,以能够在屏幕上生成任意一个像素点为本实验的结束。

二、实验内容:(1)了解和使用VC的开发环境,理解简单的OpenGL程序结构。

(2)掌握OpenGL提供的基本图形函数,尤其是生成点的函数。

三、该程序的作用是在一个黑色的窗口中央画一个矩形、三角形和三个点,如图所示。

下面对各行语句进行说明:首先,需要包含头文件#include <GL/glut.h>,这是GLUT的头文件。

然后看main函数。

int main(int argc, char *argv[]),这个是带命令行参数的main函数。

这种以glut开头的函数都是GLUT工具包所提供的函数,下面对用到的几个函数进行介绍;1)glutInit,对GLUT进行初始化,这个函数必须在其它的GLUT使用之前调用一次。

其格式比较固定,一般都是glutInit(&argc, argv)就行;2) glutInitDisplayMode,设置显示方式,其中GLUT_RGB表示使用RGB颜色,与之对应的还有GLUT_INDEX(表示使用索引颜色)。

GLUT_SINGLE表示使用单缓冲,与之对应的还有GLUT_DOUBLE(使用双缓冲)。

更多信息,以后的实验教程会有讲解介绍;3) glutInitWindowPosition,设置窗口在屏幕中的位置;4) glutInitWindowSize,设置窗口的大小;5) glutCreateWindow,根据前述设置的信息创建窗口。

参数将被作为窗口的标题。

注意:窗口被创建后,并不立即显示到屏幕上。

需要调用glutMainLoop才能看到窗口;6) glutDisplayFunc,设置一个函数,当需要进行画图时,这个函数就会被调用。

(暂且这样理解);7) glutMainLoop,进行一个消息循环。

关于opengl实验报告

关于opengl实验报告

关于opengl实验报告OpenGL实验报告一、实验目的本实验旨在通过使用OpenGL图形库,掌握基本的3D图形编程技术,以及了解OpenGL的基本操作和常用函数。

二、实验环境1. 操作系统:Windows 102. 开发环境:Visual Studio 20193. 编程语言:C++4. 图形库:OpenGL三、实验内容1. 创建一个窗口并初始化OpenGL环境2. 绘制一个简单的三维立方体3. 添加光照效果和材质4. 实现简单的相机控制5. 添加纹理贴图四、实验过程1. 创建窗口并初始化OpenGL环境首先,我们使用OpenGL提供的函数来创建一个窗口,并初始化OpenGL环境。

这一步是整个实验的基础,也是我们能够进行后续操作的前提。

2. 绘制一个简单的三维立方体利用OpenGL提供的函数,我们可以很容易地绘制一个简单的三维立方体。

通过设置顶点坐标和法向量,我们可以使用OpenGL提供的函数来绘制出一个立方体。

3. 添加光照效果和材质在绘制立方体的基础上,我们可以通过设置光源的位置和颜色,以及物体的材质属性,来实现光照效果和材质的渲染。

这一步可以让我们的立方体看起来更加真实。

4. 实现简单的相机控制通过控制相机的位置和方向,我们可以实现简单的相机控制。

这样可以让我们在3D场景中自由地移动和观察物体。

5. 添加纹理贴图最后,我们可以通过加载纹理图片,并将其贴到立方体的表面上,来实现纹理贴图。

这样可以让我们的立方体看起来更加生动和具有真实感。

五、实验总结通过本次实验,我们学习了如何使用OpenGL图形库进行3D图形编程,掌握了基本的操作和常用函数。

同时,我们也实现了一个简单的3D场景,包括绘制立方体、添加光照效果和材质、实现相机控制以及添加纹理贴图。

这些技术和知识对于今后的图形编程工作将会有很大的帮助。

计算机图形学实验报告(一).doc

计算机图形学实验报告(一).doc

实验一OpenGL开发环境及扫描转换算法1、实验目的与要求1.通过实验掌握OpenGL中编程环境的设置,了解相关函数用途及设置步骤;2.通过实验掌握基本图形元素的生成,给出相关代码和运行结果;3.用WINDOWS GDI函数编写生成直线或区域填充的程序(选DDA或Bresenham直线算法,活性边表算法填充多边形),演示算法过程。

4.画矩形,调用一个函数画一个矩形。

画椭圆,调用一个函数画一个椭圆。

画Bezier 曲线。

2、实验方案请描述为达到实验的需要完成哪些方面的实验,列举出实验的基本要点和重点。

在工程WinAPIEX加入void createLine(HDC tmpDC)和void Polyline (tmpDC)在void createLine(HDC tmpDC)用DDA直线算法或Bresenham直线算法生成直线在void Polyline (tmpDC)添加活泩边表填充算法,生成填充四边形和八边形加入Rectangle(tmpDC,x0,y0,x1,y1);加入Ellipse (tmpDC, x0,y0,a,b) ;加入PolyBezier(tmpDC,arr_vertex,4) ;3、实验结果和数据处理1)生成直线的DDA直线算法在createLine(tmpDC)中加入以下代码int x0,y0,x1,y1,color; //自定义直线的起点(x0,y0)和终点(x1,y1),及颜色colorfloat dx,dy,x,y;int length,i;x0=50;y0=160;x1=900;y1=200;//此处修改了color=1000; color=1;if(abs(x1-x0)>=abs(y1-y0))length=abs(x1-x0);elselength=abs(y1-y0);dx=(x1-x0)/(float)length;dy=(y1-y0)/(float)length;i=1;x=(float)x0;y=(float)y0;while(i<=length){SetPixel(tmpDC,int(x+0.5),int(y+0.5),color);x+=dx;y+=dy;i++;}2)区域填充的程序在void Polyline (tmpDC) 添加活性边表填充void Polyline (HDC tmpDC) //多边形边数.{const int POINTNUM=4;//或者是八边形8/******定义结构体用于活性边表AET和新边表NET***************************** ******/typedef struct XET{float x;float dx,ymax;XET* next;}AET,NET;/******定义点结构体point**************************** **************************/struct point{float x;float y;}polypoint[POINTNUM]={100,10 0,400,100,400,400,100,400};//正方形//polypoint[POINTNUM]={600,10 0,700,100,800,200,800,300,700,400,600, 400,500,300,500,200};//八边形顶点/******计算最高点的y坐标(扫描到此结束)****************************** **********/int MaxY=0;int i;for(i=0;i<POINTNUM;i++)if(polypoint[i].y>MaxY) MaxY=(int)polypoint[i].y;/*******初始化AET表********************************* **************************/AET *pAET=new AET;pAET->next=NULL;/******初始化NET表********************************* ***************************/NET *pNET[1024];for(i=0;i<=MaxY;i++){pNET[i]=new NET;pNET[i]->next=NULL;}/******扫描并建立NET表********************************* ************************/for(i=0;i<=MaxY;i++){for(intj=0;j<POINTNUM;j++)if(polypoint[j].y==i){if(polypoint[(j-1+POINTNUM)%POINT NUM].y>polypoint[j].y){NET*p=new NET;p->x=polypoint[j].x;p->ymax=polypoint[(j-1+POINTNUM) %POINTNUM].y;p->dx=(polypoint[(j-1+POINTNUM)%P OINTNUM].x-polypoint[j].x)/(polypoint [(j-1+POINTNUM)%POINTNUM].y-po lypoint[j].y);p->next=pNET[i]->next;pNET[i]->next=p;}if(polypoint[(j+1+POINTNUM)%POIN TNUM].y>polypoint[j].y){NET*p=new NET;p->x=polypoint[j].x;p->ymax=polypoint[(j+1+POINTNUM) %POINTNUM].y;p->dx=(polypoint[(j+1+POINTNUM)% POINTNUM].x-polypoint[j].x)/(polypoint[(j+1+POINTNUM)%POINTNUM].y-polypoint[j].y);p->next=pNET[i]->next;pNET[i]->next=p;}}}/******建立并更新活性边表AET***************************** ************************/for(i=0;i<=MaxY;i++){//计算新的交点x,更新AET***************************** ***************************/NET *p=pAET->next;while(p){p->x=p->x + p->dx;p=p->next;}//更新后新AET先排序********************************* ****************************///断表排序,不再开辟空间AET *tq=pAET;p=pAET->next;tq->next=NULL;while(p){while(tq->next && p->x >= tq->next->x)tq=tq->next;NET *s=p->next;p->next=tq->next;tq->next=p;p=s;tq=pAET;}//(改进算法)先从AET表中删除ymax==i的结点********************************* *******/AET *q=pAET;p=q->next;while(p){if(p->ymax==i){q->next=p->next;delete p;p=q->next;}else{q=q->next;p=q->next;}}//将NET中的新点加入AET,并用插入法按X值递增排序********************************* */p=pNET[i]->next;q=pAET;while(p){while(q->next && p->x >= q->next->x)q=q->next;NET *s=p->next;p->next=q->next;q->next=p;p=s;q=pAET;}/******配对填充颜色********************************* ******************************/p=pAET->next;while(p && p->next){for(floatj=p->x;j<=p->next->x;j++){SetPixel(tmpDC,static_cast<int>(j),i,RG B(255,200,0));//此处我改变了颜色,八边形的为黄色//SetPixel(tmpDC,static_cast<int>(j),i,RG B(255,0,0));//还有四边形的红色}p=p->next->next;//考虑端点情况}} }//画矩形Rectangle(tmpDC,20,20,80,80); //左上顶点,右下顶点//画椭圆Ellipse (tmpDC, 20,20,160,360) ;//画Bezier 曲线,利用已有的顶点数据PolyBezier(tmpDC,arr_vertex,4) ;实验截图:1.DDA算法的直线2.四边形和八边形3.正方形4.椭行5.Bezier 曲线实习总结:通过本次实验,我掌握了opengl绘图的一些基本知识,会在vc里面加入opengl的基本库。

图形学实验报告 OpenGL中的变换

图形学实验报告 OpenGL中的变换

《计算机图形学基础》实验6 OpenGL中的变换一、实验目的及要求1.理解OpenGL中的各种变换的实现原理;2.掌握OpenGL中模型视图矩阵的操作方法。

3.掌握OpenGL中投影变换的实现方法。

二、实验环境主要是软件开发环境VC 6.0三、实验内容1、分子动画示例2、深度测试示例四、实验结果1、分子动画五、程序代码1.分子动画#include <gl/glut.h>void Initial(){glEnable(GL_DEPTH_TEST); // 启用深度测试glClearColor(1.0f, 1.0f, 1.0f, 1.0f ); //背景为白色}void ChangeSize(int w, int h){if(h == 0) h = 1;glViewport(0, 0, w, h); // 设置视区尺寸glMatrixMode(GL_PROJECTION); // 指定当前操作投影矩阵堆栈glLoadIdentity(); // 重置投影矩阵GLfloat fAspect;fAspect = (float)w/(float)h; // 计算视区的宽高比gluPerspective(45.0, fAspect, 1.0, 500.0); // 指定透视投影的观察空间glMatrixMode(GL_MODELVIEW);glLoadIdentity();}void Display(void){static float fElect1 = 0.0f; // 绕原子旋转的角度glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //清除颜色和深度缓冲区glMatrixMode(GL_MODELVIEW); // 指定当前操作模型视图矩阵堆栈glLoadIdentity(); // 重置模型视图矩阵glTranslatef(0.0f, 0.0f, -250.0f); //将图形沿z轴负向移动glColor3f(1.0f, 0.0f, 0.0f);glutSolidSphere(12.0f, 15, 15); // 绘制红色的原子glColor3f(0.0f, 0.0f, 0.0f);glPushMatrix(); // 保存当前的模型视图矩阵glRotatef(fElect1, 0.0f, 1.0f, 0.0f); // 绕y轴旋转一定的角度glTranslatef(90.0f, 0.0f, 0.0f); // 平移一段距离glutSolidSphere(6.0f, 15, 15); // 画出第一个电子glPopMatrix(); // 恢复模型视图矩阵glPushMatrix(); // 保存当前的模型视图矩阵glRotatef(45.0f, 0.0f, 0.0f, 1.0f); //绕z轴旋转45°glRotatef(fElect1, 0.0f, 1.0f, 0.0f);glTranslatef(-70.0f, 0.0f, 0.0f);glutSolidSphere(6.0f, 15, 15); // 画出第二个电子glPopMatrix(); // 恢复模型视图矩阵glPushMatrix(); // 保存当前的模型视图矩阵glRotatef(-45.0f,0.0f, 0.0f, 1.0f); //绕z轴旋转-45°glRotatef(fElect1, 0.0f, 1.0f, 0.0f);glTranslatef(0.0f, 0.0f, 60.0f);glutSolidSphere(6.0f, 15, 15); // 画出第三个电子glPopMatrix();fElect1 += 10.0f; // 增加旋转步长,产生动画效果if(fElect1 > 360.0f) fElect1 = 10.0f;glutSwapBuffers();}void TimerFunc(int value){glutPostRedisplay();glutTimerFunc(100, TimerFunc, 1);}int main(int argc, char* argv[]){glutInit(&argc, argv);glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);glutCreateWindow("分子动画示例");glutReshapeFunc(ChangeSize);glutDisplayFunc(Display);glutTimerFunc(500, TimerFunc, 1); //指定定时器回调函数Initial();glutMainLoop();return 0;}六、心得体会这次的分子动画实验比较有意思,就是对代码的理解性不是很高。

《计算机图形学》课内实验报告(实验一)

《计算机图形学》课内实验报告(实验一)
PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
PFNGLUNIFORM1FARBPROC glUniform1fARB;
PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
#ifndef __APPLE__
PFNGLSECONDARYCOLOR3FPROC glSecondaryColor3f;
{
GLbyte infoLog[MAX_INFO_LOG_SIZE];
glGetInfoLogARB(progObj, MAX_INFO_LOG_SIZE, NULL, infoLog);
fprintf(stderr, "Error in program linkage!\n");
fprintf(stderr, "Info log: %s\n", infoLog);
// Demonstrates high-level shaders
// Program by Benjamin Lipchak
#include "../../Common/OpenGLSB.h" // System and OpenGL Stuff
#include "../../Common/GLTools.h" // System and OpenGL Stuff
// Initially set the blink parameter to 1 (no flicker)
if (flickerLocation != -1)
glUniform1fARB(flickerLocation,1.0f);
// Program object has changed, so we should revalidate

计算机图形学实验报告

计算机图形学实验报告

计算机图形学实验报告计算机图形学实验报告引言计算机图形学是研究计算机生成和处理图像的学科,它在现代科技和娱乐产业中扮演着重要的角色。

本实验报告旨在总结和分享我在计算机图形学实验中的经验和收获。

一、实验背景计算机图形学实验是计算机科学与技术专业的一门重要课程,通过实践操作和编程,学生可以深入了解图形学的基本原理和算法。

本次实验主要涉及三维图形的建模、渲染和动画。

二、实验内容1. 三维图形建模在实验中,我们学习了三维图形的表示和建模方法。

通过使用OpenGL或其他图形库,我们可以创建基本的几何体,如立方体、球体和圆柱体,并进行变换操作,如平移、旋转和缩放。

这些基本操作为后续的图形处理和渲染打下了基础。

2. 光照和着色光照和着色是图形学中重要的概念。

我们学习了不同的光照模型,如环境光、漫反射和镜面反射,并了解了如何在三维场景中模拟光照效果。

通过设置材质属性和光源参数,我们可以实现逼真的光照效果,使物体看起来更加真实。

3. 纹理映射纹理映射是一种将二维图像映射到三维物体表面的技术。

通过将纹理图像与物体的顶点坐标相对应,我们可以实现更加细致的渲染效果。

在实验中,我们学习了纹理坐标的计算和纹理映射的应用,使物体表面呈现出具有纹理和细节的效果。

4. 动画和交互动画和交互是计算机图形学的重要应用领域。

在实验中,我们学习了基本的动画原理和算法,如关键帧动画和插值技术。

通过设置动画参数和交互控制,我们可以实现物体的平滑移动和变形效果,提升用户体验。

三、实验过程在实验过程中,我们首先熟悉了图形库的使用和基本的编程技巧。

然后,我们按照实验指导书的要求,逐步完成了三维图形建模、光照和着色、纹理映射以及动画和交互等任务。

在实验过程中,我们遇到了许多挑战和问题,但通过不断的尝试和调试,最终成功实现了预期的效果。

四、实验结果通过实验,我们成功实现了三维图形的建模、渲染和动画效果。

我们可以通过键盘和鼠标控制物体的移动和变形,同时观察到真实的光照效果和纹理映射效果。

参考资料--opengl实验报告

参考资料--opengl实验报告

贵州大学实验报告学院:计算计科学与信息学院专业:班级:
这次试验的主要任务是学会配置opengl的运行环境,并通过编写程序来测试能否正确的生成相应的图案,所以还算比较简单的,做实验时只要看一下老师发给我们的ppt,然后按照上面的步骤一步一步的操作就行,先是把下载好的压缩包解压然后找到安装目录,然后将相应的文件放到相
贵州大学实验报告
学院:计算计科学与信息学院专业:数字媒体技术班级:数媒091
贵州大学实验报告
学院:计算计科学与信息学院专业:数字媒体技术班级:数媒091。

计算机图形学OpenGL实验一

计算机图形学OpenGL实验一
精品资料一实验目的理解图形元素显示的基本原理掌握扫描转换直线段的常用算法原理扫描转换圆弧的常用算法原理
实验报告
学院(系)名称:\
姓名
学号
专业
班级
实验项目
实验一:绘制基本图形
课程名称
计算机图形学
课程代码
实验时间
实验地点
批改意见
成绩
教师签字:
一、实验目的
1.理解图形元素显示的基本原理,掌握扫描转换直线段的常用算法原理,扫描转换圆弧的常用算法原理。
2.分别实现港口起重机、工程车、等设备的绘制。
3.颜色的设置要合适,且易于更换。
#include <math.h>
#include <gl/glut.h>
int SCREEN_HEIGHT = 480;//屏幕高度
//跟踪鼠标点击次数,达到3次后绘制Bezier曲线
int NUMPOINTS = 0;
Point POld = abc[0];
//绘制Bezier曲线段,控制t的增量可以控制曲线精度
for(double t = 0.0;t <= 1.0; t += 0.1) {
Point P = drawBezier(abc[0], abc[1], abc[2], t);
drawLine(POld, P);
2.熟悉glut常用几个功能函数
3.熟悉glut的函数回调机制
4.掌握绘制不同大小和颜色的点的方法
5.掌握绘制不同线型和颜色的直线的方法(直线,折线,环线)
6.掌握绘制彩色多边形边框的方法(各种设备)
7.熟悉OpenGL的编程环境(OpenGL+GlUT/SDK/MFC+C++)

计算机图形学实验报告三

计算机图形学实验报告三

《计算机图形学》实验报告glClear(GL_COLOR_BUFFER_BIT);//glEnable(GL_SCISSOR_TEST);//glScissor(0.0f,0.0f,500,300);glutWireTeapot(0.4);glFlush();}//窗口调整子程序void myReshape(int w, int h){glViewport(500, -300, (GLsizei)w, (GLsizei)h);glMatrixMode(GL_PROJECTION);glLoadIdentity();if (w <= h)glOrtho(-1, 1, -(float)h / w, (float)h / w, -1, 1);elseglOrtho(-(float)w / h, (float)w / h, -1, 1, -1, 0.5);}2,使用opengl函数写一个图形程序,要求分别使用三个光源从一个茶壶的前右上方(偏红色),正左侧(偏绿色)和前左下方(偏蓝色)对于其进行照射,完成程序并观察效果。

}//绘图子程序void display(void){glColor3f(1.0, 1.0, 0.0);glClear(GL_COLOR_BUFFER_BIT);//glMatrixMode(GL_MODELVIEW);//glLoadIdentity();//设置光源的属性1GLfloat LightAmbient1[] = { 1.0f, 0.0f, 0.0f, 1.0f }; //环境光参数 ( 新增 )GLfloat LightDiffuse1[] = { 1.0f, 0.0f, 0.0f, 1.0f }; // 漫射光参数 ( 新增 )GLfloat Lightspecular1[] = { 1.0f, 0.0f, 0.0f, 1.0f }; // 镜面反射GLfloat LightPosition1[] = { 500.0f, 500.0f, 500.0f, 1.0f }; // 光源位置 ( 新增 ) glLightfv(GL_LIGHT0, GL_POSITION, LightPosition1);glViewport(0, 0, (GLsizei)w, (GLsizei)h);glMatrixMode(GL_PROJECTION);glLoadIdentity();3,使用opengl函数完成一个图形动画程序,显示一个球沿正弦曲线运动的过程,同时显示一个立方体沿抛物线运动过程。

计算机图形学实验2------OPengl绘制3D图形

计算机图形学实验2------OPengl绘制3D图形

实验二 OPengl绘制3D图形一、实验目的➢了解和学习OpengL的编程➢通过学习掌握OpenGL 基本图元的绘制,进行3D图形的绘制➢掌握基于 Win32、Visual C++环境绘制3D 图形配置过程、绘制原理二、环境配置1)创建一个工程。

2)链接OpenGL libraries。

在Visual C++中先单击Project,再单击Settings,再找到Link单击,最后在Object/library modules 的最前面加上opengl32.lib glu32.lib glut.lib g laux.lib gdi32.lib user32.lib advapi32.lib或者在project -> add to project ->files引入需要的头文件3)单击Project Settings中的C/C++标签,将Preprocessor definitions 中的_CONSOLE 改为__WINDOWS。

最后单击OK。

三、实验关键代码void CCMyOpenGLView::RenderScene(){glLoadIdentity();glTranslatef(m_xPos,m_yPos,-5.0f);glRotatef(m_xAngle,1.0f,0.0f,0.0f);glRotatef(m_yAngle,0.0f,1.0f,0.0f);glutWireCone(1.0f,2.0,20,20);}bool CCMyOpenGLView::InitializeOpenGL(){m_pDC = new CClientDC(this);if(m_pDC == NULL){MessageBox("Error Obtaining DC");return FALSE;}if(!SetupPixelFormat()){return FALSE;}m_hRC = ::wglCreateContext (m_pDC->GetSafeHdc ());if(m_hRC == 0){MessageBox("RC创建失败!");return FALSE;}if(::wglMakeCurrent (m_pDC->GetSafeHdc (), m_hRC)==FALSE) {MessageBox("设置当前RC失败!");return FALSE;}::glClearColor(0.0f,0.0f,0.0f,0.0f);::glClearDepth(1.0f);::glEnable(GL_DEPTH_TEST);return TRUE;}bool CCMyOpenGLView::SetupPixelFormat(){static PIXELFORMATDESCRIPTOR pfd ={sizeof(PIXELFORMATDESCRIPTOR),1, PFD_DRAW_TO_WINDOW |PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,PFD_TYPE_RGBA, 24, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0};int m_nPixelFormat = ::ChoosePixelFormat(m_pDC->GetSafeHdc(), &pfd);if ( m_nPixelFormat == 0 ){return FALSE;}if(::SetPixelFormat(m_pDC->GetSafeHdc(),m_nPixelFormat,&pfd)==FALSE){return FALSE;}return TRUE;}int CCMyOpenGLView::OnCreate(LPCREATESTRUCT lpCreateStruct) {if (CView::OnCreate(lpCreateStruct) == -1)return -1;InitializeOpenGL();return 0;}void CCMyOpenGLView::OnDestroy(){CView::OnDestroy();if(::wglMakeCurrent (0,0) == FALSE)MessageBox("Could not make RC non-current");if(::wglDeleteContext (m_hRC)==FALSE)MessageBox("Could not delete RC");if(m_pDC)delete m_pDC;m_pDC = NULL;}BOOL CCMyOpenGLView::OnEraseBkgnd(CDC* pDC){return TRUE;}void CCMyOpenGLView::OnSize(UINT nType, int cx, int cy){CView::OnSize(nType, cx, cy);GLdouble aspect_ratio;if ( 0 >= cx || 0 >= cy )return;::glViewport(0, 0, cx, cy);aspect_ratio = (GLdouble)cx/(GLdouble)cy;::glMatrixMode(GL_PROJECTION);::glLoadIdentity();::gluPerspective(45.0f, aspect_ratio, .01f, 200.0f);::glMatrixMode(GL_MODELVIEW);::glLoadIdentity();}void CCMyOpenGLView::OnLButtonDown(UINT nFlags, CPoint point) {m_MouseDownPoint=point;SetCapture();CView::OnLButtonDown(nFlags, point);}void CCMyOpenGLView::OnLButtonUp(UINT nFlags, CPoint point) {m_MouseDownPoint=CPoint(0,0);ReleaseCapture();CView::OnLButtonUp(nFlags, point);}void CCMyOpenGLView::OnMouseMove(UINT nFlags, CPoint point) {if (GetCapture()==this){m_xAngle+=(point.y-m_MouseDownPoint.y)/3.6;m_yAngle+=(point.x-m_MouseDownPoint.x)/3.6;InvalidateRect(NULL,FALSE);m_MouseDownPoint=point;};CView::OnMouseMove(nFlags, point);}void CCMyOpenGLView::OnObjectsCone(){m_bTeapot=FALSE;m_bSphere=FALSE;m_bCone=TRUE;InvalidateRect(NULL,FALSE);}四、实验结果五、心得体会通过学习Opengl编程,实现三维立体图形的绘制,了解了设置像素格式,即OpenGL怎样操作像素、创建着色描述表并当前化着色表、删除着色表,响应WM_DESTROY消息响应WM_CREATE消息等等,函数实现了解了Opengl实用工具集,它体现了几乎所有现代窗口系统所共有的功能的函数库。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

《高级计算机图形学》实验报告姓名:学号:班级:【实验报告要求】实验名称:高级计算机图形学室内场景实验目的:掌握使用OpenGL生成真实感复杂对象的方法,进一步熟练掌握构造实体几何表示法、扫描表示法、八叉树法、BSP树法等建模方法。

实验要求:要求利用OpenGL生成一个真实感的复杂对象及其周围场景,并显示观测点变化时的几何变换,要具备在一个纹理复杂的场景中漫游功能。

要求使用到光线跟踪算法、纹理映射技术以及实时绘制技术。

一、实验效果图图1:正面效果图图2:背面效果图图4:背面效果图图4:室内场景细节效果图图5:场景角度转换效果图二、源文件数据代码:共6个文件,其实现代码如下:1、DlgAbout.cpp#include "StdAfx.h"#include "DlgAbout.h"CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX) {CDialog::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()2、FormCommandView.cpp#include "stdafx.h"#include "Tool.h"#include "MainFrm.h"#include "FormCommandView.h"#include "ToolDoc.h"#include "RenderView.h"// Download by #ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CFormCommandViewIMPLEMENT_DYNCREATE(CFormCommandView, CFormView) CFormCommandView::CFormCommandView(): CFormView(CFormCommandView::IDD){//{{AFX_DATA_INIT(CFormCommandView)m_Smooth = FALSE;m_Antialias = FALSE;//}}AFX_DATA_INIT}CFormCommandView::~CFormCommandView(){}void CFormCommandView::DoDataExchange(CDataExchange* pDX) {CFormView::DoDataExchange(pDX);//{{AFX_DATA_MAP(CFormCommandView)DDX_Control(pDX, IDC_FRAME_COLOR_BACK, m_ControlBackColor);DDX_Check(pDX, IDC_CHECK_SMOOTH, m_Smooth);DDX_Check(pDX, IDC_CHECK_ANTIALIAS, m_Antialias);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CFormCommandView, CFormView) //{{AFX_MSG_MAP(CFormCommandView)ON_WM_PAINT()ON_WM_LBUTTONUP()ON_BN_CLICKED(IDC_RADIO_MODEL_1, OnRadioModel1)ON_BN_CLICKED(IDC_RADIO_MODEL_2, OnRadioModel2)ON_BN_CLICKED(IDC_CHECK_SMOOTH, OnCheckSmooth)ON_BN_CLICKED(IDC_CHECK_ANTIALIAS, OnCheckAntialias)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CFormCommandView diagnostics#ifdef _DEBUGvoid CFormCommandView::AssertValid() const{CFormView::AssertValid();}void CFormCommandView::Dump(CDumpContext& dc) const{CFormView::Dump(dc);}CToolDoc* CFormCommandView::GetDocument() // non-debug version is inline{ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CToolDoc)));return (CToolDoc*)m_pDocument;}#endif //_DEBUG// OnPaintvoid CFormCommandView::OnPaint(){// Device context for paintingCPaintDC dc(this);// Options are stored in ApplicationCToolApp *pApp = (CToolApp *)AfxGetApp();CRect rect;// Color backm_ControlBackColor.GetWindowRect(&rect);ScreenToClient(&rect);CBrush BrushBack(pApp->m_OptionColorGlBack);dc.FillRect(&rect,&BrushBack);}// OnLButtonUpvoid CFormCommandView::OnLButtonUp(UINT nFlags,CPoint point){CRect rect;CToolApp *pApp = (CToolApp *)AfxGetApp();// Option back colorm_ControlBackColor.GetWindowRect(&rect);ScreenToClient(&rect);if(rect.PtInRect(point)){CColorDialog dlg(pApp->m_OptionColorGlBack);if(dlg.DoModal()==IDOK){pApp->m_OptionColorGlBack = dlg.GetColor();CRenderView *pView = (CRenderView *)GetRenderView();pView->m_ClearColorRed = (float)GetRValue(pApp->m_OptionColorGlBack) / 255.0f;pView->m_ClearColorGreen = (float)GetGValue(pApp->m_OptionColorGlBack) / 255.0f;pView->m_ClearColorBlue = (float)GetBValue(pApp->m_OptionColorGlBack) / 255.0f;this->InvalidateRect(&rect,FALSE);pView->InvalidateRect(NULL,FALSE);}}CFormView::OnLButtonUp(nFlags, point);}// GetRenderViewCView *CFormCommandView::GetRenderView(){CToolApp *pApp = (CToolApp *)AfxGetApp();CMainFrame *pFrame = (CMainFrame *)pApp->m_pMainWnd;CView *pView = (CView *)pFrame->m_wndSplitter.GetPane(0,1);return pView;}// Modelvoid CFormCommandView::OnRadioModel1(){glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);this->GetRenderView()->InvalidateRect(NULL,FALSE);}void CFormCommandView::OnRadioModel2(){glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);this->GetRenderView()->InvalidateRect(NULL,FALSE);}// OnCheckSmoothvoid CFormCommandView::OnCheckSmooth(){m_Smooth = !m_Smooth;if(m_Smooth)glShadeModel(GL_SMOOTH);elseglShadeModel(GL_FLAT);this->GetRenderView()->InvalidateRect(NULL,FALSE);}// OnCheckAntialias// Toggle antialiased linesvoid CFormCommandView::OnCheckAntialias(){m_Antialias = !m_Antialias;if(m_Antialias){glEnable(GL_LINE_SMOOTH);glEnable(GL_BLEND);glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);glLineWidth(1.5f);}else{glDisable(GL_LINE_SMOOTH);glDisable(GL_BLEND);glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);glLineWidth(1.0f);}GetRenderView()->InvalidateRect(NULL,FALSE);}3、MainFrm.cpp#include "stdafx.h"#include "Tool.h"// Download by #include "MainFrm.h"#include "FormCommandView.h"#include "RenderView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CMainFrameIMPLEMENT_DYNAMIC(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame)ON_WM_CREATE()ON_WM_PAINT()//}}AFX_MSG_MAPEND_MESSAGE_MAP()static UINT indicators[] ={ID_SEPARATOR, // status line indicatorID_INDICATOR_CAPS,ID_INDICATOR_NUM,ID_INDICATOR_SCRL,};// CMainFrame construction/destruction CMainFrame::CMainFrame(){}CMainFrame::~CMainFrame(){}int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {if (CFrameWnd::OnCreate(lpCreateStruct) == -1)return -1;if (!m_wndToolBar.Create(this) ||!m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) {TRACE0("Failed to create toolbar\n");return -1; // fail to create}if (!m_wndStatusBar.Create(this) ||!m_wndStatusBar.SetIndicators(indicators,sizeof(indicators)/sizeof(UINT))){TRACE0("Failed to create status bar\n");return -1; // fail to create}m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC);return 0;}BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) {cs.cx = 600; cs.cy = 500;return CFrameWnd::PreCreateWindow(cs);}// CMainFrame diagnostics#ifdef _DEBUGvoid CMainFrame::AssertValid() const{CFrameWnd::AssertValid();}void CMainFrame::Dump(CDumpContext& dc) const{CFrameWnd::Dump(dc);}#endif //_DEBUG// CMainFrame message handlersvoid CMainFrame::OnPaint(){CPaintDC dc(this); // device context for painting}BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext){if (!m_wndSplitter.CreateStatic(this, 1, 2,WS_CHILD | WS_VISIBLE)){TRACE("Failed to CreateStaticSplitter\n");return FALSE;}// First splitter paneif (!m_wndSplitter.CreateView(0, 0,RUNTIME_CLASS(CRenderView), CSize(600,500), pContext)) {TRACE("Failed to create command view pane\n");return FALSE;}if (!m_wndSplitter.CreateView(0, 1,RUNTIME_CLASS(CFormCommandView), CSize(0,0), pContext)) {TRACE("Failed to create command view pane\n");return FALSE;}// Second splitter panereturn TRUE;}4、RenderView.cpp#include "stdafx.h"#include "Tool.h"#include <string.h>#include <time.h>#include <math.h>#include "ToolDoc.h"#include "RenderView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifextern void Render(void);// This is the holding space for the landscape colours.int WinWidth, WinHeigth;unsigned short int comp = 32; // Scale modifier.unsigned short int temp, texture_mapping = FALSE,land_fogging = TRUE, flat_shading = TRUE; float angle, Near, ex, ey, ez, cx, cy, cz;// Initial eye position and vector of sight.static GLfloat speed = 0;// The following code for mouse routines was contributed.// These are used for the motion function.#define FORWARD 1#define UP 2#define TURNLEFT 3#define LOOKUP 5// Mouse position and button.int oldmx = 0, oldmy = 0, mb;// CRenderViewIMPLEMENT_DYNCREATE(CRenderView, CView)BEGIN_MESSAGE_MAP(CRenderView, CView)//{{AFX_MSG_MAP(CRenderView)ON_WM_DESTROY()ON_WM_SIZE()ON_WM_LBUTTONDOWN()ON_WM_LBUTTONUP()ON_WM_MOUSEMOVE()ON_WM_PAINT()ON_WM_CREATE()//}}AFX_MSG_MAP// Standard printing commandsON_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()// CRenderView construction/destructionCRenderView::CRenderView(){// OpenGLm_hGLContext = NULL;m_GLPixelIndex = 0;// Mousem_LeftButtonDown = FALSE;m_RightButtonDown = FALSE;m_CursorRotation = AfxGetApp()->LoadCursor(IDC_CURSOR_ROTATION); // ColorsCToolApp *pApp = (CToolApp *)AfxGetApp();m_ClearColorRed = GetRValue(pApp->m_OptionColorGlBack); m_ClearColorGreen = GetGValue(pApp->m_OptionColorGlBack); m_ClearColorBlue = GetBValue(pApp->m_OptionColorGlBack); ReadData();WinWidth=1000;WinHeigth=800;LoadAllTexture();InitLookAt();}//============================================// InitGeometry//============================================void CRenderView::InitGeometry(void){GLfloat fogColor[4] = {0.75, 0.75, 1.0, 1.0};speed = 0;srand(224);srand((unsigned)time(NULL));glPixelStorei(GL_UNPACK_ALIGNMENT, 1);glEnable(GL_DEPTH_TEST);glShadeModel(GL_FLAT);glFogi(GL_FOG_MODE, GL_LINEAR);glFogfv(GL_FOG_COLOR, fogColor);glFogf(GL_FOG_DENSITY, 0.8f);glFogf(GL_FOG_START, 400.0f);glFogf(GL_FOG_END, 500.0f);glClearColor(0.75f, 0.75f, 1.0f, 1.0f);}CRenderView::~CRenderView(){FreeAllTexture();freelist();}BOOL CRenderView::PreCreateWindow(CREATESTRUCT& cs){return CView::PreCreateWindow(cs);}// CRenderView drawingvoid CRenderView::OnDraw(CDC* pDC){}BOOL CRenderView::OnPreparePrinting(CPrintInfo* pInfo){return DoPreparePrinting(pInfo);}void CRenderView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) {}void CRenderView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) {}// CRenderView diagnostics#ifdef _DEBUGvoid CRenderView::AssertValid() const{CView::AssertValid();}void CRenderView::Dump(CDumpContext& dc) const{CView::Dump(dc);}CToolDoc* CRenderView::GetDocument() // non-debug version is inline {if (m_pDocument){ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CToolDoc)));return (CToolDoc*)m_pDocument;}else return NULL;}#endif //_DEBUG// Create OpenGL rendering contextint CRenderView::OnCreate(LPCREATESTRUCT lpCreateStruct) {if (CView::OnCreate(lpCreateStruct) == -1)return -1;HWND hWnd = GetSafeHwnd();HDC hDC = ::GetDC(hWnd);if(SetWindowPixelFormat(hDC)==FALSE)return 0;if(CreateViewGLContext(hDC)==FALSE)return 0;// Default modeglPolygonMode(GL_FRONT,GL_FILL);glPolygonMode(GL_BACK,GL_FILL);glShadeModel(GL_FLAT);// light must be disabled// while rendering the terrain// because it has no normal definitionInitGeometry();glEnable(GL_TEXTURE_2D);glDisable(GL_LIGHTING);return 0;}BOOL CRenderView::SetWindowPixelFormat(HDC hDC){PIXELFORMATDESCRIPTOR pixelDesc;pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);pixelDesc.nVersion = 1;pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE;pixelDesc.iPixelType = PFD_TYPE_RGBA;olorBits = 32;pixelDesc.cRedBits = 8;pixelDesc.cRedShift = 16;pixelDesc.cGreenBits = 8;pixelDesc.cGreenShift = 8;pixelDesc.cBlueBits = 8;pixelDesc.cBlueShift = 0;pixelDesc.cAlphaBits = 0;pixelDesc.cAlphaShift = 0;pixelDesc.cAccumBits = 64;pixelDesc.cAccumRedBits = 16;pixelDesc.cAccumGreenBits = 16;pixelDesc.cAccumBlueBits = 16;pixelDesc.cAccumAlphaBits = 0;pixelDesc.cDepthBits = 32;pixelDesc.cStencilBits = 8;pixelDesc.cAuxBuffers = 0;pixelDesc.iLayerType = PFD_MAIN_PLANE;pixelDesc.bReserved = 0;pixelDesc.dwLayerMask = 0;pixelDesc.dwVisibleMask = 0;pixelDesc.dwDamageMask = 0;m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);if(m_GLPixelIndex == 0) // Choose default{m_GLPixelIndex = 1;if(DescribePixelFormat(hDC,m_GLPixelIndex,sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)return FALSE;}if(!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc))return FALSE;return TRUE;}// Create an OpenGL rendering contextBOOL CRenderView::CreateViewGLContext(HDC hDC) {m_hGLContext = wglCreateContext(hDC);if(m_hGLContext==NULL)return FALSE;if(wglMakeCurrent(hDC,m_hGLContext)==FALSE)return FALSE;return TRUE;}// Cleanup every OpenGL rendering contextvoid CRenderView::OnDestroy(){if(wglGetCurrentContext() != NULL)wglMakeCurrent(NULL,NULL);if(m_hGLContext != NULL){wglDeleteContext(m_hGLContext);m_hGLContext = NULL;}CView::OnDestroy();}void CRenderView::OnSize(UINT nType, int cx, int cy) {CView::OnSize(nType, cx, cy);// Set OpenGL perspective, viewport and modeCSize size(cx,cy);double aspect;aspect = (cy == 0) ? (double)size.cx : (double)size.cx/(double)size.cy; glViewport(0, 0, (GLsizei) cx, (GLsizei) cy);glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(60.0, (GLfloat) cx/(GLfloat) cy, 1.0f, 500.0f); glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt (ex, ey, ez, cx, cy, cz, 0.0f, 1.0f, 0.0f);}void CRenderView::OnLButtonDown(UINT nFlags, CPoint point){m_LeftButtonDown = TRUE;m_LeftDownPos = point;CView::OnLButtonDown(nFlags, point);}void CRenderView::OnLButtonUp(UINT nFlags,CPoint point){m_LeftButtonDown = FALSE;CView::OnLButtonUp(nFlags, point);}void CRenderView::OnMouseMove(UINT nFlags, CPoint point){switch(nFlags){case(MK_LBUTTON):MoveEye(FORWARD,(GLfloat)(oldmy-point.y)/5.0f,1);break;case(MK_RBUTTON):MoveEye(TURNLEFT, (GLfloat)(oldmx-point.x), 1);break;}oldmy = point.y;oldmx = point.x;Invalidate(FALSE);CView::OnMouseMove(nFlags, point);}void CRenderView::OnPaint(){// Device context for paintingCPaintDC dc(this);// Useful in singledoc templatesHWND hWnd = GetSafeHwnd();HDC hDC = ::GetDC(hWnd);wglMakeCurrent(hDC,m_hGLContext);glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glClearColor(m_ClearColorRed,m_ClearColorGreen,m_ClearColorBlue,1.0f); glPushMatrix();glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);InitRenderWin();Render();// Double buffersSwapBuffers(hDC);}// Function that moves the eye or turns the angle of sight.// Updates scene if update != 0.void CRenderView::MoveEye(int type, GLfloat amount, int update){GLfloat a;switch(type){case FORWARD:a = sqrt((cx-ex)*(cx-ex)+(cz-ez)*(cz-ez));ex = (amount*(cx-ex)+a*ex) / a;ez = (amount*(cz-ez)+a*ez) / a;cx = (amount*(cx-ex)+a*cx) / a;cz = (amount*(cz-ez)+a*cz) / a;break;case TURNLEFT:cx = (cx-ex)*(float)cos(amount/360.0f) + (cz-ez)*(float)sin(amount/360.0f)+ex;cz = (cz-ez)*(float)cos(amount/360.0f) - (cx-ex)*(float)sin(amount/360.0f)+ez;break;case UP:ey += amount;break;case LOOKUP:cy += amount;break;}if (update){glMatrixMode(GL_MODELVIEW);glLoadIdentity();gluLookAt(ex, ey, ez, cx, cy, cz, 0.0f,1.0f,0.0f);}}TEXTURE_2D **TextureList;OBJECT *ObjectList; /* ObjectList[0]:isolated surfaces*/INT4S ObjectNum;char gEnergyFile[30];char sLookAtFN[100];char ImageName[30];void CRenderView::ReadData(){int i,j,l;FILE *fp;char stemp[100];POINT3D *plist;INT4U nAllVertexNum;INT4U *pchlist;strcpy(gEnergyFile,"room.ed");fp = fopen( gEnergyFile, "r" );if ( fp == NULL ){printf( "\n Can not open energy data file:%s\n", gEnergyFile);exit(0);}fseek( fp, 0, SEEK_SET);/****** read texture list ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"texnum" ) != 0) fscanf( fp, "%s", stemp); fscanf( fp, "%d", &texnum );TextureList = (TEXTURE_2D **)malloc( sizeof(TEXTURE_2D)*(texnum+1)); for(i=1; i<=texnum; i++){TextureList[i] = (TEXTURE_2D *)malloc( sizeof(TEXTURE_2D));fscanf( fp, "%s%s", TextureList[i]->fname, stemp );if ( strcmp( stemp,"REPEAT_TEXTURE" ) == 0)TextureList[i]->type = 1;else if ( strcmp( stemp,"CLAMP_TEXTURE" ) == 0)TextureList[i]->type = 0;}/****** Read object list ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"ObjectNum" ) != 0) fscanf(fp,"%s",stemp); fscanf( fp, "%ld", &ObjectNum);ObjectList = (OBJECT *)malloc( sizeof(OBJECT ) * ObjectNum);for(i = 0; i < ObjectNum; i ++ ){f scanf( fp, "%s", stemp);w hile( strcmp( stemp,"SurfaceNum" ) != 0) fscanf(fp,"%s",stemp);f scanf( fp, "%ld", &(ObjectList[i].SurfNum) );ObjectList[i].surflist = (SURFACE *)malloc( sizeof(SURFACE) * ObjectList[i].SurfNum);for(j = 0; j < ObjectList[i].SurfNum; j ++ ){/****** Read surface infor ******/fscanf( fp, "%s", stemp);while( strcmp( stemp,"TextureId" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].texId) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"pointnum" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].pointn) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"triangle" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].triangle) );fscanf( fp, "%s", stemp);while( strcmp( stemp,"quadrangle" ) != 0) fscanf(fp,"%s",stemp);fscanf( fp, "%d", &(ObjectList[i].surflist[j].quadric) );/****** Read point list ******/ObjectList[i].surflist[j].pointlist = (POINT3D*)malloc(sizeof(POINT3D) *ObjectList[i].surflist[j].pointn);plist = ObjectList[i].surflist[j].pointlist;for( l = 0; l < ObjectList[i].surflist[j].pointn ; l ++ )fscanf( fp, "%f%f%f%f%f%f%f%f",&(plist[l].r), &(plist[l].g), &(plist[l].b),&(plist[l].u), &(plist[l].v),&(plist[l].x), &(plist[l].y), &(plist[l].z) );/****** Read patchlist ******/nAllVertexNum = ObjectList[i].surflist[j].triangle * 3 +ObjectList[i].surflist[j].quadric *4 ;ObjectList[i].surflist[j].patchlist = (INT4U *)malloc( sizeof(INT4U) * nAllVertexNum);pchlist = ObjectList[i].surflist[j].patchlist;for( l = 0; l < nAllVertexNum; l ++ )fscanf( fp, "%ld", &(pchlist[l]) );}}fclose(fp);}void CRenderView::InitLookAt(){FILE *fp;strcpy(sLookAtFN,"room.lk");fp = fopen(sLookAtFN, "rb");if (fp == NULL){ex = ey = ez =1.0f;cx = cy = cz =0.0f;Near = 0.1f;angle = 30.0f;}else fscanf(fp, "%f%f%f%f%f%f%f%f", &angle, &Near, &ex, &ey, &ez, &cx, &cy, &cz);fclose(fp);}void CRenderView::InitRenderWin(){glShadeModel ( GL_SMOOTH );glDepthFunc ( GL_LESS );glEnable ( GL_DEPTH_TEST );glMatrixMode ( GL_PROJECTION );glLoadIdentity();glMatrixMode ( GL_MODELVIEW );glLoadIdentity();gluPerspective ( angle, (float)WinWidth/(float)WinHeigth, Near, 1000000000.0); gluLookAt( ex, ey, ez, cx, cy, cz, 0.0, 1.0, 0.0);}void CRenderView::Render(void){int i, j, k, l, m, TexIndex;POINT3D *plist;INT4U *pchlist;glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);for(i = 0; i < ObjectNum; i ++ )for(j = 0; j < ObjectList[i].SurfNum; j ++ ){TexIndex = ObjectList[i].surflist[j].texId;if( TexIndex > 0 )InitTex( TexIndex );plist = ObjectList[i].surflist[j].pointlist;pchlist = ObjectList[i].surflist[j].patchlist;l = 0;for ( k = 0; k < ObjectList[i].surflist[j].triangle; k ++){glBegin( GL_TRIANGLES );for( m = 0; m < 3; m ++ ){glColor3f ( plist[pchlist[l]].r,plist[pchlist[l]].g,plist[pchlist[l]].b );glTexCoord2f( plist[pchlist[l]].u,plist[pchlist[l]].v );glVertex3f( plist[pchlist[l]].x,plist[pchlist[l]].y,plist[pchlist[l]].z );l ++;}/* m */glEnd();}/* k */for ( k = 0; k < ObjectList[i].surflist[j].quadric; k ++){glBegin( GL_QUADS );for( m = 0; m < 4; m ++ ){glColor3f ( plist[pchlist[l]].r,plist[pchlist[l]].g,plist[pchlist[l]].b );glTexCoord2f( plist[pchlist[l]].u,plist[pchlist[l]].v );glVertex3f( plist[pchlist[l]].x,plist[pchlist[l]].y,plist[pchlist[l]].z );l ++;}/* m */glEnd();}/* k */glFlush();CloseTex();}}void CRenderView::freelist(){int i, j;for( i=0; i<ObjectNum; i++){for( j=0; j<ObjectList[i].SurfNum; j++){free(ObjectList[i].surflist[j].pointlist);free(ObjectList[i].surflist[j].patchlist);}free( ObjectList[i].surflist );}free(ObjectList);for(i=1; i<=texnum; i++)free(TextureList[i]);free(TextureList);}extern TEXTURE_2D **TextureList;/********************************//* function : OpenTexImage *//********************************/unsigned char *CRenderView::OpenTexImage( INT2U TexIndex, INT2U *rslx, INT2U *rsly ){unsigned char *image;FILE *fp;INT2U srcx, srcy;INT4U i, j;char ImageName[30];unsigned char *SImageData;int rc;int width, height;strcpy( ImageName, TextureList[TexIndex]->fname);/* load a image */fp = fopen(ImageName,"rb");if(!fp) return 0;fseek(fp,18L,0);rc=fread(&width,sizeof(long),1,fp);rc=fread(&height,sizeof(long),1,fp);*rslx=srcx=width; *rsly=srcy=height;fseek(fp,54L,0);image = (unsigned char *)malloc(width*height*3);rc=fread(image,width*height*3,1,fp);fclose(fp);SImageData = (unsigned char *)malloc(srcx*srcy*3);for(i=0; i<srcx; i++) {for(j=0; j<srcy; j++) {(unsigned char)*(SImageData+i*srcx*3+j*3+0) = (unsigned char)*(image+i*srcx*3+j*3+2);(unsigned char)*(SImageData+i*srcx*3+j*3+1) = (unsigned char)*(image+i*srcx*3+j*3+1);(unsigned char)*(SImageData+i*srcx*3+j*3+2) = (unsigned char)*(image+i*srcx*3+j*3+0);}}free(image);printf("%s : %ld=%ld\n", ImageName, srcx*srcy*3,i*j*3);return( SImageData );}/********************************//* function : InitTex *//********************************/void CRenderView::InitTex( int TexIndex ){INT2U TextType;unsigned char *ImageData;static int OldIndex = -1;if(TexIndex<=0) return;if(TexIndex == OldIndex){glEnable(GL_TEXTURE_2D);return;}ImageData = ImageDatas[TexIndex-1];TextType = TextureList[TexIndex]->type;glPixelStorei(GL_UNPACK_ALIGNMENT, 1);glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);if( TextType == CLAMP_TEXTURE ){glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);}else{glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);}glTexImage2D( GL_TEXTURE_2D, 0, 3, rslxs[TexIndex-1], rslys[TexIndex-1],0,GL_RGB, GL_UNSIGNED_BYTE, ImageData );glEnable(GL_TEXTURE_2D);OldIndex = TexIndex;}/********************************//* function : CloseTex *//********************************/void CRenderView::CloseTex(){glDisable(GL_TEXTURE_2D);}void CRenderView::LoadAllTexture(){int i;for (i=0; i <texnum ; i++)ImageDatas[i] = OpenTexImage( i+1, &rslxs[i], &rslys[i] );}void CRenderView::FreeAllTexture(){int i;for (i=0; i <texnum ; i++)free(ImageDatas[i]);}5、StdAfx.cpp#include "stdafx.h"6、Tool.cpp#include "stdafx.h"#include "Tool.h"#include "DlgAbout.h"#include "MainFrm.h"#include "ToolDoc.h"#include "RenderView.h"// Download by #ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// CToolAppCToolDoc *MyDocument;BEGIN_MESSAGE_MAP(CToolApp, CWinApp)//{{AFX_MSG_MAP(CToolApp)ON_COMMAND(ID_APP_ABOUT, OnAppAbout)//}}AFX_MSG_MAP// Standard file based document commands// Standard print setup commandON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP()// CToolApp constructionCToolApp::CToolApp(){// Optionsm_OptionColorGlBack = RGB(0,0,255);}// The one and only CToolApp objectCToolApp theApp;// CToolApp initializationBOOL CToolApp::InitInstance(){AfxEnableControlContainer();// Standard initialization// If you are not using these features and wish to reduce the size// of your final executable, you should remove from the following// the specific initialization routines you do not need.#ifdef _AFXDLLEnable3dControls(); // Call this when using MFC in a shared DLL#elseEnable3dControlsStatic(); // Call this when linking to MFC statically#endif// Change the registry key under which our settings are stored.// You should modify this string to be something appropriate// such as the name of your company or organization.SetRegistryKey(_T("3D Toolbox"));LoadStdProfileSettings(10); // Load standard INI file options (including MRU)// Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views.CSingleDocTemplate* pDocTemplate;// create main SDI Frame windowCMainFrame* pMainFrame = new CMainFrame;if (!pMainFrame->LoadFrame(IDR_MAINFRAME))return FALSE;m_pMainWnd = pMainFrame;pDocTemplate = new CSingleDocTemplate(IDR_MODELTYPE,RUNTIME_CLASS(CToolDoc),RUNTIME_CLASS(CMainFrame),RUNTIME_CLASS(CRenderView));AddDocTemplate(pDocTemplate);// The main window has been initialized, so show and update it.//pMainFrame->ShowWindow(SW_SHOWMAXIMIZED);pMainFrame->ShowWindow(SW_SHOW);pMainFrame->UpdateWindow();return TRUE;}// App command to run the dialogvoid CToolApp::OnAppAbout(){CAboutDlg aboutDlg;aboutDlg.DoModal();}6、ToolDoc.cpp#include "stdafx.h"#include "math.h"#include "Tool.h"#include "ToolDoc.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifIMPLEMENT_DYNCREATE(CToolDoc, CDocument)BEGIN_MESSAGE_MAP(CToolDoc, CDocument)//{{AFX_MSG_MAP(CToolDoc)// NOTE - the ClassWizard will add and remove mapping macros here.// DO NOT EDIT what you see in these blocks of generated code!//}}AFX_MSG_MAPEND_MESSAGE_MAP()。

相关文档
最新文档