Merge origin/master into asteroid-floater-layer

This commit is contained in:
Meta Vens 2026-10-17 18:25:01 +02:00
commit da2a7cc56a
17 changed files with 947 additions and 109 deletions

View file

@ -0,0 +1,126 @@
using System.Linq;
using CultMath;
using Xunit;
// HullFootprint: the one rule for editing a hardpoint's schematic footprint (Position + Shape together) and the
// one reading of its cells in hull space.
public sealed class HullFootprintTests
{
private static HardpointData Hardpoint(int2 position, params int2[] cellsInShapeSpace)
{
var max = cellsInShapeSpace.Aggregate(new int2(0, 0), (a, c) => new int2(CultMath.math.max(a.x, c.x), CultMath.math.max(a.y, c.y)));
var shape = new Shape(max.x + 1, max.y + 1);
foreach (var c in cellsInShapeSpace) shape[c] = true;
return new HardpointData { Position = position, Shape = shape };
}
private static int2[] Hull(HardpointData hp) => HullFootprint.Cells(hp).OrderBy(c => c.y).ThenBy(c => c.x).ToArray();
private static HardpointData Apply(HardpointData hp, int2 hullCell)
{
Assert.True(HullFootprint.Toggle(hp.Shape, hp.Position, hullCell, out var shape, out var position));
return new HardpointData { Position = position, Shape = shape };
}
[Fact]
public void CellsAreTheShapeLaidAtPosition()
{
var hp = Hardpoint(new int2(3, 3), new int2(0, 0), new int2(1, 0));
Assert.Equal(new[] { new int2(3, 3), new int2(4, 3) }, Hull(hp));
}
[Fact]
public void FootprintGrowsTowardAnyEdgeAndKeepsItsCells()
{
var hp = Hardpoint(new int2(3, 3), new int2(0, 0));
var grown = Apply(Apply(hp, new int2(2, 3)), new int2(3, 2));
Assert.Equal(new int2(2, 2), grown.Position);
Assert.Equal(2, grown.Shape.Width);
Assert.Equal(2, grown.Shape.Height);
Assert.Equal(new[] { new int2(3, 2), new int2(2, 3), new int2(3, 3) }, Hull(grown));
var right = Apply(Apply(hp, new int2(4, 3)), new int2(3, 4));
Assert.Equal(new int2(3, 3), right.Position);
Assert.Equal(new[] { new int2(3, 3), new int2(4, 3), new int2(3, 4) }, Hull(right));
}
[Fact]
public void FootprintTrimsBackToItsOriginal()
{
var hp = Hardpoint(new int2(3, 3), new int2(0, 0));
var grown = Apply(Apply(hp, new int2(2, 3)), new int2(3, 2));
var trimmed = Apply(Apply(grown, new int2(2, 3)), new int2(3, 2));
Assert.Equal(hp.Position, trimmed.Position);
Assert.Equal(1, trimmed.Shape.Width);
Assert.Equal(1, trimmed.Shape.Height);
Assert.Equal(Hull(hp), Hull(trimmed));
}
[Fact]
public void FootprintRefusesItsLastCell()
{
var hp = Hardpoint(new int2(3, 3), new int2(0, 0));
Assert.False(HullFootprint.Toggle(hp.Shape, hp.Position, new int2(3, 3), out var shape, out var position));
Assert.Equal(hp.Position, position);
Assert.Same(hp.Shape, shape);
Assert.Equal(new[] { new int2(3, 3) }, Hull(hp));
}
[Fact]
public void RefusedClickLeavesPositionWhereItWasWhenTheLastCellIsNotAtPosition()
{
var hp = Hardpoint(new int2(3, 3), new int2(1, 0));
Assert.Equal(new[] { new int2(4, 3) }, Hull(hp));
Assert.False(HullFootprint.Toggle(hp.Shape, hp.Position, new int2(4, 3), out var shape, out var position));
Assert.Equal(new int2(3, 3), position);
Assert.Same(hp.Shape, shape);
}
[Fact]
public void WideFootprintLaysEveryCellAtPositionAndEditsAtItsFarEnd()
{
var hp = Hardpoint(new int2(2, 2), new int2(0, 0), new int2(1, 0), new int2(2, 0), new int2(3, 0), new int2(4, 0));
Assert.Equal(new[] { new int2(2, 2), new int2(3, 2), new int2(4, 2), new int2(5, 2), new int2(6, 2) }, Hull(hp));
var grown = Apply(hp, new int2(7, 2));
Assert.Equal(new int2(2, 2), grown.Position);
Assert.Equal(new[] { new int2(2, 2), new int2(3, 2), new int2(4, 2), new int2(5, 2), new int2(6, 2), new int2(7, 2) }, Hull(grown));
var trimmed = Apply(hp, new int2(6, 2));
Assert.Equal(new int2(2, 2), trimmed.Position);
Assert.Equal(new[] { new int2(2, 2), new int2(3, 2), new int2(4, 2), new int2(5, 2) }, Hull(trimmed));
}
[Fact]
public void FootprintToggleLeavesItsInputUnchanged()
{
var hp = Hardpoint(new int2(3, 3), new int2(0, 0), new int2(1, 0));
HullFootprint.Toggle(hp.Shape, hp.Position, new int2(2, 3), out _, out _);
HullFootprint.Toggle(hp.Shape, hp.Position, new int2(4, 3), out _, out _);
Assert.Equal(new int2(3, 3), hp.Position);
Assert.Equal(2, hp.Shape.Width);
Assert.Equal(1, hp.Shape.Height);
Assert.Equal(new[] { new int2(3, 3), new int2(4, 3) }, Hull(hp));
}
[Fact]
public void TrimmingAnInteriorBorderMovesPositionWithoutMovingCells()
{
var hp = Hardpoint(new int2(5, 5), new int2(0, 0), new int2(1, 0), new int2(2, 0));
var trimmed = Apply(hp, new int2(5, 5));
Assert.Equal(new int2(6, 5), trimmed.Position);
Assert.Equal(new[] { new int2(6, 5), new int2(7, 5) }, Hull(trimmed));
}
}

View file

@ -0,0 +1,146 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using CultMath;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// The Aya Collective, Megiddo and Orbital Forge (aetheria-release, cut minor-power-factions; ruling no-territory-ban): three
// ordinary factions in the shipped catalog, authored by AetherDb's minor-power-factions command, which a scratch copy of the
// catalog without them proves idempotent and conflict-refusing.
public sealed class MinorPowersTests : IDisposable
{
private static readonly string[] Minor = { "Aya", "Megiddo", "Forge" };
private readonly string _root = Path.Combine(Path.GetTempPath(), "minor-powers-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
public void Dispose()
{
if (Directory.Exists(_root)) Directory.Delete(_root, true);
}
// A scratch copy of the shipped catalog with the three, their products and every allegiance toward them removed, through a
// registry scoped to the shipped assembly (as PiratesFactionCommandTests does), so the command has all of it to author.
private void StripTheMinorPowers()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), CatalogPath);
using var cache = new CultCache(TestCatalog.Registry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var gone = cache.GetAll<Faction>().Where(f => Minor.Contains(f.ShortName)).Select(f => cache.RefOf(f)).ToArray();
Assert.Equal(3, gone.Length);
foreach (var product in cache.GetAll<FactionProductData>().Where(p => gone.Any(g => g.Key.Equals(p.Manufacturer.Key))).ToArray())
Assert.True(cache.Remove(cache.RefOf(product).Key));
foreach (var reference in gone) Assert.True(cache.Remove(reference.Key));
foreach (var faction in cache.GetAll<Faction>())
foreach (var key in faction.Allegiance.Keys.Where(k => gone.Any(g => g.Key.Equals(k.Key))).ToArray())
faction.Allegiance.Remove(key);
cache.Commit(batch =>
{
foreach (var faction in cache.GetAll<Faction>()) batch.Upsert(typeof(Faction), faction, cache.RefOf(faction).Key);
});
cache.FlushAsync().Wait();
}
[Fact]
public void TheMinorPowersAreOrdinaryFactions()
{
using var cache = RestoredHullsTests.OpenCatalog();
var factions = cache.GetAll<Faction>().ToArray();
foreach (var shortName in Minor)
{
var faction = Assert.Single(factions, f => f.ShortName == shortName);
Assert.NotNull(cache.Get(faction.GeonameFile));
Assert.True(faction.InfluenceDistance > 0, shortName);
var named = faction.Allegiance.Keys.Select(k => k.Key).ToArray();
var expected = factions.Where(f => f != faction && f.ShortName != "Pirates").Select(f => cache.RefOf(f).Key).ToArray();
Assert.Equal(expected.Length, named.Length);
Assert.All(expected, key => Assert.Contains(named, n => n.Equals(key)));
}
// Territory is nothing a faction can say of itself: no member of Faction marks a maker-only or landless power.
Assert.DoesNotContain(typeof(Faction).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic),
m => m.Name.Contains("ManufacturerOnly") || m.Name.Contains("Territory"));
}
[Fact]
public void TheCommandIsIdempotentAndRefusesAConflict()
{
StripTheMinorPowers();
var before = File.ReadAllBytes(CatalogPath);
Assert.Equal(0, MinorPowerFactionsCommand.Run(new string[0], _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, MinorPowerFactionsCommand.Run(new[] { "apply" }, _root));
var landed = File.ReadAllBytes(CatalogPath);
Assert.NotEqual(before, landed);
var db = AetherDb.Open(root: _root);
try
{
var factions = db.Cache.GetAll<Faction>().ToArray();
foreach (var shortName in Minor) Assert.Single(factions, f => f.ShortName == shortName);
foreach (var shortName in Minor)
{
var own = factions.Single(f => f.ShortName == shortName);
var expected = factions.Where(f => f != own && f.ShortName != "Pirates").Select(f => db.Cache.RefOf(f).Key).ToArray();
Assert.Equal(expected.Length, own.Allegiance.Count);
Assert.All(expected, key => Assert.Contains(own.Allegiance.Keys, k => k.Key.Equals(key)));
}
var forge = db.Cache.RefOf(factions.Single(f => f.ShortName == "Forge"));
Assert.Equal(.5f, factions.Single(f => f.ShortName == "AU").Allegiance[forge]);
// The Pirates' allegiance is pirates-faction's; Miss Terri's is her own.
Assert.All(factions.Where(f => f.ShortName is "Pirates" or "Miss Terri's"), f => Assert.DoesNotContain(f.Allegiance.Keys, k => k.Equals(forge)));
}
finally { db.Cache.Dispose(); }
Assert.Equal(0, MinorPowerFactionsCommand.Run(new[] { "apply" }, _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void ANameHeldUnderAnotherKeyIsRefusedWithNothingWritten()
{
StripTheMinorPowers();
var squatter = AetherDb.Open(catalogWritable: true, root: _root);
squatter.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Megiddo", ShortName = "Megiddo" }));
squatter.Cache.Dispose();
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => MinorPowerFactionsCommand.Run(new[] { "apply" }, _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
}
public sealed partial class RunStartTests
{
// Forge holds no zone in the prelude, so its gear reaches AU only through allegiance (ruling gear-without-presence); a
// design-only slot draws among the makers AU can reach (ruling design-only-weighted-draw). Miss Terri's names none of them.
[Fact]
public void TheirGearSellsWhereTheyAreAbsent()
{
var factions = _cache.GetAll<Faction>().ToArray();
var forge = factions.Single(f => f.ShortName == "Forge");
Assert.DoesNotContain(_galaxy.Factions, f => f == forge);
var autocannon = _cache.GetAll<CraftedItemData>().Single(d => d.Name == "Autocannon");
var pattern30 = _cache.GetAll<FactionProductData>().Single(p => p.Name == "Pattern 30");
LoadoutGenerator For(string shortName, uint seed)
{
_items.Random = new CultMath.Random(seed);
return new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, factions.Single(f => f.ShortName == shortName), .5f);
}
Assert.True(For("AU", 1).IsAvailable(pattern30));
// Seeds 1-64 spread by a multiplicative hash: the generator's first draws of adjacent small seeds are close together.
Assert.Contains(Enumerable.Range(1, 64), seed => For("AU", unchecked((uint) seed * 2654435761u)).ChooseProduct(autocannon)?.Name == pattern30.Name);
var terri = For("Miss Terri's", 1);
var theirs = _cache.GetAll<FactionProductData>().Where(p => new[] { "Aya", "Megiddo", "Forge" }.Contains(_cache.Get(p.Manufacturer).ShortName)).ToArray();
Assert.Equal(10, theirs.Length);
Assert.All(theirs, product => Assert.False(terri.IsAvailable(product), product.Name));
}
}

View file

@ -64,7 +64,9 @@ public sealed class PickupTests : IDisposable
};
}
private Lab Build(PickupData beam, float lifetime = 30f)
// With `wells`, the zone has a sun (a parentless rail off the ship's side, strength 400) and a planet on a moving rail round
// it (strength 25), the field a floater layer is read against; without, the zone is flat and nothing pulls on anything.
private Lab Build(PickupData beam, float lifetime = 30f, bool wells = false)
{
var settings = new GameplaySettings
{
@ -77,7 +79,8 @@ public sealed class PickupTests : IDisposable
LootDropProbability = 0, LootDropVelocity = 25, FloatingItemLifetime = lifetime,
ShipLayerHeight = 3f, FloaterLayerHeight = -1.5f
};
var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
var id = Guid.NewGuid().ToString("N");
var cache = AetheriaStores.Open(Path.Combine(_root, id + ".cc"), Path.Combine(_root, id + "-run.cc"), catalogWritable: true);
_caches.Add(cache);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = Solid(5, 5), Durability = 1000000, Mass = 1000 });
@ -104,7 +107,26 @@ public sealed class PickupTests : IDisposable
var ledger = new ProvenanceLedger();
for (var i = 1; i <= 9000; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 };
var items = new ItemManager(cache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack { Radius = 0 }, new GalaxyZone { Name = "Pickup", Owner = null }, null);
var pack = new ZonePack { Radius = 0 };
var curves = new PlanetSettings();
if (wells)
{
curves = new PlanetSettings
{
BodyRadius = new ExponentialCurve(),
WellStrength = new ExponentialCurve { Multiplier = 1f, Exponent = 1f },
RocheLimit = new ExponentialCurve { Constant = 2f }
};
var sunOrbit = cache.Upsert(new OrbitData { FixedPosition = float2(-50, 0) }).Key;
var planetOrbit = cache.Upsert(new OrbitData { Parent = new CultRecordRef<OrbitData>(sunOrbit), Distance = 90f, Phase = .9f }).Key;
pack.Radius = 5000f;
pack.Mass = 10000f;
pack.Orbits.Add(new CultRecordRef<OrbitData>(sunOrbit));
pack.Orbits.Add(new CultRecordRef<OrbitData>(planetOrbit));
pack.Planets.Add(new CultRecordRef<BodyData>(cache.Upsert(new PlanetData { Name = "Sun", Orbit = new CultRecordRef<OrbitData>(sunOrbit), Mass = 400f }).Key));
pack.Planets.Add(new CultRecordRef<BodyData>(cache.Upsert(new PlanetData { Name = "Planet", Orbit = new CultRecordRef<OrbitData>(planetOrbit), Mass = 25f }).Key));
}
var zone = new Zone(items, curves, pack, new GalaxyZone { Name = "Pickup", Owner = null }, null);
return new Lab { Items = items, Zone = zone };
}
@ -251,16 +273,29 @@ public sealed class PickupTests : IDisposable
public void AGrabPointRidesTheFloaterLayerNotTheShips()
{
using var bag = new CompositeDisposable();
var lab = Build(Beam());
var lab = Build(Beam(), wells: true);
var ship = Spawn(lab, float3(0, 0, 0));
var item = Drift(lab, 40, 0);
var events = Watch(ship, bag);
// The fixture has a field to ride: it differs between the ship's point and the item's, and between the start and
// the end of the run, so a grab point read at the ship's xz or at the wrong time cannot agree with it.
var atShip = lab.Zone.GetHeight(float2(0, 0), lab.Zone.ExactTime);
var atItem = lab.Zone.GetHeight(float2(40, 0), lab.Zone.ExactTime);
Assert.True(abs(atItem - atShip) > 1f, $"the field is flat under the grab: ship {atShip}, item {atItem}");
var start = lab.Zone.ExactTime;
// Each event is checked at the zone time it was published, where the sim read the field.
var seen = new List<(GrabEvent Event, double Time)>();
ship.Capabilities.Grab.Subscribe(e => seen.Add((e, lab.Zone.ExactTime))).AddTo(bag);
ship.TractorCommand = 1;
for (var tick = 1; tick <= 150; tick++) lab.Zone.Update(1 / 60f);
Assert.NotEmpty(events);
Assert.All(events, e => Assert.Equal(lab.Zone.GetHeight(e.TargetPosition.xz, lab.Zone.ExactTime) - 1.5f, e.TargetPosition.y, 3));
Assert.NotEmpty(seen);
Assert.True(abs(lab.Zone.GetHeight(float2(40, 0), lab.Zone.ExactTime) - lab.Zone.GetHeight(float2(40, 0), start)) > .01f, "the wells did not move");
Assert.All(seen, s => Assert.Equal(lab.Zone.GetHeight(s.Event.TargetPosition.xz, s.Time) - 1.5f, s.Event.TargetPosition.y, 3));
Assert.All(seen, s => Assert.True(abs(s.Event.TargetPosition.y - (-1.5f)) > 1f, "the grab point sits on the bare layer, the field dropped"));
}
[Fact]
public void GrabEventsNameTheFloatingItem()
{

View file

@ -39,6 +39,13 @@ public sealed class PiratesFactionCommandTests : IDisposable
public void Dispose() => Directory.Delete(_root, true);
private int AllFactionsButThePirates()
{
var db = AetherDb.Open(root: _root);
try { return db.Cache.GetAll<Faction>().Count(f => f.Name != "Pirates"); }
finally { db.Cache.Dispose(); }
}
private (Faction[] Pirates, FactionProductData[] Products) Read()
{
var db = AetherDb.Open(root: _root);
@ -69,7 +76,7 @@ public sealed class PiratesFactionCommandTests : IDisposable
Assert.Equal(3, faction.InfluenceDistance);
Assert.Equal(new CultMath.float3(.42f, .40f, .37f), faction.PrimaryColor);
Assert.Equal(new CultMath.float3(1f, .45f, .05f), faction.SecondaryColor);
Assert.Equal(12, faction.Allegiance.Count);
Assert.Equal(AllFactionsButThePirates(), faction.Allegiance.Count);
Assert.All(faction.Allegiance.Values, value => Assert.Equal(1f, value));
var db = AetherDb.Open(root: _root);
@ -105,17 +112,52 @@ public sealed class PiratesFactionCommandTests : IDisposable
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
// An existing hand-authored Pirates record is topped up, never rewritten (follow-up pirates-allegiance-and-identity): it keeps
// its description, short name and record key and gains no products; after a faction is added, apply gives allegiance 1.0 to
// that faction alone; a second apply leaves the file bytes unchanged and a dry run writes nothing.
[Fact]
public void An_existing_Pirates_faction_is_left_as_it_is()
public void An_existing_Pirates_faction_is_topped_up_with_allegiance_and_nothing_else()
{
var db = AetherDb.Open(catalogWritable: true, root: _root);
db.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Pirates", ShortName = "Mine", Description = "authored by hand" }));
var key = db.Cache.RefOf(db.Cache.GetAll<Faction>().Single(f => f.Name == "Pirates")).Key;
db.Cache.Dispose();
var beforeDry = File.ReadAllBytes(CatalogPath);
Assert.Equal(0, Program.PiratesFaction(apply: false, root: _root));
Assert.Equal(beforeDry, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
var (pirates, products) = Read();
Assert.Equal("authored by hand", Assert.Single(pirates).Description);
var record = Assert.Single(pirates);
Assert.Equal("authored by hand", record.Description);
Assert.Equal("Mine", record.ShortName);
Assert.Empty(products);
var topped = File.ReadAllBytes(CatalogPath);
var late = AetherDb.Open(catalogWritable: true, root: _root);
late.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Latecomer", ShortName = "Late" }));
var lateRef = late.Cache.RefOf(late.Cache.GetAll<Faction>().Single(f => f.Name == "Latecomer"));
var others = late.Cache.GetAll<Faction>().Count(f => f.Name != "Pirates");
late.Cache.Dispose();
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
var check = AetherDb.Open(root: _root);
try
{
var after = check.Cache.GetAll<Faction>().Single(f => f.Name == "Pirates");
Assert.Equal(key, check.Cache.RefOf(after).Key);
Assert.Equal("authored by hand", after.Description);
Assert.Equal(others, after.Allegiance.Count);
Assert.Equal(1f, after.Allegiance[lateRef]);
Assert.All(after.Allegiance.Values, value => Assert.Equal(1f, value));
}
finally { check.Cache.Dispose(); }
var settled = File.ReadAllBytes(CatalogPath);
Assert.NotEqual(topped, settled);
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
Assert.Equal(settled, File.ReadAllBytes(CatalogPath));
}
[Fact]

View file

@ -45,12 +45,42 @@ public sealed class ProductLinesCatalogTests
Assert.Empty(shared);
}
// Ruling gear-without-presence: a sold ship gear design with roles has two makers. The six reactor designs named here are
// station gear or Faction Play's NiteLife-only quirk, and keep their one maker.
private static readonly string[] OneMakerGear =
{
"Muon Fusion Reactor", "Muon Fusion Station Reactor", "Station Reactor", "Heavy Station Reactor",
"High-Yield Station Reactor", "Ring Station Reactor",
};
[Fact]
public void WeaponLineRowsAreShipped()
public void EveryRoleBearingGearDesignWithAProductHasTwoMakers()
{
using var cache = RestoredHullsTests.OpenCatalog();
var table = ProductLinesCommand.Table("weapons");
Assert.Equal(20, table.Count);
var products = cache.GetAll<FactionProductData>().ToArray();
var gear = cache.GetAll<GearData>().Where(d => d is not WeaponItemData && (d.Roles?.Count ?? 0) > 0).ToArray();
Assert.All(OneMakerGear, name => Assert.Contains(gear, d => d.Name == name));
var sold = 0;
foreach (var design in gear.Where(d => !OneMakerGear.Contains(d.Name)))
{
var key = cache.RefOf(design).Key;
var makers = products.Where(p => p.Design.Key.Equals(key)).Select(p => p.Manufacturer.Key).Distinct().Count();
if (makers == 0) continue;
sold++;
Assert.True(makers >= 2, $"the gear design \"{design.Name}\" is sold by {makers} maker");
}
Assert.True(sold >= 20, "the gear designs with products should be many");
}
[Theory]
[InlineData("weapons", 20)]
[InlineData("gear", 22)]
[InlineData("minor-powers", 10)]
public void LineRowsAreShipped(string line, int count)
{
using var cache = RestoredHullsTests.OpenCatalog();
var table = ProductLinesCommand.Table(line);
Assert.Equal(count, table.Count);
foreach (var row in table)
{
var product = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Name == row.Name);
@ -60,7 +90,7 @@ public sealed class ProductLinesCatalogTests
Assert.Equal(row.Description, product.Description);
var (mean, dev) = Program.MakerProfiles[row.Maker];
Assert.Equal(
design.Roles.Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal),
(design.Roles ?? new()).Select(r => r.Name).OrderBy(n => n, StringComparer.Ordinal),
product.Roles.Select(r => r.Role).OrderBy(n => n, StringComparer.Ordinal));
foreach (var role in product.Roles)
{

View file

@ -6,28 +6,32 @@ using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's product-lines command (cut product-lines-weapons), run on a scratch copy of the shipped catalog with the weapon
// line's twenty products removed from it. Apply must write what the shipped catalog holds, only its own records, finish a
// catalog that holds part of the line, refuse a name that is another product's, and accept a maker that already sells the design.
public sealed class ProductLinesCommandTests : IDisposable
// AetherDb's product-lines command (cuts product-lines-weapons and gear-lines), run per line on a scratch copy of the shipped
// catalog with that line's products removed from it. Apply must write what the shipped catalog holds, only its own records,
// land on an older-schema catalog, and accept a maker that already sells the design. The weapon line adds the tests that
// need weapon rows by name; the gear line adds the cargo-bay exemption from the no-roles refusal.
public abstract class ProductLinesCommandTests : IDisposable
{
private static readonly string[] Names = ProductLinesCommand.Table("weapons").Select(r => r.Name).ToArray();
private static readonly string[] Line = { "weapons" };
private static readonly string[] LineApply = { "weapons", "apply" };
protected readonly string[] Names;
protected readonly string[] Line;
protected readonly string[] LineApply;
private readonly string _root = Path.Combine(Path.GetTempPath(), "product-lines-command-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
protected readonly string _root = Path.Combine(Path.GetTempPath(), "product-lines-command-" + Guid.NewGuid().ToString("N"));
protected string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
// The rows as the shipped catalog holds them, taken before they are removed from the scratch copy.
private readonly string[] _shipped;
protected readonly string[] _shipped;
private readonly string[] _shippedKeys;
private static string Describe(CultCache cache, FactionProductData product) =>
$"{cache.Get(product.Design).Name} | {product.Name} | {cache.Get(product.Manufacturer).ShortName} | {product.Description} | " +
string.Join(",", product.Roles.OrderBy(r => r.Role, StringComparer.Ordinal).Select(r => $"{r.Role}:{r.Mean}:{r.StandardDeviation}"));
public ProductLinesCommandTests()
protected ProductLinesCommandTests(string line)
{
Names = ProductLinesCommand.Table(line).Select(r => r.Name).ToArray();
Line = new[] { line };
LineApply = new[] { line, "apply" };
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
Directory.CreateDirectory(Path.Combine(_root, "Assets", "Resources"));
var shipped = AetherDb.FindRoot();
@ -44,14 +48,14 @@ public sealed class ProductLinesCommandTests : IDisposable
public void Dispose() => Directory.Delete(_root, true);
private CultCache Open()
protected CultCache Open()
{
var cache = new CultCache(TestCatalog.Registry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
return cache;
}
private string[] Line20()
protected string[] Line20()
{
using var cache = Open();
return cache.GetAll<FactionProductData>().Where(p => Names.Contains(p.Name)).Select(p => Describe(cache, p)).OrderBy(x => x, StringComparer.Ordinal).ToArray();
@ -127,38 +131,6 @@ public sealed class ProductLinesCommandTests : IDisposable
}
}
[Fact]
public void Apply_finishes_a_catalog_that_holds_part_of_the_line()
{
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
using (var cache = Open())
{
foreach (var product in cache.GetAll<FactionProductData>().Where(p => p.Name == "Merlin" || p.Name == "Tripwire").ToArray())
Assert.True(cache.Remove(cache.RefOf(product).Key));
cache.FlushAsync().Wait();
}
Assert.Equal(Names.Length - 2, Line20().Length);
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(_shipped, Line20());
}
[Fact]
public void Apply_refuses_a_row_name_that_is_another_products_and_writes_nothing()
{
using (var cache = Open())
{
var other = cache.GetAll<WeaponItemData>().First(w => w.Name == "Light Machine Gun");
var maker = cache.GetAll<Faction>().First(f => f.ShortName == "Zhestokost");
cache.Upsert(new FactionProductData { Name = "Sparrow", Design = new CultRecordRef<CraftedItemData>(cache.RefOf(other).Key), Manufacturer = cache.RefOf(maker) });
cache.FlushAsync().Wait();
}
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
}
// Ruling maker-design-tiers-allowed: a maker that already sells a design may sell another product of it.
[Fact]
public void Apply_accepts_a_maker_that_already_sells_the_design()
@ -215,6 +187,46 @@ public sealed class ProductLinesCommandTests : IDisposable
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
}
// One collection: the lines open the same catalog records through shared state and must not run side by side.
[Collection("ProductLinesCommand")]
public sealed class WeaponLineCommandTests : ProductLinesCommandTests
{
public WeaponLineCommandTests() : base("weapons") { }
[Fact]
public void Apply_finishes_a_catalog_that_holds_part_of_the_line()
{
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
using (var cache = Open())
{
foreach (var product in cache.GetAll<FactionProductData>().Where(p => p.Name == "Merlin" || p.Name == "Tripwire").ToArray())
Assert.True(cache.Remove(cache.RefOf(product).Key));
cache.FlushAsync().Wait();
}
Assert.Equal(Names.Length - 2, Line20().Length);
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(_shipped, Line20());
}
[Fact]
public void Apply_refuses_a_row_name_that_is_another_products_and_writes_nothing()
{
using (var cache = Open())
{
var other = cache.GetAll<WeaponItemData>().First(w => w.Name == "Light Machine Gun");
var maker = cache.GetAll<Faction>().First(f => f.ShortName == "Zhestokost");
cache.Upsert(new FactionProductData { Name = "Sparrow", Design = new CultRecordRef<CraftedItemData>(cache.RefOf(other).Key), Manufacturer = cache.RefOf(maker) });
cache.FlushAsync().Wait();
}
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
}
private void AddProduct(string name, string design, string maker)
{
using var cache = Open();
@ -260,3 +272,40 @@ public sealed class ProductLinesCommandTests : IDisposable
Assert.Equal(1, Program.Main(new[] { "product-lines", "nonesuch" }));
}
}
[Collection("ProductLinesCommand")]
public sealed class GearLineCommandTests : ProductLinesCommandTests
{
public GearLineCommandTests() : base("gear") { }
// Cargo bays carry no roles (ruling catalog-breadth-roles-and-components): their product lands with none. Any other design
// with no roles is still refused, with nothing written.
[Fact]
public void Apply_accepts_a_roleless_cargo_bay_and_refuses_a_roleless_gear_design()
{
using (var cache = Open())
{
var radiator = cache.GetAll<GearData>().Single(g => g.Name == "Radiator");
radiator.Behaviors.Clear(); // the store refuses a behavior that names a role the design lacks
radiator.Roles.Clear();
cache.Upsert(radiator);
cache.FlushAsync().Wait();
}
var conflicted = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => ProductLinesCommand.Run(LineApply, _root));
Assert.Equal(conflicted, File.ReadAllBytes(CatalogPath));
using (var cache = Open())
{
var radiator = cache.GetAll<GearData>().Single(g => g.Name == "Radiator");
radiator.Roles.Add(new ItemRole { Name = "Cooling" });
cache.Upsert(radiator);
cache.FlushAsync().Wait();
}
Assert.Equal(0, ProductLinesCommand.Run(LineApply, _root));
using var after = Open();
var pithos = Assert.Single(after.GetAll<FactionProductData>(), p => p.Name == "Pithos");
Assert.IsType<CargoBayData>(after.Get(pithos.Design));
Assert.Empty(pithos.Roles);
}
}

View file

@ -0,0 +1,68 @@
using System.Linq;
using CultMath;
using Xunit;
using static CultMath.math;
// Shape's derived reads (Coordinates, AllCoordinates, CenterOfMass) are caches of Cells and follow every edit.
public sealed class ShapeCacheTests
{
[Fact]
public void CenterOfMassFollowsACellCleared()
{
var shape = new Shape(2, 1);
shape[int2(0, 0)] = true;
shape[int2(1, 0)] = true;
Assert.Equal(0.5f, shape.CenterOfMass.x);
shape[int2(0, 0)] = false;
Assert.Equal(1f, shape.CenterOfMass.x);
Assert.Equal(0f, shape.CenterOfMass.y);
}
[Fact]
public void ResizeRecountsEveryCoordinateRead()
{
var shape = new Shape(2, 1);
shape[int2(0, 0)] = true;
shape[int2(1, 0)] = true;
Assert.Equal(2, shape.AllCoordinates.Length);
Assert.Equal(2, shape.Coordinates.Length);
var before = shape.CenterOfMass;
shape.Resize(3, 2);
Assert.Equal(6, shape.AllCoordinates.Length);
Assert.Equal(shape.Cells.Cast<bool>().Count(c => c), shape.Coordinates.Length);
Assert.NotEqual(before, shape.CenterOfMass);
}
[Fact]
public void ResizeKeepsExistingCellsAndFillsNewOnes()
{
// The hull drawer's width grow relies on the fill (ships-studio-footprint r1 keeps it).
var shape = new Shape(2, 1);
shape[int2(0, 0)] = true;
shape.Resize(3, 1);
Assert.True(shape[int2(0, 0)]);
Assert.False(shape[int2(1, 0)]);
Assert.True(shape[int2(2, 0)]);
}
[Fact]
public void SetLineRecountsEveryCoordinateRead()
{
var shape = new Shape(4, 1);
shape[int2(0, 0)] = true;
Assert.Single(shape.Coordinates);
Assert.Equal(0f, shape.CenterOfMass.x);
shape.SetLine(float2(0f, 0f), float2(3f, 0f));
Assert.Equal(4, shape.Coordinates.Length);
Assert.Equal(4, shape.AllCoordinates.Length);
Assert.Equal(1.5f, shape.CenterOfMass.x);
}
}