Compound commodities stack: ICommodityStack owns interchangeability, one bay rule serves every stack

ICommodityStack (StacksWith, Split) on SimpleCommodity and CompoundCommodity; CompoundCommodity.Quantity at Key(13),
CompoundCommodityData.MaxStack at Key(12), ItemManager.MaxStack. The bay's typed SimpleCommodity and CraftedItemInstance
entries are private behind the ItemInstance dispatchers, Remove and TryTransferItem take ItemInstance with a quantity,
EquippedCargoBay.Count serves CountItemsInCargo and the trade menu. Restore, pickup, prices, give and sale follow
(sale absorbs for any stack: question compound-stack-sale-absorbs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-27 18:59:38 +01:00
commit a30f3be50d
12 changed files with 213 additions and 200 deletions

View file

@ -23,7 +23,8 @@ public enum GiveEnd
public sealed class GiveOrder
{
public readonly Entity Receiver;
// A commodity order is for any stack of this item's design in the giver's bays; a crafted order is for this instance.
// A stack order is for any stack the item StacksWith in the giver's bays (the same design, and for a compound
// commodity the same lot); a unit order is for this instance.
public readonly ItemInstance Item;
// Units still to move.
public int Remaining { get; internal set; }
@ -99,27 +100,25 @@ public static class CargoTransfer
}
}
// Where the next unit comes from: the first stack of the order's design in the giver's bays, or the crafted instance.
// Where the next unit comes from: the first stack in the giver's bays the order's item StacksWith, or the unit itself.
private static (EquippedCargoBay Bay, ItemInstance Item) Source(Entity giver, GiveOrder order)
{
foreach (var bay in giver.CargoBays)
{
if (order.Item is CraftedItemInstance crafted)
if (order.Item is ICommodityStack wanted)
{
if (bay.Cargo.ContainsKey(crafted)) return (bay, crafted);
}
else if (bay.ItemsOfType.TryGetValue(order.Item.Data.Key, out var stacks))
{
var stack = stacks.OfType<SimpleCommodity>().FirstOrDefault();
if (stack != null) return (bay, stack);
if (bay.ItemsOfType.TryGetValue(order.Item.Data.Key, out var stacks))
{
var stack = stacks.FirstOrDefault(wanted.StacksWith);
if (stack != null) return (bay, stack);
}
}
else if (bay.Cargo.ContainsKey(order.Item)) return (bay, order.Item);
}
return (null, null);
}
// One unit of a commodity, or the crafted item, into the first receiver bay that takes it.
// One unit of a stack, or the unit itself, into the first receiver bay that takes it.
private static bool Move(EquippedCargoBay from, ItemInstance item, Entity receiver) =>
item is SimpleCommodity commodity
? receiver.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, 1))
: receiver.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item));
receiver.CargoBays.Any(bay => from.TryTransferItem(bay, item, 1));
}

View file

@ -1448,19 +1448,7 @@ public abstract class Entity
Temperature[position.x, position.y] += heat / ThermalMass[position.x, position.y];
}
public int CountItemsInCargo(CultRecordKey itemDataID)
{
int sum = 0;
foreach (var x in CargoBays)
{
if (x.ItemsOfType.ContainsKey(itemDataID))
{
foreach (var i in x.ItemsOfType[itemDataID]) sum += i is SimpleCommodity simpleCommodity ? simpleCommodity.Quantity : 1;
}
}
return sum;
}
public int CountItemsInCargo(CultRecordKey itemDataID) => CargoBays.Sum(bay => bay.Count(itemDataID));
public EquippedCargoBay FindItemInCargo(CultRecordKey itemDataID)
{
@ -2476,38 +2464,39 @@ public class EquippedCargoBay : EquippedItem
public bool TryFindSpace(ItemInstance item)
{
if (item is SimpleCommodity simpleCommodity)
return TryFindSpace(simpleCommodity, out _);
if (item is ICommodityStack)
return TryFindStackSpace(item, out _);
if (item is CraftedItemInstance craftedItem)
return TryFindSpace(craftedItem, out _);
return TryFindUnitSpace(craftedItem, out _);
return false;
}
// Tries to find a place to put the given items in the inventory
// Will attempt to fill existing item stacks first
// Returns true only when ALL of the items have places to go
public bool TryFindSpace(SimpleCommodity item, out List<int2> positions)
// Tries to find a place to put the given stack in the inventory
// Will attempt to fill existing stacks it StacksWith first
// Returns true only when ALL of the units have places to go
private bool TryFindStackSpace(ItemInstance item, out List<int2> positions)
{
positions = new List<int2>();
var itemData = ItemManager.GetData(item);
var remainingQuantity = item.Quantity;
// For simple commodities, search for existing item stacks to add to
var stack = (ICommodityStack) item;
var maxStack = ItemManager.MaxStack(item);
var remainingQuantity = stack.Quantity;
// Search for existing stacks to add to
foreach (var cargoItem in Cargo.Keys)
{
if (!item.Data.Key.Equals(cargoItem.Data.Key)) continue;
var cargoCommodity = (SimpleCommodity) cargoItem;
if (cargoCommodity.Quantity >= itemData.MaxStack) continue;
if (!stack.StacksWith(cargoItem)) continue;
var held = (ICommodityStack) cargoItem;
if (held.Quantity >= maxStack) continue;
// Subtract remaining space in existing stack from remaining quantity
remainingQuantity -= min(itemData.MaxStack - cargoCommodity.Quantity, remainingQuantity);
remainingQuantity -= min(maxStack - held.Quantity, remainingQuantity);
positions.Add(Cargo[cargoItem]);
// If we've moved all of the items into existing stacks, no need to search for empty space!
if (remainingQuantity == 0) return true;
}
// TODO: Try alternate item rotations / use Shape.FitsWithin
// Search all the space in the cargo bay for an empty space where the item fits
foreach (var cargoCoord in Data.InteriorShape.Coordinates)
@ -2523,7 +2512,7 @@ public class EquippedCargoBay : EquippedItem
}
// Searches the cargo bay for a position where the item will fit, returns true when found
public bool TryFindSpace(CraftedItemInstance item, out int2 position)
private bool TryFindUnitSpace(CraftedItemInstance item, out int2 position)
{
// Search all the space in the cargo bay for an empty space where the item fits
foreach (var cargoCoord in Data.InteriorShape.Coordinates)
@ -2538,48 +2527,50 @@ public class EquippedCargoBay : EquippedItem
position = int2.zero;
return false;
}
public bool TryStore(ItemInstance item)
{
if (item is SimpleCommodity simpleCommodity)
return TryStore(simpleCommodity);
if (item is ICommodityStack)
return TryStoreStack(item);
if (item is CraftedItemInstance craftedItem)
return TryStore(craftedItem);
return TryStoreUnit(craftedItem);
return false;
}
public bool TryStore(ItemInstance item, int2 cargoCoord)
{
if (item is SimpleCommodity simpleCommodity)
return TryStore(simpleCommodity, cargoCoord);
if (item is ICommodityStack)
return TryStoreStack(item, cargoCoord);
if (item is CraftedItemInstance craftedItem)
return TryStore(craftedItem, cargoCoord);
return TryStoreUnit(craftedItem, cargoCoord);
return false;
}
// Attempts to store all of the given item anywhere in the inventory
// Will attempt to fill existing item stacks first
// Returns true only when ALL of the items are successfully stored
public bool TryStore(SimpleCommodity item)
// Attempts to store all of the given stack anywhere in the inventory
// Will attempt to fill existing stacks first
// Returns true only when ALL of the units are successfully stored
private bool TryStoreStack(ItemInstance item)
{
if (!TryFindSpace(item, out var positions)) return false;
if (!TryFindStackSpace(item, out var positions)) return false;
foreach (var position in positions)
{
if (TryStore(item, position)) return true;
if (TryStoreStack(item, position)) return true;
}
return false;
}
// Try to store the given commodity at the given position
// If there's a stack at the given position it will be added to
// Returns true only when ALL of the items are successfully stored
// Try to store the given stack at the given position
// If there's a stack it StacksWith at the given position it will be added to
// Returns true only when ALL of the units are successfully stored
// The bay decides what quantity may sit in it: a stack below one unit or above its design's MaxStack is refused with
// the bay as it was, so no caller, loot, pickup or restore has to check for it.
public bool TryStore(SimpleCommodity item, int2 cargoCoord)
private bool TryStoreStack(ItemInstance item, int2 cargoCoord)
{
var stack = (ICommodityStack) item;
var itemData = ItemManager.GetData(item);
if (item.Quantity < 1 || item.Quantity > itemData.MaxStack) return false;
var maxStack = ItemManager.MaxStack(item);
if (stack.Quantity < 1 || stack.Quantity > maxStack) return false;
if (ItemFits(item, cargoCoord))
{
foreach (var p in itemData.Shape.Coordinates)
@ -2588,43 +2579,43 @@ public class EquippedCargoBay : EquippedItem
Occupancy[pos.x, pos.y] = item;
}
Cargo[item] = cargoCoord;
if(!ItemsOfType.ContainsKey(item.Data.Key))
ItemsOfType[item.Data.Key] = new List<ItemInstance>();
ItemsOfType[item.Data.Key].Add(item);
}
else if (Occupancy[cargoCoord.x, cargoCoord.y] is SimpleCommodity cargoCommodity && cargoCommodity.Data.Key.Equals(item.Data.Key))
else if (Occupancy[cargoCoord.x, cargoCoord.y] is ICommodityStack held && stack.StacksWith(Occupancy[cargoCoord.x, cargoCoord.y]))
{
if (cargoCommodity.Quantity + item.Quantity <= itemData.MaxStack)
if (held.Quantity + stack.Quantity <= maxStack)
{
cargoCommodity.Quantity += item.Quantity;
held.Quantity += stack.Quantity;
}
else
{
var quantityTransferred = itemData.MaxStack - cargoCommodity.Quantity;
item.Quantity -= quantityTransferred;
cargoCommodity.Quantity = itemData.MaxStack;
var quantityTransferred = maxStack - held.Quantity;
stack.Quantity -= quantityTransferred;
held.Quantity = maxStack;
Mass += itemData.Mass * quantityTransferred;
ThermalMass += itemData.Mass * itemData.SpecificHeat * quantityTransferred;
return false;
}
}
else return false;
Mass += ItemManager.GetMass(item);
ThermalMass += ItemManager.GetThermalMass(item);
return true;
}
// Try to store the given item anywhere it will fit, returns true when the item was successfully stored
public bool TryStore(CraftedItemInstance item) => TryFindSpace(item, out var position) && TryStore(item, position);
private bool TryStoreUnit(CraftedItemInstance item) => TryFindUnitSpace(item, out var position) && TryStoreUnit(item, position);
// Try to store the given item at the given position, returns true when the item was successfully stored
public bool TryStore(CraftedItemInstance item, int2 cargoCoord)
private bool TryStoreUnit(CraftedItemInstance item, int2 cargoCoord)
{
if (!ItemFits(item, cargoCoord)) return false;
var itemData = ItemManager.GetData(item);
foreach (var p in itemData.Shape.Coordinates)
{
@ -2632,19 +2623,26 @@ public class EquippedCargoBay : EquippedItem
Occupancy[pos.x, pos.y] = item;
}
Cargo[item] = cargoCoord;
if(!ItemsOfType.ContainsKey(item.Data.Key))
ItemsOfType[item.Data.Key] = new List<ItemInstance>();
ItemsOfType[item.Data.Key].Add(item);
Mass += ItemManager.GetMass(item);
ThermalMass += ItemManager.GetThermalMass(item);
return true;
}
// The part removed: null, with the bay as it was, when the item is not here or the quantity is below one unit.
public SimpleCommodity Remove(SimpleCommodity item, int quantity)
// The units of a design in the bay: a stack counts its Quantity, any other item one. The one reader of how many
// units a bay holds; Entity.CountItemsInCargo and the trade menu's Owned column derive from it.
public int Count(CultRecordKey design) =>
ItemsOfType.TryGetValue(design, out var items) ? items.Sum(i => i is ICommodityStack stack ? stack.Quantity : 1) : 0;
// The part removed: null, with the bay as it was, when the item is not here or the quantity is below one unit. A
// stack gives up `quantity` units through its own Split (the stack itself, whole, when it holds no more); a unit
// leaves whole for any quantity of one or more.
public ItemInstance Remove(ItemInstance item, int quantity)
{
if (quantity < 1) return null;
if (!Cargo.ContainsKey(item))
@ -2652,60 +2650,46 @@ public class EquippedCargoBay : EquippedItem
ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!");
return null;
}
var itemData = ItemManager.GetData(item);
if(quantity >= item.Quantity)
if (item is ICommodityStack stack && quantity < stack.Quantity)
{
foreach(var v in Data.InteriorShape.Coordinates)
if (Occupancy[v.x, v.y] == item)
Occupancy[v.x, v.y] = null;
Cargo.Remove(item);
ItemsOfType[item.Data.Key].Remove(item);
if (!ItemsOfType[item.Data.Key].Any())
ItemsOfType.Remove(item.Data.Key);
Mass -= ItemManager.GetMass(item);
ThermalMass -= ItemManager.GetThermalMass(item);
return item;
var itemData = ItemManager.GetData(item);
stack.Quantity -= quantity;
Mass -= itemData.Mass * quantity;
ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity;
return stack.Split(quantity);
}
item.Quantity -= quantity;
Mass -= itemData.Mass * quantity;
ThermalMass -= itemData.Mass * itemData.SpecificHeat * quantity;
return new SimpleCommodity{Data = item.Data, Quantity = quantity, Rotation = item.Rotation};
}
public void Remove(CraftedItemInstance item)
{
if (!Cargo.ContainsKey(item))
{
ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!");
return;
}
var itemData = ItemManager.GetData(item);
foreach(var v in Data.InteriorShape.Coordinates)
if (Occupancy[v.x, v.y] == item)
Occupancy[v.x, v.y] = null;
Cargo.Remove(item);
ItemsOfType[item.Data.Key].Remove(item);
if (!ItemsOfType[item.Data.Key].Any())
ItemsOfType.Remove(item.Data.Key);
Mass -= ItemManager.GetMass(item);
ThermalMass -= ItemManager.GetThermalMass(item);
RemoveWhole(item);
return item;
}
public void Remove(ItemInstance item)
{
if (item is SimpleCommodity simpleCommodity)
Remove(simpleCommodity, simpleCommodity.Quantity);
if (item is CraftedItemInstance craftedItem)
Remove(craftedItem);
if (item is ICommodityStack stack)
Remove(item, stack.Quantity);
else if (item is CraftedItemInstance)
Remove(item, 1);
}
public bool TryTransferItem(EquippedCargoBay target, SimpleCommodity item, int quantity)
// The item, with everything it holds, leaves the bay: the one place a cell is freed.
private void RemoveWhole(ItemInstance item)
{
foreach(var v in Data.InteriorShape.Coordinates)
if (Occupancy[v.x, v.y] == item)
Occupancy[v.x, v.y] = null;
Cargo.Remove(item);
ItemsOfType[item.Data.Key].Remove(item);
if (!ItemsOfType[item.Data.Key].Any())
ItemsOfType.Remove(item.Data.Key);
Mass -= ItemManager.GetMass(item);
ThermalMass -= ItemManager.GetThermalMass(item);
}
// Moves `quantity` units of a stack, or the one unit, to the target bay. The part goes across, never the stack left
// behind; whole or nothing: a refusal puts the part back where it came from.
public bool TryTransferItem(EquippedCargoBay target, ItemInstance item, int quantity)
{
if (quantity < 1) return false;
if (!Cargo.ContainsKey(item))
@ -2714,25 +2698,15 @@ public class EquippedCargoBay : EquippedItem
return false;
}
var oldPos = Cargo[item];
var newItem = Remove(item, quantity);
// The part removed goes across, never the stack left behind.
if (target.TryStore(newItem)) return true;
// Whole or nothing: TryStore takes all of the part or none of it, so a refusal puts the part back where it came from.
TryStore(newItem, oldPos);
return false;
}
public bool TryTransferItem(EquippedCargoBay target, CraftedItemInstance item)
{
if (!Cargo.ContainsKey(item))
if (item is ICommodityStack)
{
ItemManager.Log("Attempted to remove item from a cargo bay that it wasn't even in! Something went wrong here!");
var oldPos = Cargo[item];
var part = Remove(item, quantity);
if (target.TryStore(part)) return true;
TryStore(part, oldPos);
return false;
}
if (!target.TryStore(item)) return false;
Remove(item);
return true;

View file

@ -54,38 +54,38 @@ public static class EntitySerializer
// first MaxStack units go back where it was and the rest is returned to be placed by SpillOversize once every stack
// has its own cell, so a spill cannot take a cell a later stack was saved in.
private static void RestoreStack(ItemManager itemManager, EquippedCargoBay bay, int2 position, ItemInstance item,
List<(EquippedCargoBay home, SimpleCommodity rest)> spill)
List<(EquippedCargoBay home, ItemInstance rest)> spill)
{
if (item is SimpleCommodity commodity && commodity.Quantity > itemManager.GetData(commodity).MaxStack
&& itemManager.GetData(commodity).MaxStack >= 1)
if (item is ICommodityStack stack && stack.Quantity > itemManager.MaxStack(item) && itemManager.MaxStack(item) >= 1)
{
var maxStack = itemManager.GetData(commodity).MaxStack;
var first = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = maxStack };
var rest = new SimpleCommodity { Data = commodity.Data, Rotation = commodity.Rotation, Quantity = commodity.Quantity - maxStack };
if (!bay.TryStore(first, position)) rest.Quantity += first.Quantity;
var maxStack = itemManager.MaxStack(item);
var first = stack.Split(maxStack);
var rest = stack.Split(stack.Quantity - maxStack);
if (!bay.TryStore(first, position)) ((ICommodityStack) rest).Quantity += maxStack;
spill.Add((bay, rest));
return;
}
if (bay.TryStore(item, position)) return;
var quantity = item is SimpleCommodity c ? $" x{c.Quantity}" : "";
var quantity = item is ICommodityStack c ? $" x{c.Quantity}" : "";
itemManager.Log($"Dropped a saved item the bay refused at {position}: {itemManager.GetData(item).Name}{quantity}");
}
// Places the units an oversize saved stack left over, in stacks of at most MaxStack: the stack's own bay first, then
// the entity's other bays. Only the units that fit nowhere are dropped, logged with their design and quantity.
private static void SpillOversize(ItemManager itemManager, IReadOnlyList<EquippedCargoBay> bays,
List<(EquippedCargoBay home, SimpleCommodity rest)> spill)
List<(EquippedCargoBay home, ItemInstance rest)> spill)
{
foreach (var (home, rest) in spill)
{
var maxStack = itemManager.GetData(rest).MaxStack;
var remaining = rest.Quantity;
var maxStack = itemManager.MaxStack(rest);
var remaining = ((ICommodityStack) rest).Quantity;
while (remaining > 0)
{
var chunk = new SimpleCommodity { Data = rest.Data, Rotation = rest.Rotation, Quantity = Math.Min(remaining, maxStack) };
var chunk = ((ICommodityStack) rest).Split(Math.Min(remaining, maxStack));
var chunkStack = (ICommodityStack) chunk;
var placed = home.TryStore(chunk) || bays.Where(b => b != home).Any(b => b.TryStore(chunk));
// A refused store may still have topped up a stack; what is left in the chunk found no room.
remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunk.Quantity);
remaining -= Math.Min(remaining, maxStack) - (placed ? 0 : chunkStack.Quantity);
if (placed) continue;
itemManager.Log($"Dropped saved units no bay has room for: {itemManager.GetData(rest).Name} x{remaining}");
break;
@ -147,7 +147,7 @@ public static class EntitySerializer
entity.DockingBays[i].DockedShip = entity.Children[pack.DockingBayAssignments[i]] as Ship;
}
var spill = new List<(EquippedCargoBay home, SimpleCommodity rest)>();
var spill = new List<(EquippedCargoBay home, ItemInstance rest)>();
for (var bayIndex = 0; bayIndex < pack.CargoContents.Length; bayIndex++)
if(entity.CargoBays.Count >= bayIndex + 1)
foreach (var (position, item) in pack.CargoContents[bayIndex])
@ -273,10 +273,7 @@ public abstract class EntityPack
foreach (var (_, item) in t)
{
var itemData = itemManager.GetData(item);
if (item is SimpleCommodity s)
_price += itemData.Price * s.Quantity;
else
_price += itemData.Price;
_price += item is ICommodityStack s ? itemData.Price * s.Quantity : itemData.Price;
}
}
@ -285,10 +282,7 @@ public abstract class EntityPack
foreach (var (_, item) in t)
{
var itemData = itemManager.GetData(item);
if (item is SimpleCommodity s)
_price += itemData.Price * s.Quantity;
else
_price += itemData.Price;
_price += item is ICommodityStack s ? itemData.Price * s.Quantity : itemData.Price;
}
}

View file

@ -360,6 +360,10 @@ public class CompoundCommodityData : CraftedItemData
{
// MessagePack keys 10 and 11 belonged to the removed demand weights and classification; do not reuse them.
// The most units of one lot a cargo cell holds. A sim-tuned knob; records written before it existed read 10.
[Inspectable, JsonProperty("maxStackSize"), Key(12)]
public int MaxStack = 10;
// A commodity is one cell unless authored otherwise: crate size is a balance knob, and a cargo bay reads Shape to store the good.
public CompoundCommodityData() => Shape = new Shape();
}

View file

@ -40,15 +40,45 @@ public abstract class CraftedItemInstance : ItemInstance
[JsonProperty("lot"), Key(11)] public int Lot;
}
// A commodity that stacks: the one owner of which units are interchangeable (StacksWith) and of what a split carries
// (Split). The cargo bay applies it at every merge and ItemManager.MaxStack bounds it; nothing else decides either.
public interface ICommodityStack
{
int Quantity { get; set; }
// True when `other` is a unit this stack may merge with.
bool StacksWith(ItemInstance other);
// A new stack of `quantity` units interchangeable with this one; this stack is left as it was.
ItemInstance Split(int quantity);
}
// Units of a compound commodity merge only within one lot (ruling compound-commodities-stack-by-lot): the lot is the
// units' provenance, workmanship and role fills.
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class CompoundCommodity : CraftedItemInstance { }
public class CompoundCommodity : CraftedItemInstance, ICommodityStack
{
// Keys 2, 9, 10 and 11 are CraftedItemInstance's and 12 EquippableItem's. A unit saved before Quantity existed has
// no slot 13 and reads one.
[JsonProperty("quantity"), Key(13)] public int Quantity { get; set; } = 1;
public bool StacksWith(ItemInstance other) =>
other is CompoundCommodity compound && compound.Data.Key.Equals(Data.Key) && compound.Lot == Lot;
public ItemInstance Split(int quantity) =>
new CompoundCommodity { Data = Data, Rotation = Rotation, Lot = Lot, Quantity = quantity };
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class SimpleCommodity : ItemInstance
public class SimpleCommodity : ItemInstance, ICommodityStack
{
// Key 11 belonged to a lot before ruling simple-commodities-fungible and is never reused; a pre-ruling stack's
// slot 11 is skipped on read.
[JsonProperty("quantity"), Key(2)] public int Quantity;
[JsonProperty("quantity"), Key(2)] public int Quantity { get; set; }
public bool StacksWith(ItemInstance other) => other is SimpleCommodity && other.Data.Key.Equals(Data.Key);
public ItemInstance Split(int quantity) => new SimpleCommodity { Data = Data, Rotation = Rotation, Quantity = quantity };
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]

View file

@ -74,8 +74,8 @@ public class ItemManager
{
return item switch
{
ICommodityStack stack => GetData(item).Mass * stack.Quantity,
CraftedItemInstance _ => GetData(item).Mass,
SimpleCommodity commodity => GetData(item).Mass * commodity.Quantity,
_ => 0
};
}
@ -85,12 +85,21 @@ public class ItemManager
var data = GetData(item);
return item switch
{
ICommodityStack stack => data.Mass * data.SpecificHeat * stack.Quantity,
CraftedItemInstance _ => data.Mass * data.SpecificHeat,
SimpleCommodity commodity => data.Mass * data.SpecificHeat * commodity.Quantity,
_ => 0
};
}
// The most units of the item one cell holds: the design's MaxStack for a commodity, one for anything else. The one
// reader of either design's MaxStack outside authoring.
public int MaxStack(ItemInstance item) => GetData(item) switch
{
SimpleCommodityData simple => simple.MaxStack,
CompoundCommodityData compound => compound.MaxStack,
_ => 1
};
// The one path from a crafted instance to its lot; a simple commodity has no lot.
public Lot GetLot(CraftedItemInstance item) => Lots[item.Lot];

View file

@ -8,12 +8,14 @@ using System.Linq;
// durabilities exactly as they were.
public static class StationServices
{
// What the station charges for the item, or for `quantity` units of a commodity (a crafted item is one unit). The
// number TradeMenu shows, checks against the run's credits and charges.
// What the station charges for the item, or for `quantity` units of a commodity, simple or compound (a crafted item
// is one unit). The number TradeMenu shows, checks against the run's credits and charges.
public static int BuyPrice(ItemManager items, ItemInstance item, int quantity = 1)
{
switch (item)
{
case CompoundCommodity compound:
return (int) Math.Min((long) items.GetPrice(compound) * quantity, int.MaxValue);
case CraftedItemInstance crafted:
return items.GetPrice(crafted);
case SimpleCommodity commodity:
@ -24,12 +26,14 @@ public static class StationServices
}
// What the station pays for the item: its price, scaled by SellFraction and by its condition. A commodity has no
// wear, so it sells at the fraction alone; a simple commodity's price is per unit.
// wear, so it sells at the fraction alone; a commodity's price, simple or compound, is per unit.
public static int SellPrice(ItemManager items, ItemInstance item)
{
var fraction = (double) items.GameplaySettings.SellFraction;
switch (item)
{
case CompoundCommodity compound:
return (int) Math.Floor((long) items.GetPrice(compound) * compound.Quantity * fraction);
case CraftedItemInstance crafted:
return SellValue(items.GetPrice(crafted), fraction, Condition(items, crafted));
case SimpleCommodity commodity:
@ -83,33 +87,35 @@ public static class StationServices
// design's MaxStack, so a stack the station holds is a lot already; a stack above it comes from outside a bay and is
// refused, as is a purchase of more than the stack holds or of a stack that holds nothing. All of that is refused
// before anything moves, so `deliver` moves units the station has and the charge is for the units it delivered.
public static BuyResult TryBuyLots(ItemManager items, SimpleCommodity stock, int quantity, ref int credits, Func<int, bool> deliver)
public static BuyResult TryBuyLots(ItemManager items, ItemInstance stock, int quantity, ref int credits, Func<int, bool> deliver)
{
if (quantity < 1 || quantity > stock.Quantity || stock.Quantity > items.GetData(stock).MaxStack) return BuyResult.NoRoom;
if (!(stock is ICommodityStack stack) || quantity < 1 || quantity > stack.Quantity || stack.Quantity > items.MaxStack(stock))
return BuyResult.NoRoom;
return TryBuy(items, stock, quantity, ref credits, () => deliver(quantity));
}
// The quantity a Buy Quantity field may hold: what was typed, at most what the credits cover and what the station
// has, and never below one unit (a price the credits do not cover is then refused as short of credits).
public static int BuyableQuantity(ItemManager items, SimpleCommodity stock, int typed, int credits) =>
Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock.Quantity));
public static int BuyableQuantity(ItemManager items, ItemInstance stock, int typed, int credits) =>
Math.Max(1, Math.Min(Math.Min(typed, credits / BuyPrice(items, stock)), stock is ICommodityStack stack ? stack.Quantity : 1));
// The sale: the item leaves the bay and the station pays SellPrice. A crafted item goes to one of the station's
// cargo bays; false, with the item in its bay and the credits unchanged, when no bay can take it. A simple
// commodity always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity): the bays take as much of
// the stack as fits and the market absorbs the rest, at the full price.
// cargo bays; false, with the item in its bay and the credits unchanged, when no bay can take it. A commodity stack,
// simple or compound, always sells (aetheria-release:ruling:station-market-absorbs-sold-commodity, and
// aetheria-living-world:question:compound-stack-sale-absorbs, option absorb): the bays take as much of the stack as
// fits and the market absorbs the rest, at the full price.
public static bool TrySell(EquippedCargoBay from, Entity station, ItemInstance item, ref int credits)
{
var price = SellPrice(station.ItemManager, item);
if (item is SimpleCommodity commodity)
if (item is ICommodityStack stack)
{
if (!from.Cargo.ContainsKey(commodity)) return false;
var offered = commodity.Quantity;
if (!from.Cargo.ContainsKey(item)) return false;
var offered = stack.Quantity;
for (var quantity = offered; quantity >= 1; quantity--)
if (station.CargoBays.Any(bay => from.TryTransferItem(bay, commodity, quantity))) break;
if (from.Cargo.ContainsKey(commodity)) from.Remove(commodity, commodity.Quantity);
if (station.CargoBays.Any(bay => from.TryTransferItem(bay, item, quantity))) break;
if (from.Cargo.ContainsKey(item)) from.Remove(item, stack.Quantity);
}
else if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, (CraftedItemInstance) item))) return false;
else if (!station.CargoBays.Any(bay => from.TryTransferItem(bay, item, 1))) return false;
credits += price;
return true;
}

View file

@ -445,7 +445,7 @@ public class Zone
if (floating == null || (floating.Holder != null && !ReferenceEquals(floating.Holder, taker))) return false;
// The quantity is read before the store: a store that merges into a part-filled stack and spills the rest into a
// new cell rewrites the item's Quantity.
var stored = floating.Item is SimpleCommodity stack ? stack.Quantity : 1;
var stored = floating.Item is ICommodityStack stack ? stack.Quantity : 1;
if (!taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false;
FloatingItems.Remove(floating);
CargoGained.OnNext(new CargoGain

View file

@ -211,18 +211,14 @@ public class TradeMenu : MonoBehaviour
{
if (x.data is HullData)
return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.Key.Equals(GameManager.ItemManager.ItemData.RefOf(x.data).Key) && s is Ship {IsPlayerShip: true}).ToString();
if(x.data is SimpleCommodityData)
return (_targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(x.data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(x.data).Key].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0).ToString();
return (_targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(x.data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(x.data).Key].Count : 0).ToString();
return _targetCargo.Count(GameManager.ItemManager.ItemData.RefOf(x.data).Key).ToString();
},
x =>
{
var data = x.data;
if (data is HullData)
return GameManager.DockedEntity.Children.Count(s => s.Hull.Data.Key.Equals(GameManager.ItemManager.ItemData.RefOf(data).Key) && s is Ship {IsPlayerShip: true});
if(data is SimpleCommodityData)
return _targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(data).Key].Cast<SimpleCommodity>().Sum(s=>s.Quantity) : 0;
return _targetCargo.ItemsOfType.ContainsKey(GameManager.ItemManager.ItemData.RefOf(data).Key) ? _targetCargo.ItemsOfType[GameManager.ItemManager.ItemData.RefOf(data).Key].Count : 0;
return _targetCargo.Count(GameManager.ItemManager.ItemData.RefOf(data).Key);
}));
Spreadsheet.ShowData(
@ -241,12 +237,12 @@ public class TradeMenu : MonoBehaviour
if (_selling) return;
switch (i.item)
{
case ICommodityStack _:
Buy(i.item, 1);
break;
case CraftedItemInstance c:
Buy(c);
break;
case SimpleCommodity s:
Buy(s, 1);
break;
}
Populate();
@ -259,7 +255,7 @@ public class TradeMenu : MonoBehaviour
ContextMenu.AddOption($"Sell ({StationServices.SellPrice(GameManager.ItemManager, i.item):N0})", () => Sell(i.item));
ContextMenu.Show();
}
else if (i.item is SimpleCommodity s)
else if (i.item is ICommodityStack)
{
ContextMenu.Clear();
ContextMenu.AddOption("Buy Quantity",
@ -270,10 +266,10 @@ public class TradeMenu : MonoBehaviour
Dialog.Title.text = $"Buying {GameManager.ItemManager.Title(i.item)}";
Dialog.AddField("Quantity",
() => quantity,
q => quantity = StationServices.BuyableQuantity(GameManager.ItemManager, s, q, GameManager.Credits));
q => quantity = StationServices.BuyableQuantity(GameManager.ItemManager, i.item, q, GameManager.Credits));
Dialog.Show(() =>
{
Buy(s,quantity);
Buy(i.item, quantity);
Populate();
});
@ -348,14 +344,14 @@ public class TradeMenu : MonoBehaviour
GameManager.CommissionShip(item as EquippableItem);
return true;
}
return Inventory.TryTransferItem(_targetCargo, item);
return Inventory.TryTransferItem(_targetCargo, item, 1);
}));
}
private void Buy(SimpleCommodity simpleCommodity, int quantity)
private void Buy(ItemInstance stock, int quantity)
{
Bought(StationServices.TryBuyLots(GameManager.ItemManager, simpleCommodity, quantity, ref GameManager.Credits,
lot => Inventory.TryTransferItem(_targetCargo, simpleCommodity, lot)));
Bought(StationServices.TryBuyLots(GameManager.ItemManager, stock, quantity, ref GameManager.Credits,
lot => Inventory.TryTransferItem(_targetCargo, stock, lot)));
}
// Refreshes the credits after a purchase, or tells the player why the station refused it.

View file

@ -364,11 +364,12 @@ public class PropertiesPanel : MonoBehaviour
AddProperty(data.Description);
if (item is SimpleCommodity simpleCommodity)
AddProperty("Quantity", () => simpleCommodity.Quantity.ToString());
if (item is ICommodityStack stack)
AddProperty("Quantity", () => stack.Quantity.ToString());
var sheet = AddStatSheet();
// Branding is derived from provenance, not stored on the design; a SimpleCommodity carries no lot and shows none.
// Branding is derived from provenance, not stored on the design: a simple commodity carries no lot and shows none,
// a compound stack's brand reads its lot below.
if (item is CraftedItemInstance crafted)
{
var (maker, product) = GameManager.ItemManager.Brand(crafted);

View file

@ -82,7 +82,7 @@ public sealed partial class RunStartTests
var stock = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType<CraftedItemInstance>().Select(piece => (bay, piece))).Single();
credits = StationServices.BuyPrice(_items, stock.piece);
Assert.Equal(BuyResult.Bought, StationServices.TryBuy(_items, stock.piece, 1, ref credits,
() => stock.bay.TryTransferItem(hold, stock.piece)));
() => stock.bay.TryTransferItem(hold, stock.piece, 1)));
Assert.Equal(0, credits);
Assert.Contains(stock.piece, hold.Cargo.Keys);
}

View file

@ -135,8 +135,8 @@ public sealed class FungibleCommodityTests : IDisposable
var small = MiningCut5aTests.Bay(f.Scene, ship, 1, 1, "Small");
Assert.True(small.TryStore(Units(f, f.Ore, 90)));
Assert.False(small.TryFindSpace(Units(f, shells, 5), out _));
Assert.True(small.TryFindSpace(Units(f, f.Ore, 5), out _));
Assert.False(small.TryFindSpace(Units(f, shells, 5)));
Assert.True(small.TryFindSpace(Units(f, f.Ore, 5)));
var other = Units(f, shells, 5);
Assert.False(small.TryStore(other, new int2(0, 0)));
Assert.Equal(90, Assert.Single(Stacks(small)).Quantity);
@ -168,7 +168,7 @@ public sealed class FungibleCommodityTests : IDisposable
Mine(f, zone, ship, 0, 0);
var stack = Assert.Single(Stacks(bay));
var part = bay.Remove(stack, 3);
Assert.Equal((3, 1), (part.Quantity, stack.Quantity));
Assert.Equal((3, 1), (((ICommodityStack) part).Quantity, stack.Quantity));
Assert.Equal(stack.Data.Key, part.Data.Key);
}