Make loadout availability a port and move the charge into Materialize (Cut 10 fix)

Materialize takes isAvailable as a Predicate<FactionProductData>; the restore
menu passes LoadoutGenerator.IsAvailable for the docked station, so generation
and loadouts still share one availability rule. Candidate products are ordered
by record key, so "first available product" no longer depends on dictionary
order. Materialize charges Price through ref credits only when it returns a
ship; RestoreLoadout no longer subtracts on its own.

Tests: a slot that resolves but does not fit builds nothing, charges nothing and
is listed; Price is the sum of design prices and is charged on success; the
first available product in key order builds a slot, a later one is used when
the first is unavailable, and none available fails the slot.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 22:27:03 +02:00
commit 5e5c304e37
4 changed files with 88 additions and 18 deletions

View file

@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
@ -64,15 +65,15 @@ public static class Loadouts
cache.Commit(batch => batch.Upsert(typeof(Loadout), loadout, key));
}
// All-or-nothing: returns a ship only when every design resolved, had an available product and fitted. Every
// failing slot is listed; on any failure nothing is returned and nothing outside this call has changed.
// Availability is LoadoutGenerator.IsAvailable, with no fallback to any manufacturer.
public static Ship Materialize(ItemManager itemManager, Galaxy galaxy, GalaxyZone zone, Faction stationFaction,
Zone liveZone, Loadout loadout, List<string> failures)
// All-or-nothing: returns a ship and charges Price only when every design resolved, had an available product and
// fitted. Every failure is listed; on any failure nothing is returned, nothing is charged and nothing outside this
// call has changed. A design is built by its first available product in record-key order. The game passes
// LoadoutGenerator.IsAvailable as isAvailable, with no fallback to any manufacturer.
public static Ship Materialize(ItemManager itemManager, Zone liveZone, Loadout loadout,
Predicate<FactionProductData> isAvailable, ref int credits, List<string> failures)
{
var cache = itemManager.ItemData;
var availability = new LoadoutGenerator(ref itemManager.Random, itemManager, galaxy, zone, stationFaction, 0);
var products = cache.GetAll<FactionProductData>().ToArray();
var products = cache.GetAll<FactionProductData>().OrderBy(p => cache.RefOf(p).Key.Value, StringComparer.Ordinal).ToArray();
var reported = failures.Count;
FactionProductData Resolve<T>(CultRecordRef<T> design, string where) where T : EquippableItemData
@ -84,7 +85,7 @@ public static class Loadouts
return null;
}
var product = products.FirstOrDefault(p => p.Design.Key.Equals(design.Key) && availability.IsAvailable(p));
var product = products.FirstOrDefault(p => p.Design.Key.Equals(design.Key) && isAvailable(p));
if (product == null) failures.Add($"{where}: no available product of {data.Name}");
return product;
}
@ -121,6 +122,7 @@ public static class Loadouts
return (items.Select(item => item.GetBehavior<Weapon>()).ToList(), items);
})
.ToArray();
credits -= Price(itemManager, loadout);
return ship;
}

View file

@ -149,7 +149,7 @@ public class LoadoutGenerator
// No galaxy means no availability to filter by: every product is on offer. A fixture generates loadouts that
// way, so a test can exercise placement and products without standing up a whole galaxy; no game path does.
// Loadouts.Materialize asks this too, so a loadout and generation share one availability rule.
// Restoring a loadout passes this to Loadouts.Materialize, so a loadout and generation share one availability rule.
public bool IsAvailable(FactionProductData product) =>
Galaxy == null || Galaxy.IsPrelude ||
Galaxy.ContainsFaction(product.Manufacturer) && (Faction == null || Faction.Allegiance.ContainsKey(product.Manufacturer));

View file

@ -187,7 +187,7 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler
loadouts.Select<Loadout, (string text, Action action, bool enabled)>(loadout =>
{
var price = Loadouts.Price(GameManager.ItemManager, loadout);
return ($"{loadout.Name} - {price:n0}", () => RestoreLoadout(loadout, price), price < GameManager.Credits);
return ($"{loadout.Name} - {price:n0}", () => RestoreLoadout(loadout), price < GameManager.Credits);
}));
}
@ -198,12 +198,14 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler
// Builds the loadout against the current galaxy at the docked station. On failure nothing changes: no ship, no
// charge, and a dialog lists every slot that could not be built here.
private void RestoreLoadout(Loadout loadout, int price)
private void RestoreLoadout(Loadout loadout)
{
var station = GameManager.DockedEntity;
var failures = new List<string>();
var ship = Loadouts.Materialize(GameManager.ItemManager, ActionGameManager.CurrentGalaxy, GameManager.Zone.GalaxyZone,
station.Faction, GameManager.Zone, loadout, failures);
var availability = new LoadoutGenerator(ref GameManager.ItemManager.Random, GameManager.ItemManager,
ActionGameManager.CurrentGalaxy, GameManager.Zone.GalaxyZone, station.Faction, 0);
var ship = Loadouts.Materialize(GameManager.ItemManager, GameManager.Zone, loadout, availability.IsAvailable,
ref GameManager.Credits, failures);
if (ship == null)
{
Dialog.Clear();
@ -214,7 +216,6 @@ public class InventoryPanel : MonoBehaviour, IPointerClickHandler
return;
}
GameManager.Credits -= price;
ship.SetParent(station);
ship.IsPlayerShip = true;
GameManager.DockingBay.DockedShip = ship;

View file

@ -69,7 +69,7 @@ public sealed class LoadoutTests : IDisposable
var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { });
hand = HandBuilt(cache);
var failures = new List<string>();
var ship = Loadouts.Materialize(items, null, null, null, null, hand, failures);
var ship = Build(items,hand, failures);
Assert.Empty(failures);
Assert.NotNull(ship);
Loadouts.Save(cache, Loadouts.Capture(items, ship, hand.Name));
@ -86,7 +86,7 @@ public sealed class LoadoutTests : IDisposable
var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { });
var failures = new List<string>();
var ship = Loadouts.Materialize(items, null, null, null, null, loaded, failures);
var ship = Build(items,loaded, failures);
Assert.Empty(failures);
Assert.Equal(hand.Slots.Select(slot => (slot.Position, slot.Design.Key)),
ship.Equipment.Concat<EquippedItem>(ship.CargoBays)
@ -141,14 +141,14 @@ public sealed class LoadoutTests : IDisposable
var missing = HandBuilt(cache);
missing.Slots[1].Design = new CultRecordRef<EquippableItemData>(new CultRecordKey("absent-design"));
var failures = new List<string>();
Assert.Null(Loadouts.Materialize(items, null, null, null, null, missing, failures));
Assert.Null(Build(items,missing, failures));
var failure = Assert.Single(failures);
Assert.Contains("1,1", failure);
Assert.Contains("absent-design", failure);
missing.Slots.Add(new LoadoutSlot { Position = new int2(2, 2), Design = cache.RefOf<EquippableItemData>(cache.GetByName<GearData>("Orphan")) });
failures.Clear();
Assert.Null(Loadouts.Materialize(items, null, null, null, null, missing, failures));
Assert.Null(Build(items,missing, failures));
Assert.Equal(2, failures.Count);
Assert.Contains("slot 1,1", failures[0]);
Assert.Contains("slot 2,2", failures[1]);
@ -158,6 +158,73 @@ public sealed class LoadoutTests : IDisposable
Assert.Equal(before, new[] { Catalog, Run, Player }.Select(Hash).ToArray());
}
[Fact]
public void FailedFitBuildsNothingAndChargesNothing()
{
using var cache = Open();
var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { });
var clash = HandBuilt(cache);
clash.Slots[1].Position = HardpointCell;
var failures = new List<string>();
var credits = 1000;
Assert.Null(Loadouts.Materialize(items, null, clash, _ => true, ref credits, failures));
Assert.Equal(1000, credits);
var failure = Assert.Single(failures);
Assert.Contains("slot 0,0: Crate does not fit", failure);
}
[Fact]
public void PriceIsTheSumOfDesignPricesAndIsCharged()
{
using var cache = Open();
var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { });
var hand = HandBuilt(cache);
Assert.Equal(100 + 10 + 5, Loadouts.Price(items, hand));
var credits = 1000;
Assert.NotNull(Loadouts.Materialize(items, null, hand, _ => true, ref credits, new List<string>()));
Assert.Equal(1000 - 115, credits);
}
// Two more Lamp products, written so insertion order (z before a) disagrees with record-key order.
[Fact]
public void FirstAvailableProductInKeyOrderBuildsTheSlot()
{
using (var catalog = AetheriaStores.Open(Catalog, catalogWritable: true))
{
var maker = catalog.RefOf(catalog.GetByName<Faction>("Maker"));
var lamp = new CultRecordRef<CraftedItemData>(catalog.RefOf(catalog.GetByName<GearData>("Lamp")).Key);
catalog.Commit(batch =>
{
foreach (var key in new[] { "lamp-z", "lamp-a" })
batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = key, Design = lamp, Manufacturer = maker }, new CultRecordKey(key));
});
}
using var cache = Open();
var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { });
var hand = HandBuilt(cache);
string LampProduct(Predicate<FactionProductData> available, List<string> failures)
{
var credits = 1000;
var ship = Loadouts.Materialize(items, null, hand, available, ref credits, failures);
return ship == null ? null : cache.Get(ship.Equipment.Single(item => item.EquippableItem != ship.Hull && item.Position.Equals(HardpointCell)).EquippableItem.Product).Name;
}
var failures = new List<string>();
Assert.Equal("lamp-a", LampProduct(p => p.Name != "Lamp by Maker", failures));
Assert.Equal("lamp-z", LampProduct(p => p.Name != "Lamp by Maker" && p.Name != "lamp-a", failures));
Assert.Empty(failures);
Assert.Null(LampProduct(p => !p.Name.StartsWith("Lamp") && !p.Name.StartsWith("lamp"), failures));
Assert.Contains("slot 0,0: no available product of Lamp", Assert.Single(failures));
}
// Everything available, credits discarded: for tests about placement and failure lists.
private static Ship Build(ItemManager items, Loadout loadout, List<string> failures)
{
var credits = 0;
return Loadouts.Materialize(items, null, loadout, _ => true, ref credits, failures);
}
private static (int2, ItemRotation, CultRecordKey) Describe(LoadoutSlot slot) => (slot.Position, slot.Rotation, slot.Design.Key);
private static string Hash(string path) => File.Exists(path) ? Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))) : "absent";