main.cpp
上传用户:liujun12jf
上传日期:2022-07-12
资源大小:638k
文件大小:16k
源码类别:

OpenGL

开发平台:

Visual C++

  1. #include "main.h"
  2. void RenderScene();
  3. bool InitializeGL();
  4. void SetupPixelFormat(HDC hDC);
  5. HDC g_HDC;
  6. HWND hwnd;
  7. CSceneRoot sRoot;
  8. CPhysic physic;
  9. CSound sound;
  10. CTimer timer;
  11. CMotionBlur mblur;
  12. CTakeTimer tt_phys(&timer, 100, "physics limit exceeded");
  13. CTakeTimer tt_draw(&timer, 100, "drawing limit exceeded");
  14. CTakeTimer tt_snd(&timer, 50, "sound limit exceeded");
  15. int obj_count = 100;
  16. int tex_id = 0;
  17. CVector cam(70, -7.0f, 40);
  18. float cam_add = 1.0f;
  19. float i1 = 100;
  20. float i1add = 100;
  21. float i2 = 63.0f;
  22. float i2add = 20;
  23. float i3 = 2.2f;
  24. float i4 = -3.0f;
  25. void brm();
  26. void abc();
  27. void TitleInfo();
  28. // init floor
  29. void initFlr()
  30. {
  31. CPhysicObject *flr = new CPhysicObject;
  32. flr->vColour.Set(0.0f, 0.6f, 0.0f, 0.5f);
  33. flr->SetPosition(CVector(0, -10, 0));
  34. flr->size.Set(100, 1, 100);
  35. flr->weight = 0;
  36. flr->isBox = 1;
  37. flr->piTexID = &tex_id;
  38. physic.AddObject(flr);
  39. sRoot.AddChild(flr);
  40. }
  41. // 1 object rnd position
  42. void objectRndPosition(CPhysicObject *o)
  43. {
  44. float min_y = 20, max_y = 30;
  45. float min_ = -50, max_ = 50;
  46. o->SetNewtonPosition(CVector(rnd(min_, max_), rnd(min_y, max_y), rnd(min_, max_)));
  47. }
  48. // 1 object init
  49. void initObject(CPhysicObject *o)
  50. {
  51. o->isBox = rand()%2;
  52. o->size = 0.5f;
  53. if (!o->isBox) o->size /= 2;
  54. o->weight = 1;
  55. o->piTexID = &tex_id;
  56. if (o->pBody) o->ReleaseFromNewton();
  57. o->mMatrix.Reset();
  58. o->vColour.Randomize();
  59. physic.AddObject(o);
  60. objectRndPosition(o);
  61. }
  62. // init all objects
  63. void initObjects()
  64. {
  65. for (int i=0 ; i < obj_count ; i++)
  66. {
  67. CPhysicObject *o = new CPhysicObject;
  68. initObject(o);
  69. sRoot.AddChild(o);
  70. CParticlesObject *po = new CParticlesObject();
  71. po->pPSystem->SetMaxLifeClrVelGrvPosEboxVvarTex(50, 0.5f, CVector(0.9f, 0.5f, 0.0), CVector(0),
  72. CVector(0, 10, 0), CVector(0, -0.98f, 0), CVector(0), CVector(0.2f), 45, 3);
  73. o->AddChild(po);
  74. }
  75. }
  76. // objects random position
  77. void objectsRndPosition()
  78. {
  79. for (vqCSNi i = sRoot.vKids.begin() ; i != sRoot.vKids.end() ; i++)
  80. {
  81. if (!*i) continue;
  82. if (!((CPhysicObject*)(*i))->weight) continue;
  83. objectRndPosition((CPhysicObject*)*i);
  84. }
  85. }
  86. bool Init()
  87. {
  88. if (!InitializeGL()) return 0;
  89. sound.Init();
  90. sound.SetListener(&cam[0]);
  91. sound.AddSound("1", "snds/1.mp3");
  92. sound.AddSound("2", "snds/2.mp3");
  93. sound.AddSound("3", "snds/3.mp3");
  94. sound.AddSound("4", "snds/4.mp3");
  95. sound.AddSound("5", "snds/5.mp3");
  96. sound.AddSound("6", "snds/6.mp3");
  97. sound.AddSound("7", "snds/7.mp3");
  98. sound.AddSound("8", "snds/8.mp3");
  99. sound.loadAndPlayLoop("snds/fire.mp3");
  100. physic.Init();
  101. initFlr();
  102. initObjects();
  103. return 1;
  104. }
  105. // The pixel format is an extension to the Win32 API that is provided
  106. // for support of OpenGL functionality.  To be honest I've never change
  107. // this code every time I use it.  If you don't understand pixel format
  108. // then don't worry.  Just know that you need this exactly how it is and
  109. // it will most likely never change or would not change much.  I will
  110. // go over it in more detail in later tutorials.
  111. void SetupPixelFormat(HDC hDC)
  112. {
  113.    int nPixelFormat;
  114.    static PIXELFORMATDESCRIPTOR pfd = {
  115.          sizeof(PIXELFORMATDESCRIPTOR),   // size of structure.
  116.          1,                               // always 1.
  117.          PFD_DRAW_TO_WINDOW |             // support window
  118.          PFD_SUPPORT_OPENGL |             // support OpenGl
  119.          PFD_DOUBLEBUFFER,                // support double buffering
  120.          PFD_TYPE_RGBA,                   // support RGBA
  121.          16,                              // 32 bit color mode
  122.          0, 0, 0, 0, 0, 0,                // ignore color bits
  123.          0,                               // no alpha buffer
  124.          0,                               // ignore shift bit
  125.          0,                               // no accumulation buffer
  126.          0, 0, 0, 0,                      // ignore accumulation bits.
  127.          16,                              // number of depth buffer bits.
  128.          0,                               // number of stencil buffer bits.
  129.          0,                               // 0 means no auxiliary buffer
  130.          PFD_MAIN_PLANE,                  // The main drawing plane
  131.          0,                               // this is reserved
  132.          0, 0, 0 };                       // layer masks ignored.
  133.    // this chooses the best pixel format and returns index.
  134.    nPixelFormat = ChoosePixelFormat(hDC, &pfd);
  135.    // This set pixel format to device context.
  136.    SetPixelFormat(hDC, nPixelFormat, &pfd);
  137.    // Remember that its not important to fully understand the pixel format,
  138.    // just remember to include in all of your applications and you'll be
  139.    // good to go.
  140. }
  141. // This is the Windows procedure (WndProc).  This handles messages that the
  142. // windows operating sends to your application.  This is similar to the
  143. // message map in MFC. There are a lot of different messages that could
  144. // be responded to that you will see little by litle as we go on.  The
  145. // LRESULT is a long integer and CALLBACK is the calling convention used
  146. // with functions that are called by the Windows operating system.  Every
  147. // program will need a Windows procedure whether it is simple or complex.
  148. // Lets take a look at the Windows procedure...
  149. LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  150. {
  151.    static HGLRC hRC;
  152.    static HDC hDC;      // Device context.
  153.    int width, height;   // The window width and height.
  154.    switch(message)
  155.       {
  156.          case WM_CREATE:                  // Windows creation.
  157.             hDC = GetDC(hwnd);            // This gets the device context for our window.
  158.             g_HDC = hDC;                  // Assigns the global device context to this one.
  159.             SetupPixelFormat(hDC);        // Call the pixel format function.
  160.             hRC = wglCreateContext(hDC);
  161.             wglMakeCurrent(hDC, hRC);
  162.             return 0;
  163.             break;
  164.          case WM_CLOSE:                   // Close message.
  165.          case WM_DESTROY:
  166.             wglMakeCurrent(hDC, NULL);
  167.             wglDeleteContext(hRC);
  168.             PostQuitMessage(0);           // Says close the program.
  169.             return 0;
  170.             break;
  171.          case WM_SIZE:                    // re-size message.
  172.             height = HIWORD(lParam);      // This gets the height of the window.
  173.             width = LOWORD(lParam);       // This gets the width of the window.
  174.             if(height==0)                 // we don't want it to be possible for a
  175.                {                          // height of 0.  If it is 0 me make it 1.
  176.                   height = 1;
  177.                }
  178.             glViewport(0, 0, width, height);// resets the viewport to new dimensions.
  179.             glMatrixMode(GL_PROJECTION);    // Sets the projection matrix.
  180.             glLoadIdentity();               // Reset the modelview matrix.
  181.             // calculate the aspect ratio of the window.
  182.             gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 10000.0f);
  183.             glMatrixMode(GL_MODELVIEW);     // Sets the projection matrix.
  184.             glLoadIdentity();               // Reset the modelview matrix.
  185. glClear(GL_ACCUM_BUFFER_BIT);
  186.             return 0;
  187.             break;
  188.    // This will be used to close the program when the keydown message is sent
  189.    // to your application if the key is escape.  If you wanted to check for
  190.    // other messages then you would add more case statements to it.  We will
  191.    // do this in future tutorials.  For now to exit when the user presses escape
  192.    // you do this...
  193.          case WM_KEYDOWN:
  194.  {
  195.       switch(wParam) 
  196.          {
  197.          case VK_ESCAPE:
  198.          PostQuitMessage(0);
  199.          break;
  200. case 'Z': physic.SwitchSlowMode(); break;
  201. case 'X': objectsRndPosition(); break;
  202. case 'T': brm(); break;
  203. case 'L': sound.PauseAll(); break;
  204. case 'K': sound.UnpauseAll(); break;
  205. case 'B': mblur.Switch(); break;
  206. case 'W': cam.x -= cam_add; break;
  207. case 'S': cam.x += cam_add; break;
  208. case 'A': cam.z += cam_add; break;
  209. case 'D': cam.z -= cam_add; break;
  210. case 'Q': cam.y += cam_add; break;
  211. case 'E': cam.y -= cam_add; break;
  212. case 'U': tex_id = CreateOneColourTexture(); break;
  213. case 'I': tex_id = CreateChaosTexture(); break;
  214. case 'O': tex_id = CreateStarTexture(); break;
  215. case 'P': tex_id = CreateLineObjectTexture(); break;
  216. case '1': sound.PlaySound("1", 0); break;
  217. case '2': sound.PlaySound("2", 0); break;
  218. case '3': sound.PlaySound("3", 0); break;
  219. case '4': sound.PlaySound("4", 0); break;
  220. case '5': sound.PlaySound("5", 0); break;
  221. case '6': sound.PlaySound("6", 0); break;
  222. case '7': sound.PlaySound("7", 0); break;
  223. case '8': sound.PlaySound("8", 0); break;
  224. case '9': i1 += i1add; break;
  225. case '0': i1 -= i1add; break;
  226. case 'N': i2 += i2add; break;
  227. case 'M': i2 -= i2add; break;
  228.          }
  229.             break;
  230. }
  231.          default:                           // Always have a default in case.
  232.             break;
  233.       }
  234.       // What this does is pass all of the unhandled messages to DefWindowProc
  235.       return (DefWindowProc(hwnd, message, wParam, lParam));
  236. }
  237. // This is the WinMain class.  Remember that every C and C++ program required
  238. // a main() function, well every Windows program require a WinMain().
  239. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
  240. {
  241.    MSG msg;                // A message variable.
  242.    WNDCLASSEX windowClass; // Your Window class.
  243. //   HWND hwnd;              // The Window handle.
  244.    bool isFinished;        // This will be used to check if the program is done or not.
  245.    // This is the Window class.  Each attribute is defined for the creation of the
  246.    // window.  I will try to go over more in future tutorials but if you want the
  247.    // complete list of all the different values you can pass, check out the MSDN.
  248.    windowClass.cbSize = sizeof(WNDCLASSEX);        // size of the WNDCLASSEX structure.
  249.    windowClass.style = CS_HREDRAW | CS_VREDRAW;    // style of the window.
  250.    windowClass.lpfnWndProc = WndProc;              // Address to the windows procedure.
  251.    windowClass.cbClsExtra = 0;                     // Extra class information.
  252.    windowClass.cbWndExtra = 0;                     // Extra window information.
  253.    windowClass.hInstance = hInstance;              // Handle of application Instance.
  254.    windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);// Handle of application Icon.
  255.    windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);// mouse cursor
  256.    windowClass.hbrBackground = NULL;               // background color.
  257.    windowClass.lpszMenuName = NULL;                // name of the main menu.
  258.    windowClass.lpszClassName = "UltimateGameProgrammingClass";// window class name.
  259.    windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);// icon when minimized.
  260.    // You must register you class with Windows.  What this does is if the class is
  261.    // not registered, then the program will close right away.
  262.    if(!RegisterClassEx(&windowClass))
  263.       return 0;
  264.    // After your class has been registered then you are ready to create your
  265.    // window.  To create the window you call the CreateWindowEx function
  266.    // and assign it to hwnd.
  267.    hwnd = CreateWindowEx(NULL,// The extended window style.
  268.                         "UltimateGameProgrammingClass",// window Class name.
  269.                         "brm", // window name.
  270.                         WS_OVERLAPPEDWINDOW | WS_VISIBLE |// The window style.
  271.                         WS_SYSMENU | WS_CLIPCHILDREN |// window style.
  272.                         WS_CLIPSIBLINGS,// window style.
  273.                         110, 80,// window x, y coordinate.
  274.                         800, 600,// window width and height.
  275.                         NULL,// handle to parent window.
  276.                         NULL,// menu.
  277.                         hInstance,// handle to app instance.
  278.                         NULL);   // pointer to window creation data.
  279.    
  280. // For more window styles check the MSDN but for now use this to create your
  281. // windows.  I will go over this in more detail in future tutorials.
  282.    // If there was an error with creating the window, then close the program.
  283.    if(!hwnd)
  284.       return 0;
  285.    ShowWindow(hwnd, SW_SHOW); // This shows the window.
  286.    UpdateWindow(hwnd);        // This forces a paint message.
  287.    isFinished = false;        // False = running, True = not running.
  288.                               // Since our program is running we will of cource
  289.                               // set this to false.  For this tutorials it has
  290.                               // no real purpose but in future tutorials we will
  291.                               // use this for when the user presses the esc key
  292.                               // the program will stop.
  293.    // If the initialization of OpenGL fail we can't run the program.
  294. if(!Init())
  295. isFinished = true;
  296.    while(!isFinished)// While the program is running...
  297.       {
  298.          PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE);
  299.          if(msg.message == WM_QUIT)// If the application gets a quit message...
  300.             {
  301.                isFinished = true;  // Then quit the program.
  302.             }
  303.          else
  304.             {
  305.                RenderScene();
  306.                TranslateMessage(&msg);
  307.                DispatchMessage(&msg);
  308.             }
  309.       }
  310.       return msg.wParam;// End of the program.
  311. }
  312. void TitleInfo()
  313. {
  314. char title[256];
  315. char q[16];
  316. strcpy(title, "brm | fps: "); itoa((int)timer.GetFPS(), q, 10); strcat(title, q);
  317. strcat(title, " . tmrs: "); itoa(timer.GetUsed(), q, 10); strcat(title, q);
  318. strcat(title, " . actv: "); itoa(physic.GetActive(), q, 10); strcat(title, q);
  319. strcat(title, " . phys: "); itoa(tt_phys.GetTaken(), q, 10); strcat(title, q);
  320. strcat(title, " . draw: "); itoa(tt_draw.GetTaken(), q, 10); strcat(title, q);
  321. strcat(title, " . snd: "); itoa(tt_snd.GetTaken(), q, 10); strcat(title, q);
  322. strcat(title, " . snds.real: "); itoa(sound.vSounds.GetRealSize(), q, 10); strcat(title, q);
  323. strcat(title, " . play.size: "); itoa(sound.vPlayed.size(), q, 10); strcat(title, q);
  324. strcat(title, " . play.real: "); itoa(sound.vPlayed.GetRealSize(), q, 10); strcat(title, q);
  325. strcat(title, " . i1: "); itoa((int)i1, q, 10); strcat(title, q);
  326. float fps = timer.GetFPS();
  327. float mspf = timer.GetMSPF();
  328. // errfi("", fps);
  329. // erri("", mspf);
  330. // errfi("fps, mspf", fps, mspf);
  331. SetWindowText(hwnd, title);
  332. }
  333. bool InitializeGL()
  334. {
  335.    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);  // Clear the screen to black.
  336.    glShadeModel(GL_SMOOTH);               // Smooth shading in our scenes.
  337.    glEnable(GL_DEPTH_TEST);               // Enable desth testing for hidden surface removal.
  338.    glDisable(GL_LIGHTING);               // Enable desth testing for hidden surface removal.
  339. glDisable(GL_BLEND);
  340. glBlendFunc(GL_SRC_COLOR, GL_SRC_ALPHA);
  341. glEnable(GL_DEPTH_TEST);
  342. CreateOneColourTexture();
  343. CreateChaosTexture();
  344. CreateStarTexture();
  345. CreateLineObjectTexture();
  346. tex_id = CreateOneColourTexture();
  347. glEnable(GL_TEXTURE_2D);
  348. glClear(GL_ACCUM_BUFFER_BIT);
  349. srand(GetTickCount());
  350.    // If all went well we return true.
  351.    return true;
  352. }
  353. void rndSound()
  354. {
  355. if (rand() > 42+23) return;
  356. CPhysicObject *o;
  357. o = (CPhysicObject*)(sRoot.vKids.GetRandom());
  358. int snd_i = rand() % 9;
  359. char str[4];
  360. itoa(snd_i, str, 10);
  361. sound.PlaySound(str, &o->mMatrix.m_posit[0]);
  362. }
  363. void RenderScene()
  364. {
  365. rndSound();
  366. timer.Frame();
  367. TitleInfo();
  368. CSceneNode *n;
  369. n = sRoot.vKids.begin()[2];
  370. CMatrix m = n->mMatrix;
  371. /**/
  372. tt_draw.start();
  373. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);   // Clears the screen.
  374. glLoadIdentity();                   //Reset modelview matrix for new frame.
  375. gluLookAt(cam.x, cam.y, cam.z, m.m_posit.x, m.m_posit.y, m.m_posit.z, 0, 1, 0);
  376. glxMatrix(1);
  377. glBindTexture(GL_TEXTURE_2D, tex_id);
  378. mblur.step(1);
  379. sRoot.Update(timer.GetSPF());
  380. sRoot.Render();
  381. mblur.step(23);
  382. SwapBuffers(g_HDC);                 // Display the new frame by swapping the
  383. tt_draw.stamp();
  384. /**/
  385. /**/
  386. tt_snd.start();
  387. sound.Frame();
  388. tt_snd.stamp();
  389. /**/
  390. /**/
  391. tt_phys.start();
  392. physic.Frame(timer.GetSPF()*3);
  393. tt_phys.stamp();
  394. /**/
  395. }
  396. void abc()
  397. {
  398. }
  399. void brm()
  400. {
  401. }