1
0
mirror of https://github.com/godotengine/godot.git synced 2025-11-04 12:00:25 +00:00

[HTML5] Run eslint --fix.

Should I write a poem about this whole new world? ;)
This commit is contained in:
Fabio Alessandrelli
2020-11-23 12:13:52 +01:00
parent c38984d286
commit 4617a7fa9c
13 changed files with 515 additions and 507 deletions

View File

@@ -32,7 +32,7 @@ const GodotRTCDataChannel = {
// Our socket implementation that forwards events to C++. // Our socket implementation that forwards events to C++.
$GodotRTCDataChannel__deps: ['$IDHandler', '$GodotRuntime'], $GodotRTCDataChannel__deps: ['$IDHandler', '$GodotRuntime'],
$GodotRTCDataChannel: { $GodotRTCDataChannel: {
connect: function(p_id, p_on_open, p_on_message, p_on_error, p_on_close) { connect: function (p_id, p_on_open, p_on_message, p_on_error, p_on_close) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -48,31 +48,31 @@ const GodotRTCDataChannel = {
ref.onerror = function (event) { ref.onerror = function (event) {
p_on_error(); p_on_error();
}; };
ref.onmessage = function(event) { ref.onmessage = function (event) {
var buffer; let buffer;
var is_string = 0; let is_string = 0;
if (event.data instanceof ArrayBuffer) { if (event.data instanceof ArrayBuffer) {
buffer = new Uint8Array(event.data); buffer = new Uint8Array(event.data);
} else if (event.data instanceof Blob) { } else if (event.data instanceof Blob) {
GodotRuntime.error("Blob type not supported"); GodotRuntime.error('Blob type not supported');
return; return;
} else if (typeof event.data === "string") { } else if (typeof event.data === 'string') {
is_string = 1; is_string = 1;
var enc = new TextEncoder("utf-8"); const enc = new TextEncoder('utf-8');
buffer = new Uint8Array(enc.encode(event.data)); buffer = new Uint8Array(enc.encode(event.data));
} else { } else {
GodotRuntime.error("Unknown message type"); GodotRuntime.error('Unknown message type');
return; return;
} }
var len = buffer.length*buffer.BYTES_PER_ELEMENT; const len = buffer.length * buffer.BYTES_PER_ELEMENT;
var out = GodotRuntime.malloc(len); const out = GodotRuntime.malloc(len);
HEAPU8.set(buffer, out); HEAPU8.set(buffer, out);
p_on_message(out, len, is_string); p_on_message(out, len, is_string);
GodotRuntime.free(out); GodotRuntime.free(out);
} };
}, },
close: function(p_id) { close: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -84,39 +84,39 @@ const GodotRTCDataChannel = {
ref.close(); ref.close();
}, },
get_prop: function(p_id, p_prop, p_def) { get_prop: function (p_id, p_prop, p_def) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
return (ref && ref[p_prop] !== undefined) ? ref[p_prop] : p_def; return (ref && ref[p_prop] !== undefined) ? ref[p_prop] : p_def;
}, },
}, },
godot_js_rtc_datachannel_ready_state_get: function(p_id) { godot_js_rtc_datachannel_ready_state_get: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return 3; // CLOSED return 3; // CLOSED
} }
switch(ref.readyState) { switch (ref.readyState) {
case "connecting": case 'connecting':
return 0; return 0;
case "open": case 'open':
return 1; return 1;
case "closing": case 'closing':
return 2; return 2;
case "closed": case 'closed':
default: default:
return 3; return 3;
} }
}, },
godot_js_rtc_datachannel_send: function(p_id, p_buffer, p_length, p_raw) { godot_js_rtc_datachannel_send: function (p_id, p_buffer, p_length, p_raw) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return 1; return 1;
} }
const bytes_array = new Uint8Array(p_length); const bytes_array = new Uint8Array(p_length);
for (var i = 0; i < p_length; i++) { for (let i = 0; i < p_length; i++) {
bytes_array[i] = GodotRuntime.getHeapValue(p_buffer + i, 'i8'); bytes_array[i] = GodotRuntime.getHeapValue(p_buffer + i, 'i8');
} }
@@ -129,15 +129,15 @@ const GodotRTCDataChannel = {
return 0; return 0;
}, },
godot_js_rtc_datachannel_is_ordered: function(p_id) { godot_js_rtc_datachannel_is_ordered: function (p_id) {
return IDHandler.get_prop(p_id, 'ordered', true); return IDHandler.get_prop(p_id, 'ordered', true);
}, },
godot_js_rtc_datachannel_id_get: function(p_id) { godot_js_rtc_datachannel_id_get: function (p_id) {
return IDHandler.get_prop(p_id, 'id', 65535); return IDHandler.get_prop(p_id, 'id', 65535);
}, },
godot_js_rtc_datachannel_max_packet_lifetime_get: function(p_id) { godot_js_rtc_datachannel_max_packet_lifetime_get: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return 65535; return 65535;
@@ -151,15 +151,15 @@ const GodotRTCDataChannel = {
return 65535; return 65535;
}, },
godot_js_rtc_datachannel_max_retransmits_get: function(p_id) { godot_js_rtc_datachannel_max_retransmits_get: function (p_id) {
return IDHandler.get_prop(p_id, 'maxRetransmits', 65535); return IDHandler.get_prop(p_id, 'maxRetransmits', 65535);
}, },
godot_js_rtc_datachannel_is_negotiated: function(p_id, p_def) { godot_js_rtc_datachannel_is_negotiated: function (p_id, p_def) {
return IDHandler.get_prop(p_id, 'negotiated', 65535); return IDHandler.get_prop(p_id, 'negotiated', 65535);
}, },
godot_js_rtc_datachannel_label_get: function(p_id) { godot_js_rtc_datachannel_label_get: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref || !ref.label) { if (!ref || !ref.label) {
return 0; return 0;
@@ -167,7 +167,7 @@ const GodotRTCDataChannel = {
return GodotRuntime.allocString(ref.label); return GodotRuntime.allocString(ref.label);
}, },
godot_js_rtc_datachannel_protocol_get: function(p_id) { godot_js_rtc_datachannel_protocol_get: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref || !ref.protocol) { if (!ref || !ref.protocol) {
return 0; return 0;
@@ -175,12 +175,12 @@ const GodotRTCDataChannel = {
return GodotRuntime.allocString(ref.protocol); return GodotRuntime.allocString(ref.protocol);
}, },
godot_js_rtc_datachannel_destroy: function(p_id) { godot_js_rtc_datachannel_destroy: function (p_id) {
GodotRTCDataChannel.close(p_id); GodotRTCDataChannel.close(p_id);
IDHandler.remove(p_id); IDHandler.remove(p_id);
}, },
godot_js_rtc_datachannel_connect: function(p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) { godot_js_rtc_datachannel_connect: function (p_id, p_ref, p_on_open, p_on_message, p_on_error, p_on_close) {
const onopen = GodotRuntime.get_func(p_on_open).bind(null, p_ref); const onopen = GodotRuntime.get_func(p_on_open).bind(null, p_ref);
const onmessage = GodotRuntime.get_func(p_on_message).bind(null, p_ref); const onmessage = GodotRuntime.get_func(p_on_message).bind(null, p_ref);
const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_ref); const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_ref);
@@ -188,7 +188,7 @@ const GodotRTCDataChannel = {
GodotRTCDataChannel.connect(p_id, onopen, onmessage, onerror, onclose); GodotRTCDataChannel.connect(p_id, onopen, onmessage, onerror, onclose);
}, },
godot_js_rtc_datachannel_close: function(p_id) { godot_js_rtc_datachannel_close: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -203,52 +203,52 @@ mergeInto(LibraryManager.library, GodotRTCDataChannel);
const GodotRTCPeerConnection = { const GodotRTCPeerConnection = {
$GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'], $GodotRTCPeerConnection__deps: ['$IDHandler', '$GodotRuntime', '$GodotRTCDataChannel'],
$GodotRTCPeerConnection: { $GodotRTCPeerConnection: {
onstatechange: function(p_id, p_conn, callback, event) { onstatechange: function (p_id, p_conn, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
} }
var state = 5; // CLOSED let state = 5; // CLOSED
switch(p_conn.iceConnectionState) { switch (p_conn.iceConnectionState) {
case "new": case 'new':
state = 0; state = 0;
break; break;
case "checking": case 'checking':
state = 1; state = 1;
break; break;
case "connected": case 'connected':
case "completed": case 'completed':
state = 2; state = 2;
break; break;
case "disconnected": case 'disconnected':
state = 3; state = 3;
break; break;
case "failed": case 'failed':
state = 4; state = 4;
break; break;
case "closed": case 'closed':
default: default:
state = 5; state = 5;
break; break;
} }
callback(state); callback(state);
}, },
onicecandidate: function(p_id, callback, event) { onicecandidate: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref || !event.candidate) { if (!ref || !event.candidate) {
return; return;
} }
let c = event.candidate; const c = event.candidate;
let candidate_str = GodotRuntime.allocString(c.candidate); const candidate_str = GodotRuntime.allocString(c.candidate);
let mid_str = GodotRuntime.allocString(c.sdpMid); const mid_str = GodotRuntime.allocString(c.sdpMid);
callback(mid_str, c.sdpMLineIndex, candidate_str); callback(mid_str, c.sdpMLineIndex, candidate_str);
GodotRuntime.free(candidate_str); GodotRuntime.free(candidate_str);
GodotRuntime.free(mid_str); GodotRuntime.free(mid_str);
}, },
ondatachannel: function(p_id, callback, event) { ondatachannel: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -258,19 +258,19 @@ const GodotRTCPeerConnection = {
callback(cid); callback(cid);
}, },
onsession: function(p_id, callback, session) { onsession: function (p_id, callback, session) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
} }
let type_str = GodotRuntime.allocString(session.type); const type_str = GodotRuntime.allocString(session.type);
let sdp_str = GodotRuntime.allocString(session.sdp); const sdp_str = GodotRuntime.allocString(session.sdp);
callback(type_str, sdp_str); callback(type_str, sdp_str);
GodotRuntime.free(type_str); GodotRuntime.free(type_str);
GodotRuntime.free(sdp_str); GodotRuntime.free(sdp_str);
}, },
onerror: function(p_id, callback, error) { onerror: function (p_id, callback, error) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -280,13 +280,13 @@ const GodotRTCPeerConnection = {
}, },
}, },
godot_js_rtc_pc_create: function(p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) { godot_js_rtc_pc_create: function (p_config, p_ref, p_on_state_change, p_on_candidate, p_on_datachannel) {
const onstatechange = GodotRuntime.get_func(p_on_state_change).bind(null, p_ref); const onstatechange = GodotRuntime.get_func(p_on_state_change).bind(null, p_ref);
const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref); const oncandidate = GodotRuntime.get_func(p_on_candidate).bind(null, p_ref);
const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref); const ondatachannel = GodotRuntime.get_func(p_on_datachannel).bind(null, p_ref);
var config = JSON.parse(GodotRuntime.parseString(p_config)); const config = JSON.parse(GodotRuntime.parseString(p_config));
var conn = null; let conn = null;
try { try {
conn = new RTCPeerConnection(config); conn = new RTCPeerConnection(config);
} catch (e) { } catch (e) {
@@ -302,7 +302,7 @@ const GodotRTCPeerConnection = {
return id; return id;
}, },
godot_js_rtc_pc_close: function(p_id) { godot_js_rtc_pc_close: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -310,7 +310,7 @@ const GodotRTCPeerConnection = {
ref.close(); ref.close();
}, },
godot_js_rtc_pc_destroy: function(p_id) { godot_js_rtc_pc_destroy: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -321,21 +321,21 @@ const GodotRTCPeerConnection = {
IDHandler.remove(p_id); IDHandler.remove(p_id);
}, },
godot_js_rtc_pc_offer_create: function(p_id, p_obj, p_on_session, p_on_error) { godot_js_rtc_pc_offer_create: function (p_id, p_obj, p_on_session, p_on_error) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
} }
const onsession = GodotRuntime.get_func(p_on_session).bind(null, p_obj); const onsession = GodotRuntime.get_func(p_on_session).bind(null, p_obj);
const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj); const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
ref.createOffer().then(function(session) { ref.createOffer().then(function (session) {
GodotRTCPeerConnection.onsession(p_id, onsession, session); GodotRTCPeerConnection.onsession(p_id, onsession, session);
}).catch(function(error) { }).catch(function (error) {
GodotRTCPeerConnection.onerror(p_id, onerror, error); GodotRTCPeerConnection.onerror(p_id, onerror, error);
}); });
}, },
godot_js_rtc_pc_local_description_set: function(p_id, p_type, p_sdp, p_obj, p_on_error) { godot_js_rtc_pc_local_description_set: function (p_id, p_type, p_sdp, p_obj, p_on_error) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -345,13 +345,13 @@ const GodotRTCPeerConnection = {
const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj); const onerror = GodotRuntime.get_func(p_on_error).bind(null, p_obj);
ref.setLocalDescription({ ref.setLocalDescription({
'sdp': sdp, 'sdp': sdp,
'type': type 'type': type,
}).catch(function(error) { }).catch(function (error) {
GodotRTCPeerConnection.onerror(p_id, onerror, error); GodotRTCPeerConnection.onerror(p_id, onerror, error);
}); });
}, },
godot_js_rtc_pc_remote_description_set: function(p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) { godot_js_rtc_pc_remote_description_set: function (p_id, p_type, p_sdp, p_obj, p_session_created, p_on_error) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -362,35 +362,35 @@ const GodotRTCPeerConnection = {
const onsession = GodotRuntime.get_func(p_session_created).bind(null, p_obj); const onsession = GodotRuntime.get_func(p_session_created).bind(null, p_obj);
ref.setRemoteDescription({ ref.setRemoteDescription({
'sdp': sdp, 'sdp': sdp,
'type': type 'type': type,
}).then(function() { }).then(function () {
if (type !== 'offer') { if (type !== 'offer') {
return Promise.resolve(); return Promise.resolve();
} }
return ref.createAnswer().then(function(session) { return ref.createAnswer().then(function (session) {
GodotRTCPeerConnection.onsession(p_id, onsession, session); GodotRTCPeerConnection.onsession(p_id, onsession, session);
}); });
}).catch(function(error) { }).catch(function (error) {
GodotRTCPeerConnection.onerror(p_id, onerror, error); GodotRTCPeerConnection.onerror(p_id, onerror, error);
}); });
}, },
godot_js_rtc_pc_ice_candidate_add: function(p_id, p_mid_name, p_mline_idx, p_sdp) { godot_js_rtc_pc_ice_candidate_add: function (p_id, p_mid_name, p_mline_idx, p_sdp) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
} }
var sdpMidName = GodotRuntime.parseString(p_mid_name); const sdpMidName = GodotRuntime.parseString(p_mid_name);
var sdpName = GodotRuntime.parseString(p_sdp); const sdpName = GodotRuntime.parseString(p_sdp);
ref.addIceCandidate(new RTCIceCandidate({ ref.addIceCandidate(new RTCIceCandidate({
"candidate": sdpName, 'candidate': sdpName,
"sdpMid": sdpMidName, 'sdpMid': sdpMidName,
"sdpMlineIndex": p_mline_idx, 'sdpMlineIndex': p_mline_idx,
})); }));
}, },
godot_js_rtc_pc_datachannel_create__deps: ['$GodotRTCDataChannel'], godot_js_rtc_pc_datachannel_create__deps: ['$GodotRTCDataChannel'],
godot_js_rtc_pc_datachannel_create: function(p_id, p_label, p_config) { godot_js_rtc_pc_datachannel_create: function (p_id, p_label, p_config) {
try { try {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
@@ -409,5 +409,5 @@ const GodotRTCPeerConnection = {
}, },
}; };
autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection') autoAddDeps(GodotRTCPeerConnection, '$GodotRTCPeerConnection');
mergeInto(LibraryManager.library, GodotRTCPeerConnection); mergeInto(LibraryManager.library, GodotRTCPeerConnection);

View File

@@ -33,46 +33,46 @@ const GodotWebSocket = {
$GodotWebSocket__deps: ['$IDHandler', '$GodotRuntime'], $GodotWebSocket__deps: ['$IDHandler', '$GodotRuntime'],
$GodotWebSocket: { $GodotWebSocket: {
// Connection opened, report selected protocol // Connection opened, report selected protocol
_onopen: function(p_id, callback, event) { _onopen: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; // Godot object is gone. return; // Godot object is gone.
} }
let c_str = GodotRuntime.allocString(ref.protocol); const c_str = GodotRuntime.allocString(ref.protocol);
callback(c_str); callback(c_str);
GodotRuntime.free(c_str); GodotRuntime.free(c_str);
}, },
// Message received, report content and type (UTF8 vs binary) // Message received, report content and type (UTF8 vs binary)
_onmessage: function(p_id, callback, event) { _onmessage: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; // Godot object is gone. return; // Godot object is gone.
} }
var buffer; let buffer;
var is_string = 0; let is_string = 0;
if (event.data instanceof ArrayBuffer) { if (event.data instanceof ArrayBuffer) {
buffer = new Uint8Array(event.data); buffer = new Uint8Array(event.data);
} else if (event.data instanceof Blob) { } else if (event.data instanceof Blob) {
GodotRuntime.error("Blob type not supported"); GodotRuntime.error('Blob type not supported');
return; return;
} else if (typeof event.data === "string") { } else if (typeof event.data === 'string') {
is_string = 1; is_string = 1;
var enc = new TextEncoder("utf-8"); const enc = new TextEncoder('utf-8');
buffer = new Uint8Array(enc.encode(event.data)); buffer = new Uint8Array(enc.encode(event.data));
} else { } else {
GodotRuntime.error("Unknown message type"); GodotRuntime.error('Unknown message type');
return; return;
} }
var len = buffer.length*buffer.BYTES_PER_ELEMENT; const len = buffer.length * buffer.BYTES_PER_ELEMENT;
var out = GodotRuntime.malloc(len); const out = GodotRuntime.malloc(len);
HEAPU8.set(buffer, out); HEAPU8.set(buffer, out);
callback(out, len, is_string); callback(out, len, is_string);
GodotRuntime.free(out); GodotRuntime.free(out);
}, },
// An error happened, 'onclose' will be called after this. // An error happened, 'onclose' will be called after this.
_onerror: function(p_id, callback, event) { _onerror: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; // Godot object is gone. return; // Godot object is gone.
@@ -81,18 +81,18 @@ const GodotWebSocket = {
}, },
// Connection is closed, this is always fired. Report close code, reason, and clean status. // Connection is closed, this is always fired. Report close code, reason, and clean status.
_onclose: function(p_id, callback, event) { _onclose: function (p_id, callback, event) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; // Godot object is gone. return; // Godot object is gone.
} }
let c_str = GodotRuntime.allocString(event.reason); const c_str = GodotRuntime.allocString(event.reason);
callback(event.code, c_str, event.wasClean ? 1 : 0); callback(event.code, c_str, event.wasClean ? 1 : 0);
GodotRuntime.free(c_str); GodotRuntime.free(c_str);
}, },
// Send a message // Send a message
send: function(p_id, p_data) { send: function (p_id, p_data) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref || ref.readyState !== ref.OPEN) { if (!ref || ref.readyState !== ref.OPEN) {
return 1; // Godot object is gone or socket is not in a ready state. return 1; // Godot object is gone or socket is not in a ready state.
@@ -101,7 +101,7 @@ const GodotWebSocket = {
return 0; return 0;
}, },
create: function(socket, p_on_open, p_on_message, p_on_error, p_on_close) { create: function (socket, p_on_open, p_on_message, p_on_error, p_on_close) {
const id = IDHandler.add(socket); const id = IDHandler.add(socket);
socket.onopen = GodotWebSocket._onopen.bind(null, id, p_on_open); socket.onopen = GodotWebSocket._onopen.bind(null, id, p_on_open);
socket.onmessage = GodotWebSocket._onmessage.bind(null, id, p_on_message); socket.onmessage = GodotWebSocket._onmessage.bind(null, id, p_on_message);
@@ -111,7 +111,7 @@ const GodotWebSocket = {
}, },
// Closes the JavaScript WebSocket (if not already closing) associated to a given C++ object. // Closes the JavaScript WebSocket (if not already closing) associated to a given C++ object.
close: function(p_id, p_code, p_reason) { close: function (p_id, p_code, p_reason) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (ref && ref.readyState < ref.CLOSING) { if (ref && ref.readyState < ref.CLOSING) {
const code = p_code; const code = p_code;
@@ -121,7 +121,7 @@ const GodotWebSocket = {
}, },
// Deletes the reference to a C++ object (closing any connected socket if necessary). // Deletes the reference to a C++ object (closing any connected socket if necessary).
destroy: function(p_id) { destroy: function (p_id) {
const ref = IDHandler.get(p_id); const ref = IDHandler.get(p_id);
if (!ref) { if (!ref) {
return; return;
@@ -135,50 +135,50 @@ const GodotWebSocket = {
}, },
}, },
godot_js_websocket_create: function(p_ref, p_url, p_proto, p_on_open, p_on_message, p_on_error, p_on_close) { godot_js_websocket_create: function (p_ref, p_url, p_proto, p_on_open, p_on_message, p_on_error, p_on_close) {
const on_open = GodotRuntime.get_func(p_on_open).bind(null, p_ref); const on_open = GodotRuntime.get_func(p_on_open).bind(null, p_ref);
const on_message = GodotRuntime.get_func(p_on_message).bind(null, p_ref); const on_message = GodotRuntime.get_func(p_on_message).bind(null, p_ref);
const on_error = GodotRuntime.get_func(p_on_error).bind(null, p_ref); const on_error = GodotRuntime.get_func(p_on_error).bind(null, p_ref);
const on_close = GodotRuntime.get_func(p_on_close).bind(null, p_ref); const on_close = GodotRuntime.get_func(p_on_close).bind(null, p_ref);
const url = GodotRuntime.parseString(p_url); const url = GodotRuntime.parseString(p_url);
const protos = GodotRuntime.parseString(p_proto); const protos = GodotRuntime.parseString(p_proto);
var socket = null; let socket = null;
try { try {
if (protos) { if (protos) {
socket = new WebSocket(url, protos.split(",")); socket = new WebSocket(url, protos.split(','));
} else { } else {
socket = new WebSocket(url); socket = new WebSocket(url);
} }
} catch (e) { } catch (e) {
return 0; return 0;
} }
socket.binaryType = "arraybuffer"; socket.binaryType = 'arraybuffer';
return GodotWebSocket.create(socket, on_open, on_message, on_error, on_close); return GodotWebSocket.create(socket, on_open, on_message, on_error, on_close);
}, },
godot_js_websocket_send: function(p_id, p_buf, p_buf_len, p_raw) { godot_js_websocket_send: function (p_id, p_buf, p_buf_len, p_raw) {
var bytes_array = new Uint8Array(p_buf_len); const bytes_array = new Uint8Array(p_buf_len);
var i = 0; let i = 0;
for(i = 0; i < p_buf_len; i++) { for (i = 0; i < p_buf_len; i++) {
bytes_array[i] = GodotRuntime.getHeapValue(p_buf + i, 'i8'); bytes_array[i] = GodotRuntime.getHeapValue(p_buf + i, 'i8');
} }
var out = bytes_array.buffer; let out = bytes_array.buffer;
if (!p_raw) { if (!p_raw) {
out = new TextDecoder("utf-8").decode(bytes_array); out = new TextDecoder('utf-8').decode(bytes_array);
} }
return GodotWebSocket.send(p_id, out); return GodotWebSocket.send(p_id, out);
}, },
godot_js_websocket_close: function(p_id, p_code, p_reason) { godot_js_websocket_close: function (p_id, p_code, p_reason) {
const code = p_code; const code = p_code;
const reason = GodotRuntime.parseString(p_reason); const reason = GodotRuntime.parseString(p_reason);
GodotWebSocket.close(p_id, code, reason); GodotWebSocket.close(p_id, code, reason);
}, },
godot_js_websocket_destroy: function(p_id) { godot_js_websocket_destroy: function (p_id) {
GodotWebSocket.destroy(p_id); GodotWebSocket.destroy(p_id);
}, },
}; };
autoAddDeps(GodotWebSocket, '$GodotWebSocket') autoAddDeps(GodotWebSocket, '$GodotWebSocket');
mergeInto(LibraryManager.library, GodotWebSocket); mergeInto(LibraryManager.library, GodotWebSocket);

View File

@@ -1,14 +1,14 @@
const Engine = (function() { const Engine = (function () {
var preloader = new Preloader(); const preloader = new Preloader();
var wasmExt = '.wasm'; let wasmExt = '.wasm';
var unloadAfterInit = true; let unloadAfterInit = true;
var loadPath = ''; let loadPath = '';
var loadPromise = null; let loadPromise = null;
var initPromise = null; let initPromise = null;
var stderr = null; let stderr = null;
var stdout = null; let stdout = null;
var progressFunc = null; let progressFunc = null;
function load(basePath) { function load(basePath) {
if (loadPromise == null) { if (loadPromise == null) {
@@ -18,11 +18,11 @@ const Engine = (function() {
requestAnimationFrame(preloader.animateProgress); requestAnimationFrame(preloader.animateProgress);
} }
return loadPromise; return loadPromise;
}; }
function unload() { function unload() {
loadPromise = null; loadPromise = null;
}; }
/** @constructor */ /** @constructor */
function Engine() { // eslint-disable-line no-shadow function Engine() { // eslint-disable-line no-shadow
@@ -34,30 +34,32 @@ const Engine = (function() {
this.onExecute = null; this.onExecute = null;
this.onExit = null; this.onExit = null;
this.persistentPaths = ['/userfs']; this.persistentPaths = ['/userfs'];
}; }
Engine.prototype.init = /** @param {string=} basePath */ function(basePath) { Engine.prototype.init = /** @param {string=} basePath */ function (basePath) {
if (initPromise) { if (initPromise) {
return initPromise; return initPromise;
} }
if (loadPromise == null) { if (loadPromise == null) {
if (!basePath) { if (!basePath) {
initPromise = Promise.reject(new Error("A base path must be provided when calling `init` and the engine is not loaded.")); initPromise = Promise.reject(new Error('A base path must be provided when calling `init` and the engine is not loaded.'));
return initPromise; return initPromise;
} }
load(basePath); load(basePath);
} }
var config = {}; let config = {};
if (typeof stdout === 'function') if (typeof stdout === 'function') {
config.print = stdout; config.print = stdout;
if (typeof stderr === 'function') }
if (typeof stderr === 'function') {
config.printErr = stderr; config.printErr = stderr;
var me = this; }
initPromise = new Promise(function(resolve, reject) { const me = this;
initPromise = new Promise(function (resolve, reject) {
config['locateFile'] = Utils.createLocateRewrite(loadPath); config['locateFile'] = Utils.createLocateRewrite(loadPath);
config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise); config['instantiateWasm'] = Utils.createInstantiatePromise(loadPromise);
Godot(config).then(function(module) { Godot(config).then(function (module) {
module['initFS'](me.persistentPaths).then(function(fs_err) { module['initFS'](me.persistentPaths).then(function (fs_err) {
me.rtenv = module; me.rtenv = module;
if (unloadAfterInit) { if (unloadAfterInit) {
unload(); unload();
@@ -71,19 +73,19 @@ const Engine = (function() {
}; };
/** @type {function(string, string):Object} */ /** @type {function(string, string):Object} */
Engine.prototype.preloadFile = function(file, path) { Engine.prototype.preloadFile = function (file, path) {
return preloader.preload(file, path); return preloader.preload(file, path);
}; };
/** @type {function(...string):Object} */ /** @type {function(...string):Object} */
Engine.prototype.start = function() { Engine.prototype.start = function () {
// Start from arguments. // Start from arguments.
var args = []; const args = [];
for (var i = 0; i < arguments.length; i++) { for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]); args.push(arguments[i]);
} }
var 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'));
} }
@@ -101,18 +103,18 @@ const Engine = (function() {
} }
// Disable right-click context menu. // Disable right-click context menu.
me.canvas.addEventListener('contextmenu', function(ev) { me.canvas.addEventListener('contextmenu', function (ev) {
ev.preventDefault(); ev.preventDefault();
}, false); }, false);
// Until context restoration is implemented warn the user of context loss. // Until context restoration is implemented warn the user of context loss.
me.canvas.addEventListener('webglcontextlost', function(ev) { me.canvas.addEventListener('webglcontextlost', function (ev) {
alert("WebGL context lost, please reload the page"); // eslint-disable-line no-alert alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
ev.preventDefault(); ev.preventDefault();
}, false); }, false);
// Browser locale, or custom one if defined. // Browser locale, or custom one if defined.
var locale = me.customLocale; let locale = me.customLocale;
if (!locale) { if (!locale) {
locale = navigator.languages ? navigator.languages[0] : navigator.language; locale = navigator.languages ? navigator.languages[0] : navigator.language;
locale = locale.split('.')[0]; locale = locale.split('.')[0];
@@ -125,14 +127,14 @@ const Engine = (function() {
'resizeCanvasOnStart': me.resizeCanvasOnStart, 'resizeCanvasOnStart': me.resizeCanvasOnStart,
'canvas': me.canvas, 'canvas': me.canvas,
'locale': locale, 'locale': locale,
'onExecute': function(p_args) { 'onExecute': function (p_args) {
if (me.onExecute) { if (me.onExecute) {
me.onExecute(p_args); me.onExecute(p_args);
return 0; return 0;
} }
return 1; return 1;
}, },
'onExit': function(p_code) { 'onExit': function (p_code) {
me.rtenv['deinitFS'](); me.rtenv['deinitFS']();
if (me.onExit) { if (me.onExit) {
me.onExit(p_code); me.onExit(p_code);
@@ -141,8 +143,8 @@ const Engine = (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
@@ -153,98 +155,101 @@ const Engine = (function() {
}); });
}; };
Engine.prototype.startGame = function(execName, mainPack, extraArgs) { Engine.prototype.startGame = function (execName, mainPack, extraArgs) {
// Start and init with execName as loadPath if not inited. // Start and init with execName as loadPath if not inited.
this.executableName = execName; this.executableName = execName;
var me = this; const me = this;
return Promise.all([ return Promise.all([
this.init(execName), this.init(execName),
this.preloadFile(mainPack, mainPack) this.preloadFile(mainPack, mainPack),
]).then(function() { ]).then(function () {
var args = ['--main-pack', mainPack]; let args = ['--main-pack', mainPack];
if (extraArgs) if (extraArgs) {
args = args.concat(extraArgs); args = args.concat(extraArgs);
}
return me.start.apply(me, args); return me.start.apply(me, args);
}); });
}; };
Engine.prototype.setWebAssemblyFilenameExtension = function(override) { Engine.prototype.setWebAssemblyFilenameExtension = function (override) {
if (String(override).length === 0) { if (String(override).length === 0) {
throw new Error('Invalid WebAssembly filename extension override'); throw new Error('Invalid WebAssembly filename extension override');
} }
wasmExt = String(override); wasmExt = String(override);
}; };
Engine.prototype.setUnloadAfterInit = function(enabled) { Engine.prototype.setUnloadAfterInit = function (enabled) {
unloadAfterInit = enabled; unloadAfterInit = enabled;
}; };
Engine.prototype.setCanvas = function(canvasElem) { Engine.prototype.setCanvas = function (canvasElem) {
this.canvas = canvasElem; this.canvas = canvasElem;
}; };
Engine.prototype.setCanvasResizedOnStart = function(enabled) { Engine.prototype.setCanvasResizedOnStart = function (enabled) {
this.resizeCanvasOnStart = enabled; this.resizeCanvasOnStart = enabled;
}; };
Engine.prototype.setLocale = function(locale) { Engine.prototype.setLocale = function (locale) {
this.customLocale = locale; this.customLocale = locale;
}; };
Engine.prototype.setExecutableName = function(newName) { Engine.prototype.setExecutableName = function (newName) {
this.executableName = newName; this.executableName = newName;
}; };
Engine.prototype.setProgressFunc = function(func) { Engine.prototype.setProgressFunc = function (func) {
progressFunc = func; progressFunc = func;
}; };
Engine.prototype.setStdoutFunc = function(func) { Engine.prototype.setStdoutFunc = function (func) {
var print = function(text) { const print = function (text) {
let msg = text; let msg = text;
if (arguments.length > 1) { if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(" "); msg = Array.prototype.slice.call(arguments).join(' ');
} }
func(msg); func(msg);
}; };
if (this.rtenv) if (this.rtenv) {
this.rtenv.print = print; this.rtenv.print = print;
}
stdout = print; stdout = print;
}; };
Engine.prototype.setStderrFunc = function(func) { Engine.prototype.setStderrFunc = function (func) {
var printErr = function(text) { const printErr = function (text) {
let msg = text let msg = text;
if (arguments.length > 1) { if (arguments.length > 1) {
msg = Array.prototype.slice.call(arguments).join(" "); msg = Array.prototype.slice.call(arguments).join(' ');
} }
func(msg); func(msg);
}; };
if (this.rtenv) if (this.rtenv) {
this.rtenv.printErr = printErr; this.rtenv.printErr = printErr;
}
stderr = printErr; stderr = printErr;
}; };
Engine.prototype.setOnExecute = function(onExecute) { Engine.prototype.setOnExecute = function (onExecute) {
this.onExecute = onExecute; this.onExecute = onExecute;
}; };
Engine.prototype.setOnExit = function(onExit) { Engine.prototype.setOnExit = function (onExit) {
this.onExit = onExit; this.onExit = onExit;
}; };
Engine.prototype.copyToFS = function(path, buffer) { Engine.prototype.copyToFS = function (path, buffer) {
if (this.rtenv == null) { if (this.rtenv == null) {
throw new Error("Engine must be inited before copying files"); throw new Error('Engine must be inited before copying files');
} }
this.rtenv['copyToFS'](path, buffer); this.rtenv['copyToFS'](path, buffer);
}; };
Engine.prototype.setPersistentPaths = function(persistentPaths) { Engine.prototype.setPersistentPaths = function (persistentPaths) {
this.persistentPaths = persistentPaths; this.persistentPaths = persistentPaths;
}; };
Engine.prototype.requestQuit = function() { Engine.prototype.requestQuit = function () {
if (this.rtenv) { if (this.rtenv) {
this.rtenv['request_quit'](); this.rtenv['request_quit']();
} }
@@ -274,5 +279,7 @@ const Engine = (function() {
Engine.prototype['setPersistentPaths'] = Engine.prototype.setPersistentPaths; Engine.prototype['setPersistentPaths'] = Engine.prototype.setPersistentPaths;
Engine.prototype['requestQuit'] = Engine.prototype.requestQuit; Engine.prototype['requestQuit'] = Engine.prototype.requestQuit;
return Engine; return Engine;
})(); }());
if (typeof window !== 'undefined') window['Engine'] = Engine; if (typeof window !== 'undefined') {
window['Engine'] = Engine;
}

View File

@@ -1,37 +1,36 @@
var Preloader = /** @constructor */ function() { // eslint-disable-line no-unused-vars const Preloader = /** @constructor */ function () { // eslint-disable-line no-unused-vars
const loadXHR = function (resolve, reject, file, tracker, attempts) {
const loadXHR = function(resolve, reject, file, tracker, attempts) {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
tracker[file] = { tracker[file] = {
total: 0, total: 0,
loaded: 0, loaded: 0,
final: false, final: false,
}; };
xhr.onerror = function() { xhr.onerror = function () {
if (attempts <= 1) { if (attempts <= 1) {
reject(new Error("Failed loading file '" + file + "'")); reject(new Error(`Failed loading file '${file}'`));
} else { } else {
setTimeout(function () { setTimeout(function () {
loadXHR(resolve, reject, file, tracker, attempts - 1); loadXHR(resolve, reject, file, tracker, attempts - 1);
}, 1000); }, 1000);
} }
}; };
xhr.onabort = function() { xhr.onabort = function () {
tracker[file].final = true; tracker[file].final = true;
reject(new Error("Loading file '" + file + "' was aborted.")); reject(new Error(`Loading file '${file}' was aborted.`));
}; };
xhr.onloadstart = function(ev) { xhr.onloadstart = function (ev) {
tracker[file].total = ev.total; tracker[file].total = ev.total;
tracker[file].loaded = ev.loaded; tracker[file].loaded = ev.loaded;
}; };
xhr.onprogress = function(ev) { xhr.onprogress = function (ev) {
tracker[file].loaded = ev.loaded; tracker[file].loaded = ev.loaded;
tracker[file].total = ev.total; tracker[file].total = ev.total;
}; };
xhr.onload = function() { xhr.onload = function () {
if (xhr.status >= 400) { if (xhr.status >= 400) {
if (xhr.status < 500 || attempts <= 1) { if (xhr.status < 500 || attempts <= 1) {
reject(new Error("Failed loading file '" + file + "': " + xhr.statusText)); reject(new Error(`Failed loading file '${file}': ${xhr.statusText}`));
xhr.abort(); xhr.abort();
} else { } else {
setTimeout(function () { setTimeout(function () {
@@ -56,14 +55,13 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
const lastProgress = { loaded: 0, total: 0 }; const lastProgress = { loaded: 0, total: 0 };
let progressFunc = null; let progressFunc = null;
const animateProgress = function() { const animateProgress = function () {
let loaded = 0;
let total = 0;
let totalIsValid = true;
let progressIsFinal = true;
var loaded = 0; Object.keys(loadingFiles).forEach(function (file) {
var total = 0;
var totalIsValid = true;
var progressIsFinal = true;
Object.keys(loadingFiles).forEach(function(file) {
const stat = loadingFiles[file]; const stat = loadingFiles[file];
if (!stat.final) { if (!stat.final) {
progressIsFinal = false; progressIsFinal = false;
@@ -79,35 +77,36 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
if (loaded !== lastProgress.loaded || total !== lastProgress.total) { if (loaded !== lastProgress.loaded || total !== lastProgress.total) {
lastProgress.loaded = loaded; lastProgress.loaded = loaded;
lastProgress.total = total; lastProgress.total = total;
if (typeof progressFunc === 'function') if (typeof progressFunc === 'function') {
progressFunc(loaded, total); progressFunc(loaded, total);
}
} }
if (!progressIsFinal) if (!progressIsFinal) {
requestAnimationFrame(animateProgress); requestAnimationFrame(animateProgress);
} }
};
this.animateProgress = animateProgress; this.animateProgress = animateProgress;
this.setProgressFunc = function(callback) { this.setProgressFunc = function (callback) {
progressFunc = callback; progressFunc = callback;
} };
this.loadPromise = function (file) {
this.loadPromise = function(file) { return new Promise(function (resolve, reject) {
return new Promise(function(resolve, reject) {
loadXHR(resolve, reject, file, loadingFiles, DOWNLOAD_ATTEMPTS_MAX); loadXHR(resolve, reject, file, loadingFiles, DOWNLOAD_ATTEMPTS_MAX);
}); });
} };
this.preloadedFiles = []; this.preloadedFiles = [];
this.preload = function(pathOrBuffer, destPath) { this.preload = function (pathOrBuffer, destPath) {
let buffer = null; let buffer = null;
if (typeof pathOrBuffer === 'string') { if (typeof pathOrBuffer === 'string') {
var me = this; const me = this;
return this.loadPromise(pathOrBuffer).then(function(xhr) { return this.loadPromise(pathOrBuffer).then(function (xhr) {
me.preloadedFiles.push({ me.preloadedFiles.push({
path: destPath || pathOrBuffer, path: destPath || pathOrBuffer,
buffer: xhr.response buffer: xhr.response,
}); });
return Promise.resolve(); return Promise.resolve();
}); });
@@ -119,11 +118,10 @@ var Preloader = /** @constructor */ function() { // eslint-disable-line no-unuse
if (buffer) { if (buffer) {
this.preloadedFiles.push({ this.preloadedFiles.push({
path: destPath, path: destPath,
buffer: pathOrBuffer buffer: pathOrBuffer,
}); });
return Promise.resolve(); return Promise.resolve();
} else {
return Promise.reject(new Error("Invalid object for preloading"));
} }
return Promise.reject(new Error('Invalid object for preloading'));
}; };
}; };

View File

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

View File

@@ -105,7 +105,7 @@ class GodotProcessor extends AudioWorkletProcessor {
} }
parse_message(p_cmd, p_data) { parse_message(p_cmd, p_data) {
if (p_cmd === "start" && p_data) { if (p_cmd === 'start' && p_data) {
const state = p_data[0]; const state = p_data[0];
let idx = 0; let idx = 0;
this.lock = state.subarray(idx, ++idx); this.lock = state.subarray(idx, ++idx);
@@ -114,7 +114,7 @@ class GodotProcessor extends AudioWorkletProcessor {
const avail_out = state.subarray(idx, ++idx); const avail_out = state.subarray(idx, ++idx);
this.input = new RingBuffer(p_data[1], avail_in); this.input = new RingBuffer(p_data[1], avail_in);
this.output = new RingBuffer(p_data[2], avail_out); this.output = new RingBuffer(p_data[2], avail_out);
} else if (p_cmd === "stop") { } else if (p_cmd === 'stop') {
this.runing = false; this.runing = false;
this.output = null; this.output = null;
this.input = null; this.input = null;
@@ -143,7 +143,7 @@ class GodotProcessor extends AudioWorkletProcessor {
GodotProcessor.write_input(this.input_buffer, input); GodotProcessor.write_input(this.input_buffer, input);
this.input.write(this.input_buffer); this.input.write(this.input_buffer);
} else { } else {
this.port.postMessage("Input buffer is full! Skipping input frame."); this.port.postMessage('Input buffer is full! Skipping input frame.');
} }
} }
const process_output = GodotProcessor.array_has_data(outputs); const process_output = GodotProcessor.array_has_data(outputs);
@@ -157,7 +157,7 @@ class GodotProcessor extends AudioWorkletProcessor {
this.output.read(this.output_buffer); this.output.read(this.output_buffer);
GodotProcessor.write_output(output, this.output_buffer); GodotProcessor.write_output(output, this.output_buffer);
} else { } else {
this.port.postMessage("Output buffer has not enough frames! Skipping output frame."); this.port.postMessage('Output buffer has not enough frames! Skipping output frame.');
} }
} }
this.process_notify(); this.process_notify();

View File

@@ -36,32 +36,32 @@ const GodotAudio = {
driver: null, driver: null,
interval: 0, interval: 0,
init: function(mix_rate, latency, onstatechange, onlatencyupdate) { init: function (mix_rate, latency, onstatechange, onlatencyupdate) {
const ctx = new (window.AudioContext || window.webkitAudioContext)({ const ctx = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: mix_rate, sampleRate: mix_rate,
// latencyHint: latency / 1000 // Do not specify, leave 'interactive' for good performance. // latencyHint: latency / 1000 // Do not specify, leave 'interactive' for good performance.
}); });
GodotAudio.ctx = ctx; GodotAudio.ctx = ctx;
ctx.onstatechange = function() { ctx.onstatechange = function () {
let state = 0; let state = 0;
switch (ctx.state) { switch (ctx.state) {
case 'suspended': case 'suspended':
state = 0; state = 0;
break; break;
case 'running': case 'running':
state = 1; state = 1;
break; break;
case 'closed': case 'closed':
state = 2; state = 2;
break; break;
// no default // no default
} }
onstatechange(state); onstatechange(state);
} };
ctx.onstatechange(); // Immeditately notify state. ctx.onstatechange(); // Immeditately notify state.
// Update computed latency // Update computed latency
GodotAudio.interval = setInterval(function() { GodotAudio.interval = setInterval(function () {
let computed_latency = 0; let computed_latency = 0;
if (ctx.baseLatency) { if (ctx.baseLatency) {
computed_latency += GodotAudio.ctx.baseLatency; computed_latency += GodotAudio.ctx.baseLatency;
@@ -75,29 +75,33 @@ const GodotAudio = {
return ctx.destination.channelCount; return ctx.destination.channelCount;
}, },
create_input: function(callback) { create_input: function (callback) {
if (GodotAudio.input) { if (GodotAudio.input) {
return; // Already started. return; // Already started.
} }
function gotMediaInput(stream) { function gotMediaInput(stream) {
GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream); GodotAudio.input = GodotAudio.ctx.createMediaStreamSource(stream);
callback(GodotAudio.input) callback(GodotAudio.input);
} }
if (navigator.mediaDevices.getUserMedia) { if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ navigator.mediaDevices.getUserMedia({
"audio": true 'audio': true,
}).then(gotMediaInput, function(e) { GodotRuntime.print(e) }); }).then(gotMediaInput, function (e) {
GodotRuntime.print(e);
});
} else { } else {
if (!navigator.getUserMedia) { if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
} }
navigator.getUserMedia({ navigator.getUserMedia({
"audio": true 'audio': true,
}, gotMediaInput, function(e) { GodotRuntime.print(e) }); }, gotMediaInput, function (e) {
GodotRuntime.print(e);
});
} }
}, },
close_async: function(resolve, reject) { close_async: function (resolve, reject) {
const ctx = GodotAudio.ctx; const ctx = GodotAudio.ctx;
GodotAudio.ctx = null; GodotAudio.ctx = null;
// Audio was not initialized. // Audio was not initialized.
@@ -120,14 +124,14 @@ const GodotAudio = {
if (GodotAudio.driver) { if (GodotAudio.driver) {
closed = GodotAudio.driver.close(); closed = GodotAudio.driver.close();
} }
closed.then(function() { closed.then(function () {
return ctx.close(); return ctx.close();
}).then(function() { }).then(function () {
ctx.onstatechange = null; ctx.onstatechange = null;
resolve(); resolve();
}).catch(function(e) { }).catch(function (e) {
ctx.onstatechange = null; ctx.onstatechange = null;
GodotRuntime.error("Error closing AudioContext", e); GodotRuntime.error('Error closing AudioContext', e);
resolve(); resolve();
}); });
}, },
@@ -141,30 +145,30 @@ const GodotAudio = {
return 1; return 1;
}, },
godot_audio_init: function(p_mix_rate, p_latency, p_state_change, p_latency_update) { godot_audio_init: function (p_mix_rate, p_latency, p_state_change, p_latency_update) {
const statechange = GodotRuntime.get_func(p_state_change); const statechange = GodotRuntime.get_func(p_state_change);
const latencyupdate = GodotRuntime.get_func(p_latency_update); const latencyupdate = GodotRuntime.get_func(p_latency_update);
return GodotAudio.init(p_mix_rate, p_latency, statechange, latencyupdate); return GodotAudio.init(p_mix_rate, p_latency, statechange, latencyupdate);
}, },
godot_audio_resume: function() { godot_audio_resume: function () {
if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') { if (GodotAudio.ctx && GodotAudio.ctx.state !== 'running') {
GodotAudio.ctx.resume(); GodotAudio.ctx.resume();
} }
}, },
godot_audio_capture_start__proxy: 'sync', godot_audio_capture_start__proxy: 'sync',
godot_audio_capture_start: function() { godot_audio_capture_start: function () {
if (GodotAudio.input) { if (GodotAudio.input) {
return; // Already started. return; // Already started.
} }
GodotAudio.create_input(function(input) { GodotAudio.create_input(function (input) {
input.connect(GodotAudio.driver.get_node()); input.connect(GodotAudio.driver.get_node());
}); });
}, },
godot_audio_capture_stop__proxy: 'sync', godot_audio_capture_stop__proxy: 'sync',
godot_audio_capture_stop: function() { godot_audio_capture_stop: function () {
if (GodotAudio.input) { if (GodotAudio.input) {
const tracks = GodotAudio.input['mediaStream']['getTracks'](); const tracks = GodotAudio.input['mediaStream']['getTracks']();
for (let i = 0; i < tracks.length; i++) { for (let i = 0; i < tracks.length; i++) {
@@ -176,7 +180,7 @@ const GodotAudio = {
}, },
}; };
autoAddDeps(GodotAudio, "$GodotAudio"); autoAddDeps(GodotAudio, '$GodotAudio');
mergeInto(LibraryManager.library, GodotAudio); mergeInto(LibraryManager.library, GodotAudio);
/** /**
@@ -188,42 +192,42 @@ const GodotAudioWorklet = {
promise: null, promise: null,
worklet: null, worklet: null,
create: function(channels) { create: function (channels) {
const path = GodotConfig.locate_file('godot.audio.worklet.js'); const path = GodotConfig.locate_file('godot.audio.worklet.js');
GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function() { GodotAudioWorklet.promise = GodotAudio.ctx.audioWorklet.addModule(path).then(function () {
GodotAudioWorklet.worklet = new AudioWorkletNode( GodotAudioWorklet.worklet = new AudioWorkletNode(
GodotAudio.ctx, GodotAudio.ctx,
'godot-processor', 'godot-processor',
{ {
'outputChannelCount': [channels] 'outputChannelCount': [channels],
} },
); );
return Promise.resolve(); return Promise.resolve();
}); });
GodotAudio.driver = GodotAudioWorklet; GodotAudio.driver = GodotAudioWorklet;
}, },
start: function(in_buf, out_buf, state) { start: function (in_buf, out_buf, state) {
GodotAudioWorklet.promise.then(function() { GodotAudioWorklet.promise.then(function () {
const node = GodotAudioWorklet.worklet; const node = GodotAudioWorklet.worklet;
node.connect(GodotAudio.ctx.destination); node.connect(GodotAudio.ctx.destination);
node.port.postMessage({ node.port.postMessage({
'cmd': 'start', 'cmd': 'start',
'data': [state, in_buf, out_buf], 'data': [state, in_buf, out_buf],
}); });
node.port.onmessage = function(event) { node.port.onmessage = function (event) {
GodotRuntime.error(event.data); GodotRuntime.error(event.data);
}; };
}); });
}, },
get_node: function() { get_node: function () {
return GodotAudioWorklet.worklet; return GodotAudioWorklet.worklet;
}, },
close: function() { close: function () {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
GodotAudioWorklet.promise.then(function() { GodotAudioWorklet.promise.then(function () {
GodotAudioWorklet.worklet.port.postMessage({ GodotAudioWorklet.worklet.port.postMessage({
'cmd': 'stop', 'cmd': 'stop',
'data': null, 'data': null,
@@ -237,32 +241,32 @@ const GodotAudioWorklet = {
}, },
}, },
godot_audio_worklet_create: function(channels) { godot_audio_worklet_create: function (channels) {
GodotAudioWorklet.create(channels); GodotAudioWorklet.create(channels);
}, },
godot_audio_worklet_start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) { godot_audio_worklet_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_state) {
const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size); const out_buffer = GodotRuntime.heapSub(HEAPF32, p_out_buf, p_out_size);
const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size); const in_buffer = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
const state = GodotRuntime.heapSub(HEAP32, p_state, 4); const state = GodotRuntime.heapSub(HEAP32, p_state, 4);
GodotAudioWorklet.start(in_buffer, out_buffer, state); GodotAudioWorklet.start(in_buffer, out_buffer, state);
}, },
godot_audio_worklet_state_wait: function(p_state, p_idx, p_expected, p_timeout) { godot_audio_worklet_state_wait: function (p_state, p_idx, p_expected, p_timeout) {
Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout); Atomics.wait(HEAP32, (p_state >> 2) + p_idx, p_expected, p_timeout);
return Atomics.load(HEAP32, (p_state >> 2) + p_idx); return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
}, },
godot_audio_worklet_state_add: function(p_state, p_idx, p_value) { godot_audio_worklet_state_add: function (p_state, p_idx, p_value) {
return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value); return Atomics.add(HEAP32, (p_state >> 2) + p_idx, p_value);
}, },
godot_audio_worklet_state_get: function(p_state, p_idx) { godot_audio_worklet_state_get: function (p_state, p_idx) {
return Atomics.load(HEAP32, (p_state >> 2) + p_idx); return Atomics.load(HEAP32, (p_state >> 2) + p_idx);
}, },
}; };
autoAddDeps(GodotAudioWorklet, "$GodotAudioWorklet"); autoAddDeps(GodotAudioWorklet, '$GodotAudioWorklet');
mergeInto(LibraryManager.library, GodotAudioWorklet); mergeInto(LibraryManager.library, GodotAudioWorklet);
/* /*
@@ -273,14 +277,14 @@ const GodotAudioScript = {
$GodotAudioScript: { $GodotAudioScript: {
script: null, script: null,
create: function(buffer_length, channel_count) { create: function (buffer_length, channel_count) {
GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count); GodotAudioScript.script = GodotAudio.ctx.createScriptProcessor(buffer_length, 2, channel_count);
GodotAudio.driver = GodotAudioScript; GodotAudio.driver = GodotAudioScript;
return GodotAudioScript.script.bufferSize; return GodotAudioScript.script.bufferSize;
}, },
start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) { start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess) {
GodotAudioScript.script.onaudioprocess = function(event) { GodotAudioScript.script.onaudioprocess = function (event) {
// Read input // Read input
const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size); const inb = GodotRuntime.heapSub(HEAPF32, p_in_buf, p_in_size);
const input = event.inputBuffer; const input = event.inputBuffer;
@@ -312,12 +316,12 @@ const GodotAudioScript = {
GodotAudioScript.script.connect(GodotAudio.ctx.destination); GodotAudioScript.script.connect(GodotAudio.ctx.destination);
}, },
get_node: function() { get_node: function () {
return GodotAudioScript.script; return GodotAudioScript.script;
}, },
close: function() { close: function () {
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
GodotAudioScript.script.disconnect(); GodotAudioScript.script.disconnect();
GodotAudioScript.script.onaudioprocess = null; GodotAudioScript.script.onaudioprocess = null;
GodotAudioScript.script = null; GodotAudioScript.script = null;
@@ -326,15 +330,15 @@ const GodotAudioScript = {
}, },
}, },
godot_audio_script_create: function(buffer_length, channel_count) { godot_audio_script_create: function (buffer_length, channel_count) {
return GodotAudioScript.create(buffer_length, channel_count); return GodotAudioScript.create(buffer_length, channel_count);
}, },
godot_audio_script_start: function(p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) { godot_audio_script_start: function (p_in_buf, p_in_size, p_out_buf, p_out_size, p_cb) {
const onprocess = GodotRuntime.get_func(p_cb); const onprocess = GodotRuntime.get_func(p_cb);
GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess); GodotAudioScript.start(p_in_buf, p_in_size, p_out_buf, p_out_size, onprocess);
}, },
}; };
autoAddDeps(GodotAudioScript, "$GodotAudioScript"); autoAddDeps(GodotAudioScript, '$GodotAudioScript');
mergeInto(LibraryManager.library, GodotAudioScript); mergeInto(LibraryManager.library, GodotAudioScript);

View File

@@ -38,13 +38,13 @@ const GodotDisplayListeners = {
$GodotDisplayListeners: { $GodotDisplayListeners: {
handlers: [], handlers: [],
has: function(target, event, method, capture) { has: function (target, event, method, capture) {
return GodotDisplayListeners.handlers.findIndex(function(e) { return GodotDisplayListeners.handlers.findIndex(function (e) {
return e.target === target && e.event === event && e.method === method && e.capture === capture; return e.target === target && e.event === event && e.method === method && e.capture === capture;
}) !== -1; }) !== -1;
}, },
add: function(target, event, method, capture) { add: function (target, event, method, capture) {
if (GodotDisplayListeners.has(target, event, method, capture)) { if (GodotDisplayListeners.has(target, event, method, capture)) {
return; return;
} }
@@ -53,13 +53,13 @@ const GodotDisplayListeners = {
this.event = p_event; this.event = p_event;
this.method = p_method; this.method = p_method;
this.capture = p_capture; this.capture = p_capture;
}; }
GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture)); GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture));
target.addEventListener(event, method, capture); target.addEventListener(event, method, capture);
}, },
clear: function() { clear: function () {
GodotDisplayListeners.handlers.forEach(function(h) { GodotDisplayListeners.handlers.forEach(function (h) {
h.target.removeEventListener(h.event, h.method, h.capture); h.target.removeEventListener(h.event, h.method, h.capture);
}); });
GodotDisplayListeners.handlers.length = 0; GodotDisplayListeners.handlers.length = 0;
@@ -84,20 +84,20 @@ const GodotDisplayDragDrop = {
promises: [], promises: [],
pending_files: [], pending_files: [],
add_entry: function(entry) { add_entry: function (entry) {
if (entry.isDirectory) { if (entry.isDirectory) {
GodotDisplayDragDrop.add_dir(entry); GodotDisplayDragDrop.add_dir(entry);
} else if (entry.isFile) { } else if (entry.isFile) {
GodotDisplayDragDrop.add_file(entry); GodotDisplayDragDrop.add_file(entry);
} else { } else {
GodotRuntime.error("Unrecognized entry...", entry); GodotRuntime.error('Unrecognized entry...', entry);
} }
}, },
add_dir: function(entry) { add_dir: function (entry) {
GodotDisplayDragDrop.promises.push(new Promise(function(resolve, reject) { GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
const reader = entry.createReader(); const reader = entry.createReader();
reader.readEntries(function(entries) { reader.readEntries(function (entries) {
for (let i = 0; i < entries.length; i++) { for (let i = 0; i < entries.length; i++) {
GodotDisplayDragDrop.add_entry(entries[i]); GodotDisplayDragDrop.add_entry(entries[i]);
} }
@@ -106,58 +106,58 @@ const GodotDisplayDragDrop = {
})); }));
}, },
add_file: function(entry) { add_file: function (entry) {
GodotDisplayDragDrop.promises.push(new Promise(function(resolve, reject) { GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
entry.file(function(file) { entry.file(function (file) {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = function() { reader.onload = function () {
const f = { const f = {
"path": file.relativePath || file.webkitRelativePath, 'path': file.relativePath || file.webkitRelativePath,
"name": file.name, 'name': file.name,
"type": file.type, 'type': file.type,
"size": file.size, 'size': file.size,
"data": reader.result 'data': reader.result,
}; };
if (!f['path']) { if (!f['path']) {
f['path'] = f['name']; f['path'] = f['name'];
} }
GodotDisplayDragDrop.pending_files.push(f); GodotDisplayDragDrop.pending_files.push(f);
resolve() resolve();
}; };
reader.onerror = function() { reader.onerror = function () {
GodotRuntime.print("Error reading file"); GodotRuntime.print('Error reading file');
reject(); reject();
} };
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(file);
}, function(err) { }, function (err) {
GodotRuntime.print("Error!"); GodotRuntime.print('Error!');
reject(); reject();
}); });
})); }));
}, },
process: function(resolve, reject) { process: function (resolve, reject) {
if (GodotDisplayDragDrop.promises.length === 0) { if (GodotDisplayDragDrop.promises.length === 0) {
resolve(); resolve();
return; return;
} }
GodotDisplayDragDrop.promises.pop().then(function() { GodotDisplayDragDrop.promises.pop().then(function () {
setTimeout(function() { setTimeout(function () {
GodotDisplayDragDrop.process(resolve, reject); GodotDisplayDragDrop.process(resolve, reject);
}, 0); }, 0);
}); });
}, },
_process_event: function(ev, callback) { _process_event: function (ev, callback) {
ev.preventDefault(); ev.preventDefault();
if (ev.dataTransfer.items) { if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s) // Use DataTransferItemList interface to access the file(s)
for (let i = 0; i < ev.dataTransfer.items.length; i++) { for (let i = 0; i < ev.dataTransfer.items.length; i++) {
const item = ev.dataTransfer.items[i]; const item = ev.dataTransfer.items[i];
let entry = null; let entry = null;
if ("getAsEntry" in item) { if ('getAsEntry' in item) {
entry = item.getAsEntry(); entry = item.getAsEntry();
} else if ("webkitGetAsEntry" in item) { } else if ('webkitGetAsEntry' in item) {
entry = item.webkitGetAsEntry(); entry = item.webkitGetAsEntry();
} }
if (entry) { if (entry) {
@@ -165,24 +165,24 @@ const GodotDisplayDragDrop = {
} }
} }
} else { } else {
GodotRuntime.error("File upload not supported"); GodotRuntime.error('File upload not supported');
} }
new Promise(GodotDisplayDragDrop.process).then(function() { new Promise(GodotDisplayDragDrop.process).then(function () {
const DROP = "/tmp/drop-" + parseInt(Math.random() * (1 << 30), 10) + "/"; const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
const drops = []; const drops = [];
const files = []; const files = [];
FS.mkdir(DROP); FS.mkdir(DROP);
GodotDisplayDragDrop.pending_files.forEach((elem) => { GodotDisplayDragDrop.pending_files.forEach((elem) => {
const path = elem['path']; const path = elem['path'];
GodotFS.copy_to_fs(DROP + path, elem['data']); GodotFS.copy_to_fs(DROP + path, elem['data']);
let idx = path.indexOf("/"); let idx = path.indexOf('/');
if (idx === -1) { if (idx === -1) {
// Root file // Root file
drops.push(DROP + path); drops.push(DROP + path);
} else { } else {
// Subdir // Subdir
const sub = path.substr(0, idx); const sub = path.substr(0, idx);
idx = sub.indexOf("/"); idx = sub.indexOf('/');
if (idx < 0 && drops.indexOf(DROP + sub) === -1) { if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
drops.push(DROP + sub); drops.push(DROP + sub);
} }
@@ -192,37 +192,38 @@ const GodotDisplayDragDrop = {
GodotDisplayDragDrop.promises = []; GodotDisplayDragDrop.promises = [];
GodotDisplayDragDrop.pending_files = []; GodotDisplayDragDrop.pending_files = [];
callback(drops); callback(drops);
const dirs = [DROP.substr(0, DROP.length -1)]; const dirs = [DROP.substr(0, DROP.length - 1)];
// Remove temporary files // Remove temporary files
files.forEach(function (file) { files.forEach(function (file) {
FS.unlink(file); FS.unlink(file);
let dir = file.replace(DROP, ""); let dir = file.replace(DROP, '');
let idx = dir.lastIndexOf("/"); let idx = dir.lastIndexOf('/');
while (idx > 0) { while (idx > 0) {
dir = dir.substr(0, idx); dir = dir.substr(0, idx);
if (dirs.indexOf(DROP + dir) === -1) { if (dirs.indexOf(DROP + dir) === -1) {
dirs.push(DROP + dir); dirs.push(DROP + dir);
} }
idx = dir.lastIndexOf("/"); idx = dir.lastIndexOf('/');
} }
}); });
// Remove dirs. // Remove dirs.
dirs.sort(function(a, b) { dirs.sort(function (a, b) {
const al = (a.match(/\//g) || []).length; const al = (a.match(/\//g) || []).length;
const bl = (b.match(/\//g) || []).length; const bl = (b.match(/\//g) || []).length;
if (al > bl) if (al > bl) {
return -1; return -1;
else if (al < bl) } else if (al < bl) {
return 1; return 1;
}
return 0; return 0;
}).forEach(function(dir) { }).forEach(function (dir) {
FS.rmdir(dir); FS.rmdir(dir);
}); });
}); });
}, },
handler: function(callback) { handler: function (callback) {
return function(ev) { return function (ev) {
GodotDisplayDragDrop._process_event(ev, callback); GodotDisplayDragDrop._process_event(ev, callback);
}; };
}, },
@@ -241,25 +242,25 @@ const GodotDisplayCursor = {
shape: 'auto', shape: 'auto',
visible: true, visible: true,
cursors: {}, cursors: {},
set_style: function(style) { set_style: function (style) {
GodotConfig.canvas.style.cursor = style; GodotConfig.canvas.style.cursor = style;
}, },
set_shape: function(shape) { set_shape: function (shape) {
GodotDisplayCursor.shape = shape; GodotDisplayCursor.shape = shape;
let css = shape; let css = shape;
if (shape in GodotDisplayCursor.cursors) { if (shape in GodotDisplayCursor.cursors) {
const c = GodotDisplayCursor.cursors[shape]; const c = GodotDisplayCursor.cursors[shape];
css = 'url("' + c.url + '") ' + c.x + ' ' + c.y + ', auto'; css = `url("${c.url}") ${c.x} ${c.y}, auto`;
} }
if (GodotDisplayCursor.visible) { if (GodotDisplayCursor.visible) {
GodotDisplayCursor.set_style(css); GodotDisplayCursor.set_style(css);
} }
}, },
clear: function() { clear: function () {
GodotDisplayCursor.set_style(''); GodotDisplayCursor.set_style('');
GodotDisplayCursor.shape = 'auto'; GodotDisplayCursor.shape = 'auto';
GodotDisplayCursor.visible = true; GodotDisplayCursor.visible = true;
Object.keys(GodotDisplayCursor.cursors).forEach(function(key) { Object.keys(GodotDisplayCursor.cursors).forEach(function (key) {
URL.revokeObjectURL(GodotDisplayCursor.cursors[key]); URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);
delete GodotDisplayCursor.cursors[key]; delete GodotDisplayCursor.cursors[key];
}); });
@@ -279,35 +280,35 @@ const GodotDisplay = {
window_icon: '', window_icon: '',
}, },
godot_js_display_is_swap_ok_cancel: function() { godot_js_display_is_swap_ok_cancel: function () {
const win = (['Windows', 'Win64', 'Win32', 'WinCE']); const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
const plat = navigator.platform || ""; const plat = navigator.platform || '';
if (win.indexOf(plat) !== -1) { if (win.indexOf(plat) !== -1) {
return 1; return 1;
} }
return 0; return 0;
}, },
godot_js_display_alert: function(p_text) { godot_js_display_alert: function (p_text) {
window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
}, },
godot_js_display_pixel_ratio_get: function() { godot_js_display_pixel_ratio_get: function () {
return window.devicePixelRatio || 1; return window.devicePixelRatio || 1;
}, },
/* /*
* Canvas * Canvas
*/ */
godot_js_display_canvas_focus: function() { godot_js_display_canvas_focus: function () {
GodotConfig.canvas.focus(); GodotConfig.canvas.focus();
}, },
godot_js_display_canvas_is_focused: function() { godot_js_display_canvas_is_focused: function () {
return document.activeElement === GodotConfig.canvas; return document.activeElement === GodotConfig.canvas;
}, },
godot_js_display_canvas_bounding_rect_position_get: function(r_x, r_y) { godot_js_display_canvas_bounding_rect_position_get: function (r_x, r_y) {
const brect = GodotConfig.canvas.getBoundingClientRect(); const brect = GodotConfig.canvas.getBoundingClientRect();
GodotRuntime.setHeapValue(r_x, brect.x, 'i32'); GodotRuntime.setHeapValue(r_x, brect.x, 'i32');
GodotRuntime.setHeapValue(r_y, brect.y, 'i32'); GodotRuntime.setHeapValue(r_y, brect.y, 'i32');
@@ -316,26 +317,26 @@ const GodotDisplay = {
/* /*
* Touchscreen * Touchscreen
*/ */
godot_js_display_touchscreen_is_available: function() { godot_js_display_touchscreen_is_available: function () {
return 'ontouchstart' in window; return 'ontouchstart' in window;
}, },
/* /*
* Clipboard * Clipboard
*/ */
godot_js_display_clipboard_set: function(p_text) { godot_js_display_clipboard_set: function (p_text) {
const text = GodotRuntime.parseString(p_text); const text = GodotRuntime.parseString(p_text);
if (!navigator.clipboard || !navigator.clipboard.writeText) { if (!navigator.clipboard || !navigator.clipboard.writeText) {
return 1; return 1;
} }
navigator.clipboard.writeText(text).catch(function(e) { navigator.clipboard.writeText(text).catch(function (e) {
// Setting OS clipboard is only possible from an input callback. // Setting OS clipboard is only possible from an input callback.
GodotRuntime.error("Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:", e); GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
}); });
return 0; return 0;
}, },
godot_js_display_clipboard_get: function(callback) { godot_js_display_clipboard_get: function (callback) {
const func = GodotRuntime.get_func(callback); const func = GodotRuntime.get_func(callback);
try { try {
navigator.clipboard.readText().then(function (result) { navigator.clipboard.readText().then(function (result) {
@@ -353,19 +354,19 @@ const GodotDisplay = {
/* /*
* Window * Window
*/ */
godot_js_display_window_request_fullscreen: function() { godot_js_display_window_request_fullscreen: function () {
const canvas = GodotConfig.canvas; const canvas = GodotConfig.canvas;
(canvas.requestFullscreen || canvas.msRequestFullscreen || (canvas.requestFullscreen || canvas.msRequestFullscreen
canvas.mozRequestFullScreen || canvas.mozRequestFullscreen || || canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
canvas.webkitRequestFullscreen || canvas.webkitRequestFullscreen
).call(canvas); ).call(canvas);
}, },
godot_js_display_window_title_set: function(p_data) { godot_js_display_window_title_set: function (p_data) {
document.title = GodotRuntime.parseString(p_data); document.title = GodotRuntime.parseString(p_data);
}, },
godot_js_display_window_icon_set: function(p_ptr, p_len) { godot_js_display_window_icon_set: function (p_ptr, p_len) {
let link = document.getElementById('-gd-engine-icon'); let link = document.getElementById('-gd-engine-icon');
if (link === null) { if (link === null) {
link = document.createElement('link'); link = document.createElement('link');
@@ -374,7 +375,7 @@ const GodotDisplay = {
document.head.appendChild(link); document.head.appendChild(link);
} }
const old_icon = GodotDisplay.window_icon; const old_icon = GodotDisplay.window_icon;
const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: "image/png" }); const png = new Blob([GodotRuntime.heapCopy(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
GodotDisplay.window_icon = URL.createObjectURL(png); GodotDisplay.window_icon = URL.createObjectURL(png);
link.href = GodotDisplay.window_icon; link.href = GodotDisplay.window_icon;
if (old_icon) { if (old_icon) {
@@ -385,7 +386,7 @@ const GodotDisplay = {
/* /*
* Cursor * Cursor
*/ */
godot_js_display_cursor_set_visible: function(p_visible) { godot_js_display_cursor_set_visible: function (p_visible) {
const visible = p_visible !== 0; const visible = p_visible !== 0;
if (visible === GodotDisplayCursor.visible) { if (visible === GodotDisplayCursor.visible) {
return; return;
@@ -398,15 +399,15 @@ const GodotDisplay = {
} }
}, },
godot_js_display_cursor_is_hidden: function() { godot_js_display_cursor_is_hidden: function () {
return !GodotDisplayCursor.visible; return !GodotDisplayCursor.visible;
}, },
godot_js_display_cursor_set_shape: function(p_string) { godot_js_display_cursor_set_shape: function (p_string) {
GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string)); GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string));
}, },
godot_js_display_cursor_set_custom_shape: function(p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) { godot_js_display_cursor_set_custom_shape: function (p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) {
const shape = GodotRuntime.parseString(p_shape); const shape = GodotRuntime.parseString(p_shape);
const old_shape = GodotDisplayCursor.cursors[shape]; const old_shape = GodotDisplayCursor.cursors[shape];
if (p_len > 0) { if (p_len > 0) {
@@ -431,20 +432,20 @@ const GodotDisplay = {
/* /*
* Listeners * Listeners
*/ */
godot_js_display_notification_cb: function(callback, p_enter, p_exit, p_in, p_out) { godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) {
const canvas = GodotConfig.canvas; const canvas = GodotConfig.canvas;
const func = GodotRuntime.get_func(callback); const func = GodotRuntime.get_func(callback);
const notif = [p_enter, p_exit, p_in, p_out]; const notif = [p_enter, p_exit, p_in, p_out];
['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function(evt_name, idx) { ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) {
GodotDisplayListeners.add(canvas, evt_name, function() { GodotDisplayListeners.add(canvas, evt_name, function () {
func.bind(null, notif[idx]); func.bind(null, notif[idx]);
}, true); }, true);
}); });
}, },
godot_js_display_paste_cb: function(callback) { godot_js_display_paste_cb: function (callback) {
const func = GodotRuntime.get_func(callback); const func = GodotRuntime.get_func(callback);
GodotDisplayListeners.add(window, 'paste', function(evt) { GodotDisplayListeners.add(window, 'paste', function (evt) {
const text = evt.clipboardData.getData('text'); const text = evt.clipboardData.getData('text');
const ptr = GodotRuntime.allocString(text); const ptr = GodotRuntime.allocString(text);
func(ptr); func(ptr);
@@ -452,9 +453,9 @@ const GodotDisplay = {
}, false); }, false);
}, },
godot_js_display_drop_files_cb: function(callback) { godot_js_display_drop_files_cb: function (callback) {
const func = GodotRuntime.get_func(callback) const func = GodotRuntime.get_func(callback);
const dropFiles = function(files) { const dropFiles = function (files) {
const args = files || []; const args = files || [];
if (!args.length) { if (!args.length) {
return; return;
@@ -465,7 +466,7 @@ const GodotDisplay = {
GodotRuntime.freeStringArray(argv, argc); GodotRuntime.freeStringArray(argv, argc);
}; };
const canvas = GodotConfig.canvas; const canvas = GodotConfig.canvas;
GodotDisplayListeners.add(canvas, 'dragover', function(ev) { GodotDisplayListeners.add(canvas, 'dragover', function (ev) {
// Prevent default behavior (which would try to open the file(s)) // Prevent default behavior (which would try to open the file(s))
ev.preventDefault(); ev.preventDefault();
}, false); }, false);

View File

@@ -30,7 +30,7 @@
const GodotEditorTools = { const GodotEditorTools = {
godot_js_editor_download_file__deps: ['$FS'], godot_js_editor_download_file__deps: ['$FS'],
godot_js_editor_download_file: function(p_path, p_name, p_mime) { godot_js_editor_download_file: function (p_path, p_name, p_mime) {
const path = GodotRuntime.parseString(p_path); const path = GodotRuntime.parseString(p_path);
const name = GodotRuntime.parseString(p_name); const name = GodotRuntime.parseString(p_name);
const mime = GodotRuntime.parseString(p_mime); const mime = GodotRuntime.parseString(p_mime);

View File

@@ -30,7 +30,7 @@
const GodotEval = { const GodotEval = {
godot_js_eval__deps: ['$GodotRuntime'], godot_js_eval__deps: ['$GodotRuntime'],
godot_js_eval: function(p_js, p_use_global_ctx, p_union_ptr, p_byte_arr, p_byte_arr_write, p_callback) { godot_js_eval: function (p_js, p_use_global_ctx, p_union_ptr, p_byte_arr, p_byte_arr_write, p_callback) {
const js_code = GodotRuntime.parseString(p_js); const js_code = GodotRuntime.parseString(p_js);
let eval_ret = null; let eval_ret = null;
try { try {
@@ -46,42 +46,40 @@ const GodotEval = {
} }
switch (typeof eval_ret) { switch (typeof eval_ret) {
case 'boolean':
GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'i32');
return 1; // BOOL
case 'boolean': case 'number':
GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'i32'); GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'double');
return 1; // BOOL return 3; // REAL
case 'number': case 'string':
GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'double'); GodotRuntime.setHeapValue(p_union_ptr, GodotRuntime.allocString(eval_ret), '*');
return 3; // REAL return 4; // STRING
case 'string': case 'object':
GodotRuntime.setHeapValue(p_union_ptr, GodotRuntime.allocString(eval_ret), '*'); if (eval_ret === null) {
return 4; // STRING
case 'object':
if (eval_ret === null) {
break;
}
if (ArrayBuffer.isView(eval_ret) && !(eval_ret instanceof Uint8Array)) {
eval_ret = new Uint8Array(eval_ret.buffer);
}
else if (eval_ret instanceof ArrayBuffer) {
eval_ret = new Uint8Array(eval_ret);
}
if (eval_ret instanceof Uint8Array) {
const func = GodotRuntime.get_func(p_callback);
const bytes_ptr = func(p_byte_arr, p_byte_arr_write, eval_ret.length);
HEAPU8.set(eval_ret, bytes_ptr);
return 20; // POOL_BYTE_ARRAY
}
break; break;
}
if (ArrayBuffer.isView(eval_ret) && !(eval_ret instanceof Uint8Array)) {
eval_ret = new Uint8Array(eval_ret.buffer);
} else if (eval_ret instanceof ArrayBuffer) {
eval_ret = new Uint8Array(eval_ret);
}
if (eval_ret instanceof Uint8Array) {
const func = GodotRuntime.get_func(p_callback);
const bytes_ptr = func(p_byte_arr, p_byte_arr_write, eval_ret.length);
HEAPU8.set(eval_ret, bytes_ptr);
return 20; // POOL_BYTE_ARRAY
}
break;
// no default // no default
} }
return 0; // NIL return 0; // NIL
}, },
} };
mergeInto(LibraryManager.library, GodotEval); mergeInto(LibraryManager.library, GodotEval);

View File

@@ -33,111 +33,113 @@ const GodotHTTPRequest = {
$GodotHTTPRequest: { $GodotHTTPRequest: {
requests: [], requests: [],
getUnusedRequestId: function() { getUnusedRequestId: function () {
var idMax = GodotHTTPRequest.requests.length; const idMax = GodotHTTPRequest.requests.length;
for (var potentialId = 0; potentialId < idMax; ++potentialId) { for (let potentialId = 0; potentialId < idMax; ++potentialId) {
if (GodotHTTPRequest.requests[potentialId] instanceof XMLHttpRequest) { if (GodotHTTPRequest.requests[potentialId] instanceof XMLHttpRequest) {
continue; continue;
} }
return potentialId; return potentialId;
} }
GodotHTTPRequest.requests.push(null) GodotHTTPRequest.requests.push(null);
return idMax; return idMax;
}, },
setupRequest: function(xhr) { setupRequest: function (xhr) {
xhr.responseType = 'arraybuffer'; xhr.responseType = 'arraybuffer';
}, },
}, },
godot_xhr_new: function() { godot_xhr_new: function () {
var newId = GodotHTTPRequest.getUnusedRequestId(); const newId = GodotHTTPRequest.getUnusedRequestId();
GodotHTTPRequest.requests[newId] = new XMLHttpRequest; GodotHTTPRequest.requests[newId] = new XMLHttpRequest();
GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[newId]); GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[newId]);
return newId; return newId;
}, },
godot_xhr_reset: function(xhrId) { godot_xhr_reset: function (xhrId) {
GodotHTTPRequest.requests[xhrId] = new XMLHttpRequest; GodotHTTPRequest.requests[xhrId] = new XMLHttpRequest();
GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[xhrId]); GodotHTTPRequest.setupRequest(GodotHTTPRequest.requests[xhrId]);
}, },
godot_xhr_free: function(xhrId) { godot_xhr_free: function (xhrId) {
GodotHTTPRequest.requests[xhrId].abort(); GodotHTTPRequest.requests[xhrId].abort();
GodotHTTPRequest.requests[xhrId] = null; GodotHTTPRequest.requests[xhrId] = null;
}, },
godot_xhr_open: function(xhrId, method, url, p_user, p_password) { godot_xhr_open: function (xhrId, method, url, p_user, p_password) {
const user = p_user > 0 ? GodotRuntime.parseString(p_user) : null; const user = p_user > 0 ? GodotRuntime.parseString(p_user) : null;
const password = p_password > 0 ? GodotRuntime.parseString(p_password) : null; const password = p_password > 0 ? GodotRuntime.parseString(p_password) : null;
GodotHTTPRequest.requests[xhrId].open(GodotRuntime.parseString(method), GodotRuntime.parseString(url), true, user, password); GodotHTTPRequest.requests[xhrId].open(GodotRuntime.parseString(method), GodotRuntime.parseString(url), true, user, password);
}, },
godot_xhr_set_request_header: function(xhrId, header, value) { godot_xhr_set_request_header: function (xhrId, header, value) {
GodotHTTPRequest.requests[xhrId].setRequestHeader(GodotRuntime.parseString(header), GodotRuntime.parseString(value)); GodotHTTPRequest.requests[xhrId].setRequestHeader(GodotRuntime.parseString(header), GodotRuntime.parseString(value));
}, },
godot_xhr_send_null: function(xhrId) { godot_xhr_send_null: function (xhrId) {
GodotHTTPRequest.requests[xhrId].send(); GodotHTTPRequest.requests[xhrId].send();
}, },
godot_xhr_send_string: function(xhrId, strPtr) { godot_xhr_send_string: function (xhrId, strPtr) {
if (!strPtr) { if (!strPtr) {
GodotRuntime.error("Failed to send string per XHR: null pointer"); GodotRuntime.error('Failed to send string per XHR: null pointer');
return; return;
} }
GodotHTTPRequest.requests[xhrId].send(GodotRuntime.parseString(strPtr)); GodotHTTPRequest.requests[xhrId].send(GodotRuntime.parseString(strPtr));
}, },
godot_xhr_send_data: function(xhrId, ptr, len) { godot_xhr_send_data: function (xhrId, ptr, len) {
if (!ptr) { if (!ptr) {
GodotRuntime.error("Failed to send data per XHR: null pointer"); GodotRuntime.error('Failed to send data per XHR: null pointer');
return; return;
} }
if (len < 0) { if (len < 0) {
GodotRuntime.error("Failed to send data per XHR: buffer length less than 0"); GodotRuntime.error('Failed to send data per XHR: buffer length less than 0');
return; return;
} }
GodotHTTPRequest.requests[xhrId].send(HEAPU8.subarray(ptr, ptr + len)); GodotHTTPRequest.requests[xhrId].send(HEAPU8.subarray(ptr, ptr + len));
}, },
godot_xhr_abort: function(xhrId) { godot_xhr_abort: function (xhrId) {
GodotHTTPRequest.requests[xhrId].abort(); GodotHTTPRequest.requests[xhrId].abort();
}, },
godot_xhr_get_status: function(xhrId) { godot_xhr_get_status: function (xhrId) {
return GodotHTTPRequest.requests[xhrId].status; return GodotHTTPRequest.requests[xhrId].status;
}, },
godot_xhr_get_ready_state: function(xhrId) { godot_xhr_get_ready_state: function (xhrId) {
return GodotHTTPRequest.requests[xhrId].readyState; return GodotHTTPRequest.requests[xhrId].readyState;
}, },
godot_xhr_get_response_headers_length: function(xhrId) { godot_xhr_get_response_headers_length: function (xhrId) {
var headers = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders(); const headers = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
return headers === null ? 0 : GodotRuntime.strlen(headers); return headers === null ? 0 : GodotRuntime.strlen(headers);
}, },
godot_xhr_get_response_headers: function(xhrId, dst, len) { godot_xhr_get_response_headers: function (xhrId, dst, len) {
var str = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders(); const str = GodotHTTPRequest.requests[xhrId].getAllResponseHeaders();
if (str === null) if (str === null) {
return; return;
}
GodotRuntime.stringToHeap(str, dst, len); GodotRuntime.stringToHeap(str, dst, len);
}, },
godot_xhr_get_response_length: function(xhrId) { godot_xhr_get_response_length: function (xhrId) {
var body = GodotHTTPRequest.requests[xhrId].response; const body = GodotHTTPRequest.requests[xhrId].response;
return body === null ? 0 : body.byteLength; return body === null ? 0 : body.byteLength;
}, },
godot_xhr_get_response: function(xhrId, dst, len) { godot_xhr_get_response: function (xhrId, dst, len) {
var buf = GodotHTTPRequest.requests[xhrId].response; let buf = GodotHTTPRequest.requests[xhrId].response;
if (buf === null) if (buf === null) {
return; return;
}
buf = new Uint8Array(buf).subarray(0, len); buf = new Uint8Array(buf).subarray(0, len);
HEAPU8.set(buf, dst); HEAPU8.set(buf, dst);
}, },
}; };
autoAddDeps(GodotHTTPRequest, "$GodotHTTPRequest"); autoAddDeps(GodotHTTPRequest, '$GodotHTTPRequest');
mergeInto(LibraryManager.library, GodotHTTPRequest); mergeInto(LibraryManager.library, GodotHTTPRequest);

View File

@@ -33,23 +33,23 @@ const IDHandler = {
_last_id: 0, _last_id: 0,
_references: {}, _references: {},
get: function(p_id) { get: function (p_id) {
return IDHandler._references[p_id]; return IDHandler._references[p_id];
}, },
add: function(p_data) { add: function (p_data) {
const id = ++IDHandler._last_id; const id = ++IDHandler._last_id;
IDHandler._references[id] = p_data; IDHandler._references[id] = p_data;
return id; return id;
}, },
remove: function(p_id) { remove: function (p_id) {
delete IDHandler._references[p_id]; delete IDHandler._references[p_id];
}, },
}, },
}; };
autoAddDeps(IDHandler, "$IDHandler"); autoAddDeps(IDHandler, '$IDHandler');
mergeInto(LibraryManager.library, IDHandler); mergeInto(LibraryManager.library, IDHandler);
const GodotConfig = { const GodotConfig = {
@@ -57,12 +57,12 @@ const GodotConfig = {
$GodotConfig__deps: ['$GodotRuntime'], $GodotConfig__deps: ['$GodotRuntime'],
$GodotConfig: { $GodotConfig: {
canvas: null, canvas: null,
locale: "en", locale: 'en',
resize_on_start: false, resize_on_start: false,
on_execute: null, on_execute: null,
init_config: function(p_opts) { init_config: function (p_opts) {
GodotConfig.resize_on_start = p_opts['resizeCanvasOnStart'] ? true : false; GodotConfig.resize_on_start = !!p_opts['resizeCanvasOnStart'];
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'];
@@ -70,20 +70,20 @@ const GodotConfig = {
Module['onExit'] = p_opts['onExit']; // eslint-disable-line no-undef 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
}, },
}, },
godot_js_config_canvas_id_get: function(p_ptr, p_ptr_max) { godot_js_config_canvas_id_get: function (p_ptr, p_ptr_max) {
GodotRuntime.stringToHeap('#' + GodotConfig.canvas.id, p_ptr, p_ptr_max); GodotRuntime.stringToHeap(`#${GodotConfig.canvas.id}`, p_ptr, p_ptr_max);
}, },
godot_js_config_locale_get: function(p_ptr, p_ptr_max) { godot_js_config_locale_get: function (p_ptr, p_ptr_max) {
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: function() { godot_js_config_is_resize_on_start: function () {
return GodotConfig.resize_on_start ? 1 : 0; return GodotConfig.resize_on_start ? 1 : 0;
}, },
}; };
@@ -91,7 +91,6 @@ const GodotConfig = {
autoAddDeps(GodotConfig, '$GodotConfig'); autoAddDeps(GodotConfig, '$GodotConfig');
mergeInto(LibraryManager.library, GodotConfig); mergeInto(LibraryManager.library, GodotConfig);
const GodotFS = { const GodotFS = {
$GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'], $GodotFS__deps: ['$FS', '$IDBFS', '$GodotRuntime'],
$GodotFS__postset: [ $GodotFS__postset: [
@@ -104,7 +103,7 @@ const GodotFS = {
_syncing: false, _syncing: false,
_mount_points: [], _mount_points: [],
is_persistent: function() { is_persistent: function () {
return GodotFS._idbfs ? 1 : 0; return GodotFS._idbfs ? 1 : 0;
}, },
@@ -112,7 +111,7 @@ const GodotFS = {
// Returns a promise that resolves when the FS is ready. // Returns a promise that resolves when the FS is ready.
// We keep track of mount_points, so that we can properly close the IDBFS // We keep track of mount_points, so that we can properly close the IDBFS
// since emscripten is not doing it by itself. (emscripten GH#12516). // since emscripten is not doing it by itself. (emscripten GH#12516).
init: function(persistentPaths) { init: function (persistentPaths) {
GodotFS._idbfs = false; GodotFS._idbfs = false;
if (!Array.isArray(persistentPaths)) { if (!Array.isArray(persistentPaths)) {
return Promise.reject(new Error('Persistent paths must be an array')); return Promise.reject(new Error('Persistent paths must be an array'));
@@ -133,16 +132,16 @@ const GodotFS = {
} }
} }
GodotFS._mount_points.forEach(function(path) { GodotFS._mount_points.forEach(function (path) {
createRecursive(path); createRecursive(path);
FS.mount(IDBFS, {}, path); FS.mount(IDBFS, {}, path);
}); });
return new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
FS.syncfs(true, function(err) { FS.syncfs(true, function (err) {
if (err) { if (err) {
GodotFS._mount_points = []; GodotFS._mount_points = [];
GodotFS._idbfs = false; GodotFS._idbfs = false;
GodotRuntime.print("IndexedDB not available: " + err.message); GodotRuntime.print(`IndexedDB not available: ${err.message}`);
} else { } else {
GodotFS._idbfs = true; GodotFS._idbfs = true;
} }
@@ -152,12 +151,12 @@ const GodotFS = {
}, },
// Deinit godot file system, making sure to unmount file systems, and close IDBFS(s). // Deinit godot file system, making sure to unmount file systems, and close IDBFS(s).
deinit: function() { deinit: function () {
GodotFS._mount_points.forEach(function(path) { GodotFS._mount_points.forEach(function (path) {
try { try {
FS.unmount(path); FS.unmount(path);
} catch (e) { } catch (e) {
GodotRuntime.print("Already unmounted", e); GodotRuntime.print('Already unmounted', e);
} }
if (GodotFS._idbfs && IDBFS.dbs[path]) { if (GodotFS._idbfs && IDBFS.dbs[path]) {
IDBFS.dbs[path].close(); IDBFS.dbs[path].close();
@@ -169,16 +168,16 @@ const GodotFS = {
GodotFS._syncing = false; GodotFS._syncing = false;
}, },
sync: function() { sync: function () {
if (GodotFS._syncing) { if (GodotFS._syncing) {
GodotRuntime.error('Already syncing!'); GodotRuntime.error('Already syncing!');
return Promise.resolve(); return Promise.resolve();
} }
GodotFS._syncing = true; GodotFS._syncing = true;
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
FS.syncfs(false, function(error) { FS.syncfs(false, function (error) {
if (error) { if (error) {
GodotRuntime.error('Failed to save IDB file system: ' + error.message); GodotRuntime.error(`Failed to save IDB file system: ${error.message}`);
} }
GodotFS._syncing = false; GodotFS._syncing = false;
resolve(error); resolve(error);
@@ -187,9 +186,9 @@ const GodotFS = {
}, },
// Copies a buffer to the internal file system. Creating directories recursively. // Copies a buffer to the internal file system. Creating directories recursively.
copy_to_fs: function(path, buffer) { copy_to_fs: function (path, buffer) {
const idx = path.lastIndexOf("/"); const idx = path.lastIndexOf('/');
let dir = "/"; let dir = '/';
if (idx > 0) { if (idx > 0) {
dir = path.slice(0, idx); dir = path.slice(0, idx);
} }
@@ -201,7 +200,7 @@ const GodotFS = {
} }
FS.mkdirTree(dir); FS.mkdirTree(dir);
} }
FS.writeFile(path, new Uint8Array(buffer), {'flags': 'wx+'}); FS.writeFile(path, new Uint8Array(buffer), { 'flags': 'wx+' });
}, },
}, },
}; };
@@ -214,54 +213,54 @@ const GodotOS = {
'GodotOS._fs_sync_promise = Promise.resolve();', 'GodotOS._fs_sync_promise = Promise.resolve();',
].join(''), ].join(''),
$GodotOS: { $GodotOS: {
request_quit: function() {}, request_quit: function () {},
_async_cbs: [], _async_cbs: [],
_fs_sync_promise: null, _fs_sync_promise: null,
atexit: function(p_promise_cb) { atexit: function (p_promise_cb) {
GodotOS._async_cbs.push(p_promise_cb); GodotOS._async_cbs.push(p_promise_cb);
}, },
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 = [];
GodotOS._async_cbs.forEach(function(cb) { GodotOS._async_cbs.forEach(function (cb) {
promises.push(new Promise(cb)); promises.push(new Promise(cb));
}); });
return Promise.all(promises); return Promise.all(promises);
}).then(function() { }).then(function () {
return GodotFS.sync(); // Final FS sync. return GodotFS.sync(); // Final FS sync.
}).then(function(err) { }).then(function (err) {
// Always deferred. // Always deferred.
setTimeout(function() { setTimeout(function () {
callback(); callback();
}, 0); }, 0);
}); });
}, },
}, },
godot_js_os_finish_async: function(p_callback) { godot_js_os_finish_async: function (p_callback) {
const func = GodotRuntime.get_func(p_callback); const func = GodotRuntime.get_func(p_callback);
GodotOS.finish_async(func); GodotOS.finish_async(func);
}, },
godot_js_os_request_quit_cb: function(p_callback) { godot_js_os_request_quit_cb: function (p_callback) {
GodotOS.request_quit = GodotRuntime.get_func(p_callback); GodotOS.request_quit = GodotRuntime.get_func(p_callback);
}, },
godot_js_os_fs_is_persistent: function() { godot_js_os_fs_is_persistent: function () {
return GodotFS.is_persistent(); return GodotFS.is_persistent();
}, },
godot_js_os_fs_sync: function(callback) { godot_js_os_fs_sync: function (callback) {
const func = GodotRuntime.get_func(callback); const func = GodotRuntime.get_func(callback);
GodotOS._fs_sync_promise = GodotFS.sync(); GodotOS._fs_sync_promise = GodotFS.sync();
GodotOS._fs_sync_promise.then(function(err) { GodotOS._fs_sync_promise.then(function (err) {
func(); func();
}); });
}, },
godot_js_os_execute: function(p_json) { godot_js_os_execute: function (p_json) {
const json_args = GodotRuntime.parseString(p_json); const json_args = GodotRuntime.parseString(p_json);
const args = JSON.parse(json_args); const args = JSON.parse(json_args);
if (GodotConfig.on_execute) { if (GodotConfig.on_execute) {
@@ -271,7 +270,7 @@ const GodotOS = {
return 1; return 1;
}, },
godot_js_os_shell_open: function(p_uri) { godot_js_os_shell_open: function (p_uri) {
window.open(GodotRuntime.parseString(p_uri), '_blank'); window.open(GodotRuntime.parseString(p_uri), '_blank');
}, },
}; };

View File

@@ -33,29 +33,29 @@ const GodotRuntime = {
/* /*
* Functions * Functions
*/ */
get_func: function(ptr) { get_func: function (ptr) {
return wasmTable.get(ptr); // eslint-disable-line no-undef return wasmTable.get(ptr); // eslint-disable-line no-undef
}, },
/* /*
* Prints * Prints
*/ */
error: function() { error: function () {
err.apply(null, Array.from(arguments)); // eslint-disable-line no-undef err.apply(null, Array.from(arguments)); // eslint-disable-line no-undef
}, },
print: function() { print: function () {
out.apply(null, Array.from(arguments)); // eslint-disable-line no-undef out.apply(null, Array.from(arguments)); // eslint-disable-line no-undef
}, },
/* /*
* Memory * Memory
*/ */
malloc: function(p_size) { malloc: function (p_size) {
return _malloc(p_size); // eslint-disable-line no-undef return _malloc(p_size); // eslint-disable-line no-undef
}, },
free: function(p_ptr) { free: function (p_ptr) {
_free(p_ptr); // eslint-disable-line no-undef _free(p_ptr); // eslint-disable-line no-undef
}, },
@@ -63,16 +63,16 @@ const GodotRuntime = {
return getValue(p_ptr, p_type); // eslint-disable-line no-undef return getValue(p_ptr, p_type); // eslint-disable-line no-undef
}, },
setHeapValue: function(p_ptr, p_value, p_type) { setHeapValue: function (p_ptr, p_value, p_type) {
setValue(p_ptr, p_value, p_type); // eslint-disable-line no-undef setValue(p_ptr, p_value, p_type); // eslint-disable-line no-undef
}, },
heapSub: function(p_heap, p_ptr, p_len) { heapSub: function (p_heap, p_ptr, p_len) {
const bytes = p_heap.BYTES_PER_ELEMENT; const bytes = p_heap.BYTES_PER_ELEMENT;
return p_heap.subarray(p_ptr / bytes, p_ptr / bytes + p_len); return p_heap.subarray(p_ptr / bytes, p_ptr / bytes + p_len);
}, },
heapCopy: function(p_heap, p_ptr, p_len) { heapCopy: function (p_heap, p_ptr, p_len) {
const bytes = p_heap.BYTES_PER_ELEMENT; const bytes = p_heap.BYTES_PER_ELEMENT;
return p_heap.slice(p_ptr / bytes, p_ptr / bytes + p_len); return p_heap.slice(p_ptr / bytes, p_ptr / bytes + p_len);
}, },
@@ -80,22 +80,22 @@ const GodotRuntime = {
/* /*
* Strings * Strings
*/ */
parseString: function(p_ptr) { parseString: function (p_ptr) {
return UTF8ToString(p_ptr); // eslint-disable-line no-undef return UTF8ToString(p_ptr); // eslint-disable-line no-undef
}, },
strlen: function(p_str) { strlen: function (p_str) {
return lengthBytesUTF8(p_str); // eslint-disable-line no-undef return lengthBytesUTF8(p_str); // eslint-disable-line no-undef
}, },
allocString: function(p_str) { allocString: function (p_str) {
const length = GodotRuntime.strlen(p_str)+1; const length = GodotRuntime.strlen(p_str) + 1;
const c_str = GodotRuntime.malloc(length); const c_str = GodotRuntime.malloc(length);
stringToUTF8(p_str, c_str, length); // eslint-disable-line no-undef stringToUTF8(p_str, c_str, length); // eslint-disable-line no-undef
return c_str; return c_str;
}, },
allocStringArray: function(p_strings) { allocStringArray: function (p_strings) {
const size = p_strings.length; const size = p_strings.length;
const c_ptr = GodotRuntime.malloc(size * 4); const c_ptr = GodotRuntime.malloc(size * 4);
for (let i = 0; i < size; i++) { for (let i = 0; i < size; i++) {
@@ -104,7 +104,7 @@ const GodotRuntime = {
return c_ptr; return c_ptr;
}, },
freeStringArray: function(p_ptr, p_len) { freeStringArray: function (p_ptr, p_len) {
for (let i = 0; i < p_len; i++) { for (let i = 0; i < p_len; i++) {
GodotRuntime.free(HEAP32[(p_ptr >> 2) + i]); GodotRuntime.free(HEAP32[(p_ptr >> 2) + i]);
} }
@@ -116,5 +116,5 @@ const GodotRuntime = {
}, },
}, },
}; };
autoAddDeps(GodotRuntime, "$GodotRuntime"); autoAddDeps(GodotRuntime, '$GodotRuntime');
mergeInto(LibraryManager.library, GodotRuntime); mergeInto(LibraryManager.library, GodotRuntime);