Opengl 导入3Dmax制作的.3ds模型 并显示出来

转载:http://blog.csdn.net/cq361106306/article/details/41876541

由于opengl并没有原始支持这种模型,所以导入是件麻烦事,但是又有很多的模型是这个格式的,这次在做图形学大作业的时候,特别想用到。

开始以为很简单,就几十行代码就能解决,但是翻了好多列子,都从解析文件格式,到分离顶点,纹理格式等等,非常复杂的工作,最后才能显示模型。

因此我把网上的列子总结成了2个文件,一个头文件和一个CPP文件,文件在最后面贴出来

叫做CLoad3DS.cpp   CLoad3DS.h

下面用nehe最简单的一个列子来展现如何导入,非常的简单 不需要管这个两个文件里面具体复杂的操作是啥,直接当成库吧。

这个模型导入进去 我把模型的包围盒的代码踢出掉了,只能显示出来看,不能某个部分运动等更具体的操作。

先看效果吧

Opengl 导入3Dmax制作的.3ds模型 并显示出来_第1张图片

1. 首先建一个win32程序

这里直接拿nehe的第6课  就是那个立方体贴图的列子

lesson6.cpp

[cpp] view plain copy
print ?
  1. / 
  2.        This Code Was Created By Jeff Molofee 2000 
  3.        A HUGE Thanks To Fredric Echols For Cleaning Up 
  4.        And Optimizing The Base Code, Making It More Flexible! 
  5.        If You’ve Found This Code Useful, Please Let Me Know. 
  6.        Visit My Site At nehe.gamedev.net 
  7.  /  
  8.   
  9. #include       // Header File For Windows  
  10. #include             // Header File For Standard Input/Output  
  11. #include             // Header File For The OpenGL32 Library  
  12. #include            // Header File For The GLu32 Library  
  13. #include      // Header File For The Glaux Library  
  14. #include “CLoad3DS.h”  
  15. HDC         hDC=NULL;       // Private GDI Device Context  
  16. HGLRC       hRC=NULL;       // Permanent Rendering Context  
  17. HWND        hWnd=NULL;      // Holds Our Window Handle  
  18. HINSTANCE   hInstance;      // Holds The Instance Of The Application  
  19.   
  20. bool    keys[256];          // Array Used For The Keyboard Routine  
  21. bool    active=TRUE;        // Window Active Flag Set To TRUE By Default  
  22. bool    fullscreen=TRUE;    // Fullscreen Flag Set To Fullscreen Mode By Default  
  23.   
  24. GLfloat xrot;               // X Rotation ( NEW )  
  25. GLfloat yrot;               // Y Rotation ( NEW )  
  26. GLfloat zrot;               // Z Rotation ( NEW )  
  27.   
  28. GLuint  texture[1];         // Storage For One Texture ( NEW )  
  29.   
  30. CLoad3DS *gothicLoader=new(CLoad3DS);  
  31. t3DModel gothicModel;  
  32. //BoundingBox gothicBoundingBox;  
  33. float gothicTrans[10] = {   
  34.     0, 0 , -30 ,     //表示在世界矩阵的位置  
  35.         0.2 , 0.2 , 0.2 ,      //表示xyz放大倍数  
  36.         0 , 0 , 0 , 0  //表示旋转  
  37. };  
  38.   
  39. LRESULT CALLBACK WndProc(HWNDUINTWPARAMLPARAM);   // Declaration For WndProc  
  40.   
  41. AUX_RGBImageRec *LoadBMP(char *Filename)                // Loads A Bitmap Image  
  42. {  
  43.     FILE *File=NULL;                                    // File Handle  
  44.   
  45.     if (!Filename)                                      // Make Sure A Filename Was Given  
  46.     {  
  47.         return NULL;                                    // If Not Return NULL  
  48.     }  
  49.   
  50.     File=fopen(Filename,”r”);                           // Check To See If The File Exists  
  51.   
  52.     if (File)                                           // Does The File Exist?  
  53.     {  
  54.         fclose(File);                                   // Close The Handle  
  55.         return auxDIBImageLoad(Filename);               // Load The Bitmap And Return A Pointer  
  56.     }  
  57.   
  58.     return NULL;                                        // If Load Failed Return NULL  
  59. }  
  60.   
  61. int LoadGLTextures()                                    // Load Bitmaps And Convert To Textures  
  62. {  
  63.     int Status=FALSE;                                   // Status Indicator  
  64.   
  65.     AUX_RGBImageRec *TextureImage[1];                   // Create Storage Space For The Texture  
  66.   
  67.     memset(TextureImage,0,sizeof(void )1);            // Set The Pointer To NULL  
  68.   
  69.     // Load The Bitmap, Check For Errors, If Bitmap’s Not Found Quit  
  70.     if (TextureImage[0]=LoadBMP(“Data/NeHe.bmp”))  
  71.     {  
  72.         Status=TRUE;                                    // Set The Status To TRUE  
  73.   
  74.         glGenTextures(1, &texture[0]);                  // Create The Texture  
  75.   
  76.         // Typical Texture Generation Using Data From The Bitmap  
  77.         glBindTexture(GL_TEXTURE_2D, texture[0]);  
  78.         glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);  
  79.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);  
  80.         glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);  
  81.     }  
  82.   
  83.     if (TextureImage[0])                                    // If Texture Exists  
  84.     {  
  85.         if (TextureImage[0]->data)                           // If Texture Image Exists  
  86.         {  
  87.             free(TextureImage[0]->data);                 // Free The Texture Image Memory  
  88.         }  
  89.   
  90.         free(TextureImage[0]);                              // Free The Image Structure  
  91.     }  
  92.   
  93.     return Status;                                      // Return The Status  
  94. }  
  95.   
  96. GLvoid ReSizeGLScene(GLsizei width, GLsizei height)     // Resize And Initialize The GL Window  
  97. {  
  98.     if (height==0)                                      // Prevent A Divide By Zero By  
  99.     {  
  100.         height=1;                                       // Making Height Equal One  
  101.     }  
  102.   
  103.     glViewport(0,0,width,height);                       // Reset The Current Viewport  
  104.   
  105.     glMatrixMode(GL_PROJECTION);                        // Select The Projection Matrix  
  106.     glLoadIdentity();                                   // Reset The Projection Matrix  
  107.   
  108.     // Calculate The Aspect Ratio Of The Window  
  109.     gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);  
  110.   
  111.     glMatrixMode(GL_MODELVIEW);                         // Select The Modelview Matrix  
  112.     glLoadIdentity();                                   // Reset The Modelview Matrix  
  113. }  
  114.   
  115. int InitGL(GLvoid)                                      // All Setup For OpenGL Goes Here  
  116. {  
  117.     if (!LoadGLTextures())                              // Jump To Texture Loading Routine ( NEW )  
  118.     {  
  119.         return FALSE;                                   // If Texture Didn’t Load Return FALSE  
  120.     }  
  121.   
  122.     glEnable(GL_TEXTURE_2D);                            // Enable Texture Mapping ( NEW )  
  123.     glShadeModel(GL_SMOOTH);                            // Enable Smooth Shading  
  124.     glClearColor(0.0f, 0.0f, 0.0f, 0.5f);               // Black Background  
  125.     glClearDepth(1.0f);                                 // Depth Buffer Setup  
  126.     glEnable(GL_DEPTH_TEST);                            // Enables Depth Testing  
  127.     glDepthFunc(GL_LEQUAL);                             // The Type Of Depth Testing To Do  
  128.     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Really Nice Perspective Calculations  
  129.       
  130.     //导入模型 模型的文件夹尽量这样设置   
  131.     //然后模型贴图 装在Data/pic里面  一定要跟前面截图的文件夹名字一样,想改得去CLoad3DS文件里面改  
  132.     gothicLoader->Import3DS(&gothicModel, ”Data/3ds/GUTEMB_L.3DS”);   
  133.       
  134.     return TRUE;                                        // Initialization Went OK  
  135. }  
  136.   
  137. int DrawGLScene(GLvoid)                                 // Here’s Where We Do All The Drawing  
  138. {  
  139.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer  
  140.     glLoadIdentity();                                   // Reset The View  
  141.     changeObject( gothicTrans );  
  142.     drawModel(gothicModel,true,false);  
  143.     glFlush ();   
  144.     return TRUE;                                        // Keep Going  
  145. }  
  146.   
  147. GLvoid KillGLWindow(GLvoid)                             // Properly Kill The Window  
  148. {  
  149.     if (fullscreen)                                     // Are We In Fullscreen Mode?  
  150.     {  
  151.         ChangeDisplaySettings(NULL,0);                  // If So Switch Back To The Desktop  
  152.         ShowCursor(TRUE);                               // Show Mouse Pointer  
  153.     }  
  154.   
  155.     if (hRC)                                            // Do We Have A Rendering Context?  
  156.     {  
  157.         if (!wglMakeCurrent(NULL,NULL))                 // Are We Able To Release The DC And RC Contexts?  
  158.         {  
  159.             MessageBox(NULL,”Release Of DC And RC Failed.”,“SHUTDOWN ERROR”,MB_OK | MB_ICONINFORMATION);  
  160.         }  
  161.   
  162.         if (!wglDeleteContext(hRC))                     // Are We Able To Delete The RC?  
  163.         {  
  164.             MessageBox(NULL,”Release Rendering Context Failed.”,“SHUTDOWN ERROR”,MB_OK | MB_ICONINFORMATION);  
  165.         }  
  166.         hRC=NULL;                                       // Set RC To NULL  
  167.     }  
  168.   
  169.     if (hDC && !ReleaseDC(hWnd,hDC))                    // Are We Able To Release The DC  
  170.     {  
  171.         MessageBox(NULL,”Release Device Context Failed.”,“SHUTDOWN ERROR”,MB_OK | MB_ICONINFORMATION);  
  172.         hDC=NULL;                                       // Set DC To NULL  
  173.     }  
  174.   
  175.     if (hWnd && !DestroyWindow(hWnd))                   // Are We Able To Destroy The Window?  
  176.     {  
  177.         MessageBox(NULL,”Could Not Release hWnd.”,“SHUTDOWN ERROR”,MB_OK | MB_ICONINFORMATION);  
  178.         hWnd=NULL;                                      // Set hWnd To NULL  
  179.     }  
  180.   
  181.     if (!UnregisterClass(“OpenGL”,hInstance))           // Are We Able To Unregister Class  
  182.     {  
  183.         MessageBox(NULL,”Could Not Unregister Class.”,“SHUTDOWN ERROR”,MB_OK | MB_ICONINFORMATION);  
  184.         hInstance=NULL;                                 // Set hInstance To NULL  
  185.     }  
  186. }  
  187.   
  188. /  This Code Creates Our OpenGL Window.  Parameters Are:                    
  189.    title           - Title To Appear At The Top Of The Window               
  190.    width           - Width Of The GL Window Or Fullscreen Mode              
  191.    height          - Height Of The GL Window Or Fullscreen Mode             
  192.    bits            - Number Of Bits To Use For Color (8/16/24/32)           
  193.    fullscreenflag  - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)   /  
  194.    
  195. BOOL CreateGLWindow(char title, int width, int height, int bits, bool fullscreenflag)  
  196. {  
  197.     GLuint      PixelFormat;            // Holds The Results After Searching For A Match  
  198.     WNDCLASS    wc;                     // Windows Class Structure  
  199.     DWORD       dwExStyle;              // Window Extended Style  
  200.     DWORD       dwStyle;                // Window Style  
  201.     RECT        WindowRect;             // Grabs Rectangle Upper Left / Lower Right Values  
  202.     WindowRect.left=(long)0;            // Set Left Value To 0  
  203.     WindowRect.right=(long)width;       // Set Right Value To Requested Width  
  204.     WindowRect.top=(long)0;             // Set Top Value To 0  
  205.     WindowRect.bottom=(long)height;     // Set Bottom Value To Requested Height  
  206.   
  207.     fullscreen=fullscreenflag;          // Set The Global Fullscreen Flag  
  208.   
  209.     hInstance           = GetModuleHandle(NULL);                // Grab An Instance For Our Window  
  210.     wc.style            = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;   // Redraw On Size, And Own DC For Window.  
  211.     wc.lpfnWndProc      = (WNDPROC) WndProc;                    // WndProc Handles Messages  
  212.     wc.cbClsExtra       = 0;                                    // No Extra Window Data  
  213.     wc.cbWndExtra       = 0;                                    // No Extra Window Data  
  214.     wc.hInstance        = hInstance;                            // Set The Instance  
  215.     wc.hIcon            = LoadIcon(NULL, IDI_WINLOGO);          // Load The Default Icon  
  216.     wc.hCursor          = LoadCursor(NULL, IDC_ARROW);          // Load The Arrow Pointer  
  217.     wc.hbrBackground    = NULL;                                 // No Background Required For GL  
  218.     wc.lpszMenuName     = NULL;                                 // We Don’t Want A Menu  
  219.     wc.lpszClassName    = ”OpenGL”;                             // Set The Class Name  
  220.   
  221.     if (!RegisterClass(&wc))                                    // Attempt To Register The Window Class  
  222.     {  
  223.         MessageBox(NULL,”Failed To Register The Window Class.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  224.         return FALSE;                                           // Return FALSE  
  225.     }  
  226.       
  227.     if (fullscreen)                                             // Attempt Fullscreen Mode?  
  228.     {  
  229.         DEVMODE dmScreenSettings;                               // Device Mode  
  230.         memset(&dmScreenSettings,0,sizeof(dmScreenSettings));   // Makes Sure Memory’s Cleared  
  231.         dmScreenSettings.dmSize=sizeof(dmScreenSettings);       // Size Of The Devmode Structure  
  232.         dmScreenSettings.dmPelsWidth    = width;                // Selected Screen Width  
  233.         dmScreenSettings.dmPelsHeight   = height;               // Selected Screen Height  
  234.         dmScreenSettings.dmBitsPerPel   = bits;                 // Selected Bits Per Pixel  
  235.         dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;  
  236.   
  237.         // Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.  
  238.         if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)  
  239.         {  
  240.             // If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.  
  241.             if (MessageBox(NULL,“The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?”,“NeHe GL”,MB_YESNO|MB_ICONEXCLAMATION)==IDYES)  
  242.             {  
  243.                 fullscreen=FALSE;       // Windowed Mode Selected.  Fullscreen = FALSE  
  244.             }  
  245.             else  
  246.             {  
  247.                 // Pop Up A Message Box Letting User Know The Program Is Closing.  
  248.                 MessageBox(NULL,”Program Will Now Close.”,“ERROR”,MB_OK|MB_ICONSTOP);  
  249.                 return FALSE;                                   // Return FALSE  
  250.             }  
  251.         }  
  252.     }  
  253.   
  254.     if (fullscreen)                                             // Are We Still In Fullscreen Mode?  
  255.     {  
  256.         dwExStyle=WS_EX_APPWINDOW;                              // Window Extended Style  
  257.         dwStyle=WS_POPUP;                                       // Windows Style  
  258.         ShowCursor(FALSE);                                      // Hide Mouse Pointer  
  259.     }  
  260.     else  
  261.     {  
  262.         dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;           // Window Extended Style  
  263.         dwStyle=WS_OVERLAPPEDWINDOW;                            // Windows Style  
  264.     }  
  265.   
  266.     AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);     // Adjust Window To True Requested Size  
  267.   
  268.     // Create The Window  
  269.     if (!(hWnd=CreateWindowEx(  dwExStyle,                          // Extended Style For The Window  
  270.                                 ”OpenGL”,                           // Class Name  
  271.                                 title,                              // Window Title  
  272.                                 dwStyle |                           // Defined Window Style  
  273.                                 WS_CLIPSIBLINGS |                   // Required Window Style  
  274.                                 WS_CLIPCHILDREN,                    // Required Window Style  
  275.                                 0, 0,                               // Window Position  
  276.                                 WindowRect.right-WindowRect.left,   // Calculate Window Width  
  277.                                 WindowRect.bottom-WindowRect.top,   // Calculate Window Height  
  278.                                 NULL,                               // No Parent Window  
  279.                                 NULL,                               // No Menu  
  280.                                 hInstance,                          // Instance  
  281.                                 NULL)))                             // Dont Pass Anything To WM_CREATE  
  282.     {  
  283.         KillGLWindow();                             // Reset The Display  
  284.         MessageBox(NULL,”Window Creation Error.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  285.         return FALSE;                               // Return FALSE  
  286.     }  
  287.   
  288.     static  PIXELFORMATDESCRIPTOR pfd=              // pfd Tells Windows How We Want Things To Be  
  289.     {  
  290.         sizeof(PIXELFORMATDESCRIPTOR),              // Size Of This Pixel Format Descriptor  
  291.         1,                                          // Version Number  
  292.         PFD_DRAW_TO_WINDOW |                        // Format Must Support Window  
  293.         PFD_SUPPORT_OPENGL |                        // Format Must Support OpenGL  
  294.         PFD_DOUBLEBUFFER,                           // Must Support Double Buffering  
  295.         PFD_TYPE_RGBA,                              // Request An RGBA Format  
  296.         bits,                                       // Select Our Color Depth  
  297.         0, 0, 0, 0, 0, 0,                           // Color Bits Ignored  
  298.         0,                                          // No Alpha Buffer  
  299.         0,                                          // Shift Bit Ignored  
  300.         0,                                          // No Accumulation Buffer  
  301.         0, 0, 0, 0,                                 // Accumulation Bits Ignored  
  302.         16,                                         // 16Bit Z-Buffer (Depth Buffer)    
  303.         0,                                          // No Stencil Buffer  
  304.         0,                                          // No Auxiliary Buffer  
  305.         PFD_MAIN_PLANE,                             // Main Drawing Layer  
  306.         0,                                          // Reserved  
  307.         0, 0, 0                                     // Layer Masks Ignored  
  308.     };  
  309.       
  310.     if (!(hDC=GetDC(hWnd)))                         // Did We Get A Device Context?  
  311.     {  
  312.         KillGLWindow();                             // Reset The Display  
  313.         MessageBox(NULL,”Can’t Create A GL Device Context.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  314.         return FALSE;                               // Return FALSE  
  315.     }  
  316.   
  317.     if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?  
  318.     {  
  319.         KillGLWindow();                             // Reset The Display  
  320.         MessageBox(NULL,”Can’t Find A Suitable PixelFormat.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  321.         return FALSE;                               // Return FALSE  
  322.     }  
  323.   
  324.     if(!SetPixelFormat(hDC,PixelFormat,&pfd))       // Are We Able To Set The Pixel Format?  
  325.     {  
  326.         KillGLWindow();                             // Reset The Display  
  327.         MessageBox(NULL,”Can’t Set The PixelFormat.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  328.         return FALSE;                               // Return FALSE  
  329.     }  
  330.   
  331.     if (!(hRC=wglCreateContext(hDC)))               // Are We Able To Get A Rendering Context?  
  332.     {  
  333.         KillGLWindow();                             // Reset The Display  
  334.         MessageBox(NULL,”Can’t Create A GL Rendering Context.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  335.         return FALSE;                               // Return FALSE  
  336.     }  
  337.   
  338.     if(!wglMakeCurrent(hDC,hRC))                    // Try To Activate The Rendering Context  
  339.     {  
  340.         KillGLWindow();                             // Reset The Display  
  341.         MessageBox(NULL,”Can’t Activate The GL Rendering Context.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  342.         return FALSE;                               // Return FALSE  
  343.     }  
  344.   
  345.     ShowWindow(hWnd,SW_SHOW);                       // Show The Window  
  346.     SetForegroundWindow(hWnd);                      // Slightly Higher Priority  
  347.     SetFocus(hWnd);                                 // Sets Keyboard Focus To The Window  
  348.     ReSizeGLScene(width, height);                   // Set Up Our Perspective GL Screen  
  349.   
  350.     if (!InitGL())                                  // Initialize Our Newly Created GL Window  
  351.     {  
  352.         KillGLWindow();                             // Reset The Display  
  353.         MessageBox(NULL,”Initialization Failed.”,“ERROR”,MB_OK|MB_ICONEXCLAMATION);  
  354.         return FALSE;                               // Return FALSE  
  355.     }  
  356.   
  357.     return TRUE;                                    // Success  
  358. }  
  359.   
  360. LRESULT CALLBACK WndProc(   HWND    hWnd,           // Handle For This Window  
  361.                             UINT    uMsg,           // Message For This Window  
  362.                             WPARAM  wParam,         // Additional Message Information  
  363.                             LPARAM  lParam)         // Additional Message Information  
  364. {  
  365.     switch (uMsg)                                   // Check For Windows Messages  
  366.     {  
  367.         case WM_ACTIVATE:                           // Watch For Window Activate Message  
  368.         {  
  369.             if (!HIWORD(wParam))                    // Check Minimization State  
  370.             {  
  371.                 active=TRUE;                        // Program Is Active  
  372.             }  
  373.             else  
  374.             {  
  375.                 active=FALSE;                       // Program Is No Longer Active  
  376.             }  
  377.   
  378.             return 0;                               // Return To The Message Loop  
  379.         }  
  380.   
  381.         case WM_SYSCOMMAND:                         // Intercept System Commands  
  382.         {  
  383.             switch (wParam)                         // Check System Calls  
  384.             {  
  385.                 case SC_SCREENSAVE:                 // Screensaver Trying To Start?  
  386.                 case SC_MONITORPOWER:               // Monitor Trying To Enter Powersave?  
  387.                 return 0;                           // Prevent From Happening  
  388.             }  
  389.             break;                                  // Exit  
  390.         }  
  391.   
  392.         case WM_CLOSE:                              // Did We Receive A Close Message?  
  393.         {  
  394.             PostQuitMessage(0);                     // Send A Quit Message  
  395.             return 0;                               // Jump Back  
  396.         }  
  397.   
  398.         case WM_KEYDOWN:                            // Is A Key Being Held Down?  
  399.         {  
  400.             keys[wParam] = TRUE;                    // If So, Mark It As TRUE  
  401.             return 0;                               // Jump Back  
  402.         }  
  403.   
  404.         case WM_KEYUP:                              // Has A Key Been Released?  
  405.         {  
  406.             keys[wParam] = FALSE;                   // If So, Mark It As FALSE  
  407.             return 0;                               // Jump Back  
  408.         }  
  409.   
  410.         case WM_SIZE:                               // Resize The OpenGL Window  
  411.         {  
  412.             ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height  
  413.             return 0;                               // Jump Back  
  414.         }  
  415.     }  
  416.   
  417.     // Pass All Unhandled Messages To DefWindowProc  
  418.     return DefWindowProc(hWnd,uMsg,wParam,lParam);  
  419. }  
  420.   
  421. int WINAPI WinMain( HINSTANCE   hInstance,          // Instance  
  422.                     HINSTANCE   hPrevInstance,      // Previous Instance  
  423.                     LPSTR       lpCmdLine,          // Command Line Parameters  
  424.                     int         nCmdShow)           // Window Show State  
  425. {  
  426.     MSG     msg;                                    // Windows Message Structure  
  427.     BOOL    done=FALSE;                             // Bool Variable To Exit Loop  
  428.   
  429.     // Ask The User Which Screen Mode They Prefer  
  430.     if (MessageBox(NULL,“Would You Like To Run In Fullscreen Mode?”“Start FullScreen?”,MB_YESNO|MB_ICONQUESTION)==IDNO)  
  431.     {  
  432.         fullscreen=FALSE;                           // Windowed Mode  
  433.     }  
  434.   
  435.     // Create Our OpenGL Window  
  436.     if (!CreateGLWindow(“NeHe’s Texture Mapping Tutorial”,640,480,16,fullscreen))  
  437.     {  
  438.         return 0;                                   // Quit If Window Was Not Created  
  439.     }  
  440.   
  441.     while(!done)                                    // Loop That Runs While done=FALSE  
  442.     {  
  443.         if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))   // Is There A Message Waiting?  
  444.         {  
  445.             if (msg.message==WM_QUIT)               // Have We Received A Quit Message?  
  446.             {  
  447.                 done=TRUE;                          // If So done=TRUE  
  448.             }  
  449.             else                                    // If Not, Deal With Window Messages  
  450.             {  
  451.                 TranslateMessage(&msg);             // Translate The Message  
  452.                 DispatchMessage(&msg);              // Dispatch The Message  
  453.             }  
  454.         }  
  455.         else                                        // If There Are No Messages  
  456.         {  
  457.             // Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()  
  458.             if ((active && !DrawGLScene()) || keys[VK_ESCAPE])  // Active?  Was There A Quit Received?  
  459.             {  
  460.                 done=TRUE;                          // ESC or DrawGLScene Signalled A Quit  
  461.             }  
  462.             else                                    // Not Time To Quit, Update Screen  
  463.             {  
  464.                 SwapBuffers(hDC);                   // Swap Buffers (Double Buffering)  
  465.             }  
  466.   
  467.             if (keys[VK_F1])                        // Is F1 Being Pressed?  
  468.             {  
  469.                 keys[VK_F1]=FALSE;                  // If So Make Key FALSE  
  470.                 KillGLWindow();                     // Kill Our Current Window  
  471.                 fullscreen=!fullscreen;             // Toggle Fullscreen / Windowed Mode  
  472.                 // Recreate Our OpenGL Window  
  473.                 if (!CreateGLWindow(“NeHe’s Texture Mapping Tutorial”,640,480,16,fullscreen))  
  474.                 {  
  475.                     return 0;                       // Quit If Window Was Not Created  
  476.                 }  
  477.             }  
  478.         }  
  479.     }  
  480.   
  481.     // Shutdown  
  482.     KillGLWindow();                                 // Kill The Window  
  483.     return (msg.wParam);                            // Exit The Program  
  484. }  
/* 
* This Code Was Created By Jeff Molofee 2000
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing The Base Code, Making It More Flexible!
* If You’ve Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/

include // Header File For Windows

include // Header File For Standard Input/Output

include // Header File For The OpenGL32 Library

include // Header File For The GLu32 Library

include // Header File For The Glaux Library

include "CLoad3DS.h"

HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application

bool keys[256]; // Array Used For The Keyboard Routine
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default

GLfloat xrot; // X Rotation ( NEW )
GLfloat yrot; // Y Rotation ( NEW )
GLfloat zrot; // Z Rotation ( NEW )

GLuint texture[1]; // Storage For One Texture ( NEW )

CLoad3DS *gothicLoader=new(CLoad3DS);
t3DModel gothicModel;
//BoundingBox gothicBoundingBox;
float gothicTrans[10] = {
0, 0 , -30 , //表示在世界矩阵的位置
0.2 , 0.2 , 0.2 , //表示xyz放大倍数
0 , 0 , 0 , 0 //表示旋转
};

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc

AUX_RGBImageRec *LoadBMP(char *Filename) // Loads A Bitmap Image
{
FILE *File=NULL; // File Handle

if (!Filename)                                      // Make Sure A Filename Was Given
{
    return NULL;                                    // If Not Return NULL
}

File=fopen(Filename,"r");                           // Check To See If The File Exists

if (File)                                           // Does The File Exist?
{
    fclose(File);                                   // Close The Handle
    return auxDIBImageLoad(Filename);               // Load The Bitmap And Return A Pointer
}

return NULL;                                        // If Load Failed Return NULL

}

int LoadGLTextures() // Load Bitmaps And Convert To Textures
{
int Status=FALSE; // Status Indicator

AUX_RGBImageRec *TextureImage[1];                   // Create Storage Space For The Texture

memset(TextureImage,0,sizeof(void *)*1);            // Set The Pointer To NULL

// Load The Bitmap, Check For Errors, If Bitmap's Not Found Quit
if (TextureImage[0]=LoadBMP("Data/NeHe.bmp"))
{
    Status=TRUE;                                    // Set The Status To TRUE

    glGenTextures(1, &texture[0]);                  // Create The Texture

    // Typical Texture Generation Using Data From The Bitmap
    glBindTexture(GL_TEXTURE_2D, texture[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, 3, TextureImage[0]->sizeX, TextureImage[0]->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage[0]->data);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
}

if (TextureImage[0])                                    // If Texture Exists
{
    if (TextureImage[0]->data)                           // If Texture Image Exists
    {
        free(TextureImage[0]->data);                 // Free The Texture Image Memory
    }

    free(TextureImage[0]);                              // Free The Image Structure
}

return Status;                                      // Return The Status

}

GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}

glViewport(0,0,width,height);                       // Reset The Current Viewport

glMatrixMode(GL_PROJECTION);                        // Select The Projection Matrix
glLoadIdentity();                                   // Reset The Projection Matrix

// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

glMatrixMode(GL_MODELVIEW);                         // Select The Modelview Matrix
glLoadIdentity();                                   // Reset The Modelview Matrix

}

int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
if (!LoadGLTextures()) // Jump To Texture Loading Routine ( NEW )
{
return FALSE; // If Texture Didn’t Load Return FALSE
}

glEnable(GL_TEXTURE_2D);                            // Enable Texture Mapping ( NEW )
glShadeModel(GL_SMOOTH);                            // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);               // 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

//导入模型 模型的文件夹尽量这样设置 
//然后模型贴图 装在Data/pic里面  一定要跟前面截图的文件夹名字一样,想改得去CLoad3DS文件里面改
gothicLoader->Import3DS(&gothicModel, "Data/3ds/GUTEMB_L.3DS"); 

return TRUE;                                        // Initialization Went OK

}

int DrawGLScene(GLvoid) // Here’s Where We Do All The Drawing
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
changeObject( gothicTrans );
drawModel(gothicModel,true,false);
glFlush ();
return TRUE; // Keep Going
}

GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

if (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 NULL
}

if (hDC && !ReleaseDC(hWnd,hDC))                    // Are We Able To Release The DC
{
    MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
    hDC=NULL;                                       // Set DC To NULL
}

if (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 NULL
}

if (!UnregisterClass("OpenGL",hInstance))           // Are We Able To Unregister Class
{
    MessageBox(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)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height

fullscreen=fullscreenflag;          // Set The Global Fullscreen Flag

hInstance           = GetModuleHandle(NULL);                // Grab An Instance For Our Window
wc.style            = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;   // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc      = (WNDPROC) WndProc;                    // WndProc Handles Messages
wc.cbClsExtra       = 0;                                    // No Extra Window Data
wc.cbWndExtra       = 0;                                    // No Extra Window Data
wc.hInstance        = hInstance;                            // Set The Instance
wc.hIcon            = LoadIcon(NULL, IDI_WINLOGO);          // Load The Default Icon
wc.hCursor          = LoadCursor(NULL, IDC_ARROW);          // Load The Arrow Pointer
wc.hbrBackground    = NULL;                                 // No Background Required For GL
wc.lpszMenuName     = NULL;                                 // We Don't Want A Menu
wc.lpszClassName    = "OpenGL";                             // Set The Class Name

if (!RegisterClass(&wc))                                    // Attempt To Register The Window Class
{
    MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                                           // Return FALSE
}

if (fullscreen)                                             // Attempt Fullscreen Mode?
{
    DEVMODE dmScreenSettings;                               // Device Mode
    memset(&dmScreenSettings,0,sizeof(dmScreenSettings));   // Makes Sure Memory's Cleared
    dmScreenSettings.dmSize=sizeof(dmScreenSettings);       // Size Of The Devmode Structure
    dmScreenSettings.dmPelsWidth    = width;                // Selected Screen Width
    dmScreenSettings.dmPelsHeight   = height;               // Selected Screen Height
    dmScreenSettings.dmBitsPerPel   = bits;                 // Selected Bits Per Pixel
    dmScreenSettings.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 By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
        {
            fullscreen=FALSE;       // Windowed Mode Selected.  Fullscreen = FALSE
        }
        else
        {
            // 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 FALSE
        }
    }
}

if (fullscreen)                                             // Are We Still In Fullscreen Mode?
{
    dwExStyle=WS_EX_APPWINDOW;                              // Window Extended Style
    dwStyle=WS_POPUP;                                       // Windows Style
    ShowCursor(FALSE);                                      // Hide Mouse Pointer
}
else
{
    dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;           // Window Extended Style
    dwStyle=WS_OVERLAPPEDWINDOW;                            // Windows Style
}

AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);     // Adjust Window To True Requested Size

// Create The Window
if (!(hWnd=CreateWindowEx(  dwExStyle,                          // Extended Style For The Window
                            "OpenGL",                           // Class Name
                            title,                              // Window Title
                            dwStyle |                           // Defined Window Style
                            WS_CLIPSIBLINGS |                   // Required Window Style
                            WS_CLIPCHILDREN,                    // Required Window Style
                            0, 0,                               // Window Position
                            WindowRect.right-WindowRect.left,   // Calculate Window Width
                            WindowRect.bottom-WindowRect.top,   // Calculate Window Height
                            NULL,                               // No Parent Window
                            NULL,                               // No Menu
                            hInstance,                          // Instance
                            NULL)))                             // Dont Pass Anything To WM_CREATE
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

static  PIXELFORMATDESCRIPTOR pfd=              // pfd Tells Windows How We Want Things To Be
{
    sizeof(PIXELFORMATDESCRIPTOR),              // Size Of This Pixel Format Descriptor
    1,                                          // Version Number
    PFD_DRAW_TO_WINDOW |                        // Format Must Support Window
    PFD_SUPPORT_OPENGL |                        // Format Must Support OpenGL
    PFD_DOUBLEBUFFER,                           // Must Support Double Buffering
    PFD_TYPE_RGBA,                              // Request An RGBA Format
    bits,                                       // Select Our 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,                                 // Accumulation Bits Ignored
    16,                                         // 16Bit Z-Buffer (Depth Buffer)  
    0,                                          // No Stencil Buffer
    0,                                          // No Auxiliary Buffer
    PFD_MAIN_PLANE,                             // Main Drawing Layer
    0,                                          // Reserved
    0, 0, 0                                     // Layer Masks Ignored
};

if (!(hDC=GetDC(hWnd)))                         // Did We Get A Device Context?
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

if(!SetPixelFormat(hDC,PixelFormat,&pfd))       // Are We Able To Set The Pixel Format?
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

if (!(hRC=wglCreateContext(hDC)))               // Are We Able To Get A Rendering Context?
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

if(!wglMakeCurrent(hDC,hRC))                    // Try To Activate The Rendering Context
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

ShowWindow(hWnd,SW_SHOW);                       // Show The Window
SetForegroundWindow(hWnd);                      // Slightly Higher Priority
SetFocus(hWnd);                                 // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height);                   // Set Up Our Perspective GL Screen

if (!InitGL())                                  // Initialize Our Newly Created GL Window
{
    KillGLWindow();                             // Reset The Display
    MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
    return FALSE;                               // Return FALSE
}

return TRUE;                                    // Success

}

LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}

        return 0;                               // Return To The Message Loop
    }

    case WM_SYSCOMMAND:                         // Intercept System Commands
    {
        switch (wParam)                         // Check System Calls
        {
            case SC_SCREENSAVE:                 // Screensaver Trying To Start?
            case SC_MONITORPOWER:               // Monitor Trying To Enter Powersave?
            return 0;                           // Prevent From Happening
        }
        break;                                  // Exit
    }

    case WM_CLOSE:                              // Did We Receive A Close Message?
    {
        PostQuitMessage(0);                     // Send A Quit Message
        return 0;                               // Jump Back
    }

    case WM_KEYDOWN:                            // Is A Key Being Held Down?
    {
        keys[wParam] = TRUE;                    // If So, Mark It As TRUE
        return 0;                               // Jump Back
    }

    case WM_KEYUP:                              // Has A Key Been Released?
    {
        keys[wParam] = FALSE;                   // If So, Mark It As FALSE
        return 0;                               // Jump Back
    }

    case WM_SIZE:                               // Resize The OpenGL Window
    {
        ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
        return 0;                               // Jump Back
    }
}

// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);

}

int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop

// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
    fullscreen=FALSE;                           // Windowed Mode
}

// Create Our OpenGL Window
if (!CreateGLWindow("NeHe's Texture Mapping Tutorial",640,480,16,fullscreen))
{
    return 0;                                   // Quit If Window Was Not Created
}

while(!done)                                    // Loop That Runs While done=FALSE
{
    if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))   // Is There A Message Waiting?
    {
        if (msg.message==WM_QUIT)               // Have We Received A Quit Message?
        {
            done=TRUE;                          // If So done=TRUE
        }
        else                                    // If Not, Deal With Window Messages
        {
            TranslateMessage(&msg);             // Translate The Message
            DispatchMessage(&msg);              // Dispatch The Message
        }
    }
    else                                        // If There Are No Messages
    {
        // Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
        if ((active && !DrawGLScene()) || keys[VK_ESCAPE])  // Active?  Was There A Quit Received?
        {
            done=TRUE;                          // ESC or DrawGLScene Signalled A Quit
        }
        else                                    // Not Time To Quit, Update Screen
        {
            SwapBuffers(hDC);                   // Swap Buffers (Double Buffering)
        }

        if (keys[VK_F1])                        // Is F1 Being Pressed?
        {
            keys[VK_F1]=FALSE;                  // If So Make Key FALSE
            KillGLWindow();                     // Kill Our Current Window
            fullscreen=!fullscreen;             // Toggle Fullscreen / Windowed Mode
            // Recreate Our OpenGL Window
            if (!CreateGLWindow("NeHe's Texture Mapping Tutorial",640,480,16,fullscreen))
            {
                return 0;                       // Quit If Window Was Not Created
            }
        }
    }
}

// Shutdown
KillGLWindow();                                 // Kill The Window
return (msg.wParam);                            // Exit The Program

}

上图就是主要的逻辑代码,我已经改成了显示3ds模型的代码了。  下面我指出改的地方都有哪

首先是文件目录。 

3D模型一定要放在Data/3ds文件夹里面

3D模型贴图一定要放在Data/pic文件夹里面 如下图:

Opengl 导入3Dmax制作的.3ds模型 并显示出来_第2张图片

Opengl 导入3Dmax制作的.3ds模型 并显示出来_第3张图片

这是VC工程,VS是一样的,直接用nehe那个工程导入CLoad3DS 并且建立那3ds和pic两个文件夹即可, 最后讲给出全部源代码和一些网上的模型

下面是主要对nehe添加3D模型支持的代码

首先加上头文件

[html] view plain copy
print ?
  1. #include “CLoad3DS.h”  
#include "CLoad3DS.h"

然后在定义全局变量的地方,也就是 定义完头文件紧接着就写如下 3D模型的定义

[html] view plain copy
print ?
  1. CLoad3DS *gothicLoader=new(CLoad3DS);  
  2. t3DModel gothicModel;  
  3.   
  4. float gothicTrans[10] = {   
  5.     0, 0 , -30 ,     //表示在世界矩阵的位置  
  6.         0.2 , 0.2 , 0.2 ,      //表示xyz放大倍数  
  7.         0 , 0 , 0 , 0  //表示旋转  
  8. };  
CLoad3DS *gothicLoader=new(CLoad3DS);
t3DModel gothicModel;

float gothicTrans[10] = { 
    0, 0 , -30 ,     //表示在世界矩阵的位置
        0.2 , 0.2 , 0.2 ,      //表示xyz放大倍数
        0 , 0 , 0 , 0  //表示旋转
};

上面代码很简单,就是加载了CLoad3DS类,  t3DModel类,然后定义了一个参数数组,中文说明。

定义好了后就要初始化了。 

在InitGL 也就是opengl初始化那个函数里面 初始化,就一句话。

[html] view plain copy
print ?
  1. //导入模型 模型的文件夹尽量这样设置   
  2.     //然后模型贴图 装在Data/pic里面  一定要跟前面截图的文件夹名字一样,想改得去CLoad3DS文件里面改  
  3.     gothicLoader->Import3DS(&gothicModel, “Data/3ds/GUTEMB_L.3DS”);   
//导入模型 模型的文件夹尽量这样设置 
    //然后模型贴图 装在Data/pic里面  一定要跟前面截图的文件夹名字一样,想改得去CLoad3DS文件里面改
    gothicLoader->Import3DS(&gothicModel, "Data/3ds/GUTEMB_L.3DS"); 

初始化直接就填你想要那个模型的XXX.3DS即可,纹理不用管,放在pic文件夹里面,他自动从模型信息里面找出纹理的对应文件名

最后就是运行了,在绘制函数里面用changeObject 导入之前设置好的参数,再用drawModel函数(在CLoad3DS定义好了的全局函数) 绘制。即可

[html] view plain copy
print ?
  1. int DrawGLScene(GLvoid)                                 // Here’s Where We Do All The Drawing  
  2. {  
  3.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer  
  4.     glLoadIdentity();                                   // Reset The View  
  5.     glPushMatrix();  
  6.     changeObject( gothicTrans );  
  7.     drawModel(gothicModel,true,false);  
  8.     glPopMatrix();  
  9.     glFlush ();   
  10.     return TRUE;                                        // Keep Going  
  11. }  
int DrawGLScene(GLvoid)                                    // Here's Where We Do All The Drawing
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
    glLoadIdentity();                                   // Reset The View
    glPushMatrix();
    changeObject( gothicTrans );
    drawModel(gothicModel,true,false);
    glPopMatrix();
    glFlush (); 
    return TRUE;                                        // Keep Going
}

完成,很简单吧, 就是添加2个文件,然后三两行代码即可实现模型导入。

下面是整个工程文件。


点我下载

你可能感兴趣的:(OpenGL学习)