PricingSystem.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. using Content.Server.Administration;
  2. using Content.Server.Body.Systems;
  3. using Content.Server.Cargo.Components;
  4. using Content.Shared.Chemistry.EntitySystems;
  5. using Content.Shared.Administration;
  6. using Content.Shared.Body.Components;
  7. using Content.Shared.Chemistry.Components.SolutionManager;
  8. using Content.Shared.Chemistry.Reagent;
  9. using Content.Shared.Materials;
  10. using Content.Shared.Mobs.Components;
  11. using Content.Shared.Mobs.Systems;
  12. using Content.Shared.Stacks;
  13. using Robust.Shared.Console;
  14. using Robust.Shared.Containers;
  15. using Robust.Shared.Map.Components;
  16. using Robust.Shared.Prototypes;
  17. using Robust.Shared.Utility;
  18. using System.Linq;
  19. using Content.Shared.Research.Prototypes;
  20. namespace Content.Server.Cargo.Systems;
  21. /// <summary>
  22. /// This handles calculating the price of items, and implements two basic methods of pricing materials.
  23. /// </summary>
  24. public sealed class PricingSystem : EntitySystem
  25. {
  26. [Dependency] private readonly IComponentFactory _factory = default!;
  27. [Dependency] private readonly IConsoleHost _consoleHost = default!;
  28. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  29. [Dependency] private readonly BodySystem _bodySystem = default!;
  30. [Dependency] private readonly MobStateSystem _mobStateSystem = default!;
  31. [Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!;
  32. /// <inheritdoc/>
  33. public override void Initialize()
  34. {
  35. SubscribeLocalEvent<MobPriceComponent, PriceCalculationEvent>(CalculateMobPrice);
  36. _consoleHost.RegisterCommand("appraisegrid",
  37. "Calculates the total value of the given grids.",
  38. "appraisegrid <grid Ids>", AppraiseGridCommand);
  39. }
  40. [AdminCommand(AdminFlags.Debug)]
  41. private void AppraiseGridCommand(IConsoleShell shell, string argstr, string[] args)
  42. {
  43. if (args.Length == 0)
  44. {
  45. shell.WriteError("Not enough arguments.");
  46. return;
  47. }
  48. foreach (var gid in args)
  49. {
  50. if (!EntityManager.TryParseNetEntity(gid, out var gridId) || !gridId.Value.IsValid())
  51. {
  52. shell.WriteError($"Invalid grid ID \"{gid}\".");
  53. continue;
  54. }
  55. if (!TryComp(gridId, out MapGridComponent? mapGrid))
  56. {
  57. shell.WriteError($"Grid \"{gridId}\" doesn't exist.");
  58. continue;
  59. }
  60. List<(double, EntityUid)> mostValuable = new();
  61. var value = AppraiseGrid(gridId.Value, null, (uid, price) =>
  62. {
  63. mostValuable.Add((price, uid));
  64. mostValuable.Sort((i1, i2) => i2.Item1.CompareTo(i1.Item1));
  65. if (mostValuable.Count > 5)
  66. mostValuable.Pop();
  67. });
  68. shell.WriteLine($"Grid {gid} appraised to {value} spesos.");
  69. shell.WriteLine($"The top most valuable items were:");
  70. foreach (var (price, ent) in mostValuable)
  71. {
  72. shell.WriteLine($"- {ToPrettyString(ent)} @ {price} spesos");
  73. }
  74. }
  75. }
  76. private void CalculateMobPrice(EntityUid uid, MobPriceComponent component, ref PriceCalculationEvent args)
  77. {
  78. // TODO: Estimated pricing.
  79. if (args.Handled)
  80. return;
  81. if (!TryComp<BodyComponent>(uid, out var body) || !TryComp<MobStateComponent>(uid, out var state))
  82. {
  83. Log.Error($"Tried to get the mob price of {ToPrettyString(uid)}, which has no {nameof(BodyComponent)} and no {nameof(MobStateComponent)}.");
  84. return;
  85. }
  86. // TODO: Better handling of missing.
  87. var partList = _bodySystem.GetBodyChildren(uid, body).ToList();
  88. var totalPartsPresent = partList.Sum(_ => 1);
  89. var totalParts = partList.Count;
  90. var partRatio = totalPartsPresent / (double) totalParts;
  91. var partPenalty = component.Price * (1 - partRatio) * component.MissingBodyPartPenalty;
  92. args.Price += (component.Price - partPenalty) * (_mobStateSystem.IsAlive(uid, state) ? 1.0 : component.DeathPenalty);
  93. }
  94. private double GetSolutionPrice(Entity<SolutionContainerManagerComponent> entity)
  95. {
  96. if (Comp<MetaDataComponent>(entity).EntityLifeStage < EntityLifeStage.MapInitialized)
  97. return GetSolutionPrice(entity.Comp);
  98. var price = 0.0;
  99. foreach (var (_, soln) in _solutionContainerSystem.EnumerateSolutions((entity.Owner, entity.Comp)))
  100. {
  101. var solution = soln.Comp.Solution;
  102. foreach (var (reagent, quantity) in solution.Contents)
  103. {
  104. if (!_prototypeManager.TryIndex<ReagentPrototype>(reagent.Prototype, out var reagentProto))
  105. continue;
  106. // TODO check ReagentData for price information?
  107. price += (float) quantity * reagentProto.PricePerUnit;
  108. }
  109. }
  110. return price;
  111. }
  112. private double GetSolutionPrice(SolutionContainerManagerComponent component)
  113. {
  114. var price = 0.0;
  115. foreach (var (_, prototype) in _solutionContainerSystem.EnumerateSolutions(component))
  116. {
  117. foreach (var (reagent, quantity) in prototype.Contents)
  118. {
  119. if (!_prototypeManager.TryIndex<ReagentPrototype>(reagent.Prototype, out var reagentProto))
  120. continue;
  121. // TODO check ReagentData for price information?
  122. price += (float) quantity * reagentProto.PricePerUnit;
  123. }
  124. }
  125. return price;
  126. }
  127. private double GetMaterialPrice(PhysicalCompositionComponent component)
  128. {
  129. double price = 0;
  130. foreach (var (id, quantity) in component.MaterialComposition)
  131. {
  132. price += _prototypeManager.Index<MaterialPrototype>(id).Price * quantity;
  133. }
  134. return price;
  135. }
  136. public double GetLatheRecipePrice(LatheRecipePrototype recipe)
  137. {
  138. var price = 0.0;
  139. if (recipe.Result is { } result)
  140. {
  141. price += GetEstimatedPrice(_prototypeManager.Index(result));
  142. }
  143. if (recipe.ResultReagents is { } resultReagents)
  144. {
  145. foreach (var (reagent, amount) in resultReagents)
  146. {
  147. price += (_prototypeManager.Index(reagent).PricePerUnit * amount).Double();
  148. }
  149. }
  150. return price;
  151. }
  152. /// <summary>
  153. /// Get a rough price for an entityprototype. Does not consider contained entities.
  154. /// </summary>
  155. public double GetEstimatedPrice(EntityPrototype prototype)
  156. {
  157. var ev = new EstimatedPriceCalculationEvent()
  158. {
  159. Prototype = prototype,
  160. };
  161. RaiseLocalEvent(ref ev);
  162. if (ev.Handled)
  163. return ev.Price;
  164. var price = ev.Price;
  165. price += GetMaterialsPrice(prototype);
  166. price += GetSolutionsPrice(prototype);
  167. // Can't use static price with stackprice
  168. var oldPrice = price;
  169. price += GetStackPrice(prototype);
  170. if (oldPrice.Equals(price))
  171. {
  172. price += GetStaticPrice(prototype);
  173. }
  174. // TODO: Proper container support.
  175. return price;
  176. }
  177. /// <summary>
  178. /// Appraises an entity, returning it's price.
  179. /// </summary>
  180. /// <param name="uid">The entity to appraise.</param>
  181. /// <returns>The price of the entity.</returns>
  182. /// <remarks>
  183. /// This fires off an event to calculate the price.
  184. /// Calculating the price of an entity that somehow contains itself will likely hang.
  185. /// </remarks>
  186. public double GetPrice(EntityUid uid, bool includeContents = true)
  187. {
  188. var ev = new PriceCalculationEvent();
  189. RaiseLocalEvent(uid, ref ev);
  190. if (ev.Handled)
  191. return ev.Price;
  192. var price = ev.Price;
  193. //TODO: Add an OpaqueToAppraisal component or similar for blocking the recursive descent into containers, or preventing material pricing.
  194. // DO NOT FORGET TO UPDATE ESTIMATED PRICING
  195. price += GetMaterialsPrice(uid);
  196. price += GetSolutionsPrice(uid);
  197. // Can't use static price with stackprice
  198. var oldPrice = price;
  199. price += GetStackPrice(uid);
  200. if (oldPrice.Equals(price))
  201. {
  202. price += GetStaticPrice(uid);
  203. }
  204. if (includeContents && TryComp<ContainerManagerComponent>(uid, out var containers))
  205. {
  206. foreach (var container in containers.Containers.Values)
  207. {
  208. foreach (var ent in container.ContainedEntities)
  209. {
  210. price += GetPrice(ent);
  211. }
  212. }
  213. }
  214. return price;
  215. }
  216. private double GetMaterialsPrice(EntityUid uid)
  217. {
  218. double price = 0;
  219. if (HasComp<MaterialComponent>(uid) &&
  220. TryComp<PhysicalCompositionComponent>(uid, out var composition))
  221. {
  222. var matPrice = GetMaterialPrice(composition);
  223. if (TryComp<StackComponent>(uid, out var stack))
  224. matPrice *= stack.Count;
  225. price += matPrice;
  226. }
  227. return price;
  228. }
  229. private double GetMaterialsPrice(EntityPrototype prototype)
  230. {
  231. double price = 0;
  232. if (prototype.Components.ContainsKey(_factory.GetComponentName(typeof(MaterialComponent))) &&
  233. prototype.Components.TryGetValue(_factory.GetComponentName(typeof(PhysicalCompositionComponent)), out var composition))
  234. {
  235. var compositionComp = (PhysicalCompositionComponent) composition.Component;
  236. var matPrice = GetMaterialPrice(compositionComp);
  237. if (prototype.Components.TryGetValue(_factory.GetComponentName(typeof(StackComponent)), out var stackProto))
  238. {
  239. matPrice *= ((StackComponent) stackProto.Component).Count;
  240. }
  241. price += matPrice;
  242. }
  243. return price;
  244. }
  245. private double GetSolutionsPrice(EntityUid uid)
  246. {
  247. var price = 0.0;
  248. if (TryComp<SolutionContainerManagerComponent>(uid, out var solComp))
  249. {
  250. price += GetSolutionPrice((uid, solComp));
  251. }
  252. return price;
  253. }
  254. private double GetSolutionsPrice(EntityPrototype prototype)
  255. {
  256. var price = 0.0;
  257. if (prototype.Components.TryGetValue(_factory.GetComponentName(typeof(SolutionContainerManagerComponent)), out var solManager))
  258. {
  259. var solComp = (SolutionContainerManagerComponent) solManager.Component;
  260. price += GetSolutionPrice(solComp);
  261. }
  262. return price;
  263. }
  264. private double GetStackPrice(EntityUid uid)
  265. {
  266. var price = 0.0;
  267. if (TryComp<StackPriceComponent>(uid, out var stackPrice) &&
  268. TryComp<StackComponent>(uid, out var stack) &&
  269. !HasComp<MaterialComponent>(uid)) // don't double count material prices
  270. {
  271. price += stack.Count * stackPrice.Price;
  272. }
  273. return price;
  274. }
  275. private double GetStackPrice(EntityPrototype prototype)
  276. {
  277. var price = 0.0;
  278. if (prototype.Components.TryGetValue(_factory.GetComponentName(typeof(StackPriceComponent)), out var stackpriceProto) &&
  279. prototype.Components.TryGetValue(_factory.GetComponentName(typeof(StackComponent)), out var stackProto) &&
  280. !prototype.Components.ContainsKey(_factory.GetComponentName(typeof(MaterialComponent))))
  281. {
  282. var stackPrice = (StackPriceComponent) stackpriceProto.Component;
  283. var stack = (StackComponent) stackProto.Component;
  284. price += stack.Count * stackPrice.Price;
  285. }
  286. return price;
  287. }
  288. private double GetStaticPrice(EntityUid uid)
  289. {
  290. var price = 0.0;
  291. if (TryComp<StaticPriceComponent>(uid, out var staticPrice))
  292. {
  293. price += staticPrice.Price;
  294. }
  295. return price;
  296. }
  297. private double GetStaticPrice(EntityPrototype prototype)
  298. {
  299. var price = 0.0;
  300. if (prototype.Components.TryGetValue(_factory.GetComponentName(typeof(StaticPriceComponent)), out var staticProto))
  301. {
  302. var staticPrice = (StaticPriceComponent) staticProto.Component;
  303. price += staticPrice.Price;
  304. }
  305. return price;
  306. }
  307. /// <summary>
  308. /// Appraises a grid, this is mainly meant to be used by yarrs.
  309. /// </summary>
  310. /// <param name="grid">The grid to appraise.</param>
  311. /// <param name="predicate">An optional predicate that controls whether or not the entity is counted toward the total.</param>
  312. /// <param name="afterPredicate">An optional predicate to run after the price has been calculated. Useful for high scores or similar.</param>
  313. /// <returns>The total value of the grid.</returns>
  314. public double AppraiseGrid(EntityUid grid, Func<EntityUid, bool>? predicate = null, Action<EntityUid, double>? afterPredicate = null)
  315. {
  316. var xform = Transform(grid);
  317. var price = 0.0;
  318. var enumerator = xform.ChildEnumerator;
  319. while (enumerator.MoveNext(out var child))
  320. {
  321. if (predicate is null || predicate(child))
  322. {
  323. var subPrice = GetPrice(child);
  324. price += subPrice;
  325. afterPredicate?.Invoke(child, subPrice);
  326. }
  327. }
  328. return price;
  329. }
  330. }
  331. /// <summary>
  332. /// A directed by-ref event fired on an entity when something needs to know it's price. This value is not cached.
  333. /// </summary>
  334. [ByRefEvent]
  335. public record struct PriceCalculationEvent()
  336. {
  337. /// <summary>
  338. /// The total price of the entity.
  339. /// </summary>
  340. public double Price = 0;
  341. /// <summary>
  342. /// Whether this event was already handled.
  343. /// </summary>
  344. public bool Handled = false;
  345. }
  346. /// <summary>
  347. /// Raised broadcast for an entity prototype to determine its estimated price.
  348. /// </summary>
  349. [ByRefEvent]
  350. public record struct EstimatedPriceCalculationEvent()
  351. {
  352. public required EntityPrototype Prototype;
  353. /// <summary>
  354. /// The total price of the entity.
  355. /// </summary>
  356. public double Price = 0;
  357. /// <summary>
  358. /// Whether this event was already handled.
  359. /// </summary>
  360. public bool Handled = false;
  361. }