[HTML5] Easier HTML templates, better deinit/cleanup.

This commit is contained in:
Fabio Alessandrelli 2021-02-07 13:45:04 +01:00
parent 5c2fe970b8
commit 2972ea3229
10 changed files with 285 additions and 290 deletions

View file

@ -236,7 +236,7 @@
<script type='text/javascript' src='godot.tools.js'></script> <script type='text/javascript' src='godot.tools.js'></script>
<script type='text/javascript'>//<![CDATA[ <script type='text/javascript'>//<![CDATA[
var engine = new Engine; var editor = null;
var game = null; var game = null;
var setStatusMode; var setStatusMode;
var setStatusNotice; var setStatusNotice;
@ -321,8 +321,8 @@
function closeEditor() { function closeEditor() {
closeGame(); closeGame();
if (engine) { if (editor) {
engine.requestQuit(); editor.requestQuit();
} }
} }
@ -336,6 +336,7 @@
var statusProgressInner = document.getElementById('status-progress-inner'); var statusProgressInner = document.getElementById('status-progress-inner');
var statusIndeterminate = document.getElementById('status-indeterminate'); var statusIndeterminate = document.getElementById('status-indeterminate');
var statusNotice = document.getElementById('status-notice'); var statusNotice = document.getElementById('status-notice');
var headerDiv = document.getElementById('tabs-buttons');
var initializing = true; var initializing = true;
var statusMode = 'hidden'; var statusMode = 'hidden';
@ -349,16 +350,23 @@
} }
requestAnimationFrame(animate); requestAnimationFrame(animate);
var lastScale = 0;
var lastWidth = 0;
var lastHeight = 0;
function adjustCanvasDimensions() { function adjustCanvasDimensions() {
var scale = window.devicePixelRatio || 1; var scale = window.devicePixelRatio || 1;
var header = document.getElementById('tabs-buttons'); var headerHeight = headerDiv.offsetHeight + 1;
var headerHeight = header.offsetHeight + 1;
var width = window.innerWidth; var width = window.innerWidth;
var height = window.innerHeight - headerHeight; var height = window.innerHeight - headerHeight;
if (lastScale !== scale || lastWidth !== width || lastHeight !== height) {
editorCanvas.width = width * scale; editorCanvas.width = width * scale;
editorCanvas.height = height * scale; editorCanvas.height = height * scale;
editorCanvas.style.width = width + "px"; editorCanvas.style.width = width + "px";
editorCanvas.style.height = height + "px"; editorCanvas.style.height = height + "px";
lastScale = scale;
lastWidth = width;
lastHeight = height;
}
} }
animationCallbacks.push(adjustCanvasDimensions); animationCallbacks.push(adjustCanvasDimensions);
adjustCanvasDimensions(); adjustCanvasDimensions();
@ -412,24 +420,23 @@
}); });
}; };
engine.setProgressFunc((current, total) => { const gameConfig = {
if (total > 0) { 'persistentPaths': persistentPaths,
statusProgressInner.style.width = current/total * 100 + '%'; 'unloadAfterInit': false,
setStatusMode('progress'); 'canvas': gameCanvas,
if (current === total) { 'canvasResizePolicy': 1,
// wait for progress bar animation 'onExit': function () {
setTimeout(() => { setGameTabEnabled(false);
setStatusMode('indeterminate'); showTab('editor');
}, 100); game = null;
} },
} else { };
setStatusMode('indeterminate');
}
});
engine.setPersistentPaths(persistentPaths); var OnEditorExit = function () {
showTab('loader');
engine.setOnExecute(function(args) { setLoaderEnabled(true);
};
function Execute(args) {
const is_editor = args.filter(function(v) { return v == '--editor' || v == '-e' }).length != 0; const is_editor = args.filter(function(v) { return v == '--editor' || v == '-e' }).length != 0;
const is_project_manager = args.filter(function(v) { return v == '--project-manager' }).length != 0; const is_project_manager = args.filter(function(v) { return v == '--project-manager' }).length != 0;
const is_game = !is_editor && !is_project_manager; const is_game = !is_editor && !is_project_manager;
@ -442,42 +449,60 @@
return; return;
} }
setGameTabEnabled(true); setGameTabEnabled(true);
game = new Engine(); game = new Engine(gameConfig);
game.setPersistentPaths(persistentPaths);
game.setUnloadAfterInit(false);
game.setOnExecute(engine.onExecute);
game.setCanvas(gameCanvas);
game.setCanvasResizedOnStart(true);
game.setOnExit(function() {
setGameTabEnabled(false);
showTab('editor');
game = null;
});
showTab('game'); showTab('game');
game.init().then(function() { game.init().then(function() {
requestAnimationFrame(function() { requestAnimationFrame(function() {
game.start.apply(game, args).then(function() { game.start({'args': args}).then(function() {
gameCanvas.focus(); gameCanvas.focus();
}); });
}); });
}); });
} else { // New editor instances will be run in the same canvas. We want to wait for it to exit. } else { // New editor instances will be run in the same canvas. We want to wait for it to exit.
engine.setOnExit(function(code) { OnEditorExit = function(code) {
setLoaderEnabled(true); setLoaderEnabled(true);
setTimeout(function() { setTimeout(function() {
engine.init().then(function() { editor.init().then(function() {
setLoaderEnabled(false); setLoaderEnabled(false);
engine.setOnExit(function() { OnEditorExit = function() {
showTab('loader'); showTab('loader');
setLoaderEnabled(true); setLoaderEnabled(true);
}); };
engine.start.apply(engine, args); editor.start({'args': args});
}); });
}, 0); }, 0);
engine.setOnExit(null); OnEditorExit = null;
}); };
} }
}); }
const editorConfig = {
'unloadAfterInit': false,
'onProgress': function progressFunction (current, total) {
if (total > 0) {
statusProgressInner.style.width = current/total * 100 + '%';
setStatusMode('progress');
if (current === total) {
// wait for progress bar animation
setTimeout(() => {
setStatusMode('indeterminate');
}, 100);
}
} else {
setStatusMode('indeterminate');
}
},
'canvas': editorCanvas,
'canvasResizePolicy': 0,
'onExit': function() {
if (OnEditorExit) {
OnEditorExit();
}
},
'onExecute': Execute,
'persistentPaths': persistentPaths,
};
editor = new Engine(editorConfig);
function displayFailureNotice(err) { function displayFailureNotice(err) {
var msg = err.message || err; var msg = err.message || err;
@ -491,26 +516,20 @@
displayFailureNotice('WebGL not available'); displayFailureNotice('WebGL not available');
} else { } else {
setStatusMode('indeterminate'); setStatusMode('indeterminate');
engine.setCanvas(editorCanvas); editor.init('godot.tools').then(function() {
engine.setUnloadAfterInit(false); // Don't want to reload when starting game.
engine.init('godot.tools').then(function() {
if (zip) { if (zip) {
engine.copyToFS("/tmp/preload.zip", zip); editor.copyToFS("/tmp/preload.zip", zip);
} }
try { try {
// Avoid user creating project in the persistent root folder. // Avoid user creating project in the persistent root folder.
engine.copyToFS("/home/web_user/keep", new Uint8Array()); editor.copyToFS("/home/web_user/keep", new Uint8Array());
} catch(e) { } catch(e) {
// File exists // File exists
} }
//selectVideoMode(); //selectVideoMode();
showTab('editor'); showTab('editor');
setLoaderEnabled(false); setLoaderEnabled(false);
engine.setOnExit(function() { editor.start({'args': ['--video-driver', video_driver]}).then(function() {
showTab('loader');
setLoaderEnabled(true);
});
engine.start('--video-driver', video_driver).then(function() {
setStatusMode('hidden'); setStatusMode('hidden');
initializing = false; initializing = false;
}); });

View file

@ -134,21 +134,14 @@ $GODOT_HEAD_INCLUDE
<div id='status-notice' class='godot' style='display: none;'></div> <div id='status-notice' class='godot' style='display: none;'></div>
</div> </div>
<script type='text/javascript' src='$GODOT_BASENAME.js'></script> <script type='text/javascript' src='$GODOT_URL'></script>
<script type='text/javascript'>//<![CDATA[ <script type='text/javascript'>//<![CDATA[
var engine = new Engine; const GODOT_CONFIG = $GODOT_CONFIG;
var setStatusMode; var engine = new Engine(GODOT_CONFIG);
var setStatusNotice;
(function() { (function() {
const EXECUTABLE_NAME = '$GODOT_BASENAME';
const MAIN_PACK = '$GODOT_BASENAME.pck';
const EXTRA_ARGS = JSON.parse('$GODOT_ARGS');
const GDNATIVE_LIBS = [$GODOT_GDNATIVE_LIBS];
const INDETERMINATE_STATUS_STEP_MS = 100; const INDETERMINATE_STATUS_STEP_MS = 100;
const FULL_WINDOW = $GODOT_FULL_WINDOW;
var canvas = document.getElementById('canvas'); var canvas = document.getElementById('canvas');
var statusProgress = document.getElementById('status-progress'); var statusProgress = document.getElementById('status-progress');
var statusProgressInner = document.getElementById('status-progress-inner'); var statusProgressInner = document.getElementById('status-progress-inner');
@ -180,14 +173,13 @@ $GODOT_HEAD_INCLUDE
canvas.style.height = lastHeight + "px"; canvas.style.height = lastHeight + "px";
} }
} }
if (FULL_WINDOW) { if (GODOT_CONFIG['canvasResizePolicy'] == 2) {
animationCallbacks.push(adjustCanvasDimensions); animationCallbacks.push(adjustCanvasDimensions);
adjustCanvasDimensions(); adjustCanvasDimensions();
} else {
engine.setCanvasResizedOnStart(true);
} }
setStatusMode = function setStatusMode(mode) { function setStatusMode(mode) {
if (statusMode === mode || !initializing) if (statusMode === mode || !initializing)
return; return;
[statusProgress, statusIndeterminate, statusNotice].forEach(elem => { [statusProgress, statusIndeterminate, statusNotice].forEach(elem => {
@ -213,7 +205,7 @@ $GODOT_HEAD_INCLUDE
throw new Error('Invalid status mode'); throw new Error('Invalid status mode');
} }
statusMode = mode; statusMode = mode;
}; }
function animateStatusIndeterminate(ms) { function animateStatusIndeterminate(ms) {
var i = Math.floor(ms / INDETERMINATE_STATUS_STEP_MS % 8); var i = Math.floor(ms / INDETERMINATE_STATUS_STEP_MS % 8);
@ -225,7 +217,7 @@ $GODOT_HEAD_INCLUDE
} }
} }
setStatusNotice = function setStatusNotice(text) { function setStatusNotice(text) {
while (statusNotice.lastChild) { while (statusNotice.lastChild) {
statusNotice.removeChild(statusNotice.lastChild); statusNotice.removeChild(statusNotice.lastChild);
} }
@ -236,21 +228,6 @@ $GODOT_HEAD_INCLUDE
}); });
}; };
engine.setProgressFunc((current, total) => {
if (total > 0) {
statusProgressInner.style.width = current/total * 100 + '%';
setStatusMode('progress');
if (current === total) {
// wait for progress bar animation
setTimeout(() => {
setStatusMode('indeterminate');
}, 500);
}
} else {
setStatusMode('indeterminate');
}
});
function displayFailureNotice(err) { function displayFailureNotice(err) {
var msg = err.message || err; var msg = err.message || err;
console.error(msg); console.error(msg);
@ -263,9 +240,22 @@ $GODOT_HEAD_INCLUDE
displayFailureNotice('WebGL not available'); displayFailureNotice('WebGL not available');
} else { } else {
setStatusMode('indeterminate'); setStatusMode('indeterminate');
engine.setCanvas(canvas); engine.startGame({
engine.setGDNativeLibraries(GDNATIVE_LIBS); 'onProgress': function (current, total) {
engine.startGame(EXECUTABLE_NAME, MAIN_PACK, EXTRA_ARGS).then(() => { if (total > 0) {
statusProgressInner.style.width = current/total * 100 + '%';
setStatusMode('progress');
if (current === total) {
// wait for progress bar animation
setTimeout(() => {
setStatusMode('indeterminate');
}, 500);
}
} else {
setStatusMode('indeterminate');
}
},
}).then(() => {
setStatusMode('hidden'); setStatusMode('hidden');
initializing = false; initializing = false;
}, displayFailureNotice); }, displayFailureNotice);

View file

@ -3,6 +3,7 @@ module.exports = {
"./.eslintrc.js", "./.eslintrc.js",
], ],
"globals": { "globals": {
"EngineConfig": true,
"Godot": true, "Godot": true,
"Preloader": true, "Preloader": true,
"Utils": true, "Utils": true,

View file

@ -74,6 +74,7 @@ sys_env.Depends(build[0], sys_env["JS_EXTERNS"])
engine = [ engine = [
"js/engine/preloader.js", "js/engine/preloader.js",
"js/engine/utils.js", "js/engine/utils.js",
"js/engine/config.js",
"js/engine/engine.js", "js/engine/engine.js",
] ]
externs = [env.File("#platform/javascript/js/engine/engine.externs.js")] externs = [env.File("#platform/javascript/js/engine/engine.externs.js")]

View file

@ -749,7 +749,7 @@ DisplayServerJavaScript::DisplayServerJavaScript(const String &p_rendering_drive
#endif #endif
window_set_mode(p_mode); window_set_mode(p_mode);
if (godot_js_config_is_resize_on_start()) { if (godot_js_config_canvas_resize_policy_get() == 1) {
window_set_size(p_resolution); window_set_size(p_resolution);
} }

View file

@ -285,24 +285,29 @@ void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t> &p_html, const Re
String str_template = String::utf8(reinterpret_cast<const char *>(p_html.ptr()), p_html.size()); String str_template = String::utf8(reinterpret_cast<const char *>(p_html.ptr()), p_html.size());
String str_export; String str_export;
Vector<String> lines = str_template.split("\n"); Vector<String> lines = str_template.split("\n");
Vector<String> flags; Array libs;
String flags_json;
gen_export_flags(flags, p_flags);
flags_json = JSON::print(flags);
String libs;
for (int i = 0; i < p_shared_objects.size(); i++) { for (int i = 0; i < p_shared_objects.size(); i++) {
libs += "\"" + p_shared_objects[i].path.get_file() + "\","; libs.push_back(p_shared_objects[i].path.get_file());
} }
Vector<String> flags;
gen_export_flags(flags, p_flags & (~DEBUG_FLAG_DUMB_CLIENT));
Array args;
for (int i = 0; i < flags.size(); i++) {
args.push_back(flags[i]);
}
Dictionary config;
config["canvasResizePolicy"] = p_preset->get("html/full_window_size") ? 2 : 1;
config["gdnativeLibs"] = libs;
config["executable"] = p_name;
config["args"] = args;
const String str_config = JSON::print(config);
for (int i = 0; i < lines.size(); i++) { for (int i = 0; i < lines.size(); i++) {
String current_line = lines[i]; String current_line = lines[i];
current_line = current_line.replace("$GODOT_BASENAME", p_name); current_line = current_line.replace("$GODOT_URL", p_name + ".js");
current_line = current_line.replace("$GODOT_PROJECT_NAME", ProjectSettings::get_singleton()->get_setting("application/config/name")); current_line = current_line.replace("$GODOT_PROJECT_NAME", ProjectSettings::get_singleton()->get_setting("application/config/name"));
current_line = current_line.replace("$GODOT_HEAD_INCLUDE", p_preset->get("html/head_include")); current_line = current_line.replace("$GODOT_HEAD_INCLUDE", p_preset->get("html/head_include"));
current_line = current_line.replace("$GODOT_FULL_WINDOW", p_preset->get("html/full_window_size") ? "true" : "false"); current_line = current_line.replace("$GODOT_CONFIG", str_config);
current_line = current_line.replace("$GODOT_GDNATIVE_LIBS", libs);
current_line = current_line.replace("$GODOT_DEBUG_ENABLED", p_debug ? "true" : "false");
current_line = current_line.replace("$GODOT_ARGS", flags_json);
str_export += current_line + "\n"; str_export += current_line + "\n";
} }

View file

@ -40,7 +40,7 @@ extern "C" {
// Config // Config
extern void godot_js_config_locale_get(char *p_ptr, int p_ptr_max); extern void godot_js_config_locale_get(char *p_ptr, int p_ptr_max);
extern void godot_js_config_canvas_id_get(char *p_ptr, int p_ptr_max); extern void godot_js_config_canvas_id_get(char *p_ptr, int p_ptr_max);
extern int godot_js_config_is_resize_on_start(); extern int godot_js_config_canvas_resize_policy_get();
// OS // OS
extern void godot_js_os_finish_async(void (*p_callback)()); extern void godot_js_os_finish_async(void (*p_callback)());

View file

@ -0,0 +1,100 @@
/** @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
};
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);
}
EngineConfig.prototype.update = function (opts) {
const config = opts || {};
function parse(key, def) {
if (typeof (config[key]) === 'undefined') {
return def;
}
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);
// 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`],
};
};
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');
}
}
// 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;
// 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);
}
},
};
};

View file

@ -1,20 +1,14 @@
const Engine = (function () { const Engine = (function () {
const preloader = new Preloader(); const preloader = new Preloader();
let wasmExt = '.wasm';
let unloadAfterInit = true;
let loadPath = '';
let loadPromise = null; let loadPromise = null;
let loadPath = '';
let initPromise = null; let initPromise = null;
let stderr = null;
let stdout = null;
let progressFunc = null;
function load(basePath) { function load(basePath) {
if (loadPromise == null) { if (loadPromise == null) {
loadPath = basePath; loadPath = basePath;
loadPromise = preloader.loadPromise(basePath + wasmExt); loadPromise = preloader.loadPromise(`${loadPath}.wasm`);
preloader.setProgressFunc(progressFunc);
requestAnimationFrame(preloader.animateProgress); requestAnimationFrame(preloader.animateProgress);
} }
return loadPromise; return loadPromise;
@ -25,16 +19,9 @@ const Engine = (function () {
} }
/** @constructor */ /** @constructor */
function Engine() { // eslint-disable-line no-shadow function Engine(opts) { // eslint-disable-line no-shadow
this.canvas = null; this.config = new EngineConfig(opts);
this.executableName = '';
this.rtenv = null; this.rtenv = null;
this.customLocale = null;
this.resizeCanvasOnStart = false;
this.onExecute = null;
this.onExit = null;
this.persistentPaths = ['/userfs'];
this.gdnativeLibs = [];
} }
Engine.prototype.init = /** @param {string=} basePath */ function (basePath) { Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
@ -48,25 +35,14 @@ const Engine = (function () {
} }
load(basePath); load(basePath);
} }
let config = {}; preloader.setProgressFunc(this.config.onProgress);
if (typeof stdout === 'function') { let config = this.config.getModuleConfig(loadPath, loadPromise);
config.print = stdout;
}
if (typeof stderr === 'function') {
config.printErr = stderr;
}
const me = this; const me = this;
initPromise = new Promise(function (resolve, reject) { initPromise = new Promise(function (resolve, reject) {
config['locateFile'] = Utils.createLocateRewrite(loadPath);
config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise);
// Emscripten configuration.
config['thisProgram'] = me.executableName;
config['noExitRuntime'] = true;
config['dynamicLibraries'] = [`${me.executableName}.side.wasm`].concat(me.gdnativeLibs);
Godot(config).then(function (module) { Godot(config).then(function (module) {
module['initFS'](me.persistentPaths).then(function (fs_err) { module['initFS'](me.config.persistentPaths).then(function (fs_err) {
me.rtenv = module; me.rtenv = module;
if (unloadAfterInit) { if (me.config.unloadAfterInit) {
unload(); unload();
} }
resolve(); resolve();
@ -83,150 +59,58 @@ const Engine = (function () {
}; };
/** @type {function(...string):Object} */ /** @type {function(...string):Object} */
Engine.prototype.start = function () { Engine.prototype.start = function (override) {
// Start from arguments. this.config.update(override);
const args = [];
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
const me = this; const me = this;
return me.init().then(function () { return me.init().then(function () {
if (!me.rtenv) { if (!me.rtenv) {
return Promise.reject(new Error('The engine must be initialized before it can be started')); return Promise.reject(new Error('The engine must be initialized before it can be started'));
} }
if (!(me.canvas instanceof HTMLCanvasElement)) { let config = {};
me.canvas = Utils.findCanvas(); try {
if (!me.canvas) { config = me.config.getGodotConfig(function () {
return Promise.reject(new Error('No canvas found in page')); me.rtenv = null;
} });
} } catch (e) {
return Promise.reject(e);
// Canvas can grab focus on click, or key events won't work.
if (me.canvas.tabIndex < 0) {
me.canvas.tabIndex = 0;
}
// Browser locale, or custom one if defined.
let locale = me.customLocale;
if (!locale) {
locale = navigator.languages ? navigator.languages[0] : navigator.language;
locale = locale.split('.')[0];
} }
// Godot configuration. // Godot configuration.
me.rtenv['initConfig']({ me.rtenv['initConfig'](config);
'resizeCanvasOnStart': me.resizeCanvasOnStart,
'canvas': me.canvas,
'locale': locale,
'onExecute': function (p_args) {
if (me.onExecute) {
me.onExecute(p_args);
return 0;
}
return 1;
},
'onExit': function (p_code) {
me.rtenv['deinitFS']();
if (me.onExit) {
me.onExit(p_code);
}
me.rtenv = null;
},
});
// 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) { return new Promise(function (resolve, reject) {
preloader.preloadedFiles.forEach(function (file) { preloader.preloadedFiles.forEach(function (file) {
me.rtenv['copyToFS'](file.path, file.buffer); me.rtenv['copyToFS'](file.path, file.buffer);
}); });
preloader.preloadedFiles.length = 0; // Clear memory preloader.preloadedFiles.length = 0; // Clear memory
me.rtenv['callMain'](args); me.rtenv['callMain'](me.config.args);
initPromise = null; initPromise = null;
resolve(); resolve();
}); });
}); });
};
Engine.prototype.startGame = function (execName, mainPack, extraArgs) {
// Start and init with execName as loadPath if not inited.
this.executableName = execName;
const me = this;
return Promise.all([
this.init(execName),
this.preloadFile(mainPack, mainPack),
]).then(function () {
let args = ['--main-pack', mainPack];
if (extraArgs) {
args = args.concat(extraArgs);
}
return me.start.apply(me, args);
}); });
}; };
Engine.prototype.setWebAssemblyFilenameExtension = function (override) { Engine.prototype.startGame = function (override) {
if (String(override).length === 0) { this.config.update(override);
throw new Error('Invalid WebAssembly filename extension override'); // Add main-pack argument.
} const exe = this.config.executable;
wasmExt = String(override); 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.
Engine.prototype.setUnloadAfterInit = function (enabled) { const me = this;
unloadAfterInit = enabled; return Promise.all([
}; this.init(exe),
this.preloadFile(pack, pack),
Engine.prototype.setCanvas = function (canvasElem) { ]).then(function () {
this.canvas = canvasElem; return me.start.apply(me);
}; });
Engine.prototype.setCanvasResizedOnStart = function (enabled) {
this.resizeCanvasOnStart = enabled;
};
Engine.prototype.setLocale = function (locale) {
this.customLocale = locale;
};
Engine.prototype.setExecutableName = function (newName) {
this.executableName = newName;
};
Engine.prototype.setProgressFunc = function (func) {
progressFunc = func;
};
Engine.prototype.setStdoutFunc = function (func) {
const print = function (text) {
let msg = text;
if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(' ');
}
func(msg);
};
if (this.rtenv) {
this.rtenv.print = print;
}
stdout = print;
};
Engine.prototype.setStderrFunc = function (func) {
const printErr = function (text) {
let msg = text;
if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(' ');
}
func(msg);
};
if (this.rtenv) {
this.rtenv.printErr = printErr;
}
stderr = printErr;
};
Engine.prototype.setOnExecute = function (onExecute) {
this.onExecute = onExecute;
};
Engine.prototype.setOnExit = function (onExit) {
this.onExit = onExit;
}; };
Engine.prototype.copyToFS = function (path, buffer) { Engine.prototype.copyToFS = function (path, buffer) {
@ -236,14 +120,6 @@ const Engine = (function () {
this.rtenv['copyToFS'](path, buffer); this.rtenv['copyToFS'](path, buffer);
}; };
Engine.prototype.setPersistentPaths = function (persistentPaths) {
this.persistentPaths = persistentPaths;
};
Engine.prototype.setGDNativeLibraries = function (gdnativeLibs) {
this.gdnativeLibs = gdnativeLibs;
};
Engine.prototype.requestQuit = function () { Engine.prototype.requestQuit = function () {
if (this.rtenv) { if (this.rtenv) {
this.rtenv['request_quit'](); this.rtenv['request_quit']();
@ -259,20 +135,7 @@ const Engine = (function () {
Engine.prototype['preloadFile'] = Engine.prototype.preloadFile; Engine.prototype['preloadFile'] = Engine.prototype.preloadFile;
Engine.prototype['start'] = Engine.prototype.start; Engine.prototype['start'] = Engine.prototype.start;
Engine.prototype['startGame'] = Engine.prototype.startGame; Engine.prototype['startGame'] = Engine.prototype.startGame;
Engine.prototype['setWebAssemblyFilenameExtension'] = Engine.prototype.setWebAssemblyFilenameExtension;
Engine.prototype['setUnloadAfterInit'] = Engine.prototype.setUnloadAfterInit;
Engine.prototype['setCanvas'] = Engine.prototype.setCanvas;
Engine.prototype['setCanvasResizedOnStart'] = Engine.prototype.setCanvasResizedOnStart;
Engine.prototype['setLocale'] = Engine.prototype.setLocale;
Engine.prototype['setExecutableName'] = Engine.prototype.setExecutableName;
Engine.prototype['setProgressFunc'] = Engine.prototype.setProgressFunc;
Engine.prototype['setStdoutFunc'] = Engine.prototype.setStdoutFunc;
Engine.prototype['setStderrFunc'] = Engine.prototype.setStderrFunc;
Engine.prototype['setOnExecute'] = Engine.prototype.setOnExecute;
Engine.prototype['setOnExit'] = Engine.prototype.setOnExit;
Engine.prototype['copyToFS'] = Engine.prototype.copyToFS; Engine.prototype['copyToFS'] = Engine.prototype.copyToFS;
Engine.prototype['setPersistentPaths'] = Engine.prototype.setPersistentPaths;
Engine.prototype['setGDNativeLibraries'] = Engine.prototype.setGDNativeLibraries;
Engine.prototype['requestQuit'] = Engine.prototype.requestQuit; Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
return Engine; return Engine;
}()); }());

View file

@ -58,21 +58,28 @@ const GodotConfig = {
$GodotConfig: { $GodotConfig: {
canvas: null, canvas: null,
locale: 'en', locale: 'en',
resize_on_start: false, canvas_resize_policy: 2, // Adaptive
on_execute: null, on_execute: null,
on_exit: null,
init_config: function (p_opts) { init_config: function (p_opts) {
GodotConfig.resize_on_start = !!p_opts['resizeCanvasOnStart']; GodotConfig.canvas_resize_policy = p_opts['canvasResizePolicy'];
GodotConfig.canvas = p_opts['canvas']; GodotConfig.canvas = p_opts['canvas'];
GodotConfig.locale = p_opts['locale'] || GodotConfig.locale; GodotConfig.locale = p_opts['locale'] || GodotConfig.locale;
GodotConfig.on_execute = p_opts['onExecute']; GodotConfig.on_execute = p_opts['onExecute'];
// This is called by emscripten, even if undocumented. GodotConfig.on_exit = p_opts['onExit'];
Module['onExit'] = p_opts['onExit']; // eslint-disable-line no-undef
}, },
locate_file: function (file) { locate_file: function (file) {
return Module['locateFile'](file); // eslint-disable-line no-undef return Module['locateFile'](file); // eslint-disable-line no-undef
}, },
clear: function () {
GodotConfig.canvas = null;
GodotConfig.locale = 'en';
GodotConfig.canvas_resize_policy = 2;
GodotConfig.on_execute = null;
GodotConfig.on_exit = null;
},
}, },
godot_js_config_canvas_id_get__sig: 'vii', godot_js_config_canvas_id_get__sig: 'vii',
@ -85,9 +92,9 @@ const GodotConfig = {
GodotRuntime.stringToHeap(GodotConfig.locale, p_ptr, p_ptr_max); GodotRuntime.stringToHeap(GodotConfig.locale, p_ptr, p_ptr_max);
}, },
godot_js_config_is_resize_on_start__sig: 'i', godot_js_config_canvas_resize_policy_get__sig: 'i',
godot_js_config_is_resize_on_start: function () { godot_js_config_canvas_resize_policy_get: function () {
return GodotConfig.resize_on_start ? 1 : 0; return GodotConfig.canvas_resize_policy;
}, },
}; };
@ -98,7 +105,6 @@ const GodotFS = {
$GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'], $GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'],
$GodotFS__postset: [ $GodotFS__postset: [
'Module["initFS"] = GodotFS.init;', 'Module["initFS"] = GodotFS.init;',
'Module["deinitFS"] = GodotFS.deinit;',
'Module["copyToFS"] = GodotFS.copy_to_fs;', 'Module["copyToFS"] = GodotFS.copy_to_fs;',
].join(''), ].join(''),
$GodotFS: { $GodotFS: {
@ -210,9 +216,10 @@ const GodotFS = {
mergeInto(LibraryManager.library, GodotFS); mergeInto(LibraryManager.library, GodotFS);
const GodotOS = { const GodotOS = {
$GodotOS__deps: ['$GodotFS', '$GodotRuntime'], $GodotOS__deps: ['$GodotRuntime', '$GodotConfig', '$GodotFS'],
$GodotOS__postset: [ $GodotOS__postset: [
'Module["request_quit"] = function() { GodotOS.request_quit() };', 'Module["request_quit"] = function() { GodotOS.request_quit() };',
'Module["onExit"] = GodotOS.cleanup;',
'GodotOS._fs_sync_promise = Promise.resolve();', 'GodotOS._fs_sync_promise = Promise.resolve();',
].join(''), ].join(''),
$GodotOS: { $GodotOS: {
@ -224,6 +231,15 @@ const GodotOS = {
GodotOS._async_cbs.push(p_promise_cb); GodotOS._async_cbs.push(p_promise_cb);
}, },
cleanup: function (exit_code) {
const cb = GodotConfig.on_exit;
GodotFS.deinit();
GodotConfig.clear();
if (cb) {
cb(exit_code);
}
},
finish_async: function (callback) { finish_async: function (callback) {
GodotOS._fs_sync_promise.then(function (err) { GodotOS._fs_sync_promise.then(function (err) {
const promises = []; const promises = [];