Browse Source

[HTML5] Implement Godot <-> JavaScript interface.

Fabio Alessandrelli 4 years ago
parent
commit
730a894bcf

+ 29 - 0
doc/classes/JavaScript.xml

@@ -11,6 +11,26 @@
 		<link>https://docs.godotengine.org/en/3.3/getting_started/workflow/export/exporting_for_web.html#calling-javascript-from-script</link>
 		<link>https://docs.godotengine.org/en/3.3/getting_started/workflow/export/exporting_for_web.html#calling-javascript-from-script</link>
 	</tutorials>
 	</tutorials>
 	<methods>
 	<methods>
+		<method name="create_callback">
+			<return type="JavaScriptObject">
+			</return>
+			<argument index="0" name="object" type="Object">
+			</argument>
+			<argument index="1" name="method" type="String">
+			</argument>
+			<description>
+				Creates a reference to a script function that can be used as a callback by JavaScript. The reference must be kept until the callback happens, or it won't be called at all. See [JavaScriptObject] for usage.
+			</description>
+		</method>
+		<method name="create_object" qualifiers="vararg">
+			<return type="Variant">
+			</return>
+			<argument index="0" name="object" type="String">
+			</argument>
+			<description>
+				Creates a new JavaScript object using the [code]new[/code] constructor. The [code]object[/code] must a valid property of the JavaScript [code]window[/code]. See [JavaScriptObject] for usage.
+			</description>
+		</method>
 		<method name="eval">
 		<method name="eval">
 			<return type="Variant">
 			<return type="Variant">
 			</return>
 			</return>
@@ -23,6 +43,15 @@
 				If [code]use_global_execution_context[/code] is [code]true[/code], the code will be evaluated in the global execution context. Otherwise, it is evaluated in the execution context of a function within the engine's runtime environment.
 				If [code]use_global_execution_context[/code] is [code]true[/code], the code will be evaluated in the global execution context. Otherwise, it is evaluated in the execution context of a function within the engine's runtime environment.
 			</description>
 			</description>
 		</method>
 		</method>
+		<method name="get_interface">
+			<return type="JavaScriptObject">
+			</return>
+			<argument index="0" name="interface" type="String">
+			</argument>
+			<description>
+				Returns an interface to a JavaScript object that can be used by scripts. The [code]interface[/code] must be a valid property of the JavaScript [code]window[/code]. The callback must accept a single [Array] argument, which will contain the JavaScript [code]arguments[/code]. See [JavaScriptObject] for usage.
+			</description>
+		</method>
 	</methods>
 	</methods>
 	<constants>
 	<constants>
 	</constants>
 	</constants>

+ 42 - 0
doc/classes/JavaScriptObject.xml

@@ -0,0 +1,42 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<class name="JavaScriptObject" inherits="Reference" version="3.4">
+	<brief_description>
+		A wrapper class for native JavaScript objects.
+	</brief_description>
+	<description>
+		JavaScriptObject is used to interact with JavaScript objects retrieved or created via [method JavaScript.get_interface], [method JavaScript.create_object], or [method JavaScript.create_callback].
+		Example:
+		[codeblock]
+		extends Node
+
+		var _my_js_callback = JavaScript.create_callback(self, "myCallback") # This reference must be kept
+		var console = JavaScript.get_interface("console")
+
+		func _init():
+		    var buf = JavaScript.create_object("ArrayBuffer", 10) # new ArrayBuffer(10)
+		    print(buf) # prints [JavaScriptObject:OBJECT_ID]
+		    var uint8arr = JavaScript.create_object("Uint8Array", buf) # new Uint8Array(buf)
+		    uint8arr[1] = 255
+		    prints(uint8arr[1], uint8arr.byteLength) # prints 255 10
+		    console.log(uint8arr) # prints in browser console "Uint8Array(10) [ 0, 255, 0, 0, 0, 0, 0, 0, 0, 0 ]"
+
+		    # Equivalent of JavaScript: Array.from(uint8arr).forEach(myCallback)
+		    JavaScript.get_interface("Array").from(uint8arr).forEach(_my_js_callback)
+
+		func myCallback(args):
+		    # Will be called with the parameters passed to the "forEach" callback
+		    # [0, 0, [JavaScriptObject:1173]]
+		    # [255, 1, [JavaScriptObject:1173]]
+		    # ...
+		    # [0, 9, [JavaScriptObject:1180]]
+		    print(args)
+		[/codeblock]
+		Note: Only available in the "HTML5" platform.
+	</description>
+	<tutorials>
+	</tutorials>
+	<methods>
+	</methods>
+	<constants>
+	</constants>
+</class>

+ 2 - 2
platform/javascript/SCsub

@@ -5,7 +5,7 @@ Import("env")
 javascript_files = [
 javascript_files = [
     "audio_driver_javascript.cpp",
     "audio_driver_javascript.cpp",
     "http_client_javascript.cpp",
     "http_client_javascript.cpp",
-    "javascript_eval.cpp",
+    "javascript_singleton.cpp",
     "javascript_main.cpp",
     "javascript_main.cpp",
     "os_javascript.cpp",
     "os_javascript.cpp",
     "api/javascript_tools_editor_plugin.cpp",
     "api/javascript_tools_editor_plugin.cpp",
@@ -25,7 +25,7 @@ sys_env.AddJSLibraries(
 if env["tools"]:
 if env["tools"]:
     sys_env.AddJSLibraries(["js/libs/library_godot_editor_tools.js"])
     sys_env.AddJSLibraries(["js/libs/library_godot_editor_tools.js"])
 if env["javascript_eval"]:
 if env["javascript_eval"]:
-    sys_env.AddJSLibraries(["js/libs/library_godot_eval.js"])
+    sys_env.AddJSLibraries(["js/libs/library_godot_javascript_singleton.js"])
 
 
 for lib in sys_env["JS_LIBS"]:
 for lib in sys_env["JS_LIBS"]:
     sys_env.Append(LINKFLAGS=["--js-library", lib])
     sys_env.Append(LINKFLAGS=["--js-library", lib])

+ 33 - 1
platform/javascript/api/api.cpp

@@ -30,13 +30,14 @@
 
 
 #include "api.h"
 #include "api.h"
 #include "core/engine.h"
 #include "core/engine.h"
-#include "javascript_eval.h"
+#include "javascript_singleton.h"
 #include "javascript_tools_editor_plugin.h"
 #include "javascript_tools_editor_plugin.h"
 
 
 static JavaScript *javascript_eval;
 static JavaScript *javascript_eval;
 
 
 void register_javascript_api() {
 void register_javascript_api() {
 	JavaScriptToolsEditorPlugin::initialize();
 	JavaScriptToolsEditorPlugin::initialize();
+	ClassDB::register_virtual_class<JavaScriptObject>();
 	ClassDB::register_virtual_class<JavaScript>();
 	ClassDB::register_virtual_class<JavaScript>();
 	javascript_eval = memnew(JavaScript);
 	javascript_eval = memnew(JavaScript);
 	Engine::get_singleton()->add_singleton(Engine::Singleton("JavaScript", javascript_eval));
 	Engine::get_singleton()->add_singleton(Engine::Singleton("JavaScript", javascript_eval));
@@ -61,10 +62,41 @@ JavaScript::~JavaScript() {}
 
 
 void JavaScript::_bind_methods() {
 void JavaScript::_bind_methods() {
 	ClassDB::bind_method(D_METHOD("eval", "code", "use_global_execution_context"), &JavaScript::eval, DEFVAL(false));
 	ClassDB::bind_method(D_METHOD("eval", "code", "use_global_execution_context"), &JavaScript::eval, DEFVAL(false));
+	ClassDB::bind_method(D_METHOD("get_interface", "interface"), &JavaScript::get_interface);
+	ClassDB::bind_method(D_METHOD("create_callback", "object", "method"), &JavaScript::create_callback);
+	{
+		MethodInfo mi;
+		mi.name = "create_object";
+		mi.arguments.push_back(PropertyInfo(Variant::STRING, "object"));
+		ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "create_object", &JavaScript::_create_object_bind, mi);
+	}
 }
 }
 
 
 #if !defined(JAVASCRIPT_ENABLED) || !defined(JAVASCRIPT_EVAL_ENABLED)
 #if !defined(JAVASCRIPT_ENABLED) || !defined(JAVASCRIPT_EVAL_ENABLED)
 Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
 Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
 	return Variant();
 	return Variant();
 }
 }
+
+Ref<JavaScriptObject> JavaScript::get_interface(const String &p_interface) {
+	return Ref<JavaScriptObject>();
+}
+
+Ref<JavaScriptObject> JavaScript::create_callback(Object *p_ref, const StringName &p_method) {
+	return Ref<JavaScriptObject>();
+}
+
+Variant JavaScript::_create_object_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
+	if (p_argcount < 1) {
+		r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+		r_error.argument = 0;
+		return Ref<JavaScriptObject>();
+	}
+	if (p_args[0]->get_type() != Variant::STRING) {
+		r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+		r_error.argument = 0;
+		r_error.expected = Variant::STRING;
+		return Ref<JavaScriptObject>();
+	}
+	return Ref<JavaScriptObject>();
+}
 #endif
 #endif

+ 18 - 4
platform/javascript/api/javascript_eval.h → platform/javascript/api/javascript_singleton.h

@@ -1,5 +1,5 @@
 /*************************************************************************/
 /*************************************************************************/
-/*  javascript_eval.h                                                    */
+/*  javascript_singleton.h                                               */
 /*************************************************************************/
 /*************************************************************************/
 /*                       This file is part of:                           */
 /*                       This file is part of:                           */
 /*                           GODOT ENGINE                                */
 /*                           GODOT ENGINE                                */
@@ -28,10 +28,21 @@
 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
 /*************************************************************************/
 /*************************************************************************/
 
 
-#ifndef JAVASCRIPT_EVAL_H
-#define JAVASCRIPT_EVAL_H
+#ifndef JAVASCRIPT_SINGLETON_H
+#define JAVASCRIPT_SINGLETON_H
 
 
 #include "core/object.h"
 #include "core/object.h"
+#include "core/reference.h"
+
+class JavaScriptObject : public Reference {
+private:
+	GDCLASS(JavaScriptObject, Reference);
+
+protected:
+	virtual bool _set(const StringName &p_name, const Variant &p_value) { return false; }
+	virtual bool _get(const StringName &p_name, Variant &r_ret) const { return false; }
+	virtual void _get_property_list(List<PropertyInfo> *p_list) const {}
+};
 
 
 class JavaScript : public Object {
 class JavaScript : public Object {
 private:
 private:
@@ -44,10 +55,13 @@ protected:
 
 
 public:
 public:
 	Variant eval(const String &p_code, bool p_use_global_exec_context = false);
 	Variant eval(const String &p_code, bool p_use_global_exec_context = false);
+	Ref<JavaScriptObject> get_interface(const String &p_interface);
+	Ref<JavaScriptObject> create_callback(Object *p_ref, const StringName &p_method);
+	Variant _create_object_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error);
 
 
 	static JavaScript *get_singleton();
 	static JavaScript *get_singleton();
 	JavaScript();
 	JavaScript();
 	~JavaScript();
 	~JavaScript();
 };
 };
 
 
-#endif // JAVASCRIPT_EVAL_H
+#endif // JAVASCRIPT_SINGLETON_H

+ 0 - 79
platform/javascript/javascript_eval.cpp

@@ -1,79 +0,0 @@
-/*************************************************************************/
-/*  javascript_eval.cpp                                                  */
-/*************************************************************************/
-/*                       This file is part of:                           */
-/*                           GODOT ENGINE                                */
-/*                      https://godotengine.org                          */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
-/*                                                                       */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the       */
-/* "Software"), to deal in the Software without restriction, including   */
-/* without limitation the rights to use, copy, modify, merge, publish,   */
-/* distribute, sublicense, and/or sell copies of the Software, and to    */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions:                                             */
-/*                                                                       */
-/* The above copyright notice and this permission notice shall be        */
-/* included in all copies or substantial portions of the Software.       */
-/*                                                                       */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
-/*************************************************************************/
-
-#ifdef JAVASCRIPT_EVAL_ENABLED
-
-#include "api/javascript_eval.h"
-#include "emscripten.h"
-
-extern "C" {
-union js_eval_ret {
-	uint32_t b;
-	double d;
-	char *s;
-};
-
-extern int godot_js_eval(const char *p_js, int p_use_global_ctx, union js_eval_ret *p_union_ptr, void *p_byte_arr, void *p_byte_arr_write, void *(*p_callback)(void *p_ptr, void *p_ptr2, int p_len));
-}
-
-void *resize_poolbytearray_and_open_write(void *p_arr, void *r_write, int p_len) {
-	PoolByteArray *arr = (PoolByteArray *)p_arr;
-	PoolByteArray::Write *write = (PoolByteArray::Write *)r_write;
-	arr->resize(p_len);
-	*write = arr->write();
-	return write->ptr();
-}
-
-Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
-	PoolByteArray arr;
-	PoolByteArray::Write arr_write;
-	union js_eval_ret js_data;
-	memset(&js_data, 0, sizeof(js_data));
-	Variant::Type return_type = static_cast<Variant::Type>(godot_js_eval(p_code.utf8().get_data(), p_use_global_exec_context, &js_data, &arr, &arr_write, resize_poolbytearray_and_open_write));
-
-	switch (return_type) {
-		case Variant::BOOL:
-			return js_data.b == 1;
-		case Variant::REAL:
-			return js_data.d;
-		case Variant::STRING: {
-			String str = String::utf8(js_data.s);
-			free(js_data.s); // Must free the string allocated in JS.
-			return str;
-		}
-		case Variant::POOL_BYTE_ARRAY:
-			arr_write = PoolByteArray::Write();
-			return arr;
-		default:
-			return Variant();
-	}
-}
-
-#endif // JAVASCRIPT_EVAL_ENABLED

+ 340 - 0
platform/javascript/javascript_singleton.cpp

@@ -0,0 +1,340 @@
+/*************************************************************************/
+/*  javascript_singleton.cpp                                             */
+/*************************************************************************/
+/*                       This file is part of:                           */
+/*                           GODOT ENGINE                                */
+/*                      https://godotengine.org                          */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
+/*                                                                       */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the       */
+/* "Software"), to deal in the Software without restriction, including   */
+/* without limitation the rights to use, copy, modify, merge, publish,   */
+/* distribute, sublicense, and/or sell copies of the Software, and to    */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions:                                             */
+/*                                                                       */
+/* The above copyright notice and this permission notice shall be        */
+/* included in all copies or substantial portions of the Software.       */
+/*                                                                       */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
+/*************************************************************************/
+
+#ifdef JAVASCRIPT_EVAL_ENABLED
+
+#include "api/javascript_singleton.h"
+#include "emscripten.h"
+
+extern "C" {
+typedef union {
+	int64_t i;
+	double r;
+	void *p;
+} godot_js_wrapper_ex;
+
+typedef int (*GodotJSWrapperVariant2JSCallback)(const void **p_args, int p_pos, godot_js_wrapper_ex *r_val, void **p_lock);
+typedef void (*GodotJSWrapperFreeLockCallback)(void **p_lock, int p_type);
+extern int godot_js_wrapper_interface_get(const char *p_name);
+extern int godot_js_wrapper_object_call(int p_id, const char *p_method, void **p_args, int p_argc, GodotJSWrapperVariant2JSCallback p_variant2js_callback, godot_js_wrapper_ex *p_cb_rval, void **p_lock, GodotJSWrapperFreeLockCallback p_lock_callback);
+extern int godot_js_wrapper_object_get(int p_id, godot_js_wrapper_ex *p_val, const char *p_prop);
+extern int godot_js_wrapper_object_getvar(int p_id, int p_type, godot_js_wrapper_ex *p_val);
+extern int godot_js_wrapper_object_setvar(int p_id, int p_key_type, godot_js_wrapper_ex *p_key_ex, int p_val_type, godot_js_wrapper_ex *p_val_ex);
+extern void godot_js_wrapper_object_set(int p_id, const char *p_name, int p_type, godot_js_wrapper_ex *p_val);
+extern void godot_js_wrapper_object_unref(int p_id);
+extern int godot_js_wrapper_create_cb(void *p_ref, void (*p_callback)(void *p_ref, int p_arg_id, int p_argc));
+extern int godot_js_wrapper_create_object(const char *p_method, void **p_args, int p_argc, GodotJSWrapperVariant2JSCallback p_variant2js_callback, godot_js_wrapper_ex *p_cb_rval, void **p_lock, GodotJSWrapperFreeLockCallback p_lock_callback);
+};
+
+class JavaScriptObjectImpl : public JavaScriptObject {
+private:
+	friend class JavaScript;
+
+	int _js_id = 0;
+	Object *_ref = nullptr;
+	StringName _method;
+
+	static int _variant2js(const void **p_args, int p_pos, godot_js_wrapper_ex *r_val, void **p_lock);
+	static void _free_lock(void **p_lock, int p_type);
+	static Variant _js2variant(int p_type, godot_js_wrapper_ex *p_val);
+	static void *_alloc_variants(int p_size);
+	static void _callback(void *p_ref, int p_arg_id, int p_argc);
+
+protected:
+	bool _set(const StringName &p_name, const Variant &p_value) override;
+	bool _get(const StringName &p_name, Variant &r_ret) const override;
+	void _get_property_list(List<PropertyInfo> *p_list) const override;
+
+public:
+	Variant getvar(const Variant &p_key, bool *r_valid = nullptr) const override;
+	void setvar(const Variant &p_key, const Variant &p_value, bool *r_valid = nullptr) override;
+	Variant call(const StringName &p_method, const Variant **p_args, int p_argc, Variant::CallError &r_error) override;
+	JavaScriptObjectImpl() {}
+	JavaScriptObjectImpl(int p_id) { _js_id = p_id; }
+	~JavaScriptObjectImpl() {
+		if (_js_id) {
+			godot_js_wrapper_object_unref(_js_id);
+		}
+	}
+};
+
+bool JavaScriptObjectImpl::_set(const StringName &p_name, const Variant &p_value) {
+	ERR_FAIL_COND_V_MSG(!_js_id, false, "Invalid JS instance");
+	const String name = p_name;
+	godot_js_wrapper_ex exchange;
+	void *lock = nullptr;
+	const Variant *v = &p_value;
+	int type = _variant2js((const void **)&v, 0, &exchange, &lock);
+	godot_js_wrapper_object_set(_js_id, name.utf8().get_data(), type, &exchange);
+	if (lock) {
+		_free_lock(&lock, type);
+	}
+	return true;
+}
+
+bool JavaScriptObjectImpl::_get(const StringName &p_name, Variant &r_ret) const {
+	ERR_FAIL_COND_V_MSG(!_js_id, false, "Invalid JS instance");
+	const String name = p_name;
+	godot_js_wrapper_ex exchange;
+	int type = godot_js_wrapper_object_get(_js_id, &exchange, name.utf8().get_data());
+	r_ret = _js2variant(type, &exchange);
+	return true;
+}
+
+Variant JavaScriptObjectImpl::getvar(const Variant &p_key, bool *r_valid) const {
+	if (r_valid) {
+		*r_valid = false;
+	}
+	godot_js_wrapper_ex exchange;
+	void *lock = nullptr;
+	const Variant *v = &p_key;
+	int prop_type = _variant2js((const void **)&v, 0, &exchange, &lock);
+	int type = godot_js_wrapper_object_getvar(_js_id, prop_type, &exchange);
+	if (lock) {
+		_free_lock(&lock, prop_type);
+	}
+	if (type < 0) {
+		return Variant();
+	}
+	if (r_valid) {
+		*r_valid = true;
+	}
+	return _js2variant(type, &exchange);
+}
+
+void JavaScriptObjectImpl::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
+	if (r_valid) {
+		*r_valid = false;
+	}
+	godot_js_wrapper_ex kex, vex;
+	void *klock = nullptr;
+	void *vlock = nullptr;
+	const Variant *kv = &p_key;
+	const Variant *vv = &p_value;
+	int ktype = _variant2js((const void **)&kv, 0, &kex, &klock);
+	int vtype = _variant2js((const void **)&vv, 0, &vex, &vlock);
+	int ret = godot_js_wrapper_object_setvar(_js_id, ktype, &kex, vtype, &vex);
+	if (klock) {
+		_free_lock(&klock, ktype);
+	}
+	if (vlock) {
+		_free_lock(&vlock, vtype);
+	}
+	if (ret == 0 && r_valid) {
+		*r_valid = true;
+	}
+}
+
+void JavaScriptObjectImpl::_get_property_list(List<PropertyInfo> *p_list) const {
+}
+
+void JavaScriptObjectImpl::_free_lock(void **p_lock, int p_type) {
+	ERR_FAIL_COND_MSG(*p_lock == nullptr, "No lock to free!");
+	const Variant::Type type = (Variant::Type)p_type;
+	switch (type) {
+		case Variant::STRING: {
+			CharString *cs = (CharString *)(*p_lock);
+			memdelete(cs);
+			*p_lock = nullptr;
+		} break;
+		default:
+			ERR_FAIL_MSG("Unknown lock type to free. Likely a bug.");
+	}
+}
+
+Variant JavaScriptObjectImpl::_js2variant(int p_type, godot_js_wrapper_ex *p_val) {
+	Variant::Type type = (Variant::Type)p_type;
+	switch (type) {
+		case Variant::BOOL:
+			return Variant((bool)p_val->i);
+		case Variant::INT:
+			return p_val->i;
+		case Variant::REAL:
+			return p_val->r;
+		case Variant::STRING: {
+			String out((const char *)p_val->p);
+			free(p_val->p);
+			return out;
+		}
+		case Variant::OBJECT: {
+			return memnew(JavaScriptObjectImpl(p_val->i));
+		}
+		default:
+			return Variant();
+	}
+}
+
+int JavaScriptObjectImpl::_variant2js(const void **p_args, int p_pos, godot_js_wrapper_ex *r_val, void **p_lock) {
+	const Variant **args = (const Variant **)p_args;
+	const Variant *v = args[p_pos];
+	Variant::Type type = v->get_type();
+	switch (type) {
+		case Variant::BOOL:
+			r_val->i = v->operator bool() ? 1 : 0;
+			break;
+		case Variant::INT: {
+			const int64_t tmp = v->operator int64_t();
+			if (tmp >= 1 << 31) {
+				r_val->r = (double)tmp;
+				return Variant::REAL;
+			}
+			r_val->i = v->operator int64_t();
+		} break;
+		case Variant::REAL:
+			r_val->r = v->operator real_t();
+			break;
+		case Variant::STRING: {
+			CharString *cs = memnew(CharString(v->operator String().utf8()));
+			r_val->p = (void *)cs->get_data();
+			*p_lock = (void *)cs;
+		} break;
+		case Variant::OBJECT: {
+			JavaScriptObject *js_obj = Object::cast_to<JavaScriptObject>(v->operator Object *());
+			r_val->i = js_obj != nullptr ? ((JavaScriptObjectImpl *)js_obj)->_js_id : 0;
+		} break;
+		default:
+			break;
+	}
+	return type;
+}
+
+Variant JavaScriptObjectImpl::call(const StringName &p_method, const Variant **p_args, int p_argc, Variant::CallError &r_error) {
+	godot_js_wrapper_ex exchange;
+	const String method = p_method;
+	void *lock = nullptr;
+	const int type = godot_js_wrapper_object_call(_js_id, method.utf8().get_data(), (void **)p_args, p_argc, &_variant2js, &exchange, &lock, &_free_lock);
+	r_error.error = Variant::CallError::CALL_OK;
+	if (type < 0) {
+		r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+		return Variant();
+	}
+	return _js2variant(type, &exchange);
+}
+
+void JavaScriptObjectImpl::_callback(void *p_ref, int p_args_id, int p_argc) {
+	const JavaScriptObjectImpl *obj = (JavaScriptObjectImpl *)p_ref;
+	ERR_FAIL_COND_MSG(obj->_ref == nullptr, "JavaScript callback failed.");
+	Vector<const Variant *> argp;
+	Array arg_arr;
+	for (int i = 0; i < p_argc; i++) {
+		godot_js_wrapper_ex exchange;
+		exchange.i = i;
+		int type = godot_js_wrapper_object_getvar(p_args_id, Variant::INT, &exchange);
+		arg_arr.push_back(_js2variant(type, &exchange));
+	}
+	Variant arg = arg_arr;
+	const Variant *argv[1] = { &arg };
+	Variant::CallError err;
+	obj->_ref->call(obj->_method, argv, 1, err);
+}
+
+Ref<JavaScriptObject> JavaScript::create_callback(Object *p_ref, const StringName &p_method) {
+	Ref<JavaScriptObjectImpl> out = memnew(JavaScriptObjectImpl);
+	out->_ref = p_ref;
+	out->_method = p_method;
+	out->_js_id = godot_js_wrapper_create_cb(out.ptr(), JavaScriptObjectImpl::_callback);
+	return out;
+}
+
+Ref<JavaScriptObject> JavaScript::get_interface(const String &p_interface) {
+	int js_id = godot_js_wrapper_interface_get(p_interface.utf8().get_data());
+	ERR_FAIL_COND_V_MSG(!js_id, Ref<JavaScriptObject>(), "No interface '" + p_interface + "' registered.");
+	return Ref<JavaScriptObject>(memnew(JavaScriptObjectImpl(js_id)));
+}
+
+Variant JavaScript::_create_object_bind(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
+	if (p_argcount < 1) {
+		r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
+		r_error.argument = 0;
+		return Ref<JavaScriptObject>();
+	}
+	if (p_args[0]->get_type() != Variant::STRING) {
+		r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT;
+		r_error.argument = 0;
+		r_error.expected = Variant::STRING;
+		return Ref<JavaScriptObject>();
+	}
+	godot_js_wrapper_ex exchange;
+	const String object = *p_args[0];
+	void *lock = nullptr;
+	const Variant **args = p_argcount > 1 ? &p_args[1] : nullptr;
+	const int type = godot_js_wrapper_create_object(object.utf8().get_data(), (void **)args, p_argcount - 1, &JavaScriptObjectImpl::_variant2js, &exchange, &lock, &JavaScriptObjectImpl::_free_lock);
+	r_error.error = Variant::CallError::CALL_OK;
+	if (type < 0) {
+		r_error.error = Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL;
+		return Ref<JavaScriptObject>();
+	}
+	return JavaScriptObjectImpl::_js2variant(type, &exchange);
+}
+
+extern "C" {
+union js_eval_ret {
+	uint32_t b;
+	double d;
+	char *s;
+};
+
+extern int godot_js_eval(const char *p_js, int p_use_global_ctx, union js_eval_ret *p_union_ptr, void *p_byte_arr, void *p_byte_arr_write, void *(*p_callback)(void *p_ptr, void *p_ptr2, int p_len));
+}
+
+void *resize_poolbytearray_and_open_write(void *p_arr, void *r_write, int p_len) {
+	PoolByteArray *arr = (PoolByteArray *)p_arr;
+	PoolByteArray::Write *write = (PoolByteArray::Write *)r_write;
+	arr->resize(p_len);
+	*write = arr->write();
+	return write->ptr();
+}
+
+Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) {
+	PoolByteArray arr;
+	PoolByteArray::Write arr_write;
+	union js_eval_ret js_data;
+	memset(&js_data, 0, sizeof(js_data));
+	Variant::Type return_type = static_cast<Variant::Type>(godot_js_eval(p_code.utf8().get_data(), p_use_global_exec_context, &js_data, &arr, &arr_write, resize_poolbytearray_and_open_write));
+
+	switch (return_type) {
+		case Variant::BOOL:
+			return js_data.b == 1;
+		case Variant::REAL:
+			return js_data.d;
+		case Variant::STRING: {
+			String str = String::utf8(js_data.s);
+			free(js_data.s); // Must free the string allocated in JS.
+			return str;
+		}
+		case Variant::POOL_BYTE_ARRAY:
+			arr_write = PoolByteArray::Write();
+			return arr;
+		default:
+			return Variant();
+	}
+}
+
+#endif // JAVASCRIPT_EVAL_ENABLED

+ 0 - 86
platform/javascript/js/libs/library_godot_eval.js

@@ -1,86 +0,0 @@
-/*************************************************************************/
-/*  library_godot_eval.js                                                */
-/*************************************************************************/
-/*                       This file is part of:                           */
-/*                           GODOT ENGINE                                */
-/*                      https://godotengine.org                          */
-/*************************************************************************/
-/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
-/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
-/*                                                                       */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the       */
-/* "Software"), to deal in the Software without restriction, including   */
-/* without limitation the rights to use, copy, modify, merge, publish,   */
-/* distribute, sublicense, and/or sell copies of the Software, and to    */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions:                                             */
-/*                                                                       */
-/* The above copyright notice and this permission notice shall be        */
-/* included in all copies or substantial portions of the Software.       */
-/*                                                                       */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
-/*************************************************************************/
-
-const GodotEval = {
-	godot_js_eval__deps: ['$GodotRuntime'],
-	godot_js_eval__sig: 'iiiiiii',
-	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);
-		let eval_ret = null;
-		try {
-			if (p_use_global_ctx) {
-				// indirect eval call grants global execution context
-				const global_eval = eval; // eslint-disable-line no-eval
-				eval_ret = global_eval(js_code);
-			} else {
-				eval_ret = eval(js_code); // eslint-disable-line no-eval
-			}
-		} catch (e) {
-			GodotRuntime.error(e);
-		}
-
-		switch (typeof eval_ret) {
-		case 'boolean':
-			GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'i32');
-			return 1; // BOOL
-
-		case 'number':
-			GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'double');
-			return 3; // REAL
-
-		case 'string':
-			GodotRuntime.setHeapValue(p_union_ptr, GodotRuntime.allocString(eval_ret), '*');
-			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;
-
-			// no default
-		}
-		return 0; // NIL
-	},
-};
-
-mergeInto(LibraryManager.library, GodotEval);

+ 333 - 0
platform/javascript/js/libs/library_godot_javascript_singleton.js

@@ -0,0 +1,333 @@
+/*************************************************************************/
+/*  library_godot_eval.js                                                */
+/*************************************************************************/
+/*                       This file is part of:                           */
+/*                           GODOT ENGINE                                */
+/*                      https://godotengine.org                          */
+/*************************************************************************/
+/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
+/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
+/*                                                                       */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the       */
+/* "Software"), to deal in the Software without restriction, including   */
+/* without limitation the rights to use, copy, modify, merge, publish,   */
+/* distribute, sublicense, and/or sell copies of the Software, and to    */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions:                                             */
+/*                                                                       */
+/* The above copyright notice and this permission notice shall be        */
+/* included in all copies or substantial portions of the Software.       */
+/*                                                                       */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
+/*************************************************************************/
+
+const GodotJSWrapper = {
+
+	$GodotJSWrapper__deps: ['$GodotRuntime', '$IDHandler'],
+	$GodotJSWrapper__postset: 'GodotJSWrapper.proxies = new Map();',
+	$GodotJSWrapper: {
+		proxies: null,
+
+		MyProxy: function (val) {
+			const id = IDHandler.add(this);
+			GodotJSWrapper.proxies.set(val, id);
+			let refs = 1;
+			this.ref = function () {
+				refs++;
+			};
+			this.unref = function () {
+				refs--;
+				if (refs === 0) {
+					IDHandler.remove(id);
+					GodotJSWrapper.proxies.delete(val);
+				}
+			};
+			this.get_val = function () {
+				return val;
+			};
+			this.get_id = function () {
+				return id;
+			};
+		},
+
+		get_proxied: function (val) {
+			const id = GodotJSWrapper.proxies.get(val);
+			if (id === undefined) {
+				const proxy = new GodotJSWrapper.MyProxy(val);
+				return proxy.get_id();
+			}
+			IDHandler.get(id).ref();
+			return id;
+		},
+
+		get_proxied_value: function (id) {
+			const proxy = IDHandler.get(id);
+			if (proxy === undefined) {
+				return undefined;
+			}
+			return proxy.get_val();
+		},
+
+		variant2js: function (type, val) {
+			switch (type) {
+			case 0:
+				return null;
+			case 1:
+				return !!GodotRuntime.getHeapValue(val, 'i64');
+			case 2:
+				return GodotRuntime.getHeapValue(val, 'i64');
+			case 3:
+				return GodotRuntime.getHeapValue(val, 'double');
+			case 4:
+				return GodotRuntime.parseString(GodotRuntime.getHeapValue(val, '*'));
+			case 17: // OBJECT
+				return GodotJSWrapper.get_proxied_value(GodotRuntime.getHeapValue(val, 'i64'));
+			default:
+				return undefined;
+			}
+		},
+
+		js2variant: function (p_val, p_exchange) {
+			if (p_val === undefined || p_val === null) {
+				return 0; // NIL
+			}
+			const type = typeof (p_val);
+			if (type === 'boolean') {
+				GodotRuntime.setHeapValue(p_exchange, p_val, 'i64');
+				return 1; // BOOL
+			} else if (type === 'number') {
+				if (Number.isInteger(p_val)) {
+					GodotRuntime.setHeapValue(p_exchange, p_val, 'i64');
+					return 2; // INT
+				}
+				GodotRuntime.setHeapValue(p_exchange, p_val, 'double');
+				return 3; // REAL
+			} else if (type === 'string') {
+				const c_str = GodotRuntime.allocString(p_val);
+				GodotRuntime.setHeapValue(p_exchange, c_str, '*');
+				return 4; // STRING
+			}
+			const id = GodotJSWrapper.get_proxied(p_val);
+			GodotRuntime.setHeapValue(p_exchange, id, 'i64');
+			return 17;
+		},
+	},
+
+	godot_js_wrapper_interface_get__sig: 'ii',
+	godot_js_wrapper_interface_get: function (p_name) {
+		const name = GodotRuntime.parseString(p_name);
+		if (typeof (window[name]) !== 'undefined') {
+			return GodotJSWrapper.get_proxied(window[name]);
+		}
+		return 0;
+	},
+
+	godot_js_wrapper_object_get__sig: 'iiii',
+	godot_js_wrapper_object_get: function (p_id, p_exchange, p_prop) {
+		const obj = GodotJSWrapper.get_proxied_value(p_id);
+		if (obj === undefined) {
+			return 0;
+		}
+		if (p_prop) {
+			const prop = GodotRuntime.parseString(p_prop);
+			try {
+				return GodotJSWrapper.js2variant(obj[prop], p_exchange);
+			} catch (e) {
+				GodotRuntime.error(`Error getting variable ${prop} on object`, obj);
+				return 0; // NIL
+			}
+		}
+		return GodotJSWrapper.js2variant(obj, p_exchange);
+	},
+
+	godot_js_wrapper_object_set__sig: 'viiii',
+	godot_js_wrapper_object_set: function (p_id, p_name, p_type, p_exchange) {
+		const obj = GodotJSWrapper.get_proxied_value(p_id);
+		if (obj === undefined) {
+			return;
+		}
+		const name = GodotRuntime.parseString(p_name);
+		try {
+			obj[name] = GodotJSWrapper.variant2js(p_type, p_exchange);
+		} catch (e) {
+			GodotRuntime.error(`Error setting variable ${name} on object`, obj);
+		}
+	},
+
+	godot_js_wrapper_object_call__sig: 'iiiiiiiii',
+	godot_js_wrapper_object_call: function (p_id, p_method, p_args, p_argc, p_convert_callback, p_exchange, p_lock, p_free_lock_callback) {
+		const obj = GodotJSWrapper.get_proxied_value(p_id);
+		if (obj === undefined) {
+			return -1;
+		}
+		const method = GodotRuntime.parseString(p_method);
+		const convert = GodotRuntime.get_func(p_convert_callback);
+		const freeLock = GodotRuntime.get_func(p_free_lock_callback);
+		const args = new Array(p_argc);
+		for (let i = 0; i < p_argc; i++) {
+			const type = convert(p_args, i, p_exchange, p_lock);
+			const lock = GodotRuntime.getHeapValue(p_lock, '*');
+			args[i] = GodotJSWrapper.variant2js(type, p_exchange);
+			if (lock) {
+				freeLock(p_lock, type);
+			}
+		}
+		try {
+			const res = obj[method](...args);
+			return GodotJSWrapper.js2variant(res, p_exchange);
+		} catch (e) {
+			GodotRuntime.error(`Error calling method ${method} on:`, obj, 'error:', e);
+			return -1;
+		}
+	},
+
+	godot_js_wrapper_object_unref__sig: 'vi',
+	godot_js_wrapper_object_unref: function (p_id) {
+		const proxy = IDHandler.get(p_id);
+		if (proxy !== undefined) {
+			proxy.unref();
+		}
+	},
+
+	godot_js_wrapper_create_cb__sig: 'vii',
+	godot_js_wrapper_create_cb: function (p_ref, p_func) {
+		const func = GodotRuntime.get_func(p_func);
+		let id = 0;
+		const cb = function () {
+			if (!GodotJSWrapper.get_proxied_value(id)) {
+				return;
+			}
+			const args = Array.from(arguments);
+			func(p_ref, GodotJSWrapper.get_proxied(args), args.length);
+		};
+		id = GodotJSWrapper.get_proxied(cb);
+		return id;
+	},
+
+	godot_js_wrapper_object_getvar__sig: 'iiii',
+	godot_js_wrapper_object_getvar: function (p_id, p_type, p_exchange) {
+		const obj = GodotJSWrapper.get_proxied_value(p_id);
+		if (obj === undefined) {
+			return -1;
+		}
+		const prop = GodotJSWrapper.variant2js(p_type, p_exchange);
+		if (prop === undefined || prop === null) {
+			return -1;
+		}
+		try {
+			return GodotJSWrapper.js2variant(obj[prop], p_exchange);
+		} catch (e) {
+			GodotRuntime.error(`Error getting variable ${prop} on object`, obj, e);
+			return -1;
+		}
+	},
+
+	godot_js_wrapper_object_setvar__sig: 'iiiiii',
+	godot_js_wrapper_object_setvar: function (p_id, p_key_type, p_key_ex, p_val_type, p_val_ex) {
+		const obj = GodotJSWrapper.get_proxied_value(p_id);
+		if (obj === undefined) {
+			return -1;
+		}
+		const key = GodotJSWrapper.variant2js(p_key_type, p_key_ex);
+		try {
+			obj[key] = GodotJSWrapper.variant2js(p_val_type, p_val_ex);
+			return 0;
+		} catch (e) {
+			GodotRuntime.error(`Error setting variable ${key} on object`, obj);
+			return -1;
+		}
+	},
+
+	godot_js_wrapper_create_object__sig: 'iiiiiiii',
+	godot_js_wrapper_create_object: function (p_object, p_args, p_argc, p_convert_callback, p_exchange, p_lock, p_free_lock_callback) {
+		const name = GodotRuntime.parseString(p_object);
+		if (typeof (window[name]) === 'undefined') {
+			return -1;
+		}
+		const convert = GodotRuntime.get_func(p_convert_callback);
+		const freeLock = GodotRuntime.get_func(p_free_lock_callback);
+		const args = new Array(p_argc);
+		for (let i = 0; i < p_argc; i++) {
+			const type = convert(p_args, i, p_exchange, p_lock);
+			const lock = GodotRuntime.getHeapValue(p_lock, '*');
+			args[i] = GodotJSWrapper.variant2js(type, p_exchange);
+			if (lock) {
+				freeLock(p_lock, type);
+			}
+		}
+		try {
+			const res = new window[name](...args);
+			return GodotJSWrapper.js2variant(res, p_exchange);
+		} catch (e) {
+			GodotRuntime.error(`Error calling constructor ${name} with args:`, args, 'error:', e);
+			return -1;
+		}
+	},
+};
+
+autoAddDeps(GodotJSWrapper, '$GodotJSWrapper');
+mergeInto(LibraryManager.library, GodotJSWrapper);
+
+const GodotEval = {
+	godot_js_eval__deps: ['$GodotRuntime'],
+	godot_js_eval__sig: 'iiiiiii',
+	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);
+		let eval_ret = null;
+		try {
+			if (p_use_global_ctx) {
+				// indirect eval call grants global execution context
+				const global_eval = eval; // eslint-disable-line no-eval
+				eval_ret = global_eval(js_code);
+			} else {
+				eval_ret = eval(js_code); // eslint-disable-line no-eval
+			}
+		} catch (e) {
+			GodotRuntime.error(e);
+		}
+
+		switch (typeof eval_ret) {
+		case 'boolean':
+			GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'i32');
+			return 1; // BOOL
+
+		case 'number':
+			GodotRuntime.setHeapValue(p_union_ptr, eval_ret, 'double');
+			return 3; // REAL
+
+		case 'string':
+			GodotRuntime.setHeapValue(p_union_ptr, GodotRuntime.allocString(eval_ret), '*');
+			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;
+
+			// no default
+		}
+		return 0; // NIL
+	},
+};
+
+mergeInto(LibraryManager.library, GodotEval);