GridBrushEditor.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEngine.Tilemaps;
  5. using UnityEditor.SceneManagement;
  6. using UnityEngine.Scripting.APIUpdating;
  7. using Object = UnityEngine.Object;
  8. namespace UnityEditor.Tilemaps
  9. {
  10. /// <summary>Editor for GridBrush.</summary>
  11. [MovedFrom(true, "UnityEditor", "UnityEditor")]
  12. [CustomEditor(typeof(GridBrush))]
  13. public class GridBrushEditor : GridBrushEditorBase
  14. {
  15. private static class Styles
  16. {
  17. public static readonly GUIContent tileLabel = EditorGUIUtility.TrTextContent("Tile", "Tile set in tilemap");
  18. public static readonly GUIContent spriteLabel = EditorGUIUtility.TrTextContent("Sprite", "Sprite set when tile is set in tilemap");
  19. public static readonly GUIContent colorLabel = EditorGUIUtility.TrTextContent("Color", "Color set when tile is set in tilemap");
  20. public static readonly GUIContent colliderTypeLabel = EditorGUIUtility.TrTextContent("Collider Type", "Collider shape used for tile");
  21. public static readonly GUIContent lockColorLabel = EditorGUIUtility.TrTextContent("Lock Color", "Prevents tilemap from changing color of tile");
  22. public static readonly GUIContent lockTransformLabel = EditorGUIUtility.TrTextContent("Lock Transform", "Prevents tilemap from changing transform of tile");
  23. public static readonly GUIContent gridSelectionPropertiesLabel = EditorGUIUtility.TrTextContent("Grid Selection Properties");
  24. public static readonly GUIContent modifyTilemapLabel = EditorGUIUtility.TrTextContent("Modify Tilemap");
  25. public static readonly GUIContent modifyLabel = EditorGUIUtility.TrTextContent("Modify");
  26. public static readonly GUIContent deleteSelectionLabel = EditorGUIUtility.TrTextContent("Delete Selection");
  27. public static readonly GUIContent noTool =
  28. EditorGUIUtility.TrTextContentWithIcon("None", "No Gizmo in the Scene view", "RectTool");
  29. public static readonly GUIContent moveTool =
  30. EditorGUIUtility.TrTextContentWithIcon("Move", "Shows a Gizmo in the Scene view for changing the offset for the Grid Selection", "MoveTool");
  31. public static readonly GUIContent rotateTool =
  32. EditorGUIUtility.TrTextContentWithIcon("Rotate", "Shows a Gizmo in the Scene view for changing the rotation for the Grid Selection", "RotateTool");
  33. public static readonly GUIContent scaleTool =
  34. EditorGUIUtility.TrTextContentWithIcon("Scale", "Shows a Gizmo in the Scene view for changing the scale for the Grid Selection", "ScaleTool");
  35. public static readonly GUIContent transformTool =
  36. EditorGUIUtility.TrTextContentWithIcon("Transform", "Shows a Gizmo in the Scene view for changing the transform for the Grid Selection", "TransformTool");
  37. public static readonly GUIContent[] selectionTools = new[]
  38. {
  39. noTool
  40. , moveTool
  41. , rotateTool
  42. , scaleTool
  43. , transformTool
  44. };
  45. }
  46. public enum ModifyCells
  47. {
  48. InsertRow,
  49. InsertColumn,
  50. InsertRowBefore,
  51. InsertColumnBefore,
  52. DeleteRow,
  53. DeleteColumn,
  54. DeleteRowBefore,
  55. DeleteColumnBefore,
  56. }
  57. private class GridBrushProperties
  58. {
  59. public static readonly GUIContent floodFillPreviewLabel = EditorGUIUtility.TrTextContent("Show Flood Fill Preview", "Whether a preview is shown while painting a Tilemap when Flood Fill mode is enabled");
  60. public static readonly string floodFillPreviewEditorPref = "GridBrush.EnableFloodFillPreview";
  61. }
  62. /// <summary>The GridBrush that is the target for this editor.</summary>
  63. public GridBrush brush { get { return target as GridBrush; } }
  64. private int m_LastPreviewRefreshHash;
  65. // These are used to clean out previews that happened on previous update
  66. private GridLayout m_LastGrid;
  67. private GameObject m_LastBrushTarget;
  68. private BoundsInt? m_LastBounds;
  69. private GridBrushBase.Tool? m_LastTool;
  70. // These are used to handle selection in Selection Inspector
  71. private TileBase[] m_SelectionTiles;
  72. private Color[] m_SelectionColors;
  73. private Matrix4x4[] m_SelectionMatrices;
  74. private TileFlags[] m_SelectionFlagsArray;
  75. private Sprite[] m_SelectionSprites;
  76. private Tile.ColliderType[] m_SelectionColliderTypes;
  77. private int selectionCellCount => GridSelection.position.size.x * GridSelection.position.size.y * GridSelection.position.size.z;
  78. // These are used to handle transform manipulation on the Tilemap
  79. private int m_SelectedTransformTool = 0;
  80. // These are used to handle insert/delete cells on the Tilemap
  81. private int m_CellCount = 1;
  82. private ModifyCells m_ModifyCells = ModifyCells.InsertRow;
  83. protected virtual void OnEnable()
  84. {
  85. Undo.undoRedoPerformed += ClearLastPreview;
  86. }
  87. protected virtual void OnDisable()
  88. {
  89. Undo.undoRedoPerformed -= ClearLastPreview;
  90. ClearLastPreview();
  91. }
  92. private void ClearLastPreview()
  93. {
  94. ClearPreview();
  95. m_LastPreviewRefreshHash = 0;
  96. }
  97. /// <summary>Callback for painting the GUI for the GridBrush in the Scene View.</summary>
  98. /// <param name="gridLayout">Grid that the brush is being used on.</param>
  99. /// <param name="brushTarget">Target of the GridBrushBase::ref::Tool operation. By default the currently selected GameObject.</param>
  100. /// <param name="position">Current selected location of the brush.</param>
  101. /// <param name="tool">Current GridBrushBase::ref::Tool selected.</param>
  102. /// <param name="executing">Whether brush is being used.</param>
  103. public override void OnPaintSceneGUI(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, bool executing)
  104. {
  105. BoundsInt gizmoRect = position;
  106. bool refreshPreviews = false;
  107. if (Event.current.type == EventType.Layout)
  108. {
  109. int newPreviewRefreshHash = GetHash(gridLayout, brushTarget, position, tool, brush);
  110. refreshPreviews = newPreviewRefreshHash != m_LastPreviewRefreshHash;
  111. if (refreshPreviews)
  112. m_LastPreviewRefreshHash = newPreviewRefreshHash;
  113. }
  114. if (tool == GridBrushBase.Tool.Move)
  115. {
  116. if (refreshPreviews && executing)
  117. {
  118. ClearPreview();
  119. PaintPreview(gridLayout, brushTarget, position.min);
  120. }
  121. }
  122. else if (tool == GridBrushBase.Tool.Paint || tool == GridBrushBase.Tool.Erase)
  123. {
  124. if (refreshPreviews)
  125. {
  126. ClearPreview();
  127. if (tool != GridBrushBase.Tool.Erase)
  128. {
  129. PaintPreview(gridLayout, brushTarget, position.min);
  130. }
  131. }
  132. gizmoRect = new BoundsInt(position.min - brush.pivot, brush.size);
  133. }
  134. else if (tool == GridBrushBase.Tool.Box)
  135. {
  136. if (refreshPreviews)
  137. {
  138. ClearPreview();
  139. BoxFillPreview(gridLayout, brushTarget, position);
  140. }
  141. }
  142. else if (tool == GridBrushBase.Tool.FloodFill)
  143. {
  144. if (refreshPreviews)
  145. {
  146. if (CheckFloodFillPreview(gridLayout, brushTarget, position.min))
  147. ClearPreview();
  148. FloodFillPreview(gridLayout, brushTarget, position.min);
  149. }
  150. }
  151. base.OnPaintSceneGUI(gridLayout, brushTarget, gizmoRect, tool, executing);
  152. }
  153. private void UpdateSelection(Tilemap tilemap)
  154. {
  155. var selection = GridSelection.position;
  156. var cellCount = selectionCellCount;
  157. if (m_SelectionTiles == null || m_SelectionTiles.Length != selectionCellCount)
  158. {
  159. m_SelectionTiles = new TileBase[cellCount];
  160. m_SelectionColors = new Color[cellCount];
  161. m_SelectionMatrices = new Matrix4x4[cellCount];
  162. m_SelectionFlagsArray = new TileFlags[cellCount];
  163. m_SelectionSprites = new Sprite[cellCount];
  164. m_SelectionColliderTypes = new Tile.ColliderType[cellCount];
  165. }
  166. int index = 0;
  167. foreach (var p in selection.allPositionsWithin)
  168. {
  169. m_SelectionTiles[index] = tilemap.GetTile(p);
  170. m_SelectionColors[index] = tilemap.GetColor(p);
  171. m_SelectionMatrices[index] = tilemap.GetTransformMatrix(p);
  172. m_SelectionFlagsArray[index] = tilemap.GetTileFlags(p);
  173. m_SelectionSprites[index] = tilemap.GetSprite(p);
  174. m_SelectionColliderTypes[index] = tilemap.GetColliderType(p);
  175. index++;
  176. }
  177. }
  178. /// <summary>Callback for drawing the Inspector GUI when there is an active GridSelection made in a Tilemap.</summary>
  179. public override void OnSelectionInspectorGUI()
  180. {
  181. BoundsInt selection = GridSelection.position;
  182. Tilemap tilemap = GridSelection.target.GetComponent<Tilemap>();
  183. int cellCount = selection.size.x * selection.size.y * selection.size.z;
  184. if (tilemap != null && cellCount > 0)
  185. {
  186. base.OnSelectionInspectorGUI();
  187. if (!EditorGUIUtility.editingTextField
  188. && Event.current.type == EventType.KeyDown
  189. && (Event.current.keyCode == KeyCode.Delete
  190. || Event.current.keyCode == KeyCode.Backspace))
  191. {
  192. DeleteSelection(tilemap, selection);
  193. Event.current.Use();
  194. }
  195. GUILayout.Space(10f);
  196. EditorGUILayout.LabelField(Styles.gridSelectionPropertiesLabel, EditorStyles.boldLabel);
  197. UpdateSelection(tilemap);
  198. EditorGUI.BeginChangeCheck();
  199. EditorGUI.showMixedValue = m_SelectionTiles.Any(tile => tile != m_SelectionTiles.First());
  200. var position = new Vector3Int(selection.xMin, selection.yMin, selection.zMin);
  201. TileBase newTile = EditorGUILayout.ObjectField(Styles.tileLabel, tilemap.GetTile(position), typeof(TileBase), false) as TileBase;
  202. if (EditorGUI.EndChangeCheck())
  203. {
  204. Undo.RecordObject(tilemap, "Edit Tilemap");
  205. foreach (var p in selection.allPositionsWithin)
  206. tilemap.SetTile(p, newTile);
  207. }
  208. using (new EditorGUI.DisabledScope(true))
  209. {
  210. EditorGUI.showMixedValue = m_SelectionSprites.Any(sprite => sprite != m_SelectionSprites.First());
  211. EditorGUILayout.ObjectField(Styles.spriteLabel, m_SelectionSprites[0], typeof(Sprite), false, GUILayout.Height(EditorGUI.kSingleLineHeight));
  212. }
  213. bool colorFlagsAllEqual = m_SelectionFlagsArray.All(flags => (flags & TileFlags.LockColor) == (m_SelectionFlagsArray.First() & TileFlags.LockColor));
  214. using (new EditorGUI.DisabledScope(!colorFlagsAllEqual || (m_SelectionFlagsArray[0] & TileFlags.LockColor) != 0))
  215. {
  216. EditorGUI.showMixedValue = m_SelectionColors.Any(color => color != m_SelectionColors.First());
  217. EditorGUI.BeginChangeCheck();
  218. Color newColor = EditorGUILayout.ColorField(Styles.colorLabel, m_SelectionColors[0]);
  219. if (EditorGUI.EndChangeCheck())
  220. {
  221. Undo.RecordObject(tilemap, "Edit Tilemap");
  222. foreach (var p in selection.allPositionsWithin)
  223. tilemap.SetColor(p, newColor);
  224. }
  225. }
  226. using (new EditorGUI.DisabledScope(true))
  227. {
  228. EditorGUI.showMixedValue = m_SelectionColliderTypes.Any(colliderType => colliderType != m_SelectionColliderTypes.First());
  229. EditorGUILayout.EnumPopup(Styles.colliderTypeLabel, m_SelectionColliderTypes[0]);
  230. }
  231. bool transformFlagsAllEqual = m_SelectionFlagsArray.All(flags => (flags & TileFlags.LockTransform) == (m_SelectionFlagsArray.First() & TileFlags.LockTransform));
  232. using (new EditorGUI.DisabledScope(!transformFlagsAllEqual || (m_SelectionFlagsArray[0] & TileFlags.LockTransform) != 0))
  233. {
  234. EditorGUI.showMixedValue = m_SelectionMatrices.Any(matrix => matrix != m_SelectionMatrices.First());
  235. EditorGUI.BeginChangeCheck();
  236. Matrix4x4 newTransformMatrix = TileEditor.TransformMatrixOnGUI(m_SelectionMatrices[0]);
  237. if (EditorGUI.EndChangeCheck())
  238. {
  239. Undo.RecordObject(tilemap, "Edit Tilemap");
  240. foreach (var p in selection.allPositionsWithin)
  241. tilemap.SetTransformMatrix(p, newTransformMatrix);
  242. }
  243. }
  244. using (new EditorGUI.DisabledScope(true))
  245. {
  246. EditorGUI.showMixedValue = !colorFlagsAllEqual;
  247. EditorGUILayout.Toggle(Styles.lockColorLabel, (m_SelectionFlagsArray[0] & TileFlags.LockColor) != 0);
  248. EditorGUI.showMixedValue = !transformFlagsAllEqual;
  249. EditorGUILayout.Toggle(Styles.lockTransformLabel, (m_SelectionFlagsArray[0] & TileFlags.LockTransform) != 0);
  250. }
  251. EditorGUI.showMixedValue = false;
  252. if (GUILayout.Button(Styles.deleteSelectionLabel))
  253. {
  254. DeleteSelection(tilemap, selection);
  255. }
  256. EditorGUILayout.Space();
  257. EditorGUILayout.LabelField(Styles.modifyTilemapLabel, EditorStyles.boldLabel);
  258. EditorGUILayout.Space();
  259. EditorGUI.BeginChangeCheck();
  260. m_SelectedTransformTool = GUILayout.Toolbar(m_SelectedTransformTool, Styles.selectionTools);
  261. if (EditorGUI.EndChangeCheck())
  262. SceneView.RepaintAll();
  263. EditorGUILayout.Space();
  264. GUILayout.BeginHorizontal();
  265. m_ModifyCells = (ModifyCells)EditorGUILayout.EnumPopup(m_ModifyCells);
  266. m_CellCount = EditorGUILayout.IntField(m_CellCount);
  267. if (GUILayout.Button(Styles.modifyLabel))
  268. {
  269. RegisterUndoForTilemap(tilemap, Enum.GetName(typeof(ModifyCells), m_ModifyCells));
  270. switch (m_ModifyCells)
  271. {
  272. case ModifyCells.InsertRow:
  273. {
  274. tilemap.InsertCells(GridSelection.position.position, 0, m_CellCount, 0);
  275. break;
  276. }
  277. case ModifyCells.InsertRowBefore:
  278. {
  279. tilemap.InsertCells(GridSelection.position.position, 0, -m_CellCount, 0);
  280. break;
  281. }
  282. case ModifyCells.InsertColumn:
  283. {
  284. tilemap.InsertCells(GridSelection.position.position, m_CellCount, 0, 0);
  285. break;
  286. }
  287. case ModifyCells.InsertColumnBefore:
  288. {
  289. tilemap.InsertCells(GridSelection.position.position, -m_CellCount, 0, 0);
  290. break;
  291. }
  292. case ModifyCells.DeleteRow:
  293. {
  294. tilemap.DeleteCells(GridSelection.position.position, 0, m_CellCount, 0);
  295. break;
  296. }
  297. case ModifyCells.DeleteRowBefore:
  298. {
  299. tilemap.DeleteCells(GridSelection.position.position, 0, -m_CellCount, 0);
  300. break;
  301. }
  302. case ModifyCells.DeleteColumn:
  303. {
  304. tilemap.DeleteCells(GridSelection.position.position, m_CellCount, 0, 0);
  305. break;
  306. }
  307. case ModifyCells.DeleteColumnBefore:
  308. {
  309. tilemap.DeleteCells(GridSelection.position.position, -m_CellCount, 0, 0);
  310. break;
  311. }
  312. }
  313. }
  314. GUILayout.EndHorizontal();
  315. }
  316. }
  317. /// <summary>Callback for painting custom gizmos when there is an active GridSelection made in a GridLayout.</summary>
  318. /// <param name="gridLayout">Grid that the brush is being used on.</param>
  319. /// <param name="brushTarget">Target of the GridBrushBase::ref::Tool operation. By default the currently selected GameObject.</param>
  320. /// <remarks>Override this to show custom gizmos for the current selection.</remarks>
  321. public override void OnSelectionSceneGUI(GridLayout gridLayout, GameObject brushTarget)
  322. {
  323. var tilemap = brushTarget.GetComponent<Tilemap>();
  324. if (tilemap == null)
  325. return;
  326. UpdateSelection(tilemap);
  327. bool transformFlagsAllEqual = m_SelectionFlagsArray.All(flags => (flags & TileFlags.LockTransform) == (m_SelectionFlagsArray.First() & TileFlags.LockTransform));
  328. if (!transformFlagsAllEqual || (m_SelectionFlagsArray[0] & TileFlags.LockTransform) != 0)
  329. return;
  330. var transformMatrix = m_SelectionMatrices[0];
  331. var p = (Vector3)transformMatrix.GetColumn(3);
  332. var r = transformMatrix.rotation;
  333. var s = transformMatrix.lossyScale;
  334. Vector3 selectionPosition = GridSelection.position.position;
  335. if (selectionCellCount > 1)
  336. {
  337. selectionPosition.x = GridSelection.position.center.x;
  338. selectionPosition.y = GridSelection.position.center.y;
  339. }
  340. selectionPosition += tilemap.tileAnchor;
  341. var gizmoPosition = tilemap.LocalToWorld(tilemap.CellToLocalInterpolated(selectionPosition + p));
  342. EditorGUI.BeginChangeCheck();
  343. switch (m_SelectedTransformTool)
  344. {
  345. case 0:
  346. break;
  347. case 1:
  348. {
  349. gizmoPosition = Handles.PositionHandle(gizmoPosition, r);
  350. }
  351. break;
  352. case 2:
  353. {
  354. r = Handles.RotationHandle(r, gizmoPosition);
  355. }
  356. break;
  357. case 3:
  358. {
  359. s = Handles.ScaleHandle(s, gizmoPosition, r, HandleUtility.GetHandleSize(gizmoPosition));
  360. }
  361. break;
  362. case 4:
  363. {
  364. Handles.TransformHandle(ref gizmoPosition, ref r, ref s);
  365. }
  366. break;
  367. default:
  368. break;
  369. }
  370. if (EditorGUI.EndChangeCheck())
  371. {
  372. RegisterUndo(brushTarget, GridBrushBase.Tool.Select);
  373. var offset = tilemap.WorldToLocal(tilemap.LocalToCellInterpolated(gizmoPosition)) - selectionPosition;
  374. foreach (var position in GridSelection.position.allPositionsWithin)
  375. {
  376. if (tilemap.HasTile(position))
  377. tilemap.SetTransformMatrix(position, Matrix4x4.TRS(offset, r, s));
  378. }
  379. InspectorWindow.RefreshInspectors();
  380. }
  381. }
  382. private void DeleteSelection(Tilemap tilemap, BoundsInt selection)
  383. {
  384. if (tilemap == null)
  385. return;
  386. RegisterUndo(tilemap.gameObject, GridBrushBase.Tool.Erase);
  387. brush.BoxErase(tilemap.layoutGrid, tilemap.gameObject, selection);
  388. }
  389. /// <summary> Callback when the mouse cursor leaves and editing area. </summary>
  390. /// <remarks> Cleans up brush previews. </remarks>
  391. public override void OnMouseLeave()
  392. {
  393. ClearPreview();
  394. }
  395. /// <summary> Callback when the GridBrush Tool is deactivated. </summary>
  396. /// <param name="tool">GridBrush Tool that is deactivated.</param>
  397. /// <remarks> Cleans up brush previews. </remarks>
  398. public override void OnToolDeactivated(GridBrushBase.Tool tool)
  399. {
  400. ClearPreview();
  401. }
  402. /// <summary> Whether the GridBrush can change Z Position. </summary>
  403. public override bool canChangeZPosition
  404. {
  405. get { return brush.canChangeZPosition; }
  406. set { brush.canChangeZPosition = value; }
  407. }
  408. /// <summary>Callback for registering an Undo action before the GridBrushBase does the current GridBrushBase::ref::Tool action.</summary>
  409. /// <param name="brushTarget">Target of the GridBrushBase::ref::Tool operation. By default the currently selected GameObject.</param>
  410. /// <param name="tool">Current GridBrushBase::ref::Tool selected.</param>
  411. /// <remarks>Implement this for any special Undo behaviours when a brush is used.</remarks>
  412. public override void RegisterUndo(GameObject brushTarget, GridBrushBase.Tool tool)
  413. {
  414. if (brushTarget != null)
  415. {
  416. var tilemap = brushTarget.GetComponent<Tilemap>();
  417. if (tilemap != null)
  418. {
  419. RegisterUndoForTilemap(tilemap, tool.ToString());
  420. }
  421. }
  422. }
  423. /// <summary>Returns all valid targets that the brush can edit.</summary>
  424. /// <remarks>Valid targets for the GridBrush are any GameObjects with a Tilemap component.</remarks>
  425. public override GameObject[] validTargets
  426. {
  427. get
  428. {
  429. StageHandle currentStageHandle = StageUtility.GetCurrentStageHandle();
  430. return currentStageHandle.FindComponentsOfType<Tilemap>().Where(x => x.gameObject.scene.isLoaded
  431. && x.gameObject.activeInHierarchy).Select(x => x.gameObject).ToArray();
  432. }
  433. }
  434. /// <summary>Paints preview data into a cell of a grid given the coordinates of the cell.</summary>
  435. /// <param name="gridLayout">Grid to paint data to.</param>
  436. /// <param name="brushTarget">Target of the paint operation. By default the currently selected GameObject.</param>
  437. /// <param name="position">The coordinates of the cell to paint data to.</param>
  438. /// <remarks>The grid brush will paint preview sprites in its brush cells onto an associated Tilemap. This will not instantiate objects associated with the painted tiles.</remarks>
  439. public virtual void PaintPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  440. {
  441. Vector3Int min = position - brush.pivot;
  442. Vector3Int max = min + brush.size;
  443. BoundsInt bounds = new BoundsInt(min, max - min);
  444. if (brushTarget != null)
  445. {
  446. Tilemap map = brushTarget.GetComponent<Tilemap>();
  447. foreach (Vector3Int location in bounds.allPositionsWithin)
  448. {
  449. Vector3Int brushPosition = location - min;
  450. GridBrush.BrushCell cell = brush.cells[brush.GetCellIndex(brushPosition)];
  451. if (cell.tile != null && map != null)
  452. {
  453. SetTilemapPreviewCell(map, location, cell.tile, cell.matrix, cell.color);
  454. }
  455. }
  456. }
  457. m_LastGrid = gridLayout;
  458. m_LastBounds = bounds;
  459. m_LastBrushTarget = brushTarget;
  460. m_LastTool = GridBrushBase.Tool.Paint;
  461. }
  462. /// <summary>Does a preview of what happens when a GridBrush.BoxFill is done with the same parameters.</summary>
  463. /// <param name="gridLayout">Grid to box fill data to.</param>
  464. /// <param name="brushTarget">Target of box fill operation. By default the currently selected GameObject.</param>
  465. /// <param name="position">The bounds to box fill data to.</param>
  466. public virtual void BoxFillPreview(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
  467. {
  468. if (brushTarget != null)
  469. {
  470. Tilemap map = brushTarget.GetComponent<Tilemap>();
  471. if (map != null)
  472. {
  473. foreach (Vector3Int location in position.allPositionsWithin)
  474. {
  475. Vector3Int local = location - position.min;
  476. GridBrush.BrushCell cell = brush.cells[brush.GetCellIndexWrapAround(local.x, local.y, local.z)];
  477. if (cell.tile != null)
  478. {
  479. SetTilemapPreviewCell(map, location, cell.tile, cell.matrix, cell.color);
  480. }
  481. }
  482. }
  483. }
  484. m_LastGrid = gridLayout;
  485. m_LastBounds = position;
  486. m_LastBrushTarget = brushTarget;
  487. m_LastTool = GridBrushBase.Tool.Box;
  488. }
  489. private bool CheckFloodFillPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  490. {
  491. if (m_LastGrid == gridLayout
  492. && m_LastBrushTarget == brushTarget
  493. && m_LastBounds.HasValue && m_LastBounds.Value.Contains(position)
  494. && brushTarget != null && brush.cellCount > 0)
  495. {
  496. Tilemap map = brushTarget.GetComponent<Tilemap>();
  497. if (map != null)
  498. {
  499. GridBrush.BrushCell cell = brush.cells[0];
  500. if (cell.tile == map.GetEditorPreviewTile(position))
  501. return false;
  502. }
  503. }
  504. return true;
  505. }
  506. /// <summary>Does a preview of what happens when a GridBrush.FloodFill is done with the same parameters.</summary>
  507. /// <param name="gridLayout">Grid to paint data to.</param>
  508. /// <param name="brushTarget">Target of the flood fill operation. By default the currently selected GameObject.</param>
  509. /// <param name="position">The coordinates of the cell to flood fill data to.</param>
  510. public virtual void FloodFillPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  511. {
  512. // This can be quite taxing on a large Tilemap, so users can choose whether to do this or not
  513. if (!EditorPrefs.GetBool(GridBrushProperties.floodFillPreviewEditorPref, true))
  514. return;
  515. var bounds = new BoundsInt(position, Vector3Int.one);
  516. if (brushTarget != null && brush.cellCount > 0)
  517. {
  518. Tilemap map = brushTarget.GetComponent<Tilemap>();
  519. if (map != null)
  520. {
  521. GridBrush.BrushCell cell = brush.cells[0];
  522. map.EditorPreviewFloodFill(position, cell.tile);
  523. // Set floodfill bounds as tilemap bounds
  524. bounds.min = map.origin;
  525. bounds.max = map.origin + map.size;
  526. }
  527. }
  528. m_LastGrid = gridLayout;
  529. m_LastBounds = bounds;
  530. m_LastBrushTarget = brushTarget;
  531. m_LastTool = GridBrushBase.Tool.FloodFill;
  532. }
  533. [SettingsProvider]
  534. internal static SettingsProvider CreateSettingsProvider()
  535. {
  536. var settingsProvider = new SettingsProvider("Preferences/2D/Grid Brush", SettingsScope.User, SettingsProvider.GetSearchKeywordsFromGUIContentProperties<GridBrushProperties>()) {
  537. guiHandler = searchContext =>
  538. {
  539. PreferencesGUI();
  540. }
  541. };
  542. return settingsProvider;
  543. }
  544. private static void PreferencesGUI()
  545. {
  546. using (new SettingsWindow.GUIScope())
  547. {
  548. EditorGUI.BeginChangeCheck();
  549. var val = EditorGUILayout.Toggle(GridBrushProperties.floodFillPreviewLabel, EditorPrefs.GetBool(GridBrushProperties.floodFillPreviewEditorPref, true));
  550. if (EditorGUI.EndChangeCheck())
  551. {
  552. EditorPrefs.SetBool(GridBrushProperties.floodFillPreviewEditorPref, val);
  553. }
  554. }
  555. }
  556. /// <summary>Clears any preview drawn previously by the GridBrushEditor.</summary>
  557. public virtual void ClearPreview()
  558. {
  559. if (m_LastGrid == null || m_LastBounds == null || m_LastBrushTarget == null || m_LastTool == null)
  560. return;
  561. Tilemap map = m_LastBrushTarget.GetComponent<Tilemap>();
  562. if (map != null)
  563. {
  564. switch (m_LastTool)
  565. {
  566. case GridBrushBase.Tool.FloodFill:
  567. {
  568. map.ClearAllEditorPreviewTiles();
  569. break;
  570. }
  571. case GridBrushBase.Tool.Box:
  572. {
  573. Vector3Int min = m_LastBounds.Value.position;
  574. Vector3Int max = min + m_LastBounds.Value.size;
  575. BoundsInt bounds = new BoundsInt(min, max - min);
  576. foreach (Vector3Int location in bounds.allPositionsWithin)
  577. {
  578. ClearTilemapPreview(map, location);
  579. }
  580. break;
  581. }
  582. case GridBrushBase.Tool.Paint:
  583. {
  584. BoundsInt bounds = m_LastBounds.Value;
  585. foreach (Vector3Int location in bounds.allPositionsWithin)
  586. {
  587. ClearTilemapPreview(map, location);
  588. }
  589. break;
  590. }
  591. }
  592. }
  593. m_LastBrushTarget = null;
  594. m_LastGrid = null;
  595. m_LastBounds = null;
  596. m_LastTool = null;
  597. }
  598. private void RegisterUndoForTilemap(Tilemap tilemap, string undoMessage)
  599. {
  600. Undo.RegisterCompleteObjectUndo(new Object[] { tilemap, tilemap.gameObject }, undoMessage);
  601. }
  602. private static void SetTilemapPreviewCell(Tilemap map, Vector3Int location, TileBase tile, Matrix4x4 transformMatrix, Color color)
  603. {
  604. if (map == null)
  605. return;
  606. map.SetEditorPreviewTile(location, tile);
  607. map.SetEditorPreviewTransformMatrix(location, transformMatrix);
  608. map.SetEditorPreviewColor(location, color);
  609. }
  610. private static void ClearTilemapPreview(Tilemap map, Vector3Int location)
  611. {
  612. if (map == null)
  613. return;
  614. map.SetEditorPreviewTile(location, null);
  615. map.SetEditorPreviewTransformMatrix(location, Matrix4x4.identity);
  616. map.SetEditorPreviewColor(location, Color.white);
  617. }
  618. private static int GetHash(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, GridBrush brush)
  619. {
  620. int hash = 0;
  621. unchecked
  622. {
  623. hash = hash * 33 + (gridLayout != null ? gridLayout.GetHashCode() : 0);
  624. hash = hash * 33 + (brushTarget != null ? brushTarget.GetHashCode() : 0);
  625. hash = hash * 33 + position.GetHashCode();
  626. hash = hash * 33 + tool.GetHashCode();
  627. hash = hash * 33 + (brush != null ? brush.GetHashCode() : 0);
  628. }
  629. return hash;
  630. }
  631. }
  632. }