Implements item pricing, and piracy. (#8548)

* Start implementing item pricing.

* Flesh out prices a bit, add the appraisal tool.

* Add prices to more things.

* YARRRRRRR

* gives pirates an appraisal tool in their pocket.

* Makes the various traitor objectives valuable. Also nerfs the price of a living person, so it's easier to bargain for them.

* Address reviews.

* Address reviews.
This commit is contained in:
Moony
2022-06-03 10:56:11 -05:00
committed by GitHub
parent c87f4ab65c
commit fada213a22
53 changed files with 712 additions and 26 deletions

View File

@@ -0,0 +1,240 @@
using System.Diagnostics.CodeAnalysis;
using Content.Server.Access.Systems;
using Content.Server.Cargo.Components;
using Content.Server.MachineLinking.System;
using Content.Shared.Access.Components;
using Content.Shared.Access.Systems;
using Content.Shared.Cargo;
using Content.Shared.GameTicking;
namespace Content.Server.Cargo.Systems
{
public sealed partial class CargoSystem
{
/// <summary>
/// How much time to wait (in seconds) before increasing bank accounts balance.
/// </summary>
private const float Delay = 10f;
/// <summary>
/// How many points to give to every bank account every <see cref="Delay"/> seconds.
/// </summary>
private const int PointIncrease = 150;
/// <summary>
/// Keeps track of how much time has elapsed since last balance increase.
/// </summary>
private float _timer;
/// <summary>
/// Stores all bank accounts.
/// </summary>
private readonly Dictionary<int, CargoBankAccount> _accountsDict = new();
private readonly Dictionary<int, CargoOrderDatabase> _databasesDict = new();
/// <summary>
/// Used to assign IDs to bank accounts. Incremental counter.
/// </summary>
private int _accountIndex;
/// <summary>
/// Enumeration of all bank accounts.
/// </summary>
public IEnumerable<CargoBankAccount> BankAccounts => _accountsDict.Values;
/// <summary>
/// The station's bank account.
/// </summary>
public CargoBankAccount StationAccount => GetBankAccount(0);
public CargoOrderDatabase StationOrderDatabase => GetOrderDatabase(0);
[Dependency] private readonly IdCardSystem _idCardSystem = default!;
[Dependency] private readonly AccessReaderSystem _accessReaderSystem = default!;
[Dependency] private readonly SignalLinkerSystem _linker = default!;
private void InitializeConsole()
{
SubscribeLocalEvent<CargoConsoleComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset);
Reset();
}
private void OnInit(EntityUid uid, CargoConsoleComponent console, ComponentInit args)
{
_linker.EnsureTransmitterPorts(uid, console.SenderPort);
}
private void Reset(RoundRestartCleanupEvent ev)
{
Reset();
}
private void Reset()
{
_accountsDict.Clear();
_databasesDict.Clear();
_timer = 0;
_accountIndex = 0;
CreateBankAccount("Space Station 14", 1000);
CreateOrderDatabase(0);
}
private void UpdateConsole(float frameTime)
{
_timer += frameTime;
while (_timer > Delay)
{
_timer -= Delay;
foreach (var account in BankAccounts)
{
account.Balance += PointIncrease;
}
}
}
/// <summary>
/// Creates a new bank account.
/// </summary>
public void CreateBankAccount(string name, int balance)
{
var account = new CargoBankAccount(_accountIndex, name, balance);
_accountsDict.Add(_accountIndex, account);
_accountIndex += 1;
}
public void CreateOrderDatabase(int id)
{
_databasesDict.Add(id, new CargoOrderDatabase(id));
}
/// <summary>
/// Returns the bank account associated with the given ID.
/// </summary>
public CargoBankAccount GetBankAccount(int id)
{
return _accountsDict[id];
}
public CargoOrderDatabase GetOrderDatabase(int id)
{
return _databasesDict[id];
}
/// <summary>
/// Returns whether the account exists, eventually passing the account in the out parameter.
/// </summary>
public bool TryGetBankAccount(int id, [NotNullWhen(true)] out CargoBankAccount? account)
{
return _accountsDict.TryGetValue(id, out account);
}
public bool TryGetOrderDatabase(int id, [NotNullWhen(true)] out CargoOrderDatabase? database)
{
return _databasesDict.TryGetValue(id, out database);
}
/// <summary>
/// Verifies if there is enough money in the account's balance to pay the amount.
/// Returns false if there's no account associated with the given ID
/// or if the balance would end up being negative.
/// </summary>
public bool CheckBalance(int id, int amount)
{
if (!TryGetBankAccount(id, out var account))
{
return false;
}
if (account.Balance + amount < 0)
{
return false;
}
return true;
}
/// <summary>
/// Attempts to change the given account's balance.
/// Returns false if there's no account associated with the given ID
/// or if the balance would end up being negative.
/// </summary>
public bool ChangeBalance(int id, int amount)
{
if (!TryGetBankAccount(id, out var account))
{
return false;
}
account.Balance += amount;
return true;
}
public bool AddOrder(int id, string requester, string reason, string productId, int amount, int payingAccountId)
{
if (amount < 1 || !TryGetOrderDatabase(id, out var database) || amount > database.MaxOrderSize)
{
return false;
}
database.AddOrder(requester, reason, productId, amount, payingAccountId);
SyncComponentsWithId(id);
return true;
}
public bool RemoveOrder(int id, int orderNumber)
{
if (!TryGetOrderDatabase(id, out var database))
return false;
database.RemoveOrder(orderNumber);
SyncComponentsWithId(id);
return true;
}
public bool ApproveOrder(EntityUid uid, EntityUid approver, int id, int orderNumber, AccessReaderComponent? reader = null)
{
// does the approver have permission to approve orders?
if (Resolve(uid, ref reader) && !_accessReaderSystem.IsAllowed(approver, reader))
return false;
// get the approver's name
_idCardSystem.TryFindIdCard(approver, out var idCard);
var approverName = idCard?.FullName ?? string.Empty;
if (!TryGetOrderDatabase(id, out var database))
return false;
if (!database.TryGetOrder(orderNumber, out var order))
return false;
if (!database.ApproveOrder(approverName, orderNumber))
return false;
SyncComponentsWithId(id);
return true;
}
public List<CargoOrderData> RemoveAndGetApprovedOrders(int id)
{
if (!TryGetOrderDatabase(id, out var database))
return new List<CargoOrderData>();
var approvedOrders = database.SpliceApproved();
SyncComponentsWithId(id);
return approvedOrders;
}
public (int CurrentCapacity, int MaxCapacity) GetCapacity(int id)
{
if (!TryGetOrderDatabase(id, out var database))
return (0,0);
return (database.CurrentOrderSize, database.MaxOrderSize);
}
private void SyncComponentsWithId(int id)
{
foreach (var comp in EntityManager.EntityQuery<CargoOrderDatabaseComponent>(true))
{
if (comp.Database == null || comp.Database.Id != id)
continue;
Dirty(comp);
}
}
}
}

View File

@@ -0,0 +1,138 @@
using Content.Server.Cargo.Components;
using Content.Server.Labels.Components;
using Content.Server.Paper;
using Content.Server.Power.Components;
using Content.Shared.Cargo;
using Robust.Shared.Audio;
using Robust.Shared.Player;
namespace Content.Server.Cargo.Systems;
public sealed partial class CargoSystem
{
[Dependency] private readonly PaperSystem _paperSystem = default!;
private void InitializeTelepad()
{
SubscribeLocalEvent<CargoTelepadComponent, ComponentInit>(OnInit);
SubscribeLocalEvent<CargoTelepadComponent, PowerChangedEvent>(OnTelepadPowerChange);
// Shouldn't need re-anchored event
SubscribeLocalEvent<CargoTelepadComponent, AnchorStateChangedEvent>(OnTelepadAnchorChange);
}
private void UpdateTelepad(float frameTime)
{
foreach (var comp in EntityManager.EntityQuery<CargoTelepadComponent>())
{
// Don't EntityQuery for it as it's not required.
TryComp<AppearanceComponent>(comp.Owner, out var appearance);
if (comp.CurrentState == CargoTelepadState.Unpowered || comp.TeleportQueue.Count <= 0)
{
comp.CurrentState = CargoTelepadState.Idle;
appearance?.SetData(CargoTelepadVisuals.State, CargoTelepadState.Idle);
comp.Accumulator = comp.Delay;
continue;
}
comp.Accumulator -= frameTime;
// Uhh listen teleporting takes time and I just want the 1 float.
if (comp.Accumulator > 0f)
{
comp.CurrentState = CargoTelepadState.Idle;
appearance?.SetData(CargoTelepadVisuals.State, CargoTelepadState.Idle);
continue;
}
var product = comp.TeleportQueue.Pop();
SoundSystem.Play(Filter.Pvs(comp.Owner), comp.TeleportSound.GetSound(), comp.Owner, AudioParams.Default.WithVolume(-8f));
SpawnProduct(comp, product);
comp.CurrentState = CargoTelepadState.Teleporting;
appearance?.SetData(CargoTelepadVisuals.State, CargoTelepadState.Teleporting);
comp.Accumulator = comp.Delay;
}
}
private void OnInit(EntityUid uid, CargoTelepadComponent telepad, ComponentInit args)
{
_linker.EnsureReceiverPorts(uid, telepad.ReceiverPort);
}
private void SetEnabled(CargoTelepadComponent component, ApcPowerReceiverComponent? receiver = null,
TransformComponent? xform = null)
{
// False due to AllCompsOneEntity test where they may not have the powerreceiver.
if (!Resolve(component.Owner, ref receiver, ref xform, false)) return;
var disabled = !receiver.Powered || !xform.Anchored;
// Setting idle state should be handled by Update();
if (disabled) return;
TryComp<AppearanceComponent>(component.Owner, out var appearance);
component.CurrentState = CargoTelepadState.Unpowered;
appearance?.SetData(CargoTelepadVisuals.State, CargoTelepadState.Unpowered);
}
private void OnTelepadPowerChange(EntityUid uid, CargoTelepadComponent component, PowerChangedEvent args)
{
SetEnabled(component);
}
private void OnTelepadAnchorChange(EntityUid uid, CargoTelepadComponent component, ref AnchorStateChangedEvent args)
{
SetEnabled(component);
}
public void QueueTeleport(CargoTelepadComponent component, CargoOrderData order)
{
for (var i = 0; i < order.Amount; i++)
{
component.TeleportQueue.Push(order);
}
}
/// <summary>
/// Spawn the product and a piece of paper. Attempt to attach the paper to the product.
/// </summary>
private void SpawnProduct(CargoTelepadComponent component, CargoOrderData data)
{
// spawn the order
if (!_protoMan.TryIndex(data.ProductId, out CargoProductPrototype? prototype))
return;
var xform = Transform(component.Owner);
var product = EntityManager.SpawnEntity(prototype.Product, xform.Coordinates);
Transform(product).Anchored = false;
// spawn a piece of paper.
var printed = EntityManager.SpawnEntity(component.PrinterOutput, xform.Coordinates);
if (!TryComp<PaperComponent>(printed, out var paper))
return;
// fill in the order data
var val = Loc.GetString("cargo-console-paper-print-name", ("orderNumber", data.OrderNumber));
MetaData(printed).EntityName = val;
_paperSystem.SetContent(printed, Loc.GetString(
"cargo-console-paper-print-text",
("orderNumber", data.OrderNumber),
("requester", data.Requester),
("reason", data.Reason),
("approver", data.Approver)),
paper);
// attempt to attach the label
if (TryComp<PaperLabelComponent>(product, out var label))
{
_slots.TryInsert(component.Owner, label.LabelSlot, printed, null);
}
}
}

View File

@@ -0,0 +1,25 @@
using Content.Shared.Cargo;
using Content.Shared.Containers.ItemSlots;
using Robust.Shared.Prototypes;
namespace Content.Server.Cargo.Systems;
public sealed partial class CargoSystem : SharedCargoSystem
{
[Dependency] private readonly IPrototypeManager _protoMan = default!;
[Dependency] private readonly ItemSlotsSystem _slots = default!;
public override void Initialize()
{
base.Initialize();
InitializeConsole();
InitializeTelepad();
}
public override void Update(float frameTime)
{
base.Update(frameTime);
UpdateConsole(frameTime);
UpdateTelepad(frameTime);
}
}

View File

@@ -0,0 +1,37 @@
using Content.Server.Cargo.Components;
using Content.Server.Popups;
using Content.Shared.Interaction;
using Content.Shared.Timing;
using Robust.Shared.Player;
namespace Content.Server.Cargo.Systems;
/// <summary>
/// This handles...
/// </summary>
public sealed class PriceGunSystem : EntitySystem
{
[Dependency] private readonly UseDelaySystem _useDelay = default!;
[Dependency] private readonly PricingSystem _pricingSystem = default!;
[Dependency] private readonly PopupSystem _popupSystem = default!;
/// <inheritdoc/>
public override void Initialize()
{
SubscribeLocalEvent<PriceGunComponent, AfterInteractEvent>(OnAfterInteract);
}
private void OnAfterInteract(EntityUid uid, PriceGunComponent component, AfterInteractEvent args)
{
if (!args.CanReach || args.Target == null)
return;
if (TryComp(args.Used, out UseDelayComponent? useDelay) && useDelay.ActiveDelay)
return;
var price = _pricingSystem.GetPrice(args.Target.Value);
_popupSystem.PopupEntity(Loc.GetString("price-gun-pricing-result", ("object", args.Target.Value), ("price", $"{price:F2}")), args.User, Filter.Entities(args.User));
_useDelay.BeginDelay(uid, useDelay);
}
}

View File

@@ -0,0 +1,190 @@
using System.Linq;
using Content.Server.Administration;
using Content.Server.Body.Components;
using Content.Server.Cargo.Components;
using Content.Server.Materials;
using Content.Server.Stack;
using Content.Shared.Administration;
using Content.Shared.MobState.Components;
using Robust.Shared.Console;
using Robust.Shared.Containers;
using Robust.Shared.Map;
using Robust.Shared.Utility;
namespace Content.Server.Cargo.Systems;
/// <summary>
/// This handles calculating the price of items, and implements two basic methods of pricing materials.
/// </summary>
public sealed class PricingSystem : EntitySystem
{
[Dependency] private readonly IConsoleHost _consoleHost = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
/// <inheritdoc/>
public override void Initialize()
{
SubscribeLocalEvent<StaticPriceComponent, PriceCalculationEvent>(CalculateStaticPrice);
SubscribeLocalEvent<StackPriceComponent, PriceCalculationEvent>(CalculateStackPrice);
SubscribeLocalEvent<MobPriceComponent, PriceCalculationEvent>(CalculateMobPrice);
_consoleHost.RegisterCommand("appraisegrid",
"Calculates the total value of the given grids.",
"appraisegrid <grid Ids>", AppraiseGridCommand);
}
[AdminCommand(AdminFlags.Debug)]
private void AppraiseGridCommand(IConsoleShell shell, string argstr, string[] args)
{
if (args.Length == 0)
{
shell.WriteError("Not enough arguments.");
return;
}
foreach (var gid in args)
{
if (!int.TryParse(gid, out var i) || i <= 0)
{
shell.WriteError($"Invalid grid ID \"{gid}\".");
continue;
}
var gridId = new GridId(i);
if (!_mapManager.TryGetGrid(gridId, out var mapGrid))
{
shell.WriteError($"Grid \"{i}\" doesn't exist.");
continue;
}
List<(double, EntityUid)> mostValuable = new();
var value = AppraiseGrid(mapGrid.GridEntityId, null, (uid, price) =>
{
mostValuable.Add((price, uid));
mostValuable.Sort((i1, i2) => i2.Item1.CompareTo(i1.Item1));
if (mostValuable.Count > 5)
mostValuable.Pop();
});
shell.WriteLine($"Grid {gid} appraised to {value} credits.");
shell.WriteLine($"The top most valuable items were:");
foreach (var (price, ent) in mostValuable)
{
shell.WriteLine($"- {ToPrettyString(ent)} @ {price} credits");
}
}
}
private void CalculateMobPrice(EntityUid uid, MobPriceComponent component, ref PriceCalculationEvent args)
{
if (!TryComp<BodyComponent>(uid, out var body) || !TryComp<MobStateComponent>(uid, out var state))
{
Logger.ErrorS("pricing", $"Tried to get the mob price of {ToPrettyString(uid)}, which has no {nameof(BodyComponent)} and no {nameof(MobStateComponent)}.");
return;
}
var partList = body.Slots.ToList();
var totalPartsPresent = partList.Sum(x => x.Part != null ? 1 : 0);
var totalParts = partList.Count;
var partRatio = totalPartsPresent / (double) totalParts;
var partPenalty = component.Price * (1 - partRatio) * component.MissingBodyPartPenalty;
args.Price += (component.Price - partPenalty) * (state.IsAlive() ? 1.0 : component.DeathPenalty);
}
private void CalculateStackPrice(EntityUid uid, StackPriceComponent component, ref PriceCalculationEvent args)
{
if (!TryComp<StackComponent>(uid, out var stack))
{
Logger.ErrorS("pricing", $"Tried to get the stack price of {ToPrettyString(uid)}, which has no {nameof(StackComponent)}.");
return;
}
args.Price += stack.Count * component.Price;
}
private void CalculateStaticPrice(EntityUid uid, StaticPriceComponent component, ref PriceCalculationEvent args)
{
args.Price += component.Price;
}
/// <summary>
/// Appraises an entity, returning it's price.
/// </summary>
/// <param name="uid">The entity to appraise.</param>
/// <returns>The price of the entity.</returns>
/// <remarks>
/// This fires off an event to calculate the price.
/// Calculating the price of an entity that somehow contains itself will likely hang.
/// </remarks>
public double GetPrice(EntityUid uid)
{
var ev = new PriceCalculationEvent();
RaiseLocalEvent(uid, ref ev);
//TODO: Add an OpaqueToAppraisal component or similar for blocking the recursive descent into containers, or preventing material pricing.
if (TryComp<MaterialComponent>(uid, out var material) && !HasComp<StackPriceComponent>(uid))
{
if (TryComp<StackComponent>(uid, out var stack))
ev.Price += stack.Count * material.Materials.Sum(x => x.Price * material._materials[x.ID]);
else
ev.Price += material.Materials.Sum(x => x.Price);
}
if (TryComp<ContainerManagerComponent>(uid, out var containers))
{
foreach (var container in containers.Containers)
{
foreach (var ent in container.Value.ContainedEntities)
{
ev.Price += GetPrice(ent);
}
}
}
return ev.Price;
}
/// <summary>
/// Appraises a grid, this is mainly meant to be used by yarrs.
/// </summary>
/// <param name="grid">The grid to appraise.</param>
/// <param name="predicate">An optional predicate that controls whether or not the entity is counted toward the total.</param>
/// <param name="afterPredicate">An optional predicate to run after the price has been calculated. Useful for high scores or similar.</param>
/// <returns>The total value of the grid.</returns>
public double AppraiseGrid(EntityUid grid, Func<EntityUid, bool>? predicate = null, Action<EntityUid, double>? afterPredicate = null)
{
var xform = Transform(grid);
var price = 0.0;
foreach (var child in xform.ChildEntities)
{
if (predicate is null || predicate(child))
{
var subPrice = GetPrice(child);
price += subPrice;
afterPredicate?.Invoke(child, subPrice);
}
}
return price;
}
}
/// <summary>
/// A directed by-ref event fired on an entity when something needs to know it's price. This value is not cached.
/// </summary>
[ByRefEvent]
public struct PriceCalculationEvent
{
/// <summary>
/// The total price of the entity.
/// </summary>
public double Price = 0;
public PriceCalculationEvent() { }
}