diff options
Diffstat (limited to 'modules')
110 files changed, 4803 insertions, 1137 deletions
diff --git a/modules/gdnative/SCsub b/modules/gdnative/SCsub index 6592d0ae1d..a6ae143947 100644 --- a/modules/gdnative/SCsub +++ b/modules/gdnative/SCsub @@ -12,6 +12,9 @@ gdn_env.add_source_files(env.modules_sources, "nativescript/*.cpp") gdn_env.Append(CPPPATH=['#modules/gdnative/include/']) +SConscript("nativearvr/SCsub") +SConscript("pluginscript/SCsub") + def _spaced(e): return e if e[-1] == '*' else e + ' ' @@ -22,7 +25,9 @@ def _build_gdnative_api_struct_header(api): '#define GODOT_GDNATIVE_API_STRUCT_H', '', '#include <gdnative/gdnative.h>', + '#include <nativearvr/godot_nativearvr.h>', '#include <nativescript/godot_nativescript.h>', + '#include <pluginscript/godot_pluginscript.h>', '', '#define GDNATIVE_API_INIT(options) do { extern const godot_gdnative_api_struct *_gdnative_wrapper_api_struct; _gdnative_wrapper_api_struct = options->api_struct; } while (0)', '', @@ -95,6 +100,7 @@ def _build_gdnative_wrapper_code(api): '', '#include <gdnative/gdnative.h>', '#include <nativescript/godot_nativescript.h>', + '#include <pluginscript/godot_pluginscript.h>', '', '#include <gdnative_api_struct.gen.h>', '', diff --git a/modules/gdnative/config.py b/modules/gdnative/config.py index 9f57b9bb74..df3556249d 100644 --- a/modules/gdnative/config.py +++ b/modules/gdnative/config.py @@ -1,8 +1,12 @@ - def can_build(platform): return True - def configure(env): env.use_ptrcall = True + +def get_doc_classes(): + return ["GDNative", "GDNativeLibrary", "NativeScript", "ARVRInterfaceGDNative"] + +def get_doc_path(): + return "doc_classes" diff --git a/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml new file mode 100644 index 0000000000..308a7d5946 --- /dev/null +++ b/modules/gdnative/doc_classes/ARVRInterfaceGDNative.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="ARVRInterfaceGDNative" inherits="ARVRInterface" category="Core" version="3.0.alpha.custom_build"> + <brief_description> + GDNative wrapper for an ARVR interface + </brief_description> + <description> + This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface simply instantiate this object and set your GDNative library containing the ARVR interface implementation. + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + </methods> + <constants> + </constants> +</class> diff --git a/modules/gdnative/doc_classes/GDNative.xml b/modules/gdnative/doc_classes/GDNative.xml new file mode 100644 index 0000000000..83a1cf06f0 --- /dev/null +++ b/modules/gdnative/doc_classes/GDNative.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GDNative" inherits="Reference" category="Core" version="3.0.alpha.custom_build"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + <method name="call_native"> + <return type="Variant"> + </return> + <argument index="0" name="calling_type" type="String"> + </argument> + <argument index="1" name="procedure_name" type="String"> + </argument> + <argument index="2" name="arguments" type="Array"> + </argument> + <description> + </description> + </method> + <method name="get_library"> + <return type="GDNativeLibrary"> + </return> + <description> + </description> + </method> + <method name="initialize"> + <return type="bool"> + </return> + <description> + </description> + </method> + <method name="set_library"> + <return type="void"> + </return> + <argument index="0" name="library" type="GDNativeLibrary"> + </argument> + <description> + </description> + </method> + <method name="terminate"> + <return type="bool"> + </return> + <description> + </description> + </method> + </methods> + <members> + <member name="library" type="GDNativeLibrary" setter="set_library" getter="get_library"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/modules/gdnative/doc_classes/GDNativeLibrary.xml b/modules/gdnative/doc_classes/GDNativeLibrary.xml new file mode 100644 index 0000000000..361c89e6b3 --- /dev/null +++ b/modules/gdnative/doc_classes/GDNativeLibrary.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="GDNativeLibrary" inherits="Resource" category="Core" version="3.0.alpha.custom_build"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + <method name="get_active_library_path" qualifiers="const"> + <return type="String"> + </return> + <description> + </description> + </method> + <method name="get_library_path" qualifiers="const"> + <return type="String"> + </return> + <argument index="0" name="platform" type="String"> + </argument> + <description> + </description> + </method> + <method name="is_singleton_gdnative" qualifiers="const"> + <return type="bool"> + </return> + <description> + </description> + </method> + <method name="set_library_path"> + <return type="void"> + </return> + <argument index="0" name="platform" type="String"> + </argument> + <argument index="1" name="path" type="String"> + </argument> + <description> + </description> + </method> + <method name="set_singleton_gdnative"> + <return type="void"> + </return> + <argument index="0" name="singleton" type="bool"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="singleton_gdnative" type="bool" setter="set_singleton_gdnative" getter="is_singleton_gdnative"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/modules/gdnative/doc_classes/NativeScript.xml b/modules/gdnative/doc_classes/NativeScript.xml new file mode 100644 index 0000000000..b040cfd966 --- /dev/null +++ b/modules/gdnative/doc_classes/NativeScript.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<class name="NativeScript" inherits="Script" category="Core" version="3.0.alpha.custom_build"> + <brief_description> + </brief_description> + <description> + </description> + <tutorials> + </tutorials> + <demos> + </demos> + <methods> + <method name="get_class_name" qualifiers="const"> + <return type="String"> + </return> + <description> + </description> + </method> + <method name="get_library" qualifiers="const"> + <return type="GDNativeLibrary"> + </return> + <description> + </description> + </method> + <method name="new" qualifiers="vararg"> + <return type="Object"> + </return> + <description> + </description> + </method> + <method name="set_class_name"> + <return type="void"> + </return> + <argument index="0" name="class_name" type="String"> + </argument> + <description> + </description> + </method> + <method name="set_library"> + <return type="void"> + </return> + <argument index="0" name="library" type="GDNativeLibrary"> + </argument> + <description> + </description> + </method> + </methods> + <members> + <member name="class_name" type="String" setter="set_class_name" getter="get_class_name"> + </member> + <member name="library" type="GDNativeLibrary" setter="set_library" getter="get_library"> + </member> + </members> + <constants> + </constants> +</class> diff --git a/modules/gdnative/gdnative.cpp b/modules/gdnative/gdnative.cpp index 373b98dc8b..3fc04a5498 100644 --- a/modules/gdnative/gdnative.cpp +++ b/modules/gdnative/gdnative.cpp @@ -199,10 +199,7 @@ void GDNative::_bind_methods() { ClassDB::bind_method(D_METHOD("initialize"), &GDNative::initialize); ClassDB::bind_method(D_METHOD("terminate"), &GDNative::terminate); - // TODO(karroffel): get_native_(raw_)call_types binding? - - // TODO(karroffel): make this a varargs function? - ClassDB::bind_method(D_METHOD("call_native", "procedure_name", "arguments"), &GDNative::call_native); + ClassDB::bind_method(D_METHOD("call_native", "calling_type", "procedure_name", "arguments"), &GDNative::call_native); ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "library", PROPERTY_HINT_RESOURCE_TYPE, "GDNativeLibrary"), "set_library", "get_library"); } @@ -239,10 +236,7 @@ bool GDNative::initialize() { } void *library_init; - err = OS::get_singleton()->get_dynamic_library_symbol_handle( - native_handle, - init_symbol, - library_init); + err = get_symbol(init_symbol, library_init); if (err || !library_init) { OS::get_singleton()->close_dynamic_library(native_handle); @@ -277,11 +271,8 @@ bool GDNative::terminate() { } void *library_terminate; - Error error = OS::get_singleton()->get_dynamic_library_symbol_handle( - native_handle, - terminate_symbol, - library_terminate); - if (error) { + Error error = get_symbol(terminate_symbol, library_terminate); + if (error || !library_terminate) { OS::get_singleton()->close_dynamic_library(native_handle); native_handle = NULL; return true; @@ -313,10 +304,6 @@ void GDNativeCallRegistry::register_native_call_type(StringName p_call_type, nat native_calls.insert(p_call_type, p_callback); } -void GDNativeCallRegistry::register_native_raw_call_type(StringName p_raw_call_type, native_raw_call_cb p_callback) { - native_raw_calls.insert(p_raw_call_type, p_callback); -} - Vector<StringName> GDNativeCallRegistry::get_native_call_types() { Vector<StringName> call_types; call_types.resize(native_calls.size()); @@ -329,18 +316,6 @@ Vector<StringName> GDNativeCallRegistry::get_native_call_types() { return call_types; } -Vector<StringName> GDNativeCallRegistry::get_native_raw_call_types() { - Vector<StringName> call_types; - call_types.resize(native_raw_calls.size()); - - size_t idx = 0; - for (Map<StringName, native_raw_call_cb>::Element *E = native_raw_calls.front(); E; E = E->next(), idx++) { - call_types[idx] = E->key(); - } - - return call_types; -} - Variant GDNative::call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments) { Map<StringName, native_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_calls.find(p_native_call_type); @@ -349,20 +324,34 @@ Variant GDNative::call_native(StringName p_native_call_type, StringName p_proced return Variant(); } - String procedure_name = p_procedure_name; - godot_variant result = E->get()(native_handle, (godot_string *)&procedure_name, (godot_array *)&p_arguments); + void *procedure_handle; + + Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( + native_handle, + p_procedure_name, + procedure_handle); + + if (err != OK || procedure_handle == NULL) { + return Variant(); + } + + godot_variant result = E->get()(procedure_handle, (godot_array *)&p_arguments); return *(Variant *)&result; } -void GDNative::call_native_raw(StringName p_raw_call_type, StringName p_procedure_name, void *data, int num_args, void **args, void *r_return) { +Error GDNative::get_symbol(StringName p_procedure_name, void *&r_handle) { - Map<StringName, native_raw_call_cb>::Element *E = GDNativeCallRegistry::singleton->native_raw_calls.find(p_raw_call_type); - if (!E) { - ERR_PRINT((String("No handler for native raw call type \"" + p_raw_call_type) + "\" found").utf8().get_data()); - return; + if (native_handle == NULL) { + ERR_PRINT("No valid library handle, can't get symbol from GDNative object"); + return ERR_CANT_OPEN; } - String procedure_name = p_procedure_name; - E->get()(native_handle, (godot_string *)&procedure_name, data, num_args, args, r_return); + Error result = OS::get_singleton()->get_dynamic_library_symbol_handle( + native_handle, + p_procedure_name, + r_handle, + true); + + return result; } diff --git a/modules/gdnative/gdnative.h b/modules/gdnative/gdnative.h index 7bbad842eb..e44cc55a79 100644 --- a/modules/gdnative/gdnative.h +++ b/modules/gdnative/gdnative.h @@ -100,8 +100,7 @@ public: _FORCE_INLINE_ void set_singleton_gdnative(bool p_singleton) { singleton_gdnative = p_singleton; } }; -typedef godot_variant (*native_call_cb)(void *, godot_string *, godot_array *); -typedef void (*native_raw_call_cb)(void *, godot_string *, void *, int, void **, void *); +typedef godot_variant (*native_call_cb)(void *, godot_array *); struct GDNativeCallRegistry { static GDNativeCallRegistry *singleton; @@ -111,17 +110,13 @@ struct GDNativeCallRegistry { } inline GDNativeCallRegistry() - : native_calls(), - native_raw_calls() {} + : native_calls() {} Map<StringName, native_call_cb> native_calls; - Map<StringName, native_raw_call_cb> native_raw_calls; void register_native_call_type(StringName p_call_type, native_call_cb p_callback); - void register_native_raw_call_type(StringName p_raw_call_type, native_raw_call_cb p_callback); Vector<StringName> get_native_call_types(); - Vector<StringName> get_native_raw_call_types(); }; class GDNative : public Reference { @@ -149,7 +144,8 @@ public: bool terminate(); Variant call_native(StringName p_native_call_type, StringName p_procedure_name, Array p_arguments = Array()); - void call_native_raw(StringName p_raw_call_type, StringName p_procedure_name, void *data, int num_args, void **args, void *r_return); + + Error get_symbol(StringName p_procedure_name, void *&r_handle); }; #endif // GDNATIVE_H diff --git a/modules/gdnative/gdnative/string.cpp b/modules/gdnative/gdnative/string.cpp index 9b715ce36a..905c513d9d 100644 --- a/modules/gdnative/gdnative/string.cpp +++ b/modules/gdnative/gdnative/string.cpp @@ -29,9 +29,9 @@ /*************************************************************************/ #include "gdnative/string.h" +#include "core/string_db.h" +#include "core/ustring.h" #include "core/variant.h" -#include "string_db.h" -#include "ustring.h" #include <string.h> diff --git a/modules/gdnative/gdnative_api.json b/modules/gdnative/gdnative_api.json index 4d3c024a8f..31b021b751 100644 --- a/modules/gdnative/gdnative_api.json +++ b/modules/gdnative/gdnative_api.json @@ -5229,6 +5229,85 @@ "arguments": [ ["godot_object *", "p_instance"] ] + }, + { + "name": "godot_arvr_register_interface", + "return_type": "void", + "arguments": [ + ["const godot_arvr_interface_gdnative *", "p_interface"] + ] + }, + { + "name": "godot_arvr_get_worldscale", + "return_type": "godot_real", + "arguments": [] + }, + { + "name": "godot_arvr_get_reference_frame", + "return_type": "godot_transform", + "arguments": [] + }, + { + "name": "godot_arvr_blit", + "return_type": "void", + "arguments": [ + ["int", "p_eye"], + ["godot_rid *", "p_render_target"], + ["godot_rect2 *", "p_screen_rect"] + ] + }, + { + "name": "godot_arvr_get_texid", + "return_type": "godot_int", + "arguments": [ + ["godot_rid *", "p_render_target"] + ] + }, + { + "name": "godot_arvr_add_controller", + "return_type": "godot_int", + "arguments": [ + ["char *", "p_device_name"], + ["godot_int", "p_hand"], + ["godot_bool", "p_tracks_orientation"], + ["godot_bool", "p_tracks_position"] + ] + }, + { + "name": "godot_arvr_remove_controller", + "return_type": "void", + "arguments": [ + ["godot_int", "p_controller_id"] + ] + }, + { + "name": "godot_arvr_set_controller_transform", + "return_type": "void", + "arguments": [ + ["godot_int", "p_controller_id"], + ["godot_transform *", "p_transform"], + ["godot_bool", "p_tracks_orientation"], + ["godot_bool", "p_tracks_position"] + ] + }, + { + "name": "godot_arvr_set_controller_button", + "return_type": "void", + "arguments": [ + ["godot_int", "p_controller_id"], + ["godot_int", "p_button"], + ["godot_bool", "p_is_pressed"] + ] + }, + { + "name": "godot_arvr_set_controller_axis", + "return_type": "void", + "arguments": [ + ["godot_int", "p_controller_id"], + ["godot_int", "p_exis"], + ["godot_real", "p_value"], + ["godot_bool", "p_can_be_negative"] + ] } ] } diff --git a/modules/gdnative/include/gdnative/array.h b/modules/gdnative/include/gdnative/array.h index edab028cba..d0639589b7 100644 --- a/modules/gdnative/include/gdnative/array.h +++ b/modules/gdnative/include/gdnative/array.h @@ -46,11 +46,20 @@ typedef struct { } godot_array; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/pool_arrays.h> #include <gdnative/variant.h> #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_array_new(godot_array *r_dest); void GDAPI godot_array_new_copy(godot_array *r_dest, const godot_array *p_src); void GDAPI godot_array_new_pool_color_array(godot_array *r_dest, const godot_pool_color_array *p_pca); diff --git a/modules/gdnative/include/gdnative/basis.h b/modules/gdnative/include/gdnative/basis.h index 8ff6a6f541..b86b1c17d8 100644 --- a/modules/gdnative/include/gdnative/basis.h +++ b/modules/gdnative/include/gdnative/basis.h @@ -45,10 +45,19 @@ typedef struct { } godot_basis; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/quat.h> #include <gdnative/vector3.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_basis_new_with_rows(godot_basis *r_dest, const godot_vector3 *p_x_axis, const godot_vector3 *p_y_axis, const godot_vector3 *p_z_axis); void GDAPI godot_basis_new_with_axis_and_angle(godot_basis *r_dest, const godot_vector3 *p_axis, const godot_real p_phi); void GDAPI godot_basis_new_with_euler(godot_basis *r_dest, const godot_vector3 *p_euler); diff --git a/modules/gdnative/include/gdnative/color.h b/modules/gdnative/include/gdnative/color.h index 14265466b9..857e86a738 100644 --- a/modules/gdnative/include/gdnative/color.h +++ b/modules/gdnative/include/gdnative/color.h @@ -45,9 +45,18 @@ typedef struct { } godot_color; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/string.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_color_new_rgba(godot_color *r_dest, const godot_real p_r, const godot_real p_g, const godot_real p_b, const godot_real p_a); void GDAPI godot_color_new_rgb(godot_color *r_dest, const godot_real p_r, const godot_real p_g, const godot_real p_b); diff --git a/modules/gdnative/include/gdnative/dictionary.h b/modules/gdnative/include/gdnative/dictionary.h index c85c3f3830..e68d0fdc29 100644 --- a/modules/gdnative/include/gdnative/dictionary.h +++ b/modules/gdnative/include/gdnative/dictionary.h @@ -45,10 +45,19 @@ typedef struct { } godot_dictionary; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/array.h> #include <gdnative/gdnative.h> #include <gdnative/variant.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_dictionary_new(godot_dictionary *r_dest); void GDAPI godot_dictionary_new_copy(godot_dictionary *r_dest, const godot_dictionary *p_src); void GDAPI godot_dictionary_destroy(godot_dictionary *p_self); diff --git a/modules/gdnative/include/gdnative/gdnative.h b/modules/gdnative/include/gdnative/gdnative.h index 2d8726e5db..25d45db306 100644 --- a/modules/gdnative/include/gdnative/gdnative.h +++ b/modules/gdnative/include/gdnative/gdnative.h @@ -47,7 +47,7 @@ extern "C" { #define GDAPI GDCALLINGCONV #endif #else -#define GDCALLINGCONV __attribute__((sysv_abi, visibility("default"))) +#define GDCALLINGCONV __attribute__((sysv_abi)) #define GDAPI GDCALLINGCONV #endif @@ -255,7 +255,7 @@ godot_dictionary GDAPI godot_get_global_constants(); ////// GDNative procedure types typedef void (*godot_gdnative_init_fn)(godot_gdnative_init_options *); typedef void (*godot_gdnative_terminate_fn)(godot_gdnative_terminate_options *); -typedef godot_variant (*godot_gdnative_procedure_fn)(void *, godot_array *); +typedef godot_variant (*godot_gdnative_procedure_fn)(godot_array *); ////// System Functions diff --git a/modules/gdnative/include/gdnative/node_path.h b/modules/gdnative/include/gdnative/node_path.h index 0cfdbc1127..42446175d8 100644 --- a/modules/gdnative/include/gdnative/node_path.h +++ b/modules/gdnative/include/gdnative/node_path.h @@ -45,9 +45,18 @@ typedef struct { } godot_node_path; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/string.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_node_path_new(godot_node_path *r_dest, const godot_string *p_from); void GDAPI godot_node_path_new_copy(godot_node_path *r_dest, const godot_node_path *p_src); void GDAPI godot_node_path_destroy(godot_node_path *p_self); diff --git a/modules/gdnative/include/gdnative/plane.h b/modules/gdnative/include/gdnative/plane.h index 6a8915e08b..dddd172122 100644 --- a/modules/gdnative/include/gdnative/plane.h +++ b/modules/gdnative/include/gdnative/plane.h @@ -45,9 +45,18 @@ typedef struct { } godot_plane; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/vector3.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_plane_new_with_reals(godot_plane *r_dest, const godot_real p_a, const godot_real p_b, const godot_real p_c, const godot_real p_d); void GDAPI godot_plane_new_with_vectors(godot_plane *r_dest, const godot_vector3 *p_v1, const godot_vector3 *p_v2, const godot_vector3 *p_v3); void GDAPI godot_plane_new_with_normal(godot_plane *r_dest, const godot_vector3 *p_normal, const godot_real p_d); diff --git a/modules/gdnative/include/gdnative/pool_arrays.h b/modules/gdnative/include/gdnative/pool_arrays.h index cb1095ee8c..93181f2a6b 100644 --- a/modules/gdnative/include/gdnative/pool_arrays.h +++ b/modules/gdnative/include/gdnative/pool_arrays.h @@ -113,6 +113,11 @@ typedef struct { } godot_pool_color_array; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/array.h> #include <gdnative/color.h> #include <gdnative/vector2.h> @@ -120,6 +125,10 @@ typedef struct { #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + // byte void GDAPI godot_pool_byte_array_new(godot_pool_byte_array *r_dest); diff --git a/modules/gdnative/include/gdnative/quat.h b/modules/gdnative/include/gdnative/quat.h index 4ffb96eb26..acae6e3e90 100644 --- a/modules/gdnative/include/gdnative/quat.h +++ b/modules/gdnative/include/gdnative/quat.h @@ -45,9 +45,18 @@ typedef struct { } godot_quat; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/vector3.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_quat_new(godot_quat *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_z, const godot_real p_w); void GDAPI godot_quat_new_with_axis_angle(godot_quat *r_dest, const godot_vector3 *p_axis, const godot_real p_angle); diff --git a/modules/gdnative/include/gdnative/rect2.h b/modules/gdnative/include/gdnative/rect2.h index 9e6cf60342..1c66443d4f 100644 --- a/modules/gdnative/include/gdnative/rect2.h +++ b/modules/gdnative/include/gdnative/rect2.h @@ -43,9 +43,18 @@ typedef struct godot_rect2 { } godot_rect2; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/vector2.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_rect2_new_with_position_and_size(godot_rect2 *r_dest, const godot_vector2 *p_pos, const godot_vector2 *p_size); void GDAPI godot_rect2_new(godot_rect2 *r_dest, const godot_real p_x, const godot_real p_y, const godot_real p_width, const godot_real p_height); diff --git a/modules/gdnative/include/gdnative/rect3.h b/modules/gdnative/include/gdnative/rect3.h index f94b6fea25..f603a9268a 100644 --- a/modules/gdnative/include/gdnative/rect3.h +++ b/modules/gdnative/include/gdnative/rect3.h @@ -45,10 +45,19 @@ typedef struct { } godot_rect3; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/plane.h> #include <gdnative/vector3.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_rect3_new(godot_rect3 *r_dest, const godot_vector3 *p_pos, const godot_vector3 *p_size); godot_vector3 GDAPI godot_rect3_get_position(const godot_rect3 *p_self); diff --git a/modules/gdnative/include/gdnative/rid.h b/modules/gdnative/include/gdnative/rid.h index d9b5336fc9..caa1bb967e 100644 --- a/modules/gdnative/include/gdnative/rid.h +++ b/modules/gdnative/include/gdnative/rid.h @@ -45,8 +45,17 @@ typedef struct { } godot_rid; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_rid_new(godot_rid *r_dest); godot_int GDAPI godot_rid_get_id(const godot_rid *p_self); diff --git a/modules/gdnative/include/gdnative/string.h b/modules/gdnative/include/gdnative/string.h index aca23a81d8..f30fdb8dc7 100644 --- a/modules/gdnative/include/gdnative/string.h +++ b/modules/gdnative/include/gdnative/string.h @@ -46,9 +46,18 @@ typedef struct { } godot_string; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/variant.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_string_new(godot_string *r_dest); void GDAPI godot_string_new_copy(godot_string *r_dest, const godot_string *p_src); void GDAPI godot_string_new_data(godot_string *r_dest, const char *p_contents, const int p_size); diff --git a/modules/gdnative/include/gdnative/string_name.h b/modules/gdnative/include/gdnative/string_name.h index e217487250..ee9f603d20 100644 --- a/modules/gdnative/include/gdnative/string_name.h +++ b/modules/gdnative/include/gdnative/string_name.h @@ -46,8 +46,17 @@ typedef struct { } godot_string_name; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_string_name_new(godot_string_name *r_dest, const godot_string *p_name); void GDAPI godot_string_name_new_data(godot_string_name *r_dest, const char *p_name); diff --git a/modules/gdnative/include/gdnative/transform.h b/modules/gdnative/include/gdnative/transform.h index 656afae129..8f50b01fb5 100644 --- a/modules/gdnative/include/gdnative/transform.h +++ b/modules/gdnative/include/gdnative/transform.h @@ -45,11 +45,20 @@ typedef struct { } godot_transform; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/basis.h> #include <gdnative/gdnative.h> #include <gdnative/variant.h> #include <gdnative/vector3.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_transform_new_with_axis_origin(godot_transform *r_dest, const godot_vector3 *p_x_axis, const godot_vector3 *p_y_axis, const godot_vector3 *p_z_axis, const godot_vector3 *p_origin); void GDAPI godot_transform_new(godot_transform *r_dest, const godot_basis *p_basis, const godot_vector3 *p_origin); diff --git a/modules/gdnative/include/gdnative/transform2d.h b/modules/gdnative/include/gdnative/transform2d.h index a945868b17..c68bd2963f 100644 --- a/modules/gdnative/include/gdnative/transform2d.h +++ b/modules/gdnative/include/gdnative/transform2d.h @@ -45,10 +45,19 @@ typedef struct { } godot_transform2d; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> #include <gdnative/variant.h> #include <gdnative/vector2.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_transform2d_new(godot_transform2d *r_dest, const godot_real p_rot, const godot_vector2 *p_pos); void GDAPI godot_transform2d_new_axis_origin(godot_transform2d *r_dest, const godot_vector2 *p_x_axis, const godot_vector2 *p_y_axis, const godot_vector2 *p_origin); diff --git a/modules/gdnative/include/gdnative/variant.h b/modules/gdnative/include/gdnative/variant.h index 7b804c1eaf..3d744ef1f2 100644 --- a/modules/gdnative/include/gdnative/variant.h +++ b/modules/gdnative/include/gdnative/variant.h @@ -99,6 +99,11 @@ typedef struct godot_variant_call_error { godot_variant_type expected; } godot_variant_call_error; +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/array.h> #include <gdnative/basis.h> #include <gdnative/color.h> @@ -119,6 +124,10 @@ typedef struct godot_variant_call_error { #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + godot_variant_type GDAPI godot_variant_get_type(const godot_variant *p_v); void GDAPI godot_variant_new_copy(godot_variant *r_dest, const godot_variant *p_src); diff --git a/modules/gdnative/include/gdnative/vector2.h b/modules/gdnative/include/gdnative/vector2.h index 0af4abae27..07105abaf2 100644 --- a/modules/gdnative/include/gdnative/vector2.h +++ b/modules/gdnative/include/gdnative/vector2.h @@ -45,8 +45,17 @@ typedef struct { } godot_vector2; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + void GDAPI godot_vector2_new(godot_vector2 *r_dest, const godot_real p_x, const godot_real p_y); godot_string GDAPI godot_vector2_as_string(const godot_vector2 *p_self); diff --git a/modules/gdnative/include/gdnative/vector3.h b/modules/gdnative/include/gdnative/vector3.h index a27d516ec5..3ed23778ec 100644 --- a/modules/gdnative/include/gdnative/vector3.h +++ b/modules/gdnative/include/gdnative/vector3.h @@ -45,9 +45,18 @@ typedef struct { } godot_vector3; #endif +// reduce extern "C" nesting for VS2013 +#ifdef __cplusplus +} +#endif + #include <gdnative/basis.h> #include <gdnative/gdnative.h> +#ifdef __cplusplus +extern "C" { +#endif + typedef enum { GODOT_VECTOR3_AXIS_X, GODOT_VECTOR3_AXIS_Y, diff --git a/modules/gdnative/include/nativearvr/godot_nativearvr.h b/modules/gdnative/include/nativearvr/godot_nativearvr.h new file mode 100644 index 0000000000..1a8970d396 --- /dev/null +++ b/modules/gdnative/include/nativearvr/godot_nativearvr.h @@ -0,0 +1,78 @@ +/*************************************************************************/ +/* godot_nativearvr.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ +#ifndef GODOT_NATIVEARVR_H +#define GODOT_NATIVEARVR_H + +#include <gdnative/gdnative.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + void *(*constructor)(godot_object *); + void (*destructor)(void *); + godot_string (*get_name)(const void *); + godot_int (*get_capabilities)(const void *); + godot_bool (*get_anchor_detection_is_enabled)(const void *); + void (*set_anchor_detection_is_enabled)(void *, godot_bool); + godot_bool (*is_stereo)(const void *); + godot_bool (*is_initialized)(const void *); + godot_bool (*initialize)(void *); + void (*uninitialize)(void *); + godot_vector2 (*get_recommended_render_targetsize)(const void *); + godot_transform (*get_transform_for_eye)(void *, godot_int, godot_transform *); + void (*fill_projection_for_eye)(void *, godot_real *, godot_int, godot_real, godot_real, godot_real); + void (*commit_for_eye)(void *, godot_int, godot_rid *, godot_rect2 *); + void (*process)(void *); +} godot_arvr_interface_gdnative; + +void GDAPI godot_arvr_register_interface(const godot_arvr_interface_gdnative *p_interface); + +// helper functions to access ARVRServer data +godot_real GDAPI godot_arvr_get_worldscale(); +godot_transform GDAPI godot_arvr_get_reference_frame(); + +// helper functions for rendering +void GDAPI godot_arvr_blit(godot_int p_eye, godot_rid *p_render_target, godot_rect2 *p_rect); +godot_int GDAPI godot_arvr_get_texid(godot_rid *p_render_target); + +// helper functions for updating ARVR controllers +godot_int GDAPI godot_arvr_add_controller(char *p_device_name, godot_int p_hand, godot_bool p_tracks_orientation, godot_bool p_tracks_position); +void GDAPI godot_arvr_remove_controller(godot_int p_controller_id); +void GDAPI godot_arvr_set_controller_transform(godot_int p_controller_id, godot_transform *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position); +void GDAPI godot_arvr_set_controller_button(godot_int p_controller_id, godot_int p_button, godot_bool p_is_pressed); +void GDAPI godot_arvr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_real p_value, godot_bool p_can_be_negative); + +#ifdef __cplusplus +} +#endif + +#endif /* !GODOT_NATIVEARVR_H */ diff --git a/modules/gdnative/include/pluginscript/godot_pluginscript.h b/modules/gdnative/include/pluginscript/godot_pluginscript.h new file mode 100644 index 0000000000..d1c210529c --- /dev/null +++ b/modules/gdnative/include/pluginscript/godot_pluginscript.h @@ -0,0 +1,171 @@ +/*************************************************************************/ +/* godot_nativescript.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ +#ifndef GODOT_PLUGINSCRIPT_H +#define GODOT_PLUGINSCRIPT_H + +#include <gdnative/gdnative.h> +#include <nativescript/godot_nativescript.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void godot_pluginscript_instance_data; +typedef void godot_pluginscript_script_data; +typedef void godot_pluginscript_language_data; + +// --- Instance --- + +// TODO: use godot_string_name for faster lookup ? +typedef struct { + godot_pluginscript_instance_data *(*init)(godot_pluginscript_script_data *p_data, godot_object *p_owner); + void (*finish)(godot_pluginscript_instance_data *p_data); + + godot_bool (*set_prop)(godot_pluginscript_instance_data *p_data, const godot_string *p_name, const godot_variant *p_value); + godot_bool (*get_prop)(godot_pluginscript_instance_data *p_data, const godot_string *p_name, godot_variant *r_ret); + + godot_variant (*call_method)(godot_pluginscript_instance_data *p_data, + const godot_string_name *p_method, const godot_variant **p_args, + int p_argcount, godot_variant_call_error *r_error); + + void (*notification)(godot_pluginscript_instance_data *p_data, int p_notification); + // TODO: could this rpc mode stuff be moved to the godot_pluginscript_script_manifest ? + godot_method_rpc_mode (*get_rpc_mode)(godot_pluginscript_instance_data *p_data, const godot_string *p_method); + godot_method_rpc_mode (*get_rset_mode)(godot_pluginscript_instance_data *p_data, const godot_string *p_variable); + + //this is used by script languages that keep a reference counter of their own + //you can make make Ref<> not die when it reaches zero, so deleting the reference + //depends entirely from the script. + // Note: You can set thoses function pointer to NULL if not needed. + void (*refcount_incremented)(godot_pluginscript_instance_data *p_data); + bool (*refcount_decremented)(godot_pluginscript_instance_data *p_data); // return true if it can die +} godot_pluginscript_instance_desc; + +// --- Script --- + +typedef struct { + godot_pluginscript_script_data *data; + godot_string_name name; + godot_bool is_tool; + godot_string_name base; + + // Member lines format: {<string>: <int>} + godot_dictionary member_lines; + // Method info dictionary format + // { + // name: <string> + // args: [<dict:property>] + // default_args: [<variant>] + // return: <dict:property> + // flags: <int> + // rpc_mode: <int:godot_method_rpc_mode> + // } + godot_array methods; + // Same format than for methods + godot_array signals; + // Property info dictionary format + // { + // name: <string> + // type: <int:godot_variant_type> + // hint: <int:godot_property_hint> + // hint_string: <string> + // usage: <int:godot_property_usage_flags> + // default_value: <variant> + // rset_mode: <int:godot_method_rpc_mode> + // } + godot_array properties; +} godot_pluginscript_script_manifest; + +typedef struct { + godot_pluginscript_script_manifest (*init)(godot_pluginscript_language_data *p_data, const godot_string *p_path, const godot_string *p_source, godot_error *r_error); + void (*finish)(godot_pluginscript_script_data *p_data); + godot_pluginscript_instance_desc instance_desc; +} godot_pluginscript_script_desc; + +// --- Language --- + +typedef struct { + godot_string_name signature; + godot_int call_count; + godot_int total_time; // In microseconds + godot_int self_time; // In microseconds +} godot_pluginscript_profiling_data; + +typedef struct { + const char *name; + const char *type; + const char *extension; + const char **recognized_extensions; // NULL terminated array + godot_pluginscript_language_data *(*init)(); + void (*finish)(godot_pluginscript_language_data *p_data); + const char **reserved_words; // NULL terminated array + const char **comment_delimiters; // NULL terminated array + const char **string_delimiters; // NULL terminated array + godot_bool has_named_classes; + godot_bool supports_builtin_mode; + + godot_string (*get_template_source_code)(godot_pluginscript_language_data *p_data, const godot_string *p_class_name, const godot_string *p_base_class_name); + godot_bool (*validate)(godot_pluginscript_language_data *p_data, const godot_string *p_script, int *r_line_error, int *r_col_error, godot_string *r_test_error, const godot_string *p_path, godot_pool_string_array *r_functions); + int (*find_function)(godot_pluginscript_language_data *p_data, const godot_string *p_function, const godot_string *p_code); // Can be NULL + godot_string (*make_function)(godot_pluginscript_language_data *p_data, const godot_string *p_class, const godot_string *p_name, const godot_pool_string_array *p_args); + godot_error (*complete_code)(godot_pluginscript_language_data *p_data, const godot_string *p_code, const godot_string *p_base_path, godot_object *p_owner, godot_array *r_options, godot_bool *r_force, godot_string *r_call_hint); + void (*auto_indent_code)(godot_pluginscript_language_data *p_data, godot_string *p_code, int p_from_line, int p_to_line); + + void (*add_global_constant)(godot_pluginscript_language_data *p_data, const godot_string *p_variable, const godot_variant *p_value); + godot_string (*debug_get_error)(godot_pluginscript_language_data *p_data); + int (*debug_get_stack_level_count)(godot_pluginscript_language_data *p_data); + int (*debug_get_stack_level_line)(godot_pluginscript_language_data *p_data, int p_level); + godot_string (*debug_get_stack_level_function)(godot_pluginscript_language_data *p_data, int p_level); + godot_string (*debug_get_stack_level_source)(godot_pluginscript_language_data *p_data, int p_level); + void (*debug_get_stack_level_locals)(godot_pluginscript_language_data *p_data, int p_level, godot_pool_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth); + void (*debug_get_stack_level_members)(godot_pluginscript_language_data *p_data, int p_level, godot_pool_string_array *p_members, godot_array *p_values, int p_max_subitems, int p_max_depth); + void (*debug_get_globals)(godot_pluginscript_language_data *p_data, godot_pool_string_array *p_locals, godot_array *p_values, int p_max_subitems, int p_max_depth); + godot_string (*debug_parse_stack_level_expression)(godot_pluginscript_language_data *p_data, int p_level, const godot_string *p_expression, int p_max_subitems, int p_max_depth); + + // TODO: could this stuff be moved to the godot_pluginscript_language_desc ? + void (*get_public_functions)(godot_pluginscript_language_data *p_data, godot_array *r_functions); + void (*get_public_constants)(godot_pluginscript_language_data *p_data, godot_dictionary *r_constants); + + void (*profiling_start)(godot_pluginscript_language_data *p_data); + void (*profiling_stop)(godot_pluginscript_language_data *p_data); + int (*profiling_get_accumulated_data)(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max); + int (*profiling_get_frame_data)(godot_pluginscript_language_data *p_data, godot_pluginscript_profiling_data *r_info, int p_info_max); + void (*profiling_frame)(godot_pluginscript_language_data *p_data); + + godot_pluginscript_script_desc script_desc; +} godot_pluginscript_language_desc; + +void GDAPI godot_pluginscript_register_language(const godot_pluginscript_language_desc *language_desc); + +#ifdef __cplusplus +} +#endif + +#endif // GODOT_PLUGINSCRIPT_H diff --git a/modules/gdnative/nativearvr/SCsub b/modules/gdnative/nativearvr/SCsub new file mode 100644 index 0000000000..ecc5996108 --- /dev/null +++ b/modules/gdnative/nativearvr/SCsub @@ -0,0 +1,13 @@ +#!/usr/bin/env python + +import os +import methods + +Import('env') +Import('env_modules') + +env_arvr_gdnative = env_modules.Clone() + +env_arvr_gdnative.Append(CPPPATH=['#modules/gdnative/include/']) +env_arvr_gdnative.add_source_files(env.modules_sources, '*.cpp') + diff --git a/modules/gdnative/nativearvr/arvr_interface_gdnative.cpp b/modules/gdnative/nativearvr/arvr_interface_gdnative.cpp new file mode 100644 index 0000000000..ff8bda162f --- /dev/null +++ b/modules/gdnative/nativearvr/arvr_interface_gdnative.cpp @@ -0,0 +1,386 @@ +/*************************************************************************/ +/* arvr_interface_gdnative.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#include "arvr_interface_gdnative.h" +#include "main/input_default.h" +#include "servers/arvr/arvr_positional_tracker.h" +#include "servers/visual/visual_server_global.h" + +ARVRInterfaceGDNative::ARVRInterfaceGDNative() { + // testing + printf("Construct gdnative interface\n"); + + // we won't have our data pointer until our library gets set + data = NULL; + + interface = NULL; +} + +ARVRInterfaceGDNative::~ARVRInterfaceGDNative() { + printf("Destruct gdnative interface\n"); + + if (is_initialized()) { + uninitialize(); + }; + + // cleanup after ourselves + cleanup(); +} + +void ARVRInterfaceGDNative::cleanup() { + if (interface != NULL) { + interface->destructor(data); + data = NULL; + interface = NULL; + } +} + +void ARVRInterfaceGDNative::set_interface(const godot_arvr_interface_gdnative *p_interface) { + // this should only be called once, just being paranoid.. + if (interface) { + cleanup(); + } + + // bind to our interface + interface = p_interface; + + // Now we do our constructing... + data = interface->constructor((godot_object *)this); +} + +StringName ARVRInterfaceGDNative::get_name() const { + + ERR_FAIL_COND_V(interface == NULL, StringName()); + + godot_string result = interface->get_name(data); + + StringName name = *(String *)&result; + + godot_string_destroy(&result); + + return name; +} + +int ARVRInterfaceGDNative::get_capabilities() const { + int capabilities; + + ERR_FAIL_COND_V(interface == NULL, 0); // 0 = None + + capabilities = interface->get_capabilities(data); + + return capabilities; +} + +bool ARVRInterfaceGDNative::get_anchor_detection_is_enabled() const { + bool enabled; + + ERR_FAIL_COND_V(interface == NULL, false); + + enabled = interface->get_anchor_detection_is_enabled(data); + + return enabled; +} + +void ARVRInterfaceGDNative::set_anchor_detection_is_enabled(bool p_enable) { + + ERR_FAIL_COND(interface == NULL); + + interface->set_anchor_detection_is_enabled(data, p_enable); +} + +bool ARVRInterfaceGDNative::is_stereo() { + bool stereo; + + ERR_FAIL_COND_V(interface == NULL, false); + + stereo = interface->is_stereo(data); + + return stereo; +} + +bool ARVRInterfaceGDNative::is_initialized() { + bool initialized; + + ERR_FAIL_COND_V(interface == NULL, false); + + initialized = interface->is_initialized(data); + + return initialized; +} + +bool ARVRInterfaceGDNative::initialize() { + bool initialized; + + ERR_FAIL_COND_V(interface == NULL, false); + + initialized = interface->initialize(data); + + if (initialized) { + // if we successfully initialize our interface and we don't have a primary interface yet, this becomes our primary interface + + ARVRServer *arvr_server = ARVRServer::get_singleton(); + if ((arvr_server != NULL) && (arvr_server->get_primary_interface() == NULL)) { + arvr_server->set_primary_interface(this); + }; + }; + + return initialized; +} + +void ARVRInterfaceGDNative::uninitialize() { + ERR_FAIL_COND(interface == NULL); + + ARVRServer *arvr_server = ARVRServer::get_singleton(); + if (arvr_server != NULL) { + // Whatever happens, make sure this is no longer our primary interface + arvr_server->clear_primary_interface_if(this); + } + + interface->uninitialize(data); +} + +Size2 ARVRInterfaceGDNative::get_recommended_render_targetsize() { + + ERR_FAIL_COND_V(interface == NULL, Size2()); + + godot_vector2 result = interface->get_recommended_render_targetsize(data); + Vector2 *vec = (Vector2 *)&result; + + return *vec; +} + +Transform ARVRInterfaceGDNative::get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform) { + Transform *ret; + + ERR_FAIL_COND_V(interface == NULL, Transform()); + + godot_transform t = interface->get_transform_for_eye(data, (int)p_eye, (godot_transform *)&p_cam_transform); + + ret = (Transform *)&t; + + return *ret; +} + +CameraMatrix ARVRInterfaceGDNative::get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far) { + CameraMatrix cm; + + ERR_FAIL_COND_V(interface == NULL, CameraMatrix()); + + interface->fill_projection_for_eye(data, (godot_real *)cm.matrix, (godot_int)p_eye, p_aspect, p_z_near, p_z_far); + + return cm; +} + +void ARVRInterfaceGDNative::commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect) { + + ERR_FAIL_COND(interface == NULL); + + interface->commit_for_eye(data, (godot_int)p_eye, (godot_rid *)&p_render_target, (godot_rect2 *)&p_screen_rect); +} + +void ARVRInterfaceGDNative::process() { + ERR_FAIL_COND(interface == NULL); + + interface->process(data); +} + +///////////////////////////////////////////////////////////////////////////////////// +// some helper callbacks + +extern "C" { + +void GDAPI godot_arvr_register_interface(const godot_arvr_interface_gdnative *p_interface) { + Ref<ARVRInterfaceGDNative> new_interface; + new_interface.instance(); + new_interface->set_interface((godot_arvr_interface_gdnative * const)p_interface); + ARVRServer::get_singleton()->add_interface(new_interface); +} + +godot_real GDAPI godot_arvr_get_worldscale() { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL_V(arvr_server, 1.0); + + return arvr_server->get_world_scale(); +} + +godot_transform GDAPI godot_arvr_get_reference_frame() { + godot_transform reference_frame; + Transform *reference_frame_ptr = (Transform *)&reference_frame; + + ARVRServer *arvr_server = ARVRServer::get_singleton(); + if (arvr_server != NULL) { + *reference_frame_ptr = arvr_server->get_reference_frame(); + } else { + godot_transform_new_identity(&reference_frame); + } + + return reference_frame; +} + +void GDAPI godot_arvr_blit(godot_int p_eye, godot_rid *p_render_target, godot_rect2 *p_rect) { + // blits out our texture as is, handy for preview display of one of the eyes that is already rendered with lens distortion on an external HMD + ARVRInterface::Eyes eye = (ARVRInterface::Eyes)p_eye; + RID *render_target = (RID *)p_render_target; + Rect2 screen_rect = *(Rect2 *)p_rect; + + if (eye == ARVRInterface::EYE_LEFT) { + screen_rect.size.x /= 2.0; + } else if (p_eye == ARVRInterface::EYE_RIGHT) { + screen_rect.size.x /= 2.0; + screen_rect.position.x += screen_rect.size.x; + } + + VSG::rasterizer->set_current_render_target(RID()); + VSG::rasterizer->blit_render_target_to_screen(*render_target, screen_rect, 0); +} + +godot_int GDAPI godot_arvr_get_texid(godot_rid *p_render_target) { + // In order to send off our textures to display on our hardware we need the opengl texture ID instead of the render target RID + // This is a handy function to expose that. + RID *render_target = (RID *)p_render_target; + + RID eye_texture = VSG::storage->render_target_get_texture(*render_target); + uint32_t texid = VS::get_singleton()->texture_get_texid(eye_texture); + + return texid; +} + +godot_int GDAPI godot_arvr_add_controller(char *p_device_name, godot_int p_hand, godot_bool p_tracks_orientation, godot_bool p_tracks_position) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL_V(arvr_server, 0); + + InputDefault *input = (InputDefault *)Input::get_singleton(); + ERR_FAIL_NULL_V(input, 0); + + ARVRPositionalTracker *new_tracker = memnew(ARVRPositionalTracker); + new_tracker->set_name(p_device_name); + new_tracker->set_type(ARVRServer::TRACKER_CONTROLLER); + if (p_hand == 1) { + new_tracker->set_hand(ARVRPositionalTracker::TRACKER_LEFT_HAND); + } else if (p_hand == 2) { + new_tracker->set_hand(ARVRPositionalTracker::TRACKER_RIGHT_HAND); + } + + // also register as joystick... + int joyid = input->get_unused_joy_id(); + if (joyid != -1) { + new_tracker->set_joy_id(joyid); + input->joy_connection_changed(joyid, true, p_device_name, ""); + } + + if (p_tracks_orientation) { + Basis orientation; + new_tracker->set_orientation(orientation); + } + if (p_tracks_position) { + Vector3 position; + new_tracker->set_position(position); + } + + // add our tracker to our server and remember its pointer + arvr_server->add_tracker(new_tracker); + + // note, this ID is only unique within controllers! + return new_tracker->get_tracker_id(); +} + +void GDAPI godot_arvr_remove_controller(godot_int p_controller_id) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL(arvr_server); + + InputDefault *input = (InputDefault *)Input::get_singleton(); + ERR_FAIL_NULL(input); + + ARVRPositionalTracker *remove_tracker = arvr_server->find_by_type_and_id(ARVRServer::TRACKER_CONTROLLER, p_controller_id); + if (remove_tracker != NULL) { + // unset our joystick if applicable + int joyid = remove_tracker->get_joy_id(); + if (joyid != -1) { + input->joy_connection_changed(joyid, false, "", ""); + remove_tracker->set_joy_id(-1); + } + + // remove our tracker from our server + arvr_server->remove_tracker(remove_tracker); + memdelete(remove_tracker); + } +} + +void GDAPI godot_arvr_set_controller_transform(godot_int p_controller_id, godot_transform *p_transform, godot_bool p_tracks_orientation, godot_bool p_tracks_position) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL(arvr_server); + + ARVRPositionalTracker *tracker = arvr_server->find_by_type_and_id(ARVRServer::TRACKER_CONTROLLER, p_controller_id); + if (tracker != NULL) { + Transform *transform = (Transform *)p_transform; + if (p_tracks_orientation) { + tracker->set_orientation(transform->basis); + } + if (p_tracks_position) { + tracker->set_position(transform->origin); + } + } +} + +void GDAPI godot_arvr_set_controller_button(godot_int p_controller_id, godot_int p_button, godot_bool p_is_pressed) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL(arvr_server); + + InputDefault *input = (InputDefault *)Input::get_singleton(); + ERR_FAIL_NULL(input); + + ARVRPositionalTracker *tracker = arvr_server->find_by_type_and_id(ARVRServer::TRACKER_CONTROLLER, p_controller_id); + if (tracker != NULL) { + int joyid = tracker->get_joy_id(); + if (joyid != -1) { + input->joy_button(joyid, p_button, p_is_pressed); + } + } +} + +void GDAPI godot_arvr_set_controller_axis(godot_int p_controller_id, godot_int p_axis, godot_real p_value, godot_bool p_can_be_negative) { + ARVRServer *arvr_server = ARVRServer::get_singleton(); + ERR_FAIL_NULL(arvr_server); + + InputDefault *input = (InputDefault *)Input::get_singleton(); + ERR_FAIL_NULL(input); + + ARVRPositionalTracker *tracker = arvr_server->find_by_type_and_id(ARVRServer::TRACKER_CONTROLLER, p_controller_id); + if (tracker != NULL) { + int joyid = tracker->get_joy_id(); + if (joyid != -1) { + InputDefault::JoyAxis jx; + jx.min = p_can_be_negative ? -1 : 0; + jx.value = p_value; + input->joy_axis(joyid, p_axis, jx); + } + } +} +} diff --git a/modules/gdnative/nativearvr/arvr_interface_gdnative.h b/modules/gdnative/nativearvr/arvr_interface_gdnative.h new file mode 100644 index 0000000000..e45b51e070 --- /dev/null +++ b/modules/gdnative/nativearvr/arvr_interface_gdnative.h @@ -0,0 +1,86 @@ +/*************************************************************************/ +/* arvr_interface_gdnative.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#ifndef ARVR_INTERFACE_GDNATIVE_H +#define ARVR_INTERFACE_GDNATIVE_H + +#include "modules/gdnative/gdnative.h" +#include "servers/arvr/arvr_interface.h" + +/** + @authors Hinsbart & Karroffel & Mux213 + + This subclass of our AR/VR interface forms a bridge to GDNative. +*/ + +class ARVRInterfaceGDNative : public ARVRInterface { + GDCLASS(ARVRInterfaceGDNative, ARVRInterface) + + void cleanup(); + +protected: + const godot_arvr_interface_gdnative *interface; + void *data; + +public: + /** general interface information **/ + ARVRInterfaceGDNative(); + ~ARVRInterfaceGDNative(); + + void set_interface(const godot_arvr_interface_gdnative *p_interface); + + virtual StringName get_name() const; + virtual int get_capabilities() const; + + virtual bool is_initialized(); + virtual bool initialize(); + virtual void uninitialize(); + + /** specific to AR **/ + virtual bool get_anchor_detection_is_enabled() const; + virtual void set_anchor_detection_is_enabled(bool p_enable); + + /** rendering and internal **/ + virtual Size2 get_recommended_render_targetsize(); + virtual bool is_stereo(); + virtual Transform get_transform_for_eye(ARVRInterface::Eyes p_eye, const Transform &p_cam_transform); + + // we expose a PoolVector<float> version of this function to GDNative + PoolVector<float> _get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far); + + // and a CameraMatrix version to ARVRServer + virtual CameraMatrix get_projection_for_eye(ARVRInterface::Eyes p_eye, real_t p_aspect, real_t p_z_near, real_t p_z_far); + + virtual void commit_for_eye(ARVRInterface::Eyes p_eye, RID p_render_target, const Rect2 &p_screen_rect); + + virtual void process(); +}; + +#endif // ARVR_INTERFACE_GDNATIVE_H diff --git a/modules/gdnative/nativearvr/config.py b/modules/gdnative/nativearvr/config.py new file mode 100644 index 0000000000..4d1bdfe4d1 --- /dev/null +++ b/modules/gdnative/nativearvr/config.py @@ -0,0 +1,5 @@ +def can_build(platform): + return True + +def configure(env): + pass diff --git a/modules/gdnative/nativearvr/register_types.cpp b/modules/gdnative/nativearvr/register_types.cpp new file mode 100644 index 0000000000..c7d7847a21 --- /dev/null +++ b/modules/gdnative/nativearvr/register_types.cpp @@ -0,0 +1,39 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#include "register_types.h" +#include "arvr_interface_gdnative.h" + +void register_nativearvr_types() { + ClassDB::register_class<ARVRInterfaceGDNative>(); +} + +void unregister_nativearvr_types() { +} diff --git a/modules/gdnative/nativearvr/register_types.h b/modules/gdnative/nativearvr/register_types.h new file mode 100644 index 0000000000..5e7557c7e9 --- /dev/null +++ b/modules/gdnative/nativearvr/register_types.h @@ -0,0 +1,32 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +void register_nativearvr_types(); +void unregister_nativearvr_types(); diff --git a/modules/gdnative/nativescript/SCsub b/modules/gdnative/nativescript/SCsub index 178afec64a..ee3b9c351d 100644 --- a/modules/gdnative/nativescript/SCsub +++ b/modules/gdnative/nativescript/SCsub @@ -4,7 +4,6 @@ Import('env') mod_env = env.Clone() mod_env.add_source_files(env.modules_sources, "*.cpp") -mod_env.Append(CPPPATH='#modules/gdnative') mod_env.Append(CPPFLAGS=['-DGDAPI_BUILT_IN']) if "platform" in env and env["platform"] in ["x11", "iphone"]: diff --git a/modules/gdnative/nativescript/api_generator.cpp b/modules/gdnative/nativescript/api_generator.cpp index 9a956ff594..63fb71feb6 100644 --- a/modules/gdnative/nativescript/api_generator.cpp +++ b/modules/gdnative/nativescript/api_generator.cpp @@ -31,7 +31,7 @@ #ifdef TOOLS_ENABLED -#include "class_db.h" +#include "core/class_db.h" #include "core/global_constants.h" #include "core/pair.h" #include "core/project_settings.h" diff --git a/modules/gdnative/nativescript/api_generator.h b/modules/gdnative/nativescript/api_generator.h index 56c2d786e6..a8e2eaf0bf 100644 --- a/modules/gdnative/nativescript/api_generator.h +++ b/modules/gdnative/nativescript/api_generator.h @@ -30,8 +30,8 @@ #ifndef API_GENERATOR_H #define API_GENERATOR_H +#include "core/typedefs.h" #include "core/ustring.h" -#include "typedefs.h" Error generate_c_api(const String &p_path); diff --git a/modules/gdnative/nativescript/nativescript.cpp b/modules/gdnative/nativescript/nativescript.cpp index b9bd65af53..c1df7def2e 100644 --- a/modules/gdnative/nativescript/nativescript.cpp +++ b/modules/gdnative/nativescript/nativescript.cpp @@ -31,11 +31,11 @@ #include "gdnative/gdnative.h" -#include "global_constants.h" +#include "core/global_constants.h" +#include "core/project_settings.h" #include "io/file_access_encrypted.h" #include "os/file_access.h" #include "os/os.h" -#include "project_settings.h" #include "scene/main/scene_tree.h" #include "scene/resources/scene_format_text.h" @@ -137,7 +137,6 @@ bool NativeScript::can_instance() const { #endif } -// TODO(karroffel): implement this Ref<Script> NativeScript::get_base_script() const { NativeScriptDesc *script_data = get_script_desc(); @@ -271,10 +270,6 @@ bool NativeScript::is_tool() const { return false; } -String NativeScript::get_node_type() const { - return ""; // NOTE(karroffel): uhm? -} - ScriptLanguage *NativeScript::get_language() const { return NativeScriptLanguage::get_singleton(); } @@ -909,6 +904,9 @@ Script *NativeScriptLanguage::create_script() const { bool NativeScriptLanguage::has_named_classes() const { return true; } +bool NativeScriptLanguage::supports_builtin_mode() const { + return true; +} int NativeScriptLanguage::find_function(const String &p_function, const String &p_code) const { return -1; } @@ -1010,17 +1008,15 @@ void NativeScriptLanguage::init_library(const Ref<GDNativeLibrary> &lib) { if (!library_script_users.has(lib_path)) library_script_users.insert(lib_path, Set<NativeScript *>()); - void *args[1] = { - (void *)&lib_path - }; + void *proc_ptr; - // here the library registers all the classes and stuff. - gdn->call_native_raw(_init_call_type, - _init_call_name, - NULL, - 1, - args, - NULL); + Error err = gdn->get_symbol(_init_call_name, proc_ptr); + + if (err != OK) { + ERR_PRINT(String("No " + _init_call_name + " in \"" + lib_path + "\" found").utf8().get_data()); + } else { + ((void (*)(godot_string *))proc_ptr)((godot_string *)&lib_path); + } } else { // already initialized. Nice. } @@ -1053,13 +1049,13 @@ void NativeScriptLanguage::call_libraries_cb(const StringName &name) { // library_gdnatives is modified only from the main thread, so it's safe not to use mutex here for (Map<String, Ref<GDNative> >::Element *L = library_gdnatives.front(); L; L = L->next()) { if (L->get()->is_initialized()) { - L->get()->call_native_raw( - _noarg_call_type, - name, - NULL, - 0, - NULL, - NULL); + + void *proc_ptr; + Error err = L->get()->get_symbol(name, proc_ptr); + + if (!err) { + ((void (*)())proc_ptr)(); + } } } } @@ -1142,12 +1138,14 @@ void NativeReloadNode::_notification(int p_what) { }; // here the library registers all the classes and stuff. - L->get()->call_native_raw(NSL->_init_call_type, - NSL->_init_call_name, - NULL, - 1, - args, - NULL); + + void *proc_ptr; + Error err = L->get()->get_symbol("godot_nativescript_init", proc_ptr); + if (err != OK) { + ERR_PRINT(String("No godot_nativescript_init in \"" + L->key() + "\" found").utf8().get_data()); + } else { + ((void (*)(void *))proc_ptr)((void *)&L->key()); + } for (Map<String, Set<NativeScript *> >::Element *U = NSL->library_script_users.front(); U; U = U->next()) { for (Set<NativeScript *>::Element *S = U->get().front(); S; S = S->next()) { diff --git a/modules/gdnative/nativescript/nativescript.h b/modules/gdnative/nativescript/nativescript.h index bc7e850d3e..e8fc9e6880 100644 --- a/modules/gdnative/nativescript/nativescript.h +++ b/modules/gdnative/nativescript/nativescript.h @@ -30,14 +30,14 @@ #ifndef NATIVE_SCRIPT_H #define NATIVE_SCRIPT_H +#include "core/resource.h" +#include "core/script_language.h" +#include "core/self_list.h" #include "io/resource_loader.h" #include "io/resource_saver.h" #include "ordered_hash_map.h" #include "os/thread_safe.h" -#include "resource.h" #include "scene/main/node.h" -#include "script_language.h" -#include "self_list.h" #include "modules/gdnative/gdnative.h" #include <nativescript/godot_nativescript.h> @@ -142,8 +142,6 @@ public: virtual bool is_tool() const; - virtual String get_node_type() const; - virtual ScriptLanguage *get_language() const; virtual bool has_script_signal(const StringName &p_signal) const; @@ -271,6 +269,7 @@ public: virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const; virtual Script *create_script() const; virtual bool has_named_classes() const; + virtual bool supports_builtin_mode() const; virtual int find_function(const String &p_function, const String &p_code) const; virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; diff --git a/modules/gdnative/nativescript/register_types.cpp b/modules/gdnative/nativescript/register_types.cpp index b846710ab8..d734bba810 100644 --- a/modules/gdnative/nativescript/register_types.cpp +++ b/modules/gdnative/nativescript/register_types.cpp @@ -38,53 +38,6 @@ NativeScriptLanguage *native_script_language; -typedef void (*native_script_init_fn)(void *); - -void init_call_cb(void *p_handle, godot_string *p_proc_name, void *p_data, int p_num_args, void **args, void *r_ret) { - if (p_handle == NULL) { - ERR_PRINT("No valid library handle, can't call nativescript init procedure"); - return; - } - - void *library_proc; - Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( - p_handle, - *(String *)p_proc_name, - library_proc, - true); // we print our own message - if (err != OK) { - ERR_PRINT((String("GDNative procedure \"" + *(String *)p_proc_name) + "\" does not exists and can't be called").utf8().get_data()); - return; - } - - native_script_init_fn fn = (native_script_init_fn)library_proc; - - fn(args[0]); -} - -typedef void (*native_script_empty_callback)(); - -void noarg_call_cb(void *p_handle, godot_string *p_proc_name, void *p_data, int p_num_args, void **args, void *r_ret) { - if (p_handle == NULL) { - ERR_PRINT("No valid library handle, can't call nativescript callback"); - return; - } - - void *library_proc; - Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( - p_handle, - *(String *)p_proc_name, - library_proc, - true); - if (err != OK) { - // it's fine if thread callbacks are not present in the library. - return; - } - - native_script_empty_callback fn = (native_script_empty_callback)library_proc; - fn(); -} - ResourceFormatLoaderNativeScript *resource_loader_gdns = NULL; ResourceFormatSaverNativeScript *resource_saver_gdns = NULL; @@ -95,9 +48,6 @@ void register_nativescript_types() { ScriptServer::register_language(native_script_language); - GDNativeCallRegistry::singleton->register_native_raw_call_type(native_script_language->_init_call_type, init_call_cb); - GDNativeCallRegistry::singleton->register_native_raw_call_type(native_script_language->_noarg_call_type, noarg_call_cb); - resource_saver_gdns = memnew(ResourceFormatSaverNativeScript); ResourceSaver::add_resource_format_saver(resource_saver_gdns); diff --git a/modules/gdnative/pluginscript/SCsub b/modules/gdnative/pluginscript/SCsub new file mode 100644 index 0000000000..2031a4236b --- /dev/null +++ b/modules/gdnative/pluginscript/SCsub @@ -0,0 +1,9 @@ +#!/usr/bin/env python + +Import('env') +Import('env_modules') + +env_pluginscript = env_modules.Clone() + +env_pluginscript.Append(CPPPATH=['#modules/gdnative/include/']) +env_pluginscript.add_source_files(env.modules_sources, '*.cpp') diff --git a/modules/gdnative/pluginscript/pluginscript_instance.cpp b/modules/gdnative/pluginscript/pluginscript_instance.cpp new file mode 100644 index 0000000000..8f01350826 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_instance.cpp @@ -0,0 +1,181 @@ +/*************************************************************************/ +/* pluginscript_instance.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +// Godot imports +#include "core/os/os.h" +#include "core/variant.h" +// PluginScript imports +#include "pluginscript_instance.h" +#include "pluginscript_language.h" +#include "pluginscript_script.h" + +bool PluginScriptInstance::set(const StringName &p_name, const Variant &p_value) { + String name = String(p_name); + return _desc->set_prop(_data, (const godot_string *)&name, (const godot_variant *)&p_value); +} + +bool PluginScriptInstance::get(const StringName &p_name, Variant &r_ret) const { + String name = String(p_name); + return _desc->get_prop(_data, (const godot_string *)&name, (godot_variant *)&r_ret); +} + +Ref<Script> PluginScriptInstance::get_script() const { + return _script; +} + +ScriptLanguage *PluginScriptInstance::get_language() { + return _script->get_language(); +} + +Variant::Type PluginScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { + if (!_script->has_property(p_name)) { + if (r_is_valid) { + *r_is_valid = false; + } + return Variant::NIL; + } + if (r_is_valid) { + *r_is_valid = true; + } + return _script->get_property_info(p_name).type; +} + +void PluginScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { + _script->get_script_property_list(p_properties); +} + +void PluginScriptInstance::get_method_list(List<MethodInfo> *p_list) const { + _script->get_script_method_list(p_list); +} + +bool PluginScriptInstance::has_method(const StringName &p_method) const { + return _script->has_method(p_method); +} + +Variant PluginScriptInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error) { + // TODO: optimize when calling a Godot method from Godot to avoid param conversion ? + godot_variant ret = _desc->call_method( + _data, (godot_string_name *)&p_method, (const godot_variant **)p_args, + p_argcount, (godot_variant_call_error *)&r_error); + Variant *var_ret = (Variant *)&ret; + return *var_ret; +} + +#if 0 // TODO: Don't rely on default implementations provided by ScriptInstance ? +void PluginScriptInstance::call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount) { + +#if 0 + PluginScript *sptr=script.ptr(); + Variant::CallError ce; + + while(sptr) { + Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + if (E) { + E->get()->call(this,p_args,p_argcount,ce); + } + sptr = sptr->_base; + } +#endif + +} + +#if 0 +void PluginScriptInstance::_ml_call_reversed(PluginScript *sptr,const StringName& p_method,const Variant** p_args,int p_argcount) { + + if (sptr->_base) + _ml_call_reversed(sptr->_base,p_method,p_args,p_argcount); + + Variant::CallError ce; + + Map<StringName,GDFunction*>::Element *E = sptr->member_functions.find(p_method); + if (E) { + E->get()->call(this,p_args,p_argcount,ce); + } + +} +#endif + + +void PluginScriptInstance::call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount) { + +#if 0 + if (script.ptr()) { + _ml_call_reversed(script.ptr(),p_method,p_args,p_argcount); + } +#endif +} +#endif // Multilevel stuff + +void PluginScriptInstance::notification(int p_notification) { + _desc->notification(_data, p_notification); +} + +ScriptInstance::RPCMode PluginScriptInstance::get_rpc_mode(const StringName &p_method) const { + return _script->get_rpc_mode(p_method); +} + +ScriptInstance::RPCMode PluginScriptInstance::get_rset_mode(const StringName &p_variable) const { + return _script->get_rset_mode(p_variable); +} + +void PluginScriptInstance::refcount_incremented() { + if (_desc->refcount_decremented) { + _desc->refcount_incremented(_data); + } +} + +bool PluginScriptInstance::refcount_decremented() { + // Return true if it can die + if (_desc->refcount_decremented) { + return _desc->refcount_decremented(_data); + } + return true; +} + +PluginScriptInstance::PluginScriptInstance() { +} + +bool PluginScriptInstance::init(PluginScript *p_script, Object *p_owner) { + _owner = p_owner; + _owner_variant = Variant(p_owner); + _script = Ref<PluginScript>(p_script); + _desc = &p_script->_desc->instance_desc; + _data = _desc->init(p_script->_data, (godot_object *)p_owner); + ERR_FAIL_COND_V(_data == NULL, false); + p_owner->set_script_instance(this); + return true; +} + +PluginScriptInstance::~PluginScriptInstance() { + _desc->finish(_data); + _script->_language->lock(); + _script->_instances.erase(_owner); + _script->_language->unlock(); +} diff --git a/modules/gdnative/pluginscript/pluginscript_instance.h b/modules/gdnative/pluginscript/pluginscript_instance.h new file mode 100644 index 0000000000..68696b4417 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_instance.h @@ -0,0 +1,90 @@ +/*************************************************************************/ +/* pluginscript_instance.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#ifndef PLUGINSCRIPT_INSTANCE_H +#define PLUGINSCRIPT_INSTANCE_H + +// Godot imports +#include "core/script_language.h" +// PluginScript imports +#include <pluginscript/godot_pluginscript.h> + +class PluginScript; + +class PluginScriptInstance : public ScriptInstance { + friend class PluginScript; + +private: + Ref<PluginScript> _script; + Object *_owner; + Variant _owner_variant; + godot_pluginscript_instance_data *_data; + const godot_pluginscript_instance_desc *_desc; + +public: + _FORCE_INLINE_ Object *get_owner() { return _owner; } + + virtual bool set(const StringName &p_name, const Variant &p_value); + virtual bool get(const StringName &p_name, Variant &r_ret) const; + virtual void get_property_list(List<PropertyInfo> *p_properties) const; + virtual Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid = NULL) const; + + virtual void get_method_list(List<MethodInfo> *p_list) const; + virtual bool has_method(const StringName &p_method) const; + + virtual Variant call(const StringName &p_method, const Variant **p_args, int p_argcount, Variant::CallError &r_error); +#if 0 + // Rely on default implementations provided by ScriptInstance for the moment. + // Note that multilevel call could be removed in 3.0 release, so stay tunned + // (see https://godotengine.org/qa/9244/can-override-the-_ready-and-_process-functions-child-classes) + virtual void call_multilevel(const StringName& p_method,const Variant** p_args,int p_argcount); + virtual void call_multilevel_reversed(const StringName& p_method,const Variant** p_args,int p_argcount); +#endif + + virtual void notification(int p_notification); + + virtual Ref<Script> get_script() const; + + virtual ScriptLanguage *get_language(); + + void set_path(const String &p_path); + + virtual RPCMode get_rpc_mode(const StringName &p_method) const; + virtual RPCMode get_rset_mode(const StringName &p_variable) const; + + virtual void refcount_incremented(); + virtual bool refcount_decremented(); + + PluginScriptInstance(); + bool init(PluginScript *p_script, Object *p_owner); + virtual ~PluginScriptInstance(); +}; + +#endif // PLUGINSCRIPT_INSTANCE_H diff --git a/modules/gdnative/pluginscript/pluginscript_language.cpp b/modules/gdnative/pluginscript/pluginscript_language.cpp new file mode 100644 index 0000000000..40feb5ae43 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_language.cpp @@ -0,0 +1,435 @@ +/*************************************************************************/ +/* pluginscript_language.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +// Godot imports +#include "core/os/file_access.h" +#include "core/os/os.h" +#include "core/project_settings.h" +// PluginScript imports +#include "pluginscript_language.h" +#include "pluginscript_script.h" + +String PluginScriptLanguage::get_name() const { + return String(_desc.name); +} + +void PluginScriptLanguage::init() { + _data = _desc.init(); +} + +String PluginScriptLanguage::get_type() const { + return String(_desc.type); +} + +String PluginScriptLanguage::get_extension() const { + return String(_desc.extension); +} + +Error PluginScriptLanguage::execute_file(const String &p_path) { + // TODO: pretty sure this method is totally deprecated and should be removed... + return OK; +} + +void PluginScriptLanguage::finish() { + _desc.finish(_data); +} + +/* EDITOR FUNCTIONS */ + +void PluginScriptLanguage::get_reserved_words(List<String> *p_words) const { + if (_desc.reserved_words) { + const char **w = _desc.reserved_words; + while (*w) { + p_words->push_back(*w); + w++; + } + } +} + +void PluginScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const { + if (_desc.comment_delimiters) { + const char **w = _desc.comment_delimiters; + while (*w) { + p_delimiters->push_back(*w); + w++; + } + } +} + +void PluginScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const { + if (_desc.string_delimiters) { + const char **w = _desc.string_delimiters; + while (*w) { + p_delimiters->push_back(*w); + w++; + } + } +} + +Ref<Script> PluginScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const { + Script *ns = create_script(); + Ref<Script> script = Ref<Script>(ns); + if (_desc.get_template_source_code) { + godot_string src = _desc.get_template_source_code(_data, (godot_string *)&p_class_name, (godot_string *)&p_base_class_name); + script->set_source_code(*(String *)&src); + } + return script; +} + +bool PluginScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { + PoolStringArray functions; + if (_desc.validate) { + bool ret = _desc.validate( + _data, + (godot_string *)&p_script, + &r_line_error, + &r_col_error, + (godot_string *)&r_test_error, + (godot_string *)&p_path, + (godot_pool_string_array *)&functions); + for (int i = 0; i < functions.size(); i++) { + r_functions->push_back(functions[i]); + } + return ret; + } + return true; +} + +Script *PluginScriptLanguage::create_script() const { + PluginScript *script = memnew(PluginScript()); + // I'm hurting kittens doing this I guess... + script->init(const_cast<PluginScriptLanguage *>(this)); + return script; +} + +bool PluginScriptLanguage::has_named_classes() const { + return _desc.has_named_classes; +} + +bool PluginScriptLanguage::supports_builtin_mode() const { + return _desc.supports_builtin_mode; +} + +int PluginScriptLanguage::find_function(const String &p_function, const String &p_code) const { + if (_desc.find_function) { + return _desc.find_function(_data, (godot_string *)&p_function, (godot_string *)&p_code); + } + return -1; +} + +String PluginScriptLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { + if (_desc.make_function) { + godot_string tmp = _desc.make_function(_data, (godot_string *)&p_class, (godot_string *)&p_name, (godot_pool_string_array *)&p_args); + String ret = *(String *)&tmp; + godot_string_destroy(&tmp); + return ret; + } + return String(); +} + +Error PluginScriptLanguage::complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint) { + if (_desc.complete_code) { + Array options; + godot_error tmp = _desc.complete_code( + _data, + (godot_string *)&p_code, + (godot_string *)&p_base_path, + (godot_object *)p_owner, + (godot_array *)&options, + &r_force, + (godot_string *)&r_call_hint); + for (int i = 0; i < options.size(); i++) { + r_options->push_back(String(options[i])); + } + Error err = *(Error *)tmp; + return err; + } + return ERR_UNAVAILABLE; +} + +void PluginScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const { + if (_desc.auto_indent_code) { + _desc.auto_indent_code(_data, (godot_string *)&p_code, p_from_line, p_to_line); + } + return; +} + +void PluginScriptLanguage::add_global_constant(const StringName &p_variable, const Variant &p_value) { + const String variable = String(p_variable); + _desc.add_global_constant(_data, (godot_string *)&variable, (godot_variant *)&p_value); +} + +/* LOADER FUNCTIONS */ + +void PluginScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const { + for (int i = 0; _desc.recognized_extensions[i]; ++i) { + p_extensions->push_back(String(_desc.recognized_extensions[i])); + } +} + +void PluginScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const { + // TODO: provid this statically in `godot_pluginscript_language_desc` ? + if (_desc.get_public_functions) { + Array functions; + _desc.get_public_functions(_data, (godot_array *)&functions); + for (int i = 0; i < functions.size(); i++) { + MethodInfo mi = MethodInfo::from_dict(functions[i]); + p_functions->push_back(mi); + } + } +} + +void PluginScriptLanguage::get_public_constants(List<Pair<String, Variant> > *p_constants) const { + // TODO: provid this statically in `godot_pluginscript_language_desc` ? + if (_desc.get_public_constants) { + Dictionary constants; + _desc.get_public_constants(_data, (godot_dictionary *)&constants); + for (const Variant *key = constants.next(); key; key = constants.next(key)) { + Variant value = constants[key]; + p_constants->push_back(Pair<String, Variant>(*key, value)); + } + } +} + +void PluginScriptLanguage::profiling_start() { +#ifdef DEBUG_ENABLED + if (_desc.profiling_start) { + lock(); + _desc.profiling_start(_data); + unlock(); + } +#endif +} + +void PluginScriptLanguage::profiling_stop() { +#ifdef DEBUG_ENABLED + if (_desc.profiling_stop) { + lock(); + _desc.profiling_stop(_data); + unlock(); + } +#endif +} + +int PluginScriptLanguage::profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max) { + int info_count = 0; +#ifdef DEBUG_ENABLED + if (_desc.profiling_get_accumulated_data) { + godot_pluginscript_profiling_data *info = (godot_pluginscript_profiling_data *)memalloc( + sizeof(godot_pluginscript_profiling_data) * p_info_max); + info_count = _desc.profiling_get_accumulated_data(_data, info, p_info_max); + for (int i = 0; i < info_count; ++i) { + p_info_arr[i].signature = *(StringName *)&info[i].signature; + p_info_arr[i].call_count = info[i].call_count; + p_info_arr[i].total_time = info[i].total_time; + p_info_arr[i].self_time = info[i].self_time; + godot_string_name_destroy(&info[i].signature); + } + } +#endif + return info_count; +} + +int PluginScriptLanguage::profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max) { + int info_count = 0; +#ifdef DEBUG_ENABLED + if (_desc.profiling_get_frame_data) { + godot_pluginscript_profiling_data *info = (godot_pluginscript_profiling_data *)memalloc( + sizeof(godot_pluginscript_profiling_data) * p_info_max); + info_count = _desc.profiling_get_frame_data(_data, info, p_info_max); + for (int i = 0; i < info_count; ++i) { + p_info_arr[i].signature = *(StringName *)&info[i].signature; + p_info_arr[i].call_count = info[i].call_count; + p_info_arr[i].total_time = info[i].total_time; + p_info_arr[i].self_time = info[i].self_time; + godot_string_name_destroy(&info[i].signature); + } + } +#endif + return info_count; +} + +void PluginScriptLanguage::frame() { +#ifdef DEBUG_ENABLED + if (_desc.profiling_frame) { + _desc.profiling_frame(_data); + } +#endif +} + +/* DEBUGGER FUNCTIONS */ + +String PluginScriptLanguage::debug_get_error() const { + if (_desc.debug_get_error) { + godot_string tmp = _desc.debug_get_error(_data); + String ret = *(String *)&tmp; + godot_string_destroy(&tmp); + return ret; + } + return String("Nothing"); +} + +int PluginScriptLanguage::debug_get_stack_level_count() const { + if (_desc.debug_get_stack_level_count) { + return _desc.debug_get_stack_level_count(_data); + } + return 1; +} + +int PluginScriptLanguage::debug_get_stack_level_line(int p_level) const { + if (_desc.debug_get_stack_level_line) { + return _desc.debug_get_stack_level_line(_data, p_level); + } + return 1; +} + +String PluginScriptLanguage::debug_get_stack_level_function(int p_level) const { + if (_desc.debug_get_stack_level_function) { + godot_string tmp = _desc.debug_get_stack_level_function(_data, p_level); + String ret = *(String *)&tmp; + godot_string_destroy(&tmp); + return ret; + } + return String("Nothing"); +} + +String PluginScriptLanguage::debug_get_stack_level_source(int p_level) const { + if (_desc.debug_get_stack_level_source) { + godot_string tmp = _desc.debug_get_stack_level_source(_data, p_level); + String ret = *(String *)&tmp; + godot_string_destroy(&tmp); + return ret; + } + return String("Nothing"); +} + +void PluginScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { + if (_desc.debug_get_stack_level_locals) { + PoolStringArray locals; + Array values; + _desc.debug_get_stack_level_locals(_data, p_level, (godot_pool_string_array *)&locals, (godot_array *)&values, p_max_subitems, p_max_depth); + for (int i = 0; i < locals.size(); i++) { + p_locals->push_back(locals[i]); + } + for (int i = 0; i < values.size(); i++) { + p_values->push_back(values[i]); + } + } +} + +void PluginScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { + if (_desc.debug_get_stack_level_members) { + PoolStringArray members; + Array values; + _desc.debug_get_stack_level_members(_data, p_level, (godot_pool_string_array *)&members, (godot_array *)&values, p_max_subitems, p_max_depth); + for (int i = 0; i < members.size(); i++) { + p_members->push_back(members[i]); + } + for (int i = 0; i < values.size(); i++) { + p_values->push_back(values[i]); + } + } +} + +void PluginScriptLanguage::debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) { + if (_desc.debug_get_globals) { + PoolStringArray locals; + Array values; + _desc.debug_get_globals(_data, (godot_pool_string_array *)&locals, (godot_array *)&values, p_max_subitems, p_max_depth); + for (int i = 0; i < locals.size(); i++) { + p_locals->push_back(locals[i]); + } + for (int i = 0; i < values.size(); i++) { + p_values->push_back(values[i]); + } + } +} + +String PluginScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) { + if (_desc.debug_parse_stack_level_expression) { + godot_string tmp = _desc.debug_parse_stack_level_expression(_data, p_level, (godot_string *)&p_expression, p_max_subitems, p_max_depth); + String ret = *(String *)&tmp; + godot_string_destroy(&tmp); + return ret; + } + return String("Nothing"); +} + +void PluginScriptLanguage::reload_all_scripts() { + // TODO +} + +void PluginScriptLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) { +#ifdef DEBUG_ENABLED + lock(); + // TODO + unlock(); +#endif +} + +void PluginScriptLanguage::lock() { +#ifndef NO_THREADS + if (_lock) { + _lock->lock(); + } +#endif +} + +void PluginScriptLanguage::unlock() { +#ifndef NO_THREADS + if (_lock) { + _lock->unlock(); + } +#endif +} + +PluginScriptLanguage::PluginScriptLanguage(const godot_pluginscript_language_desc *desc) + : _desc(*desc) { + _resource_loader = memnew(ResourceFormatLoaderPluginScript(this)); + _resource_saver = memnew(ResourceFormatSaverPluginScript(this)); + +// TODO: totally remove _lock attribute if NO_THREADS is set +#ifdef NO_THREADS + _lock = NULL; +#else + _lock = Mutex::create(); +#endif +} + +PluginScriptLanguage::~PluginScriptLanguage() { + memdelete(_resource_loader); + memdelete(_resource_saver); +#ifndef NO_THREADS + if (_lock) { + memdelete(_lock); + _lock = NULL; + } +#endif +} diff --git a/modules/gdnative/pluginscript/pluginscript_language.h b/modules/gdnative/pluginscript/pluginscript_language.h new file mode 100644 index 0000000000..79b95ff4e6 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_language.h @@ -0,0 +1,132 @@ +/*************************************************************************/ +/* pluginscript_language.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#ifndef PLUGINSCRIPT_LANGUAGE_H +#define PLUGINSCRIPT_LANGUAGE_H + +// Godot imports +#include "core/io/resource_loader.h" +#include "core/io/resource_saver.h" +#include "core/map.h" +#include "core/script_language.h" +#include "core/self_list.h" +// PluginScript imports +#include "pluginscript_loader.h" +#include <pluginscript/godot_pluginscript.h> + +class PluginScript; +class PluginScriptInstance; + +class PluginScriptLanguage : public ScriptLanguage { + friend class PluginScript; + friend class PluginScriptInstance; + + ResourceFormatLoaderPluginScript *_resource_loader; + ResourceFormatSaverPluginScript *_resource_saver; + const godot_pluginscript_language_desc _desc; + godot_pluginscript_language_data *_data; + + Mutex *_lock; + SelfList<PluginScript>::List _script_list; + +public: + virtual String get_name() const; + + _FORCE_INLINE_ ResourceFormatLoaderPluginScript *get_resource_loader() { return _resource_loader; }; + _FORCE_INLINE_ ResourceFormatSaverPluginScript *get_resource_saver() { return _resource_saver; }; + + /* LANGUAGE FUNCTIONS */ + virtual void init(); + virtual String get_type() const; + virtual String get_extension() const; + virtual Error execute_file(const String &p_path); + virtual void finish(); + + /* EDITOR FUNCTIONS */ + virtual void get_reserved_words(List<String> *p_words) const; + virtual void get_comment_delimiters(List<String> *p_delimiters) const; + virtual void get_string_delimiters(List<String> *p_delimiters) const; + virtual Ref<Script> get_template(const String &p_class_name, const String &p_base_class_name) const; + virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; + virtual Script *create_script() const; + virtual bool has_named_classes() const; + virtual bool supports_builtin_mode() const; + virtual bool can_inherit_from_file() { return true; } + virtual int find_function(const String &p_function, const String &p_code) const; + virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; + virtual Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, bool &r_force, String &r_call_hint); + virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; + virtual void add_global_constant(const StringName &p_variable, const Variant &p_value); + + /* MULTITHREAD FUNCTIONS */ + + //some VMs need to be notified of thread creation/exiting to allocate a stack + // void thread_enter() {} + // void thread_exit() {} + + /* DEBUGGER FUNCTIONS */ + + virtual String debug_get_error() const; + virtual int debug_get_stack_level_count() const; + virtual int debug_get_stack_level_line(int p_level) const; + virtual String debug_get_stack_level_function(int p_level) const; + virtual String debug_get_stack_level_source(int p_level) const; + virtual void debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual void debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual void debug_get_globals(List<String> *p_locals, List<Variant> *p_values, int p_max_subitems = -1, int p_max_depth = -1); + virtual String debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems = -1, int p_max_depth = -1); + + // virtual Vector<StackInfo> debug_get_current_stack_info() { return Vector<StackInfo>(); } + + virtual void reload_all_scripts(); + virtual void reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload); + + /* LOADER FUNCTIONS */ + + virtual void get_recognized_extensions(List<String> *p_extensions) const; + virtual void get_public_functions(List<MethodInfo> *p_functions) const; + virtual void get_public_constants(List<Pair<String, Variant> > *p_constants) const; + + virtual void profiling_start(); + virtual void profiling_stop(); + + virtual int profiling_get_accumulated_data(ProfilingInfo *p_info_arr, int p_info_max); + virtual int profiling_get_frame_data(ProfilingInfo *p_info_arr, int p_info_max); + + virtual void frame(); + + void lock(); + void unlock(); + + PluginScriptLanguage(const godot_pluginscript_language_desc *desc); + virtual ~PluginScriptLanguage(); +}; + +#endif // PLUGINSCRIPT_LANGUAGE_H diff --git a/modules/gdnative/pluginscript/pluginscript_loader.cpp b/modules/gdnative/pluginscript/pluginscript_loader.cpp new file mode 100644 index 0000000000..3648e1a5b4 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_loader.cpp @@ -0,0 +1,113 @@ +/*************************************************************************/ +/* pluginscript_loader.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +// Godot imports +#include "os/file_access.h" +// Pythonscript imports +#include "pluginscript_language.h" +#include "pluginscript_loader.h" +#include "pluginscript_script.h" + +ResourceFormatLoaderPluginScript::ResourceFormatLoaderPluginScript(PluginScriptLanguage *language) { + _language = language; +} + +RES ResourceFormatLoaderPluginScript::load(const String &p_path, const String &p_original_path, Error *r_error) { + if (r_error) + *r_error = ERR_FILE_CANT_OPEN; + + PluginScript *script = memnew(PluginScript); + script->init(_language); + + Ref<PluginScript> scriptres(script); + + Error err = script->load_source_code(p_path); + ERR_FAIL_COND_V(err != OK, RES()); + + script->set_path(p_original_path); + + script->reload(); + + if (r_error) + *r_error = OK; + + return scriptres; +} + +void ResourceFormatLoaderPluginScript::get_recognized_extensions(List<String> *p_extensions) const { + p_extensions->push_back(_language->get_extension()); +} + +bool ResourceFormatLoaderPluginScript::handles_type(const String &p_type) const { + return p_type == "Script" || p_type == _language->get_type(); +} + +String ResourceFormatLoaderPluginScript::get_resource_type(const String &p_path) const { + String el = p_path.get_extension().to_lower(); + if (el == _language->get_extension()) + return _language->get_type(); + return ""; +} + +ResourceFormatSaverPluginScript::ResourceFormatSaverPluginScript(PluginScriptLanguage *language) { + _language = language; +} + +Error ResourceFormatSaverPluginScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) { + Ref<PluginScript> sqscr = p_resource; + ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER); + + String source = sqscr->get_source_code(); + + Error err; + FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err); + ERR_FAIL_COND_V(err, err); + + file->store_string(source); + if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) { + memdelete(file); + return ERR_CANT_CREATE; + } + file->close(); + memdelete(file); + return OK; +} + +void ResourceFormatSaverPluginScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const { + + if (Object::cast_to<PluginScript>(*p_resource)) { + p_extensions->push_back(_language->get_extension()); + } +} + +bool ResourceFormatSaverPluginScript::recognize(const RES &p_resource) const { + + return Object::cast_to<PluginScript>(*p_resource) != NULL; +} diff --git a/modules/gdnative/pluginscript/pluginscript_loader.h b/modules/gdnative/pluginscript/pluginscript_loader.h new file mode 100644 index 0000000000..b85e7725a1 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_loader.h @@ -0,0 +1,62 @@ +/*************************************************************************/ +/* pluginscript_loader.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#ifndef PYTHONSCRIPT_PY_LOADER_H +#define PYTHONSCRIPT_PY_LOADER_H + +// Godot imports +#include "core/script_language.h" +#include "io/resource_loader.h" +#include "io/resource_saver.h" + +class PluginScriptLanguage; + +class ResourceFormatLoaderPluginScript : public ResourceFormatLoader { + PluginScriptLanguage *_language; + +public: + ResourceFormatLoaderPluginScript(PluginScriptLanguage *language); + virtual RES load(const String &p_path, const String &p_original_path = "", Error *r_error = NULL); + virtual void get_recognized_extensions(List<String> *p_extensions) const; + virtual bool handles_type(const String &p_type) const; + virtual String get_resource_type(const String &p_path) const; +}; + +class ResourceFormatSaverPluginScript : public ResourceFormatSaver { + PluginScriptLanguage *_language; + +public: + ResourceFormatSaverPluginScript(PluginScriptLanguage *language); + virtual Error save(const String &p_path, const RES &p_resource, uint32_t p_flags = 0); + virtual void get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const; + virtual bool recognize(const RES &p_resource) const; +}; + +#endif // PYTHONSCRIPT_PY_LOADER_H diff --git a/modules/gdnative/pluginscript/pluginscript_script.cpp b/modules/gdnative/pluginscript/pluginscript_script.cpp new file mode 100644 index 0000000000..4169b07f63 --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_script.cpp @@ -0,0 +1,449 @@ +/*************************************************************************/ +/* pluginscript_script.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +// Godot imports +#include "core/os/file_access.h" +// PluginScript imports +#include "pluginscript_instance.h" +#include "pluginscript_script.h" + +#if DEBUG_ENABLED +#define __ASSERT_SCRIPT_REASON "Cannot retrieve pluginscript class for this script, is you code correct ?" +#define ASSERT_SCRIPT_VALID() \ + { \ + ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ + ERR_FAIL_COND(!can_instance()) \ + } +#define ASSERT_SCRIPT_VALID_V(ret) \ + { \ + ERR_EXPLAIN(__ASSERT_SCRIPT_REASON); \ + ERR_FAIL_COND_V(!can_instance(), ret) \ + } +#else +#define ASSERT_SCRIPT_VALID() +#define ASSERT_SCRIPT_VALID_V(ret) +#endif + +void PluginScript::_bind_methods() { +} + +#ifdef TOOLS_ENABLED + +void PluginScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) { + placeholders.erase(p_placeholder); +} + +#endif + +bool PluginScript::can_instance() const { + bool can = _valid || (!_tool && !ScriptServer::is_scripting_enabled()); + return can; +} + +Ref<Script> PluginScript::get_base_script() const { + if (_ref_base_parent.is_valid()) { + return Ref<PluginScript>(_ref_base_parent); + } else { + return Ref<Script>(); + } +} + +StringName PluginScript::get_instance_base_type() const { + if (_native_parent) + return _native_parent; + if (_ref_base_parent.is_valid()) + return _ref_base_parent->get_instance_base_type(); + return StringName(); +} + +void PluginScript::update_exports() { +// TODO +#ifdef TOOLS_ENABLED +#if 0 + ASSERT_SCRIPT_VALID(); + if (/*changed &&*/ placeholders.size()) { //hm :( + + //update placeholders if any + Map<StringName, Variant> propdefvalues; + List<PropertyInfo> propinfos; + const String *props = (const String *)pybind_get_prop_list(_py_exposed_class); + for (int i = 0; props[i] != ""; ++i) { + const String propname = props[i]; + pybind_get_prop_default_value(_py_exposed_class, propname.c_str(), (godot_variant *)&propdefvalues[propname]); + pybind_prop_info raw_info; + pybind_get_prop_info(_py_exposed_class, propname.c_str(), &raw_info); + PropertyInfo info; + info.type = (Variant::Type)raw_info.type; + info.name = propname; + info.hint = (PropertyHint)raw_info.hint; + info.hint_string = *(String *)&raw_info.hint_string; + info.usage = raw_info.usage; + propinfos.push_back(info); + } + for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { + E->get()->update(propinfos, propdefvalues); + } + } +#endif +#endif +} + +// TODO: rename p_this "p_owner" ? +ScriptInstance *PluginScript::instance_create(Object *p_this) { + ASSERT_SCRIPT_VALID_V(NULL); + // TODO check script validity ? + if (!_tool && !ScriptServer::is_scripting_enabled()) { +#ifdef TOOLS_ENABLED + // Instance a fake script for editing the values + PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(get_language(), Ref<Script>(this), p_this)); + placeholders.insert(si); + update_exports(); + return si; +#else + return NULL; +#endif + } + + PluginScript *top = this; + // TODO: can be optimized by storing a PluginScript::_base_parent direct pointer + while (top->_ref_base_parent.is_valid()) + top = top->_ref_base_parent.ptr(); + if (top->_native_parent) { + if (!ClassDB::is_parent_class(p_this->get_class_name(), top->_native_parent)) { + String msg = "Script inherits from native type '" + String(top->_native_parent) + "', so it can't be instanced in object of type: '" + p_this->get_class() + "'"; + // TODO: implement PluginscriptLanguage::debug_break_parse + // if (ScriptDebugger::get_singleton()) { + // _language->debug_break_parse(get_path(), 0, msg); + // } + ERR_EXPLAIN(msg); + ERR_FAIL_V(NULL); + } + } + + PluginScriptInstance *instance = memnew(PluginScriptInstance()); + const bool success = instance->init(this, p_this); + if (success) { + _language->lock(); + _instances.insert(instance->get_owner()); + _language->unlock(); + return instance; + } else { + memdelete(instance); + ERR_FAIL_V(NULL); + } +} + +bool PluginScript::instance_has(const Object *p_this) const { + _language->lock(); + bool hasit = _instances.has((Object *)p_this); + _language->unlock(); + return hasit; +} + +bool PluginScript::has_source_code() const { + bool has = _source != ""; + return has; +} + +String PluginScript::get_source_code() const { + return _source; +} + +void PluginScript::set_source_code(const String &p_code) { + if (_source == p_code) + return; + _source = p_code; +} + +Error PluginScript::reload(bool p_keep_state) { + _language->lock(); + ERR_FAIL_COND_V(!p_keep_state && _instances.size(), ERR_ALREADY_IN_USE); + _language->unlock(); + + _valid = false; + String basedir = _path; + + if (basedir == "") + basedir = get_path(); + + if (basedir != "") + basedir = basedir.get_base_dir(); + + if (_data) { + _desc->finish(_data); + } + + Error err; + godot_pluginscript_script_manifest manifest = _desc->init( + _language->_data, + (godot_string *)&_path, + (godot_string *)&_source, + (godot_error *)&err); + if (err) { + // TODO: GDscript uses `ScriptDebugger` here to jump into the parsing error + return err; + } + _valid = true; + // Use the manifest to configure this script object + _data = manifest.data; + _name = *(StringName *)&manifest.name; + _tool = manifest.is_tool; + // Base name is either another PluginScript or a regular class accessible + // through ClassDB + StringName *base_name = (StringName *)&manifest.base; + for (SelfList<PluginScript> *e = _language->_script_list.first(); e != NULL; e = e->next()) { + if (e->self()->_name == *base_name) { + // Found you, base is a PluginScript ! + _ref_base_parent = Ref<PluginScript>(e->self()); + break; + } + } + if (!_ref_base_parent.is_valid()) { + // Base is a native ClassDB + if (!ClassDB::class_exists(*base_name)) { + ERR_EXPLAIN("Unknown script '" + String(_name) + "' parent '" + String(*base_name) + "'."); + ERR_FAIL_V(ERR_PARSE_ERROR); + } + _native_parent = *base_name; + } + + Dictionary *members = (Dictionary *)&manifest.member_lines; + for (const Variant *key = members->next(); key != NULL; key = members->next(key)) { + _member_lines[*key] = (*members)[key]; + } + Array *methods = (Array *)&manifest.methods; + for (int i = 0; i < methods->size(); ++i) { + Dictionary v = (*methods)[i]; + MethodInfo mi = MethodInfo::from_dict(v); + _methods_info[mi.name] = mi; + // rpc_mode is passed as an optional field and is not part of MethodInfo + Variant var = v["rpc_mode"]; + if (var == Variant()) { + _methods_rpc_mode[mi.name] = ScriptInstance::RPC_MODE_DISABLED; + } else { + _methods_rpc_mode[mi.name] = ScriptInstance::RPCMode(int(var)); + } + } + Array *signals = (Array *)&manifest.signals; + for (int i = 0; i < signals->size(); ++i) { + Variant v = (*signals)[i]; + MethodInfo mi = MethodInfo::from_dict(v); + _signals_info[mi.name] = mi; + } + Array *properties = (Array *)&manifest.properties; + for (int i = 0; i < properties->size(); ++i) { + Dictionary v = (*properties)[i]; + PropertyInfo pi = PropertyInfo::from_dict(v); + _properties_info[pi.name] = pi; + _properties_default_values[pi.name] = v["default_value"]; + // rset_mode is passed as an optional field and is not part of PropertyInfo + Variant var = v["rset_mode"]; + if (var == Variant()) { + _methods_rpc_mode[pi.name] = ScriptInstance::RPC_MODE_DISABLED; + } else { + _methods_rpc_mode[pi.name] = ScriptInstance::RPCMode(int(var)); + } + } + // Manifest's attributes must be explicitly freed + godot_string_name_destroy(&manifest.name); + godot_string_name_destroy(&manifest.base); + godot_dictionary_destroy(&manifest.member_lines); + godot_array_destroy(&manifest.methods); + godot_array_destroy(&manifest.signals); + godot_array_destroy(&manifest.properties); + +#ifdef TOOLS_ENABLED +/*for (Set<PlaceHolderScriptInstance*>::Element *E=placeholders.front();E;E=E->next()) { + + _update_placeholder(E->get()); + }*/ +#endif + return OK; +} + +void PluginScript::get_script_method_list(List<MethodInfo> *r_methods) const { + ASSERT_SCRIPT_VALID(); + for (Map<StringName, MethodInfo>::Element *e = _methods_info.front(); e != NULL; e = e->next()) { + r_methods->push_back(e->get()); + } +} + +void PluginScript::get_script_property_list(List<PropertyInfo> *r_properties) const { + ASSERT_SCRIPT_VALID(); + for (Map<StringName, PropertyInfo>::Element *e = _properties_info.front(); e != NULL; e = e->next()) { + r_properties->push_back(e->get()); + } +} + +bool PluginScript::has_method(const StringName &p_method) const { + ASSERT_SCRIPT_VALID_V(false); + return _methods_info.has(p_method); +} + +MethodInfo PluginScript::get_method_info(const StringName &p_method) const { + ASSERT_SCRIPT_VALID_V(MethodInfo()); + const Map<StringName, MethodInfo>::Element *e = _methods_info.find(p_method); + if (e != NULL) { + return e->get(); + } else { + return MethodInfo(); + } +} + +bool PluginScript::has_property(const StringName &p_method) const { + ASSERT_SCRIPT_VALID_V(false); + return _properties_info.has(p_method); +} + +PropertyInfo PluginScript::get_property_info(const StringName &p_property) const { + ASSERT_SCRIPT_VALID_V(PropertyInfo()); + const Map<StringName, PropertyInfo>::Element *e = _properties_info.find(p_property); + if (e != NULL) { + return e->get(); + } else { + return PropertyInfo(); + } +} + +bool PluginScript::get_property_default_value(const StringName &p_property, Variant &r_value) const { + ASSERT_SCRIPT_VALID_V(false); +#ifdef TOOLS_ENABLED + const Map<StringName, Variant>::Element *e = _properties_default_values.find(p_property); + if (e != NULL) { + r_value = e->get(); + return true; + } else { + return false; + } +#endif + return false; +} + +ScriptLanguage *PluginScript::get_language() const { + return _language; +} + +Error PluginScript::load_source_code(const String &p_path) { + + PoolVector<uint8_t> sourcef; + Error err; + FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err); + if (err) { + ERR_FAIL_COND_V(err, err); + } + + int len = f->get_len(); + sourcef.resize(len + 1); + PoolVector<uint8_t>::Write w = sourcef.write(); + int r = f->get_buffer(w.ptr(), len); + f->close(); + memdelete(f); + ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN); + w[len] = 0; + + String s; + if (s.parse_utf8((const char *)w.ptr())) { + ERR_EXPLAIN("Script '" + p_path + "' contains invalid unicode (utf-8), so it was not loaded. Please ensure that scripts are saved in valid utf-8 unicode."); + ERR_FAIL_V(ERR_INVALID_DATA); + } + + _source = s; +#ifdef TOOLS_ENABLED +// source_changed_cache=true; +#endif + _path = p_path; + return OK; +} + +bool PluginScript::has_script_signal(const StringName &p_signal) const { + ASSERT_SCRIPT_VALID_V(false); + return _signals_info.has(p_signal); +} + +void PluginScript::get_script_signal_list(List<MethodInfo> *r_signals) const { + ASSERT_SCRIPT_VALID(); + for (Map<StringName, MethodInfo>::Element *e = _signals_info.front(); e != NULL; e = e->next()) { + r_signals->push_back(e->get()); + } +} + +int PluginScript::get_member_line(const StringName &p_member) const { +#ifdef TOOLS_ENABLED + if (_member_lines.has(p_member)) + return _member_lines[p_member]; + else +#endif + return -1; +} + +ScriptInstance::RPCMode PluginScript::get_rpc_mode(const StringName &p_method) const { + ASSERT_SCRIPT_VALID_V(ScriptInstance::RPC_MODE_DISABLED); + const Map<StringName, ScriptInstance::RPCMode>::Element *e = _methods_rpc_mode.find(p_method); + if (e != NULL) { + return e->get(); + } else { + return ScriptInstance::RPC_MODE_DISABLED; + } +} + +ScriptInstance::RPCMode PluginScript::get_rset_mode(const StringName &p_variable) const { + ASSERT_SCRIPT_VALID_V(ScriptInstance::RPC_MODE_DISABLED); + const Map<StringName, ScriptInstance::RPCMode>::Element *e = _variables_rset_mode.find(p_variable); + if (e != NULL) { + return e->get(); + } else { + return ScriptInstance::RPC_MODE_DISABLED; + } +} + +PluginScript::PluginScript() + : _data(NULL), _tool(false), _valid(false), _script_list(this) { +} + +void PluginScript::init(PluginScriptLanguage *language) { + _desc = &language->_desc.script_desc; + _language = language; + +#ifdef DEBUG_ENABLED + _language->lock(); + _language->_script_list.add(&_script_list); + _language->unlock(); +#endif +} + +PluginScript::~PluginScript() { + _desc->finish(_data); + +#ifdef DEBUG_ENABLED + _language->lock(); + _language->_script_list.remove(&_script_list); + _language->unlock(); +#endif +} diff --git a/modules/gdnative/pluginscript/pluginscript_script.h b/modules/gdnative/pluginscript/pluginscript_script.h new file mode 100644 index 0000000000..5600bca5ef --- /dev/null +++ b/modules/gdnative/pluginscript/pluginscript_script.h @@ -0,0 +1,127 @@ +/*************************************************************************/ +/* pluginscript_script.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ + +#ifndef PLUGINSCRIPT_SCRIPT_H +#define PLUGINSCRIPT_SCRIPT_H + +// Godot imports +#include "core/script_language.h" +// PluginScript imports +#include "pluginscript_language.h" +#include <pluginscript/godot_pluginscript.h> + +class PyInstance; + +class PluginScript : public Script { + + GDCLASS(PluginScript, Script); + + friend class PluginScriptInstance; + friend class PluginScriptLanguage; + +private: + godot_pluginscript_script_data *_data; + const godot_pluginscript_script_desc *_desc; + PluginScriptLanguage *_language; + bool _tool; + bool _valid; + + Ref<PluginScript> _ref_base_parent; + StringName _native_parent; + SelfList<PluginScript> _script_list; + + Map<StringName, int> _member_lines; + Map<StringName, Variant> _properties_default_values; + Map<StringName, PropertyInfo> _properties_info; + Map<StringName, MethodInfo> _signals_info; + Map<StringName, MethodInfo> _methods_info; + Map<StringName, ScriptInstance::RPCMode> _variables_rset_mode; + Map<StringName, ScriptInstance::RPCMode> _methods_rpc_mode; + + Set<Object *> _instances; + //exported members + String _source; + String _path; + StringName _name; + +protected: + static void _bind_methods(); + +#ifdef TOOLS_ENABLED + Set<PlaceHolderScriptInstance *> placeholders; + //void _update_placeholder(PlaceHolderScriptInstance *p_placeholder); + virtual void _placeholder_erased(PlaceHolderScriptInstance *p_placeholder); +#endif +public: + virtual bool can_instance() const; + + virtual Ref<Script> get_base_script() const; //for script inheritance + + virtual StringName get_instance_base_type() const; // this may not work in all scripts, will return empty if so + virtual ScriptInstance *instance_create(Object *p_this); + virtual bool instance_has(const Object *p_this) const; + + virtual bool has_source_code() const; + virtual String get_source_code() const; + virtual void set_source_code(const String &p_code); + virtual Error reload(bool p_keep_state = false); + // TODO: load_source_code only allow utf-8 file, should handle bytecode as well ? + virtual Error load_source_code(const String &p_path); + + virtual bool has_method(const StringName &p_method) const; + virtual MethodInfo get_method_info(const StringName &p_method) const; + + bool has_property(const StringName &p_method) const; + PropertyInfo get_property_info(const StringName &p_property) const; + + bool is_tool() const { return _tool; } + + virtual ScriptLanguage *get_language() const; + + virtual bool has_script_signal(const StringName &p_signal) const; + virtual void get_script_signal_list(List<MethodInfo> *r_signals) const; + + virtual bool get_property_default_value(const StringName &p_property, Variant &r_value) const; + + virtual void update_exports(); + virtual void get_script_method_list(List<MethodInfo> *r_methods) const; + virtual void get_script_property_list(List<PropertyInfo> *r_propertieslist) const; + + virtual int get_member_line(const StringName &p_member) const; + + ScriptInstance::RPCMode get_rpc_mode(const StringName &p_method) const; + ScriptInstance::RPCMode get_rset_mode(const StringName &p_variable) const; + + PluginScript(); + void init(PluginScriptLanguage *language); + virtual ~PluginScript(); +}; + +#endif // PLUGINSCRIPT_SCRIPT_H diff --git a/modules/gdnative/pluginscript/register_types.cpp b/modules/gdnative/pluginscript/register_types.cpp new file mode 100644 index 0000000000..5829d08dff --- /dev/null +++ b/modules/gdnative/pluginscript/register_types.cpp @@ -0,0 +1,118 @@ +/*************************************************************************/ +/* register_types.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ +#include "register_types.h" + +#include "core/project_settings.h" +#include "io/resource_loader.h" +#include "io/resource_saver.h" +#include "os/dir_access.h" +#include "os/os.h" +#include "scene/main/scene_tree.h" + +#include "pluginscript_language.h" +#include "pluginscript_script.h" +#include <pluginscript/godot_pluginscript.h> + +static List<PluginScriptLanguage *> pluginscript_languages; + +static Error _check_language_desc(const godot_pluginscript_language_desc *desc) { + ERR_FAIL_COND_V(!desc->name || desc->name == String(), ERR_BUG); + ERR_FAIL_COND_V(!desc->type || desc->type == String(), ERR_BUG); + ERR_FAIL_COND_V(!desc->extension || desc->extension == String(), ERR_BUG); + ERR_FAIL_COND_V(!desc->recognized_extensions || !desc->recognized_extensions[0], ERR_BUG); + ERR_FAIL_COND_V(!desc->init, ERR_BUG); + ERR_FAIL_COND_V(!desc->finish, ERR_BUG); + + // desc->reserved_words is not mandatory + // desc->comment_delimiters is not mandatory + // desc->string_delimiters is not mandatory + + // desc->get_template_source_code is not mandatory + // desc->validate is not mandatory + + // desc->get_template_source_code is not mandatory + // desc->validate is not mandatory + // desc->find_function is not mandatory + // desc->make_function is not mandatory + // desc->complete_code is not mandatory + // desc->auto_indent_code is not mandatory + // desc->add_global_constant is not mandatory + // desc->debug_get_error is not mandatory + // desc->debug_get_stack_level_count is not mandatory + // desc->debug_get_stack_level_line is not mandatory + // desc->debug_get_stack_level_function is not mandatory + // desc->debug_get_stack_level_source is not mandatory + // desc->debug_get_stack_level_locals is not mandatory + // desc->debug_get_stack_level_members is not mandatory + // desc->debug_get_globals is not mandatory + // desc->debug_parse_stack_level_expression is not mandatory + // desc->profiling_start is not mandatory + // desc->profiling_stop is not mandatory + // desc->profiling_get_accumulated_data is not mandatory + // desc->profiling_get_frame_data is not mandatory + // desc->frame is not mandatory + + ERR_FAIL_COND_V(!desc->script_desc.init, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.finish, ERR_BUG); + + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.init, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.finish, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.set_prop, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.get_prop, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.call_method, ERR_BUG); + ERR_FAIL_COND_V(!desc->script_desc.instance_desc.notification, ERR_BUG); + // desc->script_desc.instance_desc.refcount_incremented is not mandatory + // desc->script_desc.instance_desc.refcount_decremented is not mandatory + return OK; +} + +void GDAPI godot_pluginscript_register_language(const godot_pluginscript_language_desc *language_desc) { + Error ret = _check_language_desc(language_desc); + if (ret) { + ERR_FAIL(); + } + PluginScriptLanguage *language = memnew(PluginScriptLanguage(language_desc)); + ScriptServer::register_language(language); + ResourceLoader::add_resource_format_loader(language->get_resource_loader()); + ResourceSaver::add_resource_format_saver(language->get_resource_saver()); + pluginscript_languages.push_back(language); +} + +void register_pluginscript_types() { + ClassDB::register_class<PluginScript>(); +} + +void unregister_pluginscript_types() { + for (List<PluginScriptLanguage *>::Element *e = pluginscript_languages.front(); e; e = e->next()) { + PluginScriptLanguage *language = e->get(); + ScriptServer::unregister_language(language); + memdelete(language); + } +} diff --git a/modules/gdnative/pluginscript/register_types.h b/modules/gdnative/pluginscript/register_types.h new file mode 100644 index 0000000000..70bbb16c62 --- /dev/null +++ b/modules/gdnative/pluginscript/register_types.h @@ -0,0 +1,31 @@ +/*************************************************************************/ +/* register_types.h */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* http://www.godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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. */ +/*************************************************************************/ +void register_pluginscript_types(); +void unregister_pluginscript_types(); diff --git a/modules/gdnative/register_types.cpp b/modules/gdnative/register_types.cpp index 059cd197d1..87f9cddaa2 100644 --- a/modules/gdnative/register_types.cpp +++ b/modules/gdnative/register_types.cpp @@ -35,7 +35,9 @@ #include "io/resource_loader.h" #include "io/resource_saver.h" +#include "nativearvr/register_types.h" #include "nativescript/register_types.h" +#include "pluginscript/register_types.h" #include "core/engine.h" #include "core/os/os.h" @@ -127,57 +129,12 @@ static void editor_init_callback() { #endif -godot_variant cb_standard_varcall(void *handle, godot_string *p_procedure, godot_array *p_args) { - if (handle == NULL) { - ERR_PRINT("No valid library handle, can't call standard varcall procedure"); - godot_variant ret; - godot_variant_new_nil(&ret); - return ret; - } - - void *library_proc; - Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( - handle, - *(String *)p_procedure, - library_proc, - true); // we roll our own message - if (err != OK) { - ERR_PRINT((String("GDNative procedure \"" + *(String *)p_procedure) + "\" does not exists and can't be called").utf8().get_data()); - godot_variant ret; - godot_variant_new_nil(&ret); - return ret; - } +godot_variant cb_standard_varcall(void *p_procedure_handle, godot_array *p_args) { godot_gdnative_procedure_fn proc; - proc = (godot_gdnative_procedure_fn)library_proc; - - return proc(NULL, p_args); -} - -void cb_singleton_call( - void *p_handle, - godot_string *p_proc_name, - void *p_data, - int p_num_args, - void **p_args, - void *r_return) { - if (p_handle == NULL) { - ERR_PRINT("No valid library handle, can't call singleton procedure"); - return; - } + proc = (godot_gdnative_procedure_fn)p_procedure_handle; - void *singleton_proc; - Error err = OS::get_singleton()->get_dynamic_library_symbol_handle( - p_handle, - *(String *)p_proc_name, - singleton_proc); - - if (err != OK) { - return; - } - - void (*singleton_procedure_ptr)() = (void (*)())singleton_proc; - singleton_procedure_ptr(); + return proc(p_args); } GDNativeCallRegistry *GDNativeCallRegistry::singleton; @@ -200,13 +157,16 @@ void register_gdnative_types() { GDNativeCallRegistry::singleton->register_native_call_type("standard_varcall", cb_standard_varcall); - GDNativeCallRegistry::singleton->register_native_raw_call_type("gdnative_singleton_call", cb_singleton_call); - + register_nativearvr_types(); register_nativescript_types(); + register_pluginscript_types(); // run singletons - Array singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); + Array singletons = Array(); + if (ProjectSettings::get_singleton()->has_setting("gdnative/singletons")) { + singletons = ProjectSettings::get_singleton()->get("gdnative/singletons"); + } singleton_gdnatives.resize(singletons.size()); @@ -223,13 +183,16 @@ void register_gdnative_types() { continue; } - singleton_gdnatives[i]->call_native_raw( - "gdnative_singleton_call", + void *proc_ptr; + Error err = singleton_gdnatives[i]->get_symbol( "godot_gdnative_singleton", - NULL, - 0, - NULL, - NULL); + proc_ptr); + + if (err != OK) { + ERR_PRINT((String("No godot_gdnative_singleton in \"" + singleton_gdnatives[i]->get_library()->get_active_library_path()) + "\" found").utf8().get_data()); + } else { + ((void (*)())proc_ptr)(); + } } } @@ -249,7 +212,9 @@ void unregister_gdnative_types() { } singleton_gdnatives.clear(); + unregister_pluginscript_types(); unregister_nativescript_types(); + unregister_nativearvr_types(); memdelete(GDNativeCallRegistry::singleton); diff --git a/modules/gdscript/gd_editor.cpp b/modules/gdscript/gd_editor.cpp index b0408917a4..d9b10ff3fa 100644 --- a/modules/gdscript/gd_editor.cpp +++ b/modules/gdscript/gd_editor.cpp @@ -61,7 +61,11 @@ Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const Str "func _ready():\n" + "%TS%# Called every time the node is added to the scene.\n" + "%TS%# Initialization here\n" + - "%TS%pass\n"; + "%TS%pass\n\n" + + "#func _process(delta):\n" + + "#%TS%# Called every frame. Delta is time since last frame.\n" + + "#%TS%# Update game logic here.\n" + + "#%TS%pass\n"; _template = _template.replace("%BASE%", p_base_class_name); _template = _template.replace("%TS%", _get_indentation()); @@ -127,6 +131,11 @@ bool GDScriptLanguage::has_named_classes() const { return false; } +bool GDScriptLanguage::supports_builtin_mode() const { + + return true; +} + int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const { GDTokenizerText tokenizer; @@ -2102,9 +2111,9 @@ Error GDScriptLanguage::complete_code(const String &p_code, const String &p_base for (List<String>::Element *E = opts.front(); E; E = E->next()) { String opt = E->get().strip_edges(); - if (opt.begins_with("\"") && opt.ends_with("\"")) { + if (opt.is_quoted()) { r_forced = true; - String idopt = opt.substr(1, opt.length() - 2); + String idopt = opt.unquote(); if (idopt.replace("/", "_").is_valid_identifier()) { options.insert(idopt); } else { diff --git a/modules/gdscript/gd_parser.cpp b/modules/gdscript/gd_parser.cpp index 36aaa1f807..94385dc0d0 100644 --- a/modules/gdscript/gd_parser.cpp +++ b/modules/gdscript/gd_parser.cpp @@ -1906,7 +1906,8 @@ GDParser::PatternNode *GDParser::_parse_pattern(bool p_static) { // all the constants like strings and numbers default: { Node *value = _parse_and_reduce_expression(pattern, p_static); - if (error_set) { + if (!value) { + _set_error("Expect constant expression or variables in a pattern"); return NULL; } diff --git a/modules/gdscript/gd_script.cpp b/modules/gdscript/gd_script.cpp index cf6529d5ae..3f3818ffb9 100644 --- a/modules/gdscript/gd_script.cpp +++ b/modules/gdscript/gd_script.cpp @@ -609,11 +609,6 @@ Error GDScript::reload(bool p_keep_state) { return OK; } -String GDScript::get_node_type() const { - - return ""; // ? -} - ScriptLanguage *GDScript::get_language() const { return GDScriptLanguage::get_singleton(); diff --git a/modules/gdscript/gd_script.h b/modules/gdscript/gd_script.h index 5e1a8b19ac..e0d142014a 100644 --- a/modules/gdscript/gd_script.h +++ b/modules/gdscript/gd_script.h @@ -172,7 +172,6 @@ public: virtual Error reload(bool p_keep_state = false); - virtual String get_node_type() const; void set_script_path(const String &p_path) { path = p_path; } //because subclasses need a path too... Error load_source_code(const String &p_path); Error load_byte_code(const String &p_path); @@ -386,6 +385,7 @@ public: virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; + virtual bool supports_builtin_mode() const; virtual bool can_inherit_from_file() { return true; } virtual int find_function(const String &p_function, const String &p_code) const; virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; diff --git a/modules/gridmap/doc_classes/GridMap.xml b/modules/gridmap/doc_classes/GridMap.xml index 3676570ec1..5b0fe56f25 100644 --- a/modules/gridmap/doc_classes/GridMap.xml +++ b/modules/gridmap/doc_classes/GridMap.xml @@ -1,8 +1,13 @@ <?xml version="1.0" encoding="UTF-8" ?> <class name="GridMap" inherits="Spatial" category="Core" version="3.0.alpha.custom_build"> <brief_description> + Node for 3D tile-based maps. </brief_description> <description> + GridMap lets you place meshes on a grid interactively. It works both from the editor and can help you create in-game level editors. + GridMaps use a [MeshLibrary] which contain a list of tiles: meshes with materials plus optional collisions and extra elements. + A GridMap contains a collection of cells. Each grid cell refers to a [MeshLibrary] item. All cells in the map have the same dimensions. + A GridMap is split into a sparse collection of octants for efficient rendering and physics processing. Every octant has the same dimensions and can contain several cells. </description> <tutorials> </tutorials> @@ -13,6 +18,7 @@ <return type="void"> </return> <description> + Clear all cells. </description> </method> <method name="get_cell_item" qualifiers="const"> @@ -25,6 +31,7 @@ <argument index="2" name="z" type="int"> </argument> <description> + The [MeshLibrary] item index located at the grid-based X, Y and Z coordinates. If the cell is empty, [INVALID_CELL_ITEM] will be returned. </description> </method> <method name="get_cell_item_orientation" qualifiers="const"> @@ -37,48 +44,75 @@ <argument index="2" name="z" type="int"> </argument> <description> + The orientation of the cell at the grid-based X, Y and Z coordinates. -1 is retuned if the cell is empty. </description> </method> <method name="get_cell_size" qualifiers="const"> <return type="Vector3"> </return> <description> + The dimensions of the grid's cells. </description> </method> <method name="get_center_x" qualifiers="const"> <return type="bool"> </return> <description> + Returns whether or not grid items are centered on the X axis. </description> </method> <method name="get_center_y" qualifiers="const"> <return type="bool"> </return> <description> + Returns whether or not grid items are centered on the Y axis. </description> </method> <method name="get_center_z" qualifiers="const"> <return type="bool"> </return> <description> + Returns whether or not grid items are centered on the Z axis. </description> </method> <method name="get_meshes"> <return type="Array"> </return> <description> + Array of [Transform] and [Mesh] references corresponding to the non empty cells in the grid. The transforms are specified in world space. </description> </method> <method name="get_octant_size" qualifiers="const"> <return type="int"> </return> <description> + The size of each octant measured in number of cells. This applies to all three axis. </description> </method> <method name="get_theme" qualifiers="const"> <return type="MeshLibrary"> </return> <description> + The assigned [MeshLibrary]. + </description> + </method> + <method name="get_used_cells" qualifiers="const"> + <return type="Array"> + </return> + <description> + Array of [Vector3] with the non empty cell coordinates in the grid map. + </description> + </method> + <method name="map_to_world" qualifiers="const"> + <return type="Vector3"> + </return> + <argument index="0" name="x" type="int"> + </argument> + <argument index="1" name="y" type="int"> + </argument> + <argument index="2" name="z" type="int"> + </argument> + <description> </description> </method> <method name="resource_changed"> @@ -103,6 +137,9 @@ <argument index="4" name="orientation" type="int" default="0"> </argument> <description> + Set the mesh index for the cell referenced by its grid-based X, Y and Z coordinates. + A negative item index will clear the cell. + Optionally, the item's orientation can be passed. </description> </method> <method name="set_cell_size"> @@ -111,6 +148,7 @@ <argument index="0" name="size" type="Vector3"> </argument> <description> + Sets the height, width and depth of the grid's cells. </description> </method> <method name="set_center_x"> @@ -119,6 +157,7 @@ <argument index="0" name="enable" type="bool"> </argument> <description> + Set grid items to be centered on the X axis. By default it is enabled. </description> </method> <method name="set_center_y"> @@ -127,6 +166,7 @@ <argument index="0" name="enable" type="bool"> </argument> <description> + Set grid items to be centered on the Y axis. By default it is enabled. </description> </method> <method name="set_center_z"> @@ -135,6 +175,7 @@ <argument index="0" name="enable" type="bool"> </argument> <description> + Set grid items to be centered on the Z axis. By default it is enabled. </description> </method> <method name="set_clip"> @@ -157,6 +198,7 @@ <argument index="0" name="size" type="int"> </argument> <description> + Sets the size for each octant measured in number of cells. This applies to all three axis. </description> </method> <method name="set_theme"> @@ -165,11 +207,21 @@ <argument index="0" name="theme" type="MeshLibrary"> </argument> <description> + Sets the collection of meshes for the map. + </description> + </method> + <method name="world_to_map" qualifiers="const"> + <return type="Vector3"> + </return> + <argument index="0" name="pos" type="Vector3"> + </argument> + <description> </description> </method> </methods> <constants> <constant name="INVALID_CELL_ITEM" value="-1" enum=""> + Invalid cell item that can be used in [method set_cell_item] to clear cells (or represent an empty cell in [method get_cell_item]). </constant> </constants> </class> diff --git a/modules/gridmap/grid_map.cpp b/modules/gridmap/grid_map.cpp index 4e8b67e4e8..cb14a5ee9c 100644 --- a/modules/gridmap/grid_map.cpp +++ b/modules/gridmap/grid_map.cpp @@ -333,6 +333,23 @@ int GridMap::get_cell_item_orientation(int p_x, int p_y, int p_z) const { return cell_map[key].rot; } +Vector3 GridMap::world_to_map(const Vector3 &p_world_pos) const { + Vector3 map_pos = p_world_pos / cell_size; + map_pos.x = floor(map_pos.x); + map_pos.y = floor(map_pos.y); + map_pos.z = floor(map_pos.z); + return map_pos; +} + +Vector3 GridMap::map_to_world(int p_x, int p_y, int p_z) const { + Vector3 offset = _get_offset(); + Vector3 world_pos( + p_x * cell_size.x + offset.x, + p_y * cell_size.y + offset.y, + p_z * cell_size.z + offset.z); + return world_pos; +} + void GridMap::_octant_transform(const OctantKey &p_key) { ERR_FAIL_COND(!octant_map.has(p_key)); @@ -407,7 +424,7 @@ bool GridMap::_octant_update(const OctantKey &p_key) { //print_line("OCTANT, CELLS: "+itos(ii.cells.size())); Vector3 cellpos = Vector3(E->get().x, E->get().y, E->get().z); - Vector3 ofs(cell_size.x * 0.5 * int(center_x), cell_size.y * 0.5 * int(center_y), cell_size.z * 0.5 * int(center_z)); + Vector3 ofs = _get_offset(); Transform xform; @@ -754,6 +771,9 @@ void GridMap::_bind_methods() { ClassDB::bind_method(D_METHOD("get_cell_item", "x", "y", "z"), &GridMap::get_cell_item); ClassDB::bind_method(D_METHOD("get_cell_item_orientation", "x", "y", "z"), &GridMap::get_cell_item_orientation); + ClassDB::bind_method(D_METHOD("world_to_map", "pos"), &GridMap::world_to_map); + ClassDB::bind_method(D_METHOD("map_to_world", "x", "y", "z"), &GridMap::map_to_world); + //ClassDB::bind_method(D_METHOD("_recreate_octants"),&GridMap::_recreate_octants); ClassDB::bind_method(D_METHOD("_update_octants_callback"), &GridMap::_update_octants_callback); ClassDB::bind_method(D_METHOD("resource_changed", "resource"), &GridMap::resource_changed); @@ -801,7 +821,7 @@ void GridMap::set_clip(bool p_enabled, bool p_clip_above, int p_floor, Vector3:: void GridMap::set_cell_scale(float p_scale) { cell_scale = p_scale; - _queue_octants_dirty(); + _recreate_octant_data(); } float GridMap::get_cell_scale() const { @@ -827,7 +847,7 @@ Array GridMap::get_meshes() { if (theme.is_null()) return Array(); - Vector3 ofs(cell_size.x * 0.5 * int(center_x), cell_size.y * 0.5 * int(center_y), cell_size.z * 0.5 * int(center_z)); + Vector3 ofs = _get_offset(); Array meshes; for (Map<IndexKey, Cell>::Element *E = cell_map.front(); E; E = E->next()) { @@ -857,6 +877,13 @@ Array GridMap::get_meshes() { return meshes; } +Vector3 GridMap::_get_offset() const { + return Vector3( + cell_size.x * 0.5 * int(center_x), + cell_size.y * 0.5 * int(center_y), + cell_size.z * 0.5 * int(center_z)); +} + GridMap::GridMap() { cell_size = Vector3(2, 2, 2); diff --git a/modules/gridmap/grid_map.h b/modules/gridmap/grid_map.h index 296956ff5d..5bfdf1dac3 100644 --- a/modules/gridmap/grid_map.h +++ b/modules/gridmap/grid_map.h @@ -184,6 +184,8 @@ class GridMap : public Spatial { void _clear_internal(); + Vector3 _get_offset() const; + protected: bool _set(const StringName &p_name, const Variant &p_value); bool _get(const StringName &p_name, Variant &r_ret) const; @@ -218,6 +220,9 @@ public: int get_cell_item(int p_x, int p_y, int p_z) const; int get_cell_item_orientation(int p_x, int p_y, int p_z) const; + Vector3 world_to_map(const Vector3 &p_pos) const; + Vector3 map_to_world(int p_x, int p_y, int p_z) const; + void set_clip(bool p_enabled, bool p_clip_above = true, int p_floor = 0, Vector3::Axis p_axis = Vector3::AXIS_X); void set_cell_scale(float p_scale); diff --git a/modules/hdr/image_loader_hdr.cpp b/modules/hdr/image_loader_hdr.cpp index 92d88207b3..08ac624504 100644 --- a/modules/hdr/image_loader_hdr.cpp +++ b/modules/hdr/image_loader_hdr.cpp @@ -38,7 +38,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force String header = f->get_token(); - print_line("HEADER: " + header); ERR_FAIL_COND_V(header != "#?RADIANCE" && header != "#?RGBE", ERR_FILE_UNRECOGNIZED); while (true) { @@ -64,8 +63,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force int width = f->get_line().to_int(); - print_line("HDR w: " + itos(width) + " h:" + itos(height)); - PoolVector<uint8_t> imgdata; imgdata.resize(height * width * sizeof(uint32_t)); @@ -102,7 +99,6 @@ Error ImageLoaderHDR::load_image(Ref<Image> p_image, FileAccess *f, bool p_force len <<= 8; len |= f->get_8(); - print_line("line: " + itos(len)); if (len != width) { ERR_EXPLAIN("invalid decoded scanline length, corrupt HDR"); ERR_FAIL_V(ERR_FILE_CORRUPT); diff --git a/modules/mobile_vr/mobile_interface.h b/modules/mobile_vr/mobile_interface.h index 6a5e01c163..747377ae46 100644 --- a/modules/mobile_vr/mobile_interface.h +++ b/modules/mobile_vr/mobile_interface.h @@ -90,7 +90,7 @@ private: ///@TODO a few support functions for trackers, most are math related and should likely be moved elsewhere float floor_decimals(float p_value, float p_decimals) { - float power_of_10 = pow(10.0, p_decimals); + float power_of_10 = pow(10.0f, p_decimals); return floor(p_value * power_of_10) / power_of_10; }; diff --git a/modules/mono/SCsub b/modules/mono/SCsub index caf4fdb3ca..27e60c4623 100644 --- a/modules/mono/SCsub +++ b/modules/mono/SCsub @@ -53,68 +53,151 @@ if env['tools']: vars = Variables() vars.Add(BoolVariable('mono_glue', 'Build with the mono glue sources', True)) +vars.Add(BoolVariable('xbuild_fallback', 'If MSBuild is not found, fallback to xbuild', False)) vars.Update(env) # Glue sources if env['mono_glue']: env.add_source_files(env.modules_sources, 'glue/*.cpp') else: - env.Append(CPPDEFINES = [ 'MONO_GLUE_DISABLED' ]) + env.Append(CPPDEFINES=['MONO_GLUE_DISABLED']) if ARGUMENTS.get('yolo_copy', False): - env.Append(CPPDEFINES = [ 'YOLO_COPY' ]) + env.Append(CPPDEFINES=['YOLO_COPY']) + # Build GodotSharpTools solution + import os -import subprocess -import mono_reg_utils as monoreg + + +def find_msbuild_unix(filename): + import os.path + import sys + + hint_dirs = ['/opt/novell/mono/bin'] + if sys.platform == "darwin": + hint_dirs = ['/Library/Frameworks/Mono.framework/Versions/Current/bin'] + hint_dirs + + for hint_dir in hint_dirs: + hint_path = os.path.join(hint_dir, filename) + if os.path.isfile(hint_path): + return hint_path + + for hint_dir in os.environ["PATH"].split(os.pathsep): + hint_dir = hint_dir.strip('"') + hint_path = os.path.join(hint_dir, filename) + if os.path.isfile(hint_path) and os.access(hint_path, os.X_OK): + return hint_path + + return None + + +def find_msbuild_windows(): + import mono_reg_utils as monoreg + + bits = env['bits'] + + if bits == '32': + if os.getenv('MONO32_PREFIX'): + mono_root = os.getenv('MONO32_PREFIX') + else: + mono_root = monoreg.find_mono_root_dir(bits) + else: + if os.getenv('MONO64_PREFIX'): + mono_root = os.getenv('MONO64_PREFIX') + else: + mono_root = monoreg.find_mono_root_dir(bits) + + if not mono_root: + raise RuntimeError('Cannot find mono root directory') + + msbuild_tools_path = monoreg.find_msbuild_tools_path_reg() + + if msbuild_tools_path: + return (os.path.join(msbuild_tools_path, 'MSBuild.exe'), os.path.join(mono_root, 'lib', 'mono', '4.5')) + else: + msbuild_mono = os.path.join(mono_root, 'bin', 'msbuild.bat') + + if os.path.isfile(msbuild_mono): + return (msbuild_mono, '') + + return None def mono_build_solution(source, target, env): + import subprocess + import mono_reg_utils as monoreg + from shutil import copyfile + + framework_path_override = '' + if os.name == 'nt': - msbuild_tools_path = monoreg.find_msbuild_tools_path_reg() - if not msbuild_tools_path: - raise RuntimeError('Cannot find MSBuild Tools Path in the registry') - msbuild_path = os.path.join(msbuild_tools_path, 'MSBuild.exe') + msbuild_info = find_msbuild_windows() + if msbuild_info is None: + raise RuntimeError('Cannot find MSBuild executable') + msbuild_path = msbuild_info[0] + framework_path_override = msbuild_info[1] else: - msbuild_path = 'msbuild' + msbuild_path = find_msbuild_unix('msbuild') + if msbuild_path is None: + xbuild_fallback = env['xbuild_fallback'] + + if xbuild_fallback and os.name == 'nt': + print("Option 'xbuild_fallback' not supported on Windows") + xbuild_fallback = False + + if xbuild_fallback: + print('Cannot find MSBuild executable, trying with xbuild') + print('Warning: xbuild is deprecated') + + msbuild_path = find_msbuild_unix('xbuild') + + if msbuild_path is None: + raise RuntimeError('Cannot find xbuild executable') + else: + raise RuntimeError('Cannot find MSBuild executable') + + print('MSBuild path: ' + msbuild_path) - output_path = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + build_config = 'Release' msbuild_args = [ msbuild_path, os.path.abspath(str(source[0])), - '/p:Configuration=Release', - '/p:OutputPath=' + output_path + '/p:Configuration=' + build_config, ] + if framework_path_override: + msbuild_args += ['/p:FrameworkPathOverride=' + framework_path_override] + msbuild_env = os.environ.copy() # Needed when running from Developer Command Prompt for VS if 'PLATFORM' in msbuild_env: del msbuild_env['PLATFORM'] - msbuild_alt_paths = [ 'xbuild' ] - - while True: - try: - subprocess.check_call(msbuild_args, env = msbuild_env) - break - except subprocess.CalledProcessError: - raise RuntimeError('GodotSharpTools build failed') - except OSError: - if os.name != 'nt': - if not msbuild_alt_paths: - raise RuntimeError('Could not find commands msbuild or xbuild') - # Try xbuild - msbuild_args[0] = msbuild_alt_paths.pop(0) - else: - raise RuntimeError('Could not find command MSBuild.exe') + try: + subprocess.check_call(msbuild_args, env=msbuild_env) + except subprocess.CalledProcessError: + raise RuntimeError('GodotSharpTools build failed') + + src_dir = os.path.abspath(os.path.join(str(source[0]), os.pardir, 'bin', build_config)) + dst_dir = os.path.abspath(os.path.join(str(target[0]), os.pardir)) + + if not os.path.isdir(dst_dir): + if os.path.exists(dst_dir): + raise RuntimeError('Target directory is a file') + os.makedirs(dst_dir) + + asm_file = 'GodotSharpTools.dll' + + copyfile(os.path.join(src_dir, asm_file), os.path.join(dst_dir, asm_file)) mono_sln_builder = Builder(action = mono_build_solution) -env.Append(BUILDERS = { 'MonoBuildSolution' : mono_sln_builder }) +env.Append(BUILDERS={'MonoBuildSolution': mono_sln_builder}) env.MonoBuildSolution( os.path.join(Dir('#bin').abspath, 'GodotSharpTools.dll'), 'editor/GodotSharpTools/GodotSharpTools.sln' diff --git a/modules/mono/config.py b/modules/mono/config.py index 9de199bb5a..44eef45f76 100644 --- a/modules/mono/config.py +++ b/modules/mono/config.py @@ -2,7 +2,6 @@ import imp import os import sys -from shutil import copyfile from SCons.Script import BoolVariable, Environment, Variables @@ -16,8 +15,7 @@ def find_file_in_dir(directory, files, prefix='', extension=''): for curfile in files: if os.path.isfile(os.path.join(directory, prefix + curfile + extension)): return curfile - - return None + return '' def can_build(platform): @@ -31,6 +29,22 @@ def is_enabled(): return False +def copy_file_no_replace(src_dir, dst_dir, name): + from shutil import copyfile + + src_path = os.path.join(src_dir, name) + dst_path = os.path.join(dst_dir, name) + need_copy = True + + if not os.path.isdir(dst_dir): + os.mkdir(dst_dir) + elif os.path.exists(dst_path): + need_copy = False + + if need_copy: + copyfile(src_path, dst_path) + + def configure(env): env.use_ptrcall = True @@ -38,6 +52,8 @@ def configure(env): envvars.Add(BoolVariable('mono_static', 'Statically link mono', False)) envvars.Update(env) + bits = env['bits'] + mono_static = env['mono_static'] mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0'] @@ -46,18 +62,18 @@ def configure(env): if mono_static: raise RuntimeError('mono-static: Not supported on Windows') - if env['bits'] == '32': + if bits == '32': if os.getenv('MONO32_PREFIX'): mono_root = os.getenv('MONO32_PREFIX') elif os.name == 'nt': - mono_root = monoreg.find_mono_root_dir() + mono_root = monoreg.find_mono_root_dir(bits) else: if os.getenv('MONO64_PREFIX'): mono_root = os.getenv('MONO64_PREFIX') elif os.name == 'nt': - mono_root = monoreg.find_mono_root_dir() + mono_root = monoreg.find_mono_root_dir(bits) - if mono_root is None: + if not mono_root: raise RuntimeError('Mono installation directory not found') mono_lib_path = os.path.join(mono_root, 'lib') @@ -67,7 +83,7 @@ def configure(env): mono_lib_name = find_file_in_dir(mono_lib_path, mono_lib_names, extension='.lib') - if mono_lib_name is None: + if not mono_lib_name: raise RuntimeError('Could not find mono library in: ' + mono_lib_path) if os.getenv('VCINSTALLDIR'): @@ -79,28 +95,23 @@ def configure(env): mono_dll_name = find_file_in_dir(mono_bin_path, mono_lib_names, extension='.dll') - mono_dll_src = os.path.join(mono_bin_path, mono_dll_name + '.dll') - mono_dll_dst = os.path.join('bin', mono_dll_name + '.dll') - copy_mono_dll = True + if not mono_dll_name: + raise RuntimeError('Could not find mono shared library in: ' + mono_bin_path) - if not os.path.isdir('bin'): - os.mkdir('bin') - elif os.path.exists(mono_dll_dst): - copy_mono_dll = False - - if copy_mono_dll: - copyfile(mono_dll_src, mono_dll_dst) + copy_file_no_replace(mono_bin_path, 'bin', mono_dll_name + '.dll') else: - mono_root = None + sharedlib_ext = '.dylib' if sys.platform == 'darwin' else '.so' + + mono_root = '' - if env['bits'] == '32': + if bits == '32': if os.getenv('MONO32_PREFIX'): mono_root = os.getenv('MONO32_PREFIX') else: if os.getenv('MONO64_PREFIX'): mono_root = os.getenv('MONO64_PREFIX') - if mono_root is not None: + if mono_root: mono_lib_path = os.path.join(mono_root, 'lib') env.Append(LIBPATH=mono_lib_path) @@ -108,7 +119,7 @@ def configure(env): mono_lib = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension='.a') - if mono_lib is None: + if not mono_lib: raise RuntimeError('Could not find mono library in: ' + mono_lib_path) env.Append(CPPFLAGS=['-D_REENTRANT']) @@ -125,12 +136,41 @@ def configure(env): else: env.Append(LIBS=[mono_lib]) - env.Append(LIBS=['m', 'rt', 'dl', 'pthread']) + if sys.platform == "darwin": + env.Append(LIBS=['iconv', 'pthread']) + elif sys.platform == "linux" or sys.platform == "linux2": + env.Append(LIBS=['m', 'rt', 'dl', 'pthread']) + + if not mono_static: + mono_so_name = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension=sharedlib_ext) + + if not mono_so_name: + raise RuntimeError('Could not find mono shared library in: ' + mono_lib_path) + + copy_file_no_replace(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext) else: if mono_static: raise RuntimeError('mono-static: Not supported with pkg-config. Specify a mono prefix manually') - env.ParseConfig('pkg-config mono-2 --cflags --libs') + env.ParseConfig('pkg-config monosgen-2 --cflags --libs') + + mono_lib_path = '' + mono_so_name = '' + + tmpenv = Environment() + tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L') + + for hint_dir in tmpenv['LIBPATH']: + name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext) + if name_found: + mono_lib_path = hint_dir + mono_so_name = name_found + break + + if not mono_so_name: + raise RuntimeError('Could not find mono shared library in: ' + str(tmpenv['LIBPATH'])) + + copy_file_no_replace(mono_lib_path, 'bin', 'lib' + mono_so_name + sharedlib_ext) env.Append(LINKFLAGS='-rdynamic') diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index b475782729..3d91a6de6c 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -41,6 +41,7 @@ #include "editor/csharp_project.h" #include "editor/editor_node.h" #include "editor/godotsharp_editor.h" +#include "utils/string_utils.h" #endif #include "godotsharp_dirs.h" @@ -48,8 +49,9 @@ #include "mono_gd/gd_mono_marshal.h" #include "signal_awaiter_utils.h" -#define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->string_names.m_var) +#define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var) +#ifdef TOOLS_ENABLED static bool _create_project_solution_if_needed() { String sln_path = GodotSharpDirs::get_project_sln_path(); @@ -64,6 +66,7 @@ static bool _create_project_solution_if_needed() { return true; } +#endif CSharpLanguage *CSharpLanguage::singleton = NULL; @@ -274,13 +277,22 @@ Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const Strin " // Initialization here\n" " \n" " }\n" + "\n" + "// public override void _Process(float delta)\n" + "// {\n" + "// // Called every frame. Delta is time since last frame.\n" + "// // Update game logic here.\n" + "// \n" + "// }\n" "}\n"; - script_template = script_template.replace("%BASE_CLASS_NAME%", p_base_class_name).replace("%CLASS_NAME%", p_class_name); + script_template = script_template.replace("%BASE_CLASS_NAME%", p_base_class_name) + .replace("%CLASS_NAME%", p_class_name); Ref<CSharpScript> script; script.instance(); script->set_source_code(script_template); + script->set_name(p_class_name); return script; } @@ -292,23 +304,96 @@ Script *CSharpLanguage::create_script() const { bool CSharpLanguage::has_named_classes() const { - return true; + return false; } -String CSharpLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { +bool CSharpLanguage::supports_builtin_mode() const { + + return false; +} + +static String variant_type_to_managed_name(const String &p_var_type_name) { + + if (p_var_type_name.empty()) + return "object"; + + if (!ClassDB::class_exists(p_var_type_name)) { + Variant::Type var_types[] = { + Variant::BOOL, + Variant::INT, + Variant::REAL, + Variant::STRING, + Variant::VECTOR2, + Variant::RECT2, + Variant::VECTOR3, + Variant::TRANSFORM2D, + Variant::PLANE, + Variant::QUAT, + Variant::RECT3, + Variant::BASIS, + Variant::TRANSFORM, + Variant::COLOR, + Variant::NODE_PATH, + Variant::_RID + }; + + for (int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) { + if (p_var_type_name == Variant::get_type_name(var_types[i])) + return p_var_type_name; + } + + if (p_var_type_name == "String") + return "string"; // I prefer this one >:[ + + // TODO these will be rewritten later into custom containers + + if (p_var_type_name == "Array") + return "object[]"; + + if (p_var_type_name == "Dictionary") + return "Dictionary<object, object>"; + + if (p_var_type_name == "PoolByteArray") + return "byte[]"; + if (p_var_type_name == "PoolIntArray") + return "int[]"; + if (p_var_type_name == "PoolRealArray") + return "float[]"; + if (p_var_type_name == "PoolStringArray") + return "string[]"; + if (p_var_type_name == "PoolVector2Array") + return "Vector2[]"; + if (p_var_type_name == "PoolVector3Array") + return "Vector3[]"; + if (p_var_type_name == "PoolColorArray") + return "Color[]"; + + return "object"; + } + return p_var_type_name; +} + +String CSharpLanguage::make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const { +#ifdef TOOLS_ENABLED // FIXME - // Due to Godot's API limitation this just appends the function to the end of the file - // Another limitation is that the parameter types are not specified, so we must use System.Object + // - Due to Godot's API limitation this just appends the function to the end of the file + // - Use fully qualified name if there is ambiguity String s = "private void " + p_name + "("; for (int i = 0; i < p_args.size(); i++) { + const String &arg = p_args[i]; + if (i > 0) s += ", "; - s += "object " + p_args[i]; + + s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0)); } s += ")\n{\n // Replace with function body\n}\n"; return s; +#else + return String(); +#endif } void CSharpLanguage::frame() { @@ -392,6 +477,7 @@ void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft (void)p_script; // UNUSED #ifdef TOOLS_ENABLED + MonoReloadNode::get_singleton()->restart_reload_timer(); reload_assemblies_if_needed(p_soft_reload); #endif } @@ -403,13 +489,17 @@ void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) { GDMonoAssembly *proj_assembly = gdmono->get_project_assembly(); + String name = ProjectSettings::get_singleton()->get("application/config/name"); + if (name.empty()) { + name = "UnnamedProject"; + } + if (proj_assembly) { String proj_asm_path = proj_assembly->get_path(); if (!FileAccess::exists(proj_assembly->get_path())) { // Maybe it wasn't loaded from the default path, so check this as well - String proj_asm_name = ProjectSettings::get_singleton()->get("application/config/name"); - proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(proj_asm_name); + proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name); if (!FileAccess::exists(proj_asm_path)) return; // No assembly to load } @@ -417,8 +507,7 @@ void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) { if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time()) return; // Already up to date } else { - String proj_asm_name = ProjectSettings::get_singleton()->get("application/config/name"); - if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(proj_asm_name))) + if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(name))) return; // No assembly to load } } @@ -536,6 +625,9 @@ void CSharpLanguage::reload_assemblies_if_needed(bool p_soft_reload) { //if instance states were saved, set them! } + + if (Engine::get_singleton()->is_editor_hint()) + EditorNode::get_singleton()->get_property_editor()->update_tree(); } #endif @@ -903,46 +995,6 @@ Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, } else { return Variant(); } - } else if (p_method == CACHED_STRING_NAME(_awaited_signal_callback)) { - // shitty hack.. - // TODO move to its own function, thx - - if (p_argcount < 1) { - r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; - r_error.argument = 1; - return Variant(); - } - - Ref<SignalAwaiterHandle> awaiter = *p_args[p_argcount - 1]; - - if (awaiter.is_null()) { - r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; - r_error.argument = p_argcount - 1; - r_error.expected = Variant::OBJECT; - return Variant(); - } - - awaiter->set_completed(true); - - int extra_argc = p_argcount - 1; - MonoArray *extra_args = mono_array_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(MonoObject), extra_argc); - - for (int i = 0; i < extra_argc; i++) { - MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_args[i]); - mono_array_set(extra_args, MonoObject *, i, boxed); - } - - GDMonoUtils::GodotObject__AwaitedSignalCallback thunk = CACHED_METHOD_THUNK(GodotObject, _AwaitedSignalCallback); - - MonoObject *ex = NULL; - thunk(mono_object, &extra_args, awaiter->get_target(), &ex); - - if (ex) { - mono_print_unhandled_exception(ex); - ERR_FAIL_V(Variant()); - } - - return Variant(); } top = top->get_parent_class(); @@ -1239,8 +1291,11 @@ bool CSharpScript::_update_exports() { for (int i = 0; i < fields.size(); i++) { GDMonoField *field = fields[i]; - if (field->is_static() || field->get_visibility() != GDMono::PUBLIC) + if (field->is_static()) { + if (field->has_attribute(CACHED_CLASS(ExportAttribute))) + ERR_PRINTS("Cannot export field because it is static: " + top->get_full_name() + "." + field->get_name()); continue; + } String name = field->get_name(); StringName cname = name; @@ -1248,17 +1303,39 @@ bool CSharpScript::_update_exports() { if (member_info.has(cname)) continue; - Variant::Type type = GDMonoMarshal::managed_to_variant_type(field->get_type()); + ManagedType field_type = field->get_type(); + Variant::Type type = GDMonoMarshal::managed_to_variant_type(field_type); if (field->has_attribute(CACHED_CLASS(ExportAttribute))) { + // Field has Export attribute MonoObject *attr = field->get_attribute(CACHED_CLASS(ExportAttribute)); - // Field has Export attribute - int hint = CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr); - String hint_string = CACHED_FIELD(ExportAttribute, hint_string)->get_string_value(attr); - int usage = CACHED_FIELD(ExportAttribute, usage)->get_int_value(attr); + PropertyHint hint; + String hint_string; + + if (type == Variant::NIL) { + ERR_PRINTS("Unknown type of exported field: " + top->get_full_name() + "." + field->get_name()); + continue; + } else if (type == Variant::INT && field_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(field_type.type_class->get_raw())) { + type = Variant::INT; + hint = PROPERTY_HINT_ENUM; + + Vector<MonoClassField *> fields = field_type.type_class->get_enum_fields(); + + for (int i = 0; i < fields.size(); i++) { + if (i > 0) + hint_string += ","; + hint_string += mono_field_get_name(fields[i]); + } + } else if (type == Variant::OBJECT && CACHED_CLASS(GodotReference)->is_assignable_from(field_type.type_class)) { + hint = PROPERTY_HINT_RESOURCE_TYPE; + hint_string = NATIVE_GDMONOCLASS_NAME(field_type.type_class); + } else { + hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr)); + hint_string = CACHED_FIELD(ExportAttribute, hint_string)->get_string_value(attr); + } - PropertyInfo prop_info = PropertyInfo(type, name, PropertyHint(hint), hint_string, PropertyUsageFlags(usage)); + PropertyInfo prop_info = PropertyInfo(type, name, hint, hint_string, PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE); member_info[cname] = prop_info; exported_members_cache.push_back(prop_info); @@ -1392,12 +1469,15 @@ bool CSharpScript::can_instance() const { #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { - if (_create_project_solution_if_needed()) { - CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(), - "Compile", - ProjectSettings::get_singleton()->globalize_path(get_path())); - } else { - ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created."); + + if (get_path().find("::") == -1) { // Ignore if built-in script. Can happen if the file is deleted... + if (_create_project_solution_if_needed()) { + CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(), + "Compile", + ProjectSettings::get_singleton()->globalize_path(get_path())); + } else { + ERR_PRINTS("Cannot add " + get_path() + " to the C# project because it could not be created."); + } } } #endif @@ -1647,11 +1727,6 @@ Error CSharpScript::reload(bool p_keep_state) { return ERR_FILE_MISSING_DEPENDENCIES; } -String CSharpScript::get_node_type() const { - - return ""; // ? -} - ScriptLanguage *CSharpScript::get_language() const { return CSharpLanguage::get_singleton(); @@ -1679,16 +1754,6 @@ void CSharpScript::update_exports() { #ifdef TOOLS_ENABLED _update_exports(); - - if (placeholders.size()) { - Map<StringName, Variant> values; - List<PropertyInfo> propnames; - _update_exports_values(values, propnames); - - for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) { - E->get()->update(propnames, values); - } - } #endif } @@ -1915,7 +1980,7 @@ bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const { CSharpLanguage::StringNameCache::StringNameCache() { - _awaited_signal_callback = StaticCString::create("_AwaitedSignalCallback"); + _signal_callback = StaticCString::create("_signal_callback"); _set = StaticCString::create("_set"); _get = StaticCString::create("_get"); _notification = StaticCString::create("_notification"); diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 3fcc3bdf04..65a6450da5 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -138,7 +138,6 @@ public: virtual bool is_tool() const { return tool; } virtual Ref<Script> get_base_script() const; - virtual String get_node_type() const; virtual ScriptLanguage *get_language() const; /* TODO */ virtual void get_script_method_list(List<MethodInfo> *p_list) const {} @@ -225,7 +224,7 @@ class CSharpLanguage : public ScriptLanguage { struct StringNameCache { - StringName _awaited_signal_callback; + StringName _signal_callback; StringName _set; StringName _get; StringName _notification; @@ -242,6 +241,8 @@ public: _FORCE_INLINE_ int get_language_index() { return lang_idx; } void set_language_index(int p_idx); + _FORCE_INLINE_ const StringNameCache &get_string_names() { return string_names; } + _FORCE_INLINE_ static CSharpLanguage *get_singleton() { return singleton; } bool debug_break(const String &p_error, bool p_allow_continue = true); @@ -268,6 +269,7 @@ public: /* TODO */ virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions) const { return true; } virtual Script *create_script() const; virtual bool has_named_classes() const; + virtual bool supports_builtin_mode() const; /* TODO? */ virtual int find_function(const String &p_function, const String &p_code) const { return -1; } virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; /* TODO? */ Error complete_code(const String &p_code, const String &p_base_path, Object *p_owner, List<String> *r_options, String &r_call_hint) { return ERR_UNAVAILABLE; } diff --git a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs index 5544233eb7..04da0600cc 100644 --- a/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs +++ b/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs @@ -4,6 +4,7 @@ using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using System.Security; using Microsoft.Build.Framework; @@ -12,22 +13,27 @@ namespace GodotSharpTools.Build public class BuildInstance : IDisposable { [MethodImpl(MethodImplOptions.InternalCall)] - internal extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode); + private extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode); [MethodImpl(MethodImplOptions.InternalCall)] - internal extern static string godot_icall_BuildInstance_get_MSBuildPath(); + private extern static void godot_icall_BuildInstance_get_MSBuildInfo(ref string msbuildPath, ref string frameworkPath); - private static string MSBuildPath + private struct MSBuildInfo { - get - { - string ret = godot_icall_BuildInstance_get_MSBuildPath(); + public string path; + public string frameworkPathOverride; + } - if (ret == null) - throw new FileNotFoundException("Cannot find the MSBuild executable."); + private static MSBuildInfo GetMSBuildInfo() + { + MSBuildInfo msbuildInfo = new MSBuildInfo(); - return ret; - } + godot_icall_BuildInstance_get_MSBuildInfo(ref msbuildInfo.path, ref msbuildInfo.frameworkPathOverride); + + if (msbuildInfo.path == null) + throw new FileNotFoundException("Cannot find the MSBuild executable."); + + return msbuildInfo; } private string solution; @@ -48,9 +54,19 @@ namespace GodotSharpTools.Build public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null) { - string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties); + MSBuildInfo msbuildInfo = GetMSBuildInfo(); + + List<string> customPropertiesList = new List<string>(); + + if (customProperties != null) + customPropertiesList.AddRange(customProperties); + + if (msbuildInfo.frameworkPathOverride != null) + customPropertiesList.Add("FrameworkPathOverride=" + msbuildInfo.frameworkPathOverride); - ProcessStartInfo startInfo = new ProcessStartInfo(MSBuildPath, compilerArgs); + string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); + + ProcessStartInfo startInfo = new ProcessStartInfo(msbuildInfo.path, compilerArgs); // No console output, thanks startInfo.RedirectStandardOutput = true; @@ -82,9 +98,19 @@ namespace GodotSharpTools.Build if (process != null) throw new InvalidOperationException("Already in use"); - string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties); + MSBuildInfo msbuildInfo = GetMSBuildInfo(); + + List<string> customPropertiesList = new List<string>(); + + if (customProperties != null) + customPropertiesList.AddRange(customProperties); + + if (msbuildInfo.frameworkPathOverride.Length > 0) + customPropertiesList.Add("FrameworkPathOverride=" + msbuildInfo.frameworkPathOverride); - ProcessStartInfo startInfo = new ProcessStartInfo("msbuild", compilerArgs); + string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); + + ProcessStartInfo startInfo = new ProcessStartInfo(msbuildInfo.path, compilerArgs); // No console output, thanks startInfo.RedirectStandardOutput = true; @@ -101,10 +127,13 @@ namespace GodotSharpTools.Build process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + return true; } - private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties) + private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, List<string> customProperties) { string arguments = string.Format(@"""{0}"" /v:normal /t:Build ""/p:{1}"" ""/l:{2},{3};{4}""", solution, @@ -114,12 +143,9 @@ namespace GodotSharpTools.Build loggerOutputDir ); - if (customProperties != null) + foreach (string customProperty in customProperties) { - foreach (string customProperty in customProperties) - { - arguments += " /p:" + customProperty; - } + arguments += " \"/p:" + customProperty + "\""; } return arguments; diff --git a/modules/mono/editor/bindings_generator.cpp b/modules/mono/editor/bindings_generator.cpp index 704910c5b9..eb504ec021 100644 --- a/modules/mono/editor/bindings_generator.cpp +++ b/modules/mono/editor/bindings_generator.cpp @@ -108,36 +108,6 @@ const char *BindingsGenerator::TypeInterface::DEFAULT_VARARG_C_IN = "\t%0 %1_in bool BindingsGenerator::verbose_output = false; -static bool is_csharp_keyword(const String &p_name) { - - // Reserved keywords - - return p_name == "abstract" || p_name == "as" || p_name == "base" || p_name == "bool" || - p_name == "break" || p_name == "byte" || p_name == "case" || p_name == "catch" || - p_name == "char" || p_name == "checked" || p_name == "class" || p_name == "const" || - p_name == "continue" || p_name == "decimal" || p_name == "default" || p_name == "delegate" || - p_name == "do" || p_name == "double" || p_name == "else" || p_name == "enum" || - p_name == "event" || p_name == "explicit" || p_name == "extern" || p_name == "false" || - p_name == "finally" || p_name == "fixed" || p_name == "float" || p_name == "for" || - p_name == "forech" || p_name == "goto" || p_name == "if" || p_name == "implicit" || - p_name == "in" || p_name == "int" || p_name == "interface" || p_name == "internal" || - p_name == "is" || p_name == "lock" || p_name == "long" || p_name == "namespace" || - p_name == "new" || p_name == "null" || p_name == "object" || p_name == "operator" || - p_name == "out" || p_name == "override" || p_name == "params" || p_name == "private" || - p_name == "protected" || p_name == "public" || p_name == "readonly" || p_name == "ref" || - p_name == "return" || p_name == "sbyte" || p_name == "sealed" || p_name == "short" || - p_name == "sizeof" || p_name == "stackalloc" || p_name == "static" || p_name == "string" || - p_name == "struct" || p_name == "switch" || p_name == "this" || p_name == "throw" || - p_name == "true" || p_name == "try" || p_name == "typeof" || p_name == "uint" || p_name == "ulong" || - p_name == "unchecked" || p_name == "unsafe" || p_name == "ushort" || p_name == "using" || - p_name == "virtual" || p_name == "volatile" || p_name == "void" || p_name == "while"; -} - -inline static String escape_csharp_keyword(const String &p_name) { - - return is_csharp_keyword(p_name) ? "@" + p_name : p_name; -} - static String snake_to_pascal_case(const String &p_identifier) { String ret; @@ -468,6 +438,9 @@ Error BindingsGenerator::generate_cs_core_project(const String &p_output_dir, bo return sln_error; } + if (verbose_output) + OS::get_singleton()->print("The solution and C# project for the Core API was generated successfully\n"); + return OK; } @@ -560,6 +533,9 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_output_dir, return sln_error; } + if (verbose_output) + OS::get_singleton()->print("The solution and C# project for the Editor API was generated successfully\n"); + return OK; } @@ -567,8 +543,6 @@ Error BindingsGenerator::generate_cs_editor_project(const String &p_output_dir, // e.g.: warning CS0108: 'SpriteBase3D.FLAG_MAX' hides inherited member 'GeometryInstance.FLAG_MAX'. Use the new keyword if hiding was intended. Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) { - int method_bind_count = 0; - bool is_derived_type = itype.base_name.length(); List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls; @@ -578,51 +552,51 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); - List<String> cs_file; + List<String> output; - cs_file.push_back("using System;\n"); // IntPtr + output.push_back("using System;\n"); // IntPtr if (itype.requires_collections) - cs_file.push_back("using System.Collections.Generic;\n"); // Dictionary + output.push_back("using System.Collections.Generic;\n"); // Dictionary - cs_file.push_back("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); + output.push_back("\nnamespace " BINDINGS_NAMESPACE "\n" OPEN_BLOCK); const DocData::ClassDoc *class_doc = itype.class_doc; if (class_doc && class_doc->description.size()) { - cs_file.push_back(INDENT1 "/// <summary>\n"); + output.push_back(INDENT1 "/// <summary>\n"); Vector<String> description_lines = class_doc->description.split("\n"); for (int i = 0; i < description_lines.size(); i++) { if (description_lines[i].size()) { - cs_file.push_back(INDENT1 "/// "); - cs_file.push_back(description_lines[i].strip_edges().xml_escape()); - cs_file.push_back("\n"); + output.push_back(INDENT1 "/// "); + output.push_back(description_lines[i].strip_edges().xml_escape()); + output.push_back("\n"); } } - cs_file.push_back(INDENT1 "/// </summary>\n"); + output.push_back(INDENT1 "/// </summary>\n"); } - cs_file.push_back(INDENT1 "public "); - cs_file.push_back(itype.is_singleton ? "static class " : "class "); - cs_file.push_back(itype.proxy_name); + output.push_back(INDENT1 "public "); + output.push_back(itype.is_singleton ? "static class " : "class "); + output.push_back(itype.proxy_name); if (itype.is_singleton || !itype.is_object_type) { - cs_file.push_back("\n"); + output.push_back("\n"); } else if (!is_derived_type) { - cs_file.push_back(" : IDisposable\n"); + output.push_back(" : IDisposable\n"); } else if (obj_types.has(itype.base_name)) { - cs_file.push_back(" : "); - cs_file.push_back(obj_types[itype.base_name].proxy_name); - cs_file.push_back("\n"); + output.push_back(" : "); + output.push_back(obj_types[itype.base_name].proxy_name); + output.push_back("\n"); } else { - ERR_PRINTS("Base type ' " + itype.base_name + "' does not exist"); + ERR_PRINTS("Base type '" + itype.base_name + "' does not exist, for class " + itype.name); return ERR_INVALID_DATA; } - cs_file.push_back(INDENT1 "{"); + output.push_back(INDENT1 "{"); if (class_doc) { @@ -632,270 +606,165 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str const DocData::ConstantDoc &const_doc = class_doc->constants[i]; if (const_doc.description.size()) { - cs_file.push_back(MEMBER_BEGIN "/// <summary>\n"); + output.push_back(MEMBER_BEGIN "/// <summary>\n"); Vector<String> description_lines = const_doc.description.split("\n"); for (int i = 0; i < description_lines.size(); i++) { if (description_lines[i].size()) { - cs_file.push_back(INDENT2 "/// "); - cs_file.push_back(description_lines[i].strip_edges().xml_escape()); - cs_file.push_back("\n"); + output.push_back(INDENT2 "/// "); + output.push_back(description_lines[i].strip_edges().xml_escape()); + output.push_back("\n"); } } - cs_file.push_back(INDENT2 "/// </summary>"); + output.push_back(INDENT2 "/// </summary>"); } - cs_file.push_back(MEMBER_BEGIN "public const int "); - cs_file.push_back(const_doc.name); - cs_file.push_back(" = "); - cs_file.push_back(const_doc.value); - cs_file.push_back(";"); + output.push_back(MEMBER_BEGIN "public const int "); + output.push_back(const_doc.name); + output.push_back(" = "); + output.push_back(const_doc.value); + output.push_back(";"); } if (class_doc->constants.size()) - cs_file.push_back("\n"); + output.push_back("\n"); // Add properties - const Vector<DocData::PropertyDoc> &properties = itype.class_doc->properties; + const Vector<DocData::PropertyDoc> &properties = class_doc->properties; for (int i = 0; i < properties.size(); i++) { const DocData::PropertyDoc &prop_doc = properties[i]; - - const MethodInterface *setter = itype.find_method_by_name(prop_doc.setter); - - // Search it in base types too - const TypeInterface *current_type = &itype; - while (!setter && current_type->base_name.length()) { - Map<String, TypeInterface>::Element *base_match = obj_types.find(current_type->base_name); - ERR_FAIL_NULL_V(base_match, ERR_BUG); - current_type = &base_match->get(); - setter = current_type->find_method_by_name(prop_doc.setter); - } - - const MethodInterface *getter = itype.find_method_by_name(prop_doc.getter); - - // Search it in base types too - current_type = &itype; - while (!getter && current_type->base_name.length()) { - Map<String, TypeInterface>::Element *base_match = obj_types.find(current_type->base_name); - ERR_FAIL_NULL_V(base_match, ERR_BUG); - current_type = &base_match->get(); - getter = current_type->find_method_by_name(prop_doc.getter); + Error prop_err = _generate_cs_property(itype, prop_doc, output); + if (prop_err != OK) { + ERR_EXPLAIN("Failed to generate property '" + prop_doc.name + "' for class '" + itype.name + "'"); + ERR_FAIL_V(prop_err); } - - ERR_FAIL_COND_V(!setter && !getter, ERR_BUG); - - bool is_valid = false; - int prop_index = ClassDB::get_property_index(itype.name, prop_doc.name, &is_valid); - ERR_FAIL_COND_V(!is_valid, ERR_BUG); - - if (setter) { - int setter_argc = prop_index != -1 ? 2 : 1; - ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG); - } - - if (getter) { - int getter_argc = prop_index != -1 ? 1 : 0; - ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG); - } - - if (getter && setter) { - ERR_FAIL_COND_V(getter->return_type != setter->arguments.back()->get().type, ERR_BUG); - } - - // Let's not trust PropertyDoc::type - String proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type; - - const TypeInterface *prop_itype = _get_type_by_name_or_null(proptype_name); - if (!prop_itype) { - // Try with underscore prefix - prop_itype = _get_type_by_name_or_null("_" + proptype_name); - } - - ERR_FAIL_NULL_V(prop_itype, ERR_BUG); - - String prop_proxy_name = escape_csharp_keyword(snake_to_pascal_case(prop_doc.name)); - - // Prevent property and enclosing type from sharing the same name - if (prop_proxy_name == itype.proxy_name) { - if (verbose_output) { - WARN_PRINTS("Name of property `" + prop_proxy_name + "` is ambiguous with the name of its class `" + - itype.proxy_name + "`. Renaming property to `" + prop_proxy_name + "_`"); - } - - prop_proxy_name += "_"; - } - - if (prop_doc.description.size()) { - cs_file.push_back(MEMBER_BEGIN "/// <summary>\n"); - - Vector<String> description_lines = prop_doc.description.split("\n"); - - for (int i = 0; i < description_lines.size(); i++) { - if (description_lines[i].size()) { - cs_file.push_back(INDENT2 "/// "); - cs_file.push_back(description_lines[i].strip_edges().xml_escape()); - cs_file.push_back("\n"); - } - } - - cs_file.push_back(INDENT2 "/// </summary>"); - } - - cs_file.push_back(MEMBER_BEGIN "public "); - - if (itype.is_singleton) - cs_file.push_back("static "); - - cs_file.push_back(prop_itype->cs_type); - cs_file.push_back(" "); - cs_file.push_back(prop_proxy_name.replace("/", "__")); - cs_file.push_back("\n" INDENT2 OPEN_BLOCK); - - if (getter) { - cs_file.push_back(INDENT3 "get\n" OPEN_BLOCK_L3); - cs_file.push_back("return "); - cs_file.push_back(getter->proxy_name + "("); - if (prop_index != -1) - cs_file.push_back(itos(prop_index)); - cs_file.push_back(");\n" CLOSE_BLOCK_L3); - } - - if (setter) { - cs_file.push_back(INDENT3 "set\n" OPEN_BLOCK_L3); - cs_file.push_back(setter->proxy_name + "("); - if (prop_index != -1) - cs_file.push_back(itos(prop_index) + ", "); - cs_file.push_back("value);\n" CLOSE_BLOCK_L3); - } - - cs_file.push_back(CLOSE_BLOCK_L2); } if (class_doc->properties.size()) - cs_file.push_back("\n"); + output.push_back("\n"); } if (!itype.is_object_type) { - cs_file.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"" + itype.name + "\";\n"); - cs_file.push_back(MEMBER_BEGIN "private bool disposed = false;\n"); - cs_file.push_back(MEMBER_BEGIN "internal IntPtr " BINDINGS_PTR_FIELD ";\n"); + output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \"" + itype.name + "\";\n"); + output.push_back(MEMBER_BEGIN "private bool disposed = false;\n"); + output.push_back(MEMBER_BEGIN "internal IntPtr " BINDINGS_PTR_FIELD ";\n"); - cs_file.push_back(MEMBER_BEGIN "internal static IntPtr " CS_SMETHOD_GETINSTANCE "("); - cs_file.push_back(itype.proxy_name); - cs_file.push_back(" instance)\n" OPEN_BLOCK_L2 "return instance == null ? IntPtr.Zero : instance." BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "internal static IntPtr " CS_SMETHOD_GETINSTANCE "("); + output.push_back(itype.proxy_name); + output.push_back(" instance)\n" OPEN_BLOCK_L2 "return instance == null ? IntPtr.Zero : instance." BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); // Add Destructor - cs_file.push_back(MEMBER_BEGIN "~"); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("()\n" OPEN_BLOCK_L2 "Dispose(false);\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "~"); + output.push_back(itype.proxy_name); + output.push_back("()\n" OPEN_BLOCK_L2 "Dispose(false);\n" CLOSE_BLOCK_L2); // Add the Dispose from IDisposable - cs_file.push_back(MEMBER_BEGIN "public void Dispose()\n" OPEN_BLOCK_L2 "Dispose(true);\n" INDENT3 "GC.SuppressFinalize(this);\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public void Dispose()\n" OPEN_BLOCK_L2 "Dispose(true);\n" INDENT3 "GC.SuppressFinalize(this);\n" CLOSE_BLOCK_L2); // Add the virtual Dispose - cs_file.push_back(MEMBER_BEGIN "public virtual void Dispose(bool disposing)\n" OPEN_BLOCK_L2 - "if (disposed) return;\n" INDENT3 - "if (" BINDINGS_PTR_FIELD " != IntPtr.Zero)\n" OPEN_BLOCK_L3 "NativeCalls.godot_icall_"); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("_Dtor(" BINDINGS_PTR_FIELD ");\n" INDENT5 BINDINGS_PTR_FIELD " = IntPtr.Zero;\n" CLOSE_BLOCK_L3 INDENT3 - "GC.SuppressFinalize(this);\n" INDENT3 "disposed = true;\n" CLOSE_BLOCK_L2); - - cs_file.push_back(MEMBER_BEGIN "internal "); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("(IntPtr " BINDINGS_PTR_FIELD ")\n" OPEN_BLOCK_L2 "this." BINDINGS_PTR_FIELD " = " BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); - - cs_file.push_back(MEMBER_BEGIN "public bool HasValidHandle()\n" OPEN_BLOCK_L2 - "return " BINDINGS_PTR_FIELD " == IntPtr.Zero;\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public virtual void Dispose(bool disposing)\n" OPEN_BLOCK_L2 + "if (disposed) return;\n" INDENT3 + "if (" BINDINGS_PTR_FIELD " != IntPtr.Zero)\n" OPEN_BLOCK_L3 "NativeCalls.godot_icall_"); + output.push_back(itype.proxy_name); + output.push_back("_Dtor(" BINDINGS_PTR_FIELD ");\n" INDENT5 BINDINGS_PTR_FIELD " = IntPtr.Zero;\n" CLOSE_BLOCK_L3 INDENT3 + "GC.SuppressFinalize(this);\n" INDENT3 "disposed = true;\n" CLOSE_BLOCK_L2); + + output.push_back(MEMBER_BEGIN "internal "); + output.push_back(itype.proxy_name); + output.push_back("(IntPtr " BINDINGS_PTR_FIELD ")\n" OPEN_BLOCK_L2 "this." BINDINGS_PTR_FIELD " = " BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); + + output.push_back(MEMBER_BEGIN "public IntPtr NativeInstance\n" OPEN_BLOCK_L2 + "get { return " BINDINGS_PTR_FIELD "; }\n" CLOSE_BLOCK_L2); } else if (itype.is_singleton) { // Add the type name and the singleton pointer as static fields - cs_file.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); - cs_file.push_back(itype.name); - cs_file.push_back("\";\n"); + output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); + output.push_back(itype.name); + output.push_back("\";\n"); - cs_file.push_back(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = "); - cs_file.push_back(itype.api_type == ClassDB::API_EDITOR ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); - cs_file.push_back("." ICALL_PREFIX); - cs_file.push_back(itype.name); - cs_file.push_back(SINGLETON_ICALL_SUFFIX "();\n"); + output.push_back(INDENT2 "internal static IntPtr " BINDINGS_PTR_FIELD " = "); + output.push_back(itype.api_type == ClassDB::API_EDITOR ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); + output.push_back("." ICALL_PREFIX); + output.push_back(itype.name); + output.push_back(SINGLETON_ICALL_SUFFIX "();\n"); } else { // Add member fields - cs_file.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); - cs_file.push_back(itype.name); - cs_file.push_back("\";\n"); + output.push_back(MEMBER_BEGIN "private const string " BINDINGS_NATIVE_NAME_FIELD " = \""); + output.push_back(itype.name); + output.push_back("\";\n"); // Only the base class stores the pointer to the native object // This pointer is expected to be and must be of type Object* if (!is_derived_type) { - cs_file.push_back(MEMBER_BEGIN "private bool disposed = false;\n"); - cs_file.push_back(INDENT2 "internal IntPtr " BINDINGS_PTR_FIELD ";\n"); - cs_file.push_back(INDENT2 "internal bool " CS_FIELD_MEMORYOWN ";\n"); + output.push_back(MEMBER_BEGIN "private bool disposed = false;\n"); + output.push_back(INDENT2 "internal IntPtr " BINDINGS_PTR_FIELD ";\n"); + output.push_back(INDENT2 "internal bool " CS_FIELD_MEMORYOWN ";\n"); } // Add default constructor if (itype.is_instantiable) { - cs_file.push_back(MEMBER_BEGIN "public "); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("() : this("); - cs_file.push_back(itype.memory_own ? "true" : "false"); + output.push_back(MEMBER_BEGIN "public "); + output.push_back(itype.proxy_name); + output.push_back("() : this("); + output.push_back(itype.memory_own ? "true" : "false"); // The default constructor may also be called by the engine when instancing existing native objects // The engine will initialize the pointer field of the managed side before calling the constructor // This is why we only allocate a new native object from the constructor if the pointer field is not set - cs_file.push_back(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = "); - cs_file.push_back(itype.api_type == ClassDB::API_EDITOR ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); - cs_file.push_back("." + ctor_method); - cs_file.push_back("(this);\n" CLOSE_BLOCK_L2); + output.push_back(")\n" OPEN_BLOCK_L2 "if (" BINDINGS_PTR_FIELD " == IntPtr.Zero)\n" INDENT4 BINDINGS_PTR_FIELD " = "); + output.push_back(itype.api_type == ClassDB::API_EDITOR ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); + output.push_back("." + ctor_method); + output.push_back("(this);\n" CLOSE_BLOCK_L2); } else { // Hide the constructor - cs_file.push_back(MEMBER_BEGIN "internal "); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("() {}\n"); + output.push_back(MEMBER_BEGIN "internal "); + output.push_back(itype.proxy_name); + output.push_back("() {}\n"); } // Add.. em.. trick constructor. Sort of. - cs_file.push_back(MEMBER_BEGIN "internal "); - cs_file.push_back(itype.proxy_name); + output.push_back(MEMBER_BEGIN "internal "); + output.push_back(itype.proxy_name); if (is_derived_type) { - cs_file.push_back("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n"); + output.push_back("(bool " CS_FIELD_MEMORYOWN ") : base(" CS_FIELD_MEMORYOWN ") {}\n"); } else { - cs_file.push_back("(bool " CS_FIELD_MEMORYOWN ")\n" OPEN_BLOCK_L2 - "this." CS_FIELD_MEMORYOWN " = " CS_FIELD_MEMORYOWN ";\n" CLOSE_BLOCK_L2); + output.push_back("(bool " CS_FIELD_MEMORYOWN ")\n" OPEN_BLOCK_L2 + "this." CS_FIELD_MEMORYOWN " = " CS_FIELD_MEMORYOWN ";\n" CLOSE_BLOCK_L2); } // Add methods if (!is_derived_type) { - cs_file.push_back(MEMBER_BEGIN "public bool HasValidHandle()\n" OPEN_BLOCK_L2 - "return " BINDINGS_PTR_FIELD " == IntPtr.Zero;\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public IntPtr NativeInstance\n" OPEN_BLOCK_L2 + "get { return " BINDINGS_PTR_FIELD "; }\n" CLOSE_BLOCK_L2); - cs_file.push_back(MEMBER_BEGIN "internal static IntPtr " CS_SMETHOD_GETINSTANCE "(Object instance)\n" OPEN_BLOCK_L2 - "return instance == null ? IntPtr.Zero : instance." BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "internal static IntPtr " CS_SMETHOD_GETINSTANCE "(Object instance)\n" OPEN_BLOCK_L2 + "return instance == null ? IntPtr.Zero : instance." BINDINGS_PTR_FIELD ";\n" CLOSE_BLOCK_L2); } if (!is_derived_type) { // Add destructor - cs_file.push_back(MEMBER_BEGIN "~"); - cs_file.push_back(itype.proxy_name); - cs_file.push_back("()\n" OPEN_BLOCK_L2 "Dispose(false);\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "~"); + output.push_back(itype.proxy_name); + output.push_back("()\n" OPEN_BLOCK_L2 "Dispose(false);\n" CLOSE_BLOCK_L2); // Add the Dispose from IDisposable - cs_file.push_back(MEMBER_BEGIN "public void Dispose()\n" OPEN_BLOCK_L2 "Dispose(true);\n" INDENT3 "GC.SuppressFinalize(this);\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public void Dispose()\n" OPEN_BLOCK_L2 "Dispose(true);\n" INDENT3 "GC.SuppressFinalize(this);\n" CLOSE_BLOCK_L2); // Add the virtual Dispose - cs_file.push_back(MEMBER_BEGIN "public virtual void Dispose(bool disposing)\n" OPEN_BLOCK_L2 - "if (disposed) return;\n" INDENT3 - "if (" BINDINGS_PTR_FIELD " != IntPtr.Zero)\n" OPEN_BLOCK_L3 - "if (" CS_FIELD_MEMORYOWN ")\n" OPEN_BLOCK_L4 CS_FIELD_MEMORYOWN - " = false;\n" INDENT5 CS_CLASS_NATIVECALLS "." ICALL_OBJECT_DTOR - "(" BINDINGS_PTR_FIELD ");\n" INDENT5 BINDINGS_PTR_FIELD - " = IntPtr.Zero;\n" CLOSE_BLOCK_L4 CLOSE_BLOCK_L3 INDENT3 - "GC.SuppressFinalize(this);\n" INDENT3 "disposed = true;\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public virtual void Dispose(bool disposing)\n" OPEN_BLOCK_L2 + "if (disposed) return;\n" INDENT3 + "if (" BINDINGS_PTR_FIELD " != IntPtr.Zero)\n" OPEN_BLOCK_L3 + "if (" CS_FIELD_MEMORYOWN ")\n" OPEN_BLOCK_L4 CS_FIELD_MEMORYOWN + " = false;\n" INDENT5 CS_CLASS_NATIVECALLS "." ICALL_OBJECT_DTOR + "(" BINDINGS_PTR_FIELD ");\n" INDENT5 BINDINGS_PTR_FIELD + " = IntPtr.Zero;\n" CLOSE_BLOCK_L4 CLOSE_BLOCK_L3 INDENT3 + "GC.SuppressFinalize(this);\n" INDENT3 "disposed = true;\n" CLOSE_BLOCK_L2); Map<String, TypeInterface>::Element *array_itype = builtin_types.find("Array"); @@ -904,416 +773,390 @@ Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const Str return ERR_BUG; } - cs_file.push_back(MEMBER_BEGIN "private void _AwaitedSignalCallback("); - cs_file.push_back(array_itype->get().cs_type); - cs_file.push_back(" args, SignalAwaiter awaiter)\n" OPEN_BLOCK_L2 "awaiter.SignalCallback(args);\n" CLOSE_BLOCK_L2); - Map<String, TypeInterface>::Element *object_itype = obj_types.find("Object"); if (!object_itype) { - ERR_PRINT("BUG: Array type interface not found!"); + ERR_PRINT("BUG: Object type interface not found!"); return ERR_BUG; } - cs_file.push_back(MEMBER_BEGIN "public " CS_CLASS_SIGNALAWAITER " ToSignal("); - cs_file.push_back(object_itype->get().cs_type); - cs_file.push_back(" source, string signal)\n" OPEN_BLOCK_L2 - "return new " CS_CLASS_SIGNALAWAITER "(source, signal, this);\n" CLOSE_BLOCK_L2); + output.push_back(MEMBER_BEGIN "public " CS_CLASS_SIGNALAWAITER " ToSignal("); + output.push_back(object_itype->get().cs_type); + output.push_back(" source, string signal)\n" OPEN_BLOCK_L2 + "return new " CS_CLASS_SIGNALAWAITER "(source, signal, this);\n" CLOSE_BLOCK_L2); } } Map<String, String>::Element *extra_member = extra_members.find(itype.name); if (extra_member) - cs_file.push_back(extra_member->get()); + output.push_back(extra_member->get()); + int method_bind_count = 0; for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { const MethodInterface &imethod = E->get(); + Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output); + if (method_err != OK) { + ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'"); + ERR_FAIL_V(method_err); + } + } - const TypeInterface *return_type = _get_type_by_name_or_placeholder(imethod.return_type); + if (itype.is_singleton) { + InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr"); - String method_bind_field = "method_bind_" + itos(method_bind_count); + if (!find_icall_by_name(singleton_icall.name, custom_icalls)) + custom_icalls.push_back(singleton_icall); + } - String icall_params = method_bind_field + ", " + sformat(itype.cs_in, "this"); - String arguments_sig; - String cs_in_statements; + if (itype.is_instantiable) { + InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj"); - List<String> default_args_doc; + if (!find_icall_by_name(ctor_icall.name, custom_icalls)) + custom_icalls.push_back(ctor_icall); + } - // Retrieve information from the arguments - for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) { - const ArgumentInterface &iarg = F->get(); - const TypeInterface *arg_type = _get_type_by_name_or_placeholder(iarg.type); + output.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); - // Add the current arguments to the signature - // If the argument has a default value which is not a constant, we will make it Nullable - { - if (F != imethod.arguments.front()) - arguments_sig += ", "; + return _save_file(p_output_file, output); +} - if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) - arguments_sig += "Nullable<"; +Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const DocData::PropertyDoc &p_prop_doc, List<String> &p_output) { - arguments_sig += arg_type->cs_type; + const MethodInterface *setter = p_itype.find_method_by_name(p_prop_doc.setter); - if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) - arguments_sig += "> "; - else - arguments_sig += " "; + // Search it in base types too + const TypeInterface *current_type = &p_itype; + while (!setter && current_type->base_name.length()) { + Map<String, TypeInterface>::Element *base_match = obj_types.find(current_type->base_name); + ERR_FAIL_NULL_V(base_match, ERR_BUG); + current_type = &base_match->get(); + setter = current_type->find_method_by_name(p_prop_doc.setter); + } - arguments_sig += iarg.name; + const MethodInterface *getter = p_itype.find_method_by_name(p_prop_doc.getter); - if (iarg.default_argument.size()) { - if (iarg.def_param_mode != ArgumentInterface::CONSTANT) - arguments_sig += " = null"; - else - arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type); - } - } + // Search it in base types too + current_type = &p_itype; + while (!getter && current_type->base_name.length()) { + Map<String, TypeInterface>::Element *base_match = obj_types.find(current_type->base_name); + ERR_FAIL_NULL_V(base_match, ERR_BUG); + current_type = &base_match->get(); + getter = current_type->find_method_by_name(p_prop_doc.getter); + } - icall_params += ", "; + ERR_FAIL_COND_V(!setter && !getter, ERR_BUG); - if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) { - // The default value of an argument must be constant. Otherwise we make it Nullable and do the following: - // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>; - String arg_in = iarg.name; - arg_in += "_in"; + bool is_valid = false; + int prop_index = ClassDB::get_property_index(p_itype.name, p_prop_doc.name, &is_valid); + ERR_FAIL_COND_V(!is_valid, ERR_BUG); - cs_in_statements += arg_type->cs_type; - cs_in_statements += " "; - cs_in_statements += arg_in; - cs_in_statements += " = "; - cs_in_statements += iarg.name; + if (setter) { + int setter_argc = prop_index != -1 ? 2 : 1; + ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG); + } - if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) - cs_in_statements += ".HasValue ? "; - else - cs_in_statements += " != null ? "; + if (getter) { + int getter_argc = prop_index != -1 ? 1 : 0; + ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG); + } - cs_in_statements += iarg.name; + if (getter && setter) { + ERR_FAIL_COND_V(getter->return_type != setter->arguments.back()->get().type, ERR_BUG); + } - if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) - cs_in_statements += ".Value : "; - else - cs_in_statements += " : "; + // Let's not trust PropertyDoc::type + String proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type; - String def_arg = sformat(iarg.default_argument, arg_type->cs_type); + const TypeInterface *prop_itype = _get_type_by_name_or_null(proptype_name); + if (!prop_itype) { + // Try with underscore prefix + prop_itype = _get_type_by_name_or_null("_" + proptype_name); + } - cs_in_statements += def_arg; - cs_in_statements += ";\n" INDENT3; + ERR_FAIL_NULL_V(prop_itype, ERR_BUG); - icall_params += arg_type->cs_in.empty() ? arg_in : sformat(arg_type->cs_in, arg_in); + String prop_proxy_name = escape_csharp_keyword(snake_to_pascal_case(p_prop_doc.name)); - default_args_doc.push_back(INDENT2 "/// <param name=\"" + iarg.name + "\">If the param is null, then the default value is " + def_arg + "</param>\n"); - } else { - icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name); - } + // Prevent property and enclosing type from sharing the same name + if (prop_proxy_name == p_itype.proxy_name) { + if (verbose_output) { + WARN_PRINTS("Name of property `" + prop_proxy_name + "` is ambiguous with the name of its class `" + + p_itype.proxy_name + "`. Renaming property to `" + prop_proxy_name + "_`"); } - // Generate method - { - if (!imethod.is_virtual && !imethod.requires_object_call) { - cs_file.push_back(MEMBER_BEGIN "private "); - cs_file.push_back(itype.is_singleton ? "static IntPtr " : "IntPtr "); - cs_file.push_back(method_bind_field + " = " CS_CLASS_NATIVECALLS "." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \""); - cs_file.push_back(imethod.name); - cs_file.push_back("\");\n"); - } + prop_proxy_name += "_"; + } - if (imethod.method_doc && imethod.method_doc->description.size()) { - cs_file.push_back(MEMBER_BEGIN "/// <summary>\n"); + if (p_prop_doc.description.size()) { + p_output.push_back(MEMBER_BEGIN "/// <summary>\n"); - Vector<String> description_lines = imethod.method_doc->description.split("\n"); + Vector<String> description_lines = p_prop_doc.description.split("\n"); - for (int i = 0; i < description_lines.size(); i++) { - if (description_lines[i].size()) { - cs_file.push_back(INDENT2 "/// "); - cs_file.push_back(description_lines[i].strip_edges().xml_escape()); - cs_file.push_back("\n"); - } - } + for (int i = 0; i < description_lines.size(); i++) { + if (description_lines[i].size()) { + p_output.push_back(INDENT2 "/// "); + p_output.push_back(description_lines[i].strip_edges().xml_escape()); + p_output.push_back("\n"); + } + } - for (List<String>::Element *E = default_args_doc.front(); E; E = E->next()) { - cs_file.push_back(E->get().xml_escape()); - } + p_output.push_back(INDENT2 "/// </summary>"); + } - cs_file.push_back(INDENT2 "/// </summary>"); - } + p_output.push_back(MEMBER_BEGIN "public "); - if (!imethod.is_internal) { - cs_file.push_back(MEMBER_BEGIN "[GodotMethod(\""); - cs_file.push_back(imethod.name); - cs_file.push_back("\")]"); - } + if (p_itype.is_singleton) + p_output.push_back("static "); - cs_file.push_back(MEMBER_BEGIN); - cs_file.push_back(imethod.is_internal ? "internal " : "public "); + p_output.push_back(prop_itype->cs_type); + p_output.push_back(" "); + p_output.push_back(prop_proxy_name.replace("/", "__")); + p_output.push_back("\n" INDENT2 OPEN_BLOCK); - if (itype.is_singleton) { - cs_file.push_back("static "); - } else if (imethod.is_virtual) { - cs_file.push_back("virtual "); - } + if (getter) { + p_output.push_back(INDENT3 "get\n" OPEN_BLOCK_L3); + p_output.push_back("return "); + p_output.push_back(getter->proxy_name + "("); + if (prop_index != -1) + p_output.push_back(itos(prop_index)); + p_output.push_back(");\n" CLOSE_BLOCK_L3); + } - cs_file.push_back(return_type->cs_type + " "); - cs_file.push_back(imethod.proxy_name + "("); - cs_file.push_back(arguments_sig + ")\n" OPEN_BLOCK_L2); + if (setter) { + p_output.push_back(INDENT3 "set\n" OPEN_BLOCK_L3); + p_output.push_back(setter->proxy_name + "("); + if (prop_index != -1) + p_output.push_back(itos(prop_index) + ", "); + p_output.push_back("value);\n" CLOSE_BLOCK_L3); + } - if (imethod.is_virtual) { - // Godot virtual method must be overridden, therefore we return a default value by default. + p_output.push_back(CLOSE_BLOCK_L2); - if (return_type->name == "void") { - cs_file.push_back("return;\n" CLOSE_BLOCK_L2); - } else { - cs_file.push_back("return default("); - cs_file.push_back(return_type->cs_type); - cs_file.push_back(");\n" CLOSE_BLOCK_L2); - } + return OK; +} - continue; - } +Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, List<String> &p_output) { - if (imethod.requires_object_call) { - // Fallback to Godot's object.Call(string, params) + const TypeInterface *return_type = _get_type_by_name_or_placeholder(p_imethod.return_type); - cs_file.push_back(CS_METHOD_CALL "(\""); - cs_file.push_back(imethod.name); - cs_file.push_back("\""); + String method_bind_field = "method_bind_" + itos(p_method_bind_count); - for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) { - cs_file.push_back(", "); - cs_file.push_back(F->get().name); - } + String icall_params = method_bind_field + ", " + sformat(p_itype.cs_in, "this"); + String arguments_sig; + String cs_in_statements; - cs_file.push_back(");\n" CLOSE_BLOCK_L2); + List<String> default_args_doc; - continue; - } + // Retrieve information from the arguments + for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { + const ArgumentInterface &iarg = F->get(); + const TypeInterface *arg_type = _get_type_by_name_or_placeholder(iarg.type); - const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&E->get()); - ERR_FAIL_NULL_V(match, ERR_BUG); + // Add the current arguments to the signature + // If the argument has a default value which is not a constant, we will make it Nullable + { + if (F != p_imethod.arguments.front()) + arguments_sig += ", "; - const InternalCall *im_icall = match->value(); + if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) + arguments_sig += "Nullable<"; - String im_call = im_icall->editor_only ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS; - im_call += "." + im_icall->name + "(" + icall_params + ");\n"; + arguments_sig += arg_type->cs_type; - if (imethod.arguments.size()) - cs_file.push_back(cs_in_statements); + if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) + arguments_sig += "> "; + else + arguments_sig += " "; - if (return_type->name == "void") { - cs_file.push_back(im_call); - } else if (return_type->cs_out.empty()) { - cs_file.push_back("return " + im_call); - } else { - cs_file.push_back(return_type->im_type_out); - cs_file.push_back(" " LOCAL_RET " = "); - cs_file.push_back(im_call); - cs_file.push_back(INDENT3); - cs_file.push_back(sformat(return_type->cs_out, LOCAL_RET) + "\n"); - } + arguments_sig += iarg.name; - cs_file.push_back(CLOSE_BLOCK_L2); + if (iarg.default_argument.size()) { + if (iarg.def_param_mode != ArgumentInterface::CONSTANT) + arguments_sig += " = null"; + else + arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type); + } } - method_bind_count++; - } + icall_params += ", "; - if (itype.is_singleton) { - InternalCall singleton_icall = InternalCall(itype.api_type, ICALL_PREFIX + itype.name + SINGLETON_ICALL_SUFFIX, "IntPtr"); + if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) { + // The default value of an argument must be constant. Otherwise we make it Nullable and do the following: + // Type arg_in = arg.HasValue ? arg.Value : <non-const default value>; + String arg_in = iarg.name; + arg_in += "_in"; - if (!find_icall_by_name(singleton_icall.name, custom_icalls)) - custom_icalls.push_back(singleton_icall); - } + cs_in_statements += arg_type->cs_type; + cs_in_statements += " "; + cs_in_statements += arg_in; + cs_in_statements += " = "; + cs_in_statements += iarg.name; - if (itype.is_instantiable) { - InternalCall ctor_icall = InternalCall(itype.api_type, ctor_method, "IntPtr", itype.proxy_name + " obj"); + if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) + cs_in_statements += ".HasValue ? "; + else + cs_in_statements += " != null ? "; - if (!find_icall_by_name(ctor_icall.name, custom_icalls)) - custom_icalls.push_back(ctor_icall); - } + cs_in_statements += iarg.name; - cs_file.push_back(INDENT1 CLOSE_BLOCK CLOSE_BLOCK); + if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) + cs_in_statements += ".Value : "; + else + cs_in_statements += " : "; - return _save_file(p_output_file, cs_file); -} + String def_arg = sformat(iarg.default_argument, arg_type->cs_type); -Error BindingsGenerator::generate_glue(const String &p_output_dir) { + cs_in_statements += def_arg; + cs_in_statements += ";\n" INDENT3; - verbose_output = true; + icall_params += arg_type->cs_in.empty() ? arg_in : sformat(arg_type->cs_in, arg_in); - bool dir_exists = DirAccess::exists(p_output_dir); - ERR_EXPLAIN("The output directory does not exist."); - ERR_FAIL_COND_V(!dir_exists, ERR_FILE_BAD_PATH); + default_args_doc.push_back(INDENT2 "/// <param name=\"" + iarg.name + "\">If the param is null, then the default value is " + def_arg + "</param>\n"); + } else { + icall_params += arg_type->cs_in.empty() ? iarg.name : sformat(arg_type->cs_in, iarg.name); + } + } - List<String> cpp_file; + // Generate method + { + if (!p_imethod.is_virtual && !p_imethod.requires_object_call) { + p_output.push_back(MEMBER_BEGIN "private "); + p_output.push_back(p_itype.is_singleton ? "static IntPtr " : "IntPtr "); + p_output.push_back(method_bind_field + " = " CS_CLASS_NATIVECALLS "." ICALL_GET_METHODBIND "(" BINDINGS_NATIVE_NAME_FIELD ", \""); + p_output.push_back(p_imethod.name); + p_output.push_back("\");\n"); + } - cpp_file.push_back("#include \"" GLUE_HEADER_FILE "\"\n" - "\n"); + if (p_imethod.method_doc && p_imethod.method_doc->description.size()) { + p_output.push_back(MEMBER_BEGIN "/// <summary>\n"); - List<const InternalCall *> generated_icall_funcs; + Vector<String> description_lines = p_imethod.method_doc->description.split("\n"); - for (Map<String, TypeInterface>::Element *type_elem = obj_types.front(); type_elem; type_elem = type_elem->next()) { - const TypeInterface &itype = type_elem->get(); + for (int i = 0; i < description_lines.size(); i++) { + if (description_lines[i].size()) { + p_output.push_back(INDENT2 "/// "); + p_output.push_back(description_lines[i].strip_edges().xml_escape()); + p_output.push_back("\n"); + } + } - List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls; + for (List<String>::Element *E = default_args_doc.front(); E; E = E->next()) { + p_output.push_back(E->get().xml_escape()); + } - OS::get_singleton()->print(String("Generating " + itype.name + "...\n").utf8()); + p_output.push_back(INDENT2 "/// </summary>"); + } - String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); + if (!p_imethod.is_internal) { + p_output.push_back(MEMBER_BEGIN "[GodotMethod(\""); + p_output.push_back(p_imethod.name); + p_output.push_back("\")]"); + } - for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { - const MethodInterface &imethod = E->get(); + p_output.push_back(MEMBER_BEGIN); + p_output.push_back(p_imethod.is_internal ? "internal " : "public "); - if (imethod.is_virtual) - continue; + if (p_itype.is_singleton) { + p_output.push_back("static "); + } else if (p_imethod.is_virtual) { + p_output.push_back("virtual "); + } - bool ret_void = imethod.return_type == "void"; + p_output.push_back(return_type->cs_type + " "); + p_output.push_back(p_imethod.proxy_name + "("); + p_output.push_back(arguments_sig + ")\n" OPEN_BLOCK_L2); - const TypeInterface *return_type = _get_type_by_name_or_placeholder(imethod.return_type); + if (p_imethod.is_virtual) { + // Godot virtual method must be overridden, therefore we return a default value by default. - String argc_str = itos(imethod.arguments.size()); + if (return_type->name == "void") { + p_output.push_back("return;\n" CLOSE_BLOCK_L2); + } else { + p_output.push_back("return default("); + p_output.push_back(return_type->cs_type); + p_output.push_back(");\n" CLOSE_BLOCK_L2); + } - String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND ", " + itype.c_type_in + " " CS_PARAM_INSTANCE; - String c_in_statements; - String c_args_var_content; + return OK; // Won't increment method bind count + } - // Get arguments information - int i = 0; - for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) { - const ArgumentInterface &iarg = F->get(); - const TypeInterface *arg_type = _get_type_by_name_or_placeholder(iarg.type); + if (p_imethod.requires_object_call) { + // Fallback to Godot's object.Call(string, params) - String c_param_name = "arg" + itos(i + 1); + p_output.push_back(CS_METHOD_CALL "(\""); + p_output.push_back(p_imethod.name); + p_output.push_back("\""); - if (imethod.is_vararg) { - if (i < imethod.arguments.size() - 1) { - c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name); - c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(0, "; - c_in_statements += sformat("&%s_in", c_param_name); - c_in_statements += ");\n"; - } - } else { - if (i > 0) - c_args_var_content += ", "; - if (arg_type->c_in.size()) - c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name); - c_args_var_content += sformat(arg_type->c_arg_in, c_param_name); - } + for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { + p_output.push_back(", "); + p_output.push_back(F->get().name); + } - c_func_sig += ", "; - c_func_sig += arg_type->c_type_in; - c_func_sig += " "; - c_func_sig += c_param_name; + p_output.push_back(");\n" CLOSE_BLOCK_L2); - i++; - } + return OK; // Won't increment method bind count + } - const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&E->get()); - ERR_FAIL_NULL_V(match, ERR_BUG); + const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod); + ERR_FAIL_NULL_V(match, ERR_BUG); - const InternalCall *im_icall = match->value(); - String icall_method = im_icall->name; + const InternalCall *im_icall = match->value(); - if (!generated_icall_funcs.find(im_icall)) { - generated_icall_funcs.push_back(im_icall); + String im_call = im_icall->editor_only ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS; + im_call += "." + im_icall->name + "(" + icall_params + ");\n"; - if (im_icall->editor_only) - cpp_file.push_back("#ifdef TOOLS_ENABLED\n"); + if (p_imethod.arguments.size()) + p_output.push_back(cs_in_statements); - // Generate icall function + if (return_type->name == "void") { + p_output.push_back(im_call); + } else if (return_type->cs_out.empty()) { + p_output.push_back("return " + im_call); + } else { + p_output.push_back(return_type->im_type_out); + p_output.push_back(" " LOCAL_RET " = "); + p_output.push_back(im_call); + p_output.push_back(INDENT3); + p_output.push_back(sformat(return_type->cs_out, LOCAL_RET) + "\n"); + } - cpp_file.push_back(ret_void ? "void " : return_type->c_type_out + " "); - cpp_file.push_back(icall_method); - cpp_file.push_back("("); - cpp_file.push_back(c_func_sig); - cpp_file.push_back(") " OPEN_BLOCK); + p_output.push_back(CLOSE_BLOCK_L2); + } - String fail_ret = ret_void ? "" : ", " + (return_type->c_type_out.ends_with("*") ? "NULL" : return_type->c_type_out + "()"); + p_method_bind_count++; + return OK; +} - if (!ret_void) { - String ptrcall_return_type; - String initialization; +Error BindingsGenerator::generate_glue(const String &p_output_dir) { - if (return_type->is_object_type) { - ptrcall_return_type = return_type->is_reference ? "Ref<Reference>" : return_type->c_type; - initialization = return_type->is_reference ? "" : " = NULL"; - } else { - ptrcall_return_type = return_type->c_type; - } + verbose_output = true; - cpp_file.push_back("\t" + ptrcall_return_type); - cpp_file.push_back(" " LOCAL_RET); - cpp_file.push_back(initialization + ";\n"); - cpp_file.push_back("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE); - cpp_file.push_back(fail_ret); - cpp_file.push_back(");\n"); - } else { - cpp_file.push_back("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n"); - } + bool dir_exists = DirAccess::exists(p_output_dir); + ERR_EXPLAIN("The output directory does not exist."); + ERR_FAIL_COND_V(!dir_exists, ERR_FILE_BAD_PATH); - if (imethod.arguments.size()) { - if (imethod.is_vararg) { - String err_fail_macro = ret_void ? "ERR_FAIL_COND" : "ERR_FAIL_COND_V"; - String vararg_arg = "arg" + argc_str; - String real_argc_str = itos(imethod.arguments.size() - 1); // Arguments count without vararg - - cpp_file.push_back("\tVector<Variant> varargs;\n" - "\tint vararg_length = mono_array_length("); - cpp_file.push_back(vararg_arg); - cpp_file.push_back(");\n\tint total_length = "); - cpp_file.push_back(real_argc_str); - cpp_file.push_back(" + vararg_length;\n\t"); - cpp_file.push_back(err_fail_macro); - cpp_file.push_back("(varargs.resize(vararg_length) != OK"); - cpp_file.push_back(fail_ret); - cpp_file.push_back(");\n\tVector<Variant*> " C_LOCAL_PTRCALL_ARGS ";\n\t"); - cpp_file.push_back(err_fail_macro); - cpp_file.push_back("(call_args.resize(total_length) != OK"); - cpp_file.push_back(fail_ret); - cpp_file.push_back(");\n"); - cpp_file.push_back(c_in_statements); - cpp_file.push_back("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK - "\t\tMonoObject* elem = mono_array_get("); - cpp_file.push_back(vararg_arg); - cpp_file.push_back(", MonoObject*, i);\n" - "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n" - "\t\t" C_LOCAL_PTRCALL_ARGS ".set("); - cpp_file.push_back(real_argc_str); - cpp_file.push_back(" + i, &varargs[i]);\n\t" CLOSE_BLOCK); - } else { - cpp_file.push_back(c_in_statements); - cpp_file.push_back("\tconst void* " C_LOCAL_PTRCALL_ARGS "["); - cpp_file.push_back(argc_str + "] = { "); - cpp_file.push_back(c_args_var_content + " };\n"); - } - } + List<String> output; - if (imethod.is_vararg) { - cpp_file.push_back("\tVariant::CallError vcall_error;\n\t"); + output.push_back("#include \"" GLUE_HEADER_FILE "\"\n" + "\n"); - if (!ret_void) - cpp_file.push_back(LOCAL_RET " = "); + generated_icall_funcs.clear(); - cpp_file.push_back(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", "); - cpp_file.push_back(imethod.arguments.size() ? "(const Variant**)" C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL"); - cpp_file.push_back(", total_length, vcall_error);\n"); - } else { - cpp_file.push_back("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", "); - cpp_file.push_back(imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, "); - cpp_file.push_back(!ret_void ? "&" LOCAL_RET ");\n" : "NULL);\n"); - } + for (Map<String, TypeInterface>::Element *type_elem = obj_types.front(); type_elem; type_elem = type_elem->next()) { + const TypeInterface &itype = type_elem->get(); - if (!ret_void) { - if (return_type->c_out.empty()) - cpp_file.push_back("\treturn " LOCAL_RET ";\n"); - else - cpp_file.push_back(sformat(return_type->c_out, return_type->c_type_out, LOCAL_RET, return_type->name)); - } + List<InternalCall> &custom_icalls = itype.api_type == ClassDB::API_EDITOR ? editor_custom_icalls : core_custom_icalls; + + OS::get_singleton()->print(String("Generating " + itype.name + "...\n").utf8()); - cpp_file.push_back(CLOSE_BLOCK "\n"); + String ctor_method(ICALL_PREFIX + itype.proxy_name + "_Ctor"); - if (im_icall->editor_only) - cpp_file.push_back("#endif // TOOLS_ENABLED\n"); + for (const List<MethodInterface>::Element *E = itype.methods.front(); E; E = E->next()) { + const MethodInterface &imethod = E->get(); + Error method_err = _generate_glue_method(itype, imethod, output); + if (method_err != OK) { + ERR_EXPLAIN("Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'"); + ERR_FAIL_V(method_err); } } @@ -1324,11 +1167,11 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (!find_icall_by_name(singleton_icall.name, custom_icalls)) custom_icalls.push_back(singleton_icall); - cpp_file.push_back("Object* "); - cpp_file.push_back(singleton_icall_name); - cpp_file.push_back("() " OPEN_BLOCK "\treturn ProjectSettings::get_singleton()->get_singleton_object(\""); - cpp_file.push_back(itype.proxy_name); - cpp_file.push_back("\");\n" CLOSE_BLOCK "\n"); + output.push_back("Object* "); + output.push_back(singleton_icall_name); + output.push_back("() " OPEN_BLOCK "\treturn ProjectSettings::get_singleton()->get_singleton_object(\""); + output.push_back(itype.proxy_name); + output.push_back("\");\n" CLOSE_BLOCK "\n"); } if (itype.is_instantiable) { @@ -1337,36 +1180,36 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (!find_icall_by_name(ctor_icall.name, custom_icalls)) custom_icalls.push_back(ctor_icall); - cpp_file.push_back("Object* "); - cpp_file.push_back(ctor_method); - cpp_file.push_back("(MonoObject* obj) " OPEN_BLOCK - "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \""); - cpp_file.push_back(itype.name); - cpp_file.push_back("\");\n" - "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n" - "\treturn instance;\n" CLOSE_BLOCK "\n"); + output.push_back("Object* "); + output.push_back(ctor_method); + output.push_back("(MonoObject* obj) " OPEN_BLOCK + "\t" C_MACRO_OBJECT_CONSTRUCT "(instance, \""); + output.push_back(itype.name); + output.push_back("\");\n" + "\t" C_METHOD_TIE_MANAGED_TO_UNMANAGED "(obj, instance);\n" + "\treturn instance;\n" CLOSE_BLOCK "\n"); } } - cpp_file.push_back("namespace GodotSharpBindings\n" OPEN_BLOCK); - cpp_file.push_back("uint64_t get_core_api_hash() { return "); - cpp_file.push_back(itos(GDMono::get_singleton()->get_api_core_hash()) + "; }\n"); - cpp_file.push_back("#ifdef TOOLS_ENABLED\n" - "uint64_t get_editor_api_hash() { return "); - cpp_file.push_back(itos(GDMono::get_singleton()->get_api_editor_hash()) + - "; }\n#endif // TOOLS_ENABLED\n"); - cpp_file.push_back("void register_generated_icalls() " OPEN_BLOCK); - -#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \ - { \ - cpp_file.push_back("\tmono_add_internal_call("); \ - cpp_file.push_back("\"" BINDINGS_NAMESPACE "."); \ - cpp_file.push_back(m_icall.editor_only ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); \ - cpp_file.push_back("::"); \ - cpp_file.push_back(m_icall.name); \ - cpp_file.push_back("\", (void*)"); \ - cpp_file.push_back(m_icall.name); \ - cpp_file.push_back(");\n"); \ + output.push_back("namespace GodotSharpBindings\n" OPEN_BLOCK); + output.push_back("uint64_t get_core_api_hash() { return "); + output.push_back(itos(GDMono::get_singleton()->get_api_core_hash()) + "; }\n"); + output.push_back("#ifdef TOOLS_ENABLED\n" + "uint64_t get_editor_api_hash() { return "); + output.push_back(itos(GDMono::get_singleton()->get_api_editor_hash()) + + "; }\n#endif // TOOLS_ENABLED\n"); + output.push_back("void register_generated_icalls() " OPEN_BLOCK); + +#define ADD_INTERNAL_CALL_REGISTRATION(m_icall) \ + { \ + output.push_back("\tmono_add_internal_call("); \ + output.push_back("\"" BINDINGS_NAMESPACE "."); \ + output.push_back(m_icall.editor_only ? CS_CLASS_NATIVECALLS_EDITOR : CS_CLASS_NATIVECALLS); \ + output.push_back("::"); \ + output.push_back(m_icall.name); \ + output.push_back("\", (void*)"); \ + output.push_back(m_icall.name); \ + output.push_back(");\n"); \ } bool tools_sequence = false; @@ -1375,11 +1218,11 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { if (!E->get().editor_only) { tools_sequence = false; - cpp_file.push_back("#endif\n"); + output.push_back("#endif\n"); } } else { if (E->get().editor_only) { - cpp_file.push_back("#ifdef TOOLS_ENABLED\n"); + output.push_back("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } @@ -1389,24 +1232,23 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { tools_sequence = false; - cpp_file.push_back("#endif\n"); + output.push_back("#endif\n"); } - cpp_file.push_back("#ifdef TOOLS_ENABLED\n"); + output.push_back("#ifdef TOOLS_ENABLED\n"); for (const List<InternalCall>::Element *E = editor_custom_icalls.front(); E; E = E->next()) ADD_INTERNAL_CALL_REGISTRATION(E->get()); - cpp_file.push_back("#endif // TOOLS_ENABLED\n"); + output.push_back("#endif // TOOLS_ENABLED\n"); for (const List<InternalCall>::Element *E = method_icalls.front(); E; E = E->next()) { - if (tools_sequence) { if (!E->get().editor_only) { tools_sequence = false; - cpp_file.push_back("#endif\n"); + output.push_back("#endif\n"); } } else { if (E->get().editor_only) { - cpp_file.push_back("#ifdef TOOLS_ENABLED\n"); + output.push_back("#ifdef TOOLS_ENABLED\n"); tools_sequence = true; } } @@ -1416,20 +1258,27 @@ Error BindingsGenerator::generate_glue(const String &p_output_dir) { if (tools_sequence) { tools_sequence = false; - cpp_file.push_back("#endif\n"); + output.push_back("#endif\n"); } #undef ADD_INTERNAL_CALL_REGISTRATION - cpp_file.push_back(CLOSE_BLOCK "}\n"); + output.push_back(CLOSE_BLOCK "}\n"); + + Error save_err = _save_file(path_join(p_output_dir, "mono_glue.gen.cpp"), output); + if (save_err != OK) + return save_err; - return _save_file(path_join(p_output_dir, "mono_glue.gen.cpp"), cpp_file); + OS::get_singleton()->print("Mono glue generated successfully\n"); + + return OK; } Error BindingsGenerator::_save_file(const String &p_path, const List<String> &p_content) { FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE); + ERR_EXPLAIN("Cannot open file: " + p_path); ERR_FAIL_COND_V(!file, ERR_FILE_CANT_WRITE); for (const List<String>::Element *E = p_content.front(); E; E = E->next()) { @@ -1441,6 +1290,163 @@ Error BindingsGenerator::_save_file(const String &p_path, const List<String> &p_ return OK; } +Error BindingsGenerator::_generate_glue_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, List<String> &p_output) { + + if (p_imethod.is_virtual) + return OK; // Ignore + + bool ret_void = p_imethod.return_type == "void"; + + const TypeInterface *return_type = _get_type_by_name_or_placeholder(p_imethod.return_type); + + String argc_str = itos(p_imethod.arguments.size()); + + String c_func_sig = "MethodBind* " CS_PARAM_METHODBIND ", " + p_itype.c_type_in + " " CS_PARAM_INSTANCE; + String c_in_statements; + String c_args_var_content; + + // Get arguments information + int i = 0; + for (const List<ArgumentInterface>::Element *F = p_imethod.arguments.front(); F; F = F->next()) { + const ArgumentInterface &iarg = F->get(); + const TypeInterface *arg_type = _get_type_by_name_or_placeholder(iarg.type); + + String c_param_name = "arg" + itos(i + 1); + + if (p_imethod.is_vararg) { + if (i < p_imethod.arguments.size() - 1) { + c_in_statements += sformat(arg_type->c_in.size() ? arg_type->c_in : TypeInterface::DEFAULT_VARARG_C_IN, "Variant", c_param_name); + c_in_statements += "\t" C_LOCAL_PTRCALL_ARGS ".set(0, "; + c_in_statements += sformat("&%s_in", c_param_name); + c_in_statements += ");\n"; + } + } else { + if (i > 0) + c_args_var_content += ", "; + if (arg_type->c_in.size()) + c_in_statements += sformat(arg_type->c_in, arg_type->c_type, c_param_name); + c_args_var_content += sformat(arg_type->c_arg_in, c_param_name); + } + + c_func_sig += ", "; + c_func_sig += arg_type->c_type_in; + c_func_sig += " "; + c_func_sig += c_param_name; + + i++; + } + + const Map<const MethodInterface *, const InternalCall *>::Element *match = method_icalls_map.find(&p_imethod); + ERR_FAIL_NULL_V(match, ERR_BUG); + + const InternalCall *im_icall = match->value(); + String icall_method = im_icall->name; + + if (!generated_icall_funcs.find(im_icall)) { + generated_icall_funcs.push_back(im_icall); + + if (im_icall->editor_only) + p_output.push_back("#ifdef TOOLS_ENABLED\n"); + + // Generate icall function + + p_output.push_back(ret_void ? "void " : return_type->c_type_out + " "); + p_output.push_back(icall_method); + p_output.push_back("("); + p_output.push_back(c_func_sig); + p_output.push_back(") " OPEN_BLOCK); + + String fail_ret = ret_void ? "" : ", " + (return_type->c_type_out.ends_with("*") ? "NULL" : return_type->c_type_out + "()"); + + if (!ret_void) { + String ptrcall_return_type; + String initialization; + + if (return_type->is_object_type) { + ptrcall_return_type = return_type->is_reference ? "Ref<Reference>" : return_type->c_type; + initialization = return_type->is_reference ? "" : " = NULL"; + } else { + ptrcall_return_type = return_type->c_type; + } + + p_output.push_back("\t" + ptrcall_return_type); + p_output.push_back(" " LOCAL_RET); + p_output.push_back(initialization + ";\n"); + p_output.push_back("\tERR_FAIL_NULL_V(" CS_PARAM_INSTANCE); + p_output.push_back(fail_ret); + p_output.push_back(");\n"); + } else { + p_output.push_back("\tERR_FAIL_NULL(" CS_PARAM_INSTANCE ");\n"); + } + + if (p_imethod.arguments.size()) { + if (p_imethod.is_vararg) { + String err_fail_macro = ret_void ? "ERR_FAIL_COND" : "ERR_FAIL_COND_V"; + String vararg_arg = "arg" + argc_str; + String real_argc_str = itos(p_imethod.arguments.size() - 1); // Arguments count without vararg + + p_output.push_back("\tVector<Variant> varargs;\n" + "\tint vararg_length = mono_array_length("); + p_output.push_back(vararg_arg); + p_output.push_back(");\n\tint total_length = "); + p_output.push_back(real_argc_str); + p_output.push_back(" + vararg_length;\n\t"); + p_output.push_back(err_fail_macro); + p_output.push_back("(varargs.resize(vararg_length) != OK"); + p_output.push_back(fail_ret); + p_output.push_back(");\n\tVector<Variant*> " C_LOCAL_PTRCALL_ARGS ";\n\t"); + p_output.push_back(err_fail_macro); + p_output.push_back("(call_args.resize(total_length) != OK"); + p_output.push_back(fail_ret); + p_output.push_back(");\n"); + p_output.push_back(c_in_statements); + p_output.push_back("\tfor (int i = 0; i < vararg_length; i++) " OPEN_BLOCK + "\t\tMonoObject* elem = mono_array_get("); + p_output.push_back(vararg_arg); + p_output.push_back(", MonoObject*, i);\n" + "\t\tvarargs.set(i, GDMonoMarshal::mono_object_to_variant(elem));\n" + "\t\t" C_LOCAL_PTRCALL_ARGS ".set("); + p_output.push_back(real_argc_str); + p_output.push_back(" + i, &varargs[i]);\n\t" CLOSE_BLOCK); + } else { + p_output.push_back(c_in_statements); + p_output.push_back("\tconst void* " C_LOCAL_PTRCALL_ARGS "["); + p_output.push_back(argc_str + "] = { "); + p_output.push_back(c_args_var_content + " };\n"); + } + } + + if (p_imethod.is_vararg) { + p_output.push_back("\tVariant::CallError vcall_error;\n\t"); + + if (!ret_void) + p_output.push_back(LOCAL_RET " = "); + + p_output.push_back(CS_PARAM_METHODBIND "->call(" CS_PARAM_INSTANCE ", "); + p_output.push_back(p_imethod.arguments.size() ? "(const Variant**)" C_LOCAL_PTRCALL_ARGS ".ptr()" : "NULL"); + p_output.push_back(", total_length, vcall_error);\n"); + } else { + p_output.push_back("\t" CS_PARAM_METHODBIND "->ptrcall(" CS_PARAM_INSTANCE ", "); + p_output.push_back(p_imethod.arguments.size() ? C_LOCAL_PTRCALL_ARGS ", " : "NULL, "); + p_output.push_back(!ret_void ? "&" LOCAL_RET ");\n" : "NULL);\n"); + } + + if (!ret_void) { + if (return_type->c_out.empty()) + p_output.push_back("\treturn " LOCAL_RET ";\n"); + else + p_output.push_back(sformat(return_type->c_out, return_type->c_type_out, LOCAL_RET, return_type->name)); + } + + p_output.push_back(CLOSE_BLOCK "\n"); + + if (im_icall->editor_only) + p_output.push_back("#endif // TOOLS_ENABLED\n"); + } + + return OK; +} + const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_by_name_or_null(const String &p_name) { const Map<String, TypeInterface>::Element *match = builtin_types.find(p_name); @@ -1505,7 +1511,8 @@ void BindingsGenerator::_populate_object_type_interfaces() { itype.memory_own = itype.is_reference; if (!ClassDB::is_class_exposed(type_cname)) { - WARN_PRINTS("Ignoring type " + String(type_cname) + " because it's not exposed"); + if (verbose_output) + WARN_PRINTS("Ignoring type " + String(type_cname) + " because it's not exposed"); class_list.pop_front(); continue; } @@ -1569,9 +1576,11 @@ void BindingsGenerator::_populate_object_type_interfaces() { // which could actually will return something differnet. // Let's put this to notify us if that ever happens. if (itype.name != "Object" || imethod.name != "free") { - WARN_PRINTS("Notification: New unexpected virtual non-overridable method found.\n" - "We only expected Object.free, but found " + - itype.name + "." + imethod.name); + if (verbose_output) { + WARN_PRINTS("Notification: New unexpected virtual non-overridable method found.\n" + "We only expected Object.free, but found " + + itype.name + "." + imethod.name); + } } } else { ERR_PRINTS("Missing MethodBind for non-virtual method: " + itype.name + "." + imethod.name); @@ -2077,7 +2086,8 @@ BindingsGenerator::BindingsGenerator() { void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) { - int options_count = 3; + const int NUM_OPTIONS = 3; + int options_left = NUM_OPTIONS; String mono_glue_option = "--generate-mono-glue"; String cs_core_api_option = "--generate-cs-core-api"; @@ -2087,33 +2097,35 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) const List<String>::Element *elem = p_cmdline_args.front(); - while (elem && options_count) { + while (elem && options_left) { if (elem->get() == mono_glue_option) { const List<String>::Element *path_elem = elem->next(); if (path_elem) { - get_singleton().generate_glue(path_elem->get()); + if (get_singleton().generate_glue(path_elem->get()) != OK) + ERR_PRINT("Mono glue generation failed"); elem = elem->next(); } else { ERR_PRINTS("--generate-mono-glue: No output directory specified"); } - --options_count; + --options_left; } else if (elem->get() == cs_core_api_option) { const List<String>::Element *path_elem = elem->next(); if (path_elem) { - get_singleton().generate_cs_core_project(path_elem->get()); + if (get_singleton().generate_cs_core_project(path_elem->get()) != OK) + ERR_PRINT("Generation of solution and C# project for the Core API failed"); elem = elem->next(); } else { ERR_PRINTS(cs_core_api_option + ": No output directory specified"); } - --options_count; + --options_left; } else if (elem->get() == cs_editor_api_option) { @@ -2121,7 +2133,8 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) if (path_elem) { if (path_elem->next()) { - get_singleton().generate_cs_editor_project(path_elem->get(), path_elem->next()->get()); + if (get_singleton().generate_cs_editor_project(path_elem->get(), path_elem->next()->get()) != OK) + ERR_PRINT("Generation of solution and C# project for the Editor API failed"); elem = path_elem->next(); } else { ERR_PRINTS(cs_editor_api_option + ": No hint path for the Core API dll specified"); @@ -2130,13 +2143,16 @@ void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) ERR_PRINTS(cs_editor_api_option + ": No output directory specified"); } - --options_count; + --options_left; } elem = elem->next(); } verbose_output = false; + + if (options_left != NUM_OPTIONS) + exit(0); } #endif diff --git a/modules/mono/editor/bindings_generator.h b/modules/mono/editor/bindings_generator.h index 437a566556..dfa3aa9911 100644 --- a/modules/mono/editor/bindings_generator.h +++ b/modules/mono/editor/bindings_generator.h @@ -368,6 +368,8 @@ class BindingsGenerator { List<InternalCall> method_icalls; Map<const MethodInterface *, const InternalCall *> method_icalls_map; + List<const InternalCall *> generated_icall_funcs; + List<InternalCall> core_custom_icalls; List<InternalCall> editor_custom_icalls; @@ -404,6 +406,11 @@ class BindingsGenerator { Error _generate_cs_type(const TypeInterface &itype, const String &p_output_file); + Error _generate_cs_property(const TypeInterface &p_itype, const DocData::PropertyDoc &p_prop_doc, List<String> &p_output); + Error _generate_cs_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, int &p_method_bind_count, List<String> &p_output); + + Error _generate_glue_method(const TypeInterface &p_itype, const MethodInterface &p_imethod, List<String> &p_output); + Error _save_file(const String &path, const List<String> &content); BindingsGenerator(); diff --git a/modules/mono/editor/godotsharp_builds.cpp b/modules/mono/editor/godotsharp_builds.cpp index 1bad8a3f85..dbe0cc294c 100644 --- a/modules/mono/editor/godotsharp_builds.cpp +++ b/modules/mono/editor/godotsharp_builds.cpp @@ -32,6 +32,7 @@ #include "main/main.h" #include "../godotsharp_dirs.h" +#include "../mono_gd/gd_mono.h" #include "../mono_gd/gd_mono_class.h" #include "../mono_gd/gd_mono_marshal.h" #include "../utils/path_utils.h" @@ -60,10 +61,10 @@ String _find_build_engine_on_unix(const String &p_name) { }; for (int i = 0; i < sizeof(locations) / sizeof(const char *); i++) { - String location = locations[i]; + String hint_path = locations[i] + p_name; - if (FileAccess::exists(location + p_name)) { - return location; + if (FileAccess::exists(hint_path)) { + return hint_path; } } @@ -71,7 +72,7 @@ String _find_build_engine_on_unix(const String &p_name) { } #endif -MonoString *godot_icall_BuildInstance_get_MSBuildPath() { +void godot_icall_BuildInstance_get_MSBuildInfo(MonoString **r_msbuild_path, MonoString **r_framework_path) { GodotSharpBuilds::BuildTool build_tool = GodotSharpBuilds::BuildTool(int(EditorSettings::get_singleton()->get("mono/builds/build_tool"))); @@ -84,11 +85,23 @@ MonoString *godot_icall_BuildInstance_get_MSBuildPath() { if (!msbuild_tools_path.ends_with("\\")) msbuild_tools_path += "\\"; - return GDMonoMarshal::mono_string_from_godot(msbuild_tools_path + "MSBuild.exe"); + // FrameworkPathOverride + const MonoRegInfo &mono_reg_info = GDMono::get_singleton()->get_mono_reg_info(); + if (mono_reg_info.assembly_dir.length()) { + *r_msbuild_path = GDMonoMarshal::mono_string_from_godot(msbuild_tools_path + "MSBuild.exe"); + + String framework_path = path_join(mono_reg_info.assembly_dir, "mono", "4.5"); + *r_framework_path = GDMonoMarshal::mono_string_from_godot(framework_path); + } else { + ERR_PRINT("Cannot find Mono's assemblies directory in the registry"); + } + + return; } - OS::get_singleton()->print("Cannot find System's MSBuild. Trying with Mono's...\n"); - } + if (OS::get_singleton()->is_stdout_verbose()) + OS::get_singleton()->print("Cannot find System's MSBuild. Trying with Mono's...\n"); + } // fall through case GodotSharpBuilds::MSBUILD_MONO: { String msbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("msbuild.bat"); @@ -96,17 +109,10 @@ MonoString *godot_icall_BuildInstance_get_MSBuildPath() { WARN_PRINTS("Cannot find msbuild ('mono/builds/build_tool'). Tried with path: " + msbuild_path); } - return GDMonoMarshal::mono_string_from_godot(msbuild_path); - } - case GodotSharpBuilds::XBUILD: { - String xbuild_path = GDMono::get_singleton()->get_mono_reg_info().bin_dir.plus_file("xbuild.bat"); + *r_msbuild_path = GDMonoMarshal::mono_string_from_godot(msbuild_path); - if (!FileAccess::exists(xbuild_path)) { - WARN_PRINTS("Cannot find xbuild ('mono/builds/build_tool'). Tried with path: " + xbuild_path); - } - - return GDMonoMarshal::mono_string_from_godot(xbuild_path); - } + return; + } break; default: ERR_EXPLAIN("You don't deserve to live"); CRASH_NOW(); @@ -118,25 +124,28 @@ MonoString *godot_icall_BuildInstance_get_MSBuildPath() { if (build_tool != GodotSharpBuilds::XBUILD) { if (msbuild_path.empty()) { WARN_PRINT("Cannot find msbuild ('mono/builds/build_tool')."); - return NULL; + return; } } else { if (xbuild_path.empty()) { WARN_PRINT("Cannot find xbuild ('mono/builds/build_tool')."); - return NULL; + return; } } - return GDMonoMarshal::mono_string_from_godot(build_tool != GodotSharpBuilds::XBUILD ? msbuild_path : xbuild_path); + *r_msbuild_path = GDMonoMarshal::mono_string_from_godot(build_tool != GodotSharpBuilds::XBUILD ? msbuild_path : xbuild_path); + + return; #else - return NULL; + ERR_PRINT("Not implemented on this platform"); + return; #endif } void GodotSharpBuilds::_register_internal_calls() { mono_add_internal_call("GodotSharpTools.Build.BuildSystem::godot_icall_BuildInstance_ExitCallback", (void *)godot_icall_BuildInstance_ExitCallback); - mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MSBuildPath", (void *)godot_icall_BuildInstance_get_MSBuildPath); + mono_add_internal_call("GodotSharpTools.Build.BuildInstance::godot_icall_BuildInstance_get_MSBuildInfo", (void *)godot_icall_BuildInstance_get_MSBuildInfo); } void GodotSharpBuilds::show_build_error_dialog(const String &p_message) { @@ -269,7 +278,7 @@ bool GodotSharpBuilds::make_api_sln(GodotSharpBuilds::APIType p_api_type) { return true; } -bool godotsharp_build_callback() { +bool GodotSharpBuilds::build_project_blocking() { if (!FileAccess::exists(GodotSharpDirs::get_project_sln_path())) return true; // No solution to build @@ -348,14 +357,27 @@ GodotSharpBuilds::GodotSharpBuilds() { singleton = this; - EditorNode::get_singleton()->add_build_callback(&godotsharp_build_callback); + EditorNode::get_singleton()->add_build_callback(&GodotSharpBuilds::build_project_blocking); // Build tool settings EditorSettings *ed_settings = EditorSettings::get_singleton(); if (!ed_settings->has_setting("mono/builds/build_tool")) { - ed_settings->set_setting("mono/builds/build_tool", MSBUILD); + ed_settings->set_setting("mono/builds/build_tool", +#ifdef WINDOWS_ENABLED + // TODO: Default to MSBUILD_MONO if its csc.exe issue is fixed in the installed mono version + MSBUILD +#else + MSBUILD_MONO +#endif + ); } - ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/builds/build_tool", PROPERTY_HINT_ENUM, "MSBuild (System),MSBuild (Mono),xbuild")); + ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/builds/build_tool", PROPERTY_HINT_ENUM, +#ifdef WINDOWS_ENABLED + "MSBuild (Mono),MSBuild (System)" +#else + "MSBuild (Mono),xbuild (Deprecated)" +#endif + )); } GodotSharpBuilds::~GodotSharpBuilds() { @@ -395,10 +417,11 @@ void GodotSharpBuilds::BuildProcess::start(bool p_blocking) { } if (!exited) { - ERR_PRINT("BuildProcess::start called, but process still running"); exited = true; - build_tab->on_build_exec_failed("!exited"); - return; + String message = "Tried to start build process, but it is already running"; + build_tab->on_build_exec_failed(message); + ERR_EXPLAIN(message); + ERR_FAIL(); } exited = false; @@ -410,10 +433,12 @@ void GodotSharpBuilds::BuildProcess::start(bool p_blocking) { if (d->file_exists(issues_file)) { Error err = d->remove(issues_file); if (err != OK) { - ERR_PRINTS("Cannot remove file: " + logs_dir.plus_file(issues_file)); exited = true; - build_tab->on_build_exec_failed("Cannot remove file: " + issues_file); - return; + String file_path = ProjectSettings::get_singleton()->localize_path(logs_dir).plus_file(issues_file); + String message = "Cannot remove issues file: " + file_path; + build_tab->on_build_exec_failed(message); + ERR_EXPLAIN(message); + ERR_FAIL(); } } @@ -434,7 +459,9 @@ void GodotSharpBuilds::BuildProcess::start(bool p_blocking) { if (ex) { exited = true; - build_tab->on_build_exec_failed("The build constructor threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(ex)); + String message = "The build constructor threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(ex); + build_tab->on_build_exec_failed(message); + ERR_EXPLAIN(message); ERR_FAIL(); } @@ -452,7 +479,9 @@ void GodotSharpBuilds::BuildProcess::start(bool p_blocking) { if (ex) { exited = true; - build_tab->on_build_exec_failed("The build method threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(ex)); + String message = "The build method threw an exception.\n" + GDMonoUtils::get_exception_name_and_message(ex); + build_tab->on_build_exec_failed(message); + ERR_EXPLAIN(message); ERR_FAIL(); } diff --git a/modules/mono/editor/godotsharp_builds.h b/modules/mono/editor/godotsharp_builds.h index 6d5fa3b44a..7d2f38a774 100644 --- a/modules/mono/editor/godotsharp_builds.h +++ b/modules/mono/editor/godotsharp_builds.h @@ -67,9 +67,12 @@ public: }; enum BuildTool { - MSBUILD, MSBUILD_MONO, - XBUILD +#ifdef WINDOWS_ENABLED + MSBUILD +#else + XBUILD // Deprecated +#endif }; _FORCE_INLINE_ static GodotSharpBuilds *get_singleton() { return singleton; } @@ -89,6 +92,8 @@ public: static bool make_api_sln(APIType p_api_type); + static bool build_project_blocking(); + GodotSharpBuilds(); ~GodotSharpBuilds(); }; diff --git a/modules/mono/editor/godotsharp_editor.cpp b/modules/mono/editor/godotsharp_editor.cpp index 30e7653256..837dbfde66 100644 --- a/modules/mono/editor/godotsharp_editor.cpp +++ b/modules/mono/editor/godotsharp_editor.cpp @@ -46,21 +46,6 @@ #include "../utils/mono_reg_utils.h" #endif -class MonoReloadNode : public Node { - GDCLASS(MonoReloadNode, Node) - -protected: - void _notification(int p_what) { - switch (p_what) { - case MainLoop::NOTIFICATION_WM_FOCUS_IN: { - CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true); - } break; - default: { - } break; - }; - } -}; - GodotSharpEditor *GodotSharpEditor::singleton = NULL; bool GodotSharpEditor::_create_project_solution() { @@ -71,6 +56,10 @@ bool GodotSharpEditor::_create_project_solution() { String path = OS::get_singleton()->get_resource_dir(); String name = ProjectSettings::get_singleton()->get("application/config/name"); + if (name.empty()) { + name = "UnnamedProject"; + } + String guid = CSharpProject::generate_game_project(path, name); if (guid.length()) { @@ -182,11 +171,6 @@ Error GodotSharpEditor::open_in_external_editor(const Ref<Script> &p_script, int String script_path = ProjectSettings::get_singleton()->globalize_path(p_script->get_path()); monodevel_instance->execute(script_path); } break; - case EDITOR_VISUAL_STUDIO: - // TODO - // devenv <PathToSolutionFolder> - // devenv /edit <PathToCsFile> /command "edit.goto <Line>" - // HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7 default: return ERR_UNAVAILABLE; } @@ -240,7 +224,7 @@ GodotSharpEditor::GodotSharpEditor(EditorNode *p_editor) { if (!ed_settings->has_setting("mono/editor/external_editor")) { ed_settings->set_setting("mono/editor/external_editor", EDITOR_NONE); } - ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/editor/external_editor", PROPERTY_HINT_ENUM, "None,MonoDevelop,Visual Studio,Visual Studio Code")); + ed_settings->add_property_hint(PropertyInfo(Variant::INT, "mono/editor/external_editor", PROPERTY_HINT_ENUM, "None,MonoDevelop,Visual Studio Code")); } GodotSharpEditor::~GodotSharpEditor() { @@ -254,3 +238,49 @@ GodotSharpEditor::~GodotSharpEditor() { monodevel_instance = NULL; } } + +MonoReloadNode *MonoReloadNode::singleton = NULL; + +void MonoReloadNode::_reload_timer_timeout() { + + CSharpLanguage::get_singleton()->reload_assemblies_if_needed(false); +} + +void MonoReloadNode::restart_reload_timer() { + + reload_timer->stop(); + reload_timer->start(); +} + +void MonoReloadNode::_bind_methods() { + + ClassDB::bind_method(D_METHOD("_reload_timer_timeout"), &MonoReloadNode::_reload_timer_timeout); +} + +void MonoReloadNode::_notification(int p_what) { + switch (p_what) { + case MainLoop::NOTIFICATION_WM_FOCUS_IN: { + restart_reload_timer(); + CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true); + } break; + default: { + } break; + }; +} + +MonoReloadNode::MonoReloadNode() { + + singleton = this; + + reload_timer = memnew(Timer); + add_child(reload_timer); + reload_timer->set_one_shot(false); + reload_timer->set_wait_time(EDITOR_DEF("mono/assembly_watch_interval_sec", 0.5)); + reload_timer->connect("timeout", this, "_reload_timer_timeout"); + reload_timer->start(); +} + +MonoReloadNode::~MonoReloadNode() { + + singleton = NULL; +} diff --git a/modules/mono/editor/godotsharp_editor.h b/modules/mono/editor/godotsharp_editor.h index 1ecb8c7a94..0f2c163582 100644 --- a/modules/mono/editor/godotsharp_editor.h +++ b/modules/mono/editor/godotsharp_editor.h @@ -69,7 +69,6 @@ public: enum ExternalEditor { EDITOR_NONE, EDITOR_MONODEVELOP, - EDITOR_VISUAL_STUDIO, EDITOR_CODE, }; @@ -84,4 +83,27 @@ public: ~GodotSharpEditor(); }; +class MonoReloadNode : public Node { + GDCLASS(MonoReloadNode, Node) + + Timer *reload_timer; + + void _reload_timer_timeout(); + + static MonoReloadNode *singleton; + +protected: + static void _bind_methods(); + + void _notification(int p_what); + +public: + _FORCE_INLINE_ static MonoReloadNode *get_singleton() { return singleton; } + + void restart_reload_timer(); + + MonoReloadNode(); + ~MonoReloadNode(); +}; + #endif // GODOTSHARP_EDITOR_H diff --git a/modules/mono/editor/mono_bottom_panel.cpp b/modules/mono/editor/mono_bottom_panel.cpp index 07109eaac7..31dc09856a 100644 --- a/modules/mono/editor/mono_bottom_panel.cpp +++ b/modules/mono/editor/mono_bottom_panel.cpp @@ -139,6 +139,14 @@ void MonoBottomPanel::_errors_toggled(bool p_pressed) { build_tab->_update_issues_list(); } +void MonoBottomPanel::_build_project_pressed() { + + GodotSharpBuilds::get_singleton()->build_project_blocking(); + + MonoReloadNode::get_singleton()->restart_reload_timer(); + CSharpLanguage::get_singleton()->reload_assemblies_if_needed(true); +} + void MonoBottomPanel::_notification(int p_what) { switch (p_what) { @@ -153,6 +161,7 @@ void MonoBottomPanel::_notification(int p_what) { void MonoBottomPanel::_bind_methods() { + ClassDB::bind_method(D_METHOD("_build_project_pressed"), &MonoBottomPanel::_build_project_pressed); ClassDB::bind_method(D_METHOD("_warnings_toggled", "pressed"), &MonoBottomPanel::_warnings_toggled); ClassDB::bind_method(D_METHOD("_errors_toggled", "pressed"), &MonoBottomPanel::_errors_toggled); ClassDB::bind_method(D_METHOD("_build_tab_item_selected", "idx"), &MonoBottomPanel::_build_tab_item_selected); @@ -187,6 +196,12 @@ MonoBottomPanel::MonoBottomPanel(EditorNode *p_editor) { toolbar_hbc->set_h_size_flags(SIZE_EXPAND_FILL); panel_builds_tab->add_child(toolbar_hbc); + ToolButton *build_project_btn = memnew(ToolButton); + build_project_btn->set_text("Build Project"); + build_project_btn->set_focus_mode(FOCUS_NONE); + build_project_btn->connect("pressed", this, "_build_project_pressed"); + toolbar_hbc->add_child(build_project_btn); + toolbar_hbc->add_spacer(); warnings_btn = memnew(ToolButton); @@ -280,7 +295,11 @@ void MonoBuildTab::_update_issues_list() { String tooltip; tooltip += String("Message: ") + issue.message; - tooltip += String("\nCode: ") + issue.code; + + if (issue.code.length()) { + tooltip += String("\nCode: ") + issue.code; + } + tooltip += String("\nType: ") + (issue.warning ? "warning" : "error"); String text; @@ -356,23 +375,21 @@ void MonoBuildTab::on_build_exit(BuildResult result) { MonoBottomPanel::get_singleton()->raise_build_tab(this); } -void MonoBuildTab::on_build_exec_failed(const String &p_cause, const String &p_detailed) { +void MonoBuildTab::on_build_exec_failed(const String &p_cause) { build_exited = true; build_result = RESULT_ERROR; issues_list->clear(); - String tooltip; + BuildIssue issue; + issue.message = p_cause; + issue.warning = false; - tooltip += "Message: " + (p_detailed.length() ? p_detailed : p_cause); - tooltip += "\nType: error"; + error_count += 1; + issues.push_back(issue); - int line_break_idx = p_cause.find("\n"); - issues_list->add_item(line_break_idx == -1 ? p_cause : p_cause.substr(0, line_break_idx), - get_icon("Error", "EditorIcons")); - int index = issues_list->get_item_count() - 1; - issues_list->set_item_tooltip(index, tooltip); + _update_issues_list(); MonoBottomPanel::get_singleton()->raise_build_tab(this); } diff --git a/modules/mono/editor/mono_bottom_panel.h b/modules/mono/editor/mono_bottom_panel.h index 909fa4b385..5cc4aa3240 100644 --- a/modules/mono/editor/mono_bottom_panel.h +++ b/modules/mono/editor/mono_bottom_panel.h @@ -61,6 +61,8 @@ class MonoBottomPanel : public VBoxContainer { void _warnings_toggled(bool p_pressed); void _errors_toggled(bool p_pressed); + void _build_project_pressed(); + static MonoBottomPanel *singleton; protected: @@ -134,7 +136,7 @@ public: void on_build_start(); void on_build_exit(BuildResult result); - void on_build_exec_failed(const String &p_cause, const String &p_detailed = String()); + void on_build_exec_failed(const String &p_cause); void restart_build(); void stop_build(); diff --git a/modules/mono/glue/cs_files/ExportAttribute.cs b/modules/mono/glue/cs_files/ExportAttribute.cs index af3f603d6d..a4e7d447dd 100644 --- a/modules/mono/glue/cs_files/ExportAttribute.cs +++ b/modules/mono/glue/cs_files/ExportAttribute.cs @@ -7,13 +7,11 @@ namespace Godot { private int hint; private string hint_string; - private int usage; - public ExportAttribute(int hint = GD.PROPERTY_HINT_NONE, string hint_string = "", int usage = GD.PROPERTY_USAGE_DEFAULT) + public ExportAttribute(int hint = GD.PROPERTY_HINT_NONE, string hint_string = "") { this.hint = hint; this.hint_string = hint_string; - this.usage = usage; } } } diff --git a/modules/mono/godotsharp_dirs.cpp b/modules/mono/godotsharp_dirs.cpp index 0a2010e99d..7cc2168b70 100644 --- a/modules/mono/godotsharp_dirs.cpp +++ b/modules/mono/godotsharp_dirs.cpp @@ -33,6 +33,7 @@ #ifdef TOOLS_ENABLED #include "editor/editor_settings.h" +#include "os/dir_access.h" #include "project_settings.h" #include "version.h" #endif @@ -60,12 +61,20 @@ String _get_mono_user_dir() { } else { String settings_path; - if (OS::get_singleton()->has_environment("APPDATA")) { - String app_data = OS::get_singleton()->get_environment("APPDATA").replace("\\", "/"); - settings_path = app_data.plus_file(String(_MKSTR(VERSION_SHORT_NAME)).capitalize()); - } else if (OS::get_singleton()->has_environment("HOME")) { - String home = OS::get_singleton()->get_environment("HOME"); - settings_path = home.plus_file("." + String(_MKSTR(VERSION_SHORT_NAME)).to_lower()); + String exe_dir = OS::get_singleton()->get_executable_path().get_base_dir(); + DirAccessRef d = DirAccess::create_for_path(exe_dir); + + if (d->file_exists("._sc_") || d->file_exists("_sc_")) { + // contain yourself + settings_path = exe_dir.plus_file("editor_data"); + } else { + if (OS::get_singleton()->has_environment("APPDATA")) { + String app_data = OS::get_singleton()->get_environment("APPDATA").replace("\\", "/"); + settings_path = app_data.plus_file(String(_MKSTR(VERSION_SHORT_NAME)).capitalize()); + } else if (OS::get_singleton()->has_environment("HOME")) { + String home = OS::get_singleton()->get_environment("HOME"); + settings_path = home.plus_file("." + String(_MKSTR(VERSION_SHORT_NAME)).to_lower()); + } } return settings_path.plus_file("mono"); @@ -113,7 +122,14 @@ private: #ifdef TOOLS_ENABLED mono_solutions_dir = mono_user_dir.plus_file("solutions"); build_logs_dir = mono_user_dir.plus_file("build_logs"); - String base_path = String("res://") + ProjectSettings::get_singleton()->get("application/config/name"); + + String name = ProjectSettings::get_singleton()->get("application/config/name"); + if (name.empty()) { + name = "UnnamedProject"; + } + + String base_path = String("res://") + name; + sln_filepath = ProjectSettings::get_singleton()->globalize_path(base_path + ".sln"); csproj_filepath = ProjectSettings::get_singleton()->globalize_path(base_path + ".csproj"); #endif diff --git a/modules/mono/mono_gd/gd_mono.cpp b/modules/mono/mono_gd/gd_mono.cpp index 98b57adc50..904a8ae2c7 100644 --- a/modules/mono/mono_gd/gd_mono.cpp +++ b/modules/mono/mono_gd/gd_mono.cpp @@ -29,6 +29,7 @@ /*************************************************************************/ #include "gd_mono.h" +#include <mono/metadata/exception.h> #include <mono/metadata/mono-config.h> #include <mono/metadata/mono-debug.h> #include <mono/metadata/mono-gc.h> @@ -47,6 +48,15 @@ #include "../editor/godotsharp_editor.h" #endif +void gdmono_unhandled_exception_hook(MonoObject *exc, void *user_data) { + + (void)user_data; // UNUSED + + ERR_PRINT(GDMonoUtils::get_exception_name_and_message(exc).utf8()); + mono_print_unhandled_exception(exc); + abort(); +} + #ifdef MONO_PRINT_HANDLER_ENABLED void gdmono_MonoPrintCallback(const char *string, mono_bool is_stdout) { @@ -132,7 +142,7 @@ void GDMono::initialize() { ERR_FAIL_NULL(Engine::get_singleton()); - OS::get_singleton()->print("Initializing mono...\n"); + OS::get_singleton()->print("Mono: Initializing module...\n"); #ifdef DEBUG_METHODS_ENABLED _initialize_and_check_api_hashes(); @@ -214,7 +224,9 @@ void GDMono::initialize() { // The following assemblies are not required at initialization _load_all_script_assemblies(); - OS::get_singleton()->print("Mono: EVERYTHING OK\n"); + mono_install_unhandled_exception_hook(gdmono_unhandled_exception_hook, NULL); + + OS::get_singleton()->print("Mono: ALL IS GOOD\n"); } #ifndef MONO_GLUE_DISABLED @@ -357,9 +369,12 @@ bool GDMono::_load_project_assembly() { if (project_assembly) return true; - String project_assembly_name = ProjectSettings::get_singleton()->get("application/config/name"); + String name = ProjectSettings::get_singleton()->get("application/config/name"); + if (name.empty()) { + name = "UnnamedProject"; + } - bool success = _load_assembly(project_assembly_name, &project_assembly); + bool success = _load_assembly(name, &project_assembly); if (success) mono_assembly_set_main(project_assembly->get_assembly()); @@ -610,6 +625,8 @@ GDMono::~GDMono() { if (gdmono_log) memdelete(gdmono_log); + + singleton = NULL; } _GodotSharp *_GodotSharp::singleton = NULL; diff --git a/modules/mono/mono_gd/gd_mono_assembly.cpp b/modules/mono/mono_gd/gd_mono_assembly.cpp index 4b370295f3..7dc7043eec 100644 --- a/modules/mono/mono_gd/gd_mono_assembly.cpp +++ b/modules/mono/mono_gd/gd_mono_assembly.cpp @@ -95,7 +95,9 @@ MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **asse (void)user_data; // UNUSED if (search_dirs.empty()) { +#ifdef TOOLS_DOMAIN search_dirs.push_back(GodotSharpDirs::get_res_temp_assemblies_dir()); +#endif search_dirs.push_back(GodotSharpDirs::get_res_assemblies_dir()); search_dirs.push_back(OS::get_singleton()->get_resource_dir()); search_dirs.push_back(OS::get_singleton()->get_executable_path().get_base_dir()); @@ -105,10 +107,11 @@ MonoAssembly *GDMonoAssembly::_preload_hook(MonoAssemblyName *aname, char **asse search_dirs.push_back(String(rootdir).plus_file("mono").plus_file("4.5")); } - while (assemblies_path) { - if (*assemblies_path) + if (assemblies_path) { + while (*assemblies_path) { search_dirs.push_back(*assemblies_path); - ++assemblies_path; + ++assemblies_path; + } } } diff --git a/modules/mono/mono_gd/gd_mono_class.cpp b/modules/mono/mono_gd/gd_mono_class.cpp index 0134ace5d7..77ba0ee90e 100644 --- a/modules/mono/mono_gd/gd_mono_class.cpp +++ b/modules/mono/mono_gd/gd_mono_class.cpp @@ -43,6 +43,14 @@ bool GDMonoClass::is_assignable_from(GDMonoClass *p_from) const { return mono_class_is_assignable_from(mono_class, p_from->mono_class); } +String GDMonoClass::get_full_name() const { + + String res = namespace_name; + if (res.length()) + res += "."; + return res + class_name; +} + GDMonoClass *GDMonoClass::get_parent_class() { if (assembly) { @@ -56,6 +64,30 @@ GDMonoClass *GDMonoClass::get_parent_class() { return NULL; } +#ifdef TOOLS_ENABLED +Vector<MonoClassField *> GDMonoClass::get_enum_fields() { + + bool class_is_enum = mono_class_is_enum(mono_class); + ERR_FAIL_COND_V(!class_is_enum, Vector<MonoClassField *>()); + + Vector<MonoClassField *> enum_fields; + + void *iter = NULL; + MonoClassField *raw_field = NULL; + while ((raw_field = mono_class_get_fields(get_raw(), &iter)) != NULL) { + uint32_t field_flags = mono_field_get_flags(raw_field); + + // Enums have an instance field named value__ which holds the value of the enum. + // Enum constants are static, so we will use this to ignore the value__ field. + if (field_flags & MONO_FIELD_ATTR_PUBLIC && field_flags & MONO_FIELD_ATTR_STATIC) { + enum_fields.push_back(raw_field); + } + } + + return enum_fields; +} +#endif + bool GDMonoClass::has_method(const StringName &p_name) { return get_method(p_name) != NULL; diff --git a/modules/mono/mono_gd/gd_mono_class.h b/modules/mono/mono_gd/gd_mono_class.h index 1e72553879..ef1ca425a7 100644 --- a/modules/mono/mono_gd/gd_mono_class.h +++ b/modules/mono/mono_gd/gd_mono_class.h @@ -98,8 +98,14 @@ public: _FORCE_INLINE_ MonoClass *get_raw() const { return mono_class; } _FORCE_INLINE_ const GDMonoAssembly *get_assembly() const { return assembly; } + String get_full_name() const; + GDMonoClass *get_parent_class(); +#ifdef TOOLS_ENABLED + Vector<MonoClassField *> get_enum_fields(); +#endif + bool has_method(const StringName &p_name); bool has_attribute(GDMonoClass *p_attr_class); diff --git a/modules/mono/mono_gd/gd_mono_field.cpp b/modules/mono/mono_gd/gd_mono_field.cpp index c2d8eeaa32..1643f8cfc5 100644 --- a/modules/mono/mono_gd/gd_mono_field.cpp +++ b/modules/mono/mono_gd/gd_mono_field.cpp @@ -51,6 +51,7 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { { \ m_type val = p_value.operator m_type(); \ mono_field_set_value(p_object, mono_field, &val); \ + break; \ } #define SET_FROM_ARRAY_AND_BREAK(m_type) \ @@ -137,6 +138,9 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { if (tclass == CACHED_CLASS(Plane)) SET_FROM_STRUCT_AND_BREAK(Plane); + if (mono_class_is_enum(tclass->get_raw())) + SET_FROM_PRIMITIVE(signed int); + ERR_EXPLAIN(String() + "Attempted to set the value of a field of unmarshallable type: " + tclass->get_name()); ERR_FAIL(); } break; @@ -179,19 +183,19 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { // GodotObject if (CACHED_CLASS(GodotObject)->is_assignable_from(type_class)) { MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); break; } if (CACHED_CLASS(NodePath) == type_class) { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); break; } if (CACHED_CLASS(RID) == type_class) { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); break; } @@ -200,8 +204,6 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { } break; case MONO_TYPE_OBJECT: { - GDMonoClass *type_class = type.type_class; - // Variant switch (p_value.get_type()) { case Variant::BOOL: { @@ -233,11 +235,11 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { case Variant::COLOR: SET_FROM_STRUCT_AND_BREAK(Color); case Variant::NODE_PATH: { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator NodePath()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); } break; case Variant::_RID: { MonoObject *managed = GDMonoUtils::create_managed_from(p_value.operator RID()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); } break; case Variant::OBJECT: { MonoObject *managed = GDMonoUtils::unmanaged_get_managed(p_value.operator Object *()); @@ -246,7 +248,7 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { } case Variant::DICTIONARY: { MonoObject *managed = GDMonoMarshal::Dictionary_to_mono_object(p_value.operator Dictionary()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); } break; case Variant::ARRAY: SET_FROM_ARRAY_AND_BREAK(Array); case Variant::POOL_BYTE_ARRAY: SET_FROM_ARRAY_AND_BREAK(PoolByteArray); @@ -264,7 +266,7 @@ void GDMonoField::set_value(MonoObject *p_object, const Variant &p_value) { case MONO_TYPE_GENERICINST: { if (CACHED_RAW_MONO_CLASS(Dictionary) == type.type_class->get_raw()) { MonoObject *managed = GDMonoMarshal::Dictionary_to_mono_object(p_value.operator Dictionary()); - mono_field_set_value(p_object, mono_field, &managed); + mono_field_set_value(p_object, mono_field, managed); break; } } break; diff --git a/modules/mono/mono_gd/gd_mono_marshal.cpp b/modules/mono/mono_gd/gd_mono_marshal.cpp index 9a6c8f0cd6..77a1ef3cb0 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.cpp +++ b/modules/mono/mono_gd/gd_mono_marshal.cpp @@ -112,6 +112,9 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type) { if (tclass == CACHED_CLASS(Plane)) return Variant::PLANE; + + if (mono_class_is_enum(tclass->get_raw())) + return Variant::INT; } break; case MONO_TYPE_ARRAY: @@ -165,9 +168,12 @@ Variant::Type managed_to_variant_type(const ManagedType &p_type) { return Variant::DICTIONARY; } } break; + + default: { + } break; } - // No error, the caller will decide what to do in this case + // Unknown return Variant::NIL; } @@ -299,6 +305,11 @@ MonoObject *variant_to_mono_object(const Variant *p_var, const ManagedType &p_ty if (tclass == CACHED_CLASS(Plane)) RETURN_BOXED_STRUCT(Plane, p_var); + + if (mono_class_is_enum(tclass->get_raw())) { + int val = p_var->operator signed int(); + return BOX_ENUM(tclass->get_raw(), val); + } } break; case MONO_TYPE_ARRAY: @@ -515,6 +526,9 @@ Variant mono_object_to_variant(MonoObject *p_obj, const ManagedType &p_type) { if (tclass == CACHED_CLASS(Plane)) RETURN_UNBOXED_STRUCT(Plane, p_obj); + + if (mono_class_is_enum(tclass->get_raw())) + return unbox<int32_t>(p_obj); } break; case MONO_TYPE_ARRAY: diff --git a/modules/mono/mono_gd/gd_mono_marshal.h b/modules/mono/mono_gd/gd_mono_marshal.h index 38dd22357d..9f403b787f 100644 --- a/modules/mono/mono_gd/gd_mono_marshal.h +++ b/modules/mono/mono_gd/gd_mono_marshal.h @@ -53,6 +53,7 @@ T unbox(MonoObject *p_obj) { #define BOX_UINT8(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(uint8_t), &x) #define BOX_BOOLEAN(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(bool), &x) #define BOX_PTR(x) mono_value_box(mono_domain_get(), CACHED_CLASS_RAW(IntPtr), x) +#define BOX_ENUM(m_enum_class, x) mono_value_box(mono_domain_get(), m_enum_class, &x) Variant::Type managed_to_variant_type(const ManagedType &p_type); diff --git a/modules/mono/mono_gd/gd_mono_method.cpp b/modules/mono/mono_gd/gd_mono_method.cpp index 6468e0d3d9..eb97d62900 100644 --- a/modules/mono/mono_gd/gd_mono_method.cpp +++ b/modules/mono/mono_gd/gd_mono_method.cpp @@ -83,9 +83,32 @@ MonoObject *GDMonoMethod::invoke(MonoObject *p_object, const Variant **p_params, mono_array_set(params, MonoObject *, i, boxed_param); } - return mono_runtime_invoke_array(mono_method, p_object, params, r_exc); + MonoObject *exc = NULL; + MonoObject *ret = mono_runtime_invoke_array(mono_method, p_object, params, &exc); + + if (exc) { + if (r_exc) { + *r_exc = exc; + } else { + ERR_PRINT(GDMonoUtils::get_exception_name_and_message(exc).utf8()); + mono_print_unhandled_exception(exc); + } + } + + return ret; } else { - mono_runtime_invoke(mono_method, p_object, NULL, r_exc); + MonoObject *exc = NULL; + mono_runtime_invoke(mono_method, p_object, NULL, &exc); + + if (exc) { + if (r_exc) { + *r_exc = exc; + } else { + ERR_PRINT(GDMonoUtils::get_exception_name_and_message(exc).utf8()); + mono_print_unhandled_exception(exc); + } + } + return NULL; } } @@ -96,7 +119,19 @@ MonoObject *GDMonoMethod::invoke(MonoObject *p_object, MonoObject **r_exc) { } MonoObject *GDMonoMethod::invoke_raw(MonoObject *p_object, void **p_params, MonoObject **r_exc) { - return mono_runtime_invoke(mono_method, p_object, p_params, r_exc); + MonoObject *exc = NULL; + MonoObject *ret = mono_runtime_invoke(mono_method, p_object, p_params, &exc); + + if (exc) { + if (r_exc) { + *r_exc = exc; + } else { + ERR_PRINT(GDMonoUtils::get_exception_name_and_message(exc).utf8()); + mono_print_unhandled_exception(exc); + } + } + + return ret; } bool GDMonoMethod::has_attribute(GDMonoClass *p_attr_class) { diff --git a/modules/mono/mono_gd/gd_mono_utils.cpp b/modules/mono/mono_gd/gd_mono_utils.cpp index 5deca8e64d..53e45002c4 100644 --- a/modules/mono/mono_gd/gd_mono_utils.cpp +++ b/modules/mono/mono_gd/gd_mono_utils.cpp @@ -86,6 +86,7 @@ void MonoCache::clear_members() { class_NodePath = NULL; class_RID = NULL; class_GodotObject = NULL; + class_GodotReference = NULL; class_Node = NULL; class_Control = NULL; class_Spatial = NULL; @@ -95,7 +96,6 @@ void MonoCache::clear_members() { class_ExportAttribute = NULL; field_ExportAttribute_hint = NULL; field_ExportAttribute_hint_string = NULL; - field_ExportAttribute_usage = NULL; class_ToolAttribute = NULL; class_RemoteAttribute = NULL; class_SyncAttribute = NULL; @@ -111,7 +111,7 @@ void MonoCache::clear_members() { methodthunk_MarshalUtils_DictionaryToArrays = NULL; methodthunk_MarshalUtils_ArraysToDictionary = NULL; - methodthunk_GodotObject__AwaitedSignalCallback = NULL; + methodthunk_SignalAwaiter_SignalCallback = NULL; methodthunk_SignalAwaiter_FailureCallback = NULL; methodthunk_GodotTaskScheduler_Activate = NULL; @@ -153,6 +153,7 @@ void update_godot_api_cache() { CACHE_CLASS_AND_CHECK(NodePath, GODOT_API_CLASS(NodePath)); CACHE_CLASS_AND_CHECK(RID, GODOT_API_CLASS(NodePath)); CACHE_CLASS_AND_CHECK(GodotObject, GODOT_API_CLASS(Object)); + CACHE_CLASS_AND_CHECK(GodotReference, GODOT_API_CLASS(Reference)); CACHE_CLASS_AND_CHECK(Node, GODOT_API_CLASS(Node)); CACHE_CLASS_AND_CHECK(Control, GODOT_API_CLASS(Control)); CACHE_CLASS_AND_CHECK(Spatial, GODOT_API_CLASS(Spatial)); @@ -163,7 +164,6 @@ void update_godot_api_cache() { CACHE_CLASS_AND_CHECK(ExportAttribute, GODOT_API_CLASS(ExportAttribute)); CACHE_FIELD_AND_CHECK(ExportAttribute, hint, CACHED_CLASS(ExportAttribute)->get_field("hint")); CACHE_FIELD_AND_CHECK(ExportAttribute, hint_string, CACHED_CLASS(ExportAttribute)->get_field("hint_string")); - CACHE_FIELD_AND_CHECK(ExportAttribute, usage, CACHED_CLASS(ExportAttribute)->get_field("usage")); CACHE_CLASS_AND_CHECK(ToolAttribute, GODOT_API_CLASS(ToolAttribute)); CACHE_CLASS_AND_CHECK(RemoteAttribute, GODOT_API_CLASS(RemoteAttribute)); CACHE_CLASS_AND_CHECK(SyncAttribute, GODOT_API_CLASS(SyncAttribute)); @@ -178,7 +178,7 @@ void update_godot_api_cache() { CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, DictionaryToArrays, (MarshalUtils_DictToArrays)CACHED_CLASS(MarshalUtils)->get_method("DictionaryToArrays", 3)->get_thunk()); CACHE_METHOD_THUNK_AND_CHECK(MarshalUtils, ArraysToDictionary, (MarshalUtils_ArraysToDict)CACHED_CLASS(MarshalUtils)->get_method("ArraysToDictionary", 2)->get_thunk()); - CACHE_METHOD_THUNK_AND_CHECK(GodotObject, _AwaitedSignalCallback, (GodotObject__AwaitedSignalCallback)CACHED_CLASS(GodotObject)->get_method("_AwaitedSignalCallback", 2)->get_thunk()); + CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, SignalCallback, (SignalAwaiter_SignalCallback)GODOT_API_CLASS(SignalAwaiter)->get_method("SignalCallback", 1)->get_thunk()); CACHE_METHOD_THUNK_AND_CHECK(SignalAwaiter, FailureCallback, (SignalAwaiter_FailureCallback)GODOT_API_CLASS(SignalAwaiter)->get_method("FailureCallback", 0)->get_thunk()); CACHE_METHOD_THUNK_AND_CHECK(GodotTaskScheduler, Activate, (GodotTaskScheduler_Activate)GODOT_API_CLASS(GodotTaskScheduler)->get_method("Activate", 0)->get_thunk()); diff --git a/modules/mono/mono_gd/gd_mono_utils.h b/modules/mono/mono_gd/gd_mono_utils.h index f97f048aa9..e3af57e78a 100644 --- a/modules/mono/mono_gd/gd_mono_utils.h +++ b/modules/mono/mono_gd/gd_mono_utils.h @@ -42,7 +42,7 @@ namespace GDMonoUtils { typedef MonoObject *(*MarshalUtils_DictToArrays)(MonoObject *, MonoArray **, MonoArray **, MonoObject **); typedef MonoObject *(*MarshalUtils_ArraysToDict)(MonoArray *, MonoArray *, MonoObject **); -typedef MonoObject *(*GodotObject__AwaitedSignalCallback)(MonoObject *, MonoArray **, MonoObject *, MonoObject **); +typedef MonoObject *(*SignalAwaiter_SignalCallback)(MonoObject *, MonoArray **, MonoObject **); typedef MonoObject *(*SignalAwaiter_FailureCallback)(MonoObject *, MonoObject **); typedef MonoObject *(*GodotTaskScheduler_Activate)(MonoObject *, MonoObject **); @@ -88,6 +88,7 @@ struct MonoCache { GDMonoClass *class_NodePath; GDMonoClass *class_RID; GDMonoClass *class_GodotObject; + GDMonoClass *class_GodotReference; GDMonoClass *class_Node; GDMonoClass *class_Control; GDMonoClass *class_Spatial; @@ -97,7 +98,6 @@ struct MonoCache { GDMonoClass *class_ExportAttribute; GDMonoField *field_ExportAttribute_hint; GDMonoField *field_ExportAttribute_hint_string; - GDMonoField *field_ExportAttribute_usage; GDMonoClass *class_ToolAttribute; GDMonoClass *class_RemoteAttribute; GDMonoClass *class_SyncAttribute; @@ -113,7 +113,7 @@ struct MonoCache { MarshalUtils_DictToArrays methodthunk_MarshalUtils_DictionaryToArrays; MarshalUtils_ArraysToDict methodthunk_MarshalUtils_ArraysToDictionary; - GodotObject__AwaitedSignalCallback methodthunk_GodotObject__AwaitedSignalCallback; + SignalAwaiter_SignalCallback methodthunk_SignalAwaiter_SignalCallback; SignalAwaiter_FailureCallback methodthunk_SignalAwaiter_FailureCallback; GodotTaskScheduler_Activate methodthunk_GodotTaskScheduler_Activate; @@ -164,7 +164,7 @@ String get_exception_name_and_message(MonoObject *p_ex); } // GDMonoUtils -#define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoMarshal::mono_string_to_godot((MonoString *)m_class->get_field("nativeName")->get_value(NULL))) +#define NATIVE_GDMONOCLASS_NAME(m_class) (GDMonoMarshal::mono_string_to_godot((MonoString *)m_class->get_field(BINDINGS_NATIVE_NAME_FIELD)->get_value(NULL))) #define CACHED_CLASS(m_class) (GDMonoUtils::mono_cache.class_##m_class) #define CACHED_CLASS_RAW(m_class) (GDMonoUtils::mono_cache.class_##m_class->get_raw()) diff --git a/modules/mono/mono_reg_utils.py b/modules/mono/mono_reg_utils.py index e9988625f5..8ddddb3a24 100644 --- a/modules/mono/mono_reg_utils.py +++ b/modules/mono/mono_reg_utils.py @@ -1,4 +1,7 @@ import os +import platform + +from compat import decode_utf8 if os.name == 'nt': import sys @@ -11,8 +14,7 @@ if os.name == 'nt': def _reg_open_key(key, subkey): try: return winreg.OpenKey(key, subkey) - except (WindowsError, EnvironmentError) as e: - import platform + except (WindowsError, OSError): if platform.architecture()[0] == '32bit': bitness_sam = winreg.KEY_WOW64_64KEY else: @@ -20,39 +22,93 @@ def _reg_open_key(key, subkey): return winreg.OpenKey(key, subkey, 0, winreg.KEY_READ | bitness_sam) -def _find_mono_in_reg(subkey): +def _reg_open_key_bits(key, subkey, bits): + sam = winreg.KEY_READ + + if platform.architecture()[0] == '32bit': + if bits == '64': + # Force 32bit process to search in 64bit registry + sam |= winreg.KEY_WOW64_64KEY + else: + if bits == '32': + # Force 64bit process to search in 32bit registry + sam |= winreg.KEY_WOW64_32KEY + + return winreg.OpenKey(key, subkey, 0, sam) + + +def _find_mono_in_reg(subkey, bits): try: - with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, subkey) as hKey: + with _reg_open_key_bits(winreg.HKEY_LOCAL_MACHINE, subkey, bits) as hKey: value, regtype = winreg.QueryValueEx(hKey, 'SdkInstallRoot') return value - except (WindowsError, EnvironmentError) as e: + except (WindowsError, OSError): return None -def _find_mono_in_reg_old(subkey): + +def _find_mono_in_reg_old(subkey, bits): try: - with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, subkey) as hKey: + with _reg_open_key_bits(winreg.HKEY_LOCAL_MACHINE, subkey, bits) as hKey: default_clr, regtype = winreg.QueryValueEx(hKey, 'DefaultCLR') if default_clr: - return _find_mono_in_reg(subkey + '\\' + default_clr) + return _find_mono_in_reg(subkey + '\\' + default_clr, bits) return None except (WindowsError, EnvironmentError): return None -def find_mono_root_dir(): - dir = _find_mono_in_reg(r'SOFTWARE\Mono') - if dir: - return dir - dir = _find_mono_in_reg_old(r'SOFTWARE\Novell\Mono') - if dir: - return dir - return None +def find_mono_root_dir(bits): + root_dir = _find_mono_in_reg(r'SOFTWARE\Mono', bits) + if root_dir is not None: + return root_dir + root_dir = _find_mono_in_reg_old(r'SOFTWARE\Novell\Mono', bits) + if root_dir is not None: + return root_dir + return '' def find_msbuild_tools_path_reg(): + import subprocess + + vswhere = os.getenv('PROGRAMFILES(X86)') + if not vswhere: + vswhere = os.getenv('PROGRAMFILES') + vswhere += r'\Microsoft Visual Studio\Installer\vswhere.exe' + + vswhere_args = ['-latest', '-requires', 'Microsoft.Component.MSBuild'] + try: - with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0') as hKey: + lines = subprocess.check_output([vswhere] + vswhere_args).splitlines() + + for line in lines: + parts = decode_utf8(line).split(':', 1) + + if len(parts) < 2 or parts[0] != 'installationPath': + continue + + val = parts[1].strip() + + if not val: + raise ValueError('Value of `installationPath` entry is empty') + + return os.path.join(val, "MSBuild\\15.0\\Bin") + + raise ValueError('Cannot find `installationPath` entry') + except ValueError as e: + print('Error reading output from vswhere: ' + e.message) + except WindowsError: + pass # Fine, vswhere not found + except (subprocess.CalledProcessError, OSError): + pass + + # Try to find 14.0 in the Registry + + try: + subkey = r'SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0' + with _reg_open_key(winreg.HKEY_LOCAL_MACHINE, subkey) as hKey: value, regtype = winreg.QueryValueEx(hKey, 'MSBuildToolsPath') return value - except (WindowsError, EnvironmentError) as e: - return None + except (WindowsError, OSError): + return '' + + return '' diff --git a/modules/mono/signal_awaiter_utils.cpp b/modules/mono/signal_awaiter_utils.cpp index 012dd119b1..7e99df29a1 100644 --- a/modules/mono/signal_awaiter_utils.cpp +++ b/modules/mono/signal_awaiter_utils.cpp @@ -29,6 +29,9 @@ /*************************************************************************/ #include "signal_awaiter_utils.h" +#include "csharp_script.h" +#include "mono_gd/gd_mono_class.h" +#include "mono_gd/gd_mono_marshal.h" #include "mono_gd/gd_mono_utils.h" namespace SignalAwaiterUtils { @@ -40,13 +43,20 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p uint32_t awaiter_handle = MonoGCHandle::make_strong_handle(p_awaiter); Ref<SignalAwaiterHandle> sa_con = memnew(SignalAwaiterHandle(awaiter_handle)); +#ifdef DEBUG_ENABLED + sa_con->set_connection_target(p_target); +#endif + Vector<Variant> binds; binds.push_back(sa_con); - Error err = p_source->connect(p_signal, p_target, "_AwaitedSignalCallback", binds, Object::CONNECT_ONESHOT); + + Error err = p_source->connect(p_signal, sa_con.ptr(), + CSharpLanguage::get_singleton()->get_string_names()._signal_callback, + binds, Object::CONNECT_ONESHOT); if (err != OK) { - // set it as completed to prevent it from calling the failure callback when deleted - // the awaiter will be aware of the failure by checking the returned error + // Set it as completed to prevent it from calling the failure callback when released. + // The awaiter will be aware of the failure by checking the returned error. sa_con->set_completed(true); } @@ -54,11 +64,68 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p } } -SignalAwaiterHandle::SignalAwaiterHandle(uint32_t p_handle) - : MonoGCHandle(p_handle) { +Variant SignalAwaiterHandle::_signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { + +#ifdef DEBUG_ENABLED + if (conn_target_id && !ObjectDB::get_instance(conn_target_id)) { + ERR_EXPLAIN("Resumed after await, but class instance is gone"); + ERR_FAIL_V(Variant()); + } +#endif + + if (p_argcount < 1) { + r_error.error = Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; + r_error.argument = 1; + return Variant(); + } + + Ref<SignalAwaiterHandle> self = *p_args[p_argcount - 1]; + + if (self.is_null()) { + r_error.error = Variant::CallError::CALL_ERROR_INVALID_ARGUMENT; + r_error.argument = p_argcount - 1; + r_error.expected = Variant::OBJECT; + return Variant(); + } + + set_completed(true); + + int signal_argc = p_argcount - 1; + MonoArray *signal_args = mono_array_new(SCRIPTS_DOMAIN, CACHED_CLASS_RAW(MonoObject), signal_argc); + + for (int i = 0; i < signal_argc; i++) { + MonoObject *boxed = GDMonoMarshal::variant_to_mono_object(*p_args[i]); + mono_array_set(signal_args, MonoObject *, i, boxed); + } + + GDMonoUtils::SignalAwaiter_SignalCallback thunk = CACHED_METHOD_THUNK(SignalAwaiter, SignalCallback); + + MonoObject *ex = NULL; + thunk(get_target(), &signal_args, &ex); + + if (ex) { + mono_print_unhandled_exception(ex); + ERR_FAIL_V(Variant()); + } + + return Variant(); +} + +void SignalAwaiterHandle::_bind_methods() { + + ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "_signal_callback", &SignalAwaiterHandle::_signal_callback, MethodInfo("_signal_callback")); +} + +SignalAwaiterHandle::SignalAwaiterHandle(uint32_t p_managed_handle) + : MonoGCHandle(p_managed_handle) { + +#ifdef DEBUG_ENABLED + conn_target_id = 0; +#endif } SignalAwaiterHandle::~SignalAwaiterHandle() { + if (!completed) { GDMonoUtils::SignalAwaiter_FailureCallback thunk = CACHED_METHOD_THUNK(SignalAwaiter, FailureCallback); diff --git a/modules/mono/signal_awaiter_utils.h b/modules/mono/signal_awaiter_utils.h index 422ed4754f..0d615b5826 100644 --- a/modules/mono/signal_awaiter_utils.h +++ b/modules/mono/signal_awaiter_utils.h @@ -40,13 +40,30 @@ Error connect_signal_awaiter(Object *p_source, const String &p_signal, Object *p class SignalAwaiterHandle : public MonoGCHandle { + GDCLASS(SignalAwaiterHandle, MonoGCHandle) + bool completed; +#ifdef DEBUG_ENABLED + ObjectID conn_target_id; +#endif + + Variant _signal_callback(const Variant **p_args, int p_argcount, Variant::CallError &r_error); + +protected: + static void _bind_methods(); + public: _FORCE_INLINE_ bool is_completed() { return completed; } _FORCE_INLINE_ void set_completed(bool p_completed) { completed = p_completed; } - SignalAwaiterHandle(uint32_t p_handle); +#ifdef DEBUG_ENABLED + _FORCE_INLINE_ void set_connection_target(Object *p_target) { + conn_target_id = p_target->get_instance_id(); + } +#endif + + SignalAwaiterHandle(uint32_t p_managed_handle); ~SignalAwaiterHandle(); }; diff --git a/modules/mono/utils/path_utils.cpp b/modules/mono/utils/path_utils.cpp index c8581f6122..105c2c981e 100644 --- a/modules/mono/utils/path_utils.cpp +++ b/modules/mono/utils/path_utils.cpp @@ -56,9 +56,6 @@ String path_which(const String &p_name) { for (int i = 0; i < env_path.size(); i++) { String p = path_join(env_path[i], p_name); - if (FileAccess::exists(p)) - return p; - #ifdef WINDOWS_ENABLED for (int j = 0; j < exts.size(); j++) { String p2 = p + exts[j]; @@ -66,6 +63,9 @@ String path_which(const String &p_name) { if (FileAccess::exists(p2)) return p2; } +#else + if (FileAccess::exists(p)) + return p; #endif } diff --git a/modules/mono/utils/string_utils.cpp b/modules/mono/utils/string_utils.cpp index de1a60dbd1..f26663ea11 100644 --- a/modules/mono/utils/string_utils.cpp +++ b/modules/mono/utils/string_utils.cpp @@ -126,3 +126,32 @@ String sformat(const String &p_text, const Variant &p1, const Variant &p2, const return new_string; } + +bool is_csharp_keyword(const String &p_name) { + + // Reserved keywords + + return p_name == "abstract" || p_name == "as" || p_name == "base" || p_name == "bool" || + p_name == "break" || p_name == "byte" || p_name == "case" || p_name == "catch" || + p_name == "char" || p_name == "checked" || p_name == "class" || p_name == "const" || + p_name == "continue" || p_name == "decimal" || p_name == "default" || p_name == "delegate" || + p_name == "do" || p_name == "double" || p_name == "else" || p_name == "enum" || + p_name == "event" || p_name == "explicit" || p_name == "extern" || p_name == "false" || + p_name == "finally" || p_name == "fixed" || p_name == "float" || p_name == "for" || + p_name == "forech" || p_name == "goto" || p_name == "if" || p_name == "implicit" || + p_name == "in" || p_name == "int" || p_name == "interface" || p_name == "internal" || + p_name == "is" || p_name == "lock" || p_name == "long" || p_name == "namespace" || + p_name == "new" || p_name == "null" || p_name == "object" || p_name == "operator" || + p_name == "out" || p_name == "override" || p_name == "params" || p_name == "private" || + p_name == "protected" || p_name == "public" || p_name == "readonly" || p_name == "ref" || + p_name == "return" || p_name == "sbyte" || p_name == "sealed" || p_name == "short" || + p_name == "sizeof" || p_name == "stackalloc" || p_name == "static" || p_name == "string" || + p_name == "struct" || p_name == "switch" || p_name == "this" || p_name == "throw" || + p_name == "true" || p_name == "try" || p_name == "typeof" || p_name == "uint" || p_name == "ulong" || + p_name == "unchecked" || p_name == "unsafe" || p_name == "ushort" || p_name == "using" || + p_name == "virtual" || p_name == "volatile" || p_name == "void" || p_name == "while"; +} + +String escape_csharp_keyword(const String &p_name) { + return is_csharp_keyword(p_name) ? "@" + p_name : p_name; +} diff --git a/modules/mono/utils/string_utils.h b/modules/mono/utils/string_utils.h index 2f2c3c2d89..a0d66ebdc3 100644 --- a/modules/mono/utils/string_utils.h +++ b/modules/mono/utils/string_utils.h @@ -35,4 +35,10 @@ String sformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant()); +#ifdef TOOLS_ENABLED +bool is_csharp_keyword(const String &p_name); + +String escape_csharp_keyword(const String &p_name); +#endif + #endif // STRING_FORMAT_H diff --git a/modules/openssl/stream_peer_openssl.cpp b/modules/openssl/stream_peer_openssl.cpp index c19bdc4214..6d1d5485f3 100644 --- a/modules/openssl/stream_peer_openssl.cpp +++ b/modules/openssl/stream_peer_openssl.cpp @@ -30,7 +30,7 @@ #include "stream_peer_openssl.h" // Compatibility with OpenSSL 1.1.0. -#if OPENSSL_VERSION_NUMBER >= 0x10100000L +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) #define BIO_set_num(b, n) #else #define BIO_set_num(b, n) ((b)->num = (n)) @@ -269,7 +269,7 @@ int StreamPeerOpenSSL::_bio_puts(BIO *b, const char *str) { return _bio_write(b, str, strlen(str)); } -#if OPENSSL_VERSION_NUMBER >= 0x10100000L +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) BIO_METHOD *StreamPeerOpenSSL::_bio_method = NULL; BIO_METHOD *StreamPeerOpenSSL::_get_bio_method() { @@ -568,7 +568,7 @@ void StreamPeerOpenSSL::initialize_ssl() { load_certs_func = _load_certs; _create = _create_func; -#if OPENSSL_VERSION_NUMBER < 0x10100000L +#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use #endif SSL_library_init(); // Initialize OpenSSL's SSL libraries diff --git a/modules/openssl/stream_peer_openssl.h b/modules/openssl/stream_peer_openssl.h index 535114058d..ad09564447 100644 --- a/modules/openssl/stream_peer_openssl.h +++ b/modules/openssl/stream_peer_openssl.h @@ -53,7 +53,7 @@ private: static int _bio_gets(BIO *b, char *buf, int len); static int _bio_puts(BIO *b, const char *str); -#if OPENSSL_VERSION_NUMBER >= 0x10100000L +#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER) static BIO_METHOD *_bio_method; #else static BIO_METHOD _bio_method; diff --git a/modules/opus/audio_stream_opus.cpp b/modules/opus/audio_stream_opus.cpp index c7748b9b21..06eab4c94d 100644 --- a/modules/opus/audio_stream_opus.cpp +++ b/modules/opus/audio_stream_opus.cpp @@ -267,7 +267,7 @@ void AudioStreamPlaybackOpus::seek(float p_time) { frames_mixed = osrate * p_time; } -int AudioStreamPlaybackOpus::mix(int16_t *p_bufer, int p_frames) { +int AudioStreamPlaybackOpus::mix(int16_t *p_buffer, int p_frames) { if (!playing) return 0; @@ -281,7 +281,7 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_bufer, int p_frames) { break; } - int ret = op_read(opus_file, (opus_int16 *)p_bufer, todo * stream_channels, ¤t_section); + int ret = op_read(opus_file, (opus_int16 *)p_buffer, todo * stream_channels, ¤t_section); if (ret < 0) { playing = false; ERR_EXPLAIN("Error reading Opus File: " + file); @@ -325,7 +325,7 @@ int AudioStreamPlaybackOpus::mix(int16_t *p_bufer, int p_frames) { frames_mixed += ret; - p_bufer += ret * stream_channels; + p_buffer += ret * stream_channels; p_frames -= ret; } diff --git a/modules/opus/audio_stream_opus.h b/modules/opus/audio_stream_opus.h index 7b7740a804..f8d8f585cf 100644 --- a/modules/opus/audio_stream_opus.h +++ b/modules/opus/audio_stream_opus.h @@ -107,7 +107,7 @@ public: virtual int get_minimum_buffer_size() const; - virtual int mix(int16_t *p_bufer, int p_frames); + virtual int mix(int16_t *p_buffer, int p_frames); AudioStreamPlaybackOpus(); ~AudioStreamPlaybackOpus(); diff --git a/modules/regex/SCsub b/modules/regex/SCsub index 2bab144a28..18b4051afe 100644 --- a/modules/regex/SCsub +++ b/modules/regex/SCsub @@ -8,7 +8,7 @@ env_regex.Append(CPPFLAGS=["-DPCRE2_CODE_UNIT_WIDTH=0"]) env_regex.add_source_files(env.modules_sources, "*.cpp") if env['builtin_pcre2']: - jit_blacklist = ['javascript'] + jit_blacklist = ['javascript', 'uwp'] thirdparty_dir = '#thirdparty/pcre2/src/' thirdparty_flags = ['-DPCRE2_STATIC', '-DHAVE_CONFIG_H'] if 'platform' in env and env['platform'] not in jit_blacklist: diff --git a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp index 27ea310780..5c252bda86 100644 --- a/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/stb_vorbis/audio_stream_ogg_vorbis.cpp @@ -129,7 +129,6 @@ AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; - printf("instance at %p, data %p\n", this, data); ERR_FAIL_COND_V(data == NULL, ovs); @@ -208,8 +207,6 @@ void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { break; } } - - printf("create at %p, data %p\n", this, data); } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { diff --git a/modules/visual_script/visual_script.cpp b/modules/visual_script/visual_script.cpp index 48145495e4..765fe4c2f2 100644 --- a/modules/visual_script/visual_script.cpp +++ b/modules/visual_script/visual_script.cpp @@ -974,11 +974,6 @@ bool VisualScript::is_tool() const { return false; } -String VisualScript::get_node_type() const { - - return String(); -} - ScriptLanguage *VisualScript::get_language() const { return VisualScriptLanguage::singleton; @@ -2412,6 +2407,10 @@ bool VisualScriptLanguage::has_named_classes() const { return false; } +bool VisualScriptLanguage::supports_builtin_mode() const { + + return true; +} int VisualScriptLanguage::find_function(const String &p_function, const String &p_code) const { return -1; diff --git a/modules/visual_script/visual_script.h b/modules/visual_script/visual_script.h index 4ae50ee829..0f60b103c9 100644 --- a/modules/visual_script/visual_script.h +++ b/modules/visual_script/visual_script.h @@ -339,8 +339,6 @@ public: virtual bool is_tool() const; - virtual String get_node_type() const; - virtual ScriptLanguage *get_language() const; virtual bool has_script_signal(const StringName &p_signal) const; @@ -569,6 +567,7 @@ public: virtual bool validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path = "", List<String> *r_functions = NULL) const; virtual Script *create_script() const; virtual bool has_named_classes() const; + virtual bool supports_builtin_mode() const; virtual int find_function(const String &p_function, const String &p_code) const; virtual String make_function(const String &p_class, const String &p_name, const PoolStringArray &p_args) const; virtual void auto_indent_code(String &p_code, int p_from_line, int p_to_line) const; diff --git a/modules/visual_script/visual_script_builtin_funcs.cpp b/modules/visual_script/visual_script_builtin_funcs.cpp index 90219e29f8..7c9d306831 100644 --- a/modules/visual_script/visual_script_builtin_funcs.cpp +++ b/modules/visual_script/visual_script_builtin_funcs.cpp @@ -65,6 +65,8 @@ const char *VisualScriptBuiltinFunc::func_name[VisualScriptBuiltinFunc::FUNC_MAX "decimals", "stepify", "lerp", + "inverse_lerp", + "range_lerp", "dectime", "randomize", "randi", @@ -196,11 +198,14 @@ int VisualScriptBuiltinFunc::get_func_argument_count(BuiltinFunc p_func) { case COLORN: return 2; case MATH_LERP: + case MATH_INVERSE_LERP: case MATH_DECTIME: case MATH_WRAP: case MATH_WRAPF: case LOGIC_CLAMP: return 3; + case MATH_RANGE_LERP: + return 5; case FUNC_MAX: { } } @@ -301,7 +306,26 @@ PropertyInfo VisualScriptBuiltinFunc::get_input_value_port_info(int p_idx) const return PropertyInfo(Variant::REAL, "to"); else return PropertyInfo(Variant::REAL, "weight"); - + } break; + case MATH_INVERSE_LERP: { + if (p_idx == 0) + return PropertyInfo(Variant::REAL, "from"); + else if (p_idx == 1) + return PropertyInfo(Variant::REAL, "to"); + else + return PropertyInfo(Variant::REAL, "value"); + } break; + case MATH_RANGE_LERP: { + if (p_idx == 0) + return PropertyInfo(Variant::REAL, "value"); + else if (p_idx == 1) + return PropertyInfo(Variant::REAL, "istart"); + else if (p_idx == 2) + return PropertyInfo(Variant::REAL, "istop"); + else if (p_idx == 3) + return PropertyInfo(Variant::REAL, "ostart"); + else + return PropertyInfo(Variant::REAL, "ostop"); } break; case MATH_DECTIME: { if (p_idx == 0) @@ -515,6 +539,8 @@ PropertyInfo VisualScriptBuiltinFunc::get_output_value_port_info(int p_idx) cons } break; case MATH_STEPIFY: case MATH_LERP: + case MATH_INVERSE_LERP: + case MATH_RANGE_LERP: case MATH_DECTIME: { t = Variant::REAL; @@ -819,6 +845,22 @@ void VisualScriptBuiltinFunc::exec_func(BuiltinFunc p_func, const Variant **p_in VALIDATE_ARG_NUM(2); *r_return = Math::lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); } break; + case VisualScriptBuiltinFunc::MATH_INVERSE_LERP: { + + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + *r_return = Math::inverse_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2]); + } break; + case VisualScriptBuiltinFunc::MATH_RANGE_LERP: { + + VALIDATE_ARG_NUM(0); + VALIDATE_ARG_NUM(1); + VALIDATE_ARG_NUM(2); + VALIDATE_ARG_NUM(3); + VALIDATE_ARG_NUM(4); + *r_return = Math::range_lerp((double)*p_inputs[0], (double)*p_inputs[1], (double)*p_inputs[2], (double)*p_inputs[3], (double)*p_inputs[4]); + } break; case VisualScriptBuiltinFunc::MATH_DECTIME: { VALIDATE_ARG_NUM(0); @@ -1239,6 +1281,8 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(MATH_DECIMALS); BIND_ENUM_CONSTANT(MATH_STEPIFY); BIND_ENUM_CONSTANT(MATH_LERP); + BIND_ENUM_CONSTANT(MATH_INVERSE_LERP); + BIND_ENUM_CONSTANT(MATH_RANGE_LERP); BIND_ENUM_CONSTANT(MATH_DECTIME); BIND_ENUM_CONSTANT(MATH_RANDOMIZE); BIND_ENUM_CONSTANT(MATH_RAND); @@ -1274,6 +1318,11 @@ void VisualScriptBuiltinFunc::_bind_methods() { BIND_ENUM_CONSTANT(FUNC_MAX); } +VisualScriptBuiltinFunc::VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func) { + + this->func = func; +} + VisualScriptBuiltinFunc::VisualScriptBuiltinFunc() { func = MATH_SIN; @@ -1282,9 +1331,7 @@ VisualScriptBuiltinFunc::VisualScriptBuiltinFunc() { template <VisualScriptBuiltinFunc::BuiltinFunc func> static Ref<VisualScriptNode> create_builtin_func_node(const String &p_name) { - Ref<VisualScriptBuiltinFunc> node; - node.instance(); - node->set_func(func); + Ref<VisualScriptBuiltinFunc> node = memnew(VisualScriptBuiltinFunc(func)); return node; } @@ -1320,6 +1367,8 @@ void register_visual_script_builtin_func_node() { VisualScriptLanguage::singleton->add_register_func("functions/built_in/decimals", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECIMALS>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/stepify", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_STEPIFY>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_LERP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/inverse_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_INVERSE_LERP>); + VisualScriptLanguage::singleton->add_register_func("functions/built_in/range_lerp", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANGE_LERP>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/dectime", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_DECTIME>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/randomize", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RANDOMIZE>); VisualScriptLanguage::singleton->add_register_func("functions/built_in/rand", create_builtin_func_node<VisualScriptBuiltinFunc::MATH_RAND>); diff --git a/modules/visual_script/visual_script_builtin_funcs.h b/modules/visual_script/visual_script_builtin_funcs.h index c530d6d2d1..34a2825938 100644 --- a/modules/visual_script/visual_script_builtin_funcs.h +++ b/modules/visual_script/visual_script_builtin_funcs.h @@ -64,6 +64,8 @@ public: MATH_DECIMALS, MATH_STEPIFY, MATH_LERP, + MATH_INVERSE_LERP, + MATH_RANGE_LERP, MATH_DECTIME, MATH_RANDOMIZE, MATH_RAND, @@ -132,6 +134,7 @@ public: virtual VisualScriptNodeInstance *instance(VisualScriptInstance *p_instance); + VisualScriptBuiltinFunc(VisualScriptBuiltinFunc::BuiltinFunc func); VisualScriptBuiltinFunc(); }; diff --git a/modules/visual_script/visual_script_editor.cpp b/modules/visual_script/visual_script_editor.cpp index 47ef0182dc..03015df844 100644 --- a/modules/visual_script/visual_script_editor.cpp +++ b/modules/visual_script/visual_script_editor.cpp @@ -809,7 +809,7 @@ void VisualScriptEditor::_update_members() { ti->set_text(0, E->get()); Variant var = script->get_variable_default_value(E->get()); - ti->set_suffix(0, "=" + String(var)); + ti->set_suffix(0, "= " + String(var)); ti->set_icon(0, type_icons[script->get_variable_info(E->get()).type]); ti->set_selectable(0, true); diff --git a/modules/visual_script/visual_script_nodes.cpp b/modules/visual_script/visual_script_nodes.cpp index 5a34fc3cd9..d3cd839cf3 100644 --- a/modules/visual_script/visual_script_nodes.cpp +++ b/modules/visual_script/visual_script_nodes.cpp @@ -532,6 +532,7 @@ String VisualScriptOperator::get_text() const { L"A or B", //OP_OR, L"A xor B", //OP_XOR, L"not A", //OP_NOT, + L"A in B", //OP_IN, }; return op_names[op]; diff --git a/modules/visual_script/visual_script_yield_nodes.cpp b/modules/visual_script/visual_script_yield_nodes.cpp index bc033418ba..3c9076246d 100644 --- a/modules/visual_script/visual_script_yield_nodes.cpp +++ b/modules/visual_script/visual_script_yield_nodes.cpp @@ -82,7 +82,7 @@ String VisualScriptYield::get_text() const { switch (yield_mode) { case YIELD_RETURN: return ""; break; case YIELD_FRAME: return "Next Frame"; break; - case YIELD_PHYSICS_FRAME: return "Next Fixed Frame"; break; + case YIELD_PHYSICS_FRAME: return "Next Physics Frame"; break; case YIELD_WAIT: return rtos(wait_time) + " sec(s)"; break; } @@ -186,7 +186,7 @@ void VisualScriptYield::_bind_methods() { ClassDB::bind_method(D_METHOD("set_wait_time", "sec"), &VisualScriptYield::set_wait_time); ClassDB::bind_method(D_METHOD("get_wait_time"), &VisualScriptYield::get_wait_time); - ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Frame,FixedFrame,Time", PROPERTY_USAGE_NOEDITOR), "set_yield_mode", "get_yield_mode"); + ADD_PROPERTY(PropertyInfo(Variant::INT, "mode", PROPERTY_HINT_ENUM, "Frame,Physics Frame,Time", PROPERTY_USAGE_NOEDITOR), "set_yield_mode", "get_yield_mode"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "wait_time"), "set_wait_time", "get_wait_time"); BIND_ENUM_CONSTANT(YIELD_FRAME); diff --git a/modules/vorbis/audio_stream_ogg_vorbis.cpp b/modules/vorbis/audio_stream_ogg_vorbis.cpp index 0afb889199..6235799fc2 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.cpp +++ b/modules/vorbis/audio_stream_ogg_vorbis.cpp @@ -92,7 +92,7 @@ long AudioStreamPlaybackOGGVorbis::_ov_tell_func(void *_f) { return fa->get_position(); } -int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_bufer, int p_frames) { +int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_buffer, int p_frames) { if (!playing) return 0; @@ -109,9 +109,9 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_bufer, int p_frames) { //printf("to mix %i - mix me %i bytes\n",to_mix,to_mix*stream_channels*sizeof(int16_t)); #ifdef BIG_ENDIAN_ENABLED - long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 1, 2, 1, ¤t_section); + long ret = ov_read(&vf, (char *)p_buffer, todo * stream_channels * sizeof(int16_t), 1, 2, 1, ¤t_section); #else - long ret = ov_read(&vf, (char *)p_bufer, todo * stream_channels * sizeof(int16_t), 0, 2, 1, ¤t_section); + long ret = ov_read(&vf, (char *)p_buffer, todo * stream_channels * sizeof(int16_t), 0, 2, 1, ¤t_section); #endif if (ret < 0) { @@ -162,7 +162,7 @@ int AudioStreamPlaybackOGGVorbis::mix(int16_t *p_bufer, int p_frames) { frames_mixed += ret; - p_bufer += ret * stream_channels; + p_buffer += ret * stream_channels; p_frames -= ret; } diff --git a/modules/vorbis/audio_stream_ogg_vorbis.h b/modules/vorbis/audio_stream_ogg_vorbis.h index 929b2651e9..79eadec56e 100644 --- a/modules/vorbis/audio_stream_ogg_vorbis.h +++ b/modules/vorbis/audio_stream_ogg_vorbis.h @@ -103,7 +103,7 @@ public: virtual int get_mix_rate() const { return stream_srate; } virtual int get_minimum_buffer_size() const { return 0; } - virtual int mix(int16_t *p_bufer, int p_frames); + virtual int mix(int16_t *p_buffer, int p_frames); AudioStreamPlaybackOGGVorbis(); ~AudioStreamPlaybackOGGVorbis(); |