class_db.hpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /**************************************************************************/
  2. /* class_db.hpp */
  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. #ifndef GODOT_CLASS_DB_HPP
  31. #define GODOT_CLASS_DB_HPP
  32. #include <gdextension_interface.h>
  33. #include <godot_cpp/core/defs.hpp>
  34. #include <godot_cpp/core/error_macros.hpp>
  35. #include <godot_cpp/core/method_bind.hpp>
  36. #include <godot_cpp/core/object.hpp>
  37. #include <godot_cpp/classes/class_db_singleton.hpp>
  38. // Makes callable_mp readily available in all classes connecting signals.
  39. // Needs to come after method_bind and object have been included.
  40. #include <godot_cpp/variant/callable_method_pointer.hpp>
  41. #include <list>
  42. #include <mutex>
  43. #include <set>
  44. #include <string>
  45. #include <unordered_map>
  46. #include <vector>
  47. // Needed to use StringName as key in `std::unordered_map`
  48. template <>
  49. struct std::hash<godot::StringName> {
  50. std::size_t operator()(godot::StringName const &s) const noexcept {
  51. return s.hash();
  52. }
  53. };
  54. namespace godot {
  55. #define DEFVAL(m_defval) (m_defval)
  56. struct MethodDefinition {
  57. StringName name;
  58. std::list<StringName> args;
  59. MethodDefinition() {}
  60. MethodDefinition(StringName p_name) :
  61. name(p_name) {}
  62. };
  63. MethodDefinition D_METHOD(StringName p_name);
  64. MethodDefinition D_METHOD(StringName p_name, StringName p_arg1);
  65. template <typename... Args>
  66. MethodDefinition D_METHOD(StringName p_name, StringName p_arg1, Args... args) {
  67. MethodDefinition md = D_METHOD(p_name, args...);
  68. md.args.push_front(p_arg1);
  69. return md;
  70. }
  71. class ClassDB {
  72. static GDExtensionInitializationLevel current_level;
  73. friend class godot::GDExtensionBinding;
  74. public:
  75. struct ClassInfo {
  76. StringName name;
  77. StringName parent_name;
  78. GDExtensionInitializationLevel level = GDEXTENSION_INITIALIZATION_SCENE;
  79. std::unordered_map<StringName, MethodBind *> method_map;
  80. std::set<StringName> signal_names;
  81. std::unordered_map<StringName, GDExtensionClassCallVirtual> virtual_methods;
  82. std::set<StringName> property_names;
  83. std::set<StringName> constant_names;
  84. // Pointer to the parent custom class, if any. Will be null if the parent class is a Godot class.
  85. ClassInfo *parent_ptr = nullptr;
  86. };
  87. private:
  88. // This may only contain custom classes, not Godot classes
  89. static std::unordered_map<StringName, ClassInfo> classes;
  90. static std::unordered_map<StringName, const GDExtensionInstanceBindingCallbacks *> instance_binding_callbacks;
  91. // Used to remember the custom class registration order.
  92. static std::vector<StringName> class_register_order;
  93. static std::unordered_map<StringName, Object *> engine_singletons;
  94. static std::mutex engine_singletons_mutex;
  95. static MethodBind *bind_methodfi(uint32_t p_flags, MethodBind *p_bind, const MethodDefinition &method_name, const void **p_defs, int p_defcount);
  96. static void initialize_class(const ClassInfo &cl);
  97. static void bind_method_godot(const StringName &p_class_name, MethodBind *p_method);
  98. template <typename T, bool is_abstract>
  99. static void _register_class(bool p_virtual = false, bool p_exposed = true, bool p_runtime = false);
  100. template <typename T>
  101. static GDExtensionObjectPtr _create_instance_func(void *data, GDExtensionBool p_notify_postinitialize) {
  102. if constexpr (!std::is_abstract_v<T>) {
  103. Wrapped::_set_construct_info<T>();
  104. T *new_object = new ("", "") T;
  105. if (p_notify_postinitialize) {
  106. new_object->_postinitialize();
  107. }
  108. return new_object->_owner;
  109. } else {
  110. return nullptr;
  111. }
  112. }
  113. template <typename T>
  114. static GDExtensionClassInstancePtr _recreate_instance_func(void *data, GDExtensionObjectPtr obj) {
  115. if constexpr (!std::is_abstract_v<T>) {
  116. #ifdef HOT_RELOAD_ENABLED
  117. #ifdef _GODOT_CPP_AVOID_THREAD_LOCAL
  118. std::lock_guard<std::recursive_mutex> lk(Wrapped::_constructing_mutex);
  119. #endif
  120. Wrapped::_constructing_recreate_owner = obj;
  121. T *new_instance = (T *)memalloc(sizeof(T));
  122. memnew_placement(new_instance, T);
  123. return new_instance;
  124. #else
  125. return nullptr;
  126. #endif
  127. } else {
  128. return nullptr;
  129. }
  130. }
  131. public:
  132. template <typename T>
  133. static void register_class(bool p_virtual = false);
  134. template <typename T>
  135. static void register_abstract_class();
  136. template <typename T>
  137. static void register_internal_class();
  138. template <typename T>
  139. static void register_runtime_class();
  140. _FORCE_INLINE_ static void _register_engine_class(const StringName &p_name, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
  141. instance_binding_callbacks[p_name] = p_callbacks;
  142. }
  143. static void _register_engine_singleton(const StringName &p_class_name, Object *p_singleton) {
  144. std::lock_guard<std::mutex> lock(engine_singletons_mutex);
  145. std::unordered_map<StringName, Object *>::const_iterator i = engine_singletons.find(p_class_name);
  146. if (i != engine_singletons.end()) {
  147. ERR_FAIL_COND((*i).second != p_singleton);
  148. return;
  149. }
  150. engine_singletons[p_class_name] = p_singleton;
  151. }
  152. static void _unregister_engine_singleton(const StringName &p_class_name) {
  153. std::lock_guard<std::mutex> lock(engine_singletons_mutex);
  154. engine_singletons.erase(p_class_name);
  155. }
  156. template <typename N, typename M, typename... VarArgs>
  157. static MethodBind *bind_method(N p_method_name, M p_method, VarArgs... p_args);
  158. template <typename N, typename M, typename... VarArgs>
  159. static MethodBind *bind_static_method(StringName p_class, N p_method_name, M p_method, VarArgs... p_args);
  160. template <typename M>
  161. static MethodBind *bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method, const MethodInfo &p_info = MethodInfo(), const std::vector<Variant> &p_default_args = std::vector<Variant>{}, bool p_return_nil_is_variant = true);
  162. static void add_property_group(const StringName &p_class, const String &p_name, const String &p_prefix);
  163. static void add_property_subgroup(const StringName &p_class, const String &p_name, const String &p_prefix);
  164. static void add_property(const StringName &p_class, const PropertyInfo &p_pinfo, const StringName &p_setter, const StringName &p_getter, int p_index = -1);
  165. static void add_signal(const StringName &p_class, const MethodInfo &p_signal);
  166. static void bind_integer_constant(const StringName &p_class_name, const StringName &p_enum_name, const StringName &p_constant_name, GDExtensionInt p_constant_value, bool p_is_bitfield = false);
  167. // Binds an implementation of a virtual method defined in Godot.
  168. static void bind_virtual_method(const StringName &p_class, const StringName &p_method, GDExtensionClassCallVirtual p_call);
  169. // Add a new virtual method that can be implemented by scripts.
  170. static void add_virtual_method(const StringName &p_class, const MethodInfo &p_method, const Vector<StringName> &p_arg_names = Vector<StringName>());
  171. static MethodBind *get_method(const StringName &p_class, const StringName &p_method);
  172. static GDExtensionClassCallVirtual get_virtual_func(void *p_userdata, GDExtensionConstStringNamePtr p_name);
  173. static const GDExtensionInstanceBindingCallbacks *get_instance_binding_callbacks(const StringName &p_class);
  174. static void initialize(GDExtensionInitializationLevel p_level);
  175. static void deinitialize(GDExtensionInitializationLevel p_level);
  176. CLASSDB_SINGLETON_FORWARD_METHODS;
  177. };
  178. #define BIND_CONSTANT(m_constant) \
  179. ::godot::ClassDB::bind_integer_constant(get_class_static(), "", #m_constant, m_constant);
  180. #define BIND_ENUM_CONSTANT(m_constant) \
  181. ::godot::ClassDB::bind_integer_constant(get_class_static(), ::godot::_gde_constant_get_enum_name(m_constant, #m_constant), #m_constant, m_constant);
  182. #define BIND_BITFIELD_FLAG(m_constant) \
  183. ::godot::ClassDB::bind_integer_constant(get_class_static(), ::godot::_gde_constant_get_bitfield_name(m_constant, #m_constant), #m_constant, m_constant, true);
  184. #define BIND_VIRTUAL_METHOD(m_class, m_method) \
  185. { \
  186. auto _call##m_method = [](GDExtensionObjectPtr p_instance, const GDExtensionConstTypePtr *p_args, GDExtensionTypePtr p_ret) -> void { \
  187. call_with_ptr_args(reinterpret_cast<m_class *>(p_instance), &m_class::m_method, p_args, p_ret); \
  188. }; \
  189. ::godot::ClassDB::bind_virtual_method(m_class::get_class_static(), #m_method, _call##m_method); \
  190. }
  191. template <typename T, bool is_abstract>
  192. void ClassDB::_register_class(bool p_virtual, bool p_exposed, bool p_runtime) {
  193. static_assert(TypesAreSame<typename T::self_type, T>::value, "Class not declared properly, please use GDCLASS.");
  194. static_assert(!FunctionsAreSame<T::self_type::_bind_methods, T::parent_type::_bind_methods>::value, "Class must declare 'static void _bind_methods'.");
  195. static_assert(!std::is_abstract_v<T> || is_abstract, "Class is abstract, please use GDREGISTER_ABSTRACT_CLASS.");
  196. instance_binding_callbacks[T::get_class_static()] = &T::_gde_binding_callbacks;
  197. // Register this class within our plugin
  198. ClassInfo cl;
  199. cl.name = T::get_class_static();
  200. cl.parent_name = T::get_parent_class_static();
  201. cl.level = current_level;
  202. std::unordered_map<StringName, ClassInfo>::iterator parent_it = classes.find(cl.parent_name);
  203. if (parent_it != classes.end()) {
  204. // Assign parent if it is also a custom class
  205. cl.parent_ptr = &parent_it->second;
  206. }
  207. classes[cl.name] = cl;
  208. class_register_order.push_back(cl.name);
  209. // Register this class with Godot
  210. GDExtensionClassCreationInfo4 class_info = {
  211. p_virtual, // GDExtensionBool is_virtual;
  212. is_abstract, // GDExtensionBool is_abstract;
  213. p_exposed, // GDExtensionBool is_exposed;
  214. p_runtime, // GDExtensionBool is_runtime;
  215. T::set_bind, // GDExtensionClassSet set_func;
  216. T::get_bind, // GDExtensionClassGet get_func;
  217. T::has_get_property_list() ? T::get_property_list_bind : nullptr, // GDExtensionClassGetPropertyList get_property_list_func;
  218. T::free_property_list_bind, // GDExtensionClassFreePropertyList2 free_property_list_func;
  219. T::property_can_revert_bind, // GDExtensionClassPropertyCanRevert property_can_revert_func;
  220. T::property_get_revert_bind, // GDExtensionClassPropertyGetRevert property_get_revert_func;
  221. T::validate_property_bind, // GDExtensionClassValidateProperty validate_property_func;
  222. T::notification_bind, // GDExtensionClassNotification2 notification_func;
  223. T::to_string_bind, // GDExtensionClassToString to_string_func;
  224. nullptr, // GDExtensionClassReference reference_func;
  225. nullptr, // GDExtensionClassUnreference unreference_func;
  226. &_create_instance_func<T>, // GDExtensionClassCreateInstance create_instance_func; /* this one is mandatory */
  227. T::free, // GDExtensionClassFreeInstance free_instance_func; /* this one is mandatory */
  228. &_recreate_instance_func<T>, // GDExtensionClassRecreateInstance recreate_instance_func;
  229. &ClassDB::get_virtual_func, // GDExtensionClassGetVirtual get_virtual_func;
  230. nullptr, // GDExtensionClassGetVirtualCallData get_virtual_call_data_func;
  231. nullptr, // GDExtensionClassCallVirtualWithData call_virtual_func;
  232. (void *)&T::get_class_static(), // void *class_userdata;
  233. };
  234. internal::gdextension_interface_classdb_register_extension_class4(internal::library, cl.name._native_ptr(), cl.parent_name._native_ptr(), &class_info);
  235. // call bind_methods etc. to register all members of the class
  236. T::initialize_class();
  237. // now register our class within ClassDB within Godot
  238. initialize_class(classes[cl.name]);
  239. }
  240. template <typename T>
  241. void ClassDB::register_class(bool p_virtual) {
  242. ClassDB::_register_class<T, false>(p_virtual);
  243. }
  244. template <typename T>
  245. void ClassDB::register_abstract_class() {
  246. ClassDB::_register_class<T, true>();
  247. }
  248. template <typename T>
  249. void ClassDB::register_internal_class() {
  250. ClassDB::_register_class<T, false>(false, false);
  251. }
  252. template <typename T>
  253. void ClassDB::register_runtime_class() {
  254. ClassDB::_register_class<T, false>(false, true, true);
  255. }
  256. template <typename N, typename M, typename... VarArgs>
  257. MethodBind *ClassDB::bind_method(N p_method_name, M p_method, VarArgs... p_args) {
  258. Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
  259. const Variant *argptrs[sizeof...(p_args) + 1];
  260. for (uint32_t i = 0; i < sizeof...(p_args); i++) {
  261. argptrs[i] = &args[i];
  262. }
  263. MethodBind *bind = create_method_bind(p_method);
  264. return bind_methodfi(METHOD_FLAGS_DEFAULT, bind, p_method_name, sizeof...(p_args) == 0 ? nullptr : (const void **)argptrs, sizeof...(p_args));
  265. }
  266. template <typename N, typename M, typename... VarArgs>
  267. MethodBind *ClassDB::bind_static_method(StringName p_class, N p_method_name, M p_method, VarArgs... p_args) {
  268. Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
  269. const Variant *argptrs[sizeof...(p_args) + 1];
  270. for (uint32_t i = 0; i < sizeof...(p_args); i++) {
  271. argptrs[i] = &args[i];
  272. }
  273. MethodBind *bind = create_static_method_bind(p_method);
  274. bind->set_instance_class(p_class);
  275. return bind_methodfi(0, bind, p_method_name, sizeof...(p_args) == 0 ? nullptr : (const void **)argptrs, sizeof...(p_args));
  276. }
  277. template <typename M>
  278. MethodBind *ClassDB::bind_vararg_method(uint32_t p_flags, StringName p_name, M p_method, const MethodInfo &p_info, const std::vector<Variant> &p_default_args, bool p_return_nil_is_variant) {
  279. MethodBind *bind = create_vararg_method_bind(p_method, p_info, p_return_nil_is_variant);
  280. ERR_FAIL_NULL_V(bind, nullptr);
  281. bind->set_name(p_name);
  282. bind->set_default_arguments(p_default_args);
  283. StringName instance_type = bind->get_instance_class();
  284. std::unordered_map<StringName, ClassInfo>::iterator type_it = classes.find(instance_type);
  285. if (type_it == classes.end()) {
  286. memdelete(bind);
  287. ERR_FAIL_V_MSG(nullptr, String("Class '{0}' doesn't exist.").format(Array::make(instance_type)));
  288. }
  289. ClassInfo &type = type_it->second;
  290. if (type.method_map.find(p_name) != type.method_map.end()) {
  291. memdelete(bind);
  292. ERR_FAIL_V_MSG(nullptr, String("Binding duplicate method: {0}::{1}.").format(Array::make(instance_type, p_method)));
  293. }
  294. // register our method bind within our plugin
  295. type.method_map[p_name] = bind;
  296. // and register with godot
  297. bind_method_godot(type.name, bind);
  298. return bind;
  299. }
  300. #define GDREGISTER_CLASS(m_class) ::godot::ClassDB::register_class<m_class>();
  301. #define GDREGISTER_VIRTUAL_CLASS(m_class) ::godot::ClassDB::register_class<m_class>(true);
  302. #define GDREGISTER_ABSTRACT_CLASS(m_class) ::godot::ClassDB::register_abstract_class<m_class>();
  303. #define GDREGISTER_INTERNAL_CLASS(m_class) ::godot::ClassDB::register_internal_class<m_class>();
  304. #define GDREGISTER_RUNTIME_CLASS(m_class) ::godot::ClassDB::register_runtime_class<m_class>();
  305. } // namespace godot
  306. CLASSDB_SINGLETON_VARIANT_CAST;
  307. #endif // GODOT_CLASS_DB_HPP