Merge origin/master into eureka/aetheria-release-thrust-allocator-core
This commit is contained in:
commit
08d064c8dc
191 changed files with 10512 additions and 90 deletions
|
|
@ -11,6 +11,8 @@
|
|||
<!-- AuthoredSettings (Unity Settings.asset YAML reader), so fixtures load the shipped gameplay settings
|
||||
instead of hand-copying them. -->
|
||||
<ProjectReference Include="..\..\tools\AetherDb\AetherDb.csproj" />
|
||||
<!-- The player build's staging rules: Unity-free, owned by Assets/Editor, compiled here so the suite can prove them. -->
|
||||
<Compile Include="..\..\Assets\Editor\PlayerStaging.cs" Link="PlayerStaging.cs" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
|
||||
|
|
|
|||
|
|
@ -116,7 +116,10 @@ public sealed class AetheriaStoresTests : IDisposable
|
|||
public void MissingCatalogGlobalIsLoud()
|
||||
{
|
||||
var empty = Path.Combine(_root, "empty.cc");
|
||||
using (AetheriaStores.Open(empty, catalogWritable: true)) { }
|
||||
// A catalog file that exists but lacks the global: the read-only open reaches the global check.
|
||||
File.Copy(Catalog, empty);
|
||||
using (var seed = AetheriaStores.Open(empty, catalogWritable: true))
|
||||
Assert.True(seed.Commit(batch => batch.Remove(seed.RefOf(seed.GetGlobal<TestCatalogGlobal>()).Key)));
|
||||
var error = Assert.Throws<InvalidOperationException>(() => AetheriaStores.Open(empty));
|
||||
Assert.Contains("aetheria.tests.catalogglobal", error.Message);
|
||||
using (AetheriaStores.Open(Catalog)) { }
|
||||
|
|
@ -200,6 +203,23 @@ public sealed class AetheriaStoresTests : IDisposable
|
|||
Assert.Null(record);
|
||||
}
|
||||
|
||||
// A shipped player with no catalog must not boot into an empty game: a read-only open of a missing path throws
|
||||
// naming the path, and does not create the file. A writable open still seeds an empty catalog.
|
||||
[Fact]
|
||||
public void AStoreRefusesAMissingCatalog()
|
||||
{
|
||||
var missing = Path.Combine(_root, "absent", "Aetheria.cc");
|
||||
|
||||
// FileNotFoundException, not the catalog-global check: that one also throws on a missing file whenever a global is registered.
|
||||
var error = Assert.Throws<FileNotFoundException>(() => AetheriaStores.Open(missing));
|
||||
Assert.Contains(missing, error.Message);
|
||||
Assert.False(File.Exists(missing));
|
||||
Assert.False(Directory.Exists(Path.GetDirectoryName(missing)));
|
||||
|
||||
using (var seeded = AetheriaStores.Open(missing, catalogWritable: true))
|
||||
Assert.Empty(seeded.GetAll<Faction>());
|
||||
}
|
||||
|
||||
private static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)));
|
||||
|
||||
private static string[] SchemaNames(string path)
|
||||
|
|
|
|||
534
tests/Aetheria.Shared.Tests/BallisticFlightTests.cs
Normal file
534
tests/Aetheria.Shared.Tests/BallisticFlightTests.cs
Normal file
|
|
@ -0,0 +1,534 @@
|
|||
/* 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.Linq;
|
||||
using System.Reflection;
|
||||
using UniRx;
|
||||
using Xunit;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
using float3 = CultMath.float3;
|
||||
using int2 = CultMath.int2;
|
||||
|
||||
// Ballistic flight: a round's flight is presentation (ruling projectile-flight-is-presentation). The simulation publishes
|
||||
// the facts (the PendingShot's frozen origin, direction, speed, fire time and arrival, the outcome with its commit tick,
|
||||
// impact cell and burst point) and DrawAhead's statics draw the round from them: Round the one statement of where a round
|
||||
// is at a sim time, Impact where a hit lands on the target's drawn pose, RoundEnd and RoundOver when its drawn flight
|
||||
// ends. FireControl owns none of it (ruling direct-arrival-keep-timing: damage keeps landing at the arrival time, the
|
||||
// hit is drawn at its cell). Unity's Projectile calls Round and integrates nothing, so these tests pin the drawing
|
||||
// against first principles (the shooter's position, the aim, the authored velocity and range, the hull's own frame)
|
||||
// rather than against the code that computes it. Shares the Cut 12.4 engagement fixture.
|
||||
public sealed partial class FireControlCut124Tests
|
||||
{
|
||||
private const float BallisticSpeed = 20f;
|
||||
|
||||
// A no-lock proximity round: flies the aim line (2,1) to max range, bursting there.
|
||||
private Engagement FireBurstRound(out float3 origin)
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, fuse: WeaponFuse.Proximity, blastRadius: 4f,
|
||||
damage: 100f, weaponRange: NoLockRange);
|
||||
Aim(e, float2(2, 1));
|
||||
e.Shooter.SetTarget(TargetRef.None);
|
||||
origin = e.Shooter.Position;
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
return e;
|
||||
}
|
||||
|
||||
// What the sim publishes for a shot, as a presenter holds it: only the result (no impact, no burst point).
|
||||
private static ShotOutcome Known(in PendingShot shot, ShotResult result) =>
|
||||
new ShotOutcome { ShotId = shot.ShotId, Result = result, ArrivalIn = max(0f, shot.ArrivalTime - shot.CommitTime) };
|
||||
|
||||
// A hit on a cell of the target, committed at `commit`: ArrivalIn is how long after the commit damage lands.
|
||||
private static ShotOutcome Hit(in PendingShot shot, Entity target, int2 cell, float commit) =>
|
||||
new ShotOutcome { ShotId = shot.ShotId, Result = ShotResult.Hit, Target = target, Cell = cell, ArrivalIn = shot.ArrivalTime - commit };
|
||||
|
||||
// The hull's occupied coordinate farthest from its centre of mass: a cell well off the target's position.
|
||||
private static int2 FarCell(Engagement e) =>
|
||||
e.HullData.Shape.Coordinates.OrderByDescending(c => length((float2) c - e.HullData.Shape.CenterOfMass)).First();
|
||||
|
||||
[Fact]
|
||||
public void ARoundIsDrawnOnItsFiredLine()
|
||||
{
|
||||
// Burst round: leaves the shooter, is where its own speed puts it a second in, and ends on the burst point.
|
||||
var e = FireBurstRound(out var origin);
|
||||
ShotOutcome outcome = null;
|
||||
PendingShot burst = default;
|
||||
using var c = e.Zone.ShotCommitted.Subscribe(o =>
|
||||
{
|
||||
outcome = o;
|
||||
e.Zone.TryGetShot(o.ShotId, out burst);
|
||||
});
|
||||
e.Zone.Update(.01f);
|
||||
Assert.NotNull(outcome);
|
||||
Assert.True(outcome.HasBurstPoint);
|
||||
var aim = normalize(float2(2, 1));
|
||||
// The shooter moves on after the round left: the line is the one frozen at Fire, not one drawn from where it is now.
|
||||
e.Shooter.Position += float3(7, 0, 3);
|
||||
|
||||
var start = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime, 0f);
|
||||
Assert.Equal(origin.x, start.x, 3);
|
||||
Assert.Equal(origin.z, start.z, 3);
|
||||
|
||||
var second = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime + 1f, 0f);
|
||||
Assert.Equal(origin.x + aim.x * BallisticSpeed, second.x, 3);
|
||||
Assert.Equal(origin.z + aim.y * BallisticSpeed, second.z, 3);
|
||||
|
||||
foreach (var known in new[] { null, outcome })
|
||||
foreach (var later in new[] { 0f, 1f, 50f })
|
||||
{
|
||||
var arrival = DrawAhead.Round(burst, known, burst.FireOrigin, 0f, burst.ArrivalTime + later, 0f);
|
||||
Assert.Equal(burst.BurstPosition.x, arrival.x, 3);
|
||||
Assert.Equal(burst.BurstPosition.z, arrival.z, 3);
|
||||
}
|
||||
|
||||
// Past the weapon's range it is held at the range point, however late it is asked.
|
||||
var held = DrawAhead.Round(burst, Known(burst, ShotResult.Miss), burst.FireOrigin, 0f, burst.FireTime + NoLockRange / BallisticSpeed + 50f, 0f);
|
||||
Assert.Equal(origin.x + aim.x * NoLockRange, held.x, 3);
|
||||
Assert.Equal(origin.z + aim.y * NoLockRange, held.z, 3);
|
||||
// Before it was fired it is still at the origin, not behind it.
|
||||
var before = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime - 5f, 0f);
|
||||
Assert.Equal(origin.x, before.x, 3);
|
||||
Assert.Equal(origin.z, before.z, 3);
|
||||
|
||||
// Direct round at a stationary target 100 ahead (+z): arrives on the target, and a miss would fly on to the weapon's range.
|
||||
var d = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, weaponRange: 1000f);
|
||||
var dOrigin = d.Shooter.Position;
|
||||
FireControl.Fire(d.Weapon, d.WeaponItem, d.Shooter);
|
||||
var direct = SafeAssert.OnlyShot(d.Zone);
|
||||
// A round not known to miss waits at its arrival point however late it is asked.
|
||||
foreach (var at in new[] { direct.ArrivalTime, direct.FireTime + 99f })
|
||||
{
|
||||
var waiting = DrawAhead.Round(direct, null, direct.FireOrigin, 0f, at, 0f);
|
||||
Assert.Equal(d.Target.Position.x, waiting.x, 2);
|
||||
Assert.Equal(d.Target.Position.z, waiting.z, 2);
|
||||
}
|
||||
Assert.Equal(dOrigin.z + 100f / 2f, DrawAhead.Round(direct, null, direct.FireOrigin, 0f, direct.FireTime + 2.5f, 0f).z, 2);
|
||||
var heldDirect = DrawAhead.Round(direct, Known(direct, ShotResult.Miss), direct.FireOrigin, 0f, direct.FireTime + 1000f / BallisticSpeed + 99f, 0f);
|
||||
Assert.Equal(dOrigin.z + 1000f, heldDirect.z, 2);
|
||||
}
|
||||
|
||||
// A round with no speed (the weapon authors Velocity 0, or effectively 0) does not fly: it is at its origin at any
|
||||
// time, and is not stretched along its line by a vanishing speed over the range it would need forever to cover.
|
||||
[Fact]
|
||||
public void ARoundWithNoSpeedStaysAtItsOrigin()
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: .005f, weaponRange: 1000f);
|
||||
var origin = e.Shooter.Position;
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
|
||||
var late = DrawAhead.Round(shot, Known(shot, ShotResult.Miss), shot.FireOrigin, 0f, shot.FireTime + 5000f, 0f);
|
||||
Assert.Equal(origin.x, late.x, 3);
|
||||
Assert.Equal(origin.z, late.z, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SpeedIsFrozenAtFire()
|
||||
{
|
||||
var e = FireBurstRound(out var origin);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.Equal(BallisticSpeed, shot.Speed, 4);
|
||||
|
||||
// The stat changes after the round left, and the weapon re-reads it.
|
||||
((InstantWeaponData) e.Weapon.WeaponData).Velocity = Constant(BallisticSpeed * 5f);
|
||||
e.Weapon.Execute(0f);
|
||||
Assert.Equal(BallisticSpeed * 5f, e.Weapon.Velocity, 4);
|
||||
|
||||
var after = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.Equal(BallisticSpeed, after.Speed, 4);
|
||||
var aim = normalize(float2(2, 1));
|
||||
var at = DrawAhead.Round(after, null, after.FireOrigin, 0f, after.FireTime + 1f, 0f);
|
||||
Assert.Equal(origin.x + aim.x * BallisticSpeed, at.x, 3);
|
||||
Assert.Equal(origin.z + aim.y * BallisticSpeed, at.z, 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ARoundIsPure()
|
||||
{
|
||||
var e = FireDirectRound(20f, 1000f);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
e.Target.Direction = normalize(float2(1, 2));
|
||||
e.Target.TurnRate = 3f;
|
||||
var time = e.Zone.Time;
|
||||
var entities = e.Zone.Entities.ToList();
|
||||
var positions = entities.Select(x => x.Position).ToList();
|
||||
var velocities = entities.Select(x => x.Velocity).ToList();
|
||||
var directions = entities.Select(x => x.Direction).ToList();
|
||||
var turnRates = entities.Select(x => x.TurnRate).ToList();
|
||||
|
||||
var barrel = shot.FireOrigin + float3(1, .5f, -2);
|
||||
var cell = FarCell(e);
|
||||
foreach (var known in new[] { null, Known(shot, ShotResult.Miss), Hit(shot, e.Target, cell, shot.CommitTime) })
|
||||
for (var i = 0; i < 25; i++)
|
||||
{
|
||||
var at = shot.FireTime + i * .37f;
|
||||
DrawAhead.Round(shot, known, barrel, .1f, at, .01f);
|
||||
DrawAhead.RoundOver(shot, known, at, .01f);
|
||||
DrawAhead.RoundEnd(shot, known?.Result);
|
||||
DrawAhead.Impact(e.Target, cell, .01f * i);
|
||||
}
|
||||
|
||||
Assert.Equal(time, e.Zone.Time);
|
||||
Assert.True(e.Zone.PendingShots.Count == 1 && e.Zone.PendingShots[0].Equals(shot), "the pending shot changed");
|
||||
Assert.True(e.Zone.Entities.SequenceEqual(entities), "the zone's entities changed");
|
||||
Assert.True(entities.Select(x => x.Position).SequenceEqual(positions), "an entity moved");
|
||||
Assert.True(entities.Select(x => x.Velocity).SequenceEqual(velocities), "an entity's velocity changed");
|
||||
Assert.True(entities.Select(x => x.Direction).SequenceEqual(directions), "an entity turned");
|
||||
Assert.True(entities.Select(x => x.TurnRate).SequenceEqual(turnRates), "an entity's turn rate changed");
|
||||
}
|
||||
|
||||
// The weapon's Range is frozen with the rest: a round that misses flies on to the range it left with, whatever the stat
|
||||
// becomes after.
|
||||
[Fact]
|
||||
public void RangeIsFrozenAtFire()
|
||||
{
|
||||
var e = FireBurstRound(out var origin);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.Equal(NoLockRange, shot.MaxRange, 4);
|
||||
var endBefore = DrawAhead.RoundEnd(shot, ShotResult.Miss);
|
||||
|
||||
// The stat changes after the round left, and the weapon re-reads it.
|
||||
((InstantWeaponData) e.Weapon.WeaponData).Range = Constant(NoLockRange * 5f);
|
||||
e.Weapon.Execute(0f);
|
||||
Assert.Equal(NoLockRange * 5f, e.Weapon.Range, 4);
|
||||
|
||||
var after = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.Equal(NoLockRange, after.MaxRange, 4);
|
||||
Assert.Equal(endBefore, DrawAhead.RoundEnd(after, ShotResult.Miss), 4);
|
||||
var aim = normalize(float2(2, 1));
|
||||
var held = DrawAhead.Round(after, Known(after, ShotResult.Miss), after.FireOrigin, 0f, after.FireTime + 1000f, 0f);
|
||||
Assert.Equal(origin.x + aim.x * NoLockRange, held.x, 3);
|
||||
Assert.Equal(origin.z + aim.y * NoLockRange, held.z, 3);
|
||||
}
|
||||
|
||||
// A direct round at a stationary target `targetRange` ahead (+z) of the shooter, weapon Range `range`, at `speed`;
|
||||
// or, with atNothing, the same weapon fired along +z at no target.
|
||||
private Engagement FireDirectRound(float speed, float range, float targetRange = 100f, bool atNothing = false)
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: speed, weaponRange: range, targetRange: targetRange);
|
||||
if (atNothing)
|
||||
{
|
||||
Aim(e, float2(0, 1));
|
||||
e.Shooter.SetTarget(TargetRef.None);
|
||||
}
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
return e;
|
||||
}
|
||||
|
||||
// A hit, a burst or an outcome not yet known ends at the round's arrival; a miss flies on to the weapon's range and
|
||||
// never ends short of its own arrival; only a published miss is over by the clock.
|
||||
[Fact]
|
||||
public void RoundEndAndRoundOverAreTheOutcomesEnd()
|
||||
{
|
||||
foreach (var speed in new[] { 20f, 200f })
|
||||
{
|
||||
var d = FireDirectRound(speed, 1000f);
|
||||
var direct = SafeAssert.OnlyShot(d.Zone);
|
||||
Assert.Equal(direct.FireTime + 100f / speed, direct.ArrivalTime, 4);
|
||||
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, null), 4);
|
||||
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, ShotResult.Hit), 4);
|
||||
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, ShotResult.Burst), 4);
|
||||
Assert.Equal(direct.FireTime + 1000f / speed, DrawAhead.RoundEnd(direct, ShotResult.Miss), 4);
|
||||
|
||||
Assert.False(DrawAhead.RoundOver(direct, null, direct.FireTime + 10000f, 0f));
|
||||
foreach (var result in new[] { ShotResult.Hit, ShotResult.Burst })
|
||||
Assert.False(DrawAhead.RoundOver(direct, Known(direct, result), direct.FireTime + 10000f, 0f));
|
||||
var missEnd = direct.FireTime + 1000f / speed;
|
||||
Assert.False(DrawAhead.RoundOver(direct, Known(direct, ShotResult.Miss), missEnd - .01f, 0f));
|
||||
Assert.True(DrawAhead.RoundOver(direct, Known(direct, ShotResult.Miss), missEnd, 0f));
|
||||
|
||||
// A target beyond the weapon's range: a miss never ends short of its own arrival.
|
||||
var far = FireDirectRound(speed, 100f, targetRange: 150f);
|
||||
var beyond = SafeAssert.OnlyShot(far.Zone);
|
||||
Assert.Equal(beyond.FireTime + 150f / speed, beyond.ArrivalTime, 4);
|
||||
Assert.Equal(beyond.FireTime + 150f / speed, DrawAhead.RoundEnd(beyond, ShotResult.Miss), 4);
|
||||
|
||||
// A round fired at nothing arrives where it left, and a miss flies on to the range.
|
||||
var none = FireDirectRound(speed, 100f, atNothing: true);
|
||||
var nothing = SafeAssert.OnlyShot(none.Zone);
|
||||
Assert.Equal(nothing.FireTime, nothing.ArrivalTime, 4);
|
||||
Assert.Equal(nothing.FireTime, DrawAhead.RoundEnd(nothing, null), 4);
|
||||
Assert.Equal(nothing.FireTime + 100f / speed, DrawAhead.RoundEnd(nothing, ShotResult.Miss), 4);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// The frame falls Lead (< one step) after the last step, so a hit or burst is drawn at Zone.Time + Lead; it must stay
|
||||
// on the arrival point until the sim resolves it, and only a published miss flies on.
|
||||
[Theory]
|
||||
[InlineData(20f)]
|
||||
[InlineData(200f)]
|
||||
public void ARoundIsDrawnNoFurtherThanItsArrivalUntilItMisses(float speed)
|
||||
{
|
||||
var e = FireDirectRound(speed, 1000f);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
var origin = shot.FireOrigin;
|
||||
const float step = 1f / 30f;
|
||||
|
||||
foreach (var lead in new[] { 0f, step / 2f, .999f * step })
|
||||
{
|
||||
var waiting = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, shot.ArrivalTime, lead);
|
||||
Assert.Equal(origin.x, waiting.x, 3);
|
||||
Assert.Equal(origin.z + 100f, waiting.z, 3);
|
||||
var missed = DrawAhead.Round(shot, Known(shot, ShotResult.Miss), shot.FireOrigin, 0f, shot.ArrivalTime, lead);
|
||||
Assert.Equal(origin.x, missed.x, 3);
|
||||
Assert.Equal(origin.z + 100f + lead * speed, missed.z, 3);
|
||||
}
|
||||
|
||||
for (var time = shot.FireTime; time <= shot.ArrivalTime + 1f; time += 1f / 144f)
|
||||
{
|
||||
var drawn = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, time, 0f);
|
||||
Assert.True(drawn.z - origin.z <= 100f + 1e-3f, "the round was drawn past its arrival point");
|
||||
}
|
||||
}
|
||||
|
||||
// A no-lock contact round stopped by a hull short of max range has its arrival shortened at the commit; the
|
||||
// simulation writes the record back before ShotCommitted fires, so a presenter re-reading it there draws the stop
|
||||
// at the committed arrival, not the fire-time copy's.
|
||||
[Fact]
|
||||
public void TheCommittedRecordCarriesTheCommittedArrival()
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: 20f, fuse: WeaponFuse.Contact, blastRadius: 4f, damage: 100f,
|
||||
weaponRange: NoLockRange);
|
||||
e.Shooter.SetTarget(TargetRef.None);
|
||||
Aim(e, float2(0, 1));
|
||||
AddShip(e, PointAlong(e, float2(0, 1), 25f), 1f, 300);
|
||||
ShotOutcome outcome = null;
|
||||
PendingShot record = default;
|
||||
var found = false;
|
||||
using var c = e.Zone.ShotCommitted.Subscribe(o =>
|
||||
{
|
||||
outcome = o;
|
||||
found = e.Zone.TryGetShot(o.ShotId, out record);
|
||||
});
|
||||
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
var fired = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.False(fired.Committed);
|
||||
e.Zone.Update(.01f);
|
||||
|
||||
Assert.True(found, "the committed record was not readable when ShotCommitted fired");
|
||||
Assert.True(record.Committed);
|
||||
Assert.Equal(fired.FireTime + 3f, fired.ArrivalTime, 2);
|
||||
Assert.Equal(fired.FireTime + 1.05f, record.ArrivalTime, 2);
|
||||
Assert.True(record.ArrivalTime < fired.ArrivalTime);
|
||||
|
||||
var stop = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime, 0f);
|
||||
var expected = outcome.HasBurstPoint
|
||||
? outcome.BurstPoint
|
||||
: record.FireOrigin.xz + record.TravelDirection * (20f * (record.ArrivalTime - record.FireTime));
|
||||
Assert.Equal(expected.x, stop.x, 3);
|
||||
Assert.Equal(expected.y, stop.z, 3);
|
||||
foreach (var later in new[] { 0f, .5f, 5f })
|
||||
{
|
||||
var drawn = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime + later, 0f);
|
||||
Assert.Equal(expected.x, drawn.x, 3);
|
||||
Assert.Equal(expected.y, drawn.z, 3);
|
||||
}
|
||||
}
|
||||
|
||||
// The barrel is only where the round is first seen: its offset from the sim line decays linearly to nothing over
|
||||
// blendTime sim seconds from FireTime.
|
||||
[Theory]
|
||||
[InlineData(.1f)]
|
||||
[InlineData(.25f)]
|
||||
public void TheBarrelBlendDecaysOnSimTime(float blend)
|
||||
{
|
||||
var e = FireBurstRound(out var origin);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
var aim = normalize(float2(2, 1));
|
||||
var offset = float3(1, .5f, -2);
|
||||
var barrel = shot.FireOrigin + offset;
|
||||
float3 Line(float dt) => float3(origin.x + aim.x * BallisticSpeed * dt, origin.y, origin.z + aim.y * BallisticSpeed * dt);
|
||||
|
||||
void Close(float3 want, float3 got)
|
||||
{
|
||||
Assert.Equal(want.x, got.x, 3);
|
||||
Assert.Equal(want.y, got.y, 3);
|
||||
Assert.Equal(want.z, got.z, 3);
|
||||
}
|
||||
|
||||
Close(barrel, DrawAhead.Round(shot, null, barrel, blend, shot.FireTime, 0f));
|
||||
Close(Line(blend / 2f) + offset * .5f, DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + blend / 2f, 0f));
|
||||
Close(Line(blend), DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + blend, 0f));
|
||||
Close(Line(2f * blend), DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + 2f * blend, 0f));
|
||||
Close(Line(0f), DrawAhead.Round(shot, null, barrel, 0f, shot.FireTime, 0f));
|
||||
}
|
||||
|
||||
// Placement depends on sim time alone: any history of frames walked to a checkpoint draws what a fresh call draws, which
|
||||
// is the frozen line at the frozen speed.
|
||||
[Theory]
|
||||
[InlineData(20f)]
|
||||
[InlineData(200f)]
|
||||
public void ARoundIsAFunctionOfSimTime(float speed)
|
||||
{
|
||||
var e = FireDirectRound(speed, 1000f);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
var checkpoints = new[] { .05f, .3f, 1f, 3f };
|
||||
var histories = new[] { new[] { 1f / 144f }, new[] { 1f / 30f }, new[] { 1f / 144f, 1f / 30f, 1f / 90f } };
|
||||
var miss = Known(shot, ShotResult.Miss);
|
||||
|
||||
foreach (var frames in histories)
|
||||
{
|
||||
var elapsed = 0f;
|
||||
var frame = 0;
|
||||
foreach (var checkpoint in checkpoints)
|
||||
{
|
||||
while (elapsed + 1e-4f < checkpoint)
|
||||
{
|
||||
elapsed = min(checkpoint, elapsed + frames[frame++ % frames.Length]);
|
||||
DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + elapsed, 0f);
|
||||
}
|
||||
var drawn = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint, 0f);
|
||||
var fresh = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint, 0f);
|
||||
// A frame that falls `lead` after the step draws what the sim time lead later would.
|
||||
foreach (var lead in new[] { 1f / 60f, 1f / 90f })
|
||||
{
|
||||
var ahead = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint - lead, lead);
|
||||
Assert.Equal(fresh.x, ahead.x, 3);
|
||||
Assert.Equal(fresh.y, ahead.y, 3);
|
||||
Assert.Equal(fresh.z, ahead.z, 3);
|
||||
}
|
||||
Assert.Equal(fresh.z, drawn.z, 3);
|
||||
Assert.Equal(shot.FireOrigin.z + speed * min(checkpoint, 1000f / speed), drawn.z, 3);
|
||||
Assert.Equal(shot.FireOrigin.x, drawn.x, 3);
|
||||
Assert.Equal(shot.FireOrigin.y, drawn.y, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A hit ends at its impact cell on the target's drawn pose when damage lands, not at the arrival point of the line
|
||||
// frozen at Fire (ruling direct-arrival-keep-timing): the target has moved and turned since, and is drawn ahead by its
|
||||
// last step's velocity and turn. The expected point is computed apart from DrawAhead, by moving the entity itself and
|
||||
// asking its own schematic frame (Entity.ToWorldPoint) where the cell is.
|
||||
[Theory]
|
||||
[InlineData(20f)]
|
||||
[InlineData(200f)]
|
||||
public void AHitEndsAtItsImpactCellOnTheTargetsDrawnPose(float speed)
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: speed, weaponRange: 1000f);
|
||||
e.Target.Velocity = float2(10, 0);
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.True(shot.TravelDirection.x > 0f, "the round did not lead the target");
|
||||
const float step = 1f / 30f;
|
||||
|
||||
e.Target.Position += float3(40, 0, 0);
|
||||
e.Target.Direction = normalize(float2(1, 2));
|
||||
e.Target.TurnRate = 3f;
|
||||
var cell = FarCell(e);
|
||||
var hit = Hit(shot, e.Target, cell, shot.CommitTime);
|
||||
var arrivalOnTheLine = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, shot.ArrivalTime, 0f);
|
||||
var cellSize = e.Items.GameplaySettings.SchematicCellSize;
|
||||
|
||||
foreach (var lead in new[] { 0f, step / 2f, .999f * step })
|
||||
{
|
||||
var position = e.Target.Position;
|
||||
var direction = e.Target.Direction;
|
||||
e.Target.Position += float3(e.Target.Velocity.x, 0, e.Target.Velocity.y) * lead;
|
||||
e.Target.Direction = mul(e.Target.Direction, CultMath.float2x2.Rotate(e.Target.TurnRate * lead));
|
||||
var cellPoint = e.Target.ToWorldPoint((float2) cell);
|
||||
var expected = float3(cellPoint.x, e.Target.Position.y, cellPoint.y);
|
||||
e.Target.Position = position;
|
||||
e.Target.Direction = direction;
|
||||
|
||||
Assert.True(length((expected - arrivalOnTheLine).xz) > cellSize, "the fixture put the cell on the frozen line's arrival point");
|
||||
var impact = DrawAhead.Impact(e.Target, cell, lead);
|
||||
Assert.Equal(expected.x, impact.x, 3);
|
||||
Assert.Equal(expected.y, impact.y, 3);
|
||||
Assert.Equal(expected.z, impact.z, 3);
|
||||
foreach (var simTime in new[] { shot.ArrivalTime, shot.ArrivalTime + .5f })
|
||||
{
|
||||
var drawn = DrawAhead.Round(shot, hit, shot.FireOrigin, .1f, simTime, lead);
|
||||
Assert.Equal(expected.x, drawn.x, 3);
|
||||
Assert.Equal(expected.y, drawn.y, 3);
|
||||
Assert.Equal(expected.z, drawn.z, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A hit leaves its frozen line at the commit tick and steers onto its end by the time damage lands: before the commit it
|
||||
// is on the line, half way through the steer it is half way to the impact cell, and a frame drawn ahead by the clock's
|
||||
// lead places the round where the sim time that much later would.
|
||||
[Fact]
|
||||
public void ASteeredRoundLeavesItsLineAtTheCommit()
|
||||
{
|
||||
var e = FireDirectRound(20f, 1000f);
|
||||
var shot = SafeAssert.OnlyShot(e.Zone);
|
||||
Assert.Equal(shot.FireTime + 5f, shot.ArrivalTime, 3);
|
||||
var cell = FarCell(e);
|
||||
var commit = shot.ArrivalTime - 2f;
|
||||
var hit = Hit(shot, e.Target, cell, commit);
|
||||
|
||||
foreach (var t in new[] { commit - 1f, commit })
|
||||
{
|
||||
var steered = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, t, 0f);
|
||||
var line = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, t, 0f);
|
||||
Assert.Equal(line.x, steered.x, 3);
|
||||
Assert.Equal(line.y, steered.y, 3);
|
||||
Assert.Equal(line.z, steered.z, 3);
|
||||
}
|
||||
|
||||
var m = commit + 1f;
|
||||
var onTheLine = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, m, 0f);
|
||||
var end = DrawAhead.Impact(e.Target, cell, 0f);
|
||||
Assert.True(length((end - onTheLine).xz) > 1f, "the fixture put the impact cell on the line");
|
||||
var halfway = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, m, 0f);
|
||||
Assert.Equal(onTheLine.x + (end.x - onTheLine.x) * .5f, halfway.x, 3);
|
||||
Assert.Equal(onTheLine.y + (end.y - onTheLine.y) * .5f, halfway.y, 3);
|
||||
Assert.Equal(onTheLine.z + (end.z - onTheLine.z) * .5f, halfway.z, 3);
|
||||
|
||||
var ahead = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, m - .02f, .02f);
|
||||
Assert.Equal(halfway.x, ahead.x, 3);
|
||||
Assert.Equal(halfway.y, ahead.y, 3);
|
||||
Assert.Equal(halfway.z, ahead.z, 3);
|
||||
}
|
||||
|
||||
// The sim states facts and draws nothing: no drawing function, and no lead, blend or barrel, lives in FireControl;
|
||||
// those belong to DrawAhead, the presentation statics.
|
||||
[Fact]
|
||||
public void FireControlHasNoDrawingFunctions()
|
||||
{
|
||||
const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
|
||||
var methods = typeof(FireControl).GetMethods(all).Cast<MethodBase>().Concat(typeof(FireControl).GetConstructors(all)).ToList();
|
||||
Assert.NotEmpty(methods);
|
||||
foreach (var method in methods)
|
||||
{
|
||||
Assert.False(method.Name.StartsWith("Round") || method.Name.StartsWith("Draw"), "FireControl has a drawing function: " + method.Name);
|
||||
foreach (var parameter in method.GetParameters())
|
||||
Assert.False(new[] { "lead", "blendTime", "barrel" }.Contains(parameter.Name), "FireControl takes a drawing parameter: " + parameter.Name);
|
||||
}
|
||||
|
||||
foreach (var name in new[] { "Round", "Impact", "RoundOver", "RoundEnd" })
|
||||
Assert.NotNull(typeof(DrawAhead).GetMethod(name, BindingFlags.Public | BindingFlags.Static));
|
||||
}
|
||||
|
||||
// A proximity round at a target that recedes faster than the round closes bursts at the weapon's range, pulled back
|
||||
// along its line, while it arrives when it has flown the distance the target was fired at: its burst point is not
|
||||
// the line at its arrival. The end is the sim's burst point, so a presenter that ended at the arrival line would
|
||||
// end the tracer short of where the round burst.
|
||||
[Fact]
|
||||
public void ABurstRoundEndsAtItsBurstPointNotItsArrivalLine()
|
||||
{
|
||||
var e = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, fuse: WeaponFuse.Proximity, blastRadius: 4f,
|
||||
damage: 100f, weaponRange: NoLockRange, targetRange: 50f);
|
||||
e.Target.Velocity = float2(0, 15);
|
||||
ShotOutcome outcome = null;
|
||||
using var c = e.Zone.ShotCommitted.Subscribe(o => outcome = o);
|
||||
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
|
||||
var origin = SafeAssert.OnlyShot(e.Zone).FireOrigin;
|
||||
for (var i = 0; i < 100 && outcome == null; i++) e.Zone.Update(.05f);
|
||||
Assert.NotNull(outcome);
|
||||
Assert.True(outcome.HasBurstPoint);
|
||||
Assert.True(e.Zone.TryGetShot(outcome.ShotId, out var record));
|
||||
|
||||
Assert.Equal(origin.x, outcome.BurstPoint.x, 3);
|
||||
Assert.Equal(origin.z + NoLockRange, outcome.BurstPoint.y, 3);
|
||||
Assert.Equal(origin.z + 50f, DrawAhead.Round(record, null, record.FireOrigin, 0f, record.ArrivalTime, 0f).z, 3);
|
||||
var stop = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime, 0f);
|
||||
Assert.Equal(outcome.BurstPoint.x, stop.x, 3);
|
||||
Assert.Equal(outcome.BurstPoint.y, stop.z, 3);
|
||||
}
|
||||
}
|
||||
266
tests/Aetheria.Shared.Tests/ConsumableTests.cs
Normal file
266
tests/Aetheria.Shared.Tests/ConsumableTests.cs
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using Xunit;
|
||||
|
||||
// A consumable is a cargo item with a timed effect (aetheria-release CS-R1). Its modifiers exist in the resolver
|
||||
// exactly while its effect is active: the host (Entity) initialises the effect's behaviours at activation and
|
||||
// disposes them at expiry, and ItemManager.CreateInstance is the one way a lot becomes a ConsumableItem.
|
||||
public sealed class ConsumableTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-consumable-" + Guid.NewGuid().ToString("N"));
|
||||
private string Catalog => Path.Combine(_root, "Aetheria.cc");
|
||||
private static readonly int2 EngineCell = new int2(0, 0);
|
||||
private static readonly int2 HoldCell = new int2(1, 1);
|
||||
|
||||
public ConsumableTests() => Directory.CreateDirectory(_root);
|
||||
public void Dispose() => Directory.Delete(_root, true);
|
||||
|
||||
private sealed class Rig
|
||||
{
|
||||
public CultCache Cache;
|
||||
public ItemManager Items;
|
||||
public Ship Ship;
|
||||
public EquippedItem Engine;
|
||||
public PerformanceStat Thrust;
|
||||
public ConsumableItemData Consumable;
|
||||
public ConsumableItemData Other; // a second, unrelated non-stackable design
|
||||
public Func<EquippableItem> NewEngine;
|
||||
public CultRecordKey Key;
|
||||
public CultRecordRef<Faction> Maker;
|
||||
|
||||
public ConsumableItem Mint(ConsumableItemData design = null) =>
|
||||
Assert.IsType<ConsumableItem>(Items.CreateInstance(Items.CreateLot(design ?? Consumable, Maker, .5f)));
|
||||
public EquippedCargoBay Hold => Ship.CargoBays.Single();
|
||||
public int InCargo => Hold.Cargo.Keys.Count(i => i is ConsumableItem);
|
||||
}
|
||||
|
||||
// A ship with a thruster (Thrust 10) and a hold; the consumable doubles ThrusterData.Thrust for one second.
|
||||
private Rig Build(bool stackable = false)
|
||||
{
|
||||
var thrust = new PerformanceStat { Min = 10, Max = 10 };
|
||||
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" });
|
||||
var hullShape = new Shape(3, 3);
|
||||
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
|
||||
var hullRef = cache.Upsert(new HullData
|
||||
{
|
||||
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10,
|
||||
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = EngineCell, Shape = new Shape() } }
|
||||
});
|
||||
var engineRef = cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Engine", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10,
|
||||
Behaviors = { new ThrusterData { Thrust = thrust } }
|
||||
});
|
||||
var interior = new Shape(2, 1); // room for two consumables
|
||||
foreach (var cell in interior.AllCoordinates) interior[cell] = true;
|
||||
var holdRef = cache.Upsert(new CargoBayData { Name = "Hold", Shape = new Shape(), InteriorShape = interior, Durability = 10 });
|
||||
var consumableRef = cache.Upsert(new ConsumableItemData
|
||||
{
|
||||
Name = "Overdrive", Duration = 1f, Stackable = stackable, Shape = new Shape(),
|
||||
Behaviors =
|
||||
{
|
||||
new StatModifierData
|
||||
{
|
||||
Stat = new StatReference { Target = nameof(ThrusterData), Stat = nameof(ThrusterData.Thrust) },
|
||||
Modifier = new PerformanceStat { Min = 2, Max = 2 },
|
||||
Type = StatModifierType.Multiplier
|
||||
}
|
||||
}
|
||||
});
|
||||
var otherRef = cache.Upsert(new ConsumableItemData { Name = "Flare", Duration = 1f, Shape = new Shape() });
|
||||
cache.FlushAsync().Wait();
|
||||
|
||||
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
|
||||
var makerRef = cache.RefOf(cache.GetByName<Faction>("Maker"));
|
||||
EquippableItem Gear(EquippableItemData design) => (EquippableItem) items.CreateInstance(items.CreateLot(design, makerRef, .5f));
|
||||
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
|
||||
var ship = new Ship(items, zone, Gear(cache.Get(hullRef)), new EntitySettings());
|
||||
Assert.True(ship.TryEquip(Gear(cache.Get(engineRef)), EngineCell));
|
||||
Assert.True(ship.TryEquip(Gear(cache.Get(holdRef)), HoldCell));
|
||||
zone.Entities.Add(ship);
|
||||
ship.Activate();
|
||||
var data = cache.Get(consumableRef);
|
||||
return new Rig
|
||||
{
|
||||
Cache = cache, Items = items, Ship = ship, Thrust = thrust, Consumable = data, Other = cache.Get(otherRef),
|
||||
NewEngine = () => Gear(cache.Get(engineRef)),
|
||||
Key = items.ItemData.RefOf<ItemData>(data).Key,
|
||||
Engine = ship.Equipment.Single(e => e.Data.Name == "Engine"),
|
||||
Maker = makerRef
|
||||
};
|
||||
}
|
||||
|
||||
// Two ticks after activation the modifier has attached (the first tick executes it, the second applies it).
|
||||
private static void Tick(Rig rig, int times, float dt)
|
||||
{
|
||||
for (var i = 0; i < times; i++) rig.Ship.Update(dt);
|
||||
}
|
||||
|
||||
// The rule: a consumable's modifiers exist in the resolver exactly while its effect is active, never after.
|
||||
// Observed at the resolved stat and at the resolver's modifier entry count, not at a flag.
|
||||
[Fact]
|
||||
public void AConsumableModifierBoostsUntilExpiry()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
var resolver = rig.Ship.Resolver;
|
||||
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
var baseline = resolver.ModifierEntryCount;
|
||||
|
||||
rig.Ship.ActivateConsumable(rig.Mint());
|
||||
Tick(rig, 2, .3f); // 0.4s of the 1s remain; the modifier has attached
|
||||
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Assert.True(resolver.ModifierEntryCount > baseline);
|
||||
|
||||
Tick(rig, 3, .3f); // 1.5s elapsed in all: the effect ran out on the fourth tick
|
||||
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Assert.Equal(baseline, resolver.ModifierEntryCount);
|
||||
}
|
||||
|
||||
// A lot minted through the one production path is a ConsumableItem, and a hold holding it activates it.
|
||||
[Fact]
|
||||
public void ABoughtConsumableActivates()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
Assert.Equal(1, rig.InCargo);
|
||||
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.Equal(0, rig.InCargo);
|
||||
Assert.NotNull(rig.Ship.FindActiveConsumable(rig.Consumable));
|
||||
}
|
||||
|
||||
// CS-R1: a non-stackable design allows one active effect at a time, so its Duration is its cooldown.
|
||||
[Fact]
|
||||
public void ANonStackableConsumableRefusesASecondActivation()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.False(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.Equal(1, rig.InCargo);
|
||||
|
||||
Tick(rig, 5, .3f); // the first effect has run out
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.Equal(0, rig.InCargo);
|
||||
}
|
||||
|
||||
// The expiry boundary: Duration 1 with 0.3 s ticks leaves 0.1 s after the third tick (still active) and
|
||||
// -0.2 s after the fourth (gone). An expiry one tick early or one tick late changes one of these two reads.
|
||||
[Fact]
|
||||
public void AConsumableLivesForItsDurationAndNoLonger()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
rig.Ship.ActivateConsumable(rig.Mint());
|
||||
Tick(rig, 3, .3f);
|
||||
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Tick(rig, 1, .3f);
|
||||
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
}
|
||||
|
||||
// An effect runs for exactly its Duration: Duration 1 with 0.25 s ticks (exact in floats) executes its
|
||||
// behaviours on four ticks and is gone when the fourth ends, not on a fifth.
|
||||
[Fact]
|
||||
public void AConsumableRunsForExactlyItsDurationInTicks()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
rig.Ship.ActivateConsumable(rig.Mint());
|
||||
Tick(rig, 3, .25f);
|
||||
Assert.NotNull(rig.Ship.FindActiveConsumable(rig.Consumable));
|
||||
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Tick(rig, 1, .25f); // the fourth tick spends the last of the Duration
|
||||
Assert.Null(rig.Ship.FindActiveConsumable(rig.Consumable));
|
||||
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
}
|
||||
|
||||
// CS-R1, the stackable side: a stackable design activates again while its first effect runs, and every
|
||||
// multiplier on the stat multiplies.
|
||||
[Fact]
|
||||
public void TwoStackableConsumablesOverlapAndMultiply()
|
||||
{
|
||||
var rig = Build(stackable: true);
|
||||
using var _ = rig.Cache;
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.Equal(0, rig.InCargo);
|
||||
Tick(rig, 2, .3f);
|
||||
Assert.Equal(40f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
}
|
||||
|
||||
// Two modifiers share one resolver entry, both attached. The first expires while the second still runs: the
|
||||
// second's boost stays, and when it expires too nothing is left behind.
|
||||
[Fact]
|
||||
public void AnExpiringConsumableLeavesAnOverlappingOnesBoost()
|
||||
{
|
||||
var rig = Build(stackable: true);
|
||||
using var _ = rig.Cache;
|
||||
var resolver = rig.Ship.Resolver;
|
||||
var baseline = resolver.ModifierEntryCount;
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Tick(rig, 1, .3f);
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Tick(rig, 2, .3f); // both attached: the first has 0.1 s left, the second 0.4 s
|
||||
Assert.Equal(40f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
|
||||
Tick(rig, 1, .3f); // the first ran out; the second's boost is still on the shared entry
|
||||
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Assert.True(resolver.ModifierEntryCount > baseline);
|
||||
|
||||
Tick(rig, 1, .3f); // and now the second
|
||||
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
Assert.Equal(baseline, resolver.ModifierEntryCount);
|
||||
}
|
||||
|
||||
// CS-R1: the cooldown is per design. A running effect of one design does not refuse another design.
|
||||
[Fact]
|
||||
public void ADesignsCooldownDoesNotBlockAnotherDesign()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint()));
|
||||
Assert.True(rig.Hold.TryStore(rig.Mint(rig.Other)));
|
||||
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
|
||||
Assert.True(rig.Ship.TryActivateConsumable(rig.Other));
|
||||
Assert.Equal(0, rig.InCargo);
|
||||
}
|
||||
|
||||
// Docking: an effect still running when the entity deactivates, is refitted and activates again boosts the
|
||||
// items now fitted, as gear modifiers do, not the thruster that was swapped out.
|
||||
[Fact]
|
||||
public void AConsumableActiveAcrossARefitBoostsTheNewItems()
|
||||
{
|
||||
var rig = Build();
|
||||
using var _ = rig.Cache;
|
||||
rig.Ship.ActivateConsumable(rig.Mint());
|
||||
Tick(rig, 2, .3f);
|
||||
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
|
||||
|
||||
rig.Ship.Deactivate();
|
||||
Assert.NotNull(rig.Ship.TryUnequip(rig.Engine));
|
||||
Assert.True(rig.Ship.TryEquip(rig.NewEngine(), EngineCell));
|
||||
rig.Ship.Activate();
|
||||
Tick(rig, 2, .1f); // 0.2 s more: the effect still has 0.2 s of its second
|
||||
var fitted = rig.Ship.Equipment.Single(e => e.Data.Name == "Engine");
|
||||
Assert.NotSame(rig.Engine, fitted);
|
||||
Assert.Equal(20f, fitted.Evaluate(rig.Thrust), 3);
|
||||
}
|
||||
}
|
||||
|
|
@ -760,11 +760,7 @@ public sealed class LoadoutTests : IDisposable
|
|||
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
|
||||
var hullItem = (EquippableItem) items.CreateInstance(items.CreateLot(hullData, maker, .5f));
|
||||
var ship = new Ship(items, null, hullItem, new EntitySettings());
|
||||
// ItemManager.CreateInstance has no ConsumableItemData branch (it only special-cases EquippableItemData,
|
||||
// falling back to CompoundCommodity otherwise); build the instance directly, as that method does for
|
||||
// EquippableItem.
|
||||
var consumableLot = items.CreateLot(consumableData, maker, .5f);
|
||||
var consumableItem = new ConsumableItem { Data = cache.RefOf<ItemData>(consumableData), Lot = consumableLot };
|
||||
var consumableItem = (ConsumableItem) items.CreateInstance(items.CreateLot(consumableData, maker, .5f));
|
||||
var effect = new ConsumableItemEffect(consumableItem, ship);
|
||||
effect.Update(5f); // half the duration elapsed -> progress .5 -> effectiveness .5 on a linear ramp
|
||||
|
||||
|
|
|
|||
101
tests/Aetheria.Shared.Tests/PlayerStagingTests.cs
Normal file
101
tests/Aetheria.Shared.Tests/PlayerStagingTests.cs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Xunit;
|
||||
|
||||
// A player directory's GameData is exactly the catalog, Narrative/** and (when the repo has them) Mods/**.
|
||||
public sealed class PlayerStagingTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-staging-" + Guid.NewGuid().ToString("N"));
|
||||
private string Repo => Path.Combine(_root, "repo");
|
||||
private string Player => Path.Combine(_root, "player");
|
||||
private string Source(string relative) => Path.Combine(Repo, "GameData", relative);
|
||||
private string Staged(string relative) => Path.Combine(Player, "GameData", relative);
|
||||
|
||||
public PlayerStagingTests()
|
||||
{
|
||||
Write(Source("Aetheria.cc"), "catalog-bytes");
|
||||
Write(Source("Narrative/Main.ink"), "main");
|
||||
Write(Source("Narrative/Quests/Deep/First.ink"), "first");
|
||||
Write(Source("SoundbanksInfo.json"), "{}");
|
||||
Write(Source("run.cc"), "a developer's run");
|
||||
Write(Source("player.cc"), "a developer's settings");
|
||||
Directory.CreateDirectory(Player);
|
||||
}
|
||||
|
||||
public void Dispose() => Directory.Delete(_root, true);
|
||||
|
||||
[Fact]
|
||||
public void StagesTheCatalogAndNarrativeFileForFile()
|
||||
{
|
||||
PlayerStaging.Stage(Repo, Player);
|
||||
|
||||
Assert.Equal("catalog-bytes", File.ReadAllText(Staged("Aetheria.cc")));
|
||||
Assert.Equal("main", File.ReadAllText(Staged("Narrative/Main.ink")));
|
||||
Assert.Equal("first", File.ReadAllText(Staged("Narrative/Quests/Deep/First.ink")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StagesModsWhenTheRepoHasThemAndNoModsFolderWhenItDoesNot()
|
||||
{
|
||||
PlayerStaging.Stage(Repo, Player);
|
||||
Assert.False(Directory.Exists(Staged("Mods")));
|
||||
|
||||
Write(Source("Mods/ship-a/ship.cc"), "ship");
|
||||
Write(Source("Mods/ship-a/mesh/hull.glb"), "hull");
|
||||
PlayerStaging.Stage(Repo, Player);
|
||||
|
||||
Assert.Equal("ship", File.ReadAllText(Staged("Mods/ship-a/ship.cc")));
|
||||
Assert.Equal("hull", File.ReadAllText(Staged("Mods/ship-a/mesh/hull.glb")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void StagesNothingElseFromGameData()
|
||||
{
|
||||
PlayerStaging.Stage(Repo, Player);
|
||||
|
||||
var staged = Directory.GetFileSystemEntries(Path.Combine(Player, "GameData")).Select(Path.GetFileName).OrderBy(name => name).ToArray();
|
||||
Assert.Equal(new[] { "Aetheria.cc", "Narrative" }, staged);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReplacesWhatAnEarlierBuildLeftInGameData()
|
||||
{
|
||||
Write(Staged("Aetheria.cc"), "stale");
|
||||
Write(Staged("run.cc"), "a played run");
|
||||
Write(Staged("Mods/gone/ship.cc"), "removed mod");
|
||||
|
||||
PlayerStaging.Stage(Repo, Player);
|
||||
|
||||
Assert.Equal("catalog-bytes", File.ReadAllText(Staged("Aetheria.cc")));
|
||||
Assert.False(File.Exists(Staged("run.cc")));
|
||||
Assert.False(Directory.Exists(Staged("Mods")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefusesAMissingCatalogNamingItAndLeavesNoGameData()
|
||||
{
|
||||
File.Delete(Source("Aetheria.cc"));
|
||||
|
||||
var error = Assert.Throws<InvalidOperationException>(() => PlayerStaging.Stage(Repo, Player));
|
||||
|
||||
Assert.Contains("GameData/Aetheria.cc", error.Message);
|
||||
Assert.False(Directory.Exists(Path.Combine(Player, "GameData")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RefusesMissingNarrative()
|
||||
{
|
||||
Directory.Delete(Source("Narrative"), true);
|
||||
|
||||
var error = Assert.Throws<InvalidOperationException>(() => PlayerStaging.Stage(Repo, Player));
|
||||
|
||||
Assert.Contains("GameData/Narrative", error.Message);
|
||||
}
|
||||
|
||||
private static void Write(string path, string text)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
File.WriteAllText(path, text);
|
||||
}
|
||||
}
|
||||
|
|
@ -441,7 +441,7 @@ public sealed class StatResolverTests : IDisposable
|
|||
for (var i = 0; i < 20; i++)
|
||||
{
|
||||
var lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(boosterData), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() });
|
||||
var consumableItem = new ConsumableItem { Data = cache.RefOf<ItemData>(boosterData), Lot = lot };
|
||||
var consumableItem = Assert.IsType<ConsumableItem>(items.CreateInstance(lot));
|
||||
ship.ActivateConsumable(consumableItem);
|
||||
|
||||
// Duration is 0.01s; one 1-second tick expires it and drives Entity.Update's expiry branch.
|
||||
|
|
@ -452,4 +452,132 @@ public sealed class StatResolverTests : IDisposable
|
|||
Assert.Equal(baselineCache, resolver.CacheEntryCount);
|
||||
Assert.Equal(baselineModifiers, resolver.ModifierEntryCount);
|
||||
}
|
||||
|
||||
// Ruling boost-stacking-multiply: every multiplier on one stat multiplies, with no stacking penalty, and every
|
||||
// constant adds. The rig is the production path end to end: gear carrying StatModifierData is equipped on a ship
|
||||
// beside a thruster, a consumable is minted through ItemManager.CreateInstance and activated on the ship, and
|
||||
// the resolved value is read through EquippedItem.Evaluate. Nothing here calls AttachModifier by hand.
|
||||
private sealed class ThrustRig
|
||||
{
|
||||
public CultCache Cache;
|
||||
public ItemManager Items;
|
||||
public Ship Ship;
|
||||
public EquippedItem Engine;
|
||||
public PerformanceStat Thrust;
|
||||
public Func<ConsumableItem> Consumable; // null when the rig was built without one
|
||||
|
||||
public float Resolved => Engine.Evaluate(Thrust);
|
||||
// Two ticks: the first executes every modifier, the second applies it (StatModifier.Update).
|
||||
public void Tick(float dt) { for (var i = 0; i < 2; i++) Ship.Update(dt); }
|
||||
}
|
||||
|
||||
private static StatModifierData ThrustModifier(StatModifierType type, float value) => new StatModifierData
|
||||
{
|
||||
Stat = new StatReference { Target = nameof(ThrusterData), Stat = nameof(ThrusterData.Thrust) },
|
||||
Modifier = new PerformanceStat { Min = value, Max = value },
|
||||
Type = type
|
||||
};
|
||||
|
||||
// A Thrust-10 thruster and one gear per entry of `gear`, in that attach order, plus (optionally) a consumable
|
||||
// whose single modifier is `consumable`. The hull has four hardpoints, so at most three gear modifiers.
|
||||
private ThrustRig BuildThrustRig((StatModifierType Type, float Value)[] gear, (StatModifierType Type, float Value)? consumable = null)
|
||||
{
|
||||
var thrust = new PerformanceStat { Min = 10, Max = 10 };
|
||||
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
var hullShape = new Shape(3, 3);
|
||||
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
|
||||
var cells = new[] { HardpointCell, SecondHardpointCell, FirstGunCell, SecondGunCell };
|
||||
cache.Upsert(new HullData
|
||||
{
|
||||
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10,
|
||||
Hardpoints = cells.Select(c => new HardpointData { Type = HardpointType.Sensors, Position = c, Shape = new Shape() }).ToList()
|
||||
});
|
||||
cache.Upsert(new GearData { Name = "Engine", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { new ThrusterData { Thrust = thrust } } });
|
||||
for (var i = 0; i < gear.Length; i++)
|
||||
cache.Upsert(new GearData { Name = "Boost" + i, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { ThrustModifier(gear[i].Type, gear[i].Value) } });
|
||||
if (consumable != null)
|
||||
cache.Upsert(new ConsumableItemData { Name = "Stim", Duration = 1f, Shape = new Shape(), Behaviors = { ThrustModifier(consumable.Value.Type, consumable.Value.Value) } });
|
||||
cache.FlushAsync().Wait();
|
||||
|
||||
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
|
||||
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
|
||||
var ship = new Ship(items, zone, Mint(cache, items, cache.GetByName<HullData>("Skiff")), new EntitySettings());
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName<GearData>("Engine")), cells[0]));
|
||||
for (var i = 0; i < gear.Length; i++)
|
||||
{
|
||||
// A test gear has no authored heat response, so its thermal performance reads 0 and it would sit offline;
|
||||
// the override is the entity's own switch for keeping a part running, not a stand-in for the rule.
|
||||
var boost = Mint(cache, items, cache.GetByName<GearData>("Boost" + i));
|
||||
boost.OverrideShutdown = true;
|
||||
Assert.True(ship.TryEquip(boost, cells[i + 1]));
|
||||
}
|
||||
ship.OverrideShutdown = true;
|
||||
zone.Entities.Add(ship);
|
||||
ship.Activate();
|
||||
|
||||
Func<ConsumableItem> mint = null;
|
||||
if (consumable != null)
|
||||
{
|
||||
var design = cache.GetByName<ConsumableItemData>("Stim");
|
||||
mint = () => Assert.IsType<ConsumableItem>(items.CreateInstance(items.Lots.Add(
|
||||
new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })));
|
||||
}
|
||||
return new ThrustRig { Cache = cache, Items = items, Ship = ship, Engine = ship.Equipment.Single(e => e.Data.Name == "Engine"), Thrust = thrust, Consumable = mint };
|
||||
}
|
||||
|
||||
// Two scales multiply: x1.2 and x1.25 on one stat resolve to base x1.5, and x1.1, x1.2, x1.25 to base x1.65,
|
||||
// whatever order they attach in. Mutations at StatResolver.ScaleModifier: a sum of excesses reads 14.5 and
|
||||
// 15.5, the strongest-only rule 12.5, a diminishing curve 14.67, and `result *= value * value` or
|
||||
// `result *= value + 0.01f` (functions of the scale itself) read off 15.
|
||||
[Theory]
|
||||
[InlineData(new[] { 1.2f, 1.25f }, 15f)]
|
||||
[InlineData(new[] { 1.25f, 1.2f }, 15f)]
|
||||
[InlineData(new[] { 1.1f, 1.2f, 1.25f }, 16.5f)]
|
||||
[InlineData(new[] { 1.25f, 1.1f, 1.2f }, 16.5f)]
|
||||
[InlineData(new[] { 1.2f, 1.25f, 1.1f }, 16.5f)]
|
||||
public void TwoScalesOnOneStatMultiply(float[] scales, float expected)
|
||||
{
|
||||
var rig = BuildThrustRig(scales.Select(s => (StatModifierType.Multiplier, s)).ToArray());
|
||||
using var _ = rig.Cache;
|
||||
Assert.Equal(10f, rig.Resolved, 3); // modifiers not yet applied
|
||||
rig.Tick(.1f);
|
||||
Assert.Equal(expected, rig.Resolved, 3);
|
||||
}
|
||||
|
||||
// A gear modifier and a consumable modifier on one drive's Thrust share one entry and multiply: x1.2 gear and
|
||||
// x1.5 consumable read x1.8, and when the consumable expires only the gear's x1.2 remains.
|
||||
[Fact]
|
||||
public void AConsumableBoostMultipliesWithGear()
|
||||
{
|
||||
var rig = BuildThrustRig(new[] { (StatModifierType.Multiplier, 1.2f) }, (StatModifierType.Multiplier, 1.5f));
|
||||
using var _ = rig.Cache;
|
||||
rig.Tick(.1f);
|
||||
Assert.Equal(12f, rig.Resolved, 3); // gear alone
|
||||
|
||||
rig.Ship.ActivateConsumable(rig.Consumable());
|
||||
rig.Tick(.1f); // 0.8s of the 1s remain
|
||||
Assert.Equal(18f, rig.Resolved, 3);
|
||||
|
||||
rig.Tick(.5f); // the consumable's duration has run out
|
||||
Assert.Equal(12f, rig.Resolved, 3);
|
||||
}
|
||||
|
||||
// Constants add, and compose with scales through PerformanceStat.Evaluate: (base x scale) + constant. +3 and +4
|
||||
// resolve as a constant of 7; with a x2 scale beside them the value is Evaluate's for scale 2 and constant 7,
|
||||
// (10 x 2) + 7. Mutations at ConstantModifier: `result = Math.Max(result, value)` reads constant 4;
|
||||
// `result += value * 2` reads constant 14.
|
||||
[Theory]
|
||||
[InlineData(new[] { 3f, 4f }, new float[0], 1f, 7f, 17f)]
|
||||
[InlineData(new[] { 3f, 4f }, new[] { 2f }, 2f, 7f, 27f)]
|
||||
public void TwoConstantsOnOneStatAdd(float[] constants, float[] scales, float expectedScale, float expectedConstant, float expected)
|
||||
{
|
||||
var rig = BuildThrustRig(constants.Select(c => (StatModifierType.Constant, c))
|
||||
.Concat(scales.Select(s => (StatModifierType.Multiplier, s))).ToArray());
|
||||
using var _ = rig.Cache;
|
||||
rig.Tick(.1f);
|
||||
Assert.Equal(expectedScale, rig.Ship.Resolver.ScaleModifier(rig.Engine, rig.Thrust), 3);
|
||||
Assert.Equal(expectedConstant, rig.Ship.Resolver.ConstantModifier(rig.Engine, rig.Thrust), 3);
|
||||
Assert.Equal(expected, rig.Resolved, 3);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
274
tests/Aetheria.Shared.Tests/ThrottleLockTests.cs
Normal file
274
tests/Aetheria.Shared.Tests/ThrottleLockTests.cs
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using Xunit;
|
||||
using static CultMath.math;
|
||||
|
||||
// A ThrottleLock on an active consumable replaces the pilot's movement intent with full forward, read once at
|
||||
// the top of Ship.Update's active branch. Turn is untouched. Every observation is a thruster's Axis after a real
|
||||
// Ship.Update, with the effect started through Entity.ActivateConsumable.
|
||||
public sealed class ThrottleLockTests : IDisposable
|
||||
{
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-throttlelock-" + Guid.NewGuid().ToString("N"));
|
||||
private string Catalog => Path.Combine(_root, "Aetheria.cc");
|
||||
|
||||
public ThrottleLockTests() => Directory.CreateDirectory(_root);
|
||||
public void Dispose() => Directory.Delete(_root, true);
|
||||
|
||||
private static GameplaySettings 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()
|
||||
};
|
||||
|
||||
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
|
||||
|
||||
private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design, ItemRotation rotation = ItemRotation.None) => new EquippableItem
|
||||
{
|
||||
Data = cache.RefOf<ItemData>(design),
|
||||
Durability = design is EquippableItemData equippable ? equippable.Durability : 0,
|
||||
Rotation = rotation,
|
||||
Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
|
||||
};
|
||||
|
||||
private sealed class Fixture
|
||||
{
|
||||
public CultCache Cache;
|
||||
public ItemManager Items;
|
||||
public Ship Ship;
|
||||
public ConsumableItemData Lock;
|
||||
public Thruster Forward, Reverse, Clockwise;
|
||||
public Thruster[] Right, Left; // pairs with opposing torque: a lone off-axis strafe thruster cancels its own torque
|
||||
|
||||
public void ActivateLock() => Ship.ActivateConsumable(new ConsumableItem
|
||||
{
|
||||
Data = Cache.RefOf<ItemData>(Lock),
|
||||
Lot = Items.Lots.Add(new Lot { Design = Cache.RefOf<ItemData>(Lock), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
|
||||
});
|
||||
}
|
||||
|
||||
// One thruster per intent direction, plus two reverse thrusters either side of the centre line, one of
|
||||
// which has clockwise torque (the one Turn reaches). Thrusters are found by their item's rotation, as Ship
|
||||
// sorts them.
|
||||
private Fixture Build(float lockDuration)
|
||||
{
|
||||
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
var hullShape = new Shape(5, 5);
|
||||
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
|
||||
cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 });
|
||||
cache.Upsert(new GearData
|
||||
{
|
||||
Name = "Thruster", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
|
||||
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
|
||||
Behaviors = { new ThrusterData { Thrust = Constant(100), Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(0) } }
|
||||
});
|
||||
var lockData = new ConsumableItemData { Name = "Overdrive", Duration = lockDuration, Behaviors = { new ThrottleLockData() } };
|
||||
cache.Upsert(lockData);
|
||||
cache.FlushAsync().Wait();
|
||||
|
||||
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
|
||||
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
|
||||
var ship = new Ship(items, zone, Mint(cache, items, cache.GetByName<HullData>("Skiff")), new EntitySettings());
|
||||
var gear = cache.GetByName<GearData>("Thruster");
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Reversed), new int2(2, 1)));
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.None), new int2(1, 2)));
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.None), new int2(3, 2)));
|
||||
// Strafe pairs sit either side of the centre line across the ship's length, so their torques oppose.
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.CounterClockwise), new int2(1, 1)));
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.CounterClockwise), new int2(1, 3)));
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Clockwise), new int2(3, 1)));
|
||||
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Clockwise), new int2(3, 3)));
|
||||
zone.Entities.Add(ship);
|
||||
ship.Aim = float3(0, 0, 1);
|
||||
ship.Activate();
|
||||
|
||||
var thrusters = ship.GetBehaviors<Thruster>().ToArray();
|
||||
return new Fixture
|
||||
{
|
||||
Cache = cache, Items = items, Ship = ship, Lock = cache.GetByName<ConsumableItemData>("Overdrive"),
|
||||
Forward = thrusters.Single(t => t.Item.EquippableItem.Rotation == ItemRotation.Reversed),
|
||||
Right = thrusters.Where(t => t.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise).ToArray(),
|
||||
Left = thrusters.Where(t => t.Item.EquippableItem.Rotation == ItemRotation.Clockwise).ToArray(),
|
||||
Reverse = thrusters.First(t => t.Item.EquippableItem.Rotation == ItemRotation.None && t.Torque <= 0),
|
||||
Clockwise = thrusters.First(t => t.Item.EquippableItem.Rotation == ItemRotation.None && t.Torque > 0)
|
||||
};
|
||||
}
|
||||
|
||||
// Spec ALockedThrottleIgnoresIntent. Mutation: read MovementDirection in place of move at any of the six
|
||||
// sites in Ship.Update and the matching assertion goes red.
|
||||
[Fact]
|
||||
public void ALockedThrottleIgnoresIntent()
|
||||
{
|
||||
var f = Build(100f);
|
||||
using var _ = f.Cache;
|
||||
f.ActivateLock();
|
||||
Assert.True(f.Ship.ThrottleLocked);
|
||||
|
||||
foreach (var intent in new[] { float2(0, -1), float2(1, 0), float2(-1, 0) })
|
||||
{
|
||||
f.Ship.MovementDirection = intent;
|
||||
f.Ship.Turn = 0;
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Forward.Axis);
|
||||
Assert.Equal(0f, f.Reverse.Axis);
|
||||
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
|
||||
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
|
||||
}
|
||||
|
||||
// Turning stays with the pilot: the clockwise-torque thruster follows Turn while the lock holds.
|
||||
f.Ship.MovementDirection = float2(0, -1);
|
||||
f.Ship.Turn = 1;
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Clockwise.Axis);
|
||||
f.Ship.Turn = 0;
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(0f, f.Clockwise.Axis);
|
||||
}
|
||||
|
||||
// Spec TheLockEndsWithItsEffect. Mutation: make ThrottleLocked a latch (set on activation, never cleared)
|
||||
// and the post-expiry reverse axis stays 0.
|
||||
[Fact]
|
||||
public void TheLockEndsWithItsEffect()
|
||||
{
|
||||
var f = Build(1f);
|
||||
using var _ = f.Cache;
|
||||
f.ActivateLock();
|
||||
f.Ship.MovementDirection = float2(0, -1);
|
||||
f.Ship.Update(0.5f);
|
||||
Assert.Equal(0f, f.Reverse.Axis);
|
||||
|
||||
f.Ship.Update(2f); // runs past the Duration; the effect leaves at the end of this tick
|
||||
Assert.False(f.Ship.ThrottleLocked);
|
||||
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Reverse.Axis);
|
||||
Assert.Equal(0f, f.Forward.Axis);
|
||||
}
|
||||
|
||||
// Spec AnUnlockedShipFollowsIntent. Mutation: replace the conditional by an unconditional float2(0, 1) and
|
||||
// the reverse and strafe assertions go red.
|
||||
[Fact]
|
||||
public void AnUnlockedShipFollowsIntent()
|
||||
{
|
||||
var f = Build(1f);
|
||||
using var _ = f.Cache;
|
||||
Assert.False(f.Ship.ThrottleLocked);
|
||||
|
||||
f.Ship.MovementDirection = float2(0, -1);
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Reverse.Axis);
|
||||
Assert.Equal(0f, f.Forward.Axis);
|
||||
|
||||
f.Ship.MovementDirection = float2(1, 0);
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.All(f.Right, t => Assert.Equal(1f, t.Axis));
|
||||
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
|
||||
Assert.Equal(0f, f.Forward.Axis);
|
||||
|
||||
f.Ship.MovementDirection = float2(-1, 0);
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.All(f.Left, t => Assert.Equal(1f, t.Axis));
|
||||
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
|
||||
|
||||
f.Ship.MovementDirection = float2(0, 1);
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Forward.Axis);
|
||||
Assert.Equal(0f, f.Reverse.Axis);
|
||||
}
|
||||
|
||||
// Finding zero-stick-unpinned. Mutation: float2(0, length(MovementDirection)) as the locked intent. The lock
|
||||
// supplies full forward whatever the stick's magnitude, including none and a short reverse push.
|
||||
[Fact]
|
||||
public void ALockedShipGetsFullForwardWhateverTheStickLength()
|
||||
{
|
||||
var f = Build(100f);
|
||||
using var _ = f.Cache;
|
||||
f.ActivateLock();
|
||||
foreach (var intent in new[] { float2(0, 0), float2(.3f, .2f), float2(-.5f, -.5f) })
|
||||
{
|
||||
f.Ship.MovementDirection = intent;
|
||||
f.Ship.Turn = 0;
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Forward.Axis);
|
||||
Assert.Equal(0f, f.Reverse.Axis);
|
||||
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
|
||||
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
|
||||
}
|
||||
}
|
||||
|
||||
// Finding ccw-turn-unpinned. Mutation: drop the counter-clockwise Turn. Turn in either sign reaches only the
|
||||
// thrusters with torque of that sign, at full, while the lock holds forward.
|
||||
[Fact]
|
||||
public void ALockedShipTurnsBothWays()
|
||||
{
|
||||
var f = Build(100f);
|
||||
using var _ = f.Cache;
|
||||
f.ActivateLock();
|
||||
var all = f.Ship.GetBehaviors<Thruster>().ToArray();
|
||||
var cw = all.Where(t => t.Torque > 0 && t.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
|
||||
var ccw = all.Where(t => t.Torque < 0 && t.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
|
||||
Assert.NotEmpty(cw);
|
||||
Assert.NotEmpty(ccw);
|
||||
f.Ship.MovementDirection = float2(1, -1);
|
||||
foreach (var turn in new[] { 1f, -1f })
|
||||
{
|
||||
f.Ship.Turn = turn;
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.All(turn > 0 ? cw : ccw, t => Assert.Equal(1f, t.Axis));
|
||||
Assert.All(turn > 0 ? ccw : cw, t => Assert.Equal(0f, t.Axis));
|
||||
Assert.Equal(1f, f.Forward.Axis);
|
||||
}
|
||||
}
|
||||
|
||||
// Finding non-lock-consumable-unpinned. Mutation: any active consumable locks. A consumable without
|
||||
// ThrottleLockData leaves the pilot's intent in force.
|
||||
[Fact]
|
||||
public void AConsumableWithoutTheLockDoesNotLock()
|
||||
{
|
||||
var f = Build(100f);
|
||||
using var _ = f.Cache;
|
||||
var plain = new ConsumableItemData { Name = "Plain", Duration = 100f };
|
||||
f.Cache.Upsert(plain);
|
||||
f.Ship.ActivateConsumable(new ConsumableItem
|
||||
{
|
||||
Data = f.Cache.RefOf<ItemData>(plain),
|
||||
Lot = f.Items.Lots.Add(new Lot { Design = f.Cache.RefOf<ItemData>(plain), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
|
||||
});
|
||||
Assert.False(f.Ship.ThrottleLocked);
|
||||
f.Ship.MovementDirection = float2(0, -1);
|
||||
f.Ship.Update(0.01f);
|
||||
Assert.Equal(1f, f.Reverse.Axis);
|
||||
Assert.Equal(0f, f.Forward.Axis);
|
||||
}
|
||||
|
||||
// Finding lock-end-boundary-unpinned, finding lock-end-at-90pct-unpinned. Mutations: the lock ends at half
|
||||
// Duration, at 0.8 or 0.9 of Duration, or one tick late. Duration 1 stepped in 0.25 s ticks (exact in
|
||||
// floats) locks the axes on exactly four ticks (reverse stays 0), the effect is gone when the fourth ends,
|
||||
// and the fifth tick follows the stick. The count scales with Duration: 2 s locks eight ticks.
|
||||
[Theory]
|
||||
[InlineData(1f, 4)]
|
||||
[InlineData(2f, 8)]
|
||||
public void TheLockEndsAtTheExactTickOfItsDuration(float duration, int lockedTicks)
|
||||
{
|
||||
var f = Build(duration);
|
||||
using var _ = f.Cache;
|
||||
f.ActivateLock();
|
||||
f.Ship.MovementDirection = float2(0, -1);
|
||||
for (var i = 0; i < lockedTicks; i++)
|
||||
{
|
||||
Assert.True(f.Ship.ThrottleLocked);
|
||||
f.Ship.Update(.25f);
|
||||
Assert.Equal(0f, f.Reverse.Axis);
|
||||
Assert.Equal(1f, f.Forward.Axis);
|
||||
}
|
||||
Assert.False(f.Ship.ThrottleLocked);
|
||||
f.Ship.Update(.25f);
|
||||
Assert.Equal(1f, f.Reverse.Axis);
|
||||
Assert.Equal(0f, f.Forward.Axis);
|
||||
}
|
||||
}
|
||||
431
tests/Aetheria.Shared.Tests/VapourCloudTests.cs
Normal file
431
tests/Aetheria.Shared.Tests/VapourCloudTests.cs
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using UniRx;
|
||||
using Xunit;
|
||||
using static CultMath.math;
|
||||
using float2 = CultMath.float2;
|
||||
using float3 = CultMath.float3;
|
||||
using int2 = CultMath.int2;
|
||||
|
||||
// Vapour clouds in the sim (aetheria-release cut vapour-cloud, ruling vapour-cloud-obscuration): a VapourDump
|
||||
// behaviour vents a zone cloud that thins every sensor sight line through it, both ways, through Sensor.Gain's
|
||||
// one detection rule; a lock falls by the existing detection-threshold rule and nothing else. The scene is two
|
||||
// ships facing each other along z with a fixed visibility, so what a sensor gathers is a number the clouds
|
||||
// alone change: steady info is visibility x sensitivity / (distance x TargetInfoDecay), and visibility 100,
|
||||
// sensitivity 1, decay .5 puts it at .5 at range 400 (above the .1 threshold) and saturated at range 40.
|
||||
public sealed class VapourCloudTests : IDisposable
|
||||
{
|
||||
private const float Dt = .05f;
|
||||
private const float Threshold = .1f;
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-vapour-" + Guid.NewGuid().ToString("N"));
|
||||
private readonly List<CultCache> _caches = new List<CultCache>();
|
||||
private static readonly object Glow = new object();
|
||||
|
||||
public VapourCloudTests() => 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 Ship Observer;
|
||||
public Ship Target;
|
||||
public EquippedItem Dump;
|
||||
public LockWeapon Lock;
|
||||
public int Lot = 1;
|
||||
public bool HoldTarget = true;
|
||||
}
|
||||
|
||||
private Lab Build(float distance, float radius = 20f, float opacity = .9f, float lifetime = 1000f)
|
||||
{
|
||||
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 = Threshold, TargetArmorInfoThreshold = .2f, TargetGearInfoThreshold = .8f,
|
||||
TargetInfoDecay = .5f, VisibilityDecay = 0f,
|
||||
FiringArc = 170, CommitHorizon = .5f, SchematicCellSize = 1f
|
||||
};
|
||||
var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
|
||||
_caches.Add(cache);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
cache.Upsert(new HullData
|
||||
{
|
||||
Name = "Hull", HullType = HullType.Ship, Shape = Solid(5, 5), Durability = 1000000, Mass = 1000,
|
||||
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } }
|
||||
});
|
||||
GearData Gear(string name, HardpointType hardpoint, BehaviorData behavior) => new GearData
|
||||
{
|
||||
Name = name, Hardpoint = hardpoint, Shape = new Shape(), Durability = 1,
|
||||
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
|
||||
Behaviors = { behavior }
|
||||
};
|
||||
cache.Upsert(Gear("Eye", HardpointType.Tool, new SensorData
|
||||
{
|
||||
Sensitivity = Constant(1f),
|
||||
SensitivityCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } },
|
||||
PingBoost = Constant(.000004f), PingEnergy = Constant(0f), PingVisibility = Constant(5f),
|
||||
PingRange = Constant(300f), PingCooldown = Constant(4f)
|
||||
}));
|
||||
cache.Upsert(Gear("Vent", HardpointType.Tool, new VapourDumpData
|
||||
{
|
||||
Radius = Constant(radius), Opacity = Constant(opacity), Lifetime = Constant(lifetime)
|
||||
}));
|
||||
cache.Upsert(Gear("LockGun", HardpointType.Sensors, new LockWeaponData
|
||||
{
|
||||
Damage = Constant(0), Range = Constant(1000), MinRange = Constant(0), Velocity = Constant(0),
|
||||
Spread = Constant(0), 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) } },
|
||||
LockSpeed = Constant(1), SensorImpact = Constant(1), LockAngle = Constant(170),
|
||||
DirectionImpact = Constant(1), Decay = Constant(1)
|
||||
}));
|
||||
cache.FlushAsync().Wait();
|
||||
|
||||
var ledger = new ProvenanceLedger();
|
||||
for (var i = 1; i <= 50; 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 = 5000 }, new GalaxyZone { Name = "Vapour", Owner = null }, null);
|
||||
var lab = new Lab { Items = items, Zone = zone };
|
||||
|
||||
EquippableItem Make(string name) => new EquippableItem
|
||||
{
|
||||
Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>(name)), Durability = 1, Lot = lab.Lot++
|
||||
};
|
||||
Ship NewShip()
|
||||
{
|
||||
var hull = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("Hull"));
|
||||
var ship = new Ship(items, zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, new EntitySettings());
|
||||
Assert.True(ship.TryEquip(Make("Eye")));
|
||||
return ship;
|
||||
}
|
||||
|
||||
lab.Observer = NewShip();
|
||||
Assert.True(lab.Observer.TryEquip(Make("LockGun"), new int2(0, 0)));
|
||||
lab.Target = NewShip();
|
||||
var dump = Make("Vent");
|
||||
Assert.True(lab.Target.TryEquip(dump));
|
||||
lab.Dump = lab.Target.Equipment.Single(x => x.EquippableItem == dump);
|
||||
// Held off until a test pulls the trigger: the dump vents on its first run.
|
||||
lab.Dump.Enabled.Value = false;
|
||||
|
||||
zone.Entities.Add(lab.Observer);
|
||||
zone.Entities.Add(lab.Target);
|
||||
lab.Observer.Activate();
|
||||
lab.Target.Activate();
|
||||
lab.Observer.Position = float3(0, 0, 0);
|
||||
lab.Observer.Aim = float3(0, 0, 1);
|
||||
lab.Target.Position = float3(0, 0, distance);
|
||||
lab.Target.Aim = float3(0, 0, -1);
|
||||
lab.Observer.SetIff(lab.Target, true);
|
||||
lab.Target.SetIff(lab.Observer, true);
|
||||
zone.Update(0f);
|
||||
lab.Lock = lab.Observer.Weapons.OfType<LockWeapon>().Single();
|
||||
return lab;
|
||||
}
|
||||
|
||||
// One tick: both ships stay where they were put, facing each other, each a fixed visibility to the other's sensor.
|
||||
private static void Tick(Lab lab)
|
||||
{
|
||||
foreach (var ship in new[] { lab.Observer, lab.Target })
|
||||
{
|
||||
ship.VisibilitySources[Glow] = 100f;
|
||||
if (ship != lab.Target || lab.HoldTarget) ship.Velocity = float2.zero;
|
||||
}
|
||||
lab.Observer.Direction = float2(0, 1);
|
||||
lab.Target.Direction = float2(0, -1);
|
||||
lab.Zone.Update(Dt);
|
||||
}
|
||||
|
||||
private static void Run(Lab lab, int ticks)
|
||||
{
|
||||
for (var i = 0; i < ticks; i++) Tick(lab);
|
||||
}
|
||||
|
||||
private static float Info(Ship watcher, Ship watched) => watcher.EntityInfoGathered[watched];
|
||||
|
||||
// The observer has settled on the target and holds a full lock on it: the state a cloud has to break.
|
||||
private static void Establish(Lab lab)
|
||||
{
|
||||
Run(lab, 100);
|
||||
Assert.True(Info(lab.Observer, lab.Target) > Threshold, "the observer never gathered the target");
|
||||
Assert.Contains(lab.Target, lab.Observer.VisibleEnemies);
|
||||
lab.Observer.SetTarget(lab.Target);
|
||||
Run(lab, 100);
|
||||
Assert.True(lab.Lock.IsLocked, "the observer never locked the target");
|
||||
Assert.Empty(lab.Zone.Clouds);
|
||||
}
|
||||
|
||||
private static void Vent(Lab lab)
|
||||
{
|
||||
lab.Dump.Enabled.Value = true;
|
||||
for (var i = 0; i < 5 && lab.Zone.Clouds.Count == 0; i++) Tick(lab);
|
||||
Assert.Single(lab.Zone.Clouds);
|
||||
}
|
||||
|
||||
private static VapourCloud Hand(Zone zone, float2 at, float radius, float opacity, float lifetime = 1000f)
|
||||
{
|
||||
var cloud = new VapourCloud { Body = new KinematicBody { Position = at }, Radius = radius, Opacity = opacity, Lifetime = lifetime };
|
||||
zone.Vent(cloud);
|
||||
return cloud;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACloudBreaksALockAtRange()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
Establish(lab);
|
||||
|
||||
Vent(lab);
|
||||
var ticks = 0;
|
||||
while (ticks++ < 600 && !lab.Observer.Target.Value.IsNone) Tick(lab);
|
||||
|
||||
Assert.True(lab.Observer.Target.Value.IsNone, "the cloud never broke the target");
|
||||
Assert.True(Info(lab.Observer, lab.Target) < Threshold, $"info {Info(lab.Observer, lab.Target)} is above the threshold");
|
||||
Run(lab, 3);
|
||||
Assert.Equal(0f, lab.Lock.Lock);
|
||||
Assert.DoesNotContain(lab.Target, lab.Observer.VisibleEnemies);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AStrongCloseSensorBurnsThrough()
|
||||
{
|
||||
var lab = Build(40f);
|
||||
Establish(lab);
|
||||
var before = Info(lab.Observer, lab.Target);
|
||||
|
||||
Vent(lab);
|
||||
Run(lab, 600);
|
||||
|
||||
var after = Info(lab.Observer, lab.Target);
|
||||
Assert.True(after < before - .2f, $"the cloud thinned nothing: {before} -> {after}");
|
||||
Assert.True(after > Threshold, $"info {after} fell below the threshold");
|
||||
Assert.Equal(lab.Target, lab.Observer.Target.Value.Entity);
|
||||
Assert.True(lab.Lock.IsLocked);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheCloudBlindsItsVenter()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
Run(lab, 100);
|
||||
Assert.True(Info(lab.Target, lab.Observer) > Threshold, "the venter never gathered the observer");
|
||||
Assert.Contains(lab.Observer, lab.Target.VisibleEnemies);
|
||||
|
||||
Vent(lab);
|
||||
Run(lab, 300);
|
||||
|
||||
Assert.True(Info(lab.Target, lab.Observer) < Threshold);
|
||||
Assert.DoesNotContain(lab.Observer, lab.Target.VisibleEnemies);
|
||||
// (The observer updates before the venter in the tick that vents, so it is one tick behind.)
|
||||
Assert.Equal(Info(lab.Observer, lab.Target), Info(lab.Target, lab.Observer), 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACloudFadesAndIsRemoved()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
// Vented 3s into the zone's life: the fade runs from the vent, not from the zone's start.
|
||||
for (var i = 0; i < 3; i++) lab.Zone.Update(1f);
|
||||
var cloud = Hand(lab.Zone, float2(0, 0), 10f, .8f, lifetime: 10f);
|
||||
var a = float2(-5, 0);
|
||||
var b = float2(5, 0);
|
||||
Assert.Equal(.2f, lab.Zone.Obscuration(a, b), 5);
|
||||
|
||||
for (var i = 0; i < 5; i++) lab.Zone.Update(1f);
|
||||
Assert.Equal(.4f, cloud.OpacityAt(lab.Zone.Time), 5);
|
||||
Assert.Equal(.6f, lab.Zone.Obscuration(a, b), 5);
|
||||
Assert.Single(lab.Zone.Clouds);
|
||||
|
||||
for (var i = 0; i < 5; i++) lab.Zone.Update(1f);
|
||||
Assert.Empty(lab.Zone.Clouds);
|
||||
Assert.Equal(1f, lab.Zone.Obscuration(a, b));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACloudDriftsWithItsVelocityUntilItFades()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
var cloud = new VapourCloud { Body = new KinematicBody { Position = float2(0, 0), Velocity = float2(10, 0) }, Radius = 5f, Opacity = .5f, Lifetime = 1000f };
|
||||
lab.Zone.Vent(cloud);
|
||||
Assert.Equal(.5f, lab.Zone.Obscuration(float2(0, -20), float2(0, 20)), 5);
|
||||
|
||||
lab.Zone.Update(1f);
|
||||
|
||||
// The launch velocity decays on the zone's launch drag, so it has moved most of the way and no further.
|
||||
Assert.InRange(cloud.Body.Position.x, 5f, 9.9f);
|
||||
Assert.Equal(1f, lab.Zone.Obscuration(float2(0, -20), float2(0, 20)));
|
||||
Assert.Equal(.5f, lab.Zone.Obscuration(float2(cloud.Body.Position.x, -20), float2(cloud.Body.Position.x, 20)), 2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACloudWithNoLifetimeObscuresNothing()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
var cloud = Hand(lab.Zone, float2(0, 0), 10f, .8f, lifetime: 0f);
|
||||
Assert.Equal(0f, cloud.OpacityAt(lab.Zone.Time));
|
||||
Assert.Equal(1f, lab.Zone.Obscuration(float2(-5, 0), float2(5, 0)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AnEffectVentsOnce()
|
||||
{
|
||||
var lab = Build(400f, radius: 17f, opacity: .7f, lifetime: 123f);
|
||||
lab.HoldTarget = false;
|
||||
Run(lab, 2);
|
||||
lab.Target.Velocity = float2(3, 0);
|
||||
VapourCloud vented = null;
|
||||
float2 venterVelocity = float2.zero;
|
||||
float2 venterAt = float2.zero;
|
||||
float2 cloudVelocity = float2.zero;
|
||||
float2 cloudAt = float2.zero;
|
||||
using var sub = lab.Zone.Clouds.ObserveAdd().Subscribe(add =>
|
||||
{
|
||||
vented = add.Value;
|
||||
cloudVelocity = add.Value.Body.Velocity;
|
||||
cloudAt = add.Value.Body.Position;
|
||||
venterVelocity = lab.Target.Velocity;
|
||||
venterAt = lab.Target.Position.xz;
|
||||
});
|
||||
|
||||
lab.Dump.Enabled.Value = true;
|
||||
Run(lab, 100);
|
||||
|
||||
Assert.Single(lab.Zone.Clouds);
|
||||
Assert.Same(vented, lab.Zone.Clouds.Single());
|
||||
Assert.True(length(venterVelocity) > 0f, "the venter was not moving");
|
||||
Assert.Equal(venterVelocity, cloudVelocity);
|
||||
Assert.Equal(venterAt, cloudAt);
|
||||
Assert.Same(lab.Target, vented.Venter);
|
||||
// Each stat is the authored one, evaluated through the host.
|
||||
Assert.Equal(17f, vented.Radius);
|
||||
Assert.Equal(.7f, vented.Opacity);
|
||||
Assert.Equal(123f, vented.Lifetime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ACloudThinsOnlyTheSightLinesItTouches()
|
||||
{
|
||||
var lab = Build(400f);
|
||||
var first = Hand(lab.Zone, float2(0, 0), 10f, .6f);
|
||||
float Through(float2 a, float2 b) => lab.Zone.Obscuration(a, b);
|
||||
|
||||
Assert.Equal(.4f, Through(float2(-50, 0), float2(50, 0)), 5);
|
||||
Assert.Equal(.4f, Through(float2(50, 0), float2(-50, 0)), 5);
|
||||
// Passing wide of the centre but within the radius, neither end inside the disc.
|
||||
Assert.Equal(.4f, Through(float2(-50, 9.9f), float2(50, 9.9f)), 5);
|
||||
Assert.Equal(1f, Through(float2(-50, 10.1f), float2(50, 10.1f)));
|
||||
// Ending inside the disc, and a point inside it (the observer inside its own cloud).
|
||||
Assert.Equal(.4f, Through(float2(-50, 0), float2(5, 0)), 5);
|
||||
Assert.Equal(.4f, Through(float2(3, 0), float2(3, 0)), 5);
|
||||
Assert.Equal(1f, Through(float2(30, 0), float2(30, 0)));
|
||||
// A segment that stops short of the disc, or starts past it, touches nothing even on the same line.
|
||||
Assert.Equal(1f, Through(float2(-50, 0), float2(-20, 0)));
|
||||
Assert.Equal(1f, Through(float2(20, 0), float2(50, 0)));
|
||||
|
||||
// Two clouds on one sight line multiply.
|
||||
var second = Hand(lab.Zone, float2(30, 0), 5f, .5f);
|
||||
Assert.NotEqual(first.Id, second.Id);
|
||||
Assert.Equal(.2f, Through(float2(-50, 0), float2(50, 0)), 5);
|
||||
Assert.Equal(.4f, Through(float2(-50, 0), float2(15, 0)), 5);
|
||||
}
|
||||
|
||||
// Where the rule is decided: once the start-up seed has decayed away, the info a sensor settles at is what
|
||||
// survives the cloud times what the open sight line settles at, in both directions.
|
||||
[Fact]
|
||||
public void TheGainIsScaledByWhatSurvivesTheCloud()
|
||||
{
|
||||
var clear = Build(400f);
|
||||
var cloudy = Build(400f);
|
||||
// Mid-way between them and clear of both: only the segment, not either end, touches it.
|
||||
Hand(cloudy.Zone, float2(0, 200), 10f, .6f, lifetime: 1e6f);
|
||||
Run(clear, 400);
|
||||
Run(cloudy, 400);
|
||||
|
||||
Assert.True(Info(clear.Observer, clear.Target) > Threshold);
|
||||
Assert.Equal(.4f, Info(cloudy.Observer, cloudy.Target) / Info(clear.Observer, clear.Target), 2);
|
||||
Assert.Equal(.4f, Info(cloudy.Target, cloudy.Observer) / Info(clear.Target, clear.Observer), 2);
|
||||
}
|
||||
|
||||
// A ping is gathered through the same rule. Settled, the tick that a ping reaches the target adds the ping gain
|
||||
// in place of the passive one; that extra, in a lab with a cloud on the sight line, is what survives the
|
||||
// cloud times the extra in the open (info is linear in the gain while nothing saturates).
|
||||
[Fact]
|
||||
public void ThePingGainIsScaledToo()
|
||||
{
|
||||
float PingExtra(Lab lab)
|
||||
{
|
||||
Run(lab, 400);
|
||||
lab.Observer.Sensor.Ping();
|
||||
var biggest = 0f;
|
||||
var last = Info(lab.Observer, lab.Target);
|
||||
for (var i = 0; i < 38; i++)
|
||||
{
|
||||
Tick(lab);
|
||||
biggest = max(biggest, Info(lab.Observer, lab.Target) - last);
|
||||
last = Info(lab.Observer, lab.Target);
|
||||
}
|
||||
return biggest;
|
||||
}
|
||||
|
||||
var clear = Build(250f);
|
||||
var cloudy = Build(250f);
|
||||
Hand(cloudy.Zone, float2(0, 125), 10f, .6f, lifetime: 1e6f);
|
||||
|
||||
var open = PingExtra(clear);
|
||||
Assert.True(open > .05f, $"the ping left no mark on the open trace ({open})");
|
||||
Assert.Equal(.4f, PingExtra(cloudy) / open, 2);
|
||||
}
|
||||
|
||||
// The chunk path reads the same rule: the passive rate toward a point is scaled by the same survivor fraction.
|
||||
[Fact]
|
||||
public void TheChunkRateIsScaledByTheSameFactor()
|
||||
{
|
||||
var lab = Build(100f);
|
||||
var at = float2(0, 100);
|
||||
var open = lab.Observer.Sensor.PassiveRate(100f, at);
|
||||
Assert.True(open > 0f);
|
||||
|
||||
Hand(lab.Zone, float2(0, 50), 10f, .6f);
|
||||
Assert.Equal(.4f, lab.Observer.Sensor.PassiveRate(100f, at) / open, 5);
|
||||
}
|
||||
|
||||
// The dump's wire shape: BehaviorData union 42, its radius, opacity and lifetime at keys 1, 2 and 3.
|
||||
[Fact]
|
||||
public void TheDumpIsUnion42WithRadiusOpacityLifetimeAtKeys1To3()
|
||||
{
|
||||
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly);
|
||||
var data = new VapourDumpData { Radius = Constant(1f), Opacity = Constant(2f), Lifetime = Constant(3f) };
|
||||
var bytes = MessagePackSerializer.Serialize<BehaviorData>(data, options);
|
||||
|
||||
var reader = new MessagePackReader(bytes);
|
||||
Assert.Equal(2, reader.ReadArrayHeader());
|
||||
Assert.Equal(42, reader.ReadInt32());
|
||||
Assert.Equal(4, reader.ReadArrayHeader());
|
||||
reader.Skip();
|
||||
Assert.Equal(1f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
|
||||
Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
|
||||
Assert.Equal(3f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue