TC_AutoStampMaker.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using UnityEngine;
  2. using UnityEditor;
  3. using System.Collections;
  4. using System.IO;
  5. namespace TerrainComposer2
  6. {
  7. class TC_AutoStampMaker : AssetPostprocessor
  8. {
  9. static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
  10. {
  11. string path;
  12. for (int i = 0; i < importedAssets.Length; i++)
  13. {
  14. path = importedAssets[i];
  15. if (path.Contains("/RawFiles/") )
  16. {
  17. string extension = path.Substring(path.Length - 3);
  18. if (extension.Contains("raw") || extension.Contains("Raw") || extension.Contains("r16") || extension.Contains("R16")) ConvertToImage(path);
  19. }
  20. }
  21. }
  22. static void ConvertToImage(string path)
  23. {
  24. byte[] newBytes;
  25. string newPath = Application.dataPath.Replace("Assets", "") + path;
  26. byte[] bytes = File.ReadAllBytes(newPath);
  27. if (path.Contains("/Resources/") && (path.Contains(".raw") || path.Contains(".Raw") || path.Contains(".r16") || path.Contains("R16")))
  28. {
  29. File.Move(newPath, newPath.Remove(newPath.Length - 3) + "bytes");
  30. AssetDatabase.Refresh();
  31. }
  32. // Debug.Log(bytes.Length);
  33. int resolution = (int)Mathf.Sqrt(bytes.Length / 2);
  34. int newResolution = resolution;
  35. if (newResolution > 512) newResolution = 512;
  36. Texture2D tex = new Texture2D(newResolution, newResolution, TextureFormat.RGB24, false);
  37. newBytes = new byte[newResolution * newResolution * 3];
  38. int index;
  39. float resConversion = (float)resolution / (float)newResolution;
  40. for (int y = 0; y < newResolution; y++)
  41. {
  42. for (int x = 0; x < newResolution; x++)
  43. {
  44. int i = (Mathf.RoundToInt(x * resConversion)) + (Mathf.RoundToInt(y * resConversion) * resolution);
  45. float v = Mathf.Round(((bytes[i * 2] + (bytes[(i * 2) + 1] * 255)) / 65535f) * 255f);
  46. index = (x + (newResolution - y - 1) * newResolution) * 3;
  47. newBytes[index] = (byte)v;
  48. newBytes[index + 1] = newBytes[index];
  49. newBytes[index + 2] = newBytes[index];
  50. }
  51. }
  52. tex.LoadRawTextureData(newBytes);
  53. index = newPath.LastIndexOf("/");
  54. string file = newPath.Substring(index + 1);
  55. file = file.Remove(file.Length - 3);
  56. file += "Jpg";
  57. newPath = newPath.Substring(0, index + 1);
  58. newPath = newPath.Replace("RawFiles/", "") + file;
  59. File.WriteAllBytes(newPath, tex.EncodeToJPG());
  60. newPath = newPath.Replace(Application.dataPath, "Assets");
  61. Object.DestroyImmediate(tex);
  62. AssetDatabase.ImportAsset(newPath);
  63. }
  64. }
  65. }