Verse grammar: VerseGrammar and VerseVerb catalog documents, validation, the verse-grammar AetherDb command, tests
Adds the aetheria.verse_grammar global and aetheria.verse_verb documents (one render path per verb, typed participant roles), VerseGrammarValidation run by AetheriaStores.Open over every verb, the AetherDb 'verse-grammar [apply]' command (starter set: one ship-action verb per TaskType plus speak; question verse-social-verbs default speak-only), and VerseGrammarTests with a deterministic fixture writer. The shipped catalog does not carry the grammar yet: it lands in the next commit, so The_shipped_catalog_holds_revision_one_and_the_seven_starter_verbs fails at this commit. Not yet built when committed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e71540be5b
commit
623072c711
6 changed files with 495 additions and 2 deletions
|
|
@ -6,7 +6,7 @@ using GameCult.Caching.MessagePack;
|
|||
// Aetheria's stores: one home store per type, composed here and nowhere else.
|
||||
public static class AetheriaStores
|
||||
{
|
||||
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData) };
|
||||
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(NameFile), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(VerseGrammar), typeof(VerseVerb) };
|
||||
public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger) };
|
||||
public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) };
|
||||
|
||||
|
|
@ -33,6 +33,7 @@ public static class AetheriaStores
|
|||
// cut.md), stat modifiers, role usage (Cut 7). Fails loudly, naming the item.
|
||||
foreach (var data in cache.GetAll<EquippableItemData>()) CultRecordRefs.Validate(data);
|
||||
foreach (var data in cache.GetAll<ConsumableItemData>()) CultRecordRefs.Validate(data);
|
||||
foreach (var verb in cache.GetAll<VerseVerb>()) VerseGrammarValidation.Validate(verb);
|
||||
return cache;
|
||||
}
|
||||
catch
|
||||
|
|
|
|||
82
Assets/Scripts/ServerShared/VerseGrammar.cs
Normal file
82
Assets/Scripts/ServerShared/VerseGrammar.cs
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
|
||||
// The verse grammar (aetheria-release, cut verse-grammar; ghostlight-verse rulings verse-grammar-home-ruled and
|
||||
// verse-verbs-two-render-paths): the verbs a Ghostlight-simulated Aetheria world may use, each rendering by exactly one
|
||||
// path the game already has, with typed participant roles. Aetheria owns which verbs exist and how each renders;
|
||||
// Ghostlight owns what each does to world state. Nothing in the game runtime reads these documents.
|
||||
[CultDocument("aetheria.verse_grammar", "1"), CultGlobal, MessagePackObject]
|
||||
public class VerseGrammar
|
||||
{
|
||||
[Key(1)] public int Revision;
|
||||
[Key(2)] public string Description;
|
||||
}
|
||||
|
||||
// How a verb is shown: filmed in-engine as a ship action, or presented as an Aetheria conversation.
|
||||
public enum VerseRenderPath
|
||||
{
|
||||
ShipAction = 1,
|
||||
Conversation = 2,
|
||||
}
|
||||
|
||||
// What kind of thing a role binds.
|
||||
public enum VerseReferentKind
|
||||
{
|
||||
Person = 1,
|
||||
Faction = 2,
|
||||
Population = 3,
|
||||
Place = 4,
|
||||
Cargo = 5,
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class VerseRole
|
||||
{
|
||||
[Key(1)] public string Name;
|
||||
[Key(2)] public VerseReferentKind Binds;
|
||||
}
|
||||
|
||||
// The actor is the invoking subject and is never a role.
|
||||
[CultDocument("aetheria.verse_verb", "1"), MessagePackObject]
|
||||
public class VerseVerb
|
||||
{
|
||||
[CultName, Key(1)] public string Name;
|
||||
[Key(2)] public VerseRenderPath RenderPath;
|
||||
[Key(3)] public VerseRole[] Roles = Array.Empty<VerseRole>();
|
||||
[Key(4)] public string Description;
|
||||
}
|
||||
|
||||
public static class VerseGrammarValidation
|
||||
{
|
||||
private static readonly Regex VerbName = new Regex("^[a-z][a-z0-9_]{0,47}\z", RegexOptions.CultureInvariant);
|
||||
private static readonly Regex RoleName = new Regex("^[a-z][a-z0-9_]{0,31}\z", RegexOptions.CultureInvariant);
|
||||
|
||||
// Canonical names, unique role names, defined enum values. A failure names the field and the rule, and the verb once
|
||||
// its name is known canonical; it never prints a value the author wrote that is itself the fault.
|
||||
public static void Validate(VerseVerb verb)
|
||||
{
|
||||
if (verb.Name == null || !VerbName.IsMatch(verb.Name))
|
||||
throw new InvalidOperationException("VerseVerb.Name: not a canonical verb name ([a-z][a-z0-9_]{0,47}).");
|
||||
if (!Enum.IsDefined(typeof(VerseRenderPath), verb.RenderPath))
|
||||
throw new InvalidOperationException($"VerseVerb \"{verb.Name}\" RenderPath: not a defined render path.");
|
||||
if (verb.Roles == null)
|
||||
throw new InvalidOperationException($"VerseVerb \"{verb.Name}\" Roles: missing.");
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var role in verb.Roles)
|
||||
{
|
||||
if (role == null || role.Name == null || !RoleName.IsMatch(role.Name))
|
||||
throw new InvalidOperationException($"VerseVerb \"{verb.Name}\" Roles.Name: not a canonical role name ([a-z][a-z0-9_]{{0,31}}).");
|
||||
if (!seen.Add(role.Name))
|
||||
throw new InvalidOperationException($"VerseVerb \"{verb.Name}\" Roles.Name: duplicate role name.");
|
||||
if (!Enum.IsDefined(typeof(VerseReferentKind), role.Binds))
|
||||
throw new InvalidOperationException($"VerseVerb \"{verb.Name}\" Roles.Binds: not a defined referent kind.");
|
||||
}
|
||||
}
|
||||
}
|
||||
11
Assets/Scripts/ServerShared/VerseGrammar.cs.meta
Normal file
11
Assets/Scripts/ServerShared/VerseGrammar.cs.meta
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 3f1a7c52d9e84b6aa0c15e7b2d4f8a91
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
286
tests/Aetheria.Shared.Tests/VerseGrammarTests.cs
Normal file
286
tests/Aetheria.Shared.Tests/VerseGrammarTests.cs
Normal file
|
|
@ -0,0 +1,286 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using CultMath;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using Xunit;
|
||||
|
||||
// The verse grammar (aetheria-release, cut verse-grammar; ghostlight-verse rulings verse-grammar-home-ruled,
|
||||
// verse-verbs-two-render-paths; question verse-social-verbs, default speak-only): the document set, its refusals through
|
||||
// AetheriaStores.Open, the AetherDb command that authors the starter set, and the fixture writer Ghostlight's
|
||||
// grammar-reader copies its fixture from.
|
||||
public sealed class VerseGrammarTests : IDisposable
|
||||
{
|
||||
// Set to a path to have FixtureWriterEmitsTheCatalogGhostlightReads leave the fixture there.
|
||||
public const string FixturePathVariable = "AETHERIA_VERSE_FIXTURE_PATH";
|
||||
|
||||
private readonly string _root = Path.Combine(Path.GetTempPath(), "verse-grammar-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public VerseGrammarTests() => Directory.CreateDirectory(_root);
|
||||
public void Dispose() => Directory.Delete(_root, true);
|
||||
|
||||
private string PathOf(string name) => Path.Combine(_root, name + ".cc");
|
||||
|
||||
private static VerseVerb Good(string name) => new VerseVerb
|
||||
{
|
||||
Name = name,
|
||||
RenderPath = VerseRenderPath.ShipAction,
|
||||
Description = "A good verb.",
|
||||
Roles = new[] { new VerseRole { Name = "site", Binds = VerseReferentKind.Place }, new VerseRole { Name = "load", Binds = VerseReferentKind.Cargo } },
|
||||
};
|
||||
|
||||
// A catalog authored through AetheriaStores.Open; TestCatalogGlobal is the record the shared registry in this test host
|
||||
// demands (see AetheriaStoresTests).
|
||||
private string Author(string name, VerseGrammar grammar, params VerseVerb[] verbs)
|
||||
{
|
||||
var path = PathOf(name);
|
||||
using var cache = AetheriaStores.Open(path, catalogWritable: true);
|
||||
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
|
||||
if (grammar != null) cache.Upsert(grammar);
|
||||
foreach (var verb in verbs) cache.Upsert(verb);
|
||||
cache.FlushAsync().Wait();
|
||||
return path;
|
||||
}
|
||||
|
||||
private static CultCache OpenScoped(string path, bool readOnly)
|
||||
{
|
||||
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
|
||||
.Where(t => t is { IsAbstract: false, IsInterface: false })
|
||||
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
|
||||
var cache = new CultCache(registry);
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path, readOnly), AetheriaStores.CatalogTypes);
|
||||
return cache;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_catalog_with_the_grammar_and_verbs_opens_read_only_and_returns_every_field()
|
||||
{
|
||||
var verbs = new[]
|
||||
{
|
||||
Good("haul"),
|
||||
new VerseVerb { Name = "speak", RenderPath = VerseRenderPath.Conversation, Description = "Say a thing.", Roles = new VerseRole[0] },
|
||||
new VerseVerb { Name = "levy", RenderPath = VerseRenderPath.ShipAction, Description = "Raise a levy.",
|
||||
Roles = new[] { new VerseRole { Name = "who", Binds = VerseReferentKind.Population }, new VerseRole { Name = "boss", Binds = VerseReferentKind.Person }, new VerseRole { Name = "flag", Binds = VerseReferentKind.Faction } } },
|
||||
};
|
||||
var path = Author("roundtrip", new VerseGrammar { Revision = 7, Description = "Seven." }, verbs);
|
||||
|
||||
using var cache = AetheriaStores.Open(path);
|
||||
var grammar = cache.GetGlobal<VerseGrammar>();
|
||||
Assert.Equal(7, grammar.Revision);
|
||||
Assert.Equal("Seven.", grammar.Description);
|
||||
Assert.Equal(verbs.Length, cache.GetAll<VerseVerb>().Count());
|
||||
foreach (var expected in verbs)
|
||||
{
|
||||
var actual = cache.GetByName<VerseVerb>(expected.Name);
|
||||
Assert.Equal(expected.RenderPath, actual.RenderPath);
|
||||
Assert.Equal(expected.Description, actual.Description);
|
||||
Assert.Equal(expected.Roles.Select(r => (r.Name, r.Binds)), actual.Roles.Select(r => (r.Name, r.Binds)));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_catalog_without_the_grammar_global_is_refused()
|
||||
{
|
||||
var path = Author("nogrammar", null, Good("haul"));
|
||||
var error = Assert.Throws<InvalidOperationException>(() => AetheriaStores.Open(path));
|
||||
Assert.Contains("aetheria.verse_grammar", error.Message);
|
||||
}
|
||||
|
||||
public static IEnumerable<object[]> Refusals() => new[]
|
||||
{
|
||||
new object[] { "name with a space", (Action<VerseVerb>)(v => v.Name = "bad name"), "VerseVerb.Name", "bad name" },
|
||||
new object[] { "name starting with a digit", (Action<VerseVerb>)(v => v.Name = "9haul"), "VerseVerb.Name", "9haul" },
|
||||
new object[] { "upper-case name", (Action<VerseVerb>)(v => v.Name = "Haul"), "VerseVerb.Name", "Haul" },
|
||||
new object[] { "name one past 48 characters", (Action<VerseVerb>)(v => v.Name = "a" + new string('b', 48)), "VerseVerb.Name", new string('b', 48) },
|
||||
new object[] { "render path zero", (Action<VerseVerb>)(v => v.RenderPath = 0), "RenderPath", null },
|
||||
new object[] { "undefined render path", (Action<VerseVerb>)(v => v.RenderPath = (VerseRenderPath)3), "RenderPath", null },
|
||||
new object[] { "missing roles", (Action<VerseVerb>)(v => v.Roles = null), "Roles", null },
|
||||
new object[] { "duplicate role name", (Action<VerseVerb>)(v => v.Roles = new[] { Good("x").Roles[0], Good("x").Roles[0] }), "duplicate role name", null },
|
||||
new object[] { "role name with a capital", (Action<VerseVerb>)(v => v.Roles[0].Name = "Site"), "Roles.Name", "Site" },
|
||||
new object[] { "role name one past 32 characters", (Action<VerseVerb>)(v => v.Roles[0].Name = "r" + new string('s', 32)), "Roles.Name", new string('s', 32) },
|
||||
new object[] { "referent kind zero", (Action<VerseVerb>)(v => v.Roles[0].Binds = 0), "Roles.Binds", null },
|
||||
new object[] { "undefined referent kind", (Action<VerseVerb>)(v => v.Roles[0].Binds = (VerseReferentKind)99), "Roles.Binds", null },
|
||||
};
|
||||
|
||||
// Every verb is held to the rule, wherever it sits among the others; a refusal names the verb (once its name is canonical)
|
||||
// and the field, and never repeats the value the author wrote.
|
||||
[Theory]
|
||||
[MemberData(nameof(Refusals))]
|
||||
public void Open_refuses_a_malformed_verb_in_any_position(string label, Action<VerseVerb> corrupt, string fragment, string echoedValue)
|
||||
{
|
||||
for (var position = 0; position < 3; position++)
|
||||
{
|
||||
var verbs = new[] { Good("alpha"), Good("beta"), Good("gamma") };
|
||||
corrupt(verbs[position]);
|
||||
var canonicalName = verbs[position].Name is "alpha" or "beta" or "gamma" ? verbs[position].Name : null;
|
||||
var path = Author($"refused-{label.Replace(' ', '-')}-{position}", new VerseGrammar { Revision = 1 }, verbs);
|
||||
|
||||
var error = Assert.Throws<InvalidOperationException>(() => AetheriaStores.Open(path));
|
||||
Assert.Contains(fragment, error.Message);
|
||||
if (canonicalName != null) Assert.Contains($"\"{canonicalName}\"", error.Message);
|
||||
if (echoedValue != null) Assert.DoesNotContain(echoedValue, error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_longest_canonical_names_are_accepted()
|
||||
{
|
||||
var verb = Good("v" + new string('x', 47));
|
||||
verb.Roles[0].Name = "r" + new string('y', 31);
|
||||
var path = Author("longest", new VerseGrammar { Revision = 1 }, verb);
|
||||
using var cache = AetheriaStores.Open(path);
|
||||
Assert.Single(cache.GetAll<VerseVerb>());
|
||||
}
|
||||
|
||||
// ---- the AetherDb command ----
|
||||
|
||||
// A scratch root holding a copy of the shipped catalog with its verse grammar removed: the catalog as it was before the
|
||||
// command ran. The catalog is stripped and read through a registry scoped to the shipped assembly, as
|
||||
// PiratesFactionCommandTests does, so the test assembly's TestCatalogGlobal does not poison it.
|
||||
private string RootWithoutGrammar(params VerseVerb[] preexisting)
|
||||
{
|
||||
var gameData = Path.Combine(_root, "cmd", "GameData");
|
||||
Directory.CreateDirectory(gameData);
|
||||
var catalog = Path.Combine(gameData, "Aetheria.cc");
|
||||
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), catalog, true);
|
||||
using (var cache = OpenScoped(catalog, false))
|
||||
{
|
||||
foreach (var grammar in cache.GetAll<VerseGrammar>().ToArray()) Assert.True(cache.Remove(cache.RefOf(grammar).Key));
|
||||
foreach (var verb in cache.GetAll<VerseVerb>().ToArray()) Assert.True(cache.Remove(cache.RefOf(verb).Key));
|
||||
foreach (var verb in preexisting) cache.Upsert(verb);
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
return Path.Combine(_root, "cmd");
|
||||
}
|
||||
|
||||
private static string CatalogOf(string root) => Path.Combine(root, "GameData", "Aetheria.cc");
|
||||
|
||||
[Fact]
|
||||
public void A_dry_run_writes_nothing()
|
||||
{
|
||||
var root = RootWithoutGrammar();
|
||||
var before = File.ReadAllBytes(CatalogOf(root));
|
||||
Assert.Equal(0, VerseGrammarCommand.Run(apply: false, root: root));
|
||||
Assert.Equal(before, File.ReadAllBytes(CatalogOf(root)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_lands_revision_one_and_one_verb_per_task_type_plus_speak_and_a_second_apply_changes_nothing()
|
||||
{
|
||||
var root = RootWithoutGrammar();
|
||||
Assert.Equal(0, VerseGrammarCommand.Run(apply: true, root: root));
|
||||
|
||||
using (var cache = OpenScoped(CatalogOf(root), true))
|
||||
{
|
||||
Assert.Equal(1, cache.GetGlobal<VerseGrammar>().Revision);
|
||||
var verbs = cache.GetAll<VerseVerb>().ToDictionary(verb => verb.Name);
|
||||
var ships = Enum.GetValues(typeof(TaskType)).Cast<TaskType>().Where(task => task != TaskType.None)
|
||||
.Select(task => task.ToString().ToLowerInvariant()).OrderBy(name => name, StringComparer.Ordinal);
|
||||
Assert.Equal(ships.Append("speak").OrderBy(name => name, StringComparer.Ordinal), verbs.Keys.OrderBy(name => name, StringComparer.Ordinal));
|
||||
Assert.All(ships, name => Assert.Equal(VerseRenderPath.ShipAction, verbs[name].RenderPath));
|
||||
Assert.Equal(VerseRenderPath.Conversation, verbs["speak"].RenderPath);
|
||||
Assert.Empty(verbs["speak"].Roles);
|
||||
Assert.All(verbs.Values, VerseGrammarValidation.Validate);
|
||||
|
||||
// The role signatures the spec names.
|
||||
string Sig(string name) => string.Join(", ", verbs[name].Roles.Select(r => $"{r.Name}: {r.Binds}"));
|
||||
Assert.Equal("site: Place, ore: Cargo", Sig("mine"));
|
||||
Assert.Equal("cargo: Cargo, destination: Place", Sig("haul"));
|
||||
Assert.Equal("target: Faction", Sig("tow"));
|
||||
Assert.Equal("protected: Faction, at: Place", Sig("defend"));
|
||||
Assert.Equal("target: Faction", Sig("attack"));
|
||||
Assert.Equal("region: Place", Sig("explore"));
|
||||
}
|
||||
|
||||
var landed = File.ReadAllBytes(CatalogOf(root));
|
||||
Assert.Equal(0, VerseGrammarCommand.Run(apply: true, root: root));
|
||||
Assert.Equal(landed, File.ReadAllBytes(CatalogOf(root)));
|
||||
}
|
||||
|
||||
// A verb already in the catalog under a starter name but with other roles is replaced; one the starter set does not name
|
||||
// is left alone.
|
||||
[Fact]
|
||||
public void Apply_replaces_a_starter_verb_that_differs_only_in_its_roles_and_leaves_other_verbs()
|
||||
{
|
||||
var stale = new VerseVerb { Name = "mine", RenderPath = VerseRenderPath.ShipAction, Description = VerseGrammarCommand.StarterVerbs().Single(v => v.Name == "mine").Description,
|
||||
Roles = new[] { new VerseRole { Name = "site", Binds = VerseReferentKind.Place } } };
|
||||
var root = RootWithoutGrammar(stale, Good("levy"));
|
||||
Assert.Equal(0, VerseGrammarCommand.Run(apply: true, root: root));
|
||||
|
||||
using var cache = OpenScoped(CatalogOf(root), true);
|
||||
Assert.Equal(2, cache.GetByName<VerseVerb>("mine").Roles.Length);
|
||||
Assert.NotNull(cache.GetByName<VerseVerb>("levy"));
|
||||
Assert.Equal(1, cache.GetAll<VerseVerb>().Count(verb => verb.Name == "mine"));
|
||||
}
|
||||
|
||||
// The shipped catalog carries the command's output.
|
||||
[Fact]
|
||||
public void The_shipped_catalog_holds_revision_one_and_the_seven_starter_verbs()
|
||||
{
|
||||
using var cache = OpenScoped(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), true);
|
||||
Assert.Equal(1, cache.GetGlobal<VerseGrammar>().Revision);
|
||||
var starter = VerseGrammarCommand.StarterVerbs();
|
||||
Assert.Equal(7, starter.Length);
|
||||
var shipped = cache.GetAll<VerseVerb>().ToArray();
|
||||
Assert.Equal(starter.Length, shipped.Length);
|
||||
foreach (var expected in starter)
|
||||
Assert.True(VerseGrammarCommand.Same(expected, cache.GetByName<VerseVerb>(expected.Name)), expected.Name);
|
||||
}
|
||||
|
||||
// ---- the fixture writer ----
|
||||
|
||||
// The minimal catalog Ghostlight's grammar-reader reads: the grammar global, three verbs, two factions with an allegiance.
|
||||
// Written through a registry scoped to the shipped assembly, so it holds nothing from this test assembly.
|
||||
public static void WriteFixture(string path)
|
||||
{
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
using var cache = OpenScoped(path, false);
|
||||
cache.Upsert(new VerseGrammar { Revision = 1, Description = "Fixture grammar." });
|
||||
cache.Upsert(new VerseVerb { Name = "haul", RenderPath = VerseRenderPath.ShipAction, Description = "Carry cargo to a place.",
|
||||
Roles = new[] { new VerseRole { Name = "cargo", Binds = VerseReferentKind.Cargo }, new VerseRole { Name = "destination", Binds = VerseReferentKind.Place } } });
|
||||
cache.Upsert(new VerseVerb { Name = "attack", RenderPath = VerseRenderPath.ShipAction, Description = "Attack a faction.",
|
||||
Roles = new[] { new VerseRole { Name = "target", Binds = VerseReferentKind.Faction } } });
|
||||
cache.Upsert(new VerseVerb { Name = "speak", RenderPath = VerseRenderPath.Conversation, Description = "Say a thing.", Roles = new VerseRole[0] });
|
||||
var first = new Faction { Name = "Adrasteia", ShortName = "ADR", Description = "First.", PrimaryColor = new float3(1, .5f, .25f) };
|
||||
var second = new Faction { Name = "Brannoch", ShortName = "BRN", Description = "Second.", PrimaryColor = new float3(.25f, .5f, 1) };
|
||||
var firstRef = cache.Upsert(first);
|
||||
var secondRef = cache.Upsert(second);
|
||||
first.Allegiance[secondRef] = .75f;
|
||||
second.Allegiance[firstRef] = .25f;
|
||||
cache.Upsert(first);
|
||||
cache.Upsert(second);
|
||||
cache.FlushAsync().Wait();
|
||||
}
|
||||
|
||||
// Two writes of the fixture are the same bytes, so Ghostlight's copy of it is reproducible and a diff of it means the
|
||||
// grammar changed. With AETHERIA_VERSE_FIXTURE_PATH set, the fixture is left at that path for Ghostlight to copy.
|
||||
[Fact]
|
||||
public void Fixture_writer_is_deterministic_and_emits_what_the_grammar_reader_needs()
|
||||
{
|
||||
var left = PathOf("fixture-left");
|
||||
var right = PathOf("fixture-right");
|
||||
WriteFixture(left);
|
||||
WriteFixture(right);
|
||||
Assert.Equal(File.ReadAllBytes(left), File.ReadAllBytes(right));
|
||||
|
||||
var emitted = Environment.GetEnvironmentVariable(FixturePathVariable);
|
||||
if (!string.IsNullOrEmpty(emitted)) WriteFixture(emitted);
|
||||
|
||||
using var cache = OpenScoped(emitted is { Length: > 0 } ? emitted : left, true);
|
||||
Assert.Equal(1, cache.GetGlobal<VerseGrammar>().Revision);
|
||||
Assert.Equal(new[] { "attack", "haul", "speak" }, cache.GetAll<VerseVerb>().Select(verb => verb.Name).OrderBy(name => name, StringComparer.Ordinal));
|
||||
Assert.All(cache.GetAll<VerseVerb>(), VerseGrammarValidation.Validate);
|
||||
var factions = cache.GetAll<Faction>().ToArray();
|
||||
Assert.Equal(2, factions.Length);
|
||||
Assert.All(factions, faction => Assert.Single(faction.Allegiance));
|
||||
var adrasteia = cache.GetByName<Faction>("Adrasteia");
|
||||
Assert.Equal(.75f, adrasteia.Allegiance[cache.RefOf(cache.GetByName<Faction>("Brannoch"))]);
|
||||
}
|
||||
}
|
||||
|
|
@ -46,8 +46,9 @@ public static class Program
|
|||
case "pirates-faction":
|
||||
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
|
||||
return PiratesFaction(args.Contains("apply"));
|
||||
case "verse-grammar": return VerseGrammarCommand.Run(args.Contains("apply"));
|
||||
default:
|
||||
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [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], roles-backfill [apply], pd-gear [apply], pirates-faction [apply]");
|
||||
Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], save, settings, settings-dump, dangling [clear <Type.Member>]... [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], roles-backfill [apply], pd-gear [apply], pirates-faction [apply], verse-grammar [apply]");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
112
tools/AetherDb/VerseGrammarCommand.cs
Normal file
112
tools/AetherDb/VerseGrammarCommand.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
||||
// verse-grammar [apply] (aetheria-release, cut verse-grammar; question verse-social-verbs, default speak-only): authors
|
||||
// the starter verse grammar into GameData/Aetheria.cc. The ship-action half is one verb per TaskType, the shapes of what
|
||||
// the game can film today; the conversation half is `speak`, matching Ghostlight's kernel-built speak. Dry run unless
|
||||
// passed "apply", same contract as the other *-migrate commands.
|
||||
//
|
||||
// The catalog is opened here rather than through AetheriaStores.Open: that refuses a populated catalog that lacks a
|
||||
// [CultGlobal], and this command is what authors the VerseGrammar global into a catalog that predates it.
|
||||
public static class VerseGrammarCommand
|
||||
{
|
||||
public const int StarterRevision = 1;
|
||||
public const string StarterDescription = "Verbs a Ghostlight-simulated Aetheria world may use: ship actions the game films in-engine, and speech rendered as Aetheria conversation.";
|
||||
|
||||
private static VerseRole Role(string name, VerseReferentKind binds) => new VerseRole { Name = name, Binds = binds };
|
||||
|
||||
// One ShipAction verb per TaskType (None excepted), then the conversation verbs.
|
||||
public static VerseVerb[] StarterVerbs() => new[]
|
||||
{
|
||||
new VerseVerb { Name = "mine", RenderPath = VerseRenderPath.ShipAction, Description = "The actor works an ore body at a place and takes the ore into its hold.",
|
||||
Roles = new[] { Role("site", VerseReferentKind.Place), Role("ore", VerseReferentKind.Cargo) } },
|
||||
new VerseVerb { Name = "haul", RenderPath = VerseRenderPath.ShipAction, Description = "The actor carries cargo to a destination place.",
|
||||
Roles = new[] { Role("cargo", VerseReferentKind.Cargo), Role("destination", VerseReferentKind.Place) } },
|
||||
new VerseVerb { Name = "tow", RenderPath = VerseRenderPath.ShipAction, Description = "The actor tows a station or hull belonging to the target faction.",
|
||||
Roles = new[] { Role("target", VerseReferentKind.Faction) } },
|
||||
new VerseVerb { Name = "defend", RenderPath = VerseRenderPath.ShipAction, Description = "The actor guards a protected faction's ships and holdings at a place.",
|
||||
Roles = new[] { Role("protected", VerseReferentKind.Faction), Role("at", VerseReferentKind.Place) } },
|
||||
new VerseVerb { Name = "attack", RenderPath = VerseRenderPath.ShipAction, Description = "The actor attacks the target faction's ships and holdings.",
|
||||
Roles = new[] { Role("target", VerseReferentKind.Faction) } },
|
||||
new VerseVerb { Name = "explore", RenderPath = VerseRenderPath.ShipAction, Description = "The actor surveys a region and charts what is there.",
|
||||
Roles = new[] { Role("region", VerseReferentKind.Place) } },
|
||||
new VerseVerb { Name = "speak", RenderPath = VerseRenderPath.Conversation, Description = "The actor says something to whoever is in earshot. Shown as Aetheria dialogue: face to face when docked, by radio with the speaker's portrait over their ship when undocked.",
|
||||
Roles = new VerseRole[0] },
|
||||
};
|
||||
|
||||
public static bool Same(VerseVerb a, VerseVerb b) =>
|
||||
a.Name == b.Name && a.RenderPath == b.RenderPath && a.Description == b.Description &&
|
||||
a.Roles.Select(r => (r.Name, r.Binds)).SequenceEqual(b.Roles.Select(r => (r.Name, r.Binds)));
|
||||
|
||||
private static string Shape(VerseVerb verb) =>
|
||||
$"{verb.Name}({string.Join(", ", verb.Roles.Select(r => $"{r.Name}: {r.Binds}"))}) [{verb.RenderPath}]";
|
||||
|
||||
public static int Run(bool apply, string root = null)
|
||||
{
|
||||
var catalogPath = Path.Combine(root ?? AetherDb.FindRoot(), "GameData", "Aetheria.cc");
|
||||
using var cache = new CultCache();
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, !apply), AetheriaStores.CatalogTypes);
|
||||
|
||||
var starter = StarterVerbs();
|
||||
foreach (var verb in starter) VerseGrammarValidation.Validate(verb);
|
||||
var missingTasks = Enum.GetValues(typeof(TaskType)).Cast<TaskType>()
|
||||
.Where(task => task != TaskType.None && starter.All(verb => verb.Name != task.ToString().ToLowerInvariant())).ToArray();
|
||||
if (missingTasks.Length > 0) throw new InvalidOperationException($"The starter grammar has no ship-action verb for TaskType {string.Join(", ", missingTasks)}.");
|
||||
|
||||
var grammar = cache.GetGlobal<VerseGrammar>();
|
||||
var grammarCurrent = grammar != null && grammar.Revision == StarterRevision && grammar.Description == StarterDescription;
|
||||
Console.WriteLine(grammar == null ? $"Grammar: new, revision {StarterRevision}."
|
||||
: grammarCurrent ? $"Grammar: revision {grammar.Revision}, already authored."
|
||||
: $"Grammar: revision {grammar.Revision} -> {StarterRevision}.");
|
||||
Console.WriteLine($" {StarterDescription}");
|
||||
|
||||
var existing = cache.GetAll<VerseVerb>().ToDictionary(verb => verb.Name, StringComparer.Ordinal);
|
||||
var changes = starter.Where(verb => !existing.TryGetValue(verb.Name, out var current) || !Same(current, verb)).ToArray();
|
||||
Console.WriteLine($"\nStarter verbs ({starter.Length}):");
|
||||
foreach (var verb in starter)
|
||||
{
|
||||
var state = !existing.TryGetValue(verb.Name, out var current) ? "new" : Same(current, verb) ? "unchanged" : "differs, will be replaced";
|
||||
Console.WriteLine($" {Shape(verb)} {state}");
|
||||
Console.WriteLine($" {verb.Description}");
|
||||
}
|
||||
var extra = existing.Keys.Where(name => starter.All(verb => verb.Name != name)).OrderBy(name => name, StringComparer.Ordinal).ToArray();
|
||||
if (extra.Length > 0) Console.WriteLine($"\nAlready in the catalog and left alone: {string.Join(", ", extra)}");
|
||||
|
||||
if (grammarCurrent && changes.Length == 0)
|
||||
{
|
||||
Console.WriteLine("\nNothing to do.");
|
||||
return 0;
|
||||
}
|
||||
if (!apply)
|
||||
{
|
||||
Console.WriteLine($"\nDry run. Pass \"apply\" to land the grammar global and {changes.Length} verb(s).");
|
||||
return 0;
|
||||
}
|
||||
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
if (!grammarCurrent)
|
||||
{
|
||||
var record = grammar ?? new VerseGrammar();
|
||||
record.Revision = StarterRevision;
|
||||
record.Description = StarterDescription;
|
||||
if (grammar == null) batch.Upsert(typeof(VerseGrammar), record);
|
||||
else batch.Upsert(typeof(VerseGrammar), record, cache.RefOf(grammar).Key);
|
||||
}
|
||||
foreach (var verb in changes)
|
||||
{
|
||||
if (existing.TryGetValue(verb.Name, out var current)) batch.Upsert(typeof(VerseVerb), verb, cache.RefOf(current).Key);
|
||||
else batch.Upsert(typeof(VerseVerb), verb);
|
||||
}
|
||||
});
|
||||
Console.WriteLine($"\nLanded the grammar global and {changes.Length} verb(s) in Aetheria.cc");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue