gdextension.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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. if (library_path.get_file().begins_with("godot-jolt_") && compatibility_minimum[0] == 4 && compatibility_minimum[1] == 1) {
  776. ERR_PRINT("Godot Jolt failed to load, as the currently installed version is incompatible with Godot 4.2. You can update it to a compatible version by deleting it and installing it again.");
  777. return ERR_INVALID_DATA;
  778. }
  779. bool is_static_library = library_path.ends_with(".a") || library_path.ends_with(".xcframework");
  780. if (!library_path.is_resource_file() && !library_path.is_absolute_path()) {
  781. library_path = p_path.get_base_dir().path_join(library_path);
  782. }
  783. if (p_extension.is_null()) {
  784. p_extension.instantiate();
  785. }
  786. #ifdef TOOLS_ENABLED
  787. p_extension->set_reloadable(config->get_value("configuration", "reloadable", false) && Engine::get_singleton()->is_extension_reloading_enabled());
  788. p_extension->update_last_modified_time(
  789. FileAccess::get_modified_time(p_path),
  790. FileAccess::get_modified_time(library_path));
  791. #endif
  792. err = p_extension->open_library(is_static_library ? String() : library_path, entry_symbol);
  793. if (err != OK) {
  794. #if defined(WINDOWS_ENABLED) && defined(TOOLS_ENABLED)
  795. // If the DLL fails to load, make sure that temporary DLL copies are cleaned up.
  796. if (Engine::get_singleton()->is_editor_hint()) {
  797. DirAccess::remove_absolute(p_extension->get_temp_library_path());
  798. }
  799. #endif
  800. // Unreference the extension so that this loading can be considered a failure.
  801. p_extension.unref();
  802. // Errors already logged in open_library()
  803. return err;
  804. }
  805. // Handle icons if any are specified.
  806. if (config->has_section("icons")) {
  807. List<String> keys;
  808. config->get_section_keys("icons", &keys);
  809. for (const String &key : keys) {
  810. String icon_path = config->get_value("icons", key);
  811. if (icon_path.is_relative_path()) {
  812. icon_path = p_path.get_base_dir().path_join(icon_path);
  813. }
  814. p_extension->class_icon_paths[key] = icon_path;
  815. }
  816. }
  817. return OK;
  818. }
  819. 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) {
  820. // We can't have two GDExtension resource object representing the same library, because
  821. // loading (or unloading) a GDExtension affects global data. So, we need reuse the same
  822. // object if one has already been loaded (even if caching is disabled at the resource
  823. // loader level).
  824. GDExtensionManager *manager = GDExtensionManager::get_singleton();
  825. if (manager->is_extension_loaded(p_path)) {
  826. return manager->get_extension(p_path);
  827. }
  828. Ref<GDExtension> lib;
  829. Error err = load_gdextension_resource(p_path, lib);
  830. if (err != OK && r_error) {
  831. // Errors already logged in load_gdextension_resource().
  832. *r_error = err;
  833. }
  834. return lib;
  835. }
  836. void GDExtensionResourceLoader::get_recognized_extensions(List<String> *p_extensions) const {
  837. p_extensions->push_back("gdextension");
  838. }
  839. bool GDExtensionResourceLoader::handles_type(const String &p_type) const {
  840. return p_type == "GDExtension";
  841. }
  842. String GDExtensionResourceLoader::get_resource_type(const String &p_path) const {
  843. String el = p_path.get_extension().to_lower();
  844. if (el == "gdextension") {
  845. return "GDExtension";
  846. }
  847. return "";
  848. }
  849. #ifdef TOOLS_ENABLED
  850. bool GDExtension::has_library_changed() const {
  851. // Check only that the last modified time is different (rather than checking
  852. // that it's newer) since some OS's (namely Windows) will preserve the modified
  853. // time by default when copying files.
  854. if (FileAccess::get_modified_time(get_path()) != resource_last_modified_time) {
  855. return true;
  856. }
  857. if (FileAccess::get_modified_time(library_path) != library_last_modified_time) {
  858. return true;
  859. }
  860. return false;
  861. }
  862. void GDExtension::prepare_reload() {
  863. is_reloading = true;
  864. for (KeyValue<StringName, Extension> &E : extension_classes) {
  865. E.value.is_reloading = true;
  866. for (KeyValue<StringName, GDExtensionMethodBind *> &M : E.value.methods) {
  867. M.value->is_reloading = true;
  868. }
  869. for (const ObjectID &obj_id : E.value.instances) {
  870. Object *obj = ObjectDB::get_instance(obj_id);
  871. if (!obj) {
  872. continue;
  873. }
  874. // Store instance state so it can be restored after reload.
  875. List<Pair<String, Variant>> state;
  876. List<PropertyInfo> prop_list;
  877. obj->get_property_list(&prop_list);
  878. for (const PropertyInfo &P : prop_list) {
  879. if (!(P.usage & PROPERTY_USAGE_STORAGE)) {
  880. continue;
  881. }
  882. Variant value = obj->get(P.name);
  883. Variant default_value = ClassDB::class_get_default_property_value(obj->get_class_name(), P.name);
  884. if (default_value.get_type() != Variant::NIL && bool(Variant::evaluate(Variant::OP_EQUAL, value, default_value))) {
  885. continue;
  886. }
  887. if (P.type == Variant::OBJECT && value.is_zero() && !(P.usage & PROPERTY_USAGE_STORE_IF_NULL)) {
  888. continue;
  889. }
  890. state.push_back(Pair<String, Variant>(P.name, value));
  891. }
  892. E.value.instance_state[obj_id] = state;
  893. }
  894. }
  895. }
  896. void GDExtension::_clear_extension(Extension *p_extension) {
  897. // Clear out hierarchy information because it may change.
  898. p_extension->gdextension.parent = nullptr;
  899. p_extension->gdextension.children.clear();
  900. // Clear all objects of any GDExtension data. It will become its native parent class
  901. // until the reload can reset the object with the new GDExtension data.
  902. for (const ObjectID &obj_id : p_extension->instances) {
  903. Object *obj = ObjectDB::get_instance(obj_id);
  904. if (!obj) {
  905. continue;
  906. }
  907. obj->clear_internal_extension();
  908. }
  909. }
  910. void GDExtension::track_instance_binding(Object *p_object) {
  911. instance_bindings.push_back(p_object->get_instance_id());
  912. }
  913. void GDExtension::untrack_instance_binding(Object *p_object) {
  914. instance_bindings.erase(p_object->get_instance_id());
  915. }
  916. void GDExtension::clear_instance_bindings() {
  917. for (ObjectID obj_id : instance_bindings) {
  918. Object *obj = ObjectDB::get_instance(obj_id);
  919. if (!obj) {
  920. continue;
  921. }
  922. obj->free_instance_binding(this);
  923. }
  924. instance_bindings.clear();
  925. }
  926. void GDExtension::finish_reload() {
  927. is_reloading = false;
  928. // Clean up any classes or methods that didn't get re-added.
  929. Vector<StringName> classes_to_remove;
  930. for (KeyValue<StringName, Extension> &E : extension_classes) {
  931. if (E.value.is_reloading) {
  932. E.value.is_reloading = false;
  933. classes_to_remove.push_back(E.key);
  934. }
  935. Vector<StringName> methods_to_remove;
  936. for (KeyValue<StringName, GDExtensionMethodBind *> &M : E.value.methods) {
  937. if (M.value->is_reloading) {
  938. M.value->valid = false;
  939. invalid_methods.push_back(M.value);
  940. M.value->is_reloading = false;
  941. methods_to_remove.push_back(M.key);
  942. }
  943. }
  944. for (const StringName &method_name : methods_to_remove) {
  945. E.value.methods.erase(method_name);
  946. }
  947. }
  948. for (const StringName &class_name : classes_to_remove) {
  949. extension_classes.erase(class_name);
  950. }
  951. // Reset any the extension on instances made from the classes that remain.
  952. for (KeyValue<StringName, Extension> &E : extension_classes) {
  953. // Loop over 'instance_state' rather than 'instance' because new instances
  954. // may have been created when re-initializing the extension.
  955. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  956. Object *obj = ObjectDB::get_instance(S.key);
  957. if (!obj) {
  958. continue;
  959. }
  960. obj->reset_internal_extension(&E.value.gdextension);
  961. }
  962. }
  963. // Now that all the classes are back, restore the state.
  964. for (KeyValue<StringName, Extension> &E : extension_classes) {
  965. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  966. Object *obj = ObjectDB::get_instance(S.key);
  967. if (!obj) {
  968. continue;
  969. }
  970. for (const Pair<String, Variant> &state : S.value) {
  971. obj->set(state.first, state.second);
  972. }
  973. }
  974. }
  975. // Finally, let the objects know that we are done reloading them.
  976. for (KeyValue<StringName, Extension> &E : extension_classes) {
  977. for (const KeyValue<ObjectID, List<Pair<String, Variant>>> &S : E.value.instance_state) {
  978. Object *obj = ObjectDB::get_instance(S.key);
  979. if (!obj) {
  980. continue;
  981. }
  982. obj->notification(NOTIFICATION_EXTENSION_RELOADED);
  983. }
  984. // Clear the instance state, we're done looping.
  985. E.value.instance_state.clear();
  986. }
  987. }
  988. void GDExtension::_track_instance(void *p_user_data, void *p_instance) {
  989. Extension *extension = reinterpret_cast<Extension *>(p_user_data);
  990. Object *obj = reinterpret_cast<Object *>(p_instance);
  991. extension->instances.insert(obj->get_instance_id());
  992. }
  993. void GDExtension::_untrack_instance(void *p_user_data, void *p_instance) {
  994. Extension *extension = reinterpret_cast<Extension *>(p_user_data);
  995. Object *obj = reinterpret_cast<Object *>(p_instance);
  996. extension->instances.erase(obj->get_instance_id());
  997. }
  998. Vector<StringName> GDExtensionEditorPlugins::extension_classes;
  999. GDExtensionEditorPlugins::EditorPluginRegisterFunc GDExtensionEditorPlugins::editor_node_add_plugin = nullptr;
  1000. GDExtensionEditorPlugins::EditorPluginRegisterFunc GDExtensionEditorPlugins::editor_node_remove_plugin = nullptr;
  1001. void GDExtensionEditorPlugins::add_extension_class(const StringName &p_class_name) {
  1002. if (editor_node_add_plugin) {
  1003. editor_node_add_plugin(p_class_name);
  1004. } else {
  1005. extension_classes.push_back(p_class_name);
  1006. }
  1007. }
  1008. void GDExtensionEditorPlugins::remove_extension_class(const StringName &p_class_name) {
  1009. if (editor_node_remove_plugin) {
  1010. editor_node_remove_plugin(p_class_name);
  1011. } else {
  1012. extension_classes.erase(p_class_name);
  1013. }
  1014. }
  1015. #endif // TOOLS_ENABLED