DumpRestockInventory.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Robust.Shared.Random;
  2. using Content.Shared.Stacks;
  3. using Content.Shared.Prototypes;
  4. using Content.Shared.VendingMachines;
  5. namespace Content.Server.Destructible.Thresholds.Behaviors
  6. {
  7. /// <summary>
  8. /// Spawns a portion of the total items from one of the canRestock
  9. /// inventory entries on a VendingMachineRestock component.
  10. /// </summary>
  11. [Serializable]
  12. [DataDefinition]
  13. public sealed partial class DumpRestockInventory: IThresholdBehavior
  14. {
  15. /// <summary>
  16. /// The percent of each inventory entry that will be salvaged
  17. /// upon destruction of the package.
  18. /// </summary>
  19. [DataField("percent", required: true)]
  20. public float Percent = 0.5f;
  21. [DataField("offset")]
  22. public float Offset { get; set; } = 0.5f;
  23. public void Execute(EntityUid owner, DestructibleSystem system, EntityUid? cause = null)
  24. {
  25. if (!system.EntityManager.TryGetComponent<VendingMachineRestockComponent>(owner, out var packagecomp) ||
  26. !system.EntityManager.TryGetComponent<TransformComponent>(owner, out var xform))
  27. return;
  28. var randomInventory = system.Random.Pick(packagecomp.CanRestock);
  29. if (!system.PrototypeManager.TryIndex(randomInventory, out VendingMachineInventoryPrototype? packPrototype))
  30. return;
  31. foreach (var (entityId, count) in packPrototype.StartingInventory)
  32. {
  33. var toSpawn = (int) Math.Round(count * Percent);
  34. if (toSpawn == 0) continue;
  35. if (EntityPrototypeHelpers.HasComponent<StackComponent>(entityId, system.PrototypeManager, system.ComponentFactory))
  36. {
  37. var spawned = system.EntityManager.SpawnEntity(entityId, xform.Coordinates.Offset(system.Random.NextVector2(-Offset, Offset)));
  38. system.StackSystem.SetCount(spawned, toSpawn);
  39. system.EntityManager.GetComponent<TransformComponent>(spawned).LocalRotation = system.Random.NextAngle();
  40. }
  41. else
  42. {
  43. for (var i = 0; i < toSpawn; i++)
  44. {
  45. var spawned = system.EntityManager.SpawnEntity(entityId, xform.Coordinates.Offset(system.Random.NextVector2(-Offset, Offset)));
  46. system.EntityManager.GetComponent<TransformComponent>(spawned).LocalRotation = system.Random.NextAngle();
  47. }
  48. }
  49. }
  50. }
  51. }
  52. }