GridPaintPaletteWindow.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEditor.EditorTools;
  5. using UnityEditor.ShortcutManagement;
  6. using UnityEngine;
  7. using UnityEngine.Tilemaps;
  8. using Event = UnityEngine.Event;
  9. using Object = UnityEngine.Object;
  10. using UnityEditor.Experimental.SceneManagement;
  11. using UnityEditor.SceneManagement;
  12. namespace UnityEditor.Tilemaps
  13. {
  14. internal class GridPaintPaletteWindow : EditorWindow
  15. {
  16. internal enum TilemapFocusMode
  17. {
  18. None = 0,
  19. Tilemap = 1,
  20. Grid = 2
  21. }
  22. private static readonly string k_TilemapFocusModeEditorPref = "TilemapFocusMode";
  23. private TilemapFocusMode focusMode
  24. {
  25. get
  26. {
  27. return (TilemapFocusMode)EditorPrefs.GetInt(k_TilemapFocusModeEditorPref, (int)TilemapFocusMode.None);
  28. }
  29. set
  30. {
  31. EditorPrefs.SetInt(k_TilemapFocusModeEditorPref, (int)value);
  32. }
  33. }
  34. private static readonly string k_TilemapLastPaletteEditorPref = "TilemapLastPalette";
  35. private string lastTilemapPalette
  36. {
  37. get
  38. {
  39. return EditorPrefs.GetString(k_TilemapLastPaletteEditorPref, "");
  40. }
  41. set
  42. {
  43. EditorPrefs.SetString(k_TilemapLastPaletteEditorPref, value);
  44. }
  45. }
  46. private static class MouseStyles
  47. {
  48. // The following paths match the enums in OperatingSystemFamily
  49. public static readonly string[] mouseCursorOSPath =
  50. {
  51. "", // Other OS
  52. "Cursors/macOS",
  53. "Cursors/Windows",
  54. "Cursors/Linux",
  55. };
  56. // The following paths match the enums in OperatingSystemFamily
  57. public static readonly Vector2[] mouseCursorOSHotspot =
  58. {
  59. Vector2.zero, // Other OS
  60. new Vector2(6f, 4f),
  61. new Vector2(6f, 4f),
  62. new Vector2(6f, 4f),
  63. };
  64. // The following paths match the enums in sceneViewEditModes above
  65. public static readonly string[] mouseCursorTexturePaths =
  66. {
  67. "",
  68. "Grid.MoveTool.png",
  69. "Grid.PaintTool.png",
  70. "Grid.BoxTool.png",
  71. "Grid.PickingTool.png",
  72. "Grid.EraserTool.png",
  73. "Grid.FillTool.png",
  74. };
  75. public static readonly Texture2D[] mouseCursorTextures;
  76. static MouseStyles()
  77. {
  78. mouseCursorTextures = new Texture2D[mouseCursorTexturePaths.Length];
  79. int osIndex = (int)SystemInfo.operatingSystemFamily;
  80. for (int i = 0; i < mouseCursorTexturePaths.Length; ++i)
  81. {
  82. if ((mouseCursorOSPath[osIndex] != null && mouseCursorOSPath[osIndex].Length > 0)
  83. && (mouseCursorTexturePaths[i] != null && mouseCursorTexturePaths[i].Length > 0))
  84. {
  85. string cursorPath = Utils.Paths.Combine(mouseCursorOSPath[osIndex], mouseCursorTexturePaths[i]);
  86. mouseCursorTextures[i] = EditorGUIUtility.LoadRequired(cursorPath) as Texture2D;
  87. }
  88. else
  89. mouseCursorTextures[i] = null;
  90. }
  91. }
  92. }
  93. private static class Styles
  94. {
  95. public static readonly GUIContent emptyProjectInfo = EditorGUIUtility.TrTextContent("Create a new palette in the dropdown above.");
  96. public static readonly GUIContent emptyPaletteInfo = EditorGUIUtility.TrTextContent("Drag Tile, Sprite or Sprite Texture assets here.");
  97. public static readonly GUIContent invalidPaletteInfo = EditorGUIUtility.TrTextContent("This is an invalid palette. Did you delete the palette asset?");
  98. public static readonly GUIContent invalidGridInfo = EditorGUIUtility.TrTextContent("The palette has an invalid Grid. Did you add a Grid to the palette asset?");
  99. public static readonly GUIContent selectPaintTarget = EditorGUIUtility.TrTextContent("Select Paint Target");
  100. public static readonly GUIContent selectPalettePrefab = EditorGUIUtility.TrTextContent("Select Palette Prefab");
  101. public static readonly GUIContent selectTileAsset = EditorGUIUtility.TrTextContent("Select Tile Asset");
  102. public static readonly GUIContent unlockPaletteEditing = EditorGUIUtility.TrTextContent("Unlock Palette Editing");
  103. public static readonly GUIContent lockPaletteEditing = EditorGUIUtility.TrTextContent("Lock Palette Editing");
  104. public static readonly GUIContent openTilePalettePreferences = EditorGUIUtility.TrTextContent("Open Tile Palette Preferences");
  105. public static readonly GUIContent createNewPalette = EditorGUIUtility.TrTextContent("Create New Palette");
  106. public static readonly GUIContent focusLabel = EditorGUIUtility.TrTextContent("Focus On");
  107. public static readonly GUIContent rendererOverlayTitleLabel = EditorGUIUtility.TrTextContent("Tilemap");
  108. public static readonly GUIContent activeTargetLabel = EditorGUIUtility.TrTextContent("Active Tilemap", "Specifies the currently active Tilemap used for painting in the Scene View.");
  109. public static readonly GUIContent prefabWarningIcon = EditorGUIUtility.TrIconContent("console.warnicon.sml", "Editing Tilemaps in Prefabs will have better performance if edited in Prefab Mode.");
  110. public static readonly GUIContent tilePalette = EditorGUIUtility.TrTextContent("Tile Palette");
  111. public static readonly GUIContent edit = EditorGUIUtility.TrTextContent("Edit", "Toggle to edit current Tile Palette");
  112. public static readonly GUIContent editModified = EditorGUIUtility.TrTextContent("Edit*", "Toggle to save edits for current Tile Palette");
  113. public static readonly GUIContent gizmos = EditorGUIUtility.TrTextContent("Gizmos", "Toggle visibility of Gizmos in the Tile Palette");
  114. public static readonly GUIContent lockZPosition = EditorGUIUtility.TrTextContent("Lock Z Position", "Toggle editing of Z position");
  115. public static readonly GUIContent zPosition = EditorGUIUtility.TrTextContent("Z Position", "Set a Z position for the active Brush for painting");
  116. public static readonly GUIContent resetZPosition = EditorGUIUtility.TrTextContent("Reset", "Reset Z position for the active Brush");
  117. public static readonly GUIStyle ToolbarTitleStyle = "Toolbar";
  118. public static readonly GUIStyle dragHandle = "RL DragHandle";
  119. public static readonly float dragPadding = 3f;
  120. public static readonly GUILayoutOption[] dropdownOptions = { GUILayout.Width(k_DropdownWidth) };
  121. }
  122. private class TilePaletteSaveScope : IDisposable
  123. {
  124. private GameObject m_GameObject;
  125. public TilePaletteSaveScope(GameObject paletteInstance)
  126. {
  127. m_GameObject = paletteInstance;
  128. if (m_GameObject != null)
  129. {
  130. GridPaintingState.savingPalette = true;
  131. SetHideFlagsRecursively(paletteInstance, HideFlags.HideInHierarchy);
  132. foreach (var renderer in paletteInstance.GetComponentsInChildren<Renderer>())
  133. renderer.gameObject.layer = 0;
  134. }
  135. }
  136. public void Dispose()
  137. {
  138. if (m_GameObject != null)
  139. {
  140. SetHideFlagsRecursively(m_GameObject, HideFlags.HideAndDontSave);
  141. GridPaintingState.savingPalette = false;
  142. }
  143. }
  144. private void SetHideFlagsRecursively(GameObject root, HideFlags flags)
  145. {
  146. root.hideFlags = flags;
  147. for (int i = 0; i < root.transform.childCount; i++)
  148. SetHideFlagsRecursively(root.transform.GetChild(i).gameObject, flags);
  149. }
  150. }
  151. internal class TilePaletteProperties
  152. {
  153. public enum PrefabEditModeSettings
  154. {
  155. EnableDialog = 0,
  156. EditInPrefabMode = 1,
  157. EditInScene = 2
  158. }
  159. public static readonly string targetEditModeDialogTitle = L10n.Tr("Open in Prefab Mode");
  160. public static readonly string targetEditModeDialogMessage = L10n.Tr("Editing Tilemaps in Prefabs will have better performance if edited in Prefab Mode. Do you want to open it in Prefab Mode or edit it in the Scene?");
  161. public static readonly string targetEditModeDialogYes = L10n.Tr("Prefab Mode");
  162. public static readonly string targetEditModeDialogChange = L10n.Tr("Preferences");
  163. public static readonly string targetEditModeDialogNo = L10n.Tr("Scene");
  164. public static readonly string targetEditModeEditorPref = "TilePalette.TargetEditMode";
  165. public static readonly string targetEditModeLookup = "Target Edit Mode";
  166. public static readonly string tilePalettePreferencesLookup = "Tile Palette";
  167. public static readonly GUIContent targetEditModeDialogLabel = EditorGUIUtility.TrTextContent(targetEditModeLookup, "Controls the behaviour of editing a Prefab Instance when one is selected as the Active Target in the Tile Palette");
  168. }
  169. private static readonly GridBrushBase.Tool[] k_SceneViewEditModes =
  170. {
  171. GridBrushBase.Tool.Select,
  172. GridBrushBase.Tool.Move,
  173. GridBrushBase.Tool.Paint,
  174. GridBrushBase.Tool.Box,
  175. GridBrushBase.Tool.Pick,
  176. GridBrushBase.Tool.Erase,
  177. GridBrushBase.Tool.FloodFill
  178. };
  179. private const float k_DropdownWidth = 200f;
  180. private const float k_ActiveTargetLabelWidth = 90f;
  181. private const float k_ActiveTargetDropdownWidth = 130f;
  182. private const float k_ActiveTargetWarningSize = 20f;
  183. private const float k_TopAreaHeight = 104f;
  184. private const float k_MinBrushInspectorHeight = 50f;
  185. private const float k_MinClipboardHeight = 200f;
  186. private const float k_ToolbarHeight = 17f;
  187. private const float k_ResizerDragRectPadding = 10f;
  188. private static readonly Vector2 k_MinWindowSize = new Vector2(k_ActiveTargetLabelWidth + k_ActiveTargetDropdownWidth + k_ActiveTargetWarningSize, 200f);
  189. private PaintableSceneViewGrid m_PaintableSceneViewGrid;
  190. class ShortcutContext : IShortcutToolContext
  191. {
  192. public bool active { get; set; }
  193. }
  194. readonly ShortcutContext m_ShortcutContext = new ShortcutContext { active = true };
  195. [FormerlyPrefKeyAs("Grid Painting/Select", "s")]
  196. [Shortcut("Grid Painting/Select", typeof(ShortcutContext), KeyCode.S)]
  197. static void GridSelectKey()
  198. {
  199. TilemapEditorTool.ToggleActiveEditorTool(typeof(SelectTool));
  200. }
  201. [FormerlyPrefKeyAs("Grid Painting/Move", "m")]
  202. [Shortcut("Grid Painting/Move", typeof(ShortcutContext), KeyCode.M)]
  203. static void GridMoveKey()
  204. {
  205. TilemapEditorTool.ToggleActiveEditorTool(typeof(MoveTool));
  206. }
  207. [FormerlyPrefKeyAs("Grid Painting/Brush", "b")]
  208. [Shortcut("Grid Painting/Brush", typeof(ShortcutContext), KeyCode.B)]
  209. static void GridBrushKey()
  210. {
  211. TilemapEditorTool.ToggleActiveEditorTool(typeof(PaintTool));
  212. }
  213. [FormerlyPrefKeyAs("Grid Painting/Rectangle", "u")]
  214. [Shortcut("Grid Painting/Rectangle", typeof(ShortcutContext), KeyCode.U)]
  215. static void GridRectangleKey()
  216. {
  217. TilemapEditorTool.ToggleActiveEditorTool(typeof(BoxTool));
  218. }
  219. [FormerlyPrefKeyAs("Grid Painting/Picker", "i")]
  220. [Shortcut("Grid Painting/Picker", typeof(ShortcutContext), KeyCode.I)]
  221. static void GridPickerKey()
  222. {
  223. TilemapEditorTool.ToggleActiveEditorTool(typeof(PickingTool));
  224. }
  225. [FormerlyPrefKeyAs("Grid Painting/Erase", "d")]
  226. [Shortcut("Grid Painting/Erase", typeof(ShortcutContext), KeyCode.D)]
  227. static void GridEraseKey()
  228. {
  229. TilemapEditorTool.ToggleActiveEditorTool(typeof(EraseTool));
  230. }
  231. [FormerlyPrefKeyAs("Grid Painting/Fill", "g")]
  232. [Shortcut("Grid Painting/Fill", typeof(ShortcutContext), KeyCode.G)]
  233. static void GridFillKey()
  234. {
  235. TilemapEditorTool.ToggleActiveEditorTool(typeof(FillTool));
  236. }
  237. static void RotateBrush(GridBrushBase.RotationDirection direction)
  238. {
  239. GridPaintingState.gridBrush.Rotate(direction, GridPaintingState.activeGrid.cellLayout);
  240. GridPaintingState.activeGrid.Repaint();
  241. }
  242. [FormerlyPrefKeyAs("Grid Painting/Rotate Clockwise", "[")]
  243. [Shortcut("Grid Painting/Rotate Clockwise", typeof(ShortcutContext), KeyCode.LeftBracket)]
  244. static void RotateBrushClockwise()
  245. {
  246. if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null)
  247. RotateBrush(GridBrushBase.RotationDirection.Clockwise);
  248. }
  249. [FormerlyPrefKeyAs("Grid Painting/Rotate Anti-Clockwise", "]")]
  250. [Shortcut("Grid Painting/Rotate Anti-Clockwise", typeof(ShortcutContext), KeyCode.RightBracket)]
  251. static void RotateBrushAntiClockwise()
  252. {
  253. if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null)
  254. RotateBrush(GridBrushBase.RotationDirection.CounterClockwise);
  255. }
  256. static void FlipBrush(GridBrushBase.FlipAxis axis)
  257. {
  258. GridPaintingState.gridBrush.Flip(axis, GridPaintingState.activeGrid.cellLayout);
  259. GridPaintingState.activeGrid.Repaint();
  260. }
  261. [FormerlyPrefKeyAs("Grid Painting/Flip X", "#[")]
  262. [Shortcut("Grid Painting/Flip X", typeof(ShortcutContext), KeyCode.LeftBracket, ShortcutModifiers.Shift)]
  263. static void FlipBrushX()
  264. {
  265. if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null)
  266. FlipBrush(GridBrushBase.FlipAxis.X);
  267. }
  268. [FormerlyPrefKeyAs("Grid Painting/Flip Y", "#]")]
  269. [Shortcut("Grid Painting/Flip Y", typeof(ShortcutContext), KeyCode.RightBracket, ShortcutModifiers.Shift)]
  270. static void FlipBrushY()
  271. {
  272. if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null)
  273. FlipBrush(GridBrushBase.FlipAxis.Y);
  274. }
  275. static void ChangeBrushZ(int change)
  276. {
  277. GridPaintingState.gridBrush.ChangeZPosition(change);
  278. GridPaintingState.activeGrid.ChangeZPosition(change);
  279. GridPaintingState.activeGrid.Repaint();
  280. foreach (var window in GridPaintPaletteWindow.instances)
  281. {
  282. window.Repaint();
  283. }
  284. }
  285. [Shortcut("Grid Painting/Increase Z", typeof(ShortcutContext), KeyCode.Minus)]
  286. static void IncreaseBrushZ()
  287. {
  288. if (GridPaintingState.gridBrush != null
  289. && GridPaintingState.activeGrid != null
  290. && GridPaintingState.activeBrushEditor != null
  291. && GridPaintingState.activeBrushEditor.canChangeZPosition)
  292. ChangeBrushZ(1);
  293. }
  294. [Shortcut("Grid Painting/Decrease Z", typeof(ShortcutContext), KeyCode.Equals)]
  295. static void DecreaseBrushZ()
  296. {
  297. if (GridPaintingState.gridBrush != null
  298. && GridPaintingState.activeGrid != null
  299. && GridPaintingState.activeBrushEditor != null
  300. && GridPaintingState.activeBrushEditor.canChangeZPosition)
  301. ChangeBrushZ(-1);
  302. }
  303. internal static void PreferencesGUI()
  304. {
  305. using (new SettingsWindow.GUIScope())
  306. {
  307. EditorGUI.BeginChangeCheck();
  308. var val = (TilePaletteProperties.PrefabEditModeSettings)EditorGUILayout.EnumPopup(TilePaletteProperties.targetEditModeDialogLabel, (TilePaletteProperties.PrefabEditModeSettings)EditorPrefs.GetInt(TilePaletteProperties.targetEditModeEditorPref, 0));
  309. if (EditorGUI.EndChangeCheck())
  310. {
  311. EditorPrefs.SetInt(TilePaletteProperties.targetEditModeEditorPref, (int)val);
  312. }
  313. }
  314. }
  315. private static List<GridPaintPaletteWindow> s_Instances;
  316. public static List<GridPaintPaletteWindow> instances
  317. {
  318. get
  319. {
  320. if (s_Instances == null)
  321. s_Instances = new List<GridPaintPaletteWindow>();
  322. return s_Instances;
  323. }
  324. }
  325. public static bool isActive
  326. {
  327. get
  328. {
  329. return s_Instances != null && s_Instances.Count > 0;
  330. }
  331. }
  332. [SerializeField]
  333. private PreviewResizer m_PreviewResizer;
  334. private GridPalettesDropdown m_PaletteDropdown;
  335. [SerializeField]
  336. private GameObject m_Palette;
  337. [SerializeField]
  338. private bool m_DrawGizmos;
  339. internal bool drawGizmos
  340. {
  341. get { return m_DrawGizmos; }
  342. }
  343. public GameObject palette
  344. {
  345. get
  346. {
  347. return m_Palette;
  348. }
  349. set
  350. {
  351. if (m_Palette != value)
  352. {
  353. clipboardView.OnBeforePaletteSelectionChanged();
  354. m_Palette = value;
  355. clipboardView.OnAfterPaletteSelectionChanged();
  356. lastTilemapPalette = AssetDatabase.GetAssetPath(m_Palette);
  357. GridPaintingState.OnPaletteChanged(m_Palette);
  358. Repaint();
  359. }
  360. }
  361. }
  362. private GameObject m_PaletteInstance;
  363. public GameObject paletteInstance
  364. {
  365. get
  366. {
  367. return m_PaletteInstance;
  368. }
  369. }
  370. private bool m_DelayedResetPaletteInstance;
  371. private bool m_Enabled;
  372. public GridPaintPaletteClipboard clipboardView { get; private set; }
  373. private Vector2 m_BrushScroll;
  374. private GridBrushEditorBase m_PreviousToolActivatedEditor;
  375. private GridBrushBase.Tool m_PreviousToolActivated;
  376. private PreviewRenderUtility m_PreviewUtility;
  377. public PreviewRenderUtility previewUtility
  378. {
  379. get
  380. {
  381. if (m_Enabled && m_PreviewUtility == null)
  382. InitPreviewUtility();
  383. return m_PreviewUtility;
  384. }
  385. }
  386. private void OnSelectionChange()
  387. {
  388. // Update active palette if user has selected a palette prefab
  389. var selectedObject = Selection.activeGameObject;
  390. if (selectedObject != null)
  391. {
  392. bool isPrefab = EditorUtility.IsPersistent(selectedObject) || (selectedObject.hideFlags & HideFlags.NotEditable) != 0;
  393. if (isPrefab)
  394. {
  395. var assetPath = AssetDatabase.GetAssetPath(selectedObject);
  396. var allAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath);
  397. foreach (var asset in allAssets)
  398. {
  399. if (asset != null && asset.GetType() == typeof(GridPalette))
  400. {
  401. var targetPalette = (GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath);
  402. if (targetPalette != palette)
  403. {
  404. palette = targetPalette;
  405. Repaint();
  406. }
  407. break;
  408. }
  409. }
  410. }
  411. }
  412. }
  413. private void OnGUI()
  414. {
  415. HandleContextMenu();
  416. EditorGUILayout.BeginVertical();
  417. GUILayout.Space(10f);
  418. EditorGUILayout.BeginHorizontal();
  419. float leftMargin = (Screen.width / EditorGUIUtility.pixelsPerPoint - TilemapEditorTool.tilemapEditorToolsToolbarSize) * 0.5f;
  420. GUILayout.Space(leftMargin);
  421. DoTilemapToolbar();
  422. GUILayout.Space(leftMargin);
  423. EditorGUILayout.EndHorizontal();
  424. EditorGUILayout.BeginHorizontal();
  425. GUILayout.Space(leftMargin);
  426. DoActiveTargetsGUI();
  427. GUILayout.Space(leftMargin);
  428. EditorGUILayout.EndHorizontal();
  429. GUILayout.Space(6f);
  430. EditorGUILayout.EndVertical();
  431. EditorGUILayout.BeginVertical();
  432. Rect clipboardToolbarRect = EditorGUILayout.BeginHorizontal(GUIContent.none, Styles.ToolbarTitleStyle);
  433. DoClipboardHeader();
  434. EditorGUILayout.EndHorizontal();
  435. ConvertGridPrefabToPalette(clipboardToolbarRect);
  436. Rect dragRect = new Rect(k_DropdownWidth + k_ResizerDragRectPadding, 0, position.width - k_DropdownWidth - k_ResizerDragRectPadding, k_ToolbarHeight);
  437. float brushInspectorSize = m_PreviewResizer.ResizeHandle(position, k_MinBrushInspectorHeight, k_MinClipboardHeight, k_ToolbarHeight, dragRect);
  438. float clipboardHeight = position.height - brushInspectorSize - k_TopAreaHeight;
  439. Rect clipboardRect = new Rect(0f, clipboardToolbarRect.yMax, position.width, clipboardHeight);
  440. OnClipboardGUI(clipboardRect);
  441. EditorGUILayout.EndVertical();
  442. GUILayout.Space(clipboardRect.height);
  443. EditorGUILayout.BeginVertical();
  444. EditorGUILayout.BeginHorizontal(GUIContent.none, Styles.ToolbarTitleStyle);
  445. DoBrushesDropdownToolbar();
  446. EditorGUILayout.EndHorizontal();
  447. m_BrushScroll = GUILayout.BeginScrollView(m_BrushScroll, false, false);
  448. GUILayout.Space(4f);
  449. OnBrushInspectorGUI();
  450. GUILayout.EndScrollView();
  451. EditorGUILayout.EndVertical();
  452. Color oldColor = Handles.color;
  453. Handles.color = Color.black;
  454. Handles.DrawLine(new Vector3(0, clipboardRect.yMax + 0.5f, 0), new Vector3(Screen.width, clipboardRect.yMax + 0.5f, 0));
  455. Handles.color = Color.black.AlphaMultiplied(0.33f);
  456. Handles.DrawLine(new Vector3(0, GUILayoutUtility.GetLastRect().yMax + 0.5f, 0), new Vector3(Screen.width, GUILayoutUtility.GetLastRect().yMax + 0.5f, 0));
  457. Handles.color = oldColor;
  458. EditorGUILayout.BeginVertical();
  459. GUILayout.Space(2f);
  460. EditorGUILayout.EndVertical();
  461. // Keep repainting until all previews are loaded
  462. if (AssetPreview.IsLoadingAssetPreviews(GetInstanceID()))
  463. Repaint();
  464. // Release keyboard focus on click to empty space
  465. if (Event.current.type == EventType.MouseDown)
  466. GUIUtility.keyboardControl = 0;
  467. }
  468. static void DoTilemapToolbar()
  469. {
  470. EditorTool active = EditorToolManager.activeTool;
  471. EditorTool selected;
  472. if (EditorGUILayout.EditorToolbar(active, TilemapEditorTool.tilemapEditorTools, out selected))
  473. {
  474. if (active == selected)
  475. ToolManager.SetActiveTool(EditorToolManager.GetLastTool(x => !TilemapEditorTool.tilemapEditorTools.Contains(x)));
  476. else
  477. ToolManager.SetActiveTool(selected);
  478. }
  479. }
  480. public void DelayedResetPreviewInstance()
  481. {
  482. m_DelayedResetPaletteInstance = true;
  483. }
  484. public void ResetPreviewInstance()
  485. {
  486. if (m_PreviewUtility == null)
  487. InitPreviewUtility();
  488. m_DelayedResetPaletteInstance = false;
  489. DestroyPreviewInstance();
  490. if (palette != null)
  491. {
  492. m_PaletteInstance = previewUtility.InstantiatePrefabInScene(palette);
  493. // Disconnecting prefabs is no longer possible.
  494. // If performance of overrides on palette palette instance turns out to be a problem.
  495. // unpack the prefab instance here, and overwrite the prefab later instead of reconnecting.
  496. PrefabUtility.UnpackPrefabInstance(m_PaletteInstance, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
  497. EditorUtility.InitInstantiatedPreviewRecursive(m_PaletteInstance);
  498. m_PaletteInstance.transform.position = new Vector3(0, 0, 0);
  499. m_PaletteInstance.transform.rotation = Quaternion.identity;
  500. m_PaletteInstance.transform.localScale = Vector3.one;
  501. GridPalette paletteAsset = GridPaletteUtility.GetGridPaletteFromPaletteAsset(palette);
  502. if (paletteAsset != null)
  503. {
  504. if (paletteAsset.cellSizing == GridPalette.CellSizing.Automatic)
  505. {
  506. Grid grid = m_PaletteInstance.GetComponent<Grid>();
  507. if (grid != null)
  508. {
  509. grid.cellSize = GridPaletteUtility.CalculateAutoCellSize(grid, grid.cellSize);
  510. }
  511. else
  512. {
  513. Debug.LogWarning("Grid component not found from: " + palette.name);
  514. }
  515. }
  516. previewUtility.camera.transparencySortMode = paletteAsset.transparencySortMode;
  517. previewUtility.camera.transparencySortAxis = paletteAsset.transparencySortAxis;
  518. }
  519. else
  520. {
  521. Debug.LogWarning("GridPalette subasset not found from: " + palette.name);
  522. previewUtility.camera.transparencySortMode = TransparencySortMode.Default;
  523. previewUtility.camera.transparencySortAxis = new Vector3(0f, 0f, 1f);
  524. }
  525. foreach (var transform in m_PaletteInstance.GetComponentsInChildren<Transform>())
  526. transform.gameObject.hideFlags = HideFlags.HideAndDontSave;
  527. // Show all renderers from Palettes from previous versions
  528. PreviewRenderUtility.SetEnabledRecursive(m_PaletteInstance, true);
  529. clipboardView.ResetPreviewMesh();
  530. }
  531. }
  532. public void DestroyPreviewInstance()
  533. {
  534. if (m_PaletteInstance != null)
  535. {
  536. Undo.ClearUndo(m_PaletteInstance);
  537. DestroyImmediate(m_PaletteInstance);
  538. }
  539. }
  540. public void InitPreviewUtility()
  541. {
  542. int previewCullingLayer = Camera.PreviewCullingLayer;
  543. m_PreviewUtility = new PreviewRenderUtility(true, true);
  544. m_PreviewUtility.camera.cullingMask = 1 << previewCullingLayer;
  545. m_PreviewUtility.camera.gameObject.layer = previewCullingLayer;
  546. m_PreviewUtility.lights[0].gameObject.layer = previewCullingLayer;
  547. m_PreviewUtility.camera.orthographic = true;
  548. m_PreviewUtility.camera.orthographicSize = 5f;
  549. m_PreviewUtility.camera.transform.position = new Vector3(0f, 0f, -10f);
  550. m_PreviewUtility.ambientColor = new Color(1f, 1f, 1f, 0);
  551. ResetPreviewInstance();
  552. clipboardView.SetupPreviewCameraOnInit();
  553. }
  554. private void HandleContextMenu()
  555. {
  556. if (Event.current.type == EventType.ContextClick)
  557. {
  558. DoContextMenu();
  559. Event.current.Use();
  560. }
  561. }
  562. public void SavePalette()
  563. {
  564. if (paletteInstance != null && palette != null)
  565. {
  566. using (new TilePaletteSaveScope(paletteInstance))
  567. {
  568. string path = AssetDatabase.GetAssetPath(palette);
  569. PrefabUtility.SaveAsPrefabAssetAndConnect(paletteInstance, path, InteractionMode.AutomatedAction);
  570. }
  571. ResetPreviewInstance();
  572. Repaint();
  573. }
  574. }
  575. private void DoContextMenu()
  576. {
  577. GenericMenu pm = new GenericMenu();
  578. if (GridPaintingState.scenePaintTarget != null)
  579. pm.AddItem(Styles.selectPaintTarget, false, SelectPaintTarget);
  580. else
  581. pm.AddDisabledItem(Styles.selectPaintTarget);
  582. if (palette != null)
  583. pm.AddItem(Styles.selectPalettePrefab, false, SelectPaletteAsset);
  584. else
  585. pm.AddDisabledItem(Styles.selectPalettePrefab);
  586. if (clipboardView.activeTile != null)
  587. pm.AddItem(Styles.selectTileAsset, false, SelectTileAsset);
  588. else
  589. pm.AddDisabledItem(Styles.selectTileAsset);
  590. pm.AddSeparator("");
  591. if (clipboardView.unlocked)
  592. pm.AddItem(Styles.lockPaletteEditing, false, FlipLocked);
  593. else
  594. pm.AddItem(Styles.unlockPaletteEditing, false, FlipLocked);
  595. pm.AddItem(Styles.openTilePalettePreferences, false, OpenTilePalettePreferences);
  596. pm.ShowAsContext();
  597. }
  598. private void OpenTilePalettePreferences()
  599. {
  600. var settingsWindow = SettingsWindow.Show(SettingsScope.User);
  601. settingsWindow.FilterProviders(TilePaletteProperties.tilePalettePreferencesLookup);
  602. }
  603. private void FlipLocked()
  604. {
  605. clipboardView.unlocked = !clipboardView.unlocked;
  606. }
  607. private void SelectPaintTarget()
  608. {
  609. Selection.activeObject = GridPaintingState.scenePaintTarget;
  610. }
  611. private void SelectPaletteAsset()
  612. {
  613. Selection.activeObject = palette;
  614. }
  615. private void SelectTileAsset()
  616. {
  617. Selection.activeObject = clipboardView.activeTile;
  618. }
  619. private bool NotOverridingColor(GridBrush defaultGridBrush)
  620. {
  621. foreach (var cell in defaultGridBrush.cells)
  622. {
  623. TileBase tile = cell.tile;
  624. if (tile is Tile && ((tile as Tile).flags & TileFlags.LockColor) == 0)
  625. {
  626. return true;
  627. }
  628. }
  629. return false;
  630. }
  631. private void DoBrushesDropdownToolbar()
  632. {
  633. GUIContent content = GUIContent.Temp(GridPaintingState.gridBrush.name);
  634. if (EditorGUILayout.DropdownButton(content, FocusType.Passive, EditorStyles.toolbarPopup, Styles.dropdownOptions))
  635. {
  636. var menuData = new GridBrushesDropdown.MenuItemProvider();
  637. var flexibleMenu = new GridBrushesDropdown(menuData, GridPaletteBrushes.brushes.IndexOf(GridPaintingState.gridBrush), null, SelectBrush, k_DropdownWidth);
  638. PopupWindow.Show(GUILayoutUtility.topLevel.GetLast(), flexibleMenu);
  639. }
  640. if (Event.current.type == EventType.Repaint)
  641. {
  642. var dragRect = GUILayoutUtility.GetLastRect();
  643. var dragIconRect = new Rect();
  644. dragIconRect.x = dragRect.x + dragRect.width + Styles.dragPadding;
  645. dragIconRect.y = dragRect.y + (dragRect.height - Styles.dragHandle.fixedHeight) / 2 + 1;
  646. dragIconRect.width = position.width - (dragIconRect.x) - Styles.dragPadding;
  647. dragIconRect.height = Styles.dragHandle.fixedHeight;
  648. Styles.dragHandle.Draw(dragIconRect, GUIContent.none, false, false, false, false);
  649. }
  650. GUILayout.FlexibleSpace();
  651. }
  652. private void SelectBrush(int i, object o)
  653. {
  654. GridPaintingState.gridBrush = GridPaletteBrushes.brushes[i];
  655. }
  656. public void OnEnable()
  657. {
  658. m_Enabled = true;
  659. instances.Add(this);
  660. if (clipboardView == null)
  661. {
  662. clipboardView = CreateInstance<GridPaintPaletteClipboard>();
  663. clipboardView.owner = this;
  664. clipboardView.hideFlags = HideFlags.HideAndDontSave;
  665. clipboardView.unlocked = false;
  666. }
  667. if (m_PaintableSceneViewGrid == null)
  668. {
  669. m_PaintableSceneViewGrid = CreateInstance<PaintableSceneViewGrid>();
  670. m_PaintableSceneViewGrid.hideFlags = HideFlags.HideAndDontSave;
  671. }
  672. GridPaletteBrushes.FlushCache();
  673. ShortcutIntegration.instance.profileManager.shortcutBindingChanged += UpdateTooltips;
  674. GridSelection.gridSelectionChanged += OnGridSelectionChanged;
  675. GridPaintingState.RegisterPainterInterest(this);
  676. GridPaintingState.scenePaintTargetChanged += OnScenePaintTargetChanged;
  677. GridPaintingState.brushChanged += OnBrushChanged;
  678. SceneView.duringSceneGui += OnSceneViewGUI;
  679. PrefabUtility.prefabInstanceUpdated += PrefabInstanceUpdated;
  680. EditorApplication.projectWasLoaded += OnProjectLoaded;
  681. AssetPreview.SetPreviewTextureCacheSize(256, GetInstanceID());
  682. wantsMouseMove = true;
  683. wantsMouseEnterLeaveWindow = true;
  684. if (m_PreviewResizer == null)
  685. {
  686. m_PreviewResizer = new PreviewResizer();
  687. m_PreviewResizer.Init("TilemapBrushInspector");
  688. }
  689. minSize = k_MinWindowSize;
  690. if (palette == null && !String.IsNullOrEmpty(lastTilemapPalette))
  691. {
  692. palette = GridPalettes.palettes
  693. .Where((palette, index) => (AssetDatabase.GetAssetPath(palette) == lastTilemapPalette))
  694. .FirstOrDefault();
  695. }
  696. if (palette == null && GridPalettes.palettes.Count > 0)
  697. {
  698. palette = GridPalettes.palettes[0];
  699. }
  700. ToolManager.activeToolChanged += ActiveToolChanged;
  701. ToolManager.activeToolChanging += ActiveToolChanging;
  702. ShortcutIntegration.instance.contextManager.RegisterToolContext(m_ShortcutContext);
  703. }
  704. private static void UpdateTooltips(IShortcutProfileManager obj, Identifier identifier, ShortcutBinding oldBinding, ShortcutBinding newBinding)
  705. {
  706. TilemapEditorTool.UpdateTooltips();
  707. }
  708. private void PrefabInstanceUpdated(GameObject updatedPrefab)
  709. {
  710. // case 947462: Reset the palette instance after its prefab has been updated as it could have been changed
  711. if (m_PaletteInstance != null && PrefabUtility.GetCorrespondingObjectFromSource(updatedPrefab) == m_Palette && !GridPaintingState.savingPalette)
  712. {
  713. ResetPreviewInstance();
  714. Repaint();
  715. }
  716. }
  717. private void OnProjectLoaded()
  718. {
  719. // ShortcutIntegration instance is recreated after LoadLayout which wipes the OnEnable registration
  720. ShortcutIntegration.instance.contextManager.RegisterToolContext(m_ShortcutContext);
  721. }
  722. private void OnBrushChanged(GridBrushBase brush)
  723. {
  724. DisableFocus();
  725. if (brush is GridBrush)
  726. EnableFocus();
  727. SceneView.RepaintAll();
  728. }
  729. private void OnGridSelectionChanged()
  730. {
  731. Repaint();
  732. }
  733. public void OnDisable()
  734. {
  735. m_Enabled = false;
  736. DisableFocus();
  737. focusMode = TilemapFocusMode.None;
  738. CallOnToolDeactivated();
  739. instances.Remove(this);
  740. if (instances.Count <= 1)
  741. GridPaintingState.gridBrush = null;
  742. DestroyPreviewInstance();
  743. DestroyImmediate(clipboardView);
  744. DestroyImmediate(m_PaintableSceneViewGrid);
  745. if (m_PreviewUtility != null)
  746. m_PreviewUtility.Cleanup();
  747. m_PreviewUtility = null;
  748. if (PaintableGrid.InGridEditMode())
  749. {
  750. // Set Editor Tool to an always available Tool, as Tile Palette Tools are not available any more
  751. ToolManager.SetActiveTool<UnityEditor.RectTool>();
  752. }
  753. ShortcutIntegration.instance.profileManager.shortcutBindingChanged -= UpdateTooltips;
  754. ToolManager.activeToolChanged -= ActiveToolChanged;
  755. ToolManager.activeToolChanging -= ActiveToolChanging;
  756. GridSelection.gridSelectionChanged -= OnGridSelectionChanged;
  757. SceneView.duringSceneGui -= OnSceneViewGUI;
  758. GridPaintingState.scenePaintTargetChanged -= OnScenePaintTargetChanged;
  759. GridPaintingState.brushChanged -= OnBrushChanged;
  760. GridPaintingState.UnregisterPainterInterest(this);
  761. PrefabUtility.prefabInstanceUpdated -= PrefabInstanceUpdated;
  762. EditorApplication.projectWasLoaded -= OnProjectLoaded;
  763. ShortcutIntegration.instance.contextManager.DeregisterToolContext(m_ShortcutContext);
  764. }
  765. private void OnScenePaintTargetChanged(GameObject scenePaintTarget)
  766. {
  767. DisableFocus();
  768. EnableFocus();
  769. Repaint();
  770. }
  771. private void ActiveToolChanged()
  772. {
  773. if (GridPaintingState.gridBrush != null && PaintableGrid.InGridEditMode() && GridPaintingState.activeBrushEditor != null)
  774. {
  775. GridBrushBase.Tool tool = PaintableGrid.EditTypeToBrushTool(ToolManager.activeToolType);
  776. GridPaintingState.activeBrushEditor.OnToolActivated(tool);
  777. m_PreviousToolActivatedEditor = GridPaintingState.activeBrushEditor;
  778. m_PreviousToolActivated = tool;
  779. for (int i = 0; i < k_SceneViewEditModes.Length; ++i)
  780. {
  781. if (k_SceneViewEditModes[i] == tool)
  782. {
  783. Cursor.SetCursor(MouseStyles.mouseCursorTextures[i],
  784. MouseStyles.mouseCursorTextures[i] != null ? MouseStyles.mouseCursorOSHotspot[(int)SystemInfo.operatingSystemFamily] : Vector2.zero,
  785. CursorMode.Auto);
  786. break;
  787. }
  788. }
  789. }
  790. else
  791. {
  792. Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
  793. }
  794. Repaint();
  795. }
  796. private void ActiveToolChanging()
  797. {
  798. if (!TilemapEditorTool.IsActive(typeof(MoveTool)) && !TilemapEditorTool.IsActive(typeof(SelectTool)))
  799. {
  800. GridSelection.Clear();
  801. }
  802. CallOnToolDeactivated();
  803. }
  804. private void CallOnToolDeactivated()
  805. {
  806. if (GridPaintingState.gridBrush != null && m_PreviousToolActivatedEditor != null)
  807. {
  808. m_PreviousToolActivatedEditor.OnToolDeactivated(m_PreviousToolActivated);
  809. m_PreviousToolActivatedEditor = null;
  810. if (!PaintableGrid.InGridEditMode())
  811. Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
  812. }
  813. }
  814. internal void ResetZPosition()
  815. {
  816. GridPaintingState.gridBrush.ResetZPosition();
  817. GridPaintingState.lastActiveGrid.ResetZPosition();
  818. }
  819. private void OnBrushInspectorGUI()
  820. {
  821. if (GridPaintingState.gridBrush == null)
  822. return;
  823. // Brush Inspector GUI
  824. EditorGUI.BeginChangeCheck();
  825. if (GridPaintingState.activeBrushEditor != null)
  826. GridPaintingState.activeBrushEditor.OnPaintInspectorGUI();
  827. else if (GridPaintingState.fallbackEditor != null)
  828. GridPaintingState.fallbackEditor.OnInspectorGUI();
  829. if (EditorGUI.EndChangeCheck())
  830. {
  831. GridPaletteBrushes.ActiveGridBrushAssetChanged();
  832. }
  833. // Z Position Inspector
  834. var hasLastActiveGrid = GridPaintingState.lastActiveGrid != null;
  835. using (new EditorGUI.DisabledScope(!hasLastActiveGrid))
  836. {
  837. var lockZPosition = false;
  838. if (GridPaintingState.activeBrushEditor != null)
  839. {
  840. EditorGUI.BeginChangeCheck();
  841. lockZPosition = EditorGUILayout.Toggle(Styles.lockZPosition, !GridPaintingState.activeBrushEditor.canChangeZPosition);
  842. if (EditorGUI.EndChangeCheck())
  843. GridPaintingState.activeBrushEditor.canChangeZPosition = !lockZPosition;
  844. }
  845. using (new EditorGUI.DisabledScope(lockZPosition))
  846. {
  847. EditorGUILayout.BeginHorizontal();
  848. EditorGUI.BeginChangeCheck();
  849. var zPosition = EditorGUILayout.DelayedIntField(Styles.zPosition, hasLastActiveGrid ? GridPaintingState.lastActiveGrid.zPosition : 0);
  850. if (EditorGUI.EndChangeCheck())
  851. {
  852. GridPaintingState.gridBrush.ChangeZPosition(zPosition - GridPaintingState.lastActiveGrid.zPosition);
  853. GridPaintingState.lastActiveGrid.zPosition = zPosition;
  854. }
  855. if (GUILayout.Button(Styles.resetZPosition))
  856. {
  857. ResetZPosition();
  858. }
  859. EditorGUILayout.EndHorizontal();
  860. }
  861. }
  862. }
  863. private bool IsObjectPrefabInstance(Object target)
  864. {
  865. return target != null && PrefabUtility.IsPartOfRegularPrefab(target);
  866. }
  867. private GameObject FindPrefabInstanceEquivalent(GameObject prefabInstance, GameObject prefabTarget)
  868. {
  869. var prefabRoot = prefabTarget.transform.root.gameObject;
  870. var currentTransform = prefabTarget.transform;
  871. var reverseTransformOrder = new Stack<int>();
  872. while (currentTransform != prefabRoot.transform && currentTransform.parent != null)
  873. {
  874. var parentTransform = currentTransform.parent;
  875. for (int i = 0; i < parentTransform.childCount; ++i)
  876. {
  877. if (currentTransform == parentTransform.GetChild(i))
  878. {
  879. reverseTransformOrder.Push(i);
  880. break;
  881. }
  882. }
  883. currentTransform = currentTransform.parent;
  884. }
  885. currentTransform = prefabInstance.transform;
  886. while (reverseTransformOrder.Count > 0)
  887. {
  888. var childIndex = reverseTransformOrder.Pop();
  889. if (childIndex >= currentTransform.childCount)
  890. return null;
  891. currentTransform = currentTransform.GetChild(childIndex);
  892. }
  893. return currentTransform.gameObject;
  894. }
  895. private void GoToPrefabMode(GameObject target)
  896. {
  897. var prefabObject = PrefabUtility.GetCorrespondingObjectFromSource(target);
  898. var assetPath = AssetDatabase.GetAssetPath(prefabObject);
  899. var stage = PrefabStageUtility.OpenPrefab(assetPath);
  900. var prefabInstance = stage.prefabContentsRoot;
  901. var prefabTarget = FindPrefabInstanceEquivalent(prefabInstance, prefabObject);
  902. if (prefabTarget != null)
  903. {
  904. GridPaintingState.scenePaintTarget = prefabTarget;
  905. }
  906. }
  907. private void DoActiveTargetsGUI()
  908. {
  909. using (new EditorGUI.DisabledScope(GridPaintingState.validTargets == null || GridPaintingState.scenePaintTarget == null))
  910. {
  911. bool hasPaintTarget = GridPaintingState.scenePaintTarget != null;
  912. bool needWarning = IsObjectPrefabInstance(GridPaintingState.scenePaintTarget);
  913. GUILayout.Label(Styles.activeTargetLabel, GUILayout.Width(k_ActiveTargetLabelWidth), GUILayout.Height(k_ActiveTargetWarningSize));
  914. GUIContent content = GUIContent.Temp(hasPaintTarget ? GridPaintingState.scenePaintTarget.name : "Nothing");
  915. if (EditorGUILayout.DropdownButton(content, FocusType.Passive, EditorStyles.popup, GUILayout.Width(k_ActiveTargetDropdownWidth - (needWarning ? k_ActiveTargetWarningSize : 0f)), GUILayout.Height(k_ActiveTargetWarningSize)))
  916. {
  917. int index = hasPaintTarget ? Array.IndexOf(GridPaintingState.validTargets, GridPaintingState.scenePaintTarget) : 0;
  918. var menuData = new GridPaintTargetsDropdown.MenuItemProvider();
  919. var flexibleMenu = new GridPaintTargetsDropdown(menuData, index, null, SelectTarget, k_ActiveTargetDropdownWidth);
  920. PopupWindow.Show(GUILayoutUtility.topLevel.GetLast(), flexibleMenu);
  921. }
  922. if (needWarning)
  923. GUILayout.Label(Styles.prefabWarningIcon, GUILayout.Width(k_ActiveTargetWarningSize), GUILayout.Height(k_ActiveTargetWarningSize));
  924. }
  925. }
  926. private void SelectTarget(int i, object o)
  927. {
  928. var obj = o as GameObject;
  929. var isPrefabInstance = IsObjectPrefabInstance(obj);
  930. if (isPrefabInstance)
  931. {
  932. var editMode = (TilePaletteProperties.PrefabEditModeSettings)EditorPrefs.GetInt(TilePaletteProperties.targetEditModeEditorPref, 0);
  933. switch (editMode)
  934. {
  935. case TilePaletteProperties.PrefabEditModeSettings.EnableDialog:
  936. {
  937. var option = EditorUtility.DisplayDialogComplex(TilePaletteProperties.targetEditModeDialogTitle
  938. , TilePaletteProperties.targetEditModeDialogMessage
  939. , TilePaletteProperties.targetEditModeDialogYes
  940. , TilePaletteProperties.targetEditModeDialogNo
  941. , TilePaletteProperties.targetEditModeDialogChange);
  942. switch (option)
  943. {
  944. case 0:
  945. GoToPrefabMode(obj);
  946. return;
  947. case 1:
  948. // Do nothing here for "No"
  949. break;
  950. case 2:
  951. var settingsWindow = SettingsWindow.Show(SettingsScope.User);
  952. settingsWindow.FilterProviders(TilePaletteProperties.targetEditModeLookup);
  953. break;
  954. }
  955. }
  956. break;
  957. case TilePaletteProperties.PrefabEditModeSettings.EditInPrefabMode:
  958. GoToPrefabMode(obj);
  959. return;
  960. case TilePaletteProperties.PrefabEditModeSettings.EditInScene:
  961. default:
  962. break;
  963. }
  964. }
  965. GridPaintingState.scenePaintTarget = obj;
  966. if (GridPaintingState.scenePaintTarget != null)
  967. EditorGUIUtility.PingObject(GridPaintingState.scenePaintTarget);
  968. }
  969. private void DoClipboardHeader()
  970. {
  971. if (!GridPalettes.palettes.Contains(palette) || palette == null) // Palette not in list means it was deleted
  972. {
  973. GridPalettes.CleanCache();
  974. if (GridPalettes.palettes.Count > 0)
  975. {
  976. palette = GridPalettes.palettes.LastOrDefault();
  977. }
  978. }
  979. EditorGUILayout.BeginHorizontal();
  980. DoPalettesDropdown();
  981. using (new EditorGUI.DisabledScope(palette == null))
  982. {
  983. clipboardView.unlocked = GUILayout.Toggle(clipboardView.unlocked,
  984. clipboardView.isModified ? Styles.editModified : Styles.edit,
  985. EditorStyles.toolbarButton);
  986. }
  987. GUILayout.FlexibleSpace();
  988. using (new EditorGUI.DisabledScope(palette == null))
  989. {
  990. EditorGUI.BeginChangeCheck();
  991. m_DrawGizmos = GUILayout.Toggle(m_DrawGizmos, Styles.gizmos, EditorStyles.toolbarButton);
  992. if (EditorGUI.EndChangeCheck())
  993. {
  994. if (m_DrawGizmos)
  995. {
  996. clipboardView.SavePaletteIfNecessary();
  997. ResetPreviewInstance();
  998. }
  999. Repaint();
  1000. }
  1001. }
  1002. EditorGUILayout.EndHorizontal();
  1003. }
  1004. private void DoPalettesDropdown()
  1005. {
  1006. string name = palette != null ? palette.name : Styles.createNewPalette.text;
  1007. Rect rect = GUILayoutUtility.GetRect(GUIContent.Temp(name), EditorStyles.toolbarDropDown, Styles.dropdownOptions);
  1008. if (GridPalettes.palettes.Count == 0)
  1009. {
  1010. if (EditorGUI.DropdownButton(rect, GUIContent.Temp(name), FocusType.Passive, EditorStyles.toolbarDropDown))
  1011. {
  1012. OpenAddPalettePopup(rect);
  1013. }
  1014. }
  1015. else
  1016. {
  1017. GUIContent content = GUIContent.Temp(GridPalettes.palettes.Count > 0 && palette != null ? palette.name : Styles.createNewPalette.text);
  1018. if (EditorGUI.DropdownButton(rect, content, FocusType.Passive, EditorStyles.toolbarPopup))
  1019. {
  1020. var menuData = new GridPalettesDropdown.MenuItemProvider();
  1021. m_PaletteDropdown = new GridPalettesDropdown(menuData, GridPalettes.palettes.IndexOf(palette), null, SelectPalette, k_DropdownWidth);
  1022. PopupWindow.Show(GUILayoutUtility.topLevel.GetLast(), m_PaletteDropdown);
  1023. }
  1024. }
  1025. }
  1026. private void SelectPalette(int i, object o)
  1027. {
  1028. if (i < GridPalettes.palettes.Count)
  1029. {
  1030. palette = GridPalettes.palettes[i];
  1031. }
  1032. else
  1033. {
  1034. m_PaletteDropdown.editorWindow.Close();
  1035. OpenAddPalettePopup(new Rect(0, 0, 0, 0));
  1036. }
  1037. }
  1038. private void OpenAddPalettePopup(Rect rect)
  1039. {
  1040. bool popupOpened = GridPaletteAddPopup.ShowAtPosition(rect, this);
  1041. if (popupOpened)
  1042. GUIUtility.ExitGUI();
  1043. }
  1044. private void DisplayClipboardText(GUIContent clipboardText, Rect position)
  1045. {
  1046. Color old = GUI.color;
  1047. GUI.color = Color.gray;
  1048. var infoSize = GUI.skin.label.CalcSize(clipboardText);
  1049. Rect rect = new Rect(position.center.x - infoSize.x * .5f, position.center.y - infoSize.y, 500, 100);
  1050. GUI.Label(rect, clipboardText);
  1051. GUI.color = old;
  1052. }
  1053. private void OnClipboardGUI(Rect position)
  1054. {
  1055. if (Event.current.type != EventType.Layout && position.Contains(Event.current.mousePosition) && GridPaintingState.activeGrid != clipboardView && clipboardView.unlocked)
  1056. {
  1057. GridPaintingState.activeGrid = clipboardView;
  1058. SceneView.RepaintAll();
  1059. }
  1060. // Validate palette (case 1017965)
  1061. GUIContent paletteError = null;
  1062. if (palette == null)
  1063. {
  1064. if (GridPalettes.palettes.Count == 0)
  1065. paletteError = Styles.emptyProjectInfo;
  1066. else
  1067. paletteError = Styles.invalidPaletteInfo;
  1068. }
  1069. else if (palette.GetComponent<Grid>() == null)
  1070. {
  1071. paletteError = Styles.invalidGridInfo;
  1072. }
  1073. if (paletteError != null)
  1074. {
  1075. DisplayClipboardText(paletteError, position);
  1076. return;
  1077. }
  1078. bool oldEnabled = GUI.enabled;
  1079. GUI.enabled = !clipboardView.showNewEmptyClipboardInfo || DragAndDrop.objectReferences.Length > 0;
  1080. if (Event.current.type == EventType.Repaint)
  1081. clipboardView.guiRect = position;
  1082. if (m_DelayedResetPaletteInstance)
  1083. ResetPreviewInstance();
  1084. EditorGUI.BeginChangeCheck();
  1085. clipboardView.OnGUI();
  1086. if (EditorGUI.EndChangeCheck())
  1087. Repaint();
  1088. GUI.enabled = oldEnabled;
  1089. if (clipboardView.showNewEmptyClipboardInfo)
  1090. {
  1091. DisplayClipboardText(Styles.emptyPaletteInfo, position);
  1092. }
  1093. }
  1094. private void ConvertGridPrefabToPalette(Rect targetPosition)
  1095. {
  1096. if (!targetPosition.Contains(Event.current.mousePosition)
  1097. || (Event.current.type != EventType.DragPerform
  1098. && Event.current.type != EventType.DragUpdated)
  1099. || DragAndDrop.objectReferences.Length != 1)
  1100. return;
  1101. var draggedObject = DragAndDrop.objectReferences[0];
  1102. if (!PrefabUtility.IsPartOfRegularPrefab(draggedObject))
  1103. return;
  1104. switch (Event.current.type)
  1105. {
  1106. case EventType.DragUpdated:
  1107. {
  1108. DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
  1109. Event.current.Use();
  1110. GUI.changed = true;
  1111. }
  1112. break;
  1113. case EventType.DragPerform:
  1114. {
  1115. var path = AssetDatabase.GetAssetPath(draggedObject);
  1116. var assets = AssetDatabase.LoadAllAssetsAtPath(path);
  1117. bool hasNewPaletteAsset = false;
  1118. Grid gridPrefab = null;
  1119. foreach (var asset in assets)
  1120. {
  1121. var gridPalette = asset as GridPalette;
  1122. hasNewPaletteAsset |= gridPalette != null;
  1123. GameObject go = asset as GameObject;
  1124. if (go != null)
  1125. {
  1126. var grid = go.GetComponent<Grid>();
  1127. if (grid != null)
  1128. gridPrefab = grid;
  1129. }
  1130. }
  1131. if (!hasNewPaletteAsset && gridPrefab != null)
  1132. {
  1133. var cellLayout = gridPrefab.cellLayout;
  1134. var cellSizing = (cellLayout == GridLayout.CellLayout.Rectangle
  1135. || cellLayout == GridLayout.CellLayout.Hexagon)
  1136. ? GridPalette.CellSizing.Automatic
  1137. : GridPalette.CellSizing.Manual;
  1138. var newPalette = GridPaletteUtility.CreateGridPalette(cellSizing);
  1139. AssetDatabase.AddObjectToAsset(newPalette, path);
  1140. AssetDatabase.ForceReserializeAssets(new string[] {path});
  1141. AssetDatabase.SaveAssets();
  1142. Event.current.Use();
  1143. GUIUtility.ExitGUI();
  1144. }
  1145. }
  1146. break;
  1147. }
  1148. }
  1149. private void OnSceneViewGUI(SceneView sceneView)
  1150. {
  1151. if (GridPaintingState.defaultBrush != null && GridPaintingState.scenePaintTarget != null)
  1152. SceneViewOverlay.Window(Styles.rendererOverlayTitleLabel, DisplayFocusMode, (int)SceneViewOverlay.Ordering.TilemapRenderer, SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle);
  1153. else if (focusMode != TilemapFocusMode.None)
  1154. {
  1155. // case 946284: Disable Focus if focus mode is set but there is nothing to focus on
  1156. DisableFocus();
  1157. focusMode = TilemapFocusMode.None;
  1158. }
  1159. }
  1160. internal void SetFocusMode(TilemapFocusMode tilemapFocusMode)
  1161. {
  1162. if (tilemapFocusMode != focusMode)
  1163. {
  1164. DisableFocus();
  1165. focusMode = tilemapFocusMode;
  1166. EnableFocus();
  1167. }
  1168. }
  1169. private void DisplayFocusMode(Object displayTarget, SceneView sceneView)
  1170. {
  1171. var labelWidth = EditorGUIUtility.labelWidth;
  1172. var fieldWidth = EditorGUIUtility.fieldWidth;
  1173. EditorGUIUtility.labelWidth = EditorGUIUtility.fieldWidth =
  1174. 0.5f * (EditorGUIUtility.labelWidth + EditorGUIUtility.fieldWidth);
  1175. var newFocus = (TilemapFocusMode)EditorGUILayout.EnumPopup(Styles.focusLabel, focusMode);
  1176. SetFocusMode(newFocus);
  1177. EditorGUIUtility.labelWidth = labelWidth;
  1178. EditorGUIUtility.fieldWidth = fieldWidth;
  1179. }
  1180. private void FilterSingleSceneObjectInScene(int instanceID)
  1181. {
  1182. if (SceneView.lastActiveSceneView != null)
  1183. SceneView.lastActiveSceneView.SetSceneViewFiltering(true);
  1184. StageHandle currentStageHandle = StageUtility.GetCurrentStageHandle();
  1185. if (currentStageHandle.IsValid() && !currentStageHandle.isMainStage)
  1186. {
  1187. HierarchyProperty.FilterSingleSceneObjectInScene(instanceID
  1188. , false
  1189. , new UnityEngine.SceneManagement.Scene[] { currentStageHandle.customScene });
  1190. }
  1191. else
  1192. {
  1193. HierarchyProperty.FilterSingleSceneObject(instanceID, false);
  1194. }
  1195. if (SceneView.lastActiveSceneView != null)
  1196. SceneView.lastActiveSceneView.Repaint();
  1197. }
  1198. private void EnableFocus()
  1199. {
  1200. if (GridPaintingState.scenePaintTarget == null)
  1201. return;
  1202. switch (focusMode)
  1203. {
  1204. case TilemapFocusMode.Tilemap:
  1205. {
  1206. FilterSingleSceneObjectInScene(GridPaintingState.scenePaintTarget.GetInstanceID());
  1207. break;
  1208. }
  1209. case TilemapFocusMode.Grid:
  1210. {
  1211. Tilemap tilemap = GridPaintingState.scenePaintTarget.GetComponent<Tilemap>();
  1212. if (tilemap != null && tilemap.layoutGrid != null)
  1213. {
  1214. FilterSingleSceneObjectInScene(tilemap.layoutGrid.gameObject.GetInstanceID());
  1215. }
  1216. break;
  1217. }
  1218. default:
  1219. {
  1220. break;
  1221. }
  1222. }
  1223. }
  1224. private void DisableFocus()
  1225. {
  1226. if (focusMode == TilemapFocusMode.None)
  1227. return;
  1228. StageHandle currentStageHandle = StageUtility.GetCurrentStageHandle();
  1229. if (currentStageHandle.IsValid() && !currentStageHandle.isMainStage)
  1230. {
  1231. HierarchyProperty.ClearSceneObjectsFilterInScene(new UnityEngine.SceneManagement.Scene[] { currentStageHandle.customScene });
  1232. }
  1233. else
  1234. {
  1235. HierarchyProperty.ClearSceneObjectsFilter();
  1236. }
  1237. if (SceneView.lastActiveSceneView != null)
  1238. {
  1239. SceneView.lastActiveSceneView.SetSceneViewFiltering(false);
  1240. SceneView.lastActiveSceneView.Repaint();
  1241. }
  1242. }
  1243. [MenuItem("Window/2D/Tile Palette", false, 2)]
  1244. public static void OpenTilemapPalette()
  1245. {
  1246. GridPaintPaletteWindow w = GetWindow<GridPaintPaletteWindow>();
  1247. w.titleContent = Styles.tilePalette;
  1248. }
  1249. // TODO: Better way of clearing caches than AssetPostprocessor
  1250. public class AssetProcessor : AssetPostprocessor
  1251. {
  1252. public override int GetPostprocessOrder()
  1253. {
  1254. return int.MaxValue;
  1255. }
  1256. private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
  1257. {
  1258. if (GridPaintingState.savingPalette)
  1259. return;
  1260. foreach (var window in instances)
  1261. {
  1262. window.DelayedResetPreviewInstance();
  1263. }
  1264. }
  1265. }
  1266. public class PaletteAssetModificationProcessor : AssetModificationProcessor
  1267. {
  1268. static void OnWillCreateAsset(string assetName)
  1269. {
  1270. SavePalettesIfRequired(null);
  1271. }
  1272. static string[] OnWillSaveAssets(string[] paths)
  1273. {
  1274. SavePalettesIfRequired(paths);
  1275. return paths;
  1276. }
  1277. static void SavePalettesIfRequired(string[] paths)
  1278. {
  1279. if (GridPaintingState.savingPalette)
  1280. return;
  1281. foreach (var window in instances)
  1282. {
  1283. if (window.clipboardView.isModified)
  1284. {
  1285. window.clipboardView.CheckRevertIfChanged(paths);
  1286. window.clipboardView.SavePaletteIfNecessary();
  1287. window.Repaint();
  1288. }
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }