diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 95cf4dd6b..2bccf5f1e 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -191,6 +191,7 @@ public interface IPowerConsumer Union(47, typeof(MunitionFuelData)), Union(48, typeof(PickupData)), Union(49, typeof(LaunchSuppressorData)), + Union(50, typeof(ListenerData)), JsonObject(MemberSerialization.OptIn)] public abstract class BehaviorData { diff --git a/Assets/Scripts/ServerShared/Behaviors/Listener.cs b/Assets/Scripts/ServerShared/Behaviors/Listener.cs new file mode 100644 index 000000000..beb622741 --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Listener.cs @@ -0,0 +1,44 @@ +/* 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 MessagePack; +using Newtonsoft.Json; + +// Passive listening gear (ruling sensor-stat-set): hears other ships' emissions at a multiple of their own range, +// bearing only. It emits nothing; Entity.HearingMultiple asks each active listener at hearing time. Its power is the +// design's EnergyDraw and its activity is the item's Active, as for sensors. +[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable] +public class ListenerData : BehaviorData +{ + // How many times an emitter's own reach this listener hears it at. + [Inspectable, JsonProperty("multiple"), Key(1), RuntimeInspectable] + public PerformanceStat Multiple = new PerformanceStat(); + + public override Behavior CreateInstance(EquippedItem item) + { + return new Listener(this, item); + } + public override Behavior CreateInstance(ConsumableItemEffect item) + { + return new Listener(this, item); + } +} + +public class Listener : Behavior +{ + private readonly ListenerData _data; + + public Listener(ListenerData data, EquippedItem item) : base(data, item) + { + _data = data; + } + public Listener(ListenerData data, ConsumableItemEffect item) : base(data, item) + { + _data = data; + } + + public float Multiple => Evaluate(_data.Multiple); + + public override bool Execute(float dt) => true; +} diff --git a/Assets/Scripts/ServerShared/Behaviors/Listener.cs.meta b/Assets/Scripts/ServerShared/Behaviors/Listener.cs.meta new file mode 100644 index 000000000..be694c775 --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Listener.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5b0e1f6c2d7a4e39a8c4d1f27e6b3a90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/Entity.cs b/Assets/Scripts/ServerShared/Entity.cs index 3ece06ec7..f256ec03b 100644 --- a/Assets/Scripts/ServerShared/Entity.cs +++ b/Assets/Scripts/ServerShared/Entity.cs @@ -694,8 +694,23 @@ public abstract class Entity } // How much of an emission's reach this observer's instruments hear it at (ruling sensor-stat-set: listeners hear at - // a multiple of an emitter's own range): 1 with an active sensor, 0 without. Listener gear extends it. - private int HearingMultiple() => ActiveSensors().Count > 0 ? 1 : 0; + // a multiple of an emitter's own range): the largest of 1 (any active sensor) and each active listener's Multiple, + // 0 with neither. Catalog values come from AetherDb sensor-stat-set. + private float HearingMultiple() + { + var multiple = ActiveSensors().Count > 0 ? 1f : 0f; + for (var i = 0; i < Equipment.Count; i++) + { + var item = Equipment[i]; + if (!item.Active.Value) continue; + foreach (var behavior in item.Behaviors) + if (behavior is Listener listener) multiple = max(multiple, listener.Multiple); + } + foreach (var effect in _activeConsumables) + foreach (var behavior in effect.Behaviors) + if (behavior is Listener listener) multiple = max(multiple, listener.Multiple); + return multiple; + } // Cut 12.3 (docs/fire-control-cut.md): "armour absorbs first" -- the per-cell armour phase, split out of // what used to be Absorb's own first half (moved verbatim from DamageSchematic's per-cell body, Cut 3) so diff --git a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs index ba5029101..387668d75 100644 --- a/tests/Aetheria.Shared.Tests/ContactRevealTests.cs +++ b/tests/Aetheria.Shared.Tests/ContactRevealTests.cs @@ -59,6 +59,7 @@ public sealed partial class ContactRevealTests : IDisposable // PingRange (300) over the intercept factor. cache.Upsert(Eye("Shout", sensitivity: 2f, interceptFactor: 2f, beamWidth: 10f)); cache.Upsert(Eye("Roar", sensitivity: 2f, interceptFactor: .5f, beamWidth: 10f)); + cache.Upsert(Listener("Listener", 3f)); cache.Upsert(Tool("Reactor", new ReactorData { Charge = Const(1000), Efficiency = Const(1), OverloadEfficiency = Const(1), ThrottlingFactor = Const(2) })); cache.Upsert(Tool("Targeting", new TargetingSystemData { Accuracy = Const(1), Resolution = Const(1000f), Precision = Const(1000f), Tracking = Const(1000000f) })); cache.Upsert(Tool("Thruster", new ThrusterData { Thrust = Const(100), Visibility = Const(10), Heat = Const(0), EnergyUsage = Const(10) })); diff --git a/tests/Aetheria.Shared.Tests/ListenerTests.cs b/tests/Aetheria.Shared.Tests/ListenerTests.cs new file mode 100644 index 000000000..f426318ee --- /dev/null +++ b/tests/Aetheria.Shared.Tests/ListenerTests.cs @@ -0,0 +1,97 @@ +using System.Linq; +using CultMath; +using GameCult.Caching.MessagePack; +using MessagePack; +using Xunit; +using static CultMath.math; +using float3 = CultMath.float3; + +// Passive listening gear (ruling sensor-stat-set): an observer with a listener hears an emission at the emitter's own +// range times the listener's Multiple, bearing only. The pinger is the fixture's "Eye" (PingRange 300, intercept +// factor absent so 1), so a sensor hears it at 300 and the "Listener" (Multiple 3) at 900. Every fixture drives the +// production path: Sensor.Execute posts through Entity.Emit and Sense hears, ticking inside Zone.Update. +public sealed partial class ContactRevealTests +{ + private static GearData Listener(string name, float multiple) + { + var cell = new Shape(1, 1); + cell[new int2(0, 0)] = true; + return new GearData + { + Name = name, Hardpoint = HardpointType.Tool, Shape = cell, Durability = 10, + MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000, + Behaviors = { new ListenerData { Multiple = Const(multiple) } } + }; + } + + // ---- AListenerHearsAtItsMultiple ---- + + [Theory] + [InlineData(899f, true)] + [InlineData(901f, false)] + public void AListenerHearsAtItsMultiple(float distance, bool heard) + { + var p = Add(float3(0, 0, 0), new[] { "Eye" }); + var ear = Add(float3(distance, 0, 0), tools: new[] { "Listener" }); + + var at = PingAt(p); + + if (!heard) { Assert.Empty(ear.RevealsOf(p)); return; } + var reveal = Assert.Single(ear.RevealsOf(p)); + Assert.Equal(SignatureChannel.Emission, reveal.Channel); + Assert.Equal(at, reveal.Time); + AssertBearing(-1f, 0f, reveal.Bearing); // normalize((P - ear).xz) + Assert.Equal(0f, Track(ear, p)); // bearing only: it builds no track + } + + // ---- AListenerAndASensorTakeTheLarger ---- + + [Theory] + [InlineData(true, 899f, true)] + [InlineData(true, 901f, false)] + [InlineData(false, 299f, true)] + [InlineData(false, 301f, false)] + public void AListenerAndASensorTakeTheLarger(bool listenerActive, float distance, bool heard) + { + var p = Add(float3(0, 0, 0), new[] { "Eye" }); + var both = Add(float3(distance, 0, 0), new[] { "Eye" }, new[] { "Listener" }); // a sum would hear at 1200 + var listener = both.Equipment.Single(i => i.Behaviors.Any(b => b is Listener)); + listener.Enabled.Value = listenerActive; + + PingAt(p); + + Assert.Equal(heard ? 1 : 0, both.RevealsOf(p).Count()); + } + + // ---- AnInactiveListenerHearsNothing ---- + + [Fact] + public void AnInactiveListenerHearsNothing() + { + var p = Add(float3(0, 0, 0), new[] { "Eye" }); + var ear = Add(float3(100, 0, 0), tools: new[] { "Listener" }); + ear.Equipment.Single(i => i.Behaviors.Any(b => b is Listener)).Enabled.Value = false; + + PingAt(p); + + Assert.Empty(ear.RevealsOf(p)); + } + + // ---- ListenerDataRoundTripsAsUnionKey50 ---- + + [Fact] + public void ListenerDataRoundTripsAsUnionKey50() + { + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly); + var data = new ListenerData { Multiple = Const(2.5f) }; + + var bytes = MessagePackSerializer.Serialize(data, options); + var reader = new MessagePackReader(bytes); + Assert.Equal(2, reader.ReadArrayHeader()); + Assert.Equal(50, reader.ReadInt32()); + Assert.Equal(2, reader.ReadArrayHeader()); // Group is key 0, then Multiple + + var back = Assert.IsType(MessagePackSerializer.Deserialize(bytes, options)); + Assert.Equal(2.5f, back.Multiple.Min); + } +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index fec27f55f..d292869bf 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -50,8 +50,9 @@ public static class Program Console.OutputEncoding = new System.Text.UTF8Encoding(false); return PiratesFaction(args.Contains("apply")); case "verse-grammar": return VerseGrammarCommand.Run(args.Contains("apply")); + case "sensor-stat-set": return SensorStatSet(args.Contains("apply")); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, field-kinds [apply], mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], pirates-faction [apply], verse-grammar [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, field-kinds [apply], mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], pirates-faction [apply], verse-grammar [apply], sensor-stat-set [apply]"); return 1; } } @@ -207,7 +208,7 @@ public static class Program { ["Sensitivity"] = "receiver", ["PingBoost"] = "emitter", ["PingEnergy"] = "emitter", ["PingRange"] = "emitter", - ["PingCooldown"] = "emitter", + ["PingCooldown"] = "emitter", ["InterceptFactor"] = "emission-discipline", }; private static readonly Dictionary ThrusterRoles = new Dictionary @@ -237,6 +238,7 @@ public static class Program { ["Capacity"] = "storage cell", ["Efficiency"] = "converter", }, + ["Passive Array"] = new Dictionary { ["Multiple"] = "receiver" }, }; // One Mean / StandardDeviation per maker, applied to every role of a design the maker sells (catalog-growth @@ -1612,6 +1614,138 @@ public static class Program return 0; } + private const string EmissionDiscipline = "emission-discipline"; + + // The intercept factor alpha is how far others hear a sensor against how far it sees: a quality-ranged stat from + // .5 (loud) to 2 (quiet) whose midpoint quality .5 reads 1, so lerp(Min, Max, q^e) with e = log2(3). Brand flavour + // lives in the product's emission-discipline quality (ruling sensor-stat-set): Lucent is low, Finch and Sol high, + // every other maker middling. A maker with no profile of its own (the Pirates) takes the Pirate deviation. + private static float DisciplineMean(Faction maker) => + maker.ShortName == "Lucent" ? .2f : maker.ShortName == "Finch" || maker.ShortName == "Sol" || maker.Name == "Sol" ? .8f : .5f; + + private static float MakerDeviation(Faction maker) => + MakerProfiles.TryGetValue(maker.ShortName ?? "", out var profile) ? profile.Dev : PirateProfile.Dev; + + // aetheria-release cut sensor-catalog (rulings sensor-stat-set, catalog-grows-generic-designs-branded-products): every + // SensorData design's InterceptFactor becomes a quality-ranged stat reading the emission-discipline role, every + // product of such a design authors that role, and the Passive Array (a generic listener gear, ListenerData) is + // authored with two products from the stealth makers. Prints the sensor census first. Dry run unless passed + // "apply"; idempotent, so a second apply writes nothing and a catalog another cut changed is rerun, never merged. + private static int SensorStatSet(bool apply) + { + var db = AetherDb.Open(catalogWritable: apply); + var designs = db.Cache.GetAll().ToArray(); + var products = db.Cache.GetAll().ToArray(); + Faction MakerOf(FactionProductData p) => db.Cache.Get(p.Manufacturer); + Faction Maker(string shortName) => + db.Cache.GetAll().FirstOrDefault(f => f.ShortName == shortName) ?? throw new InvalidOperationException($"No faction with short name \"{shortName}\"."); + + var sensors = designs.Where(d => d.Behaviors != null && d.Behaviors.OfType().Any()).OrderBy(d => d.Name, StringComparer.Ordinal).ToArray(); + var listeners = designs.Where(d => d.Behaviors != null && d.Behaviors.OfType().Any()).OrderBy(d => d.Name, StringComparer.Ordinal).ToArray(); + Console.WriteLine($"Census: {sensors.Length} sensor designs, {listeners.Length} listener designs."); + foreach (var design in sensors.Concat(listeners)) + { + var key = db.Cache.RefOf(design).Key; + Console.WriteLine($" {design.Name} [{design.HardpointType}] roles [{string.Join(", ", (design.Roles ?? new List()).Select(r => r.Name))}]"); + foreach (var product in products.Where(p => p.Design.Key.Equals(key)).OrderBy(p => p.Name, StringComparer.Ordinal)) + Console.WriteLine($" {product.Name} by {MakerOf(product)?.ShortName ?? "(none)"}: " + string.Join(", ", (product.Roles ?? new List()).Select(r => $"{r.Role} {r.Mean:0.00}±{r.StandardDeviation:0.00}"))); + } + foreach (var consumable in db.Cache.GetAll().Where(c => c.Behaviors != null && c.Behaviors.OfType().Any()).OrderBy(c => c.Name, StringComparer.Ordinal)) + Console.WriteLine($" consumable {consumable.Name} carries SensorData; consumables are not catalog sensor designs and keep their alpha"); + + var changedDesigns = new List<(object Document, CultRecordKey Key)>(); + var changedProducts = new List<(object Document, CultRecordKey Key)>(); + var exponent = MathF.Log2(3f); + foreach (var design in sensors) + { + var key = db.Cache.RefOf(design).Key; + var designChanged = false; + foreach (var sensor in design.Behaviors.OfType()) + { + var stat = sensor.InterceptFactor; + var current = stat != null && stat.Min == .5f && stat.Max == 2f && stat.Terms != null && stat.Terms.Count == 1 + && stat.Terms[0].Source == StatSource.Quality && stat.Terms[0].Role == EmissionDiscipline && stat.Terms[0].Exponent == exponent; + if (current) continue; + sensor.InterceptFactor = new PerformanceStat { Min = .5f, Max = 2f, Terms = new List { new StatTerm { Source = StatSource.Quality, Exponent = exponent, Role = EmissionDiscipline } } }; + designChanged = true; + } + design.Roles ??= new List(); + if (!design.Roles.Any(r => r.Name == EmissionDiscipline)) { design.Roles.Add(new ItemRole { Name = EmissionDiscipline }); designChanged = true; } + if (designChanged) changedDesigns.Add((design, key)); + foreach (var product in products.Where(p => p.Design.Key.Equals(key))) + { + var maker = MakerOf(product) ?? throw new InvalidOperationException($"Product \"{product.Name}\" has no maker."); + product.Roles ??= new List(); + var mean = DisciplineMean(maker); + var dev = MakerDeviation(maker); + var existing = product.Roles.FirstOrDefault(r => r.Role == EmissionDiscipline); + if (existing != null && existing.Mean == mean && existing.StandardDeviation == dev) continue; + if (existing != null) { existing.Mean = mean; existing.StandardDeviation = dev; } + else product.Roles.Add(new ProductRole { Role = EmissionDiscipline, Mean = mean, StandardDeviation = dev }); + changedProducts.Add((product, db.Cache.RefOf(product).Key)); + } + } + + // The Passive Array takes its thermal envelope and sound from a sensor gear, then becomes a Tool listener. + GearData array = null; + var arrayProducts = new List<(string Name, string Maker, string Description)>(); + if (listeners.Length == 0) + { + var template = sensors.OfType().FirstOrDefault() ?? throw new InvalidOperationException("No sensor gear to take the Passive Array's thermal envelope from."); + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(GearData).Assembly); + array = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(template, options), options); + array.Name = "Passive Array"; + array.Description = "Listens for what others shout. Hears every emitter at a multiple of its own reach, on a bearing only, and never says a word itself."; + array.Hardpoint = HardpointType.Tool; + array.Mass = 20f; array.Price = 60000; array.Durability = 30f; + array.Shape = new Shape(1, 1); + array.Shape.Cells[0, 0] = true; + array.Behaviors = new List + { + new EnergyDrawData { EnergyDraw = new PerformanceStat { Min = 10f, Max = 10f, Terms = new List() }, PerSecond = true }, + new ListenerData { Multiple = new PerformanceStat { Min = 2f, Max = 3f, Terms = new List { new StatTerm { Source = StatSource.Quality, Exponent = 1f, Role = "receiver" } } } }, + }; + array.Roles = new List { new ItemRole { Name = "receiver" } }; + arrayProducts.Add(("Feather", "Finch", "Light as the thing it is named for, and about as easy to notice. Hears a shout from the next sector over.")); + arrayProducts.Add(("Wallflower", "NiteLife", "Stands in the corner of your hull and takes notes on everyone's business.")); + foreach (var (name, maker, description) in arrayProducts) Maker(maker); + Console.WriteLine($"\nNew design: Passive Array [Tool] 1x1, EnergyDraw 10/s, Multiple 2-3 reading receiver; products {string.Join(", ", arrayProducts.Select(p => $"{p.Name} by {p.Maker}"))}"); + } + + Console.WriteLine($"\nIntercept factor: {changedDesigns.Count} designs and {changedProducts.Count} products to change; Passive Array {(array == null ? "already authored" : "to author")}."); + if (changedDesigns.Count == 0 && changedProducts.Count == 0 && array == null) + { + Console.WriteLine("Sensor stats are already authored; nothing to do."); + return 0; + } + if (!apply) + { + Console.WriteLine("Dry run. Pass \"apply\" to write them."); + return 0; + } + if (array != null) CultRecordRefs.Validate(array); + db.Cache.Commit(batch => + { + foreach (var (document, key) in changedDesigns) batch.Upsert(document.GetType(), document, key); + foreach (var (document, key) in changedProducts) batch.Upsert(document.GetType(), document, key); + if (array == null) return; + var arrayKey = batch.Upsert(typeof(GearData), array); + foreach (var (name, maker, description) in arrayProducts) + { + var (mean, dev) = MakerProfiles[maker]; + batch.Upsert(typeof(FactionProductData), new FactionProductData + { + Name = name, Description = description, + Design = new CultRecordRef(arrayKey), + Manufacturer = db.Cache.RefOf(Maker(maker)), + Roles = array.Roles.Select(r => new ProductRole { Role = r.Name, Mean = mean, StandardDeviation = dev }).ToList(), + }); + } + }); + Console.WriteLine($"Landed {changedDesigns.Count} designs and {changedProducts.Count} products{(array == null ? "" : ", the Passive Array and its products")} in Aetheria.cc"); + return 0; + } + // aetheria-release cut scenarios-smoke (rulings weapon-feel-to-smoke-cut-test-hull, test-hull-both-flanks): the // Smoke Test Hull, a copy of the Longinus hull that no product sells, so no generated ship, station or shop offers // it and only a scenario fits it. It adds what no shipped ship hull has, where the Longinus runs out of cells: two