InventoryDisplay.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Numerics;
  2. using Content.Client.UserInterface.Controls;
  3. using Robust.Client.UserInterface;
  4. using Robust.Client.UserInterface.Controls;
  5. namespace Content.Client.UserInterface.Systems.Inventory.Controls;
  6. public sealed class InventoryDisplay : LayoutContainer
  7. {
  8. private int Columns = 0;
  9. private int Rows = 0;
  10. private const int MarginThickness = 10;
  11. private const int ButtonSpacing = 5;
  12. private const int ButtonSize = 75;
  13. private readonly Control resizer;
  14. private readonly Dictionary<string, (SlotControl, Vector2i)> _buttons = new();
  15. public InventoryDisplay()
  16. {
  17. resizer = new Control();
  18. AddChild(resizer);
  19. }
  20. public SlotControl AddButton(SlotControl newButton, Vector2i buttonOffset)
  21. {
  22. AddChild(newButton);
  23. HorizontalExpand = true;
  24. VerticalExpand = true;
  25. InheritChildMeasure = true;
  26. if (!_buttons.TryAdd(newButton.SlotName, (newButton, buttonOffset)))
  27. Logger.Warning("Tried to add button without a slot!");
  28. SetPosition(newButton, buttonOffset * ButtonSize + new Vector2(ButtonSpacing, ButtonSpacing));
  29. UpdateSizeData(buttonOffset);
  30. return newButton;
  31. }
  32. public SlotControl? GetButton(string slotName)
  33. {
  34. return !_buttons.TryGetValue(slotName, out var foundButton) ? null : foundButton.Item1;
  35. }
  36. private void UpdateSizeData(Vector2i buttonOffset)
  37. {
  38. var (x, _) = buttonOffset;
  39. if (x > Columns)
  40. Columns = x;
  41. var (_, y) = buttonOffset;
  42. if (y > Rows)
  43. Rows = y;
  44. resizer.SetHeight = (Rows + 1) * (ButtonSize + ButtonSpacing);
  45. resizer.SetWidth = (Columns + 1) * (ButtonSize + ButtonSpacing);
  46. }
  47. public bool TryGetButton(string slotName, out SlotControl? button)
  48. {
  49. var success = _buttons.TryGetValue(slotName, out var buttonData);
  50. button = buttonData.Item1;
  51. return success;
  52. }
  53. public void RemoveButton(string slotName)
  54. {
  55. if (!_buttons.Remove(slotName))
  56. return;
  57. //recalculate the size of the control when a slot is removed
  58. Columns = 0;
  59. Rows = 0;
  60. foreach (var (_, (_, buttonOffset)) in _buttons)
  61. {
  62. UpdateSizeData(buttonOffset);
  63. }
  64. }
  65. public void ClearButtons()
  66. {
  67. Children.Clear();
  68. }
  69. }