2
0

gdextension.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. /**************************************************************************/
  2. /* gdextension.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gdextension.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/object/class_db.h"
  34. #include "core/object/method_bind.h"
  35. #include "core/os/os.h"
  36. #include "core/version.h"
  37. #include "gdextension_manager.h"
  38. extern void gdextension_setup_interface();
  39. extern GDExtensionInterfaceFunctionPtr gdextension_get_proc_address(const char *p_name);
  40. typedef GDExtensionBool (*GDExtensionLegacyInitializationFunction)(void *p_interface, GDExtensionClassLibraryPtr p_library, GDExtensionInitialization *r_initialization);
  41. String GDExtension::get_extension_list_config_file() {
  42. return ProjectSettings::get_singleton()->get_project_data_path().path_join("extension_list.cfg");
  43. }
  44. String GDExtension::find_extension_library(const String &p_path, Ref<ConfigFile> p_config, std::function<bool(String)> p_has_feature, PackedStringArray *r_tags) {
  45. // First, check the explicit libraries.
  46. if (p_config->has_section("libraries")) {
  47. List<String> libraries;
  48. p_config->get_section_keys("libraries", &libraries);
  49. // Iterate the libraries, finding the best matching tags.
  50. String best_library_path;
  51. Vector<String> best_library_tags;
  52. for (const String &E : libraries) {
  53. Vector<String> tags = E.split(".");
  54. bool all_tags_met = true;
  55. for (int i = 0; i < tags.size(); i++) {
  56. String tag = tags[i].strip_edges();
  57. if (!p_has_feature(tag)) {
  58. all_tags_met = false;
  59. break;
  60. }
  61. }
  62. if (all_tags_met && tags.size() > best_library_tags.size()) {
  63. best_library_path = p_config->get_value("libraries", E);
  64. best_library_tags = tags;
  65. }
  66. }
  67. if (!best_library_path.is_empty()) {
  68. if (best_library_path.is_relative_path()) {
  69. best_library_path = p_path.get_base_dir().path_join(best_library_path);
  70. }
  71. if (r_tags != nullptr) {
  72. r_tags->append_array(best_library_tags);
  73. }
  74. return best_library_path;
  75. }
  76. }
  77. // Second, try to autodetect
  78. String autodetect_library_prefix;
  79. if (p_config->has_section_key("configuration", "autodetect_library_prefix")) {
  80. autodetect_library_prefix = p_config->get_value("configuration", "autodetect_library_prefix");
  81. }
  82. if (!autodetect_library_prefix.is_empty()) {
  83. String autodetect_path = autodetect_library_prefix;
  84. if (autodetect_path.is_relative_path()) {
  85. autodetect_path = p_path.get_base_dir().path_join(autodetect_path);
  86. }
  87. // Find the folder and file parts of the prefix.
  88. String folder;
  89. String file_prefix;
  90. if (DirAccess::dir_exists_absolute(autodetect_path)) {
  91. folder = autodetect_path;
  92. } else if (DirAccess::dir_exists_absolute(autodetect_path.get_base_dir())) {
  93. folder = autodetect_path.get_base_dir();
  94. file_prefix = autodetect_path.get_file();
  95. } else {
  96. ERR_FAIL_V_MSG(String(), vformat("Error in extension: %s. Could not find folder for automatic detection of libraries files. autodetect_library_prefix=\"%s\"", p_path, autodetect_library_prefix));
  97. }
  98. // Open the folder.
  99. Ref<DirAccess> dir = DirAccess::open(folder);
  100. ERR_FAIL_COND_V_MSG(!dir.is_valid(), String(), vformat("Error in extension: %s. Could not open folder for automatic detection of libraries files. autodetect_library_prefix=\"%s\"", p_path, autodetect_library_prefix));
  101. // Iterate the files and check the prefixes, finding the best matching file.
  102. String best_file;
  103. Vector<String> best_file_tags;
  104. dir->list_dir_begin();
  105. String file_name = dir->_get_next();
  106. while (file_name != "") {
  107. if (!dir->current_is_dir() && file_name.begins_with(file_prefix)) {
  108. // Check if the files matches all requested feature tags.
  109. String tags_str = file_name.trim_prefix(file_prefix);
  110. tags_str = tags_str.trim_suffix(tags_str.get_extension());
  111. Vector<String> tags = tags_str.split(".", false);
  112. bool all_tags_met = true;
  113. for (int i = 0; i < tags.size(); i++) {
  114. String tag = tags[i].strip_edges();
  115. if (!p_has_feature(tag)) {
  116. all_tags_met = false;
  117. break;
  118. }
  119. }
  120. // If all tags are found in the feature list, and we found more tags than before, use this file.
  121. if (all_tags_met && tags.size() > best_file_tags.size()) {
  122. best_file_tags = tags;
  123. best_file = file_name;
  124. }
  125. }
  126. file_name = dir->_get_next();
  127. }
  128. if (!best_file.is_empty()) {
  129. String library_path = folder.path_join(best_file);
  130. if (r_tags != nullptr) {
  131. r_tags->append_array(best_file_tags);
  132. }
  133. return library_path;
  134. }
  135. }
  136. return String();
  137. }
  138. class GDExtensionMethodBind : public MethodBind {
  139. GDExtensionClassMethodCall call_func;
  140. GDExtensionClassMethodValidatedCall validated_call_func;
  141. GDExtensionClassMethodPtrCall ptrcall_func;
  142. void *method_userdata;
  143. bool vararg;
  144. uint32_t argument_count;
  145. PropertyInfo return_value_info;
  146. GodotTypeInfo::Metadata return_value_metadata;
  147. List<PropertyInfo> arguments_info;
  148. List<GodotTypeInfo::Metadata> arguments_metadata;
  149. #ifdef TOOLS_ENABLED
  150. friend class GDExtension;
  151. StringName name;
  152. bool is_reloading = false;
  153. bool valid = true;
  154. #endif
  155. protected:
  156. virtual Variant::Type _gen_argument_type(int p_arg) const override {
  157. if (p_arg < 0) {
  158. return return_value_info.type;
  159. } else {
  160. return arguments_info[p_arg].type;
  161. }
  162. }
  163. virtual PropertyInfo _gen_argument_type_info(int p_arg) const override {
  164. if (p_arg < 0) {
  165. return return_value_info;
  166. } else {
  167. return arguments_info[p_arg];
  168. }
  169. }
  170. public:
  171. #ifdef TOOLS_ENABLED
  172. virtual bool is_valid() const override { return valid; }
  173. #endif
  174. #ifdef DEBUG_METHODS_ENABLED
  175. virtual GodotTypeInfo::Metadata get_argument_meta(int p_arg) const override {
  176. if (p_arg < 0) {
  177. return return_value_metadata;
  178. } else {
  179. return arguments_metadata[p_arg];
  180. }
  181. }
  182. #endif
  183. virtual Variant call(Object *p_object, const Variant **p_args, int p_arg_count, Callable::CallError &r_error) const override {
  184. #ifdef TOOLS_ENABLED
  185. ERR_FAIL_COND_V_MSG(!valid, Variant(), vformat("Cannot call invalid GDExtension method bind '%s'. It's probably cached - you may need to restart Godot.", name));
  186. #endif
  187. Variant ret;
  188. GDExtensionClassInstancePtr extension_instance = is_static() ? nullptr : p_object->_get_extension_instance();
  189. GDExtensionCallError ce{ GDEXTENSION_CALL_OK, 0, 0 };
  190. call_func(method_userdata, extension_instance, reinterpret_cast<GDExtensionConstVariantPtr *>(p_args), p_arg_count, (GDExtensionVariantPtr)&ret, &ce);
  191. r_error.error = Callable::CallError::Error(ce.error);
  192. r_error.argument = ce.argument;
  193. r_error.expected = ce.expected;
  194. return ret;
  195. }
  196. virtual void validated_call(Object *p_object, const Variant **p_args, Variant *r_ret) const override {
  197. #ifdef TOOLS_ENABLED
  198. ERR_FAIL_COND_MSG(!valid, vformat("Cannot call invalid GDExtension method bind '%s'. It's probably cached - you may need to restart Godot.", name));
  199. #endif
  200. ERR_FAIL_COND_MSG(vararg, "Vararg methods don't have validated call support. This is most likely an engine bug.");
  201. GDExtensionClassInstancePtr extension_instance = is_static() ? nullptr : p_object->_get_extension_instance();
  202. if (validated_call_func) {
  203. // This is added here, but it's unlikely to be provided by most extensions.
  204. validated_call_func(method_userdata, extension_instance, reinterpret_cast<GDExtensionConstVariantPtr *>(p_args), (GDExtensionVariantPtr)r_ret);
  205. } else {
  206. // If not provided, go via ptrcall, which is faster than resorting to regular call.
  207. const void **argptrs = (const void **)alloca(argument_count * sizeof(void *));
  208. for (uint32_t i = 0; i < argument_count; i++) {
  209. argptrs[i] = VariantInternal::get_opaque_pointer(p_args[i]);
  210. }
  211. void *ret_opaque = nullptr;
  212. if (r_ret) {
  213. VariantInternal::initialize(r_ret, return_value_info.type);
  214. ret_opaque = r_ret->get_type() == Variant::NIL ? r_ret : VariantInternal::get_opaque_pointer(r_ret);
  215. }
  216. ptrcall(p_object, argptrs, ret_opaque);
  217. if (r_ret && r_ret->get_type() == Variant::OBJECT) {
  218. VariantInternal::update_object_id(r_ret);
  219. }
  220. }
  221. }
  222. virtual void ptrcall(Object *p_object, const void **p_args, void *r_ret) const override {
  223. #ifdef TOOLS_ENABLED
  224. ERR_FAIL_COND_MSG(!valid, vformat("Cannot call invalid GDExtension method bind '%s'. It's probably cached - you may need to restart Godot.", name));
  225. #endif
  226. ERR_FAIL_COND_MSG(vararg, "Vararg methods don't have ptrcall support. This is most likely an engine bug.");
  227. GDExtensionClassInstancePtr extension_instance = p_object->_get_extension_instance();
  228. ptrcall_func(method_userdata, extension_instance, reinterpret_cast<GDExtensionConstTypePtr *>(p_args), (GDExtensionTypePtr)r_ret);
  229. }
  230. virtual bool is_vararg() const override {
  231. return false;
  232. }
  233. #ifdef TOOLS_ENABLED
  234. bool try_update(const GDExtensionClassMethodInfo *p_method_info) {
  235. if (is_static() != (bool)(p_method_info->method_flags & GDEXTENSION_METHOD_FLAG_STATIC)) {
  236. return false;
  237. }
  238. if (vararg != (bool)(p_method_info->method_flags & GDEXTENSION_METHOD_FLAG_VARARG)) {
  239. return false;
  240. }
  241. if (has_return() != (bool)p_method_info->has_return_value) {
  242. return false;
  243. }
  244. if (has_return() && return_value_info.type != (Variant::Type)p_method_info->return_value_info->type) {
  245. return false;
  246. }
  247. if (argument_count != p_method_info->argument_count) {
  248. return false;
  249. }
  250. for (uint32_t i = 0; i < p_method_info->argument_count; i++) {
  251. if (arguments_info[i].type != (Variant::Type)p_method_info->arguments_info[i].type) {
  252. return false;
  253. }
  254. }
  255. update(p_method_info);
  256. return true;
  257. }
  258. #endif
  259. void update(const GDExtensionClassMethodInfo *p_method_info) {
  260. #ifdef TOOLS_ENABLED
  261. name = *reinterpret_cast<StringName *>(p_method_info->name);
  262. #endif
  263. method_userdata = p_method_info->method_userdata;
  264. call_func = p_method_info->call_func;
  265. validated_call_func = nullptr;
  266. ptrcall_func = p_method_info->ptrcall_func;
  267. set_name(*reinterpret_cast<StringName *>(p_method_info->name));
  268. if (p_method_info->has_return_value) {
  269. return_value_info = PropertyInfo(*p_method_info->return_value_info);
  270. return_value_metadata = GodotTypeInfo::Metadata(p_method_info->return_value_metadata);
  271. }
  272. arguments_info.clear();
  273. arguments_metadata.clear();
  274. for (uint32_t i = 0; i < p_method_info->argument_count; i++) {
  275. arguments_info.push_back(PropertyInfo(p_method_info->arguments_info[i]));
  276. arguments_metadata.push_back(GodotTypeInfo::Metadata(p_method_info->arguments_metadata[i]));
  277. }
  278. set_hint_flags(p_method_info->method_flags);
  279. argument_count = p_method_info->argument_count;
  280. vararg = p_method_info->method_flags & GDEXTENSION_METHOD_FLAG_VARARG;
  281. _set_returns(p_method_info->has_return_value);
  282. _set_const(p_method_info->method_flags & GDEXTENSION_METHOD_FLAG_CONST);
  283. _set_static(p_method_info->method_flags & GDEXTENSION_METHOD_FLAG_STATIC);
  284. #ifdef DEBUG_METHODS_ENABLED
  285. _generate_argument_types(p_method_info->argument_count);
  286. #endif
  287. set_argument_count(p_method_info->argument_count);
  288. Vector<Variant> defargs;
  289. defargs.resize(p_method_info->default_argument_count);
  290. for (uint32_t i = 0; i < p_method_info->default_argument_count; i++) {
  291. defargs.write[i] = *static_cast<Variant *>(p_method_info->default_arguments[i]);
  292. }
  293. set_default_arguments(defargs);
  294. }
  295. explicit GDExtensionMethodBind(const GDExtensionClassMethodInfo *p_method_info) {
  296. update(p_method_info);
  297. }
  298. };
  299. #ifndef DISABLE_DEPRECATED
  300. void GDExtension::_register_extension_class(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringNamePtr p_parent_class_name, const GDExtensionClassCreationInfo *p_extension_funcs) {
  301. const GDExtensionClassCreationInfo2 class_info2 = {
  302. p_extension_funcs->is_virtual, // GDExtensionBool is_virtual;
  303. p_extension_funcs->is_abstract, // GDExtensionBool is_abstract;
  304. true, // GDExtensionBool is_exposed;
  305. p_extension_funcs->set_func, // GDExtensionClassSet set_func;
  306. p_extension_funcs->get_func, // GDExtensionClassGet get_func;
  307. p_extension_funcs->get_property_list_func, // GDExtensionClassGetPropertyList get_property_list_func;
  308. p_extension_funcs->free_property_list_func, // GDExtensionClassFreePropertyList free_property_list_func;
  309. p_extension_funcs->property_can_revert_func, // GDExtensionClassPropertyCanRevert property_can_revert_func;
  310. p_extension_funcs->property_get_revert_func, // GDExtensionClassPropertyGetRevert property_get_revert_func;
  311. nullptr, // GDExtensionClassValidateProperty validate_property_func;
  312. nullptr, // GDExtensionClassNotification2 notification_func;
  313. p_extension_funcs->to_string_func, // GDExtensionClassToString to_string_func;
  314. p_extension_funcs->reference_func, // GDExtensionClassReference reference_func;
  315. p_extension_funcs->unreference_func, // GDExtensionClassUnreference unreference_func;
  316. p_extension_funcs->create_instance_func, // GDExtensionClassCreateInstance create_instance_func; /* this one is mandatory */
  317. p_extension_funcs->free_instance_func, // GDExtensionClassFreeInstance free_instance_func; /* this one is mandatory */
  318. nullptr, // GDExtensionClassRecreateInstance recreate_instance_func;
  319. p_extension_funcs->get_virtual_func, // GDExtensionClassGetVirtual get_virtual_func;
  320. nullptr, // GDExtensionClassGetVirtualCallData get_virtual_call_data_func;
  321. nullptr, // GDExtensionClassCallVirtualWithData call_virtual_func;
  322. p_extension_funcs->get_rid_func, // GDExtensionClassGetRID get_rid;
  323. p_extension_funcs->class_userdata, // void *class_userdata;
  324. };
  325. const ClassCreationDeprecatedInfo legacy = {
  326. p_extension_funcs->notification_func,
  327. };
  328. _register_extension_class_internal(p_library, p_class_name, p_parent_class_name, &class_info2, &legacy);
  329. }
  330. #endif // DISABLE_DEPRECATED
  331. void GDExtension::_register_extension_class2(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringNamePtr p_parent_class_name, const GDExtensionClassCreationInfo2 *p_extension_funcs) {
  332. _register_extension_class_internal(p_library, p_class_name, p_parent_class_name, p_extension_funcs);
  333. }
  334. void GDExtension::_register_extension_class_internal(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringNamePtr p_parent_class_name, const GDExtensionClassCreationInfo2 *p_extension_funcs, const ClassCreationDeprecatedInfo *p_deprecated_funcs) {
  335. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  336. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  337. StringName parent_class_name = *reinterpret_cast<const StringName *>(p_parent_class_name);
  338. ERR_FAIL_COND_MSG(!String(class_name).is_valid_identifier(), "Attempt to register extension class '" + class_name + "', which is not a valid class identifier.");
  339. ERR_FAIL_COND_MSG(ClassDB::class_exists(class_name), "Attempt to register extension class '" + class_name + "', which appears to be already registered.");
  340. Extension *parent_extension = nullptr;
  341. if (self->extension_classes.has(parent_class_name)) {
  342. parent_extension = &self->extension_classes[parent_class_name];
  343. } else if (ClassDB::class_exists(parent_class_name)) {
  344. if (ClassDB::get_api_type(parent_class_name) == ClassDB::API_EXTENSION || ClassDB::get_api_type(parent_class_name) == ClassDB::API_EDITOR_EXTENSION) {
  345. ERR_PRINT("Unimplemented yet");
  346. //inheriting from another extension
  347. } else {
  348. //inheriting from engine class
  349. }
  350. } else {
  351. ERR_FAIL_MSG("Attempt to register an extension class '" + String(class_name) + "' using non-existing parent class '" + String(parent_class_name) + "'");
  352. }
  353. #ifdef TOOLS_ENABLED
  354. Extension *extension = nullptr;
  355. if (self->is_reloading && self->extension_classes.has(class_name)) {
  356. extension = &self->extension_classes[class_name];
  357. if (!parent_extension && parent_class_name != extension->gdextension.parent_class_name) {
  358. ERR_FAIL_MSG(vformat("GDExtension class '%s' attempt to change parent type from '%s' to '%s' on hot reload. Restart Godot for this change to take effect.", class_name, extension->gdextension.parent_class_name, parent_class_name));
  359. }
  360. extension->is_reloading = false;
  361. } else {
  362. self->extension_classes[class_name] = Extension();
  363. extension = &self->extension_classes[class_name];
  364. }
  365. #else
  366. self->extension_classes[class_name] = Extension();
  367. Extension *extension = &self->extension_classes[class_name];
  368. #endif
  369. if (parent_extension) {
  370. extension->gdextension.parent = &parent_extension->gdextension;
  371. parent_extension->gdextension.children.push_back(&extension->gdextension);
  372. }
  373. if (self->reloadable && p_extension_funcs->recreate_instance_func == nullptr) {
  374. ERR_PRINT(vformat("Extension marked as reloadable, but attempted to register class '%s' which doesn't support reloading. Perhaps your language binding don't support it? Reloading disabled for this extension.", class_name));
  375. self->reloadable = false;
  376. }
  377. extension->gdextension.library = self;
  378. extension->gdextension.parent_class_name = parent_class_name;
  379. extension->gdextension.class_name = class_name;
  380. extension->gdextension.editor_class = self->level_initialized == INITIALIZATION_LEVEL_EDITOR;
  381. extension->gdextension.is_virtual = p_extension_funcs->is_virtual;
  382. extension->gdextension.is_abstract = p_extension_funcs->is_abstract;
  383. extension->gdextension.is_exposed = p_extension_funcs->is_exposed;
  384. extension->gdextension.set = p_extension_funcs->set_func;
  385. extension->gdextension.get = p_extension_funcs->get_func;
  386. extension->gdextension.get_property_list = p_extension_funcs->get_property_list_func;
  387. extension->gdextension.free_property_list = p_extension_funcs->free_property_list_func;
  388. extension->gdextension.property_can_revert = p_extension_funcs->property_can_revert_func;
  389. extension->gdextension.property_get_revert = p_extension_funcs->property_get_revert_func;
  390. extension->gdextension.validate_property = p_extension_funcs->validate_property_func;
  391. #ifndef DISABLE_DEPRECATED
  392. if (p_deprecated_funcs) {
  393. extension->gdextension.notification = p_deprecated_funcs->notification_func;
  394. }
  395. #endif // DISABLE_DEPRECATED
  396. extension->gdextension.notification2 = p_extension_funcs->notification_func;
  397. extension->gdextension.to_string = p_extension_funcs->to_string_func;
  398. extension->gdextension.reference = p_extension_funcs->reference_func;
  399. extension->gdextension.unreference = p_extension_funcs->unreference_func;
  400. extension->gdextension.class_userdata = p_extension_funcs->class_userdata;
  401. extension->gdextension.create_instance = p_extension_funcs->create_instance_func;
  402. extension->gdextension.free_instance = p_extension_funcs->free_instance_func;
  403. extension->gdextension.recreate_instance = p_extension_funcs->recreate_instance_func;
  404. extension->gdextension.get_virtual = p_extension_funcs->get_virtual_func;
  405. extension->gdextension.get_virtual_call_data = p_extension_funcs->get_virtual_call_data_func;
  406. extension->gdextension.call_virtual_with_data = p_extension_funcs->call_virtual_with_data_func;
  407. extension->gdextension.get_rid = p_extension_funcs->get_rid_func;
  408. extension->gdextension.reloadable = self->reloadable;
  409. #ifdef TOOLS_ENABLED
  410. if (extension->gdextension.reloadable) {
  411. extension->gdextension.tracking_userdata = extension;
  412. extension->gdextension.track_instance = &GDExtension::_track_instance;
  413. extension->gdextension.untrack_instance = &GDExtension::_untrack_instance;
  414. } else {
  415. extension->gdextension.tracking_userdata = nullptr;
  416. extension->gdextension.track_instance = nullptr;
  417. extension->gdextension.untrack_instance = nullptr;
  418. }
  419. #endif
  420. ClassDB::register_extension_class(&extension->gdextension);
  421. }
  422. void GDExtension::_register_extension_class_method(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, const GDExtensionClassMethodInfo *p_method_info) {
  423. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  424. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  425. StringName method_name = *reinterpret_cast<const StringName *>(p_method_info->name);
  426. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension method '" + String(method_name) + "' for unexisting class '" + class_name + "'.");
  427. #ifdef TOOLS_ENABLED
  428. Extension *extension = &self->extension_classes[class_name];
  429. GDExtensionMethodBind *method = nullptr;
  430. // If the extension is still marked as reloading, that means it failed to register again.
  431. if (extension->is_reloading) {
  432. return;
  433. }
  434. if (self->is_reloading && extension->methods.has(method_name)) {
  435. method = extension->methods[method_name];
  436. // Try to update the method bind. If it doesn't work (because it's incompatible) then
  437. // mark as invalid and create a new one.
  438. if (!method->is_reloading || !method->try_update(p_method_info)) {
  439. method->valid = false;
  440. self->invalid_methods.push_back(method);
  441. method = nullptr;
  442. }
  443. }
  444. if (method == nullptr) {
  445. method = memnew(GDExtensionMethodBind(p_method_info));
  446. method->set_instance_class(class_name);
  447. extension->methods[method_name] = method;
  448. } else {
  449. method->is_reloading = false;
  450. }
  451. #else
  452. GDExtensionMethodBind *method = memnew(GDExtensionMethodBind(p_method_info));
  453. method->set_instance_class(class_name);
  454. #endif
  455. ClassDB::bind_method_custom(class_name, method);
  456. }
  457. void GDExtension::_register_extension_class_integer_constant(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringNamePtr p_enum_name, GDExtensionConstStringNamePtr p_constant_name, GDExtensionInt p_constant_value, GDExtensionBool p_is_bitfield) {
  458. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  459. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  460. StringName enum_name = *reinterpret_cast<const StringName *>(p_enum_name);
  461. StringName constant_name = *reinterpret_cast<const StringName *>(p_constant_name);
  462. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension constant '" + constant_name + "' for unexisting class '" + class_name + "'.");
  463. #ifdef TOOLS_ENABLED
  464. // If the extension is still marked as reloading, that means it failed to register again.
  465. Extension *extension = &self->extension_classes[class_name];
  466. if (extension->is_reloading) {
  467. return;
  468. }
  469. #endif
  470. ClassDB::bind_integer_constant(class_name, enum_name, constant_name, p_constant_value, p_is_bitfield);
  471. }
  472. void GDExtension::_register_extension_class_property(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, const GDExtensionPropertyInfo *p_info, GDExtensionConstStringNamePtr p_setter, GDExtensionConstStringNamePtr p_getter) {
  473. _register_extension_class_property_indexed(p_library, p_class_name, p_info, p_setter, p_getter, -1);
  474. }
  475. void GDExtension::_register_extension_class_property_indexed(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, const GDExtensionPropertyInfo *p_info, GDExtensionConstStringNamePtr p_setter, GDExtensionConstStringNamePtr p_getter, GDExtensionInt p_index) {
  476. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  477. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  478. StringName setter = *reinterpret_cast<const StringName *>(p_setter);
  479. StringName getter = *reinterpret_cast<const StringName *>(p_getter);
  480. String property_name = *reinterpret_cast<const StringName *>(p_info->name);
  481. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property '" + property_name + "' for unexisting class '" + class_name + "'.");
  482. #ifdef TOOLS_ENABLED
  483. // If the extension is still marked as reloading, that means it failed to register again.
  484. Extension *extension = &self->extension_classes[class_name];
  485. if (extension->is_reloading) {
  486. return;
  487. }
  488. #endif
  489. PropertyInfo pinfo(*p_info);
  490. ClassDB::add_property(class_name, pinfo, setter, getter, p_index);
  491. }
  492. void GDExtension::_register_extension_class_property_group(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringPtr p_group_name, GDExtensionConstStringPtr p_prefix) {
  493. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  494. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  495. String group_name = *reinterpret_cast<const String *>(p_group_name);
  496. String prefix = *reinterpret_cast<const String *>(p_prefix);
  497. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property group '" + group_name + "' for unexisting class '" + class_name + "'.");
  498. #ifdef TOOLS_ENABLED
  499. // If the extension is still marked as reloading, that means it failed to register again.
  500. Extension *extension = &self->extension_classes[class_name];
  501. if (extension->is_reloading) {
  502. return;
  503. }
  504. #endif
  505. ClassDB::add_property_group(class_name, group_name, prefix);
  506. }
  507. void GDExtension::_register_extension_class_property_subgroup(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringPtr p_subgroup_name, GDExtensionConstStringPtr p_prefix) {
  508. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  509. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  510. String subgroup_name = *reinterpret_cast<const String *>(p_subgroup_name);
  511. String prefix = *reinterpret_cast<const String *>(p_prefix);
  512. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class property subgroup '" + subgroup_name + "' for unexisting class '" + class_name + "'.");
  513. #ifdef TOOLS_ENABLED
  514. // If the extension is still marked as reloading, that means it failed to register again.
  515. Extension *extension = &self->extension_classes[class_name];
  516. if (extension->is_reloading) {
  517. return;
  518. }
  519. #endif
  520. ClassDB::add_property_subgroup(class_name, subgroup_name, prefix);
  521. }
  522. void GDExtension::_register_extension_class_signal(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name, GDExtensionConstStringNamePtr p_signal_name, const GDExtensionPropertyInfo *p_argument_info, GDExtensionInt p_argument_count) {
  523. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  524. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  525. StringName signal_name = *reinterpret_cast<const StringName *>(p_signal_name);
  526. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to register extension class signal '" + signal_name + "' for unexisting class '" + class_name + "'.");
  527. #ifdef TOOLS_ENABLED
  528. // If the extension is still marked as reloading, that means it failed to register again.
  529. Extension *extension = &self->extension_classes[class_name];
  530. if (extension->is_reloading) {
  531. return;
  532. }
  533. #endif
  534. MethodInfo s;
  535. s.name = signal_name;
  536. for (int i = 0; i < p_argument_count; i++) {
  537. PropertyInfo arg(p_argument_info[i]);
  538. s.arguments.push_back(arg);
  539. }
  540. ClassDB::add_signal(class_name, s);
  541. }
  542. void GDExtension::_unregister_extension_class(GDExtensionClassLibraryPtr p_library, GDExtensionConstStringNamePtr p_class_name) {
  543. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  544. StringName class_name = *reinterpret_cast<const StringName *>(p_class_name);
  545. ERR_FAIL_COND_MSG(!self->extension_classes.has(class_name), "Attempt to unregister unexisting extension class '" + class_name + "'.");
  546. Extension *ext = &self->extension_classes[class_name];
  547. #ifdef TOOLS_ENABLED
  548. if (ext->is_reloading) {
  549. self->_clear_extension(ext);
  550. }
  551. #endif
  552. ERR_FAIL_COND_MSG(ext->gdextension.children.size(), "Attempt to unregister class '" + class_name + "' while other extension classes inherit from it.");
  553. #ifdef TOOLS_ENABLED
  554. ClassDB::unregister_extension_class(class_name, !ext->is_reloading);
  555. #else
  556. ClassDB::unregister_extension_class(class_name);
  557. #endif
  558. if (ext->gdextension.parent != nullptr) {
  559. ext->gdextension.parent->children.erase(&ext->gdextension);
  560. }
  561. #ifdef TOOLS_ENABLED
  562. if (!ext->is_reloading) {
  563. self->extension_classes.erase(class_name);
  564. }
  565. #else
  566. self->extension_classes.erase(class_name);
  567. #endif
  568. }
  569. void GDExtension::_get_library_path(GDExtensionClassLibraryPtr p_library, GDExtensionUninitializedStringPtr r_path) {
  570. GDExtension *self = reinterpret_cast<GDExtension *>(p_library);
  571. memnew_placement(r_path, String(self->library_path));
  572. }
  573. HashMap<StringName, GDExtensionInterfaceFunctionPtr> GDExtension::gdextension_interface_functions;
  574. void GDExtension::register_interface_function(StringName p_function_name, GDExtensionInterfaceFunctionPtr p_function_pointer) {
  575. ERR_FAIL_COND_MSG(gdextension_interface_functions.has(p_function_name), "Attempt to register interface function '" + p_function_name + "', which appears to be already registered.");
  576. gdextension_interface_functions.insert(p_function_name, p_function_pointer);
  577. }
  578. GDExtensionInterfaceFunctionPtr GDExtension::get_interface_function(StringName p_function_name) {
  579. GDExtensionInterfaceFunctionPtr *function = gdextension_interface_functions.getptr(p_function_name);
  580. ERR_FAIL_NULL_V_MSG(function, nullptr, "Attempt to get non-existent interface function: " + String(p_function_name) + ".");
  581. return *function;
  582. }
  583. Error GDExtension::open_library(const String &p_path, const String &p_entry_symbol) {
  584. String abs_path = ProjectSettings::get_singleton()->globalize_path(p_path);
  585. #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
  586. // If running on the editor on Windows, we copy the library and open the copy.
  587. // This is so the original file isn't locked and can be updated by a compiler.
  588. bool library_copied = false;
  589. if (Engine::get_singleton()->is_editor_hint()) {
  590. if (!FileAccess::exists(abs_path)) {
  591. ERR_PRINT("GDExtension library not found: " + library_path);
  592. return ERR_FILE_NOT_FOUND;
  593. }
  594. // Copy the file to the same directory as the original with a prefix in the name.
  595. // This is so relative path to dependencies are satisfied.
  596. String copy_path = abs_path.get_base_dir().path_join("~" + abs_path.get_file());
  597. // If there's a left-over copy (possibly from a crash) then delete it first.
  598. if (FileAccess::exists(copy_path)) {
  599. DirAccess::remove_absolute(copy_path);
  600. }
  601. Error copy_err = DirAccess::copy_absolute(abs_path, copy_path);
  602. if (copy_err) {
  603. ERR_PRINT("Error copying GDExtension library: " + library_path);
  604. return ERR_CANT_CREATE;
  605. }
  606. FileAccess::set_hidden_attribute(copy_path, true);
  607. library_copied = true;
  608. // Save the copied path so it can be deleted later.
  609. temp_lib_path = copy_path;
  610. // Use the copy to open the library.
  611. abs_path = copy_path;
  612. }
  613. #endif
  614. Error err = OS::get_singleton()->open_dynamic_library(abs_path, library, true, &library_path);
  615. if (err != OK) {
  616. ERR_PRINT("GDExtension dynamic library not found: " + abs_path);
  617. return err;
  618. }
  619. #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
  620. // If we copied the file, let's change the library path to point at the original,
  621. // because that's what we want to check to see if it's changed.
  622. if (library_copied) {
  623. library_path = library_path.get_base_dir() + "\\" + p_path.get_file();
  624. }
  625. #endif
  626. void *entry_funcptr = nullptr;
  627. err = OS::get_singleton()->get_dynamic_library_symbol_handle(library, p_entry_symbol, entry_funcptr, false);
  628. if (err != OK) {
  629. ERR_PRINT("GDExtension entry point '" + p_entry_symbol + "' not found in library " + abs_path);
  630. OS::get_singleton()->close_dynamic_library(library);
  631. return err;
  632. }
  633. GDExtensionInitializationFunction initialization_function = (GDExtensionInitializationFunction)entry_funcptr;
  634. GDExtensionBool ret = initialization_function(&gdextension_get_proc_address, this, &initialization);
  635. if (ret) {
  636. level_initialized = -1;
  637. return OK;
  638. } else {
  639. ERR_PRINT("GDExtension initialization function '" + p_entry_symbol + "' returned an error.");
  640. OS::get_singleton()->close_dynamic_library(library);
  641. return FAILED;
  642. }
  643. }
  644. void GDExtension::close_library() {
  645. ERR_FAIL_NULL(library);
  646. OS::get_singleton()->close_dynamic_library(library);
  647. #if defined(TOOLS_ENABLED) && defined(WINDOWS_ENABLED)
  648. // Delete temporary copy of library if it exists.
  649. if (!temp_lib_path.is_empty() && Engine::get_singleton()->is_editor_hint()) {
  650. DirAccess::remove_absolute(temp_lib_path);
  651. }
  652. #endif
  653. library = nullptr;
  654. class_icon_paths.clear();
  655. #ifdef TOOLS_ENABLED
  656. instance_bindings.clear();
  657. #endif
  658. }
  659. bool GDExtension::is_library_open() const {
  660. return library != nullptr;
  661. }
  662. GDExtension::InitializationLevel GDExtension::get_minimum_library_initialization_level() const {
  663. ERR_FAIL_NULL_V(library, INITIALIZATION_LEVEL_CORE);
  664. return InitializationLevel(initialization.minimum_initialization_level);
  665. }
  666. void GDExtension::initialize_library(InitializationLevel p_level) {
  667. ERR_FAIL_NULL(library);
  668. ERR_FAIL_COND_MSG(p_level <= int32_t(level_initialized), vformat("Level '%d' must be higher than the current level '%d'", p_level, level_initialized));
  669. level_initialized = int32_t(p_level);
  670. ERR_FAIL_NULL(initialization.initialize);
  671. initialization.initialize(initialization.userdata, GDExtensionInitializationLevel(p_level));
  672. }
  673. void GDExtension::deinitialize_library(InitializationLevel p_level) {
  674. ERR_FAIL_NULL(library);
  675. ERR_FAIL_COND(p_level > int32_t(level_initialized));
  676. level_initialized = int32_t(p_level) - 1;
  677. initialization.deinitialize(initialization.userdata, GDExtensionInitializationLevel(p_level));
  678. }
  679. void GDExtension::_bind_methods() {
  680. ClassDB::bind_method(D_METHOD("open_library", "path", "entry_symbol"), &GDExtension::open_library);
  681. ClassDB::bind_method(D_METHOD("close_library"), &GDExtension::close_library);
  682. ClassDB::bind_method(D_METHOD("is_library_open"), &GDExtension::is_library_open);
  683. ClassDB::bind_method(D_METHOD("get_minimum_library_initialization_level"), &GDExtension::get_minimum_library_initialization_level);
  684. ClassDB::bind_method(D_METHOD("initialize_library", "level"), &GDExtension::initialize_library);
  685. BIND_ENUM_CONSTANT(INITIALIZATION_LEVEL_CORE);
  686. BIND_ENUM_CONSTANT(INITIALIZATION_LEVEL_SERVERS);
  687. BIND_ENUM_CONSTANT(INITIALIZATION_LEVEL_SCENE);
  688. BIND_ENUM_CONSTANT(INITIALIZATION_LEVEL_EDITOR);
  689. }
  690. GDExtension::GDExtension() {
  691. }
  692. GDExtension::~GDExtension() {
  693. if (library != nullptr) {
  694. close_library();
  695. }
  696. #ifdef TOOLS_ENABLED
  697. // If we have any invalid method binds still laying around, we can finally free them!
  698. for (GDExtensionMethodBind *E : invalid_methods) {
  699. memdelete(E);
  700. }
  701. #endif
  702. }
  703. void GDExtension::initialize_gdextensions() {
  704. gdextension_setup_interface();
  705. #ifndef DISABLE_DEPRECATED
  706. register_interface_function("classdb_register_extension_class", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class);
  707. #endif // DISABLE_DEPRECATED
  708. register_interface_function("classdb_register_extension_class2", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class2);
  709. register_interface_function("classdb_register_extension_class_method", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_method);
  710. register_interface_function("classdb_register_extension_class_integer_constant", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_integer_constant);
  711. register_interface_function("classdb_register_extension_class_property", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_property);
  712. register_interface_function("classdb_register_extension_class_property_indexed", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_property_indexed);
  713. register_interface_function("classdb_register_extension_class_property_group", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_property_group);
  714. register_interface_function("classdb_register_extension_class_property_subgroup", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_property_subgroup);
  715. register_interface_function("classdb_register_extension_class_signal", (GDExtensionInterfaceFunctionPtr)&GDExtension::_register_extension_class_signal);
  716. register_interface_function("classdb_unregister_extension_class", (GDExtensionInterfaceFunctionPtr)&GDExtension::_unregister_extension_class);
  717. register_interface_function("get_library_path", (GDExtensionInterfaceFunctionPtr)&GDExtension::_get_library_path);
  718. }
  719. void GDExtension::finalize_gdextensions() {
  720. gdextension_interface_functions.clear();
  721. }
  722. Error GDExtensionResourceLoader::load_gdextension_resource(const String &p_path, Ref<GDExtension> &p_extension) {
  723. ERR_FAIL_COND_V_MSG(p_extension.is_valid() && p_extension->is_library_open(), ERR_ALREADY_IN_USE, "Cannot load GDExtension resource into already opened library.");
  724. Ref<ConfigFile> config;
  725. config.instantiate();
  726. Error err = config->load(p_path);
  727. if (err != OK) {
  728. ERR_PRINT("Error loading GDExtension configuration file: " + p_path);
  729. return err;
  730. }
  731. if (!config->has_section_key("configuration", "entry_symbol")) {
  732. ERR_PRINT("GDExtension configuration file must contain a \"configuration/entry_symbol\" key: " + p_path);
  733. return ERR_INVALID_DATA;
  734. }
  735. String entry_symbol = config->get_value("configuration", "entry_symbol");
  736. uint32_t compatibility_minimum[3] = { 0, 0, 0 };
  737. if (config->has_section_key("configuration", "compatibility_minimum")) {
  738. String compat_string = config->get_value("configuration", "compatibility_minimum");
  739. Vector<int> parts = compat_string.split_ints(".");
  740. for (int i = 0; i < parts.size(); i++) {
  741. if (i >= 3) {
  742. break;
  743. }
  744. if (parts[i] >= 0) {
  745. compatibility_minimum[i] = parts[i];
  746. }
  747. }
  748. } else {
  749. ERR_PRINT("GDExtension configuration file must contain a \"configuration/compatibility_minimum\" key: " + p_path);
  750. return ERR_INVALID_DATA;
  751. }
  752. if (compatibility_minimum[0] < 4 || (compatibility_minimum[0] == 4 && compatibility_minimum[1] == 0)) {
  753. ERR_PRINT(vformat("GDExtension's compatibility_minimum (%d.%d.%d) must be at least 4.1.0: %s", compatibility_minimum[0], compatibility_minimum[1], compatibility_minimum[2], p_path));
  754. return ERR_INVALID_DATA;
  755. }
  756. bool compatible = true;
  757. // Check version lexicographically.
  758. if (VERSION_MAJOR != compatibility_minimum[0]) {
  759. compatible = VERSION_MAJOR > compatibility_minimum[0];
  760. } else if (VERSION_MINOR != compatibility_minimum[1]) {
  761. compatible = VERSION_MINOR > compatibility_minimum[1];
  762. } else {
  763. compatible = VERSION_PATCH >= compatibility_minimum[2];
  764. }
  765. if (!compatible) {
  766. ERR_PRINT(vformat("GDExtension only compatible with Godot version %d.%d.%d or later: %s", compatibility_minimum[0], compatibility_minimum[1], compatibility_minimum[2], p_path));
  767. return ERR_INVALID_DATA;
  768. }
  769. String library_path = GDExtension::find_extension_library(p_path, config, [](String p_feature) { return OS::get_singleton()->has_feature(p_feature); });
  770. if (library_path.is_empty()) {
  771. const String os_arch = OS::get_singleton()->get_name().to_lower() + "." + Engine::get_singleton()->get_architecture_name();
  772. ERR_PRINT(vformat("No GDExtension library found for current OS and architecture (%s) in configuration file: %s", os_arch, p_path));
  773. return ERR_FILE_NOT_FOUND;
  774. }
  775. bool is_static_library = library_path.ends_with(".a") || library_path.ends_with(".xcframework");
  776. if (!library_path.is_resource_file() && !library_path.is_absolute_path()) {
  777. library_path = p_path.get_base_dir().path_join(library_path);
  778. }
  779. if (p_extension.is_null()) {
  780. p_extension.instantiate();
  781. }
  782. #ifdef TOOLS_ENABLED
  783. p_extension->set_reloadable(config->get_value("configuration", "reloadable", false) && Engine::get_singleton()->is_extension_reloading_enabled());
  784. p_extension->update_last_modified_time(
  785. FileAccess::get_modified_time(p_path),
  786. FileAccess::get_modified_time(library_path));
  787. #endif
  788. err = p_extension->open_library(is_static_library ? String() : library_path, entry_symbol);
  789. if (err != OK) {
  790. #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
  791. // If the DLL fails to load, make sure that temporary DLL copies are cleaned up.
  792. if (Engine::get_singleton()->is_editor_hint()) {
  793. DirAccess::remove_absolute(p_extension->get_temp_library_path());
  794. }
  795. #endif
  796. // Unreference the extension so that this loading can be considered a failure.
  797. p_extension.unref();
  798. // Errors already logged in open_library()
  799. return err;
  800. }
  801. // Handle icons if any are specified.
  802. if (config->has_section("icons")) {
  803. List<String> keys;
  804. config->get_section_keys("icons", &keys);
  805. for (const String &key : keys) {
  806. String icon_path = config->get_value("icons", key);
  807. if (icon_path.is_relative_path()) {
  808. icon_path = p_path.get_base_dir().path_join(icon_path);
  809. }
  810. p_extension->class_icon_paths[key] = icon_path;
  811. }
  812. }
  813. return OK;
  814. }
  815. Ref<Resource> GDExtensionResourceLoader::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, CacheMode p_cache_mode) {
  816. // We can't have two GDExtension resource object representing the same library, because
  817. // loading (or unloading) a GDExtension affects global data. So, we need reuse the same
  818. // object if one has already been loaded (even if caching is disabled at the resource
  819. // loader level).
  820. GDExtensionManager *manager = GDExtensionManager::get_singleton();
  821. if (manager->is_extension_loaded(p_path)) {
  822. return manager->get_extension(p_path);
  823. }
  824. Ref<GDExtension> lib;
  825. Error err = load_gdextension_resource(p_path, lib);
  826. if (err != OK && r_error) {
  827. // Errors already logged in load_gdextension_resource().
  828. *r_error = err;
  829. }
  830. return lib;
  831. }
  832. void GDExtensionResourceLoader::get_recognized_extensions(List<String> *p_extensions) const {
  833. p_extensions->push_back("gdextension");
  834. }
  835. bool GDExtensionResourceLoader::handles_type(const String &p_type) const {
  836. return p_type == "GDExtension";
  837. }
  838. String GDExtensionResourceLoader::get_resource_type(const String &p_path) const {
  839. String el = p_path.get_extension().to_lower();
  840. if (el == "gdextension") {
  841. return "GDExtension";
  842. }
  843. return "";
  844. }
  845. #ifdef TOOLS_ENABLED
  846. bool GDExtension::has_library_changed() const {
  847. // Check only that the last modified time is different (rather than checking
  848. // that it's newer) since some OS's (namely Windows) will preserve the modified
  849. // time by default when copying files.
  850. if (FileAccess::get_modified_time(get_path()) != resource_last_modified_time) {
  851. return true;
  852. }
  853. if (FileAccess::get_modified_time(library_path) != library_last_modified_time) {
  854. return true;
  855. }
  856. return false;
  857. }
  858. void GDExtension::prepare_reload() {
  859. is_reloading = true;
  860. for (KeyValue<StringName, Extension> &E : extension_classes) {
  861. E.value.is_reloading = true;
  862. for (KeyValue<StringName, GDExtensionMethodBind *> &M : E.value.methods) {
  863. M.value->is_reloading = true;
  864. }
  865. for (const ObjectID &obj_id : E.value.instances) {
  866. Object *obj = ObjectDB::get_instance(obj_id);
  867. if (!obj) {
  868. continue;
  869. }
  870. // Store instance state so it can be restored after reload.
  871. List<Pair<String, Variant>> state;
  872. List<PropertyInfo> prop_list;
  873. obj->get_property_list(&prop_list);
  874. for (const PropertyInfo &P : prop_list) {
  875. if (!(P.usage & PROPERTY_USAGE_STORAGE)) {
  876. continue;
  877. }
  878. Variant value = obj->get(P.name);
  879. Variant default_value = ClassDB::class_get_default_property_value(obj->get_class_name(), P.name);
  880. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  881. continue;
  882. }
  883. if (P.type == Variant::OBJECT && value.is_zero() && !(P.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
  884. continue;
  885. }
  886. state.push_back(Pair<String, Variant>(P.name, value));
  887. }
  888. E.value.instance_state[obj_id] = state;
  889. }
  890. }
  891. }
  892. void GDExtension::_clear_extension(Extension *p_extension) {
  893. // Clear out hierarchy information because it may change.
  894. p_extension->gdextension.parent = nullptr;
  895. p_extension->gdextension.children.clear();
  896. // Clear all objects of any GDExtension data. It will become its native parent class
  897. // until the reload can reset the object with the new GDExtension data.
  898. for (const ObjectID &obj_id : p_extension->instances) {
  899. Object *obj = ObjectDB::get_instance(obj_id);
  900. if (!obj) {
  901. continue;
  902. }
  903. obj->clear_internal_extension();
  904. }
  905. }
  906. void GDExtension::track_instance_binding(Object *p_object) {
  907. instance_bindings.push_back(p_object->get_instance_id());
  908. }
  909. void GDExtension::untrack_instance_binding(Object *p_object) {
  910. instance_bindings.erase(p_object->get_instance_id());
  911. }
  912. void GDExtension::clear_instance_bindings() {
  913. for (ObjectID obj_id : instance_bindings) {
  914. Object *obj = ObjectDB::get_instance(obj_id);
  915. if (!obj) {
  916. continue;
  917. }
  918. obj->free_instance_binding(this);
  919. }
  920. instance_bindings.clear();
  921. }
  922. void GDExtension::finish_reload() {
  923. is_reloading = false;
  924. // Clean up any classes or methods that didn't get re-added.
  925. Vector<StringName> classes_to_remove;
  926. for (KeyValue<StringName, Extension> &E : extension_classes) {
  927. if (E.value.is_reloading) {
  928. E.value.is_reloading = false;
  929. classes_to_remove.push_back(E.key);
  930. }
  931. Vector<StringName> methods_to_remove;
  932. for (KeyValue<StringName, GDExtensionMethodBind *> &M : E.value.methods) {
  933. if (M.value->is_reloading) {
  934. M.value->valid = false;
  935. invalid_methods.push_back(M.value);
  936. M.value->is_reloading = false;
  937. methods_to_remove.push_back(M.key);
  938. }
  939. }
  940. for (const StringName &method_name : methods_to_remove) {
  941. E.value.methods.erase(method_name);
  942. }
  943. }
  944. for (const StringName &class_name : classes_to_remove) {
  945. extension_classes.erase(class_name);
  946. }
  947. // Reset any the extension on instances made from the classes that remain.
  948. for (KeyValue<StringName, Extension> &E : extension_classes) {
  949. // Loop over 'instance_state' rather than 'instance' because new instances
  950. // may have been created when re-initializing the extension.
  951. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  952. Object *obj = ObjectDB::get_instance(S.key);
  953. if (!obj) {
  954. continue;
  955. }
  956. obj->reset_internal_extension(&E.value.gdextension);
  957. }
  958. }
  959. // Now that all the classes are back, restore the state.
  960. for (KeyValue<StringName, Extension> &E : extension_classes) {
  961. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  962. Object *obj = ObjectDB::get_instance(S.key);
  963. if (!obj) {
  964. continue;
  965. }
  966. for (const Pair<String, Variant> &state : S.value) {
  967. obj->set(state.first, state.second);
  968. }
  969. }
  970. }
  971. // Finally, let the objects know that we are done reloading them.
  972. for (KeyValue<StringName, Extension> &E : extension_classes) {
  973. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  974. Object *obj = ObjectDB::get_instance(S.key);
  975. if (!obj) {
  976. continue;
  977. }
  978. obj->notification(NOTIFICATION_EXTENSION_RELOADED);
  979. }
  980. // Clear the instance state, we're done looping.
  981. E.value.instance_state.clear();
  982. }
  983. }
  984. void GDExtension::_track_instance(void *p_user_data, void *p_instance) {
  985. Extension *extension = reinterpret_cast<Extension *>(p_user_data);
  986. Object *obj = reinterpret_cast<Object *>(p_instance);
  987. extension->instances.insert(obj->get_instance_id());
  988. }
  989. void GDExtension::_untrack_instance(void *p_user_data, void *p_instance) {
  990. Extension *extension = reinterpret_cast<Extension *>(p_user_data);
  991. Object *obj = reinterpret_cast<Object *>(p_instance);
  992. extension->instances.erase(obj->get_instance_id());
  993. }
  994. Vector<StringName> GDExtensionEditorPlugins::extension_classes;
  995. GDExtensionEditorPlugins::EditorPluginRegisterFunc GDExtensionEditorPlugins::editor_node_add_plugin = nullptr;
  996. GDExtensionEditorPlugins::EditorPluginRegisterFunc GDExtensionEditorPlugins::editor_node_remove_plugin = nullptr;
  997. void GDExtensionEditorPlugins::add_extension_class(const StringName &p_class_name) {
  998. if (editor_node_add_plugin) {
  999. editor_node_add_plugin(p_class_name);
  1000. } else {
  1001. extension_classes.push_back(p_class_name);
  1002. }
  1003. }
  1004. void GDExtensionEditorPlugins::remove_extension_class(const StringName &p_class_name) {
  1005. if (editor_node_remove_plugin) {
  1006. editor_node_remove_plugin(p_class_name);
  1007. } else {
  1008. extension_classes.erase(p_class_name);
  1009. }
  1010. }
  1011. #endif // TOOLS_ENABLED