From fa4467e9a3e1b4e389ad474ee7355601b00d6044 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 04:00:08 +0200 Subject: [PATCH 01/10] Loot 1 (simulation): Zone owns floating items, rolls death drops on SimulationDice, expires them and commits pickups Zone.Release is the one adder, StepFloatingItems and TryPickUp the only removers; DropLoot runs from the one death subscription before the entity leaves the zone. Three C# default settings. Unity's drop path is untouched (loot-1-present deletes it). Not yet built or run at this commit. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/FloatingBodies.cs | 11 + Assets/Scripts/ServerShared/Settings.cs | 5 + Assets/Scripts/ServerShared/Zone.cs | 65 ++- tests/Aetheria.Shared.Tests/LootTests.cs | 388 ++++++++++++++++++ 4 files changed, 468 insertions(+), 1 deletion(-) create mode 100644 tests/Aetheria.Shared.Tests/LootTests.cs diff --git a/Assets/Scripts/ServerShared/FloatingBodies.cs b/Assets/Scripts/ServerShared/FloatingBodies.cs index a5d26ae20..e6a873b44 100644 --- a/Assets/Scripts/ServerShared/FloatingBodies.cs +++ b/Assets/Scripts/ServerShared/FloatingBodies.cs @@ -40,3 +40,14 @@ public struct KinematicBody Position += (Velocity + Drift) * dt; } } + +// An item adrift in a zone: a death drop or jettisoned cargo. Zone.Release is its only adder; Zone's floating-item +// step (expiry) and TryPickUp are its only removers. Runtime state, never saved. +public sealed class FloatingItem +{ + public FloatingBodyId Id; + public ItemInstance Item; + public KinematicBody Body; + public double ReleasedAt; + public float Lifetime; +} diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 9c4bd459f..32914f77f 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -178,6 +178,11 @@ public class GameplaySettings public float FloatingBodyDrag = .05f; public float FloatingBodyLaunchDrag = .2f; public float FloatingBodyGravity = 1f; + // Loot: the chance each equipped item (the hull excepted) drops when its carrier dies, the launch speed of a + // dropped item, and how many seconds a floating item lasts. + public float LootDropProbability = .25f; + public float LootDropVelocity = 25f; + public float FloatingItemLifetime = 30f; public float SevereHeatstrokeRiskThreshold = .25f; public float WormholeDepth = 1000; public float WormholeExitVelocity = 20; diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 4aa2063cc..a3d390992 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -24,6 +24,10 @@ public class Zone // Vented vapour clouds, in vent order. Zone owns their existence: Vent is the one adder, StepClouds the one // remover, and Obscuration the one reader that detection uses. Runtime state, never saved. public ReactiveCollection Clouds = new ReactiveCollection(); + + // Floating items (death drops, jettisoned cargo), in release order. Zone owns their existence: Release is the one + // adder; StepFloatingItems (expiry) and TryPickUp are the only removers. Runtime state, never saved. + public ReactiveCollection FloatingItems = new ReactiveCollection(); public Dictionary Planets = new Dictionary(); public Dictionary PlanetInstances = new Dictionary(); @@ -93,6 +97,9 @@ public class Zone private uint _lastBodyId; public FloatingBodyId NextBodyId() => new FloatingBodyId(++_lastBodyId); + // The death ordinal of the loot dice: the nth death in this zone rolls on SimulationDice.For(CombatSeed, LootStream, n). + private uint _deaths; + public Zone(ItemManager itemManager, PlanetSettings settings, ZonePack pack, GalaxyZone galaxyZone, Galaxy galaxy) { _time = pack.Time; @@ -108,7 +115,7 @@ public class Zone // in the simulation, not only in Unity's own loot-drop subscription. One subscription point covers // every join, whichever caller admits the entity (deserialization below, a jump, a spawned turret) -- // ObserveAdd fires for all of them. Forbidden writer: no presentation may remove an entity from Zone. - Entities.ObserveAdd().Subscribe(add => add.Value.Death.Subscribe(_ => { Entities.Remove(add.Value); add.Value.Deactivate(); })); + Entities.ObserveAdd().Subscribe(add => add.Value.Death.Subscribe(_ => { DropLoot(add.Value); Entities.Remove(add.Value); add.Value.Deactivate(); })); Targets.Add(new EntityTargets()); @@ -232,6 +239,7 @@ public class Zone StepMines(deltaTime); StepClouds(deltaTime); + StepFloatingItems(deltaTime); // Cut 3: after every entity has had its chance to fire this tick, age and resolve the shots that // firing queued. A shot fired this tick with a flight time shorter than CommitHorizon commits and @@ -252,6 +260,61 @@ public class Zone Clouds.Add(cloud); } + // The one adder of floating items: death drops and jettison both come here. The item drifts as a KinematicBody + // launched at `velocity` and expires after FloatingItemLifetime. + public FloatingItem Release(ItemInstance item, float2 position, float2 velocity) + { + var floating = new FloatingItem + { + Id = NextBodyId(), Item = item, Body = new KinematicBody { Position = position, Velocity = velocity }, + ReleasedAt = _time, Lifetime = _itemManager.GameplaySettings.FloatingItemLifetime + }; + FloatingItems.Add(floating); + return floating; + } + + // The one commit of a pickup: the first of the taker's cargo bays that accepts the item stores it and the item + // stops floating. Otherwise nothing changes. + public bool TryPickUp(Entity taker, FloatingBodyId id) + { + var floating = FloatingItems.FirstOrDefault(f => f.Id.Equals(id)); + if (floating == null || !taker.CargoBays.Any(bay => bay.TryStore(floating.Item))) return false; + FloatingItems.Remove(floating); + return true; + } + + // Called from the death subscription, before the entity leaves the zone: one generator per death. Each equipped + // item but the hull drops on a LootDropProbability draw; every cargo stack drops whole. Each drop leaves from the + // dead entity's position at a random heading. Draw order: Equipment order (the probability draw, then the heading + // of a dropped item), then each cargo bay's stacks in CargoBays order (a heading each). + private void DropLoot(Entity dead) + { + var settings = _itemManager.GameplaySettings; + var random = SimulationDice.For(CombatSeed, SimulationDice.LootStream, ++_deaths); + var at = new float2(dead.Position.x, dead.Position.z); + float2 Heading() { var angle = random.NextFloat() * 2f * PI; return float2(cos(angle), sin(angle)); } + foreach (var equipped in dead.Equipment.ToArray()) + { + if (equipped == dead.EquippedHull || !(random.NextFloat() < settings.LootDropProbability)) continue; + Release(equipped.EquippableItem, at, Heading() * settings.LootDropVelocity); + } + foreach (var bay in dead.CargoBays.ToArray()) + foreach (var stack in bay.Cargo.Keys.ToArray()) + Release(stack, at, Heading() * settings.LootDropVelocity); + } + + // After StepClouds and before FireControl.Step: each floating item drifts as a KinematicBody on the zone's force + // and is removed once its lifetime has run out. + private void StepFloatingItems(float deltaTime) + { + var settings = _itemManager.GameplaySettings; + foreach (var floating in FloatingItems.ToArray()) + { + floating.Body.Step(deltaTime, GetForce(floating.Body.Position), settings); + if (floating.ReleasedAt + floating.Lifetime <= _time) FloatingItems.Remove(floating); + } + } + // The fraction of a sight line's signal that survives the clouds between `a` and `b`: the product of // (1 - opacity now) over every cloud whose disc the segment touches, so 1f when none does. Derived from the // live clouds at each call and stored nowhere; Sensor.Gain is where it enters detection. diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs new file mode 100644 index 000000000..ffdea32b9 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -0,0 +1,388 @@ +/* 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.Collections.Generic; +using System.IO; +using System.Linq; +using CultMath; +using GameCult.Caching; +using UniRx; +using Xunit; +using static CultMath.math; +using float2 = CultMath.float2; +using float3 = CultMath.float3; +using int2 = CultMath.int2; + +// Loot in the sim (aetheria-release cut loot-1): a death drops gear by probability and cargo whole, rolled on the +// zone's own dice; the drops float as free bodies, expire, and are collected through Zone.TryPickUp. Rulings: +// jettison-shared-floating-items, mines-float-like-loot, one-gravity-law. Every death here goes through the +// production path: an entity's own death stream, observed by the one death subscription in Zone. +public sealed class LootTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-loot-" + Guid.NewGuid().ToString("N")); + private readonly List _caches = new List(); + + public LootTests() => Directory.CreateDirectory(_root); + + public void Dispose() + { + foreach (var c in _caches) c.Dispose(); + Directory.Delete(_root, true); + } + + private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v }; + + private static Shape Solid(int w, int h) + { + var shape = new Shape(w, h); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + return shape; + } + + private sealed class Lab + { + public ItemManager Items; + public Zone Zone; + public int Lot = 4001; + + public EquippableItem Make(string name, float durability = 1) => new EquippableItem + { + Data = Items.ItemData.RefOf(Items.ItemData.GetByName(name)), Durability = durability, Lot = Lot++ + }; + + public SimpleCommodity Ore(int quantity) => new SimpleCommodity + { + Data = Items.ItemData.RefOf(Items.ItemData.GetByName("Ore")), Quantity = quantity + }; + + public string Describe(ItemInstance item) => Items.GetData(item).Name + (item is SimpleCommodity c ? "x" + c.Quantity : ""); + } + + private Lab Build(string zoneName = "Loot", float probability = .5f, float lifetime = 30f, float velocity = 25f, + PlanetSettings planets = null, float spread = 0f) + { + var settings = new GameplaySettings + { + DefaultEntitySettings = new EntitySettings(), + Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } }, + QualityPriceModifier = new ExponentialLerp(), + TargetDetectionInfoThreshold = .1f, TargetArmorInfoThreshold = .2f, TargetGearInfoThreshold = .8f, + FiringArc = 170, CommitHorizon = .5f, SchematicCellSize = 1f, + UnaidedAccuracy = .05f, UnaidedTracking = 10f, UnaidedPrecision = 2f, AgentMinHitProbability = 0f, + LootDropProbability = probability, LootDropVelocity = velocity, FloatingItemLifetime = lifetime + }; + var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true); + _caches.Add(cache); + cache.Upsert(new VerseGrammar { Revision = 1 }); + var hardpoint = new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() }; + cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = Solid(5, 5), Durability = 1000000, Mass = 1000, Hardpoints = { hardpoint } }); + cache.Upsert(new HullData { Name = "Hub", HullType = HullType.Station, Shape = Solid(5, 5), Durability = 1000000, Mass = 1000 }); + cache.Upsert(new GearData + { + Name = "Gun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new InstantWeaponData + { + Damage = Constant(1), Range = Constant(1000), MinRange = Constant(0), Velocity = Constant(0), Spread = Constant(spread), + DamageSpread = Constant(0), Penetration = Constant(0), Count = Constant(1), BurstTime = Constant(0), Cooldown = Constant(1000), + DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } } + } } + }); + cache.Upsert(new GearData + { + Name = "Targeting", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new TargetingSystemData { Accuracy = Constant(1), Resolution = Constant(1000), Precision = Constant(1), Tracking = Constant(100000) } } + }); + // One occupied cell, so a bay can be filled with it. + cache.Upsert(new GearData + { + Name = "Spare", Hardpoint = HardpointType.Tool, Shape = Solid(1, 1), Durability = 1, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000 + }); + cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Durability = 4 }); + cache.Upsert(new CargoBayData { Name = "Tiny", Shape = new Shape(), InteriorShape = Solid(1, 1), Durability = 4 }); + cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = Solid(1, 1), MaxStack = 100 }); + cache.FlushAsync().Wait(); + + var ledger = new ProvenanceLedger(); + for (var i = 1; i <= 4000; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 }; + var items = new ItemManager(cache, ledger, settings, _ => { }); + var zone = new Zone(items, planets ?? new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = zoneName, Owner = null }, null); + return new Lab { Items = items, Zone = zone }; + } + + // A ship carrying a gun, a targeting system and a spare, with ore and a spare gun in its crate. + private static Ship Spawn(Lab lab, float3 at, string bay = "Crate", bool cargo = true) + { + var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Skiff")); + var ship = new Ship(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, new EntitySettings()); + Assert.True(ship.TryEquip(lab.Make("Gun"), new int2(0, 0))); + foreach (var name in new[] { "Targeting", "Spare" }) + { + var gear = lab.Make(name); + Assert.True(ship.TryFindSpace(gear, out var pos)); + Assert.True(ship.TryEquip(gear, pos)); + } + var crate = lab.Make(bay); + Assert.True(ship.TryFindSpace(crate, out var cratePos)); + Assert.True(ship.TryEquip(crate, cratePos)); + if (cargo) + { + Assert.True(ship.CargoBays.Single().TryStore(lab.Ore(7))); + Assert.True(ship.CargoBays.Single().TryStore(lab.Make("Spare"))); + } + lab.Zone.Entities.Add(ship); + ship.Activate(); + ship.Position = at; + return ship; + } + + private static Entity Station(Lab lab, float3 at) + { + var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Hub")); + var station = new OrbitalEntity(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, default, new EntitySettings()); + var spare = lab.Make("Spare"); + Assert.True(station.TryFindSpace(spare, out var pos)); + Assert.True(station.TryEquip(spare, pos)); + var crate = lab.Make("Crate"); + Assert.True(station.TryFindSpace(crate, out var cratePos)); + Assert.True(station.TryEquip(crate, cratePos)); + Assert.True(station.CargoBays.Single().TryStore(lab.Ore(3))); + lab.Zone.Entities.Add(station); + station.Activate(); + station.Position = at; + return station; + } + + private static void Kill(Entity e) => e.HeatstrokeDeath.OnNext(Unit.Default); + + private static List<(string Item, float2 Position, float2 Velocity)> Released(Lab lab, int from) => + lab.Zone.FloatingItems.Skip(from).Select(f => (lab.Describe(f.Item), f.Body.Position, f.Body.Velocity)).ToList(); + + private static void AssertSameDrops(List<(string Item, float2 Position, float2 Velocity)> a, List<(string Item, float2 Position, float2 Velocity)> b) + { + Assert.Equal(a.Count, b.Count); + for (var i = 0; i < a.Count; i++) + { + Assert.Equal(a[i].Item, b[i].Item); + Assert.Equal(a[i].Position, b[i].Position); + Assert.Equal(a[i].Velocity, b[i].Velocity); + } + } + + private static bool Differ(List<(string Item, float2 Position, float2 Velocity)> a, List<(string Item, float2 Position, float2 Velocity)> b) => + a.Count != b.Count || a.Zip(b, (x, y) => x.Item != y.Item || !x.Position.Equals(y.Position) || !x.Velocity.Equals(y.Velocity)).Any(d => d); + + [Fact] + public void DeathDropsAreRolledOnTheZonesDice() + { + var at = float3(31, 0, -17); + var first = Build("Dice"); + Kill(Spawn(first, at)); + var dropsA = Released(first, 0); + Assert.True(dropsA.Count > 2, "the fixture must drop enough for a draw to show"); + Assert.All(dropsA, d => Assert.Equal(new float2(31, -17), d.Position)); + Assert.All(dropsA, d => Assert.Equal(25f, length(d.Velocity), 3)); + + // Another zone with the same name (the same galaxy seed) and the same ship drops the same things the same way, + // whatever the item manager's own generator has been asked in between. + var second = Build("Dice"); + for (var i = 0; i < 5; i++) second.Items.Random.NextFloat(); + var shipB = Spawn(second, at); + for (var i = 0; i < 5; i++) second.Items.Random.NextFloat(); + Kill(shipB); + AssertSameDrops(dropsA, Released(second, 0)); + + // Another combat seed rolls differently. + var other = Build("Other dice"); + Kill(Spawn(other, at)); + Assert.True(Differ(dropsA, Released(other, 0))); + + // A second death in the same zone uses the next ordinal. + var count = first.Zone.FloatingItems.Count; + Kill(Spawn(first, at)); + Assert.True(Differ(dropsA, Released(first, count))); + } + + [Fact] + public void GearDropsByProbabilityCargoAlways() + { + foreach (var probability in new[] { 0f, 1f }) + { + var lab = Build(probability: probability); + var ship = Spawn(lab, float3(5, 0, 5)); + var gear = ship.Equipment.Where(e => e != ship.EquippedHull).Select(e => (ItemInstance) e.EquippableItem).ToList(); + var cargo = ship.CargoBays.Single().Cargo.Keys.ToList(); + Assert.Equal(3, gear.Count); + Assert.Equal(2, cargo.Count); + Kill(ship); + var dropped = lab.Zone.FloatingItems.Select(f => f.Item).ToList(); + Assert.All(cargo, c => Assert.Contains(c, dropped)); + Assert.DoesNotContain(ship.EquippedHull.EquippableItem, dropped); + if (probability == 0f) Assert.Equal(cargo.Count, dropped.Count); + else + { + Assert.Equal(cargo.Count + gear.Count, dropped.Count); + Assert.All(gear, g => Assert.Contains(g, dropped)); + } + } + + // 400 deaths at .5: the drop rate of the equipped gear is .5 within three sigma (sigma = .5 / sqrt(1200)). + var rate = Build(probability: .5f); + var equipped = 0; + for (var i = 0; i < 400; i++) + { + var ship = Spawn(rate, float3(i, 0, 0), cargo: false); + var gear = ship.Equipment.Where(e => e != ship.EquippedHull).Select(e => (ItemInstance) e.EquippableItem).ToList(); + var before = rate.Zone.FloatingItems.Count; + Kill(ship); + equipped += rate.Zone.FloatingItems.Skip(before).Count(f => gear.Contains(f.Item)); + } + Assert.InRange(equipped / (400f * 3f), .5f - 3 * .0144f, .5f + 3 * .0144f); + + // A station's death drops through the same path. + var hub = Build(probability: 1f); + Kill(Station(hub, float3(9, 0, 9))); + Assert.Equal(new[] { "Orex3", "Spare" }, hub.Zone.FloatingItems.Select(f => hub.Describe(f.Item)).OrderBy(x => x).ToArray()); + } + + // One unaimed shot with spread, and what the commit decided. + private static (ShotResult Result, int2 Cell, float Lateral, float2 Bearing) OneShot(Lab lab, Ship shooter) + { + ShotOutcome outcome = null; + using var c = lab.Zone.ShotCommitted.Subscribe(o => outcome = o); + var gun = shooter.Equipment.Single(e => lab.Items.GetData(e.EquippableItem).Name == "Gun"); + ((InstantWeapon) gun.Behaviors.Single(b => b is Weapon)).Activate(); + lab.Zone.Update(.01f); + Assert.NotNull(outcome); + return (outcome.Result, outcome.Cell, outcome.Lateral, outcome.Bearing); + } + + [Fact] + public void LootDiceDoNotTouchShotDice() + { + (ShotResult Result, int2 Cell, float Lateral, float2 Bearing) Run(bool death) + { + var lab = Build("Shots", spread: 5f); + var shooter = Spawn(lab, float3(37, 0, -11), cargo: false); + var target = Spawn(lab, float3(37, 0, 89), cargo: false); + var bystander = Spawn(lab, float3(900, 0, 900)); + shooter.SetTarget(target); + shooter.EntityInfoGathered[target] = 1f; + shooter.SetIff(target, true); + lab.Zone.Update(0f); + if (death) Kill(bystander); + return OneShot(lab, shooter); + } + var quiet = Run(false); + var after = Run(true); + Assert.NotEqual(0f, quiet.Lateral); + Assert.Equal(quiet, after); + } + + [Fact] + public void AFloatingItemDriftsAsABodyAndExpires() + { + var planets = new PlanetSettings { ZoneDepth = 1000, ZoneDepthExponent = 1, GravityStrength = 1 }; + var lab = Build(lifetime: 3f, planets: planets); + var settings = lab.Items.GameplaySettings; + var start = new float2(40, -25); + var launch = new float2(6, 2); + var item = lab.Ore(1); + var floating = lab.Zone.Release(item, start, launch); + Assert.Same(item, floating.Item); + Assert.Equal(lab.Zone.Time, floating.ReleasedAt); + Assert.Equal(3f, floating.Lifetime); + Assert.True(length(lab.Zone.GetForce(start)) > 0, "the fixture's zone must pull, or drift proves nothing"); + + var removals = 0; + using var sub = lab.Zone.FloatingItems.ObserveRemove().Subscribe(_ => removals++); + var alone = new KinematicBody { Position = start, Velocity = launch }; + var steps = 0; + while (lab.Zone.FloatingItems.Count > 0) + { + Assert.True(steps < 20, "the item must expire"); + alone.Step(.5f, lab.Zone.GetForce(alone.Position), settings); + lab.Zone.Update(.5f); + steps++; + if (lab.Zone.FloatingItems.Count > 0) + { + Assert.Equal(alone.Position, floating.Body.Position); + Assert.Equal(alone.Velocity, floating.Body.Velocity); + Assert.Equal(alone.Drift, floating.Body.Drift); + } + } + // Three seconds at half-second steps: it survives five steps and goes on the sixth, not before and not after. + Assert.Equal(6, steps); + Assert.Equal(1, removals); + } + + [Fact] + public void TryPickUpStoresAndRemoves() + { + var lab = Build(); + var taker = Spawn(lab, float3(0, 0, 0), bay: "Tiny", cargo: false); + var big = lab.Make("Crate"); + Assert.True(taker.TryFindSpace(big, out var pos)); + Assert.True(taker.TryEquip(big, pos)); + Assert.Equal(2, taker.CargoBays.Count); + + var removals = 0; + using var sub = lab.Zone.FloatingItems.ObserveRemove().Subscribe(_ => removals++); + var ore = lab.Ore(5); + var floating = lab.Zone.Release(ore, new float2(1, 2), new float2(3, 4)); + + // The one-cell bay is full, so the first bay that accepts the ore is the second. + Assert.True(taker.CargoBays[0].TryStore(lab.Make("Spare"))); + Assert.True(lab.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(1, removals); + Assert.Empty(lab.Zone.FloatingItems); + Assert.Contains(ore, taker.CargoBays[1].Cargo.Keys); + Assert.DoesNotContain(ore, taker.CargoBays[0].Cargo.Keys); + + // The same id again is unknown now. + Assert.False(lab.Zone.TryPickUp(taker, floating.Id)); + + // Every bay full: false, and the item floats on with its body unchanged. + while (taker.CargoBays[1].TryStore(lab.Make("Spare"))) { } + var stuck = lab.Zone.Release(lab.Make("Spare"), new float2(7, 8), new float2(1, 1)); + var body = stuck.Body; + Assert.False(lab.Zone.TryPickUp(taker, stuck.Id)); + Assert.Same(stuck, lab.Zone.FloatingItems.Single()); + Assert.Equal(body.Position, stuck.Body.Position); + Assert.Equal(body.Velocity, stuck.Body.Velocity); + Assert.Equal(1, removals); + + Assert.False(lab.Zone.TryPickUp(taker, new FloatingBodyId(9999))); + } + + [Fact] + public void DropsTakeFreshBodyIds() + { + var lab = Build(probability: 1f); + Kill(Spawn(lab, float3(0, 0, 0))); + var before = lab.Zone.FloatingItems.Select(f => f.Id.Value).ToList(); + var mine = new Mine { Id = lab.Zone.NextBodyId(), Body = new KinematicBody { Position = new float2(50, 50) }, Lifetime = 1000, FuseDelay = 1000, ArmingDelay = 1000 }; + lab.Zone.Lay(mine); + Kill(Spawn(lab, float3(0, 0, 0))); + var all = lab.Zone.FloatingItems.Select(f => f.Id.Value).ToList(); + var after = all.Skip(before.Count).ToList(); + Assert.NotEmpty(before); + Assert.NotEmpty(after); + Assert.Equal(Enumerable.Range(1, all.Count + 1).Select(i => (uint) i), before.Concat(new[] { mine.Id.Value }).Concat(after)); + } + + [Fact] + public void FloatingItemsAreNotSaved() + { + var lab = Build(probability: 1f); + Kill(Spawn(lab, float3(0, 0, 0))); + Assert.NotEmpty(lab.Zone.FloatingItems); + var pack = lab.Zone.PackZone(); + var restored = new Zone(lab.Items, new PlanetSettings(), pack, new GalaxyZone { Name = "Loot", Owner = null }, null); + Assert.Empty(restored.FloatingItems); + } +} From 5a72c6f5c8151a0808cb50d515d70ede61671a7c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 04:32:16 +0200 Subject: [PATCH 02/10] LootTests: the ledger holds lots for every minted ship (previous commit's tests failed on it) Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index ffdea32b9..f12994127 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -45,7 +45,7 @@ public sealed class LootTests : IDisposable { public ItemManager Items; public Zone Zone; - public int Lot = 4001; + public int Lot = 1; public EquippableItem Make(string name, float durability = 1) => new EquippableItem { @@ -108,7 +108,7 @@ public sealed class LootTests : IDisposable cache.FlushAsync().Wait(); var ledger = new ProvenanceLedger(); - for (var i = 1; i <= 4000; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 }; + 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, planets ?? new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = zoneName, Owner = null }, null); return new Lab { Items = items, Zone = zone }; From 7d2276a7088d329130939f9961f1897d168642bf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 04:37:38 +0200 Subject: [PATCH 03/10] LootTests: fixture fixes (zone radius for the well, six pieces of gear, a hitting shot, second bay by cell) Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index f12994127..510813007 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -110,7 +110,7 @@ public sealed class LootTests : 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, planets ?? new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = zoneName, Owner = null }, null); + var zone = new Zone(items, planets ?? new PlanetSettings(), new ZonePack { Radius = planets == null ? 0 : 1000 }, new GalaxyZone { Name = zoneName, Owner = null }, null); return new Lab { Items = items, Zone = zone }; } @@ -120,7 +120,7 @@ public sealed class LootTests : IDisposable var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Skiff")); var ship = new Ship(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, new EntitySettings()); Assert.True(ship.TryEquip(lab.Make("Gun"), new int2(0, 0))); - foreach (var name in new[] { "Targeting", "Spare" }) + foreach (var name in new[] { "Targeting", "Spare", "Spare", "Spare", "Spare" }) { var gear = lab.Make(name); Assert.True(ship.TryFindSpace(gear, out var pos)); @@ -216,7 +216,7 @@ public sealed class LootTests : IDisposable var ship = Spawn(lab, float3(5, 0, 5)); var gear = ship.Equipment.Where(e => e != ship.EquippedHull).Select(e => (ItemInstance) e.EquippableItem).ToList(); var cargo = ship.CargoBays.Single().Cargo.Keys.ToList(); - Assert.Equal(3, gear.Count); + Assert.Equal(6, gear.Count); Assert.Equal(2, cargo.Count); Kill(ship); var dropped = lab.Zone.FloatingItems.Select(f => f.Item).ToList(); @@ -230,7 +230,7 @@ public sealed class LootTests : IDisposable } } - // 400 deaths at .5: the drop rate of the equipped gear is .5 within three sigma (sigma = .5 / sqrt(1200)). + // 400 deaths at .5: the drop rate of the equipped gear is .5 within three sigma (sigma = .5 / sqrt(2400)). var rate = Build(probability: .5f); var equipped = 0; for (var i = 0; i < 400; i++) @@ -241,7 +241,7 @@ public sealed class LootTests : IDisposable Kill(ship); equipped += rate.Zone.FloatingItems.Skip(before).Count(f => gear.Contains(f.Item)); } - Assert.InRange(equipped / (400f * 3f), .5f - 3 * .0144f, .5f + 3 * .0144f); + Assert.InRange(equipped / (400f * 6f), .5f - 3 * .0102f, .5f + 3 * .0102f); // A station's death drops through the same path. var hub = Build(probability: 1f); @@ -266,7 +266,7 @@ public sealed class LootTests : IDisposable { (ShotResult Result, int2 Cell, float Lateral, float2 Bearing) Run(bool death) { - var lab = Build("Shots", spread: 5f); + var lab = Build("Shots"); var shooter = Spawn(lab, float3(37, 0, -11), cargo: false); var target = Spawn(lab, float3(37, 0, 89), cargo: false); var bystander = Spawn(lab, float3(900, 0, 900)); @@ -279,6 +279,7 @@ public sealed class LootTests : IDisposable } var quiet = Run(false); var after = Run(true); + Assert.Equal(ShotResult.Hit, quiet.Result); Assert.NotEqual(0f, quiet.Lateral); Assert.Equal(quiet, after); } @@ -326,8 +327,7 @@ public sealed class LootTests : IDisposable var lab = Build(); var taker = Spawn(lab, float3(0, 0, 0), bay: "Tiny", cargo: false); var big = lab.Make("Crate"); - Assert.True(taker.TryFindSpace(big, out var pos)); - Assert.True(taker.TryEquip(big, pos)); + Assert.Contains(Solid(5, 5).AllCoordinates, cell => taker.TryEquip(big, cell)); Assert.Equal(2, taker.CargoBays.Count); var removals = 0; From 43b8db6bcd3a4c29df998c107517d56b3e468c06 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 04:52:27 +0200 Subject: [PATCH 04/10] LootTests: the pickup test uses a two-bay station and a non-stacking item Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index 510813007..3c5ccd057 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -103,7 +103,6 @@ public sealed class LootTests : IDisposable MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000 }); cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Durability = 4 }); - cache.Upsert(new CargoBayData { Name = "Tiny", Shape = new Shape(), InteriorShape = Solid(1, 1), Durability = 4 }); cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = Solid(1, 1), MaxStack = 100 }); cache.FlushAsync().Wait(); @@ -115,7 +114,7 @@ public sealed class LootTests : IDisposable } // A ship carrying a gun, a targeting system and a spare, with ore and a spare gun in its crate. - private static Ship Spawn(Lab lab, float3 at, string bay = "Crate", bool cargo = true) + private static Ship Spawn(Lab lab, float3 at, bool cargo = true) { var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Skiff")); var ship = new Ship(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, new EntitySettings()); @@ -126,7 +125,7 @@ public sealed class LootTests : IDisposable Assert.True(ship.TryFindSpace(gear, out var pos)); Assert.True(ship.TryEquip(gear, pos)); } - var crate = lab.Make(bay); + var crate = lab.Make("Crate"); Assert.True(ship.TryFindSpace(crate, out var cratePos)); Assert.True(ship.TryEquip(crate, cratePos)); if (cargo) @@ -325,23 +324,21 @@ public sealed class LootTests : IDisposable public void TryPickUpStoresAndRemoves() { var lab = Build(); - var taker = Spawn(lab, float3(0, 0, 0), bay: "Tiny", cargo: false); - var big = lab.Make("Crate"); - Assert.Contains(Solid(5, 5).AllCoordinates, cell => taker.TryEquip(big, cell)); + var taker = Station(lab, float3(0, 0, 0)); + Assert.True(taker.TryEquip(lab.Make("Crate"), new int2(2, 2))); Assert.Equal(2, taker.CargoBays.Count); + // The first bay is full, so the first bay that accepts the item is the second. + while (taker.CargoBays[0].TryStore(lab.Make("Spare"))) { } var removals = 0; using var sub = lab.Zone.FloatingItems.ObserveRemove().Subscribe(_ => removals++); - var ore = lab.Ore(5); - var floating = lab.Zone.Release(ore, new float2(1, 2), new float2(3, 4)); - - // The one-cell bay is full, so the first bay that accepts the ore is the second. - Assert.True(taker.CargoBays[0].TryStore(lab.Make("Spare"))); + var item = lab.Make("Spare"); + var floating = lab.Zone.Release(item, new float2(1, 2), new float2(3, 4)); Assert.True(lab.Zone.TryPickUp(taker, floating.Id)); Assert.Equal(1, removals); Assert.Empty(lab.Zone.FloatingItems); - Assert.Contains(ore, taker.CargoBays[1].Cargo.Keys); - Assert.DoesNotContain(ore, taker.CargoBays[0].Cargo.Keys); + Assert.Contains(item, taker.CargoBays[1].Cargo.Keys); + Assert.DoesNotContain(item, taker.CargoBays[0].Cargo.Keys); // The same id again is unknown now. Assert.False(lab.Zone.TryPickUp(taker, floating.Id)); From c34f72e3d55ae14484add3fe446829c3c0924b17 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 04:55:37 +0200 Subject: [PATCH 05/10] LootTests: the station's bay goes in first, as the StationServices fixture does Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index 3c5ccd057..5d5d63c09 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -143,12 +143,10 @@ public sealed class LootTests : IDisposable { var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Hub")); var station = new OrbitalEntity(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, default, new EntitySettings()); + Assert.True(station.TryEquip(lab.Make("Crate"), new int2(1, 1))); var spare = lab.Make("Spare"); Assert.True(station.TryFindSpace(spare, out var pos)); Assert.True(station.TryEquip(spare, pos)); - var crate = lab.Make("Crate"); - Assert.True(station.TryFindSpace(crate, out var cratePos)); - Assert.True(station.TryEquip(crate, cratePos)); Assert.True(station.CargoBays.Single().TryStore(lab.Ore(3))); lab.Zone.Entities.Add(station); station.Activate(); @@ -325,7 +323,7 @@ public sealed class LootTests : IDisposable { var lab = Build(); var taker = Station(lab, float3(0, 0, 0)); - Assert.True(taker.TryEquip(lab.Make("Crate"), new int2(2, 2))); + Assert.Contains(Solid(5, 5).AllCoordinates, cell => taker.TryEquip(lab.Make("Crate"), cell)); Assert.Equal(2, taker.CargoBays.Count); // The first bay is full, so the first bay that accepts the item is the second. while (taker.CargoBays[0].TryStore(lab.Make("Spare"))) { } From ca19deab682249abe3c459b1a33ebaba36e3c2e1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 05:33:27 +0200 Subject: [PATCH 06/10] LootTests: the pickup taker is an unstocked two-bay station, as the StationServices fixture builds one Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index 5d5d63c09..62763403f 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -139,15 +139,18 @@ public sealed class LootTests : IDisposable return ship; } - private static Entity Station(Lab lab, float3 at) + private static Entity Station(Lab lab, float3 at, bool stocked = true) { var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Hub")); var station = new OrbitalEntity(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, default, new EntitySettings()); Assert.True(station.TryEquip(lab.Make("Crate"), new int2(1, 1))); - var spare = lab.Make("Spare"); - Assert.True(station.TryFindSpace(spare, out var pos)); - Assert.True(station.TryEquip(spare, pos)); - Assert.True(station.CargoBays.Single().TryStore(lab.Ore(3))); + if (stocked) + { + var spare = lab.Make("Spare"); + Assert.True(station.TryFindSpace(spare, out var pos)); + Assert.True(station.TryEquip(spare, pos)); + Assert.True(station.CargoBays.Single().TryStore(lab.Ore(3))); + } lab.Zone.Entities.Add(station); station.Activate(); station.Position = at; @@ -322,8 +325,8 @@ public sealed class LootTests : IDisposable public void TryPickUpStoresAndRemoves() { var lab = Build(); - var taker = Station(lab, float3(0, 0, 0)); - Assert.Contains(Solid(5, 5).AllCoordinates, cell => taker.TryEquip(lab.Make("Crate"), cell)); + var taker = Station(lab, float3(0, 0, 0), stocked: false); + Assert.True(taker.TryEquip(lab.Make("Crate"), new int2(2, 2))); Assert.Equal(2, taker.CargoBays.Count); // The first bay is full, so the first bay that accepts the item is the second. while (taker.CargoBays[0].TryStore(lab.Make("Spare"))) { } From 6130eb7d04dfe97d14dad258794467821d57ba42 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 19:30:30 +0200 Subject: [PATCH 07/10] LootTests: a station is active once built, so the pickup taker's second bay is equipped before Activate Station() activates the entity and TryEquip refuses while active; the second Crate at (2,2) failed for that reason, not a hull rule. Builds. Co-Authored-By: Claude Opus 5.5 --- tests/Aetheria.Shared.Tests/LootTests.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index 62763403f..02998bca7 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -139,11 +139,13 @@ public sealed class LootTests : IDisposable return ship; } - private static Entity Station(Lab lab, float3 at, bool stocked = true) + private static Entity Station(Lab lab, float3 at, bool stocked = true, bool secondBay = false) { var hull = lab.Items.ItemData.RefOf(lab.Items.ItemData.GetByName("Hub")); var station = new OrbitalEntity(lab.Items, lab.Zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, default, new EntitySettings()); Assert.True(station.TryEquip(lab.Make("Crate"), new int2(1, 1))); + // Equipping is refused once a station is active, so a second bay goes in before Activate. + if (secondBay) Assert.True(station.TryEquip(lab.Make("Crate"), new int2(2, 2))); if (stocked) { var spare = lab.Make("Spare"); @@ -325,8 +327,7 @@ public sealed class LootTests : IDisposable public void TryPickUpStoresAndRemoves() { var lab = Build(); - var taker = Station(lab, float3(0, 0, 0), stocked: false); - Assert.True(taker.TryEquip(lab.Make("Crate"), new int2(2, 2))); + var taker = Station(lab, float3(0, 0, 0), stocked: false, secondBay: true); Assert.Equal(2, taker.CargoBays.Count); // The first bay is full, so the first bay that accepts the item is the second. while (taker.CargoBays[0].TryStore(lab.Make("Spare"))) { } From cc9403ce5840e90063538603d8a349d760f91380 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 20:51:45 +0200 Subject: [PATCH 08/10] Loot-1 fix batch: whole-or-nothing commodity store, and tests for the Soul s1/s2 findings EquippedCargoBay.TryStore(SimpleCommodity) now returns false before touching anything when TryFindSpace says the whole quantity does not fit (its documented contract: true only when ALL is stored), so Zone.TryPickUp keeps "first accepting bay, otherwise nothing changes" with no rollback in Zone. Tests: refused pickup of a stackable item changes nothing; a stack plus free cell stores whole; first accepting bay; headings cover the circle; the loot stream is not the mine stream; dock/undock and jump drop once and only in the zone the ship is in. Untested on this commit: not yet built (verify job follows). Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/Entity.cs | 2 +- tests/Aetheria.Shared.Tests/LootTests.cs | 124 +++++++++++++++++++++++ tests/Aetheria.Shared.Tests/MineTests.cs | 34 +++++++ 3 files changed, 159 insertions(+), 1 deletion(-) diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index f38053ef5..2716cb7c3 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -2376,7 +2376,7 @@ public class EquippedCargoBay : EquippedItem // Returns true only when ALL of the items are successfully stored public bool TryStore(SimpleCommodity item) { - TryFindSpace(item, out var positions); + if (!TryFindSpace(item, out var positions)) return false; foreach (var position in positions) { if (TryStore(item, position)) return true; diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index 02998bca7..c8a07a74d 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -384,4 +384,128 @@ public sealed class LootTests : IDisposable var restored = new Zone(lab.Items, new PlanetSettings(), pack, new GalaxyZone { Name = "Loot", Owner = null }, null); Assert.Empty(restored.FloatingItems); } + + // The death watch lives as long as the entity is a member of the zone (aetheria-release loot-1, Soul s1): an + // entity that docks and undocks, or jumps, never holds a second one and never drops in a zone it has left. + [Fact] + public void ADockedAndUndockedShipDropsEachItemOnce() + { + var lab = Build(probability: 1f); + var ship = Spawn(lab, float3(3, 0, 4)); + // What Entity.TryDock then Entity.TryUndock do to the zone: Entities.Remove + Deactivate, then Zone.Admit. + lab.Zone.Entities.Remove(ship); + ship.Deactivate(); + lab.Zone.Admit(ship, piloted: false); + lab.Zone.Entities.Remove(ship); + lab.Zone.Admit(ship, piloted: false); + Kill(ship); + var dropped = lab.Zone.FloatingItems.Select(f => f.Item).ToList(); + Assert.NotEmpty(dropped); + Assert.Equal(dropped.Count, dropped.Distinct().Count()); + } + + [Fact] + public void AShipThatJumpedDropsNothingInTheZoneItLeft() + { + var lab = Build("JumpA", probability: 1f); + var other = new Zone(lab.Items, new PlanetSettings(), new ZonePack { Radius = 0 }, new GalaxyZone { Name = "JumpB", Owner = null }, null); + var ship = Spawn(lab, float3(3, 0, 4)); + // What ActionGameManager does on a jump. + ship.Deactivate(); + lab.Zone.Entities.Remove(ship); + ship.Zone = other; + other.Admit(ship, piloted: false); + Kill(ship); + Assert.NotEmpty(other.FloatingItems); + Assert.Empty(lab.Zone.FloatingItems); + } + + [Fact] + public void ADeathDropsOnceAndTheRemovedShipDropsNoMore() + { + var lab = Build(probability: 1f); + var ship = Spawn(lab, float3(3, 0, 4)); + Kill(ship); + var count = lab.Zone.FloatingItems.Count; + Assert.NotEmpty(lab.Zone.FloatingItems); + Assert.DoesNotContain(ship, lab.Zone.Entities); + // A second death signal from the removed entity reaches no subscription. + Kill(ship); + Assert.Equal(count, lab.Zone.FloatingItems.Count); + } + + // TryPickUp commits whole or changes nothing: a stackable item the bays can only partly take stays whole. + [Fact] + public void ARefusedPickUpOfAStackableItemChangesNothing() + { + var lab = Build(); + var taker = Station(lab, float3(0, 0, 0), stocked: false); + var bay = taker.CargoBays.Single(); + Assert.True(bay.TryStore(lab.Ore(95))); + while (bay.TryStore(lab.Make("Spare"))) { } + var stack = bay.Cargo.Keys.OfType().Single(); + var ore = lab.Ore(30); + var floating = lab.Zone.Release(ore, new float2(1, 2), float2.zero); + var mass = taker.Mass; + for (var attempt = 0; attempt < 3; attempt++) + { + Assert.False(lab.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(30, ore.Quantity); + Assert.Equal(95, stack.Quantity); + Assert.Equal(mass, taker.Mass); + Assert.Same(floating, lab.Zone.FloatingItems.Single()); + } + } + + [Fact] + public void AStackableItemSplitAcrossAStackAndAFreeCellIsStoredWhole() + { + var lab = Build(); + var taker = Station(lab, float3(0, 0, 0), stocked: false); + var bay = taker.CargoBays.Single(); + Assert.True(bay.TryStore(lab.Ore(95))); + var floating = lab.Zone.Release(lab.Ore(30), new float2(1, 2), float2.zero); + Assert.True(lab.Zone.TryPickUp(taker, floating.Id)); + Assert.Empty(lab.Zone.FloatingItems); + Assert.Equal(125, bay.Cargo.Keys.OfType().Sum(c => c.Quantity)); + } + + [Fact] + public void PickUpFillsTheFirstAcceptingBay() + { + var lab = Build(); + var taker = Station(lab, float3(0, 0, 0), stocked: false, secondBay: true); + var item = lab.Make("Spare"); + var floating = lab.Zone.Release(item, new float2(1, 2), float2.zero); + Assert.True(lab.Zone.TryPickUp(taker, floating.Id)); + Assert.Contains(item, taker.CargoBays[0].Cargo.Keys); + Assert.DoesNotContain(item, taker.CargoBays[1].Cargo.Keys); + } + + [Fact] + public void DropHeadingsCoverTheWholeCircle() + { + var lab = Build(probability: 1f); + var velocities = new List(); + for (var i = 0; i < 40; i++) + { + var before = lab.Zone.FloatingItems.Count; + Kill(Spawn(lab, float3(i, 0, 0), cargo: false)); + velocities.AddRange(lab.Zone.FloatingItems.Skip(before).Select(f => f.Body.Velocity)); + } + Assert.Contains(velocities, v => v.x > 10); + Assert.Contains(velocities, v => v.x < -10); + Assert.Contains(velocities, v => v.y > 10); + Assert.Contains(velocities, v => v.y < -10); + Assert.True(Math.Abs(velocities.Sum(v => v.x) / velocities.Count) < 8 && Math.Abs(velocities.Sum(v => v.y) / velocities.Count) < 8, + "headings are not centred on the origin"); + } + + [Fact] + public void OneDeathsDropsLeaveOnDistinctHeadings() + { + var lab = Build(probability: 1f); + Kill(Spawn(lab, float3(1, 0, 1))); + Assert.True(lab.Zone.FloatingItems.Select(f => Math.Round(Math.Atan2(f.Body.Velocity.y, f.Body.Velocity.x), 3)).Distinct().Count() > 1); + } } diff --git a/tests/Aetheria.Shared.Tests/MineTests.cs b/tests/Aetheria.Shared.Tests/MineTests.cs index 1323f8541..f132de9d2 100644 --- a/tests/Aetheria.Shared.Tests/MineTests.cs +++ b/tests/Aetheria.Shared.Tests/MineTests.cs @@ -742,4 +742,38 @@ public sealed class MineTests : IDisposable Assert.False(string.IsNullOrWhiteSpace(log[0])); Assert.Empty(lab.Zone.PendingShots); } + + // Loot is drawn on its own stream (aetheria-release loot-1): a mine laid with body id 1 and the zone's first + // death share ordinal 1, so only the stream tells their draws apart. The lay's first draw fixes the mine's + // turn; setting LootDropProbability just either side of that same number decides the first gate draw of the + // first death. With one stream the gate would follow the mine's turn. + private (Lab Lab, float U) LayThenReadTurn(float? probability) + { + var lab = Build(spread: 40f, velocity: 5f, layerFaction: A); + lab.Layer.Velocity = float2.zero; + lab.Layer.Direction = normalize(float2(1, 2)); + var mine = LayOne(lab); + var mount = FireControl.MountDirection(lab.WeaponItem).xz; + var turned = mine.Body.Velocity / 5f; + var degrees = (MathF.Atan2(turned.y, turned.x) - MathF.Atan2(mount.y, mount.x)) * 180f / MathF.PI; + if (probability.HasValue) lab.Items.GameplaySettings.LootDropProbability = probability.Value; + return (lab, (degrees + 20f) / 40f); + } + + private static bool FirstGearDropped(Lab lab) + { + var gear = lab.Layer.Equipment.First(e => e != lab.Layer.EquippedHull).EquippableItem; + lab.Layer.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + return lab.Zone.FloatingItems.Any(f => f.Item == gear); + } + + [Fact] + public void LootDiceAreNotTheMineDice() + { + var u = LayThenReadTurn(null).U; + Assert.InRange(u, .01f, .99f); + var above = FirstGearDropped(LayThenReadTurn(u + .003f).Lab); + var below = FirstGearDropped(LayThenReadTurn(u - .003f).Lab); + Assert.False(above && !below, "the first loot gate draw equals the first mine draw"); + } } From 82d4881ca251f2f1a7c9885aad01e4050692a1f3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 12 Oct 2026 20:53:15 +0200 Subject: [PATCH 09/10] Zone: the death watch is added, not overwritten, so a second one for a member cannot exist Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/Zone.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index c6956e7b3..3930977dc 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -111,8 +111,7 @@ public class Zone private void WatchDeath(Entity entity) { - UnwatchDeath(entity); - _deathWatches[entity] = entity.Death.Subscribe(_ => { DropLoot(entity); Entities.Remove(entity); entity.Deactivate(); }); + _deathWatches.Add(entity, entity.Death.Subscribe(_ => { DropLoot(entity); Entities.Remove(entity); entity.Deactivate(); })); } private void UnwatchDeath(Entity entity) From f2bf0c0410683177a7824d323d28e13f26425034 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 13 Oct 2026 00:43:12 +0200 Subject: [PATCH 10/10] Zone: a death watch exists only for a non-member and is disposed by Remove and Clear; tests for duplicate Add, Clear and the pickup room boundary WatchDeath returns when the entity already holds a watch, so a duplicate Entities.Add neither throws nor leaves a second live subscription; Entities.Clear (ObserveReset) disposes every watch. Adds AMemberAddedTwiceStillDropsEachItemOnce, AClearedZoneDropsNothingWhenAFormerMemberDies (finding duplicate-add-leaks-second-watch) and APickUpOfExactlyTheRoomLeftFitsAndOneMoreChangesNothing (finding pickup-room-arithmetic-unpinned, from Soul's boundary probe). Unverified until the Yggdrasil job; no commit here is known not to build. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/ServerShared/Zone.cs | 13 +++++- tests/Aetheria.Shared.Tests/LootTests.cs | 54 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index 3930977dc..5b4a5ccc9 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -105,12 +105,14 @@ public class Zone // The death ordinal of the loot dice: the nth death in this zone rolls on SimulationDice.For(CombatSeed, LootStream, n). private uint _deaths; - // One death subscription per member entity, owned here: WatchDeath installs it, UnwatchDeath (the entity leaving - // Entities) disposes it, and nothing else touches it. + // One death subscription per member entity, owned here: a membership record and its subscription are created + // together, and only when the entity is not already a member. Leaving Entities (Remove) or resetting it (Clear) + // disposes it; nothing else touches it. private readonly Dictionary _deathWatches = new Dictionary(); private void WatchDeath(Entity entity) { + if (_deathWatches.ContainsKey(entity)) return; _deathWatches.Add(entity, entity.Death.Subscribe(_ => { DropLoot(entity); Entities.Remove(entity); entity.Deactivate(); })); } @@ -119,6 +121,12 @@ public class Zone if (_deathWatches.Remove(entity, out var watch)) watch.Dispose(); } + private void UnwatchAll() + { + foreach (var watch in _deathWatches.Values) watch.Dispose(); + _deathWatches.Clear(); + } + public Zone(ItemManager itemManager, PlanetSettings settings, ZonePack pack, GalaxyZone galaxyZone, Galaxy galaxy) { _time = pack.Time; @@ -138,6 +146,7 @@ public class Zone // disposed on removal (death, dock, jump), so an entity admitted again never holds a second one. Entities.ObserveAdd().Subscribe(add => WatchDeath(add.Value)); Entities.ObserveRemove().Subscribe(remove => UnwatchDeath(remove.Value)); + Entities.ObserveReset().Subscribe(_ => UnwatchAll()); // The one record of a removal for observers (ruling reveal-ends-on-perception): read by the next Sense pass. Entities.ObserveRemove().Subscribe(remove => _departures.Add(new Departure(remove.Value, remove.Value.Position.xz, remove.Value.Visibility - remove.Value.SignatureOn(SignatureChannel.Emission)))); diff --git a/tests/Aetheria.Shared.Tests/LootTests.cs b/tests/Aetheria.Shared.Tests/LootTests.cs index c8a07a74d..ab2c19511 100644 --- a/tests/Aetheria.Shared.Tests/LootTests.cs +++ b/tests/Aetheria.Shared.Tests/LootTests.cs @@ -508,4 +508,58 @@ public sealed class LootTests : IDisposable Kill(Spawn(lab, float3(1, 0, 1))); Assert.True(lab.Zone.FloatingItems.Select(f => Math.Round(Math.Atan2(f.Body.Velocity.y, f.Body.Velocity.x), 3)).Distinct().Count() > 1); } + + // A member added twice holds one death subscription, so it drops each item once, as a single death would. + [Fact] + public void AMemberAddedTwiceStillDropsEachItemOnce() + { + var once = Build("Once", probability: 1f); + Kill(Spawn(once, float3(3, 0, 4))); + var baseline = once.Zone.FloatingItems.Count; + Assert.NotEqual(0, baseline); + + var lab = Build("Twice", probability: 1f); + var ship = Spawn(lab, float3(3, 0, 4)); + lab.Zone.Entities.Add(ship); + Kill(ship); + Assert.Equal(baseline, lab.Zone.FloatingItems.Count); + } + + // Clearing Entities removes every member, so a death afterwards drops nothing in this zone. + [Fact] + public void AClearedZoneDropsNothingWhenAFormerMemberDies() + { + var lab = Build("Cleared", probability: 1f); + var ship = Spawn(lab, float3(3, 0, 4)); + lab.Zone.Entities.Clear(); + Kill(ship); + Assert.Empty(lab.Zone.FloatingItems); + } + + // The pickup is whole or nothing at the arithmetic boundary: two stacks of 90 hold 20 more in all and no free + // cell is left, so a stack of 20 is stored (quantity 200 across both) and a stack of 21 changes nothing. + [Fact] + public void APickUpOfExactlyTheRoomLeftFitsAndOneMoreChangesNothing() + { + var lab = Build(); + var taker = Station(lab, float3(0, 0, 0), stocked: false); + var bay = taker.CargoBays[0]; + Assert.True(bay.TryStore(lab.Ore(90), new int2(0, 0))); + Assert.True(bay.TryStore(lab.Ore(90), new int2(1, 0))); + while (bay.TryStore(lab.Make("Spare"))) { } + (int Quantity, int Cells) Held() => (bay.Cargo.Keys.OfType().Sum(c => c.Quantity), bay.Cargo.Count); + var before = Held(); + + var over = lab.Ore(21); + var overFloating = lab.Zone.Release(over, new float2(1, 1), float2.zero); + Assert.False(lab.Zone.TryPickUp(taker, overFloating.Id)); + Assert.Equal(21, over.Quantity); + Assert.Equal(before, Held()); + Assert.Contains(overFloating, lab.Zone.FloatingItems); + + var exact = lab.Zone.Release(lab.Ore(20), new float2(1, 1), float2.zero); + Assert.True(lab.Zone.TryPickUp(taker, exact.Id)); + Assert.Equal((200, before.Cells), Held()); + Assert.DoesNotContain(exact, lab.Zone.FloatingItems); + } }