engine.js 7.9 KB

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