engine.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. const Engine = (function () {
  2. const preloader = new Preloader();
  3. let wasmExt = '.wasm';
  4. let unloadAfterInit = true;
  5. let loadPath = '';
  6. let loadPromise = null;
  7. let initPromise = null;
  8. let stderr = null;
  9. let stdout = null;
  10. let progressFunc = null;
  11. function load(basePath) {
  12. if (loadPromise == null) {
  13. loadPath = basePath;
  14. loadPromise = preloader.loadPromise(basePath + wasmExt);
  15. preloader.setProgressFunc(progressFunc);
  16. requestAnimationFrame(preloader.animateProgress);
  17. }
  18. return loadPromise;
  19. }
  20. function unload() {
  21. loadPromise = null;
  22. }
  23. /** @constructor */
  24. function Engine() { // eslint-disable-line no-shadow
  25. this.canvas = null;
  26. this.executableName = '';
  27. this.rtenv = null;
  28. this.customLocale = null;
  29. this.resizeCanvasOnStart = false;
  30. this.onExecute = null;
  31. this.onExit = null;
  32. this.persistentPaths = ['/userfs'];
  33. this.gdnativeLibs = [];
  34. }
  35. Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
  36. if (initPromise) {
  37. return initPromise;
  38. }
  39. if (loadPromise == null) {
  40. if (!basePath) {
  41. initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
  42. return initPromise;
  43. }
  44. load(basePath);
  45. }
  46. let config = {};
  47. if (typeof stdout === 'function') {
  48. config.print = stdout;
  49. }
  50. if (typeof stderr === 'function') {
  51. config.printErr = stderr;
  52. }
  53. const me = this;
  54. initPromise = new Promise(function (resolve, reject) {
  55. config['locateFile'] = Utils.createLocateRewrite(loadPath);
  56. config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise);
  57. // Emscripten configuration.
  58. config['thisProgram'] = me.executableName;
  59. config['noExitRuntime'] = true;
  60. config['dynamicLibraries'] = [`${me.executableName}.side.wasm`].concat(me.gdnativeLibs);
  61. Godot(config).then(function (module) {
  62. module['initFS'](me.persistentPaths).then(function (fs_err) {
  63. me.rtenv = module;
  64. if (unloadAfterInit) {
  65. unload();
  66. }
  67. resolve();
  68. config = null;
  69. });
  70. });
  71. });
  72. return initPromise;
  73. };
  74. /** @type {function(string, string):Object} */
  75. Engine.prototype.preloadFile = function (file, path) {
  76. return preloader.preload(file, path);
  77. };
  78. /** @type {function(...string):Object} */
  79. Engine.prototype.start = function () {
  80. // Start from arguments.
  81. const args = [];
  82. for (let i = 0; i < arguments.length; i++) {
  83. args.push(arguments[i]);
  84. }
  85. const me = this;
  86. return me.init().then(function () {
  87. if (!me.rtenv) {
  88. return Promise.reject(new Error('The engine must be initialized before it can be started'));
  89. }
  90. if (!(me.canvas instanceof HTMLCanvasElement)) {
  91. me.canvas = Utils.findCanvas();
  92. if (!me.canvas) {
  93. return Promise.reject(new Error('No canvas found in page'));
  94. }
  95. }
  96. // Canvas can grab focus on click, or key events won't work.
  97. if (me.canvas.tabIndex < 0) {
  98. me.canvas.tabIndex = 0;
  99. }
  100. // Browser locale, or custom one if defined.
  101. let locale = me.customLocale;
  102. if (!locale) {
  103. locale = navigator.languages ? navigator.languages[0] : navigator.language;
  104. locale = locale.split('.')[0];
  105. }
  106. // Godot configuration.
  107. me.rtenv['initConfig']({
  108. 'resizeCanvasOnStart': me.resizeCanvasOnStart,
  109. 'canvas': me.canvas,
  110. 'locale': locale,
  111. 'onExecute': function (p_args) {
  112. if (me.onExecute) {
  113. me.onExecute(p_args);
  114. return 0;
  115. }
  116. return 1;
  117. },
  118. 'onExit': function (p_code) {
  119. me.rtenv['deinitFS']();
  120. if (me.onExit) {
  121. me.onExit(p_code);
  122. }
  123. me.rtenv = null;
  124. },
  125. });
  126. return new Promise(function (resolve, reject) {
  127. preloader.preloadedFiles.forEach(function (file) {
  128. me.rtenv['copyToFS'](file.path, file.buffer);
  129. });
  130. preloader.preloadedFiles.length = 0; // Clear memory
  131. me.rtenv['callMain'](args);
  132. initPromise = null;
  133. resolve();
  134. });
  135. });
  136. };
  137. Engine.prototype.startGame = function (execName, mainPack, extraArgs) {
  138. // Start and init with execName as loadPath if not inited.
  139. this.executableName = execName;
  140. const me = this;
  141. return Promise.all([
  142. this.init(execName),
  143. this.preloadFile(mainPack, mainPack),
  144. ]).then(function () {
  145. let args = ['--main-pack', mainPack];
  146. if (extraArgs) {
  147. args = args.concat(extraArgs);
  148. }
  149. return me.start.apply(me, args);
  150. });
  151. };
  152. Engine.prototype.setWebAssemblyFilenameExtension = function (override) {
  153. if (String(override).length === 0) {
  154. throw new Error('Invalid WebAssembly filename extension override');
  155. }
  156. wasmExt = String(override);
  157. };
  158. Engine.prototype.setUnloadAfterInit = function (enabled) {
  159. unloadAfterInit = enabled;
  160. };
  161. Engine.prototype.setCanvas = function (canvasElem) {
  162. this.canvas = canvasElem;
  163. };
  164. Engine.prototype.setCanvasResizedOnStart = function (enabled) {
  165. this.resizeCanvasOnStart = enabled;
  166. };
  167. Engine.prototype.setLocale = function (locale) {
  168. this.customLocale = locale;
  169. };
  170. Engine.prototype.setExecutableName = function (newName) {
  171. this.executableName = newName;
  172. };
  173. Engine.prototype.setProgressFunc = function (func) {
  174. progressFunc = func;
  175. };
  176. Engine.prototype.setStdoutFunc = function (func) {
  177. const print = function (text) {
  178. let msg = text;
  179. if (arguments.length > 1) {
  180. msg = Array.prototype.slice.call(arguments).join(' ');
  181. }
  182. func(msg);
  183. };
  184. if (this.rtenv) {
  185. this.rtenv.print = print;
  186. }
  187. stdout = print;
  188. };
  189. Engine.prototype.setStderrFunc = function (func) {
  190. const printErr = function (text) {
  191. let msg = text;
  192. if (arguments.length > 1) {
  193. msg = Array.prototype.slice.call(arguments).join(' ');
  194. }
  195. func(msg);
  196. };
  197. if (this.rtenv) {
  198. this.rtenv.printErr = printErr;
  199. }
  200. stderr = printErr;
  201. };
  202. Engine.prototype.setOnExecute = function (onExecute) {
  203. this.onExecute = onExecute;
  204. };
  205. Engine.prototype.setOnExit = function (onExit) {
  206. this.onExit = onExit;
  207. };
  208. Engine.prototype.copyToFS = function (path, buffer) {
  209. if (this.rtenv == null) {
  210. throw new Error('Engine must be inited before copying files');
  211. }
  212. this.rtenv['copyToFS'](path, buffer);
  213. };
  214. Engine.prototype.setPersistentPaths = function (persistentPaths) {
  215. this.persistentPaths = persistentPaths;
  216. };
  217. Engine.prototype.setGDNativeLibraries = function (gdnativeLibs) {
  218. this.gdnativeLibs = gdnativeLibs;
  219. };
  220. Engine.prototype.requestQuit = function () {
  221. if (this.rtenv) {
  222. this.rtenv['request_quit']();
  223. }
  224. };
  225. // Closure compiler exported engine methods.
  226. /** @export */
  227. Engine['isWebGLAvailable'] = Utils.isWebGLAvailable;
  228. Engine['load'] = load;
  229. Engine['unload'] = unload;
  230. Engine.prototype['init'] = Engine.prototype.init;
  231. Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
  232. Engine.prototype['start'] = Engine.prototype.start;
  233. Engine.prototype['startGame'] = Engine.prototype.startGame;
  234. Engine.prototype['setWebAssemblyFilenameExtension'] = Engine.prototype.setWebAssemblyFilenameExtension;
  235. Engine.prototype['setUnloadAfterInit'] = Engine.prototype.setUnloadAfterInit;
  236. Engine.prototype['setCanvas'] = Engine.prototype.setCanvas;
  237. Engine.prototype['setCanvasResizedOnStart'] = Engine.prototype.setCanvasResizedOnStart;
  238. Engine.prototype['setLocale'] = Engine.prototype.setLocale;
  239. Engine.prototype['setExecutableName'] = Engine.prototype.setExecutableName;
  240. Engine.prototype['setProgressFunc'] = Engine.prototype.setProgressFunc;
  241. Engine.prototype['setStdoutFunc'] = Engine.prototype.setStdoutFunc;
  242. Engine.prototype['setStderrFunc'] = Engine.prototype.setStderrFunc;
  243. Engine.prototype['setOnExecute'] = Engine.prototype.setOnExecute;
  244. Engine.prototype['setOnExit'] = Engine.prototype.setOnExit;
  245. Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
  246. Engine.prototype['setPersistentPaths'] = Engine.prototype.setPersistentPaths;
  247. Engine.prototype['setGDNativeLibraries'] = Engine.prototype.setGDNativeLibraries;
  248. Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
  249. return Engine;
  250. }());
  251. if (typeof window !== 'undefined') {
  252. window['Engine'] = Engine;
  253. }