Нема описа
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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 => Math.Abs(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 = selectionCellCount;
  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. if (m_SelectionFlagsArray == null || m_SelectionFlagsArray.Length <= 0)
  328. return;
  329. bool transformFlagsAllEqual = m_SelectionFlagsArray.All(flags => (flags & TileFlags.LockTransform) == (m_SelectionFlagsArray.First() & TileFlags.LockTransform));
  330. if (!transformFlagsAllEqual || (m_SelectionFlagsArray[0] & TileFlags.LockTransform) != 0)
  331. return;
  332. var transformMatrix = m_SelectionMatrices[0];
  333. var p = (Vector3)transformMatrix.GetColumn(3);
  334. var r = transformMatrix.rotation;
  335. var s = transformMatrix.lossyScale;
  336. Vector3 selectionPosition = GridSelection.position.position;
  337. if (selectionCellCount > 1)
  338. {
  339. selectionPosition.x = GridSelection.position.center.x;
  340. selectionPosition.y = GridSelection.position.center.y;
  341. }
  342. selectionPosition += tilemap.tileAnchor;
  343. var gizmoPosition = tilemap.LocalToWorld(tilemap.CellToLocalInterpolated(selectionPosition + p));
  344. EditorGUI.BeginChangeCheck();
  345. switch (m_SelectedTransformTool)
  346. {
  347. case 0:
  348. break;
  349. case 1:
  350. {
  351. gizmoPosition = Handles.PositionHandle(gizmoPosition, r);
  352. }
  353. break;
  354. case 2:
  355. {
  356. r = Handles.RotationHandle(r, gizmoPosition);
  357. }
  358. break;
  359. case 3:
  360. {
  361. s = Handles.ScaleHandle(s, gizmoPosition, r, HandleUtility.GetHandleSize(gizmoPosition));
  362. }
  363. break;
  364. case 4:
  365. {
  366. Handles.TransformHandle(ref gizmoPosition, ref r, ref s);
  367. }
  368. break;
  369. default:
  370. break;
  371. }
  372. if (EditorGUI.EndChangeCheck())
  373. {
  374. RegisterUndo(brushTarget, GridBrushBase.Tool.Select);
  375. var offset = tilemap.WorldToLocal(tilemap.LocalToCellInterpolated(gizmoPosition)) - selectionPosition;
  376. foreach (var position in GridSelection.position.allPositionsWithin)
  377. {
  378. if (tilemap.HasTile(position))
  379. tilemap.SetTransformMatrix(position, Matrix4x4.TRS(offset, r, s));
  380. }
  381. InspectorWindow.RefreshInspectors();
  382. }
  383. }
  384. private void DeleteSelection(Tilemap tilemap, BoundsInt selection)
  385. {
  386. if (tilemap == null)
  387. return;
  388. RegisterUndo(tilemap.gameObject, GridBrushBase.Tool.Erase);
  389. brush.BoxErase(tilemap.layoutGrid, tilemap.gameObject, selection);
  390. }
  391. /// <summary> Callback when the mouse cursor leaves and editing area. </summary>
  392. /// <remarks> Cleans up brush previews. </remarks>
  393. public override void OnMouseLeave()
  394. {
  395. ClearPreview();
  396. }
  397. /// <summary> Callback when the GridBrush Tool is deactivated. </summary>
  398. /// <param name="tool">GridBrush Tool that is deactivated.</param>
  399. /// <remarks> Cleans up brush previews. </remarks>
  400. public override void OnToolDeactivated(GridBrushBase.Tool tool)
  401. {
  402. ClearPreview();
  403. }
  404. /// <summary> Whether the GridBrush can change Z Position. </summary>
  405. public override bool canChangeZPosition
  406. {
  407. get { return brush.canChangeZPosition; }
  408. set { brush.canChangeZPosition = value; }
  409. }
  410. /// <summary>Callback for registering an Undo action before the GridBrushBase does the current GridBrushBase::ref::Tool action.</summary>
  411. /// <param name="brushTarget">Target of the GridBrushBase::ref::Tool operation. By default the currently selected GameObject.</param>
  412. /// <param name="tool">Current GridBrushBase::ref::Tool selected.</param>
  413. /// <remarks>Implement this for any special Undo behaviours when a brush is used.</remarks>
  414. public override void RegisterUndo(GameObject brushTarget, GridBrushBase.Tool tool)
  415. {
  416. if (brushTarget != null)
  417. {
  418. var tilemap = brushTarget.GetComponent<Tilemap>();
  419. if (tilemap != null)
  420. {
  421. RegisterUndoForTilemap(tilemap, tool.ToString());
  422. }
  423. }
  424. }
  425. /// <summary>Returns all valid targets that the brush can edit.</summary>
  426. /// <remarks>Valid targets for the GridBrush are any GameObjects with a Tilemap component.</remarks>
  427. public override GameObject[] validTargets
  428. {
  429. get
  430. {
  431. StageHandle currentStageHandle = StageUtility.GetCurrentStageHandle();
  432. return currentStageHandle.FindComponentsOfType<Tilemap>().Where(x => x.gameObject.scene.isLoaded
  433. && x.gameObject.activeInHierarchy).Select(x => x.gameObject).ToArray();
  434. }
  435. }
  436. /// <summary>Paints preview data into a cell of a grid given the coordinates of the cell.</summary>
  437. /// <param name="gridLayout">Grid to paint data to.</param>
  438. /// <param name="brushTarget">Target of the paint operation. By default the currently selected GameObject.</param>
  439. /// <param name="position">The coordinates of the cell to paint data to.</param>
  440. /// <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>
  441. public virtual void PaintPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  442. {
  443. Vector3Int min = position - brush.pivot;
  444. Vector3Int max = min + brush.size;
  445. BoundsInt bounds = new BoundsInt(min, max - min);
  446. if (brushTarget != null)
  447. {
  448. Tilemap map = brushTarget.GetComponent<Tilemap>();
  449. foreach (Vector3Int location in bounds.allPositionsWithin)
  450. {
  451. Vector3Int brushPosition = location - min;
  452. GridBrush.BrushCell cell = brush.cells[brush.GetCellIndex(brushPosition)];
  453. if (cell.tile != null && map != null)
  454. {
  455. SetTilemapPreviewCell(map, location, cell.tile, cell.matrix, cell.color);
  456. }
  457. }
  458. }
  459. m_LastGrid = gridLayout;
  460. m_LastBounds = bounds;
  461. m_LastBrushTarget = brushTarget;
  462. m_LastTool = GridBrushBase.Tool.Paint;
  463. }
  464. /// <summary>Does a preview of what happens when a GridBrush.BoxFill is done with the same parameters.</summary>
  465. /// <param name="gridLayout">Grid to box fill data to.</param>
  466. /// <param name="brushTarget">Target of box fill operation. By default the currently selected GameObject.</param>
  467. /// <param name="position">The bounds to box fill data to.</param>
  468. public virtual void BoxFillPreview(GridLayout gridLayout, GameObject brushTarget, BoundsInt position)
  469. {
  470. if (brushTarget != null)
  471. {
  472. Tilemap map = brushTarget.GetComponent<Tilemap>();
  473. if (map != null)
  474. {
  475. foreach (Vector3Int location in position.allPositionsWithin)
  476. {
  477. Vector3Int local = location - position.min;
  478. GridBrush.BrushCell cell = brush.cells[brush.GetCellIndexWrapAround(local.x, local.y, local.z)];
  479. if (cell.tile != null)
  480. {
  481. SetTilemapPreviewCell(map, location, cell.tile, cell.matrix, cell.color);
  482. }
  483. }
  484. }
  485. }
  486. m_LastGrid = gridLayout;
  487. m_LastBounds = position;
  488. m_LastBrushTarget = brushTarget;
  489. m_LastTool = GridBrushBase.Tool.Box;
  490. }
  491. private bool CheckFloodFillPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  492. {
  493. if (m_LastGrid == gridLayout
  494. && m_LastBrushTarget == brushTarget
  495. && m_LastBounds.HasValue && m_LastBounds.Value.Contains(position)
  496. && brushTarget != null && brush.cellCount > 0)
  497. {
  498. Tilemap map = brushTarget.GetComponent<Tilemap>();
  499. if (map != null)
  500. {
  501. GridBrush.BrushCell cell = brush.cells[0];
  502. if (cell.tile == map.GetEditorPreviewTile(position))
  503. return false;
  504. }
  505. }
  506. return true;
  507. }
  508. /// <summary>Does a preview of what happens when a GridBrush.FloodFill is done with the same parameters.</summary>
  509. /// <param name="gridLayout">Grid to paint data to.</param>
  510. /// <param name="brushTarget">Target of the flood fill operation. By default the currently selected GameObject.</param>
  511. /// <param name="position">The coordinates of the cell to flood fill data to.</param>
  512. public virtual void FloodFillPreview(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
  513. {
  514. // This can be quite taxing on a large Tilemap, so users can choose whether to do this or not
  515. if (!EditorPrefs.GetBool(GridBrushProperties.floodFillPreviewEditorPref, true))
  516. return;
  517. var bounds = new BoundsInt(position, Vector3Int.one);
  518. if (brushTarget != null && brush.cellCount > 0)
  519. {
  520. Tilemap map = brushTarget.GetComponent<Tilemap>();
  521. if (map != null)
  522. {
  523. GridBrush.BrushCell cell = brush.cells[0];
  524. map.EditorPreviewFloodFill(position, cell.tile);
  525. // Set floodfill bounds as tilemap bounds
  526. bounds.min = map.origin;
  527. bounds.max = map.origin + map.size;
  528. }
  529. }
  530. m_LastGrid = gridLayout;
  531. m_LastBounds = bounds;
  532. m_LastBrushTarget = brushTarget;
  533. m_LastTool = GridBrushBase.Tool.FloodFill;
  534. }
  535. [SettingsProvider]
  536. internal static SettingsProvider CreateSettingsProvider()
  537. {
  538. var settingsProvider = new SettingsProvider("Preferences/2D/Grid Brush", SettingsScope.User, SettingsProvider.GetSearchKeywordsFromGUIContentProperties<GridBrushProperties>()) {
  539. guiHandler = searchContext =>
  540. {
  541. PreferencesGUI();
  542. }
  543. };
  544. return settingsProvider;
  545. }
  546. private static void PreferencesGUI()
  547. {
  548. using (new SettingsWindow.GUIScope())
  549. {
  550. EditorGUI.BeginChangeCheck();
  551. var val = EditorGUILayout.Toggle(GridBrushProperties.floodFillPreviewLabel, EditorPrefs.GetBool(GridBrushProperties.floodFillPreviewEditorPref, true));
  552. if (EditorGUI.EndChangeCheck())
  553. {
  554. EditorPrefs.SetBool(GridBrushProperties.floodFillPreviewEditorPref, val);
  555. }
  556. }
  557. }
  558. /// <summary>Clears any preview drawn previously by the GridBrushEditor.</summary>
  559. public virtual void ClearPreview()
  560. {
  561. if (m_LastGrid == null || m_LastBounds == null || m_LastBrushTarget == null || m_LastTool == null)
  562. return;
  563. Tilemap map = m_LastBrushTarget.GetComponent<Tilemap>();
  564. if (map != null)
  565. {
  566. switch (m_LastTool)
  567. {
  568. case GridBrushBase.Tool.FloodFill:
  569. {
  570. map.ClearAllEditorPreviewTiles();
  571. break;
  572. }
  573. case GridBrushBase.Tool.Box:
  574. {
  575. Vector3Int min = m_LastBounds.Value.position;
  576. Vector3Int max = min + m_LastBounds.Value.size;
  577. BoundsInt bounds = new BoundsInt(min, max - min);
  578. foreach (Vector3Int location in bounds.allPositionsWithin)
  579. {
  580. ClearTilemapPreview(map, location);
  581. }
  582. break;
  583. }
  584. case GridBrushBase.Tool.Paint:
  585. {
  586. BoundsInt bounds = m_LastBounds.Value;
  587. foreach (Vector3Int location in bounds.allPositionsWithin)
  588. {
  589. ClearTilemapPreview(map, location);
  590. }
  591. break;
  592. }
  593. }
  594. }
  595. m_LastBrushTarget = null;
  596. m_LastGrid = null;
  597. m_LastBounds = null;
  598. m_LastTool = null;
  599. }
  600. private void RegisterUndoForTilemap(Tilemap tilemap, string undoMessage)
  601. {
  602. Undo.RegisterCompleteObjectUndo(new Object[] { tilemap, tilemap.gameObject }, undoMessage);
  603. }
  604. private static void SetTilemapPreviewCell(Tilemap map, Vector3Int location, TileBase tile, Matrix4x4 transformMatrix, Color color)
  605. {
  606. if (map == null)
  607. return;
  608. map.SetEditorPreviewTile(location, tile);
  609. map.SetEditorPreviewTransformMatrix(location, transformMatrix);
  610. map.SetEditorPreviewColor(location, color);
  611. }
  612. private static void ClearTilemapPreview(Tilemap map, Vector3Int location)
  613. {
  614. if (map == null)
  615. return;
  616. map.SetEditorPreviewTile(location, null);
  617. map.SetEditorPreviewTransformMatrix(location, Matrix4x4.identity);
  618. map.SetEditorPreviewColor(location, Color.white);
  619. }
  620. private static int GetHash(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, GridBrushBase.Tool tool, GridBrush brush)
  621. {
  622. int hash = 0;
  623. unchecked
  624. {
  625. hash = hash * 33 + (gridLayout != null ? gridLayout.GetHashCode() : 0);
  626. hash = hash * 33 + (brushTarget != null ? brushTarget.GetHashCode() : 0);
  627. hash = hash * 33 + position.GetHashCode();
  628. hash = hash * 33 + tool.GetHashCode();
  629. hash = hash * 33 + (brush != null ? brush.GetHashCode() : 0);
  630. }
  631. return hash;
  632. }
  633. }
  634. }