FR2_Asset.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. using System.Globalization;
  2. //#define FR2_DEBUG_BRACE_LEVEL
  3. //#define FR2_DEBUG_SYMBOL
  4. //#define FR2_DEBUG
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using UnityEditor;
  12. using UnityEngine;
  13. #if FR2_ADDRESSABLE
  14. using UnityEditor.AddressableAssets;
  15. using UnityEngine.AddressableAssets;
  16. #endif
  17. using UnityObject = UnityEngine.Object;
  18. namespace vietlabs.fr2
  19. {
  20. public enum FR2_AssetType
  21. {
  22. UNKNOWN,
  23. FOLDER,
  24. SCRIPT,
  25. SCENE,
  26. DLL,
  27. REFERENCABLE,
  28. BINARY_ASSET,
  29. MODEL,
  30. TERRAIN,
  31. NON_READABLE
  32. }
  33. public enum FR2_AssetState
  34. {
  35. NEW,
  36. CACHE,
  37. MISSING
  38. }
  39. [Serializable]
  40. public class FR2_Asset
  41. {
  42. // ------------------------------ CONSTANTS ---------------------------
  43. private static readonly HashSet<string> SCRIPT_EXTENSIONS = new HashSet<string>
  44. {
  45. ".cs", ".js", ".boo", ".h", ".java", ".cpp", ".m", ".mm"
  46. };
  47. private static readonly HashSet<string> REFERENCABLE_EXTENSIONS = new HashSet<string>
  48. {
  49. ".anim", ".controller", ".mat", ".unity", ".guiskin", ".prefab",
  50. ".overridecontroller", ".mask", ".rendertexture", ".cubemap", ".flare",
  51. ".mat", ".prefab", ".physicsmaterial", ".fontsettings", ".asset", ".prefs", ".spriteatlas"
  52. };
  53. private static readonly Dictionary<int, Type> HashClasses = new Dictionary<int, Type>();
  54. internal static Dictionary<string, GUIContent> cacheImage = new Dictionary<string, GUIContent>();
  55. private bool _isExcluded;
  56. private Dictionary<string, HashSet<int>> _UseGUIDs;
  57. private float excludeTS;
  58. public static float ignoreTS;
  59. // ----------------------------- DRAW ---------------------------------------
  60. [NonSerialized] private GUIContent fileSizeText;
  61. // ----------------------------- DRAW ---------------------------------------
  62. [SerializeField] public string guid;
  63. // easy to recalculate: will not cache
  64. [NonSerialized] private bool m_pathLoaded;
  65. [NonSerialized] private string m_assetFolder;
  66. [NonSerialized] private string m_assetName;
  67. [NonSerialized] private string m_assetPath;
  68. [NonSerialized] private string m_extension;
  69. [NonSerialized] private bool m_inEditor;
  70. [NonSerialized] private bool m_inPlugins;
  71. [NonSerialized] private bool m_inResources;
  72. [NonSerialized] private bool m_inStreamingAsset;
  73. [NonSerialized] private bool m_isAssetFile;
  74. // Need to read FileInfo: soft-cache (always re-read when needed)
  75. [SerializeField] public FR2_AssetType type;
  76. [SerializeField] private string m_fileInfoHash;
  77. [SerializeField] private string m_assetbundle;
  78. [SerializeField] private string m_addressable;
  79. [SerializeField] private string m_atlas;
  80. [SerializeField] private long m_fileSize;
  81. [SerializeField] private int m_assetChangeTS; // Realtime when asset changed (trigger by import asset operation)
  82. [SerializeField] private int m_fileInfoReadTS; // Realtime when asset being read
  83. [SerializeField] private int m_fileWriteTS; // file's lastModification (file content + meta)
  84. [SerializeField] private int m_cachefileWriteTS; // file's lastModification at the time the content being read
  85. [SerializeField] internal int refreshStamp; // use to check if asset has been deleted (refreshStamp not updated)
  86. // Do not cache
  87. [NonSerialized] internal FR2_AssetState state;
  88. internal Dictionary<string, FR2_Asset> UsedByMap = new Dictionary<string, FR2_Asset>();
  89. internal HashSet<int> HashUsedByClassesIds = new HashSet<int>();
  90. [SerializeField] private List<Classes> UseGUIDsList = new List<Classes>();
  91. public FR2_Asset(string guid)
  92. {
  93. this.guid = guid;
  94. type = FR2_AssetType.UNKNOWN;
  95. }
  96. // ----------------------- PATH INFO ------------------------
  97. public void LoadPathInfo()
  98. {
  99. if (m_pathLoaded) return;
  100. m_pathLoaded = true;
  101. m_assetPath = AssetDatabase.GUIDToAssetPath(guid);
  102. if (string.IsNullOrEmpty(assetPath))
  103. {
  104. state = FR2_AssetState.MISSING;
  105. return;
  106. }
  107. #if FR2_DEBUG
  108. Debug.LogWarning("Refreshing ... " + loadInfoTS + ":" + AssetDatabase.GUIDToAssetPath(guid));
  109. if (!m_assetPath.StartsWith("Assets"))
  110. {
  111. Debug.Log("LoadAssetInfo: " + m_assetPath);
  112. }
  113. #endif
  114. FR2_Unity.SplitPath(m_assetPath, out m_assetName, out m_extension, out m_assetFolder);
  115. if (m_assetFolder.StartsWith("Assets/"))
  116. {
  117. m_assetFolder = m_assetFolder.Substring(7);
  118. }
  119. else if (!FR2_Unity.StringStartsWith(m_assetPath, "Packages/", "Project Settings/", "Library/"))
  120. {
  121. m_assetFolder = "built-in/";
  122. }
  123. m_inEditor = m_assetPath.Contains("/Editor/") || m_assetPath.Contains("/Editor Default Resources/");
  124. m_inResources = m_assetPath.Contains("/Resources/");
  125. m_inStreamingAsset = m_assetPath.Contains("/StreamingAssets/");
  126. m_inPlugins = m_assetPath.Contains("/Plugins/");
  127. m_isAssetFile = m_assetPath.EndsWith(".asset", StringComparison.Ordinal);
  128. }
  129. public string assetName { get {
  130. LoadPathInfo();
  131. return m_assetName;
  132. } }
  133. public string assetPath
  134. {
  135. get
  136. {
  137. if (!string.IsNullOrEmpty(m_assetPath)) return m_assetPath;
  138. m_assetPath = AssetDatabase.GUIDToAssetPath(guid);
  139. if (string.IsNullOrEmpty(m_assetPath))
  140. {
  141. state = FR2_AssetState.MISSING;
  142. }
  143. return m_assetPath;
  144. }
  145. }
  146. public string parentFolderPath { get { LoadPathInfo(); return m_assetFolder; } }
  147. public string assetFolder { get { LoadPathInfo(); return m_assetFolder; } }
  148. public string extension { get { LoadPathInfo(); return m_extension; } }
  149. public bool inEditor { get { LoadPathInfo(); return m_inEditor; } }
  150. public bool inPlugins { get { LoadPathInfo(); return m_inPlugins; } }
  151. public bool inResources { get { LoadPathInfo(); return m_inResources; } }
  152. public bool inStreamingAsset { get { LoadPathInfo(); return m_inStreamingAsset; } }
  153. // ----------------------- TYPE INFO ------------------------
  154. internal bool IsFolder { get { return type == FR2_AssetType.FOLDER; } }
  155. internal bool IsScript { get { return type == FR2_AssetType.SCRIPT; } }
  156. internal bool IsMissing { get { return state == FR2_AssetState.MISSING; } }
  157. internal bool IsReferencable { get {
  158. return type == FR2_AssetType.REFERENCABLE ||
  159. type == FR2_AssetType.SCENE;
  160. }}
  161. internal bool IsBinaryAsset { get {
  162. return type == FR2_AssetType.BINARY_ASSET ||
  163. type == FR2_AssetType.MODEL ||
  164. type == FR2_AssetType.TERRAIN;
  165. }}
  166. // ----------------------- PATH INFO ------------------------
  167. public bool fileInfoDirty { get { return (type == FR2_AssetType.UNKNOWN) || (m_fileInfoReadTS <= m_assetChangeTS); } }
  168. public bool fileContentDirty { get { return m_fileWriteTS != m_cachefileWriteTS; } }
  169. public bool isDirty
  170. {
  171. get { return fileInfoDirty || fileContentDirty; }
  172. }
  173. bool ExistOnDisk()
  174. {
  175. if (IsMissing) return false; // asset not exist - no need to check FileSystem!
  176. if (type == FR2_AssetType.FOLDER || type == FR2_AssetType.UNKNOWN)
  177. {
  178. if (Directory.Exists(m_assetPath))
  179. {
  180. if (type == FR2_AssetType.UNKNOWN) type = FR2_AssetType.FOLDER;
  181. return true;
  182. }
  183. if (type == FR2_AssetType.FOLDER) return false;
  184. }
  185. // must be file here
  186. if (!File.Exists(m_assetPath)) return false;
  187. if (type == FR2_AssetType.UNKNOWN) GuessAssetType();
  188. return true;
  189. }
  190. internal void LoadFileInfo()
  191. {
  192. if (!fileInfoDirty) return;
  193. if (string.IsNullOrEmpty(m_assetPath)) LoadPathInfo(); // always reload Path Info
  194. //Debug.Log("--> Read: " + assetPath + " --> " + m_fileInfoReadTS + "<" + m_assetChangeTS);
  195. m_fileInfoReadTS = FR2_Unity.Epoch(DateTime.Now);
  196. if (IsMissing)
  197. {
  198. Debug.LogWarning("Should never be here! - missing files can not trigger LoadFileInfo()");
  199. return;
  200. }
  201. if (!ExistOnDisk())
  202. {
  203. state = FR2_AssetState.MISSING;
  204. return;
  205. }
  206. if (type == FR2_AssetType.FOLDER) return; // nothing to read
  207. var assetType = AssetDatabase.GetMainAssetTypeAtPath(m_assetPath);
  208. if (assetType == typeof(FR2_Cache)) return;
  209. var info = new FileInfo(m_assetPath);
  210. m_fileSize = info.Length;
  211. m_fileInfoHash = info.Length + info.Extension;
  212. m_addressable = FR2_Unity.GetAddressable(guid);
  213. //if (!string.IsNullOrEmpty(m_addressable)) Debug.LogWarning(guid + " --> " + m_addressable);
  214. m_assetbundle = AssetDatabase.GetImplicitAssetBundleName(m_assetPath);
  215. if (assetType == typeof(Texture2D))
  216. {
  217. var importer = AssetImporter.GetAtPath(m_assetPath);
  218. if (importer is TextureImporter)
  219. {
  220. var tImporter = importer as TextureImporter;
  221. if (tImporter.qualifiesForSpritePacking)
  222. {
  223. m_atlas = tImporter.spritePackingTag;
  224. }
  225. }
  226. }
  227. // check if file content changed
  228. var metaInfo = new FileInfo(m_assetPath + ".meta");
  229. var assetTime = FR2_Unity.Epoch(info.LastWriteTime);
  230. var metaTime = FR2_Unity.Epoch(metaInfo.LastWriteTime);
  231. // update fileChangeTimeStamp
  232. m_fileWriteTS = Mathf.Max(metaTime, assetTime);
  233. }
  234. internal string fileInfoHash { get { LoadFileInfo(); return m_fileInfoHash; } }
  235. internal long fileSize { get { LoadFileInfo(); return m_fileSize; } }
  236. public string AtlasName { get { LoadFileInfo(); return m_atlas;}}
  237. public string AssetBundleName { get { LoadFileInfo(); return m_assetbundle;}}
  238. public string AddressableName { get { LoadFileInfo(); return m_addressable; }}
  239. public Dictionary<string, HashSet<int>> UseGUIDs
  240. {
  241. get
  242. {
  243. if (_UseGUIDs != null)
  244. {
  245. return _UseGUIDs;
  246. }
  247. _UseGUIDs = new Dictionary<string, HashSet<int>>(UseGUIDsList.Count);
  248. for (var i = 0; i < UseGUIDsList.Count; i++)
  249. {
  250. string guid = UseGUIDsList[i].guid;
  251. if (_UseGUIDs.ContainsKey(guid))
  252. {
  253. for (var j = 0; j < UseGUIDsList[i].ids.Count; j++)
  254. {
  255. int val = UseGUIDsList[i].ids[j];
  256. if (_UseGUIDs[guid].Contains(val))
  257. {
  258. continue;
  259. }
  260. _UseGUIDs[guid].Add(UseGUIDsList[i].ids[j]);
  261. }
  262. }
  263. else
  264. {
  265. _UseGUIDs.Add(guid, new HashSet<int>(UseGUIDsList[i].ids));
  266. }
  267. }
  268. return _UseGUIDs;
  269. }
  270. }
  271. // ------------------------------- GETTERS -----------------------------
  272. internal bool IsExcluded
  273. {
  274. get
  275. {
  276. if (excludeTS >= ignoreTS)
  277. {
  278. return _isExcluded;
  279. }
  280. excludeTS = ignoreTS;
  281. _isExcluded = false;
  282. HashSet<string> h = FR2_Setting.IgnoreAsset;
  283. foreach (string item in FR2_Setting.IgnoreAsset)
  284. {
  285. if (m_assetPath.StartsWith(item, false, CultureInfo.InvariantCulture))
  286. {
  287. _isExcluded = true;
  288. break;
  289. }
  290. }
  291. return _isExcluded;
  292. }
  293. }
  294. public void AddUsedBy(string guid, FR2_Asset asset)
  295. {
  296. if (UsedByMap.ContainsKey(guid))
  297. {
  298. return;
  299. }
  300. if(guid == this.guid)
  301. {
  302. //Debug.LogWarning("self used");
  303. return;
  304. }
  305. UsedByMap.Add(guid, asset);
  306. HashSet<int> output;
  307. if (HashUsedByClassesIds == null)
  308. {
  309. HashUsedByClassesIds = new HashSet<int>();
  310. }
  311. if (asset.UseGUIDs.TryGetValue(this.guid, out output))
  312. {
  313. foreach (int item in output)
  314. {
  315. HashUsedByClassesIds.Add(item);
  316. }
  317. }
  318. // int classId = HashUseByClassesIds
  319. }
  320. public int UsageCount()
  321. {
  322. return UsedByMap.Count;
  323. }
  324. public override string ToString()
  325. {
  326. return string.Format("FR2_Asset[{0}]", m_assetName);
  327. }
  328. //--------------------------------- STATIC ----------------------------
  329. internal static bool IsValidGUID(string guid)
  330. {
  331. return AssetDatabase.GUIDToAssetPath(guid) != FR2_Cache.CachePath; // just skip FR2_Cache asset
  332. }
  333. internal void MarkAsDirty(bool isMoved = true, bool force = false)
  334. {
  335. if (isMoved)
  336. {
  337. var newPath = AssetDatabase.GUIDToAssetPath(guid);
  338. if (newPath != m_assetPath)
  339. {
  340. m_pathLoaded = false;
  341. m_assetPath = newPath;
  342. }
  343. }
  344. state = FR2_AssetState.CACHE;
  345. m_assetChangeTS = FR2_Unity.Epoch(DateTime.Now); // re-read FileInfo
  346. if (force) m_cachefileWriteTS = 0;
  347. }
  348. // --------------------------------- APIs ------------------------------
  349. internal void GuessAssetType()
  350. {
  351. if (SCRIPT_EXTENSIONS.Contains(m_extension))
  352. {
  353. type = FR2_AssetType.SCRIPT;
  354. }
  355. else if (REFERENCABLE_EXTENSIONS.Contains(m_extension))
  356. {
  357. bool isUnity = m_extension == ".unity";
  358. type = isUnity ? FR2_AssetType.SCENE : FR2_AssetType.REFERENCABLE;
  359. if (m_extension == ".asset" || isUnity || m_extension == ".spriteatlas")
  360. {
  361. var buffer = new byte[5];
  362. try
  363. {
  364. FileStream stream = File.OpenRead(m_assetPath);
  365. stream.Read(buffer, 0, 5);
  366. stream.Close();
  367. }
  368. #if FR2_DEBUG
  369. catch (Exception e)
  370. {
  371. Debug.LogWarning("Guess Asset Type error :: " + e + "\n" + m_assetPath);
  372. #else
  373. catch
  374. {
  375. #endif
  376. state = FR2_AssetState.MISSING;
  377. return;
  378. }
  379. string str = string.Empty;
  380. foreach (byte t in buffer)
  381. {
  382. str += (char) t;
  383. }
  384. if (str != "%YAML")
  385. {
  386. type = FR2_AssetType.BINARY_ASSET;
  387. }
  388. }
  389. }
  390. else if (m_extension == ".fbx")
  391. {
  392. type = FR2_AssetType.MODEL;
  393. }
  394. else if (m_extension == ".dll")
  395. {
  396. type = FR2_AssetType.DLL;
  397. }
  398. else
  399. {
  400. type = FR2_AssetType.NON_READABLE;
  401. }
  402. }
  403. internal void LoadContent()
  404. {
  405. if (!fileContentDirty) return;
  406. m_cachefileWriteTS = m_fileWriteTS;
  407. if (IsMissing || type == FR2_AssetType.NON_READABLE)
  408. {
  409. return;
  410. }
  411. if (type == FR2_AssetType.DLL)
  412. {
  413. #if FR2_DEBUG
  414. Debug.LogWarning("Parsing DLL not yet supportted ");
  415. #endif
  416. return;
  417. }
  418. if (!ExistOnDisk())
  419. {
  420. state = FR2_AssetState.MISSING;
  421. return;
  422. }
  423. ClearUseGUIDs();
  424. if (IsFolder)
  425. {
  426. LoadFolder();
  427. }
  428. else if (IsReferencable)
  429. {
  430. LoadYAML2();
  431. }
  432. else if (IsBinaryAsset)
  433. {
  434. LoadBinaryAsset();
  435. }
  436. }
  437. internal void AddUseGUID(string fguid, int fFileId = -1, bool checkExist = true)
  438. {
  439. // if (checkExist && UseGUIDs.ContainsKey(fguid)) return;
  440. if (!IsValidGUID(fguid))
  441. {
  442. return;
  443. }
  444. if (!UseGUIDs.ContainsKey(fguid))
  445. {
  446. UseGUIDsList.Add(new Classes
  447. {
  448. guid = fguid,
  449. ids = new List<int>()
  450. });
  451. UseGUIDs.Add(fguid, new HashSet<int>());
  452. }
  453. if (fFileId != -1)
  454. {
  455. if (UseGUIDs[fguid].Contains(fFileId))
  456. {
  457. return;
  458. }
  459. UseGUIDs[fguid].Add(fFileId);
  460. Classes i = UseGUIDsList.FirstOrDefault(x => x.guid == fguid);
  461. if (i != null)
  462. {
  463. i.ids.Add(fFileId);
  464. }
  465. }
  466. }
  467. // ----------------------------- STATIC ---------------------------------------
  468. internal static int SortByExtension(FR2_Asset a1, FR2_Asset a2)
  469. {
  470. if (a1 == null)
  471. {
  472. return -1;
  473. }
  474. if (a2 == null)
  475. {
  476. return 1;
  477. }
  478. int result = string.Compare(a1.m_extension, a2.m_extension, StringComparison.Ordinal);
  479. return result == 0 ? string.Compare(a1.m_assetName, a2.m_assetName, StringComparison.Ordinal) : result;
  480. }
  481. internal static List<FR2_Asset> FindUsage(FR2_Asset asset)
  482. {
  483. if (asset == null)
  484. {
  485. return null;
  486. }
  487. List<FR2_Asset> refs = FR2_Cache.Api.FindAssets(asset.UseGUIDs.Keys.ToArray(), true);
  488. return refs;
  489. }
  490. internal static List<FR2_Asset> FindUsedBy(FR2_Asset asset)
  491. {
  492. return asset.UsedByMap.Values.ToList();
  493. }
  494. internal static List<string> FindUsageGUIDs(FR2_Asset asset, bool includeScriptSymbols)
  495. {
  496. var result = new HashSet<string>();
  497. if (asset == null)
  498. {
  499. Debug.LogWarning("Asset invalid : " + asset.m_assetName);
  500. return result.ToList();
  501. }
  502. // for (var i = 0;i < asset.UseGUIDs.Count; i++)
  503. // {
  504. // result.Add(asset.UseGUIDs[i]);
  505. // }
  506. foreach (KeyValuePair<string, HashSet<int>> item in asset.UseGUIDs)
  507. {
  508. result.Add(item.Key);
  509. }
  510. //if (!includeScriptSymbols) return result.ToList();
  511. //if (asset.ScriptUsage != null)
  512. //{
  513. // for (var i = 0; i < asset.ScriptUsage.Count; i++)
  514. // {
  515. // var symbolList = FR2_Cache.Api.FindAllSymbol(asset.ScriptUsage[i]);
  516. // if (symbolList.Contains(asset)) continue;
  517. // var symbol = symbolList[0];
  518. // if (symbol == null || result.Contains(symbol.guid)) continue;
  519. // result.Add(symbol.guid);
  520. // }
  521. //}
  522. return result.ToList();
  523. }
  524. internal static List<string> FindUsedByGUIDs(FR2_Asset asset)
  525. {
  526. return asset.UsedByMap.Keys.ToList();
  527. }
  528. internal float Draw(Rect r,
  529. bool highlight,
  530. bool drawPath = true,
  531. bool showFileSize = true,
  532. bool showABName = false,
  533. bool showAtlasName = false,
  534. bool showUsageIcon = true,
  535. IWindow window = null
  536. ){
  537. bool singleLine = r.height <= 18f;
  538. float rw = r.width;
  539. bool selected = FR2_Bookmark.Contains(guid);
  540. r.height = 16f;
  541. bool hasMouse = Event.current.type == EventType.MouseUp && r.Contains(Event.current.mousePosition);
  542. if (hasMouse && Event.current.button == 1)
  543. {
  544. var menu = new GenericMenu();
  545. if (m_extension == ".prefab")
  546. {
  547. menu.AddItem(new GUIContent("Edit in Scene"), false, EditPrefab);
  548. }
  549. menu.AddItem(new GUIContent("Open"), false, Open);
  550. menu.AddItem(new GUIContent("Ping"), false, Ping);
  551. menu.AddItem(new GUIContent(guid), false, CopyGUID);
  552. //menu.AddItem(new GUIContent("Reload"), false, Reload);
  553. menu.AddSeparator(string.Empty);
  554. menu.AddItem(new GUIContent("Bookmark"), selected, AddToSelection);
  555. menu.AddSeparator(string.Empty);
  556. menu.AddItem(new GUIContent("Copy path"), false, CopyAssetPath);
  557. menu.AddItem(new GUIContent("Copy full path"), false, CopyAssetPathFull);
  558. //if (IsScript)
  559. //{
  560. // menu.AddSeparator(string.Empty);
  561. // AddArray(menu, ScriptSymbols, "+ ", "Definitions", "No Definition", false);
  562. // menu.AddSeparator(string.Empty);
  563. // AddArray(menu, ScriptUsage, "-> ", "Depends", "No Dependency", true);
  564. //}
  565. menu.ShowAsContext();
  566. Event.current.Use();
  567. }
  568. if (IsMissing)
  569. {
  570. if (!singleLine)
  571. {
  572. r.y += 16f;
  573. }
  574. if (Event.current.type != EventType.Repaint)
  575. {
  576. return 0;
  577. }
  578. GUI.Label(r, "(missing) " + guid, EditorStyles.whiteBoldLabel);
  579. return 0;
  580. }
  581. Rect iconRect = GUI2.LeftRect(16f, ref r);
  582. if (Event.current.type == EventType.Repaint)
  583. {
  584. Texture icon = AssetDatabase.GetCachedIcon(m_assetPath);
  585. if (icon != null)
  586. {
  587. GUI.DrawTexture(iconRect, icon);
  588. }
  589. }
  590. if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
  591. {
  592. Rect pingRect = FR2_Setting.PingRow ? new Rect(0, r.y, r.x + r.width, r.height) : iconRect;
  593. if (pingRect.Contains(Event.current.mousePosition))
  594. {
  595. if (Event.current.control || Event.current.command)
  596. {
  597. if (selected)
  598. {
  599. RemoveFromSelection();
  600. }
  601. else
  602. {
  603. AddToSelection();
  604. }
  605. if (window != null)
  606. {
  607. window.Repaint();
  608. }
  609. }
  610. else
  611. {
  612. Ping();
  613. }
  614. //Event.current.Use();
  615. }
  616. }
  617. if (Event.current.type != EventType.Repaint)
  618. {
  619. return 0;
  620. }
  621. if (UsedByMap != null && UsedByMap.Count > 0)
  622. {
  623. var str = new GUIContent(UsedByMap.Count.ToString());
  624. Rect countRect = iconRect;
  625. countRect.x -= 16f;
  626. countRect.xMin = -10f;
  627. GUI.Label(countRect, str, GUI2.miniLabelAlignRight);
  628. }
  629. float pathW = drawPath ? EditorStyles.miniLabel.CalcSize(new GUIContent(m_assetFolder)).x : 0;
  630. float nameW = EditorStyles.boldLabel.CalcSize(new GUIContent(m_assetName)).x;
  631. Color cc = FR2_Cache.Api.setting.SelectedColor;
  632. if (singleLine)
  633. {
  634. Rect lbRect = GUI2.LeftRect(pathW + nameW, ref r);
  635. if (selected)
  636. {
  637. Color c1 = GUI.color;
  638. GUI.color = cc;
  639. GUI.DrawTexture(lbRect, EditorGUIUtility.whiteTexture);
  640. GUI.color = c1;
  641. }
  642. if (drawPath)
  643. {
  644. Color c2 = GUI.color;
  645. GUI.color = new Color(c2.r, c2.g, c2.b, c2.a*0.5f);
  646. GUI.Label(GUI2.LeftRect(pathW, ref lbRect), m_assetFolder, EditorStyles.miniLabel);
  647. GUI.color = c2;
  648. lbRect.xMin -= 4f;
  649. GUI.Label(lbRect, m_assetName, EditorStyles.boldLabel);
  650. }
  651. else
  652. {
  653. GUI.Label(lbRect, m_assetName);
  654. }
  655. }
  656. else
  657. {
  658. if (drawPath)
  659. {
  660. GUI.Label(new Rect(r.x, r.y + 16f, r.width, r.height), m_assetFolder, EditorStyles.miniLabel);
  661. }
  662. Rect lbRect = GUI2.LeftRect(nameW, ref r);
  663. if (selected)
  664. {
  665. GUI2.Rect(lbRect, cc);
  666. }
  667. GUI.Label(lbRect, m_assetName, EditorStyles.boldLabel);
  668. }
  669. var rr = GUI2.RightRect(10f, ref r); //margin
  670. if (highlight)
  671. {
  672. rr.xMin += 2f;
  673. rr.width = 1f;
  674. GUI2.Rect(rr, GUI2.darkGreen);
  675. }
  676. Color c = GUI.color;
  677. GUI.color = new Color(c.r, c.g, c.b, c.a*0.5f);
  678. if (showFileSize)
  679. {
  680. Rect fsRect = GUI2.RightRect(40f, ref r); // filesize label
  681. if (fileSizeText == null)
  682. {
  683. fileSizeText = new GUIContent(FR2_Helper.GetfileSizeString(fileSize));
  684. }
  685. GUI.Label(fsRect, fileSizeText, GUI2.miniLabelAlignRight);
  686. }
  687. if (!string.IsNullOrEmpty(m_addressable))
  688. {
  689. Rect adRect = GUI2.RightRect(100f, ref r);
  690. GUI.Label(adRect, m_addressable, GUI2.miniLabelAlignRight);
  691. }
  692. if (showUsageIcon && HashUsedByClassesIds != null)
  693. {
  694. foreach (int item in HashUsedByClassesIds)
  695. {
  696. if (!FR2_Unity.HashClassesNormal.ContainsKey(item))
  697. {
  698. continue;
  699. }
  700. string name = FR2_Unity.HashClassesNormal[item];
  701. Type t = null;
  702. if (!HashClasses.TryGetValue(item, out t))
  703. {
  704. t = FR2_Unity.GetType(name);
  705. HashClasses.Add(item, t);
  706. }
  707. GUIContent content = null;
  708. var isExisted = cacheImage.TryGetValue(name, out content);
  709. if (content == null) content = new GUIContent(EditorGUIUtility.ObjectContent(null, t).image, name);
  710. if (!isExisted)
  711. {
  712. cacheImage.Add(name, content);
  713. } else {
  714. cacheImage[name] = content;
  715. }
  716. if (content != null)
  717. {
  718. try
  719. {
  720. GUI.Label(GUI2.RightRect(15f, ref r), content, GUI2.miniLabelAlignRight);
  721. }
  722. #if !FR2_DEBUG
  723. catch {}
  724. #else
  725. catch (Exception e)
  726. {
  727. UnityEngine.Debug.LogWarning(e);
  728. }
  729. #endif
  730. }
  731. }
  732. }
  733. if (showAtlasName)
  734. {
  735. GUI2.RightRect(10f, ref r); //margin
  736. Rect abRect = GUI2.RightRect(120f, ref r); // filesize label
  737. if (!string.IsNullOrEmpty(m_atlas))
  738. {
  739. GUI.Label(abRect, m_atlas, GUI2.miniLabelAlignRight);
  740. }
  741. }
  742. if (showABName)
  743. {
  744. GUI2.RightRect(10f, ref r); //margin
  745. Rect abRect = GUI2.RightRect(100f, ref r); // filesize label
  746. if (!string.IsNullOrEmpty(m_assetbundle))
  747. {
  748. GUI.Label(abRect, m_assetbundle, GUI2.miniLabelAlignRight);
  749. }
  750. }
  751. if (true)
  752. {
  753. GUI2.RightRect(10f, ref r); //margin
  754. Rect abRect = GUI2.RightRect(100f, ref r); // filesize label
  755. if (!string.IsNullOrEmpty(m_addressable))
  756. {
  757. GUI.Label(abRect, m_addressable, GUI2.miniLabelAlignRight);
  758. }
  759. }
  760. GUI.color = c;
  761. if (Event.current.type == EventType.Repaint)
  762. {
  763. return rw < pathW + nameW ? 32f : 18f;
  764. }
  765. return r.height;
  766. }
  767. internal GenericMenu AddArray(GenericMenu menu, List<string> list, string prefix, string title,
  768. string emptyTitle, bool showAsset, int max = 10)
  769. {
  770. //if (list.Count > 0)
  771. //{
  772. // if (list.Count > max)
  773. // {
  774. // prefix = string.Format("{0} _{1}/", title, list.Count) + prefix;
  775. // }
  776. // //for (var i = 0; i < list.Count; i++)
  777. // //{
  778. // // var def = list[i];
  779. // // var suffix = showAsset ? "/" + FR2_Cache.Api.FindSymbol(def).assetName : string.Empty;
  780. // // menu.AddItem(new GUIContent(prefix + def + suffix), false, () => OpenScript(def));
  781. // //}
  782. //}
  783. //else
  784. {
  785. menu.AddItem(new GUIContent(emptyTitle), true, null);
  786. }
  787. return menu;
  788. }
  789. internal void CopyGUID()
  790. {
  791. EditorGUIUtility.systemCopyBuffer = guid;
  792. Debug.Log(guid);
  793. }
  794. internal void CopyName()
  795. {
  796. EditorGUIUtility.systemCopyBuffer = m_assetName;
  797. Debug.Log(m_assetName);
  798. }
  799. internal void CopyAssetPath()
  800. {
  801. EditorGUIUtility.systemCopyBuffer = m_assetPath;
  802. Debug.Log(m_assetPath);
  803. }
  804. internal void CopyAssetPathFull()
  805. {
  806. string fullName = new FileInfo(m_assetPath).FullName;
  807. EditorGUIUtility.systemCopyBuffer = fullName;
  808. Debug.Log(fullName);
  809. }
  810. internal void AddToSelection()
  811. {
  812. if (!FR2_Bookmark.Contains(guid))
  813. {
  814. FR2_Bookmark.Add(guid);
  815. }
  816. //var list = Selection.objects.ToList();
  817. //var obj = FR2_Unity.LoadAssetAtPath<Object>(assetPath);
  818. //if (!list.Contains(obj))
  819. //{
  820. // list.Add(obj);
  821. // Selection.objects = list.ToArray();
  822. //}
  823. }
  824. internal void RemoveFromSelection()
  825. {
  826. if (FR2_Bookmark.Contains(guid))
  827. {
  828. FR2_Bookmark.Remove(guid);
  829. }
  830. }
  831. internal void Ping()
  832. {
  833. EditorGUIUtility.PingObject(
  834. AssetDatabase.LoadAssetAtPath(m_assetPath, typeof(UnityObject))
  835. );
  836. }
  837. internal void Open()
  838. {
  839. AssetDatabase.OpenAsset(
  840. AssetDatabase.LoadAssetAtPath(m_assetPath, typeof(UnityObject))
  841. );
  842. }
  843. internal void EditPrefab()
  844. {
  845. UnityObject prefab = AssetDatabase.LoadAssetAtPath(m_assetPath, typeof(UnityObject));
  846. UnityObject.Instantiate(prefab);
  847. }
  848. //internal void OpenScript(string definition)
  849. //{
  850. // var asset = FR2_Cache.Api.FindSymbol(definition);
  851. // if (asset == null) return;
  852. // EditorGUIUtility.PingObject(
  853. // AssetDatabase.LoadAssetAtPath(asset.assetPath, typeof(Object))
  854. // );
  855. //}
  856. // ----------------------------- SERIALIZED UTILS ---------------------------------------
  857. // ----------------------------- LOAD ASSETS ---------------------------------------
  858. internal void LoadGameObject(GameObject go)
  859. {
  860. Component[] compList = go.GetComponentsInChildren<Component>();
  861. for (var i = 0; i < compList.Length; i++)
  862. {
  863. LoadSerialized(compList[i]);
  864. }
  865. }
  866. internal void LoadSerialized(UnityObject target)
  867. {
  868. SerializedProperty[] props = FR2_Unity.xGetSerializedProperties(target, true);
  869. for (var i = 0; i < props.Length; i++)
  870. {
  871. if (props[i].propertyType != SerializedPropertyType.ObjectReference)
  872. {
  873. continue;
  874. }
  875. UnityObject refObj = props[i].objectReferenceValue;
  876. if (refObj == null)
  877. {
  878. continue;
  879. }
  880. string refGUID = AssetDatabase.AssetPathToGUID(
  881. AssetDatabase.GetAssetPath(refObj)
  882. );
  883. //Debug.Log("Found Reference BinaryAsset <" + assetPath + "> : " + refGUID + ":" + refObj);
  884. AddUseGUID(refGUID);
  885. }
  886. }
  887. internal void LoadTerrainData(TerrainData terrain)
  888. {
  889. #if UNITY_2018_3_OR_NEWER
  890. TerrainLayer[] arr0 = terrain.terrainLayers;
  891. for (var i = 0; i < arr0.Length; i++)
  892. {
  893. string aPath = AssetDatabase.GetAssetPath(arr0[i]);
  894. string refGUID = AssetDatabase.AssetPathToGUID(aPath);
  895. AddUseGUID(refGUID);
  896. }
  897. #endif
  898. DetailPrototype[] arr = terrain.detailPrototypes;
  899. for (var i = 0; i < arr.Length; i++)
  900. {
  901. string aPath = AssetDatabase.GetAssetPath(arr[i].prototypeTexture);
  902. string refGUID = AssetDatabase.AssetPathToGUID(aPath);
  903. AddUseGUID(refGUID);
  904. }
  905. TreePrototype[] arr2 = terrain.treePrototypes;
  906. for (var i = 0; i < arr2.Length; i++)
  907. {
  908. string aPath = AssetDatabase.GetAssetPath(arr2[i].prefab);
  909. string refGUID = AssetDatabase.AssetPathToGUID(aPath);
  910. AddUseGUID(refGUID);
  911. }
  912. FR2_Unity.TerrainTextureData[] arr3 = FR2_Unity.GetTerrainTextureDatas(terrain);
  913. for (var i = 0; i < arr3.Length; i++)
  914. {
  915. FR2_Unity.TerrainTextureData texs = arr3[i];
  916. for (var k = 0; k < texs.textures.Length; k++)
  917. {
  918. Texture2D tex = texs.textures[k];
  919. if (tex == null)
  920. {
  921. continue;
  922. }
  923. string aPath = AssetDatabase.GetAssetPath(tex);
  924. if (string.IsNullOrEmpty(aPath))
  925. {
  926. continue;
  927. }
  928. string refGUID = AssetDatabase.AssetPathToGUID(aPath);
  929. if (string.IsNullOrEmpty(refGUID))
  930. {
  931. continue;
  932. }
  933. AddUseGUID(refGUID);
  934. }
  935. }
  936. }
  937. private void ClearUseGUIDs()
  938. {
  939. #if FR2_DEBUG
  940. Debug.Log("ClearUseGUIDs: " + assetPath);
  941. #endif
  942. UseGUIDs.Clear();
  943. UseGUIDsList.Clear();
  944. }
  945. static int binaryLoaded;
  946. internal void LoadBinaryAsset()
  947. {
  948. ClearUseGUIDs();
  949. UnityObject assetData = AssetDatabase.LoadAssetAtPath(m_assetPath, typeof(UnityObject));
  950. if (assetData is GameObject)
  951. {
  952. type = FR2_AssetType.MODEL;
  953. LoadGameObject(assetData as GameObject);
  954. }
  955. else if (assetData is TerrainData)
  956. {
  957. type = FR2_AssetType.TERRAIN;
  958. LoadTerrainData(assetData as TerrainData);
  959. }
  960. else
  961. {
  962. LoadSerialized(assetData);
  963. }
  964. #if FR2_DEBUG
  965. Debug.Log("LoadBinaryAsset :: " + assetData + ":" + type);
  966. #endif
  967. assetData = null;
  968. if (binaryLoaded++ <= 30) return;
  969. binaryLoaded = 0;
  970. FR2_Unity.UnloadUnusedAssets();
  971. }
  972. internal void LoadYAML()
  973. {
  974. if (!File.Exists(m_assetPath))
  975. {
  976. state = FR2_AssetState.MISSING;
  977. return;
  978. }
  979. if (m_isAssetFile)
  980. {
  981. var s = AssetDatabase.LoadAssetAtPath<FR2_Cache>(m_assetPath);
  982. if (s != null)
  983. {
  984. return;
  985. }
  986. }
  987. string text = string.Empty;
  988. try
  989. {
  990. text = File.ReadAllText(m_assetPath);
  991. }
  992. #if FR2_DEBUG
  993. catch (Exception e)
  994. {
  995. Debug.LogWarning("Guess Asset Type error :: " + e + "\n" + assetPath);
  996. #else
  997. catch
  998. {
  999. #endif
  1000. state = FR2_AssetState.MISSING;
  1001. return;
  1002. }
  1003. #if FR2_DEBUG
  1004. Debug.Log("LoadYAML: " + assetPath);
  1005. #endif
  1006. //if(assetPath.Contains("Myriad Pro - Bold SDF"))
  1007. //{
  1008. // Debug.Log("no ne");
  1009. //}
  1010. // PERFORMANCE HOG!
  1011. // var matches = Regex.Matches(text, @"\bguid: [a-f0-9]{32}\b");
  1012. MatchCollection matches = Regex.Matches(text, @".*guid: [a-f0-9]{32}.*\n");
  1013. foreach (Match match in matches)
  1014. {
  1015. Match guidMatch = Regex.Match(match.Value, @"\bguid: [a-f0-9]{32}\b");
  1016. string refGUID = guidMatch.Value.Replace("guid: ", string.Empty);
  1017. Match fileIdMatch = Regex.Match(match.Value, @"\bfileID: ([0-9]*).*");
  1018. int id = -1;
  1019. try
  1020. {
  1021. id = int.Parse(fileIdMatch.Groups[1].Value) / 100000;
  1022. }
  1023. catch { }
  1024. AddUseGUID(refGUID, id);
  1025. }
  1026. //var idx = text.IndexOf("guid: ");
  1027. //var counter=0;
  1028. //while (idx != -1)
  1029. //{
  1030. // var guid = text.Substring(idx + 6, 32);
  1031. // if (UseGUIDs.Contains(guid)) continue;
  1032. // AddUseGUID(guid);
  1033. // idx += 39;
  1034. // if (idx > text.Length-40) break;
  1035. // //Debug.Log(assetName + ":" + guid);
  1036. // idx = text.IndexOf("guid: ", idx + 39);
  1037. // if (counter++ > 100) break;
  1038. //}
  1039. //if (counter > 100){
  1040. // Debug.LogWarning("Never finish on " + assetName);
  1041. //}
  1042. }
  1043. internal void LoadYAML2()
  1044. {
  1045. if (!File.Exists(m_assetPath))
  1046. {
  1047. state = FR2_AssetState.MISSING;
  1048. return;
  1049. }
  1050. if (m_assetPath == "ProjectSettings/EditorBuildSettings.asset")
  1051. {
  1052. var listScenes = EditorBuildSettings.scenes;
  1053. foreach (var scene in listScenes)
  1054. {
  1055. if (!scene.enabled) continue;
  1056. var path = scene.path;
  1057. var guid = AssetDatabase.AssetPathToGUID(path);
  1058. AddUseGUID(guid, 0);
  1059. #if FR2_DEBUG
  1060. Debug.Log("AddScene: " + path);
  1061. #endif
  1062. }
  1063. }
  1064. // var text = string.Empty;
  1065. try
  1066. {
  1067. using (var sr = new StreamReader(m_assetPath))
  1068. {
  1069. while (sr.Peek() >= 0)
  1070. {
  1071. string line = sr.ReadLine();
  1072. int index = line.IndexOf("guid: ");
  1073. if (index < 0)
  1074. {
  1075. continue;
  1076. }
  1077. string refGUID = line.Substring(index + 6, 32);
  1078. int indexFileId = line.IndexOf("fileID: ");
  1079. int fileID = -1;
  1080. if (indexFileId >= 0)
  1081. {
  1082. indexFileId += 8;
  1083. string fileIDStr =
  1084. line.Substring(indexFileId, line.IndexOf(',', indexFileId) - indexFileId);
  1085. try
  1086. {
  1087. fileID = int.Parse(fileIDStr) / 100000;
  1088. }
  1089. catch { }
  1090. }
  1091. AddUseGUID(refGUID, fileID);
  1092. }
  1093. }
  1094. #if FR2_DEBUG
  1095. if (UseGUIDsList.Count > 0)
  1096. {
  1097. Debug.Log(assetPath + ":" + UseGUIDsList.Count);
  1098. }
  1099. #endif
  1100. }
  1101. #if FR2_DEBUG
  1102. catch (Exception e)
  1103. {
  1104. Debug.LogWarning("Guess Asset Type error :: " + e + "\n" + assetPath);
  1105. #else
  1106. catch
  1107. {
  1108. #endif
  1109. state = FR2_AssetState.MISSING;
  1110. }
  1111. }
  1112. internal void LoadFolder()
  1113. {
  1114. if (!Directory.Exists(m_assetPath))
  1115. {
  1116. state = FR2_AssetState.MISSING;
  1117. return;
  1118. }
  1119. // do not analyse folders outside project
  1120. if (!m_assetPath.StartsWith("Assets/")) return;
  1121. try
  1122. {
  1123. string[] files = Directory.GetFiles(m_assetPath);
  1124. string[] dirs = Directory.GetDirectories(m_assetPath);
  1125. foreach (string f in files)
  1126. {
  1127. if (f.EndsWith(".meta", StringComparison.Ordinal))
  1128. {
  1129. continue;
  1130. }
  1131. string fguid = AssetDatabase.AssetPathToGUID(f);
  1132. if (string.IsNullOrEmpty(fguid))
  1133. {
  1134. continue;
  1135. }
  1136. // AddUseGUID(fguid, true);
  1137. AddUseGUID(fguid);
  1138. }
  1139. foreach (string d in dirs)
  1140. {
  1141. string fguid = AssetDatabase.AssetPathToGUID(d);
  1142. if (string.IsNullOrEmpty(fguid))
  1143. {
  1144. continue;
  1145. }
  1146. // AddUseGUID(fguid, true);
  1147. AddUseGUID(fguid);
  1148. }
  1149. }
  1150. #if FR2_DEBUG
  1151. catch (Exception e)
  1152. {
  1153. Debug.LogWarning("LoadFolder() error :: " + e + "\n" + assetPath);
  1154. #else
  1155. catch
  1156. {
  1157. #endif
  1158. state = FR2_AssetState.MISSING;
  1159. }
  1160. //Debug.Log("Load Folder :: " + assetName + ":" + type + ":" + UseGUIDs.Count);
  1161. }
  1162. // ----------------------------- REPLACE GUIDS ---------------------------------------
  1163. internal bool ReplaceReference(string fromGUID, string toGUID, TerrainData terrain = null)
  1164. {
  1165. if (IsMissing)
  1166. {
  1167. return false;
  1168. }
  1169. if (IsReferencable)
  1170. {
  1171. string text = string.Empty;
  1172. if (!File.Exists(m_assetPath))
  1173. {
  1174. state = FR2_AssetState.MISSING;
  1175. return false;
  1176. }
  1177. try
  1178. {
  1179. text = File.ReadAllText(m_assetPath).Replace("\r", "\n");
  1180. File.WriteAllText(m_assetPath, text.Replace(fromGUID, toGUID));
  1181. // AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.Default);
  1182. return true;
  1183. }
  1184. catch (Exception e)
  1185. {
  1186. state = FR2_AssetState.MISSING;
  1187. //#if FR2_DEBUG
  1188. Debug.LogWarning("Replace Reference error :: " + e + "\n" + m_assetPath);
  1189. //#endif
  1190. }
  1191. return false;
  1192. }
  1193. if (type == FR2_AssetType.TERRAIN)
  1194. {
  1195. var fromObj = FR2_Unity.LoadAssetWithGUID<UnityObject>(fromGUID);
  1196. var toObj = FR2_Unity.LoadAssetWithGUID<UnityObject>(toGUID);
  1197. var found = 0;
  1198. // var terrain = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object)) as TerrainData;
  1199. if (fromObj is Texture2D)
  1200. {
  1201. DetailPrototype[] arr = terrain.detailPrototypes;
  1202. for (var i = 0; i < arr.Length; i++)
  1203. {
  1204. if (arr[i].prototypeTexture == (Texture2D) fromObj)
  1205. {
  1206. found++;
  1207. arr[i].prototypeTexture = (Texture2D) toObj;
  1208. }
  1209. }
  1210. terrain.detailPrototypes = arr;
  1211. FR2_Unity.ReplaceTerrainTextureDatas(terrain, (Texture2D) fromObj, (Texture2D) toObj);
  1212. }
  1213. if (fromObj is GameObject)
  1214. {
  1215. TreePrototype[] arr2 = terrain.treePrototypes;
  1216. for (var i = 0; i < arr2.Length; i++)
  1217. {
  1218. if (arr2[i].prefab == (GameObject) fromObj)
  1219. {
  1220. found++;
  1221. arr2[i].prefab = (GameObject) toObj;
  1222. }
  1223. }
  1224. terrain.treePrototypes = arr2;
  1225. }
  1226. // EditorUtility.SetDirty(terrain);
  1227. // AssetDatabase.SaveAssets();
  1228. fromObj = null;
  1229. toObj = null;
  1230. terrain = null;
  1231. // FR2_Unity.UnloadUnusedAssets();
  1232. return found > 0;
  1233. }
  1234. Debug.LogWarning("Something wrong, should never be here - Ignored <" + m_assetPath +
  1235. "> : not a readable type, can not replace ! " + type);
  1236. return false;
  1237. }
  1238. internal bool ReplaceReference(string fromGUID, string toGUID, long toFileId, TerrainData terrain = null)
  1239. {
  1240. Debug.Log("ReplaceReference: from " + fromGUID + " to: " + toGUID + " toFileId: " + toFileId);
  1241. if (IsMissing)
  1242. {
  1243. // Debug.Log("this asset is missing");
  1244. return false;
  1245. }
  1246. if (IsReferencable)
  1247. {
  1248. string text = string.Empty;
  1249. if (!File.Exists(m_assetPath))
  1250. {
  1251. state = FR2_AssetState.MISSING;
  1252. // Debug.Log("this asset not exits");
  1253. return false;
  1254. }
  1255. try
  1256. {
  1257. var sb = new StringBuilder();
  1258. text = File.ReadAllText(assetPath).Replace("\r", "\n");
  1259. var lines = text.Split('\n');
  1260. //string result = "";
  1261. for(int i = 0; i < lines.Length; i++)
  1262. {
  1263. var line = lines[i];
  1264. if(line.IndexOf(fromGUID, StringComparison.Ordinal) >= 0)
  1265. {
  1266. if(toFileId > 0)
  1267. {
  1268. const string FileID = "fileID: ";
  1269. var index = line.IndexOf(FileID, StringComparison.Ordinal);
  1270. if(index >= 0)
  1271. {
  1272. var fromFileId = line.Substring(index + FileID.Length, line.IndexOf(',', index) - (index + FileID.Length));
  1273. long fileType = 0;
  1274. if(!long.TryParse(fromFileId, out fileType))
  1275. {
  1276. Debug.LogWarning("cannot parse file");
  1277. return false;
  1278. }
  1279. if (fileType.ToString().Substring(0,3) != toFileId.ToString().Substring(0,3))
  1280. {
  1281. //difference file type
  1282. Debug.LogWarning("Difference file type");
  1283. return false;
  1284. }
  1285. Debug.Log("ReplaceReference: fromFileId " + fromFileId + " to File Id " + toFileId);
  1286. line = line.Replace(fromFileId, toFileId.ToString());
  1287. }
  1288. }
  1289. line = line.Replace(fromGUID, toGUID);
  1290. }
  1291. sb.Append(line);
  1292. sb.AppendLine();
  1293. //result += line + "\n";
  1294. }
  1295. //File.WriteAllText(assetPath, result.Trim());
  1296. File.WriteAllText(assetPath, sb.ToString());
  1297. //AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.Default);
  1298. return true;
  1299. }
  1300. catch (Exception e)
  1301. {
  1302. state = FR2_AssetState.MISSING;
  1303. //#if FR2_DEBUG
  1304. Debug.LogWarning("Replace Reference error :: " + e + "\n" + m_assetPath);
  1305. //#endif
  1306. }
  1307. return false;
  1308. }
  1309. if (type == FR2_AssetType.TERRAIN)
  1310. {
  1311. var fromObj = FR2_Unity.LoadAssetWithGUID<UnityObject>(fromGUID);
  1312. var toObj = FR2_Unity.LoadAssetWithGUID<UnityObject>(toGUID);
  1313. var found = 0;
  1314. // var terrain = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object)) as TerrainData;
  1315. if (fromObj is Texture2D)
  1316. {
  1317. DetailPrototype[] arr = terrain.detailPrototypes;
  1318. for (var i = 0; i < arr.Length; i++)
  1319. {
  1320. if (arr[i].prototypeTexture == (Texture2D)fromObj)
  1321. {
  1322. found++;
  1323. arr[i].prototypeTexture = (Texture2D)toObj;
  1324. }
  1325. }
  1326. terrain.detailPrototypes = arr;
  1327. FR2_Unity.ReplaceTerrainTextureDatas(terrain, (Texture2D)fromObj, (Texture2D)toObj);
  1328. }
  1329. if (fromObj is GameObject)
  1330. {
  1331. TreePrototype[] arr2 = terrain.treePrototypes;
  1332. for (var i = 0; i < arr2.Length; i++)
  1333. {
  1334. if (arr2[i].prefab == (GameObject)fromObj)
  1335. {
  1336. found++;
  1337. arr2[i].prefab = (GameObject)toObj;
  1338. }
  1339. }
  1340. terrain.treePrototypes = arr2;
  1341. }
  1342. // EditorUtility.SetDirty(terrain);
  1343. // AssetDatabase.SaveAssets();
  1344. fromObj = null;
  1345. toObj = null;
  1346. terrain = null;
  1347. // FR2_Unity.UnloadUnusedAssets();
  1348. return found > 0;
  1349. }
  1350. Debug.LogWarning("Something wrong, should never be here - Ignored <" + m_assetPath +
  1351. "> : not a readable type, can not replace ! " + type);
  1352. return false;
  1353. }
  1354. [Serializable]
  1355. private class Classes
  1356. {
  1357. public string guid;
  1358. public List<int> ids;
  1359. }
  1360. }
  1361. }