1 /* 2 Copyright © 2020, Luna Nielsen 3 Distributed under the 2-Clause BSD License, see LICENSE file. 4 5 Authors: Luna Nielsen 6 */ 7 module engine.game; 8 import bindbc.glfw; 9 import engine; 10 11 private double previousTime_; 12 private double currentTime_; 13 private double deltaTime_; 14 15 /** 16 Function run when the game is to initialize 17 */ 18 void function() gameInit; 19 20 /** 21 Function run when the game is to update 22 */ 23 void function() gameUpdate; 24 25 /** 26 Function run after the main rendering has happened, Used to draw borders for the gameplay 27 */ 28 void function() gameBorder; 29 30 /** 31 Function run after updates and rendering of the game 32 */ 33 void function() gamePostUpdate; 34 35 /** 36 Function run when the game is to clean up 37 */ 38 void function() gameCleanup; 39 40 /** 41 Starts the game loop 42 43 viewportSize sets the desired viewport size for the framebuffer, defaults to 1080p (1920x1080) 44 */ 45 void startGame(vec2i viewportSize = vec2i(1920, 1080)) { 46 gameInit(); 47 resetTime(); 48 49 Framebuffer framebuffer = new Framebuffer(GameWindow, viewportSize); 50 while(!GameWindow.isExitRequested) { 51 52 currentTime_ = glfwGetTime(); 53 deltaTime_ = currentTime_-previousTime_; 54 previousTime_ = currentTime_; 55 56 // Bind our framebuffer 57 framebuffer.bind(); 58 59 // Clear color and depth buffers 60 glClearColor(0, 0, 0, 1); 61 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 62 63 // Update and render the game 64 gameUpdate(); 65 66 // Unbind our framebuffer 67 framebuffer.unbind(); 68 69 // Clear color and depth bits 70 glClearColor(0, 0, 0, 0); 71 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 72 73 // Draw border, framebuffer and post update content 74 if (gameBorder !is null) gameBorder(); 75 framebuffer.renderToFit(); 76 if (gamePostUpdate !is null) gamePostUpdate(); 77 78 // Update the mouse's state 79 Mouse.update(); 80 Input.update(); 81 82 // Swap buffers and update the window 83 GameWindow.swapBuffers(); 84 GameWindow.update(); 85 } 86 87 // Pop all states 88 GameStateManager.popAll(); 89 90 // Game cleanup 91 gameCleanup(); 92 } 93 94 /** 95 Gets delta time 96 */ 97 double deltaTime() { 98 return deltaTime_; 99 } 100 101 /** 102 Gets delta time 103 */ 104 double prevTime() { 105 return previousTime_; 106 } 107 108 /** 109 Gets delta time 110 */ 111 double currTime() { 112 return currentTime_; 113 } 114 115 /** 116 Resets the time scale 117 */ 118 void resetTime() { 119 glfwSetTime(0); 120 previousTime_ = 0; 121 currentTime_ = 0; 122 }