No Description
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.

PSDImporterEditor.cs 85KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using PhotoshopFile;
  5. using UnityEditor.AssetImporters;
  6. using UnityEditor.U2D.Common;
  7. using UnityEditor.U2D.Sprites;
  8. using UnityEngine;
  9. using UnityEngine.Scripting.APIUpdating;
  10. using UnityEngine.UIElements;
  11. #if ENABLE_2D_ANIMATION
  12. using UnityEngine.U2D.Animation;
  13. using UnityEditor.U2D.Animation;
  14. #endif
  15. namespace UnityEditor.U2D.PSD
  16. {
  17. /// <summary>
  18. /// Inspector for PSDImporter
  19. /// </summary>
  20. [CustomEditor(typeof(PSDImporter))]
  21. [MovedFrom("UnityEditor.Experimental.AssetImporters")]
  22. [CanEditMultipleObjects]
  23. public class PSDImporterEditor : ScriptedImporterEditor, ITexturePlatformSettingsDataProvider
  24. {
  25. struct InspectorGUI
  26. {
  27. public VisualElement container;
  28. public bool needsRepaint;
  29. public Action onUpdate;
  30. public Action onUIActivated;
  31. }
  32. const string kReferencePref = "PSDImporterPreviewShowReference";
  33. SerializedProperty m_TextureType;
  34. SerializedProperty m_TextureShape;
  35. SerializedProperty m_SpriteMode;
  36. SerializedProperty m_SpritePixelsToUnits;
  37. SerializedProperty m_SpriteMeshType;
  38. SerializedProperty m_SpriteExtrude;
  39. SerializedProperty m_Alignment;
  40. SerializedProperty m_SpritePivot;
  41. SerializedProperty m_NPOTScale;
  42. SerializedProperty m_IsReadable;
  43. SerializedProperty m_sRGBTexture;
  44. SerializedProperty m_AlphaSource;
  45. SerializedProperty m_Swizzle;
  46. #if ENABLE_TEXTURE_STREAMING
  47. SerializedProperty m_StreamingMipmaps;
  48. SerializedProperty m_StreamingMipmapsPriority;
  49. #endif
  50. SerializedProperty m_MipMapMode;
  51. SerializedProperty m_EnableMipMap;
  52. SerializedProperty m_FadeOut;
  53. SerializedProperty m_BorderMipMap;
  54. SerializedProperty m_MipMapsPreserveCoverage;
  55. SerializedProperty m_AlphaTestReferenceValue;
  56. SerializedProperty m_MipMapFadeDistanceStart;
  57. SerializedProperty m_MipMapFadeDistanceEnd;
  58. SerializedProperty m_AlphaIsTransparency;
  59. SerializedProperty m_FilterMode;
  60. SerializedProperty m_Aniso;
  61. SerializedProperty m_WrapU;
  62. SerializedProperty m_WrapV;
  63. SerializedProperty m_WrapW;
  64. SerializedProperty m_ConvertToNormalMap;
  65. SerializedProperty m_MosaicLayers;
  66. SerializedProperty m_ImportHiddenLayers;
  67. SerializedProperty m_ResliceFromLayer;
  68. SerializedProperty m_CharacterMode;
  69. SerializedProperty m_DocumentPivot;
  70. SerializedProperty m_DocumentAlignment;
  71. SerializedProperty m_GenerateGOHierarchy;
  72. SerializedProperty m_KeepDupilcateSpriteName;
  73. SerializedProperty m_GeneratePhysicsShape;
  74. SerializedProperty m_LayerMappingOption;
  75. SerializedProperty m_Padding;
  76. SerializedProperty m_SpriteSizeExpand;
  77. SerializedProperty m_SpriteSizeExpandChanged;
  78. #if ENABLE_2D_ANIMATION
  79. SerializedProperty m_PaperDollMode;
  80. SerializedProperty m_SkeletonAssetReferenceID;
  81. #endif
  82. uint m_SpriteSizePreviousSize;
  83. readonly int[] m_FilterModeOptions = (int[])(Enum.GetValues(typeof(FilterMode)));
  84. static readonly int s_SwizzleFieldHash = "SwizzleField".GetHashCode();
  85. bool m_IsPOT = false;
  86. Dictionary<TextureImporterType, Action[]> m_AdvanceInspectorGUI = new Dictionary<TextureImporterType, Action[]>();
  87. int m_PlatformSettingsIndex;
  88. bool m_ShowPerAxisWrapModes = false;
  89. int m_ActiveEditorIndex = 0;
  90. TexturePlatformSettingsHelper m_TexturePlatformSettingsHelper;
  91. PSDImporterEditorFoldOutState m_EditorFoldOutState = new PSDImporterEditorFoldOutState();
  92. InspectorGUI[] m_InspectorUI;
  93. PSDImporter m_CurrentTarget;
  94. bool m_ShowPivot;
  95. PSDGameObjectPreviewData m_PreviewRenderUtility;
  96. PSDImporterLayerManagementMultiColumnTreeView m_LayerManagementTreeView;
  97. IMGUIContainer m_LayerManagementSettingsContainer;
  98. IMGUIContainer m_ApplyRevertGUIVisualElement;
  99. VisualElement m_InspectorSettingsView;
  100. VisualElement m_MultiSupportForLayerManagementNotSupported;
  101. VisualElement m_RootVisualElement;
  102. IMGUIContainer m_ToolbarContainer;
  103. ScrollView m_InspectorScrollView;
  104. int m_LayerTreeViewUpdateCount = 0;
  105. SerializedProperty m_PlatformSettingsArrProp;
  106. SerializedProperty m_Pipeline;
  107. #if ENABLE_2D_ANIMATION
  108. SkeletonAsset m_SkeletonAsset;
  109. #endif
  110. /// <summary>
  111. /// Implementation of AssetImporterEditor.OnEnable
  112. /// </summary>
  113. public override void OnEnable()
  114. {
  115. base.OnEnable();
  116. m_MosaicLayers = serializedObject.FindProperty("m_MosaicLayers");
  117. m_ImportHiddenLayers = serializedObject.FindProperty("m_ImportHiddenLayers");
  118. m_ResliceFromLayer = serializedObject.FindProperty("m_ResliceFromLayer");
  119. m_CharacterMode = serializedObject.FindProperty("m_CharacterMode");
  120. m_DocumentPivot = serializedObject.FindProperty("m_DocumentPivot");
  121. m_DocumentAlignment = serializedObject.FindProperty("m_DocumentAlignment");
  122. m_GenerateGOHierarchy = serializedObject.FindProperty("m_GenerateGOHierarchy");
  123. m_KeepDupilcateSpriteName = serializedObject.FindProperty("m_KeepDupilcateSpriteName");
  124. m_GeneratePhysicsShape = serializedObject.FindProperty("m_GeneratePhysicsShape");
  125. m_LayerMappingOption = serializedObject.FindProperty("m_LayerMappingOption");
  126. m_Padding = serializedObject.FindProperty("m_Padding");
  127. m_SpriteSizeExpand = serializedObject.FindProperty("m_SpriteSizeExpand");
  128. m_SpriteSizePreviousSize = m_SpriteSizeExpand.uintValue;
  129. m_SpriteSizeExpandChanged = serializedObject.FindProperty("m_SpriteSizeExpandChanged");
  130. m_Pipeline = serializedObject.FindProperty("m_Pipeline");
  131. var textureImporterSettingsSP = serializedObject.FindProperty("m_TextureImporterSettings");
  132. m_TextureType = textureImporterSettingsSP.FindPropertyRelative("m_TextureType");
  133. m_TextureShape = textureImporterSettingsSP.FindPropertyRelative("m_TextureShape");
  134. m_ConvertToNormalMap = textureImporterSettingsSP.FindPropertyRelative("m_ConvertToNormalMap");
  135. m_SpriteMode = textureImporterSettingsSP.FindPropertyRelative("m_SpriteMode");
  136. m_SpritePixelsToUnits = textureImporterSettingsSP.FindPropertyRelative("m_SpritePixelsToUnits");
  137. m_SpriteMeshType = textureImporterSettingsSP.FindPropertyRelative("m_SpriteMeshType");
  138. m_SpriteExtrude = textureImporterSettingsSP.FindPropertyRelative("m_SpriteExtrude");
  139. m_Alignment = textureImporterSettingsSP.FindPropertyRelative("m_Alignment");
  140. m_SpritePivot = textureImporterSettingsSP.FindPropertyRelative("m_SpritePivot");
  141. m_NPOTScale = textureImporterSettingsSP.FindPropertyRelative("m_NPOTScale");
  142. m_IsReadable = textureImporterSettingsSP.FindPropertyRelative("m_IsReadable");
  143. m_sRGBTexture = textureImporterSettingsSP.FindPropertyRelative("m_sRGBTexture");
  144. m_AlphaSource = textureImporterSettingsSP.FindPropertyRelative("m_AlphaSource");
  145. #if ENABLE_TEXTURE_STREAMING
  146. m_StreamingMipmaps = textureImporterSettingsSP.FindPropertyRelative("m_StreamingMipmaps");
  147. m_StreamingMipmapsPriority = textureImporterSettingsSP.FindPropertyRelative("m_StreamingMipmapsPriority");
  148. #endif
  149. m_MipMapMode = textureImporterSettingsSP.FindPropertyRelative("m_MipMapMode");
  150. m_EnableMipMap = textureImporterSettingsSP.FindPropertyRelative("m_EnableMipMap");
  151. m_Swizzle = textureImporterSettingsSP.FindPropertyRelative("m_Swizzle");
  152. m_FadeOut = textureImporterSettingsSP.FindPropertyRelative("m_FadeOut");
  153. m_BorderMipMap = textureImporterSettingsSP.FindPropertyRelative("m_BorderMipMap");
  154. m_MipMapsPreserveCoverage = textureImporterSettingsSP.FindPropertyRelative("m_MipMapsPreserveCoverage");
  155. m_AlphaTestReferenceValue = textureImporterSettingsSP.FindPropertyRelative("m_AlphaTestReferenceValue");
  156. m_MipMapFadeDistanceStart = textureImporterSettingsSP.FindPropertyRelative("m_MipMapFadeDistanceStart");
  157. m_MipMapFadeDistanceEnd = textureImporterSettingsSP.FindPropertyRelative("m_MipMapFadeDistanceEnd");
  158. m_AlphaIsTransparency = textureImporterSettingsSP.FindPropertyRelative("m_AlphaIsTransparency");
  159. m_FilterMode = textureImporterSettingsSP.FindPropertyRelative("m_FilterMode");
  160. m_Aniso = textureImporterSettingsSP.FindPropertyRelative("m_Aniso");
  161. m_WrapU = textureImporterSettingsSP.FindPropertyRelative("m_WrapU");
  162. m_WrapV = textureImporterSettingsSP.FindPropertyRelative("m_WrapV");
  163. m_WrapW = textureImporterSettingsSP.FindPropertyRelative("m_WrapW");
  164. m_PlatformSettingsArrProp = extraDataSerializedObject.FindProperty("platformSettings");
  165. foreach (var t in targets)
  166. {
  167. m_IsPOT &= ((PSDImporter)t).isNPOT;
  168. }
  169. #if ENABLE_2D_ANIMATION
  170. m_PaperDollMode = serializedObject.FindProperty("m_PaperDollMode");
  171. m_SkeletonAssetReferenceID = serializedObject.FindProperty("m_SkeletonAssetReferenceID");
  172. var assetPath = AssetDatabase.GUIDToAssetPath(m_SkeletonAssetReferenceID.stringValue);
  173. m_SkeletonAsset = AssetDatabase.LoadAssetAtPath<SkeletonAsset>(assetPath);
  174. #endif
  175. var advanceGUIAction = new Action[]
  176. {
  177. ColorSpaceGUI,
  178. AlphaHandlingGUI,
  179. POTScaleGUI,
  180. ReadableGUI,
  181. MipMapGUI,
  182. SwizzleGUI,
  183. CustomPipelineGUI,
  184. };
  185. m_AdvanceInspectorGUI.Add(TextureImporterType.Sprite, advanceGUIAction);
  186. advanceGUIAction = new Action[]
  187. {
  188. POTScaleGUI,
  189. ReadableGUI,
  190. MipMapGUI,
  191. SwizzleGUI,
  192. CustomPipelineGUI,
  193. };
  194. m_AdvanceInspectorGUI.Add(TextureImporterType.Default, advanceGUIAction);
  195. m_TexturePlatformSettingsHelper = new TexturePlatformSettingsHelper(this);
  196. m_InspectorUI = new []
  197. {
  198. new InspectorGUI()
  199. {
  200. container = new IMGUIContainer(DoInspectorSettings)
  201. {
  202. name = "DoSettingsUI"
  203. },
  204. needsRepaint = false,
  205. },
  206. new InspectorGUI()
  207. {
  208. container = CreateLayerManagementUI(),
  209. needsRepaint = false,
  210. onUpdate = OnLayerManagementUIUpdate,
  211. onUIActivated = OnLayerManagementViewActivated
  212. }
  213. };
  214. m_ActiveEditorIndex = Mathf.Max(EditorPrefs.GetInt(this.GetType().Name + "ActiveEditorIndex", 0), 0);
  215. m_ActiveEditorIndex %= m_InspectorUI.Length;
  216. UpdateLayerTreeView();
  217. m_ShowPivot = EditorPrefs.GetBool(kReferencePref, true);
  218. InitPreview();
  219. }
  220. void CustomPipelineGUI()
  221. {
  222. if (Unsupported.IsDeveloperMode())
  223. {
  224. EditorGUILayout.PropertyField(m_Pipeline);
  225. }
  226. }
  227. /// <summary>
  228. /// Override for AssetImporter.extraDataType
  229. /// </summary>
  230. protected override Type extraDataType => typeof(PSDImporterEditorExternalData);
  231. /// <summary>
  232. /// Override for AssetImporter.InitializeExtraDataInstance
  233. /// </summary>
  234. /// <param name="extraTarget">Target object</param>
  235. /// <param name="targetIndex">Target index</param>
  236. protected override void InitializeExtraDataInstance(UnityEngine.Object extraTarget, int targetIndex)
  237. {
  238. var importer = targets[targetIndex] as PSDImporter;
  239. var extraData = extraTarget as PSDImporterEditorExternalData;
  240. var platformSettingsNeeded = TexturePlatformSettingsHelper.PlatformSettingsNeeded(this);
  241. if (importer != null)
  242. {
  243. extraData.Init(importer, platformSettingsNeeded);
  244. }
  245. }
  246. void OnLayerManagementUIUpdate()
  247. {
  248. if (m_LayerManagementTreeView != null)
  249. m_LayerManagementTreeView.Update();
  250. }
  251. void OnLayerManagementViewActivated()
  252. {
  253. if(serializedObject.isEditingMultipleObjects)
  254. {
  255. m_MultiSupportForLayerManagementNotSupported.SetHiddenFromLayout(false);
  256. m_LayerManagementTreeView.SetHiddenFromLayout(true);
  257. m_LayerManagementSettingsContainer.SetHiddenFromLayout(true);
  258. }
  259. else
  260. {
  261. m_MultiSupportForLayerManagementNotSupported.SetHiddenFromLayout(true);
  262. m_LayerManagementTreeView.SetHiddenFromLayout(false);
  263. m_LayerManagementSettingsContainer.SetHiddenFromLayout(false);
  264. }
  265. }
  266. VisualElement CreateLayerManagementUI()
  267. {
  268. var ve = new VisualElement();
  269. m_MultiSupportForLayerManagementNotSupported = new Label()
  270. {
  271. name = "MultiSupportForLayerManagementNotSupported",
  272. text = styles.multiEditLayerManagementNotSupported.text
  273. };
  274. m_LayerManagementSettingsContainer = new IMGUIContainer(DoLayerManagementUI)
  275. {
  276. name = "LayerManagementSettings",
  277. style =
  278. {
  279. flexGrow = 0,
  280. flexShrink = 0
  281. }
  282. };
  283. m_LayerManagementTreeView = new PSDImporterLayerManagementMultiColumnTreeView(serializedObject)
  284. {
  285. name = "LayerManagementTreeView"
  286. };
  287. m_LayerManagementTreeView.RegisterCallback<AttachToPanelEvent>(OnTreeViewAttachedToPanel);
  288. m_ApplyRevertGUIVisualElement = new IMGUIContainer(ApplyRevertGUIVisualElement)
  289. {
  290. name = "LayerManagementApplyRevertGUI",
  291. style =
  292. {
  293. flexGrow = 0,
  294. flexShrink = 0
  295. }
  296. };
  297. m_ApplyRevertGUIVisualElement.RegisterCallback<GeometryChangedEvent>(OnUpdateLayerTreeViewHeight);
  298. ve.Add(m_MultiSupportForLayerManagementNotSupported);
  299. ve.Add(m_LayerManagementSettingsContainer);
  300. ve.Add(m_LayerManagementTreeView);
  301. ve.Add(m_ApplyRevertGUIVisualElement);
  302. return ve;
  303. }
  304. void OnTreeViewAttachedToPanel(AttachToPanelEvent evt)
  305. {
  306. m_InspectorScrollView = m_RootVisualElement.panel.visualTree.Q<ScrollView>();
  307. m_InspectorScrollView.RegisterCallback<GeometryChangedEvent>(OnUpdateLayerTreeViewHeight);
  308. }
  309. void OnUpdateLayerTreeViewHeight(GeometryChangedEvent g)
  310. {
  311. ++m_LayerTreeViewUpdateCount;
  312. }
  313. void UpdateLayerTreeViewHeight()
  314. {
  315. // var h = m_InspectorScrollView.worldBound.height - (m_LayerManagementTreeView.worldBound.y - m_InspectorScrollView.worldBound.y) - m_ApplyRevertGUIVisualElement.worldBound.height;
  316. // if (h != m_LayerManagementTreeView.style.height)
  317. // {
  318. // m_LayerManagementTreeView.style.height = h;
  319. // m_LayerManagementTreeView.MarkDirtyRepaint();
  320. // }
  321. }
  322. void ApplyRevertGUIVisualElement()
  323. {
  324. serializedObject.ApplyModifiedProperties();
  325. extraDataSerializedObject.ApplyModifiedProperties();
  326. ApplyRevertGUI();
  327. }
  328. void InitPreview()
  329. {
  330. var t = (PSDImporter)target;
  331. var gameObject = AssetDatabase.LoadAssetAtPath<GameObject>(t.assetPath);
  332. if (m_PreviewRenderUtility != null)
  333. {
  334. m_PreviewRenderUtility.Dispose();
  335. m_PreviewRenderUtility = null;
  336. }
  337. if (gameObject != null)
  338. {
  339. var documentSize = new Rect(0, 0, t.importData.documentSize.x / t.pixelsPerUnit, t.importData.documentSize.y / t.pixelsPerUnit);
  340. var pivot = (Vector3)ImportUtilities.GetPivotPoint(documentSize, (SpriteAlignment)m_DocumentAlignment.intValue, m_DocumentPivot.vector2Value);
  341. documentSize.x = -pivot.x;
  342. documentSize.y = -pivot.y;
  343. m_PreviewRenderUtility = new PSDGameObjectPreviewData(gameObject, m_ShowPivot, documentSize);
  344. }
  345. }
  346. /// <summary>
  347. /// Implmentation of AssetImporterEditor.OnDisable
  348. /// </summary>
  349. public override void OnDisable()
  350. {
  351. base.OnDisable();
  352. if (m_PreviewRenderUtility != null)
  353. {
  354. m_PreviewRenderUtility.Dispose();
  355. m_PreviewRenderUtility = null;
  356. }
  357. if(m_RootVisualElement != null)
  358. m_RootVisualElement.Clear();
  359. if(m_LayerManagementTreeView != null)
  360. m_LayerManagementTreeView.UnregisterCallback<AttachToPanelEvent>(OnTreeViewAttachedToPanel);
  361. if(m_ApplyRevertGUIVisualElement != null)
  362. m_ApplyRevertGUIVisualElement.UnregisterCallback<GeometryChangedEvent>(OnUpdateLayerTreeViewHeight);
  363. if(m_InspectorScrollView != null)
  364. m_InspectorScrollView.UnregisterCallback<GeometryChangedEvent>(OnUpdateLayerTreeViewHeight);
  365. }
  366. void UpdateLayerTreeView()
  367. {
  368. if (!ReferenceEquals(m_CurrentTarget, target))
  369. {
  370. m_CurrentTarget = (PSDImporter)target;
  371. m_LayerManagementTreeView.UpdateTreeView(serializedObject);
  372. }
  373. }
  374. /// <summary>
  375. /// Override from AssetImporterEditor.RequiresConstantRepaint
  376. /// </summary>
  377. /// <returns>Returns true when in Layer Management tab for UI feedback update, false otherwise.</returns>
  378. public override bool RequiresConstantRepaint()
  379. {
  380. return m_InspectorUI[m_ActiveEditorIndex].needsRepaint;
  381. }
  382. void DoInspectorSettings()
  383. {
  384. serializedObject.Update();
  385. extraDataSerializedObject.Update();
  386. DoSettingsUI();
  387. ApplyRevertGUIVisualElement();
  388. }
  389. /// <summary>
  390. /// Implementation of virtual method CreateInspectorGUI.
  391. /// </summary>
  392. /// <returns>VisualElement container for Inspector visual.</returns>
  393. public override VisualElement CreateInspectorGUI()
  394. {
  395. var styleSheet = EditorGUIUtility.Load("packages/com.unity.2d.psdimporter/Editor/Assets/UI/PSDImporterStylesheet.uss") as StyleSheet;
  396. m_RootVisualElement = new VisualElement()
  397. {
  398. name = "Root"
  399. };
  400. if(EditorGUIUtility.isProSkin)
  401. m_RootVisualElement.AddToClassList("psdimporter-editor-dark");
  402. else
  403. m_RootVisualElement.AddToClassList("psdimporter-editor-light");
  404. m_RootVisualElement.styleSheets.Add(styleSheet);
  405. m_ToolbarContainer = new IMGUIContainer(DoToolBarIMGUI)
  406. {
  407. name = "Toolbar"
  408. };
  409. m_InspectorSettingsView = new VisualElement()
  410. {
  411. name = "InspectorSettings"
  412. };
  413. m_RootVisualElement.Add(m_ToolbarContainer);
  414. m_RootVisualElement.Add(m_InspectorSettingsView);
  415. m_RootVisualElement.schedule.Execute(VisualElementUpdate);
  416. ShowInspectorTab(m_ActiveEditorIndex);
  417. return m_RootVisualElement;
  418. }
  419. void VisualElementUpdate()
  420. {
  421. if (m_LayerTreeViewUpdateCount > 1)
  422. UpdateLayerTreeViewHeight();
  423. m_LayerTreeViewUpdateCount = 0;
  424. serializedObject.Update();
  425. extraDataSerializedObject.Update();
  426. try
  427. {
  428. if(m_InspectorUI[m_ActiveEditorIndex].onUpdate != null)
  429. m_InspectorUI[m_ActiveEditorIndex].onUpdate.Invoke();
  430. }
  431. catch (Exception e)
  432. {
  433. Debug.Log("Update:"+e);
  434. }
  435. serializedObject.ApplyModifiedProperties();
  436. extraDataSerializedObject.ApplyModifiedProperties();
  437. m_RootVisualElement.schedule.Execute(VisualElementUpdate);
  438. }
  439. void ShowInspectorTab(int tab)
  440. {
  441. m_InspectorSettingsView.Clear();
  442. m_InspectorSettingsView.Add(m_InspectorUI[tab].container);
  443. m_InspectorUI[tab].onUIActivated?.Invoke();
  444. }
  445. void DoToolBarIMGUI()
  446. {
  447. GUILayout.Space(5);
  448. using (new GUILayout.HorizontalScope())
  449. {
  450. GUILayout.FlexibleSpace();
  451. using (var check = new EditorGUI.ChangeCheckScope())
  452. {
  453. m_ActiveEditorIndex = GUILayout.Toolbar(m_ActiveEditorIndex, styles.editorTabNames, "LargeButton", GUI.ToolbarButtonSize.FitToContents);
  454. if (check.changed)
  455. {
  456. EditorPrefs.SetInt(GetType().Name + "ActiveEditorIndex", m_ActiveEditorIndex);
  457. ShowInspectorTab(m_ActiveEditorIndex);
  458. }
  459. }
  460. GUILayout.FlexibleSpace();
  461. }
  462. GUILayout.Space(5);
  463. }
  464. void DoLayerManagementUI()
  465. {
  466. EditorGUILayout.PropertyField(m_ImportHiddenLayers, styles.importHiddenLayer);
  467. var headerRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.Height(EditorGUIUtility.singleLineHeight));
  468. if (Event.current.type == EventType.Repaint)
  469. {
  470. GUIStyle header = "RL Header";
  471. headerRect.height = EditorGUIUtility.singleLineHeight;
  472. header.Draw(headerRect, false, false, false, false);
  473. GUI.Label(headerRect, "Layer Import Settings");
  474. }
  475. }
  476. void DoSettingsUI()
  477. {
  478. if (m_EditorFoldOutState.DoGeneralUI(styles.generalHeaderText))
  479. {
  480. EditorGUI.showMixedValue = m_TextureType.hasMultipleDifferentValues;
  481. m_TextureType.intValue = EditorGUILayout.IntPopup(styles.textureTypeTitle, m_TextureType.intValue, styles.textureTypeOptions, styles.textureTypeValues);
  482. EditorGUI.showMixedValue = false;
  483. switch ((TextureImporterType)m_TextureType.intValue)
  484. {
  485. case TextureImporterType.Sprite:
  486. DoSpriteTextureTypeInspector();
  487. break;
  488. case TextureImporterType.Default:
  489. DoTextureDefaultTextureTypeInspector();
  490. break;
  491. default:
  492. m_TextureType.intValue = (int)TextureImporterType.Default;
  493. break;
  494. }
  495. GUILayout.Space(5);
  496. }
  497. if ((TextureImporterType)m_TextureType.intValue == TextureImporterType.Sprite)
  498. DoSpriteInspector();
  499. CommonTextureSettingsGUI();
  500. DoPlatformSettings();
  501. DoAdvanceInspector();
  502. }
  503. void MainRigPropertyField()
  504. {
  505. #if ENABLE_2D_ANIMATION
  506. EditorGUI.BeginChangeCheck();
  507. m_SkeletonAsset = EditorGUILayout.ObjectField(styles.mainSkeletonName, m_SkeletonAsset, typeof(SkeletonAsset), false) as SkeletonAsset;
  508. if (EditorGUI.EndChangeCheck())
  509. {
  510. var referencePath = AssetDatabase.GetAssetPath(m_SkeletonAsset);
  511. if (referencePath == ((AssetImporter) target).assetPath)
  512. m_SkeletonAssetReferenceID.stringValue = "";
  513. else
  514. m_SkeletonAssetReferenceID.stringValue = AssetDatabase.GUIDFromAssetPath(referencePath).ToString();
  515. }
  516. #endif
  517. }
  518. /// <summary>
  519. /// Implementation of AssetImporterEditor.Apply
  520. /// </summary>
  521. protected override void Apply()
  522. {
  523. // Send analytics first while the SerializedObject is still valid
  524. FileStream fileStream = new FileStream(((AssetImporter)target).assetPath, FileMode.Open, FileAccess.Read);
  525. var doc = PaintDotNet.Data.PhotoshopFileType.PsdLoad.Load(fileStream, ELoadFlag.Header | ELoadFlag.ColorMode);
  526. PSDApplyEvent evt = new PSDApplyEvent()
  527. {
  528. instance_id = target.GetInstanceID(),
  529. texture_type = m_TextureType.intValue,
  530. sprite_mode = m_SpriteMode.intValue,
  531. mosaic_layer = m_MosaicLayers.boolValue,
  532. import_hidden_layer = m_ImportHiddenLayers.boolValue,
  533. character_mode = m_CharacterMode.boolValue,
  534. generate_go_hierarchy = m_GenerateGOHierarchy.boolValue,
  535. reslice_from_layer = m_ResliceFromLayer.boolValue,
  536. is_character_rigged = IsCharacterRigged(),
  537. is_psd = IsPSD(doc),
  538. color_mode = FileColorMode(doc)
  539. };
  540. doc.Cleanup();
  541. AnalyticFactory.analytics.SendApplyEvent(evt);
  542. InternalEditorBridge.ApplySpriteEditorWindow();
  543. base.Apply();
  544. PSDImportPostProcessor.currentApplyAssetPath = ((PSDImporter) target).assetPath;
  545. if (m_PreviewRenderUtility != null)
  546. {
  547. m_PreviewRenderUtility.Dispose();
  548. m_PreviewRenderUtility = null;
  549. }
  550. }
  551. static bool IsPSD(PsdFile doc)
  552. {
  553. return !doc.IsLargeDocument;
  554. }
  555. static PsdColorMode FileColorMode(PsdFile doc)
  556. {
  557. return doc.ColorMode;
  558. }
  559. bool IsCharacterRigged()
  560. {
  561. #if ENABLE_2D_ANIMATION
  562. var importer = target as PSDImporter;
  563. if (importer != null)
  564. {
  565. var characterProvider = importer.GetDataProvider<ICharacterDataProvider>();
  566. var meshDataProvider = importer.GetDataProvider<ISpriteMeshDataProvider>();
  567. if (characterProvider != null && meshDataProvider != null)
  568. {
  569. var character = characterProvider.GetCharacterData();
  570. foreach (var parts in character.parts)
  571. {
  572. var vert = meshDataProvider.GetVertices(new GUID(parts.spriteId));
  573. var indices = meshDataProvider.GetIndices(new GUID(parts.spriteId));
  574. if (parts.bones != null && parts.bones.Length > 0 &&
  575. vert != null && vert.Length > 0 &&
  576. indices != null && indices.Length > 0)
  577. return true;
  578. }
  579. }
  580. }
  581. #endif
  582. return false;
  583. }
  584. void DoPlatformSettings()
  585. {
  586. if (m_EditorFoldOutState.DoPlatformSettingsUI(styles.platformSettingsHeaderText))
  587. {
  588. GUILayout.Space(5);
  589. m_TexturePlatformSettingsHelper.ShowPlatformSpecificSettings();
  590. GUILayout.Space(5);
  591. }
  592. }
  593. void DoAdvanceInspector()
  594. {
  595. if (!m_TextureType.hasMultipleDifferentValues)
  596. {
  597. if (m_AdvanceInspectorGUI.ContainsKey((TextureImporterType)m_TextureType.intValue))
  598. {
  599. if (m_EditorFoldOutState.DoAdvancedUI(styles.advancedHeaderText))
  600. {
  601. foreach (var action in m_AdvanceInspectorGUI[(TextureImporterType)m_TextureType.intValue])
  602. {
  603. action();
  604. }
  605. }
  606. }
  607. }
  608. }
  609. void CommonTextureSettingsGUI()
  610. {
  611. if (m_EditorFoldOutState.DoTextureUI(styles.textureHeaderText))
  612. {
  613. EditorGUI.BeginChangeCheck();
  614. // Wrap mode
  615. bool isVolume = false;
  616. WrapModePopup(m_WrapU, m_WrapV, m_WrapW, isVolume, ref m_ShowPerAxisWrapModes);
  617. // Display warning about repeat wrap mode on restricted npot emulation
  618. if (m_NPOTScale.intValue == (int)TextureImporterNPOTScale.None &&
  619. (m_WrapU.intValue == (int)TextureWrapMode.Repeat || m_WrapV.intValue == (int)TextureWrapMode.Repeat) &&
  620. !InternalEditorBridge.DoesHardwareSupportsFullNPOT())
  621. {
  622. bool displayWarning = false;
  623. foreach (var target in targets)
  624. {
  625. var imp = (PSDImporter)target;
  626. int w = imp.textureActualWidth;
  627. int h = imp.textureActualHeight;
  628. if (!Mathf.IsPowerOfTwo(w) || !Mathf.IsPowerOfTwo(h))
  629. {
  630. displayWarning = true;
  631. break;
  632. }
  633. }
  634. if (displayWarning)
  635. {
  636. EditorGUILayout.HelpBox(styles.warpNotSupportWarning.text, MessageType.Warning, true);
  637. }
  638. }
  639. // Filter mode
  640. EditorGUI.showMixedValue = m_FilterMode.hasMultipleDifferentValues;
  641. FilterMode filter = (FilterMode)m_FilterMode.intValue;
  642. if ((int)filter == -1)
  643. {
  644. if (m_FadeOut.intValue > 0 || m_ConvertToNormalMap.intValue > 0)
  645. filter = FilterMode.Trilinear;
  646. else
  647. filter = FilterMode.Bilinear;
  648. }
  649. filter = (FilterMode)EditorGUILayout.IntPopup(styles.filterMode, (int)filter, styles.filterModeOptions, m_FilterModeOptions);
  650. EditorGUI.showMixedValue = false;
  651. if (EditorGUI.EndChangeCheck())
  652. m_FilterMode.intValue = (int)filter;
  653. // Aniso
  654. bool showAniso = (FilterMode)m_FilterMode.intValue != FilterMode.Point
  655. && m_EnableMipMap.intValue > 0
  656. && (TextureImporterShape)m_TextureShape.intValue != TextureImporterShape.TextureCube;
  657. using (new EditorGUI.DisabledScope(!showAniso))
  658. {
  659. EditorGUI.BeginChangeCheck();
  660. EditorGUI.showMixedValue = m_Aniso.hasMultipleDifferentValues;
  661. int aniso = m_Aniso.intValue;
  662. if (aniso == -1)
  663. aniso = 1;
  664. aniso = EditorGUILayout.IntSlider(styles.anisoLevelLabel, aniso, 0, 16);
  665. EditorGUI.showMixedValue = false;
  666. if (EditorGUI.EndChangeCheck())
  667. m_Aniso.intValue = aniso;
  668. if (aniso > 1)
  669. {
  670. if (QualitySettings.anisotropicFiltering == AnisotropicFiltering.Disable)
  671. EditorGUILayout.HelpBox(styles.anisotropicDisableInfo.text, MessageType.Info);
  672. else if (QualitySettings.anisotropicFiltering == AnisotropicFiltering.ForceEnable)
  673. EditorGUILayout.HelpBox(styles.anisotropicForceEnableInfo.text, MessageType.Info);
  674. }
  675. }
  676. GUILayout.Space(5);
  677. }
  678. }
  679. private static bool IsAnyTextureObjectUsingPerAxisWrapMode(UnityEngine.Object[] objects, bool isVolumeTexture)
  680. {
  681. foreach (var o in objects)
  682. {
  683. int u = 0, v = 0, w = 0;
  684. // the objects can be Textures themselves, or texture-related importers
  685. if (o is Texture)
  686. {
  687. var ti = (Texture)o;
  688. u = (int)ti.wrapModeU;
  689. v = (int)ti.wrapModeV;
  690. w = (int)ti.wrapModeW;
  691. }
  692. if (o is TextureImporter)
  693. {
  694. var ti = (TextureImporter)o;
  695. u = (int)ti.wrapModeU;
  696. v = (int)ti.wrapModeV;
  697. w = (int)ti.wrapModeW;
  698. }
  699. if (o is IHVImageFormatImporter)
  700. {
  701. var ti = (IHVImageFormatImporter)o;
  702. u = (int)ti.wrapModeU;
  703. v = (int)ti.wrapModeV;
  704. w = (int)ti.wrapModeW;
  705. }
  706. u = Mathf.Max(0, u);
  707. v = Mathf.Max(0, v);
  708. w = Mathf.Max(0, w);
  709. if (u != v)
  710. {
  711. return true;
  712. }
  713. if (isVolumeTexture)
  714. {
  715. if (u != w || v != w)
  716. {
  717. return true;
  718. }
  719. }
  720. }
  721. return false;
  722. }
  723. // showPerAxisWrapModes is state of whether "Per-Axis" mode should be active in the main dropdown.
  724. // It is set automatically if wrap modes in UVW are different, or if user explicitly picks "Per-Axis" option -- when that one is picked,
  725. // then it should stay true even if UVW wrap modes will initially be the same.
  726. //
  727. // Note: W wrapping mode is only shown when isVolumeTexture is true.
  728. static void WrapModePopup(SerializedProperty wrapU, SerializedProperty wrapV, SerializedProperty wrapW, bool isVolumeTexture, ref bool showPerAxisWrapModes)
  729. {
  730. // In texture importer settings, serialized properties for things like wrap modes can contain -1;
  731. // that seems to indicate "use defaults, user has not changed them to anything" but not totally sure.
  732. // Show them as Repeat wrap modes in the popups.
  733. var wu = (TextureWrapMode)Mathf.Max(wrapU.intValue, 0);
  734. var wv = (TextureWrapMode)Mathf.Max(wrapV.intValue, 0);
  735. var ww = (TextureWrapMode)Mathf.Max(wrapW.intValue, 0);
  736. // automatically go into per-axis mode if values are already different
  737. if (wu != wv)
  738. showPerAxisWrapModes = true;
  739. if (isVolumeTexture)
  740. {
  741. if (wu != ww || wv != ww)
  742. showPerAxisWrapModes = true;
  743. }
  744. // It's not possible to determine whether any single texture in the whole selection is using per-axis wrap modes
  745. // just from SerializedProperty values. They can only tell if "some values in whole selection are different" (e.g.
  746. // wrap value on U axis is not the same among all textures), and can return value of "some" object in the selection
  747. // (typically based on object loading order). So in order for more intuitive behavior with multi-selection,
  748. // we go over the actual objects when there's >1 object selected and some wrap modes are different.
  749. if (!showPerAxisWrapModes)
  750. {
  751. if (wrapU.hasMultipleDifferentValues || wrapV.hasMultipleDifferentValues || (isVolumeTexture && wrapW.hasMultipleDifferentValues))
  752. {
  753. if (IsAnyTextureObjectUsingPerAxisWrapMode(wrapU.serializedObject.targetObjects, isVolumeTexture))
  754. {
  755. showPerAxisWrapModes = true;
  756. }
  757. }
  758. }
  759. int value = showPerAxisWrapModes ? -1 : (int)wu;
  760. // main wrap mode popup
  761. EditorGUI.BeginChangeCheck();
  762. EditorGUI.showMixedValue = !showPerAxisWrapModes && (wrapU.hasMultipleDifferentValues || wrapV.hasMultipleDifferentValues || (isVolumeTexture && wrapW.hasMultipleDifferentValues));
  763. value = EditorGUILayout.IntPopup(styles.wrapModeLabel, value, styles.wrapModeContents, styles.wrapModeValues);
  764. if (EditorGUI.EndChangeCheck() && value != -1)
  765. {
  766. // assign the same wrap mode to all axes, and hide per-axis popups
  767. wrapU.intValue = value;
  768. wrapV.intValue = value;
  769. wrapW.intValue = value;
  770. showPerAxisWrapModes = false;
  771. }
  772. // show per-axis popups if needed
  773. if (value == -1)
  774. {
  775. showPerAxisWrapModes = true;
  776. EditorGUI.indentLevel++;
  777. WrapModeAxisPopup(styles.wrapU, wrapU);
  778. WrapModeAxisPopup(styles.wrapV, wrapV);
  779. if (isVolumeTexture)
  780. {
  781. WrapModeAxisPopup(styles.wrapW, wrapW);
  782. }
  783. EditorGUI.indentLevel--;
  784. }
  785. EditorGUI.showMixedValue = false;
  786. }
  787. static void WrapModeAxisPopup(GUIContent label, SerializedProperty wrapProperty)
  788. {
  789. // In texture importer settings, serialized properties for wrap modes can contain -1, which means "use default".
  790. var wrap = (TextureWrapMode)Mathf.Max(wrapProperty.intValue, 0);
  791. Rect rect = EditorGUILayout.GetControlRect();
  792. EditorGUI.BeginChangeCheck();
  793. EditorGUI.BeginProperty(rect, label, wrapProperty);
  794. wrap = (TextureWrapMode)EditorGUI.EnumPopup(rect, label, wrap);
  795. EditorGUI.EndProperty();
  796. if (EditorGUI.EndChangeCheck())
  797. {
  798. wrapProperty.intValue = (int)wrap;
  799. }
  800. }
  801. void DoWrapModePopup()
  802. {
  803. WrapModePopup(m_WrapU, m_WrapV, m_WrapW, IsVolume(), ref m_ShowPerAxisWrapModes);
  804. }
  805. bool IsVolume()
  806. {
  807. var t = target as Texture;
  808. return t != null && t.dimension == UnityEngine.Rendering.TextureDimension.Tex3D;
  809. }
  810. void DoSpriteTextureTypeInspector()
  811. {
  812. EditorGUI.BeginChangeCheck();
  813. EditorGUILayout.IntPopup(m_SpriteMode, styles.spriteModeOptions, new[] { 1, 2, 3 }, styles.spriteMode);
  814. // Ensure that PropertyField focus will be cleared when we change spriteMode.
  815. if (EditorGUI.EndChangeCheck())
  816. {
  817. GUIUtility.keyboardControl = 0;
  818. }
  819. // Show generic attributes
  820. using (new EditorGUI.DisabledScope(m_SpriteMode.intValue == 0))
  821. {
  822. EditorGUILayout.PropertyField(m_SpritePixelsToUnits, styles.spritePixelsPerUnit);
  823. if (m_SpriteMode.intValue != (int)SpriteImportMode.Polygon && !m_SpriteMode.hasMultipleDifferentValues)
  824. {
  825. EditorGUILayout.IntPopup(m_SpriteMeshType, styles.spriteMeshTypeOptions, new[] { 0, 1 }, styles.spriteMeshType);
  826. }
  827. EditorGUILayout.IntSlider(m_SpriteExtrude, 0, 32, styles.spriteExtrude);
  828. if (m_SpriteMode.intValue == 1)
  829. {
  830. EditorGUILayout.IntPopup(m_Alignment, styles.spriteAlignmentOptions, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, styles.spriteAlignment);
  831. if (m_Alignment.intValue == (int)SpriteAlignment.Custom)
  832. {
  833. GUILayout.BeginHorizontal();
  834. EditorGUILayout.PropertyField(m_SpritePivot, new GUIContent());
  835. GUILayout.EndHorizontal();
  836. }
  837. }
  838. }
  839. EditorGUILayout.PropertyField(m_GeneratePhysicsShape, styles.generatePhysicsShape);
  840. using (new EditorGUI.DisabledScope(!m_MosaicLayers.boolValue))
  841. {
  842. EditorGUILayout.PropertyField(m_ResliceFromLayer, styles.resliceFromLayer);
  843. if (m_ResliceFromLayer.boolValue)
  844. {
  845. EditorGUILayout.HelpBox(styles.resliceFromLayerWarning.text, MessageType.Info, true);
  846. }
  847. }
  848. DoOpenSpriteEditorButton();
  849. }
  850. void DoSpriteInspector()
  851. {
  852. if (m_EditorFoldOutState.DoLayerImportUI(styles.layerImportHeaderText))
  853. {
  854. EditorGUILayout.PropertyField(m_ImportHiddenLayers, styles.importHiddenLayer);
  855. using (new EditorGUI.DisabledScope(m_SpriteMode.intValue != (int)SpriteImportMode.Multiple || m_SpriteMode.hasMultipleDifferentValues))
  856. {
  857. using (new EditorGUI.DisabledScope(m_MosaicLayers.boolValue == false))
  858. {
  859. EditorGUILayout.PropertyField(m_KeepDupilcateSpriteName, styles.keepDuplicateSpriteName);
  860. using (new EditorGUI.DisabledScope(!m_MosaicLayers.boolValue || !m_CharacterMode.boolValue))
  861. {
  862. EditorGUILayout.PropertyField(m_GenerateGOHierarchy, styles.layerGroupLabel);
  863. }
  864. EditorGUILayout.IntPopup(m_LayerMappingOption, styles.layerMappingOption, styles.layerMappingOptionValues, styles.layerMapping);
  865. }
  866. var boolToInt = !m_MosaicLayers.boolValue ? 1 : 0;
  867. EditorGUI.BeginChangeCheck();
  868. boolToInt = EditorGUILayout.IntPopup(styles.mosaicLayers, boolToInt, styles.importModeOptions, styles.falseTrueOptionValue);
  869. if (EditorGUI.EndChangeCheck())
  870. m_MosaicLayers.boolValue = boolToInt != 1;
  871. using (new EditorGUI.DisabledScope(m_MosaicLayers.boolValue == false))
  872. {
  873. EditorGUILayout.IntSlider(m_Padding, 0, 32, styles.padding);
  874. EditorGUILayout.PropertyField(m_SpriteSizeExpand, styles.spriteSizeExpand);
  875. }
  876. }
  877. GUILayout.Space(5);
  878. }
  879. #if ENABLE_2D_ANIMATION
  880. if (m_EditorFoldOutState.DoCharacterRigUI(styles.characterRigHeaderText))
  881. {
  882. using (new EditorGUI.DisabledScope(m_SpriteMode.intValue != (int)SpriteImportMode.Multiple || m_SpriteMode.hasMultipleDifferentValues || m_MosaicLayers.boolValue == false))
  883. {
  884. EditorGUILayout.PropertyField(m_CharacterMode, styles.characterMode);
  885. using (new EditorGUI.DisabledScope(!m_CharacterMode.boolValue))
  886. {
  887. MainRigPropertyField();
  888. EditorGUILayout.IntPopup(m_DocumentAlignment, styles.spriteAlignmentOptions, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, styles.characterAlignment);
  889. if (m_DocumentAlignment.intValue == (int)SpriteAlignment.Custom)
  890. {
  891. GUILayout.BeginHorizontal();
  892. GUILayout.Space(EditorGUIUtility.labelWidth);
  893. EditorGUILayout.PropertyField(m_DocumentPivot, new GUIContent());
  894. GUILayout.EndHorizontal();
  895. }
  896. }
  897. }
  898. GUILayout.Space(5);
  899. //EditorGUILayout.PropertyField(m_PaperDollMode, s_Styles.paperDollMode);
  900. }
  901. #endif
  902. }
  903. void DoOpenSpriteEditorButton()
  904. {
  905. using (new EditorGUI.DisabledScope(targets.Length != 1))
  906. {
  907. GUILayout.BeginHorizontal();
  908. GUILayout.FlexibleSpace();
  909. if (GUILayout.Button(styles.spriteEditorButtonLabel))
  910. {
  911. if (HasModified())
  912. {
  913. // To ensure Sprite Editor Window to have the latest texture import setting,
  914. // We must applied those modified values first.
  915. string dialogText = string.Format(styles.unappliedSettingsDialogContent.text, ((AssetImporter)target).assetPath);
  916. if (EditorUtility.DisplayDialog(styles.unappliedSettingsDialogTitle.text,
  917. dialogText, styles.applyButtonLabel.text, styles.cancelButtonLabel.text))
  918. {
  919. SaveChanges();
  920. InternalEditorBridge.ShowSpriteEditorWindow(this.assetTarget);
  921. // We reimported the asset which destroyed the editor, so we can't keep running the UI here.
  922. GUIUtility.ExitGUI();
  923. }
  924. }
  925. else
  926. {
  927. InternalEditorBridge.ShowSpriteEditorWindow(this.assetTarget);
  928. }
  929. }
  930. GUILayout.EndHorizontal();
  931. }
  932. }
  933. /// <summary>
  934. /// Implementation of AssetImporterEditor.SaveChanges.
  935. /// </summary>
  936. public override void SaveChanges()
  937. {
  938. if (m_SpriteSizePreviousSize != m_SpriteSizeExpand.uintValue)
  939. {
  940. m_SpriteSizeExpandChanged.boolValue = true;
  941. serializedObject.ApplyModifiedProperties();
  942. extraDataSerializedObject.ApplyModifiedProperties();
  943. m_SpriteSizePreviousSize = m_SpriteSizeExpand.uintValue;
  944. }
  945. ApplyTexturePlatformSettings();
  946. serializedObject.ApplyModifiedProperties();
  947. extraDataSerializedObject.ApplyModifiedProperties();
  948. base.SaveChanges();
  949. }
  950. void ApplyTexturePlatformSettings()
  951. {
  952. for(int i = 0; i< targets.Length && i < extraDataTargets.Length; ++i)
  953. {
  954. var psdImporter = (PSDImporter)targets[i];
  955. var externalData = (PSDImporterEditorExternalData)extraDataTargets[i];
  956. foreach (var ps in externalData.platformSettings)
  957. {
  958. psdImporter.SetImporterPlatformSettings(ps);
  959. }
  960. }
  961. }
  962. void DoTextureDefaultTextureTypeInspector()
  963. {
  964. ColorSpaceGUI();
  965. AlphaHandlingGUI();
  966. }
  967. void ColorSpaceGUI()
  968. {
  969. ToggleFromInt(m_sRGBTexture, styles.sRGBTexture);
  970. }
  971. void POTScaleGUI()
  972. {
  973. using (new EditorGUI.DisabledScope(m_IsPOT || m_TextureType.intValue == (int)TextureImporterType.Sprite))
  974. {
  975. EnumPopup(m_NPOTScale, typeof(TextureImporterNPOTScale), styles.npot);
  976. }
  977. }
  978. void ReadableGUI()
  979. {
  980. ToggleFromInt(m_IsReadable, styles.readWrite);
  981. }
  982. void AlphaHandlingGUI()
  983. {
  984. EditorGUI.showMixedValue = m_AlphaSource.hasMultipleDifferentValues;
  985. EditorGUI.BeginChangeCheck();
  986. int newAlphaUsage = EditorGUILayout.IntPopup(styles.alphaSource, m_AlphaSource.intValue, styles.alphaSourceOptions, styles.alphaSourceValues);
  987. EditorGUI.showMixedValue = false;
  988. if (EditorGUI.EndChangeCheck())
  989. {
  990. m_AlphaSource.intValue = newAlphaUsage;
  991. }
  992. bool showAlphaIsTransparency = (TextureImporterAlphaSource)m_AlphaSource.intValue != TextureImporterAlphaSource.None;
  993. using (new EditorGUI.DisabledScope(!showAlphaIsTransparency))
  994. {
  995. ToggleFromInt(m_AlphaIsTransparency, styles.alphaIsTransparency);
  996. }
  997. }
  998. void MipMapGUI()
  999. {
  1000. ToggleFromInt(m_EnableMipMap, styles.generateMipMaps);
  1001. if (m_EnableMipMap.boolValue && !m_EnableMipMap.hasMultipleDifferentValues)
  1002. {
  1003. EditorGUI.indentLevel++;
  1004. ToggleFromInt(m_BorderMipMap, styles.borderMipMaps);
  1005. #if ENABLE_TEXTURE_STREAMING
  1006. ToggleFromInt(m_StreamingMipmaps, styles.streamingMipMaps);
  1007. if (m_StreamingMipmaps.boolValue && !m_StreamingMipmaps.hasMultipleDifferentValues)
  1008. {
  1009. EditorGUI.indentLevel++;
  1010. EditorGUI.BeginChangeCheck();
  1011. EditorGUILayout.PropertyField(m_StreamingMipmapsPriority, styles.streamingMipmapsPriority);
  1012. if (EditorGUI.EndChangeCheck())
  1013. {
  1014. m_StreamingMipmapsPriority.intValue = Mathf.Clamp(m_StreamingMipmapsPriority.intValue, -128, 127);
  1015. }
  1016. EditorGUI.indentLevel--;
  1017. }
  1018. #endif
  1019. m_MipMapMode.intValue = EditorGUILayout.Popup(styles.mipMapFilter, m_MipMapMode.intValue, styles.mipMapFilterOptions);
  1020. ToggleFromInt(m_MipMapsPreserveCoverage, styles.mipMapsPreserveCoverage);
  1021. if (m_MipMapsPreserveCoverage.intValue != 0 && !m_MipMapsPreserveCoverage.hasMultipleDifferentValues)
  1022. {
  1023. EditorGUI.indentLevel++;
  1024. EditorGUILayout.PropertyField(m_AlphaTestReferenceValue, styles.alphaTestReferenceValue);
  1025. EditorGUI.indentLevel--;
  1026. }
  1027. // Mipmap fadeout
  1028. ToggleFromInt(m_FadeOut, styles.mipmapFadeOutToggle);
  1029. if (m_FadeOut.intValue > 0)
  1030. {
  1031. EditorGUI.indentLevel++;
  1032. EditorGUI.BeginChangeCheck();
  1033. float min = m_MipMapFadeDistanceStart.intValue;
  1034. float max = m_MipMapFadeDistanceEnd.intValue;
  1035. EditorGUILayout.MinMaxSlider(styles.mipmapFadeOut, ref min, ref max, 0, 10);
  1036. if (EditorGUI.EndChangeCheck())
  1037. {
  1038. m_MipMapFadeDistanceStart.intValue = Mathf.RoundToInt(min);
  1039. m_MipMapFadeDistanceEnd.intValue = Mathf.RoundToInt(max);
  1040. }
  1041. EditorGUI.indentLevel--;
  1042. }
  1043. EditorGUI.indentLevel--;
  1044. }
  1045. }
  1046. void ToggleFromInt(SerializedProperty property, GUIContent label)
  1047. {
  1048. EditorGUI.BeginChangeCheck();
  1049. EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
  1050. int value = EditorGUILayout.Toggle(label, property.intValue > 0) ? 1 : 0;
  1051. EditorGUI.showMixedValue = false;
  1052. if (EditorGUI.EndChangeCheck())
  1053. property.intValue = value;
  1054. }
  1055. void EnumPopup(SerializedProperty property, System.Type type, GUIContent label)
  1056. {
  1057. EditorGUILayout.IntPopup(label.text, property.intValue,
  1058. System.Enum.GetNames(type),
  1059. System.Enum.GetValues(type) as int[]);
  1060. }
  1061. void ExportMosaicTexture()
  1062. {
  1063. var assetPath = ((AssetImporter)target).assetPath;
  1064. var texture2D = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
  1065. if (texture2D == null)
  1066. return;
  1067. if (!texture2D.isReadable)
  1068. texture2D = InternalEditorBridge.CreateTemporaryDuplicate(texture2D, texture2D.width, texture2D.height);
  1069. var pixelData = texture2D.GetPixels();
  1070. texture2D = new Texture2D(texture2D.width, texture2D.height);
  1071. texture2D.SetPixels(pixelData);
  1072. texture2D.Apply();
  1073. byte[] bytes = texture2D.EncodeToPNG();
  1074. var fileName = Path.GetFileNameWithoutExtension(assetPath);
  1075. var filePath = Path.GetDirectoryName(assetPath);
  1076. var savePath = Path.Combine(filePath, fileName + ".png");
  1077. File.WriteAllBytes(savePath, bytes);
  1078. AssetDatabase.Refresh();
  1079. }
  1080. static void SwizzleField(SerializedProperty property, GUIContent label)
  1081. {
  1082. EditorGUI.BeginProperty(EditorGUILayout.BeginHorizontal(), label, property);
  1083. EditorGUI.BeginChangeCheck();
  1084. EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
  1085. var rect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector4, label), EditorStyles.numberField);
  1086. var id = GUIUtility.GetControlID(s_SwizzleFieldHash, FocusType.Keyboard, rect);
  1087. rect = EditorGUI.PrefixLabel(rect, id, label);
  1088. var value = property.uintValue;
  1089. float w = (rect.width - 3 * EditorGUIUtility.standardVerticalSpacing) / 4;
  1090. var subRect = new Rect(rect) {width = w};
  1091. var oldIndent = EditorGUI.indentLevel;
  1092. EditorGUI.indentLevel = 0;
  1093. for (int i = 0; i < 4; i++)
  1094. {
  1095. int shift = 8 * i;
  1096. uint swz = (value >> shift) & 0xFF;
  1097. swz = (uint)EditorGUI.Popup(subRect, (int)swz, styles.swizzleOptions);
  1098. value &= ~(0xFFu << shift);
  1099. value |= swz << shift;
  1100. subRect.x += w + EditorGUIUtility.standardVerticalSpacing;
  1101. }
  1102. EditorGUI.indentLevel = oldIndent;
  1103. EditorGUI.showMixedValue = false;
  1104. if (EditorGUI.EndChangeCheck())
  1105. property.uintValue = value;
  1106. EditorGUILayout.EndHorizontal();
  1107. EditorGUI.EndProperty();
  1108. }
  1109. void SwizzleGUI()
  1110. {
  1111. SwizzleField(m_Swizzle, styles.swizzle);
  1112. }
  1113. /// <summary>
  1114. /// Implementation of AssetImporterEditor.ResetValues.
  1115. /// </summary>
  1116. [Obsolete("UnityUpgradeable () -> DiscardChanges")]
  1117. protected override void ResetValues()
  1118. {
  1119. DiscardChanges();
  1120. }
  1121. /// <summary>
  1122. /// Implementation of AssetImporterEditor.DiscardChanges.
  1123. /// </summary>
  1124. public override void DiscardChanges()
  1125. {
  1126. base.DiscardChanges();
  1127. m_TexturePlatformSettingsHelper = new TexturePlatformSettingsHelper(this);
  1128. m_LayerManagementTreeView.UpdateTreeView(serializedObject);
  1129. }
  1130. /// <summary>
  1131. /// Implementation of ITexturePlatformSettingsDataProvider.GetTargetCount.
  1132. /// </summary>
  1133. /// <returns>Returns the number of selected targets.</returns>
  1134. int ITexturePlatformSettingsDataProvider.GetTargetCount()
  1135. {
  1136. return targets.Length;
  1137. }
  1138. /// <summary>
  1139. /// ITexturePlatformSettingsDataProvider.GetPlatformTextureSettings.
  1140. /// </summary>
  1141. /// <param name="i">Selected target index.</param>
  1142. /// <param name="name">Name of the platform.</param>
  1143. /// <returns>TextureImporterPlatformSettings for the given platform name and selected target index.</returns>
  1144. TextureImporterPlatformSettings ITexturePlatformSettingsDataProvider.GetPlatformTextureSettings(int i, string name)
  1145. {
  1146. var externalData = extraDataSerializedObject.targetObjects[i] as PSDImporterEditorExternalData;
  1147. if (externalData != null)
  1148. {
  1149. foreach (var ps in externalData.platformSettings)
  1150. {
  1151. if (ps.name == name)
  1152. return ps;
  1153. }
  1154. }
  1155. return new TextureImporterPlatformSettings()
  1156. {
  1157. name = name,
  1158. overridden = false
  1159. };
  1160. }
  1161. /// <summary>
  1162. /// Implementation of ITexturePlatformSettingsDataProvider.ShowPresetSettings.
  1163. /// </summary>
  1164. /// <returns>True if valid asset is selected, false otherwiser.</returns>
  1165. bool ITexturePlatformSettingsDataProvider.ShowPresetSettings()
  1166. {
  1167. return assetTarget == null;
  1168. }
  1169. /// <summary>
  1170. /// Implementation of ITexturePlatformSettingsDataProvider.DoesSourceTextureHaveAlpha.
  1171. /// </summary>
  1172. /// <param name="i">Index to selected target.</param>
  1173. /// <returns>Always returns true since importer deals with source file that has alpha.</returns>
  1174. bool ITexturePlatformSettingsDataProvider.DoesSourceTextureHaveAlpha(int i)
  1175. {
  1176. return true;
  1177. }
  1178. /// <summary>
  1179. /// Implementation of ITexturePlatformSettingsDataProvider.IsSourceTextureHDR.
  1180. /// </summary>
  1181. /// <param name="i">Index to selected target.</param>
  1182. /// <returns>Always returns false since importer does not handle HDR textures.</returns>
  1183. bool ITexturePlatformSettingsDataProvider.IsSourceTextureHDR(int i)
  1184. {
  1185. return false;
  1186. }
  1187. /// <summary>
  1188. /// Implementation of ITexturePlatformSettingsDataProvider.SetPlatformTextureSettings.
  1189. /// </summary>
  1190. /// <param name="i">Selected target index.</param>
  1191. /// <param name="platformSettings">TextureImporterPlatformSettings to apply to target.</param>
  1192. void ITexturePlatformSettingsDataProvider.SetPlatformTextureSettings(int i, TextureImporterPlatformSettings platformSettings)
  1193. {
  1194. var psdImporter = ((PSDImporter)targets[i]);
  1195. var sp = new SerializedObject(psdImporter);
  1196. sp.FindProperty("m_PlatformSettingsDirtyTick").longValue = System.DateTime.Now.Ticks;
  1197. sp.ApplyModifiedProperties();
  1198. }
  1199. /// <summary>
  1200. /// Implementation of ITexturePlatformSettingsDataProvider.GetImporterSettings.
  1201. /// </summary>
  1202. /// <param name="i">Selected target index.</param>
  1203. /// <param name="settings">TextureImporterPlatformSettings reference for data retrieval.</param>
  1204. void ITexturePlatformSettingsDataProvider.GetImporterSettings(int i, TextureImporterSettings settings)
  1205. {
  1206. ((PSDImporter)targets[i]).ReadTextureSettings(settings);
  1207. // Get settings that have been changed in the inspector
  1208. GetSerializedPropertySettings(settings);
  1209. }
  1210. /// <summary>
  1211. /// Get the name property of TextureImporterPlatformSettings from a SerializedProperty.
  1212. /// </summary>
  1213. /// <param name="sp">The SerializedProperty to retrive data.</param>
  1214. /// <returns>The name value in string.</returns>
  1215. public string GetBuildTargetName(SerializedProperty sp)
  1216. {
  1217. return sp.FindPropertyRelative("m_Name").stringValue;
  1218. }
  1219. /// <summary>
  1220. /// The SerializedProperty of an array of TextureImporterPlatformSettings.
  1221. /// </summary>
  1222. public SerializedProperty platformSettingsArray => m_PlatformSettingsArrProp;
  1223. static (TextureImporterSwizzle r, TextureImporterSwizzle g, TextureImporterSwizzle b, TextureImporterSwizzle a) ConvertSwizzleRaw(uint value)
  1224. {
  1225. return ((TextureImporterSwizzle)((int)value & (int)byte.MaxValue),
  1226. (TextureImporterSwizzle) ((int)(value >> 8) & (int) byte.MaxValue),
  1227. (TextureImporterSwizzle) ((int)(value >> 16) & (int) byte.MaxValue),
  1228. (TextureImporterSwizzle) ((int)(value >> 24) & (int) byte.MaxValue));
  1229. }
  1230. internal TextureImporterSettings GetSerializedPropertySettings(TextureImporterSettings settings)
  1231. {
  1232. if (!m_AlphaSource.hasMultipleDifferentValues)
  1233. settings.alphaSource = (TextureImporterAlphaSource)m_AlphaSource.intValue;
  1234. if (!m_ConvertToNormalMap.hasMultipleDifferentValues)
  1235. settings.convertToNormalMap = m_ConvertToNormalMap.intValue > 0;
  1236. if (!m_BorderMipMap.hasMultipleDifferentValues)
  1237. settings.borderMipmap = m_BorderMipMap.intValue > 0;
  1238. #if ENABLE_TEXTURE_STREAMING
  1239. if (!m_StreamingMipmaps.hasMultipleDifferentValues)
  1240. settings.streamingMipmaps = m_StreamingMipmaps.intValue > 0;
  1241. if (!m_StreamingMipmapsPriority.hasMultipleDifferentValues)
  1242. settings.streamingMipmapsPriority = m_StreamingMipmapsPriority.intValue;
  1243. #endif
  1244. if (!m_MipMapsPreserveCoverage.hasMultipleDifferentValues)
  1245. settings.mipMapsPreserveCoverage = m_MipMapsPreserveCoverage.intValue > 0;
  1246. if (!m_AlphaTestReferenceValue.hasMultipleDifferentValues)
  1247. settings.alphaTestReferenceValue = m_AlphaTestReferenceValue.floatValue;
  1248. if (!m_NPOTScale.hasMultipleDifferentValues)
  1249. settings.npotScale = (TextureImporterNPOTScale)m_NPOTScale.intValue;
  1250. if (!m_IsReadable.hasMultipleDifferentValues)
  1251. settings.readable = m_IsReadable.intValue > 0;
  1252. if (!m_sRGBTexture.hasMultipleDifferentValues)
  1253. settings.sRGBTexture = m_sRGBTexture.intValue > 0;
  1254. if (!m_EnableMipMap.hasMultipleDifferentValues)
  1255. settings.mipmapEnabled = m_EnableMipMap.intValue > 0;
  1256. if (!m_MipMapMode.hasMultipleDifferentValues)
  1257. settings.mipmapFilter = (TextureImporterMipFilter)m_MipMapMode.intValue;
  1258. if (!m_Swizzle.hasMultipleDifferentValues)
  1259. {
  1260. var swizzleValue = ConvertSwizzleRaw(m_Swizzle.uintValue);
  1261. settings.swizzleR = swizzleValue.r;
  1262. settings.swizzleG = swizzleValue.g;
  1263. settings.swizzleB = swizzleValue.b;
  1264. settings.swizzleA = swizzleValue.a;
  1265. }
  1266. if (!m_FadeOut.hasMultipleDifferentValues)
  1267. settings.fadeOut = m_FadeOut.intValue > 0;
  1268. if (!m_MipMapFadeDistanceStart.hasMultipleDifferentValues)
  1269. settings.mipmapFadeDistanceStart = m_MipMapFadeDistanceStart.intValue;
  1270. if (!m_MipMapFadeDistanceEnd.hasMultipleDifferentValues)
  1271. settings.mipmapFadeDistanceEnd = m_MipMapFadeDistanceEnd.intValue;
  1272. if (!m_SpriteMode.hasMultipleDifferentValues)
  1273. settings.spriteMode = m_SpriteMode.intValue;
  1274. if (!m_SpritePixelsToUnits.hasMultipleDifferentValues)
  1275. settings.spritePixelsPerUnit = m_SpritePixelsToUnits.floatValue;
  1276. if (!m_SpriteExtrude.hasMultipleDifferentValues)
  1277. settings.spriteExtrude = (uint)m_SpriteExtrude.intValue;
  1278. if (!m_SpriteMeshType.hasMultipleDifferentValues)
  1279. settings.spriteMeshType = (SpriteMeshType)m_SpriteMeshType.intValue;
  1280. if (!m_Alignment.hasMultipleDifferentValues)
  1281. settings.spriteAlignment = m_Alignment.intValue;
  1282. if (!m_SpritePivot.hasMultipleDifferentValues)
  1283. settings.spritePivot = m_SpritePivot.vector2Value;
  1284. if (!m_WrapU.hasMultipleDifferentValues)
  1285. settings.wrapModeU = (TextureWrapMode)m_WrapU.intValue;
  1286. if (!m_WrapV.hasMultipleDifferentValues)
  1287. settings.wrapModeU = (TextureWrapMode)m_WrapV.intValue;
  1288. if (!m_WrapW.hasMultipleDifferentValues)
  1289. settings.wrapModeU = (TextureWrapMode)m_WrapW.intValue;
  1290. if (!m_FilterMode.hasMultipleDifferentValues)
  1291. settings.filterMode = (FilterMode)m_FilterMode.intValue;
  1292. if (!m_Aniso.hasMultipleDifferentValues)
  1293. settings.aniso = m_Aniso.intValue;
  1294. if (!m_AlphaIsTransparency.hasMultipleDifferentValues)
  1295. settings.alphaIsTransparency = m_AlphaIsTransparency.intValue > 0;
  1296. if (!m_TextureType.hasMultipleDifferentValues)
  1297. settings.textureType = (TextureImporterType)m_TextureType.intValue;
  1298. if (!m_TextureShape.hasMultipleDifferentValues)
  1299. settings.textureShape = (TextureImporterShape)m_TextureShape.intValue;
  1300. return settings;
  1301. }
  1302. /// <summary>
  1303. /// Override of AssetImporterEditor.showImportedObject
  1304. /// The property always returns false so that imported objects does not show up in the Inspector.
  1305. /// </summary>
  1306. /// <returns>false</returns>
  1307. public override bool showImportedObject
  1308. {
  1309. get { return false; }
  1310. }
  1311. bool ITexturePlatformSettingsDataProvider.textureTypeHasMultipleDifferentValues
  1312. {
  1313. get { return m_TextureType.hasMultipleDifferentValues; }
  1314. }
  1315. TextureImporterType ITexturePlatformSettingsDataProvider.textureType
  1316. {
  1317. get { return (TextureImporterType)m_TextureType.intValue; }
  1318. }
  1319. SpriteImportMode ITexturePlatformSettingsDataProvider.spriteImportMode => spriteImportMode;
  1320. SpriteImportMode spriteImportMode
  1321. {
  1322. get { return (SpriteImportMode)m_SpriteMode.intValue; }
  1323. }
  1324. /// <summary>
  1325. /// Override of AssetImporterEditor.HasModified.
  1326. /// </summary>
  1327. /// <returns>Returns True if has modified data. False otherwise.</returns>
  1328. public override bool HasModified()
  1329. {
  1330. if (base.HasModified())
  1331. return true;
  1332. return m_TexturePlatformSettingsHelper.HasModified();
  1333. }
  1334. bool shouldProduceGameObject
  1335. {
  1336. get { return m_CharacterMode.boolValue && m_MosaicLayers.boolValue && spriteImportMode == SpriteImportMode.Multiple; }
  1337. }
  1338. /// <summary>
  1339. /// Override from AssetImporterEditor to show preview settings.
  1340. /// </summary>
  1341. public override void OnPreviewSettings()
  1342. {
  1343. base.OnPreviewSettings();
  1344. using(new EditorGUI.DisabledScope(!shouldProduceGameObject || m_PreviewRenderUtility == null))
  1345. {
  1346. EditorGUI.BeginChangeCheck();
  1347. m_ShowPivot = GUILayout.Toggle(m_ShowPivot, styles.previewPivotButtonContent, "toolbarbutton");
  1348. if (EditorGUI.EndChangeCheck())
  1349. EditorPrefs.SetBool(kReferencePref, m_ShowPivot);
  1350. }
  1351. }
  1352. /// <summary>
  1353. /// Override from AssetImporterEditor to show custom preview.
  1354. /// </summary>
  1355. /// <param name="r">Preview Rect.</param>
  1356. public override void DrawPreview(Rect r)
  1357. {
  1358. if (shouldProduceGameObject)
  1359. {
  1360. if (m_PreviewRenderUtility == null)
  1361. {
  1362. InitPreview();
  1363. }
  1364. if (m_PreviewRenderUtility != null)
  1365. {
  1366. var t = (PSDImporter)target;
  1367. var prefabBounds = new Rect(0 , 0, t.importData.documentSize.x/ t.pixelsPerUnit, t.importData.documentSize.y/ t.pixelsPerUnit);
  1368. var documentPivot = ImportUtilities.GetPivotPoint(prefabBounds, (SpriteAlignment)m_DocumentAlignment.intValue, m_DocumentPivot.vector2Value);
  1369. m_PreviewRenderUtility.DrawPreview(r, "PreBackgroundSolid", documentPivot, m_ShowPivot);
  1370. }
  1371. else
  1372. base.DrawPreview(r);
  1373. }
  1374. else
  1375. {
  1376. base.DrawPreview(r);
  1377. }
  1378. }
  1379. internal class Styles
  1380. {
  1381. public readonly GUIContent padding = EditorGUIUtility.TrTextContent("Mosaic Padding", "Padding between each SpriteRect in pixel unit.");
  1382. public readonly GUIContent spriteSizeExpand = EditorGUIUtility.TrTextContent("Sprite Padding", "Internal padding within each SpriteRect generated from the Photoshop file.");
  1383. public readonly GUIContent previewPivotButtonContent = EditorGUIUtility.TrIconContent("AvatarPivot", "Displays generated Prefab's pivot. The option will only be enabled if a Prefab is already generated and the import options will generate a Prefab.");
  1384. public readonly GUIContent textureTypeTitle = new GUIContent("Texture Type", "What will this texture be used for?");
  1385. public readonly GUIContent[] textureTypeOptions =
  1386. {
  1387. new GUIContent("Default", "Texture is a normal image such as a diffuse texture or other."),
  1388. new GUIContent("Sprite (2D and UI)", "Texture is used for a sprite."),
  1389. };
  1390. public readonly int[] textureTypeValues =
  1391. {
  1392. (int)TextureImporterType.Default,
  1393. (int)TextureImporterType.Sprite,
  1394. };
  1395. private readonly GUIContent textureShape2D = new GUIContent("2D, Texture is 2D.");
  1396. private readonly GUIContent textureShapeCube = new GUIContent("Cube", "Texture is a Cubemap.");
  1397. public readonly Dictionary<TextureImporterShape, GUIContent[]> textureShapeOptionsDictionnary = new Dictionary<TextureImporterShape, GUIContent[]>();
  1398. public readonly Dictionary<TextureImporterShape, int[]> textureShapeValuesDictionnary = new Dictionary<TextureImporterShape, int[]>();
  1399. public readonly GUIContent filterMode = new GUIContent("Filter Mode");
  1400. public readonly GUIContent[] filterModeOptions =
  1401. {
  1402. new GUIContent("Point (no filter)"),
  1403. new GUIContent("Bilinear"),
  1404. new GUIContent("Trilinear")
  1405. };
  1406. public readonly GUIContent mipmapFadeOutToggle = new GUIContent("Fadeout Mip Maps");
  1407. public readonly GUIContent mipmapFadeOut = new GUIContent("Fade Range");
  1408. public readonly GUIContent readWrite = new GUIContent("Read/Write Enabled", "Enable to be able to access the raw pixel data from code.");
  1409. public readonly GUIContent alphaSource = new GUIContent("Alpha Source", "How is the alpha generated for the imported texture.");
  1410. public readonly GUIContent[] alphaSourceOptions =
  1411. {
  1412. new GUIContent("None", "No Alpha will be used."),
  1413. new GUIContent("Input Texture Alpha", "Use Alpha from the input texture if one is provided."),
  1414. new GUIContent("From Gray Scale", "Generate Alpha from image gray scale."),
  1415. };
  1416. public readonly int[] alphaSourceValues =
  1417. {
  1418. (int)TextureImporterAlphaSource.None,
  1419. (int)TextureImporterAlphaSource.FromInput,
  1420. (int)TextureImporterAlphaSource.FromGrayScale,
  1421. };
  1422. public readonly GUIContent generateMipMaps = new GUIContent("Generate Mip Maps");
  1423. public readonly GUIContent sRGBTexture = new GUIContent("sRGB (Color Texture)", "Texture content is stored in gamma space. Non-HDR color textures should enable this flag (except if used for IMGUI).");
  1424. public readonly GUIContent borderMipMaps = new GUIContent("Border Mip Maps");
  1425. #if ENABLE_TEXTURE_STREAMING
  1426. public readonly GUIContent streamingMipMaps = EditorGUIUtility.TrTextContent("Mip Streaming", "Only load larger mipmaps as needed to render the current game cameras. Requires texture streaming to be enabled in quality settings.");
  1427. public readonly GUIContent streamingMipmapsPriority = EditorGUIUtility.TrTextContent("Priority", "Mipmap streaming priority when there's contention for resources. Positive numbers represent higher priority. Valid range is -128 to 127.");
  1428. #endif
  1429. public readonly GUIContent mipMapsPreserveCoverage = new GUIContent("Mip Maps Preserve Coverage", "The alpha channel of generated Mip Maps will preserve coverage during the alpha test.");
  1430. public readonly GUIContent alphaTestReferenceValue = new GUIContent("Alpha Cutoff Value", "The reference value used during the alpha test. Controls Mip Map coverage.");
  1431. public readonly GUIContent mipMapFilter = new GUIContent("Mip Map Filtering");
  1432. public readonly GUIContent[] mipMapFilterOptions =
  1433. {
  1434. new GUIContent("Box"),
  1435. new GUIContent("Kaiser"),
  1436. };
  1437. public readonly GUIContent npot = new GUIContent("Non Power of 2", "How non-power-of-two textures are scaled on import.");
  1438. public readonly GUIContent spriteMode = new GUIContent("Sprite Mode");
  1439. public readonly GUIContent[] spriteModeOptions =
  1440. {
  1441. new GUIContent("Single"),
  1442. new GUIContent("Multiple"),
  1443. new GUIContent("Polygon"),
  1444. };
  1445. public readonly GUIContent[] spriteMeshTypeOptions =
  1446. {
  1447. new GUIContent("Full Rect"),
  1448. new GUIContent("Tight"),
  1449. };
  1450. public readonly GUIContent spritePixelsPerUnit = new GUIContent("Pixels Per Unit", "How many pixels in the sprite correspond to one unit in the world.");
  1451. public readonly GUIContent spriteExtrude = new GUIContent("Extrude Edges", "How much empty area to leave around the sprite in the generated mesh.");
  1452. public readonly GUIContent spriteMeshType = new GUIContent("Mesh Type", "Type of sprite mesh to generate.");
  1453. public readonly GUIContent spriteAlignment = new GUIContent("Pivot", "Sprite pivot point in its local space. May be used for syncing animation frames of different sizes.");
  1454. public readonly GUIContent characterAlignment = new GUIContent("Pivot", "Character pivot point in its local space using normalized value i.e. 0 - 1");
  1455. public readonly GUIContent[] spriteAlignmentOptions =
  1456. {
  1457. new GUIContent("Center"),
  1458. new GUIContent("Top Left"),
  1459. new GUIContent("Top"),
  1460. new GUIContent("Top Right"),
  1461. new GUIContent("Left"),
  1462. new GUIContent("Right"),
  1463. new GUIContent("Bottom Left"),
  1464. new GUIContent("Bottom"),
  1465. new GUIContent("Bottom Right"),
  1466. new GUIContent("Custom"),
  1467. };
  1468. public readonly GUIContent warpNotSupportWarning = new GUIContent("Graphics device doesn't support Repeat wrap mode on NPOT textures. Falling back to Clamp.");
  1469. public readonly GUIContent anisoLevelLabel = new GUIContent("Aniso Level");
  1470. public readonly GUIContent anisotropicDisableInfo = new GUIContent("Anisotropic filtering is disabled for all textures in Quality Settings.");
  1471. public readonly GUIContent anisotropicForceEnableInfo = new GUIContent("Anisotropic filtering is enabled for all textures in Quality Settings.");
  1472. public readonly GUIContent unappliedSettingsDialogTitle = new GUIContent("Unapplied import settings");
  1473. public readonly GUIContent unappliedSettingsDialogContent = new GUIContent("Unapplied import settings for \'{0}\'.\nApply and continue to sprite editor or cancel.");
  1474. public readonly GUIContent applyButtonLabel = new GUIContent("Apply");
  1475. public readonly GUIContent cancelButtonLabel = new GUIContent("Cancel");
  1476. public readonly GUIContent spriteEditorButtonLabel = new GUIContent("Open Sprite Editor");
  1477. public readonly GUIContent resliceFromLayerWarning = new GUIContent("This will reinitialize and recreate all Sprites based on the file’s layer data. Existing Sprite metadata from previously generated Sprites are copied over.");
  1478. public readonly GUIContent alphaIsTransparency = new GUIContent("Alpha Is Transparency", "If the provided alpha channel is transparency, enable this to pre-filter the color to avoid texture filtering artifacts. This is not supported for HDR textures.");
  1479. public readonly GUIContent advancedHeaderText = new GUIContent("Advanced", "Show advanced settings.");
  1480. public readonly GUIContent platformSettingsHeaderText = new GUIContent("Platform Setttings");
  1481. public readonly GUIContent[] platformSettingsSelection;
  1482. public readonly GUIContent wrapModeLabel = new GUIContent("Wrap Mode");
  1483. public readonly GUIContent wrapU = new GUIContent("U axis");
  1484. public readonly GUIContent wrapV = new GUIContent("V axis");
  1485. public readonly GUIContent wrapW = new GUIContent("W axis");
  1486. public readonly GUIContent[] wrapModeContents =
  1487. {
  1488. new GUIContent("Repeat"),
  1489. new GUIContent("Clamp"),
  1490. new GUIContent("Mirror"),
  1491. new GUIContent("Mirror Once"),
  1492. new GUIContent("Per-axis")
  1493. };
  1494. public readonly int[] wrapModeValues =
  1495. {
  1496. (int)TextureWrapMode.Repeat,
  1497. (int)TextureWrapMode.Clamp,
  1498. (int)TextureWrapMode.Mirror,
  1499. (int)TextureWrapMode.MirrorOnce,
  1500. -1
  1501. };
  1502. public readonly GUIContent layerMapping = EditorGUIUtility.TrTextContent("Layer Mapping", "Options for indicating how layer to Sprite mapping.");
  1503. public readonly GUIContent generatePhysicsShape = EditorGUIUtility.TrTextContent("Generate Physics Shape", "Generates a default physics shape from the outline of the Sprite/s when a physics shape has not been set in the Sprite Editor.");
  1504. public readonly GUIContent importHiddenLayer = EditorGUIUtility.TrTextContent("Include Hidden Layers", "Settings to determine when hidden layers should be imported.");
  1505. public readonly GUIContent mosaicLayers = EditorGUIUtility.TrTextContent("Import Mode", "Layers will be imported as individual Sprites.");
  1506. public readonly GUIContent characterMode = EditorGUIUtility.TrTextContent("Use as Rig","Enable to support 2D Animation character rigging.");
  1507. public readonly GUIContent layerGroupLabel = EditorGUIUtility.TrTextContent("Use Layer Group", "GameObjects are grouped according to source file layer grouping.");
  1508. public readonly GUIContent resliceFromLayer = EditorGUIUtility.TrTextContent("Automatic Reslice", "Recreate Sprite rects from file.");
  1509. public readonly GUIContent paperDollMode = EditorGUIUtility.TrTextContent("Paper Doll Mode", "Special mode to generate a Prefab for Paper Doll use case.");
  1510. public readonly GUIContent keepDuplicateSpriteName = EditorGUIUtility.TrTextContent("Keep Duplicate Names", "Keep Sprite name same as Layer Name even if there are duplicated Layer Name.");
  1511. public readonly GUIContent mainSkeletonName = EditorGUIUtility.TrTextContent("Main Skeleton", "Main Skeleton to use for Rigging.");
  1512. public readonly GUIContent generalHeaderText = EditorGUIUtility.TrTextContent("General", "General settings.");
  1513. public readonly GUIContent layerImportHeaderText = EditorGUIUtility.TrTextContent("Layer Import","Layer Import settings.");
  1514. public readonly GUIContent textureHeaderText = EditorGUIUtility.TrTextContent("Texture","Texture settings.");
  1515. public readonly GUIContent multiEditLayerManagementNotSupported = EditorGUIUtility.TrTextContent("Multi editing in Layer Management is not supported.","");
  1516. public readonly GUIContent characterRigHeaderText = EditorGUIUtility.TrTextContent("Character Rig","Character Rig settings.");
  1517. public readonly int[] falseTrueOptionValue =
  1518. {
  1519. 0,
  1520. 1
  1521. };
  1522. public readonly GUIContent[] importModeOptions=
  1523. {
  1524. EditorGUIUtility.TrTextContent("Individual Sprites (Mosaic)","Import individual Photoshop layers as Sprites."),
  1525. new GUIContent("Merged","Merge Photoshop layers and import as single Sprite.")
  1526. };
  1527. public readonly GUIContent[] layerMappingOption=
  1528. {
  1529. EditorGUIUtility.TrTextContent("Use Layer ID","Use layer's ID to identify layer and Sprite mapping."),
  1530. EditorGUIUtility.TrTextContent("Use Layer Name","Use layer's name to identify layer and Sprite mapping."),
  1531. EditorGUIUtility.TrTextContent("Use Layer Name (Case Sensitive)","Use layer's name to identify layer and Sprite mapping."),
  1532. };
  1533. public readonly int[] layerMappingOptionValues =
  1534. {
  1535. (int)PSDImporter.ELayerMappingOption.UseLayerId,
  1536. (int)PSDImporter.ELayerMappingOption.UseLayerName,
  1537. (int)PSDImporter.ELayerMappingOption.UseLayerNameCaseSensitive
  1538. };
  1539. public readonly GUIContent[] layerGroupOption=
  1540. {
  1541. EditorGUIUtility.TrTextContent("Ignore Layer Groups","Only layers will generate GameObjects."),
  1542. EditorGUIUtility.TrTextContent("User Layer Groups", "Group GameObjects according to source file's layer grouping")
  1543. };
  1544. public readonly GUIContent[] editorTabNames =
  1545. {
  1546. EditorGUIUtility.TrTextContent("Settings", "Importer Settings."),
  1547. EditorGUIUtility.TrTextContent("Layer Management", "Layer merge settings.")
  1548. };
  1549. public readonly GUIContent swizzle = EditorGUIUtility.TrTextContent("Swizzle",
  1550. "Reorder and invert texture color channels. For each of R,G,B,A channels pick where the channel data comes from.");
  1551. public readonly string[] swizzleOptions = new[] {"R","G","B","A", "1-R","1-G","1-B","1-A", "0","1" };
  1552. public Styles()
  1553. {
  1554. // This is far from ideal, but it's better than having tons of logic in the GUI code itself.
  1555. // The combination should not grow too much anyway since only Texture3D will be added later.
  1556. GUIContent[] s2D_Options = { textureShape2D };
  1557. GUIContent[] sCube_Options = { textureShapeCube };
  1558. GUIContent[] s2D_Cube_Options = { textureShape2D, textureShapeCube };
  1559. textureShapeOptionsDictionnary.Add(TextureImporterShape.Texture2D, s2D_Options);
  1560. textureShapeOptionsDictionnary.Add(TextureImporterShape.TextureCube, sCube_Options);
  1561. textureShapeOptionsDictionnary.Add(TextureImporterShape.Texture2D | TextureImporterShape.TextureCube, s2D_Cube_Options);
  1562. int[] s2D_Values = { (int)TextureImporterShape.Texture2D };
  1563. int[] sCube_Values = { (int)TextureImporterShape.TextureCube };
  1564. int[] s2D_Cube_Values = { (int)TextureImporterShape.Texture2D, (int)TextureImporterShape.TextureCube };
  1565. textureShapeValuesDictionnary.Add(TextureImporterShape.Texture2D, s2D_Values);
  1566. textureShapeValuesDictionnary.Add(TextureImporterShape.TextureCube, sCube_Values);
  1567. textureShapeValuesDictionnary.Add(TextureImporterShape.Texture2D | TextureImporterShape.TextureCube, s2D_Cube_Values);
  1568. platformSettingsSelection = new GUIContent[TexturePlatformSettingsModal.kValidBuildPlatform.Length];
  1569. for (int i = 0; i < TexturePlatformSettingsModal.kValidBuildPlatform.Length; ++i)
  1570. {
  1571. platformSettingsSelection[i] = new GUIContent(TexturePlatformSettingsModal.kValidBuildPlatform[i].buildTargetName);
  1572. }
  1573. }
  1574. }
  1575. static Styles m_Styles;
  1576. internal static Styles styles
  1577. {
  1578. get
  1579. {
  1580. if(m_Styles == null)
  1581. m_Styles = new Styles();
  1582. return m_Styles;
  1583. }
  1584. }
  1585. }
  1586. class PSDImporterEditorFoldOutState
  1587. {
  1588. SavedBool m_GeneralFoldout;
  1589. SavedBool m_LayerImportFoldout;
  1590. SavedBool m_CharacterRigFoldout;
  1591. SavedBool m_AdvancedFoldout;
  1592. SavedBool m_TextureFoldout;
  1593. SavedBool m_PlatformSettingsFoldout;
  1594. public PSDImporterEditorFoldOutState()
  1595. {
  1596. m_GeneralFoldout = new SavedBool("PSDImporterEditor.m_GeneralFoldout", true);
  1597. m_LayerImportFoldout = new SavedBool("PSDImporterEditor.m_LayerImportFoldout", true);
  1598. m_CharacterRigFoldout = new SavedBool("PSDImporterEditor.m_CharacterRigFoldout", false);
  1599. m_AdvancedFoldout = new SavedBool("PSDImporterEditor.m_AdvancedFoldout", false);
  1600. m_TextureFoldout = new SavedBool("PSDImporterEditor.m_TextureFoldout", false);
  1601. m_PlatformSettingsFoldout = new SavedBool("PSDImporterEditor.m_PlatformSettingsFoldout", false);
  1602. }
  1603. bool DoFoldout(GUIContent title, bool state)
  1604. {
  1605. InspectorUtils.DrawSplitter();
  1606. return InspectorUtils.DrawHeaderFoldout(title, state);
  1607. }
  1608. public bool DoGeneralUI(GUIContent title)
  1609. {
  1610. m_GeneralFoldout.value = DoFoldout(title, m_GeneralFoldout.value);
  1611. return m_GeneralFoldout.value;
  1612. }
  1613. public bool DoLayerImportUI(GUIContent title)
  1614. {
  1615. m_LayerImportFoldout.value = DoFoldout(title, m_LayerImportFoldout.value);
  1616. return m_LayerImportFoldout.value;
  1617. }
  1618. public bool DoCharacterRigUI(GUIContent title)
  1619. {
  1620. m_CharacterRigFoldout.value = DoFoldout(title, m_CharacterRigFoldout.value);
  1621. return m_CharacterRigFoldout.value;
  1622. }
  1623. public bool DoAdvancedUI(GUIContent title)
  1624. {
  1625. m_AdvancedFoldout.value = DoFoldout(title, m_AdvancedFoldout.value);
  1626. return m_AdvancedFoldout.value;
  1627. }
  1628. public bool DoPlatformSettingsUI(GUIContent title)
  1629. {
  1630. m_PlatformSettingsFoldout.value = DoFoldout(title, m_PlatformSettingsFoldout.value);
  1631. return m_PlatformSettingsFoldout.value;
  1632. }
  1633. public bool DoTextureUI(GUIContent title)
  1634. {
  1635. m_TextureFoldout.value = DoFoldout(title, m_TextureFoldout.value);
  1636. return m_TextureFoldout.value;
  1637. }
  1638. class SavedBool
  1639. {
  1640. bool m_Value;
  1641. string m_Name;
  1642. bool m_Loaded;
  1643. public SavedBool(string name, bool value)
  1644. {
  1645. m_Name = name;
  1646. m_Loaded = false;
  1647. m_Value = value;
  1648. }
  1649. private void Load()
  1650. {
  1651. if (m_Loaded)
  1652. return;
  1653. m_Loaded = true;
  1654. m_Value = EditorPrefs.GetBool(m_Name, m_Value);
  1655. }
  1656. public bool value
  1657. {
  1658. get { Load(); return m_Value; }
  1659. set
  1660. {
  1661. Load();
  1662. if (m_Value == value)
  1663. return;
  1664. m_Value = value;
  1665. EditorPrefs.SetBool(m_Name, value);
  1666. }
  1667. }
  1668. public static implicit operator bool(SavedBool s)
  1669. {
  1670. return s.value;
  1671. }
  1672. }
  1673. }
  1674. }