object.cpp 76 KB

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