2
0

scene_tree.cpp 64 KB

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