BoardLayoutCalculator.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using UnityEngine;
  3. namespace DevilLink2.Presentation
  4. {
  5. public readonly struct BoardLayout
  6. {
  7. public float TileSize { get; }
  8. public Vector2 Size { get; }
  9. public float CellGap { get; }
  10. public float Padding { get; }
  11. public BoardLayout(float tileSize, Vector2 size) { TileSize = tileSize; Size = size; CellGap = BoardLayoutCalculator.Gap; Padding = BoardLayoutCalculator.Pad + BoardLayoutCalculator.Inset; }
  12. public BoardLayout(float tileSize, Vector2 size, float gap, float padding)
  13. { TileSize = tileSize; Size = size; CellGap = gap; Padding = padding; }
  14. public Vector2 TilePosition(int row, int column) => new Vector2(
  15. Padding + column * (TileSize + CellGap),
  16. -(Padding + row * (TileSize + CellGap)));
  17. }
  18. public static class BoardLayoutCalculator
  19. {
  20. public const int Gap = 2, Inset = 4, Pad = 12, AreaWidth = 418, AreaHeight = 385;
  21. public static BoardLayout Calculate(int columns, int rows)
  22. {
  23. if (columns <= 0 || rows <= 0) throw new ArgumentOutOfRangeException();
  24. float tile = Mathf.Max(18, Mathf.Min(44,
  25. Mathf.Floor((AreaHeight - 2f * (Pad + Inset) - Gap * (rows - 1f)) / rows),
  26. Mathf.Floor((AreaWidth - 2f * (Pad + Inset) - Gap * (columns - 1f)) / columns)));
  27. return new BoardLayout(tile, new Vector2(columns * tile + Gap * (columns - 1f) + 2 * (Pad + Inset),
  28. rows * tile + Gap * (rows - 1f) + 2 * (Pad + Inset)));
  29. }
  30. // Presentation-only fit. Reserve enough margin for the OUTSIDE row/column path centers.
  31. public static BoardLayout CalculateResponsive(int columns, int rows, Vector2 area)
  32. {
  33. if (columns <= 0 || rows <= 0 || float.IsNaN(area.x) || float.IsNaN(area.y) ||
  34. float.IsInfinity(area.x) || float.IsInfinity(area.y) || area.x <= 22 || area.y <= 22)
  35. throw new ArgumentOutOfRangeException();
  36. const float gap = 3, pathClearance = 6;
  37. float tile = Mathf.Min(60,
  38. Mathf.Floor((area.x - 2 * pathClearance) / (columns + 1) - gap),
  39. Mathf.Floor((area.y - 2 * pathClearance) / (rows + 1) - gap));
  40. if (tile < 1) throw new ArgumentOutOfRangeException(nameof(area));
  41. float padding = tile * .5f + gap + pathClearance;
  42. return new BoardLayout(tile, new Vector2(columns * tile + (columns - 1) * gap + 2 * padding,
  43. rows * tile + (rows - 1) * gap + 2 * padding), gap, padding);
  44. }
  45. public static float FitWidth(BoardLayout layout, float viewportWidth) => Mathf.Min(1, Mathf.Max(0, viewportWidth) / layout.Size.x);
  46. }
  47. }