scene_tree.cpp 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  1. /**************************************************************************/
  2. /* scene_tree.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 "scene_tree.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/input/input.h"
  34. #include "core/io/dir_access.h"
  35. #include "core/io/image_loader.h"
  36. #include "core/io/marshalls.h"
  37. #include "core/io/resource_loader.h"
  38. #include "core/object/message_queue.h"
  39. #include "core/object/worker_thread_pool.h"
  40. #include "core/os/keyboard.h"
  41. #include "core/os/os.h"
  42. #include "core/string/print_string.h"
  43. #include "node.h"
  44. #include "scene/animation/tween.h"
  45. #include "scene/debugger/scene_debugger.h"
  46. #include "scene/gui/control.h"
  47. #include "scene/main/multiplayer_api.h"
  48. #include "scene/main/viewport.h"
  49. #include "scene/resources/environment.h"
  50. #include "scene/resources/font.h"
  51. #include "scene/resources/image_texture.h"
  52. #include "scene/resources/material.h"
  53. #include "scene/resources/mesh.h"
  54. #include "scene/resources/packed_scene.h"
  55. #include "scene/resources/world_2d.h"
  56. #include "servers/display_server.h"
  57. #include "servers/navigation_server_3d.h"
  58. #include "servers/physics_server_2d.h"
  59. #ifndef _3D_DISABLED
  60. #include "scene/3d/node_3d.h"
  61. #include "scene/resources/3d/world_3d.h"
  62. #include "servers/physics_server_3d.h"
  63. #endif // _3D_DISABLED
  64. #include "window.h"
  65. #include <stdio.h>
  66. #include <stdlib.h>
  67. void SceneTreeTimer::_bind_methods() {
  68. ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left);
  69. ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left);
  70. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_left", PROPERTY_HINT_NONE, "suffix:s"), "set_time_left", "get_time_left");
  71. ADD_SIGNAL(MethodInfo("timeout"));
  72. }
  73. void SceneTreeTimer::set_time_left(double p_time) {
  74. time_left = p_time;
  75. }
  76. double SceneTreeTimer::get_time_left() const {
  77. return MAX(time_left, 0.0);
  78. }
  79. void SceneTreeTimer::set_process_always(bool p_process_always) {
  80. process_always = p_process_always;
  81. }
  82. bool SceneTreeTimer::is_process_always() {
  83. return process_always;
  84. }
  85. void SceneTreeTimer::set_process_in_physics(bool p_process_in_physics) {
  86. process_in_physics = p_process_in_physics;
  87. }
  88. bool SceneTreeTimer::is_process_in_physics() {
  89. return process_in_physics;
  90. }
  91. void SceneTreeTimer::set_ignore_time_scale(bool p_ignore) {
  92. ignore_time_scale = p_ignore;
  93. }
  94. bool SceneTreeTimer::is_ignore_time_scale() {
  95. return ignore_time_scale;
  96. }
  97. void SceneTreeTimer::release_connections() {
  98. List<Connection> signal_connections;
  99. get_all_signal_connections(&signal_connections);
  100. for (const Connection &connection : signal_connections) {
  101. disconnect(connection.signal.get_name(), connection.callable);
  102. }
  103. }
  104. SceneTreeTimer::SceneTreeTimer() {}
  105. #ifndef _3D_DISABLED
  106. // This should be called once per physics tick, to make sure the transform previous and current
  107. // is kept up to date on the few Node3Ds that are using client side physics interpolation.
  108. void SceneTree::ClientPhysicsInterpolation::physics_process() {
  109. for (SelfList<Node3D> *E = _node_3d_list.first(); E;) {
  110. Node3D *node_3d = E->self();
  111. SelfList<Node3D> *current = E;
  112. // Get the next element here BEFORE we potentially delete one.
  113. E = E->next();
  114. // This will return false if the Node3D has timed out ..
  115. // i.e. if get_global_transform_interpolated() has not been called
  116. // for a few seconds, we can delete from the list to keep processing
  117. // to a minimum.
  118. if (!node_3d->update_client_physics_interpolation_data()) {
  119. _node_3d_list.remove(current);
  120. }
  121. }
  122. }
  123. #endif
  124. void SceneTree::tree_changed() {
  125. emit_signal(tree_changed_name);
  126. }
  127. void SceneTree::node_added(Node *p_node) {
  128. emit_signal(node_added_name, p_node);
  129. }
  130. void SceneTree::node_removed(Node *p_node) {
  131. // Nodes can only be removed from the main thread.
  132. if (current_scene == p_node) {
  133. current_scene = nullptr;
  134. }
  135. emit_signal(node_removed_name, p_node);
  136. if (nodes_removed_on_group_call_lock) {
  137. nodes_removed_on_group_call.insert(p_node);
  138. }
  139. }
  140. void SceneTree::node_renamed(Node *p_node) {
  141. emit_signal(node_renamed_name, p_node);
  142. }
  143. SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) {
  144. _THREAD_SAFE_METHOD_
  145. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  146. if (!E) {
  147. E = group_map.insert(p_group, Group());
  148. }
  149. ERR_FAIL_COND_V_MSG(E->value.nodes.has(p_node), &E->value, "Already in group: " + p_group + ".");
  150. E->value.nodes.push_back(p_node);
  151. E->value.changed = true;
  152. return &E->value;
  153. }
  154. void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) {
  155. _THREAD_SAFE_METHOD_
  156. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  157. ERR_FAIL_COND(!E);
  158. E->value.nodes.erase(p_node);
  159. if (E->value.nodes.is_empty()) {
  160. group_map.remove(E);
  161. }
  162. }
  163. void SceneTree::make_group_changed(const StringName &p_group) {
  164. _THREAD_SAFE_METHOD_
  165. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  166. if (E) {
  167. E->value.changed = true;
  168. }
  169. }
  170. void SceneTree::flush_transform_notifications() {
  171. _THREAD_SAFE_METHOD_
  172. SelfList<Node> *n = xform_change_list.first();
  173. while (n) {
  174. Node *node = n->self();
  175. SelfList<Node> *nx = n->next();
  176. xform_change_list.remove(n);
  177. n = nx;
  178. node->notification(NOTIFICATION_TRANSFORM_CHANGED);
  179. }
  180. }
  181. void SceneTree::_flush_ugc() {
  182. ugc_locked = true;
  183. while (unique_group_calls.size()) {
  184. HashMap<UGCall, Vector<Variant>, UGCall>::Iterator E = unique_group_calls.begin();
  185. const Variant **argptrs = (const Variant **)alloca(E->value.size() * sizeof(Variant *));
  186. for (int i = 0; i < E->value.size(); i++) {
  187. argptrs[i] = &E->value[i];
  188. }
  189. call_group_flagsp(GROUP_CALL_DEFAULT, E->key.group, E->key.call, argptrs, E->value.size());
  190. unique_group_calls.remove(E);
  191. }
  192. ugc_locked = false;
  193. }
  194. void SceneTree::_update_group_order(Group &g) {
  195. if (!g.changed) {
  196. return;
  197. }
  198. if (g.nodes.is_empty()) {
  199. return;
  200. }
  201. Node **gr_nodes = g.nodes.ptrw();
  202. int gr_node_count = g.nodes.size();
  203. SortArray<Node *, Node::Comparator> node_sort;
  204. node_sort.sort(gr_nodes, gr_node_count);
  205. g.changed = false;
  206. }
  207. void SceneTree::call_group_flagsp(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, const Variant **p_args, int p_argcount) {
  208. Vector<Node *> nodes_copy;
  209. {
  210. _THREAD_SAFE_METHOD_
  211. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  212. if (!E) {
  213. return;
  214. }
  215. Group &g = E->value;
  216. if (g.nodes.is_empty()) {
  217. return;
  218. }
  219. if (p_call_flags & GROUP_CALL_UNIQUE && p_call_flags & GROUP_CALL_DEFERRED) {
  220. ERR_FAIL_COND(ugc_locked);
  221. UGCall ug;
  222. ug.call = p_function;
  223. ug.group = p_group;
  224. if (unique_group_calls.has(ug)) {
  225. return;
  226. }
  227. Vector<Variant> args;
  228. for (int i = 0; i < p_argcount; i++) {
  229. args.push_back(*p_args[i]);
  230. }
  231. unique_group_calls[ug] = args;
  232. return;
  233. }
  234. _update_group_order(g);
  235. nodes_copy = g.nodes;
  236. }
  237. Node **gr_nodes = nodes_copy.ptrw();
  238. int gr_node_count = nodes_copy.size();
  239. {
  240. _THREAD_SAFE_METHOD_
  241. nodes_removed_on_group_call_lock++;
  242. }
  243. if (p_call_flags & GROUP_CALL_REVERSE) {
  244. for (int i = gr_node_count - 1; i >= 0; i--) {
  245. if (nodes_removed_on_group_call_lock && nodes_removed_on_group_call.has(gr_nodes[i])) {
  246. continue;
  247. }
  248. Node *node = gr_nodes[i];
  249. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  250. Callable::CallError ce;
  251. node->callp(p_function, p_args, p_argcount, ce);
  252. if (unlikely(ce.error != Callable::CallError::CALL_OK && ce.error != Callable::CallError::CALL_ERROR_INVALID_METHOD)) {
  253. ERR_PRINT(vformat("Error calling group method on node \"%s\": %s.", node->get_name(), Variant::get_callable_error_text(Callable(node, p_function), p_args, p_argcount, ce)));
  254. }
  255. } else {
  256. MessageQueue::get_singleton()->push_callp(node, p_function, p_args, p_argcount);
  257. }
  258. }
  259. } else {
  260. for (int i = 0; i < gr_node_count; i++) {
  261. if (nodes_removed_on_group_call_lock && nodes_removed_on_group_call.has(gr_nodes[i])) {
  262. continue;
  263. }
  264. Node *node = gr_nodes[i];
  265. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  266. Callable::CallError ce;
  267. node->callp(p_function, p_args, p_argcount, ce);
  268. if (unlikely(ce.error != Callable::CallError::CALL_OK && ce.error != Callable::CallError::CALL_ERROR_INVALID_METHOD)) {
  269. ERR_PRINT(vformat("Error calling group method on node \"%s\": %s.", node->get_name(), Variant::get_callable_error_text(Callable(node, p_function), p_args, p_argcount, ce)));
  270. }
  271. } else {
  272. MessageQueue::get_singleton()->push_callp(node, p_function, p_args, p_argcount);
  273. }
  274. }
  275. }
  276. {
  277. _THREAD_SAFE_METHOD_
  278. nodes_removed_on_group_call_lock--;
  279. if (nodes_removed_on_group_call_lock == 0) {
  280. nodes_removed_on_group_call.clear();
  281. }
  282. }
  283. }
  284. void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) {
  285. Vector<Node *> nodes_copy;
  286. {
  287. _THREAD_SAFE_METHOD_
  288. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  289. if (!E) {
  290. return;
  291. }
  292. Group &g = E->value;
  293. if (g.nodes.is_empty()) {
  294. return;
  295. }
  296. _update_group_order(g);
  297. nodes_copy = g.nodes;
  298. }
  299. Node **gr_nodes = nodes_copy.ptrw();
  300. int gr_node_count = nodes_copy.size();
  301. {
  302. _THREAD_SAFE_METHOD_
  303. nodes_removed_on_group_call_lock++;
  304. }
  305. if (p_call_flags & GROUP_CALL_REVERSE) {
  306. for (int i = gr_node_count - 1; i >= 0; i--) {
  307. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  308. continue;
  309. }
  310. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  311. gr_nodes[i]->notification(p_notification, true);
  312. } else {
  313. MessageQueue::get_singleton()->push_notification(gr_nodes[i], p_notification);
  314. }
  315. }
  316. } else {
  317. for (int i = 0; i < gr_node_count; i++) {
  318. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  319. continue;
  320. }
  321. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  322. gr_nodes[i]->notification(p_notification);
  323. } else {
  324. MessageQueue::get_singleton()->push_notification(gr_nodes[i], p_notification);
  325. }
  326. }
  327. }
  328. {
  329. _THREAD_SAFE_METHOD_
  330. nodes_removed_on_group_call_lock--;
  331. if (nodes_removed_on_group_call_lock == 0) {
  332. nodes_removed_on_group_call.clear();
  333. }
  334. }
  335. }
  336. void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) {
  337. Vector<Node *> nodes_copy;
  338. {
  339. _THREAD_SAFE_METHOD_
  340. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  341. if (!E) {
  342. return;
  343. }
  344. Group &g = E->value;
  345. if (g.nodes.is_empty()) {
  346. return;
  347. }
  348. _update_group_order(g);
  349. nodes_copy = g.nodes;
  350. }
  351. Node **gr_nodes = nodes_copy.ptrw();
  352. int gr_node_count = nodes_copy.size();
  353. {
  354. _THREAD_SAFE_METHOD_
  355. nodes_removed_on_group_call_lock++;
  356. }
  357. if (p_call_flags & GROUP_CALL_REVERSE) {
  358. for (int i = gr_node_count - 1; i >= 0; i--) {
  359. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  360. continue;
  361. }
  362. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  363. gr_nodes[i]->set(p_name, p_value);
  364. } else {
  365. MessageQueue::get_singleton()->push_set(gr_nodes[i], p_name, p_value);
  366. }
  367. }
  368. } else {
  369. for (int i = 0; i < gr_node_count; i++) {
  370. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  371. continue;
  372. }
  373. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  374. gr_nodes[i]->set(p_name, p_value);
  375. } else {
  376. MessageQueue::get_singleton()->push_set(gr_nodes[i], p_name, p_value);
  377. }
  378. }
  379. }
  380. {
  381. _THREAD_SAFE_METHOD_
  382. nodes_removed_on_group_call_lock--;
  383. if (nodes_removed_on_group_call_lock == 0) {
  384. nodes_removed_on_group_call.clear();
  385. }
  386. }
  387. }
  388. void SceneTree::notify_group(const StringName &p_group, int p_notification) {
  389. notify_group_flags(GROUP_CALL_DEFAULT, p_group, p_notification);
  390. }
  391. void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) {
  392. set_group_flags(GROUP_CALL_DEFAULT, p_group, p_name, p_value);
  393. }
  394. void SceneTree::initialize() {
  395. ERR_FAIL_NULL(root);
  396. MainLoop::initialize();
  397. root->_set_tree(this);
  398. }
  399. void SceneTree::set_physics_interpolation_enabled(bool p_enabled) {
  400. // We never want interpolation in the editor.
  401. if (Engine::get_singleton()->is_editor_hint()) {
  402. p_enabled = false;
  403. }
  404. if (p_enabled == _physics_interpolation_enabled) {
  405. return;
  406. }
  407. _physics_interpolation_enabled = p_enabled;
  408. RenderingServer::get_singleton()->set_physics_interpolation_enabled(p_enabled);
  409. }
  410. bool SceneTree::is_physics_interpolation_enabled() const {
  411. return _physics_interpolation_enabled;
  412. }
  413. #ifndef _3D_DISABLED
  414. void SceneTree::client_physics_interpolation_add_node_3d(SelfList<Node3D> *p_elem) {
  415. // This ensures that _update_physics_interpolation_data() will be called at least once every
  416. // physics tick, to ensure the previous and current transforms are kept up to date.
  417. _client_physics_interpolation._node_3d_list.add(p_elem);
  418. }
  419. void SceneTree::client_physics_interpolation_remove_node_3d(SelfList<Node3D> *p_elem) {
  420. _client_physics_interpolation._node_3d_list.remove(p_elem);
  421. }
  422. #endif
  423. void SceneTree::iteration_prepare() {
  424. if (_physics_interpolation_enabled) {
  425. // Make sure any pending transforms from the last tick / frame
  426. // are flushed before pumping the interpolation prev and currents.
  427. flush_transform_notifications();
  428. RenderingServer::get_singleton()->tick();
  429. #ifndef _3D_DISABLED
  430. // Any objects performing client physics interpolation
  431. // should be given an opportunity to keep their previous transforms
  432. // up to date before each new physics tick.
  433. _client_physics_interpolation.physics_process();
  434. #endif
  435. }
  436. }
  437. bool SceneTree::physics_process(double p_time) {
  438. current_frame++;
  439. flush_transform_notifications();
  440. if (MainLoop::physics_process(p_time)) {
  441. _quit = true;
  442. }
  443. physics_process_time = p_time;
  444. emit_signal(SNAME("physics_frame"));
  445. call_group(SNAME("_picking_viewports"), SNAME("_process_picking"));
  446. _process(true);
  447. _flush_ugc();
  448. MessageQueue::get_singleton()->flush(); //small little hack
  449. process_timers(p_time, true); //go through timers
  450. process_tweens(p_time, true);
  451. flush_transform_notifications();
  452. _flush_delete_queue();
  453. _call_idle_callbacks();
  454. return _quit;
  455. }
  456. void SceneTree::iteration_end() {
  457. // When physics interpolation is active, we want all pending transforms
  458. // to be flushed to the RenderingServer before finishing a physics tick.
  459. if (_physics_interpolation_enabled) {
  460. flush_transform_notifications();
  461. }
  462. }
  463. bool SceneTree::process(double p_time) {
  464. if (MainLoop::process(p_time)) {
  465. _quit = true;
  466. }
  467. process_time = p_time;
  468. if (multiplayer_poll) {
  469. multiplayer->poll();
  470. for (KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  471. E.value->poll();
  472. }
  473. }
  474. emit_signal(SNAME("process_frame"));
  475. MessageQueue::get_singleton()->flush(); //small little hack
  476. flush_transform_notifications();
  477. _process(false);
  478. _flush_ugc();
  479. MessageQueue::get_singleton()->flush(); //small little hack
  480. flush_transform_notifications(); //transforms after world update, to avoid unnecessary enter/exit notifications
  481. _flush_delete_queue();
  482. if (unlikely(pending_new_scene)) {
  483. _flush_scene_change();
  484. }
  485. process_timers(p_time, false); //go through timers
  486. process_tweens(p_time, false);
  487. flush_transform_notifications(); //additional transforms after timers update
  488. _call_idle_callbacks();
  489. #ifdef TOOLS_ENABLED
  490. #ifndef _3D_DISABLED
  491. if (Engine::get_singleton()->is_editor_hint()) {
  492. //simple hack to reload fallback environment if it changed from editor
  493. String env_path = GLOBAL_GET(SNAME("rendering/environment/defaults/default_environment"));
  494. env_path = env_path.strip_edges(); //user may have added a space or two
  495. String cpath;
  496. Ref<Environment> fallback = get_root()->get_world_3d()->get_fallback_environment();
  497. if (fallback.is_valid()) {
  498. cpath = fallback->get_path();
  499. }
  500. if (cpath != env_path) {
  501. if (!env_path.is_empty()) {
  502. fallback = ResourceLoader::load(env_path);
  503. if (fallback.is_null()) {
  504. //could not load fallback, set as empty
  505. ProjectSettings::get_singleton()->set("rendering/environment/defaults/default_environment", "");
  506. }
  507. } else {
  508. fallback.unref();
  509. }
  510. get_root()->get_world_3d()->set_fallback_environment(fallback);
  511. }
  512. }
  513. #endif // _3D_DISABLED
  514. #endif // TOOLS_ENABLED
  515. if (_physics_interpolation_enabled) {
  516. RenderingServer::get_singleton()->pre_draw(true);
  517. }
  518. return _quit;
  519. }
  520. void SceneTree::process_timers(double p_delta, bool p_physics_frame) {
  521. _THREAD_SAFE_METHOD_
  522. List<Ref<SceneTreeTimer>>::Element *L = timers.back(); //last element
  523. for (List<Ref<SceneTreeTimer>>::Element *E = timers.front(); E;) {
  524. List<Ref<SceneTreeTimer>>::Element *N = E->next();
  525. if ((paused && !E->get()->is_process_always()) || (E->get()->is_process_in_physics() != p_physics_frame)) {
  526. if (E == L) {
  527. break; //break on last, so if new timers were added during list traversal, ignore them.
  528. }
  529. E = N;
  530. continue;
  531. }
  532. double time_left = E->get()->get_time_left();
  533. if (E->get()->is_ignore_time_scale()) {
  534. time_left -= Engine::get_singleton()->get_process_step();
  535. } else {
  536. time_left -= p_delta;
  537. }
  538. E->get()->set_time_left(time_left);
  539. if (time_left <= 0) {
  540. E->get()->emit_signal(SNAME("timeout"));
  541. timers.erase(E);
  542. }
  543. if (E == L) {
  544. break; //break on last, so if new timers were added during list traversal, ignore them.
  545. }
  546. E = N;
  547. }
  548. }
  549. void SceneTree::process_tweens(double p_delta, bool p_physics) {
  550. _THREAD_SAFE_METHOD_
  551. // This methods works similarly to how SceneTreeTimers are handled.
  552. List<Ref<Tween>>::Element *L = tweens.back();
  553. for (List<Ref<Tween>>::Element *E = tweens.front(); E;) {
  554. List<Ref<Tween>>::Element *N = E->next();
  555. // Don't process if paused or process mode doesn't match.
  556. if (!E->get()->can_process(paused) || (p_physics == (E->get()->get_process_mode() == Tween::TWEEN_PROCESS_IDLE))) {
  557. if (E == L) {
  558. break;
  559. }
  560. E = N;
  561. continue;
  562. }
  563. if (!E->get()->step(p_delta)) {
  564. E->get()->clear();
  565. tweens.erase(E);
  566. }
  567. if (E == L) {
  568. break;
  569. }
  570. E = N;
  571. }
  572. }
  573. void SceneTree::finalize() {
  574. _flush_delete_queue();
  575. _flush_ugc();
  576. if (root) {
  577. root->_set_tree(nullptr);
  578. root->_propagate_after_exit_tree();
  579. memdelete(root); //delete root
  580. root = nullptr;
  581. // In case deletion of some objects was queued when destructing the `root`.
  582. // E.g. if `queue_free()` was called for some node outside the tree when handling NOTIFICATION_PREDELETE for some node in the tree.
  583. _flush_delete_queue();
  584. }
  585. MainLoop::finalize();
  586. // Cleanup timers.
  587. for (Ref<SceneTreeTimer> &timer : timers) {
  588. timer->release_connections();
  589. }
  590. timers.clear();
  591. // Cleanup tweens.
  592. for (Ref<Tween> &tween : tweens) {
  593. tween->clear();
  594. }
  595. tweens.clear();
  596. }
  597. void SceneTree::quit(int p_exit_code) {
  598. _THREAD_SAFE_METHOD_
  599. OS::get_singleton()->set_exit_code(p_exit_code);
  600. _quit = true;
  601. }
  602. void SceneTree::_main_window_close() {
  603. if (accept_quit) {
  604. _quit = true;
  605. }
  606. }
  607. void SceneTree::_main_window_go_back() {
  608. if (quit_on_go_back) {
  609. _quit = true;
  610. }
  611. }
  612. void SceneTree::_main_window_focus_in() {
  613. Input *id = Input::get_singleton();
  614. if (id) {
  615. id->ensure_touch_mouse_raised();
  616. }
  617. }
  618. void SceneTree::_notification(int p_notification) {
  619. switch (p_notification) {
  620. case NOTIFICATION_TRANSLATION_CHANGED: {
  621. if (!Engine::get_singleton()->is_editor_hint()) {
  622. get_root()->propagate_notification(p_notification);
  623. }
  624. } break;
  625. case NOTIFICATION_OS_MEMORY_WARNING:
  626. case NOTIFICATION_OS_IME_UPDATE:
  627. case NOTIFICATION_WM_ABOUT:
  628. case NOTIFICATION_CRASH:
  629. case NOTIFICATION_APPLICATION_RESUMED:
  630. case NOTIFICATION_APPLICATION_PAUSED:
  631. case NOTIFICATION_APPLICATION_FOCUS_IN:
  632. case NOTIFICATION_APPLICATION_FOCUS_OUT: {
  633. // Pass these to nodes, since they are mirrored.
  634. get_root()->propagate_notification(p_notification);
  635. } break;
  636. }
  637. }
  638. bool SceneTree::is_auto_accept_quit() const {
  639. return accept_quit;
  640. }
  641. void SceneTree::set_auto_accept_quit(bool p_enable) {
  642. accept_quit = p_enable;
  643. }
  644. bool SceneTree::is_quit_on_go_back() const {
  645. return quit_on_go_back;
  646. }
  647. void SceneTree::set_quit_on_go_back(bool p_enable) {
  648. quit_on_go_back = p_enable;
  649. }
  650. #ifdef DEBUG_ENABLED
  651. void SceneTree::set_debug_collisions_hint(bool p_enabled) {
  652. debug_collisions_hint = p_enabled;
  653. }
  654. bool SceneTree::is_debugging_collisions_hint() const {
  655. return debug_collisions_hint;
  656. }
  657. void SceneTree::set_debug_paths_hint(bool p_enabled) {
  658. debug_paths_hint = p_enabled;
  659. }
  660. bool SceneTree::is_debugging_paths_hint() const {
  661. return debug_paths_hint;
  662. }
  663. void SceneTree::set_debug_navigation_hint(bool p_enabled) {
  664. debug_navigation_hint = p_enabled;
  665. }
  666. bool SceneTree::is_debugging_navigation_hint() const {
  667. return debug_navigation_hint;
  668. }
  669. #endif
  670. void SceneTree::set_debug_collisions_color(const Color &p_color) {
  671. debug_collisions_color = p_color;
  672. }
  673. Color SceneTree::get_debug_collisions_color() const {
  674. return debug_collisions_color;
  675. }
  676. void SceneTree::set_debug_collision_contact_color(const Color &p_color) {
  677. debug_collision_contact_color = p_color;
  678. }
  679. Color SceneTree::get_debug_collision_contact_color() const {
  680. return debug_collision_contact_color;
  681. }
  682. void SceneTree::set_debug_paths_color(const Color &p_color) {
  683. debug_paths_color = p_color;
  684. }
  685. Color SceneTree::get_debug_paths_color() const {
  686. return debug_paths_color;
  687. }
  688. void SceneTree::set_debug_paths_width(float p_width) {
  689. debug_paths_width = p_width;
  690. }
  691. float SceneTree::get_debug_paths_width() const {
  692. return debug_paths_width;
  693. }
  694. Ref<Material> SceneTree::get_debug_paths_material() {
  695. _THREAD_SAFE_METHOD_
  696. if (debug_paths_material.is_valid()) {
  697. return debug_paths_material;
  698. }
  699. Ref<StandardMaterial3D> _debug_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  700. _debug_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  701. _debug_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  702. _debug_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  703. _debug_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  704. _debug_material->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  705. _debug_material->set_albedo(get_debug_paths_color());
  706. debug_paths_material = _debug_material;
  707. return debug_paths_material;
  708. }
  709. Ref<Material> SceneTree::get_debug_collision_material() {
  710. _THREAD_SAFE_METHOD_
  711. if (collision_material.is_valid()) {
  712. return collision_material;
  713. }
  714. Ref<StandardMaterial3D> line_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  715. line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  716. line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  717. line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  718. line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  719. line_material->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  720. line_material->set_albedo(get_debug_collisions_color());
  721. collision_material = line_material;
  722. return collision_material;
  723. }
  724. Ref<ArrayMesh> SceneTree::get_debug_contact_mesh() {
  725. _THREAD_SAFE_METHOD_
  726. if (debug_contact_mesh.is_valid()) {
  727. return debug_contact_mesh;
  728. }
  729. debug_contact_mesh.instantiate();
  730. Ref<StandardMaterial3D> mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  731. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  732. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  733. mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  734. mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  735. mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  736. mat->set_albedo(get_debug_collision_contact_color());
  737. Vector3 diamond[6] = {
  738. Vector3(-1, 0, 0),
  739. Vector3(1, 0, 0),
  740. Vector3(0, -1, 0),
  741. Vector3(0, 1, 0),
  742. Vector3(0, 0, -1),
  743. Vector3(0, 0, 1)
  744. };
  745. /* clang-format off */
  746. int diamond_faces[8 * 3] = {
  747. 0, 2, 4,
  748. 0, 3, 4,
  749. 1, 2, 4,
  750. 1, 3, 4,
  751. 0, 2, 5,
  752. 0, 3, 5,
  753. 1, 2, 5,
  754. 1, 3, 5,
  755. };
  756. /* clang-format on */
  757. Vector<int> indices;
  758. for (int i = 0; i < 8 * 3; i++) {
  759. indices.push_back(diamond_faces[i]);
  760. }
  761. Vector<Vector3> vertices;
  762. for (int i = 0; i < 6; i++) {
  763. vertices.push_back(diamond[i] * 0.1);
  764. }
  765. Array arr;
  766. arr.resize(Mesh::ARRAY_MAX);
  767. arr[Mesh::ARRAY_VERTEX] = vertices;
  768. arr[Mesh::ARRAY_INDEX] = indices;
  769. debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  770. debug_contact_mesh->surface_set_material(0, mat);
  771. return debug_contact_mesh;
  772. }
  773. void SceneTree::set_pause(bool p_enabled) {
  774. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Pause can only be set from the main thread.");
  775. ERR_FAIL_COND_MSG(suspended, "Pause state cannot be modified while suspended.");
  776. if (p_enabled == paused) {
  777. return;
  778. }
  779. paused = p_enabled;
  780. #ifndef _3D_DISABLED
  781. PhysicsServer3D::get_singleton()->set_active(!p_enabled);
  782. #endif // _3D_DISABLED
  783. PhysicsServer2D::get_singleton()->set_active(!p_enabled);
  784. if (get_root()) {
  785. get_root()->_propagate_pause_notification(p_enabled);
  786. }
  787. }
  788. bool SceneTree::is_paused() const {
  789. return paused;
  790. }
  791. void SceneTree::set_suspend(bool p_enabled) {
  792. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Suspend can only be set from the main thread.");
  793. if (p_enabled == suspended) {
  794. return;
  795. }
  796. suspended = p_enabled;
  797. Engine::get_singleton()->set_freeze_time_scale(p_enabled);
  798. #ifndef _3D_DISABLED
  799. PhysicsServer3D::get_singleton()->set_active(!p_enabled && !paused);
  800. #endif // _3D_DISABLED
  801. PhysicsServer2D::get_singleton()->set_active(!p_enabled && !paused);
  802. if (get_root()) {
  803. get_root()->_propagate_suspend_notification(p_enabled);
  804. }
  805. }
  806. bool SceneTree::is_suspended() const {
  807. return suspended;
  808. }
  809. void SceneTree::_process_group(ProcessGroup *p_group, bool p_physics) {
  810. // When reading this function, keep in mind that this code must work in a way where
  811. // if any node is removed, this needs to continue working.
  812. p_group->call_queue.flush(); // Flush messages before processing.
  813. Vector<Node *> &nodes = p_physics ? p_group->physics_nodes : p_group->nodes;
  814. if (nodes.is_empty()) {
  815. return;
  816. }
  817. if (p_physics) {
  818. if (p_group->physics_node_order_dirty) {
  819. nodes.sort_custom<Node::ComparatorWithPhysicsPriority>();
  820. p_group->physics_node_order_dirty = false;
  821. }
  822. } else {
  823. if (p_group->node_order_dirty) {
  824. nodes.sort_custom<Node::ComparatorWithPriority>();
  825. p_group->node_order_dirty = false;
  826. }
  827. }
  828. // Make a copy, so if nodes are added/removed from process, this does not break
  829. Vector<Node *> nodes_copy = nodes;
  830. uint32_t node_count = nodes_copy.size();
  831. Node **nodes_ptr = (Node **)nodes_copy.ptr(); // Force cast, pointer will not change.
  832. for (uint32_t i = 0; i < node_count; i++) {
  833. Node *n = nodes_ptr[i];
  834. if (nodes_removed_on_group_call.has(n)) {
  835. // Node may have been removed during process, skip it.
  836. // Keep in mind removals can only happen on the main thread.
  837. continue;
  838. }
  839. if (!n->can_process() || !n->is_inside_tree()) {
  840. continue;
  841. }
  842. if (p_physics) {
  843. if (n->is_physics_processing_internal()) {
  844. n->notification(Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS);
  845. }
  846. if (n->is_physics_processing()) {
  847. n->notification(Node::NOTIFICATION_PHYSICS_PROCESS);
  848. }
  849. } else {
  850. if (n->is_processing_internal()) {
  851. n->notification(Node::NOTIFICATION_INTERNAL_PROCESS);
  852. }
  853. if (n->is_processing()) {
  854. n->notification(Node::NOTIFICATION_PROCESS);
  855. }
  856. }
  857. }
  858. p_group->call_queue.flush(); // Flush messages also after processing (for potential deferred calls).
  859. }
  860. void SceneTree::_process_groups_thread(uint32_t p_index, bool p_physics) {
  861. Node::current_process_thread_group = local_process_group_cache[p_index]->owner;
  862. _process_group(local_process_group_cache[p_index], p_physics);
  863. Node::current_process_thread_group = nullptr;
  864. }
  865. void SceneTree::_process(bool p_physics) {
  866. if (process_groups_dirty) {
  867. {
  868. // First, remove dirty groups.
  869. // This needs to be done when not processing to avoid problems.
  870. ProcessGroup **pg_ptr = (ProcessGroup **)process_groups.ptr(); // discard constness.
  871. uint32_t pg_count = process_groups.size();
  872. for (uint32_t i = 0; i < pg_count; i++) {
  873. if (pg_ptr[i]->removed) {
  874. // Replace removed with last.
  875. pg_ptr[i] = pg_ptr[pg_count - 1];
  876. // Retry
  877. i--;
  878. pg_count--;
  879. }
  880. }
  881. if (pg_count != process_groups.size()) {
  882. process_groups.resize(pg_count);
  883. }
  884. }
  885. {
  886. // Then, re-sort groups.
  887. process_groups.sort_custom<ProcessGroupSort>();
  888. }
  889. process_groups_dirty = false;
  890. }
  891. // Cache the group count, because during processing new groups may be added.
  892. // They will be added at the end, hence for consistency they will be ignored by this process loop.
  893. // No group will be removed from the array during processing (this is done earlier in this function by marking the groups dirty).
  894. uint32_t group_count = process_groups.size();
  895. if (group_count == 0) {
  896. return;
  897. }
  898. process_last_pass++; // Increment pass
  899. uint32_t from = 0;
  900. uint32_t process_count = 0;
  901. nodes_removed_on_group_call_lock++;
  902. int current_order = process_groups[0]->owner ? process_groups[0]->owner->data.process_thread_group_order : 0;
  903. bool current_threaded = process_groups[0]->owner ? process_groups[0]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD : false;
  904. for (uint32_t i = 0; i <= group_count; i++) {
  905. int order = i < group_count && process_groups[i]->owner ? process_groups[i]->owner->data.process_thread_group_order : 0;
  906. bool threaded = i < group_count && process_groups[i]->owner ? process_groups[i]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD : false;
  907. if (i == group_count || current_order != order || current_threaded != threaded) {
  908. if (process_count > 0) {
  909. // Proceed to process the group.
  910. bool using_threads = process_groups[from]->owner && process_groups[from]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD && !node_threading_disabled;
  911. if (using_threads) {
  912. local_process_group_cache.clear();
  913. }
  914. for (uint32_t j = from; j < i; j++) {
  915. if (process_groups[j]->last_pass == process_last_pass) {
  916. if (using_threads) {
  917. local_process_group_cache.push_back(process_groups[j]);
  918. } else {
  919. _process_group(process_groups[j], p_physics);
  920. }
  921. }
  922. }
  923. if (using_threads) {
  924. WorkerThreadPool::GroupID id = WorkerThreadPool::get_singleton()->add_template_group_task(this, &SceneTree::_process_groups_thread, p_physics, local_process_group_cache.size(), -1, true);
  925. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(id);
  926. }
  927. }
  928. if (i == group_count) {
  929. // This one is invalid, no longer process
  930. break;
  931. }
  932. from = i;
  933. current_threaded = threaded;
  934. current_order = order;
  935. }
  936. if (process_groups[i]->removed) {
  937. continue;
  938. }
  939. ProcessGroup *pg = process_groups[i];
  940. // Validate group for processing
  941. bool process_valid = false;
  942. if (p_physics) {
  943. if (!pg->physics_nodes.is_empty()) {
  944. process_valid = true;
  945. } else if ((pg == &default_process_group || (pg->owner != nullptr && pg->owner->data.process_thread_messages.has_flag(Node::FLAG_PROCESS_THREAD_MESSAGES_PHYSICS))) && pg->call_queue.has_messages()) {
  946. process_valid = true;
  947. }
  948. } else {
  949. if (!pg->nodes.is_empty()) {
  950. process_valid = true;
  951. } else if ((pg == &default_process_group || (pg->owner != nullptr && pg->owner->data.process_thread_messages.has_flag(Node::FLAG_PROCESS_THREAD_MESSAGES))) && pg->call_queue.has_messages()) {
  952. process_valid = true;
  953. }
  954. }
  955. if (process_valid) {
  956. pg->last_pass = process_last_pass; // Enable for processing
  957. process_count++;
  958. }
  959. }
  960. nodes_removed_on_group_call_lock--;
  961. if (nodes_removed_on_group_call_lock == 0) {
  962. nodes_removed_on_group_call.clear();
  963. }
  964. }
  965. bool SceneTree::ProcessGroupSort::operator()(const ProcessGroup *p_left, const ProcessGroup *p_right) const {
  966. int left_order = p_left->owner ? p_left->owner->data.process_thread_group_order : 0;
  967. int right_order = p_right->owner ? p_right->owner->data.process_thread_group_order : 0;
  968. if (left_order == right_order) {
  969. int left_threaded = p_left->owner != nullptr && p_left->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD ? 0 : 1;
  970. int right_threaded = p_right->owner != nullptr && p_right->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD ? 0 : 1;
  971. return left_threaded < right_threaded;
  972. } else {
  973. return left_order < right_order;
  974. }
  975. }
  976. void SceneTree::_remove_process_group(Node *p_node) {
  977. _THREAD_SAFE_METHOD_
  978. ProcessGroup *pg = (ProcessGroup *)p_node->data.process_group;
  979. ERR_FAIL_NULL(pg);
  980. ERR_FAIL_COND(pg->removed);
  981. pg->removed = true;
  982. pg->owner = nullptr;
  983. p_node->data.process_group = nullptr;
  984. process_groups_dirty = true;
  985. }
  986. void SceneTree::_add_process_group(Node *p_node) {
  987. _THREAD_SAFE_METHOD_
  988. ERR_FAIL_NULL(p_node);
  989. ProcessGroup *pg = memnew(ProcessGroup);
  990. pg->owner = p_node;
  991. p_node->data.process_group = pg;
  992. process_groups.push_back(pg);
  993. process_groups_dirty = true;
  994. }
  995. void SceneTree::_remove_node_from_process_group(Node *p_node, Node *p_owner) {
  996. _THREAD_SAFE_METHOD_
  997. ProcessGroup *pg = p_owner ? (ProcessGroup *)p_owner->data.process_group : &default_process_group;
  998. if (p_node->is_processing() || p_node->is_processing_internal()) {
  999. bool found = pg->nodes.erase(p_node);
  1000. ERR_FAIL_COND(!found);
  1001. }
  1002. if (p_node->is_physics_processing() || p_node->is_physics_processing_internal()) {
  1003. bool found = pg->physics_nodes.erase(p_node);
  1004. ERR_FAIL_COND(!found);
  1005. }
  1006. }
  1007. void SceneTree::_add_node_to_process_group(Node *p_node, Node *p_owner) {
  1008. _THREAD_SAFE_METHOD_
  1009. ProcessGroup *pg = p_owner ? (ProcessGroup *)p_owner->data.process_group : &default_process_group;
  1010. if (p_node->is_processing() || p_node->is_processing_internal()) {
  1011. pg->nodes.push_back(p_node);
  1012. pg->node_order_dirty = true;
  1013. }
  1014. if (p_node->is_physics_processing() || p_node->is_physics_processing_internal()) {
  1015. pg->physics_nodes.push_back(p_node);
  1016. pg->physics_node_order_dirty = true;
  1017. }
  1018. }
  1019. void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_call_type, const Ref<InputEvent> &p_input, Viewport *p_viewport) {
  1020. Vector<Node *> nodes_copy;
  1021. {
  1022. _THREAD_SAFE_METHOD_
  1023. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1024. if (!E) {
  1025. return;
  1026. }
  1027. Group &g = E->value;
  1028. if (g.nodes.is_empty()) {
  1029. return;
  1030. }
  1031. _update_group_order(g);
  1032. //copy, so copy on write happens in case something is removed from process while being called
  1033. //performance is not lost because only if something is added/removed the vector is copied.
  1034. nodes_copy = g.nodes;
  1035. }
  1036. int gr_node_count = nodes_copy.size();
  1037. Node **gr_nodes = nodes_copy.ptrw();
  1038. {
  1039. _THREAD_SAFE_METHOD_
  1040. nodes_removed_on_group_call_lock++;
  1041. }
  1042. Vector<ObjectID> no_context_node_ids; // Nodes may be deleted due to this shortcut input.
  1043. for (int i = gr_node_count - 1; i >= 0; i--) {
  1044. if (p_viewport->is_input_handled()) {
  1045. break;
  1046. }
  1047. Node *n = gr_nodes[i];
  1048. if (nodes_removed_on_group_call.has(n)) {
  1049. continue;
  1050. }
  1051. if (!n->can_process()) {
  1052. continue;
  1053. }
  1054. switch (p_call_type) {
  1055. case CALL_INPUT_TYPE_INPUT:
  1056. n->_call_input(p_input);
  1057. break;
  1058. case CALL_INPUT_TYPE_SHORTCUT_INPUT: {
  1059. const Control *c = Object::cast_to<Control>(n);
  1060. if (c) {
  1061. // If calling shortcut input on a control, ensure it respects the shortcut context.
  1062. // Shortcut context (based on focus) only makes sense for controls (UI), so don't need to worry about it for nodes
  1063. if (c->get_shortcut_context() == nullptr) {
  1064. no_context_node_ids.append(n->get_instance_id());
  1065. continue;
  1066. }
  1067. if (!c->is_focus_owner_in_shortcut_context()) {
  1068. continue;
  1069. }
  1070. }
  1071. n->_call_shortcut_input(p_input);
  1072. break;
  1073. }
  1074. case CALL_INPUT_TYPE_UNHANDLED_INPUT:
  1075. n->_call_unhandled_input(p_input);
  1076. break;
  1077. case CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT:
  1078. n->_call_unhandled_key_input(p_input);
  1079. break;
  1080. }
  1081. }
  1082. for (const ObjectID &id : no_context_node_ids) {
  1083. if (p_viewport->is_input_handled()) {
  1084. break;
  1085. }
  1086. Node *n = Object::cast_to<Node>(ObjectDB::get_instance(id));
  1087. if (n) {
  1088. n->_call_shortcut_input(p_input);
  1089. }
  1090. }
  1091. {
  1092. _THREAD_SAFE_METHOD_
  1093. nodes_removed_on_group_call_lock--;
  1094. if (nodes_removed_on_group_call_lock == 0) {
  1095. nodes_removed_on_group_call.clear();
  1096. }
  1097. }
  1098. }
  1099. void SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1100. r_error.error = Callable::CallError::CALL_OK;
  1101. ERR_FAIL_COND(p_argcount < 3);
  1102. ERR_FAIL_COND(!p_args[0]->is_num());
  1103. ERR_FAIL_COND(!p_args[1]->is_string());
  1104. ERR_FAIL_COND(!p_args[2]->is_string());
  1105. int flags = *p_args[0];
  1106. StringName group = *p_args[1];
  1107. StringName method = *p_args[2];
  1108. call_group_flagsp(flags, group, method, p_args + 3, p_argcount - 3);
  1109. }
  1110. void SceneTree::_call_group(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1111. r_error.error = Callable::CallError::CALL_OK;
  1112. ERR_FAIL_COND(p_argcount < 2);
  1113. ERR_FAIL_COND(!p_args[0]->is_string());
  1114. ERR_FAIL_COND(!p_args[1]->is_string());
  1115. StringName group = *p_args[0];
  1116. StringName method = *p_args[1];
  1117. call_group_flagsp(GROUP_CALL_DEFAULT, group, method, p_args + 2, p_argcount - 2);
  1118. }
  1119. int64_t SceneTree::get_frame() const {
  1120. return current_frame;
  1121. }
  1122. TypedArray<Node> SceneTree::_get_nodes_in_group(const StringName &p_group) {
  1123. _THREAD_SAFE_METHOD_
  1124. TypedArray<Node> ret;
  1125. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1126. if (!E) {
  1127. return ret;
  1128. }
  1129. _update_group_order(E->value); //update order just in case
  1130. int nc = E->value.nodes.size();
  1131. if (nc == 0) {
  1132. return ret;
  1133. }
  1134. ret.resize(nc);
  1135. Node **ptr = E->value.nodes.ptrw();
  1136. for (int i = 0; i < nc; i++) {
  1137. ret[i] = ptr[i];
  1138. }
  1139. return ret;
  1140. }
  1141. bool SceneTree::has_group(const StringName &p_identifier) const {
  1142. _THREAD_SAFE_METHOD_
  1143. return group_map.has(p_identifier);
  1144. }
  1145. int SceneTree::get_node_count_in_group(const StringName &p_group) const {
  1146. _THREAD_SAFE_METHOD_
  1147. HashMap<StringName, Group>::ConstIterator E = group_map.find(p_group);
  1148. if (!E) {
  1149. return 0;
  1150. }
  1151. return E->value.nodes.size();
  1152. }
  1153. Node *SceneTree::get_first_node_in_group(const StringName &p_group) {
  1154. _THREAD_SAFE_METHOD_
  1155. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1156. if (!E) {
  1157. return nullptr; // No group.
  1158. }
  1159. _update_group_order(E->value); // Update order just in case.
  1160. if (E->value.nodes.is_empty()) {
  1161. return nullptr;
  1162. }
  1163. return E->value.nodes[0];
  1164. }
  1165. void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) {
  1166. _THREAD_SAFE_METHOD_
  1167. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1168. if (!E) {
  1169. return;
  1170. }
  1171. _update_group_order(E->value); //update order just in case
  1172. int nc = E->value.nodes.size();
  1173. if (nc == 0) {
  1174. return;
  1175. }
  1176. Node **ptr = E->value.nodes.ptrw();
  1177. for (int i = 0; i < nc; i++) {
  1178. p_list->push_back(ptr[i]);
  1179. }
  1180. }
  1181. void SceneTree::_flush_delete_queue() {
  1182. _THREAD_SAFE_METHOD_
  1183. while (delete_queue.size()) {
  1184. Object *obj = ObjectDB::get_instance(delete_queue.front()->get());
  1185. if (obj) {
  1186. memdelete(obj);
  1187. }
  1188. delete_queue.pop_front();
  1189. }
  1190. }
  1191. void SceneTree::queue_delete(Object *p_object) {
  1192. _THREAD_SAFE_METHOD_
  1193. ERR_FAIL_NULL(p_object);
  1194. p_object->_is_queued_for_deletion = true;
  1195. delete_queue.push_back(p_object->get_instance_id());
  1196. }
  1197. int SceneTree::get_node_count() const {
  1198. return nodes_in_tree_count;
  1199. }
  1200. void SceneTree::set_edited_scene_root(Node *p_node) {
  1201. #ifdef TOOLS_ENABLED
  1202. edited_scene_root = p_node;
  1203. #endif
  1204. }
  1205. Node *SceneTree::get_edited_scene_root() const {
  1206. #ifdef TOOLS_ENABLED
  1207. return edited_scene_root;
  1208. #else
  1209. return nullptr;
  1210. #endif
  1211. }
  1212. void SceneTree::set_current_scene(Node *p_scene) {
  1213. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Changing scene can only be done from the main thread.");
  1214. ERR_FAIL_COND(p_scene && p_scene->get_parent() != root);
  1215. current_scene = p_scene;
  1216. }
  1217. Node *SceneTree::get_current_scene() const {
  1218. return current_scene;
  1219. }
  1220. void SceneTree::_flush_scene_change() {
  1221. if (prev_scene) {
  1222. memdelete(prev_scene);
  1223. prev_scene = nullptr;
  1224. }
  1225. current_scene = pending_new_scene;
  1226. root->add_child(pending_new_scene);
  1227. pending_new_scene = nullptr;
  1228. // Update display for cursor instantly.
  1229. root->update_mouse_cursor_state();
  1230. }
  1231. Error SceneTree::change_scene_to_file(const String &p_path) {
  1232. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), ERR_INVALID_PARAMETER, "Changing scene can only be done from the main thread.");
  1233. Ref<PackedScene> new_scene = ResourceLoader::load(p_path);
  1234. if (new_scene.is_null()) {
  1235. return ERR_CANT_OPEN;
  1236. }
  1237. return change_scene_to_packed(new_scene);
  1238. }
  1239. Error SceneTree::change_scene_to_packed(const Ref<PackedScene> &p_scene) {
  1240. ERR_FAIL_COND_V_MSG(p_scene.is_null(), ERR_INVALID_PARAMETER, "Can't change to a null scene. Use unload_current_scene() if you wish to unload it.");
  1241. Node *new_scene = p_scene->instantiate();
  1242. ERR_FAIL_NULL_V(new_scene, ERR_CANT_CREATE);
  1243. // If called again while a change is pending.
  1244. if (pending_new_scene) {
  1245. queue_delete(pending_new_scene);
  1246. pending_new_scene = nullptr;
  1247. }
  1248. prev_scene = current_scene;
  1249. if (current_scene) {
  1250. // Let as many side effects as possible happen or be queued now,
  1251. // so they are run before the scene is actually deleted.
  1252. root->remove_child(current_scene);
  1253. }
  1254. DEV_ASSERT(!current_scene);
  1255. pending_new_scene = new_scene;
  1256. return OK;
  1257. }
  1258. Error SceneTree::reload_current_scene() {
  1259. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), ERR_INVALID_PARAMETER, "Reloading scene can only be done from the main thread.");
  1260. ERR_FAIL_NULL_V(current_scene, ERR_UNCONFIGURED);
  1261. String fname = current_scene->get_scene_file_path();
  1262. return change_scene_to_file(fname);
  1263. }
  1264. void SceneTree::unload_current_scene() {
  1265. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Unloading the current scene can only be done from the main thread.");
  1266. if (current_scene) {
  1267. memdelete(current_scene);
  1268. current_scene = nullptr;
  1269. }
  1270. }
  1271. void SceneTree::add_current_scene(Node *p_current) {
  1272. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Adding a current scene can only be done from the main thread.");
  1273. current_scene = p_current;
  1274. root->add_child(p_current);
  1275. }
  1276. Ref<SceneTreeTimer> SceneTree::create_timer(double p_delay_sec, bool p_process_always, bool p_process_in_physics, bool p_ignore_time_scale) {
  1277. _THREAD_SAFE_METHOD_
  1278. Ref<SceneTreeTimer> stt;
  1279. stt.instantiate();
  1280. stt->set_process_always(p_process_always);
  1281. stt->set_time_left(p_delay_sec);
  1282. stt->set_process_in_physics(p_process_in_physics);
  1283. stt->set_ignore_time_scale(p_ignore_time_scale);
  1284. timers.push_back(stt);
  1285. return stt;
  1286. }
  1287. Ref<Tween> SceneTree::create_tween() {
  1288. _THREAD_SAFE_METHOD_
  1289. Ref<Tween> tween = memnew(Tween(true));
  1290. tweens.push_back(tween);
  1291. return tween;
  1292. }
  1293. TypedArray<Tween> SceneTree::get_processed_tweens() {
  1294. _THREAD_SAFE_METHOD_
  1295. TypedArray<Tween> ret;
  1296. ret.resize(tweens.size());
  1297. int i = 0;
  1298. for (const Ref<Tween> &tween : tweens) {
  1299. ret[i] = tween;
  1300. i++;
  1301. }
  1302. return ret;
  1303. }
  1304. Ref<MultiplayerAPI> SceneTree::get_multiplayer(const NodePath &p_for_path) const {
  1305. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), Ref<MultiplayerAPI>(), "Multiplayer can only be manipulated from the main thread.");
  1306. if (p_for_path.is_empty()) {
  1307. return multiplayer;
  1308. }
  1309. const Vector<StringName> tnames = p_for_path.get_names();
  1310. const StringName *nptr = tnames.ptr();
  1311. for (const KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  1312. const Vector<StringName> snames = E.key.get_names();
  1313. if (tnames.size() < snames.size()) {
  1314. continue;
  1315. }
  1316. const StringName *sptr = snames.ptr();
  1317. bool valid = true;
  1318. for (int i = 0; i < snames.size(); i++) {
  1319. if (sptr[i] != nptr[i]) {
  1320. valid = false;
  1321. break;
  1322. }
  1323. }
  1324. if (valid) {
  1325. return E.value;
  1326. }
  1327. }
  1328. return multiplayer;
  1329. }
  1330. void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer, const NodePath &p_root_path) {
  1331. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Multiplayer can only be manipulated from the main thread.");
  1332. if (p_root_path.is_empty()) {
  1333. ERR_FAIL_COND(!p_multiplayer.is_valid());
  1334. if (multiplayer.is_valid()) {
  1335. multiplayer->object_configuration_remove(nullptr, NodePath("/" + root->get_name()));
  1336. }
  1337. multiplayer = p_multiplayer;
  1338. multiplayer->object_configuration_add(nullptr, NodePath("/" + root->get_name()));
  1339. } else {
  1340. if (custom_multiplayers.has(p_root_path)) {
  1341. custom_multiplayers[p_root_path]->object_configuration_remove(nullptr, p_root_path);
  1342. } else if (p_multiplayer.is_valid()) {
  1343. const Vector<StringName> tnames = p_root_path.get_names();
  1344. const StringName *nptr = tnames.ptr();
  1345. for (const KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  1346. const Vector<StringName> snames = E.key.get_names();
  1347. if (tnames.size() < snames.size()) {
  1348. continue;
  1349. }
  1350. const StringName *sptr = snames.ptr();
  1351. bool valid = true;
  1352. for (int i = 0; i < snames.size(); i++) {
  1353. if (sptr[i] != nptr[i]) {
  1354. valid = false;
  1355. break;
  1356. }
  1357. }
  1358. ERR_FAIL_COND_MSG(valid, "Multiplayer is already configured for a parent of this path: '" + p_root_path + "' in '" + E.key + "'.");
  1359. }
  1360. }
  1361. if (p_multiplayer.is_valid()) {
  1362. custom_multiplayers[p_root_path] = p_multiplayer;
  1363. p_multiplayer->object_configuration_add(nullptr, p_root_path);
  1364. } else {
  1365. custom_multiplayers.erase(p_root_path);
  1366. }
  1367. }
  1368. }
  1369. void SceneTree::set_multiplayer_poll_enabled(bool p_enabled) {
  1370. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Multiplayer can only be manipulated from the main thread.");
  1371. multiplayer_poll = p_enabled;
  1372. }
  1373. bool SceneTree::is_multiplayer_poll_enabled() const {
  1374. return multiplayer_poll;
  1375. }
  1376. void SceneTree::_bind_methods() {
  1377. ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root);
  1378. ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);
  1379. ClassDB::bind_method(D_METHOD("is_auto_accept_quit"), &SceneTree::is_auto_accept_quit);
  1380. ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit);
  1381. ClassDB::bind_method(D_METHOD("is_quit_on_go_back"), &SceneTree::is_quit_on_go_back);
  1382. ClassDB::bind_method(D_METHOD("set_quit_on_go_back", "enabled"), &SceneTree::set_quit_on_go_back);
  1383. ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint);
  1384. ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint);
  1385. ClassDB::bind_method(D_METHOD("set_debug_paths_hint", "enable"), &SceneTree::set_debug_paths_hint);
  1386. ClassDB::bind_method(D_METHOD("is_debugging_paths_hint"), &SceneTree::is_debugging_paths_hint);
  1387. ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint);
  1388. ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint);
  1389. ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root);
  1390. ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root);
  1391. ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause);
  1392. ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused);
  1393. ClassDB::bind_method(D_METHOD("create_timer", "time_sec", "process_always", "process_in_physics", "ignore_time_scale"), &SceneTree::create_timer, DEFVAL(true), DEFVAL(false), DEFVAL(false));
  1394. ClassDB::bind_method(D_METHOD("create_tween"), &SceneTree::create_tween);
  1395. ClassDB::bind_method(D_METHOD("get_processed_tweens"), &SceneTree::get_processed_tweens);
  1396. ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count);
  1397. ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame);
  1398. ClassDB::bind_method(D_METHOD("quit", "exit_code"), &SceneTree::quit, DEFVAL(EXIT_SUCCESS));
  1399. ClassDB::bind_method(D_METHOD("set_physics_interpolation_enabled", "enabled"), &SceneTree::set_physics_interpolation_enabled);
  1400. ClassDB::bind_method(D_METHOD("is_physics_interpolation_enabled"), &SceneTree::is_physics_interpolation_enabled);
  1401. ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete);
  1402. MethodInfo mi;
  1403. mi.name = "call_group_flags";
  1404. mi.arguments.push_back(PropertyInfo(Variant::INT, "flags"));
  1405. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
  1406. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1407. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi);
  1408. ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags);
  1409. ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags);
  1410. MethodInfo mi2;
  1411. mi2.name = "call_group";
  1412. mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
  1413. mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1414. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2);
  1415. ClassDB::bind_method(D_METHOD("notify_group", "group", "notification"), &SceneTree::notify_group);
  1416. ClassDB::bind_method(D_METHOD("set_group", "group", "property", "value"), &SceneTree::set_group);
  1417. ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group);
  1418. ClassDB::bind_method(D_METHOD("get_first_node_in_group", "group"), &SceneTree::get_first_node_in_group);
  1419. ClassDB::bind_method(D_METHOD("get_node_count_in_group", "group"), &SceneTree::get_node_count_in_group);
  1420. ClassDB::bind_method(D_METHOD("set_current_scene", "child_node"), &SceneTree::set_current_scene);
  1421. ClassDB::bind_method(D_METHOD("get_current_scene"), &SceneTree::get_current_scene);
  1422. ClassDB::bind_method(D_METHOD("change_scene_to_file", "path"), &SceneTree::change_scene_to_file);
  1423. ClassDB::bind_method(D_METHOD("change_scene_to_packed", "packed_scene"), &SceneTree::change_scene_to_packed);
  1424. ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);
  1425. ClassDB::bind_method(D_METHOD("unload_current_scene"), &SceneTree::unload_current_scene);
  1426. ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer", "root_path"), &SceneTree::set_multiplayer, DEFVAL(NodePath()));
  1427. ClassDB::bind_method(D_METHOD("get_multiplayer", "for_path"), &SceneTree::get_multiplayer, DEFVAL(NodePath()));
  1428. ClassDB::bind_method(D_METHOD("set_multiplayer_poll_enabled", "enabled"), &SceneTree::set_multiplayer_poll_enabled);
  1429. ClassDB::bind_method(D_METHOD("is_multiplayer_poll_enabled"), &SceneTree::is_multiplayer_poll_enabled);
  1430. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_accept_quit"), "set_auto_accept_quit", "is_auto_accept_quit");
  1431. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "quit_on_go_back"), "set_quit_on_go_back", "is_quit_on_go_back");
  1432. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_collisions_hint"), "set_debug_collisions_hint", "is_debugging_collisions_hint");
  1433. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_paths_hint"), "set_debug_paths_hint", "is_debugging_paths_hint");
  1434. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_navigation_hint"), "set_debug_navigation_hint", "is_debugging_navigation_hint");
  1435. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "paused"), "set_pause", "is_paused");
  1436. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "edited_scene_root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_edited_scene_root", "get_edited_scene_root");
  1437. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "current_scene", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_current_scene", "get_current_scene");
  1438. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "", "get_root");
  1439. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multiplayer_poll"), "set_multiplayer_poll_enabled", "is_multiplayer_poll_enabled");
  1440. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "physics_interpolation"), "set_physics_interpolation_enabled", "is_physics_interpolation_enabled");
  1441. ADD_SIGNAL(MethodInfo("tree_changed"));
  1442. ADD_SIGNAL(MethodInfo("tree_process_mode_changed")); //editor only signal, but due to API hash it can't be removed in run-time
  1443. ADD_SIGNAL(MethodInfo("node_added", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1444. ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1445. ADD_SIGNAL(MethodInfo("node_renamed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1446. ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1447. ADD_SIGNAL(MethodInfo("process_frame"));
  1448. ADD_SIGNAL(MethodInfo("physics_frame"));
  1449. BIND_ENUM_CONSTANT(GROUP_CALL_DEFAULT);
  1450. BIND_ENUM_CONSTANT(GROUP_CALL_REVERSE);
  1451. BIND_ENUM_CONSTANT(GROUP_CALL_DEFERRED);
  1452. BIND_ENUM_CONSTANT(GROUP_CALL_UNIQUE);
  1453. }
  1454. SceneTree *SceneTree::singleton = nullptr;
  1455. SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS];
  1456. int SceneTree::idle_callback_count = 0;
  1457. void SceneTree::_call_idle_callbacks() {
  1458. for (int i = 0; i < idle_callback_count; i++) {
  1459. idle_callbacks[i]();
  1460. }
  1461. }
  1462. void SceneTree::add_idle_callback(IdleCallback p_callback) {
  1463. ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS);
  1464. idle_callbacks[idle_callback_count++] = p_callback;
  1465. }
  1466. #ifdef TOOLS_ENABLED
  1467. void SceneTree::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1468. const String pf = p_function;
  1469. bool add_options = false;
  1470. if (p_idx == 0) {
  1471. add_options = pf == "get_nodes_in_group" || pf == "has_group" || pf == "get_first_node_in_group" || pf == "set_group" || pf == "notify_group" || pf == "call_group" || pf == "add_to_group";
  1472. } else if (p_idx == 1) {
  1473. add_options = pf == "set_group_flags" || pf == "call_group_flags" || pf == "notify_group_flags";
  1474. }
  1475. if (add_options) {
  1476. HashMap<StringName, String> global_groups = ProjectSettings::get_singleton()->get_global_groups_list();
  1477. for (const KeyValue<StringName, String> &E : global_groups) {
  1478. r_options->push_back(E.key.operator String().quote());
  1479. }
  1480. }
  1481. MainLoop::get_argument_options(p_function, p_idx, r_options);
  1482. }
  1483. #endif
  1484. void SceneTree::set_disable_node_threading(bool p_disable) {
  1485. node_threading_disabled = p_disable;
  1486. }
  1487. SceneTree::SceneTree() {
  1488. if (singleton == nullptr) {
  1489. singleton = this;
  1490. }
  1491. debug_collisions_color = GLOBAL_DEF("debug/shapes/collision/shape_color", Color(0.0, 0.6, 0.7, 0.42));
  1492. debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
  1493. debug_paths_color = GLOBAL_DEF("debug/shapes/paths/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
  1494. debug_paths_width = GLOBAL_DEF("debug/shapes/paths/geometry_width", 2.0);
  1495. collision_debug_contacts = GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1"), 10000);
  1496. GLOBAL_DEF("debug/shapes/collision/draw_2d_outlines", true);
  1497. process_group_call_queue_allocator = memnew(CallQueue::Allocator(64));
  1498. Math::randomize();
  1499. // Create with mainloop.
  1500. root = memnew(Window);
  1501. root->set_min_size(Size2i(64, 64)); // Define a very small minimum window size to prevent bugs such as GH-37242.
  1502. root->set_process_mode(Node::PROCESS_MODE_PAUSABLE);
  1503. root->set_auto_translate_mode(GLOBAL_GET("internationalization/rendering/root_node_auto_translate") ? Node::AUTO_TRANSLATE_MODE_ALWAYS : Node::AUTO_TRANSLATE_MODE_DISABLED);
  1504. root->set_name("root");
  1505. root->set_title(GLOBAL_GET("application/config/name"));
  1506. if (Engine::get_singleton()->is_editor_hint()) {
  1507. root->set_wrap_controls(true);
  1508. }
  1509. #ifndef _3D_DISABLED
  1510. if (!root->get_world_3d().is_valid()) {
  1511. root->set_world_3d(Ref<World3D>(memnew(World3D)));
  1512. }
  1513. root->set_as_audio_listener_3d(true);
  1514. #endif // _3D_DISABLED
  1515. set_physics_interpolation_enabled(GLOBAL_DEF("physics/common/physics_interpolation", false));
  1516. // Always disable jitter fix if physics interpolation is enabled -
  1517. // Jitter fix will interfere with interpolation, and is not necessary
  1518. // when interpolation is active.
  1519. if (is_physics_interpolation_enabled()) {
  1520. Engine::get_singleton()->set_physics_jitter_fix(0);
  1521. }
  1522. // Initialize network state.
  1523. set_multiplayer(MultiplayerAPI::create_default_interface());
  1524. root->set_as_audio_listener_2d(true);
  1525. current_scene = nullptr;
  1526. const int msaa_mode_2d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_2d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
  1527. root->set_msaa_2d(Viewport::MSAA(msaa_mode_2d));
  1528. const int msaa_mode_3d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_3d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
  1529. root->set_msaa_3d(Viewport::MSAA(msaa_mode_3d));
  1530. const bool transparent_background = GLOBAL_DEF("rendering/viewport/transparent_background", false);
  1531. root->set_transparent_background(transparent_background);
  1532. const bool use_hdr_2d = GLOBAL_DEF_RST_BASIC("rendering/viewport/hdr_2d", false);
  1533. root->set_use_hdr_2d(use_hdr_2d);
  1534. const int ssaa_mode = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"), 0);
  1535. root->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
  1536. const bool use_taa = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/use_taa", false);
  1537. root->set_use_taa(use_taa);
  1538. const bool use_debanding = GLOBAL_DEF("rendering/anti_aliasing/quality/use_debanding", false);
  1539. root->set_use_debanding(use_debanding);
  1540. const bool use_occlusion_culling = GLOBAL_DEF("rendering/occlusion_culling/use_occlusion_culling", false);
  1541. root->set_use_occlusion_culling(use_occlusion_culling);
  1542. float mesh_lod_threshold = GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "rendering/mesh_lod/lod_change/threshold_pixels", PROPERTY_HINT_RANGE, "0,1024,0.1"), 1.0);
  1543. root->set_mesh_lod_threshold(mesh_lod_threshold);
  1544. bool snap_2d_transforms = GLOBAL_DEF_BASIC("rendering/2d/snap/snap_2d_transforms_to_pixel", false);
  1545. root->set_snap_2d_transforms_to_pixel(snap_2d_transforms);
  1546. bool snap_2d_vertices = GLOBAL_DEF("rendering/2d/snap/snap_2d_vertices_to_pixel", false);
  1547. root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);
  1548. // We setup VRS for the main viewport here, in the editor this will have little effect.
  1549. const int vrs_mode = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/vrs/mode", PROPERTY_HINT_ENUM, String::utf8("Disabled,Texture,XR")), 0);
  1550. root->set_vrs_mode(Viewport::VRSMode(vrs_mode));
  1551. const String vrs_texture_path = String(GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/vrs/texture", PROPERTY_HINT_FILE, "*.bmp,*.png,*.tga,*.webp"), String())).strip_edges();
  1552. if (vrs_mode == 1 && !vrs_texture_path.is_empty()) {
  1553. Ref<Image> vrs_image;
  1554. vrs_image.instantiate();
  1555. Error load_err = ImageLoader::load_image(vrs_texture_path, vrs_image);
  1556. if (load_err) {
  1557. ERR_PRINT("Non-existing or invalid VRS texture at '" + vrs_texture_path + "'.");
  1558. } else {
  1559. Ref<ImageTexture> vrs_texture;
  1560. vrs_texture.instantiate();
  1561. vrs_texture->create_from_image(vrs_image);
  1562. root->set_vrs_texture(vrs_texture);
  1563. }
  1564. }
  1565. int shadowmap_size = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_size", PROPERTY_HINT_RANGE, "256,16384"), 4096);
  1566. GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_size.mobile", 2048);
  1567. bool shadowmap_16_bits = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_16_bits", true);
  1568. int atlas_q0 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
  1569. int atlas_q1 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
  1570. int atlas_q2 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 3);
  1571. int atlas_q3 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 4);
  1572. root->set_positional_shadow_atlas_size(shadowmap_size);
  1573. root->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
  1574. root->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
  1575. root->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
  1576. root->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
  1577. root->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
  1578. Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/oversize", PROPERTY_HINT_ENUM, "100%,120%,150%,200%"), 1)));
  1579. root->set_sdf_oversize(sdf_oversize);
  1580. Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/scale", PROPERTY_HINT_ENUM, "100%,50%,25%"), 1)));
  1581. root->set_sdf_scale(sdf_scale);
  1582. #ifndef _3D_DISABLED
  1583. { // Load default fallback environment.
  1584. // Get possible extensions.
  1585. List<String> exts;
  1586. ResourceLoader::get_recognized_extensions_for_type("Environment", &exts);
  1587. String ext_hint;
  1588. for (const String &E : exts) {
  1589. if (!ext_hint.is_empty()) {
  1590. ext_hint += ",";
  1591. }
  1592. ext_hint += "*." + E;
  1593. }
  1594. // Get path.
  1595. String env_path = GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/environment/defaults/default_environment", PROPERTY_HINT_FILE, ext_hint), "");
  1596. // Setup property.
  1597. env_path = env_path.strip_edges();
  1598. if (!env_path.is_empty()) {
  1599. Ref<Environment> env = ResourceLoader::load(env_path);
  1600. if (env.is_valid()) {
  1601. root->get_world_3d()->set_fallback_environment(env);
  1602. } else {
  1603. if (Engine::get_singleton()->is_editor_hint()) {
  1604. // File was erased, clear the field.
  1605. ProjectSettings::get_singleton()->set("rendering/environment/defaults/default_environment", "");
  1606. } else {
  1607. // File was erased, notify user.
  1608. ERR_PRINT("Default Environment as specified in the project setting \"rendering/environment/defaults/default_environment\" could not be loaded.");
  1609. }
  1610. }
  1611. }
  1612. }
  1613. #endif // _3D_DISABLED
  1614. root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true));
  1615. root->connect("close_requested", callable_mp(this, &SceneTree::_main_window_close));
  1616. root->connect("go_back_requested", callable_mp(this, &SceneTree::_main_window_go_back));
  1617. root->connect(SceneStringName(focus_entered), callable_mp(this, &SceneTree::_main_window_focus_in));
  1618. #ifdef TOOLS_ENABLED
  1619. edited_scene_root = nullptr;
  1620. #endif
  1621. process_groups.push_back(&default_process_group);
  1622. }
  1623. SceneTree::~SceneTree() {
  1624. if (prev_scene) {
  1625. memdelete(prev_scene);
  1626. prev_scene = nullptr;
  1627. }
  1628. if (pending_new_scene) {
  1629. memdelete(pending_new_scene);
  1630. pending_new_scene = nullptr;
  1631. }
  1632. if (root) {
  1633. root->_set_tree(nullptr);
  1634. root->_propagate_after_exit_tree();
  1635. memdelete(root);
  1636. }
  1637. // Process groups are not deleted immediately, they may remain around. Delete them now.
  1638. for (uint32_t i = 0; i < process_groups.size(); i++) {
  1639. if (process_groups[i] != &default_process_group) {
  1640. memdelete(process_groups[i]);
  1641. }
  1642. }
  1643. memdelete(process_group_call_queue_allocator);
  1644. if (singleton == this) {
  1645. singleton = nullptr;
  1646. }
  1647. }