ConsoleFace.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace Fateforge
  5. {
  6. // Project the enamel and keycaps toward a common point above the cabinet.
  7. // Button hit regions stay rectangular, including the front lip.
  8. [DisallowMultipleComponent]
  9. public sealed class ConsoleFace : BaseMeshEffect
  10. {
  11. public RectTransform cabinet;
  12. public float lip;
  13. readonly List<UIVertex> face = new List<UIVertex>();
  14. readonly List<UIVertex> layers = new List<UIVertex>();
  15. public static void Fit(Graphic graphic, RectTransform cabinet, float lip = 0)
  16. {
  17. if (!graphic.TryGetComponent<ConsoleFace>(out var effect))
  18. effect = graphic.gameObject.AddComponent<ConsoleFace>();
  19. effect.cabinet = cabinet;
  20. effect.lip = lip;
  21. graphic.SetVerticesDirty();
  22. }
  23. public override void ModifyMesh(VertexHelper mesh)
  24. {
  25. if (!IsActive() || !cabinet) return;
  26. var rect = graphic.rectTransform.rect;
  27. if (rect.height <= lip) return;
  28. float axis = transform.InverseTransformPoint(cabinet.position).x;
  29. face.Clear();
  30. mesh.GetUIVertexStream(face);
  31. for (int i = 0; i < face.Count; i++)
  32. {
  33. var vertex = face[i];
  34. float far = Mathf.InverseLerp(rect.yMin, rect.yMax, vertex.position.y);
  35. vertex.position.x = Mathf.Lerp(vertex.position.x, axis, far * rect.height / 950f);
  36. vertex.position.y += lip * (1f - far);
  37. face[i] = vertex;
  38. }
  39. mesh.Clear();
  40. if (lip > 0)
  41. {
  42. layers.Clear();
  43. for (int step = 2; step >= 1; step--)
  44. {
  45. var shade = step == 2 ? new Color(.22f, .13f, .10f) : new Color(.50f, .32f, .21f);
  46. foreach (var front in face)
  47. {
  48. var side = front;
  49. side.position.y -= lip * step / 2f;
  50. side.color = (Color)front.color * shade;
  51. layers.Add(side);
  52. }
  53. }
  54. layers.AddRange(face);
  55. mesh.AddUIVertexTriangleStream(layers);
  56. }
  57. else mesh.AddUIVertexTriangleStream(face);
  58. }
  59. }
  60. }