tile_map_layer.cpp 152 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877
  1. /**************************************************************************/
  2. /* tile_map_layer.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 "tile_map_layer.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/math/geometry_2d.h"
  33. #include "core/math/random_pcg.h"
  34. #include "core/templates/a_hash_map.h"
  35. #include "scene/2d/tile_map.h"
  36. #include "scene/gui/control.h"
  37. #include "scene/resources/2d/navigation_mesh_source_geometry_data_2d.h"
  38. #include "scene/resources/world_2d.h"
  39. #ifndef PHYSICS_2D_DISABLED
  40. #include "servers/physics_server_2d.h"
  41. #endif // PHYSICS_3D_DISABLED
  42. #ifndef NAVIGATION_2D_DISABLED
  43. #include "servers/navigation_server_2d.h"
  44. Callable TileMapLayer::_navmesh_source_geometry_parsing_callback;
  45. RID TileMapLayer::_navmesh_source_geometry_parser;
  46. #endif // NAVIGATION_2D_DISABLED
  47. Vector2i TileMapLayer::_coords_to_quadrant_coords(const Vector2i &p_coords, const int p_quadrant_size) const {
  48. return Vector2i(
  49. p_coords.x > 0 ? p_coords.x / p_quadrant_size : (p_coords.x - (p_quadrant_size - 1)) / p_quadrant_size,
  50. p_coords.y > 0 ? p_coords.y / p_quadrant_size : (p_coords.y - (p_quadrant_size - 1)) / p_quadrant_size);
  51. }
  52. #ifdef DEBUG_ENABLED
  53. /////////////////////////////// Debug //////////////////////////////////////////
  54. constexpr int TILE_MAP_DEBUG_QUADRANT_SIZE = 16;
  55. void TileMapLayer::_debug_update(bool p_force_cleanup) {
  56. RenderingServer *rs = RenderingServer::get_singleton();
  57. // Check if we should cleanup everything.
  58. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  59. if (forced_cleanup) {
  60. for (KeyValue<Vector2i, Ref<DebugQuadrant>> &kv : debug_quadrant_map) {
  61. // Free the quadrant.
  62. Ref<DebugQuadrant> &debug_quadrant = kv.value;
  63. if (debug_quadrant->canvas_item.is_valid()) {
  64. rs->free(debug_quadrant->canvas_item);
  65. }
  66. if (debug_quadrant->physics_mesh.is_valid()) {
  67. rs->free(debug_quadrant->physics_mesh);
  68. }
  69. }
  70. debug_quadrant_map.clear();
  71. _debug_was_cleaned_up = true;
  72. return;
  73. }
  74. // Check if anything is dirty, in such a case, redraw debug.
  75. bool anything_changed = false;
  76. for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
  77. if (dirty.flags[i]) {
  78. anything_changed = true;
  79. break;
  80. }
  81. }
  82. // List all debug quadrants to update.
  83. HashSet<Vector2i> quadrants_to_updates;
  84. if (_debug_was_cleaned_up || anything_changed) {
  85. // Update all cells.
  86. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  87. CellData &cell_data = kv.value;
  88. quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
  89. #ifndef PHYSICS_2D_DISABLED
  90. // Physics quadrants are drawn from their origin.
  91. Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
  92. quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
  93. #endif // PHYSICS_2D_DISABLED
  94. }
  95. } else {
  96. // Update dirty cells.
  97. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  98. CellData &cell_data = *cell_data_list_element->self();
  99. quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
  100. #ifndef PHYSICS_2D_DISABLED
  101. // Physics quadrants are drawn from their origin.
  102. Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
  103. quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
  104. #endif // PHYSICS_2D_DISABLED
  105. }
  106. }
  107. // Create new quadrants if needed.
  108. for (const Vector2i &quadrant_coords : quadrants_to_updates) {
  109. if (!debug_quadrant_map.has(quadrant_coords)) {
  110. // Create a new quadrant and add it to the quadrant map.
  111. Ref<DebugQuadrant> new_quadrant;
  112. new_quadrant.instantiate();
  113. new_quadrant->quadrant_coords = quadrant_coords;
  114. debug_quadrant_map[quadrant_coords] = new_quadrant;
  115. }
  116. }
  117. // Second pass on modified cells to update the list of cells per quandrant.
  118. if (_debug_was_cleaned_up || anything_changed) {
  119. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  120. CellData &cell_data = kv.value;
  121. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
  122. if (!cell_data.debug_quadrant_list_element.in_list()) {
  123. debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
  124. }
  125. }
  126. } else {
  127. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  128. CellData &cell_data = *cell_data_list_element->self();
  129. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
  130. if (!cell_data.debug_quadrant_list_element.in_list()) {
  131. debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
  132. }
  133. }
  134. }
  135. // Update those quadrants.
  136. bool needs_set_not_interpolated = is_inside_tree() && get_tree()->is_physics_interpolation_enabled() && !is_physics_interpolated();
  137. for (const Vector2i &quadrant_coords : quadrants_to_updates) {
  138. Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[quadrant_coords];
  139. // Update the quadrant's canvas item.
  140. RID &ci = debug_quadrant->canvas_item;
  141. if (ci.is_valid()) {
  142. rs->canvas_item_clear(ci);
  143. } else {
  144. ci = rs->canvas_item_create();
  145. if (needs_set_not_interpolated) {
  146. rs->canvas_item_set_interpolated(ci, false);
  147. }
  148. rs->canvas_item_set_z_index(ci, RS::CANVAS_ITEM_Z_MAX - 1);
  149. rs->canvas_item_set_parent(ci, get_canvas_item());
  150. }
  151. const Vector2 quadrant_pos = tile_set->map_to_local(debug_quadrant->quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
  152. Transform2D xform(0, quadrant_pos);
  153. rs->canvas_item_set_transform(ci, xform);
  154. #ifndef PHYSICS_2D_DISABLED
  155. // Draw physics.
  156. _physics_draw_quadrant_debug(ci, *debug_quadrant.ptr());
  157. #endif // PHYSICS_2D_DISABLED
  158. // Draw debug info.
  159. for (SelfList<CellData> *cell_data_list_element = debug_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  160. CellData &cell_data = *cell_data_list_element->self();
  161. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  162. _rendering_draw_cell_debug(ci, quadrant_pos, cell_data);
  163. #ifndef NAVIGATION_2D_DISABLED
  164. _navigation_draw_cell_debug(ci, quadrant_pos, cell_data);
  165. #endif // NAVIGATION_2D_DISABLED
  166. _scenes_draw_cell_debug(ci, quadrant_pos, cell_data);
  167. debug_quadrant->drawn_to = true;
  168. }
  169. }
  170. // Free the quadrants that were not drawn to.
  171. if (!debug_quadrant->drawn_to) {
  172. // Free the quadrant.
  173. if (ci.is_valid()) {
  174. rs->free(ci);
  175. }
  176. debug_quadrant_map.erase(quadrant_coords);
  177. }
  178. }
  179. _debug_was_cleaned_up = false;
  180. }
  181. #endif // DEBUG_ENABLED
  182. /////////////////////////////// Rendering //////////////////////////////////////
  183. void TileMapLayer::_rendering_update(bool p_force_cleanup) {
  184. RenderingServer *rs = RenderingServer::get_singleton();
  185. // Check if we should cleanup everything.
  186. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  187. // ----------- Layer level processing -----------
  188. if (!forced_cleanup) {
  189. // Modulate the layer.
  190. Color layer_modulate = get_modulate();
  191. #ifdef TOOLS_ENABLED
  192. if (highlight_mode == HIGHLIGHT_MODE_BELOW) {
  193. layer_modulate = layer_modulate.darkened(0.5);
  194. } else if (highlight_mode == HIGHLIGHT_MODE_ABOVE) {
  195. layer_modulate = layer_modulate.darkened(0.5);
  196. layer_modulate.a *= 0.3;
  197. }
  198. #endif // TOOLS_ENABLED
  199. rs->canvas_item_set_modulate(get_canvas_item(), layer_modulate);
  200. }
  201. // ----------- Quadrants processing -----------
  202. // List all rendering quadrants to update, creating new ones if needed.
  203. SelfList<RenderingQuadrant>::List dirty_rendering_quadrant_list;
  204. // Check if anything changed that might change the quadrant shape.
  205. // If so, recreate everything.
  206. bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] || dirty.flags[DIRTY_FLAGS_TILE_SET] ||
  207. (is_y_sort_enabled() && (dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] || dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] || dirty.flags[DIRTY_FLAGS_LAYER_LOCAL_TRANSFORM])) ||
  208. (!is_y_sort_enabled() && dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE]);
  209. // Free all quadrants.
  210. if (forced_cleanup || quadrant_shape_changed) {
  211. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  212. for (const RID &ci : kv.value->canvas_items) {
  213. if (ci.is_valid()) {
  214. rs->free(ci);
  215. }
  216. }
  217. kv.value->cells.clear();
  218. }
  219. rendering_quadrant_map.clear();
  220. _rendering_was_cleaned_up = true;
  221. }
  222. if (!forced_cleanup) {
  223. // List all quadrants to update, recreating them if needed.
  224. if (dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _rendering_was_cleaned_up) {
  225. // Update all cells.
  226. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  227. CellData &cell_data = kv.value;
  228. _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
  229. }
  230. } else {
  231. // Update dirty cells.
  232. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  233. CellData &cell_data = *cell_data_list_element->self();
  234. _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
  235. }
  236. }
  237. // Update all dirty quadrants.
  238. bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
  239. for (SelfList<RenderingQuadrant> *quadrant_list_element = dirty_rendering_quadrant_list.first(); quadrant_list_element;) {
  240. SelfList<RenderingQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
  241. const Ref<RenderingQuadrant> &rendering_quadrant = quadrant_list_element->self();
  242. // Check if the quadrant has a tile.
  243. bool has_a_tile = false;
  244. for (SelfList<CellData> *cell_data_list_element = rendering_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  245. CellData &cell_data = *cell_data_list_element->self();
  246. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  247. has_a_tile = true;
  248. break;
  249. }
  250. }
  251. if (has_a_tile) {
  252. // Process the quadrant.
  253. // First, clear the quadrant's canvas items.
  254. for (RID &ci : rendering_quadrant->canvas_items) {
  255. rs->free(ci);
  256. }
  257. rendering_quadrant->canvas_items.clear();
  258. // Sort the quadrant cells.
  259. if (is_y_sort_enabled() && x_draw_order_reversed) {
  260. rendering_quadrant->cells.sort_custom<CellDataYSortedXReversedComparator>();
  261. } else {
  262. rendering_quadrant->cells.sort();
  263. }
  264. // Those allow to group cell per material or z-index.
  265. Ref<Material> prev_material;
  266. int prev_z_index = 0;
  267. RID prev_ci;
  268. for (SelfList<CellData> *cell_data_quadrant_list_element = rendering_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
  269. CellData &cell_data = *cell_data_quadrant_list_element->self();
  270. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
  271. // Get the tile data.
  272. const TileData *tile_data;
  273. if (cell_data.runtime_tile_data_cache) {
  274. tile_data = cell_data.runtime_tile_data_cache;
  275. } else {
  276. tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
  277. }
  278. Ref<Material> mat = tile_data->get_material();
  279. int tile_z_index = tile_data->get_z_index();
  280. // Quandrant pos.
  281. // --- CanvasItems ---
  282. RID ci;
  283. // Check if the material or the z_index changed.
  284. if (prev_ci == RID() || prev_material != mat || prev_z_index != tile_z_index) {
  285. // If so, create a new CanvasItem.
  286. ci = rs->canvas_item_create();
  287. if (needs_set_not_interpolated) {
  288. rs->canvas_item_set_interpolated(ci, false);
  289. }
  290. if (mat.is_valid()) {
  291. rs->canvas_item_set_material(ci, mat->get_rid());
  292. }
  293. rs->canvas_item_set_parent(ci, get_canvas_item());
  294. rs->canvas_item_set_use_parent_material(ci, mat.is_null());
  295. Transform2D xform(0, rendering_quadrant->canvas_items_position);
  296. rs->canvas_item_set_transform(ci, xform);
  297. rs->canvas_item_set_light_mask(ci, get_light_mask());
  298. rs->canvas_item_set_z_as_relative_to_parent(ci, true);
  299. rs->canvas_item_set_z_index(ci, tile_z_index);
  300. rs->canvas_item_set_self_modulate(ci, get_self_modulate());
  301. rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
  302. rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
  303. rendering_quadrant->canvas_items.push_back(ci);
  304. prev_ci = ci;
  305. prev_material = mat;
  306. prev_z_index = tile_z_index;
  307. } else {
  308. // Keep the same canvas_item to draw on.
  309. ci = prev_ci;
  310. }
  311. const Vector2 local_tile_pos = tile_set->map_to_local(cell_data.coords);
  312. // Random animation offset.
  313. real_t random_animation_offset = 0.0;
  314. if (atlas_source->get_tile_animation_mode(cell_data.cell.get_atlas_coords()) != TileSetAtlasSource::TILE_ANIMATION_MODE_DEFAULT) {
  315. Array to_hash = { local_tile_pos, get_instance_id() }; // Use instance id as a random hash
  316. random_animation_offset = RandomPCG(to_hash.hash()).randf();
  317. }
  318. // Drawing the tile in the canvas item.
  319. draw_tile(ci, local_tile_pos - rendering_quadrant->canvas_items_position, tile_set, cell_data.cell.source_id, cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile, -1, tile_data, random_animation_offset);
  320. }
  321. // Reset physics interpolation for any recreated canvas items.
  322. if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
  323. for (const RID &ci : rendering_quadrant->canvas_items) {
  324. rs->canvas_item_reset_physics_interpolation(ci);
  325. }
  326. }
  327. } else {
  328. // Free the quadrant.
  329. for (const RID &ci : rendering_quadrant->canvas_items) {
  330. if (ci.is_valid()) {
  331. rs->free(ci);
  332. }
  333. }
  334. rendering_quadrant->cells.clear();
  335. rendering_quadrant_map.erase(rendering_quadrant->quadrant_coords);
  336. }
  337. quadrant_list_element = next_quadrant_list_element;
  338. }
  339. dirty_rendering_quadrant_list.clear();
  340. // Reset the drawing indices.
  341. {
  342. int index = -(int64_t)0x80000000; // Always must be drawn below children.
  343. // Sort the quadrants coords per local coordinates.
  344. RBMap<Vector2, Ref<RenderingQuadrant>, RenderingQuadrant::CoordsWorldComparator> local_to_map;
  345. for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  346. Ref<RenderingQuadrant> &rendering_quadrant = kv.value;
  347. local_to_map[tile_set->map_to_local(rendering_quadrant->quadrant_coords)] = rendering_quadrant;
  348. }
  349. // Sort the quadrants.
  350. for (const KeyValue<Vector2, Ref<RenderingQuadrant>> &E : local_to_map) {
  351. for (const RID &ci : E.value->canvas_items) {
  352. RS::get_singleton()->canvas_item_set_draw_index(ci, index++);
  353. }
  354. }
  355. }
  356. // Updates on rendering changes.
  357. if (dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] ||
  358. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] ||
  359. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] ||
  360. dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE]) {
  361. for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  362. Ref<RenderingQuadrant> &rendering_quadrant = kv.value;
  363. for (const RID &ci : rendering_quadrant->canvas_items) {
  364. rs->canvas_item_set_light_mask(ci, get_light_mask());
  365. rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
  366. rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
  367. rs->canvas_item_set_self_modulate(ci, get_self_modulate());
  368. }
  369. }
  370. }
  371. }
  372. // ----------- Occluders processing -----------
  373. if (forced_cleanup || !occlusion_enabled) {
  374. // Clean everything.
  375. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  376. _rendering_occluders_clear_cell(kv.value);
  377. }
  378. } else {
  379. if (_rendering_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
  380. // Update all cells.
  381. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  382. _rendering_occluders_update_cell(kv.value);
  383. }
  384. } else {
  385. // Update dirty cells.
  386. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  387. CellData &cell_data = *cell_data_list_element->self();
  388. _rendering_occluders_update_cell(cell_data);
  389. }
  390. }
  391. }
  392. // -----------
  393. // Mark the rendering state as up to date.
  394. _rendering_was_cleaned_up = forced_cleanup || !occlusion_enabled;
  395. }
  396. void TileMapLayer::_rendering_notification(int p_what) {
  397. RenderingServer *rs = RenderingServer::get_singleton();
  398. if (p_what == NOTIFICATION_TRANSFORM_CHANGED || p_what == NOTIFICATION_ENTER_CANVAS || p_what == NOTIFICATION_VISIBILITY_CHANGED) {
  399. if (tile_set.is_valid()) {
  400. Transform2D tilemap_xform = get_global_transform();
  401. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  402. const CellData &cell_data = kv.value;
  403. for (const LocalVector<RID> &polygons : cell_data.occluders) {
  404. for (const RID &rid : polygons) {
  405. if (rid.is_null()) {
  406. continue;
  407. }
  408. Transform2D xform(0, tile_set->map_to_local(kv.key));
  409. rs->canvas_light_occluder_attach_to_canvas(rid, get_canvas());
  410. rs->canvas_light_occluder_set_transform(rid, tilemap_xform * xform);
  411. }
  412. }
  413. }
  414. }
  415. } else if (p_what == NOTIFICATION_RESET_PHYSICS_INTERPOLATION) {
  416. if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
  417. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  418. for (const RID &ci : kv.value->canvas_items) {
  419. if (ci.is_valid()) {
  420. rs->canvas_item_reset_physics_interpolation(ci);
  421. }
  422. }
  423. }
  424. }
  425. }
  426. }
  427. void TileMapLayer::_rendering_quadrants_update_cell(CellData &r_cell_data, SelfList<RenderingQuadrant>::List &r_dirty_rendering_quadrant_list) {
  428. // Check if the cell is valid and retrieve its y_sort_origin.
  429. bool is_valid = false;
  430. int tile_y_sort_origin = 0;
  431. TileSetSource *source;
  432. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  433. source = *tile_set->get_source(r_cell_data.cell.source_id);
  434. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  435. if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  436. is_valid = true;
  437. const TileData *tile_data;
  438. if (r_cell_data.runtime_tile_data_cache) {
  439. tile_data = r_cell_data.runtime_tile_data_cache;
  440. } else {
  441. tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
  442. }
  443. tile_y_sort_origin = tile_data->get_y_sort_origin();
  444. }
  445. }
  446. if (is_valid) {
  447. // Get the quadrant coords.
  448. Vector2 canvas_items_position;
  449. Vector2i quadrant_coords;
  450. if (is_y_sort_enabled()) {
  451. canvas_items_position = Vector2(0, tile_set->map_to_local(r_cell_data.coords).y + tile_y_sort_origin + y_sort_origin);
  452. quadrant_coords = canvas_items_position * 100;
  453. } else {
  454. const Vector2i &coords = r_cell_data.coords;
  455. // Rounding down, instead of simply rounding towards zero (truncating).
  456. quadrant_coords = _coords_to_quadrant_coords(coords, rendering_quadrant_size);
  457. canvas_items_position = tile_set->map_to_local(rendering_quadrant_size * quadrant_coords);
  458. }
  459. Ref<RenderingQuadrant> rendering_quadrant;
  460. if (rendering_quadrant_map.has(quadrant_coords)) {
  461. // Reuse existing rendering quadrant.
  462. rendering_quadrant = rendering_quadrant_map[quadrant_coords];
  463. } else {
  464. // Create a new rendering quadrant.
  465. rendering_quadrant.instantiate();
  466. rendering_quadrant->quadrant_coords = quadrant_coords;
  467. rendering_quadrant->canvas_items_position = canvas_items_position;
  468. rendering_quadrant_map[quadrant_coords] = rendering_quadrant;
  469. }
  470. // Mark the old quadrant as dirty (if it exists).
  471. if (r_cell_data.rendering_quadrant.is_valid()) {
  472. if (!r_cell_data.rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  473. r_dirty_rendering_quadrant_list.add(&r_cell_data.rendering_quadrant->dirty_quadrant_list_element);
  474. }
  475. }
  476. // Remove the cell from that quadrant.
  477. if (r_cell_data.rendering_quadrant_list_element.in_list()) {
  478. r_cell_data.rendering_quadrant_list_element.remove_from_list();
  479. }
  480. // Add the cell to its new quadrant.
  481. r_cell_data.rendering_quadrant = rendering_quadrant;
  482. r_cell_data.rendering_quadrant->cells.add(&r_cell_data.rendering_quadrant_list_element);
  483. // Add the new quadrant to the dirty quadrant list.
  484. if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  485. r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
  486. }
  487. } else {
  488. Ref<RenderingQuadrant> rendering_quadrant = r_cell_data.rendering_quadrant;
  489. // Remove the cell from its quadrant.
  490. r_cell_data.rendering_quadrant = Ref<RenderingQuadrant>();
  491. if (r_cell_data.rendering_quadrant_list_element.in_list()) {
  492. rendering_quadrant->cells.remove(&r_cell_data.rendering_quadrant_list_element);
  493. }
  494. if (rendering_quadrant.is_valid()) {
  495. // Add the quadrant to the dirty quadrant list.
  496. if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
  497. r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
  498. }
  499. }
  500. }
  501. }
  502. void TileMapLayer::_rendering_occluders_clear_cell(CellData &r_cell_data) {
  503. RenderingServer *rs = RenderingServer::get_singleton();
  504. // Free the occluders.
  505. for (const LocalVector<RID> &polygons : r_cell_data.occluders) {
  506. for (const RID &rid : polygons) {
  507. rs->free(rid);
  508. }
  509. }
  510. r_cell_data.occluders.clear();
  511. }
  512. void TileMapLayer::_rendering_occluders_update_cell(CellData &r_cell_data) {
  513. RenderingServer *rs = RenderingServer::get_singleton();
  514. // Free unused occluders then resize the occluder array.
  515. for (uint32_t i = tile_set->get_occlusion_layers_count(); i < r_cell_data.occluders.size(); i++) {
  516. for (const RID &occluder_id : r_cell_data.occluders[i]) {
  517. if (occluder_id.is_valid()) {
  518. rs->free(occluder_id);
  519. }
  520. }
  521. }
  522. r_cell_data.occluders.resize(tile_set->get_occlusion_layers_count());
  523. TileSetSource *source;
  524. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  525. source = *tile_set->get_source(r_cell_data.cell.source_id);
  526. if (source->has_tile(r_cell_data.cell.get_atlas_coords()) && source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  527. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  528. if (atlas_source) {
  529. // Get the tile data.
  530. const TileData *tile_data;
  531. if (r_cell_data.runtime_tile_data_cache) {
  532. tile_data = r_cell_data.runtime_tile_data_cache;
  533. } else {
  534. tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
  535. }
  536. // Transform flags.
  537. bool flip_h = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  538. bool flip_v = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  539. bool transpose = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  540. // Create, update or clear occluders.
  541. bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
  542. for (uint32_t occlusion_layer_index = 0; occlusion_layer_index < r_cell_data.occluders.size(); occlusion_layer_index++) {
  543. LocalVector<RID> &occluders = r_cell_data.occluders[occlusion_layer_index];
  544. // Free unused occluders then resize the occluders array.
  545. for (uint32_t i = tile_data->get_occluder_polygons_count(occlusion_layer_index); i < r_cell_data.occluders[occlusion_layer_index].size(); i++) {
  546. RID occluder_id = occluders[i];
  547. if (occluder_id.is_valid()) {
  548. rs->free(occluder_id);
  549. }
  550. }
  551. occluders.resize(tile_data->get_occluder_polygons_count(occlusion_layer_index));
  552. for (uint32_t occlusion_polygon_index = 0; occlusion_polygon_index < occluders.size(); occlusion_polygon_index++) {
  553. RID &occluder = occluders[occlusion_polygon_index];
  554. Ref<OccluderPolygon2D> occluder_polygon = tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index);
  555. if (occluder_polygon.is_valid()) {
  556. // Create or update occluder.
  557. Transform2D xform;
  558. xform.set_origin(tile_set->map_to_local(r_cell_data.coords));
  559. if (!occluder.is_valid()) {
  560. occluder = rs->canvas_light_occluder_create();
  561. if (needs_set_not_interpolated) {
  562. rs->canvas_light_occluder_set_interpolated(occluder, false);
  563. }
  564. }
  565. rs->canvas_light_occluder_set_transform(occluder, get_global_transform() * xform);
  566. rs->canvas_light_occluder_set_polygon(occluder, tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index, flip_h, flip_v, transpose)->get_rid());
  567. rs->canvas_light_occluder_attach_to_canvas(occluder, get_canvas());
  568. rs->canvas_light_occluder_set_light_mask(occluder, tile_set->get_occlusion_layer_light_mask(occlusion_layer_index));
  569. rs->canvas_light_occluder_set_as_sdf_collision(occluder, tile_set->get_occlusion_layer_sdf_collision(occlusion_layer_index));
  570. } else {
  571. // Clear occluder.
  572. if (occluder.is_valid()) {
  573. rs->free(occluder);
  574. occluder = RID();
  575. }
  576. }
  577. }
  578. }
  579. return;
  580. }
  581. }
  582. }
  583. // If we did not return earlier, clear the cell.
  584. _rendering_occluders_clear_cell(r_cell_data);
  585. }
  586. #ifdef DEBUG_ENABLED
  587. void TileMapLayer::_rendering_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  588. ERR_FAIL_COND(tile_set.is_null());
  589. if (!Engine::get_singleton()->is_editor_hint()) {
  590. return;
  591. }
  592. // Draw a placeholder for tiles needing one.
  593. RenderingServer *rs = RenderingServer::get_singleton();
  594. const TileMapCell &c = r_cell_data.cell;
  595. TileSetSource *source;
  596. if (tile_set->has_source(c.source_id)) {
  597. source = *tile_set->get_source(c.source_id);
  598. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  599. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  600. if (atlas_source) {
  601. Vector2i grid_size = atlas_source->get_atlas_grid_size();
  602. if (atlas_source->get_runtime_texture().is_null() || c.get_atlas_coords().x >= grid_size.x || c.get_atlas_coords().y >= grid_size.y) {
  603. // Generate a random color from the hashed values of the tiles.
  604. Array to_hash = { c.source_id, c.get_atlas_coords(), c.alternative_tile };
  605. uint32_t hash = RandomPCG(to_hash.hash()).rand();
  606. Color color;
  607. color = color.from_hsv(
  608. (float)((hash >> 24) & 0xFF) / 256.0,
  609. Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
  610. Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
  611. 0.8);
  612. // Draw a placeholder tile.
  613. Transform2D cell_to_quadrant;
  614. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  615. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  616. rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
  617. }
  618. }
  619. }
  620. }
  621. }
  622. #endif // DEBUG_ENABLED
  623. /////////////////////////////// Physics //////////////////////////////////////
  624. #ifndef PHYSICS_2D_DISABLED
  625. void TileMapLayer::_physics_update(bool p_force_cleanup) {
  626. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  627. // Check if we should cleanup everything.
  628. bool forced_cleanup = p_force_cleanup || !enabled || !collision_enabled || !is_inside_tree() || tile_set.is_null();
  629. // ----------- Quadrants processing -----------
  630. // List all physics quadrants to update, creating new ones if needed.
  631. SelfList<PhysicsQuadrant>::List dirty_physics_quadrant_list;
  632. // Check if anything changed that might change the quadrant shape.
  633. // If so, recreate everything.
  634. bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE];
  635. // Free all quadrants.
  636. if (forced_cleanup || quadrant_shape_changed) {
  637. for (const KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  638. // Clear bodies.
  639. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  640. if (kvbody.value.body.is_valid()) {
  641. bodies_coords.erase(kvbody.value.body);
  642. ps->free(kvbody.value.body);
  643. }
  644. }
  645. kv.value->bodies.clear();
  646. kv.value->cells.clear();
  647. }
  648. physics_quadrant_map.clear();
  649. _physics_was_cleaned_up = true;
  650. }
  651. if (!forced_cleanup) {
  652. RID space = get_world_2d()->get_space();
  653. Transform2D gl_transform = get_global_transform();
  654. // List all quadrants to update, recreating them if needed.
  655. if (dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _physics_was_cleaned_up) {
  656. // Update all cells.
  657. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  658. CellData &cell_data = kv.value;
  659. _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
  660. }
  661. } else {
  662. // Update dirty cells.
  663. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  664. CellData &cell_data = *cell_data_list_element->self();
  665. _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
  666. }
  667. }
  668. // Update all dirty quadrants.
  669. for (SelfList<PhysicsQuadrant> *quadrant_list_element = dirty_physics_quadrant_list.first(); quadrant_list_element;) {
  670. SelfList<PhysicsQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
  671. const Ref<PhysicsQuadrant> &physics_quadrant = quadrant_list_element->self();
  672. // Check if the quadrant has a tile.
  673. bool has_a_tile = false;
  674. for (SelfList<CellData> *cell_data_list_element = physics_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  675. CellData &cell_data = *cell_data_list_element->self();
  676. if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
  677. has_a_tile = true;
  678. break;
  679. }
  680. }
  681. if (has_a_tile) {
  682. // Process the quadrant.
  683. // First, clear the quadrant bodies.
  684. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  685. RID &body = kvbody.value.body;
  686. if (body.is_valid()) {
  687. bodies_coords.erase(body);
  688. ps->free(body);
  689. body = RID();
  690. }
  691. }
  692. physics_quadrant->bodies.clear();
  693. physics_quadrant->shapes.clear();
  694. // Quadrant origin
  695. Vector2 quadrant_origin = tile_set->map_to_local(physics_quadrant->quadrant_coords);
  696. // Recreate the quadrant bodies.
  697. for (uint32_t tile_set_physics_layer = 0; tile_set_physics_layer < (uint32_t)tile_set->get_physics_layers_count(); tile_set_physics_layer++) {
  698. Ref<PhysicsMaterial> physics_material = tile_set->get_physics_layer_physics_material(tile_set_physics_layer);
  699. uint32_t physics_layer = tile_set->get_physics_layer_collision_layer(tile_set_physics_layer);
  700. uint32_t physics_mask = tile_set->get_physics_layer_collision_mask(tile_set_physics_layer);
  701. // Merge polygons together for each quadrant.
  702. for (SelfList<CellData> *cell_data_quadrant_list_element = physics_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
  703. CellData &cell_data = *cell_data_quadrant_list_element->self();
  704. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
  705. // Get the tile data.
  706. const TileData *tile_data;
  707. if (cell_data.runtime_tile_data_cache) {
  708. tile_data = cell_data.runtime_tile_data_cache;
  709. } else {
  710. tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
  711. }
  712. // Transform flags.
  713. bool flip_h = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  714. bool flip_v = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  715. bool transpose = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  716. Vector2 linear_velocity = tile_data->get_constant_linear_velocity(tile_set_physics_layer);
  717. real_t angular_velocity = tile_data->get_constant_angular_velocity(tile_set_physics_layer);
  718. // Setup polygons for merge.
  719. for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(tile_set_physics_layer); polygon_index++) {
  720. // Iterate over the polygons.
  721. int shapes_count = tile_data->get_collision_polygon_shapes_count(tile_set_physics_layer, polygon_index);
  722. // Check if we need to create a new body.
  723. PhysicsQuadrant::PhysicsBodyKey physics_body_key;
  724. physics_body_key.physics_layer = tile_set_physics_layer;
  725. physics_body_key.linear_velocity = linear_velocity;
  726. physics_body_key.angular_velocity = angular_velocity;
  727. physics_body_key.one_way_collision = tile_data->is_collision_polygon_one_way(tile_set_physics_layer, polygon_index);
  728. physics_body_key.one_way_collision_margin = tile_data->get_collision_polygon_one_way_margin(tile_set_physics_layer, polygon_index);
  729. physics_body_key.y_origin = map_to_local(cell_data.coords).y;
  730. if (!physics_quadrant->bodies.has(physics_body_key)) {
  731. RID body = ps->body_create();
  732. physics_quadrant->bodies[physics_body_key] = {};
  733. physics_quadrant->bodies[physics_body_key].body = body;
  734. bodies_coords[body] = physics_quadrant->quadrant_coords;
  735. // Create or update the body.
  736. ps->body_set_mode(body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
  737. ps->body_set_space(body, space);
  738. Transform2D xform;
  739. xform.set_origin(quadrant_origin);
  740. xform = gl_transform * xform;
  741. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
  742. ps->body_attach_object_instance_id(body, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
  743. ps->body_set_collision_layer(body, physics_layer);
  744. ps->body_set_collision_mask(body, physics_mask);
  745. ps->body_set_pickable(body, false);
  746. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
  747. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
  748. if (!physics_material.is_valid()) {
  749. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, 0);
  750. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, 1);
  751. } else {
  752. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, physics_material->computed_bounce());
  753. ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, physics_material->computed_friction());
  754. }
  755. }
  756. for (int shape_index = 0; shape_index < shapes_count; shape_index++) {
  757. Ref<ConvexPolygonShape2D> shape = tile_data->get_collision_polygon_shape(tile_set_physics_layer, polygon_index, shape_index, flip_h, flip_v, transpose);
  758. // Translate the polygon.
  759. Vector<Vector2> convex_polygon = shape->get_points();
  760. for (int i = 0; i < convex_polygon.size(); i++) {
  761. convex_polygon.set(i, convex_polygon[i] + tile_set->map_to_local(cell_data.coords) - quadrant_origin);
  762. }
  763. physics_quadrant->bodies[physics_body_key].polygons.push_back(convex_polygon);
  764. }
  765. }
  766. }
  767. }
  768. // Iterate over the bodies
  769. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  770. // Actually merge the polygons.
  771. Vector<Vector<Vector2>> out_polygons;
  772. Vector<Vector<Vector2>> out_holes;
  773. Geometry2D::merge_many_polygons(kvbody.value.polygons, out_polygons, out_holes);
  774. // Create shapes for each polygon.
  775. int body_shape_index = 0;
  776. Vector<Vector<Vector2>> convex_polygons = Geometry2D::decompose_many_polygons_in_convex(out_polygons, out_holes);
  777. for (Vector<Vector2> &convex_polygon : convex_polygons) {
  778. Ref<ConvexPolygonShape2D> shape;
  779. shape.instantiate();
  780. shape->set_points(convex_polygon);
  781. ps->body_add_shape(kvbody.value.body, shape->get_rid());
  782. ps->body_set_shape_as_one_way_collision(kvbody.value.body, body_shape_index, kvbody.key.one_way_collision, kvbody.key.one_way_collision_margin);
  783. physics_quadrant->shapes.push_back(shape);
  784. body_shape_index++;
  785. }
  786. }
  787. } else {
  788. // Free the quadrant.
  789. for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kv : physics_quadrant->bodies) {
  790. RID &body = kv.value.body;
  791. if (body.is_valid()) {
  792. bodies_coords.erase(body);
  793. ps->free(body);
  794. }
  795. }
  796. physics_quadrant->bodies.clear();
  797. physics_quadrant->cells.clear();
  798. physics_quadrant_map.erase(physics_quadrant->quadrant_coords);
  799. }
  800. quadrant_list_element = next_quadrant_list_element;
  801. }
  802. dirty_physics_quadrant_list.clear();
  803. // Updates on physics changes.
  804. if (dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES]) {
  805. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  806. Ref<PhysicsQuadrant> &physics_quadrant = kv.value;
  807. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  808. ps->body_set_mode(kvbody.value.body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
  809. }
  810. }
  811. }
  812. }
  813. // -----------
  814. // Mark the physics state as up to date.
  815. _physics_was_cleaned_up = forced_cleanup || !occlusion_enabled;
  816. }
  817. void TileMapLayer::_physics_quadrants_update_cell(CellData &r_cell_data, SelfList<PhysicsQuadrant>::List &r_dirty_physics_quadrant_list) {
  818. // Check if the cell is valid and retrieve its y_sort_origin.
  819. bool is_valid = false;
  820. TileSetSource *source;
  821. if (tile_set->has_source(r_cell_data.cell.source_id)) {
  822. source = *tile_set->get_source(r_cell_data.cell.source_id);
  823. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  824. if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
  825. is_valid = true;
  826. }
  827. }
  828. if (is_valid) {
  829. // Get the quadrant coords.
  830. const Vector2i &coords = r_cell_data.coords;
  831. Vector2i quadrant_coords = _coords_to_quadrant_coords(coords, physics_quadrant_size);
  832. Ref<PhysicsQuadrant> physics_quadrant;
  833. if (physics_quadrant_map.has(quadrant_coords)) {
  834. // Reuse existing physics quadrant.
  835. physics_quadrant = physics_quadrant_map[quadrant_coords];
  836. } else {
  837. // Create a new physics quadrant.
  838. physics_quadrant.instantiate();
  839. physics_quadrant->quadrant_coords = quadrant_coords;
  840. physics_quadrant_map[quadrant_coords] = physics_quadrant;
  841. }
  842. // Mark the old quadrant as dirty (if it exists).
  843. if (r_cell_data.physics_quadrant.is_valid()) {
  844. if (!r_cell_data.physics_quadrant->dirty_quadrant_list_element.in_list()) {
  845. r_dirty_physics_quadrant_list.add(&r_cell_data.physics_quadrant->dirty_quadrant_list_element);
  846. }
  847. }
  848. // Remove the cell from that quadrant.
  849. if (r_cell_data.physics_quadrant_list_element.in_list()) {
  850. r_cell_data.physics_quadrant_list_element.remove_from_list();
  851. }
  852. // Add the cell to its new quadrant.
  853. r_cell_data.physics_quadrant = physics_quadrant;
  854. r_cell_data.physics_quadrant->cells.add(&r_cell_data.physics_quadrant_list_element);
  855. // Add the new quadrant to the dirty quadrant list.
  856. if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
  857. r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
  858. }
  859. } else {
  860. Ref<PhysicsQuadrant> physics_quadrant = r_cell_data.physics_quadrant;
  861. // Remove the cell from its quadrant.
  862. r_cell_data.physics_quadrant = Ref<PhysicsQuadrant>();
  863. if (r_cell_data.physics_quadrant_list_element.in_list()) {
  864. physics_quadrant->cells.remove(&r_cell_data.physics_quadrant_list_element);
  865. }
  866. if (physics_quadrant.is_valid()) {
  867. // Add the quadrant to the dirty quadrant list.
  868. if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
  869. r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
  870. }
  871. }
  872. }
  873. }
  874. void TileMapLayer::_physics_notification(int p_what) {
  875. Transform2D gl_transform = get_global_transform();
  876. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  877. switch (p_what) {
  878. case NOTIFICATION_TRANSFORM_CHANGED:
  879. // Move the collisison shapes along with the TileMap.
  880. if (is_inside_tree() && tile_set.is_valid()) {
  881. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  882. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  883. const RID &body = kvbody.value.body;
  884. Transform2D xform(0, tile_set->map_to_local(kv.key));
  885. xform = gl_transform * xform;
  886. ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
  887. }
  888. }
  889. }
  890. break;
  891. case NOTIFICATION_ENTER_TREE:
  892. // Changes in the tree may cause the space to change (e.g. when reparenting to a SubViewport).
  893. if (is_inside_tree()) {
  894. RID space = get_world_2d()->get_space();
  895. for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
  896. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
  897. const RID &body = kvbody.value.body;
  898. ps->body_set_space(body, space);
  899. }
  900. }
  901. }
  902. }
  903. }
  904. #ifdef DEBUG_ENABLED
  905. void TileMapLayer::_physics_draw_quadrant_debug(const RID &p_canvas_item, DebugQuadrant &r_debug_quadrant) {
  906. // Draw the debug collision shapes.
  907. ERR_FAIL_COND(tile_set.is_null());
  908. if (!get_tree()) {
  909. return;
  910. }
  911. bool show_collision = false;
  912. switch (collision_visibility_mode) {
  913. case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
  914. show_collision = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_collisions_hint();
  915. break;
  916. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
  917. show_collision = false;
  918. break;
  919. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
  920. show_collision = true;
  921. break;
  922. }
  923. if (!show_collision) {
  924. return;
  925. }
  926. RenderingServer *rs = RenderingServer::get_singleton();
  927. PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
  928. const Color &debug_collision_color = get_tree()->get_debug_collisions_color();
  929. RandomPCG rand;
  930. rand.seed(hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.y, hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.x)));
  931. // Create a mesh.
  932. if (!r_debug_quadrant.physics_mesh.is_valid()) {
  933. r_debug_quadrant.physics_mesh = rs->mesh_create();
  934. }
  935. rs->mesh_clear(r_debug_quadrant.physics_mesh);
  936. // Redraw all shapes from the physics quadrants
  937. Rect2i covered_cell_area = Rect2i(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE, Vector2i(TILE_MAP_DEBUG_QUADRANT_SIZE, TILE_MAP_DEBUG_QUADRANT_SIZE));
  938. Vector2i first_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_position() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
  939. Vector2i last_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_end() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
  940. LocalVector<Vector2> face_vertex_array;
  941. LocalVector<Color> face_color_array;
  942. LocalVector<int32_t> face_index_array;
  943. LocalVector<Vector2> line_vertex_array;
  944. LocalVector<Color> line_color_array;
  945. AHashMap<Vector2, int> vertex_map;
  946. // Arrays to generate a mesh.
  947. for (int x = first_physics_quadrant_coords.x; x < last_physics_quadrant_coords.x; x++) {
  948. for (int y = first_physics_quadrant_coords.y; y < last_physics_quadrant_coords.y; y++) {
  949. const Vector2i physics_quadrant_coords = Vector2i(x, y);
  950. if (!physics_quadrant_map.has(physics_quadrant_coords)) {
  951. continue;
  952. }
  953. r_debug_quadrant.drawn_to = true;
  954. Ref<PhysicsQuadrant> physics_quadrant = physics_quadrant_map[physics_quadrant_coords];
  955. const Vector2 debug_quadrant_pos = tile_set->map_to_local(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
  956. Transform2D global_to_debug_quadrant = (get_global_transform() * Transform2D(0, debug_quadrant_pos)).affine_inverse();
  957. // Clear arrays for new quadrant while keeping allocated memory.
  958. face_vertex_array.clear();
  959. face_color_array.clear();
  960. face_index_array.clear();
  961. line_vertex_array.clear();
  962. line_color_array.clear();
  963. vertex_map.clear();
  964. for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
  965. const RID &body = kvbody.value.body;
  966. int shape_count = ps->body_get_shape_count(body);
  967. if (shape_count == 0) {
  968. continue;
  969. }
  970. const Transform2D body_to_quadrant = global_to_debug_quadrant * Transform2D(ps->body_get_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM));
  971. Color face_random_variation_color;
  972. face_random_variation_color.set_hsv(
  973. debug_collision_color.get_h() + rand.random(-1.0, 1.0) * 0.05,
  974. debug_collision_color.get_s(),
  975. debug_collision_color.get_v() + rand.random(-1.0, 1.0) * 0.1,
  976. debug_collision_color.a);
  977. const Color line_random_variation_color = face_random_variation_color.lightened(0.2);
  978. for (int shape_index = 0; shape_index < shape_count; shape_index++) {
  979. const RID &shape = ps->body_get_shape(body, shape_index);
  980. const Transform2D &shape_xform = ps->body_get_shape_transform(body, shape_index);
  981. const PhysicsServer2D::ShapeType &type = ps->shape_get_type(shape);
  982. if (type == PhysicsServer2D::SHAPE_CONVEX_POLYGON) {
  983. PackedVector2Array outline = ps->shape_get_data(shape);
  984. const int outline_size = outline.size();
  985. if (outline_size < 3) {
  986. continue;
  987. }
  988. const Transform2D outline_xform = body_to_quadrant * shape_xform;
  989. // Adds debug mesh lines.
  990. Vector2 previous_line_vertex = outline_xform.xform(outline[outline_size - 1]);
  991. for (int i = 0; i < outline_size; i++) {
  992. Vector2 line_vertex = outline_xform.xform(outline[i]);
  993. line_vertex_array.push_back(previous_line_vertex);
  994. line_vertex_array.push_back(line_vertex);
  995. previous_line_vertex = line_vertex;
  996. line_color_array.push_back(line_random_variation_color);
  997. line_color_array.push_back(line_random_variation_color);
  998. }
  999. // Adds debug mesh faces.
  1000. const Vector2 vertex1 = outline_xform.xform(outline[0]);
  1001. const Vector2 vertex2 = outline_xform.xform(outline[1]);
  1002. Vector2 vertex3;
  1003. int vertex1_index = -1;
  1004. int vertex2_index = -1;
  1005. int vertex3_index = -1;
  1006. int last_vertex3_index = -1;
  1007. // Find triangle fan anchor vertex1 index.
  1008. {
  1009. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex1);
  1010. if (!E) {
  1011. E = vertex_map.insert(vertex1, vertex_map.size());
  1012. face_vertex_array.push_back(vertex1);
  1013. face_color_array.push_back(face_random_variation_color);
  1014. }
  1015. vertex1_index = E->value;
  1016. }
  1017. // Find starting vertex2 index.
  1018. {
  1019. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex2);
  1020. if (!E) {
  1021. E = vertex_map.insert(vertex2, vertex_map.size());
  1022. face_vertex_array.push_back(vertex2);
  1023. face_color_array.push_back(face_random_variation_color);
  1024. }
  1025. vertex2_index = E->value;
  1026. }
  1027. // Create mesh triangle face fan from outline vertices using vertex_map indices.
  1028. for (int i = 1; i < outline_size - 1; i++) {
  1029. if (i > 1) {
  1030. vertex2_index = last_vertex3_index;
  1031. }
  1032. vertex3 = outline_xform.xform(outline[i + 1]);
  1033. {
  1034. AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex3);
  1035. if (!E) {
  1036. E = vertex_map.insert(vertex3, vertex_map.size());
  1037. face_vertex_array.push_back(vertex3);
  1038. face_color_array.push_back(face_random_variation_color);
  1039. }
  1040. vertex3_index = E->value;
  1041. last_vertex3_index = vertex3_index;
  1042. }
  1043. face_index_array.push_back(vertex1_index);
  1044. face_index_array.push_back(vertex2_index);
  1045. face_index_array.push_back(vertex3_index);
  1046. }
  1047. } else {
  1048. WARN_PRINT("Wrong shape type for a tile, should be SHAPE_CONVEX_POLYGON.");
  1049. }
  1050. }
  1051. }
  1052. if (face_index_array.size() > 2) {
  1053. Array face_mesh_array;
  1054. face_mesh_array.resize(Mesh::ARRAY_MAX);
  1055. face_mesh_array[Mesh::ARRAY_VERTEX] = Vector<Vector2>(face_vertex_array);
  1056. face_mesh_array[Mesh::ARRAY_INDEX] = Vector<int32_t>(face_index_array);
  1057. face_mesh_array[Mesh::ARRAY_COLOR] = Vector<Color>(face_color_array);
  1058. rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_TRIANGLES, face_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
  1059. Array line_mesh_array;
  1060. line_mesh_array.resize(Mesh::ARRAY_MAX);
  1061. line_mesh_array[Mesh::ARRAY_VERTEX] = Vector<Vector2>(line_vertex_array);
  1062. line_mesh_array[Mesh::ARRAY_COLOR] = Vector<Color>(line_color_array);
  1063. rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_LINES, line_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
  1064. }
  1065. }
  1066. }
  1067. rs->canvas_item_add_mesh(p_canvas_item, r_debug_quadrant.physics_mesh, Transform2D());
  1068. }
  1069. #endif // DEBUG_ENABLED
  1070. #endif // PHYSICS_2D_DISABLED
  1071. #ifndef NAVIGATION_2D_DISABLED
  1072. /////////////////////////////// Navigation //////////////////////////////////////
  1073. void TileMapLayer::_navigation_update(bool p_force_cleanup) {
  1074. ERR_FAIL_NULL(NavigationServer2D::get_singleton());
  1075. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1076. // Check if we should cleanup everything.
  1077. bool forced_cleanup = p_force_cleanup || !enabled || !navigation_enabled || !is_inside_tree() || tile_set.is_null();
  1078. // ----------- Layer level processing -----------
  1079. // All this processing is kept for compatibility with the TileMap node.
  1080. // Otherwise, layers shall use the World2D navigation map or define a custom one with set_navigation_map(...).
  1081. if (tile_map_node) {
  1082. if (forced_cleanup) {
  1083. if (navigation_map_override.is_valid()) {
  1084. ns->free(navigation_map_override);
  1085. navigation_map_override = RID();
  1086. }
  1087. } else {
  1088. // Update navigation maps.
  1089. if (!navigation_map_override.is_valid()) {
  1090. if (layer_index_in_tile_map_node > 0) {
  1091. // Create a dedicated map for each layer.
  1092. RID new_layer_map = ns->map_create();
  1093. // Set the default NavigationPolygon cell_size on the new map as a mismatch causes an error.
  1094. ns->map_set_cell_size(new_layer_map, NavigationDefaults2D::NAV_MESH_CELL_SIZE);
  1095. ns->map_set_active(new_layer_map, true);
  1096. navigation_map_override = new_layer_map;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. // ----------- Navigation regions processing -----------
  1102. if (forced_cleanup) {
  1103. // Clean everything.
  1104. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1105. _navigation_clear_cell(kv.value);
  1106. }
  1107. } else {
  1108. if (_navigation_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP]) {
  1109. // Update all cells.
  1110. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1111. _navigation_update_cell(kv.value);
  1112. }
  1113. } else {
  1114. // Update dirty cells.
  1115. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1116. CellData &cell_data = *cell_data_list_element->self();
  1117. _navigation_update_cell(cell_data);
  1118. }
  1119. }
  1120. }
  1121. // -----------
  1122. // Mark the navigation state as up to date.
  1123. _navigation_was_cleaned_up = forced_cleanup;
  1124. }
  1125. void TileMapLayer::_navigation_notification(int p_what) {
  1126. if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
  1127. if (tile_set.is_valid()) {
  1128. Transform2D tilemap_xform = get_global_transform();
  1129. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1130. const CellData &cell_data = kv.value;
  1131. // Update navigation regions transform.
  1132. for (const RID &region : cell_data.navigation_regions) {
  1133. if (!region.is_valid()) {
  1134. continue;
  1135. }
  1136. Transform2D tile_transform;
  1137. tile_transform.set_origin(tile_set->map_to_local(kv.key));
  1138. NavigationServer2D::get_singleton()->region_set_transform(region, tilemap_xform * tile_transform);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. void TileMapLayer::_navigation_clear_cell(CellData &r_cell_data) {
  1145. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1146. // Clear navigation shapes.
  1147. for (uint32_t i = 0; i < r_cell_data.navigation_regions.size(); i++) {
  1148. const RID &region = r_cell_data.navigation_regions[i];
  1149. if (region.is_valid()) {
  1150. ns->region_set_map(region, RID());
  1151. ns->free(region);
  1152. }
  1153. }
  1154. r_cell_data.navigation_regions.clear();
  1155. }
  1156. void TileMapLayer::_navigation_update_cell(CellData &r_cell_data) {
  1157. NavigationServer2D *ns = NavigationServer2D::get_singleton();
  1158. Transform2D gl_xform = get_global_transform();
  1159. RID navigation_map = navigation_map_override.is_valid() ? navigation_map_override : get_world_2d()->get_navigation_map();
  1160. ERR_FAIL_COND(navigation_map.is_null());
  1161. // Get the navigation polygons and create regions.
  1162. TileMapCell &c = r_cell_data.cell;
  1163. TileSetSource *source;
  1164. if (tile_set->has_source(c.source_id)) {
  1165. source = *tile_set->get_source(c.source_id);
  1166. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1167. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1168. if (atlas_source) {
  1169. const TileData *tile_data;
  1170. if (r_cell_data.runtime_tile_data_cache) {
  1171. tile_data = r_cell_data.runtime_tile_data_cache;
  1172. } else {
  1173. tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1174. }
  1175. // Transform flags.
  1176. bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  1177. bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  1178. bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  1179. // Free unused regions then resize the regions array.
  1180. for (uint32_t i = tile_set->get_navigation_layers_count(); i < r_cell_data.navigation_regions.size(); i++) {
  1181. RID &region = r_cell_data.navigation_regions[i];
  1182. if (region.is_valid()) {
  1183. ns->region_set_map(region, RID());
  1184. ns->free(region);
  1185. region = RID();
  1186. }
  1187. }
  1188. r_cell_data.navigation_regions.resize(tile_set->get_navigation_layers_count());
  1189. // Create, update or clear regions.
  1190. for (uint32_t navigation_layer_index = 0; navigation_layer_index < r_cell_data.navigation_regions.size(); navigation_layer_index++) {
  1191. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer_index, flip_h, flip_v, transpose);
  1192. RID &region = r_cell_data.navigation_regions[navigation_layer_index];
  1193. if (navigation_polygon.is_valid() && (navigation_polygon->get_polygon_count() > 0 || navigation_polygon->get_outline_count() > 0)) {
  1194. // Create or update regions.
  1195. Transform2D tile_transform;
  1196. tile_transform.set_origin(tile_set->map_to_local(r_cell_data.coords));
  1197. if (!region.is_valid()) {
  1198. region = ns->region_create();
  1199. }
  1200. ns->region_set_owner_id(region, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
  1201. ns->region_set_map(region, navigation_map);
  1202. ns->region_set_transform(region, gl_xform * tile_transform);
  1203. ns->region_set_navigation_layers(region, tile_set->get_navigation_layer_layers(navigation_layer_index));
  1204. ns->region_set_navigation_polygon(region, navigation_polygon);
  1205. } else {
  1206. // Clear region.
  1207. if (region.is_valid()) {
  1208. ns->region_set_map(region, RID());
  1209. ns->free(region);
  1210. region = RID();
  1211. }
  1212. }
  1213. }
  1214. return;
  1215. }
  1216. }
  1217. }
  1218. // If we did not return earlier, clear the cell.
  1219. _navigation_clear_cell(r_cell_data);
  1220. }
  1221. #ifdef DEBUG_ENABLED
  1222. void TileMapLayer::_navigation_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  1223. // Draw the debug collision shapes.
  1224. bool show_navigation = false;
  1225. switch (navigation_visibility_mode) {
  1226. case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
  1227. show_navigation = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_navigation_hint();
  1228. break;
  1229. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
  1230. show_navigation = false;
  1231. break;
  1232. case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
  1233. show_navigation = true;
  1234. break;
  1235. }
  1236. if (!show_navigation) {
  1237. return;
  1238. }
  1239. // Check if the navigation is used.
  1240. if (r_cell_data.navigation_regions.is_empty()) {
  1241. return;
  1242. }
  1243. RenderingServer *rs = RenderingServer::get_singleton();
  1244. const NavigationServer2D *ns2d = NavigationServer2D::get_singleton();
  1245. bool enabled_geometry_face_random_color = ns2d->get_debug_navigation_enable_geometry_face_random_color();
  1246. bool enabled_edge_lines = ns2d->get_debug_navigation_enable_edge_lines();
  1247. Color debug_face_color = ns2d->get_debug_navigation_geometry_face_color();
  1248. Color debug_edge_color = ns2d->get_debug_navigation_geometry_edge_color();
  1249. RandomPCG rand;
  1250. const TileMapCell &c = r_cell_data.cell;
  1251. TileSetSource *source;
  1252. if (tile_set->has_source(c.source_id)) {
  1253. source = *tile_set->get_source(c.source_id);
  1254. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1255. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1256. if (atlas_source) {
  1257. const TileData *tile_data;
  1258. if (r_cell_data.runtime_tile_data_cache) {
  1259. tile_data = r_cell_data.runtime_tile_data_cache;
  1260. } else {
  1261. tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1262. }
  1263. Transform2D cell_to_quadrant;
  1264. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  1265. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  1266. for (int layer_index = 0; layer_index < tile_set->get_navigation_layers_count(); layer_index++) {
  1267. bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  1268. bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  1269. bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  1270. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(layer_index, flip_h, flip_v, transpose);
  1271. if (navigation_polygon.is_valid()) {
  1272. Vector<Vector2> navigation_polygon_vertices = navigation_polygon->get_vertices();
  1273. if (navigation_polygon_vertices.size() < 3) {
  1274. continue;
  1275. }
  1276. for (int i = 0; i < navigation_polygon->get_polygon_count(); i++) {
  1277. // An array of vertices for this polygon.
  1278. Vector<int> polygon = navigation_polygon->get_polygon(i);
  1279. Vector<Vector2> debug_polygon_vertices;
  1280. debug_polygon_vertices.resize(polygon.size());
  1281. for (int j = 0; j < polygon.size(); j++) {
  1282. ERR_FAIL_INDEX(polygon[j], navigation_polygon_vertices.size());
  1283. debug_polygon_vertices.write[j] = navigation_polygon_vertices[polygon[j]];
  1284. }
  1285. // Generate the polygon color, slightly randomly modified from the settings one.
  1286. Color random_variation_color = debug_face_color;
  1287. if (enabled_geometry_face_random_color) {
  1288. random_variation_color.set_hsv(
  1289. debug_face_color.get_h() + rand.random(-1.0, 1.0) * 0.1,
  1290. debug_face_color.get_s(),
  1291. debug_face_color.get_v() + rand.random(-1.0, 1.0) * 0.2);
  1292. }
  1293. random_variation_color.a = debug_face_color.a;
  1294. Vector<Color> debug_face_colors;
  1295. debug_face_colors.push_back(random_variation_color);
  1296. rs->canvas_item_add_polygon(p_canvas_item, debug_polygon_vertices, debug_face_colors);
  1297. if (enabled_edge_lines) {
  1298. Vector<Color> debug_edge_colors;
  1299. debug_edge_colors.push_back(debug_edge_color);
  1300. debug_polygon_vertices.push_back(debug_polygon_vertices[0]); // Add first again for closing polyline.
  1301. rs->canvas_item_add_polyline(p_canvas_item, debug_polygon_vertices, debug_edge_colors);
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. }
  1308. }
  1309. }
  1310. #endif // DEBUG_ENABLED
  1311. #endif // NAVIGATION_2D_DISABLED
  1312. /////////////////////////////// Scenes //////////////////////////////////////
  1313. void TileMapLayer::_scenes_update(bool p_force_cleanup) {
  1314. // Check if we should cleanup everything.
  1315. bool forced_cleanup = p_force_cleanup || !enabled || !is_inside_tree() || tile_set.is_null();
  1316. if (forced_cleanup) {
  1317. // Clean everything.
  1318. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1319. _scenes_clear_cell(kv.value);
  1320. }
  1321. } else {
  1322. if (_scenes_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE]) {
  1323. // Update all cells.
  1324. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  1325. _scenes_update_cell(kv.value);
  1326. }
  1327. } else {
  1328. // Update dirty cells.
  1329. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1330. CellData &cell_data = *cell_data_list_element->self();
  1331. _scenes_update_cell(cell_data);
  1332. }
  1333. }
  1334. }
  1335. // -----------
  1336. // Mark the scenes state as up to date.
  1337. _scenes_was_cleaned_up = forced_cleanup;
  1338. }
  1339. void TileMapLayer::_scenes_clear_cell(CellData &r_cell_data) {
  1340. // Cleanup existing scene.
  1341. Node *node = nullptr;
  1342. if (tile_map_node) {
  1343. // Compatibility with TileMap.
  1344. node = tile_map_node->get_node_or_null(r_cell_data.scene);
  1345. } else {
  1346. node = get_node_or_null(r_cell_data.scene);
  1347. }
  1348. if (node) {
  1349. node->queue_free();
  1350. }
  1351. r_cell_data.scene = "";
  1352. }
  1353. void TileMapLayer::_scenes_update_cell(CellData &r_cell_data) {
  1354. // Clear the scene in any case.
  1355. _scenes_clear_cell(r_cell_data);
  1356. // Create the scene.
  1357. const TileMapCell &c = r_cell_data.cell;
  1358. TileSetSource *source;
  1359. if (tile_set->has_source(c.source_id)) {
  1360. source = *tile_set->get_source(c.source_id);
  1361. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1362. TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
  1363. if (scenes_collection_source) {
  1364. Ref<PackedScene> packed_scene = scenes_collection_source->get_scene_tile_scene(c.alternative_tile);
  1365. if (packed_scene.is_valid()) {
  1366. Node *scene = packed_scene->instantiate();
  1367. Control *scene_as_control = Object::cast_to<Control>(scene);
  1368. Node2D *scene_as_node2d = Object::cast_to<Node2D>(scene);
  1369. if (scene_as_control) {
  1370. scene_as_control->set_position(tile_set->map_to_local(r_cell_data.coords) + scene_as_control->get_position());
  1371. } else if (scene_as_node2d) {
  1372. Transform2D xform;
  1373. xform.set_origin(tile_set->map_to_local(r_cell_data.coords));
  1374. scene_as_node2d->set_transform(xform * scene_as_node2d->get_transform());
  1375. }
  1376. if (tile_map_node) {
  1377. // Compatibility with TileMap.
  1378. tile_map_node->add_child(scene);
  1379. } else {
  1380. add_child(scene);
  1381. }
  1382. r_cell_data.scene = scene->get_name();
  1383. }
  1384. }
  1385. }
  1386. }
  1387. }
  1388. #ifdef DEBUG_ENABLED
  1389. void TileMapLayer::_scenes_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
  1390. ERR_FAIL_COND(tile_set.is_null());
  1391. if (!Engine::get_singleton()->is_editor_hint()) {
  1392. return;
  1393. }
  1394. // Draw a placeholder for scenes needing one.
  1395. RenderingServer *rs = RenderingServer::get_singleton();
  1396. const TileMapCell &c = r_cell_data.cell;
  1397. TileSetSource *source;
  1398. if (tile_set->has_source(c.source_id)) {
  1399. source = *tile_set->get_source(c.source_id);
  1400. if (!source->has_tile(c.get_atlas_coords()) || !source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1401. return;
  1402. }
  1403. TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
  1404. if (scenes_collection_source) {
  1405. if (scenes_collection_source->get_scene_tile_scene(c.alternative_tile).is_null() || scenes_collection_source->get_scene_tile_display_placeholder(c.alternative_tile)) {
  1406. // Generate a random color from the hashed values of the tiles.
  1407. Array to_hash = { c.source_id, c.alternative_tile };
  1408. uint32_t hash = RandomPCG(to_hash.hash()).rand();
  1409. Color color;
  1410. color = color.from_hsv(
  1411. (float)((hash >> 24) & 0xFF) / 256.0,
  1412. Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
  1413. Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
  1414. 0.8);
  1415. // Draw a placeholder tile.
  1416. Transform2D cell_to_quadrant;
  1417. cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
  1418. rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
  1419. rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
  1420. }
  1421. }
  1422. }
  1423. }
  1424. #endif // DEBUG_ENABLED
  1425. /////////////////////////////////////////////////////////////////////
  1426. void TileMapLayer::_build_runtime_update_tile_data(bool p_force_cleanup) {
  1427. // Check if we should cleanup everything.
  1428. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  1429. if (!forced_cleanup) {
  1430. bool valid_runtime_update = GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update);
  1431. bool valid_runtime_update_for_tilemap = tile_map_node && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update); // For keeping compatibility.
  1432. if (valid_runtime_update || valid_runtime_update_for_tilemap) {
  1433. bool use_tilemap_for_runtime = valid_runtime_update_for_tilemap && !valid_runtime_update;
  1434. if (_runtime_update_tile_data_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
  1435. _runtime_update_needs_all_cells_cleaned_up = true;
  1436. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1437. _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime);
  1438. }
  1439. } else if (dirty.flags[DIRTY_FLAGS_LAYER_RUNTIME_UPDATE]) {
  1440. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1441. _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime, true);
  1442. }
  1443. } else {
  1444. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1445. CellData &cell_data = *cell_data_list_element->self();
  1446. _build_runtime_update_tile_data_for_cell(cell_data, use_tilemap_for_runtime);
  1447. }
  1448. }
  1449. }
  1450. }
  1451. // -----------
  1452. // Mark the navigation state as up to date.
  1453. _runtime_update_tile_data_was_cleaned_up = forced_cleanup;
  1454. }
  1455. void TileMapLayer::_build_runtime_update_tile_data_for_cell(CellData &r_cell_data, bool p_use_tilemap_for_runtime, bool p_auto_add_to_dirty_list) {
  1456. TileMapCell &c = r_cell_data.cell;
  1457. TileSetSource *source;
  1458. if (tile_set->has_source(c.source_id)) {
  1459. source = *tile_set->get_source(c.source_id);
  1460. if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
  1461. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  1462. if (atlas_source) {
  1463. bool ret = false;
  1464. if (p_use_tilemap_for_runtime) {
  1465. // Compatibility with TileMap.
  1466. if (tile_map_node->GDVIRTUAL_CALL(_use_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, ret) && ret) {
  1467. TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1468. // Create the runtime TileData.
  1469. TileData *tile_data_runtime_use = tile_data->duplicate();
  1470. tile_data_runtime_use->set_allow_transform(true);
  1471. r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
  1472. tile_map_node->GDVIRTUAL_CALL(_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, tile_data_runtime_use);
  1473. if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
  1474. dirty.cell_list.add(&r_cell_data.dirty_list_element);
  1475. }
  1476. }
  1477. } else {
  1478. if (GDVIRTUAL_CALL(_use_tile_data_runtime_update, r_cell_data.coords, ret) && ret) {
  1479. TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
  1480. // Create the runtime TileData.
  1481. TileData *tile_data_runtime_use = tile_data->duplicate();
  1482. tile_data_runtime_use->set_allow_transform(true);
  1483. r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
  1484. GDVIRTUAL_CALL(_tile_data_runtime_update, r_cell_data.coords, tile_data_runtime_use);
  1485. if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
  1486. dirty.cell_list.add(&r_cell_data.dirty_list_element);
  1487. }
  1488. }
  1489. }
  1490. }
  1491. }
  1492. }
  1493. }
  1494. void TileMapLayer::_clear_runtime_update_tile_data() {
  1495. if (_runtime_update_needs_all_cells_cleaned_up) {
  1496. for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1497. _clear_runtime_update_tile_data_for_cell(E.value);
  1498. }
  1499. _runtime_update_needs_all_cells_cleaned_up = false;
  1500. } else {
  1501. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1502. CellData &r_cell_data = *cell_data_list_element->self();
  1503. _clear_runtime_update_tile_data_for_cell(r_cell_data);
  1504. }
  1505. }
  1506. }
  1507. void TileMapLayer::_clear_runtime_update_tile_data_for_cell(CellData &r_cell_data) {
  1508. // Clear the runtime tile data.
  1509. if (r_cell_data.runtime_tile_data_cache) {
  1510. memdelete(r_cell_data.runtime_tile_data_cache);
  1511. r_cell_data.runtime_tile_data_cache = nullptr;
  1512. }
  1513. }
  1514. void TileMapLayer::_update_cells_callback(bool p_force_cleanup) {
  1515. if (!GDVIRTUAL_IS_OVERRIDDEN(_update_cells)) {
  1516. return;
  1517. }
  1518. // Check if we should cleanup everything.
  1519. bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
  1520. // List all the dirty cell's positions to notify script of cell updates.
  1521. TypedArray<Vector2i> dirty_cell_positions;
  1522. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1523. CellData &cell_data = *cell_data_list_element->self();
  1524. dirty_cell_positions.push_back(cell_data.coords);
  1525. }
  1526. GDVIRTUAL_CALL(_update_cells, dirty_cell_positions, forced_cleanup);
  1527. }
  1528. TileSet::TerrainsPattern TileMapLayer::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, const RBSet<TerrainConstraint> &p_constraints, TileSet::TerrainsPattern p_current_pattern) const {
  1529. if (tile_set.is_null()) {
  1530. return TileSet::TerrainsPattern();
  1531. }
  1532. // Returns all tiles compatible with the given constraints.
  1533. RBMap<TileSet::TerrainsPattern, int> terrain_pattern_score;
  1534. RBSet<TileSet::TerrainsPattern> pattern_set = tile_set->get_terrains_pattern_set(p_terrain_set);
  1535. ERR_FAIL_COND_V(pattern_set.is_empty(), TileSet::TerrainsPattern());
  1536. for (TileSet::TerrainsPattern &terrain_pattern : pattern_set) {
  1537. int score = 0;
  1538. // Check the center bit constraint.
  1539. TerrainConstraint terrain_constraint = TerrainConstraint(tile_set, p_position, terrain_pattern.get_terrain());
  1540. const RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
  1541. if (in_set_constraint_element) {
  1542. if (in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
  1543. score += in_set_constraint_element->get().get_priority();
  1544. }
  1545. } else if (p_current_pattern.get_terrain() != terrain_pattern.get_terrain()) {
  1546. continue; // Ignore a pattern that cannot keep bits without constraints unmodified.
  1547. }
  1548. // Check the surrounding bits
  1549. bool invalid_pattern = false;
  1550. for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
  1551. TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
  1552. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  1553. // Check if the bit is compatible with the constraints.
  1554. TerrainConstraint terrain_bit_constraint = TerrainConstraint(tile_set, p_position, bit, terrain_pattern.get_terrain_peering_bit(bit));
  1555. in_set_constraint_element = p_constraints.find(terrain_bit_constraint);
  1556. if (in_set_constraint_element) {
  1557. if (in_set_constraint_element->get().get_terrain() != terrain_bit_constraint.get_terrain()) {
  1558. score += in_set_constraint_element->get().get_priority();
  1559. }
  1560. } else if (p_current_pattern.get_terrain_peering_bit(bit) != terrain_pattern.get_terrain_peering_bit(bit)) {
  1561. invalid_pattern = true; // Ignore a pattern that cannot keep bits without constraints unmodified.
  1562. break;
  1563. }
  1564. }
  1565. }
  1566. if (invalid_pattern) {
  1567. continue;
  1568. }
  1569. terrain_pattern_score[terrain_pattern] = score;
  1570. }
  1571. // Compute the minimum score.
  1572. TileSet::TerrainsPattern min_score_pattern = p_current_pattern;
  1573. int min_score = INT32_MAX;
  1574. for (KeyValue<TileSet::TerrainsPattern, int> E : terrain_pattern_score) {
  1575. if (E.value < min_score) {
  1576. min_score_pattern = E.key;
  1577. min_score = E.value;
  1578. }
  1579. }
  1580. return min_score_pattern;
  1581. }
  1582. RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_added_pattern(const Vector2i &p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const {
  1583. if (tile_set.is_null()) {
  1584. return RBSet<TerrainConstraint>();
  1585. }
  1586. // Compute the constraints needed from the surrounding tiles.
  1587. RBSet<TerrainConstraint> output;
  1588. output.insert(TerrainConstraint(tile_set, p_position, p_terrains_pattern.get_terrain()));
  1589. for (uint32_t i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
  1590. TileSet::CellNeighbor side = TileSet::CellNeighbor(i);
  1591. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, side)) {
  1592. TerrainConstraint c = TerrainConstraint(tile_set, p_position, side, p_terrains_pattern.get_terrain_peering_bit(side));
  1593. output.insert(c);
  1594. }
  1595. }
  1596. return output;
  1597. }
  1598. RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_painted_cells_list(const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const {
  1599. if (tile_set.is_null()) {
  1600. return RBSet<TerrainConstraint>();
  1601. }
  1602. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), RBSet<TerrainConstraint>());
  1603. // Build a set of dummy constraints to get the constrained points.
  1604. RBSet<TerrainConstraint> dummy_constraints;
  1605. for (const Vector2i &E : p_painted) {
  1606. for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) { // Iterates over neighbor bits.
  1607. TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
  1608. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  1609. dummy_constraints.insert(TerrainConstraint(tile_set, E, bit, -1));
  1610. }
  1611. }
  1612. }
  1613. // For each constrained point, we get all overlapping tiles, and select the most adequate terrain for it.
  1614. RBSet<TerrainConstraint> constraints;
  1615. for (const TerrainConstraint &E_constraint : dummy_constraints) {
  1616. HashMap<int, int> terrain_count;
  1617. // Count the number of occurrences per terrain.
  1618. HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = E_constraint.get_overlapping_coords_and_peering_bits();
  1619. for (const KeyValue<Vector2i, TileSet::CellNeighbor> &E_overlapping : overlapping_terrain_bits) {
  1620. TileData *neighbor_tile_data = nullptr;
  1621. TileMapCell neighbor_cell = get_cell(E_overlapping.key);
  1622. if (neighbor_cell.source_id != TileSet::INVALID_SOURCE) {
  1623. Ref<TileSetSource> source = tile_set->get_source(neighbor_cell.source_id);
  1624. Ref<TileSetAtlasSource> atlas_source = source;
  1625. if (atlas_source.is_valid()) {
  1626. TileData *tile_data = atlas_source->get_tile_data(neighbor_cell.get_atlas_coords(), neighbor_cell.alternative_tile);
  1627. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  1628. neighbor_tile_data = tile_data;
  1629. }
  1630. }
  1631. }
  1632. int terrain = neighbor_tile_data ? neighbor_tile_data->get_terrain_peering_bit(TileSet::CellNeighbor(E_overlapping.value)) : -1;
  1633. if (!p_ignore_empty_terrains || terrain >= 0) {
  1634. if (!terrain_count.has(terrain)) {
  1635. terrain_count[terrain] = 0;
  1636. }
  1637. terrain_count[terrain] += 1;
  1638. }
  1639. }
  1640. // Get the terrain with the max number of occurrences.
  1641. int max = 0;
  1642. int max_terrain = -1;
  1643. for (const KeyValue<int, int> &E_terrain_count : terrain_count) {
  1644. if (E_terrain_count.value > max) {
  1645. max = E_terrain_count.value;
  1646. max_terrain = E_terrain_count.key;
  1647. }
  1648. }
  1649. // Set the adequate terrain.
  1650. if (max > 0) {
  1651. TerrainConstraint c = E_constraint;
  1652. c.set_terrain(max_terrain);
  1653. constraints.insert(c);
  1654. }
  1655. }
  1656. // Add the centers as constraints.
  1657. for (Vector2i E_coords : p_painted) {
  1658. TileData *tile_data = nullptr;
  1659. TileMapCell cell = get_cell(E_coords);
  1660. if (cell.source_id != TileSet::INVALID_SOURCE) {
  1661. Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
  1662. Ref<TileSetAtlasSource> atlas_source = source;
  1663. if (atlas_source.is_valid()) {
  1664. tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  1665. }
  1666. }
  1667. int terrain = (tile_data && tile_data->get_terrain_set() == p_terrain_set) ? tile_data->get_terrain() : -1;
  1668. if (!p_ignore_empty_terrains || terrain >= 0) {
  1669. constraints.insert(TerrainConstraint(tile_set, E_coords, terrain));
  1670. }
  1671. }
  1672. return constraints;
  1673. }
  1674. void TileMapLayer::_tile_set_changed() {
  1675. dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
  1676. _queue_internal_update();
  1677. emit_signal(CoreStringName(changed));
  1678. }
  1679. void TileMapLayer::_renamed() {
  1680. emit_signal(CoreStringName(changed));
  1681. }
  1682. void TileMapLayer::_update_notify_local_transform() {
  1683. bool notify = is_using_kinematic_bodies() || is_y_sort_enabled();
  1684. if (!notify) {
  1685. if (is_y_sort_enabled()) {
  1686. notify = true;
  1687. }
  1688. }
  1689. set_notify_local_transform(notify);
  1690. }
  1691. void TileMapLayer::_queue_internal_update() {
  1692. if (pending_update) {
  1693. return;
  1694. }
  1695. // Don't update when outside the tree, it doesn't do anything useful, and causes threading problems.
  1696. if (is_inside_tree()) {
  1697. pending_update = true;
  1698. callable_mp(this, &TileMapLayer::_deferred_internal_update).call_deferred();
  1699. }
  1700. }
  1701. void TileMapLayer::_deferred_internal_update() {
  1702. // Other updates.
  1703. if (!pending_update) {
  1704. return;
  1705. }
  1706. // Update dirty quadrants on layers.
  1707. _internal_update(false);
  1708. }
  1709. void TileMapLayer::_internal_update(bool p_force_cleanup) {
  1710. // Find TileData that need a runtime modification.
  1711. // This may add cells to the dirty list if a runtime modification has been notified.
  1712. _build_runtime_update_tile_data(p_force_cleanup);
  1713. // Callback for implementing custom subsystems.
  1714. // This may add to the dirty list if some cells are changed inside _update_cells.
  1715. _update_cells_callback(p_force_cleanup);
  1716. // Update all subsystems.
  1717. _rendering_update(p_force_cleanup);
  1718. #ifndef PHYSICS_2D_DISABLED
  1719. _physics_update(p_force_cleanup);
  1720. #endif // PHYSICS_2D_DISABLED
  1721. #ifndef NAVIGATION_2D_DISABLED
  1722. _navigation_update(p_force_cleanup);
  1723. #endif // NAVIGATION_2D_DISABLED
  1724. _scenes_update(p_force_cleanup);
  1725. #ifdef DEBUG_ENABLED
  1726. _debug_update(p_force_cleanup);
  1727. #endif // DEBUG_ENABLED
  1728. _clear_runtime_update_tile_data();
  1729. // Clear the "what is dirty" flags.
  1730. for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
  1731. dirty.flags[i] = false;
  1732. }
  1733. // List the cells to delete definitely.
  1734. Vector<Vector2i> to_delete;
  1735. for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
  1736. CellData &cell_data = *cell_data_list_element->self();
  1737. // Select the cell from tile_map if it is invalid.
  1738. if (cell_data.cell.source_id == TileSet::INVALID_SOURCE) {
  1739. to_delete.push_back(cell_data.coords);
  1740. }
  1741. }
  1742. // Remove cells that are empty after the cleanup.
  1743. for (const Vector2i &coords : to_delete) {
  1744. tile_map_layer_data.erase(coords);
  1745. }
  1746. // Clear the dirty cells list.
  1747. dirty.cell_list.clear();
  1748. pending_update = false;
  1749. }
  1750. void TileMapLayer::_physics_interpolated_changed() {
  1751. RenderingServer *rs = RenderingServer::get_singleton();
  1752. bool interpolated = is_physics_interpolated();
  1753. bool needs_reset = interpolated && is_visible_in_tree();
  1754. for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
  1755. for (const RID &ci : kv.value->canvas_items) {
  1756. if (ci.is_valid()) {
  1757. rs->canvas_item_set_interpolated(ci, interpolated);
  1758. if (needs_reset) {
  1759. rs->canvas_item_reset_physics_interpolation(ci);
  1760. }
  1761. }
  1762. }
  1763. }
  1764. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1765. for (const LocalVector<RID> &polygons : E.value.occluders) {
  1766. for (const RID &occluder_id : polygons) {
  1767. if (occluder_id.is_valid()) {
  1768. rs->canvas_light_occluder_set_interpolated(occluder_id, interpolated);
  1769. if (needs_reset) {
  1770. rs->canvas_light_occluder_reset_physics_interpolation(occluder_id);
  1771. }
  1772. }
  1773. }
  1774. }
  1775. }
  1776. }
  1777. void TileMapLayer::_notification(int p_what) {
  1778. switch (p_what) {
  1779. case NOTIFICATION_POSTINITIALIZE: {
  1780. connect(SNAME("renamed"), callable_mp(this, &TileMapLayer::_renamed));
  1781. break;
  1782. }
  1783. case NOTIFICATION_ENTER_TREE: {
  1784. _update_notify_local_transform();
  1785. dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
  1786. _queue_internal_update();
  1787. } break;
  1788. case NOTIFICATION_EXIT_TREE: {
  1789. dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
  1790. // Update immediately on exiting, and force cleanup.
  1791. _internal_update(true);
  1792. } break;
  1793. case NOTIFICATION_ENTER_CANVAS: {
  1794. dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
  1795. _queue_internal_update();
  1796. } break;
  1797. case NOTIFICATION_EXIT_CANVAS: {
  1798. dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
  1799. // Update immediately on exiting, and force cleanup.
  1800. _internal_update(true);
  1801. } break;
  1802. case NOTIFICATION_VISIBILITY_CHANGED: {
  1803. dirty.flags[DIRTY_FLAGS_LAYER_VISIBILITY] = true;
  1804. _queue_internal_update();
  1805. } break;
  1806. }
  1807. _rendering_notification(p_what);
  1808. #ifndef PHYSICS_2D_DISABLED
  1809. _physics_notification(p_what);
  1810. #endif // PHYSICS_2D_DISABLED
  1811. #ifndef NAVIGATION_2D_DISABLED
  1812. _navigation_notification(p_what);
  1813. #endif // NAVIGATION_2D_DISABLED
  1814. }
  1815. void TileMapLayer::_bind_methods() {
  1816. // --- Cells manipulation ---
  1817. // Generic cells manipulations and access.
  1818. ClassDB::bind_method(D_METHOD("set_cell", "coords", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::set_cell, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(0));
  1819. ClassDB::bind_method(D_METHOD("erase_cell", "coords"), &TileMapLayer::erase_cell);
  1820. ClassDB::bind_method(D_METHOD("fix_invalid_tiles"), &TileMapLayer::fix_invalid_tiles);
  1821. ClassDB::bind_method(D_METHOD("clear"), &TileMapLayer::clear);
  1822. ClassDB::bind_method(D_METHOD("get_cell_source_id", "coords"), &TileMapLayer::get_cell_source_id);
  1823. ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "coords"), &TileMapLayer::get_cell_atlas_coords);
  1824. ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "coords"), &TileMapLayer::get_cell_alternative_tile);
  1825. ClassDB::bind_method(D_METHOD("get_cell_tile_data", "coords"), &TileMapLayer::get_cell_tile_data);
  1826. ClassDB::bind_method(D_METHOD("is_cell_flipped_h", "coords"), &TileMapLayer::is_cell_flipped_h);
  1827. ClassDB::bind_method(D_METHOD("is_cell_flipped_v", "coords"), &TileMapLayer::is_cell_flipped_v);
  1828. ClassDB::bind_method(D_METHOD("is_cell_transposed", "coords"), &TileMapLayer::is_cell_transposed);
  1829. ClassDB::bind_method(D_METHOD("get_used_cells"), &TileMapLayer::get_used_cells);
  1830. ClassDB::bind_method(D_METHOD("get_used_cells_by_id", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::get_used_cells_by_id, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(TileSetSource::INVALID_TILE_ALTERNATIVE));
  1831. ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMapLayer::get_used_rect);
  1832. // Patterns.
  1833. ClassDB::bind_method(D_METHOD("get_pattern", "coords_array"), &TileMapLayer::get_pattern);
  1834. ClassDB::bind_method(D_METHOD("set_pattern", "position", "pattern"), &TileMapLayer::set_pattern);
  1835. // Terrains.
  1836. ClassDB::bind_method(D_METHOD("set_cells_terrain_connect", "cells", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_connect, DEFVAL(true));
  1837. ClassDB::bind_method(D_METHOD("set_cells_terrain_path", "path", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_path, DEFVAL(true));
  1838. #ifndef PHYSICS_2D_DISABLED
  1839. // --- Physics helpers ---
  1840. ClassDB::bind_method(D_METHOD("has_body_rid", "body"), &TileMapLayer::has_body_rid);
  1841. ClassDB::bind_method(D_METHOD("get_coords_for_body_rid", "body"), &TileMapLayer::get_coords_for_body_rid);
  1842. #endif // PHYSICS_2D_DISABLED
  1843. // --- Runtime ---
  1844. ClassDB::bind_method(D_METHOD("update_internals"), &TileMapLayer::update_internals);
  1845. ClassDB::bind_method(D_METHOD("notify_runtime_tile_data_update"), &TileMapLayer::notify_runtime_tile_data_update);
  1846. // --- Shortcuts to methods defined in TileSet ---
  1847. ClassDB::bind_method(D_METHOD("map_pattern", "position_in_tilemap", "coords_in_pattern", "pattern"), &TileMapLayer::map_pattern);
  1848. ClassDB::bind_method(D_METHOD("get_surrounding_cells", "coords"), &TileMapLayer::get_surrounding_cells);
  1849. ClassDB::bind_method(D_METHOD("get_neighbor_cell", "coords", "neighbor"), &TileMapLayer::get_neighbor_cell);
  1850. ClassDB::bind_method(D_METHOD("map_to_local", "map_position"), &TileMapLayer::map_to_local);
  1851. ClassDB::bind_method(D_METHOD("local_to_map", "local_position"), &TileMapLayer::local_to_map);
  1852. // --- Accessors ---
  1853. ClassDB::bind_method(D_METHOD("set_tile_map_data_from_array", "tile_map_layer_data"), &TileMapLayer::set_tile_map_data_from_array);
  1854. ClassDB::bind_method(D_METHOD("get_tile_map_data_as_array"), &TileMapLayer::get_tile_map_data_as_array);
  1855. ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &TileMapLayer::set_enabled);
  1856. ClassDB::bind_method(D_METHOD("is_enabled"), &TileMapLayer::is_enabled);
  1857. ClassDB::bind_method(D_METHOD("set_tile_set", "tile_set"), &TileMapLayer::set_tile_set);
  1858. ClassDB::bind_method(D_METHOD("get_tile_set"), &TileMapLayer::get_tile_set);
  1859. ClassDB::bind_method(D_METHOD("set_y_sort_origin", "y_sort_origin"), &TileMapLayer::set_y_sort_origin);
  1860. ClassDB::bind_method(D_METHOD("get_y_sort_origin"), &TileMapLayer::get_y_sort_origin);
  1861. ClassDB::bind_method(D_METHOD("set_x_draw_order_reversed", "x_draw_order_reversed"), &TileMapLayer::set_x_draw_order_reversed);
  1862. ClassDB::bind_method(D_METHOD("is_x_draw_order_reversed"), &TileMapLayer::is_x_draw_order_reversed);
  1863. ClassDB::bind_method(D_METHOD("set_rendering_quadrant_size", "size"), &TileMapLayer::set_rendering_quadrant_size);
  1864. ClassDB::bind_method(D_METHOD("get_rendering_quadrant_size"), &TileMapLayer::get_rendering_quadrant_size);
  1865. ClassDB::bind_method(D_METHOD("set_collision_enabled", "enabled"), &TileMapLayer::set_collision_enabled);
  1866. ClassDB::bind_method(D_METHOD("is_collision_enabled"), &TileMapLayer::is_collision_enabled);
  1867. ClassDB::bind_method(D_METHOD("set_use_kinematic_bodies", "use_kinematic_bodies"), &TileMapLayer::set_use_kinematic_bodies);
  1868. ClassDB::bind_method(D_METHOD("is_using_kinematic_bodies"), &TileMapLayer::is_using_kinematic_bodies);
  1869. ClassDB::bind_method(D_METHOD("set_collision_visibility_mode", "visibility_mode"), &TileMapLayer::set_collision_visibility_mode);
  1870. ClassDB::bind_method(D_METHOD("get_collision_visibility_mode"), &TileMapLayer::get_collision_visibility_mode);
  1871. ClassDB::bind_method(D_METHOD("set_physics_quadrant_size", "size"), &TileMapLayer::set_physics_quadrant_size);
  1872. ClassDB::bind_method(D_METHOD("get_physics_quadrant_size"), &TileMapLayer::get_physics_quadrant_size);
  1873. ClassDB::bind_method(D_METHOD("set_occlusion_enabled", "enabled"), &TileMapLayer::set_occlusion_enabled);
  1874. ClassDB::bind_method(D_METHOD("is_occlusion_enabled"), &TileMapLayer::is_occlusion_enabled);
  1875. #ifndef NAVIGATION_2D_DISABLED
  1876. ClassDB::bind_method(D_METHOD("set_navigation_enabled", "enabled"), &TileMapLayer::set_navigation_enabled);
  1877. ClassDB::bind_method(D_METHOD("is_navigation_enabled"), &TileMapLayer::is_navigation_enabled);
  1878. ClassDB::bind_method(D_METHOD("set_navigation_map", "map"), &TileMapLayer::set_navigation_map);
  1879. ClassDB::bind_method(D_METHOD("get_navigation_map"), &TileMapLayer::get_navigation_map);
  1880. ClassDB::bind_method(D_METHOD("set_navigation_visibility_mode", "show_navigation"), &TileMapLayer::set_navigation_visibility_mode);
  1881. ClassDB::bind_method(D_METHOD("get_navigation_visibility_mode"), &TileMapLayer::get_navigation_visibility_mode);
  1882. #endif // NAVIGATION_2D_DISABLED
  1883. GDVIRTUAL_BIND(_use_tile_data_runtime_update, "coords");
  1884. GDVIRTUAL_BIND(_tile_data_runtime_update, "coords", "tile_data");
  1885. GDVIRTUAL_BIND(_update_cells, "coords", "forced_cleanup");
  1886. ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "tile_map_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_tile_map_data_from_array", "get_tile_map_data_as_array");
  1887. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
  1888. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tile_set", "get_tile_set");
  1889. ADD_GROUP("Rendering", "");
  1890. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "occlusion_enabled"), "set_occlusion_enabled", "is_occlusion_enabled");
  1891. ADD_PROPERTY(PropertyInfo(Variant::INT, "y_sort_origin"), "set_y_sort_origin", "get_y_sort_origin");
  1892. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "x_draw_order_reversed"), "set_x_draw_order_reversed", "is_x_draw_order_reversed");
  1893. ADD_PROPERTY(PropertyInfo(Variant::INT, "rendering_quadrant_size"), "set_rendering_quadrant_size", "get_rendering_quadrant_size");
  1894. ADD_GROUP("Physics", "");
  1895. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_enabled"), "set_collision_enabled", "is_collision_enabled");
  1896. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_kinematic_bodies"), "set_use_kinematic_bodies", "is_using_kinematic_bodies");
  1897. ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_collision_visibility_mode", "get_collision_visibility_mode");
  1898. ADD_PROPERTY(PropertyInfo(Variant::INT, "physics_quadrant_size"), "set_physics_quadrant_size", "get_physics_quadrant_size");
  1899. #ifndef NAVIGATION_2D_DISABLED
  1900. ADD_GROUP("Navigation", "navigation_");
  1901. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "navigation_enabled", PROPERTY_HINT_GROUP_ENABLE), "set_navigation_enabled", "is_navigation_enabled");
  1902. ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_navigation_visibility_mode", "get_navigation_visibility_mode");
  1903. #endif // NAVIGATION_2D_DISABLED
  1904. ADD_SIGNAL(MethodInfo(CoreStringName(changed)));
  1905. ADD_PROPERTY_DEFAULT("tile_map_data_format", TileMapDataFormat::TILE_MAP_DATA_FORMAT_1);
  1906. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_DEFAULT);
  1907. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_HIDE);
  1908. BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_SHOW);
  1909. }
  1910. void TileMapLayer::_validate_property(PropertyInfo &p_property) const {
  1911. if (!Engine::get_singleton()->is_editor_hint()) {
  1912. return;
  1913. }
  1914. if (is_y_sort_enabled()) {
  1915. if (p_property.name == "rendering_quadrant_size") {
  1916. p_property.usage |= PROPERTY_USAGE_READ_ONLY;
  1917. }
  1918. } else {
  1919. if (p_property.name == "x_draw_order_reversed") {
  1920. p_property.usage |= PROPERTY_USAGE_READ_ONLY;
  1921. }
  1922. }
  1923. }
  1924. void TileMapLayer::_update_self_texture_filter(RS::CanvasItemTextureFilter p_texture_filter) {
  1925. // Set a default texture filter for the whole tilemap.
  1926. CanvasItem::_update_self_texture_filter(p_texture_filter);
  1927. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] = true;
  1928. _queue_internal_update();
  1929. emit_signal(CoreStringName(changed));
  1930. }
  1931. void TileMapLayer::_update_self_texture_repeat(RS::CanvasItemTextureRepeat p_texture_repeat) {
  1932. // Set a default texture repeat for the whole tilemap.
  1933. CanvasItem::_update_self_texture_repeat(p_texture_repeat);
  1934. dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] = true;
  1935. _queue_internal_update();
  1936. emit_signal(CoreStringName(changed));
  1937. }
  1938. #ifdef TOOLS_ENABLED
  1939. bool TileMapLayer::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
  1940. return tile_set.is_valid() && get_cell_source_id(local_to_map(p_point)) != TileSet::INVALID_SOURCE;
  1941. }
  1942. #endif
  1943. void TileMapLayer::set_as_tile_map_internal_node(int p_index) {
  1944. // Compatibility with TileMap.
  1945. ERR_FAIL_NULL(get_parent());
  1946. tile_map_node = Object::cast_to<TileMap>(get_parent());
  1947. set_use_parent_material(true);
  1948. if (layer_index_in_tile_map_node != p_index) {
  1949. layer_index_in_tile_map_node = p_index;
  1950. dirty.flags[DIRTY_FLAGS_LAYER_INDEX_IN_TILE_MAP_NODE] = true;
  1951. _queue_internal_update();
  1952. }
  1953. }
  1954. Rect2 TileMapLayer::get_rect(bool &r_changed) const {
  1955. if (tile_set.is_null()) {
  1956. r_changed = rect_cache != Rect2();
  1957. return Rect2();
  1958. }
  1959. // Compute the displayed area of the tilemap.
  1960. r_changed = false;
  1961. #ifdef DEBUG_ENABLED
  1962. if (rect_cache_dirty) {
  1963. Rect2 r_total;
  1964. bool first = true;
  1965. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  1966. Rect2 r;
  1967. r.position = tile_set->map_to_local(E.key);
  1968. r.size = Size2();
  1969. if (first) {
  1970. r_total = r;
  1971. first = false;
  1972. } else {
  1973. r_total = r_total.merge(r);
  1974. }
  1975. }
  1976. r_changed = rect_cache != r_total;
  1977. rect_cache = r_total;
  1978. rect_cache_dirty = false;
  1979. }
  1980. #endif
  1981. return rect_cache;
  1982. }
  1983. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_constraints(const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> &p_constraints) const {
  1984. if (tile_set.is_null()) {
  1985. return HashMap<Vector2i, TileSet::TerrainsPattern>();
  1986. }
  1987. // Copy the constraints set.
  1988. RBSet<TerrainConstraint> constraints = p_constraints;
  1989. // Output map.
  1990. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  1991. // Add all positions to a set.
  1992. for (int i = 0; i < p_to_replace.size(); i++) {
  1993. const Vector2i &coords = p_to_replace[i];
  1994. // Select the best pattern for the given constraints.
  1995. TileSet::TerrainsPattern current_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  1996. TileMapCell cell = get_cell(coords);
  1997. if (cell.source_id != TileSet::INVALID_SOURCE) {
  1998. TileSetSource *source = *tile_set->get_source(cell.source_id);
  1999. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2000. if (atlas_source) {
  2001. // Get tile data.
  2002. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2003. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2004. current_pattern = tile_data->get_terrains_pattern();
  2005. }
  2006. }
  2007. }
  2008. TileSet::TerrainsPattern pattern = _get_best_terrain_pattern_for_constraints(p_terrain_set, coords, constraints, current_pattern);
  2009. // Update the constraint set with the new ones.
  2010. RBSet<TerrainConstraint> new_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, pattern);
  2011. for (const TerrainConstraint &E_constraint : new_constraints) {
  2012. if (constraints.has(E_constraint)) {
  2013. constraints.erase(E_constraint);
  2014. }
  2015. TerrainConstraint c = E_constraint;
  2016. c.set_priority(5);
  2017. constraints.insert(c);
  2018. }
  2019. output[coords] = pattern;
  2020. }
  2021. return output;
  2022. }
  2023. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_connect(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
  2024. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2025. ERR_FAIL_COND_V(tile_set.is_null(), output);
  2026. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), output);
  2027. // Build list and set of tiles that can be modified (painted and their surroundings).
  2028. Vector<Vector2i> can_modify_list;
  2029. RBSet<Vector2i> can_modify_set;
  2030. RBSet<Vector2i> painted_set;
  2031. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2032. const Vector2i &coords = p_coords_array[i];
  2033. can_modify_list.push_back(coords);
  2034. can_modify_set.insert(coords);
  2035. painted_set.insert(coords);
  2036. }
  2037. for (Vector2i coords : p_coords_array) {
  2038. // Find the adequate neighbor.
  2039. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2040. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2041. if (tile_set->is_existing_neighbor(bit)) {
  2042. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2043. if (!can_modify_set.has(neighbor)) {
  2044. can_modify_list.push_back(neighbor);
  2045. can_modify_set.insert(neighbor);
  2046. }
  2047. }
  2048. }
  2049. }
  2050. // Build a set, out of the possibly modified tiles, of the one with a center bit that is set (or will be) to the painted terrain.
  2051. RBSet<Vector2i> cells_with_terrain_center_bit;
  2052. for (Vector2i coords : can_modify_set) {
  2053. bool connect = false;
  2054. if (painted_set.has(coords)) {
  2055. connect = true;
  2056. } else {
  2057. // Get the center bit of the cell.
  2058. TileData *tile_data = nullptr;
  2059. TileMapCell cell = get_cell(coords);
  2060. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2061. Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
  2062. Ref<TileSetAtlasSource> atlas_source = source;
  2063. if (atlas_source.is_valid()) {
  2064. tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2065. }
  2066. }
  2067. if (tile_data && tile_data->get_terrain_set() == p_terrain_set && tile_data->get_terrain() == p_terrain) {
  2068. connect = true;
  2069. }
  2070. }
  2071. if (connect) {
  2072. cells_with_terrain_center_bit.insert(coords);
  2073. }
  2074. }
  2075. RBSet<TerrainConstraint> constraints;
  2076. // Add new constraints from the path drawn.
  2077. for (Vector2i coords : p_coords_array) {
  2078. // Constraints on the center bit.
  2079. TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
  2080. c.set_priority(10);
  2081. constraints.insert(c);
  2082. // Constraints on the connecting bits.
  2083. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2084. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2085. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  2086. c = TerrainConstraint(tile_set, coords, bit, p_terrain);
  2087. c.set_priority(10);
  2088. if ((int(bit) % 2) == 0) {
  2089. // Side peering bits: add the constraint if the center is of the same terrain.
  2090. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2091. if (cells_with_terrain_center_bit.has(neighbor)) {
  2092. constraints.insert(c);
  2093. }
  2094. } else {
  2095. // Corner peering bits: add the constraint if all tiles on the constraint has the same center bit.
  2096. HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = c.get_overlapping_coords_and_peering_bits();
  2097. bool valid = true;
  2098. for (KeyValue<Vector2i, TileSet::CellNeighbor> kv : overlapping_terrain_bits) {
  2099. if (!cells_with_terrain_center_bit.has(kv.key)) {
  2100. valid = false;
  2101. break;
  2102. }
  2103. }
  2104. if (valid) {
  2105. constraints.insert(c);
  2106. }
  2107. }
  2108. }
  2109. }
  2110. }
  2111. // Fills in the constraint list from existing tiles.
  2112. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2113. constraints.insert(c);
  2114. }
  2115. // Fill the terrains.
  2116. output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2117. return output;
  2118. }
  2119. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_path(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
  2120. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2121. ERR_FAIL_COND_V(tile_set.is_null(), output);
  2122. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), output);
  2123. // Make sure the path is correct and build the peering bit list while doing it.
  2124. Vector<TileSet::CellNeighbor> neighbor_list;
  2125. for (int i = 0; i < p_coords_array.size() - 1; i++) {
  2126. // Find the adequate neighbor.
  2127. TileSet::CellNeighbor found_bit = TileSet::CELL_NEIGHBOR_MAX;
  2128. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2129. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2130. if (tile_set->is_existing_neighbor(bit)) {
  2131. if (tile_set->get_neighbor_cell(p_coords_array[i], bit) == p_coords_array[i + 1]) {
  2132. found_bit = bit;
  2133. break;
  2134. }
  2135. }
  2136. }
  2137. ERR_FAIL_COND_V_MSG(found_bit == TileSet::CELL_NEIGHBOR_MAX, output, vformat("Invalid terrain path, %s is not a neighboring tile of %s", p_coords_array[i + 1], p_coords_array[i]));
  2138. neighbor_list.push_back(found_bit);
  2139. }
  2140. // Build list and set of tiles that can be modified (painted and their surroundings).
  2141. Vector<Vector2i> can_modify_list;
  2142. RBSet<Vector2i> can_modify_set;
  2143. RBSet<Vector2i> painted_set;
  2144. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2145. const Vector2i &coords = p_coords_array[i];
  2146. can_modify_list.push_back(coords);
  2147. can_modify_set.insert(coords);
  2148. painted_set.insert(coords);
  2149. }
  2150. for (Vector2i coords : p_coords_array) {
  2151. // Find the adequate neighbor.
  2152. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2153. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2154. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  2155. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2156. if (!can_modify_set.has(neighbor)) {
  2157. can_modify_list.push_back(neighbor);
  2158. can_modify_set.insert(neighbor);
  2159. }
  2160. }
  2161. }
  2162. }
  2163. RBSet<TerrainConstraint> constraints;
  2164. // Add new constraints from the path drawn.
  2165. for (Vector2i coords : p_coords_array) {
  2166. // Constraints on the center bit.
  2167. TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
  2168. c.set_priority(10);
  2169. constraints.insert(c);
  2170. }
  2171. for (int i = 0; i < p_coords_array.size() - 1; i++) {
  2172. // Constraints on the peering bits.
  2173. TerrainConstraint c = TerrainConstraint(tile_set, p_coords_array[i], neighbor_list[i], p_terrain);
  2174. c.set_priority(10);
  2175. constraints.insert(c);
  2176. }
  2177. // Fills in the constraint list from existing tiles.
  2178. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2179. constraints.insert(c);
  2180. }
  2181. // Fill the terrains.
  2182. output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2183. return output;
  2184. }
  2185. HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_pattern(const Vector<Vector2i> &p_coords_array, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern, bool p_ignore_empty_terrains) const {
  2186. HashMap<Vector2i, TileSet::TerrainsPattern> output;
  2187. ERR_FAIL_COND_V(tile_set.is_null(), output);
  2188. ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), output);
  2189. // Build list and set of tiles that can be modified (painted and their surroundings).
  2190. Vector<Vector2i> can_modify_list;
  2191. RBSet<Vector2i> can_modify_set;
  2192. RBSet<Vector2i> painted_set;
  2193. for (int i = p_coords_array.size() - 1; i >= 0; i--) {
  2194. const Vector2i &coords = p_coords_array[i];
  2195. can_modify_list.push_back(coords);
  2196. can_modify_set.insert(coords);
  2197. painted_set.insert(coords);
  2198. }
  2199. for (Vector2i coords : p_coords_array) {
  2200. // Find the adequate neighbor.
  2201. for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
  2202. TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
  2203. if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
  2204. Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
  2205. if (!can_modify_set.has(neighbor)) {
  2206. can_modify_list.push_back(neighbor);
  2207. can_modify_set.insert(neighbor);
  2208. }
  2209. }
  2210. }
  2211. }
  2212. // Add constraint by the new ones.
  2213. RBSet<TerrainConstraint> constraints;
  2214. // Add new constraints from the path drawn.
  2215. for (Vector2i coords : p_coords_array) {
  2216. // Constraints on the center bit.
  2217. RBSet<TerrainConstraint> added_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, p_terrains_pattern);
  2218. for (TerrainConstraint c : added_constraints) {
  2219. c.set_priority(10);
  2220. constraints.insert(c);
  2221. }
  2222. }
  2223. // Fills in the constraint list from modified tiles border.
  2224. for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
  2225. constraints.insert(c);
  2226. }
  2227. // Fill the terrains.
  2228. output = terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
  2229. return output;
  2230. }
  2231. TileMapCell TileMapLayer::get_cell(const Vector2i &p_coords) const {
  2232. if (!tile_map_layer_data.has(p_coords)) {
  2233. return TileMapCell();
  2234. } else {
  2235. return tile_map_layer_data.find(p_coords)->value.cell;
  2236. }
  2237. }
  2238. void TileMapLayer::draw_tile(RID p_canvas_item, const Vector2 &p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile, int p_frame, const TileData *p_tile_data_override, real_t p_normalized_animation_offset) {
  2239. ERR_FAIL_COND(p_tile_set.is_null());
  2240. ERR_FAIL_COND(!p_tile_set->has_source(p_atlas_source_id));
  2241. ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_tile(p_atlas_coords));
  2242. ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_alternative_tile(p_atlas_coords, p_alternative_tile));
  2243. TileSetSource *source = *p_tile_set->get_source(p_atlas_source_id);
  2244. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2245. if (atlas_source) {
  2246. // Check for the frame.
  2247. if (p_frame >= 0) {
  2248. ERR_FAIL_INDEX(p_frame, atlas_source->get_tile_animation_frames_count(p_atlas_coords));
  2249. }
  2250. // Get the texture.
  2251. Ref<Texture2D> tex = atlas_source->get_runtime_texture();
  2252. if (tex.is_null()) {
  2253. return;
  2254. }
  2255. // Check if we are in the texture, return otherwise.
  2256. Vector2i grid_size = atlas_source->get_atlas_grid_size();
  2257. if (p_atlas_coords.x >= grid_size.x || p_atlas_coords.y >= grid_size.y) {
  2258. return;
  2259. }
  2260. // Get tile data.
  2261. const TileData *tile_data = p_tile_data_override ? p_tile_data_override : atlas_source->get_tile_data(p_atlas_coords, p_alternative_tile);
  2262. // Get the tile modulation.
  2263. Color modulate = tile_data->get_modulate();
  2264. // Compute the dest rect.
  2265. Rect2 dest_rect;
  2266. bool transpose;
  2267. compute_transformed_tile_dest_rect(dest_rect, transpose, p_position, atlas_source->get_runtime_tile_texture_region(p_atlas_coords).size, tile_data, p_alternative_tile);
  2268. // Draw the tile.
  2269. if (p_frame >= 0) {
  2270. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, p_frame);
  2271. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2272. } else if (atlas_source->get_tile_animation_frames_count(p_atlas_coords) == 1) {
  2273. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, 0);
  2274. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2275. } else {
  2276. real_t speed = atlas_source->get_tile_animation_speed(p_atlas_coords);
  2277. real_t animation_duration = atlas_source->get_tile_animation_total_duration(p_atlas_coords) / speed;
  2278. real_t animation_offset = p_normalized_animation_offset * animation_duration;
  2279. // Accumulate durations unaffected by the speed to avoid accumulating floating point division errors.
  2280. // Aka do `sum(duration[i]) / speed` instead of `sum(duration[i] / speed)`.
  2281. real_t time_unscaled = 0.0;
  2282. for (int frame = 0; frame < atlas_source->get_tile_animation_frames_count(p_atlas_coords); frame++) {
  2283. real_t frame_duration_unscaled = atlas_source->get_tile_animation_frame_duration(p_atlas_coords, frame);
  2284. real_t slice_start = time_unscaled / speed;
  2285. real_t slice_end = (time_unscaled + frame_duration_unscaled) / speed;
  2286. RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, animation_duration, slice_start, slice_end, animation_offset);
  2287. Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, frame);
  2288. tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
  2289. time_unscaled += frame_duration_unscaled;
  2290. }
  2291. RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, 1.0, 0.0, 1.0, 0.0);
  2292. }
  2293. }
  2294. }
  2295. void TileMapLayer::compute_transformed_tile_dest_rect(Rect2 &r_dest_rect, bool &r_transpose, const Vector2 &p_position, const Vector2 &p_dest_rect_size, const TileData *p_tile_data, int p_alternative_tile) {
  2296. DEV_ASSERT(p_tile_data);
  2297. // Conceptually the order of transformations is (starting from the tile centered at the origin):
  2298. // - Per TileSet-tile transforms (transpose then flips).
  2299. // - Translation so texture origin is at the origin.
  2300. // - Per TileMapLayer-cell transforms (transpose then flips).
  2301. // - Translation to target position.
  2302. const bool tile_transpose = p_tile_data->get_transpose();
  2303. const bool tile_flip_h = p_tile_data->get_flip_h();
  2304. const bool tile_flip_v = p_tile_data->get_flip_v();
  2305. const Vector2 texture_origin = p_tile_data->get_texture_origin();
  2306. const bool cell_transpose = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  2307. const bool cell_flip_h = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
  2308. const bool cell_flip_v = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
  2309. const bool final_transpose = tile_transpose != cell_transpose;
  2310. const bool final_flip_h = cell_flip_h != (cell_transpose ? tile_flip_v : tile_flip_h);
  2311. const bool final_flip_v = cell_flip_v != (cell_transpose ? tile_flip_h : tile_flip_v);
  2312. // Rect draw commands swap the size based on the passed transpose, so the size is left non-tranposed here.
  2313. // Position calculations need to use transposed size though.
  2314. Rect2 dest_rect;
  2315. dest_rect.size = p_dest_rect_size;
  2316. dest_rect.size.x += FP_ADJUST;
  2317. dest_rect.size.y += FP_ADJUST;
  2318. Vector2 transposed_size = final_transpose ? Vector2(dest_rect.size.y, dest_rect.size.x) : dest_rect.size;
  2319. if (final_flip_h) {
  2320. dest_rect.size.x = -dest_rect.size.x;
  2321. }
  2322. if (final_flip_v) {
  2323. dest_rect.size.y = -dest_rect.size.y;
  2324. }
  2325. dest_rect.position = -0.5f * transposed_size;
  2326. dest_rect.position -= cell_transpose ? Vector2(texture_origin.y, texture_origin.x) : texture_origin;
  2327. if (cell_flip_h) {
  2328. dest_rect.position.x = -(dest_rect.position.x + transposed_size.x);
  2329. }
  2330. if (cell_flip_v) {
  2331. dest_rect.position.y = -(dest_rect.position.y + transposed_size.y);
  2332. }
  2333. dest_rect.position += p_position;
  2334. r_dest_rect = dest_rect;
  2335. r_transpose = final_transpose;
  2336. }
  2337. void TileMapLayer::set_cell(const Vector2i &p_coords, int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) {
  2338. // Set the current cell tile (using integer position).
  2339. Vector2i pk(p_coords);
  2340. HashMap<Vector2i, CellData>::Iterator E = tile_map_layer_data.find(pk);
  2341. int source_id = p_source_id;
  2342. Vector2i atlas_coords = p_atlas_coords;
  2343. int alternative_tile = p_alternative_tile;
  2344. if ((source_id == TileSet::INVALID_SOURCE || atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE) &&
  2345. (source_id != TileSet::INVALID_SOURCE || atlas_coords != TileSetSource::INVALID_ATLAS_COORDS || alternative_tile != TileSetSource::INVALID_TILE_ALTERNATIVE)) {
  2346. source_id = TileSet::INVALID_SOURCE;
  2347. atlas_coords = TileSetSource::INVALID_ATLAS_COORDS;
  2348. alternative_tile = TileSetSource::INVALID_TILE_ALTERNATIVE;
  2349. }
  2350. if (!E) {
  2351. if (source_id == TileSet::INVALID_SOURCE) {
  2352. return; // Nothing to do, the tile is already empty.
  2353. }
  2354. // Insert a new cell in the tile map.
  2355. CellData new_cell_data;
  2356. new_cell_data.coords = pk;
  2357. E = tile_map_layer_data.insert(pk, new_cell_data);
  2358. } else {
  2359. if (E->value.cell.source_id == source_id && E->value.cell.get_atlas_coords() == atlas_coords && E->value.cell.alternative_tile == alternative_tile) {
  2360. return; // Nothing changed.
  2361. }
  2362. }
  2363. TileMapCell &c = E->value.cell;
  2364. c.source_id = source_id;
  2365. c.set_atlas_coords(atlas_coords);
  2366. c.alternative_tile = alternative_tile;
  2367. // Make the given cell dirty.
  2368. if (!E->value.dirty_list_element.in_list()) {
  2369. dirty.cell_list.add(&(E->value.dirty_list_element));
  2370. }
  2371. _queue_internal_update();
  2372. used_rect_cache_dirty = true;
  2373. }
  2374. void TileMapLayer::erase_cell(const Vector2i &p_coords) {
  2375. set_cell(p_coords, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
  2376. }
  2377. void TileMapLayer::fix_invalid_tiles() {
  2378. ERR_FAIL_COND_MSG(tile_set.is_null(), "Cannot call fix_invalid_tiles() on a TileMapLayer without a valid TileSet.");
  2379. RBSet<Vector2i> coords;
  2380. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2381. TileSetSource *source = *tile_set->get_source(E.value.cell.source_id);
  2382. if (!source || !source->has_tile(E.value.cell.get_atlas_coords()) || !source->has_alternative_tile(E.value.cell.get_atlas_coords(), E.value.cell.alternative_tile)) {
  2383. coords.insert(E.key);
  2384. }
  2385. }
  2386. for (const Vector2i &E : coords) {
  2387. set_cell(E, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
  2388. }
  2389. }
  2390. void TileMapLayer::clear() {
  2391. // Remove all tiles.
  2392. for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
  2393. erase_cell(kv.key);
  2394. }
  2395. used_rect_cache_dirty = true;
  2396. }
  2397. int TileMapLayer::get_cell_source_id(const Vector2i &p_coords) const {
  2398. // Get a cell source id from position.
  2399. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2400. if (!E) {
  2401. return TileSet::INVALID_SOURCE;
  2402. }
  2403. return E->value.cell.source_id;
  2404. }
  2405. Vector2i TileMapLayer::get_cell_atlas_coords(const Vector2i &p_coords) const {
  2406. // Get a cell source id from position.
  2407. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2408. if (!E) {
  2409. return TileSetSource::INVALID_ATLAS_COORDS;
  2410. }
  2411. return E->value.cell.get_atlas_coords();
  2412. }
  2413. int TileMapLayer::get_cell_alternative_tile(const Vector2i &p_coords) const {
  2414. // Get a cell source id from position.
  2415. HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
  2416. if (!E) {
  2417. return TileSetSource::INVALID_TILE_ALTERNATIVE;
  2418. }
  2419. return E->value.cell.alternative_tile;
  2420. }
  2421. TileData *TileMapLayer::get_cell_tile_data(const Vector2i &p_coords) const {
  2422. int source_id = get_cell_source_id(p_coords);
  2423. if (source_id == TileSet::INVALID_SOURCE) {
  2424. return nullptr;
  2425. }
  2426. Ref<TileSetAtlasSource> source = tile_set->get_source(source_id);
  2427. if (source.is_valid()) {
  2428. return source->get_tile_data(get_cell_atlas_coords(p_coords), get_cell_alternative_tile(p_coords));
  2429. }
  2430. return nullptr;
  2431. }
  2432. TypedArray<Vector2i> TileMapLayer::get_used_cells() const {
  2433. // Returns the cells used in the tilemap.
  2434. TypedArray<Vector2i> a;
  2435. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2436. const TileMapCell &c = E.value.cell;
  2437. if (c.source_id == TileSet::INVALID_SOURCE) {
  2438. continue;
  2439. }
  2440. a.push_back(E.key);
  2441. }
  2442. return a;
  2443. }
  2444. TypedArray<Vector2i> TileMapLayer::get_used_cells_by_id(int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) const {
  2445. // Returns the cells used in the tilemap.
  2446. TypedArray<Vector2i> a;
  2447. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2448. const TileMapCell &c = E.value.cell;
  2449. if (c.source_id == TileSet::INVALID_SOURCE) {
  2450. continue;
  2451. }
  2452. if ((p_source_id == TileSet::INVALID_SOURCE || p_source_id == c.source_id) &&
  2453. (p_atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || p_atlas_coords == c.get_atlas_coords()) &&
  2454. (p_alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE || p_alternative_tile == c.alternative_tile)) {
  2455. a.push_back(E.key);
  2456. }
  2457. }
  2458. return a;
  2459. }
  2460. Rect2i TileMapLayer::get_used_rect() const {
  2461. // Return the rect of the currently used area.
  2462. if (used_rect_cache_dirty) {
  2463. used_rect_cache = Rect2i();
  2464. bool first = true;
  2465. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2466. const TileMapCell &c = E.value.cell;
  2467. if (c.source_id == TileSet::INVALID_SOURCE) {
  2468. continue;
  2469. }
  2470. if (first) {
  2471. used_rect_cache = Rect2i(E.key, Size2i());
  2472. first = false;
  2473. } else {
  2474. used_rect_cache.expand_to(E.key);
  2475. }
  2476. }
  2477. if (!first) {
  2478. // Only if we have at least one cell.
  2479. // The cache expands to top-left coordinate, so we add one full tile.
  2480. used_rect_cache.size += Vector2i(1, 1);
  2481. }
  2482. used_rect_cache_dirty = false;
  2483. }
  2484. return used_rect_cache;
  2485. }
  2486. bool TileMapLayer::is_cell_flipped_h(const Vector2i &p_coords) const {
  2487. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_H;
  2488. }
  2489. bool TileMapLayer::is_cell_flipped_v(const Vector2i &p_coords) const {
  2490. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_V;
  2491. }
  2492. bool TileMapLayer::is_cell_transposed(const Vector2i &p_coords) const {
  2493. return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_TRANSPOSE;
  2494. }
  2495. Ref<TileMapPattern> TileMapLayer::get_pattern(TypedArray<Vector2i> p_coords_array) {
  2496. ERR_FAIL_COND_V(tile_set.is_null(), nullptr);
  2497. Ref<TileMapPattern> output;
  2498. output.instantiate();
  2499. if (p_coords_array.is_empty()) {
  2500. return output;
  2501. }
  2502. Vector2i min = Vector2i(p_coords_array[0]);
  2503. for (int i = 1; i < p_coords_array.size(); i++) {
  2504. min = min.min(p_coords_array[i]);
  2505. }
  2506. Vector<Vector2i> coords_in_pattern_array;
  2507. coords_in_pattern_array.resize(p_coords_array.size());
  2508. Vector2i ensure_positive_offset;
  2509. for (int i = 0; i < p_coords_array.size(); i++) {
  2510. Vector2i coords = p_coords_array[i];
  2511. Vector2i coords_in_pattern = coords - min;
  2512. if (tile_set->get_tile_shape() != TileSet::TILE_SHAPE_SQUARE) {
  2513. if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED) {
  2514. if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
  2515. coords_in_pattern.x -= 1;
  2516. if (coords_in_pattern.x < 0) {
  2517. ensure_positive_offset.x = 1;
  2518. }
  2519. } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
  2520. coords_in_pattern.y -= 1;
  2521. if (coords_in_pattern.y < 0) {
  2522. ensure_positive_offset.y = 1;
  2523. }
  2524. }
  2525. } else if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED_OFFSET) {
  2526. if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
  2527. coords_in_pattern.x += 1;
  2528. } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
  2529. coords_in_pattern.y += 1;
  2530. }
  2531. }
  2532. }
  2533. coords_in_pattern_array.write[i] = coords_in_pattern;
  2534. }
  2535. for (int i = 0; i < coords_in_pattern_array.size(); i++) {
  2536. Vector2i coords = p_coords_array[i];
  2537. Vector2i coords_in_pattern = coords_in_pattern_array[i];
  2538. output->set_cell(coords_in_pattern + ensure_positive_offset, get_cell_source_id(coords), get_cell_atlas_coords(coords), get_cell_alternative_tile(coords));
  2539. }
  2540. return output;
  2541. }
  2542. void TileMapLayer::set_pattern(const Vector2i &p_position, const Ref<TileMapPattern> p_pattern) {
  2543. ERR_FAIL_COND(tile_set.is_null());
  2544. ERR_FAIL_COND(p_pattern.is_null());
  2545. TypedArray<Vector2i> used_cells = p_pattern->get_used_cells();
  2546. for (int i = 0; i < used_cells.size(); i++) {
  2547. Vector2i coords = tile_set->map_pattern(p_position, used_cells[i], p_pattern);
  2548. set_cell(coords, p_pattern->get_cell_source_id(used_cells[i]), p_pattern->get_cell_atlas_coords(used_cells[i]), p_pattern->get_cell_alternative_tile(used_cells[i]));
  2549. }
  2550. }
  2551. void TileMapLayer::set_cells_terrain_connect(TypedArray<Vector2i> p_cells, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
  2552. ERR_FAIL_COND(tile_set.is_null());
  2553. ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
  2554. Vector<Vector2i> cells_vector;
  2555. HashSet<Vector2i> painted_set;
  2556. for (int i = 0; i < p_cells.size(); i++) {
  2557. cells_vector.push_back(p_cells[i]);
  2558. painted_set.insert(p_cells[i]);
  2559. }
  2560. HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_connect(cells_vector, p_terrain_set, p_terrain, p_ignore_empty_terrains);
  2561. for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
  2562. if (painted_set.has(kv.key)) {
  2563. // Paint a random tile with the correct terrain for the painted path.
  2564. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2565. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2566. } else {
  2567. // Avoids updating the painted path from the output if the new pattern is the same as before.
  2568. TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  2569. TileMapCell cell = get_cell(kv.key);
  2570. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2571. TileSetSource *source = *tile_set->get_source(cell.source_id);
  2572. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2573. if (atlas_source) {
  2574. // Get tile data.
  2575. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2576. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2577. in_map_terrain_pattern = tile_data->get_terrains_pattern();
  2578. }
  2579. }
  2580. }
  2581. if (in_map_terrain_pattern != kv.value) {
  2582. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2583. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2584. }
  2585. }
  2586. }
  2587. }
  2588. void TileMapLayer::set_cells_terrain_path(TypedArray<Vector2i> p_path, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
  2589. ERR_FAIL_COND(tile_set.is_null());
  2590. ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
  2591. Vector<Vector2i> vector_path;
  2592. HashSet<Vector2i> painted_set;
  2593. for (int i = 0; i < p_path.size(); i++) {
  2594. vector_path.push_back(p_path[i]);
  2595. painted_set.insert(p_path[i]);
  2596. }
  2597. HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_path(vector_path, p_terrain_set, p_terrain, p_ignore_empty_terrains);
  2598. for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
  2599. if (painted_set.has(kv.key)) {
  2600. // Paint a random tile with the correct terrain for the painted path.
  2601. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2602. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2603. } else {
  2604. // Avoids updating the painted path from the output if the new pattern is the same as before.
  2605. TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
  2606. TileMapCell cell = get_cell(kv.key);
  2607. if (cell.source_id != TileSet::INVALID_SOURCE) {
  2608. TileSetSource *source = *tile_set->get_source(cell.source_id);
  2609. TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
  2610. if (atlas_source) {
  2611. // Get tile data.
  2612. TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
  2613. if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
  2614. in_map_terrain_pattern = tile_data->get_terrains_pattern();
  2615. }
  2616. }
  2617. }
  2618. if (in_map_terrain_pattern != kv.value) {
  2619. TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
  2620. set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
  2621. }
  2622. }
  2623. }
  2624. }
  2625. #ifndef PHYSICS_2D_DISABLED
  2626. bool TileMapLayer::has_body_rid(RID p_physics_body) const {
  2627. return bodies_coords.has(p_physics_body);
  2628. }
  2629. Vector2i TileMapLayer::get_coords_for_body_rid(RID p_physics_body) const {
  2630. const Vector2i *found = bodies_coords.getptr(p_physics_body);
  2631. ERR_FAIL_NULL_V(found, Vector2i());
  2632. return *found;
  2633. }
  2634. #endif // PHYSICS_2D_DISABLED
  2635. void TileMapLayer::update_internals() {
  2636. _internal_update(false);
  2637. }
  2638. void TileMapLayer::notify_runtime_tile_data_update() {
  2639. dirty.flags[TileMapLayer::DIRTY_FLAGS_LAYER_RUNTIME_UPDATE] = true;
  2640. _queue_internal_update();
  2641. emit_signal(CoreStringName(changed));
  2642. }
  2643. Vector2i TileMapLayer::map_pattern(const Vector2i &p_position_in_tilemap, const Vector2i &p_coords_in_pattern, Ref<TileMapPattern> p_pattern) {
  2644. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2645. return tile_set->map_pattern(p_position_in_tilemap, p_coords_in_pattern, p_pattern);
  2646. }
  2647. TypedArray<Vector2i> TileMapLayer::get_surrounding_cells(const Vector2i &p_coords) {
  2648. ERR_FAIL_COND_V(tile_set.is_null(), TypedArray<Vector2i>());
  2649. return tile_set->get_surrounding_cells(p_coords);
  2650. }
  2651. Vector2i TileMapLayer::get_neighbor_cell(const Vector2i &p_coords, TileSet::CellNeighbor p_cell_neighbor) const {
  2652. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2653. return tile_set->get_neighbor_cell(p_coords, p_cell_neighbor);
  2654. }
  2655. Vector2 TileMapLayer::map_to_local(const Vector2i &p_pos) const {
  2656. ERR_FAIL_COND_V(tile_set.is_null(), Vector2());
  2657. return tile_set->map_to_local(p_pos);
  2658. }
  2659. Vector2i TileMapLayer::local_to_map(const Vector2 &p_pos) const {
  2660. ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
  2661. return tile_set->local_to_map(p_pos);
  2662. }
  2663. void TileMapLayer::set_enabled(bool p_enabled) {
  2664. if (enabled == p_enabled) {
  2665. return;
  2666. }
  2667. enabled = p_enabled;
  2668. dirty.flags[DIRTY_FLAGS_LAYER_ENABLED] = true;
  2669. _queue_internal_update();
  2670. emit_signal(CoreStringName(changed));
  2671. }
  2672. bool TileMapLayer::is_enabled() const {
  2673. return enabled;
  2674. }
  2675. void TileMapLayer::set_tile_set(const Ref<TileSet> &p_tile_set) {
  2676. if (p_tile_set == tile_set) {
  2677. return;
  2678. }
  2679. dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
  2680. _queue_internal_update();
  2681. // Set the TileSet, registering to its changes.
  2682. if (tile_set.is_valid()) {
  2683. tile_set->disconnect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
  2684. }
  2685. tile_set = p_tile_set;
  2686. if (tile_set.is_valid()) {
  2687. tile_set->connect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
  2688. }
  2689. emit_signal(CoreStringName(changed));
  2690. // Trigger updates for TileSet's read-only status.
  2691. notify_property_list_changed();
  2692. }
  2693. Ref<TileSet> TileMapLayer::get_tile_set() const {
  2694. return tile_set;
  2695. }
  2696. void TileMapLayer::set_highlight_mode(HighlightMode p_highlight_mode) {
  2697. if (p_highlight_mode == highlight_mode) {
  2698. return;
  2699. }
  2700. highlight_mode = p_highlight_mode;
  2701. _queue_internal_update();
  2702. }
  2703. TileMapLayer::HighlightMode TileMapLayer::get_highlight_mode() const {
  2704. return highlight_mode;
  2705. }
  2706. void TileMapLayer::set_tile_map_data_from_array(const Vector<uint8_t> &p_data) {
  2707. if (p_data.is_empty()) {
  2708. clear();
  2709. return;
  2710. }
  2711. const int cell_data_struct_size = 12;
  2712. int size = p_data.size();
  2713. const uint8_t *ptr = p_data.ptr();
  2714. // Index in the array.
  2715. int index = 0;
  2716. // First extract the data version.
  2717. ERR_FAIL_COND_MSG(size < 2, "Corrupted tile map data: not enough bytes.");
  2718. uint16_t format = decode_uint16(&ptr[index]);
  2719. index += 2;
  2720. ERR_FAIL_COND_MSG(format >= TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX, vformat("Unsupported tile map data format: %s. Expected format ID lower or equal to: %s", format, TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1));
  2721. // Clear the TileMap.
  2722. clear();
  2723. while (index < size) {
  2724. ERR_FAIL_COND_MSG(index + cell_data_struct_size > size, vformat("Corrupted tile map data: tiles might be missing."));
  2725. // Get a pointer at the start of the cell data.
  2726. const uint8_t *cell_data_ptr = &ptr[index];
  2727. // Extracts position in TileMap.
  2728. int16_t x = decode_uint16(&cell_data_ptr[0]);
  2729. int16_t y = decode_uint16(&cell_data_ptr[2]);
  2730. // Extracts the tile identifiers.
  2731. uint16_t source_id = decode_uint16(&cell_data_ptr[4]);
  2732. uint16_t atlas_coords_x = decode_uint16(&cell_data_ptr[6]);
  2733. uint16_t atlas_coords_y = decode_uint16(&cell_data_ptr[8]);
  2734. uint16_t alternative_tile = decode_uint16(&cell_data_ptr[10]);
  2735. set_cell(Vector2i(x, y), source_id, Vector2i(atlas_coords_x, atlas_coords_y), alternative_tile);
  2736. index += cell_data_struct_size;
  2737. }
  2738. }
  2739. Vector<uint8_t> TileMapLayer::get_tile_map_data_as_array() const {
  2740. const int cell_data_struct_size = 12;
  2741. Vector<uint8_t> tile_map_data_array;
  2742. if (tile_map_layer_data.is_empty()) {
  2743. return tile_map_data_array;
  2744. }
  2745. tile_map_data_array.resize(2 + tile_map_layer_data.size() * cell_data_struct_size);
  2746. uint8_t *ptr = tile_map_data_array.ptrw();
  2747. // Index in the array.
  2748. int index = 0;
  2749. // Save the version.
  2750. encode_uint16(TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1, &ptr[index]);
  2751. index += 2;
  2752. // Save in highest format.
  2753. for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
  2754. // Get a pointer at the start of the cell data.
  2755. uint8_t *cell_data_ptr = (uint8_t *)&ptr[index];
  2756. // Store position in TileMap.
  2757. encode_uint16((int16_t)(E.key.x), &cell_data_ptr[0]);
  2758. encode_uint16((int16_t)(E.key.y), &cell_data_ptr[2]);
  2759. // Store the tile identifiers.
  2760. encode_uint16(E.value.cell.source_id, &cell_data_ptr[4]);
  2761. encode_uint16(E.value.cell.coord_x, &cell_data_ptr[6]);
  2762. encode_uint16(E.value.cell.coord_y, &cell_data_ptr[8]);
  2763. encode_uint16(E.value.cell.alternative_tile, &cell_data_ptr[10]);
  2764. index += cell_data_struct_size;
  2765. }
  2766. return tile_map_data_array;
  2767. }
  2768. void TileMapLayer::set_self_modulate(const Color &p_self_modulate) {
  2769. if (get_self_modulate() == p_self_modulate) {
  2770. return;
  2771. }
  2772. CanvasItem::set_self_modulate(p_self_modulate);
  2773. dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE] = true;
  2774. _queue_internal_update();
  2775. emit_signal(CoreStringName(changed));
  2776. }
  2777. void TileMapLayer::set_y_sort_enabled(bool p_y_sort_enabled) {
  2778. if (is_y_sort_enabled() == p_y_sort_enabled) {
  2779. return;
  2780. }
  2781. CanvasItem::set_y_sort_enabled(p_y_sort_enabled);
  2782. dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] = true;
  2783. _queue_internal_update();
  2784. emit_signal(CoreStringName(changed));
  2785. notify_property_list_changed();
  2786. _update_notify_local_transform();
  2787. }
  2788. void TileMapLayer::set_y_sort_origin(int p_y_sort_origin) {
  2789. if (y_sort_origin == p_y_sort_origin) {
  2790. return;
  2791. }
  2792. y_sort_origin = p_y_sort_origin;
  2793. dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] = true;
  2794. _queue_internal_update();
  2795. emit_signal(CoreStringName(changed));
  2796. }
  2797. int TileMapLayer::get_y_sort_origin() const {
  2798. return y_sort_origin;
  2799. }
  2800. void TileMapLayer::set_x_draw_order_reversed(bool p_x_draw_order_reversed) {
  2801. if (x_draw_order_reversed == p_x_draw_order_reversed) {
  2802. return;
  2803. }
  2804. x_draw_order_reversed = p_x_draw_order_reversed;
  2805. dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] = true;
  2806. _queue_internal_update();
  2807. emit_signal(CoreStringName(changed));
  2808. }
  2809. bool TileMapLayer::is_x_draw_order_reversed() const {
  2810. return x_draw_order_reversed;
  2811. }
  2812. void TileMapLayer::set_z_index(int p_z_index) {
  2813. if (get_z_index() == p_z_index) {
  2814. return;
  2815. }
  2816. CanvasItem::set_z_index(p_z_index);
  2817. dirty.flags[DIRTY_FLAGS_LAYER_Z_INDEX] = true;
  2818. _queue_internal_update();
  2819. emit_signal(CoreStringName(changed));
  2820. }
  2821. void TileMapLayer::set_light_mask(int p_light_mask) {
  2822. if (get_light_mask() == p_light_mask) {
  2823. return;
  2824. }
  2825. CanvasItem::set_light_mask(p_light_mask);
  2826. dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] = true;
  2827. _queue_internal_update();
  2828. emit_signal(CoreStringName(changed));
  2829. }
  2830. void TileMapLayer::set_rendering_quadrant_size(int p_size) {
  2831. if (rendering_quadrant_size == p_size) {
  2832. return;
  2833. }
  2834. ERR_FAIL_COND_MSG(p_size < 1, "TileMapQuadrant size cannot be smaller than 1.");
  2835. rendering_quadrant_size = p_size;
  2836. dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE] = true;
  2837. _queue_internal_update();
  2838. emit_signal(CoreStringName(changed));
  2839. }
  2840. int TileMapLayer::get_rendering_quadrant_size() const {
  2841. return rendering_quadrant_size;
  2842. }
  2843. void TileMapLayer::set_collision_enabled(bool p_enabled) {
  2844. if (collision_enabled == p_enabled) {
  2845. return;
  2846. }
  2847. collision_enabled = p_enabled;
  2848. dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_ENABLED] = true;
  2849. _queue_internal_update();
  2850. emit_signal(CoreStringName(changed));
  2851. }
  2852. bool TileMapLayer::is_collision_enabled() const {
  2853. return collision_enabled;
  2854. }
  2855. void TileMapLayer::set_use_kinematic_bodies(bool p_use_kinematic_bodies) {
  2856. if (use_kinematic_bodies == p_use_kinematic_bodies) {
  2857. return;
  2858. }
  2859. use_kinematic_bodies = p_use_kinematic_bodies;
  2860. dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES] = p_use_kinematic_bodies;
  2861. _queue_internal_update();
  2862. emit_signal(CoreStringName(changed));
  2863. }
  2864. bool TileMapLayer::is_using_kinematic_bodies() const {
  2865. return use_kinematic_bodies;
  2866. }
  2867. void TileMapLayer::set_collision_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_collision) {
  2868. if (collision_visibility_mode == p_show_collision) {
  2869. return;
  2870. }
  2871. collision_visibility_mode = p_show_collision;
  2872. dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_VISIBILITY_MODE] = true;
  2873. _queue_internal_update();
  2874. emit_signal(CoreStringName(changed));
  2875. }
  2876. TileMapLayer::DebugVisibilityMode TileMapLayer::get_collision_visibility_mode() const {
  2877. return collision_visibility_mode;
  2878. }
  2879. void TileMapLayer::set_physics_quadrant_size(int p_size) {
  2880. if (physics_quadrant_size == p_size) {
  2881. return;
  2882. }
  2883. ERR_FAIL_COND_MSG(p_size < 1, "Physics quandrant size cannot be smaller than 1.");
  2884. physics_quadrant_size = p_size;
  2885. dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE] = true;
  2886. _queue_internal_update();
  2887. emit_signal(CoreStringName(changed));
  2888. }
  2889. int TileMapLayer::get_physics_quadrant_size() const {
  2890. return physics_quadrant_size;
  2891. }
  2892. void TileMapLayer::set_occlusion_enabled(bool p_enabled) {
  2893. if (occlusion_enabled == p_enabled) {
  2894. return;
  2895. }
  2896. occlusion_enabled = p_enabled;
  2897. dirty.flags[DIRTY_FLAGS_LAYER_OCCLUSION_ENABLED] = true;
  2898. _queue_internal_update();
  2899. emit_signal(CoreStringName(changed));
  2900. }
  2901. bool TileMapLayer::is_occlusion_enabled() const {
  2902. return occlusion_enabled;
  2903. }
  2904. #ifndef NAVIGATION_2D_DISABLED
  2905. void TileMapLayer::set_navigation_enabled(bool p_enabled) {
  2906. if (navigation_enabled == p_enabled) {
  2907. return;
  2908. }
  2909. navigation_enabled = p_enabled;
  2910. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_ENABLED] = true;
  2911. _queue_internal_update();
  2912. emit_signal(CoreStringName(changed));
  2913. }
  2914. bool TileMapLayer::is_navigation_enabled() const {
  2915. return navigation_enabled;
  2916. }
  2917. void TileMapLayer::set_navigation_map(RID p_map) {
  2918. if (navigation_map_override == p_map) {
  2919. return;
  2920. }
  2921. navigation_map_override = p_map;
  2922. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP] = true;
  2923. _queue_internal_update();
  2924. emit_signal(CoreStringName(changed));
  2925. }
  2926. RID TileMapLayer::get_navigation_map() const {
  2927. if (navigation_map_override.is_valid()) {
  2928. return navigation_map_override;
  2929. } else if (is_inside_tree()) {
  2930. return get_world_2d()->get_navigation_map();
  2931. }
  2932. return RID();
  2933. }
  2934. void TileMapLayer::set_navigation_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_navigation) {
  2935. if (navigation_visibility_mode == p_show_navigation) {
  2936. return;
  2937. }
  2938. navigation_visibility_mode = p_show_navigation;
  2939. dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_VISIBILITY_MODE] = true;
  2940. _queue_internal_update();
  2941. emit_signal(CoreStringName(changed));
  2942. }
  2943. TileMapLayer::DebugVisibilityMode TileMapLayer::get_navigation_visibility_mode() const {
  2944. return navigation_visibility_mode;
  2945. }
  2946. void TileMapLayer::navmesh_parse_init() {
  2947. ERR_FAIL_NULL(NavigationServer2D::get_singleton());
  2948. if (!_navmesh_source_geometry_parser.is_valid()) {
  2949. _navmesh_source_geometry_parsing_callback = callable_mp_static(&TileMapLayer::navmesh_parse_source_geometry);
  2950. _navmesh_source_geometry_parser = NavigationServer2D::get_singleton()->source_geometry_parser_create();
  2951. NavigationServer2D::get_singleton()->source_geometry_parser_set_callback(_navmesh_source_geometry_parser, _navmesh_source_geometry_parsing_callback);
  2952. }
  2953. }
  2954. void TileMapLayer::navmesh_parse_source_geometry(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
  2955. TileMapLayer *tile_map_layer = Object::cast_to<TileMapLayer>(p_node);
  2956. if (tile_map_layer == nullptr) {
  2957. return;
  2958. }
  2959. Ref<TileSet> tile_set = tile_map_layer->get_tile_set();
  2960. if (tile_set.is_null()) {
  2961. return;
  2962. }
  2963. int navigation_layers_count = tile_set->get_navigation_layers_count();
  2964. #ifndef PHYSICS_2D_DISABLED
  2965. int physics_layers_count = tile_set->get_physics_layers_count();
  2966. if (physics_layers_count <= 0 && navigation_layers_count <= 0) {
  2967. return;
  2968. }
  2969. #else
  2970. if (navigation_layers_count <= 0) {
  2971. return;
  2972. }
  2973. #endif // PHYSICS_2D_DISABLED
  2974. const Transform2D tilemap_xform = p_source_geometry_data->root_node_transform * tile_map_layer->get_global_transform();
  2975. for (KeyValue<Vector2i, CellData> kv : tile_map_layer->get_tile_map_layer_data()) {
  2976. const Vector2i &cell = kv.key;
  2977. const TileData *tile_data = tile_map_layer->get_cell_tile_data(cell);
  2978. if (tile_data == nullptr) {
  2979. continue;
  2980. }
  2981. // Transform flags.
  2982. const int alternative_id = tile_map_layer->get_cell_alternative_tile(cell);
  2983. bool flip_h = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_H);
  2984. bool flip_v = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_V);
  2985. bool transpose = (alternative_id & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
  2986. Transform2D tile_transform;
  2987. tile_transform.set_origin(tile_map_layer->map_to_local(cell));
  2988. const Transform2D tile_transform_offset = tilemap_xform * tile_transform;
  2989. // Parse traversable polygons.
  2990. for (int navigation_layer = 0; navigation_layer < navigation_layers_count; navigation_layer++) {
  2991. Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer, flip_h, flip_v, transpose);
  2992. if (navigation_polygon.is_valid()) {
  2993. for (int outline_index = 0; outline_index < navigation_polygon->get_outline_count(); outline_index++) {
  2994. const Vector<Vector2> &navigation_polygon_outline = navigation_polygon->get_outline(outline_index);
  2995. if (navigation_polygon_outline.is_empty()) {
  2996. continue;
  2997. }
  2998. Vector<Vector2> traversable_outline;
  2999. traversable_outline.resize(navigation_polygon_outline.size());
  3000. const Vector2 *navigation_polygon_outline_ptr = navigation_polygon_outline.ptr();
  3001. Vector2 *traversable_outline_ptrw = traversable_outline.ptrw();
  3002. for (int traversable_outline_index = 0; traversable_outline_index < traversable_outline.size(); traversable_outline_index++) {
  3003. traversable_outline_ptrw[traversable_outline_index] = tile_transform_offset.xform(navigation_polygon_outline_ptr[traversable_outline_index]);
  3004. }
  3005. p_source_geometry_data->_add_traversable_outline(traversable_outline);
  3006. }
  3007. }
  3008. }
  3009. #ifndef PHYSICS_2D_DISABLED
  3010. NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
  3011. uint32_t parsed_collision_mask = p_navigation_mesh->get_parsed_collision_mask();
  3012. // Parse obstacles.
  3013. for (int physics_layer = 0; physics_layer < physics_layers_count; physics_layer++) {
  3014. if ((parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH) &&
  3015. (tile_set->get_physics_layer_collision_layer(physics_layer) & parsed_collision_mask)) {
  3016. for (int collision_polygon_index = 0; collision_polygon_index < tile_data->get_collision_polygons_count(physics_layer); collision_polygon_index++) {
  3017. PackedVector2Array collision_polygon_points = tile_data->get_collision_polygon_points(physics_layer, collision_polygon_index);
  3018. if (collision_polygon_points.is_empty()) {
  3019. continue;
  3020. }
  3021. if (flip_h || flip_v || transpose) {
  3022. collision_polygon_points = TileData::get_transformed_vertices(collision_polygon_points, flip_h, flip_v, transpose);
  3023. }
  3024. Vector<Vector2> obstruction_outline;
  3025. obstruction_outline.resize(collision_polygon_points.size());
  3026. const Vector2 *collision_polygon_points_ptr = collision_polygon_points.ptr();
  3027. Vector2 *obstruction_outline_ptrw = obstruction_outline.ptrw();
  3028. for (int obstruction_outline_index = 0; obstruction_outline_index < obstruction_outline.size(); obstruction_outline_index++) {
  3029. obstruction_outline_ptrw[obstruction_outline_index] = tile_transform_offset.xform(collision_polygon_points_ptr[obstruction_outline_index]);
  3030. }
  3031. p_source_geometry_data->_add_obstruction_outline(obstruction_outline);
  3032. }
  3033. }
  3034. }
  3035. #endif // PHYSICS_2D_DISABLED
  3036. }
  3037. }
  3038. #endif // NAVIGATION_2D_DISABLED
  3039. TileMapLayer::TileMapLayer() {
  3040. set_notify_transform(true);
  3041. }
  3042. TileMapLayer::~TileMapLayer() {
  3043. clear();
  3044. _internal_update(true);
  3045. }
  3046. HashMap<Vector2i, TileSet::CellNeighbor> TerrainConstraint::get_overlapping_coords_and_peering_bits() const {
  3047. HashMap<Vector2i, TileSet::CellNeighbor> output;
  3048. ERR_FAIL_COND_V(is_center_bit(), output);
  3049. ERR_FAIL_COND_V(tile_set.is_null(), output);
  3050. TileSet::TileShape shape = tile_set->get_tile_shape();
  3051. if (shape == TileSet::TILE_SHAPE_SQUARE) {
  3052. switch (bit) {
  3053. case 1:
  3054. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
  3055. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
  3056. break;
  3057. case 2:
  3058. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3059. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3060. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3061. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
  3062. break;
  3063. case 3:
  3064. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
  3065. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
  3066. break;
  3067. default:
  3068. ERR_FAIL_V(output);
  3069. }
  3070. } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
  3071. switch (bit) {
  3072. case 1:
  3073. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3074. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3075. break;
  3076. case 2:
  3077. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
  3078. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
  3079. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
  3080. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
  3081. break;
  3082. case 3:
  3083. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3084. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3085. break;
  3086. default:
  3087. ERR_FAIL_V(output);
  3088. }
  3089. } else {
  3090. // Half offset shapes.
  3091. TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
  3092. if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
  3093. switch (bit) {
  3094. case 1:
  3095. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
  3096. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
  3097. break;
  3098. case 2:
  3099. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3100. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3101. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
  3102. break;
  3103. case 3:
  3104. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3105. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3106. break;
  3107. case 4:
  3108. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
  3109. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3110. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
  3111. break;
  3112. case 5:
  3113. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3114. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3115. break;
  3116. default:
  3117. ERR_FAIL_V(output);
  3118. }
  3119. } else {
  3120. switch (bit) {
  3121. case 1:
  3122. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
  3123. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
  3124. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3125. break;
  3126. case 2:
  3127. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
  3128. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
  3129. break;
  3130. case 3:
  3131. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
  3132. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
  3133. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
  3134. break;
  3135. case 4:
  3136. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
  3137. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
  3138. break;
  3139. case 5:
  3140. output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
  3141. output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
  3142. break;
  3143. default:
  3144. ERR_FAIL_V(output);
  3145. }
  3146. }
  3147. }
  3148. return output;
  3149. }
  3150. TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, int p_terrain) {
  3151. ERR_FAIL_COND(p_tile_set.is_null());
  3152. tile_set = p_tile_set;
  3153. bit = 0;
  3154. base_cell_coords = p_position;
  3155. terrain = p_terrain;
  3156. }
  3157. TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, const TileSet::CellNeighbor &p_bit, int p_terrain) {
  3158. // The way we build the constraint make it easy to detect conflicting constraints.
  3159. ERR_FAIL_COND(p_tile_set.is_null());
  3160. tile_set = p_tile_set;
  3161. TileSet::TileShape shape = tile_set->get_tile_shape();
  3162. if (shape == TileSet::TILE_SHAPE_SQUARE) {
  3163. switch (p_bit) {
  3164. case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
  3165. bit = 1;
  3166. base_cell_coords = p_position;
  3167. break;
  3168. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3169. bit = 2;
  3170. base_cell_coords = p_position;
  3171. break;
  3172. case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
  3173. bit = 3;
  3174. base_cell_coords = p_position;
  3175. break;
  3176. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3177. bit = 2;
  3178. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3179. break;
  3180. case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
  3181. bit = 1;
  3182. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3183. break;
  3184. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3185. bit = 2;
  3186. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER);
  3187. break;
  3188. case TileSet::CELL_NEIGHBOR_TOP_SIDE:
  3189. bit = 3;
  3190. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3191. break;
  3192. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3193. bit = 2;
  3194. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3195. break;
  3196. default:
  3197. ERR_FAIL();
  3198. break;
  3199. }
  3200. } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
  3201. switch (p_bit) {
  3202. case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
  3203. bit = 2;
  3204. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3205. break;
  3206. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3207. bit = 1;
  3208. base_cell_coords = p_position;
  3209. break;
  3210. case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
  3211. bit = 2;
  3212. base_cell_coords = p_position;
  3213. break;
  3214. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3215. bit = 3;
  3216. base_cell_coords = p_position;
  3217. break;
  3218. case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
  3219. bit = 2;
  3220. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3221. break;
  3222. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3223. bit = 1;
  3224. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3225. break;
  3226. case TileSet::CELL_NEIGHBOR_TOP_CORNER:
  3227. bit = 2;
  3228. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_CORNER);
  3229. break;
  3230. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3231. bit = 3;
  3232. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3233. break;
  3234. default:
  3235. ERR_FAIL();
  3236. break;
  3237. }
  3238. } else {
  3239. // Half-offset shapes.
  3240. TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
  3241. if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
  3242. switch (p_bit) {
  3243. case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
  3244. bit = 1;
  3245. base_cell_coords = p_position;
  3246. break;
  3247. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3248. bit = 2;
  3249. base_cell_coords = p_position;
  3250. break;
  3251. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3252. bit = 3;
  3253. base_cell_coords = p_position;
  3254. break;
  3255. case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
  3256. bit = 4;
  3257. base_cell_coords = p_position;
  3258. break;
  3259. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3260. bit = 5;
  3261. base_cell_coords = p_position;
  3262. break;
  3263. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3264. bit = 2;
  3265. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3266. break;
  3267. case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
  3268. bit = 1;
  3269. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
  3270. break;
  3271. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3272. bit = 4;
  3273. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3274. break;
  3275. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3276. bit = 3;
  3277. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3278. break;
  3279. case TileSet::CELL_NEIGHBOR_TOP_CORNER:
  3280. bit = 2;
  3281. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3282. break;
  3283. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3284. bit = 5;
  3285. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3286. break;
  3287. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3288. bit = 4;
  3289. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3290. break;
  3291. default:
  3292. ERR_FAIL();
  3293. break;
  3294. }
  3295. } else {
  3296. switch (p_bit) {
  3297. case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
  3298. bit = 1;
  3299. base_cell_coords = p_position;
  3300. break;
  3301. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
  3302. bit = 2;
  3303. base_cell_coords = p_position;
  3304. break;
  3305. case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
  3306. bit = 3;
  3307. base_cell_coords = p_position;
  3308. break;
  3309. case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
  3310. bit = 4;
  3311. base_cell_coords = p_position;
  3312. break;
  3313. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
  3314. bit = 1;
  3315. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE);
  3316. break;
  3317. case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
  3318. bit = 5;
  3319. base_cell_coords = p_position;
  3320. break;
  3321. case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
  3322. bit = 3;
  3323. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3324. break;
  3325. case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
  3326. bit = 2;
  3327. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3328. break;
  3329. case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
  3330. bit = 1;
  3331. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
  3332. break;
  3333. case TileSet::CELL_NEIGHBOR_TOP_SIDE:
  3334. bit = 4;
  3335. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3336. break;
  3337. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
  3338. bit = 3;
  3339. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
  3340. break;
  3341. case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
  3342. bit = 5;
  3343. base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
  3344. break;
  3345. default:
  3346. ERR_FAIL();
  3347. break;
  3348. }
  3349. }
  3350. }
  3351. terrain = p_terrain;
  3352. }