gdextension.cpp 56 KB

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