Debian Codegraph @

platform/web/js/engine/engine.js

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