engine.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // The following is concatenated with generated code, and acts as the end
  2. // of a wrapper for said code. See pre.js for the other part of the
  3. // wrapper.
  4. exposedLibs['PATH'] = PATH;
  5. exposedLibs['FS'] = FS;
  6. return Module;
  7. },
  8. };
  9. (function() {
  10. var engine = Engine;
  11. var DOWNLOAD_ATTEMPTS_MAX = 4;
  12. var basePath = null;
  13. var wasmFilenameExtensionOverride = null;
  14. var engineLoadPromise = null;
  15. var loadingFiles = {};
  16. function getPathLeaf(path) {
  17. while (path.endsWith('/'))
  18. path = path.slice(0, -1);
  19. return path.slice(path.lastIndexOf('/') + 1);
  20. }
  21. function getBasePath(path) {
  22. if (path.endsWith('/'))
  23. path = path.slice(0, -1);
  24. if (path.lastIndexOf('.') > path.lastIndexOf('/'))
  25. path = path.slice(0, path.lastIndexOf('.'));
  26. return path;
  27. }
  28. function getBaseName(path) {
  29. return getPathLeaf(getBasePath(path));
  30. }
  31. Engine = function Engine() {
  32. this.rtenv = null;
  33. var LIBS = {};
  34. var initPromise = null;
  35. var unloadAfterInit = true;
  36. var preloadedFiles = [];
  37. var resizeCanvasOnStart = true;
  38. var progressFunc = null;
  39. var preloadProgressTracker = {};
  40. var lastProgress = { loaded: 0, total: 0 };
  41. var canvas = null;
  42. var executableName = null;
  43. var locale = null;
  44. var stdout = null;
  45. var stderr = null;
  46. this.init = function(newBasePath) {
  47. if (!initPromise) {
  48. initPromise = Engine.load(newBasePath).then(
  49. instantiate.bind(this)
  50. );
  51. requestAnimationFrame(animateProgress);
  52. if (unloadAfterInit)
  53. initPromise.then(Engine.unloadEngine);
  54. }
  55. return initPromise;
  56. };
  57. function instantiate(wasmBuf) {
  58. var rtenvProps = {
  59. engine: this,
  60. ENV: {},
  61. };
  62. if (typeof stdout === 'function')
  63. rtenvProps.print = stdout;
  64. if (typeof stderr === 'function')
  65. rtenvProps.printErr = stderr;
  66. rtenvProps.instantiateWasm = function(imports, onSuccess) {
  67. WebAssembly.instantiate(wasmBuf, imports).then(function(result) {
  68. onSuccess(result.instance);
  69. });
  70. return {};
  71. };
  72. return new Promise(function(resolve, reject) {
  73. rtenvProps.onRuntimeInitialized = resolve;
  74. rtenvProps.onAbort = reject;
  75. rtenvProps.thisProgram = executableName;
  76. rtenvProps.engine.rtenv = Engine.RuntimeEnvironment(rtenvProps, LIBS);
  77. });
  78. }
  79. this.preloadFile = function(pathOrBuffer, destPath) {
  80. if (pathOrBuffer instanceof ArrayBuffer) {
  81. pathOrBuffer = new Uint8Array(pathOrBuffer);
  82. } else if (ArrayBuffer.isView(pathOrBuffer)) {
  83. pathOrBuffer = new Uint8Array(pathOrBuffer.buffer);
  84. }
  85. if (pathOrBuffer instanceof Uint8Array) {
  86. preloadedFiles.push({
  87. path: destPath,
  88. buffer: pathOrBuffer
  89. });
  90. return Promise.resolve();
  91. } else if (typeof pathOrBuffer === 'string') {
  92. return loadPromise(pathOrBuffer, preloadProgressTracker).then(function(xhr) {
  93. preloadedFiles.push({
  94. path: destPath || pathOrBuffer,
  95. buffer: xhr.response
  96. });
  97. });
  98. } else {
  99. throw Promise.reject("Invalid object for preloading");
  100. }
  101. };
  102. this.start = function() {
  103. return this.init().then(
  104. Function.prototype.apply.bind(synchronousStart, this, arguments)
  105. );
  106. };
  107. this.startGame = function(execName, mainPack) {
  108. executableName = execName;
  109. var mainArgs = [ '--main-pack', mainPack ];
  110. return Promise.all([
  111. // Load from directory,
  112. this.init(getBasePath(mainPack)),
  113. // ...but write to root where the engine expects it.
  114. this.preloadFile(mainPack, getPathLeaf(mainPack))
  115. ]).then(
  116. Function.prototype.apply.bind(synchronousStart, this, mainArgs)
  117. );
  118. };
  119. function synchronousStart() {
  120. if (canvas instanceof HTMLCanvasElement) {
  121. this.rtenv.canvas = canvas;
  122. } else {
  123. var firstCanvas = document.getElementsByTagName('canvas')[0];
  124. if (firstCanvas instanceof HTMLCanvasElement) {
  125. this.rtenv.canvas = firstCanvas;
  126. } else {
  127. throw new Error("No canvas found");
  128. }
  129. }
  130. var actualCanvas = this.rtenv.canvas;
  131. // canvas can grab focus on click
  132. if (actualCanvas.tabIndex < 0) {
  133. actualCanvas.tabIndex = 0;
  134. }
  135. // necessary to calculate cursor coordinates correctly
  136. actualCanvas.style.padding = 0;
  137. actualCanvas.style.borderWidth = 0;
  138. actualCanvas.style.borderStyle = 'none';
  139. // disable right-click context menu
  140. actualCanvas.addEventListener('contextmenu', function(ev) {
  141. ev.preventDefault();
  142. }, false);
  143. // until context restoration is implemented
  144. actualCanvas.addEventListener('webglcontextlost', function(ev) {
  145. alert("WebGL context lost, please reload the page");
  146. ev.preventDefault();
  147. }, false);
  148. if (locale) {
  149. this.rtenv.locale = locale;
  150. } else {
  151. this.rtenv.locale = navigator.languages ? navigator.languages[0] : navigator.language;
  152. }
  153. this.rtenv.locale = this.rtenv.locale.split('.')[0];
  154. this.rtenv.resizeCanvasOnStart = resizeCanvasOnStart;
  155. preloadedFiles.forEach(function(file) {
  156. var dir = LIBS.PATH.dirname(file.path);
  157. try {
  158. LIBS.FS.stat(dir);
  159. } catch (e) {
  160. if (e.code !== 'ENOENT') {
  161. throw e;
  162. }
  163. LIBS.FS.mkdirTree(dir);
  164. }
  165. // With memory growth, canOwn should be false.
  166. LIBS.FS.createDataFile(file.path, null, new Uint8Array(file.buffer), true, true, false);
  167. }, this);
  168. preloadedFiles = null;
  169. initPromise = null;
  170. this.rtenv.callMain(arguments);
  171. }
  172. this.setProgressFunc = function(func) {
  173. progressFunc = func;
  174. };
  175. this.setResizeCanvasOnStart = function(enabled) {
  176. resizeCanvasOnStart = enabled;
  177. };
  178. function animateProgress() {
  179. var loaded = 0;
  180. var total = 0;
  181. var totalIsValid = true;
  182. var progressIsFinal = true;
  183. [loadingFiles, preloadProgressTracker].forEach(function(tracker) {
  184. Object.keys(tracker).forEach(function(file) {
  185. if (!tracker[file].final)
  186. progressIsFinal = false;
  187. if (!totalIsValid || tracker[file].total === 0) {
  188. totalIsValid = false;
  189. total = 0;
  190. } else {
  191. total += tracker[file].total;
  192. }
  193. loaded += tracker[file].loaded;
  194. });
  195. });
  196. if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
  197. lastProgress.loaded = loaded;
  198. lastProgress.total = total;
  199. if (typeof progressFunc === 'function')
  200. progressFunc(loaded, total);
  201. }
  202. if (!progressIsFinal)
  203. requestAnimationFrame(animateProgress);
  204. }
  205. this.setCanvas = function(elem) {
  206. canvas = elem;
  207. };
  208. this.setExecutableName = function(newName) {
  209. executableName = newName;
  210. };
  211. this.setLocale = function(newLocale) {
  212. locale = newLocale;
  213. };
  214. this.setUnloadAfterInit = function(enabled) {
  215. if (enabled && !unloadAfterInit && initPromise) {
  216. initPromise.then(Engine.unloadEngine);
  217. }
  218. unloadAfterInit = enabled;
  219. };
  220. this.setStdoutFunc = function(func) {
  221. var print = function(text) {
  222. if (arguments.length > 1) {
  223. text = Array.prototype.slice.call(arguments).join(" ");
  224. }
  225. func(text);
  226. };
  227. if (this.rtenv)
  228. this.rtenv.print = print;
  229. stdout = print;
  230. };
  231. this.setStderrFunc = function(func) {
  232. var printErr = function(text) {
  233. if (arguments.length > 1)
  234. text = Array.prototype.slice.call(arguments).join(" ");
  235. func(text);
  236. };
  237. if (this.rtenv)
  238. this.rtenv.printErr = printErr;
  239. stderr = printErr;
  240. };
  241. }; // Engine()
  242. Engine.RuntimeEnvironment = engine.RuntimeEnvironment;
  243. Engine.isWebGLAvailable = function(majorVersion = 1) {
  244. var testContext = false;
  245. try {
  246. var testCanvas = document.createElement('canvas');
  247. if (majorVersion === 1) {
  248. testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
  249. } else if (majorVersion === 2) {
  250. testContext = testCanvas.getContext('webgl2') || testCanvas.getContext('experimental-webgl2');
  251. }
  252. } catch (e) {}
  253. return !!testContext;
  254. };
  255. Engine.setWebAssemblyFilenameExtension = function(override) {
  256. if (String(override).length === 0) {
  257. throw new Error('Invalid WebAssembly filename extension override');
  258. }
  259. wasmFilenameExtensionOverride = String(override);
  260. }
  261. Engine.load = function(newBasePath) {
  262. if (newBasePath !== undefined) basePath = getBasePath(newBasePath);
  263. if (engineLoadPromise === null) {
  264. if (typeof WebAssembly !== 'object')
  265. return Promise.reject(new Error("Browser doesn't support WebAssembly"));
  266. // TODO cache/retrieve module to/from idb
  267. engineLoadPromise = loadPromise(basePath + '.' + (wasmFilenameExtensionOverride || 'wasm')).then(function(xhr) {
  268. return xhr.response;
  269. });
  270. engineLoadPromise = engineLoadPromise.catch(function(err) {
  271. engineLoadPromise = null;
  272. throw err;
  273. });
  274. }
  275. return engineLoadPromise;
  276. };
  277. Engine.unload = function() {
  278. engineLoadPromise = null;
  279. };
  280. function loadPromise(file, tracker) {
  281. if (tracker === undefined)
  282. tracker = loadingFiles;
  283. return new Promise(function(resolve, reject) {
  284. loadXHR(resolve, reject, file, tracker);
  285. });
  286. }
  287. function loadXHR(resolve, reject, file, tracker) {
  288. var xhr = new XMLHttpRequest;
  289. xhr.open('GET', file);
  290. if (!file.endsWith('.js')) {
  291. xhr.responseType = 'arraybuffer';
  292. }
  293. ['loadstart', 'progress', 'load', 'error', 'abort'].forEach(function(ev) {
  294. xhr.addEventListener(ev, onXHREvent.bind(xhr, resolve, reject, file, tracker));
  295. });
  296. xhr.send();
  297. }
  298. function onXHREvent(resolve, reject, file, tracker, ev) {
  299. if (this.status >= 400) {
  300. if (this.status < 500 || ++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
  301. reject(new Error("Failed loading file '" + file + "': " + this.statusText));
  302. this.abort();
  303. return;
  304. } else {
  305. setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
  306. }
  307. }
  308. switch (ev.type) {
  309. case 'loadstart':
  310. if (tracker[file] === undefined) {
  311. tracker[file] = {
  312. total: ev.total,
  313. loaded: ev.loaded,
  314. attempts: 0,
  315. final: false,
  316. };
  317. }
  318. break;
  319. case 'progress':
  320. tracker[file].loaded = ev.loaded;
  321. tracker[file].total = ev.total;
  322. break;
  323. case 'load':
  324. tracker[file].final = true;
  325. resolve(this);
  326. break;
  327. case 'error':
  328. if (++tracker[file].attempts >= DOWNLOAD_ATTEMPTS_MAX) {
  329. tracker[file].final = true;
  330. reject(new Error("Failed loading file '" + file + "'"));
  331. } else {
  332. setTimeout(loadXHR.bind(null, resolve, reject, file, tracker), 1000);
  333. }
  334. break;
  335. case 'abort':
  336. tracker[file].final = true;
  337. reject(new Error("Loading file '" + file + "' was aborted."));
  338. break;
  339. }
  340. }
  341. })();