engine.js 9.8 KB

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