| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Security.Cryptography;
- using System.Text;
- using DevilLink2.UI;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.UI;
- namespace DevilLink2.Editor
- {
- [InitializeOnLoad]
- public static class WheelFormalRenderCompare
- {
- private const string Menu="Tools/Devil Link 2/Diagnostics/Popup Render Compare/";
- private sealed class Effect { public Type Type;public string Json; }
- private sealed class Saved {
- public GameObject Object;public Type Type;public string Json;public Image Native;
- public readonly List<Effect> Effects=new List<Effect>();public readonly List<Selectable> Targets=new List<Selectable>();
- public Color Tint;public bool Enabled;
- public readonly Dictionary<Selectable,SpriteState> SpriteStates=new Dictionary<Selectable,SpriteState>();
- }
- private static readonly List<Saved> saved=new List<Saved>();
- private static readonly List<UnityEngine.Object> owned=new List<UnityEngine.Object>();
- private static readonly List<string> manifest=new List<string>();
- private static readonly Dictionary<UITransition,bool?> overrides=new Dictionary<UITransition,bool?>();
- static WheelFormalRenderCompare(){EditorApplication.playModeStateChanged+=Changed;AssemblyReloadEvents.beforeAssemblyReload+=Restore;}
- [MenuItem(Menu+"A - Formal Original Rendering (Static)")]
- private static void A(){Apply(false,true);}
- [MenuItem(Menu+"B - Formal Native PNG (Static)")]
- private static void B(){Apply(true,true);}
- [MenuItem(Menu+"C - Formal Native PNG + Static")]
- private static void C(){Apply(true,false);}
- [MenuItem(Menu+"Restore Formal Wheel")]
- private static void Restore(){
- foreach(var pair in overrides)if(pair.Key)pair.Key.SetPopupAnimationOverride(pair.Value);overrides.Clear();
- for(int i=saved.Count-1;i>=0;i--){var entry=saved[i];if(!entry.Object)continue;
- foreach(var effect in entry.Object.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
- if(entry.Native)UnityEngine.Object.DestroyImmediate(entry.Native);
- var original=(Image)entry.Object.AddComponent(entry.Type);EditorJsonUtility.FromJsonOverwrite(entry.Json,original);
- foreach(var effect in entry.Effects){var component=entry.Object.AddComponent(effect.Type);EditorJsonUtility.FromJsonOverwrite(effect.Json,component);}
- foreach(var target in entry.Targets)if(target){target.targetGraphic=original;if(entry.SpriteStates.ContainsKey(target))target.spriteState=entry.SpriteStates[target];}
- original.canvasRenderer.SetColor(entry.Tint);
- }
- saved.Clear();foreach(var item in owned)if(item)UnityEngine.Object.DestroyImmediate(item);owned.Clear();
- }
- private static void Changed(PlayModeStateChange state){if(state==PlayModeStateChange.ExitingPlayMode)Restore();}
- private static void Apply(bool png,bool motion){
- if(!Application.isPlaying){Debug.LogWarning("Requires the real Main Play Mode. No test copy is created.");return;}
- var wheel=UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
- if(!wheel||wheel.IsSpinning){Debug.LogWarning("Wheel must be initialized and not spinning before mode changes.");return;}
- Restore();manifest.Clear();manifest.Add("REAL Wheel instance="+wheel.GetInstanceID()+" mode="+(png?(motion?"B":"C"):"A"));
- try{
- foreach(var root in new[]{wheel.gameObject,wheel.ResultPanel}){
- var transition=root.GetComponent<UITransition>();if(!transition)throw new InvalidOperationException("Missing real UITransition");
- // Motion overrides retired: every formal UITransition is synchronous.
- }
- if(png)foreach(var graphic in wheel.GetComponentsInChildren<Image>(true).ToArray()){
- if(graphic.GetType()==typeof(Image) && !graphic.GetComponent<UIGradient>())continue;
- Convert(graphic,wheel);
- }
- Directory.CreateDirectory("Temp/DevilLink2Task13B05G");File.WriteAllLines("Temp/DevilLink2Task13B05G/LastFormalManifest.txt",manifest);
- Debug.Log("Formal rendering mode ready (popup motion retired; static only); use actual Lobby WHEEL / X / SPIN / CONFIRM. Real rewards remain active. Use an isolated save.");
- }catch(Exception e){Restore();Debug.LogException(e);}
- }
- private static void Convert(Image source,LuckyWheelScreen wheel){
- var entry=new Saved{Object=source.gameObject,Type=source.GetType(),Json=EditorJsonUtility.ToJson(source),Tint=source.canvasRenderer.GetColor(),Enabled=source.enabled};
- foreach(var e in source.GetComponents<BaseMeshEffect>())entry.Effects.Add(new Effect{Type=e.GetType(),Json=EditorJsonUtility.ToJson(e)});
- foreach(var target in wheel.GetComponentsInChildren<Selectable>(true))if(target.targetGraphic==source){entry.Targets.Add(target);entry.SpriteStates[target]=target.spriteState;}
- Sprite sprite=null;var variants=new Dictionary<Sprite,Sprite>();
- if(source.sprite && (source.GetType().Name=="WheelSpinOrnament"||source.GetType().Name=="WheelPointerGraphic")){
- sprite=source.sprite;manifest.Add("REUSE existing PNG sprite: "+source.name);
- }else{
- var temp=new GameObject("GraphicBakeScratch",typeof(RectTransform),typeof(CanvasRenderer));temp.hideFlags=HideFlags.HideAndDontSave;
- try{
- // Scratch contains graphics only, never a screen, service, Button or player.
- temp.transform.SetParent(source.GetComponentInParent<Canvas>().transform,false);
- var r=(RectTransform)temp.transform;r.pivot=source.rectTransform.pivot;r.sizeDelta=source.rectTransform.rect.size;r.anchoredPosition=new Vector2(-100000,-100000);
- var copy=(Image)temp.AddComponent(source.GetType());EditorJsonUtility.FromJsonOverwrite(entry.Json,copy);copy.enabled=true;
- foreach(var e in entry.Effects)if(e.Type.Namespace!="UnityEngine.UI"){
- var effect=(BaseMeshEffect)temp.AddComponent(e.Type);EditorJsonUtility.FromJsonOverwrite(e.Json,effect);
- }
- string key;
- using(var sha=SHA256.Create())key=BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(entry.Type.FullName+entry.Json+source.rectTransform.rect+string.Join("",entry.Effects.Select(e=>e.Json))))).Replace("-","");
- var normal=source.sprite;
- copy.overrideSprite=normal;sprite=Bake(copy,key+"_normal");
- if(normal)variants[normal]=sprite;
- foreach(var target in entry.Targets)if(target.transition==Selectable.Transition.SpriteSwap){
- var state=target.spriteState;
- foreach(var variant in new[]{state.highlightedSprite,state.pressedSprite,state.selectedSprite,state.disabledSprite}){
- if(!variant||variants.ContainsKey(variant))continue;
- copy.overrideSprite=variant;variants[variant]=Bake(copy,key+"_"+variant.GetInstanceID());
- }
- }
- }finally{UnityEngine.Object.DestroyImmediate(temp);}
- }
- saved.Add(entry);
- foreach(var effect in source.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
- bool hit=source.raycastTarget,maskable=source.maskable;UnityEngine.Object.DestroyImmediate(source);
- var image=entry.Object.AddComponent<Image>();entry.Native=image;image.sprite=sprite;image.color=Color.white;image.material=null;
- image.raycastTarget=entry.Targets.Count>0?hit:false;image.maskable=maskable;image.type=Image.Type.Simple;
- foreach(var effect in entry.Effects)if(effect.Type.Namespace=="UnityEngine.UI"){
- var component=entry.Object.AddComponent(effect.Type);EditorJsonUtility.FromJsonOverwrite(effect.Json,component);
- }
- foreach(var target in entry.Targets){
- target.targetGraphic=image;
- if(target.transition==Selectable.Transition.SpriteSwap){var state=target.spriteState;
- if(state.highlightedSprite && variants.ContainsKey(state.highlightedSprite))state.highlightedSprite=variants[state.highlightedSprite];
- if(state.selectedSprite && variants.ContainsKey(state.selectedSprite))state.selectedSprite=variants[state.selectedSprite];
- if(state.pressedSprite && variants.ContainsKey(state.pressedSprite))state.pressedSprite=variants[state.pressedSprite];
- if(state.disabledSprite && variants.ContainsKey(state.disabledSprite))state.disabledSprite=variants[state.disabledSprite];
- target.spriteState=state;
- }
- }
- image.enabled=entry.Enabled;image.canvasRenderer.SetColor(entry.Tint);
- manifest.Add("REPLACED same object "+entry.Object.name+" from "+entry.Type.Name+" with native Image; white/opaque; Rect unchanged");
- }
- private static Sprite Bake(Image graphic,string cacheKey){
- string cached="Temp/DevilLink2Task13B05G/Bakes/"+cacheKey+".png";
- if(File.Exists(cached)){
- var texture=new Texture2D(2,2,TextureFormat.RGBA32,false,true);texture.LoadImage(File.ReadAllBytes(cached));texture.filterMode=FilterMode.Bilinear;texture.wrapMode=TextureWrapMode.Clamp;owned.Add(texture);
- var reused=Sprite.Create(texture,new Rect(0,0,texture.width,texture.height),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(reused);manifest.Add("REUSE cached PNG "+cached);return reused;
- }
- var rect=graphic.rectTransform.rect;if(rect.width<=0||rect.height<=0)throw new InvalidOperationException("Zero-size graphic");
- var mesh=new Mesh();using(var helper=new VertexHelper()){
- var method=graphic.GetType().GetMethod("OnPopulateMesh",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic,null,new[]{typeof(VertexHelper)},null);
- method.Invoke(graphic,new object[]{helper});
- foreach(var effect in graphic.GetComponents<BaseMeshEffect>())if(effect.enabled && effect.GetType().Namespace!="UnityEngine.UI")effect.ModifyMesh(helper);
- helper.FillMesh(mesh);
- }
- var vertices=mesh.vertices;var colors=mesh.colors32;var triangles=mesh.triangles;var uv=mesh.uv;
- if(vertices.Length==0){UnityEngine.Object.DestroyImmediate(mesh);throw new InvalidOperationException("Empty graphic mesh: "+graphic.name);}
- // Read authored textures without changing their importers, preserving custom panel UV slicing.
- Color[] texels=null;int tw=0,th=0;
- if(graphic.sprite){
- var texture=graphic.mainTexture;tw=texture.width;th=texture.height;
- var rt=RenderTexture.GetTemporary(tw,th,0,RenderTextureFormat.ARGB32,RenderTextureReadWrite.Linear);var previous=RenderTexture.active;
- 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);}
- finally{RenderTexture.active=previous;RenderTexture.ReleaseTemporary(rt);}
- }
- var bounds=rect;
- 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);}
- int w=Mathf.Clamp(Mathf.CeilToInt(bounds.width*2),1,2048),h=Mathf.Clamp(Mathf.CeilToInt(bounds.height*2),1,2048);
- var pixels=new Color[w*h];
- for(int t=0;t<triangles.Length;t+=3){
- int a=triangles[t],b=triangles[t+1],c=triangles[t+2];
- Vector2 x=Pixel(vertices[a],bounds,w,h),y=Pixel(vertices[b],bounds,w,h),z=Pixel(vertices[c],bounds,w,h);
- float area=Cross(y-x,z-x);if(Mathf.Abs(area)<.00001f)continue;
- 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);
- 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);
- for(int py=bottom;py<=top;py++)for(int px=left;px<=right;px++){
- 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;
- if(u<-.00001f||v<-.00001f||q<-.00001f)continue;
- Color color=(Color)colors[a]*u+(Color)colors[b]*v+(Color)colors[c]*q;
- 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;}
- int k=py*w+px;var old=pixels[k];float alpha=color.a+old.a*(1-color.a);
- 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;
- }
- }
- UnityEngine.Object.DestroyImmediate(mesh);
- var tex=new Texture2D(w,h,TextureFormat.RGBA32,false,true);tex.SetPixels(pixels);tex.Apply();
- byte[] png=tex.EncodeToPNG();UnityEngine.Object.DestroyImmediate(tex);
- string dir="Temp/DevilLink2Task13B05G/Bakes";Directory.CreateDirectory(dir);
- string file=dir+"/"+cacheKey+".png";
- if(File.Exists(file))png=File.ReadAllBytes(file);else File.WriteAllBytes(file,png);
- manifest.Add("PNG "+file+" "+w+"x"+h);
- tex=new Texture2D(2,2,TextureFormat.RGBA32,false,true);tex.LoadImage(png);tex.filterMode=FilterMode.Bilinear;tex.wrapMode=TextureWrapMode.Clamp;owned.Add(tex);
- var sprite=Sprite.Create(tex,new Rect(0,0,w,h),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(sprite);
- return sprite;
- }
- 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);
- private static float Cross(Vector2 a,Vector2 b)=>a.x*b.y-a.y*b.x;
- }
- }
|