Нема описа
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GridPaintPaletteClipboard.cs 86KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEditor.EditorTools;
  4. using UnityEngine;
  5. using UnityEngine.Tilemaps;
  6. using UnityEngine.UIElements;
  7. namespace UnityEditor.Tilemaps
  8. {
  9. [Serializable]
  10. internal class GridPaintPaletteClipboard : PaintableGrid
  11. {
  12. private static List<GridPaintPaletteClipboard> s_Instances;
  13. public static List<GridPaintPaletteClipboard> instances
  14. {
  15. get
  16. {
  17. if (s_Instances == null)
  18. s_Instances = new List<GridPaintPaletteClipboard>();
  19. return s_Instances;
  20. }
  21. }
  22. private bool m_DisableOnBrushPicked;
  23. public event Action onBrushPicked;
  24. private static readonly string paletteSavedOutsideClipboard = L10n.Tr("Palette Asset {0} was changed outside of the Tile Palette. All changes in the Tile Palette made will be reverted.");
  25. private bool m_PaletteNeedsSave;
  26. private const float k_ZoomSpeed = 7f;
  27. private const float k_MinZoom = 10f; // How many pixels per cell at minimum
  28. private const float k_MaxZoom = 200f; // How many pixels per cell at maximum
  29. private const float k_Padding = 0.75f; // How many percentages of window size is the empty padding around the palette content
  30. private int m_KeyboardPanningID;
  31. private int m_MousePanningID;
  32. private Vector2 m_MouseZoomInitialPosition;
  33. private float k_KeyboardPanningSpeed = 9.0f;
  34. private Vector3 m_KeyboardPanning;
  35. private Rect m_GUIRect = new Rect(0, 0, 200, 200);
  36. public Rect guiRect
  37. {
  38. get => m_GUIRect;
  39. set
  40. {
  41. if (m_GUIRect == value)
  42. return;
  43. var oldValue = m_GUIRect;
  44. m_GUIRect = value;
  45. OnViewSizeChanged(oldValue, m_GUIRect);
  46. }
  47. }
  48. private VisualElement m_VisualElement;
  49. public bool activeDragAndDrop { get { return DragAndDrop.objectReferences.Length > 0 && guiRect.Contains(mousePosition); } }
  50. public bool invalidDragAndDrop => m_HoverData != null && m_HoverData.Count == 0;
  51. [SerializeField]
  52. private GridPaletteUtility.GridPaletteType m_FirstUserPaletteType = GridPaletteUtility.GridPaletteType.Rectangle;
  53. [SerializeField] private bool m_CameraInitializedToBounds;
  54. [SerializeField] public bool m_CameraPositionSaved;
  55. [SerializeField] public Vector3 m_CameraPosition;
  56. [SerializeField] public float m_CameraOrthographicSize;
  57. [SerializeField] public GridLayout.CellSwizzle m_CameraSwizzleView;
  58. private Dictionary<Vector2Int, TileDragAndDropHoverData> m_HoverData;
  59. private bool m_Unlocked;
  60. private GameObject palette => GridPaintingState.palette;
  61. private GridBrushBase gridBrush => GridPaintingState.gridBrush;
  62. private PreviewRenderUtility m_PreviewUtility;
  63. internal Vector3 cameraPosition
  64. {
  65. get => m_PreviewUtility.camera.transform.position;
  66. set
  67. {
  68. m_PreviewUtility.camera.transform.position = value;
  69. ClampZoomAndPan();
  70. }
  71. }
  72. internal float cameraSize
  73. {
  74. get => m_PreviewUtility.camera.orthographicSize;
  75. set
  76. {
  77. m_PreviewUtility.camera.orthographicSize = value;
  78. ClampZoomAndPan();
  79. }
  80. }
  81. internal TransparencySortMode cameraTransparencySortMode
  82. {
  83. get => m_PreviewUtility.camera.transparencySortMode;
  84. set => m_PreviewUtility.camera.transparencySortMode = value;
  85. }
  86. internal Vector3 cameraTransparencySortAxis
  87. {
  88. get => m_PreviewUtility.camera.transparencySortAxis;
  89. set => m_PreviewUtility.camera.transparencySortAxis = value;
  90. }
  91. [SerializeField] private GameObject m_PaletteInstance;
  92. internal GameObject paletteInstance
  93. {
  94. get
  95. {
  96. if (m_PaletteInstance == null && palette != null && m_PreviewUtility != null)
  97. ResetPreviewInstance();
  98. return m_PaletteInstance;
  99. }
  100. }
  101. private Tilemap tilemap { get { return paletteInstance != null ? paletteInstance.GetComponentInChildren<Tilemap>() : null; } }
  102. private Grid grid { get { return paletteInstance != null ? paletteInstance.GetComponent<Grid>() : null; } }
  103. private Grid prefabGrid { get { return palette != null ? palette.GetComponent<Grid>() : null; } }
  104. private Mesh m_GridMesh;
  105. private int m_LastGridHash;
  106. private Material m_GridMaterial;
  107. private static readonly PrefColor k_GridColor = new PrefColor("2D/Tile Palette Grid", 255.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 25.5f / 255.0f);
  108. private static readonly PrefColor tilePaletteBackgroundColor = new PrefColor("2D/Tile Palette Background"
  109. , 1.0f / 255.0f // Light
  110. , 35.0f / 255.0f
  111. , 90.0f / 255.0f
  112. , 127.0f / 255.0f
  113. , 1.0f / 255.0f // Dark
  114. , 35.0f / 255.0f
  115. , 90.0f / 255.0f
  116. , 127.0f / 255.0f);
  117. private bool m_PaletteUsed; // We mark palette used, when it has been changed in any way during being actively open.
  118. private Vector2? m_PreviousMousePosition;
  119. private bool m_DelayedResetPaletteInstance;
  120. internal void DelayedResetPreviewInstance()
  121. {
  122. m_DelayedResetPaletteInstance = true;
  123. }
  124. public TileBase activeTile
  125. {
  126. get
  127. {
  128. if (GridPaintingState.hasActivePick
  129. && GridPaintingState.activePick.size == Vector3Int.one
  130. && GridPaintingState.defaultBrush != null
  131. && GridPaintingState.defaultBrush.cellCount > 0)
  132. return GridPaintingState.defaultBrush.cells[0].tile;
  133. return null;
  134. }
  135. }
  136. private RectInt? m_GameObjectBounds = null;
  137. private RectInt bounds
  138. {
  139. get
  140. {
  141. RectInt r = default;
  142. if (tilemap == null || TilemapIsEmpty(tilemap))
  143. {
  144. if (!isReceivingDragAndDrop)
  145. return m_GameObjectBounds.HasValue ? m_GameObjectBounds.Value : r;
  146. r = TileDragAndDrop.GetMinMaxRect(m_HoverData.Keys);
  147. }
  148. else
  149. {
  150. tilemap.CompressBounds();
  151. r = new RectInt((Vector2Int) tilemap.origin, (Vector2Int) tilemap.size);
  152. }
  153. if (m_GameObjectBounds.HasValue)
  154. {
  155. var origin = r.position;
  156. var size = r.size;
  157. var extent = origin + size;
  158. var goOrigin = m_GameObjectBounds.Value.min;
  159. var goExtent = m_GameObjectBounds.Value.max;
  160. if (goOrigin.x < origin.x)
  161. origin.x = goOrigin.x;
  162. if (goOrigin.y < origin.y)
  163. origin.y = goOrigin.y;
  164. if (goExtent.x > extent.x)
  165. extent.x = goExtent.x;
  166. if (goExtent.y > extent.y)
  167. extent.y = goExtent.y;
  168. size = extent - origin;
  169. r = new RectInt(origin.x, origin.y, size.x, size.y);
  170. }
  171. return r;
  172. }
  173. }
  174. // Max area we are ever showing. Depends on the zoom level and content of palette.
  175. private Rect paddedBounds
  176. {
  177. get
  178. {
  179. var GUIAspect = m_GUIRect.width / m_GUIRect.height;
  180. var orthographicSize = m_PreviewUtility.camera.orthographicSize;
  181. var paddingW = orthographicSize * GUIAspect * k_Padding * 2f;
  182. var paddingH = orthographicSize * k_Padding * 2f;
  183. Bounds localBounds = grid.GetBoundsLocal(
  184. new Vector3(bounds.xMin, bounds.yMin, 0.0f),
  185. new Vector3(bounds.size.x, bounds.size.y, 0.0f));
  186. Rect result = new Rect(
  187. new Vector2(localBounds.min.x - paddingW, localBounds.min.y - paddingH),
  188. new Vector2(localBounds.size.x + paddingW * 2f, localBounds.size.y + paddingH * 2f));
  189. return result;
  190. }
  191. }
  192. private RectInt paddedBoundsInt
  193. {
  194. get
  195. {
  196. var min = Vector3Int.FloorToInt(paddedBounds.min);
  197. var max = Vector3Int.CeilToInt(paddedBounds.max);
  198. return new RectInt(min.x, min.y, max.x - min.x, max.y - min.y);
  199. }
  200. }
  201. private GameObject brushTarget
  202. {
  203. get
  204. {
  205. return (tilemap != null) ? tilemap.gameObject : (grid != null) ? grid.gameObject : null;
  206. }
  207. }
  208. public bool unlocked
  209. {
  210. get { return m_Unlocked; }
  211. set
  212. {
  213. if (value == false && m_Unlocked)
  214. {
  215. if (tilemap != null)
  216. tilemap.ClearAllEditorPreviewTiles();
  217. SavePaletteIfNecessary();
  218. }
  219. m_Unlocked = value;
  220. unlockedChanged?.Invoke(m_Unlocked);
  221. }
  222. }
  223. public event Action<bool> unlockedChanged;
  224. public bool isReceivingDragAndDrop => m_HoverData != null && m_HoverData.Count > 0;
  225. public bool isInvalidDragAndDrop => m_HoverData != null && m_HoverData.Count == 0;
  226. public bool showNewEmptyClipboardInfo
  227. {
  228. get
  229. {
  230. if (paletteInstance == null)
  231. return false;
  232. if (tilemap == null)
  233. return false;
  234. if (unlocked && inEditMode)
  235. return false;
  236. if (!TilemapIsEmpty(tilemap))
  237. return false;
  238. if (tilemap.transform.childCount > 0)
  239. return false;
  240. if (isReceivingDragAndDrop)
  241. return false;
  242. if (isInvalidDragAndDrop)
  243. return false;
  244. // If user happens to erase the last content of used palette, we don't want to show the new palette info anymore
  245. if (m_PaletteUsed)
  246. return false;
  247. return true;
  248. }
  249. }
  250. public bool isModified { get { return m_PaletteNeedsSave; } }
  251. public VisualElement attachedVisualElement
  252. {
  253. set { m_VisualElement = value; }
  254. }
  255. public void OnBeforePaletteSelectionChanged()
  256. {
  257. SavePaletteIfNecessary();
  258. DestroyPreviewInstance();
  259. FlushHoverData();
  260. }
  261. private void FlushHoverData()
  262. {
  263. if (m_HoverData != null)
  264. {
  265. m_HoverData.Clear();
  266. m_HoverData = null;
  267. if (palette == null)
  268. DestroyPreviewInstance();
  269. }
  270. }
  271. public void OnAfterPaletteSelectionChanged()
  272. {
  273. m_PaletteUsed = false;
  274. ResetPreviewInstance();
  275. if (palette != null)
  276. ResetPreviewCamera();
  277. }
  278. public void SetupPreviewCameraOnInit()
  279. {
  280. if (m_CameraPositionSaved)
  281. LoadSavedCameraPosition();
  282. else
  283. ResetPreviewCamera();
  284. }
  285. private void LoadSavedCameraPosition()
  286. {
  287. m_PreviewUtility.camera.transform.position = m_CameraPosition;
  288. m_PreviewUtility.camera.orthographicSize = m_CameraOrthographicSize;
  289. m_PreviewUtility.camera.nearClipPlane = 0.01f;
  290. m_PreviewUtility.camera.farClipPlane = 100f;
  291. }
  292. private Vector3 GetCameraPositionFromXYZ(Vector3 xyzPosition)
  293. {
  294. var position = Grid.Swizzle(m_CameraSwizzleView, xyzPosition);
  295. position = GetCameraPosition(position);
  296. return position;
  297. }
  298. private Vector3 GetCameraPosition(Vector3 xyzPosition)
  299. {
  300. var position = xyzPosition;
  301. switch (m_CameraSwizzleView)
  302. {
  303. case GridLayout.CellSwizzle.XZY:
  304. {
  305. position.y = 10f;
  306. }
  307. break;
  308. case GridLayout.CellSwizzle.YZX:
  309. {
  310. position.y = -10f;
  311. }
  312. break;
  313. case GridLayout.CellSwizzle.ZYX:
  314. {
  315. position.x = 10f;
  316. }
  317. break;
  318. case GridLayout.CellSwizzle.ZXY:
  319. {
  320. position.x = -10f;
  321. }
  322. break;
  323. case GridLayout.CellSwizzle.YXZ:
  324. {
  325. position.z = 10f;
  326. }
  327. break;
  328. case GridLayout.CellSwizzle.XYZ:
  329. default:
  330. {
  331. position.z = -10f;
  332. }
  333. break;
  334. }
  335. return position;
  336. }
  337. private void ResetPreviewCamera()
  338. {
  339. var transform = m_PreviewUtility.camera.transform;
  340. transform.position = GetCameraPositionFromXYZ(Vector3.zero);
  341. switch (m_CameraSwizzleView)
  342. {
  343. case GridLayout.CellSwizzle.XZY:
  344. {
  345. transform.rotation = Quaternion.LookRotation(new Vector3(0, -1, 0), new Vector3(0, 0, 1));
  346. }
  347. break;
  348. case GridLayout.CellSwizzle.YZX:
  349. {
  350. transform.rotation = Quaternion.LookRotation(new Vector3(0, 1, 0), new Vector3(1, 0, 0));
  351. }
  352. break;
  353. case GridLayout.CellSwizzle.ZXY:
  354. {
  355. transform.rotation = Quaternion.LookRotation(new Vector3(1, 0, 0), new Vector3(0, 0, 1));
  356. }
  357. break;
  358. case GridLayout.CellSwizzle.ZYX:
  359. {
  360. transform.rotation = Quaternion.LookRotation(new Vector3(-1, 0, 0), new Vector3(0, 1, 0));
  361. }
  362. break;
  363. case GridLayout.CellSwizzle.YXZ:
  364. {
  365. transform.rotation = Quaternion.LookRotation(new Vector3(0, 0, -1), new Vector3(1, 0, 0));
  366. }
  367. break;
  368. case GridLayout.CellSwizzle.XYZ:
  369. default:
  370. {
  371. transform.rotation = Quaternion.identity;
  372. }
  373. break;
  374. }
  375. m_PreviewUtility.camera.nearClipPlane = 0.01f;
  376. m_PreviewUtility.camera.farClipPlane = 100f;
  377. FrameEntirePalette();
  378. }
  379. public void InitPreviewUtility()
  380. {
  381. m_PreviewUtility = new PreviewRenderUtility(true, true);
  382. m_PreviewUtility.camera.orthographic = true;
  383. m_PreviewUtility.camera.orthographicSize = 5f;
  384. m_PreviewUtility.camera.transform.position = new Vector3(0f, 0f, -10f);
  385. m_PreviewUtility.ambientColor = new Color(1f, 1f, 1f, 0);
  386. }
  387. public void ResetPreviewInstance()
  388. {
  389. // Store GridSelection for current Palette Instance
  390. Stack<int> childPositions = null;
  391. BoundsInt previousGridSelectionPosition = default;
  392. if (m_PaletteInstance != null && GridSelection.active && GridSelection.target.transform.IsChildOf(m_PaletteInstance.transform))
  393. {
  394. childPositions = new Stack<int>();
  395. var transform = GridSelection.target.transform;
  396. while (transform != null && transform != m_PaletteInstance.transform)
  397. {
  398. childPositions.Push(transform.GetSiblingIndex());
  399. transform = transform.parent;
  400. }
  401. previousGridSelectionPosition = GridSelection.position;
  402. ClearGridSelection();
  403. }
  404. DestroyPreviewInstance();
  405. if (palette != null)
  406. {
  407. m_PaletteInstance = m_PreviewUtility.InstantiatePrefabInScene(palette);
  408. // Disconnecting prefabs is no longer possible.
  409. // If performance of overrides on palette palette instance turns out to be a problem.
  410. // unpack the prefab instance here, and overwrite the prefab later instead of reconnecting.
  411. PrefabUtility.UnpackPrefabInstance(m_PaletteInstance, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
  412. EditorUtility.InitInstantiatedPreviewRecursive(m_PaletteInstance);
  413. m_PaletteInstance.transform.position = new Vector3(0, 0, 0);
  414. m_PaletteInstance.transform.rotation = Quaternion.identity;
  415. m_PaletteInstance.transform.localScale = Vector3.one;
  416. var paletteAsset = GridPaletteUtility.GetGridPaletteFromPaletteAsset(palette);
  417. if (paletteAsset != null)
  418. {
  419. // Handle Cell Sizing for Palette
  420. if (paletteAsset.cellSizing == GridPalette.CellSizing.Automatic)
  421. {
  422. var paletteGrid = m_PaletteInstance.GetComponent<Grid>();
  423. if (paletteGrid != null)
  424. {
  425. paletteGrid.cellSize = GridPaletteUtility.CalculateAutoCellSize(paletteGrid, paletteGrid.cellSize);
  426. }
  427. else
  428. {
  429. Debug.LogWarning("Grid component not found from: " + palette.name);
  430. }
  431. }
  432. // Handle Transparency Sort Settings
  433. m_PreviewUtility.camera.transparencySortMode = paletteAsset.transparencySortMode;
  434. m_PreviewUtility.camera.transparencySortAxis = paletteAsset.transparencySortAxis;
  435. // Handle Camera View for Grid
  436. m_CameraSwizzleView = GridLayout.CellSwizzle.XYZ;
  437. var instanceGrid = m_PaletteInstance.GetComponent<Grid>();
  438. if (instanceGrid != null)
  439. m_CameraSwizzleView = instanceGrid.cellSwizzle;
  440. }
  441. else
  442. {
  443. Debug.LogWarning("GridPalette subasset not found from: " + palette.name);
  444. m_PreviewUtility.camera.transparencySortMode = TransparencySortMode.Default;
  445. m_PreviewUtility.camera.transparencySortAxis = new Vector3(0f, 0f, 1f);
  446. }
  447. foreach (var transform in m_PaletteInstance.GetComponentsInChildren<Transform>())
  448. transform.gameObject.hideFlags = HideFlags.HideAndDontSave;
  449. // Show all renderers from Palettes from previous versions
  450. var goBounds = SetEnableRenderersAndGetBounds(m_PaletteInstance, true);
  451. if (float.IsNormal(goBounds.x) && float.IsNormal(goBounds.y))
  452. {
  453. m_GameObjectBounds = new RectInt(Mathf.FloorToInt(goBounds.x)
  454. , Mathf.FloorToInt(goBounds.y)
  455. , Mathf.CeilToInt(goBounds.width)
  456. , Mathf.CeilToInt(goBounds.height));
  457. }
  458. else
  459. {
  460. m_GameObjectBounds = null;
  461. }
  462. // Update preview Grid Mesh for new palette instance
  463. ResetPreviewGridMesh();
  464. // Restore GridSelection for new palette instance
  465. if (childPositions != null)
  466. {
  467. var transform = m_PaletteInstance.transform;
  468. while (childPositions.Count > 0)
  469. {
  470. var siblingIndex = childPositions.Pop();
  471. if (siblingIndex < transform.childCount)
  472. transform = transform.GetChild(siblingIndex);
  473. }
  474. GridSelection.Select(transform.gameObject, previousGridSelectionPosition);
  475. }
  476. }
  477. m_DelayedResetPaletteInstance = false;
  478. }
  479. internal static Rect SetEnableRenderersAndGetBounds(GameObject go, bool enabled)
  480. {
  481. var origin = Vector2.positiveInfinity;
  482. var extents = Vector2.negativeInfinity;
  483. foreach (Renderer renderer in go.GetComponentsInChildren<Renderer>())
  484. {
  485. renderer.enabled = enabled;
  486. if (renderer is not TilemapRenderer)
  487. {
  488. var rbounds = renderer.bounds;
  489. if (rbounds.min.x < origin.x)
  490. origin.x = rbounds.min.x;
  491. if (rbounds.min.y < origin.y)
  492. origin.y = rbounds.min.y;
  493. if (rbounds.max.x > extents.x)
  494. extents.x = rbounds.max.x;
  495. if (rbounds.min.x < extents.x)
  496. extents.y = rbounds.max.y;
  497. }
  498. }
  499. return new Rect(origin, extents - origin);
  500. }
  501. public void CreateTemporaryPreviewInstance()
  502. {
  503. if (palette != null)
  504. return;
  505. DestroyPreviewInstance();
  506. m_PaletteInstance = new GameObject("First User Palette", typeof(Grid), typeof(Tilemap),
  507. typeof(TilemapRenderer));
  508. m_PreviewUtility.camera.transparencySortMode = TransparencySortMode.Default;
  509. m_PreviewUtility.camera.transparencySortAxis = new Vector3(0f, 0f, 1f);
  510. var paletteGrid = m_PaletteInstance.GetComponent<Grid>();
  511. switch (m_FirstUserPaletteType)
  512. {
  513. case GridPaletteUtility.GridPaletteType.Rectangle:
  514. {
  515. paletteGrid.cellLayout = GridLayout.CellLayout.Rectangle;
  516. paletteGrid.cellSize = new Vector3(1, 1, 0);
  517. break;
  518. }
  519. case GridPaletteUtility.GridPaletteType.HexagonalPointTop:
  520. {
  521. paletteGrid.cellLayout = GridLayout.CellLayout.Hexagon;
  522. paletteGrid.cellSize = new Vector3(1, 1, 0);
  523. break;
  524. }
  525. case GridPaletteUtility.GridPaletteType.HexagonalFlatTop:
  526. {
  527. paletteGrid.cellLayout = GridLayout.CellLayout.Hexagon;
  528. paletteGrid.cellSize = new Vector3(1, 1, 0);
  529. paletteGrid.cellSwizzle = GridLayout.CellSwizzle.YXZ;
  530. break;
  531. }
  532. case GridPaletteUtility.GridPaletteType.Isometric:
  533. {
  534. paletteGrid.cellLayout = GridLayout.CellLayout.Isometric;
  535. paletteGrid.cellSize = new Vector3(1, 0.5f, 1);
  536. break;
  537. }
  538. case GridPaletteUtility.GridPaletteType.IsometricZAsY:
  539. {
  540. paletteGrid.cellLayout = GridLayout.CellLayout.IsometricZAsY;
  541. paletteGrid.cellSize = new Vector3(1, 0.5f, 1);
  542. m_PreviewUtility.camera.transparencySortMode = TransparencySortMode.CustomAxis;
  543. m_PreviewUtility.camera.transparencySortAxis = new Vector3(0f, 1f, -0.25f);
  544. break;
  545. }
  546. }
  547. EditorUtility.InitInstantiatedPreviewRecursive(m_PaletteInstance);
  548. m_PaletteInstance.transform.position = new Vector3(0, 0, 0);
  549. m_PaletteInstance.transform.rotation = Quaternion.identity;
  550. m_PaletteInstance.transform.localScale = Vector3.one;
  551. foreach (var transform in m_PaletteInstance.GetComponentsInChildren<Transform>())
  552. transform.gameObject.hideFlags = HideFlags.HideAndDontSave;
  553. // Show all renderers from Palettes from previous versions
  554. PreviewRenderUtility.SetEnabledRecursive(m_PaletteInstance, true);
  555. // Update preview Grid Mesh for new palette instance
  556. ResetPreviewGridMesh();
  557. }
  558. public void DestroyPreviewInstance()
  559. {
  560. if (m_PaletteInstance != null)
  561. {
  562. Undo.ClearUndo(m_PaletteInstance);
  563. if (GridSelection.active && GridSelection.target == tilemap.gameObject)
  564. {
  565. GridSelection.TransferToStandalone(palette);
  566. }
  567. else
  568. {
  569. DestroyImmediate(m_PaletteInstance);
  570. }
  571. m_PaletteInstance = null;
  572. }
  573. }
  574. private void ResetPreviewGridMesh()
  575. {
  576. if (m_GridMesh != null)
  577. {
  578. DestroyImmediate(m_GridMesh);
  579. m_GridMesh = null;
  580. }
  581. m_GridMaterial = null;
  582. }
  583. public void FrameEntirePalette()
  584. {
  585. Frame(bounds);
  586. }
  587. private void Frame(RectInt rect)
  588. {
  589. if (grid == null)
  590. return;
  591. var position = grid.CellToLocalInterpolated(new Vector3(rect.center.x, rect.center.y, 0));
  592. position = GetCameraPosition(position);
  593. var height = (grid.CellToLocal(new Vector3Int(0, rect.yMax, 0)) - grid.CellToLocal(new Vector3Int(0, rect.yMin, 0))).magnitude;
  594. var width = (grid.CellToLocal(new Vector3Int(rect.xMax, 0, 0)) - grid.CellToLocal(new Vector3Int(rect.xMin, 0, 0))).magnitude;
  595. var cellSize = grid.cellSize;
  596. width += cellSize.x;
  597. height += cellSize.y;
  598. var guiAspect = m_GUIRect.width / m_GUIRect.height;
  599. var contentAspect = width / height;
  600. m_PreviewUtility.camera.transform.position = position;
  601. m_PreviewUtility.camera.orthographicSize = (guiAspect > contentAspect ? height : width / guiAspect) / 2f;
  602. ClampZoomAndPan();
  603. }
  604. private void RefreshAllTiles()
  605. {
  606. if (tilemap != null)
  607. tilemap.RefreshAllTiles();
  608. }
  609. protected override void OnEnable()
  610. {
  611. base.OnEnable();
  612. instances.Add(this);
  613. EditorApplication.editorApplicationQuit += EditorApplicationQuit;
  614. PrefabUtility.prefabInstanceUpdated += PrefabInstanceUpdated;
  615. Undo.undoRedoPerformed += UndoRedoPerformed;
  616. m_KeyboardPanningID = GUIUtility.GetPermanentControlID();
  617. m_MousePanningID = GUIUtility.GetPermanentControlID();
  618. InitPreviewUtility();
  619. ResetPreviewInstance();
  620. SetupPreviewCameraOnInit();
  621. }
  622. protected override void OnDisable()
  623. {
  624. SavePaletteIfNecessary();
  625. unlocked = false;
  626. DestroyPreviewInstance();
  627. if (m_PreviewUtility != null && m_PreviewUtility.camera != null)
  628. {
  629. // Save Preview camera coordinates
  630. m_CameraPosition = m_PreviewUtility.camera.transform.position;
  631. m_CameraOrthographicSize = m_PreviewUtility.camera.orthographicSize;
  632. m_CameraPositionSaved = true;
  633. }
  634. ResetPreviewGridMesh();
  635. if (m_PreviewUtility != null)
  636. m_PreviewUtility.Cleanup();
  637. m_PreviewUtility = null;
  638. Undo.undoRedoPerformed -= UndoRedoPerformed;
  639. PrefabUtility.prefabInstanceUpdated -= PrefabInstanceUpdated;
  640. EditorApplication.editorApplicationQuit -= EditorApplicationQuit;
  641. GridPaintingState.RemoveActiveGrid(this);
  642. instances.Remove(this);
  643. base.OnDisable();
  644. }
  645. private void OnViewSizeChanged(Rect oldSize, Rect newSize)
  646. {
  647. if (Mathf.Approximately(oldSize.height * oldSize.width * newSize.height * newSize.width, 0f))
  648. return;
  649. ClampZoomAndPan();
  650. }
  651. private void EditorApplicationQuit()
  652. {
  653. SavePaletteIfNecessary();
  654. }
  655. private void UndoRedoPerformed()
  656. {
  657. if (!unlocked)
  658. return;
  659. m_PaletteNeedsSave = true;
  660. RefreshAllTiles();
  661. Repaint();
  662. }
  663. private void PrefabInstanceUpdated(GameObject updatedPrefab)
  664. {
  665. // case 947462: Reset the palette instance after its prefab has been updated as it could have been changed
  666. if (m_PaletteInstance != null && PrefabUtility.GetCorrespondingObjectFromSource(updatedPrefab) == palette && !GridPaintingState.savingPalette)
  667. {
  668. m_PaletteNeedsSave = true;
  669. RefreshAllTiles();
  670. Repaint();
  671. }
  672. }
  673. public void HandleExecuteCommandEvent(ExecuteCommandEvent evt)
  674. {
  675. if (evt.commandName == EventCommandNames.FrameSelected)
  676. {
  677. if (GridPaintingState.hasActivePick)
  678. {
  679. var rect = new RectInt(GridPaintingState.activePick.x, GridPaintingState.activePick.y,
  680. GridPaintingState.activePick.size.x, GridPaintingState.activePick.size.y);
  681. Frame(rect);
  682. }
  683. else
  684. FrameEntirePalette();
  685. evt.StopPropagation();
  686. }
  687. }
  688. public void HandleValidateCommandEvent(ValidateCommandEvent evt)
  689. {
  690. if (evt.commandName == EventCommandNames.FrameSelected)
  691. {
  692. evt.StopPropagation();
  693. }
  694. }
  695. public void HandlePointerDownEvent(PointerDownEvent evt, int button, bool alt, bool control, Vector3 localMousePosition)
  696. {
  697. if (grid != null)
  698. UpdateMouseGridPositionUIToolkit(localMousePosition);
  699. if (m_MarqueeStart != null)
  700. {
  701. m_MarqueeType = MarqueeType.None;
  702. m_MarqueeStart = null;
  703. GUIUtility.hotControl = 0;
  704. }
  705. // Mouse Panning
  706. if (MousePanningEvent(button, alt) && guiRect.Contains(localMousePosition) && GUIUtility.hotControl == 0)
  707. {
  708. GUIUtility.hotControl = m_MousePanningID;
  709. m_MouseZoomInitialPosition = localMousePosition;
  710. evt.StopPropagation();
  711. }
  712. // Brush Picking
  713. if (IsPickingEvent(evt) && !isHotControl)
  714. {
  715. m_TypeBeforeExecution = typeof(PaintTool);
  716. if (inEditMode && !TilemapEditorTool.IsActive(typeof(PickingTool)))
  717. {
  718. m_TypeBeforeExecution = ToolManager.activeToolType;
  719. TilemapEditorTool.SetActiveEditorTool(typeof(PickingTool));
  720. }
  721. m_MarqueeStart = mouseGridPosition;
  722. m_MarqueeType = MarqueeType.Pick;
  723. evt.StopPropagation();
  724. GUI.changed = true;
  725. GUIUtility.hotControl = m_PermanentControlID;
  726. OnBrushPickStarted();
  727. }
  728. if (!inEditMode)
  729. return;
  730. // Brush Select
  731. if (IsSelectingEvent(evt))
  732. {
  733. if (TilemapEditorTool.IsActive(typeof(MoveTool)) && control)
  734. TilemapEditorTool.SetActiveEditorTool(typeof(SelectTool));
  735. m_PreviousMove = null;
  736. m_MarqueeStart = mouseGridPosition;
  737. m_MarqueeType = MarqueeType.Select;
  738. GUIUtility.hotControl = m_PermanentControlID;
  739. evt.StopPropagation();
  740. }
  741. if (!unlocked)
  742. return;
  743. // Brush Painting
  744. if (IsPaintingEvent(evt) || IsErasingEvent(evt))
  745. {
  746. RegisterUndo();
  747. GUIUtility.hotControl = m_PermanentControlID;
  748. executing = true;
  749. if (ToolManager.activeToolType != null && ToolManager.activeToolType.IsSubclassOf(typeof(TilemapEditorTool)))
  750. m_TypeBeforeExecution = ToolManager.activeToolType;
  751. var position = new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition);
  752. if (IsErasingEvent(evt))
  753. {
  754. if (!TilemapEditorTool.IsActive(typeof(EraseTool)))
  755. TilemapEditorTool.SetActiveEditorTool(typeof(EraseTool));
  756. Erase(position);
  757. }
  758. else
  759. {
  760. if (!TilemapEditorTool.IsActive(typeof(PaintTool)))
  761. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  762. Paint(position);
  763. }
  764. ResetPreviousMousePositionToCurrentPosition();
  765. evt.StopPropagation();
  766. GUI.changed = true;
  767. }
  768. // Brush Move
  769. if (IsMoveEvent(evt))
  770. {
  771. RegisterUndo();
  772. var mouse3D = new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, GridSelection.position.zMin);
  773. if (GridSelection.active && GridSelection.position.Contains(mouse3D))
  774. {
  775. GUIUtility.hotControl = m_PermanentControlID;
  776. executing = true;
  777. m_MarqueeStart = null;
  778. m_MarqueeType = MarqueeType.None;
  779. m_PreviousMove = mouseGridPosition;
  780. MoveStart(GridSelection.position);
  781. }
  782. evt.StopPropagation();
  783. }
  784. // Brush FloodFill
  785. if (TilemapEditorTool.IsActive(typeof(FillTool)) && GridPaintingState.gridBrush != null &&
  786. ValidateFloodFillPosition(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, 0)))
  787. {
  788. if (button == 0 && !alt)
  789. {
  790. GUIUtility.hotControl = m_PermanentControlID;
  791. GUI.changed = true;
  792. executing = true;
  793. evt.StopPropagation();
  794. }
  795. }
  796. // Brush Box
  797. if (button == 0 && !alt && TilemapEditorTool.IsActive(typeof(BoxTool)))
  798. {
  799. m_MarqueeStart = mouseGridPosition;
  800. m_MarqueeType = MarqueeType.Box;
  801. GUI.changed = true;
  802. executing = true;
  803. evt.StopPropagation();
  804. GUIUtility.hotControl = m_PermanentControlID;
  805. }
  806. // Brush Custom Tool
  807. if (TilemapEditorTool.IsCustomTilemapEditorToolActive())
  808. {
  809. var activeTool = EditorToolManager.activeTool as TilemapEditorTool;
  810. var executed = CustomTool(isHotControl, activeTool, new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition));
  811. if (executed != executing)
  812. {
  813. GUIUtility.hotControl = executed ? m_PermanentControlID : 0;
  814. executing = executed;
  815. GUI.changed = true;
  816. evt.StopPropagation();
  817. }
  818. else if (executing)
  819. {
  820. GUI.changed = true;
  821. evt.StopPropagation();
  822. }
  823. }
  824. }
  825. public void HandlePointerMoveEvent(PointerMoveEvent evt, int button, bool alt, Vector3 localMousePosition, Vector3 deltaPosition)
  826. {
  827. if (grid == null)
  828. return;
  829. var isButton0 = (evt.pressedButtons & 1) > 0;
  830. UpdateMouseGridPositionUIToolkit(localMousePosition, true);
  831. // Mouse Panning
  832. if (GUIUtility.hotControl == m_MousePanningID)
  833. {
  834. if (alt && button == 1)
  835. {
  836. HandleWheelEvent(deltaPosition, m_MouseZoomInitialPosition, evt.shiftKey);
  837. }
  838. else
  839. {
  840. var delta = new Vector3(-deltaPosition.x, deltaPosition.y, 0f) / LocalToScreenRatio();
  841. m_PreviewUtility.camera.transform.Translate(delta);
  842. ClampZoomAndPan();
  843. }
  844. evt.StopPropagation();
  845. }
  846. // Brush Pick
  847. if (isHotControl && m_MarqueeStart.HasValue && m_MarqueeType == MarqueeType.Pick && IsPickingEvent(evt))
  848. {
  849. var rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition);
  850. OnBrushPickDragged(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1)));
  851. evt.StopPropagation();
  852. GUI.changed = true;
  853. }
  854. if (!inEditMode || !unlocked)
  855. return;
  856. // Brush Painting
  857. if (IsPaintingEvent(evt) || IsErasingEvent(evt))
  858. {
  859. if (isHotControl && executing && mouseGridPositionChanged)
  860. {
  861. var points = GridEditorUtility.GetPointsOnLine(m_PreviousMouseGridPosition, mouseGridPosition);
  862. if (!evt.shiftKey && !TilemapEditorTool.IsActive(typeof(PaintTool)) && m_TypeBeforeExecution == typeof(PaintTool))
  863. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  864. else if (evt.shiftKey && TilemapEditorTool.IsActive(typeof(PaintTool)))
  865. TilemapEditorTool.SetActiveEditorTool(typeof(EraseTool));
  866. foreach (var point in points)
  867. {
  868. var position = new Vector3Int(point.x, point.y, zPosition);
  869. if (IsErasingEvent(evt))
  870. Erase(position);
  871. else
  872. Paint(position);
  873. }
  874. ResetPreviousMousePositionToCurrentPosition();
  875. evt.StopPropagation();
  876. GUI.changed = true;
  877. }
  878. }
  879. // Brush Move
  880. if (isButton0 && TilemapEditorTool.IsActive(typeof(MoveTool)) && isHotControl)
  881. {
  882. if (m_MouseGridPositionChanged && m_PreviousMove.HasValue)
  883. {
  884. executing = true;
  885. var previousRect = GridSelection.position;
  886. var previousBounds = new BoundsInt(new Vector3Int(previousRect.xMin, previousRect.yMin, GridSelection.position.zMin), new Vector3Int(previousRect.size.x, previousRect.size.y, 1));
  887. var direction = mouseGridPosition - m_PreviousMove.Value;
  888. var pos = GridSelection.position;
  889. pos.position = new Vector3Int(pos.x + direction.x, pos.y + direction.y, pos.z);
  890. GridSelection.position = pos;
  891. Move(previousBounds, pos);
  892. m_PreviousMove = mouseGridPosition;
  893. evt.StopPropagation();
  894. }
  895. }
  896. }
  897. public void HandlePointerUpEvent(PointerUpEvent evt)
  898. {
  899. // Mouse Panning
  900. if (GUIUtility.hotControl == m_MousePanningID)
  901. {
  902. ClampZoomAndPan();
  903. GUIUtility.hotControl = 0;
  904. evt.StopPropagation();
  905. }
  906. // Brush Pick
  907. if (isHotControl && m_MarqueeStart.HasValue && m_MarqueeType == MarqueeType.Pick && IsPickingEvent(evt))
  908. {
  909. // Check if event only occurred in the PaintableGrid window as evt.type will filter for this
  910. if (IsMouseUpInWindow() && m_MarqueeType == MarqueeType.Pick)
  911. {
  912. var rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition);
  913. var pivot = GetMarqueePivot(m_MarqueeStart.Value, mouseGridPosition);
  914. PickBrush(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1)), new Vector3Int(pivot.x, pivot.y, 0));
  915. if (inEditMode && ToolManager.activeToolType != m_TypeBeforeExecution)
  916. {
  917. if (PickingIsDefaultTool()
  918. && (m_TypeBeforeExecution == typeof(EraseTool)
  919. || m_TypeBeforeExecution == typeof(MoveTool)))
  920. {
  921. // If Picking is default, change to a Paint Tool to facilitate editing if previous tool does not allow for painting
  922. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  923. }
  924. else
  925. {
  926. TilemapEditorTool.SetActiveEditorTool(m_TypeBeforeExecution);
  927. }
  928. }
  929. GridPaintingState.ActiveGridBrushAssetChanged();
  930. evt.StopPropagation();
  931. GUI.changed = true;
  932. }
  933. else
  934. // Event occurred outside of PaintableGrid window, cancel the pick event
  935. {
  936. OnBrushPickCancelled();
  937. }
  938. m_MarqueeType = MarqueeType.None;
  939. m_MarqueeStart = null;
  940. GUIUtility.hotControl = 0;
  941. InspectorWindow.RepaintAllInspectors();
  942. }
  943. if (!inEditMode)
  944. return;
  945. // Brush Select
  946. if (IsSelectingEvent(evt) && m_MarqueeStart.HasValue && isHotControl)
  947. {
  948. // Check if event only occurred in the PaintableGrid window as evt.type will filter for this
  949. if (IsMouseUpInWindow() && m_MarqueeType == MarqueeType.Select)
  950. {
  951. var rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition);
  952. Select(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1)));
  953. evt.StopPropagation();
  954. }
  955. if (evt.ctrlKey)
  956. TilemapEditorTool.SetActiveEditorTool(typeof(MoveTool));
  957. m_MarqueeStart = null;
  958. m_MarqueeType = MarqueeType.None;
  959. InspectorWindow.RepaintAllInspectors();
  960. GUIUtility.hotControl = 0;
  961. }
  962. if (!unlocked)
  963. return;
  964. // Brush Painting
  965. if (IsPaintingEvent(evt) || IsErasingEvent(evt))
  966. {
  967. executing = false;
  968. if (isHotControl)
  969. {
  970. if (!TilemapEditorTool.IsActive(typeof(PaintTool)) && m_TypeBeforeExecution == typeof(PaintTool))
  971. {
  972. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  973. }
  974. evt.StopPropagation();
  975. GUI.changed = true;
  976. GUIUtility.hotControl = 0;
  977. }
  978. }
  979. // Brush Move
  980. if (IsMouseUpInWindow() && IsMoveEvent(evt) && m_PreviousMove.HasValue && isHotControl)
  981. {
  982. m_PreviousMove = null;
  983. MoveEnd(GridSelection.position);
  984. executing = false;
  985. evt.StopPropagation();
  986. GUIUtility.hotControl = 0;
  987. }
  988. // Brush FloodFill
  989. if (TilemapEditorTool.IsActive(typeof(FillTool)) && GridPaintingState.gridBrush != null && ValidateFloodFillPosition(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, 0)))
  990. {
  991. if (IsMouseUpInWindow() && evt.button == 0 && isHotControl)
  992. {
  993. RegisterUndo();
  994. FloodFill(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition));
  995. executing = false;
  996. GUI.changed = true;
  997. evt.StopPropagation();
  998. GUIUtility.hotControl = 0;
  999. }
  1000. }
  1001. // Brush Box
  1002. if (IsMouseUpInWindow() && evt.button == 0 && TilemapEditorTool.IsActive(typeof(BoxTool)))
  1003. {
  1004. if (isHotControl && m_MarqueeStart.HasValue)
  1005. {
  1006. RegisterUndo();
  1007. var rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition);
  1008. if (evt.shiftKey)
  1009. BoxErase(new BoundsInt(rect.x, rect.y, zPosition, rect.size.x, rect.size.y, 1));
  1010. else
  1011. BoxFill(new BoundsInt(rect.x, rect.y, zPosition, rect.size.x, rect.size.y, 1));
  1012. executing = false;
  1013. GUI.changed = true;
  1014. evt.StopPropagation();
  1015. GUIUtility.hotControl = 0;
  1016. }
  1017. m_MarqueeStart = null;
  1018. m_MarqueeType = MarqueeType.None;
  1019. }
  1020. // Brush Custom Tool
  1021. if (TilemapEditorTool.IsCustomTilemapEditorToolActive())
  1022. {
  1023. var activeTool = EditorToolManager.activeTool as TilemapEditorTool;
  1024. var executed = CustomTool(isHotControl, activeTool, new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition));
  1025. if (executed != executing)
  1026. {
  1027. GUIUtility.hotControl = executed ? m_PermanentControlID : 0;
  1028. executing = executed;
  1029. GUI.changed = true;
  1030. evt.StopPropagation();
  1031. }
  1032. else if (executing)
  1033. {
  1034. GUI.changed = true;
  1035. evt.StopPropagation();
  1036. }
  1037. }
  1038. }
  1039. public void HandlePointerEnterEvent(PointerEnterEvent evt)
  1040. {
  1041. if (m_PreviousMousePosition.HasValue && !guiRect.Contains(m_PreviousMousePosition.Value) || !m_PreviousMousePosition.HasValue)
  1042. {
  1043. if (GridPaintingState.activeGrid != this)
  1044. {
  1045. GridPaintingState.AddActiveGrid(this);
  1046. }
  1047. if (GridPaintingState.activeBrushEditor != null)
  1048. {
  1049. GridPaintingState.activeBrushEditor.OnMouseEnter();
  1050. }
  1051. }
  1052. }
  1053. public void HandlePointerLeaveEvent(PointerLeaveEvent evt)
  1054. {
  1055. // Mouse Pick
  1056. if (isHotControl
  1057. && m_MarqueeStart.HasValue && m_MarqueeType == MarqueeType.Pick
  1058. && IsPickingEvent(evt))
  1059. {
  1060. // Event occurred outside of PaintableGrid window, cancel the pick event
  1061. OnBrushPickCancelled();
  1062. InspectorWindow.RepaintAllInspectors();
  1063. }
  1064. // Mouse Leave
  1065. var gridActive = GridPaintingState.activeGrid == this;
  1066. GridPaintingState.RemoveActiveGrid(this);
  1067. if (gridActive)
  1068. {
  1069. if (GridPaintingState.activeBrushEditor != null)
  1070. {
  1071. GridPaintingState.activeBrushEditor.OnMouseLeave();
  1072. Repaint();
  1073. }
  1074. FlushHoverData();
  1075. }
  1076. }
  1077. public void HandleKeyDownEvent(KeyDownEvent evt)
  1078. {
  1079. var keyCode = evt.keyCode;
  1080. var shift = evt.shiftKey;
  1081. if ((GUIUtility.hotControl == 0 || GUIUtility.hotControl == m_KeyboardPanningID))
  1082. {
  1083. // Keyboard Panning
  1084. if (!shift)
  1085. {
  1086. switch (keyCode)
  1087. {
  1088. case KeyCode.LeftArrow:
  1089. m_KeyboardPanning.x = -k_KeyboardPanningSpeed / LocalToScreenRatio();
  1090. GUIUtility.hotControl = m_KeyboardPanningID;
  1091. break;
  1092. case KeyCode.RightArrow:
  1093. m_KeyboardPanning.x = k_KeyboardPanningSpeed / LocalToScreenRatio();
  1094. GUIUtility.hotControl = m_KeyboardPanningID;
  1095. break;
  1096. case KeyCode.UpArrow:
  1097. m_KeyboardPanning.y = k_KeyboardPanningSpeed / LocalToScreenRatio();
  1098. GUIUtility.hotControl = m_KeyboardPanningID;
  1099. break;
  1100. case KeyCode.DownArrow:
  1101. m_KeyboardPanning.y = -k_KeyboardPanningSpeed / LocalToScreenRatio();
  1102. GUIUtility.hotControl = m_KeyboardPanningID;
  1103. break;
  1104. }
  1105. if (GUIUtility.hotControl == m_KeyboardPanningID)
  1106. {
  1107. m_PreviewUtility.camera.transform.Translate(m_KeyboardPanning);
  1108. ClampZoomAndPan();
  1109. Repaint();
  1110. evt.StopPropagation();
  1111. }
  1112. }
  1113. // Brush Pick selection
  1114. if (shift && GridPaintingState.hasActivePick)
  1115. {
  1116. var delta = Vector3Int.zero;
  1117. switch (keyCode)
  1118. {
  1119. case KeyCode.LeftArrow:
  1120. delta = Vector3Int.left;
  1121. break;
  1122. case KeyCode.RightArrow:
  1123. delta = Vector3Int.right;
  1124. break;
  1125. case KeyCode.UpArrow:
  1126. delta = Vector3Int.up;
  1127. break;
  1128. case KeyCode.DownArrow:
  1129. delta = Vector3Int.down;
  1130. break;
  1131. }
  1132. if (delta != Vector3Int.zero)
  1133. {
  1134. m_DisableOnBrushPicked = true;
  1135. PickBrush(new BoundsInt(GridPaintingState.activePick.position + delta, GridPaintingState.activePick.size),
  1136. GridPaintingState.activePivot);
  1137. GridPaintingState.ActiveGridBrushAssetChanged();
  1138. m_DisableOnBrushPicked = false;
  1139. evt.StopPropagation();
  1140. }
  1141. }
  1142. }
  1143. // Drag Escape
  1144. if (m_HoverData != null && (keyCode == KeyCode.Escape))
  1145. {
  1146. DragAndDrop.visualMode = DragAndDropVisualMode.None;
  1147. FlushHoverData();
  1148. }
  1149. // Grid Selection
  1150. if (keyCode == KeyCode.Escape
  1151. && !m_MarqueeStart.HasValue
  1152. && !m_PreviousMove.HasValue)
  1153. {
  1154. ClearGridSelection();
  1155. evt.StopPropagation();
  1156. }
  1157. }
  1158. public void HandleKeyUpEvent()
  1159. {
  1160. if (GUIUtility.hotControl == m_KeyboardPanningID)
  1161. {
  1162. m_KeyboardPanning = Vector3.zero;
  1163. GUIUtility.hotControl = 0;
  1164. }
  1165. }
  1166. public void HandleWheelEvent(Vector3 delta, Vector2 currentMousePosition, bool shift)
  1167. {
  1168. var zoomDelta = HandleUtility.niceMouseDeltaZoom * (shift ? -9 : -3) * k_ZoomSpeed;
  1169. var camera = m_PreviewUtility.camera;
  1170. var oldLocalPos = ScreenToLocal(currentMousePosition);
  1171. camera.orthographicSize = Mathf.Max(.0001f, camera.orthographicSize * (1 + zoomDelta * .001f));
  1172. ClampZoomAndPan();
  1173. var newLocalPos = ScreenToLocal(currentMousePosition);
  1174. var localDelta = newLocalPos - oldLocalPos;
  1175. camera.transform.position -= (Vector3) localDelta;
  1176. ClampZoomAndPan();
  1177. EditorGUIUtility.AddCursorRect(guiRect, MouseCursor.Zoom);
  1178. }
  1179. public void HandleDragEnterEvent(DragEnterEvent evt)
  1180. {
  1181. if (m_HoverData == null)
  1182. {
  1183. var sheets = TileDragAndDrop.GetValidSpritesheets(DragAndDrop.objectReferences);
  1184. var sprites = TileDragAndDrop.GetValidSingleSprites(DragAndDrop.objectReferences);
  1185. var tiles = TileDragAndDrop.GetValidTiles(DragAndDrop.objectReferences);
  1186. var gos = TileDragAndDrop.GetValidGameObjects(DragAndDrop.objectReferences);
  1187. var noPalette = tilemap == null || palette == null;
  1188. if (!noPalette)
  1189. {
  1190. TileDragAndDrop.FilterForValidGameObjectsForPrefab(palette, gos);
  1191. }
  1192. var targetLayout = !noPalette ? tilemap.cellLayout : GridPaletteUtility.GetCellLayoutFromGridPaletteType(m_FirstUserPaletteType);
  1193. m_HoverData = TileDragAndDrop.CreateHoverData(sheets, sprites, tiles, gos, targetLayout);
  1194. if (m_HoverData is { Count: > 0 })
  1195. {
  1196. if (noPalette)
  1197. CreateTemporaryPreviewInstance();
  1198. }
  1199. }
  1200. if (m_HoverData != null)
  1201. {
  1202. ClampZoomAndPan();
  1203. DragAndDrop.visualMode = m_HoverData.Count > 0 ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Rejected;
  1204. evt.StopPropagation();
  1205. GUI.changed = true;
  1206. }
  1207. }
  1208. public void HandleDragUpdatedEvent(DragUpdatedEvent evt)
  1209. {
  1210. if (grid == null)
  1211. return;
  1212. UpdateMouseGridPositionUIToolkit(evt.localMousePosition, true);
  1213. }
  1214. public void HandleDragPerformEvent(DragPerformEvent evt)
  1215. {
  1216. var performed = DoDragPerform();
  1217. if (performed)
  1218. evt.StopPropagation();
  1219. }
  1220. public void HandleDragLeaveEvent(DragLeaveEvent evt)
  1221. {
  1222. if (m_HoverData != null)
  1223. {
  1224. DragAndDrop.visualMode = DragAndDropVisualMode.None;
  1225. FlushHoverData();
  1226. evt.StopPropagation();
  1227. }
  1228. }
  1229. public void HandleDragExitedEvent(DragExitedEvent evt)
  1230. {
  1231. if (m_HoverData != null)
  1232. {
  1233. DragAndDrop.visualMode = DragAndDropVisualMode.None;
  1234. FlushHoverData();
  1235. evt.StopPropagation();
  1236. }
  1237. }
  1238. private static bool MousePanningEvent(int button, bool alt)
  1239. {
  1240. return (button == 0 && alt || button > 0);
  1241. }
  1242. private void ClampZoomAndPan()
  1243. {
  1244. if (grid == null)
  1245. return;
  1246. var pixelsPerCell = grid.cellSize.y * LocalToScreenRatio();
  1247. if (pixelsPerCell < k_MinZoom)
  1248. m_PreviewUtility.camera.orthographicSize = (grid.cellSize.y * guiRect.height) / (k_MinZoom * 2f);
  1249. else if (pixelsPerCell > k_MaxZoom)
  1250. m_PreviewUtility.camera.orthographicSize = (grid.cellSize.y * guiRect.height) / (k_MaxZoom * 2f);
  1251. var cam = m_PreviewUtility.camera;
  1252. var cameraOrthographicSize = cam.orthographicSize;
  1253. var r = paddedBounds;
  1254. var camPos = cam.transform.position;
  1255. var camLimit = Grid.Swizzle(m_CameraSwizzleView, new Vector3(cameraOrthographicSize * (guiRect.width / guiRect.height), cameraOrthographicSize));
  1256. var camMin = camPos - camLimit;
  1257. var camMax = camPos + camLimit;
  1258. var rMin = Grid.Swizzle(m_CameraSwizzleView, r.min);
  1259. var rMax = Grid.Swizzle(m_CameraSwizzleView, r.max);
  1260. if (m_CameraSwizzleView != GridLayout.CellSwizzle.ZXY && m_CameraSwizzleView != GridLayout.CellSwizzle.ZYX)
  1261. {
  1262. if (camMin.x < rMin.x)
  1263. {
  1264. camPos += new Vector3(rMin.x - camMin.x, 0f, 0f);
  1265. }
  1266. if (camMax.x > rMax.x)
  1267. {
  1268. camPos += new Vector3(rMax.x - camMax.x, 0f, 0f);
  1269. }
  1270. }
  1271. if (m_CameraSwizzleView != GridLayout.CellSwizzle.XZY && m_CameraSwizzleView != GridLayout.CellSwizzle.YZX)
  1272. {
  1273. if (camMin.y < rMin.y)
  1274. {
  1275. camPos += new Vector3(0f, rMin.y - camMin.y, 0f);
  1276. }
  1277. if (camMax.y > rMax.y)
  1278. {
  1279. camPos += new Vector3(0f, rMax.y - camMax.y, 0f);
  1280. }
  1281. }
  1282. if (m_CameraSwizzleView != GridLayout.CellSwizzle.XYZ && m_CameraSwizzleView != GridLayout.CellSwizzle.YXZ)
  1283. {
  1284. if (camMin.z < rMin.z)
  1285. {
  1286. camPos += new Vector3(0f, 0f, rMin.z - camMin.z);
  1287. }
  1288. if (camMax.z > rMax.z)
  1289. {
  1290. camPos += new Vector3(0f, 0f, rMax.z - camMax.z);
  1291. }
  1292. }
  1293. cam.transform.position = camPos;
  1294. DestroyImmediate(m_GridMesh);
  1295. m_GridMesh = null;
  1296. }
  1297. public Texture RenderTexture()
  1298. {
  1299. if (guiRect.width <= 0f || guiRect.height <= 0f)
  1300. return null;
  1301. if (m_DelayedResetPaletteInstance)
  1302. {
  1303. m_DelayedResetPaletteInstance = false;
  1304. ResetPreviewInstance();
  1305. }
  1306. if (paletteInstance == null)
  1307. return null;
  1308. if (m_GridMesh != null && GetGridHash() != m_LastGridHash)
  1309. {
  1310. ResetPreviewGridMesh();
  1311. }
  1312. using (new PreviewInstanceScope(guiRect, m_PreviewUtility, paletteInstance, GridPaintingState.drawGizmos))
  1313. {
  1314. m_PreviewUtility.Render(true);
  1315. if (GridPaintingState.drawGridGizmo)
  1316. {
  1317. RenderGrid();
  1318. }
  1319. CallOnPaintSceneGUI(mouseGridPosition);
  1320. if (GridPaintingState.drawGizmos)
  1321. {
  1322. // Set CameraType to SceneView to force Gizmos to be drawn
  1323. var storedType = m_PreviewUtility.camera.cameraType;
  1324. m_PreviewUtility.camera.cameraType = CameraType.SceneView;
  1325. Handles.Internal_DoDrawGizmos(m_PreviewUtility.camera);
  1326. m_PreviewUtility.camera.cameraType = storedType;
  1327. }
  1328. }
  1329. RenderDragAndDropPreview();
  1330. RenderSelectedBrushMarquee();
  1331. CallOnSceneGUI();
  1332. var texture = m_PreviewUtility.EndPreview();
  1333. m_LastGridHash = GetGridHash();
  1334. return texture;
  1335. }
  1336. private int GetGridHash()
  1337. {
  1338. var gridToHash = prefabGrid;
  1339. if (gridToHash == null)
  1340. return 0;
  1341. int hash = gridToHash.GetHashCode();
  1342. unchecked
  1343. {
  1344. hash = hash * 33 + gridToHash.cellGap.GetHashCode();
  1345. hash = hash * 33 + gridToHash.cellLayout.GetHashCode();
  1346. hash = hash * 33 + gridToHash.cellSize.GetHashCode();
  1347. hash = hash * 33 + gridToHash.cellSwizzle.GetHashCode();
  1348. hash = hash * 33 + SceneViewGridManager.sceneViewGridComponentGizmo.Color.GetHashCode();
  1349. }
  1350. return hash;
  1351. }
  1352. private void RenderDragAndDropPreview()
  1353. {
  1354. if (!activeDragAndDrop || m_HoverData == null || m_HoverData.Count == 0)
  1355. return;
  1356. var rect = TileDragAndDrop.GetMinMaxRect(m_HoverData.Keys);
  1357. rect.position += mouseGridPosition;
  1358. DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
  1359. GridEditorUtility.DrawGridMarquee(grid, new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.width, rect.height, 1)), Color.white);
  1360. }
  1361. private void RenderGrid()
  1362. {
  1363. // MeshTopology.Lines doesn't give nice pixel perfect grid so we have to have separate codepath with MeshTopology.Quads specially for palette window here
  1364. if (m_GridMesh == null && grid.cellLayout == GridLayout.CellLayout.Rectangle)
  1365. {
  1366. m_GridMesh = GridEditorUtility.GenerateCachedGridMesh(grid, k_GridColor, 1f / LocalToScreenRatio(), paddedBoundsInt, grid.cellSwizzle == GridLayout.CellSwizzle.XYZ ? MeshTopology.Quads : MeshTopology.Lines);
  1367. }
  1368. GridEditorUtility.DrawGridGizmo(grid, grid.transform, k_GridColor, ref m_GridMesh, ref m_GridMaterial);
  1369. }
  1370. private bool IsPickingEvent<T>(T evt) where T : PointerEventBase<T>, new()
  1371. {
  1372. return ((evt.ctrlKey && !TilemapEditorTool.IsActive(typeof(MoveTool)))
  1373. || TilemapEditorTool.IsActive(typeof(PickingTool))
  1374. || !TilemapEditorTool.IsActive(typeof(SelectTool)) && PickingIsDefaultTool())
  1375. && evt.button == 0 && !evt.altKey;
  1376. }
  1377. private bool IsPaintingEvent<T>(T evt) where T : PointerEventBase<T>, new()
  1378. {
  1379. return (evt.button == 0 && !evt.ctrlKey && !evt.altKey && TilemapEditorTool.IsActive(typeof(PaintTool)));
  1380. }
  1381. private bool IsErasingEvent<T>(T evt) where T : PointerEventBase<T>, new()
  1382. {
  1383. return (evt.button == 0 && !evt.ctrlKey && !evt.altKey
  1384. && ((evt.shiftKey && !TilemapEditorTool.IsActive(typeof(BoxTool))
  1385. && !TilemapEditorTool.IsActive(typeof(FillTool))
  1386. && !TilemapEditorTool.IsActive(typeof(SelectTool))
  1387. && !TilemapEditorTool.IsActive(typeof(MoveTool)))
  1388. || TilemapEditorTool.IsActive(typeof(EraseTool))));
  1389. }
  1390. private bool IsMoveEvent<T>(T evt) where T : PointerEventBase<T>, new()
  1391. {
  1392. return (evt.button == 0
  1393. && !evt.altKey
  1394. && TilemapEditorTool.IsActive(typeof(MoveTool)));
  1395. }
  1396. private bool IsSelectingEvent<T>(T evt) where T : PointerEventBase<T>, new()
  1397. {
  1398. return (evt.button == 0
  1399. && !evt.altKey
  1400. && (TilemapEditorTool.IsActive(typeof(SelectTool)) ||
  1401. (TilemapEditorTool.IsActive(typeof(MoveTool)) && evt.ctrlKey)));
  1402. }
  1403. private class PreviewInstanceScope : IDisposable
  1404. {
  1405. private readonly bool m_OldFog;
  1406. private readonly bool m_DrawGizmos;
  1407. private readonly Transform[] m_PaletteTransforms;
  1408. public PreviewInstanceScope(Rect guiRect, PreviewRenderUtility previewRenderUtility, GameObject paletteInstance, bool drawGizmos)
  1409. {
  1410. m_DrawGizmos = drawGizmos;
  1411. m_OldFog = RenderSettings.fog;
  1412. previewRenderUtility.BeginPreview(guiRect, null);
  1413. // Draw Background here with user preference color
  1414. Graphics.DrawTexture(new Rect(0.0f, 0.0f
  1415. , (float) 2 * EditorGUIUtility.pixelsPerPoint * guiRect.width
  1416. , (float) 2 * EditorGUIUtility.pixelsPerPoint * guiRect.height)
  1417. , Texture2D.grayTexture, new Rect(0.0f, 0.0f, 1f, 1f)
  1418. , 0, 0, 0, 0
  1419. , tilePaletteBackgroundColor.Color, null);
  1420. Unsupported.SetRenderSettingsUseFogNoDirty(false);
  1421. if (m_DrawGizmos)
  1422. {
  1423. m_PaletteTransforms = paletteInstance.GetComponentsInChildren<Transform>();
  1424. foreach (var transform in m_PaletteTransforms)
  1425. transform.gameObject.hideFlags = HideFlags.None;
  1426. // Case 1199516: Set Dirty on palette instance to force a refresh on gizmo drawing
  1427. EditorUtility.SetDirty(paletteInstance);
  1428. Unsupported.SceneTrackerFlushDirty();
  1429. }
  1430. var renderers = paletteInstance.GetComponentsInChildren<Renderer>();
  1431. foreach (var renderer in renderers)
  1432. {
  1433. renderer.allowOcclusionWhenDynamic = false;
  1434. }
  1435. previewRenderUtility.AddManagedGO(paletteInstance);
  1436. Handles.DrawCameraImpl(guiRect, previewRenderUtility.camera, DrawCameraMode.Textured, false, new DrawGridParameters(), true, false);
  1437. }
  1438. public void Dispose()
  1439. {
  1440. if (m_DrawGizmos && m_PaletteTransforms != null)
  1441. {
  1442. foreach (var transform in m_PaletteTransforms)
  1443. transform.gameObject.hideFlags = HideFlags.HideAndDontSave;
  1444. }
  1445. Unsupported.SetRenderSettingsUseFogNoDirty(m_OldFog);
  1446. }
  1447. }
  1448. private bool DoDragPerform()
  1449. {
  1450. if (m_HoverData == null)
  1451. return false;
  1452. if (m_HoverData.Count == 0)
  1453. {
  1454. FlushHoverData();
  1455. GUI.changed = true;
  1456. return false;
  1457. }
  1458. var paletteDirectory = string.Empty;
  1459. if (palette == null)
  1460. {
  1461. DestroyPreviewInstance();
  1462. var cellLayout = GridPaletteUtility.GetCellLayoutFromGridPaletteType(m_FirstUserPaletteType);
  1463. var cellSizing = GridPalette.CellSizing.Automatic;
  1464. var cellSize = new Vector3(1f, 1f, 0f);
  1465. var cellSwizzle = GridLayout.CellSwizzle.XYZ;
  1466. var sortMode = TransparencySortMode.Default;
  1467. var sortAxis = new Vector3(0f, 0f, 1f);
  1468. switch (m_FirstUserPaletteType)
  1469. {
  1470. case GridPaletteUtility.GridPaletteType.HexagonalFlatTop:
  1471. {
  1472. cellSwizzle = GridLayout.CellSwizzle.YXZ;
  1473. break;
  1474. }
  1475. case GridPaletteUtility.GridPaletteType.Isometric:
  1476. {
  1477. cellSizing = GridPalette.CellSizing.Manual;
  1478. cellSize = new Vector3(1, 0.5f, 1);
  1479. break;
  1480. }
  1481. case GridPaletteUtility.GridPaletteType.IsometricZAsY:
  1482. {
  1483. cellSizing = GridPalette.CellSizing.Manual;
  1484. cellSize = new Vector3(1, 0.5f, 1);
  1485. sortMode = TransparencySortMode.CustomAxis;
  1486. sortAxis = new Vector3(0f, 1f, -0.25f);
  1487. break;
  1488. }
  1489. }
  1490. var go = GridPaletteUtility.CreateNewPaletteAtCurrentFolder("New Tile Palette"
  1491. , cellLayout
  1492. , cellSizing
  1493. , cellSize
  1494. , cellSwizzle, sortMode, sortAxis);
  1495. var temporaryHoverData = m_HoverData;
  1496. m_HoverData = null;
  1497. if (go != null)
  1498. {
  1499. GridPaintingState.palette = go;
  1500. var assetPath = AssetDatabase.GetAssetPath(go);
  1501. if (!String.IsNullOrEmpty(assetPath))
  1502. {
  1503. paletteDirectory = FileUtil.UnityGetDirectoryName(assetPath);
  1504. }
  1505. Selection.activeObject = go;
  1506. }
  1507. ResetPreviewInstance();
  1508. m_HoverData = temporaryHoverData;
  1509. }
  1510. // No palette was created
  1511. var paletteTilemap = tilemap;
  1512. if (paletteTilemap == null)
  1513. return false;
  1514. RegisterUndo();
  1515. var wasEmpty = TilemapIsEmpty(paletteTilemap);
  1516. var targetPosition = mouseGridPosition;
  1517. var tilemapPosition = new Vector2Int(-Int32.MaxValue, -Int32.MaxValue);
  1518. DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
  1519. var tileSheet = TileDragAndDrop.ConvertToTileSheet(m_HoverData, paletteDirectory);
  1520. var i = 0;
  1521. foreach (var item in m_HoverData)
  1522. {
  1523. var offset = Vector3.zero;
  1524. if (item.Value.hasOffset)
  1525. {
  1526. offset = item.Value.positionOffset - paletteTilemap.tileAnchor;
  1527. var cellSize = paletteTilemap.cellSize;
  1528. if (wasEmpty)
  1529. {
  1530. cellSize = item.Value.scaleFactor;
  1531. }
  1532. offset.x *= cellSize.x;
  1533. offset.y *= cellSize.y;
  1534. offset.z *= cellSize.z;
  1535. }
  1536. var placePosition = targetPosition + item.Key;
  1537. // Placing Tiles
  1538. if (i < tileSheet.Count)
  1539. {
  1540. if (tilemapPosition.y < placePosition.y ||
  1541. (tilemapPosition.y == placePosition.y && tilemapPosition.x > placePosition.x))
  1542. tilemapPosition = placePosition;
  1543. SetTile(paletteTilemap
  1544. , targetPosition + item.Key
  1545. , tileSheet[i++]
  1546. , Color.white
  1547. , Matrix4x4.TRS(offset, Quaternion.identity, Vector3.one));
  1548. }
  1549. else
  1550. // Placing GameObjects
  1551. {
  1552. if (item.Value.hoverObject is not GameObject go)
  1553. continue;
  1554. GameObject instance;
  1555. if (PrefabUtility.IsPartOfPrefabAsset(go))
  1556. {
  1557. instance = (GameObject) PrefabUtility.InstantiatePrefab(go, paletteTilemap.transform);
  1558. }
  1559. else
  1560. {
  1561. instance = Instantiate(go, paletteTilemap.transform);
  1562. instance.name = go.name;
  1563. instance.SetActive(true);
  1564. foreach (var renderer in instance.GetComponentsInChildren<Renderer>())
  1565. {
  1566. renderer.enabled = true;
  1567. }
  1568. }
  1569. var tileAnchor = paletteTilemap.tileAnchor;
  1570. var cellSize = paletteTilemap.cellSize;
  1571. var cellStride = cellSize + paletteTilemap.cellGap;
  1572. cellStride.x = Mathf.Approximately(0f, cellStride.x) ? 1f : cellStride.x;
  1573. cellStride.y = Mathf.Approximately(0f, cellStride.y) ? 1f : cellStride.y;
  1574. cellStride.z = Mathf.Approximately(0f, cellStride.z) ? 1f : cellStride.z;
  1575. var anchorRatio = new Vector3(
  1576. tileAnchor.x * cellSize.x / cellStride.x,
  1577. tileAnchor.y * cellSize.y / cellStride.y,
  1578. tileAnchor.z * cellSize.z / cellStride.z
  1579. );
  1580. instance.transform.position = grid.LocalToWorld(grid.CellToLocalInterpolated(((Vector3Int) placePosition) + anchorRatio));
  1581. Undo.RegisterCreatedObjectUndo(instance, "Drag and drop GameObject");
  1582. }
  1583. }
  1584. if (wasEmpty && paletteTilemap.GetUsedTilesCount() != 0 &&
  1585. GridPaintingState.gridBrush != null)
  1586. {
  1587. var pickBounds = new BoundsInt(new Vector3Int(tilemapPosition.x, tilemapPosition.y, 0), Vector3Int.one);
  1588. PickBrush(pickBounds, GridPaintingState.activePivot);
  1589. }
  1590. OnPaletteChanged();
  1591. m_PaletteNeedsSave = true;
  1592. FlushHoverData();
  1593. GUI.changed = true;
  1594. SavePaletteIfNecessary();
  1595. if (wasEmpty)
  1596. {
  1597. ResetPreviewInstance();
  1598. FrameEntirePalette();
  1599. }
  1600. GUIUtility.ExitGUI();
  1601. return true;
  1602. }
  1603. internal void SetTile(Tilemap tilemapTarget, Vector2Int position, TileBase tile, Color color, Matrix4x4 matrix)
  1604. {
  1605. Vector3Int pos3 = new Vector3Int(position.x, position.y, zPosition);
  1606. tilemapTarget.SetTile(pos3, tile);
  1607. tilemapTarget.SetColor(pos3, color);
  1608. tilemapTarget.SetTransformMatrix(pos3, tilemapTarget.GetTransformMatrix(pos3) * matrix);
  1609. }
  1610. protected override void Paint(Vector3Int position)
  1611. {
  1612. if (gridBrush == null)
  1613. return;
  1614. gridBrush.Paint(grid, brushTarget, position);
  1615. OnPaletteChanged();
  1616. }
  1617. protected override void Erase(Vector3Int position)
  1618. {
  1619. if (gridBrush == null)
  1620. return;
  1621. gridBrush.Erase(grid, brushTarget, position);
  1622. OnPaletteChanged();
  1623. }
  1624. protected override void BoxFill(BoundsInt position)
  1625. {
  1626. if (gridBrush == null)
  1627. return;
  1628. gridBrush.BoxFill(grid, brushTarget, position);
  1629. OnPaletteChanged();
  1630. }
  1631. protected override void BoxErase(BoundsInt position)
  1632. {
  1633. if (gridBrush == null)
  1634. return;
  1635. gridBrush.BoxErase(grid, brushTarget, position);
  1636. OnPaletteChanged();
  1637. }
  1638. protected override void FloodFill(Vector3Int position)
  1639. {
  1640. if (gridBrush == null)
  1641. return;
  1642. gridBrush.FloodFill(grid, brushTarget, position);
  1643. OnPaletteChanged();
  1644. }
  1645. protected override void PickBrush(BoundsInt position, Vector3Int pickingStart)
  1646. {
  1647. if (grid == null || gridBrush == null)
  1648. return;
  1649. gridBrush.Pick(grid, brushTarget, position, pickingStart);
  1650. if (!InGridEditMode())
  1651. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  1652. GridPaintingState.hasActivePick = true;
  1653. GridPaintingState.activePick = position;
  1654. GridPaintingState.activePivot = pickingStart;
  1655. GridPaintingState.activePickPalette = GridPaintingState.palette;
  1656. if (!m_DisableOnBrushPicked)
  1657. onBrushPicked?.Invoke();
  1658. }
  1659. protected override void Select(BoundsInt position)
  1660. {
  1661. if (grid)
  1662. {
  1663. GridSelection.Select(brushTarget, position);
  1664. gridBrush.Select(grid, brushTarget, position);
  1665. }
  1666. }
  1667. protected override void Move(BoundsInt from, BoundsInt to)
  1668. {
  1669. if (grid)
  1670. gridBrush.Move(grid, brushTarget, from, to);
  1671. }
  1672. protected override void MoveStart(BoundsInt position)
  1673. {
  1674. if (grid)
  1675. gridBrush.MoveStart(grid, brushTarget, position);
  1676. }
  1677. protected override void MoveEnd(BoundsInt position)
  1678. {
  1679. if (grid)
  1680. {
  1681. gridBrush.MoveEnd(grid, brushTarget, position);
  1682. OnPaletteChanged();
  1683. }
  1684. }
  1685. protected override bool CustomTool(bool isToolHotControl, TilemapEditorTool tool, Vector3Int position)
  1686. {
  1687. var executed = false;
  1688. if (grid)
  1689. {
  1690. executed = tool.HandleTool(isToolHotControl, grid, brushTarget, position);
  1691. if (executed)
  1692. OnPaletteChanged();
  1693. }
  1694. return executed;
  1695. }
  1696. protected bool IsMouseUpInWindow()
  1697. {
  1698. return guiRect.Contains(mousePosition);
  1699. }
  1700. public override void Repaint()
  1701. {
  1702. if (m_VisualElement != null)
  1703. m_VisualElement.MarkDirtyRepaint();
  1704. }
  1705. protected override void ClearGridSelection()
  1706. {
  1707. GridSelection.Clear();
  1708. }
  1709. public override bool isActive => grid != null;
  1710. public override Rect rectPosition => m_VisualElement.worldBound;
  1711. public override VisualElement windowRoot => m_VisualElement?.GetRoot();
  1712. protected override void OnBrushPickStarted()
  1713. {
  1714. }
  1715. protected override void OnBrushPickDragged(BoundsInt position)
  1716. {
  1717. GridPaintingState.hasActivePick = true;
  1718. GridPaintingState.activePick = position;
  1719. GridPaintingState.activePickPalette = GridPaintingState.palette;
  1720. }
  1721. protected override void OnBrushPickCancelled()
  1722. {
  1723. GridPaintingState.hasActivePick = false;
  1724. GridPaintingState.activePick = new BoundsInt(Vector3Int.zero, Vector3Int.zero);
  1725. GridPaintingState.activePivot = Vector3Int.zero;
  1726. GridPaintingState.activePickPalette = null;
  1727. }
  1728. private void PingTileAsset(RectInt rect)
  1729. {
  1730. // Only able to ping asset if only one asset is selected
  1731. if (rect.size == Vector2Int.zero && tilemap != null)
  1732. {
  1733. TileBase tile = tilemap.GetTile(new Vector3Int(rect.xMin, rect.yMin, zPosition));
  1734. EditorGUIUtility.PingObject(tile);
  1735. Selection.activeObject = tile;
  1736. }
  1737. }
  1738. protected override bool ValidateFloodFillPosition(Vector3Int position)
  1739. {
  1740. return true;
  1741. }
  1742. protected override bool PickingIsDefaultTool()
  1743. {
  1744. return !m_Unlocked;
  1745. }
  1746. protected override bool CanPickOutsideEditMode()
  1747. {
  1748. return true;
  1749. }
  1750. protected override GridLayout.CellLayout CellLayout()
  1751. {
  1752. if (grid != null)
  1753. return grid.cellLayout;
  1754. return GridLayout.CellLayout.Rectangle;
  1755. }
  1756. protected override Vector2Int ScreenToGrid(Vector2 screenPosition, float zPosition)
  1757. {
  1758. Vector3 local = ScreenToLocal(screenPosition);
  1759. if (GridPaintingState.gridBrushMousePositionAtZ)
  1760. local.z = zPosition;
  1761. var localS = Grid.Swizzle(m_CameraSwizzleView, local);
  1762. var result3 = grid.LocalToCell(localS);
  1763. var result = new Vector2Int(result3.x, result3.y);
  1764. return result;
  1765. }
  1766. private void RenderSelectedBrushMarquee()
  1767. {
  1768. if (!activeDragAndDrop && !unlocked && GridPaintingState.hasActivePick)
  1769. {
  1770. DrawSelectionGizmo(GridPaintingState.activePick);
  1771. }
  1772. }
  1773. private void DrawSelectionGizmo(BoundsInt selectionBounds)
  1774. {
  1775. if (!GUI.enabled)
  1776. return;
  1777. var color = Color.white;
  1778. if (isPicking)
  1779. color = Color.cyan;
  1780. GridEditorUtility.DrawGridMarquee(grid, new BoundsInt(new Vector3Int(selectionBounds.xMin, selectionBounds.yMin, 0), new Vector3Int(selectionBounds.size.x, selectionBounds.size.y, 1)), color);
  1781. }
  1782. private void CallOnSceneGUI()
  1783. {
  1784. var gridLayout = tilemap != null ? tilemap : grid as GridLayout;
  1785. var hasSelection = GridSelection.active && GridSelection.target == brushTarget;
  1786. if (hasSelection)
  1787. {
  1788. var rect = new RectInt(GridSelection.position.xMin, GridSelection.position.yMin, GridSelection.position.size.x, GridSelection.position.size.y);
  1789. var brushBounds = new BoundsInt(new Vector3Int(rect.x, rect.y, zPosition), new Vector3Int(rect.width, rect.height, 1));
  1790. GridBrushEditorBase.OnSceneGUIInternal(gridLayout, brushTarget, brushBounds, EditTypeToBrushTool(ToolManager.activeToolType), m_MarqueeStart.HasValue || executing);
  1791. }
  1792. if (GridPaintingState.activeBrushEditor != null)
  1793. {
  1794. GridPaintingState.activeBrushEditor.OnSceneGUI(gridLayout, brushTarget);
  1795. if (hasSelection)
  1796. {
  1797. GridPaintingState.activeBrushEditor.OnSelectionSceneGUI(gridLayout, brushTarget);
  1798. if (GridSelectionTool.IsActive() && unlocked)
  1799. {
  1800. var tool = EditorToolManager.activeTool as GridSelectionTool;
  1801. tool.OnToolGUI();
  1802. }
  1803. }
  1804. }
  1805. }
  1806. private void CallOnPaintSceneGUI(Vector2Int position)
  1807. {
  1808. if (!activeDragAndDrop && !unlocked && !TilemapEditorTool.IsActive(typeof(SelectTool)) && !TilemapEditorTool.IsActive(typeof(PickingTool)))
  1809. return;
  1810. var hasSelection = GridSelection.active && GridSelection.target == brushTarget;
  1811. if (!hasSelection && GridPaintingState.activeGrid != this)
  1812. return;
  1813. var brush = GridPaintingState.gridBrush;
  1814. if (brush == null)
  1815. return;
  1816. var rect = new RectInt(position, new Vector2Int(1, 1));
  1817. if (m_MarqueeStart.HasValue)
  1818. rect = GridEditorUtility.GetMarqueeRect(position, m_MarqueeStart.Value);
  1819. else if (hasSelection)
  1820. rect = new RectInt(GridSelection.position.xMin, GridSelection.position.yMin, GridSelection.position.size.x, GridSelection.position.size.y);
  1821. var gridLayout = tilemap != null ? tilemap.layoutGrid : grid as GridLayout;
  1822. var brushBounds = new BoundsInt(new Vector3Int(rect.x, rect.y, zPosition), new Vector3Int(rect.width, rect.height, 1));
  1823. if (GridPaintingState.activeBrushEditor != null)
  1824. GridPaintingState.activeBrushEditor.OnPaintSceneGUI(gridLayout, brushTarget, brushBounds,
  1825. EditTypeToBrushTool(ToolManager.activeToolType),
  1826. m_MarqueeStart.HasValue || executing);
  1827. else // Fallback when user hasn't defined custom editor
  1828. GridBrushEditorBase.OnPaintSceneGUIInternal(gridLayout, Selection.activeGameObject, brushBounds,
  1829. EditTypeToBrushTool(ToolManager.activeToolType),
  1830. m_MarqueeStart.HasValue || executing);
  1831. }
  1832. protected override void RegisterUndo()
  1833. {
  1834. if (palette != null && paletteInstance != null)
  1835. Undo.RegisterFullObjectHierarchyUndo(paletteInstance, "Edit Palette");
  1836. }
  1837. private void OnPaletteChanged()
  1838. {
  1839. m_PaletteUsed = true;
  1840. m_PaletteNeedsSave = true;
  1841. Undo.FlushUndoRecordObjects();
  1842. }
  1843. public void CheckRevertIfChanged(string[] paths)
  1844. {
  1845. if (paths != null && m_PaletteNeedsSave && palette != null)
  1846. {
  1847. var currentPalettePath = AssetDatabase.GetAssetPath(palette);
  1848. foreach (var path in paths)
  1849. {
  1850. if (currentPalettePath == path)
  1851. {
  1852. m_PaletteNeedsSave = false;
  1853. ResetPreviewInstance();
  1854. Debug.LogWarningFormat(palette, paletteSavedOutsideClipboard, palette.name);
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. }
  1860. public bool SavePaletteIfNecessary()
  1861. {
  1862. bool needsSave = m_PaletteNeedsSave;
  1863. if (needsSave)
  1864. {
  1865. SavePalette();
  1866. m_PaletteNeedsSave = false;
  1867. }
  1868. return needsSave;
  1869. }
  1870. private void SavePalette()
  1871. {
  1872. if (palette != null && paletteInstance != null)
  1873. {
  1874. TilePaletteSaveUtility.SaveTilePalette(palette, paletteInstance);
  1875. ResetPreviewInstance();
  1876. Repaint();
  1877. }
  1878. }
  1879. public Vector2 GridToScreen(Vector2 gridPosition)
  1880. {
  1881. var gridPosition3 = new Vector3(gridPosition.x, gridPosition.y, 0);
  1882. return LocalToScreen(grid.CellToLocalInterpolated(gridPosition3));
  1883. }
  1884. public Vector2 ScreenToLocal(Vector2 screenPosition)
  1885. {
  1886. var viewPosition = m_PreviewUtility.camera.transform.position;
  1887. Vector2 viewXYPosition = Grid.InverseSwizzle(m_CameraSwizzleView, viewPosition);
  1888. screenPosition -= new Vector2(guiRect.xMin, guiRect.yMin);
  1889. var offsetFromCenter = new Vector2(screenPosition.x - guiRect.width * .5f, guiRect.height * .5f - screenPosition.y);
  1890. return viewXYPosition + offsetFromCenter / LocalToScreenRatio();
  1891. }
  1892. protected Vector2 LocalToScreen(Vector2 localPosition)
  1893. {
  1894. var viewPosition = m_PreviewUtility.camera.transform.position;
  1895. Vector2 viewXYPosition = Grid.InverseSwizzle(m_CameraSwizzleView, viewPosition);
  1896. var offsetFromCenter = new Vector2(localPosition.x - viewXYPosition.x, viewXYPosition.y - localPosition.y);
  1897. return offsetFromCenter * LocalToScreenRatio() + new Vector2(guiRect.width * .5f + guiRect.xMin, guiRect.height * .5f + guiRect.yMin);
  1898. }
  1899. private float LocalToScreenRatio()
  1900. {
  1901. return guiRect.height / (m_PreviewUtility.camera.orthographicSize * 2f);
  1902. }
  1903. private float LocalToScreenRatio(float viewHeight)
  1904. {
  1905. return viewHeight / (m_PreviewUtility.camera.orthographicSize * 2f);
  1906. }
  1907. private static bool TilemapIsEmpty(Tilemap tilemap)
  1908. {
  1909. return tilemap.GetUsedTilesCount() == 0;
  1910. }
  1911. public void UnlockAndEdit()
  1912. {
  1913. unlocked = true;
  1914. m_PaletteNeedsSave = true;
  1915. }
  1916. internal void PickFirstFromPalette()
  1917. {
  1918. if (tilemap == null)
  1919. return;
  1920. var pickBounds = tilemap.cellBounds;
  1921. pickBounds.size = Vector3Int.one;
  1922. PickBrush(pickBounds, Vector3Int.zero);
  1923. if (!TilemapEditorTool.IsActive(typeof(PaintTool)))
  1924. TilemapEditorTool.SetActiveEditorTool(typeof(PaintTool));
  1925. }
  1926. // TODO: Better way of clearing caches than AssetPostprocessor
  1927. public class AssetProcessor : AssetPostprocessor
  1928. {
  1929. public override int GetPostprocessOrder()
  1930. {
  1931. return int.MaxValue;
  1932. }
  1933. private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
  1934. {
  1935. foreach (var clipboard in instances)
  1936. {
  1937. clipboard.DelayedResetPreviewInstance();
  1938. }
  1939. }
  1940. }
  1941. public class PaletteAssetModificationProcessor : AssetModificationProcessor
  1942. {
  1943. static void OnWillCreateAsset(string assetName)
  1944. {
  1945. SavePalettesIfRequired(null);
  1946. }
  1947. static string[] OnWillSaveAssets(string[] paths)
  1948. {
  1949. SavePalettesIfRequired(paths);
  1950. return paths;
  1951. }
  1952. static void SavePalettesIfRequired(string[] paths)
  1953. {
  1954. if (GridPaintingState.savingPalette)
  1955. return;
  1956. foreach (var clipboard in instances)
  1957. {
  1958. if (clipboard.isModified)
  1959. {
  1960. clipboard.CheckRevertIfChanged(paths);
  1961. clipboard.SavePaletteIfNecessary();
  1962. clipboard.Repaint();
  1963. }
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }