object.cpp 73 KB

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