| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using DevilLink2.UI;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.EventSystems;
- using UnityEngine.UI;
- namespace DevilLink2.Editor
- {
- // Editor-only, explicitly enabled bounded trace. Never invokes Button.onClick or a reward service.
- [DefaultExecutionOrder(2000)]
- public sealed class WheelButtonDiagnostics : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler,
- IPointerDownHandler, IPointerUpHandler, ISelectHandler, IDeselectHandler, ISubmitHandler
- {
- private const string Menu = "Devil Link 2/Diagnostics/Wheel Buttons/";
- private static readonly List<string> rows = new List<string>();
- private static readonly List<RaycastResult> hits = new List<RaycastResult>();
- private static bool capturing, bypassScale, hoverIsolation;
- private sealed class HoverSnapshot
- {
- public Button Button; public ColorBlock Colors; public SpriteState Sprites;
- }
- private static readonly List<HoverSnapshot> hoverSnapshots = new List<HoverSnapshot>();
- private static string phase = "Unmarked", topHit;
- private static int hitFrame = -1;
- private Button button;
- private string previous, previousGraphic, previousTint, previousBlock, previousSprite, previousLayers, previousAlpha, previousState, previousMaterial;
- private static string PathOf(GameObject go)
- {
- if (!go) return "<none>";
- string name = go.name; for (var t = go.transform.parent; t; t = t.parent) name = t.name + "/" + name;
- return name;
- }
- [MenuItem(Menu + "Start Capture")]
- private static void StartCapture() { StartCapture(0); }
- [MenuItem(Menu + "Start Capture - SPIN Only")]
- private static void StartSpinCapture() { StartCapture(1); }
- [MenuItem(Menu + "Start Capture - CONFIRM Only")]
- private static void StartConfirmCapture() { StartCapture(2); }
- private static void StartCapture(int scope)
- {
- if (!Application.isPlaying) { Debug.LogWarning("Enter Main Play Mode with an isolated save before starting Wheel capture."); return; }
- StopCapture();
- var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
- if (!wheel) { Debug.LogWarning("LuckyWheelScreen was not found."); return; }
- rows.Clear(); phase = "Unmarked"; hitFrame = -1; capturing = true; bypassScale = false;
- rows.Add("frame,time,case,event,changes,button,selected,pointer,topHit,state,appliedState,localInteractable,effectiveInteractable,activeSelf,activeInHierarchy,componentEnabled,navigation,transition,colorBlock,expectedColorTint,target,sprite,graphicColor,rendererColor,material,layers,scale,parentScale,canvasGroups,transitions,scaleBypass,colorSpace,hoverIsolation");
- foreach (var b in new[] { wheel.SpinButton, wheel.ConfirmButton }) {
- if (scope == 1 && b != wheel.SpinButton || scope == 2 && b != wheel.ConfirmButton) continue;
- var probe = b.gameObject.AddComponent<WheelButtonDiagnostics>(); probe.button = b; probe.Record("Attach");
- }
- Debug.Log("Wheel button trace enabled. Mark A-E, reproduce briefly, then Stop and Export. No save or service calls are made by this probe.");
- }
- [MenuItem(Menu + "Enable Hover Isolation (Temporary)")]
- private static void EnableHoverIsolation()
- {
- if (!Application.isPlaying || !capturing || hoverIsolation) return;
- var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
- if (!wheel || !wheel.SpinButton || !wheel.ConfirmButton) return;
- phase = "Hover isolation BEFORE"; RecordAll("HoverBefore");
- foreach (var b in new[] { wheel.SpinButton, wheel.ConfirmButton })
- hoverSnapshots.Add(new HoverSnapshot { Button = b, Colors = b.colors, Sprites = b.spriteState });
- try {
- var spin = wheel.SpinButton; var colors = spin.colors;
- colors.highlightedColor = colors.selectedColor = colors.normalColor;
- colors.normalColor = Opaque(colors.normalColor); colors.highlightedColor = Opaque(colors.highlightedColor);
- colors.selectedColor = Opaque(colors.selectedColor); colors.pressedColor = Opaque(colors.pressedColor);
- colors.disabledColor = Opaque(colors.disabledColor); colors.fadeDuration = 0; spin.colors = colors;
- var confirm = wheel.ConfirmButton; var sprites = confirm.spriteState;
- var normal = confirm.targetGraphic as Image;
- if (!normal || !normal.sprite) throw new InvalidOperationException("CONFIRM normal sprite is unavailable; isolation cancelled.");
- sprites.highlightedSprite = sprites.selectedSprite = normal.sprite;
- confirm.spriteState = sprites; colors = confirm.colors; colors.fadeDuration = 0; confirm.colors = colors;
- hoverIsolation = true; phase = "Hover isolation ON"; RecordAll("HoverEnabled");
- Debug.Log("Temporary hover isolation enabled. Pressed/Disabled images and normal appearance are preserved. Restore or Stop Capture when finished.");
- } catch { RestoreHoverIsolation(); throw; }
- }
- private static Color Opaque(Color value) { value.a = 1; return value; }
- [MenuItem(Menu + "Restore Original Hover")]
- private static void RestoreHoverIsolation()
- {
- bool hadSnapshot = hoverSnapshots.Count > 0;
- // Clear snapshots first so lifecycle callbacks cannot re-enter restoration.
- var saved = hoverSnapshots.ToArray(); hoverSnapshots.Clear(); hoverIsolation = false;
- foreach (var snapshot in saved) if (snapshot.Button) {
- snapshot.Button.colors = snapshot.Colors;
- snapshot.Button.spriteState = snapshot.Sprites;
- }
- if (hadSnapshot) { phase = "Hover isolation RESTORED"; RecordAll("HoverRestored"); }
- }
- private static void RecordAll(string action)
- {
- foreach (var probe in UnityEngine.Object.FindObjectsByType<WheelButtonDiagnostics>(FindObjectsInactive.Include, FindObjectsSortMode.None))
- probe.Record(action);
- }
- [MenuItem(Menu + "Case A - Pointer on Blank")]
- private static void CaseA() { phase = "A blank"; }
- [MenuItem(Menu + "Case B - Pointer on SPIN")]
- private static void CaseB() { phase = "B SPIN"; }
- [MenuItem(Menu + "Case C - Pointer on CONFIRM")]
- private static void CaseC() { phase = "C CONFIRM"; }
- [MenuItem(Menu + "Case D - Keyboard Submit")]
- private static void CaseD() { phase = "D keyboard"; }
- [MenuItem(Menu + "Case E - Toggle Scale Bypass")]
- private static void CaseE() { if (capturing) { bypassScale = !bypassScale; phase = "E scale bypass=" + bypassScale; } }
- [MenuItem(Menu + "Select SPIN for Keyboard Test")]
- private static void SelectSpin() { SelectForKeyboard(false); }
- [MenuItem(Menu + "Select CONFIRM for Keyboard Test")]
- private static void SelectConfirm() { SelectForKeyboard(true); }
- private static void SelectForKeyboard(bool confirm)
- {
- if (!capturing || !EventSystem.current) return;
- var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
- if (!wheel) return;
- var target = confirm ? wheel.ConfirmButton : wheel.SpinButton;
- if (target.IsActive() && target.IsInteractable()) EventSystem.current.SetSelectedGameObject(target.gameObject);
- }
- [MenuItem(Menu + "Stop and Export")]
- private static void StopCapture()
- {
- RestoreHoverIsolation();
- try {
- if (capturing) {
- var path = System.IO.Path.Combine(Directory.GetParent(Application.dataPath).FullName, "Temp/DevilLink2Task13B04ER6/HoverIsolationTrace.csv");
- Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
- var encoding = new System.Text.UTF8Encoding(false);
- File.WriteAllLines(path, rows, encoding);
- var archive = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "HoverIsolationTrace_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff", CultureInfo.InvariantCulture) + "_" + Guid.NewGuid().ToString("N").Substring(0, 6) + ".csv");
- File.WriteAllLines(archive, rows, encoding);
- Debug.Log("Wheel hover trace exported: " + path + " (maximum 4096 records). Original hover settings restored.");
- }
- } finally {
- capturing = false; bypassScale = false;
- foreach (var probe in UnityEngine.Object.FindObjectsByType<WheelButtonDiagnostics>(FindObjectsInactive.Include, FindObjectsSortMode.None))
- UnityEngine.Object.DestroyImmediate(probe);
- }
- }
- [InitializeOnLoadMethod]
- private static void Register()
- {
- EditorApplication.playModeStateChanged -= PlayState; EditorApplication.playModeStateChanged += PlayState;
- AssemblyReloadEvents.beforeAssemblyReload -= BeforeReload; AssemblyReloadEvents.beforeAssemblyReload += BeforeReload;
- }
- private static void BeforeReload() { if (capturing || hoverSnapshots.Count > 0) StopCapture(); }
- private static void PlayState(PlayModeStateChange state)
- { if (state == PlayModeStateChange.ExitingPlayMode && (capturing || hoverSnapshots.Count > 0)) StopCapture(); }
- private void LateUpdate()
- {
- if (bypassScale) foreach (var popup in GetComponentsInParent<PopupAnimationController>()) popup.SetScale(1);
- Record("Frame", true);
- }
- private void OnEnable() { Record("Enable"); }
- private void OnDisable() { Record("Disable"); }
- private static string Cell(object value)
- {
- string quote = ((char)34).ToString();
- return quote + (value == null ? "" : value.ToString()).Replace(quote, quote + quote) + quote;
- }
- private static string ColorValue(Color value) => string.Format(CultureInfo.InvariantCulture,
- "({0:F5};{1:F5};{2:F5};{3:F5})", value.r, value.g, value.b, value.a);
- private static string SpriteValue(Image image) => image && image.overrideSprite
- ? image.overrideSprite.name + "#" + image.overrideSprite.GetInstanceID() : "<none>";
- private static string RendererValue(Graphic graphic)
- {
- var renderer = graphic ? graphic.GetComponent<CanvasRenderer>() : null;
- return renderer ? ColorValue(renderer.GetColor()) : "<missing>";
- }
- private string Layers()
- {
- var text = new System.Text.StringBuilder();
- foreach (var graphic in button.GetComponentsInChildren<Graphic>(true)) {
- var gradient = graphic.GetComponent<UIGradient>();
- text.Append(graphic.name).Append('#').Append(graphic.GetInstanceID()).Append(":enabled=").Append(graphic.enabled)
- .Append("/active=").Append(graphic.gameObject.activeInHierarchy)
- .Append("/G=").Append(ColorValue(graphic.color)).Append("/R=").Append(RendererValue(graphic))
- .Append("/sprite=").Append(SpriteValue(graphic as Image));
- if (gradient) text.Append("/gradient=").Append(gradient.enabled).Append(':')
- .Append(ColorValue(gradient.Top)).Append(':').Append(ColorValue(gradient.Bottom));
- text.Append(';');
- }
- return text.ToString();
- }
- private void Record(string action, bool changesOnly = false)
- {
- if (!capturing || !button || rows.Count >= 4096) return;
- var es = EventSystem.current;
- if (hitFrame != Time.frameCount) {
- hitFrame = Time.frameCount; topHit = "<none>"; hits.Clear();
- if (es) { es.RaycastAll(new PointerEventData(es) { position = Input.mousePosition }, hits); if (hits.Count > 0) topHit = PathOf(hits[0].gameObject); }
- }
- var graphic = button.targetGraphic; var image = graphic as Image;
- string state = typeof(Selectable).GetProperty("currentSelectionState", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(button)?.ToString();
- string groups = "", transitions = ""; bool modalLock = false;
- foreach (var g in GetComponentsInParent<CanvasGroup>()) groups += g.name + ":" + g.alpha.ToString("F5", CultureInfo.InvariantCulture) + "/" + g.interactable + "/" + g.blocksRaycasts + ";";
- foreach (var t in GetComponentsInParent<UITransition>()) {
- transitions += t.name + ":" + t.IsShown + "/" + t.IsTransitioning + ";";
- var group = t.GetComponent<CanvasGroup>();
- modalLock |= !t.IsShown || t.IsTransitioning || (group && !group.interactable);
- }
- var feedback = button as UIFeedbackButton;
- string applied = feedback && feedback.PreserveAppearanceDuringModalLock && button.interactable && modalLock ? "Normal" : state;
- var c = button.colors;
- Color tint = applied == "Highlighted" ? c.highlightedColor : applied == "Pressed" ? c.pressedColor
- : applied == "Selected" ? c.selectedColor : applied == "Disabled" ? c.disabledColor : c.normalColor;
- string block = "N=" + ColorValue(c.normalColor) + ";H=" + ColorValue(c.highlightedColor) + ";P=" + ColorValue(c.pressedColor)
- + ";S=" + ColorValue(c.selectedColor) + ";D=" + ColorValue(c.disabledColor)
- + ";multiplier=" + c.colorMultiplier.ToString("F5", CultureInfo.InvariantCulture) + ";fade=" + c.fadeDuration.ToString("F5", CultureInfo.InvariantCulture);
- string gColor = graphic ? ColorValue(graphic.color) : "<none>", rColor = RendererValue(graphic), sprite = SpriteValue(image), layers = Layers();
- var material = graphic ? graphic.material : null; // Do not request materialForRendering or create stencil materials.
- string mat = material ? material.name + "#" + material.GetInstanceID() + "/shader=" + (material.shader ? material.shader.name : "<none>")
- + (material.HasProperty("_Color") ? "/color=" + ColorValue(material.GetColor("_Color")) : "") : "<none>";
- string selected = PathOf(es ? es.currentSelectedGameObject : null);
- string stateKey = state + "/" + applied + "/" + selected + "/" + button.interactable + "/" + button.IsInteractable()
- + "/" + gameObject.activeSelf + "/" + gameObject.activeInHierarchy + "/" + button.enabled + "/" + button.navigation.mode
- + "/" + button.transition + "/" + PathOf(graphic ? graphic.gameObject : null) + "/" + transitions + "/" + bypassScale + "/" + hoverIsolation;
- // Pointer position, hit object and transforms are context, not per-frame logging triggers.
- string key = stateKey + block + gColor + rColor + sprite + mat + layers + groups;
- if (changesOnly && previous == key) return;
- string changes = previous == null ? "Initial" : "";
- if (previous != null) {
- if (stateKey != previousState) changes += "StateOrFocus;";
- if (block != previousBlock) changes += "ColorBlock;";
- if (gColor != previousGraphic) changes += "GraphicColor;";
- if (rColor != previousTint) changes += "RendererTint;";
- if (sprite != previousSprite) changes += "Sprite;";
- if (mat != previousMaterial) changes += "Material;";
- if (layers != previousLayers) changes += "GraphicLayer;";
- if (groups != previousAlpha) changes += "CanvasGroup;";
- }
- object[] values = { changes, PathOf(gameObject), selected, Input.mousePosition, topHit, state, applied,
- button.interactable, button.IsInteractable(), gameObject.activeSelf, gameObject.activeInHierarchy, button.enabled,
- button.navigation.mode, button.transition, block, button.transition == Selectable.Transition.ColorTint ? ColorValue(tint * c.colorMultiplier) : "NotUsedByTransition",
- PathOf(graphic ? graphic.gameObject : null), sprite, gColor, rColor, mat, layers, transform.localScale,
- transform.parent ? transform.parent.localScale : Vector3.one, groups, transitions, bypassScale, QualitySettings.activeColorSpace, hoverIsolation };
- previous = key; previousState = stateKey; previousBlock = block; previousGraphic = gColor; previousTint = rColor;
- previousSprite = sprite; previousMaterial = mat; previousLayers = layers; previousAlpha = groups;
- rows.Add(Time.frameCount + "," + Time.unscaledTime.ToString("F4", CultureInfo.InvariantCulture) + "," + Cell(phase) + "," + Cell(action) + "," + string.Join(",", Array.ConvertAll(values, Cell)));
- }
- public void OnPointerEnter(PointerEventData e) { Record("PointerEnter"); }
- public void OnPointerExit(PointerEventData e) { Record("PointerExit"); }
- public void OnPointerDown(PointerEventData e) { Record("PointerDown"); }
- public void OnPointerUp(PointerEventData e) { Record("PointerUp"); }
- public void OnSelect(BaseEventData e) { Record("Select"); }
- public void OnDeselect(BaseEventData e) { Record("Deselect"); }
- public void OnSubmit(BaseEventData e) { Record("Submit"); }
- }
- }
|