PopupRenderCompare.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using DevilLink2.UI;
  6. using UnityEditor;
  7. using UnityEngine;
  8. using UnityEngine.UI;
  9. namespace DevilLink2.Editor
  10. {
  11. // Editor-only transient visual copy: never opens a real screen or invokes a business callback.
  12. [InitializeOnLoad]
  13. public static class PopupRenderCompare
  14. {
  15. private const string Menu="Tools/Devil Link 2/Diagnostics/Popup Render Compare/";
  16. private static GameObject overlay;private static RectTransform card;private static PopupAnimationController motion;
  17. private static CanvasGroup gate;private static bool native,shown,moving,staticMode;
  18. private static float started,from;private static int serial;
  19. private static readonly List<UnityEngine.Object> owned=new List<UnityEngine.Object>();
  20. private static readonly List<string> manifest=new List<string>();
  21. static PopupRenderCompare(){EditorApplication.playModeStateChanged+=State;AssemblyReloadEvents.beforeAssemblyReload+=Clear;}
  22. [MenuItem(Menu+"Original Rendering")]
  23. private static void Original(){native=false;Clear();Debug.Log("Render comparison A selected. Open Test Popup to run.");}
  24. [MenuItem(Menu+"Native Image Rendering")]
  25. private static void Native(){native=true;Clear();Debug.Log("Render comparison B selected. Open Test Popup to run.");}
  26. [MenuItem(Menu+"Open Test Popup")]
  27. private static void Open()
  28. {
  29. if(!Application.isPlaying){Debug.LogWarning("Requires Main Play Mode. Real save data is not touched by this tool.");return;}
  30. staticMode=true;
  31. if(shown)return;
  32. try {if(!overlay && !Build())return;}catch(Exception error){Clear();Debug.LogException(error);return;}
  33. shown=true;from=moving?motion.CurrentOffset:12;gate.alpha=1;motion.ResetVisual();overlay.SetActive(true);
  34. moving=!staticMode;started=Time.realtimeSinceStartup;gate.interactable=staticMode;gate.blocksRaycasts=true;
  35. }
  36. [MenuItem(Menu+"Close Test Popup")]
  37. private static void Close()
  38. {
  39. if(!overlay||!shown)return;shown=false;from=motion.CurrentOffset;started=Time.realtimeSinceStartup;moving=!staticMode;
  40. gate.interactable=false;if(staticMode)Finish();
  41. }
  42. [MenuItem(Menu+"Static No Motion")]
  43. private static void Static(){staticMode=true;if(overlay)Finish();}
  44. [MenuItem(Menu+"Motion Retired - Static Only")]
  45. private static void Animated(){staticMode=true;Debug.Log("Popup motion retired; static rendering comparison only.");}
  46. [MenuItem(Menu+"Remove Test Popup")]
  47. private static void Clear()
  48. {
  49. moving=shown=false;if(overlay)UnityEngine.Object.DestroyImmediate(overlay);overlay=null;card=null;motion=null;gate=null;
  50. foreach(var item in owned)if(item)UnityEngine.Object.DestroyImmediate(item);owned.Clear();
  51. }
  52. private static void State(PlayModeStateChange state){if(state==PlayModeStateChange.ExitingPlayMode)Clear();}
  53. private static bool Build()
  54. {
  55. var wheel=UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
  56. if(!wheel){Debug.LogWarning("Cached LuckyWheelScreen not found. Initialize Main first.");return false;}
  57. var source=wheel.transform.Find("Card") as RectTransform;if(!source){Debug.LogWarning("Wheel Card not found; no hierarchy changed.");return false;}
  58. if(wheel.IsSpinning){Debug.LogWarning("Wait until the real wheel is idle before creating a visual test copy.");return false;}
  59. var originalRoot=(RectTransform)wheel.transform;
  60. var root=new GameObject("DiagnosticPopupRenderCompare",typeof(RectTransform));overlay=root;
  61. root.SetActive(false);var rect=(RectTransform)root.transform;rect.SetParent(wheel.transform.parent,false);
  62. rect.anchorMin=originalRoot.anchorMin;rect.anchorMax=originalRoot.anchorMax;rect.pivot=originalRoot.pivot;rect.sizeDelta=originalRoot.sizeDelta;rect.anchoredPosition=originalRoot.anchoredPosition;
  63. root.hideFlags=HideFlags.DontSave;var shade=root.AddComponent<Image>();shade.color=wheel.GetComponent<Image>().color;shade.raycastTarget=true;
  64. gate=root.AddComponent<CanvasGroup>();gate.alpha=1;
  65. card=UnityEngine.Object.Instantiate(source,rect,false);card.name="TestVisualRoot";
  66. // Disable layout/business updates before activation, preserving only visual and input primitives.
  67. foreach(var script in card.GetComponentsInChildren<MonoBehaviour>(true)){
  68. bool keep=script is Graphic || script is BaseMeshEffect || script is Selectable || script is ScrollRect;
  69. if(!keep)script.enabled=false;
  70. }
  71. foreach(var button in card.GetComponentsInChildren<Button>(true))button.onClick=new Button.ButtonClickedEvent();
  72. // No original screen root, player, service, or result panel is cloned.
  73. motion=root.AddComponent<PopupAnimationController>();motion.Bind(card);
  74. root.transform.SetAsLastSibling();gate.interactable=false;root.SetActive(true);Canvas.ForceUpdateCanvases();
  75. manifest.Clear();manifest.Add("Mode="+(native?"B native Image":"A original")+"; Card="+card.rect.size+"; source="+source.rect.size);
  76. if(native){
  77. int index=0;
  78. foreach(var graphic in card.GetComponentsInChildren<Image>(true).Where(g=>g.GetType()!=typeof(Image)||g.GetComponent<UIGradient>()).ToArray()){
  79. if(!graphic.gameObject.activeInHierarchy)continue;
  80. BakeAndReplace(graphic,index++);
  81. }
  82. }
  83. Directory.CreateDirectory("Temp/DevilLink2Task13B05F");File.WriteAllLines("Temp/DevilLink2Task13B05F/LastBuildManifest.txt",manifest);
  84. root.SetActive(false);return true;
  85. }
  86. private static void BakeAndReplace(Image graphic,int index)
  87. {
  88. var rect=graphic.rectTransform.rect;if(rect.width<=0||rect.height<=0)return;
  89. graphic.Rebuild(CanvasUpdate.PreRender);var mesh=graphic.canvasRenderer.GetMesh();
  90. var vertices=mesh.vertices;var colors=mesh.colors32;var triangles=mesh.triangles;var uv=mesh.uv;
  91. if(vertices.Length==0){UnityEngine.Object.DestroyImmediate(mesh);manifest.Add("SKIPPED empty mesh: "+graphic.name);return;}
  92. // Read authored textures without changing their importers, preserving custom panel UV slicing.
  93. Color[] texels=null;int tw=0,th=0;
  94. if(graphic.sprite){
  95. var texture=graphic.mainTexture;tw=texture.width;th=texture.height;
  96. var rt=RenderTexture.GetTemporary(tw,th,0,RenderTextureFormat.ARGB32,RenderTextureReadWrite.Linear);var previous=RenderTexture.active;
  97. try{Graphics.Blit(texture,rt);RenderTexture.active=rt;var copy=new Texture2D(tw,th,TextureFormat.RGBA32,false,true);copy.ReadPixels(new Rect(0,0,tw,th),0,0);copy.Apply();texels=copy.GetPixels();UnityEngine.Object.DestroyImmediate(copy);}
  98. finally{RenderTexture.active=previous;RenderTexture.ReleaseTemporary(rt);}
  99. }
  100. var bounds=rect;
  101. foreach(var v in vertices){bounds.xMin=Mathf.Min(bounds.xMin,v.x);bounds.xMax=Mathf.Max(bounds.xMax,v.x);bounds.yMin=Mathf.Min(bounds.yMin,v.y);bounds.yMax=Mathf.Max(bounds.yMax,v.y);}
  102. int w=Mathf.Clamp(Mathf.CeilToInt(bounds.width*2),1,2048),h=Mathf.Clamp(Mathf.CeilToInt(bounds.height*2),1,2048);
  103. var pixels=new Color[w*h];
  104. for(int t=0;t<triangles.Length;t+=3){
  105. int a=triangles[t],b=triangles[t+1],c=triangles[t+2];
  106. Vector2 x=Pixel(vertices[a],bounds,w,h),y=Pixel(vertices[b],bounds,w,h),z=Pixel(vertices[c],bounds,w,h);
  107. float area=Cross(y-x,z-x);if(Mathf.Abs(area)<.00001f)continue;
  108. int left=Mathf.Clamp(Mathf.FloorToInt(Mathf.Min(x.x,Mathf.Min(y.x,z.x))),0,w-1),right=Mathf.Clamp(Mathf.CeilToInt(Mathf.Max(x.x,Mathf.Max(y.x,z.x))),0,w-1);
  109. int bottom=Mathf.Clamp(Mathf.FloorToInt(Mathf.Min(x.y,Mathf.Min(y.y,z.y))),0,h-1),top=Mathf.Clamp(Mathf.CeilToInt(Mathf.Max(x.y,Mathf.Max(y.y,z.y))),0,h-1);
  110. for(int py=bottom;py<=top;py++)for(int px=left;px<=right;px++){
  111. var p=new Vector2(px+.5f,py+.5f);float u=Cross(y-p,z-p)/area,v=Cross(z-p,x-p)/area,q=1-u-v;
  112. if(u<-.00001f||v<-.00001f||q<-.00001f)continue;
  113. Color color=(Color)colors[a]*u+(Color)colors[b]*v+(Color)colors[c]*q;
  114. if(texels!=null){var at=uv[a]*u+uv[b]*v+uv[c]*q;float xx=Mathf.Clamp01(at.x)*(tw-1),yy=Mathf.Clamp01(at.y)*(th-1);int ix=(int)xx,iy=(int)yy;var sample=Color.Lerp(Color.Lerp(texels[iy*tw+ix],texels[iy*tw+Mathf.Min(ix+1,tw-1)],xx-ix),Color.Lerp(texels[Mathf.Min(iy+1,th-1)*tw+ix],texels[Mathf.Min(iy+1,th-1)*tw+Mathf.Min(ix+1,tw-1)],xx-ix),yy-iy);color*=sample;}
  115. int k=py*w+px;var old=pixels[k];float alpha=color.a+old.a*(1-color.a);
  116. pixels[k]=alpha>0?new Color((color.r*color.a+old.r*old.a*(1-color.a))/alpha,(color.g*color.a+old.g*old.a*(1-color.a))/alpha,(color.b*color.a+old.b*old.a*(1-color.a))/alpha,alpha):Color.clear;
  117. }
  118. }
  119. UnityEngine.Object.DestroyImmediate(mesh);
  120. var tex=new Texture2D(w,h,TextureFormat.RGBA32,false,true);tex.SetPixels(pixels);tex.Apply();
  121. byte[] png=tex.EncodeToPNG();UnityEngine.Object.DestroyImmediate(tex);
  122. string dir="Temp/DevilLink2Task13B05F/Bakes";Directory.CreateDirectory(dir);File.WriteAllBytes(dir+"/"+index+"_"+graphic.name+".png",png);
  123. tex=new Texture2D(2,2,TextureFormat.RGBA32,false,true);tex.LoadImage(png);tex.filterMode=FilterMode.Bilinear;tex.wrapMode=TextureWrapMode.Clamp;owned.Add(tex);
  124. var sprite=Sprite.Create(tex,new Rect(0,0,w,h),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(sprite);
  125. var go=graphic.gameObject;var tint=graphic.canvasRenderer.GetColor();var buttons=card.GetComponentsInChildren<Selectable>(true);
  126. var targets=new List<Selectable>();foreach(var button in buttons)if(button.targetGraphic==graphic)targets.Add(button);
  127. foreach(var effect in go.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
  128. bool hit=graphic.raycastTarget;UnityEngine.Object.DestroyImmediate(graphic);
  129. // Keep the original hit rectangle; bake shadow pixels outside it into a non-interactive child.
  130. var surface=go.AddComponent<Image>();surface.color=Color.clear;surface.raycastTarget=hit;surface.material=null;
  131. var art=new GameObject("NativeBakedArtwork",typeof(RectTransform),typeof(CanvasRenderer));var ar=(RectTransform)art.transform;ar.SetParent(go.transform,false);
  132. ar.anchorMin=ar.anchorMax=new Vector2(0,1);ar.pivot=new Vector2(0,1);ar.sizeDelta=bounds.size;ar.anchoredPosition=new Vector2(bounds.xMin-rect.xMin,bounds.yMax-rect.yMax);ar.SetAsFirstSibling();
  133. var image=art.AddComponent<Image>();image.sprite=sprite;image.color=Color.white;image.material=null;image.raycastTarget=false;image.type=Image.Type.Simple;
  134. foreach(var button in targets)button.targetGraphic=image;
  135. image.canvasRenderer.SetColor(tint);
  136. manifest.Add("BAKED "+go.name+" "+w+"x"+h+" native Image; no runtime MeshEffect; tint="+tint);
  137. }
  138. private static Vector2 Pixel(Vector3 p,Rect r,int w,int h)=>new Vector2((p.x-r.xMin)/r.width*w,(p.y-r.yMin)/r.height*h);
  139. private static float Cross(Vector2 a,Vector2 b)=>a.x*b.y-a.y*b.x;
  140. private static void Finish(){moving=false;if(!overlay)return;motion.ResetVisual();gate.alpha=1;gate.interactable=shown;gate.blocksRaycasts=shown;overlay.SetActive(shown);}
  141. }
  142. }