outdated: 39.Introduction to Physical Simulations
这一节说明了三种运动,直线运动,弹性运动和万有引力下运动。本节对三种运动在每个点上力做了分析。
Physics.h文件中定义了四个类,Vector3D类重载了基本的操作运算符和求解法向量函数。Mass类有基本的质量m、位置position、速率velocity和力force,及牛顿第一定律。Simulation类为模拟类,ConstantVelocity类、MotionUnderGravitation类和MassConnectedWithSpring类都继承自Simulation类。
下面为代码,
#ifndef GL_FRAMEWORK_INCLUDED #define GL_FRAMEWORK_INCLUDED #include <windows.h> typedef struct { // Structure for keyboard stuff BOOL keyDown[256]; } Keys; typedef struct { // Contains information vital to applications HMODULE hInstance; // Application Instance const char* className; } Application; typedef struct { // Window creation info Application* application; char* title; int width; int height; int bitsPerPixel; BOOL isFullScreen; } GL_WindowInit; typedef struct { // Contains information vital to a window Keys* keys; HWND hWnd; // Windows handle HDC hDC; // Device context HGLRC hRC; // Rendering context GL_WindowInit init; BOOL isVisible; // Window visiable? DWORD lastTickCount; // Tick counter } GL_Window; void TerminateApplication(GL_Window* window); // Terminate the application void ToggleFullscreen(GL_Window* window); // Toggle fullscreen / Windowed mode BOOL Initialize(GL_Window* window, Keys* keys); void Deinitialize(void); void Update(DWORD milliseconds); void Draw(void); #endif
#include <Windows.h> #include <GL\glew.h> #include <GL\glut.h> #include "Previous.h" #define WM_TOGGLEFULLSCREEN (WM_USER+1) // Application define message for toggling // between fulscreen / windowed mode static BOOL g_isProgramLooping; // Window creation loop, for fullscreen / windowed mode static BOOL g_createFullScreen; // If true, then create window void TerminateApplication(GL_Window* window) // Terminate the application { PostMessage(window->hWnd, WM_QUIT, 0, 0); // Send a WM_QUIT message g_isProgramLooping = FALSE; // Stop looping of the program } void ToggleFullscreen(GL_Window* window) // Toggle fullscreen /windowed mode { PostMessage(window->hWnd, WM_TOGGLEFULLSCREEN, 0, 0); // Send a WM_TOGGLEFULLSCREEN message } void ReshapeGL(int width, int height) // Reshape the window when it's moved or resized { glViewport(0, 0, (GLsizei)(width), (GLsizei)(height)); // Reset the current viewport glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Calcutate the aspect ratio of the window gluPerspective(45.0f, (GLfloat)(width) / (GLfloat)(height), 1.0, 100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } BOOL ChangeScreenResolution(int width, int height, int bitsPerPixel) // Change the screen resolution { DEVMODE dmScreenSettings; // Device mode ZeroMemory(&dmScreenSettings, sizeof(DEVMODE)); // Make sure memory is cleared dmScreenSettings.dmSize = sizeof(DEVMODE); // Size of the devmode structure dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bitsPerPixel; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { return FALSE; // Display change failed } return TRUE; } BOOL CreateWindowGL(GL_Window* window) { DWORD windowStyle = WS_OVERLAPPEDWINDOW; // Define window style DWORD windowExtendedStyle = WS_EX_APPWINDOW; // Define the window's extended style PIXELFORMATDESCRIPTOR pdf = { 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 window->init.bitsPerPixel, // Select 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, // 16bits 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 }; RECT windowRect = { 0, 0, window->init.width, window->init.height }; // Window coordiantes GLuint PixelFormat; if (window->init.isFullScreen == TRUE) { if (ChangeScreenResolution(window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE) { // Fullscreen mode failed, run in windowed mode instead MessageBox(HWND_DESKTOP, "Mode Switch Failed.\nRuning In Windowed Mode.", "Error", MB_OK | MB_ICONEXCLAMATION); window->init.isFullScreen = FALSE; } else { ShowCursor(FALSE); windowStyle = WS_POPUP; // Popup window windowExtendedStyle |= WS_EX_TOPMOST; } } else { // Adjust window, account for window borders AdjustWindowRectEx(&windowRect, windowStyle, 0, windowExtendedStyle); } // Create Opengl window window->hWnd = CreateWindowEx(windowExtendedStyle, // Extended style window->init.application->className, // Class name window->init.title, // Window title windowStyle, // Window style 0, 0, // Window X,Y position windowRect.right - windowRect.left, // Window width windowRect.bottom - windowRect.top, // Window height HWND_DESKTOP, // Desktop is window's parent 0, // No menu window->init.application->hInstance, // Pass the window instance window); if (window->hWnd == 0) { // Was window creation a success? return FALSE; } window->hDC = GetDC(window->hWnd); if (window->hDC == 0) { DestroyWindow(window->hWnd); window->hWnd = 0; return FALSE; } PixelFormat = ChoosePixelFormat(window->hDC, &pdf); // Find a compatible pixel format if (PixelFormat == 0) { ReleaseDC(window->hWnd, window->hDC); // Release device context window->hDC = 0; DestroyWindow(window->hWnd); window->hWnd = 0; return FALSE; } if (SetPixelFormat(window->hDC, PixelFormat, &pdf) == FALSE) { // Try to set the pixel format ReleaseDC(window->hWnd, window->hDC); window->hDC = 0; DestroyWindow(window->hWnd); window->hWnd = 0; return FALSE; } window->hRC = wglCreateContext(window->hDC); // Try to get a rendering context if (window->hRC == 0) { ReleaseDC(window->hWnd, window->hDC); window->hDC = 0; DestroyWindow(window->hWnd); window->hWnd = 0; return FALSE; } // Make the rendering context our current rendering context if (wglMakeCurrent(window->hDC, window->hRC) == FALSE) { wglDeleteContext(window->hRC); // Delete the rendering context window->hRC = 0; ReleaseDC(window->hWnd, window->hDC); window->hDC = 0; DestroyWindow(window->hWnd); window->hWnd = 0; return FALSE; } ShowWindow(window->hWnd, SW_NORMAL); // Make the window visiable window->isVisible = TRUE; ReshapeGL(window->init.width, window->init.height); // Reshape our GL window ZeroMemory(window->keys, sizeof(Keys)); // Clear all keys window->lastTickCount = GetTickCount(); return TRUE; } BOOL DestoryWindowGL(GL_Window* window) { if (window->hWnd != 0) { if (window->hDC != 0) { wglMakeCurrent(window->hDC, 0); // Setting current active rendering context to zero if (window->hRC != 0) { wglDeleteContext(window->hRC); window->hRC = 0; } ReleaseDC(window->hWnd, window->hDC); window->hDC = 0; } DestroyWindow(window->hWnd); window->hWnd = 0; } if (window->init.isFullScreen) { ChangeDisplaySettings(NULL, 0); // Switch back to desktop resolution ShowCursor(TRUE); } return TRUE; } // Process window message callback LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Get the window context GL_Window* window = (GL_Window*)(GetWindowLong(hWnd, GWL_USERDATA)); switch (uMsg) { // Evaluate window message case WM_SYSCOMMAND: // Intercept system commands { switch (wParam) { // Check system calls case SC_SCREENSAVE: // Screensaver trying to start? case SC_MONITORPOWER: // Mointer trying to enter powersave? return 0; // Prevent form happening } break; } return 0; case WM_CREATE: { CREATESTRUCT* creation = (CREATESTRUCT*)(lParam); // Store window structure pointer window = (GL_Window*)(creation->lpCreateParams); SetWindowLong(hWnd, GWL_USERDATA, (LONG)(window)); } return 0; case WM_CLOSE: TerminateApplication(window); return 0; case WM_SIZE: switch (wParam) { case SIZE_MINIMIZED: // Was window minimized? window->isVisible = FALSE; return 0; case SIZE_MAXIMIZED: window->isVisible = TRUE; ReshapeGL(LOWORD(lParam), HIWORD(lParam)); return 0; case SIZE_RESTORED: window->isVisible = TRUE; ReshapeGL(LOWORD(lParam), HIWORD(lParam)); return 0; } break; case WM_KEYDOWN: if ((wParam >= 0) && (wParam <= 255)) { window->keys->keyDown[wParam] = TRUE; // Set the selected key(wParam) to true return 0; } break; case WM_KEYUP: if ((wParam >= 0) && (wParam <= 255)) { window->keys->keyDown[wParam] = FALSE; return 0; } break; case WM_TOGGLEFULLSCREEN: g_createFullScreen = (g_createFullScreen == TRUE) ? FALSE : TRUE; PostMessage(hWnd, WM_QUIT, 0, 0); break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); // Pass unhandle message to DefWindowProc } BOOL RegisterWindowClass(Application* application) { WNDCLASSEX windowClass; ZeroMemory(&windowClass, sizeof(WNDCLASSEX)); // Make sure memory is cleared windowClass.cbSize = sizeof(WNDCLASSEX); // Size of the windowClass structure windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraws the window for any movement / resizing windowClass.lpfnWndProc = (WNDPROC)(WindowProc); // WindowProc handles message windowClass.hInstance = application->hInstance; // Set the instance windowClass.hbrBackground = (HBRUSH)(COLOR_APPWORKSPACE);// Class background brush color windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Load the arrow pointer windowClass.lpszClassName = application->className; // Sets the application className if (RegisterClassEx(&windowClass) == 0) { MessageBox(HWND_DESKTOP, "RegisterClassEx Failed!", "Error", MB_OK | MB_ICONEXCLAMATION); return FALSE; } return TRUE; } int WINAPI WinMain(HINSTANCE hIstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { Application application; GL_Window window; Keys keys; BOOL isMessagePumpActive; MSG msg; DWORD tickCount; application.className = "OpenGL"; application.hInstance = hIstance; ZeroMemory(&window, sizeof(GL_Window)); window.keys = &keys; // Window key structure window.init.application = &application; // Window application window.init.title = "Resource File"; // Window title window.init.width = 640; // Window width window.init.height = 480; // Window height window.init.bitsPerPixel = 16; // Bits per pixel window.init.isFullScreen = TRUE; // Fullscreen? (set to TRUE) ZeroMemory(&keys, sizeof(Keys)); if (MessageBox(HWND_DESKTOP, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) { window.init.isFullScreen = FALSE; } if (RegisterWindowClass(&application) == FALSE) { MessageBox(HWND_DESKTOP, "Error Registering Window Class!", "Error", MB_OK | MB_ICONEXCLAMATION); return -1; } g_isProgramLooping = TRUE; g_createFullScreen = window.init.isFullScreen; while (g_isProgramLooping) { // Loop until WM_QUIT is received window.init.isFullScreen = g_createFullScreen; // Set init param of window creation to fullscreen? if (CreateWindowGL(&window) == TRUE) { // Was window creation successful? // At this point we should have a window that is setup to render OpenGL if (Initialize(&window, &keys) == FALSE) { TerminateApplication(&window); // Close window, this will handle the shutdown } else { isMessagePumpActive = TRUE; while (isMessagePumpActive == TRUE) { // Success creating window. Check for window messages if (PeekMessage(&msg, window.hWnd, 0, 0, PM_REMOVE) != 0) { if (msg.message != WM_QUIT) { DispatchMessage(&msg); } else { isMessagePumpActive = FALSE; // Terminate the message pump } } else { if (window.isVisible == FALSE) { WaitMessage(); // Application is minimized wait for a message } else { // Process application loop tickCount = GetTickCount(); // Get the tick count Update(tickCount - window.lastTickCount); // Update the counter window.lastTickCount = tickCount;// Set last count to current count Draw(); // Draw screen SwapBuffers(window.hDC); } } } } // Application is finished Deinitialize(); DestoryWindowGL(&window); } else { MessageBox(HWND_DESKTOP, "Error Creating OpenGL Window", "Error", MB_OK | MB_ICONEXCLAMATION); g_isProgramLooping = FALSE; } } UnregisterClass(application.className, application.hInstance); // UnRegister window class return 0; }
#include <math.h> class Vector3D { public: float x, y, z; Vector3D(): x(0), y(0), z(0) {} Vector3D(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } Vector3D& operator= (Vector3D v) { x = v.x; y = v.y; z = v.z; return *this; } Vector3D operator+ (Vector3D v) { return Vector3D(x + v.x, y + v.y, z + v.z); } Vector3D operator- (Vector3D v) { return Vector3D(x - v.x, y - v.y, z - v.z); } Vector3D operator* (float value) { return Vector3D(x * value, y * value, z * value); } Vector3D operator/ (float value) { return Vector3D(x / value, y / value, z / value); } Vector3D& operator+= (Vector3D v) { x += v.x; y += v.y; z += v.z; return *this; } Vector3D& operator-= (Vector3D v) { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3D& operator*= (Vector3D v) { x *= v.x; y *= v.y; z *= v.z; return *this; } Vector3D& operator/= (Vector3D v) { x /= v.x; y /= v.y; z /= v.z; return *this; } Vector3D operator- () { return Vector3D(-x, -y, -z); } float length() { return sqrtf(x*x + y*y + z*z); } void unitize() // Normalizes { float length = this->length(); if (length == 0) return; x /= length; y /= length; z /= length; } Vector3D unit() // Normalizes return a new Vector3D { float length = this->length(); if (length == 0) return *this; return Vector3D(x / length, y / length, z / length); } }; class Mass { public: float m; // The mass value Vector3D pos; // Position Vector3D vel; // Velocity Vector3D force; // Force Mass(float m): m(m) {} void applyForce(Vector3D force) { this->force += force; } void init() { force.x = 0; force.y = 0; force.z = 0; } void simulate(float dt) // New velocity and position { vel += (force / m) * dt; pos += vel * dt; } }; class Simulation { public: int numOfMasses; Mass** masses; Simulation(int numOfMasses, float m) // Constructor { this->numOfMasses = numOfMasses; masses = new Mass*[numOfMasses]; for (int i = 0; i < numOfMasses; ++i) { masses[i] = new Mass(m); } } virtual void release() // Delete { for (int i = 0; i < numOfMasses; ++i) { delete(masses[i]); masses[i] = NULL; } delete(masses); masses = NULL; } Mass* getMass(int index) { if (index < 0 || index >= numOfMasses) { return NULL; } return masses[index]; } virtual void init() { for (int i = 0; i < numOfMasses; ++i) { masses[i]->init(); } } // No implementation because no forces are wanted in this basic container // in advanced containers, this method will be overrided and some forces will act on masses virtual void solve() {} virtual void simulate(float dt) { for (int i = 0; i < numOfMasses; ++i) { masses[i]->simulate(dt); } } virtual void operate(float dt) // The complete produce of simulation { init(); solve(); simulate(dt); } }; class ConstantVelocity : public Simulation { public: ConstantVelocity() : Simulation(1, 1.0f) { masses[0]->pos = Vector3D(0.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D(1.0f, 0.0f, 0.0f); } }; class MotionUnderGravitation : public Simulation { public: Vector3D gravitation; MotionUnderGravitation(Vector3D gravitation) : Simulation(1, 1.0f) { this->gravitation = gravitation; masses[0]->pos = Vector3D(-10.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D(10.0f, 15.0f, 0.0f); } virtual void solve() { for (int i = 0; i < numOfMasses; ++i) { masses[i]->applyForce(gravitation * masses[i]->m); } } }; class MassConnectedWithSpring : public Simulation { public: float springConstant; // More the springConstant, stiffer the spring force Vector3D connectionPos; // The arbitrary constant point that the mass is connected MassConnectedWithSpring(float springConstant) :Simulation(1, 1.0f) { this->springConstant = springConstant; connectionPos = Vector3D(0.0f, -5.0f, 0.0f); masses[0]->pos = connectionPos + Vector3D(10.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D(0.0f, 0.0f, 0.0f); } virtual void solve() { for (int i = 0; i < numOfMasses; ++i) { Vector3D springVector = masses[i]->pos - connectionPos; masses[i]->applyForce(-springVector * springConstant); } } };
#include <Windows.h> #include <GL/glew.h> #include <GL/glut.h> #include <GL/GLUAX.H> #include <math.h> #include <stdio.h> #include "Previous.h" #include "Physics.h" // Introduction to Physical Simulations #pragma comment(lib, "legacy_stdio_definitions.lib") #ifndef CDS_FULLSCREEN #define CDS_FULLSCREEN 4 #endif GL_Window* g_window; Keys* g_keys; ConstantVelocity* constantVelocity = new ConstantVelocity(); MotionUnderGravitation* motionUnderGravitation = new MotionUnderGravitation(Vector3D(0.0f, -9.81f, 0.0f)); MassConnectedWithSpring* massConnectedWithSpring = new MassConnectedWithSpring(2.0f); float slowMotionRatio = 10.0f; // Slow down the simulation float timeElapsed = 0; // Not equal to real world's time unless slowMotionRatio Is 1 GLuint base; // Display GLYPHMETRICSFLOAT gmf[256]; // Storage font characters GLvoid BuildFont(GL_Window* window) // Build bitmap font { HFONT font; base = glGenLists(256); font = CreateFont(-12, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH, NULL); HDC hDC = window->hDC; SelectObject(hDC, font); wglUseFontOutlines(hDC, // Select the current DC 0, // Starting character 255, // Number of display lists to build base, // Starting display lists 0.0f, // Deviation from the true outlines 0.0f, // Font thickness in the Z direction WGL_FONT_POLYGONS, // Use polygons, not lines gmf); // Address of buffer to recieve data } GLvoid KillFont(GLvoid) { glDeleteLists(base, 256); } GLvoid glPrint(float x, float y, float z, const char* fmt, ...) { float length = 0; // The length of text char text[256]; // String va_list ap; // Pointer to list of arguments if (fmt == NULL) { return; } va_start(ap, fmt); vsprintf(text, fmt, ap); va_end(ap); for (unsigned int loop = 0; loop < (strlen(text)); ++loop) { length += gmf[text[loop]].gmfCellIncX; // Increase length by each characters width } glTranslatef(x - length, y, z); glPushAttrib(GL_LIST_BIT); glListBase(base); glCallLists(strlen(text), GL_UNSIGNED_BYTE, text); glPopAttrib(); glTranslatef(-x, -y, -z); } BOOL Initialize(GL_Window* window, Keys* keys) { g_window = window; g_keys = keys; glClearColor(0.0f, 0.0f, 0.0f, 0.5f); glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); BuildFont(window); return TRUE; } void Deinitialize(void) { KillFont(); constantVelocity->release(); delete(constantVelocity); constantVelocity = NULL; motionUnderGravitation->release(); delete(motionUnderGravitation); motionUnderGravitation = NULL; massConnectedWithSpring->release(); delete(massConnectedWithSpring); massConnectedWithSpring = NULL; } void Update(DWORD milliseconds) { if (g_keys->keyDown[VK_ESCAPE] == TRUE) { TerminateApplication(g_window); } if (g_keys->keyDown[VK_F1] == TRUE) { ToggleFullscreen(g_window); } if (g_keys->keyDown[VK_F2] == TRUE) { slowMotionRatio = 1.0f; } if (g_keys->keyDown[VK_F3] == TRUE) { slowMotionRatio = 10.0f; } float dt = milliseconds / 1000.0f; dt /= slowMotionRatio; timeElapsed += dt; float maxPossible_dt = 0.1f; //The maximum possible dt is 0.1 seconds int numOfIterations = (int)(dt / maxPossible_dt) + 1; if (numOfIterations != 0) { dt = dt / numOfIterations; } for (int i = 0; i < numOfIterations; ++i) { constantVelocity->operate(dt); motionUnderGravitation->operate(dt); massConnectedWithSpring->operate(dt); } } void Draw(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0, 0, 40, 0, 0, 0, 0, 1, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor3ub(0, 0, 255); // Blue glBegin(GL_LINES); for (float x = -20; x <= 20; x += 1.0f) { glVertex3f(x, 20, 0); glVertex3f(x, -20, 0); } for (float y = -20; y <= 20; y += 1.0f) { glVertex3f(20, y, 0); glVertex3f(-20, y, 0); } glEnd(); glColor3ub(255, 0, 0); for (int i = 0; i < constantVelocity->numOfMasses; ++i) { Mass* mass = constantVelocity->getMass(i); Vector3D* pos = &mass->pos; glPrint(pos->x, pos->y + 1, pos->z, "Mass with constant vel"); glPointSize(4); glBegin(GL_POINTS); glVertex3f(pos->x, pos->y, pos->z); glEnd(); } glColor3ub(255, 255, 0); for (int i = 0; i < motionUnderGravitation->numOfMasses; ++i) { Mass* mass = motionUnderGravitation->getMass(i); Vector3D* pos = &mass->pos; glPrint(pos->x, pos->y + 1, pos->z, "Motion under gravitation"); glPointSize(4); glBegin(GL_POINTS); glVertex3f(pos->x, pos->y, pos->z); glEnd(); } glColor3ub(0, 255, 0); for (int i = 0; i < massConnectedWithSpring->numOfMasses; ++i) { Mass* mass = massConnectedWithSpring->getMass(i); Vector3D* pos = &mass->pos; glPrint(pos->x, pos->y + 1, pos->z, "Mass connected with spring"); glPointSize(8); glBegin(GL_POINTS); glVertex3f(pos->x, pos->y, pos->z); glEnd(); glBegin(GL_LINES); glVertex3f(pos->x, pos->y, pos->z); pos = &massConnectedWithSpring->connectionPos; glVertex3f(pos->x, pos->y, pos->z); glEnd(); } glColor3ub(255, 255, 255); glPrint(-5.0f, 14, 0, "Time elapsed (seconds): %.2f", timeElapsed); glPrint(-5.0f, 13, 0, "Slow motion ratio: %.2f", slowMotionRatio); glPrint(-5.0f, 12, 0, "Press F2 for normal motion"); glPrint(-5.0f, 11, 0, "Press F3 for slow motion"); glFlush(); }
Thanks for Nehe's tutorials, this is his home.