tile_map_layer.cpp 131 KB

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