基于openGL的三阶魔方程序代码.docx_第1页
基于openGL的三阶魔方程序代码.docx_第2页
基于openGL的三阶魔方程序代码.docx_第3页
基于openGL的三阶魔方程序代码.docx_第4页
基于openGL的三阶魔方程序代码.docx_第5页
已阅读5页,还剩35页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

/*Magic2D.cpp文件:可以播放爱你一万年歌曲,需要在工程文件夹中新建文件夹“sound”并存放“爱你一万年.wav”文件需要在Data文件夹中上传y2.bmp到y7.bmp的图片,当然也可以在程序中相应部分自己修改该程序有两个文件,Magic2D.cpp和MoFang.cpp,可以实现三阶魔方任意层面的旋转并能使魔方在界面来回移动反弹,具体的建工程的步骤就不说了,祝大家好运*/#include MoFang.h#include /提供与多媒体有关的接口#pragma comment(lib, WINMM.LIB) /导入winmm.lib库,实现对多媒体编程的支持HDChDC=NULL;/ Private GDI Device ContextHGLRChRC=NULL;/ Permanent Rendering ContextHWNDhWnd=NULL;/ Holds Our Window Handleboolkeys256;/ Array Used For The Keyboard RoutineHINSTANCEhInstance;/ Holds The Instance Of The Applicationboolactive=TRUE;/ Window Active Flag Set To TRUE By Defaultboolfullscreen=TRUE;/ Fullscreen Flag Set To Fullscreen Mode By DefaultGLfloatxrot;/ X Rotation ( NEW )GLfloatyrot;/ Y Rotation ( NEW )GLfloatzrot;/ Z Rotation ( NEW )GLfloat RX=0;GLfloat RY=0;GLuinttexture7;/ Storage For One Texture ( NEW )GLboolean b_RX,b_RY;GLfloat turn_x=1,turn_y=1;LRESULTCALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);/ CALLBACK代表回调函数 Declaration For WndProc,函数声明,监听windowsAUX_RGBImageRec *LoadBMP(char *Filename)/ Loads A Bitmap ImageFILE *File=NULL;/ File Handleif (!Filename)/ Make Sure A Filename Was Givenreturn NULL;/ If Not Return NULLFile=fopen(Filename,r);/ Check To See If The File Existsif (File)/ Does The File Exist?fclose(File);/ Close The Handlereturn auxDIBImageLoad(Filename);/ Load The Bitmap And Return A Pointerreturn NULL;/ If Load Failed Return NULLvoid loadsound()PlaySound(sound爱你一万年.wav,NULL,SND_LOOP|SND_ASYNC|SND_FILENAME);int LoadGLTextures()/ Load Bitmaps And Convert To Texturesint Status=FALSE;/ Status IndicatorAUX_RGBImageRec *TextureImage1;/ Create Storage Space For The Texturememset(TextureImage,0,sizeof(void *)*1); / Set The Pointer To NULL/ Load The Bitmap, Check For Errors, If Bitmaps Not Found Quitif (TextureImage0=LoadBMP(Data/NeHe.bmp)Status=TRUE;/ Set The Status To TRUEglGenTextures(1, &texture0);/ Create The Texture/ Typical Texture Generation Using Data From The BitmapglBindTexture(GL_TEXTURE_2D, texture0);glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage0-sizeX, TextureImage0-sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage0-data);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);if (TextureImage0)/ If Texture Existsif (TextureImage0-data)/ If Texture Image Existsfree(TextureImage0-data);/ Free The Texture Image Memoryfree(TextureImage0);/ Free The Image Structurereturn Status;/ Return The Statusint LoadGLTextures(char *file,int index)/ Load Bitmaps And Convert To Texturesint Status=FALSE;/ Status IndicatorAUX_RGBImageRec *TextureImage1;/ 创建纹理储存空间memset(TextureImage,0,sizeof(void *)*1); / Set The Pointer To NULL/ Load The Bitmap, Check For Errors, If Bitmaps Not Found Quitif (TextureImage0=LoadBMP(file)Status=TRUE;/ Set The Status To TRUEglGenTextures(1, &textureindex);/ 生成纹理/ Typical Texture Generation Using Data From The BitmapglBindTexture(GL_TEXTURE_2D, textureindex); /glBindTexture函数实现了将调用glGenTextures函数生成的纹理的名字绑定到对应的目标纹理上。glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage0-sizeX, TextureImage0-sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage0-data);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);if (TextureImage0)/ If Texture Existsif (TextureImage0-data)/ If Texture Image Existsfree(TextureImage0-data);/ Free The Texture Image Memoryfree(TextureImage0);/ Free The Image Structurereturn Status;/ Return The StatusGLvoid ReSizeGLScene(GLsizei width, GLsizei height)/ Resize And Initialize The GL Windowif (height=0)/ Prevent A Divide By Zero Byheight=1;/ Making Height Equal OneglViewport(0,0,width,height);/ 按照指定的高和宽显示图像Reset The Current ViewportglMatrixMode(GL_PROJECTION);/ Select The Projection MatrixglLoadIdentity();/ Reset The Projection Matrix/ Calculate The Aspect Ratio Of The WindowgluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); /使图像显示时自身比例相同,不会产生扭曲,图像在z轴方向上的坐标必须介于-0.1到-100之间,不然显示不出来 glMatrixMode(GL_MODELVIEW);/ Select The Modelview MatrixglLoadIdentity();/ 使原点重新回到屏幕中心Reset The Modelview Matrixint InitGL(GLvoid)/ All Setup For OpenGL Goes Hereif (!LoadGLTextures(Data/y2.bmp,1)/ 生成纹理texture1return FALSE;/ If Texture Didnt Load Return FALSEif (!LoadGLTextures(Data/y3.bmp,2)/ Jump To Texture Loading Routine ( NEW )return FALSE;/ If Texture Didnt Load Return FALSEif (!LoadGLTextures(Data/y4.bmp,3)/ Jump To Texture Loading Routine ( NEW )return FALSE;/ If Texture Didnt Load Return FALSEif (!LoadGLTextures(Data/y5.bmp,4)/ Jump To Texture Loading Routine ( NEW )return FALSE;/ If Texture Didnt Load Return FALSEif (!LoadGLTextures(Data/y6.bmp,5)/ Jump To Texture Loading Routine ( NEW )return FALSE;/ If Texture Didnt Load Return FALSEif (!LoadGLTextures(Data/y7.bmp,6)/ Jump To Texture Loading Routine ( NEW )return FALSE;/ If Texture Didnt Load Return FALSEglEnable(GL_TEXTURE_2D);/ Enable Texture Mapping ( NEW )glShadeModel(GL_SMOOTH);/ Enable Smooth Shading,启用阴影平滑glClearColor(0.5f, 0.0f, 0.0f, 0.5f);/ Black Background,背景设为黑色glClearDepth(1.0f);/ Depth Buffer Setup,设置深度缓存glEnable(GL_DEPTH_TEST);/ Enables Depth TestingglDepthFunc(GL_LEQUAL);/ The Type Of Depth Testing To DoglHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);/ Really Nice Perspective Calculationsloadsound();return TRUE;/ Initialization Went OK void DrawObject(int ID) /画出一个 立方体,六个面,贴图stPoint *CubePoint = CubeID.CubePoint;/ Front Face glBindTexture(GL_TEXTURE_2D, texture1); glBegin(GL_QUADS); /发布四边形绘图指令glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint0.p);/glTexCoord2f指定平面纹理坐标,glVertex3fv是四边形的顶点坐标glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint1.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint2.p);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint3.p);glEnd();/ Back FaceglBindTexture(GL_TEXTURE_2D, texture2); glBegin(GL_QUADS);glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint4.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint5.p);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint6.p);glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint7.p);glEnd();/ Top FaceglBindTexture(GL_TEXTURE_2D, texture3); glBegin(GL_QUADS);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint5.p);glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint3.p);glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint2.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint6.p);glEnd();/ Bottom FaceglBindTexture(GL_TEXTURE_2D, texture4); glBegin(GL_QUADS);glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint4.p);glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint7.p);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint1.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint0.p);glEnd();/ Right faceglBindTexture(GL_TEXTURE_2D, texture5); glBegin(GL_QUADS);glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint7.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint6.p);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint2.p);glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint1.p);glEnd();/ Left FaceglBindTexture(GL_TEXTURE_2D, texture6); glBegin(GL_QUADS);glTexCoord2f(0.0f, 0.0f); glVertex3fv( CubePoint4.p);glTexCoord2f(1.0f, 0.0f); glVertex3fv( CubePoint0.p);glTexCoord2f(1.0f, 1.0f); glVertex3fv( CubePoint3.p);glTexCoord2f(0.0f, 1.0f); glVertex3fv( CubePoint5.p);glEnd(); int DrawGLScene(GLvoid)/ Heres Where We Do All The Drawing int i;glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);/ Clear The Screen And The Depth BufferglLoadIdentity();/ Reset The ViewglTranslatef(0.0f,0.0f,-12.0f); / glTranslatef为坐标系原点平移函数,相当于相对平面向里面平移12, glTranslatef(RX,0.0f,0.0f); glTranslatef(0.0,RY,0.0); glRotatef(xrot,1.0f,0.0f,0.0f); / 整体的旋转靠库函数来实现,glRotatef为坐标系旋转函数 glRotatef(yrot,0.0f,1.0f,0.0f); glRotatef(zrot,0.0f,0.0f,1.0f); for (i=0;i27;i+) DrawObject(i);xrot+=0.2f; yrot+=0.2f; zrot+=0.2f; /控制魔方整体的旋转return TRUE;/ Keep GoingGLvoid KillGLWindow(GLvoid)/ Properly Kill The Windowif (fullscreen)/ Are We In Fullscreen Mode?ChangeDisplaySettings(NULL,0);/ If So Switch Back To The DesktopShowCursor(TRUE);/ Show Mouse Pointerif (hRC)/ Do We Have A Rendering Context?if (!wglMakeCurrent(NULL,NULL)/ Are We Able To Release The DC And RC Contexts?MessageBox(NULL,Release Of DC And RC Failed.,SHUTDOWN ERROR,MB_OK | MB_ICONINFORMATION);if (!wglDeleteContext(hRC)/ Are We Able To Delete The RC?MessageBox(NULL,Release Rendering Context Failed.,SHUTDOWN ERROR,MB_OK | MB_ICONINFORMATION);hRC=NULL;/ Set RC To NULLif (hDC & !ReleaseDC(hWnd,hDC)/ Are We Able To Release The DCMessageBox(NULL,Release Device Context Failed.,SHUTDOWN ERROR,MB_OK | MB_ICONINFORMATION);hDC=NULL;/ Set DC To NULLif (hWnd & !DestroyWindow(hWnd)/ Are We Able To Destroy The Window?MessageBox(NULL,Could Not Release hWnd.,SHUTDOWN ERROR,MB_OK | MB_ICONINFORMATION);hWnd=NULL;/ Set hWnd To NULLif (!UnregisterClass(OpenGL,hInstance)/ Are We Able To Unregister ClassMessageBox(NULL,Could Not Unregister Class.,SHUTDOWN ERROR,MB_OK | MB_ICONINFORMATION);hInstance=NULL;/ Set hInstance To NULL/*This Code Creates Our OpenGL Window. Parameters Are:* *title- Title To Appear At The Top Of The Window* *width- Width Of The GL Window Or Fullscreen Mode* *height- Height Of The GL Window Or Fullscreen Mode* *bits- Number Of Bits To Use For Color (8/16/24/32)* *fullscreenflag- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)*/ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)GLuintPixelFormat;/ Holds The Results After Searching For A MatchWNDCLASSwc;/ Windows Class StructureDWORDdwExStyle;/ Window Extended StyleDWORDdwStyle;/ Window StyleRECTWindowRect;/ Grabs Rectangle Upper Left / Lower Right ValuesWindowRect.left=(long)0;/ Set Left Value To 0WindowRect.right=(long)width;/ Set Right Value To Requested WidthWindowRect.top=(long)0;/ Set Top Value To 0WindowRect.bottom=(long)height;/ Set Bottom Value To Requested Heightfullscreen=fullscreenflag;/ Set The Global Fullscreen FlaghInstance= GetModuleHandle(NULL);/ Grab An Instance For Our Windowwc.style= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;/ Redraw On Size, And Own DC For Window.wc.lpfnWndProc= (WNDPROC) WndProc;/ WndProc Handles Messageswc.cbClsExtra= 0;/ No Extra Window Datawc.cbWndExtra= 0;/ No Extra Window Datawc.hInstance= hInstance;/ Set The Instancewc.hIcon= LoadIcon(NULL, IDI_WINLOGO);/ Load The Default Iconwc.hCursor= LoadCursor(NULL, IDC_ARROW);/ Load The Arrow Pointerwc.hbrBackground= NULL;/ No Background Required For GLwc.lpszMenuName= NULL;/ We Dont Want A Menuwc.lpszClassName= OpenGL;/ Set The Class Nameif (!RegisterClass(&wc)/ Attempt To Register The Window ClassMessageBox(NULL,Failed To Register The Window Class.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEif (fullscreen)/ Attempt Fullscreen Mode?DEVMODE dmScreenSettings;/ Device Modememset(&dmScreenSettings,0,sizeof(dmScreenSettings);/ Makes Sure Memorys CleareddmScreenSettings.dmSize=sizeof(dmScreenSettings);/ Size Of The Devmode StructuredmScreenSettings.dmPelsWidth= width;/ Selected Screen WidthdmScreenSettings.dmPelsHeight= height;/ Selected Screen HeightdmScreenSettings.dmBitsPerPel= bits;/ Selected Bits Per PixeldmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;/ Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)/ If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.if (MessageBox(NULL,The Requested Fullscreen Mode Is Not Supported BynYour Video Card. Use Windowed Mode Instead?,NeHe GL,MB_YESNO|MB_ICONEXCLAMATION)=IDYES)fullscreen=FALSE;/ Windowed Mode Selected. Fullscreen = FALSEelse/ Pop Up A Message Box Letting User Know The Program Is Closing.MessageBox(NULL,Program Will Now Close.,ERROR,MB_OK|MB_ICONSTOP);return FALSE;/ Return FALSEif (fullscreen)/ Are We Still In Fullscreen Mode?dwExStyle=WS_EX_APPWINDOW;/ Window Extended StyledwStyle=WS_POPUP;/ Windows StyleShowCursor(FALSE);/ Hide Mouse Pointer全屏则隐去光标elsedwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;/ Window Extended StyledwStyle=WS_OVERLAPPEDWINDOW;/ Windows StyleAdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);/ 不管全屏或者非全屏,都将屏幕调整到要求的大小/ Create The Windowif (!(hWnd=CreateWindowEx(dwExStyle,/ Extended Style For The WindowOpenGL,/ Class Nametitle,/ Window TitledwStyle |/ Defined Window StyleWS_CLIPSIBLINGS |/ Required Window StyleWS_CLIPCHILDREN,/ Required Window Style0, 0,/ Window PositionWindowRect.right-WindowRect.left,/ Calculate Window WidthWindowRect.bottom-WindowRect.top,/ Calculate Window HeightNULL,/ No Parent WindowNULL,/ No MenuhInstance,/ InstanceNULL)/ Dont Pass Anything To WM_CREATEKillGLWindow();/ Reset The DisplayMessageBox(NULL,Window Creation Error.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEstaticPIXELFORMATDESCRIPTOR pfd=/ pfd Tells Windows How We Want Things To Besizeof(PIXELFORMATDESCRIPTOR),/ Size Of This Pixel Format Descriptor1,/ Version NumberPFD_DRAW_TO_WINDOW |/ Format Must Support WindowPFD_SUPPORT_OPENGL |/ Format Must Support OpenGLPFD_DOUBLEBUFFER,/ Must Support Double BufferingPFD_TYPE_RGBA,/ Request An RGBA Formatbits,/ Select Our Color Depth0, 0, 0, 0, 0, 0,/ Color Bits Ignored0,/ No Alpha Buffer0,/ Shift Bit Ignored0,/ No Accumulation Buffer0, 0, 0, 0,/ Accumulation Bits Ignored16,/ 16Bit Z-Buffer (Depth Buffer) 0,/ No Stencil Buffer0,/ No Auxiliary BufferPFD_MAIN_PLANE,/ Main Drawing Layer0,/ Reserved0, 0, 0/ Layer Masks Ignored;if (!(hDC=GetDC(hWnd)/ Did We Get A Device Context?KillGLWindow();/ Reset The DisplayMessageBox(NULL,Cant Create A GL Device Context.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEif (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)/ Did Windows Find A Matching Pixel Format?KillGLWindow();/ Reset The DisplayMessageBox(NULL,Cant Find A Suitable PixelFormat.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEif(!SetPixelFormat(hDC,PixelFormat,&pfd)/ Are We Able To Set The Pixel Format?KillGLWindow();/ Reset The DisplayMessageBox(NULL,Cant Set The PixelFormat.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEif (!(hRC=wglCreateContext(hDC)/ Are We Able To Get A Rendering Context?KillGLWindow();/ Reset The DisplayMessageBox(NULL,Cant Create A GL Rendering Context.,ERROR,MB_OK|MB_ICONEXCLAMATION);return FALSE;/ Return FALSEif(!wglMakeCurrent(hDC,hRC)/ Try To Activate T

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论