tile_map_layer.cpp 147 KB

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