diff --git a/Assets/Scripts/ServerShared/Loadout.cs b/Assets/Scripts/ServerShared/Loadout.cs index 570521531..6c31b422d 100644 --- a/Assets/Scripts/ServerShared/Loadout.cs +++ b/Assets/Scripts/ServerShared/Loadout.cs @@ -51,7 +51,7 @@ public static class Loadouts Design = cache.RefOf(itemManager.GetData(item.EquippableItem)) }).ToList(), WeaponGroups = entity.WeaponGroups - .Select(group => group.items.Select(item => items.IndexOf(item)).Where(index => index >= 0).ToArray()) // skips unequipped items + .Select(group => group.items.Select(item => items.IndexOf(item)).ToArray()) .ToArray() }; } @@ -65,10 +65,13 @@ public static class Loadouts cache.Commit(batch => batch.Upsert(typeof(Loadout), loadout, key)); } - // All-or-nothing: returns a ship and charges Price only when credits cover Price and every design resolved, had an - // available product and fitted. Affordability is decided here and nowhere else. 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. + // All-or-nothing: returns a ship and charges Price only when credits cover Price, every design resolved, had an + // available product and fitted, the loadout has at most WeaponGroupCount weapon groups, and every group index names + // a weapon slot. Affordability is decided here and nowhere else. Every failure is listed; on any failure nothing is + // returned and nothing is charged. The ship, credits, zone and cache are unchanged, but a failed fit has already + // drawn from itemManager.Random. 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. The ship always gets + // exactly WeaponGroupCount groups; a loadout with fewer is padded with empty groups. public static Ship Materialize(ItemManager itemManager, Zone liveZone, Loadout loadout, Predicate isAvailable, ref int credits, List failures) { @@ -92,8 +95,15 @@ public static class Loadouts var hullProduct = Resolve(loadout.Hull, "hull"); var slotProducts = loadout.Slots.Select(slot => Resolve(slot.Design, Cell(slot))).ToArray(); - foreach (var index in (loadout.WeaponGroups ?? new int[0][]).SelectMany(group => group)) + var groups = loadout.WeaponGroups ?? new int[0][]; + var groupCount = itemManager.GameplaySettings.WeaponGroupCount; + if (groups.Length > groupCount) failures.Add($"weapon groups: {groups.Length} groups, at most {groupCount}"); + foreach (var index in groups.SelectMany(group => group)) + { if (index < 0 || index >= loadout.Slots.Count) failures.Add($"weapon group: no slot {index}"); + else if (cache.Get(loadout.Slots[index].Design) is { } design && !design.Behaviors.Any(behavior => behavior is WeaponData)) + failures.Add($"weapon group: {Cell(loadout.Slots[index])}: {design.Name} is not a weapon"); + } var price = Price(itemManager, loadout); if (credits < price) failures.Add($"cannot afford {price:n0} credits"); if (failures.Count > reported) return null; @@ -119,22 +129,23 @@ public static class Loadouts } if (failures.Count > reported) return null; - ship.WeaponGroups = (loadout.WeaponGroups ?? new int[0][]) - .Select(indices => - { - var items = indices.Select(i => equipped[i]).ToList(); - return (items.Select(item => item.GetBehavior()).ToList(), items); - }) - .ToArray(); - credits -= price; + var built = new (List weapons, List items)[groupCount]; + for (var g = 0; g < groupCount; g++) + { + var items = g < groups.Length ? groups[g].Select(i => equipped[i]).ToList() : new List(); + built[g] = (items.Select(item => item.GetBehavior()).ToList(), items); + } + ship.WeaponGroups = built; + credits -= (int) price; return ship; } - // The hull design's price plus each slot design's price. - public static int Price(ItemManager itemManager, Loadout loadout) + // The hull design's price plus each slot design's price. Summed as long so no loadout wraps to a negative price; + // a price beyond any int credit balance is simply unaffordable. + public static long Price(ItemManager itemManager, Loadout loadout) { var cache = itemManager.ItemData; - return (cache.Get(loadout.Hull)?.Price ?? 0) + loadout.Slots.Sum(slot => cache.Get(slot.Design)?.Price ?? 0); + return (long) (cache.Get(loadout.Hull)?.Price ?? 0) + loadout.Slots.Sum(slot => (long) (cache.Get(slot.Design)?.Price ?? 0)); } private static string Cell(LoadoutSlot slot) => $"slot {slot.Position.x},{slot.Position.y}"; diff --git a/tests/Aetheria.Shared.Tests/LoadoutTests.cs b/tests/Aetheria.Shared.Tests/LoadoutTests.cs index 385088fd0..c7916df6f 100644 --- a/tests/Aetheria.Shared.Tests/LoadoutTests.cs +++ b/tests/Aetheria.Shared.Tests/LoadoutTests.cs @@ -36,9 +36,10 @@ public sealed class LoadoutTests : IDisposable }); var gear = cache.Upsert(new GearData { Name = "Lamp", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10 }); var cargo = cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = new Shape(), Price = 5 }); + var gun = cache.Upsert(new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Behaviors = { new InstantWeaponData() } }); cache.Upsert(new GearData { Name = "Orphan", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1 }); - foreach (var (name, design) in new[] { ("Skiff by Maker", hull.Key), ("Lamp by Maker", gear.Key), ("Crate by Maker", cargo.Key) }) + foreach (var (name, design) in new[] { ("Skiff by Maker", hull.Key), ("Lamp by Maker", gear.Key), ("Crate by Maker", cargo.Key), ("Gun by Maker", gun.Key) }) cache.Upsert(new FactionProductData { Name = name, Design = new CultRecordRef(design), Manufacturer = maker }); cache.FlushAsync().Wait(); } @@ -47,7 +48,7 @@ public sealed class LoadoutTests : IDisposable private CultCache Open() => AetheriaStores.Open(Catalog, Run, Player); - // Gear on the hull's hardpoint cell, cargo on an interior cell, and the gear alone in the first weapon group. + // Gear on the hull's hardpoint cell, cargo on an interior cell, and two empty weapon groups (fewer than the game's six). private static Loadout HandBuilt(CultCache cache, string name = "Skiff build") => new Loadout { Name = name, @@ -57,9 +58,24 @@ public sealed class LoadoutTests : IDisposable new LoadoutSlot { Position = HardpointCell, Design = cache.RefOf(cache.GetByName("Lamp")) }, new LoadoutSlot { Position = InteriorCell, Design = cache.RefOf(cache.GetByName("Crate")) } }, - WeaponGroups = new[] { new[] { 0 }, new int[0] } + WeaponGroups = new[] { new int[0], new int[0] } }; + // HandBuilt with the Gun on the hardpoint, alone in the first of the game's six weapon groups. + private static Loadout Armed(CultCache cache) + { + var armed = HandBuilt(cache, "Armed build"); + armed.Slots[0].Design = cache.RefOf(cache.GetByName("Gun")); + armed.WeaponGroups = Enumerable.Range(0, 6).Select(g => g == 0 ? new[] { 0 } : new int[0]).ToArray(); + return armed; + } + + private static Loadout WithDesign(Loadout loadout, int slot, CultCache cache, string gear) + { + loadout.Slots[slot].Design = cache.RefOf(cache.GetByName(gear)); + return loadout; + } + [Fact] public void LoadoutRoundTripsThroughAFreshCache() { @@ -67,7 +83,7 @@ public sealed class LoadoutTests : IDisposable using (var cache = Open()) { var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); - hand = HandBuilt(cache); + hand = Armed(cache); var failures = new List(); var ship = Build(items,hand, failures); Assert.Empty(failures); @@ -214,30 +230,12 @@ public sealed class LoadoutTests : IDisposable Assert.Contains("slot 0,0: no available product of Lamp", Assert.Single(failures)); } - // Entity.TryUnequip leaves a non-weapon item in its weapon group; Capture must not record it. - [Fact] - public void CaptureSkipsGroupedItemsNoLongerEquipped() - { - using var cache = Open(); - var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); - var ship = Build(items, HandBuilt(cache), new List()); - Assert.NotNull(ship.TryUnequip(Assert.Single(ship.WeaponGroups[0].items))); - Assert.NotEmpty(ship.WeaponGroups[0].items); - - var captured = Loadouts.Capture(items, ship, "stripped"); - Assert.Single(captured.Slots); - Assert.All(captured.WeaponGroups, group => Assert.Empty(group)); - var failures = new List(); - Assert.NotNull(Build(items, captured, failures)); - Assert.Empty(failures); - } - [Fact] public void OutOfRangeWeaponGroupIndexBuildsNothing() { using var cache = Open(); var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); - var stale = HandBuilt(cache); + var stale = Armed(cache); stale.WeaponGroups = new[] { new[] { 0, 2 }, new[] { -1 } }; var failures = new List(); var credits = 1000; @@ -253,7 +251,7 @@ public sealed class LoadoutTests : IDisposable var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); var hand = HandBuilt(cache); var failures = new List(); - var credits = Loadouts.Price(items, hand) - 1; + var credits = (int) Loadouts.Price(items, hand) - 1; Assert.Null(Loadouts.Materialize(items, null, hand, _ => true, ref credits, failures)); Assert.Equal(114, credits); Assert.Equal("cannot afford 115 credits", Assert.Single(failures)); @@ -262,19 +260,9 @@ public sealed class LoadoutTests : IDisposable [Fact] public void UnequippingAGroupedWeaponRemovesItFromItsGroups() { - using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); - var gun = new GearData { Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 1, Behaviors = { new InstantWeaponData() } }; - cache.Commit(batch => batch.Upsert(typeof(GearData), gun, new CultRecordKey("gun"))); - cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData - { - Name = "Gun by Maker", Design = new CultRecordRef(new CultRecordKey("gun")), - Manufacturer = cache.RefOf(cache.GetByName("Maker")) - }, new CultRecordKey("gun-by-maker"))); - + using var cache = Open(); var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); - var armed = HandBuilt(cache); - armed.Slots[0].Design = new CultRecordRef(new CultRecordKey("gun")); - var ship = Build(items, armed, new List()); + var ship = Build(items, Armed(cache), new List()); var item = Assert.Single(ship.WeaponGroups[0].items); Assert.NotNull(item.GetBehavior()); @@ -283,6 +271,74 @@ public sealed class LoadoutTests : IDisposable Assert.All(ship.WeaponGroups, group => Assert.Empty(group.weapons)); } + // A group index on a non-weapon slot would put a null weapon in the group; it is refused before anything is built. + [Fact] + public void NonWeaponGroupIndexBuildsNothing() + { + using var cache = Open(); + var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); + var lampGrouped = WithDesign(Armed(cache), 0, cache, "Lamp"); + var failures = new List(); + var credits = 1000; + Assert.Null(Loadouts.Materialize(items, null, lampGrouped, _ => true, ref credits, failures)); + Assert.Equal(1000, credits); + Assert.Equal("weapon group: slot 0,0: Lamp is not a weapon", Assert.Single(failures)); + } + + [Fact] + public void MoreWeaponGroupsThanTheGameHasBuildsNothing() + { + using var cache = Open(); + var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); + var wide = Armed(cache); + wide.WeaponGroups = wide.WeaponGroups.Append(new[] { 0 }).ToArray(); + var failures = new List(); + var credits = 1000; + Assert.Null(Loadouts.Materialize(items, null, wide, _ => true, ref credits, failures)); + Assert.Equal(1000, credits); + Assert.Equal("weapon groups: 7 groups, at most 6", Assert.Single(failures)); + } + + // Fewer groups, or none, still give the ship exactly WeaponGroupCount groups, so GenerateWeaponGroups and G1-G6 + // bindings can index every one. + [Fact] + public void FewerWeaponGroupsArePaddedToTheGameCount() + { + using var cache = Open(); + var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); + var armed = Armed(cache); + armed.WeaponGroups = new[] { new[] { 0 } }; + foreach (var groups in new[] { armed.WeaponGroups, null }) + { + armed.WeaponGroups = groups; + var failures = new List(); + var ship = Build(items, armed, failures); + Assert.Empty(failures); + Assert.Equal(6, ship.WeaponGroups.Length); + Assert.All(ship.WeaponGroups.Skip(1), group => Assert.Empty(group.items)); + Assert.Equal(groups == null ? 0 : 1, ship.WeaponGroups[0].items.Count); + ship.GenerateWeaponGroups(); + } + } + + // The slots alone sum to exactly int.MaxValue; adding the hull must not wrap the total negative and pay the player. + [Fact] + public void PriceBeyondIntIsUnaffordable() + { + using var cache = AetheriaStores.Open(Catalog, catalogWritable: true); + var brick = cache.Upsert(new GearData { Name = "Brick", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = int.MaxValue - 5 }); + cache.Upsert(new FactionProductData { Name = "Brick by Maker", Design = new CultRecordRef(brick.Key), Manufacturer = cache.RefOf(cache.GetByName("Maker")) }); + + var items = new ItemManager(cache, RunSaveTests.TestSettings(), _ => { }); + var gold = WithDesign(HandBuilt(cache), 0, cache, "Brick"); + Assert.Equal(100L + int.MaxValue, Loadouts.Price(items, gold)); + var failures = new List(); + var credits = int.MaxValue; + Assert.Null(Loadouts.Materialize(items, null, gold, _ => true, ref credits, failures)); + Assert.Equal(int.MaxValue, credits); + Assert.StartsWith("cannot afford", Assert.Single(failures)); + } + // Everything available and affordable: for tests about placement and failure lists. private static Ship Build(ItemManager items, Loadout loadout, List failures) {