engine.js 9.7 KB

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