/**1* Projects exported for the Web expose the :js:class:`Engine` class to the JavaScript environment, that allows2* fine control over the engine's start-up process.3*4* This API is built in an asynchronous manner and requires basic understanding5* of `Promises <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises>`__.6*7* @module Engine8* @header Web export JavaScript reference9*/10const Engine = (function () {11const preloader = new Preloader();1213let loadPromise = null;14let loadPath = '';15let initPromise = null;1617/**18* @classdesc The ``Engine`` class provides methods for loading and starting exported projects on the Web. For default export19* settings, this is already part of the exported HTML page. To understand practical use of the ``Engine`` class,20* see :ref:`Custom HTML page for Web export <doc_customizing_html5_shell>`.21*22* @description Create a new Engine instance with the given configuration.23*24* @global25* @constructor26* @param {EngineConfig} initConfig The initial config for this instance.27*/28function Engine(initConfig) { // eslint-disable-line no-shadow29this.config = new InternalConfig(initConfig);30this.rtenv = null;31}3233/**34* Load the engine from the specified base path.35*36* @param {string} basePath Base path of the engine to load.37* @param {number=} [size=0] The file size if known.38* @returns {Promise} A Promise that resolves once the engine is loaded.39*40* @function Engine.load41*/42Engine.load = function (basePath, size) {43if (loadPromise == null) {44loadPath = basePath;45loadPromise = preloader.loadPromise(`${loadPath}.wasm`, size, true);46requestAnimationFrame(preloader.animateProgress);47}48return loadPromise;49};5051/**52* Unload the engine to free memory.53*54* This method will be called automatically depending on the configuration. See :js:attr:`unloadAfterInit`.55*56* @function Engine.unload57*/58Engine.unload = function () {59loadPromise = null;60};6162/**63* Safe Engine constructor, creates a new prototype for every new instance to avoid prototype pollution.64* @ignore65* @constructor66*/67function SafeEngine(initConfig) {68const proto = /** @lends Engine.prototype */ {69/**70* Initialize the engine instance. Optionally, pass the base path to the engine to load it,71* if it hasn't been loaded yet. See :js:meth:`Engine.load`.72*73* @param {string=} basePath Base path of the engine to load.74* @return {Promise} A ``Promise`` that resolves once the engine is loaded and initialized.75*/76init: function (basePath) {77if (initPromise) {78return initPromise;79}80if (loadPromise == null) {81if (!basePath) {82initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));83return initPromise;84}85Engine.load(basePath, this.config.fileSizes[`${basePath}.wasm`]);86}87const me = this;88function doInit(promise) {89// Care! Promise chaining is bogus with old emscripten versions.90// This caused a regression with the Mono build (which uses an older emscripten version).91// Make sure to test that when refactoring.92return new Promise(function (resolve, reject) {93promise.then(function (response) {94const cloned = new Response(response.clone().body, { 'headers': [['content-type', 'application/wasm']] });95Godot(me.config.getModuleConfig(loadPath, cloned)).then(function (module) {96const paths = me.config.persistentPaths;97module['initFS'](paths).then(function (err) {98me.rtenv = module;99if (me.config.unloadAfterInit) {100Engine.unload();101}102resolve();103});104});105});106});107}108preloader.setProgressFunc(this.config.onProgress);109initPromise = doInit(loadPromise);110return initPromise;111},112113/**114* Load a file so it is available in the instance's file system once it runs. Must be called **before** starting the115* instance.116*117* If not provided, the ``path`` is derived from the URL of the loaded file.118*119* @param {string|ArrayBuffer} file The file to preload.120*121* If a ``string`` the file will be loaded from that path.122*123* If an ``ArrayBuffer`` or a view on one, the buffer will used as the content of the file.124*125* @param {string=} path Path by which the file will be accessible. Required, if ``file`` is not a string.126*127* @returns {Promise} A Promise that resolves once the file is loaded.128*/129preloadFile: function (file, path) {130return preloader.preload(file, path, this.config.fileSizes[file]);131},132133/**134* Start the engine instance using the given override configuration (if any).135* :js:meth:`startGame <Engine.prototype.startGame>` can be used in typical cases instead.136*137* This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.138* The engine must be loaded beforehand.139*140* Fails if a canvas cannot be found on the page, or not specified in the configuration.141*142* @param {EngineConfig} override An optional configuration override.143* @return {Promise} Promise that resolves once the engine started.144*/145start: function (override) {146this.config.update(override);147const me = this;148return me.init().then(function () {149if (!me.rtenv) {150return Promise.reject(new Error('The engine must be initialized before it can be started'));151}152153let config = {};154try {155config = me.config.getGodotConfig(function () {156me.rtenv = null;157});158} catch (e) {159return Promise.reject(e);160}161// Godot configuration.162me.rtenv['initConfig'](config);163164// Preload GDExtension libraries.165if (me.config.gdextensionLibs.length > 0 && !me.rtenv['loadDynamicLibrary']) {166return Promise.reject(new Error('GDExtension libraries are not supported by this engine version. '167+ 'Enable "Extensions Support" for your export preset and/or build your custom template with "dlink_enabled=yes".'));168}169return new Promise(function (resolve, reject) {170for (const file of preloader.preloadedFiles) {171me.rtenv['copyToFS'](file.path, file.buffer);172}173preloader.preloadedFiles.length = 0; // Clear memory174me.rtenv['callMain'](me.config.args);175initPromise = null;176me.installServiceWorker();177resolve();178});179});180},181182/**183* Start the game instance using the given configuration override (if any).184*185* This will initialize the instance if it is not initialized. For manual initialization, see :js:meth:`init <Engine.prototype.init>`.186*187* This will load the engine if it is not loaded, and preload the main pck.188*189* This method expects the initial config (or the override) to have both the :js:attr:`executable` and :js:attr:`mainPack`190* properties set (normally done by the editor during export).191*192* @param {EngineConfig} override An optional configuration override.193* @return {Promise} Promise that resolves once the game started.194*/195startGame: function (override) {196this.config.update(override);197// Add main-pack argument.198const exe = this.config.executable;199const pack = this.config.mainPack || `${exe}.pck`;200this.config.args = ['--main-pack', pack].concat(this.config.args);201// Start and init with execName as loadPath if not inited.202const me = this;203return Promise.all([204this.init(exe),205this.preloadFile(pack, pack),206]).then(function () {207return me.start.apply(me);208});209},210211/**212* Create a file at the specified ``path`` with the passed as ``buffer`` in the instance's file system.213*214* @param {string} path The location where the file will be created.215* @param {ArrayBuffer} buffer The content of the file.216*/217copyToFS: function (path, buffer) {218if (this.rtenv == null) {219throw new Error('Engine must be inited before copying files');220}221this.rtenv['copyToFS'](path, buffer);222},223224/**225* Request that the current instance quit.226*227* This is akin the user pressing the close button in the window manager, and will228* have no effect if the engine has crashed, or is stuck in a loop.229*230*/231requestQuit: function () {232if (this.rtenv) {233this.rtenv['request_quit']();234}235},236237/**238* Install the progressive-web app service worker.239* @returns {Promise} The service worker registration promise.240*/241installServiceWorker: function () {242if (this.config.serviceWorker && 'serviceWorker' in navigator) {243try {244return navigator.serviceWorker.register(this.config.serviceWorker);245} catch (e) {246return Promise.reject(e);247}248}249return Promise.resolve();250},251};252253Engine.prototype = proto;254// Closure compiler exported instance methods.255Engine.prototype['init'] = Engine.prototype.init;256Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;257Engine.prototype['start'] = Engine.prototype.start;258Engine.prototype['startGame'] = Engine.prototype.startGame;259Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;260Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;261Engine.prototype['installServiceWorker'] = Engine.prototype.installServiceWorker;262// Also expose static methods as instance methods263Engine.prototype['load'] = Engine.load;264Engine.prototype['unload'] = Engine.unload;265return new Engine(initConfig);266}267268// Closure compiler exported static methods.269SafeEngine['load'] = Engine.load;270SafeEngine['unload'] = Engine.unload;271272// Feature-detection utilities.273SafeEngine['isWebGLAvailable'] = Features.isWebGLAvailable;274SafeEngine['isFetchAvailable'] = Features.isFetchAvailable;275SafeEngine['isSecureContext'] = Features.isSecureContext;276SafeEngine['isCrossOriginIsolated'] = Features.isCrossOriginIsolated;277SafeEngine['isSharedArrayBufferAvailable'] = Features.isSharedArrayBufferAvailable;278SafeEngine['isAudioWorkletAvailable'] = Features.isAudioWorkletAvailable;279SafeEngine['getMissingFeatures'] = Features.getMissingFeatures;280281return SafeEngine;282}());283if (typeof window !== 'undefined') {284window['Engine'] = Engine;285}286287288