1
0

RandomSpriteSystem.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Content.Client.Clothing;
  2. using Content.Shared.Clothing.Components;
  3. using Content.Shared.Sprite;
  4. using Robust.Client.GameObjects;
  5. using Robust.Shared.GameStates;
  6. using Robust.Shared.Reflection;
  7. namespace Content.Client.Sprite;
  8. public sealed class RandomSpriteSystem : SharedRandomSpriteSystem
  9. {
  10. [Dependency] private readonly IReflectionManager _reflection = default!;
  11. [Dependency] private readonly ClientClothingSystem _clothing = default!;
  12. public override void Initialize()
  13. {
  14. base.Initialize();
  15. SubscribeLocalEvent<RandomSpriteComponent, ComponentHandleState>(OnHandleState);
  16. }
  17. private void OnHandleState(EntityUid uid, RandomSpriteComponent component, ref ComponentHandleState args)
  18. {
  19. if (args.Current is not RandomSpriteColorComponentState state)
  20. return;
  21. if (state.Selected.Equals(component.Selected))
  22. return;
  23. component.Selected.Clear();
  24. component.Selected.EnsureCapacity(state.Selected.Count);
  25. foreach (var layer in state.Selected)
  26. {
  27. component.Selected.Add(layer.Key, layer.Value);
  28. }
  29. UpdateSpriteComponentAppearance(uid, component);
  30. UpdateClothingComponentAppearance(uid, component);
  31. }
  32. private void UpdateClothingComponentAppearance(EntityUid uid, RandomSpriteComponent component, ClothingComponent? clothing = null)
  33. {
  34. if (!Resolve(uid, ref clothing, false))
  35. return;
  36. foreach (var slotPair in clothing.ClothingVisuals)
  37. {
  38. foreach (var keyColorPair in component.Selected)
  39. {
  40. _clothing.SetLayerColor(clothing, slotPair.Key, keyColorPair.Key, keyColorPair.Value.Color);
  41. _clothing.SetLayerState(clothing, slotPair.Key, keyColorPair.Key, keyColorPair.Value.State);
  42. }
  43. }
  44. }
  45. private void UpdateSpriteComponentAppearance(EntityUid uid, RandomSpriteComponent component, SpriteComponent? sprite = null)
  46. {
  47. if (!Resolve(uid, ref sprite, false))
  48. return;
  49. foreach (var layer in component.Selected)
  50. {
  51. int index;
  52. if (_reflection.TryParseEnumReference(layer.Key, out var @enum))
  53. {
  54. if (!sprite.LayerMapTryGet(@enum, out index, logError: true))
  55. continue;
  56. }
  57. else if (!sprite.LayerMapTryGet(layer.Key, out index))
  58. {
  59. if (layer.Key is not { } strKey || !int.TryParse(strKey, out index))
  60. {
  61. Log.Error($"Invalid key `{layer.Key}` for entity with random sprite {ToPrettyString(uid)}");
  62. continue;
  63. }
  64. }
  65. sprite.LayerSetState(index, layer.Value.State);
  66. sprite.LayerSetColor(index, layer.Value.Color ?? Color.White);
  67. }
  68. }
  69. }