WheelButtonDiagnostics.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Reflection;
  6. using DevilLink2.UI;
  7. using UnityEditor;
  8. using UnityEngine;
  9. using UnityEngine.EventSystems;
  10. using UnityEngine.UI;
  11. namespace DevilLink2.Editor
  12. {
  13. // Editor-only, explicitly enabled bounded trace. Never invokes Button.onClick or a reward service.
  14. [DefaultExecutionOrder(2000)]
  15. public sealed class WheelButtonDiagnostics : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler,
  16. IPointerDownHandler, IPointerUpHandler, ISelectHandler, IDeselectHandler, ISubmitHandler
  17. {
  18. private const string Menu = "Devil Link 2/Diagnostics/Wheel Buttons/";
  19. private static readonly List<string> rows = new List<string>();
  20. private static readonly List<RaycastResult> hits = new List<RaycastResult>();
  21. private static bool capturing, bypassScale, hoverIsolation;
  22. private sealed class HoverSnapshot
  23. {
  24. public Button Button; public ColorBlock Colors; public SpriteState Sprites;
  25. }
  26. private static readonly List<HoverSnapshot> hoverSnapshots = new List<HoverSnapshot>();
  27. private static string phase = "Unmarked", topHit;
  28. private static int hitFrame = -1;
  29. private Button button;
  30. private string previous, previousGraphic, previousTint, previousBlock, previousSprite, previousLayers, previousAlpha, previousState, previousMaterial;
  31. private static string PathOf(GameObject go)
  32. {
  33. if (!go) return "<none>";
  34. string name = go.name; for (var t = go.transform.parent; t; t = t.parent) name = t.name + "/" + name;
  35. return name;
  36. }
  37. [MenuItem(Menu + "Start Capture")]
  38. private static void StartCapture() { StartCapture(0); }
  39. [MenuItem(Menu + "Start Capture - SPIN Only")]
  40. private static void StartSpinCapture() { StartCapture(1); }
  41. [MenuItem(Menu + "Start Capture - CONFIRM Only")]
  42. private static void StartConfirmCapture() { StartCapture(2); }
  43. private static void StartCapture(int scope)
  44. {
  45. if (!Application.isPlaying) { Debug.LogWarning("Enter Main Play Mode with an isolated save before starting Wheel capture."); return; }
  46. StopCapture();
  47. var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
  48. if (!wheel) { Debug.LogWarning("LuckyWheelScreen was not found."); return; }
  49. rows.Clear(); phase = "Unmarked"; hitFrame = -1; capturing = true; bypassScale = false;
  50. 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");
  51. foreach (var b in new[] { wheel.SpinButton, wheel.ConfirmButton }) {
  52. if (scope == 1 && b != wheel.SpinButton || scope == 2 && b != wheel.ConfirmButton) continue;
  53. var probe = b.gameObject.AddComponent<WheelButtonDiagnostics>(); probe.button = b; probe.Record("Attach");
  54. }
  55. 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.");
  56. }
  57. [MenuItem(Menu + "Enable Hover Isolation (Temporary)")]
  58. private static void EnableHoverIsolation()
  59. {
  60. if (!Application.isPlaying || !capturing || hoverIsolation) return;
  61. var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
  62. if (!wheel || !wheel.SpinButton || !wheel.ConfirmButton) return;
  63. phase = "Hover isolation BEFORE"; RecordAll("HoverBefore");
  64. foreach (var b in new[] { wheel.SpinButton, wheel.ConfirmButton })
  65. hoverSnapshots.Add(new HoverSnapshot { Button = b, Colors = b.colors, Sprites = b.spriteState });
  66. try {
  67. var spin = wheel.SpinButton; var colors = spin.colors;
  68. colors.highlightedColor = colors.selectedColor = colors.normalColor;
  69. colors.normalColor = Opaque(colors.normalColor); colors.highlightedColor = Opaque(colors.highlightedColor);
  70. colors.selectedColor = Opaque(colors.selectedColor); colors.pressedColor = Opaque(colors.pressedColor);
  71. colors.disabledColor = Opaque(colors.disabledColor); colors.fadeDuration = 0; spin.colors = colors;
  72. var confirm = wheel.ConfirmButton; var sprites = confirm.spriteState;
  73. var normal = confirm.targetGraphic as Image;
  74. if (!normal || !normal.sprite) throw new InvalidOperationException("CONFIRM normal sprite is unavailable; isolation cancelled.");
  75. sprites.highlightedSprite = sprites.selectedSprite = normal.sprite;
  76. confirm.spriteState = sprites; colors = confirm.colors; colors.fadeDuration = 0; confirm.colors = colors;
  77. hoverIsolation = true; phase = "Hover isolation ON"; RecordAll("HoverEnabled");
  78. Debug.Log("Temporary hover isolation enabled. Pressed/Disabled images and normal appearance are preserved. Restore or Stop Capture when finished.");
  79. } catch { RestoreHoverIsolation(); throw; }
  80. }
  81. private static Color Opaque(Color value) { value.a = 1; return value; }
  82. [MenuItem(Menu + "Restore Original Hover")]
  83. private static void RestoreHoverIsolation()
  84. {
  85. bool hadSnapshot = hoverSnapshots.Count > 0;
  86. // Clear snapshots first so lifecycle callbacks cannot re-enter restoration.
  87. var saved = hoverSnapshots.ToArray(); hoverSnapshots.Clear(); hoverIsolation = false;
  88. foreach (var snapshot in saved) if (snapshot.Button) {
  89. snapshot.Button.colors = snapshot.Colors;
  90. snapshot.Button.spriteState = snapshot.Sprites;
  91. }
  92. if (hadSnapshot) { phase = "Hover isolation RESTORED"; RecordAll("HoverRestored"); }
  93. }
  94. private static void RecordAll(string action)
  95. {
  96. foreach (var probe in UnityEngine.Object.FindObjectsByType<WheelButtonDiagnostics>(FindObjectsInactive.Include, FindObjectsSortMode.None))
  97. probe.Record(action);
  98. }
  99. [MenuItem(Menu + "Case A - Pointer on Blank")]
  100. private static void CaseA() { phase = "A blank"; }
  101. [MenuItem(Menu + "Case B - Pointer on SPIN")]
  102. private static void CaseB() { phase = "B SPIN"; }
  103. [MenuItem(Menu + "Case C - Pointer on CONFIRM")]
  104. private static void CaseC() { phase = "C CONFIRM"; }
  105. [MenuItem(Menu + "Case D - Keyboard Submit")]
  106. private static void CaseD() { phase = "D keyboard"; }
  107. [MenuItem(Menu + "Case E - Toggle Scale Bypass")]
  108. private static void CaseE() { if (capturing) { bypassScale = !bypassScale; phase = "E scale bypass=" + bypassScale; } }
  109. [MenuItem(Menu + "Select SPIN for Keyboard Test")]
  110. private static void SelectSpin() { SelectForKeyboard(false); }
  111. [MenuItem(Menu + "Select CONFIRM for Keyboard Test")]
  112. private static void SelectConfirm() { SelectForKeyboard(true); }
  113. private static void SelectForKeyboard(bool confirm)
  114. {
  115. if (!capturing || !EventSystem.current) return;
  116. var wheel = UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
  117. if (!wheel) return;
  118. var target = confirm ? wheel.ConfirmButton : wheel.SpinButton;
  119. if (target.IsActive() && target.IsInteractable()) EventSystem.current.SetSelectedGameObject(target.gameObject);
  120. }
  121. [MenuItem(Menu + "Stop and Export")]
  122. private static void StopCapture()
  123. {
  124. RestoreHoverIsolation();
  125. try {
  126. if (capturing) {
  127. var path = System.IO.Path.Combine(Directory.GetParent(Application.dataPath).FullName, "Temp/DevilLink2Task13B04ER6/HoverIsolationTrace.csv");
  128. Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
  129. var encoding = new System.Text.UTF8Encoding(false);
  130. File.WriteAllLines(path, rows, encoding);
  131. 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");
  132. File.WriteAllLines(archive, rows, encoding);
  133. Debug.Log("Wheel hover trace exported: " + path + " (maximum 4096 records). Original hover settings restored.");
  134. }
  135. } finally {
  136. capturing = false; bypassScale = false;
  137. foreach (var probe in UnityEngine.Object.FindObjectsByType<WheelButtonDiagnostics>(FindObjectsInactive.Include, FindObjectsSortMode.None))
  138. UnityEngine.Object.DestroyImmediate(probe);
  139. }
  140. }
  141. [InitializeOnLoadMethod]
  142. private static void Register()
  143. {
  144. EditorApplication.playModeStateChanged -= PlayState; EditorApplication.playModeStateChanged += PlayState;
  145. AssemblyReloadEvents.beforeAssemblyReload -= BeforeReload; AssemblyReloadEvents.beforeAssemblyReload += BeforeReload;
  146. }
  147. private static void BeforeReload() { if (capturing || hoverSnapshots.Count > 0) StopCapture(); }
  148. private static void PlayState(PlayModeStateChange state)
  149. { if (state == PlayModeStateChange.ExitingPlayMode && (capturing || hoverSnapshots.Count > 0)) StopCapture(); }
  150. private void LateUpdate()
  151. {
  152. if (bypassScale) foreach (var popup in GetComponentsInParent<PopupAnimationController>()) popup.SetScale(1);
  153. Record("Frame", true);
  154. }
  155. private void OnEnable() { Record("Enable"); }
  156. private void OnDisable() { Record("Disable"); }
  157. private static string Cell(object value)
  158. {
  159. string quote = ((char)34).ToString();
  160. return quote + (value == null ? "" : value.ToString()).Replace(quote, quote + quote) + quote;
  161. }
  162. private static string ColorValue(Color value) => string.Format(CultureInfo.InvariantCulture,
  163. "({0:F5};{1:F5};{2:F5};{3:F5})", value.r, value.g, value.b, value.a);
  164. private static string SpriteValue(Image image) => image && image.overrideSprite
  165. ? image.overrideSprite.name + "#" + image.overrideSprite.GetInstanceID() : "<none>";
  166. private static string RendererValue(Graphic graphic)
  167. {
  168. var renderer = graphic ? graphic.GetComponent<CanvasRenderer>() : null;
  169. return renderer ? ColorValue(renderer.GetColor()) : "<missing>";
  170. }
  171. private string Layers()
  172. {
  173. var text = new System.Text.StringBuilder();
  174. foreach (var graphic in button.GetComponentsInChildren<Graphic>(true)) {
  175. var gradient = graphic.GetComponent<UIGradient>();
  176. text.Append(graphic.name).Append('#').Append(graphic.GetInstanceID()).Append(":enabled=").Append(graphic.enabled)
  177. .Append("/active=").Append(graphic.gameObject.activeInHierarchy)
  178. .Append("/G=").Append(ColorValue(graphic.color)).Append("/R=").Append(RendererValue(graphic))
  179. .Append("/sprite=").Append(SpriteValue(graphic as Image));
  180. if (gradient) text.Append("/gradient=").Append(gradient.enabled).Append(':')
  181. .Append(ColorValue(gradient.Top)).Append(':').Append(ColorValue(gradient.Bottom));
  182. text.Append(';');
  183. }
  184. return text.ToString();
  185. }
  186. private void Record(string action, bool changesOnly = false)
  187. {
  188. if (!capturing || !button || rows.Count >= 4096) return;
  189. var es = EventSystem.current;
  190. if (hitFrame != Time.frameCount) {
  191. hitFrame = Time.frameCount; topHit = "<none>"; hits.Clear();
  192. if (es) { es.RaycastAll(new PointerEventData(es) { position = Input.mousePosition }, hits); if (hits.Count > 0) topHit = PathOf(hits[0].gameObject); }
  193. }
  194. var graphic = button.targetGraphic; var image = graphic as Image;
  195. string state = typeof(Selectable).GetProperty("currentSelectionState", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(button)?.ToString();
  196. string groups = "", transitions = ""; bool modalLock = false;
  197. foreach (var g in GetComponentsInParent<CanvasGroup>()) groups += g.name + ":" + g.alpha.ToString("F5", CultureInfo.InvariantCulture) + "/" + g.interactable + "/" + g.blocksRaycasts + ";";
  198. foreach (var t in GetComponentsInParent<UITransition>()) {
  199. transitions += t.name + ":" + t.IsShown + "/" + t.IsTransitioning + ";";
  200. var group = t.GetComponent<CanvasGroup>();
  201. modalLock |= !t.IsShown || t.IsTransitioning || (group && !group.interactable);
  202. }
  203. var feedback = button as UIFeedbackButton;
  204. string applied = feedback && feedback.PreserveAppearanceDuringModalLock && button.interactable && modalLock ? "Normal" : state;
  205. var c = button.colors;
  206. Color tint = applied == "Highlighted" ? c.highlightedColor : applied == "Pressed" ? c.pressedColor
  207. : applied == "Selected" ? c.selectedColor : applied == "Disabled" ? c.disabledColor : c.normalColor;
  208. string block = "N=" + ColorValue(c.normalColor) + ";H=" + ColorValue(c.highlightedColor) + ";P=" + ColorValue(c.pressedColor)
  209. + ";S=" + ColorValue(c.selectedColor) + ";D=" + ColorValue(c.disabledColor)
  210. + ";multiplier=" + c.colorMultiplier.ToString("F5", CultureInfo.InvariantCulture) + ";fade=" + c.fadeDuration.ToString("F5", CultureInfo.InvariantCulture);
  211. string gColor = graphic ? ColorValue(graphic.color) : "<none>", rColor = RendererValue(graphic), sprite = SpriteValue(image), layers = Layers();
  212. var material = graphic ? graphic.material : null; // Do not request materialForRendering or create stencil materials.
  213. string mat = material ? material.name + "#" + material.GetInstanceID() + "/shader=" + (material.shader ? material.shader.name : "<none>")
  214. + (material.HasProperty("_Color") ? "/color=" + ColorValue(material.GetColor("_Color")) : "") : "<none>";
  215. string selected = PathOf(es ? es.currentSelectedGameObject : null);
  216. string stateKey = state + "/" + applied + "/" + selected + "/" + button.interactable + "/" + button.IsInteractable()
  217. + "/" + gameObject.activeSelf + "/" + gameObject.activeInHierarchy + "/" + button.enabled + "/" + button.navigation.mode
  218. + "/" + button.transition + "/" + PathOf(graphic ? graphic.gameObject : null) + "/" + transitions + "/" + bypassScale + "/" + hoverIsolation;
  219. // Pointer position, hit object and transforms are context, not per-frame logging triggers.
  220. string key = stateKey + block + gColor + rColor + sprite + mat + layers + groups;
  221. if (changesOnly && previous == key) return;
  222. string changes = previous == null ? "Initial" : "";
  223. if (previous != null) {
  224. if (stateKey != previousState) changes += "StateOrFocus;";
  225. if (block != previousBlock) changes += "ColorBlock;";
  226. if (gColor != previousGraphic) changes += "GraphicColor;";
  227. if (rColor != previousTint) changes += "RendererTint;";
  228. if (sprite != previousSprite) changes += "Sprite;";
  229. if (mat != previousMaterial) changes += "Material;";
  230. if (layers != previousLayers) changes += "GraphicLayer;";
  231. if (groups != previousAlpha) changes += "CanvasGroup;";
  232. }
  233. object[] values = { changes, PathOf(gameObject), selected, Input.mousePosition, topHit, state, applied,
  234. button.interactable, button.IsInteractable(), gameObject.activeSelf, gameObject.activeInHierarchy, button.enabled,
  235. button.navigation.mode, button.transition, block, button.transition == Selectable.Transition.ColorTint ? ColorValue(tint * c.colorMultiplier) : "NotUsedByTransition",
  236. PathOf(graphic ? graphic.gameObject : null), sprite, gColor, rColor, mat, layers, transform.localScale,
  237. transform.parent ? transform.parent.localScale : Vector3.one, groups, transitions, bypassScale, QualitySettings.activeColorSpace, hoverIsolation };
  238. previous = key; previousState = stateKey; previousBlock = block; previousGraphic = gColor; previousTint = rColor;
  239. previousSprite = sprite; previousMaterial = mat; previousLayers = layers; previousAlpha = groups;
  240. rows.Add(Time.frameCount + "," + Time.unscaledTime.ToString("F4", CultureInfo.InvariantCulture) + "," + Cell(phase) + "," + Cell(action) + "," + string.Join(",", Array.ConvertAll(values, Cell)));
  241. }
  242. public void OnPointerEnter(PointerEventData e) { Record("PointerEnter"); }
  243. public void OnPointerExit(PointerEventData e) { Record("PointerExit"); }
  244. public void OnPointerDown(PointerEventData e) { Record("PointerDown"); }
  245. public void OnPointerUp(PointerEventData e) { Record("PointerUp"); }
  246. public void OnSelect(BaseEventData e) { Record("Select"); }
  247. public void OnDeselect(BaseEventData e) { Record("Deselect"); }
  248. public void OnSubmit(BaseEventData e) { Record("Submit"); }
  249. }
  250. }