GameHandler.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /************************************************************************
  2. * GameHandler.js
  3. ************************************************************************
  4. * Copyright (c) 2021 Pedro Tonini Rosenberg Schneider.
  5. *
  6. * This file is part of Pandora.
  7. *
  8. * Pandora is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * Pandora is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with Pandora. If not, see <https://www.gnu.org/licenses/>.
  20. *************************************************************************/
  21. /**
  22. * This {@code GameHandler} singleton provides an interface for the user
  23. * to manipulate various parameters of the game, instance objects, and more.
  24. *
  25. * @author Pedro Schneider
  26. *
  27. * @namespace
  28. */
  29. const GameHandler = {
  30. nextId: 0, // ID to be given to the next object added to the tree.
  31. rootObjects: [], // List of objects on the root of the tree.
  32. renderMode: 1, // Can be RENDER_MODES.P2D or RENDER_MODES.WEBGL.
  33. bDrawDebugFPS: false, // Should fps be drawn (for debug only).
  34. debugFpsLabel: null, // Object that drwas fps.
  35. bDrawDebugBufferBounds: false, // Should the secondary buffer's bounds be drawn?
  36. prevMillis: 0, // Milliseconds ellapsed since the begining of the application.
  37. delta: 0, // Milliseconds ellapsed since the last frame.
  38. db: null, // Object to hold the secondary buffer.
  39. dbWidth: 1920, // Width of the secondary buffer.
  40. dbHeight: 1080, // Height of the secondary buffer.
  41. isMobile: null, // True if the device is a mobile device (tablet of phone).
  42. pixelDen: 1, // Pixel density for the canvas on destop devices.
  43. pixelDenMobile: 2, // Pixel denisty for the canvas on mobile devices.
  44. mouseX: 0, // X position of the mouse relative to the secondary buffer.
  45. mouseY: 0, // Y position of the mouse relative to the secondary buffer.
  46. /**
  47. * Sets the initial game render mode.
  48. *
  49. * @param {RENDER_MODES} mode RENDER_MODES.P2D for default P5Js render or
  50. * RENDER_MODES.WEBGL for webgl (not recomended for mobile).
  51. */
  52. setRenderMode: function(mode)
  53. {
  54. this.renderMode = mode;
  55. },
  56. /**
  57. * Sets the width and height in pixels to initialize the secondary buffer.
  58. *
  59. * @param {number} w width in pixels to initialize the secondary buffer.
  60. * @param {number} h height in pixels to initialize the secondary buffer.
  61. */
  62. setDoubleBufferSize: function(w, h)
  63. {
  64. this.dbWidth = w;
  65. this.dbHeight = h;
  66. },
  67. /**
  68. * Sets the pixel density for the canvas to be initialized with on desktop
  69. * devices.
  70. *
  71. * @param {number} val pixel density for the canvas on desktop devices.
  72. */
  73. setPixelDensity: function(val)
  74. {
  75. this.pixelDen = val;
  76. },
  77. /**
  78. * Sets the pixel density for the canvas to be initialized with on desktop
  79. * devices.
  80. *
  81. * @param {number} val pixel density for the canvas on desktop devices.
  82. */
  83. setPixelDensityMobile: function(val)
  84. {
  85. this.pixelDenMobile = val;
  86. },
  87. /**
  88. * Sets the flag to draw the debug fps.
  89. *
  90. * @param {boolean} val true if debug fps should be drawn, false if not.
  91. */
  92. drawDebugFPS(val)
  93. {
  94. this.bDrawDebugFPS = val;
  95. },
  96. /**
  97. * Sets the flag to draw secondary buffer bounds.
  98. *
  99. * @param {boolean} val true if debug secondary buffer bounds should be drawn, false if not.
  100. */
  101. drawDebugBufferBounds(val)
  102. {
  103. this.bDrawDebugBufferBounds = val;
  104. },
  105. /**
  106. * Initializes the game, creating the canvas, secondary buffer, and creates the
  107. * debug fps label if necessary.
  108. *
  109. * @param {number} fps target fps for the game (default if 60).
  110. */
  111. init: function(fps = 60)
  112. {
  113. // Sets the mobile flag.
  114. this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  115. // Creates the main canvas and the secondary buffer with the specified size and render mode.
  116. switch (this.renderMode)
  117. {
  118. case RENDER_MODES.P2D:
  119. createCanvas(windowWidth, windowHeight);
  120. this.db = createGraphics(this.dbWidth, this.dbHeight);
  121. break;
  122. case RENDER_MODES.WEBGL:
  123. createCanvas(windowWidth, windowHeight, WEBGL);
  124. this.db = createGraphics(this.dbWidth, this.dbHeight, WEBGL);
  125. this.db.smooth();
  126. break;
  127. }
  128. // Sets framerate and pixel density accordingly.
  129. frameRate(fps);
  130. if (this.isMobile)
  131. pixelDensity(this.pixelDenMobile);
  132. else
  133. pixelDensity(this.pixelDen);
  134. smooth();
  135. // Translates the canvas to the middle if render mode is webgl to maintain
  136. // consistency on the coordinate system.
  137. if (this.renderMode == RENDER_MODES.WEBGL)
  138. {
  139. translate(-windowWidth / 2, -windowHeight / 2);
  140. db.translate(-this.dbWidth / 2, -this.dbHeight / 2);
  141. }
  142. // Creates the debug fps label.
  143. if (this.bDrawDebugFPS)
  144. {
  145. this.debugFpsLabel = new Label("debugFps", `FPS: ${frameRate()}`);
  146. this.addRootObject(this.debugFpsLabel);
  147. }
  148. },
  149. /**
  150. * Instances a GameObject, meaning to give it an ID. This function is only called on the
  151. * constructor of GameObject, and probably shouldn't be used for anything else.
  152. *
  153. * @param {GameObject} obj GameObject to be instanced.
  154. */
  155. instanceGameObject: function(obj)
  156. {
  157. obj.id = this.nextId;
  158. this.nextId++;
  159. },
  160. /**
  161. * Adds a GameObject to the root of the tree. There should be as little root objects as possible.
  162. *
  163. * @param {GameObject} obj GameObject to be added as a root of the tree.
  164. */
  165. addRootObject: function(obj)
  166. {
  167. this.rootObjects.push(obj);
  168. obj.isRoot = true;
  169. obj.setup();
  170. },
  171. /**
  172. * Removes a GameObject from the root of the tree. This function is called automatically when a root object
  173. * is freed from memory, and probably shoudn't be used for anything else. DOES NOT DELETE THE OBJECT, ONLY
  174. * REMOVES IT FROM THE TREE.
  175. *
  176. * @param {number} id object id of the GameObject that should be removed from the tree.
  177. */
  178. removeRootObjectById: function(id)
  179. {
  180. for (let i = 0; i < this.rootObjects.length; i++)
  181. {
  182. if (this.rootObjects[i].id == id)
  183. this.rootObjects.splice(i, 1);
  184. }
  185. },
  186. upframecount: 0, // Frame count to be displayed.
  187. upframenum: 20, // Delay in frames to update the frame count.
  188. /**
  189. * Updates all of the GameObjects on the tree.
  190. */
  191. update: function()
  192. {
  193. // Updates the debug fps label if it existis.
  194. if (this.bDrawDebugFPS)
  195. {
  196. if (frameCount % this.upframenum == 0)
  197. {
  198. this.debugFpsLabel.setText(`FPS: ${
  199. Math.round(this.upframecount * 1000) / 1000
  200. }`);
  201. this.upframecount = 0;
  202. }
  203. else
  204. this.upframecount = max(this.upframecount, frameRate());
  205. }
  206. // Updates the delta.
  207. this.delta = (millis() - this.prevMillis) / 1000;
  208. let ar = this.db.screenWidth / this.db.width;
  209. let offsetx = (windowWidth - this.db.screenWidth) / 2;
  210. let offsety = (windowHeight - this.db.screenHeight) / 2;
  211. this.mouseX = (mouseX - offsetx) / ar;
  212. this.mouseY = (mouseY - offsety) / ar;
  213. // Updates all game objects on the tree.
  214. for (let i = 0; i < this.rootObjects.length; i++)
  215. this.rootObjects[i].update(this.delta);
  216. },
  217. /**
  218. * Draws all of the GameObjects on the tree.
  219. */
  220. draw: function()
  221. {
  222. // Clear the secondary buffer.
  223. this.db.clear();
  224. if (this.bDrawDebugBufferBounds)
  225. {
  226. // Draw a rectangle to visualize the secondary buffer.
  227. this.db.push();
  228. this.db.strokeWeight(5);
  229. this.db.noFill();
  230. this.db.rect(0, 0, this.dbWidth, this.dbHeight);
  231. this.db.pop();
  232. }
  233. // Centers the image and calculates the dimensions of the secondary
  234. // buffer to best fit the size of the window.
  235. imageMode(CENTER);
  236. if (windowWidth / windowHeight < this.dbWidth / this.dbHeight)
  237. {
  238. this.db.screenWidth = windowWidth;
  239. this.db.screenHeight = windowWidth * (this.dbHeight / this.dbWidth);
  240. }
  241. else
  242. {
  243. this.db.screenHeight = windowHeight;
  244. this.db.screenWidth = windowHeight * (this.dbWidth / this.dbHeight);
  245. }
  246. // Draw all game objects.
  247. for (let i = 0; i < this.rootObjects.length; i++)
  248. this.rootObjects[i].draw(this.delta, this.db);
  249. // Draws the secondary buffer to the main canvas.
  250. image(this.db, windowWidth / 2, windowHeight / 2, this.db.screenWidth, this.db.screenHeight);
  251. // Updates the delta
  252. this.prevMillis = millis();
  253. }
  254. }
  255. /**
  256. * This function is called once every time the browser window is resized. Here, its used to make the game
  257. * always ocupy the entire browser window.
  258. *
  259. * @callback
  260. */
  261. function windowResized()
  262. {
  263. resizeCanvas(windowWidth, windowHeight);
  264. }