Преглед на файлове

[HTML5] Document Engine and EngineConfig (jsdoc).

This commit also removes the utils.js engine file, moving some of it's
content to config.js and some to engine.js .
Fabio Alessandrelli преди 4 години
родител
ревизия
018ee5a4dc

+ 1 - 2
platform/javascript/.eslintrc.engine.js

@@ -3,9 +3,8 @@ module.exports = {
 		"./.eslintrc.js",
 	],
 	"globals": {
-		"EngineConfig": true,
+		"InternalConfig": true,
 		"Godot": true,
 		"Preloader": true,
-		"Utils": true,
 	},
 };

+ 0 - 1
platform/javascript/SCsub

@@ -73,7 +73,6 @@ sys_env.Depends(build[0], sys_env["JS_EXTERNS"])
 
 engine = [
     "js/engine/preloader.js",
-    "js/engine/utils.js",
     "js/engine/config.js",
     "js/engine/engine.js",
 ]

+ 296 - 87
platform/javascript/js/engine/config.js

@@ -1,100 +1,309 @@
-/** @constructor */
-function EngineConfig(opts) {
-	// Module config
-	this.unloadAfterInit = true;
-	this.onPrintError = function () {
-		console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
-	};
-	this.onPrint = function () {
-		console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
+/**
+ * An object used to configure the Engine instance based on godot export options, and to override those in custom HTML
+ * templates if needed.
+ *
+ * @header Engine configuration
+ * @summary The Engine configuration object. This is just a typedef, create it like a regular object, e.g.:
+ *
+ * ``const MyConfig = { executable: 'godot', unloadAfterInit: false }``
+ *
+ * @typedef {Object} EngineConfig
+ */
+const EngineConfig = {}; // eslint-disable-line no-unused-vars
+
+/**
+ * @struct
+ * @constructor
+ * @ignore
+ */
+const InternalConfig = function (initConfig) { // eslint-disable-line no-unused-vars
+	const cfg = /** @lends {InternalConfig.prototype} */ {
+		/**
+		 * Whether the unload the engine automatically after the instance is initialized.
+		 *
+		 * @memberof EngineConfig
+		 * @default
+		 * @type {boolean}
+		 */
+		unloadAfterInit: true,
+		/**
+		 * The HTML DOM Canvas object to use.
+		 *
+		 * By default, the first canvas element in the document will be used is none is specified.
+		 *
+		 * @memberof EngineConfig
+		 * @default
+		 * @type {?HTMLCanvasElement}
+		 */
+		canvas: null,
+		/**
+		 * The name of the WASM file without the extension. (Set by Godot Editor export process).
+		 *
+		 * @memberof EngineConfig
+		 * @default
+		 * @type {string}
+		 */
+		executable: '',
+		/**
+		 * An alternative name for the game pck to load. The executable name is used otherwise.
+		 *
+		 * @memberof EngineConfig
+		 * @default
+		 * @type {?string}
+		 */
+		mainPack: null,
+		/**
+		 * Specify a language code to select the proper localization for the game.
+		 *
+		 * The browser locale will be used if none is specified. See complete list of
+		 * :ref:`supported locales <doc_locales>`.
+		 *
+		 * @memberof EngineConfig
+		 * @type {?string}
+		 * @default
+		 */
+		locale: null,
+		/**
+		 * The canvas resize policy determines how the canvas should be resized by Godot.
+		 *
+		 * ``0`` means Godot won't do any resizing. This is useful if you want to control the canvas size from
+		 * javascript code in your template.
+		 *
+		 * ``1`` means Godot will resize the canvas on start, and when changing window size via engine functions.
+		 *
+		 * ``2`` means Godot will adapt the canvas size to match the whole browser window.
+		 *
+		 * @memberof EngineConfig
+		 * @type {number}
+		 * @default
+		 */
+		canvasResizePolicy: 2,
+		/**
+		 * The arguments to be passed as command line arguments on startup.
+		 *
+		 * See :ref:`command line tutorial <doc_command_line_tutorial>`.
+		 *
+		 * **Note**: :js:meth:`startGame <Engine.prototype.startGame>` will always add the ``--main-pack`` argument.
+		 *
+		 * @memberof EngineConfig
+		 * @type {Array<string>}
+		 * @default
+		 */
+		args: [],
+		/**
+		 * @ignore
+		 * @type {Array.<string>}
+		 */
+		persistentPaths: ['/userfs'],
+		/**
+		 * @ignore
+		 * @type {Array.<string>}
+		 */
+		gdnativeLibs: [],
+		/**
+		 * A callback function for handling Godot's ``OS.execute`` calls.
+		 *
+		 * This is for example used in the Web Editor template to switch between project manager and editor, and for running the game.
+		 *
+		 * @callback EngineConfig.onExecute
+		 * @param {string} path The path that Godot's wants executed.
+		 * @param {Array.<string>} args The arguments of the "command" to execute.
+		 */
+		/**
+		 * @ignore
+		 * @type {?function(string, Array.<string>)}
+		 */
+		onExecute: null,
+		/**
+		 * A callback function for being notified when the Godot instance quits.
+		 *
+		 * **Note**: This function will not be called if the engine crashes or become unresponsive.
+		 *
+		 * @callback EngineConfig.onExit
+		 * @param {number} status_code The status code returned by Godot on exit.
+		 */
+		/**
+		 * @ignore
+		 * @type {?function(number)}
+		 */
+		onExit: null,
+		/**
+		 * A callback function for displaying download progress.
+		 *
+		 * The function is called once per frame while downloading files, so the usage of ``requestAnimationFrame()``
+		 * is not necessary.
+		 *
+		 * If the callback function receives a total amount of bytes as 0, this means that it is impossible to calculate.
+		 * Possible reasons include:
+		 *
+		 * -  Files are delivered with server-side chunked compression
+		 * -  Files are delivered with server-side compression on Chromium
+		 * -  Not all file downloads have started yet (usually on servers without multi-threading)
+		 *
+		 * @callback EngineConfig.onProgress
+		 * @param {number} current The current amount of downloaded bytes so far.
+		 * @param {number} total The total amount of bytes to be downloaded.
+		 */
+		/**
+		 * @ignore
+		 * @type {?function(number, number)}
+		 */
+		onProgress: null,
+		/**
+		 * A callback function for handling the standard output stream. This method should usually only be used in debug pages.
+		 *
+		 * By default, ``console.log()`` is used.
+		 *
+		 * @callback EngineConfig.onPrint
+		 * @param {...*} [var_args] A variadic number of arguments to be printed.
+		 */
+		/**
+		 * @ignore
+		 * @type {?function(...*)}
+		 */
+		onPrint: function () {
+			console.log.apply(console, Array.from(arguments)); // eslint-disable-line no-console
+		},
+		/**
+		 * A callback function for handling the standard error stream. This method should usually only be used in debug pages.
+		 *
+		 * By default, ``console.error()`` is used.
+		 *
+		 * @callback EngineConfig.onPrintError
+		 * @param {...*} [var_args] A variadic number of arguments to be printed as errors.
+		*/
+		/**
+		 * @ignore
+		 * @type {?function(...*)}
+		 */
+		onPrintError: function (var_args) {
+			console.error.apply(console, Array.from(arguments)); // eslint-disable-line no-console
+		},
 	};
-	this.onProgress = null;
 
-	// Godot Config
-	this.canvas = null;
-	this.executable = '';
-	this.mainPack = null;
-	this.locale = null;
-	this.canvasResizePolicy = false;
-	this.persistentPaths = ['/userfs'];
-	this.gdnativeLibs = [];
-	this.args = [];
-	this.onExecute = null;
-	this.onExit = null;
-	this.update(opts);
-}
+	/**
+	 * @ignore
+	 * @struct
+	 * @constructor
+	 * @param {EngineConfig} opts
+	 */
+	function Config(opts) {
+		this.update(opts);
+	}
+
+	Config.prototype = cfg;
 
-EngineConfig.prototype.update = function (opts) {
-	const config = opts || {};
-	function parse(key, def) {
-		if (typeof (config[key]) === 'undefined') {
-			return def;
+	/**
+	 * @ignore
+	 * @param {EngineConfig} opts
+	 */
+	Config.prototype.update = function (opts) {
+		const config = opts || {};
+		function parse(key, def) {
+			if (typeof (config[key]) === 'undefined') {
+				return def;
+			}
+			return config[key];
 		}
-		return config[key];
-	}
-	// Module config
-	this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
-	this.onPrintError = parse('onPrintError', this.onPrintError);
-	this.onPrint = parse('onPrint', this.onPrint);
-	this.onProgress = parse('onProgress', this.onProgress);
+		// Module config
+		this.unloadAfterInit = parse('unloadAfterInit', this.unloadAfterInit);
+		this.onPrintError = parse('onPrintError', this.onPrintError);
+		this.onPrint = parse('onPrint', this.onPrint);
+		this.onProgress = parse('onProgress', this.onProgress);
 
-	// Godot config
-	this.canvas = parse('canvas', this.canvas);
-	this.executable = parse('executable', this.executable);
-	this.mainPack = parse('mainPack', this.mainPack);
-	this.locale = parse('locale', this.locale);
-	this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
-	this.persistentPaths = parse('persistentPaths', this.persistentPaths);
-	this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
-	this.args = parse('args', this.args);
-	this.onExecute = parse('onExecute', this.onExecute);
-	this.onExit = parse('onExit', this.onExit);
-};
+		// Godot config
+		this.canvas = parse('canvas', this.canvas);
+		this.executable = parse('executable', this.executable);
+		this.mainPack = parse('mainPack', this.mainPack);
+		this.locale = parse('locale', this.locale);
+		this.canvasResizePolicy = parse('canvasResizePolicy', this.canvasResizePolicy);
+		this.persistentPaths = parse('persistentPaths', this.persistentPaths);
+		this.gdnativeLibs = parse('gdnativeLibs', this.gdnativeLibs);
+		this.args = parse('args', this.args);
+		this.onExecute = parse('onExecute', this.onExecute);
+		this.onExit = parse('onExit', this.onExit);
+	};
 
-EngineConfig.prototype.getModuleConfig = function (loadPath, loadPromise) {
-	const me = this;
-	return {
-		'print': this.onPrint,
-		'printErr': this.onPrintError,
-		'locateFile': Utils.createLocateRewrite(loadPath),
-		'instantiateWasm': Utils.createInstantiatePromise(loadPromise),
-		'thisProgram': me.executable,
-		'noExitRuntime': true,
-		'dynamicLibraries': [`${me.executable}.side.wasm`],
+	/**
+	 * @ignore
+	 * @param {string} loadPath
+	 * @param {Promise} loadPromise
+	 */
+	Config.prototype.getModuleConfig = function (loadPath, loadPromise) {
+		let loader = loadPromise;
+		return {
+			'print': this.onPrint,
+			'printErr': this.onPrintError,
+			'thisProgram': this.executable,
+			'noExitRuntime': true,
+			'dynamicLibraries': [`${loadPath}.side.wasm`],
+			'instantiateWasm': function (imports, onSuccess) {
+				loader.then(function (xhr) {
+					WebAssembly.instantiate(xhr.response, imports).then(function (result) {
+						onSuccess(result['instance'], result['module']);
+					});
+				});
+				loader = null;
+				return {};
+			},
+			'locateFile': function (path) {
+				if (path.endsWith('.worker.js')) {
+					return `${loadPath}.worker.js`;
+				} else if (path.endsWith('.audio.worklet.js')) {
+					return `${loadPath}.audio.worklet.js`;
+				} else if (path.endsWith('.js')) {
+					return `${loadPath}.js`;
+				} else if (path.endsWith('.side.wasm')) {
+					return `${loadPath}.side.wasm`;
+				} else if (path.endsWith('.wasm')) {
+					return `${loadPath}.wasm`;
+				}
+				return path;
+			},
+		};
 	};
-};
 
-EngineConfig.prototype.getGodotConfig = function (cleanup) {
-	if (!(this.canvas instanceof HTMLCanvasElement)) {
-		this.canvas = Utils.findCanvas();
-		if (!this.canvas) {
-			throw new Error('No canvas found in page');
+	/**
+	 * @ignore
+	 * @param {function()} cleanup
+	 */
+	Config.prototype.getGodotConfig = function (cleanup) {
+		// Try to find a canvas
+		if (!(this.canvas instanceof HTMLCanvasElement)) {
+			const nodes = document.getElementsByTagName('canvas');
+			if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
+				this.canvas = nodes[0];
+			}
+			if (!this.canvas) {
+				throw new Error('No canvas found in page');
+			}
+		}
+		// Canvas can grab focus on click, or key events won't work.
+		if (this.canvas.tabIndex < 0) {
+			this.canvas.tabIndex = 0;
 		}
-	}
 
-	// Canvas can grab focus on click, or key events won't work.
-	if (this.canvas.tabIndex < 0) {
-		this.canvas.tabIndex = 0;
-	}
+		// Browser locale, or custom one if defined.
+		let locale = this.locale;
+		if (!locale) {
+			locale = navigator.languages ? navigator.languages[0] : navigator.language;
+			locale = locale.split('.')[0];
+		}
+		const onExit = this.onExit;
 
-	// Browser locale, or custom one if defined.
-	let locale = this.locale;
-	if (!locale) {
-		locale = navigator.languages ? navigator.languages[0] : navigator.language;
-		locale = locale.split('.')[0];
-	}
-	const onExit = this.onExit;
-	// Godot configuration.
-	return {
-		'canvas': this.canvas,
-		'canvasResizePolicy': this.canvasResizePolicy,
-		'locale': locale,
-		'onExecute': this.onExecute,
-		'onExit': function (p_code) {
-			cleanup(); // We always need to call the cleanup callback to free memory.
-			if (typeof (onExit) === 'function') {
-				onExit(p_code);
-			}
-		},
+		// Godot configuration.
+		return {
+			'canvas': this.canvas,
+			'canvasResizePolicy': this.canvasResizePolicy,
+			'locale': locale,
+			'onExecute': this.onExecute,
+			'onExit': function (p_code) {
+				cleanup(); // We always need to call the cleanup callback to free memory.
+				if (typeof (onExit) === 'function') {
+					onExit(p_code);
+				}
+			},
+		};
 	};
+	return new Config(initConfig);
 };

+ 238 - 113
platform/javascript/js/engine/engine.js

@@ -1,3 +1,13 @@
+/**
+ * Projects exported for the Web expose the :js:class:`Engine` class to the JavaScript environment, that allows
+ * fine control over the engine's start-up process.
+ *
+ * This API is built in an asynchronous manner and requires basic understanding
+ * of `Promises <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises>`__.
+ *
+ * @module Engine
+ * @header HTML5 shell class reference
+ */
 const Engine = (function () {
 	const preloader = new Preloader();
 
@@ -5,139 +15,254 @@ const Engine = (function () {
 	let loadPath = '';
 	let initPromise = null;
 
-	function load(basePath) {
+	/**
+	 * @classdesc The ``Engine`` class provides methods for loading and starting exported projects on the Web. For default export
+	 * settings, this is already part of the exported HTML page. To understand practical use of the ``Engine`` class,
+	 * see :ref:`Custom HTML page for Web export <doc_customizing_html5_shell>`.
+	 *
+	 * @description Create a new Engine instance with the given configuration.
+	 *
+	 * @global
+	 * @constructor
+	 * @param {EngineConfig} initConfig The initial config for this instance.
+	 */
+	function Engine(initConfig) { // eslint-disable-line no-shadow
+		this.config = new InternalConfig(initConfig);
+		this.rtenv = null;
+	}
+
+	/**
+	 * Load the engine from the specified base path.
+	 *
+	 * @param {string} basePath Base path of the engine to load.
+	 * @returns {Promise} A Promise that resolves once the engine is loaded.
+	 *
+	 * @function Engine.load
+	 */
+	Engine.load = function (basePath) {
 		if (loadPromise == null) {
 			loadPath = basePath;
 			loadPromise = preloader.loadPromise(`${loadPath}.wasm`);
 			requestAnimationFrame(preloader.animateProgress);
 		}
 		return loadPromise;
-	}
+	};
 
-	function unload() {
+	/**
+	 * Unload the engine to free memory.
+	 *
+	 * This method will be called automatically depending on the configuration. See :js:attr:`unloadAfterInit`.
+	 *
+	 * @function Engine.unload
+	 */
+	Engine.unload = function () {
 		loadPromise = null;
-	}
+	};
 
-	/** @constructor */
-	function Engine(opts) { // eslint-disable-line no-shadow
-		this.config = new EngineConfig(opts);
-		this.rtenv = null;
-	}
+	/**
+	 * Check whether WebGL is available. Optionally, specify a particular version of WebGL to check for.
+	 *
+	 * @param {number=} [majorVersion=1] The major WebGL version to check for.
+	 * @returns {boolean} If the given major version of WebGL is available.
+	 * @function Engine.isWebGLAvailable
+	 */
+	Engine.isWebGLAvailable = function (majorVersion = 1) {
+		try {
+			return !!document.createElement('canvas').getContext(['webgl', 'webgl2'][majorVersion - 1]);
+		} catch (e) { /* Not available */ }
+		return false;
+	};
 
-	Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
-		if (initPromise) {
-			return initPromise;
-		}
-		if (loadPromise == null) {
-			if (!basePath) {
-				initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
-				return initPromise;
-			}
-			load(basePath);
-		}
-		preloader.setProgressFunc(this.config.onProgress);
-		let config = this.config.getModuleConfig(loadPath, loadPromise);
-		const me = this;
-		initPromise = new Promise(function (resolve, reject) {
-			Godot(config).then(function (module) {
-				module['initFS'](me.config.persistentPaths).then(function (fs_err) {
-					me.rtenv = module;
-					if (me.config.unloadAfterInit) {
-						unload();
+	/**
+	 * Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution.
+	 * @ignore
+	 * @constructor
+	 */
+	function SafeEngine(initConfig) {
+		const proto = /** @lends Engine.prototype */ {
+			/**
+			 * Initialize the engine instance. Optionally, pass the base path to the engine to load it,
+			 * if it hasn't been loaded yet. See :js:meth:`Engine.load`.
+			 *
+			 * @param {string=} basePath Base path of the engine to load.
+			 * @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized.
+			 */
+			init: function (basePath) {
+				if (initPromise) {
+					return initPromise;
+				}
+				if (loadPromise == null) {
+					if (!basePath) {
+						initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
+						return initPromise;
 					}
-					resolve();
-					config = null;
+					Engine.load(basePath);
+				}
+				preloader.setProgressFunc(this.config.onProgress);
+				let config = this.config.getModuleConfig(loadPath, loadPromise);
+				const me = this;
+				initPromise = new Promise(function (resolve, reject) {
+					Godot(config).then(function (module) {
+						module['initFS'](me.config.persistentPaths).then(function (fs_err) {
+							me.rtenv = module;
+							if (me.config.unloadAfterInit) {
+								Engine.unload();
+							}
+							resolve();
+							config = null;
+						});
+					});
 				});
-			});
-		});
-		return initPromise;
-	};
+				return initPromise;
+			},
 
-	/** @type {function(string, string):Object} */
-	Engine.prototype.preloadFile = function (file, path) {
-		return preloader.preload(file, path);
-	};
+			/**
+			 * Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the
+			 * instance.
+			 *
+			 * If not provided, the ``path`` is derived from the URL of the loaded file.
+			 *
+			 * @param {string|ArrayBuffer} file The file to preload.
+			 *
+			 * If a ``string`` the file will be loaded from that path.
+			 *
+			 * If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.
+			 *
+			 * @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.
+			 *
+			 * @returns {Promise} A Promise that resolves once the file is loaded.
+			 */
+			preloadFile: function (file, path) {
+				return preloader.preload(file, path);
+			},
 
-	/** @type {function(...string):Object} */
-	Engine.prototype.start = function (override) {
-		this.config.update(override);
-		const me = this;
-		return me.init().then(function () {
-			if (!me.rtenv) {
-				return Promise.reject(new Error('The engine must be initialized before it can be started'));
-			}
-
-			let config = {};
-			try {
-				config = me.config.getGodotConfig(function () {
-					me.rtenv = null;
-				});
-			} catch (e) {
-				return Promise.reject(e);
-			}
-			// Godot configuration.
-			me.rtenv['initConfig'](config);
-
-			// Preload GDNative libraries.
-			const libs = [];
-			me.config.gdnativeLibs.forEach(function (lib) {
-				libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
-			});
-			return Promise.all(libs).then(function () {
-				return new Promise(function (resolve, reject) {
-					preloader.preloadedFiles.forEach(function (file) {
-						me.rtenv['copyToFS'](file.path, file.buffer);
+			/**
+			 * Start the engine instance using the given override configuration (if any).
+			 * :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.
+			 *
+			 * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
+			 * The engine must be loaded beforehand.
+			 *
+			 * Fails if a canvas cannot be found on the page, or not specified in the configuration.
+			 *
+			 * @param {EngineConfig} override An optional configuration override.
+			 * @return {Promise} Promise that resolves once the engine started.
+			 */
+			start: function (override) {
+				this.config.update(override);
+				const me = this;
+				return me.init().then(function () {
+					if (!me.rtenv) {
+						return Promise.reject(new Error('The engine must be initialized before it can be started'));
+					}
+
+					let config = {};
+					try {
+						config = me.config.getGodotConfig(function () {
+							me.rtenv = null;
+						});
+					} catch (e) {
+						return Promise.reject(e);
+					}
+					// Godot configuration.
+					me.rtenv['initConfig'](config);
+
+					// Preload GDNative libraries.
+					const libs = [];
+					me.config.gdnativeLibs.forEach(function (lib) {
+						libs.push(me.rtenv['loadDynamicLibrary'](lib, { 'loadAsync': true }));
+					});
+					return Promise.all(libs).then(function () {
+						return new Promise(function (resolve, reject) {
+							preloader.preloadedFiles.forEach(function (file) {
+								me.rtenv['copyToFS'](file.path, file.buffer);
+							});
+							preloader.preloadedFiles.length = 0; // Clear memory
+							me.rtenv['callMain'](me.config.args);
+							initPromise = null;
+							resolve();
+						});
 					});
-					preloader.preloadedFiles.length = 0; // Clear memory
-					me.rtenv['callMain'](me.config.args);
-					initPromise = null;
-					resolve();
 				});
-			});
-		});
-	};
+			},
 
-	Engine.prototype.startGame = function (override) {
-		this.config.update(override);
-		// Add main-pack argument.
-		const exe = this.config.executable;
-		const pack = this.config.mainPack || `${exe}.pck`;
-		this.config.args = ['--main-pack', pack].concat(this.config.args);
-		// Start and init with execName as loadPath if not inited.
-		const me = this;
-		return Promise.all([
-			this.init(exe),
-			this.preloadFile(pack, pack),
-		]).then(function () {
-			return me.start.apply(me);
-		});
-	};
+			/**
+			 * Start the game instance using the given configuration override (if any).
+			 *
+			 * This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.
+			 *
+			 * This will load the engine if it is not loaded, and preload the main pck.
+			 *
+			 * This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`
+			 * properties set (normally done by the editor during export).
+			 *
+			 * @param {EngineConfig} override An optional configuration override.
+			 * @return {Promise} Promise that resolves once the game started.
+			 */
+			startGame: function (override) {
+				this.config.update(override);
+				// Add main-pack argument.
+				const exe = this.config.executable;
+				const pack = this.config.mainPack || `${exe}.pck`;
+				this.config.args = ['--main-pack', pack].concat(this.config.args);
+				// Start and init with execName as loadPath if not inited.
+				const me = this;
+				return Promise.all([
+					this.init(exe),
+					this.preloadFile(pack, pack),
+				]).then(function () {
+					return me.start.apply(me);
+				});
+			},
 
-	Engine.prototype.copyToFS = function (path, buffer) {
-		if (this.rtenv == null) {
-			throw new Error('Engine must be inited before copying files');
-		}
-		this.rtenv['copyToFS'](path, buffer);
-	};
+			/**
+			 * Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.
+			 *
+			 * @param {string} path The location where the file will be created.
+			 * @param {ArrayBuffer} buffer The content of the file.
+			 */
+			copyToFS: function (path, buffer) {
+				if (this.rtenv == null) {
+					throw new Error('Engine must be inited before copying files');
+				}
+				this.rtenv['copyToFS'](path, buffer);
+			},
 
-	Engine.prototype.requestQuit = function () {
-		if (this.rtenv) {
-			this.rtenv['request_quit']();
-		}
-	};
+			/**
+			 * Request that the current instance quit.
+			 *
+			 * This is akin the user pressing the close button in the window manager, and will
+			 * have no effect if the engine has crashed, or is stuck in a loop.
+			 *
+			 */
+			requestQuit: function () {
+				if (this.rtenv) {
+					this.rtenv['request_quit']();
+				}
+			},
+		};
+
+		Engine.prototype = proto;
+		// Closure compiler exported instance methods.
+		Engine.prototype['init'] = Engine.prototype.init;
+		Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
+		Engine.prototype['start'] = Engine.prototype.start;
+		Engine.prototype['startGame'] = Engine.prototype.startGame;
+		Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
+		Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
+		// Also expose static methods as instance methods
+		Engine.prototype['load'] = Engine.load;
+		Engine.prototype['unload'] = Engine.unload;
+		Engine.prototype['isWebGLAvailable'] = Engine.isWebGLAvailable;
+		return new Engine(initConfig);
+	}
+
+	// Closure compiler exported static methods.
+	SafeEngine['load'] = Engine.load;
+	SafeEngine['unload'] = Engine.unload;
+	SafeEngine['isWebGLAvailable'] = Engine.isWebGLAvailable;
 
-	// Closure compiler exported engine methods.
-	/** @export */
-	Engine['isWebGLAvailable'] = Utils.isWebGLAvailable;
-	Engine['load'] = load;
-	Engine['unload'] = unload;
-	Engine.prototype['init'] = Engine.prototype.init;
-	Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
-	Engine.prototype['start'] = Engine.prototype.start;
-	Engine.prototype['startGame'] = Engine.prototype.startGame;
-	Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
-	Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
-	return Engine;
+	return SafeEngine;
 }());
 if (typeof window !== 'undefined') {
 	window['Engine'] = Engine;

+ 0 - 58
platform/javascript/js/engine/utils.js

@@ -1,58 +0,0 @@
-const Utils = { // eslint-disable-line no-unused-vars
-
-	createLocateRewrite: function (execName) {
-		function rw(path) {
-			if (path.endsWith('.worker.js')) {
-				return `${execName}.worker.js`;
-			} else if (path.endsWith('.audio.worklet.js')) {
-				return `${execName}.audio.worklet.js`;
-			} else if (path.endsWith('.js')) {
-				return `${execName}.js`;
-			} else if (path.endsWith('.side.wasm')) {
-				return `${execName}.side.wasm`;
-			} else if (path.endsWith('.wasm')) {
-				return `${execName}.wasm`;
-			}
-			return path;
-		}
-		return rw;
-	},
-
-	createInstantiatePromise: function (wasmLoader) {
-		let loader = wasmLoader;
-		function instantiateWasm(imports, onSuccess) {
-			loader.then(function (xhr) {
-				WebAssembly.instantiate(xhr.response, imports).then(function (result) {
-					onSuccess(result['instance'], result['module']);
-				});
-			});
-			loader = null;
-			return {};
-		}
-
-		return instantiateWasm;
-	},
-
-	findCanvas: function () {
-		const nodes = document.getElementsByTagName('canvas');
-		if (nodes.length && nodes[0] instanceof HTMLCanvasElement) {
-			return nodes[0];
-		}
-		return null;
-	},
-
-	isWebGLAvailable: function (majorVersion = 1) {
-		let testContext = false;
-		try {
-			const testCanvas = document.createElement('canvas');
-			if (majorVersion === 1) {
-				testContext = testCanvas.getContext('webgl') || testCanvas.getContext('experimental-webgl');
-			} else if (majorVersion === 2) {
-				testContext = testCanvas.getContext('webgl2') || testCanvas.getContext('experimental-webgl2');
-			}
-		} catch (e) {
-			// Not available
-		}
-		return !!testContext;
-	},
-};