config.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /**
  2. * An object used to configure the Engine instance based on godot export options, and to override those in custom HTML
  3. * templates if needed.
  4. *
  5. * @header Engine configuration
  6. * @summary The Engine configuration object. This is just a typedef, create it like a regular object, e.g.:
  7. *
  8. * ``const MyConfig = { executable: 'godot', unloadAfterInit: false }``
  9. *
  10. * @typedef {Object} EngineConfig
  11. */
  12. const EngineConfig = {}; // eslint-disable-line no-unused-vars
  13. /**
  14. * @struct
  15. * @constructor
  16. * @ignore
  17. */
  18. const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-vars
  19. const cfg = /** @lends {InternalConfig.prototype} */ {
  20. /**
  21. * Whether the unload the engine automatically after the instance is initialized.
  22. *
  23. * @memberof EngineConfig
  24. * @default
  25. * @type {boolean}
  26. */
  27. unloadAfterInit: true,
  28. /**
  29. * The HTML DOM Canvas object to use.
  30. *
  31. * By default, the first canvas element in the document will be used is none is specified.
  32. *
  33. * @memberof EngineConfig
  34. * @default
  35. * @type {?HTMLCanvasElement}
  36. */
  37. canvas: null,
  38. /**
  39. * The name of the WASM file without the extension. (Set by Godot Editor export process).
  40. *
  41. * @memberof EngineConfig
  42. * @default
  43. * @type {string}
  44. */
  45. executable: '',
  46. /**
  47. * An alternative name for the game pck to load. The executable name is used otherwise.
  48. *
  49. * @memberof EngineConfig
  50. * @default
  51. * @type {?string}
  52. */
  53. mainPack: null,
  54. /**
  55. * Specify a language code to select the proper localization for the game.
  56. *
  57. * The browser locale will be used if none is specified. See complete list of
  58. * :ref:`supported locales <doc_locales>`.
  59. *
  60. * @memberof EngineConfig
  61. * @type {?string}
  62. * @default
  63. */
  64. locale: null,
  65. /**
  66. * The canvas resize policy determines how the canvas should be resized by Godot.
  67. *
  68. * ``0`` means Godot won't do any resizing. This is useful if you want to control the canvas size from
  69. * javascript code in your template.
  70. *
  71. * ``1`` means Godot will resize the canvas on start, and when changing window size via engine functions.
  72. *
  73. * ``2`` means Godot will adapt the canvas size to match the whole browser window.
  74. *
  75. * @memberof EngineConfig
  76. * @type {number}
  77. * @default
  78. */
  79. canvasResizePolicy: 2,
  80. /**
  81. * The arguments to be passed as command line arguments on startup.
  82. *
  83. * See :ref:`command line tutorial <doc_command_line_tutorial>`.
  84. *
  85. * **Note**: :js:meth:`startGame <Engine.prototype.startGame>` will always add the ``--main-pack`` argument.
  86. *
  87. * @memberof EngineConfig
  88. * @type {Array<string>}
  89. * @default
  90. */
  91. args: [],
  92. /**
  93. * When enabled, this will turn on experimental virtual keyboard support on mobile.
  94. *
  95. * @memberof EngineConfig
  96. * @type {boolean}
  97. * @default
  98. */
  99. experimentalVK: false,
  100. /**
  101. * @ignore
  102. * @type {Array.<string>}
  103. */
  104. persistentPaths: ['/userfs'],
  105. /**
  106. * @ignore
  107. * @type {boolean}
  108. */
  109. persistentDrops: false,
  110. /**
  111. * @ignore
  112. * @type {Array.<string>}
  113. */
  114. gdnativeLibs: [],
  115. /**
  116. * @ignore
  117. * @type {Array.<string>}
  118. */
  119. fileSizes: [],
  120. /**
  121. * A callback function for handling Godot's ``OS.execute`` calls.
  122. *
  123. * This is for example used in the Web Editor template to switch between project manager and editor, and for running the game.
  124. *
  125. * @callback EngineConfig.onExecute
  126. * @param {string} path The path that Godot's wants executed.
  127. * @param {Array.<string>} args The arguments of the "command" to execute.
  128. */
  129. /**
  130. * @ignore
  131. * @type {?function(string, Array.<string>)}
  132. */
  133. onExecute: null,
  134. /**
  135. * A callback function for being notified when the Godot instance quits.
  136. *
  137. * **Note**: This function will not be called if the engine crashes or become unresponsive.
  138. *
  139. * @callback EngineConfig.onExit
  140. * @param {number} status_code The status code returned by Godot on exit.
  141. */
  142. /**
  143. * @ignore
  144. * @type {?function(number)}
  145. */
  146. onExit: null,
  147. /**
  148. * A callback function for displaying download progress.
  149. *
  150. * The function is called once per frame while downloading files, so the usage of ``requestAnimationFrame()``
  151. * is not necessary.
  152. *
  153. * If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate.
  154. * Possible reasons include:
  155. *
  156. * - Files are delivered with server-side chunked compression
  157. * - Files are delivered with server-side compression on Chromium
  158. * - Not all file downloads have started yet (usually on servers without multi-threading)
  159. *
  160. * @callback EngineConfig.onProgress
  161. * @param {number} current The current amount of downloaded bytes so far.
  162. * @param {number} total The total amount of bytes to be downloaded.
  163. */
  164. /**
  165. * @ignore
  166. * @type {?function(number, number)}
  167. */
  168. onProgress: null,
  169. /**
  170. * A callback function for handling the standard output stream. This method should usually only be used in debug pages.
  171. *
  172. * By default, ``console.log()`` is used.
  173. *
  174. * @callback EngineConfig.onPrint
  175. * @param {...*} [var_args] A variadic number of arguments to be printed.
  176. */
  177. /**
  178. * @ignore
  179. * @type {?function(...*)}
  180. */
  181. onPrint: function () {
  182. console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
  183. },
  184. /**
  185. * A callback function for handling the standard error stream. This method should usually only be used in debug pages.
  186. *
  187. * By default, ``console.error()`` is used.
  188. *
  189. * @callback EngineConfig.onPrintError
  190. * @param {...*} [var_args] A variadic number of arguments to be printed as errors.
  191. */
  192. /**
  193. * @ignore
  194. * @type {?function(...*)}
  195. */
  196. onPrintError: function (var_args) {
  197. console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
  198. },
  199. };
  200. /**
  201. * @ignore
  202. * @struct
  203. * @constructor
  204. * @param {EngineConfig} opts
  205. */
  206. function Config(opts) {
  207. this.update(opts);
  208. }
  209. Config.prototype = cfg;
  210. /**
  211. * @ignore
  212. * @param {EngineConfig} opts
  213. */
  214. Config.prototype.update = function (opts) {
  215. const config = opts || {};
  216. function parse(key, def) {
  217. if (typeof (config[key]) === 'undefined') {
  218. return def;
  219. }
  220. return config[key];
  221. }
  222. // Module config
  223. this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
  224. this.onPrintError = parse('onPrintError', this.onPrintError);
  225. this.onPrint = parse('onPrint', this.onPrint);
  226. this.onProgress = parse('onProgress', this.onProgress);
  227. // Godot config
  228. this.canvas = parse('canvas', this.canvas);
  229. this.executable = parse('executable', this.executable);
  230. this.mainPack = parse('mainPack', this.mainPack);
  231. this.locale = parse('locale', this.locale);
  232. this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
  233. this.persistentPaths = parse('persistentPaths', this.persistentPaths);
  234. this.persistentDrops = parse('persistentDrops', this.persistentDrops);
  235. this.experimentalVK = parse('experimentalVK', this.experimentalVK);
  236. this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
  237. this.fileSizes = parse('fileSizes', this.fileSizes);
  238. this.args = parse('args', this.args);
  239. this.onExecute = parse('onExecute', this.onExecute);
  240. this.onExit = parse('onExit', this.onExit);
  241. };
  242. /**
  243. * @ignore
  244. * @param {string} loadPath
  245. * @param {Response} response
  246. */
  247. Config.prototype.getModuleConfig = function (loadPath, response) {
  248. let r = response;
  249. return {
  250. 'print': this.onPrint,
  251. 'printErr': this.onPrintError,
  252. 'thisProgram': this.executable,
  253. 'noExitRuntime': true,
  254. 'dynamicLibraries': [`${loadPath}.side.wasm`],
  255. 'instantiateWasm': function (imports, onSuccess) {
  256. function done(result) {
  257. onSuccess(result['instance'], result['module']);
  258. }
  259. if (typeof (WebAssembly.instantiateStreaming) !== 'undefined') {
  260. WebAssembly.instantiateStreaming(Promise.resolve(r), imports).then(done);
  261. } else {
  262. r.arrayBuffer().then(function (buffer) {
  263. WebAssembly.instantiate(buffer, imports).then(done);
  264. });
  265. }
  266. r = null;
  267. return {};
  268. },
  269. 'locateFile': function (path) {
  270. if (path.endsWith('.worker.js')) {
  271. return `${loadPath}.worker.js`;
  272. } else if (path.endsWith('.audio.worklet.js')) {
  273. return `${loadPath}.audio.worklet.js`;
  274. } else if (path.endsWith('.js')) {
  275. return `${loadPath}.js`;
  276. } else if (path.endsWith('.side.wasm')) {
  277. return `${loadPath}.side.wasm`;
  278. } else if (path.endsWith('.wasm')) {
  279. return `${loadPath}.wasm`;
  280. }
  281. return path;
  282. },
  283. };
  284. };
  285. /**
  286. * @ignore
  287. * @param {function()} cleanup
  288. */
  289. Config.prototype.getGodotConfig = function (cleanup) {
  290. // Try to find a canvas
  291. if (!(this.canvas instanceof HTMLCanvasElement)) {
  292. const nodes = document.getElementsByTagName('canvas');
  293. if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
  294. this.canvas = nodes[0];
  295. }
  296. if (!this.canvas) {
  297. throw new Error('No canvas found in page');
  298. }
  299. }
  300. // Canvas can grab focus on click, or key events won't work.
  301. if (this.canvas.tabIndex < 0) {
  302. this.canvas.tabIndex = 0;
  303. }
  304. // Browser locale, or custom one if defined.
  305. let locale = this.locale;
  306. if (!locale) {
  307. locale = navigator.languages ? navigator.languages[0] : navigator.language;
  308. locale = locale.split('.')[0];
  309. }
  310. const onExit = this.onExit;
  311. // Godot configuration.
  312. return {
  313. 'canvas': this.canvas,
  314. 'canvasResizePolicy': this.canvasResizePolicy,
  315. 'locale': locale,
  316. 'persistentDrops': this.persistentDrops,
  317. 'virtualKeyboard': this.experimentalVK,
  318. 'onExecute': this.onExecute,
  319. 'onExit': function (p_code) {
  320. cleanup(); // We always need to call the cleanup callback to free memory.
  321. if (typeof (onExit) === 'function') {
  322. onExit(p_code);
  323. }
  324. },
  325. };
  326. };
  327. return new Config(initConfig);
  328. };