engine.js 9.7 KB

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