Debian Codegraph @

core/object/object.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* object.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
31 #include "object.h"
32
33 #include "core/extension/gdextension_manager.h"
34 #include "core/io/resource.h"
35 #include "core/object/class_db.h"
36 #include "core/object/message_queue.h"
37 #include "core/object/script_language.h"
38 #include "core/os/os.h"
39 #include "core/string/print_string.h"
40 #include "core/string/translation_server.h"
41 #include "core/variant/typed_array.h"
42
43 #ifdef DEBUG_ENABLED
44
45 struct _ObjectDebugLock {
46 ObjectID obj_id;
47
48 _ObjectDebugLock(Object *p_obj) {
49 obj_id = p_obj->get_instance_id();
50 p_obj->_lock_index.ref();
51 }
52 ~_ObjectDebugLock() {
53 Object *obj_ptr = ObjectDB::get_instance(obj_id);
54 if (likely(obj_ptr)) {
55 obj_ptr->_lock_index.unref();
56 }
57 }
58 };
59
60 #define OBJ_DEBUG_LOCK _ObjectDebugLock _debug_lock(this);
61
62 #else
63
64 #define OBJ_DEBUG_LOCK
65
66 #endif
67
68 struct ObjectSignalLock {
69 Mutex *mutex1 = nullptr;
70 Mutex *mutex2 = nullptr;
71
72 ObjectSignalLock(const Object *p_obj1, const Object *p_obj2 = nullptr) {
73 mutex1 = p_obj1->signal_mutex;
74
75 if (p_obj2 != nullptr) {
76 mutex2 = p_obj2->signal_mutex;
77
78 if (mutex2 < mutex1) {
79 // We must always lock two locks in the same order.
80 SWAP(mutex1, mutex2);
81 } else if (unlikely(mutex2 == mutex1)) {
82 // No point locking the same lock twice.
83 mutex2 = nullptr;
84 }
85 }
86
87 if (mutex1) {
88 mutex1->lock();
89 }
90
91 if (mutex2) {
92 mutex2->lock();
93 }
94 }
95
96 ~ObjectSignalLock() {
97 if (mutex2) {
98 mutex2->unlock();
99 }
100
101 if (mutex1) {
102 mutex1->unlock();
103 }
104 }
105 };
106
107 PropertyInfo::operator Dictionary() const {
108 Dictionary d;
109 d["name"] = name;
110 d["class_name"] = class_name;
111 d["type"] = type;
112 d["hint"] = hint;
113 d["hint_string"] = hint_string;
114 d["usage"] = usage;
115 return d;
116 }
117
118 PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) {
119 PropertyInfo pi;
120
121 if (p_dict.has("type")) {
122 pi.type = Variant::Type(int(p_dict["type"]));
123 }
124
125 if (p_dict.has("name")) {
126 pi.name = p_dict["name"];
127 }
128
129 if (p_dict.has("class_name")) {
130 pi.class_name = p_dict["class_name"];
131 }
132
133 if (p_dict.has("hint")) {
134 pi.hint = PropertyHint(int(p_dict["hint"]));
135 }
136
137 if (p_dict.has("hint_string")) {
138 pi.hint_string = p_dict["hint_string"];
139 }
140
141 if (p_dict.has("usage")) {
142 pi.usage = p_dict["usage"];
143 }
144
145 return pi;
146 }
147
148 TypedArray<Dictionary> convert_property_list(const List<PropertyInfo> *p_list) {
149 TypedArray<Dictionary> va;
150 for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) {
151 va.push_back(Dictionary(E->get()));
152 }
153
154 return va;
155 }
156
157 TypedArray<Dictionary> convert_property_list(const Vector<PropertyInfo> &p_vector) {
158 TypedArray<Dictionary> va;
159 for (const PropertyInfo &E : p_vector) {
160 va.push_back(Dictionary(E));
161 }
162
163 return va;
164 }
165
166 MethodInfo::operator Dictionary() const {
167 Dictionary d;
168 d["name"] = name;
169 d["args"] = convert_property_list(arguments);
170 Array da;
171 for (int i = 0; i < default_arguments.size(); i++) {
172 da.push_back(default_arguments[i]);
173 }
174 d["default_args"] = da;
175 d["flags"] = flags;
176 d["id"] = id;
177 Dictionary r = return_val;
178 d["return"] = r;
179 return d;
180 }
181
182 MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) {
183 MethodInfo mi;
184
185 if (p_dict.has("name")) {
186 mi.name = p_dict["name"];
187 }
188 Array args;
189 if (p_dict.has("args")) {
190 args = p_dict["args"];
191 }
192
193 for (const Variant &arg : args) {
194 Dictionary d = arg;
195 mi.arguments.push_back(PropertyInfo::from_dict(d));
196 }
197 Array defargs;
198 if (p_dict.has("default_args")) {
199 defargs = p_dict["default_args"];
200 }
201 for (const Variant &defarg : defargs) {
202 mi.default_arguments.push_back(defarg);
203 }
204
205 if (p_dict.has("return")) {
206 mi.return_val = PropertyInfo::from_dict(p_dict["return"]);
207 }
208
209 if (p_dict.has("flags")) {
210 mi.flags = p_dict["flags"];
211 }
212
213 return mi;
214 }
215
216 uint32_t MethodInfo::get_compatibility_hash() const {
217 bool has_return = (return_val.type != Variant::NIL) || (return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT);
218
219 uint32_t hash = hash_murmur3_one_32(has_return);
220 hash = hash_murmur3_one_32(arguments.size(), hash);
221
222 if (has_return) {
223 hash = hash_murmur3_one_32(return_val.type, hash);
224 if (return_val.class_name != StringName()) {
225 hash = hash_murmur3_one_32(return_val.class_name.hash(), hash);
226 }
227 }
228
229 for (const PropertyInfo &arg : arguments) {
230 hash = hash_murmur3_one_32(arg.type, hash);
231 if (arg.class_name != StringName()) {
232 hash = hash_murmur3_one_32(arg.class_name.hash(), hash);
233 }
234 }
235
236 hash = hash_murmur3_one_32(default_arguments.size(), hash);
237 for (const Variant &v : default_arguments) {
238 hash = hash_murmur3_one_32(v.hash(), hash);
239 }
240
241 hash = hash_murmur3_one_32(flags & METHOD_FLAG_CONST ? 1 : 0, hash);
242 hash = hash_murmur3_one_32(flags & METHOD_FLAG_VARARG ? 1 : 0, hash);
243
244 return hash_fmix32(hash);
245 }
246
247 Object::Connection::operator Variant() const {
248 Dictionary d;
249 d["signal"] = signal;
250 d["callable"] = callable;
251 d["flags"] = flags;
252 return d;
253 }
254
255 void ObjectGDExtension::create_gdtype() {
256 ERR_FAIL_COND(gdtype);
257
258 gdtype = memnew(GDType(ClassDB::get_gdtype(parent_class_name), class_name));
259 }
260
261 void ObjectGDExtension::destroy_gdtype() {
262 ERR_FAIL_COND(!gdtype);
263
264 memdelete(const_cast<GDType *>(gdtype));
265 gdtype = nullptr;
266 }
267
268 ObjectGDExtension::~ObjectGDExtension() {
269 if (gdtype) {
270 memdelete(const_cast<GDType *>(gdtype));
271 }
272 }
273
274 bool Object::Connection::operator<(const Connection &p_conn) const {
275 if (signal == p_conn.signal) {
276 return callable < p_conn.callable;
277 } else {
278 return signal < p_conn.signal;
279 }
280 }
281
282 Object::Connection::Connection(const Variant &p_variant) {
283 Dictionary d = p_variant;
284 if (d.has("signal")) {
285 signal = d["signal"];
286 }
287 if (d.has("callable")) {
288 callable = d["callable"];
289 }
290 if (d.has("flags")) {
291 flags = d["flags"];
292 }
293 }
294
295 bool Object::_predelete() {
296 _predelete_ok = true;
297 notification(NOTIFICATION_PREDELETE, true);
298 if (!_predelete_ok) {
299 return false;
300 }
301
302 _gdtype_ptr = nullptr; // Must restore, so constructors/destructors have proper class name access at each stage.
303 notification(NOTIFICATION_PREDELETE_CLEANUP, true);
304
305 // Destruction order starts with the most derived class, and progresses towards the base Object class:
306 // Script subclasses -> GDExtension subclasses -> C++ subclasses -> Object
307 if (script_instance) {
308 memdelete(script_instance);
309 }
310 script_instance = nullptr;
311
312 if (_extension) {
313 #ifdef TOOLS_ENABLED
314 if (_extension->untrack_instance) {
315 _extension->untrack_instance(_extension->tracking_userdata, this);
316 }
317 #endif
318 if (_extension->free_instance) {
319 _extension->free_instance(_extension->class_userdata, _extension_instance);
320 }
321 _extension = nullptr;
322 _extension_instance = nullptr;
323 // _gdtype_ptr = nullptr; // The pointer already set to nullptr above, no need to do it again.
324 }
325 #ifdef TOOLS_ENABLED
326 else if (_instance_bindings != nullptr) {
327 Engine *engine = Engine::get_singleton();
328 GDExtensionManager *gdextension_manager = GDExtensionManager::get_singleton();
329 if (engine && gdextension_manager && engine->is_extension_reloading_enabled()) {
330 for (uint32_t i = 0; i < _instance_binding_count; i++) {
331 gdextension_manager->untrack_instance_binding(_instance_bindings[i].token, this);
332 }
333 }
334 }
335 #endif
336
337 return true;
338 }
339
340 void Object::cancel_free() {
341 _predelete_ok = false;
342 }
343
344 void Object::_initialize() {
345 // Cache the class name in the object for quick reference.
346 _gdtype_ptr = &_get_typev();
347 _initialize_classv();
348 }
349
350 void Object::_postinitialize() {
351 if (_uses_signal_mutex()) {
352 signal_mutex = memnew(Mutex);
353 }
354 notification(NOTIFICATION_POSTINITIALIZE);
355 }
356
357 void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) {
358 #ifdef TOOLS_ENABLED
359
360 _edited = true;
361 #endif
362
363 if (script_instance) {
364 if (script_instance->set(p_name, p_value)) {
365 if (r_valid) {
366 *r_valid = true;
367 }
368 return;
369 }
370 }
371
372 if (_extension && _extension->set) {
373 if (_extension->set(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionConstVariantPtr)&p_value)) {
374 if (r_valid) {
375 *r_valid = true;
376 }
377 return;
378 }
379 }
380
381 // Try built-in setter.
382 {
383 if (ClassDB::set_property(this, p_name, p_value, r_valid)) {
384 return;
385 }
386 }
387
388 if (p_name == CoreStringName(script)) {
389 set_script(p_value);
390 if (r_valid) {
391 *r_valid = true;
392 }
393 return;
394
395 } else {
396 Variant **V = metadata_properties.getptr(p_name);
397 if (V) {
398 **V = p_value;
399 if (r_valid) {
400 *r_valid = true;
401 }
402 return;
403 } else if (p_name.operator String().begins_with("metadata/")) {
404 // Must exist, otherwise duplicate() will not work.
405 set_meta(p_name.operator String().replace_first("metadata/", ""), p_value);
406 if (r_valid) {
407 *r_valid = true;
408 }
409 return;
410 }
411 }
412
413 #ifdef TOOLS_ENABLED
414 if (script_instance) {
415 bool valid;
416 script_instance->property_set_fallback(p_name, p_value, &valid);
417 if (valid) {
418 if (r_valid) {
419 *r_valid = true;
420 }
421 return;
422 }
423 }
424 #endif
425
426 // Something inside the object... :|
427 bool success = _setv(p_name, p_value);
428 if (success) {
429 if (r_valid) {
430 *r_valid = true;
431 }
432 return;
433 }
434
435 if (r_valid) {
436 *r_valid = false;
437 }
438 }
439
440 Variant Object::get(const StringName &p_name, bool *r_valid) const {
441 Variant ret;
442
443 if (script_instance) {
444 if (script_instance->get(p_name, ret)) {
445 if (r_valid) {
446 *r_valid = true;
447 }
448 return ret;
449 }
450 }
451 if (_extension && _extension->get) {
452 if (_extension->get(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
453 if (r_valid) {
454 *r_valid = true;
455 }
456 return ret;
457 }
458 }
459
460 // Try built-in getter.
461 {
462 if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) {
463 if (r_valid) {
464 *r_valid = true;
465 }
466 return ret;
467 }
468 }
469
470 if (p_name == CoreStringName(script)) {
471 ret = get_script();
472 if (r_valid) {
473 *r_valid = true;
474 }
475 return ret;
476 }
477
478 const Variant *const *V = metadata_properties.getptr(p_name);
479
480 if (V) {
481 ret = **V;
482 if (r_valid) {
483 *r_valid = true;
484 }
485 return ret;
486
487 } else {
488 #ifdef TOOLS_ENABLED
489 if (script_instance) {
490 bool valid;
491 ret = script_instance->property_get_fallback(p_name, &valid);
492 if (valid) {
493 if (r_valid) {
494 *r_valid = true;
495 }
496 return ret;
497 }
498 }
499 #endif
500 // Something inside the object... :|
501 bool success = _getv(p_name, ret);
502 if (success) {
503 if (r_valid) {
504 *r_valid = true;
505 }
506 return ret;
507 }
508
509 if (r_valid) {
510 *r_valid = false;
511 }
512 return Variant();
513 }
514 }
515
516 void Object::set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid) {
517 if (p_names.is_empty()) {
518 if (r_valid) {
519 *r_valid = false;
520 }
521 return;
522 }
523 if (p_names.size() == 1) {
524 set(p_names[0], p_value, r_valid);
525 return;
526 }
527
528 bool valid = false;
529 if (!r_valid) {
530 r_valid = &valid;
531 }
532
533 List<Variant> value_stack;
534
535 value_stack.push_back(get(p_names[0], r_valid));
536
537 if (!*r_valid) {
538 value_stack.clear();
539 return;
540 }
541
542 for (int i = 1; i < p_names.size() - 1; i++) {
543 value_stack.push_back(value_stack.back()->get().get_named(p_names[i], valid));
544 if (r_valid) {
545 *r_valid = valid;
546 }
547
548 if (!valid) {
549 value_stack.clear();
550 return;
551 }
552 }
553
554 value_stack.push_back(p_value); // p_names[p_names.size() - 1]
555
556 for (int i = p_names.size() - 1; i > 0; i--) {
557 value_stack.back()->prev()->get().set_named(p_names[i], value_stack.back()->get(), valid);
558 value_stack.pop_back();
559
560 if (r_valid) {
561 *r_valid = valid;
562 }
563 if (!valid) {
564 value_stack.clear();
565 return;
566 }
567 }
568
569 set(p_names[0], value_stack.back()->get(), r_valid);
570 value_stack.pop_back();
571
572 ERR_FAIL_COND(!value_stack.is_empty());
573 }
574
575 Variant Object::get_indexed(const Vector<StringName> &p_names, bool *r_valid) const {
576 if (p_names.is_empty()) {
577 if (r_valid) {
578 *r_valid = false;
579 }
580 return Variant();
581 }
582 bool valid = false;
583
584 Variant current_value = get(p_names[0], &valid);
585 for (int i = 1; i < p_names.size(); i++) {
586 current_value = current_value.get_named(p_names[i], valid);
587
588 if (!valid) {
589 break;
590 }
591 }
592 if (r_valid) {
593 *r_valid = valid;
594 }
595
596 return current_value;
597 }
598
599 void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const {
600 if (script_instance && p_reversed) {
601 script_instance->get_property_list(p_list);
602 }
603
604 if (_extension) {
605 const ObjectGDExtension *current_extension = _extension;
606 while (current_extension) {
607 p_list->push_back(PropertyInfo(Variant::NIL, current_extension->class_name, PROPERTY_HINT_NONE, current_extension->class_name, PROPERTY_USAGE_CATEGORY));
608
609 ClassDB::get_property_list(current_extension->class_name, p_list, true, this);
610
611 if (current_extension->get_property_list) {
612 #ifdef TOOLS_ENABLED
613 // If this is a placeholder, we can't call into the GDExtension on the parent class,
614 // because we don't have a real instance of the class to give it.
615 if (likely(!_extension->is_placeholder)) {
616 #endif
617 uint32_t pcount;
618 const GDExtensionPropertyInfo *pinfo = current_extension->get_property_list(_extension_instance, &pcount);
619 for (uint32_t i = 0; i < pcount; i++) {
620 p_list->push_back(PropertyInfo(pinfo[i]));
621 }
622 if (current_extension->free_property_list2) {
623 current_extension->free_property_list2(_extension_instance, pinfo, pcount);
624 }
625 #ifndef DISABLE_DEPRECATED
626 else if (current_extension->free_property_list) {
627 current_extension->free_property_list(_extension_instance, pinfo);
628 }
629 #endif // DISABLE_DEPRECATED
630 #ifdef TOOLS_ENABLED
631 }
632 #endif
633 }
634
635 current_extension = current_extension->parent;
636 }
637 }
638
639 _get_property_listv(p_list, p_reversed);
640
641 if (!is_class("Script")) { // can still be set, but this is for user-friendliness
642 p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NEVER_DUPLICATE));
643 }
644
645 if (script_instance && !p_reversed) {
646 script_instance->get_property_list(p_list);
647 }
648
649 for (const KeyValue<StringName, Variant> &K : metadata) {
650 PropertyInfo pi = PropertyInfo(K.value.get_type(), "metadata/" + K.key.operator String());
651 if (K.value.get_type() == Variant::OBJECT) {
652 pi.hint = PROPERTY_HINT_RESOURCE_TYPE;
653 Object *obj = K.value;
654 if (Object::cast_to<Script>(obj)) {
655 pi.hint_string = "Script";
656 pi.usage |= PROPERTY_USAGE_NEVER_DUPLICATE;
657 } else {
658 pi.hint_string = "Resource";
659 }
660 }
661 p_list->push_back(pi);
662 }
663 }
664
665 void Object::validate_property(PropertyInfo &p_property) const {
666 _validate_propertyv(p_property);
667
668 if (_extension && _extension->validate_property) {
669 // GDExtension uses a StringName rather than a String for property name.
670 StringName prop_name = p_property.name;
671 GDExtensionPropertyInfo gdext_prop = {
672 (GDExtensionVariantType)p_property.type,
673 &prop_name,
674 &p_property.class_name,
675 (uint32_t)p_property.hint,
676 &p_property.hint_string,
677 p_property.usage,
678 };
679 if (_extension->validate_property(_extension_instance, &gdext_prop)) {
680 p_property.type = (Variant::Type)gdext_prop.type;
681 p_property.name = *reinterpret_cast<StringName *>(gdext_prop.name);
682 p_property.class_name = *reinterpret_cast<StringName *>(gdext_prop.class_name);
683 p_property.hint = (PropertyHint)gdext_prop.hint;
684 p_property.hint_string = *reinterpret_cast<String *>(gdext_prop.hint_string);
685 p_property.usage = gdext_prop.usage;
686 };
687 }
688
689 if (script_instance) { // Call it last to allow user altering already validated properties.
690 script_instance->validate_property(p_property);
691 }
692 }
693
694 bool Object::property_can_revert(const StringName &p_name) const {
695 if (script_instance) {
696 if (script_instance->property_can_revert(p_name)) {
697 return true;
698 }
699 }
700
701 if (_extension && _extension->property_can_revert) {
702 if (_extension->property_can_revert(_extension_instance, (GDExtensionConstStringNamePtr)&p_name)) {
703 return true;
704 }
705 }
706
707 return _property_can_revertv(p_name);
708 }
709
710 Variant Object::property_get_revert(const StringName &p_name) const {
711 Variant ret;
712
713 if (script_instance) {
714 if (script_instance->property_get_revert(p_name, ret)) {
715 return ret;
716 }
717 }
718
719 if (_extension && _extension->property_get_revert) {
720 if (_extension->property_get_revert(_extension_instance, (GDExtensionConstStringNamePtr)&p_name, (GDExtensionVariantPtr)&ret)) {
721 return ret;
722 }
723 }
724
725 if (_property_get_revertv(p_name, ret)) {
726 return ret;
727 }
728 return Variant();
729 }
730
731 void Object::get_method_list(List<MethodInfo> *p_list) const {
732 ClassDB::get_method_list(get_class_name(), p_list);
733 if (script_instance) {
734 script_instance->get_method_list(p_list);
735 }
736 }
737
738 Variant Object::_call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
739 if (p_argcount < 1) {
740 r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
741 r_error.expected = 1;
742 return Variant();
743 }
744
745 if (!p_args[0]->is_string()) {
746 r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
747 r_error.argument = 0;
748 r_error.expected = Variant::STRING_NAME;
749 return Variant();
750 }
751
752 StringName method = *p_args[0];
753
754 return callp(method, &p_args[1], p_argcount - 1, r_error);
755 }
756
757 Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
758 if (p_argcount < 1) {
759 r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
760 r_error.expected = 1;
761 return Variant();
762 }
763
764 if (!p_args[0]->is_string()) {
765 r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
766 r_error.argument = 0;
767 r_error.expected = Variant::STRING_NAME;
768 return Variant();
769 }
770
771 r_error.error = Callable::CallError::CALL_OK;
772
773 StringName method = *p_args[0];
774
775 MessageQueue::get_singleton()->push_callp(get_instance_id(), method, &p_args[1], p_argcount - 1, true);
776
777 return Variant();
778 }
779
780 bool Object::has_method(const StringName &p_method) const {
781 if (p_method == CoreStringName(free_)) {
782 return true;
783 }
784
785 if (script_instance && script_instance->has_method(p_method)) {
786 return true;
787 }
788
789 MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
790 if (method != nullptr) {
791 return true;
792 }
793
794 const Script *scr = Object::cast_to<Script>(this);
795 if (scr != nullptr) {
796 return scr->has_static_method(p_method);
797 }
798
799 return false;
800 }
801
802 int Object::_get_method_argument_count_bind(const StringName &p_method) const {
803 return get_method_argument_count(p_method);
804 }
805
806 int Object::get_method_argument_count(const StringName &p_method, bool *r_is_valid) const {
807 if (p_method == CoreStringName(free_)) {
808 if (r_is_valid) {
809 *r_is_valid = true;
810 }
811 return 0;
812 }
813
814 if (script_instance) {
815 bool valid = false;
816 int ret = script_instance->get_method_argument_count(p_method, &valid);
817 if (valid) {
818 if (r_is_valid) {
819 *r_is_valid = true;
820 }
821 return ret;
822 }
823 }
824
825 {
826 bool valid = false;
827 int ret = ClassDB::get_method_argument_count(get_class_name(), p_method, &valid);
828 if (valid) {
829 if (r_is_valid) {
830 *r_is_valid = true;
831 }
832 return ret;
833 }
834 }
835
836 const Script *scr = Object::cast_to<Script>(this);
837 while (scr != nullptr) {
838 bool valid = false;
839 int ret = scr->get_script_method_argument_count(p_method, &valid);
840 if (valid) {
841 if (r_is_valid) {
842 *r_is_valid = true;
843 }
844 return ret;
845 }
846 scr = scr->get_base_script().ptr();
847 }
848
849 if (r_is_valid) {
850 *r_is_valid = false;
851 }
852 return 0;
853 }
854
855 Variant Object::getvar(const Variant &p_key, bool *r_valid) const {
856 if (r_valid) {
857 *r_valid = false;
858 }
859
860 if (p_key.is_string()) {
861 return get(p_key, r_valid);
862 }
863 return Variant();
864 }
865
866 void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) {
867 if (r_valid) {
868 *r_valid = false;
869 }
870 if (p_key.is_string()) {
871 return set(p_key, p_value, r_valid);
872 }
873 }
874
875 Variant Object::callv(const StringName &p_method, const Array &p_args) {
876 const Variant **argptrs = nullptr;
877
878 if (p_args.size() > 0) {
879 argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size());
880 for (int i = 0; i < p_args.size(); i++) {
881 argptrs[i] = &p_args[i];
882 }
883 }
884
885 Callable::CallError ce;
886 const Variant ret = callp(p_method, argptrs, p_args.size(), ce);
887 if (ce.error != Callable::CallError::CALL_OK) {
888 ERR_FAIL_V_MSG(Variant(), vformat("Error calling method from 'callv': %s.", Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce)));
889 }
890 return ret;
891 }
892
893 Variant Object::callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
894 r_error.error = Callable::CallError::CALL_OK;
895
896 if (p_method == CoreStringName(free_)) {
897 //free must be here, before anything, always ready
898 #ifdef DEBUG_ENABLED
899 if (p_argcount != 0) {
900 r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS;
901 r_error.expected = 0;
902 return Variant();
903 }
904 if (is_ref_counted()) {
905 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
906 ERR_FAIL_V_MSG(Variant(), "Can't free a RefCounted object.");
907 }
908
909 if (_lock_index.get() > 1) {
910 r_error.argument = 0;
911 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
912 ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed.");
913 }
914
915 #endif
916 //must be here, must be before everything,
917 memdelete(this);
918 r_error.error = Callable::CallError::CALL_OK;
919 return Variant();
920 }
921
922 Variant ret;
923 OBJ_DEBUG_LOCK
924
925 if (script_instance) {
926 ret = script_instance->callp(p_method, p_args, p_argcount, r_error);
927 // Force jump table.
928 switch (r_error.error) {
929 case Callable::CallError::CALL_OK:
930 return ret;
931 case Callable::CallError::CALL_ERROR_INVALID_METHOD:
932 break;
933 case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
934 case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
935 case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
936 case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
937 return ret;
938 case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
939 }
940 }
941 }
942
943 //extension does not need this, because all methods are registered in MethodBind
944
945 MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
946
947 if (method) {
948 ret = method->call(this, p_args, p_argcount, r_error);
949 } else {
950 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
951 }
952
953 return ret;
954 }
955
956 Variant Object::call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
957 r_error.error = Callable::CallError::CALL_OK;
958
959 if (p_method == CoreStringName(free_)) {
960 // Free is not const, so fail.
961 r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
962 return Variant();
963 }
964
965 Variant ret;
966 OBJ_DEBUG_LOCK
967
968 if (script_instance) {
969 ret = script_instance->call_const(p_method, p_args, p_argcount, r_error);
970 //force jumptable
971 switch (r_error.error) {
972 case Callable::CallError::CALL_OK:
973 return ret;
974 case Callable::CallError::CALL_ERROR_INVALID_METHOD:
975 break;
976 case Callable::CallError::CALL_ERROR_METHOD_NOT_CONST:
977 break;
978 case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
979 case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
980 case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
981 return ret;
982 case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: {
983 }
984 }
985 }
986
987 //extension does not need this, because all methods are registered in MethodBind
988
989 MethodBind *method = ClassDB::get_method(get_class_name(), p_method);
990
991 if (method) {
992 if (!method->is_const()) {
993 r_error.error = Callable::CallError::CALL_ERROR_METHOD_NOT_CONST;
994 return ret;
995 }
996 ret = method->call(this, p_args, p_argcount, r_error);
997 } else {
998 r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
999 }
1000
1001 return ret;
1002 }
1003
1004 void Object::_gdvirtual_init_method_ptr(uint32_t p_compat_hash, void *&r_fn_ptr, const StringName &p_fn_name, bool p_compat) const {
1005 r_fn_ptr = nullptr;
1006 if (_extension->get_virtual_call_data2 && _extension->call_virtual_with_data) {
1007 r_fn_ptr = _extension->get_virtual_call_data2(_extension->class_userdata, &p_fn_name, p_compat_hash);
1008 } else if (_extension->get_virtual2) {
1009 r_fn_ptr = (void *)_extension->get_virtual2(_extension->class_userdata, &p_fn_name, p_compat_hash);
1010 #ifndef DISABLE_DEPRECATED
1011 } else if (p_compat || ClassDB::get_virtual_method_compatibility_hashes(get_class_name(), p_fn_name).size() == 0) {
1012 if (_extension->get_virtual_call_data && _extension->call_virtual_with_data) {
1013 r_fn_ptr = _extension->get_virtual_call_data(_extension->class_userdata, &p_fn_name);
1014 } else if (_extension->get_virtual) {
1015 r_fn_ptr = (void *)_extension->get_virtual(_extension->class_userdata, &p_fn_name);
1016 }
1017 #endif
1018 }
1019 #ifdef TOOLS_ENABLED
1020 if (_extension->reloadable) {
1021 VirtualMethodTracker *tracker = memnew(VirtualMethodTracker);
1022 tracker->method = (void **)&r_fn_ptr;
1023 tracker->next = virtual_method_list;
1024 virtual_method_list = tracker;
1025 }
1026 #endif
1027 if (r_fn_ptr == nullptr) {
1028 r_fn_ptr = reinterpret_cast<void *>(_INVALID_GDVIRTUAL_FUNC_ADDR);
1029 }
1030 }
1031
1032 void Object::_notification_forward(int p_notification) {
1033 // Notify classes starting with Object and ending with most derived subclass.
1034 // e.g. Object -> Node -> Node3D
1035 _notification_forwardv(p_notification);
1036
1037 if (_extension) {
1038 if (_extension->notification2) {
1039 _extension->notification2(_extension_instance, p_notification, static_cast<GDExtensionBool>(false));
1040 #ifndef DISABLE_DEPRECATED
1041 } else if (_extension->notification) {
1042 _extension->notification(_extension_instance, p_notification);
1043 #endif // DISABLE_DEPRECATED
1044 }
1045 }
1046
1047 if (script_instance) {
1048 script_instance->notification(p_notification, false);
1049 }
1050 }
1051
1052 void Object::_notification_backward(int p_notification) {
1053 if (script_instance) {
1054 script_instance->notification(p_notification, true);
1055 }
1056
1057 if (_extension) {
1058 if (_extension->notification2) {
1059 _extension->notification2(_extension_instance, p_notification, static_cast<GDExtensionBool>(true));
1060 #ifndef DISABLE_DEPRECATED
1061 } else if (_extension->notification) {
1062 _extension->notification(_extension_instance, p_notification);
1063 #endif // DISABLE_DEPRECATED
1064 }
1065 }
1066
1067 // Notify classes starting with most derived subclass and ending in Object.
1068 // e.g. Node3D -> Node -> Object
1069 _notification_backwardv(p_notification);
1070 }
1071
1072 String Object::to_string() {
1073 // Keep this method in sync with `Node::to_string`.
1074 if (script_instance) {
1075 bool valid;
1076 String ret = script_instance->to_string(&valid);
1077 if (valid) {
1078 return ret;
1079 }
1080 }
1081 if (_extension && _extension->to_string) {
1082 String ret;
1083 GDExtensionBool is_valid;
1084 _extension->to_string(_extension_instance, &is_valid, &ret);
1085 if (is_valid) {
1086 return ret;
1087 }
1088 }
1089 return _to_string();
1090 }
1091
1092 void Object::set_script(const Variant &p_script) {
1093 if (get_script() == p_script) {
1094 return;
1095 }
1096
1097 Ref<Script> s = p_script;
1098 if (!p_script.is_null()) {
1099 ERR_FAIL_COND_MSG(s.is_null(), "Cannot set object script. Parameter should be null or a reference to a valid script.");
1100 ERR_FAIL_COND_MSG(s->is_abstract(), vformat("Cannot set object script. Script '%s' should not be abstract.", s->get_path()));
1101 }
1102
1103 if (script_instance) {
1104 memdelete(script_instance);
1105 script_instance = nullptr;
1106 }
1107
1108 if (s.is_valid()) {
1109 if (s->can_instantiate()) {
1110 OBJ_DEBUG_LOCK
1111 script_instance = s->instance_create(this);
1112 } else if (Engine::get_singleton()->is_editor_hint()) {
1113 OBJ_DEBUG_LOCK
1114 script_instance = s->placeholder_instance_create(this);
1115 }
1116 }
1117
1118 notify_property_list_changed(); //scripts may add variables, so refresh is desired
1119 emit_signal(CoreStringName(script_changed));
1120 }
1121
1122 void Object::set_script_instance(ScriptInstance *p_instance) {
1123 if (script_instance == p_instance) {
1124 return;
1125 }
1126
1127 if (script_instance) {
1128 memdelete(script_instance);
1129 }
1130
1131 script_instance = p_instance;
1132 }
1133
1134 Variant Object::get_script() const {
1135 return script_instance ? Variant(script_instance->get_script()) : Variant();
1136 }
1137
1138 bool Object::has_meta(const StringName &p_name) const {
1139 return metadata.has(p_name);
1140 }
1141
1142 void Object::set_meta(const StringName &p_name, const Variant &p_value) {
1143 if (p_value.get_type() == Variant::NIL) {
1144 if (metadata.has(p_name)) {
1145 metadata.erase(p_name);
1146
1147 const String &sname = p_name;
1148 metadata_properties.erase("metadata/" + sname);
1149 if (!sname.begins_with("_")) {
1150 // Metadata starting with _ don't show up in the inspector, so no need to update.
1151 notify_property_list_changed();
1152 }
1153 }
1154 return;
1155 }
1156
1157 HashMap<StringName, Variant>::Iterator E = metadata.find(p_name);
1158 if (E) {
1159 E->value = p_value;
1160 } else {
1161 ERR_FAIL_COND_MSG(!p_name.operator String().is_valid_ascii_identifier(), vformat("Invalid metadata identifier: '%s'.", p_name));
1162 Variant *V = &metadata.insert(p_name, p_value)->value;
1163
1164 const String &sname = p_name;
1165 metadata_properties["metadata/" + sname] = V;
1166 if (!sname.begins_with("_")) {
1167 notify_property_list_changed();
1168 }
1169 }
1170 }
1171
1172 Variant Object::get_meta(const StringName &p_name, const Variant &p_default) const {
1173 if (!metadata.has(p_name)) {
1174 if (p_default != Variant()) {
1175 return p_default;
1176 } else {
1177 ERR_FAIL_V_MSG(Variant(), vformat("The object does not have any 'meta' values with the key '%s'.", p_name));
1178 }
1179 }
1180 return metadata[p_name];
1181 }
1182
1183 void Object::remove_meta(const StringName &p_name) {
1184 set_meta(p_name, Variant());
1185 }
1186
1187 void Object::merge_meta_from(const Object *p_src) {
1188 List<StringName> meta_keys;
1189 p_src->get_meta_list(&meta_keys);
1190 for (const StringName &key : meta_keys) {
1191 set_meta(key, p_src->get_meta(key));
1192 }
1193 }
1194
1195 TypedArray<Dictionary> Object::_get_property_list_bind() const {
1196 List<PropertyInfo> lpi;
1197 get_property_list(&lpi);
1198 return convert_property_list(&lpi);
1199 }
1200
1201 TypedArray<Dictionary> Object::_get_method_list_bind() const {
1202 List<MethodInfo> ml;
1203 get_method_list(&ml);
1204 TypedArray<Dictionary> ret;
1205
1206 for (const MethodInfo &mi : ml) {
1207 Dictionary d = mi;
1208 //va.push_back(d);
1209 ret.push_back(d);
1210 }
1211
1212 return ret;
1213 }
1214
1215 TypedArray<StringName> Object::_get_meta_list_bind() const {
1216 TypedArray<StringName> _metaret;
1217
1218 for (const KeyValue<StringName, Variant> &K : metadata) {
1219 _metaret.push_back(K.key);
1220 }
1221
1222 return _metaret;
1223 }
1224
1225 void Object::get_meta_list(List<StringName> *p_list) const {
1226 for (const KeyValue<StringName, Variant> &K : metadata) {
1227 p_list->push_back(K.key);
1228 }
1229 }
1230
1231 void Object::add_user_signal(const MethodInfo &p_signal) {
1232 ERR_FAIL_COND_MSG(p_signal.name.is_empty(), "Signal name cannot be empty.");
1233 ERR_FAIL_COND_MSG(ClassDB::has_signal(get_class_name(), p_signal.name), vformat("User signal's name conflicts with a built-in signal of '%s'.", get_class_name()));
1234
1235 ObjectSignalLock signal_lock(this);
1236
1237 ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), vformat("Trying to add already existing signal '%s'.", p_signal.name));
1238 SignalData s;
1239 s.user = p_signal;
1240 signal_map[p_signal.name] = s;
1241 }
1242
1243 bool Object::_has_user_signal(const StringName &p_name) const {
1244 ObjectSignalLock signal_lock(this);
1245
1246 if (!signal_map.has(p_name)) {
1247 return false;
1248 }
1249 return signal_map[p_name].user.name.length() > 0;
1250 }
1251
1252 void Object::_remove_user_signal(const StringName &p_name) {
1253 HashMap<Callable, Object::SignalData::Slot> slots_to_disconnect;
1254
1255 {
1256 ObjectSignalLock signal_lock(this);
1257
1258 SignalData *s = signal_map.getptr(p_name);
1259 ERR_FAIL_NULL_MSG(s, "Provided signal does not exist.");
1260 ERR_FAIL_COND_MSG(!s->removable, "Signal is not removable (not added with add_user_signal).");
1261
1262 slots_to_disconnect = std::move(s->slot_map);
1263 signal_map.erase(p_name);
1264 }
1265
1266 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : slots_to_disconnect) {
1267 Object *target = slot_kv.key.get_object();
1268 if (likely(target)) {
1269 ObjectSignalLock signal_lock(target);
1270 target->connections.erase(slot_kv.value.cE);
1271 }
1272 }
1273 }
1274
1275 Error Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
1276 if (unlikely(p_argcount < 1)) {
1277 r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS;
1278 r_error.expected = 1;
1279 ERR_FAIL_V(Error::ERR_INVALID_PARAMETER);
1280 }
1281
1282 if (unlikely(!p_args[0]->is_string())) {
1283 r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
1284 r_error.argument = 0;
1285 r_error.expected = Variant::STRING_NAME;
1286 ERR_FAIL_V(Error::ERR_INVALID_PARAMETER);
1287 }
1288
1289 r_error.error = Callable::CallError::CALL_OK;
1290
1291 StringName signal = *p_args[0];
1292
1293 const Variant **args = nullptr;
1294
1295 int argc = p_argcount - 1;
1296 if (argc) {
1297 args = &p_args[1];
1298 }
1299
1300 return emit_signalp(signal, args, argc);
1301 }
1302
1303 Error Object::emit_signalp(const StringName &p_name, const Variant **p_args, int p_argcount) {
1304 if (_block_signals) {
1305 return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked
1306 }
1307
1308 constexpr int MAX_SLOTS_ON_STACK = 5;
1309 // Don't default initialize the Callable objects on the stack, just reserve the space - we'll memnew_placement() them later.
1310 alignas(Callable) uint8_t slot_callable_stack[sizeof(Callable) * MAX_SLOTS_ON_STACK];
1311 uint32_t slot_flags_stack[MAX_SLOTS_ON_STACK];
1312
1313 Callable *slot_callables = (Callable *)slot_callable_stack;
1314 uint32_t *slot_flags = slot_flags_stack;
1315 uint32_t slot_count = 0;
1316
1317 {
1318 ObjectSignalLock signal_lock(this);
1319
1320 SignalData *s = signal_map.getptr(p_name);
1321 if (!s) {
1322 #ifdef DEBUG_ENABLED
1323 bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name);
1324 //check in script
1325 ERR_FAIL_COND_V_MSG(!signal_is_valid && script_instance && !script_instance->get_script()->has_script_signal(p_name), ERR_UNAVAILABLE, vformat("Can't emit non-existing signal \"%s\".", p_name));
1326 #endif
1327 //not connected? just return
1328 return ERR_UNAVAILABLE;
1329 }
1330
1331 if (s->slot_map.size() > MAX_SLOTS_ON_STACK) {
1332 slot_callables = (Callable *)memalloc(sizeof(Callable) * s->slot_map.size());
1333 slot_flags = (uint32_t *)memalloc(sizeof(uint32_t) * s->slot_map.size());
1334 }
1335
1336 // Ensure that disconnecting the signal or even deleting the object
1337 // will not affect the signal calling.
1338 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
1339 memnew_placement(&slot_callables[slot_count], Callable(slot_kv.value.conn.callable));
1340 slot_flags[slot_count] = slot_kv.value.conn.flags;
1341 ++slot_count;
1342 }
1343
1344 DEV_ASSERT(slot_count == s->slot_map.size());
1345 }
1346
1347 // Disconnect all one-shot connections before emitting to prevent recursion.
1348 for (uint32_t i = 0; i < slot_count; ++i) {
1349 bool disconnect = slot_flags[i] & CONNECT_ONE_SHOT;
1350 #ifdef TOOLS_ENABLED
1351 if (disconnect && (slot_flags[i] & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) {
1352 // This signal was connected from the editor, and is being edited. Just don't disconnect for now.
1353 disconnect = false;
1354 }
1355 #endif
1356 if (disconnect) {
1357 _disconnect(p_name, slot_callables[i]);
1358 }
1359 }
1360
1361 OBJ_DEBUG_LOCK
1362
1363 // If this is a ref-counted object, prevent it from being destroyed during signal
1364 // emission, which is needed in certain edge cases; e.g., GH-73889 and GH-109471.
1365 // Moreover, since signals can be emitted from constructors (classic example being
1366 // notify_property_list_changed), we must be careful not to do the ref init ourselves,
1367 // which would lead to the object being destroyed at the end of this function.
1368 bool pending_unref = Object::cast_to<RefCounted>(this) ? ((RefCounted *)this)->reference() : false;
1369
1370 Error err = OK;
1371
1372 Vector<const Variant *> append_source_mem;
1373 Variant source = this;
1374
1375 for (uint32_t i = 0; i < slot_count; ++i) {
1376 const Callable &callable = slot_callables[i];
1377 const uint32_t &flags = slot_flags[i];
1378
1379 if (!callable.is_valid()) {
1380 // Target might have been deleted during signal callback, this is expected and OK.
1381 continue;
1382 }
1383
1384 const Variant **args = p_args;
1385 int argc = p_argcount;
1386
1387 if (flags & CONNECT_APPEND_SOURCE_OBJECT) {
1388 // Source is being appended regardless of unbinds.
1389 // Implemented by inserting before the first to-be-unbinded arg.
1390 int source_index = p_argcount - callable.get_unbound_arguments_count();
1391 if (source_index >= 0) {
1392 append_source_mem.resize(p_argcount + 1);
1393 const Variant **args_mem = append_source_mem.ptrw();
1394
1395 for (int j = 0; j < source_index; j++) {
1396 args_mem[j] = p_args[j];
1397 }
1398 args_mem[source_index] = &source;
1399 for (int j = source_index; j < p_argcount; j++) {
1400 args_mem[j + 1] = p_args[j];
1401 }
1402
1403 args = args_mem;
1404 argc = p_argcount + 1;
1405 } else {
1406 // More args unbound than provided, call will fail.
1407 // Since appended source is non-unbindable, the error
1408 // about too many unbinds should be correct as is.
1409 }
1410 }
1411
1412 if (flags & CONNECT_DEFERRED) {
1413 MessageQueue::get_singleton()->push_callablep(callable, args, argc, true);
1414 } else {
1415 Callable::CallError ce;
1416 _emitting = true;
1417 Variant ret;
1418 callable.callp(args, argc, ret, ce);
1419 _emitting = false;
1420
1421 if (ce.error != Callable::CallError::CALL_OK) {
1422 Object *target = callable.get_object();
1423 #ifdef DEBUG_ENABLED
1424 if (target && flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint()) {
1425 Ref<Script> other_scr = target->get_script();
1426 if (other_scr.is_valid() && !other_scr->is_tool()) {
1427 // Trying to call not-tool method in editor, just ignore it.
1428 continue;
1429 }
1430 }
1431 #endif
1432 if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && target && !ClassDB::class_exists(target->get_class_name())) {
1433 // Most likely object is not initialized yet, do not throw error.
1434 } else {
1435 ERR_PRINT(vformat("Error calling from signal '%s' to callable: %s.", String(p_name), Variant::get_callable_error_text(callable, args, argc, ce)));
1436 err = ERR_METHOD_NOT_FOUND;
1437 }
1438 }
1439 }
1440 }
1441
1442 for (uint32_t i = 0; i < slot_count; ++i) {
1443 slot_callables[i].~Callable();
1444 }
1445
1446 if (slot_callables != (Callable *)slot_callable_stack) {
1447 memfree(slot_callables);
1448 memfree(slot_flags);
1449 }
1450
1451 if (pending_unref) {
1452 // We have to do the same Ref<T> would do. We can't just use Ref<T>
1453 // because it would do the init ref logic, which is something this function
1454 // shouldn't do, as explained above.
1455 if (((RefCounted *)this)->unreference()) {
1456 memdelete(this);
1457 }
1458 }
1459
1460 return err;
1461 }
1462
1463 void Object::_reset_gdtype() const {
1464 if (_extension) {
1465 // Set to extension's type.
1466 _gdtype_ptr = _extension->gdtype;
1467 } else {
1468 // Reset to internal type.
1469 _gdtype_ptr = &_get_typev();
1470 }
1471 }
1472
1473 void Object::_add_user_signal(const String &p_name, const Array &p_args) {
1474 // this version of add_user_signal is meant to be used from scripts or external apis
1475 // without access to ADD_SIGNAL in bind_methods
1476 // added events are per instance, as opposed to the other ones, which are global
1477
1478 ObjectSignalLock signal_lock(this);
1479
1480 MethodInfo mi;
1481 mi.name = p_name;
1482
1483 for (const Variant &arg : p_args) {
1484 Dictionary d = arg;
1485 PropertyInfo param;
1486
1487 if (d.has("name")) {
1488 param.name = d["name"];
1489 }
1490 if (d.has("type")) {
1491 param.type = (Variant::Type)(int)d["type"];
1492 }
1493
1494 mi.arguments.push_back(param);
1495 }
1496
1497 add_user_signal(mi);
1498
1499 if (signal_map.has(p_name)) {
1500 signal_map.getptr(p_name)->removable = true;
1501 }
1502 }
1503
1504 TypedArray<Dictionary> Object::_get_signal_list() const {
1505 List<MethodInfo> signal_list;
1506 get_signal_list(&signal_list);
1507
1508 TypedArray<Dictionary> ret;
1509 for (const MethodInfo &E : signal_list) {
1510 ret.push_back(Dictionary(E));
1511 }
1512
1513 return ret;
1514 }
1515
1516 TypedArray<Dictionary> Object::_get_signal_connection_list(const StringName &p_signal) const {
1517 List<Connection> conns;
1518 get_all_signal_connections(&conns);
1519
1520 TypedArray<Dictionary> ret;
1521
1522 for (const Connection &c : conns) {
1523 if (c.signal.get_name() == p_signal) {
1524 ret.push_back(c);
1525 }
1526 }
1527
1528 return ret;
1529 }
1530
1531 TypedArray<Dictionary> Object::_get_incoming_connections() const {
1532 ObjectSignalLock signal_lock(this);
1533
1534 TypedArray<Dictionary> ret;
1535 for (const Object::Connection &connection : connections) {
1536 ret.push_back(connection);
1537 }
1538
1539 return ret;
1540 }
1541
1542 bool Object::has_signal(const StringName &p_name) const {
1543 if (script_instance && script_instance->get_script()->has_script_signal(p_name)) {
1544 return true;
1545 }
1546
1547 if (ClassDB::has_signal(get_class_name(), p_name)) {
1548 return true;
1549 }
1550
1551 if (_has_user_signal(p_name)) {
1552 return true;
1553 }
1554
1555 return false;
1556 }
1557
1558 void Object::get_signal_list(List<MethodInfo> *p_signals) const {
1559 ObjectSignalLock signal_lock(this);
1560
1561 if (script_instance) {
1562 script_instance->get_script()->get_script_signal_list(p_signals);
1563 }
1564
1565 ClassDB::get_signal_list(get_class_name(), p_signals);
1566 //find maybe usersignals?
1567
1568 for (const KeyValue<StringName, SignalData> &E : signal_map) {
1569 if (!E.value.user.name.is_empty()) {
1570 //user signal
1571 p_signals->push_back(E.value.user);
1572 }
1573 }
1574 }
1575
1576 void Object::get_all_signal_connections(List<Connection> *p_connections) const {
1577 ObjectSignalLock signal_lock(this);
1578
1579 for (const KeyValue<StringName, SignalData> &E : signal_map) {
1580 const SignalData *s = &E.value;
1581
1582 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
1583 p_connections->push_back(slot_kv.value.conn);
1584 }
1585 }
1586 }
1587
1588 void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const {
1589 ObjectSignalLock signal_lock(this);
1590
1591 const SignalData *s = signal_map.getptr(p_signal);
1592 if (!s) {
1593 return; //nothing
1594 }
1595
1596 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
1597 p_connections->push_back(slot_kv.value.conn);
1598 }
1599 }
1600
1601 int Object::get_persistent_signal_connection_count() const {
1602 ObjectSignalLock signal_lock(this);
1603 int count = 0;
1604
1605 for (const KeyValue<StringName, SignalData> &E : signal_map) {
1606 const SignalData *s = &E.value;
1607
1608 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
1609 if (slot_kv.value.conn.flags & CONNECT_PERSIST) {
1610 count += 1;
1611 }
1612 }
1613 }
1614
1615 return count;
1616 }
1617
1618 uint32_t Object::get_signal_connection_flags(const StringName &p_name, const Callable &p_callable) const {
1619 ObjectSignalLock signal_lock(this);
1620 const SignalData *signal_data = signal_map.getptr(p_name);
1621 if (signal_data) {
1622 const SignalData::Slot *slot = signal_data->slot_map.getptr(p_callable);
1623 if (slot) {
1624 return slot->conn.flags;
1625 }
1626 }
1627 return 0;
1628 }
1629
1630 void Object::get_signals_connected_to_this(List<Connection> *p_connections) const {
1631 ObjectSignalLock signal_lock(this);
1632
1633 for (const Connection &E : connections) {
1634 p_connections->push_back(E);
1635 }
1636 }
1637
1638 Error Object::connect(const StringName &p_signal, const Callable &p_callable, uint32_t p_flags) {
1639 ERR_FAIL_COND_V_MSG(p_callable.is_null(), ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s': the provided callable is null.", p_signal));
1640 Object *target_object = p_callable.get_object();
1641 ObjectSignalLock signal_lock(this, target_object);
1642
1643 if (p_callable.is_standard()) {
1644 // FIXME: This branch should probably removed in favor of the `is_valid()` branch, but there exist some classes
1645 // that call `connect()` before they are fully registered with ClassDB. Until all such classes can be found
1646 // and registered soon enough this branch is needed to allow `connect()` to succeed.
1647 ERR_FAIL_NULL_V_MSG(target_object, ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s' to callable '%s': the callable object is null.", p_signal, p_callable));
1648 } else {
1649 ERR_FAIL_COND_V_MSG(!p_callable.is_valid(), ERR_INVALID_PARAMETER, vformat("Cannot connect to '%s': the provided callable is not valid: '%s'.", p_signal, p_callable));
1650 }
1651
1652 SignalData *s = signal_map.getptr(p_signal);
1653 if (!s) {
1654 bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
1655 //check in script
1656 if (!signal_is_valid && script_instance) {
1657 if (script_instance->get_script()->has_script_signal(p_signal)) {
1658 signal_is_valid = true;
1659 }
1660 #ifdef TOOLS_ENABLED
1661 else {
1662 //allow connecting signals anyway if script is invalid, see issue #17070
1663 if (!script_instance->get_script()->is_valid()) {
1664 signal_is_valid = true;
1665 }
1666 }
1667 #endif
1668 }
1669
1670 ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, vformat("In Object of type '%s': Attempt to connect nonexistent signal '%s' to callable '%s'.", String(get_class()), p_signal, p_callable));
1671
1672 signal_map[p_signal] = SignalData();
1673 s = &signal_map[p_signal];
1674 }
1675
1676 //compare with the base callable, so binds can be ignored
1677 if (s->slot_map.has(*p_callable.get_base_comparator())) {
1678 if (p_flags & CONNECT_REFERENCE_COUNTED) {
1679 s->slot_map[*p_callable.get_base_comparator()].reference_count++;
1680 return OK;
1681 } else {
1682 ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("Signal '%s' is already connected to given callable '%s' in that object.", p_signal, p_callable));
1683 }
1684 }
1685
1686 SignalData::Slot slot;
1687
1688 Connection conn;
1689 conn.callable = p_callable;
1690 conn.signal = ::Signal(this, p_signal);
1691 conn.flags = p_flags;
1692 slot.conn = conn;
1693 if (target_object) {
1694 slot.cE = target_object->connections.push_back(conn);
1695 }
1696 if (p_flags & CONNECT_REFERENCE_COUNTED) {
1697 slot.reference_count = 1;
1698 }
1699
1700 //use callable version as key, so binds can be ignored
1701 s->slot_map[*p_callable.get_base_comparator()] = slot;
1702
1703 return OK;
1704 }
1705
1706 bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const {
1707 ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, vformat("Cannot determine if connected to '%s': the provided callable is null.", p_signal)); // Should use `is_null`, see note in `connect` about the use of `is_valid`.
1708 ObjectSignalLock signal_lock(this);
1709
1710 const SignalData *s = signal_map.getptr(p_signal);
1711 if (!s) {
1712 bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
1713 if (signal_is_valid) {
1714 return false;
1715 }
1716
1717 if (script_instance && script_instance->get_script()->has_script_signal(p_signal)) {
1718 return false;
1719 }
1720
1721 ERR_FAIL_V_MSG(false, vformat("Nonexistent signal: '%s'.", p_signal));
1722 }
1723
1724 return s->slot_map.has(*p_callable.get_base_comparator());
1725 }
1726
1727 bool Object::has_connections(const StringName &p_signal) const {
1728 ObjectSignalLock signal_lock(this);
1729
1730 const SignalData *s = signal_map.getptr(p_signal);
1731 if (!s) {
1732 bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal);
1733 if (signal_is_valid) {
1734 return false;
1735 }
1736
1737 if (script_instance && script_instance->get_script()->has_script_signal(p_signal)) {
1738 return false;
1739 }
1740
1741 ERR_FAIL_V_MSG(false, vformat("Nonexistent signal: '%s'.", p_signal));
1742 }
1743
1744 return !s->slot_map.is_empty();
1745 }
1746
1747 void Object::disconnect(const StringName &p_signal, const Callable &p_callable) {
1748 _disconnect(p_signal, p_callable);
1749 }
1750
1751 bool Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) {
1752 ERR_FAIL_COND_V_MSG(p_callable.is_null(), false, vformat("Cannot disconnect from '%s': the provided callable is null.", p_signal)); // Should use `is_null`, see note in `connect` about the use of `is_valid`.
1753 Object *target_object = p_callable.get_object();
1754 ObjectSignalLock signal_lock(this, target_object);
1755
1756 SignalData *s = signal_map.getptr(p_signal);
1757 if (!s) {
1758 bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal) ||
1759 (script_instance && script_instance->get_script()->has_script_signal(p_signal));
1760 ERR_FAIL_COND_V_MSG(signal_is_valid, false, vformat("Attempt to disconnect a nonexistent connection from '%s'. Signal: '%s', callable: '%s'.", to_string(), p_signal, p_callable));
1761 }
1762 ERR_FAIL_NULL_V_MSG(s, false, vformat("Disconnecting nonexistent signal '%s' in '%s'.", p_signal, to_string()));
1763
1764 ERR_FAIL_COND_V_MSG(!s->slot_map.has(*p_callable.get_base_comparator()), false, vformat("Attempt to disconnect a nonexistent connection from '%s'. Signal: '%s', callable: '%s'.", to_string(), p_signal, p_callable));
1765
1766 SignalData::Slot *slot = &s->slot_map[*p_callable.get_base_comparator()];
1767
1768 if (!p_force) {
1769 slot->reference_count--; // by default is zero, if it was not referenced it will go below it
1770 if (slot->reference_count > 0) {
1771 return false;
1772 }
1773 }
1774
1775 if (likely(target_object)) {
1776 target_object->connections.erase(slot->cE);
1777 }
1778
1779 s->slot_map.erase(*p_callable.get_base_comparator());
1780
1781 if (s->slot_map.is_empty() && ClassDB::has_signal(get_class_name(), p_signal)) {
1782 //not user signal, delete
1783 signal_map.erase(p_signal);
1784 }
1785
1786 return true;
1787 }
1788
1789 bool Object::_uses_signal_mutex() const {
1790 return true;
1791 }
1792
1793 String Object::_get_locale() const {
1794 TranslationServer *ts = TranslationServer::get_singleton();
1795 const StringName domain_name = get_translation_domain();
1796 if (ts->has_domain(domain_name)) {
1797 const Ref<TranslationDomain> domain = ts->get_or_add_domain(domain_name);
1798 const String &overridden = domain->get_locale_override();
1799 if (!overridden.is_empty()) {
1800 return overridden;
1801 }
1802 }
1803 return ts->get_locale();
1804 }
1805
1806 void Object::_set_bind(const StringName &p_set, const Variant &p_value) {
1807 set(p_set, p_value);
1808 }
1809
1810 Variant Object::_get_bind(const StringName &p_name) const {
1811 return get(p_name);
1812 }
1813
1814 void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) {
1815 set_indexed(p_name.get_as_property_path().get_subnames(), p_value);
1816 }
1817
1818 Variant Object::_get_indexed_bind(const NodePath &p_name) const {
1819 return get_indexed(p_name.get_as_property_path().get_subnames());
1820 }
1821
1822 void Object::initialize_class() {
1823 static bool initialized = false;
1824 if (initialized) {
1825 return;
1826 }
1827 _add_class_to_classdb(get_gdtype_static(), nullptr);
1828 _bind_methods();
1829 _bind_compatibility_methods();
1830 initialized = true;
1831 }
1832
1833 StringName Object::get_translation_domain() const {
1834 return _translation_domain;
1835 }
1836
1837 void Object::set_translation_domain(const StringName &p_domain) {
1838 _translation_domain = p_domain;
1839 }
1840
1841 String Object::tr(const StringName &p_message, const StringName &p_context) const {
1842 if (!_can_translate || !TranslationServer::get_singleton()) {
1843 return p_message;
1844 }
1845
1846 const Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(get_translation_domain());
1847 return domain->translate(p_message, p_context);
1848 }
1849
1850 String Object::tr_n(const StringName &p_message, const StringName &p_message_plural, int p_n, const StringName &p_context) const {
1851 if (!_can_translate || !TranslationServer::get_singleton()) {
1852 // Return message based on English plural rule if translation is not possible.
1853 if (p_n == 1) {
1854 return p_message;
1855 }
1856 return p_message_plural;
1857 }
1858
1859 const Ref<TranslationDomain> domain = TranslationServer::get_singleton()->get_or_add_domain(get_translation_domain());
1860 return domain->translate_plural(p_message, p_message_plural, p_n, p_context);
1861 }
1862
1863 void Object::_clear_internal_resource_paths(const Variant &p_var) {
1864 switch (p_var.get_type()) {
1865 case Variant::OBJECT: {
1866 Ref<Resource> r = p_var;
1867 if (r.is_null()) {
1868 return;
1869 }
1870
1871 if (!r->is_built_in()) {
1872 return; //not an internal resource
1873 }
1874
1875 Object *object = p_var;
1876 if (!object) {
1877 return;
1878 }
1879
1880 r->set_path("");
1881 r->clear_internal_resource_paths();
1882 } break;
1883 case Variant::ARRAY: {
1884 Array a = p_var;
1885 for (const Variant &var : a) {
1886 _clear_internal_resource_paths(var);
1887 }
1888
1889 } break;
1890 case Variant::DICTIONARY: {
1891 Dictionary d = p_var;
1892
1893 for (const KeyValue<Variant, Variant> &kv : d) {
1894 _clear_internal_resource_paths(kv.key);
1895 _clear_internal_resource_paths(kv.value);
1896 }
1897 } break;
1898 default: {
1899 }
1900 }
1901 }
1902
1903 void Object::_add_class_to_classdb(const GDType &p_type, const GDType *p_inherits) {
1904 ClassDB::_add_class(p_type, p_inherits);
1905 }
1906
1907 void Object::_get_property_list_from_classdb(const StringName &p_class, List<PropertyInfo> *p_list, bool p_no_inheritance, const Object *p_validator) {
1908 ClassDB::get_property_list(p_class, p_list, p_no_inheritance, p_validator);
1909 }
1910
1911 #ifdef TOOLS_ENABLED
1912 void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded, bool p_initializing) {
1913 if (!p_initializing) {
1914 set_edited(true);
1915 }
1916
1917 if (p_unfolded) {
1918 editor_section_folding.insert(p_section);
1919 } else {
1920 editor_section_folding.erase(p_section);
1921 }
1922 }
1923
1924 bool Object::editor_is_section_unfolded(const String &p_section) {
1925 return editor_section_folding.has(p_section);
1926 }
1927
1928 #endif
1929
1930 void Object::clear_internal_resource_paths() {
1931 List<PropertyInfo> pinfo;
1932
1933 get_property_list(&pinfo);
1934
1935 for (const PropertyInfo &E : pinfo) {
1936 _clear_internal_resource_paths(get(E.name));
1937 }
1938 }
1939
1940 void Object::notify_property_list_changed() {
1941 emit_signal(CoreStringName(property_list_changed));
1942 }
1943
1944 String Object::_to_string() {
1945 return "<" + get_class() + "#" + itos(get_instance_id()) + ">";
1946 }
1947
1948 void Object::_bind_methods() {
1949 ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class);
1950 ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class);
1951 ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind);
1952 ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind);
1953 ClassDB::bind_method(D_METHOD("set_indexed", "property_path", "value"), &Object::_set_indexed_bind);
1954 ClassDB::bind_method(D_METHOD("get_indexed", "property_path"), &Object::_get_indexed_bind);
1955 ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind);
1956 ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind);
1957 ClassDB::bind_method(D_METHOD("property_can_revert", "property"), &Object::property_can_revert);
1958 ClassDB::bind_method(D_METHOD("property_get_revert", "property"), &Object::property_get_revert);
1959 ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false));
1960 ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string);
1961 ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id);
1962
1963 ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script);
1964 ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script);
1965
1966 ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta);
1967 ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta);
1968 ClassDB::bind_method(D_METHOD("get_meta", "name", "default"), &Object::get_meta, DEFVAL(Variant()));
1969 ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta);
1970 ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind);
1971
1972 ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array()));
1973 ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal);
1974 ClassDB::bind_method(D_METHOD("remove_user_signal", "signal"), &Object::_remove_user_signal);
1975
1976 {
1977 MethodInfo mi;
1978 mi.name = "emit_signal";
1979 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal"));
1980
1981 ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false);
1982 }
1983
1984 {
1985 MethodInfo mi;
1986 mi.name = "call";
1987 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
1988
1989 ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi);
1990 }
1991
1992 {
1993 MethodInfo mi;
1994 mi.name = "call_deferred";
1995 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
1996
1997 ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false);
1998 }
1999
2000 ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred);
2001
2002 ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv);
2003
2004 ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method);
2005
2006 ClassDB::bind_method(D_METHOD("get_method_argument_count", "method"), &Object::_get_method_argument_count_bind);
2007
2008 ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal);
2009 ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list);
2010 ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list);
2011 ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections);
2012
2013 ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "flags"), &Object::connect, DEFVAL(0));
2014 ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect);
2015 ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected);
2016 ClassDB::bind_method(D_METHOD("has_connections", "signal"), &Object::has_connections);
2017
2018 ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals);
2019 ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals);
2020 ClassDB::bind_method(D_METHOD("notify_property_list_changed"), &Object::notify_property_list_changed);
2021
2022 ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation);
2023 ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages);
2024 ClassDB::bind_method(D_METHOD("tr", "message", "context"), &Object::tr, DEFVAL(StringName()));
2025 ClassDB::bind_method(D_METHOD("tr_n", "message", "plural_message", "n", "context"), &Object::tr_n, DEFVAL(StringName()));
2026 ClassDB::bind_method(D_METHOD("get_translation_domain"), &Object::get_translation_domain);
2027 ClassDB::bind_method(D_METHOD("set_translation_domain", "domain"), &Object::set_translation_domain);
2028
2029 ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion);
2030 ClassDB::bind_method(D_METHOD("cancel_free"), &Object::cancel_free);
2031
2032 ClassDB::add_virtual_method("Object", MethodInfo("free"), false);
2033
2034 ADD_SIGNAL(MethodInfo("script_changed"));
2035 ADD_SIGNAL(MethodInfo("property_list_changed"));
2036
2037 #define BIND_OBJ_CORE_METHOD(m_method) \
2038 ::ClassDB::add_virtual_method(get_class_static(), m_method, true, Vector<String>(), true);
2039
2040 BIND_OBJ_CORE_METHOD(MethodInfo("_init"));
2041
2042 BIND_OBJ_CORE_METHOD(MethodInfo(Variant::STRING, "_to_string"));
2043
2044 {
2045 MethodInfo mi("_notification");
2046 mi.arguments.push_back(PropertyInfo(Variant::INT, "what"));
2047 mi.arguments_metadata.push_back(GodotTypeInfo::Metadata::METADATA_INT_IS_INT32);
2048 BIND_OBJ_CORE_METHOD(mi);
2049 }
2050
2051 {
2052 MethodInfo mi("_set");
2053 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
2054 mi.arguments.push_back(PropertyInfo(Variant::NIL, "value", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
2055 mi.return_val.type = Variant::BOOL;
2056 BIND_OBJ_CORE_METHOD(mi);
2057 }
2058
2059 #ifdef TOOLS_ENABLED
2060 {
2061 MethodInfo mi("_get");
2062 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
2063 mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
2064 BIND_OBJ_CORE_METHOD(mi);
2065 }
2066
2067 {
2068 MethodInfo mi("_get_property_list");
2069 mi.return_val.type = Variant::ARRAY;
2070 mi.return_val.hint = PROPERTY_HINT_ARRAY_TYPE;
2071 mi.return_val.hint_string = "Dictionary";
2072 BIND_OBJ_CORE_METHOD(mi);
2073 }
2074
2075 BIND_OBJ_CORE_METHOD(MethodInfo(Variant::NIL, "_validate_property", PropertyInfo(Variant::DICTIONARY, "property")));
2076
2077 BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_property_can_revert", PropertyInfo(Variant::STRING_NAME, "property")));
2078
2079 {
2080 MethodInfo mi("_property_get_revert");
2081 mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "property"));
2082 mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
2083 BIND_OBJ_CORE_METHOD(mi);
2084 }
2085
2086 // These are actually `Variant` methods, but that doesn't matter since scripts can't inherit built-in types.
2087
2088 BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_iter_init", PropertyInfo(Variant::ARRAY, "iter")));
2089
2090 BIND_OBJ_CORE_METHOD(MethodInfo(Variant::BOOL, "_iter_next", PropertyInfo(Variant::ARRAY, "iter")));
2091
2092 {
2093 MethodInfo mi("_iter_get");
2094 mi.arguments.push_back(PropertyInfo(Variant::NIL, "iter", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_NIL_IS_VARIANT));
2095 mi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
2096 BIND_OBJ_CORE_METHOD(mi);
2097 }
2098 #endif
2099
2100 BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE);
2101 BIND_CONSTANT(NOTIFICATION_PREDELETE);
2102 BIND_CONSTANT(NOTIFICATION_EXTENSION_RELOADED);
2103
2104 BIND_ENUM_CONSTANT(CONNECT_DEFERRED);
2105 BIND_ENUM_CONSTANT(CONNECT_PERSIST);
2106 BIND_ENUM_CONSTANT(CONNECT_ONE_SHOT);
2107 BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED);
2108 BIND_ENUM_CONSTANT(CONNECT_APPEND_SOURCE_OBJECT);
2109 }
2110
2111 void Object::set_deferred(const StringName &p_property, const Variant &p_value) {
2112 MessageQueue::get_singleton()->push_set(this, p_property, p_value);
2113 }
2114
2115 void Object::set_block_signals(bool p_block) {
2116 _block_signals = p_block;
2117 }
2118
2119 bool Object::is_blocking_signals() const {
2120 return _block_signals;
2121 }
2122
2123 Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const {
2124 bool valid;
2125 Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid);
2126 if (valid) {
2127 if (r_valid) {
2128 *r_valid = true;
2129 }
2130 return t;
2131 }
2132
2133 if (get_script_instance()) {
2134 return get_script_instance()->get_property_type(p_property, r_valid);
2135 }
2136 if (r_valid) {
2137 *r_valid = false;
2138 }
2139
2140 return Variant::NIL;
2141 }
2142
2143 Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const {
2144 if (p_path.is_empty()) {
2145 if (r_valid) {
2146 *r_valid = false;
2147 }
2148
2149 return Variant::NIL;
2150 }
2151
2152 bool valid = false;
2153 Variant::Type t = get_static_property_type(p_path[0], &valid);
2154 if (!valid) {
2155 if (r_valid) {
2156 *r_valid = false;
2157 }
2158
2159 return Variant::NIL;
2160 }
2161
2162 Callable::CallError ce;
2163 Variant check;
2164 Variant::construct(t, check, nullptr, 0, ce);
2165
2166 for (int i = 1; i < p_path.size(); i++) {
2167 if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) {
2168 // We cannot be sure about the type of properties this type can have
2169 if (r_valid) {
2170 *r_valid = false;
2171 }
2172 return Variant::NIL;
2173 }
2174
2175 check = check.get_named(p_path[i], valid);
2176
2177 if (!valid) {
2178 if (r_valid) {
2179 *r_valid = false;
2180 }
2181 return Variant::NIL;
2182 }
2183 }
2184
2185 if (r_valid) {
2186 *r_valid = true;
2187 }
2188
2189 return check.get_type();
2190 }
2191
2192 bool Object::is_queued_for_deletion() const {
2193 return _is_queued_for_deletion;
2194 }
2195
2196 #ifdef TOOLS_ENABLED
2197 void Object::set_edited(bool p_edited) {
2198 _edited = p_edited;
2199 _edited_version++;
2200 }
2201
2202 bool Object::is_edited() const {
2203 return _edited;
2204 }
2205
2206 uint32_t Object::get_edited_version() const {
2207 return _edited_version;
2208 }
2209 #endif
2210
2211 const GDType &Object::get_gdtype() const {
2212 if (unlikely(!_gdtype_ptr)) {
2213 // While class is initializing / deinitializing, constructors and destructors
2214 // need access to the proper type at the proper stage.
2215 return _get_typev();
2216 }
2217 return *_gdtype_ptr;
2218 }
2219
2220 bool Object::is_class(const String &p_class) const {
2221 for (const StringName &name : get_gdtype().get_name_hierarchy()) {
2222 if (name == p_class) {
2223 return true;
2224 }
2225 }
2226 return false;
2227 }
2228
2229 const StringName &Object::get_class_name() const {
2230 return get_gdtype().get_name();
2231 }
2232
2233 StringName Object::get_class_name_for_extension(const GDExtension *p_library) const {
2234 #ifdef TOOLS_ENABLED
2235 // If this is the library this extension comes from and it's a placeholder, we
2236 // have to return the closest native parent's class name, so that it doesn't try to
2237 // use this like the real object.
2238 if (unlikely(_extension && _extension->library == p_library && _extension->is_placeholder)) {
2239 return get_class_name();
2240 }
2241 #endif
2242
2243 // Only return the class name per the extension if it matches the given p_library.
2244 if (_extension && _extension->library == p_library) {
2245 return _extension->class_name;
2246 }
2247
2248 // Extensions only have wrapper classes for classes exposed in ClassDB.
2249 const StringName &class_name = get_class_name();
2250 if (ClassDB::is_class_exposed(class_name)) {
2251 return class_name;
2252 }
2253
2254 // Find the nearest parent class that's exposed.
2255 StringName parent_class = ClassDB::get_parent_class(class_name);
2256 while (parent_class != StringName()) {
2257 if (ClassDB::is_class_exposed(parent_class)) {
2258 return parent_class;
2259 }
2260 parent_class = ClassDB::get_parent_class(parent_class);
2261 }
2262
2263 return SNAME("Object");
2264 }
2265
2266 void Object::set_instance_binding(void *p_token, void *p_binding, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
2267 // This is only meant to be used on creation by the binder, but we also
2268 // need to account for reloading (where the 'binding' will be cleared).
2269 ERR_FAIL_COND(_instance_bindings != nullptr && _instance_bindings[0].binding != nullptr);
2270 if (_instance_bindings == nullptr) {
2271 _instance_bindings = (InstanceBinding *)memalloc(sizeof(InstanceBinding));
2272 _instance_binding_count = 1;
2273 }
2274 _instance_bindings[0].binding = p_binding;
2275 _instance_bindings[0].free_callback = p_callbacks->free_callback;
2276 _instance_bindings[0].reference_callback = p_callbacks->reference_callback;
2277 _instance_bindings[0].token = p_token;
2278 }
2279
2280 void *Object::get_instance_binding(void *p_token, const GDExtensionInstanceBindingCallbacks *p_callbacks) {
2281 void *binding = nullptr;
2282 MutexLock instance_binding_lock(_instance_binding_mutex);
2283 for (uint32_t i = 0; i < _instance_binding_count; i++) {
2284 if (_instance_bindings[i].token == p_token) {
2285 binding = _instance_bindings[i].binding;
2286 break;
2287 }
2288 }
2289 if (unlikely(!binding && p_callbacks)) {
2290 uint32_t current_size = next_power_of_2(_instance_binding_count);
2291 uint32_t new_size = next_power_of_2(_instance_binding_count + 1);
2292
2293 if (current_size == 0 || new_size > current_size) {
2294 _instance_bindings = (InstanceBinding *)memrealloc(_instance_bindings, new_size * sizeof(InstanceBinding));
2295 }
2296
2297 _instance_bindings[_instance_binding_count].free_callback = p_callbacks->free_callback;
2298 _instance_bindings[_instance_binding_count].reference_callback = p_callbacks->reference_callback;
2299 _instance_bindings[_instance_binding_count].token = p_token;
2300
2301 binding = p_callbacks->create_callback(p_token, this);
2302 _instance_bindings[_instance_binding_count].binding = binding;
2303
2304 #ifdef TOOLS_ENABLED
2305 if (!_extension && Engine::get_singleton()->is_extension_reloading_enabled()) {
2306 GDExtensionManager::get_singleton()->track_instance_binding(p_token, this);
2307 }
2308 #endif
2309
2310 _instance_binding_count++;
2311 }
2312
2313 return binding;
2314 }
2315
2316 bool Object::has_instance_binding(void *p_token) {
2317 bool found = false;
2318 MutexLock instance_binding_lock(_instance_binding_mutex);
2319 for (uint32_t i = 0; i < _instance_binding_count; i++) {
2320 if (_instance_bindings[i].token == p_token) {
2321 found = true;
2322 break;
2323 }
2324 }
2325
2326 return found;
2327 }
2328
2329 void Object::free_instance_binding(void *p_token) {
2330 bool found = false;
2331 MutexLock instance_binding_lock(_instance_binding_mutex);
2332 for (uint32_t i = 0; i < _instance_binding_count; i++) {
2333 if (!found && _instance_bindings[i].token == p_token) {
2334 if (_instance_bindings[i].free_callback) {
2335 _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
2336 }
2337 found = true;
2338 }
2339 if (found) {
2340 if (i + 1 < _instance_binding_count) {
2341 _instance_bindings[i] = _instance_bindings[i + 1];
2342 } else {
2343 _instance_bindings[i] = { nullptr };
2344 }
2345 }
2346 }
2347 if (found) {
2348 _instance_binding_count--;
2349 }
2350 }
2351
2352 #ifdef TOOLS_ENABLED
2353 void Object::clear_internal_extension() {
2354 ERR_FAIL_NULL(_extension);
2355
2356 // Free the instance inside the GDExtension.
2357 if (_extension->free_instance) {
2358 _extension->free_instance(_extension->class_userdata, _extension_instance);
2359 }
2360 _extension = nullptr;
2361 _extension_instance = nullptr;
2362 // Reset GDType to internal type.
2363 _gdtype_ptr = &_get_typev();
2364
2365 // Clear the instance bindings.
2366 _instance_binding_mutex.lock();
2367 if (_instance_bindings) {
2368 if (_instance_bindings[0].free_callback) {
2369 _instance_bindings[0].free_callback(_instance_bindings[0].token, this, _instance_bindings[0].binding);
2370 }
2371 _instance_bindings[0].binding = nullptr;
2372 _instance_bindings[0].token = nullptr;
2373 _instance_bindings[0].free_callback = nullptr;
2374 _instance_bindings[0].reference_callback = nullptr;
2375 }
2376 _instance_binding_mutex.unlock();
2377
2378 // Clear the virtual methods.
2379 while (virtual_method_list) {
2380 (*virtual_method_list->method) = nullptr;
2381 virtual_method_list = virtual_method_list->next;
2382 }
2383 }
2384
2385 void Object::reset_internal_extension(ObjectGDExtension *p_extension) {
2386 ERR_FAIL_COND(_extension != nullptr);
2387
2388 if (p_extension) {
2389 _extension_instance = p_extension->recreate_instance ? p_extension->recreate_instance(p_extension->class_userdata, (GDExtensionObjectPtr)this) : nullptr;
2390 ERR_FAIL_NULL_MSG(_extension_instance, "Unable to recreate GDExtension instance - does this extension support hot reloading?");
2391 _extension = p_extension;
2392 _gdtype_ptr = p_extension->gdtype;
2393 }
2394 }
2395 #endif
2396
2397 void Object::_construct_object(bool p_reference) {
2398 _block_signals = false;
2399 _can_translate = true;
2400 _emitting = false;
2401 _is_queued_for_deletion = false;
2402 _predelete_ok = false;
2403
2404 // ObjectDB::add_instance relies on AncestralClass::REF_COUNTED
2405 // being already set in the case of references.
2406 _ancestry = p_reference ? (uint32_t)AncestralClass::REF_COUNTED : 0;
2407
2408 _instance_id = ObjectDB::add_instance(this);
2409
2410 #ifdef TOOLS_ENABLED
2411 _edited = false;
2412 #endif
2413
2414 #ifdef DEBUG_ENABLED
2415 _lock_index.init(1);
2416 #endif
2417 }
2418
2419 Object::Object(bool p_reference) {
2420 _construct_object(p_reference);
2421 }
2422
2423 Object::Object() {
2424 _construct_object(false);
2425 }
2426
2427 void Object::detach_from_objectdb() {
2428 if (_instance_id != ObjectID()) {
2429 ObjectDB::remove_instance(this);
2430 _instance_id = ObjectID();
2431 }
2432 }
2433
2434 void Object::assign_type_static(GDType **type_ptr, const char *p_name, const GDType *super_type) {
2435 static BinaryMutex _mutex;
2436 MutexLock lock(_mutex);
2437 GDType *type = *type_ptr;
2438 if (type) {
2439 // Assigned while we were waiting.
2440 return;
2441 }
2442 type = memnew(GDType(super_type, StringName(p_name)));
2443 *type_ptr = type;
2444
2445 ClassDB::gdtype_autorelease_pool.push_back(type_ptr);
2446 }
2447
2448 Object::~Object() {
2449 if (_emitting) {
2450 //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before
2451 ERR_PRINT(vformat("Object '%s' was freed or unreferenced while a signal is being emitted from it. Try connecting to the signal using 'CONNECT_DEFERRED' flag, or use queue_free() to free the object (if this object is a Node) to avoid this error and potential crashes.", to_string()));
2452 }
2453
2454 // Drop all connections to the signals of this object.
2455 while (signal_map.size()) {
2456 // Avoid regular iteration so erasing is safe.
2457 KeyValue<StringName, SignalData> &E = *signal_map.begin();
2458 SignalData *s = &E.value;
2459
2460 for (const KeyValue<Callable, SignalData::Slot> &slot_kv : s->slot_map) {
2461 Object *target = slot_kv.value.conn.callable.get_object();
2462 if (likely(target)) {
2463 ObjectSignalLock signal_lock(this, target);
2464 target->connections.erase(slot_kv.value.cE);
2465 }
2466 }
2467
2468 signal_map.erase(E.key);
2469 }
2470
2471 // Disconnect signals that connect to this object.
2472 while (connections.size()) {
2473 Connection c = connections.front()->get();
2474 bool disconnected = c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true);
2475 if (unlikely(!disconnected)) {
2476 // If the disconnect has failed, abandon the connection to avoid getting trapped in an infinite loop here.
2477 connections.pop_front();
2478 }
2479 }
2480
2481 if (_instance_id != ObjectID()) {
2482 ObjectDB::remove_instance(this);
2483 _instance_id = ObjectID();
2484 }
2485 _predelete_ok = true;
2486
2487 if (_instance_bindings != nullptr) {
2488 for (uint32_t i = 0; i < _instance_binding_count; i++) {
2489 if (_instance_bindings[i].free_callback) {
2490 _instance_bindings[i].free_callback(_instance_bindings[i].token, this, _instance_bindings[i].binding);
2491 }
2492 }
2493 memfree(_instance_bindings);
2494 }
2495
2496 if (signal_mutex) {
2497 memdelete(signal_mutex);
2498 }
2499 }
2500
2501 bool predelete_handler(Object *p_object) {
2502 return p_object->_predelete();
2503 }
2504
2505 void postinitialize_handler(Object *p_object) {
2506 p_object->_initialize();
2507 p_object->_postinitialize();
2508 }
2509
2510 void ObjectDB::debug_objects(DebugFunc p_func, void *p_user_data) {
2511 spin_lock.lock();
2512
2513 for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
2514 if (object_slots[i].validator) {
2515 p_func(object_slots[i].object, p_user_data);
2516 count--;
2517 }
2518 }
2519 spin_lock.unlock();
2520 }
2521
2522 #ifdef TOOLS_ENABLED
2523 void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
2524 const String pf = p_function;
2525 if (p_idx == 0) {
2526 if (pf == "connect" || pf == "is_connected" || pf == "disconnect" || pf == "emit_signal" || pf == "has_signal") {
2527 List<MethodInfo> signals;
2528 get_signal_list(&signals);
2529 for (const MethodInfo &E : signals) {
2530 r_options->push_back(E.name.quote());
2531 }
2532 } else if (pf == "call" || pf == "call_deferred" || pf == "callv" || pf == "has_method") {
2533 List<MethodInfo> methods;
2534 get_method_list(&methods);
2535 for (const MethodInfo &E : methods) {
2536 if (E.name.begins_with("_") && !(E.flags & METHOD_FLAG_VIRTUAL)) {
2537 continue;
2538 }
2539 r_options->push_back(E.name.quote());
2540 }
2541 } else if (pf == "set" || pf == "set_deferred" || pf == "get") {
2542 List<PropertyInfo> properties;
2543 get_property_list(&properties);
2544 for (const PropertyInfo &E : properties) {
2545 if (E.usage & PROPERTY_USAGE_DEFAULT && !(E.usage & PROPERTY_USAGE_INTERNAL)) {
2546 r_options->push_back(E.name.quote());
2547 }
2548 }
2549 } else if (pf == "set_meta" || pf == "get_meta" || pf == "has_meta" || pf == "remove_meta") {
2550 for (const KeyValue<StringName, Variant> &K : metadata) {
2551 r_options->push_back(String(K.key).quote());
2552 }
2553 }
2554 } else if (p_idx == 2) {
2555 if (pf == "connect") {
2556 // Ideally, the constants should be inferred by the parameter.
2557 // But a parameter's PropertyInfo does not store the enum they come from, so this will do for now.
2558 List<StringName> constants;
2559 ClassDB::get_enum_constants("Object", "ConnectFlags", &constants);
2560 for (const StringName &E : constants) {
2561 r_options->push_back(String(E));
2562 }
2563 }
2564 }
2565 }
2566 #endif
2567
2568 SpinLock ObjectDB::spin_lock;
2569 uint32_t ObjectDB::slot_count = 0;
2570 uint32_t ObjectDB::slot_max = 0;
2571 ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr;
2572 uint64_t ObjectDB::validator_counter = 0;
2573
2574 int ObjectDB::get_object_count() {
2575 return slot_count;
2576 }
2577
2578 ObjectID ObjectDB::add_instance(Object *p_object) {
2579 spin_lock.lock();
2580 if (unlikely(slot_count == slot_max)) {
2581 CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS));
2582
2583 uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1;
2584 object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max);
2585 for (uint32_t i = slot_max; i < new_slot_max; i++) {
2586 object_slots[i].object = nullptr;
2587 object_slots[i].is_ref_counted = false;
2588 object_slots[i].next_free = i;
2589 object_slots[i].validator = 0;
2590 }
2591 slot_max = new_slot_max;
2592 }
2593
2594 uint32_t slot = object_slots[slot_count].next_free;
2595 if (object_slots[slot].object != nullptr) {
2596 spin_lock.unlock();
2597 ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID());
2598 }
2599 object_slots[slot].object = p_object;
2600 object_slots[slot].is_ref_counted = p_object->is_ref_counted();
2601 validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK;
2602 if (unlikely(validator_counter == 0)) {
2603 validator_counter = 1;
2604 }
2605 object_slots[slot].validator = validator_counter;
2606
2607 uint64_t id = validator_counter;
2608 id <<= OBJECTDB_SLOT_MAX_COUNT_BITS;
2609 id |= uint64_t(slot);
2610
2611 if (p_object->is_ref_counted()) {
2612 id |= OBJECTDB_REFERENCE_BIT;
2613 }
2614
2615 slot_count++;
2616
2617 spin_lock.unlock();
2618
2619 return ObjectID(id);
2620 }
2621
2622 void ObjectDB::remove_instance(Object *p_object) {
2623 uint64_t t = p_object->get_instance_id();
2624 uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object
2625
2626 spin_lock.lock();
2627
2628 #ifdef DEBUG_ENABLED
2629
2630 if (object_slots[slot].object != p_object) {
2631 spin_lock.unlock();
2632 ERR_FAIL_COND(object_slots[slot].object != p_object);
2633 }
2634 {
2635 uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK;
2636 if (object_slots[slot].validator != validator) {
2637 spin_lock.unlock();
2638 ERR_FAIL_COND(object_slots[slot].validator != validator);
2639 }
2640 }
2641
2642 #endif
2643 //decrease slot count
2644 slot_count--;
2645 //set the free slot properly
2646 object_slots[slot_count].next_free = slot;
2647 //invalidate, so checks against it fail
2648 object_slots[slot].validator = 0;
2649 object_slots[slot].is_ref_counted = false;
2650 object_slots[slot].object = nullptr;
2651
2652 spin_lock.unlock();
2653 }
2654
2655 void ObjectDB::setup() {
2656 //nothing to do now
2657 }
2658
2659 void ObjectDB::cleanup() {
2660 spin_lock.lock();
2661
2662 if (slot_count > 0) {
2663 WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details).");
2664 if (OS::get_singleton()->is_stdout_verbose()) {
2665 // Ensure calling the native classes because if a leaked instance has a script
2666 // that overrides any of those methods, it'd not be OK to call them at this point,
2667 // now the scripting languages have already been terminated.
2668 MethodBind *node_get_path = ClassDB::get_method("Node", "get_path");
2669 MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path");
2670 Callable::CallError call_error;
2671
2672 for (uint32_t i = 0, count = slot_count; i < slot_max && count != 0; i++) {
2673 if (object_slots[i].validator) {
2674 Object *obj = object_slots[i].object;
2675
2676 String extra_info;
2677 if (obj->is_class("Node")) {
2678 extra_info = " - Node path: " + String(node_get_path->call(obj, nullptr, 0, call_error));
2679 }
2680 if (obj->is_class("Resource")) {
2681 extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error));
2682 }
2683 if (obj->is_class("RefCounted")) {
2684 extra_info = " - Reference count: " + itos((static_cast<RefCounted *>(obj))->get_reference_count());
2685 }
2686
2687 uint64_t id = uint64_t(i) | (uint64_t(object_slots[i].validator) << OBJECTDB_SLOT_MAX_COUNT_BITS) | (object_slots[i].is_ref_counted ? OBJECTDB_REFERENCE_BIT : 0);
2688 DEV_ASSERT(id == (uint64_t)obj->get_instance_id()); // We could just use the id from the object, but this check may help catching memory corruption catastrophes.
2689 print_line("Leaked instance: " + String(obj->get_class()) + ":" + uitos(id) + extra_info);
2690
2691 count--;
2692 }
2693 }
2694 print_line("Hint: Leaked instances typically happen when nodes are removed from the scene tree (with `remove_child()`) but not freed (with `free()` or `queue_free()`).");
2695 }
2696 }
2697
2698 if (object_slots) {
2699 memfree(object_slots);
2700 }
2701
2702 spin_lock.unlock();
2703 }