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 Effects=new List();public readonly List Targets=new List(); public Color Tint;public bool Enabled; public readonly Dictionary SpriteStates=new Dictionary(); } private static readonly List saved=new List(); private static readonly List owned=new List(); private static readonly List manifest=new List(); private static readonly Dictionary overrides=new Dictionary(); 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())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(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();if(!transition)throw new InvalidOperationException("Missing real UITransition"); // Motion overrides retired: every formal UITransition is synchronous. } if(png)foreach(var graphic in wheel.GetComponentsInChildren(true).ToArray()){ if(graphic.GetType()==typeof(Image) && !graphic.GetComponent())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())entry.Effects.Add(new Effect{Type=e.GetType(),Json=EditorJsonUtility.ToJson(e)}); foreach(var target in wheel.GetComponentsInChildren(true))if(target.targetGraphic==source){entry.Targets.Add(target);entry.SpriteStates[target]=target.spriteState;} Sprite sprite=null;var variants=new Dictionary(); 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().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())UnityEngine.Object.DestroyImmediate(effect); bool hit=source.raycastTarget,maskable=source.maskable;UnityEngine.Object.DestroyImmediate(source); var image=entry.Object.AddComponent();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())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;t0?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; } }