From e956b2415a7882444c76e34766bdf96c2fb6104c Mon Sep 17 00:00:00 2001 From: Techno453 Date: Tue, 20 Oct 2026 23:43:13 -0600 Subject: [PATCH 1/4] Register activities from installed templates --- Sunrise Studio.sln | 15 ++ .../ActivityRegistrationCompiler.cs | 225 ++++++++++++++++++ .../ActivityRegistrationIdentity.cs | 118 +++++++++ .../ActivityRegistrationTables.cs | 193 +++++++++++++++ src/SunriseStudio.Authoring/NativeRows.cs | 36 +++ .../Creation/ActivityRegistrationWorkflow.cs | 120 ++++++++++ .../Creation/CreationTypes.Activities.cs | 10 + .../Creation/CreationTypes.cs | 3 + .../StudioForm.Browser.cs | 2 + .../StudioWorkspace.Transactions.cs | 7 +- src/SunriseStudio.Editor/StudioWorkspace.cs | 9 +- src/SunriseStudio.Projects/AddedActivity.cs | 53 +++++ .../ProjectBuilder.Activities.cs | 8 + .../ProjectBuilder.RootManifests.cs | 4 +- src/SunriseStudio.Projects/ProjectBuilder.cs | 23 +- src/SunriseStudio.Projects/ProjectModels.cs | 10 +- .../ProjectTransactions.cs | 5 +- src/SunriseStudio.Projects/StudioProject.cs | 15 +- .../ActivityFixture.cs | 155 ++++++++++++ .../InstalledChecks.cs | 45 ++++ tests/SunriseStudio.Activity.Tests/Program.cs | 162 +++++++++++++ .../SunriseStudio.Activity.Tests.csproj | 11 + .../activity_registration_golden.json | 45 ++++ tests/SunriseStudio.Activity.Tests/oracle.py | 38 +++ .../registration-parity.json | 8 + verify.ps1 | 2 + 26 files changed, 1300 insertions(+), 22 deletions(-) create mode 100644 src/SunriseStudio.Authoring/ActivityRegistrationCompiler.cs create mode 100644 src/SunriseStudio.Authoring/ActivityRegistrationIdentity.cs create mode 100644 src/SunriseStudio.Authoring/ActivityRegistrationTables.cs create mode 100644 src/SunriseStudio.Authoring/NativeRows.cs create mode 100644 src/SunriseStudio.Editor/Creation/ActivityRegistrationWorkflow.cs create mode 100644 src/SunriseStudio.Editor/Creation/CreationTypes.Activities.cs create mode 100644 src/SunriseStudio.Projects/AddedActivity.cs create mode 100644 src/SunriseStudio.Projects/ProjectBuilder.Activities.cs create mode 100644 tests/SunriseStudio.Activity.Tests/ActivityFixture.cs create mode 100644 tests/SunriseStudio.Activity.Tests/InstalledChecks.cs create mode 100644 tests/SunriseStudio.Activity.Tests/Program.cs create mode 100644 tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj create mode 100644 tests/SunriseStudio.Activity.Tests/activity_registration_golden.json create mode 100644 tests/SunriseStudio.Activity.Tests/oracle.py create mode 100644 tests/SunriseStudio.Activity.Tests/registration-parity.json diff --git a/Sunrise Studio.sln b/Sunrise Studio.sln index ac97bc15..028fba14 100644 --- a/Sunrise Studio.sln +++ b/Sunrise Studio.sln @@ -107,6 +107,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SunriseStudio.WorldAuthorin EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SunriseStudio.Navigation.Tests", "tests\SunriseStudio.Navigation.Tests\SunriseStudio.Navigation.Tests.csproj", "{19782212-F914-4034-A205-B6184E7CB71C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SunriseStudio.Activity.Tests", "tests\SunriseStudio.Activity.Tests\SunriseStudio.Activity.Tests.csproj", "{A1060A37-D012-4FFC-AAF2-18ECF270A2DD}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -717,6 +719,18 @@ Global {19782212-F914-4034-A205-B6184E7CB71C}.Release|x64.Build.0 = Release|Any CPU {19782212-F914-4034-A205-B6184E7CB71C}.Release|x86.ActiveCfg = Release|Any CPU {19782212-F914-4034-A205-B6184E7CB71C}.Release|x86.Build.0 = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|x64.Build.0 = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Debug|x86.Build.0 = Debug|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|Any CPU.Build.0 = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|x64.ActiveCfg = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|x64.Build.0 = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|x86.ActiveCfg = Release|Any CPU + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -772,5 +786,6 @@ Global {787695FC-2C0C-4763-A20D-E4CA9E724BE9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {B58598DD-F04E-45B8-B373-D48B08FD5792} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {19782212-F914-4034-A205-B6184E7CB71C} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {A1060A37-D012-4FFC-AAF2-18ECF270A2DD} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection EndGlobal diff --git a/src/SunriseStudio.Authoring/ActivityRegistrationCompiler.cs b/src/SunriseStudio.Authoring/ActivityRegistrationCompiler.cs new file mode 100644 index 00000000..e757bdc1 --- /dev/null +++ b/src/SunriseStudio.Authoring/ActivityRegistrationCompiler.cs @@ -0,0 +1,225 @@ +using System.Buffers.Binary; +using SunriseStudio.Packages; +using SunriseStudio.Projects; +using static SunriseStudio.Authoring.ActivityRegistrationTables; +using static SunriseStudio.Authoring.ActivityRegistrationIdentity; + +namespace SunriseStudio.Authoring; + +public sealed record ActivityRegistrationPlan(IReadOnlyList Additions, ActivityTableAddition Row); + +/** Template registrations keep their complete policy and whole-map scenario ownership. */ +public sealed class ActivityRegistrationCompiler : IActivityRegistrationCompiler +{ + public static ActivityRegistrationCompiler Default { get; } = new(); + public const string WipReason = "Upstream Sunrise 0.6 reads the activity table with a fixed count of 1,170 rows and refuses the whole table otherwise. Until the bounded-reader fix lands, a registered activity builds but cannot be seen by the game."; + public static IReadOnlyDictionary ProvenTypes { get; } = new Dictionary + { + [0] = "Story", [3] = "Strike", [5] = "Nightfall", [7] = "Raid", [9] = "Explore", + [15] = "Rumble", [20] = "Social", [45] = "Nightmare Hunt", [46] = "Dungeon" + }; + + public IReadOnlyDictionary Compile(StudioProject project, PackageCatalog catalog) + { + var result = new Dictionary(); var rows = new List(); + foreach (var recipe in project.AddedActivities) + { + var plan = Prepare(project, catalog, recipe); rows.Add(plan.Row); + foreach (var addition in plan.Additions) + { + uint tag = NativeTag(addition.Native!); + var saved = project.AddedAssets.SingleOrDefault(asset => asset.Native is { } native && NativeTag(native) == tag); + Require(saved is not null && saved.Native == addition.Native && saved.BaseTagHash == addition.BaseTagHash, + "Activity allocation changed. Recreate the registration."); + Require(project.ReadAddedAsset(saved!.Id, catalog).AsSpan().SequenceEqual(addition.Data), + "Activity assets differ from their registration recipe. Recreate the registration."); + Require(result.TryAdd(tag, addition.Data), "Activity registrations overlap."); + } + } + if (rows.Count == 0) return result; + var tables = Append(catalog.ReadOriginal(DefinitionTag), catalog.ReadOriginal(ClientTag), rows); + foreach (var (tag, bytes) in new[] { (DefinitionTag, tables.Definitions), (ClientTag, tables.Clients) }) + { + Require(project.ReadAsset(tag, catalog).AsSpan().SequenceEqual(bytes), "Activity table edits differ from their registration recipes."); + result.Add(tag, bytes); + } + return result; + } + + public static ActivityRegistrationPlan Prepare(StudioProject project, PackageCatalog catalog, AddedActivity recipe) + { + recipe.Validate(); + Require(!project.AddedActivities.Any(other => other.InternalName != recipe.InternalName && Hash(other.InternalName) == Hash(recipe.InternalName)), + "Activity name hash collides with another project registration."); + Require(!catalog.ContainsInstalledPackage(recipe.PackageId), "Choose an unused project package."); + byte[] Installed(uint tag, uint cls) + { + Require(catalog.TryGetEntry(tag, out var entry) && catalog.ContainsInstalledPackage(entry.PackageId) + && entry.Reference == cls && entry.Type is 8 or 16, $"Installed activity dependency {tag:X8} has the wrong class."); + return catalog.ReadOriginal(tag); + } + byte[] definitions = Installed(DefinitionTag, DefinitionClass); _ = Installed(ClientTag, ClientClass); + var template = ReadDefinitions(definitions).SingleOrDefault(row => row.Hash == recipe.TemplateActivity) + ?? throw new InvalidDataException("Choose an installed template activity."); + Require(recipe.Type == template.Type, "Choose a template of the requested activity type; its policy cannot change type."); + ValidateType(Installed(0x81327CE8, 0x80807773), Installed(0x81327D64, 0x80805F3C), recipe.Type, + ReadTypeNames(catalog).GetValueOrDefault(recipe.Type)); + uint sourceRoot = Named(catalog, template.Name, 0x80808AAE); + byte[] root = Installed(sourceRoot, 0x80808AAE); var rootData = Sized(root, 72); + Require(root.Length == 72 && rootData.U32(8) == Hash(template.Name) + && rootData.U32(12) == 0 && Rows(rootData, 16, 0x80808491, 4).SequenceEqual(new[] { 64, 68 }), "Unsupported activity root layout."); + uint sourceScenario = rootData.U32(64); _ = Installed(rootData.U32(68), 0x80809BA3); + byte[] scenario = Installed(sourceScenario, 0x80809994); var original = Sized(scenario, 140); + string sourceStem = Text(original, Relative(original, 48, 96)); + uint sourceMap = Named(catalog, "map:" + sourceStem + ":root", 0x808091DE); + string mapName = "map:" + recipe.ScenarioStem + ":root"; + var mapAsset = project.AddedAssets.SingleOrDefault(asset => asset.Native is { } native && NativeTag(native) == recipe.MapRootTag); + Require(mapAsset is null ? recipe.MapRootTag == sourceMap : mapAsset.BaseTagHash == sourceMap, + "NO_SAME_MAP_TEMPLATE: choose the template's map or a derived whole-map copy of it."); + Require(mapAsset is null ? catalog.NamedTags.Any(row => row.TagHash == recipe.MapRootTag && row.ClassHash == 0x808091DE && row.Name == mapName) + : mapAsset.Native!.Reference == 0x808091DE && mapAsset.Native.Name == mapName, "Scenario stem must match the target map's native name."); + byte[] ReadMap(uint tag) => project.AddedAssets.SingleOrDefault(asset => asset.Native is { } native && NativeTag(native) == tag) is { } own + ? project.ReadAddedAsset(own.Id, catalog) : project.ReadAsset(tag, catalog); + var sourceMapData = Sized(Installed(sourceMap, 0x808091DE), 40); + var targetMapData = Sized(ReadMap(recipe.MapRootTag), 40); + var sourceDefinition = Sized(Installed(sourceMapData.U32(8), 0x80809962), 64); + var targetDefinition = Sized(ReadMap(targetMapData.U32(8)), 64); + int[] sourceBubbles = Rows(sourceDefinition, 32, 0x808098C2, 80), targetBubbles = Rows(targetDefinition, 32, 0x808098C2, 80); + Require(sourceBubbles.Length is > 0 and <= 64 && sourceBubbles.Length == targetBubbles.Length, + "STANDALONE_ACTIVITY_SUBSET: choose the template map or a whole-map copy with the same bubbles."); + for (int i = 0; i < sourceBubbles.Length; i++) + Require(sourceDefinition.U32(sourceBubbles[i]) == targetDefinition.U32(targetBubbles[i]) + && sourceDefinition.U32(sourceBubbles[i] + 72) == (uint)i && targetDefinition.U32(targetBubbles[i] + 72) == (uint)i + && sourceDefinition.U32(sourceBubbles[i] + 4) < 256 && targetDefinition.U32(targetBubbles[i] + 4) < 256, + "STANDALONE_ACTIVITY_SUBSET: target map changes bubble identities or order."); + uint identity = Hash("studio:activity-definition:" + recipe.InternalName); + Require(!ReadDefinitions(definitions).Any(row => row.Hash == identity || row.Name == recipe.InternalName), "Activity identity already exists."); + Require(!catalog.NamedTags.Any(row => row.Name == recipe.InternalName || row.Name == recipe.InternalName + ":scenario_client" + || row.ClassHash == 0x80808AAE && Hash(row.Name) == Hash(recipe.InternalName)), "Activity native name already exists."); + var nodes = new List<(uint Source, uint Class, byte[] Data, string? Name)> + { + (sourceRoot, 0x80808AAE, root.ToArray(), recipe.InternalName), + (sourceScenario, 0x80809994, RebindScenario(scenario, template.Name, recipe.InternalName, recipe.ScenarioStem), recipe.InternalName + ":scenario_client") + }; + var sliceTags = new List(); var registryTags = new SortedSet(); var objectTags = new SortedSet(); + int[] bubbles = Rows(original, 80, 0x8080924D, 24); + Require(bubbles.Length is > 0 and <= 64, "Scenario has no bubbles."); + foreach (int bubble in bubbles) + { + int mapIndex = Array.FindIndex(sourceBubbles, at => sourceDefinition.U32(at) == original.U32(bubble)); + Require(mapIndex >= 0, "Scenario bubble is absent from the template map."); + int[] states = Rows(original, bubble + 8, 0x8080924F, 76); + Require(states.Length <= 8, "Scenario has too many states."); + foreach (int state in states) + { + Require(original.U32(state + 64) == original.U32(bubble) + && original.U32(state + 28) == sourceDefinition.U32(sourceBubbles[mapIndex] + 4) + && original.Span(state + 32, 32).SequenceEqual(sourceDefinition.Span(sourceBubbles[mapIndex] + 40, 32)), + "Scenario state differs from its template bubble."); + // Whole copies may add connection keys; each state follows its bubble's full mask. + targetDefinition.Span(targetBubbles[mapIndex] + 40, 32).CopyTo(nodes[1].Data.AsSpan(state + 32)); + BinaryPrimitives.WriteUInt32LittleEndian(nodes[1].Data.AsSpan(state + 28), targetDefinition.U32(targetBubbles[mapIndex] + 4)); + uint slice = original.U32(state + 68); + if (!sliceTags.Contains(slice)) sliceTags.Add(slice); + var sliceData = Sized(Installed(slice, 0x8080925B), 42); + Require(sliceData.U32(16) == (uint)Array.IndexOf(bubbles, bubble) && Text(sliceData, 40) == sourceStem, + "Scenario slice ordinal or stem differs."); + registryTags.Add(sliceData.U32(20)); + } + } + foreach (uint registry in registryTags) + { + var data = Sized(Installed(registry, 0x8080925E), 56); + foreach (int field in new[] { 8, 24, 40 }) + foreach (int at in Rows(data, field, 0x80809260, 4)) + { + uint tag = data.U32(at); var obj = Sized(Installed(tag, 0x80809462), 72); + Require(obj.U32(8) == Hash(sourceStem) || obj.U32(8) == 0x811C9DC5, + "STANDALONE_OBJECT_WORD: object belongs to an unknown map stem."); + foreach (int slot in Rows(obj, 32, 0x80809B3A, 8)) Require(obj.U32(slot) is >= 1 and <= 72, "Unsupported object slot."); + foreach (int block in Rows(obj, 56, 0x80809464, 24)) + { Require(obj.I32(block) is >= -1 and < 64, "Invalid object bubble ordinal."); _ = Rows(obj, block + 8, 0x80809466, 4); } + if (obj.U32(8) != 0x811C9DC5) objectTags.Add(tag); + } + } + foreach (uint tag in sliceTags) nodes.Add((tag, 0x8080925B, Installed(tag, 0x8080925B), null)); + foreach (uint tag in registryTags) nodes.Add((tag, 0x8080925E, Installed(tag, 0x8080925E), null)); + foreach (uint tag in objectTags) nodes.Add((tag, 0x80809462, Installed(tag, 0x80809462), null)); + int manifests = nodes.Count(node => catalog.TryGetEntry(node.Source, out var entry) && (entry.TypeInfo & 0xF000) == 0x2000); + Require(recipe.FirstEntryIndex + nodes.Count + 2 + manifests <= 8192, "Activity package has no room for its entries and manifests."); + uint Tag(int i) => recipe.Tag(i); + var mapped = nodes.Select((node, i) => (node.Source, Tag: Tag(i))).ToDictionary(pair => pair.Source, pair => pair.Tag); + uint textTag = Tag(nodes.Count), textDataTag = Tag(nodes.Count + 1); + Put(nodes[0].Data, 8, Hash(recipe.InternalName)); Put(nodes[0].Data, 64, mapped[sourceScenario]); + Put(nodes[1].Data, 40, textTag); + foreach (int bubble in bubbles) + foreach (int state in Rows(original, bubble + 8, 0x8080924F, 76)) Put(nodes[1].Data, state + 68, mapped[original.U32(state + 68)]); + for (int i = 2; i < nodes.Count; i++) + { + var node = nodes[i]; var data = new NativeRows(node.Data); + if (node.Class == 0x8080925B) nodes[i] = node with { Data = RebindSlice(node.Data, recipe.ScenarioStem, mapped[data.U32(20)]) }; + else if (node.Class == 0x80809462) Put(node.Data, 8, Hash(recipe.ScenarioStem)); + else foreach (int field in new[] { 8, 24, 40 }) + foreach (int at in Rows(data, field, 0x80809260, 4)) if (mapped.TryGetValue(data.U32(at), out uint target)) Put(node.Data, at, target); + } + var additions = new List(); + for (int i = 0; i < nodes.Count; i++) + { + var node = nodes[i]; catalog.TryGetEntry(node.Source, out var entry); + additions.Add(new(recipe.InternalName + $"-{i}.bin", node.Data, + new(recipe.PackageId, node.Class, entry!.TypeInfo, node.Name, recipe.FirstEntryIndex + i), node.Source)); + } + var labels = new Dictionary { [Hash(recipe.ScenarioStem)] = recipe.DisplayName }; + // Authored text contains no installed strings; all areas receive the requested world title. + foreach (int bubble in bubbles) labels.TryAdd(original.U32(bubble), recipe.DisplayName); + var text = LocalizedText(labels, textDataTag); + additions.Add(new(recipe.InternalName + "-text.bin", text.Container, new(recipe.PackageId, 0x80809A88, 0x100A, null, recipe.FirstEntryIndex + nodes.Count))); + additions.Add(new(recipe.InternalName + "-english.bin", text.Data, new(recipe.PackageId, 0x80809A8A, 0x100A, null, recipe.FirstEntryIndex + nodes.Count + 1))); + return new(additions, new(recipe.TemplateActivity, identity, recipe.InternalName, recipe.Type, recipe.Destination)); + } + + public static void ValidateType(byte[] investment, byte[] client, byte type, string? nativeName = null) + { + var inv = Sized(investment, 24); var cli = Sized(client, 24); + int[] types = Rows(inv, 8, 0x80807778, 16), clients = Rows(cli, 8, 0x80805F40, 128); + Require(types.Length == 54 && clients.Length == 54 + && types.Select(inv.U32).SequenceEqual(clients.Select(cli.U32)), "Activity type tables differ."); + Require(type < types.Length, "Unknown activity type."); + string name = nativeName ?? ProvenTypes.GetValueOrDefault(type, $"native type {type}"); + Require(client[clients[type] + 0x78] != 0, $"ORBIT_ROUTE: {name} sends the player to orbit."); + Require(investment[types[type] + 10] == 0 || type == 15, $"PVP_RUMBLE_ONLY: {name} is not supported; choose Rumble."); + Require(ProvenTypes.ContainsKey(type), $"ACTIVITY_TYPE_UNPROVEN: {name} has no proven standalone-copy export."); + } + + /** Native type labels are optional presentation; routing still requires both exact type tables. */ + public static IReadOnlyDictionary ReadTypeNames(PackageCatalog catalog) + { + var names = Enumerable.Range(0, 54).ToDictionary(value => (byte)value, + value => ProvenTypes.GetValueOrDefault((byte)value, $"Native type {value}")); + if (!catalog.TryGetEntry(0x81A27211, out _)) return names; // string bank index + var banks = Sized(catalog.ReadOriginal(0x81A27211), 24); + int[] bankRows = Rows(banks, 8, 0x80805F9E, 8); + var types = Sized(catalog.ReadOriginal(0x81327D64), 24); + int[] rows = Rows(types, 8, 0x80805F40, 128); + var containers = rows.Select(at => types.U16(at + 4)).Where(index => index < bankRows.Length) + .Select(index => banks.U32(bankRows[index] + 4)).Distinct().ToArray(); + var strings = LocalizedStrings.LoadBanks(catalog, containers); + for (int i = 0; i < rows.Length && i < 54; i++) + { + int bank = types.U16(rows[i] + 4); + if (bank < bankRows.Length && strings.Get(banks.U32(bankRows[bank] + 4), types.U32(rows[i] + 8)) is { Length: > 0 } text) + names[(byte)i] = text; + } + return names; + } + + private static uint Named(PackageCatalog catalog, string name, uint cls) + { + uint[] tags = catalog.NamedTags.Where(row => row.Name == name && row.ClassHash == cls + && catalog.TryGetEntry(row.TagHash, out var entry) && catalog.ContainsInstalledPackage(entry.PackageId)) + .Select(row => row.TagHash).Distinct().ToArray(); + Require(tags.Length == 1, $"Expected one installed {name}."); return tags[0]; + } + private static void Put(byte[] bytes, int at, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(at), value); + private static uint NativeTag(NativeAssetMetadata native) => checked(0x80800000U + ((uint)native.PackageId << 13) + (uint)native.EntryIndex!.Value); +} diff --git a/src/SunriseStudio.Authoring/ActivityRegistrationIdentity.cs b/src/SunriseStudio.Authoring/ActivityRegistrationIdentity.cs new file mode 100644 index 00000000..eaf2def8 --- /dev/null +++ b/src/SunriseStudio.Authoring/ActivityRegistrationIdentity.cs @@ -0,0 +1,118 @@ +using System.Text; +using static SunriseStudio.Authoring.ActivityRegistrationTables; + +namespace SunriseStudio.Authoring; + +/** Scenario symbols and map stems use FNV-1, with the native suffix-sharing string pool. */ +public static class ActivityRegistrationIdentity +{ + public static uint Hash(string text) + { + uint value = 0x811C9DC5; + foreach (byte item in Encoding.UTF8.GetBytes(text)) value = unchecked(value * 0x01000193) ^ item; + return value; + } + + public static byte[] RebindScenario(byte[] original, string sourceName, string name, string stem) + { + var data = Sized(original, 140); + Require(data.U32(8) == Hash(sourceName) && data.U32(12) == 0, "Scenario identity differs from its activity."); + int[] symbols = Rows(data, 64, 0x8080924A, 16); + Require(symbols.Length is > 0 and <= 8192, "Scenario symbols are absent."); + var fields = new List { 48 }; + var seen = new HashSet(); + int primary = -1; + foreach (int at in symbols) + { + string text = Text(data, Relative(data, at + 8, 96)); + Require(data.U32(at) == Hash(text) && data.U32(at + 4) == 0 && data.U32(at) != Hash(name) + && seen.Add(data.U32(at)), "Scenario symbol identity collides."); + if (text == sourceName) { Require(primary < 0, "Duplicate primary scenario symbol."); primary = at; } + fields.Add(at + 8); + } + Require(primary >= 0, "Scenario primary symbol is absent."); + foreach (int at in Rows(data, 96, 0x8080924B, 24)) // sequence references + { + Require(data.U32(at + 20) == 0 && (data.I64(at + 8) == 0) == (data.U32(at + 16) == uint.MaxValue), + "SCENARIO_STRING_PROFILE: unsupported sequence string."); + if (data.I64(at + 8) != 0) fields.Add(at + 8); + } + fields.Sort(); + int[] targets = fields.Select(field => Relative(data, field, 96)).ToArray(); + int tail = targets[0]; + Require(tail >= 12 && data.U32(tail - 12) == 0x80800065 && data.U64(tail - 8) == (ulong)(original.Length - tail), + "SCENARIO_STRING_PROFILE: unsupported scenario string pool."); + string[] texts = targets.Select(target => Text(data, target, original.Length - target)).ToArray(); + var before = Pool(texts); + Require(before.Bytes.AsSpan().SequenceEqual(original.AsSpan(tail)) && before.Starts.Select(at => at + tail).SequenceEqual(targets), + "SCENARIO_STRING_PROFILE: scenario pool is not canonical."); + Require(data.U32(32) == Hash(texts[0]), "Scenario stem hash differs."); + texts[fields.IndexOf(48)] = stem; texts[fields.IndexOf(primary + 8)] = name; + var pool = Pool(texts); var output = new ActivityBytes(original[..tail]); output.Add(pool.Bytes); + for (int i = 0; i < fields.Count; i++) output.I64(fields[i], tail + pool.Starts[i] - fields[i]); + output.I64(tail - 8, pool.Bytes.Length); output.U32(8, Hash(name)); output.U32(32, Hash(stem)); output.U32(primary, Hash(name)); + return output.Finish(); + } + + private static (byte[] Bytes, int[] Starts) Pool(IEnumerable texts) + { + var bytes = new List(); var placed = new List<(int At, string Text)>(); var starts = new List(); + foreach (string text in texts) + { + Require(text.Length > 0 && !text.Contains('\0') && text.All(c => c < 128), "Invalid scenario pool text."); + int at = -1; + foreach (var previous in placed) + if (previous.Text.EndsWith(text, StringComparison.Ordinal)) { at = previous.At + previous.Text.Length - text.Length; break; } + if (at < 0) { at = bytes.Count; placed.Add((at, text)); bytes.AddRange(Encoding.ASCII.GetBytes(text + "\0")); } + starts.Add(at); + } + return (bytes.ToArray(), starts.ToArray()); + } + + public static byte[] RebindSlice(byte[] original, string stem, uint registry) + { + var data = Sized(original, 42); + Require(data.I64(8) == 32 && data.U32(24) == 0 && data.U32(28) == 0x80800065 + && data.U64(32) == (ulong)(original.Length - 40) && original[^1] == 0 + && !original.AsSpan(40, original.Length - 41).Contains((byte)0), "Unsupported scenario slice layout."); + var output = new ActivityBytes(original[..40]); output.Add(Encoding.ASCII.GetBytes(stem + "\0")); + output.I64(32, stem.Length + 1); output.U32(20, registry); return output.Finish(); + } + + /** Thirteen language slots share the authored text, matching localized_strings.build. */ + public static (byte[] Container, byte[] Data) LocalizedText(IReadOnlyDictionary entries, uint dataTag) + { + Require(entries.Count is > 0 and <= 65535 && !entries.ContainsKey(0x811C9DC5), "Invalid localized keys."); + var sorted = entries.OrderBy(pair => pair.Key).ToArray(); + var container = new ActivityBytes(80); + for (int i = 0; i < 13; i++) container.U32(24 + i * 4, dataTag); + int[] keys = container.Array(8, 0x80800070, 4, new byte[sorted.Length * 4], true); + for (int i = 0; i < keys.Length; i++) container.U32(keys[i], sorted[i].Key); + var data = new ActivityBytes(88); + int[] parts = data.Array(8, 0x80809A90, 32, new byte[sorted.Length * 32], true); + var encoded = new List(); var shifts = new List(); var counts = new List(); + foreach (var (_, text) in sorted) + { + try { _ = new UTF8Encoding(false, true).GetByteCount(text); } + catch (EncoderFallbackException error) { throw new InvalidDataException("Localized text contains an invalid surrogate.", error); } + int[] points = text.EnumerateRunes().Select(rune => rune.Value).ToArray(); + Require(points.Length is > 0 and < 65536 && !points.Contains(0), "Invalid localized text."); + int shift = points.Min() - 1; + Require(shift < 65536, "Localized text exceeds native shift."); + byte[] bytes = Encoding.UTF8.GetBytes(string.Concat(points.Select(point => char.ConvertFromUtf32(point - shift)))); + Require(bytes.Length < 65536, "Localized text is too long."); + encoded.Add(bytes); shifts.Add((ushort)shift); counts.Add(points.Length); + } + data.Array(40, 0x80800006, 2, new byte[2], true); + int payload = data.Array(56, 0x80800005, 1, [.. encoded.SelectMany(bytes => bytes), 0], true)[0]; + int[] strings = data.Array(72, 0x80809A8E, 16, new byte[sorted.Length * 16], true); + for (int i = 0; i < parts.Length; i++) + { + int at = parts[i]; data.I64(at + 8, payload - at - 8); data.U32(at + 16, 0x811C9DC5); + data.U16(at + 20, (ushort)encoded[i].Length); data.U16(at + 22, (ushort)counts[i]); + data.U16(at + 24, shifts[i]); data.U16(at + 26, 0xF400); + data.I64(strings[i], at - strings[i]); data.I64(strings[i] + 8, 1); payload += encoded[i].Length; + } + return (container.Finish(), data.Finish()); + } +} diff --git a/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs b/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs new file mode 100644 index 00000000..189f0140 --- /dev/null +++ b/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs @@ -0,0 +1,193 @@ +using System.Buffers.Binary; +using System.Text; + +namespace SunriseStudio.Authoring; + +public sealed record ActivityDefinition(int Index, uint Hash, int Offset, string Name, byte Type, byte Destination); +public sealed record ActivityClientDefinition(uint Hash, int Offset, int DisplayIndex); +public sealed record ActivityTableAddition(uint TemplateHash, uint Hash, string Name, byte Type, byte Destination); + +/** Native fixed-record relocation retains immutable policy at its installed offsets. */ +public static class ActivityRegistrationTables +{ + public const uint DefinitionTag = 0x81327CF0, ClientTag = 0x81327D35; + public const uint DefinitionClass = 0x808076F0, ClientClass = 0x80805E0A; + private static readonly int[] DefinitionPointers = [16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 104, 112, 128, 144, 168, 192, 208]; + private static readonly int[] ClientPointers = [0, 16, 32, 48, 72, 80, 96, 112, 120]; + + public static IReadOnlyList ReadDefinitions(byte[] bytes) + { + var data = Sized(bytes, 136); + int[] index = Rows(data, 8, 0x808076FC, 16); // activity definition index + Require(index.Length is > 0 and <= 4095 && index[0] >= 156, "Invalid activity index framing."); + var result = new List(); + var seen = new HashSet(); + int previous = 0; + foreach (int at in index) + { + uint hash = data.U32(at); + int pos = Relative(data, at + 8, 136); + Require(hash is not (0 or uint.MaxValue) && seen.Add(hash) && data.U32(at + 4) == 0 + && pos >= 140 && pos > previous && pos <= bytes.Length - 232 + && (pos + 232 <= index[0] - 20 || pos - 4 >= index[^1] + 16) + && (previous == 0 || previous + 232 <= pos - 4), "Invalid activity record extent or identity."); + Require(data.U32(pos - 4) == 0x80807711 && data.U32(pos) == hash, "Activity record class or identity differs."); + foreach (int field in DefinitionPointers) _ = Relative(data, pos + field, 136); + int name = Relative(data, pos + 104, 136); + int match = Relative(data, pos + 32, 136); + Require(match != 0, "Activity matchmaking policy is absent."); + uint tag = data.U32(match); + Require((tag == uint.MaxValue || tag is >= 0x80800000 and <= 0x83FFFFFF) + && bytes[pos + 218] < 54 && bytes[pos + 224] < 48, "Invalid activity policy."); + result.Add(new(result.Count, hash, pos, name == 0 ? "" : Text(data, name, 256), bytes[pos + 218], bytes[pos + 224])); + previous = pos; + } + return result; + } + + public static IReadOnlyList ReadClients(byte[] bytes) + { + var data = Sized(bytes, 120); + int[] index = Rows(data, 8, 0x80805E15, 16), display = Rows(data, 24, 0x80805E23, 36); + Require(index.Length is > 0 and <= 4095 && display.Length > 0 && index[0] >= 140 + && display[0] > index[^1] + 16, "Invalid client activity framing."); + var result = new List(); + var seen = new HashSet(); + int previous = 0; + foreach (int at in index) + { + uint hash = data.U32(at); + int pos = Relative(data, at + 8, 120); + Require(hash is not (0 or uint.MaxValue) && seen.Add(hash) && data.U32(at + 4) == 0 + && pos % 8 == 0 && pos - 4 >= index[^1] + 16 && pos > previous + && pos + 136 <= display[0] - 16 && (previous == 0 || previous + 136 <= pos - 4), + "Invalid client activity extent or identity."); + Require(data.U32(pos - 4) == 0x80805E18, "Client activity record class differs."); + foreach (int field in ClientPointers) _ = Relative(data, pos + field, 120); + int target = Relative(data, pos, 120), slot = Array.IndexOf(display, target); + Require(slot >= 0, "Client activity display is outside its table."); + result.Add(new(hash, pos, slot)); previous = pos; + } + return result; + } + + public static (byte[] Definitions, byte[] Clients) Append(byte[] definitions, byte[] clients, + IReadOnlyList additions) + { + var original = ReadDefinitions(definitions); var client = ReadClients(clients); + Require(original.Select(row => row.Hash).SequenceEqual(client.Select(row => row.Hash)), "Activity table indices differ."); + Require(additions.Count > 0 && original.Count + additions.Count <= 4095, "Activity catalog capacity exceeded."); + var hashes = original.Select(row => row.Hash).ToHashSet(); + var names = original.Select(row => row.Name).ToHashSet(StringComparer.Ordinal); + foreach (var item in additions) + { + Require(original.Any(row => row.Hash == item.TemplateHash), "Choose an installed template activity."); + Require(item.Hash is not (0 or uint.MaxValue) && hashes.Add(item.Hash) && names.Add(item.Name) + && System.Text.RegularExpressions.Regex.IsMatch(item.Name, "\\A[a-z][a-z0-9_]{0,38}\\z"), "Activity identity or name collides."); + Require(item.Type < 54 && item.Destination < 48, "Invalid activity type or destination."); + } + var inv = new ActivityBytes(definitions); + var positions = original.Select(row => row.Offset).ToList(); + foreach (var item in additions) + { + int old = original.Single(row => row.Hash == item.TemplateHash).Offset; + int pos = inv.Object(0x80807711, new byte[232]); + inv.Copy(pos, Relocate(definitions, old, pos, 232, DefinitionPointers, 136)); + inv.U32(pos, item.Hash); + int name = inv.Add(Encoding.ASCII.GetBytes(item.Name + "\0")); inv.I64(pos + 104, name - pos - 104); + inv.Byte(pos + 218, item.Type); inv.Byte(pos + 224, item.Destination); + positions.Add(pos); + } + uint[] identities = [.. original.Select(row => row.Hash), .. additions.Select(row => row.Hash)]; + int[] indices = inv.Array(8, 0x808076FC, 16, new byte[positions.Count * 16]); + for (int i = 0; i < indices.Length; i++) { inv.U32(indices[i], identities[i]); inv.I64(indices[i] + 8, positions[i] - indices[i] - 8); } + byte[] result = inv.Finish(); _ = ReadDefinitions(result); + Require(result.AsSpan(24, definitions.Length - 24).SequenceEqual(definitions.AsSpan(24)), "Installed activity bytes changed."); + + var cli = new ActivityBytes(clients); + var sources = client.Concat(additions.Select(item => client.Single(row => row.Hash == item.TemplateHash))).ToArray(); + indices = cli.Array(8, 0x80805E15, 16, new byte[sources.Length * 16]); positions.Clear(); + foreach (var row in sources) + { + int pos = cli.Object(0x80805E18, new byte[136]); + cli.Copy(pos, Relocate(clients, row.Offset, pos, 136, ClientPointers, 120)); positions.Add(pos); + } + int[] oldDisplay = Rows(new NativeRows(clients), 24, 0x80805E23, 36); + int[] displays = cli.Array(24, 0x80805E23, 36, oldDisplay.SelectMany(at => clients.AsSpan(at, 36).ToArray()).ToArray()); + for (int i = 0; i < indices.Length; i++) + { + cli.U32(indices[i], identities[i]); cli.I64(indices[i] + 8, positions[i] - indices[i] - 8); + cli.I64(positions[i], displays[sources[i].DisplayIndex] - positions[i]); + } + byte[] paired = cli.Finish(); _ = ReadClients(paired); + Require(paired.AsSpan(40, clients.Length - 40).SequenceEqual(clients.AsSpan(40)), "Installed client bytes changed."); + return (result, paired); + } + + private static byte[] Relocate(byte[] bytes, int old, int next, int size, int[] fields, int minimum) + { + var data = new NativeRows(bytes); byte[] result = bytes.AsSpan(old, size).ToArray(); + foreach (int field in fields) + { + int target = Relative(data, old + field, minimum); + if (target == 0) continue; + if (target >= old && target < old + size) target += next - old; + BinaryPrimitives.WriteInt64LittleEndian(result.AsSpan(field), target - next - field); + } + return result; + } + + internal static NativeRows Sized(byte[] bytes, int minimum) + { + Require(bytes.Length >= minimum && bytes.Length <= 4 * 1024 * 1024, "Invalid activity resource size."); + var data = new NativeRows(bytes); Require(data.U64(0) == (ulong)bytes.Length, "Activity resource size differs."); return data; + } + internal static int[] Rows(NativeRows data, int field, uint cls, int stride) + { + try { return data.Rows(field, cls, stride); } + catch (OverflowException error) { throw new InvalidDataException("Activity array leaves its resource.", error); } + } + internal static int Relative(NativeRows data, int at, int minimum) + { + long relative = data.I64(at); if (relative == 0) return 0; + Require(relative >= minimum - (long)at && relative < data.Bytes.Length - (long)at, "Activity pointer leaves its resource."); + return (int)(at + relative); + } + internal static string Text(NativeRows data, int at, int capacity = 128) + { + int end = Array.IndexOf(data.Bytes, (byte)0, at, Math.Min(capacity, data.Bytes.Length - at)); + Require(end >= at && data.Bytes.AsSpan(at, end - at).IndexOfAnyInRange((byte)128, byte.MaxValue) < 0, "Invalid activity string."); + return Encoding.ASCII.GetString(data.Bytes, at, end - at); + } + internal static void Require(bool valid, string message) { if (!valid) throw new InvalidDataException(message); } +} + +/** Activity arrays use the Python oracle's padded layout; scenario and text arrays use tight native framing. */ +internal sealed class ActivityBytes +{ + private readonly MemoryStream stream = new(); + internal ActivityBytes(byte[] bytes) => stream.Write(bytes); + internal ActivityBytes(int size) : this(new byte[size]) { } + internal int Length => checked((int)stream.Length); + internal Span Span(int at) => stream.GetBuffer().AsSpan(at, Length - at); + internal int Add(byte[] bytes) { int at = Length; stream.Position = at; stream.Write(bytes); return at; } + internal void Copy(int at, byte[] bytes) => bytes.CopyTo(Span(at)); + internal void U32(int at, uint value) => BinaryPrimitives.WriteUInt32LittleEndian(Span(at), value); + internal void U16(int at, ushort value) => BinaryPrimitives.WriteUInt16LittleEndian(Span(at), value); + internal void I64(int at, long value) => BinaryPrimitives.WriteInt64LittleEndian(Span(at), value); + internal void Byte(int at, byte value) => Span(at)[0] = value; + internal int Object(uint cls, byte[] bytes) + { + Add(new byte[(-(Length + 4)) & 7]); int marker = Add(new byte[4]); U32(marker, cls); return Add(bytes); + } + internal int[] Array(int field, uint cls, int stride, byte[] rows, bool tight = false) + { + if (rows.Length == 0) { I64(field, 0); I64(field + 8, 0); return []; } + int count = rows.Length / stride; + int first = tight ? (Length + 35) & ~15 : ((Length + 15) & ~15) + 32; + Add(new byte[first - Length]); U32(first - 20, 0x80809FBD); I64(first - 16, count); U32(first - 8, cls); + Add(rows); I64(field, count); I64(field + 8, first - field - 24); + return Enumerable.Range(0, count).Select(i => first + i * stride).ToArray(); + } + internal byte[] Finish() { I64(0, Length); ActivityRegistrationTables.Require(Length <= 4 * 1024 * 1024, "Activity resource exceeds capacity."); return stream.ToArray(); } +} diff --git a/src/SunriseStudio.Authoring/NativeRows.cs b/src/SunriseStudio.Authoring/NativeRows.cs new file mode 100644 index 00000000..ba7374d2 --- /dev/null +++ b/src/SunriseStudio.Authoring/NativeRows.cs @@ -0,0 +1,36 @@ +using System.Buffers.Binary; + +namespace SunriseStudio.Authoring; + +/** Bounds-checked little-endian reads over one tag payload, and its typed array headers. Activity registration reads through it. */ +internal sealed class NativeRows(byte[] bytes) +{ + internal byte[] Bytes { get; } = bytes; + internal uint U32(int p) => BinaryPrimitives.ReadUInt32LittleEndian(Span(p, 4)); + internal int I32(int p) => BinaryPrimitives.ReadInt32LittleEndian(Span(p, 4)); + internal ushort U16(int p) => BinaryPrimitives.ReadUInt16LittleEndian(Span(p, 2)); + internal ulong U64(int p) => BinaryPrimitives.ReadUInt64LittleEndian(Span(p, 8)); + internal long I64(int p) => BinaryPrimitives.ReadInt64LittleEndian(Span(p, 8)); + + internal ReadOnlySpan Span(int offset, int count) + { + if (offset < 0 || count < 0 || offset > Bytes.Length - count) throw new InvalidDataException("Placement range leaves its source."); + return Bytes.AsSpan(offset, count); + } + + /** Row offsets of the typed array whose count and relative pointer sit at field. */ + internal int[] Rows(int field, uint type, int stride) + { + long count = I64(field), relative = I64(field + 8); + if (count == 0 && relative == 0) return []; + int header = checked((int)(field + 8 + relative)); + if (count is < 0 or > 1_000_000 || U32(header - 4) != ArrayMarker || I64(header) != count + || U32(header + 8) != type || U32(header + 12) != 0) + throw new InvalidDataException("Placement array layout is invalid."); + Span(header + 16, checked((int)count * stride)); + return Enumerable.Range(0, (int)count).Select(i => checked(header + 16 + i * stride)).ToArray(); + } + + // The word just before every typed array header. + internal const uint ArrayMarker = 0x80809FBD; +} diff --git a/src/SunriseStudio.Editor/Creation/ActivityRegistrationWorkflow.cs b/src/SunriseStudio.Editor/Creation/ActivityRegistrationWorkflow.cs new file mode 100644 index 00000000..ba053bf7 --- /dev/null +++ b/src/SunriseStudio.Editor/Creation/ActivityRegistrationWorkflow.cs @@ -0,0 +1,120 @@ +using SunriseStudio.Authoring; +using SunriseStudio.Formats; +using SunriseStudio.Packages; +using SunriseStudio.Projects; +using SunriseStudio.Viewport; + +namespace SunriseStudio.Editor.Creation; + +/** Installed table rows supply display and launch policy; the project owns the new scenario identity. */ +public sealed class ActivityRegistrationWorkflow : CreationWorkflow +{ + private readonly StudioProject? project; + private readonly PackageCatalog? catalog; + private readonly int revision; + private readonly CreationField template, definition, map, name, display, type, destination, stem, package, warning; + private readonly IReadOnlyList definitions; + private readonly IReadOnlyDictionary templateRows; + private readonly IReadOnlyDictionary typeNames; + private uint? previousTemplate, previousMap; + private string previousDefinition = ""; + + public ActivityRegistrationWorkflow(StudioWorkspace workspace) + { + project = workspace.Project; catalog = workspace.Catalog; revision = workspace.ProjectRevision; + definitions = catalog is null ? [] : ActivityRegistrationTables.ReadDefinitions(catalog.ReadOriginal(ActivityRegistrationTables.DefinitionTag)); + typeNames = catalog is null ? ActivityRegistrationCompiler.ProvenTypes : ActivityRegistrationCompiler.ReadTypeNames(catalog); + templateRows = catalog?.NamedTags.Where(row => row.ClassHash == 0x80808AAE).GroupBy(row => row.TagHash) + .ToDictionary(group => group.Key, group => definitions.Where(row => group.Any(name => name.Name == row.Name)) + .Select(row => new CreationChoice(row.Hash, $"{typeNames[row.Type]} / row {row.Index}", row.Hash.ToString("X8"))).ToArray()) ?? []; + template = RowPick("Template activity", true, "Installed activity root and definition policy", + () => workspace.Assets, row => row.Entry.Reference == 0x80808AAE); + definition = new("Template row", CreationFieldKind.Scalar, true, "Installed activity definition identity") + { Encoding = ScalarEncoding.UInt32, Hexadecimal = true, Choices = TemplateRows }; + map = RowPick("Map root", true, "Named map root", () => workspace.Assets, row => row.Entry.Reference == 0x808091DE); + name = new("Internal name", CreationFieldKind.Text, true, "Activity/scenario name hash") { Hint = "A lowercase letter, then lowercase letters, digits or underscores. Up to 39 characters." }; + display = new("Display name", CreationFieldKind.Text, true, "Scenario title and area text"); + type = new("Type", CreationFieldKind.Scalar, true, "Definition +218") + { Encoding = ScalarEncoding.UInt8, Choices = () => ActivityRegistrationCompiler.ProvenTypes.Select(pair => new CreationChoice(pair.Key, typeNames[pair.Key])).ToArray() }; + destination = new("Destination index", CreationFieldKind.Scalar, true, "Definition +224") { Encoding = ScalarEncoding.UInt8, Hint = "0 to 47. Starts with the template's destination." }; + stem = new("Scenario stem", CreationFieldKind.Text, true, "Scenario +32/+48 map lookup") { Hint = "Must match map::root. The complete map name must be under 64 bytes." }; + package = PackageField(workspace); + warning = new("Status", CreationFieldKind.Rows, true, "Runtime verification") + { DrawRows = () => StudioUi.Wip(ActivityRegistrationCompiler.WipReason) }; + } + + public override string Title => "Register activity"; + public override uint? AnchorTag => template.Tag; + public override IReadOnlyList Fields => [warning, template, definition, map, name, display, type, destination, stem, package]; + public override IReadOnlyList Limits => [ActivityRegistrationCompiler.WipReason, + "Choose the template map or a whole-map copy with the same bubbles.", + "Keeps the template's client display and gameplay policy. The display name sets the scenario title and area text in all languages.", + "Two mods registering activities may conflict. No Director node or launch action is created."]; + + private IReadOnlyList TemplateRows() => template.Tag is { } tag ? templateRows.GetValueOrDefault(tag) ?? [] : []; + + public override void Update(StudioWorkspace workspace) + { + if (template.Tag != previousTemplate) + { previousTemplate = template.Tag; definition.Text = TemplateRows().FirstOrDefault()?.Value.ToString("X8") ?? ""; } + if (definition.Text != previousDefinition) + { + previousDefinition = definition.Text; + if (definition.TryParse(out ulong hash) && definitions.FirstOrDefault(row => row.Hash == hash) is { } row) + { type.Text = row.Type.ToString(); destination.Text = row.Destination.ToString(); } + } + if (map.Tag != previousMap) + { + previousMap = map.Tag; + string? nativeName = project?.AddedAssets.FirstOrDefault(asset => asset.Native is { } native && ProjectTags.Tag(native) == map.Tag)?.Native?.Name + ?? catalog?.NamedTags.FirstOrDefault(row => row.TagHash == map.Tag && row.ClassHash == 0x808091DE)?.Name; + if (nativeName is not null && nativeName.StartsWith("map:", StringComparison.Ordinal) && nativeName.EndsWith(":root", StringComparison.Ordinal)) + stem.Text = nativeName[4..^5]; + } + } + + protected override IEnumerable Validate(StudioWorkspace workspace) + { + if (project != workspace.Project || catalog != workspace.Catalog || workspace.ProjectRevision != revision) + { yield return "The project changed. Reopen this workflow."; yield break; } + if (template.Tag is not { } tag || catalog is null || !catalog.TryGetEntry(tag, out var entry) + || !catalog.ContainsInstalledPackage(entry.PackageId) || entry.Reference != 0x80808AAE) + { yield return "Choose an installed template activity."; yield break; } + if (!definition.TryParse(out ulong hash) || !TemplateRows().Any(row => row.Value == hash)) + yield return "Choose an installed row of the template activity."; + if (PackageProblem(workspace, package) is { } problem) yield return problem; + string? invalid = null; + try + { + var recipe = Recipe(); recipe.Validate(); + if (project!.AddedActivities.Any(activity => activity.InternalName == recipe.InternalName)) invalid = "Activity name already exists in this project."; + else if (!ActivityRegistrationCompiler.ProvenTypes.ContainsKey(recipe.Type)) invalid = $"ACTIVITY_TYPE_UNPROVEN: {typeNames[recipe.Type]}."; + else if (definitions.FirstOrDefault(row => row.Hash == recipe.TemplateActivity)?.Type != recipe.Type) invalid = "Choose a template of the requested type."; + } + catch (Exception error) when (error is InvalidDataException or FormatException or OverflowException) { invalid = error.Message; } + if (invalid is not null) yield return invalid; + } + + private AddedActivity Recipe() => new(Convert.ToUInt32(definition.Text, 16), name.Text, display.Text, + byte.Parse(type.Text), byte.Parse(destination.Text), map.Tag!.Value, stem.Text, PackageId(package), NextEntryIndex(project!, PackageId(package))); + + public override CreationFollowUp Create(StudioWorkspace workspace) + { + if (Problems(workspace) is { Count: > 0 } problems) throw new InvalidDataException(string.Join("\n", problems)); + var recipe = Recipe(); var plan = ActivityRegistrationCompiler.Prepare(project!, catalog!, recipe); + var recipes = project!.AddedActivities.Append(recipe).ToArray(); + var rows = project.AddedActivities.Select(item => ActivityRegistrationCompiler.Prepare(project, catalog!, item).Row).Append(plan.Row).ToArray(); + var tables = ActivityRegistrationTables.Append(catalog!.ReadOriginal(ActivityRegistrationTables.DefinitionTag), catalog.ReadOriginal(ActivityRegistrationTables.ClientTag), rows); + // Existing registrations must still re-derive before a new one replaces their table deltas. + _ = project.CompileActivities(catalog); + if (project.AddedActivities.Count == 0 && (project.ContainsEdit(ActivityRegistrationTables.DefinitionTag) || project.ContainsEdit(ActivityRegistrationTables.ClientTag))) + throw new InvalidDataException("Activity tables already have raw edits. Revert those edits before registering an activity."); + var added = workspace.ApplyAssetTransaction(plan.Additions, allocated => + { + if (ProjectTags.Tag(allocated[0].Native!) != recipe.Tag()) throw new InvalidDataException("Activity allocation changed."); + return new(new Dictionary { [ActivityRegistrationTables.DefinitionTag] = tables.Definitions, + [ActivityRegistrationTables.ClientTag] = tables.Clients }) { AddedActivities = recipes }; + }, "Registered activity"); + return new(AddedAssetId: added[0].Id, Status: "Registered activity. Requires the bounded Sunrise activity reader."); + } +} diff --git a/src/SunriseStudio.Editor/Creation/CreationTypes.Activities.cs b/src/SunriseStudio.Editor/Creation/CreationTypes.Activities.cs new file mode 100644 index 00000000..82a42d10 --- /dev/null +++ b/src/SunriseStudio.Editor/Creation/CreationTypes.Activities.cs @@ -0,0 +1,10 @@ +namespace SunriseStudio.Editor.Creation; + +public static partial class CreationTypes +{ + public const string ActivityKey = "Activity"; + + static partial void AddActivityTypes() => Add(ActivityKey, CreationMode.New, + new("Activity registration", "Register an activity for a map. WIP: requires the Sunrise bounded activity reader.", "", + workspace => new ActivityRegistrationWorkflow(workspace))); +} diff --git a/src/SunriseStudio.Editor/Creation/CreationTypes.cs b/src/SunriseStudio.Editor/Creation/CreationTypes.cs index c42e6caf..7aaf3aec 100644 --- a/src/SunriseStudio.Editor/Creation/CreationTypes.cs +++ b/src/SunriseStudio.Editor/Creation/CreationTypes.cs @@ -65,6 +65,7 @@ static CreationTypes() AddVendorTypes(); AddContentTypes(); AddEntityTypes(); + AddActivityTypes(); Add(OtherKey, CreationMode.New, new("Asset", "", "Use Add asset for raw files.")); Add(OtherKey, CreationMode.Clone, new(Duplicate, "A copy of this asset in a new package. May not work in game.", "")); } @@ -93,6 +94,7 @@ when entry.TagHash is not (InvestmentCatalog.ItemIndexTag or InvestmentCatalog.D private static string KeyOf(PackageEntry entry) => entry switch { + { Reference: 0x80808AAE, Type: 8 or 16 } => ActivityKey, { Type: 32, SubType: >= 1 and <= 3 } => TextureKey, { Reference: STechnique.Class } => MaterialKey, { Reference: SStaticMesh.Class } => StaticPropKey, @@ -120,4 +122,5 @@ _ when CuiDocument.Supports(document.Entry.Reference) && document.Entry.Type is static partial void AddVendorTypes(); static partial void AddContentTypes(); static partial void AddEntityTypes(); + static partial void AddActivityTypes(); } diff --git a/src/SunriseStudio.Editor/StudioForm.Browser.cs b/src/SunriseStudio.Editor/StudioForm.Browser.cs index f4de4d81..44416eab 100644 --- a/src/SunriseStudio.Editor/StudioForm.Browser.cs +++ b/src/SunriseStudio.Editor/StudioForm.Browser.cs @@ -329,6 +329,8 @@ private void DrawOtherCreation() CreationMenuItem("Director entry", CreationTypes.Director, () => StartCreation(CreationTypes.Director)); CreationMenuItem("Door from model", CreationTypes.Door, () => StartCreation(CreationTypes.Door)); ImGui.Separator(); + var activity = CreationTypes.For(CreationTypes.ActivityKey, CreationMode.New); + CreationMenuItem("Register activity", activity, () => StartCreation(activity)); foreach (var type in CreationTypes.Blocked) CreationMenuItem(type.Name, type, () => { }); ImGui.EndPopup(); } diff --git a/src/SunriseStudio.Editor/StudioWorkspace.Transactions.cs b/src/SunriseStudio.Editor/StudioWorkspace.Transactions.cs index d9ae29a3..7065a092 100644 --- a/src/SunriseStudio.Editor/StudioWorkspace.Transactions.cs +++ b/src/SunriseStudio.Editor/StudioWorkspace.Transactions.cs @@ -14,9 +14,11 @@ public IReadOnlyList ApplyAssetTransaction(IReadOnlyList(); var previousAdded = new Dictionary(StringComparer.Ordinal); IReadOnlyList created = []; + IReadOnlyList? previousActivities = null; MutateProject(() => created = project.ApplyTransaction(additions, allocated => { var proposed = editFactory(allocated); + if (proposed.AddedActivities is not null) previousActivities = project.AddedActivities.ToArray(); var changed = new Dictionary(); foreach (var (tag, proposedBytes) in proposed.Assets) { @@ -36,11 +38,12 @@ public IReadOnlyList ApplyAssetTransaction(IReadOnlyList? ObjectStates = null, IReadOnlyList? ConfigStates = null, ImportSelection? ReverseSelection = null, - IReadOnlyDictionary? ContentFiles = null); + IReadOnlyDictionary? ContentFiles = null) + { + public IReadOnlyList? ActivityStates { get; init; } + } private sealed record ImportSelection(uint Tag, string? AddedId, AssetOpenContext? Context); private readonly Stack undo = []; private readonly Stack redo = []; @@ -535,6 +538,7 @@ private void AdoptProject(StudioProject? project) } BeforeAssetMutation?.Invoke(); if (project is not null) project.ObjectEditCompiler ??= ObjectEditCompiler.Default; + if (project is not null) project.ActivityRegistrationCompiler ??= ActivityRegistrationCompiler.Default; if (project is not null) project.ConfigBindingCompiler ??= CuiConfigBindingCompiler.Default; Project = project; LastBuild = null; LastInstall = null; @@ -767,6 +771,7 @@ private EditFrame ReadFrame(EditFrame frame) StringComparer.Ordinal); var objects = frame.ObjectStates?.Keys.ToDictionary(key => key, Project!.FindObjectEdit, StringComparer.Ordinal); var next = frame with { Bytes = bytes, AddedStates = states, ObjectStates = objects, + ActivityStates = frame.ActivityStates is null ? null : Project!.AddedActivities.ToArray(), ConfigStates = frame.ConfigStates is null ? null : Project!.ConfigBindings.ToArray() }; return frame.ReverseSelection is not { } selection ? next : next with { @@ -797,7 +802,7 @@ private void RestoreFrame(EditFrame frame) var edits = frame.Selection == 0 && frame.AddedAssetId is { } id && frame.Bytes.ContainsKey(0) ? new ProjectAssetEdits(new Dictionary(), new Dictionary { [id] = frame.Bytes[0] }) : SplitAssetEdits(frame.Bytes); - Project!.RestoreTransaction(edits, frame.AddedStates ?? new Dictionary(), Catalog, + Project!.RestoreTransaction(edits with { AddedActivities = frame.ActivityStates }, frame.AddedStates ?? new Dictionary(), Catalog, frame.ObjectStates); }, frame.AddedAssetId is null && frame.AddedStates is not { Count: > 0 } ? frame.Bytes.Keys : null); } diff --git a/src/SunriseStudio.Projects/AddedActivity.cs b/src/SunriseStudio.Projects/AddedActivity.cs new file mode 100644 index 00000000..07c36f28 --- /dev/null +++ b/src/SunriseStudio.Projects/AddedActivity.cs @@ -0,0 +1,53 @@ +using System.Text.RegularExpressions; +using SunriseStudio.Packages; + +namespace SunriseStudio.Projects; + +/** A registration recipe owns identities and allocation, never installed payload bytes. */ +public sealed record AddedActivity(uint TemplateActivity, string InternalName, string DisplayName, + byte Type, byte Destination, uint MapRootTag, string ScenarioStem, ushort PackageId, int FirstEntryIndex) +{ + public uint Tag(int offset = 0) => checked(0x80800000U + ((uint)PackageId << 13) + (uint)(FirstEntryIndex + offset)); + + public void Validate() + { + if (!Regex.IsMatch(InternalName ?? "", "\\A[a-z][a-z0-9_]{0,38}\\z") + || !Regex.IsMatch(ScenarioStem ?? "", "\\A[a-z][a-z0-9_]{0,53}\\z")) + throw new InvalidDataException("Activity names use [a-z][a-z0-9_]{0,38}; map names must fit in 63 bytes."); + if (string.IsNullOrWhiteSpace(DisplayName) || DisplayName.Length > 200 || DisplayName.Any(char.IsControl) + || DisplayName != DisplayName.Trim()) throw new InvalidDataException("Display name must be one trimmed line of up to 200 characters."); + if (TemplateActivity is 0 or uint.MaxValue || MapRootTag < 0x80800000 || MapRootTag > 0x83FFFFFF + || Type >= 54 || Destination >= 48 || !PackageWriter.IsNewPackageId(PackageId) + || FirstEntryIndex is < 0 or >= 8192) throw new InvalidDataException("Invalid activity registration."); + } +} + +/** The Authoring implementation re-derives every registration from installed originals. */ +public interface IActivityRegistrationCompiler +{ + IReadOnlyDictionary Compile(StudioProject project, PackageCatalog catalog); +} + +public sealed partial class StudioProject +{ + public IReadOnlyList AddedActivities => manifest.AddedActivities ?? []; + public IActivityRegistrationCompiler? ActivityRegistrationCompiler { get; set; } + + public IReadOnlyDictionary CompileActivities(PackageCatalog catalog) => AddedActivities.Count == 0 + ? new Dictionary() + : (ActivityRegistrationCompiler ?? throw new InvalidOperationException("Activity registration needs its compiler.")).Compile(this, catalog); + + private static void ValidateActivities(IReadOnlyList activities, IReadOnlyList assets) + { + foreach (var activity in activities) + { + if (activity is null) throw new InvalidDataException("Invalid activity registration."); + activity.Validate(); + if (!assets.Any(asset => asset.Native is { } native && native.PackageId == activity.PackageId + && native.EntryIndex == activity.FirstEntryIndex && native.Reference == 0x80808AAE)) // activity root + throw new InvalidDataException("Activity registration has no owned activity root."); + } + if (activities.Select(activity => activity.InternalName).Distinct(StringComparer.Ordinal).Count() != activities.Count) + throw new InvalidDataException("Activity registration names must be unique."); + } +} diff --git a/src/SunriseStudio.Projects/ProjectBuilder.Activities.cs b/src/SunriseStudio.Projects/ProjectBuilder.Activities.cs new file mode 100644 index 00000000..192718f3 --- /dev/null +++ b/src/SunriseStudio.Projects/ProjectBuilder.Activities.cs @@ -0,0 +1,8 @@ +namespace SunriseStudio.Projects; + +public static partial class ProjectBuilder +{ + /** Investment resolves activity roots by name, so its load dependency is not a tag-shaped word. */ + private static IEnumerable<(uint From, uint To)> ActivityEdges(IReadOnlyList activities) => + activities.SelectMany(activity => new[] { (0x81327CF0U, activity.Tag()), (activity.Tag(), activity.MapRootTag) }); +} diff --git a/src/SunriseStudio.Projects/ProjectBuilder.RootManifests.cs b/src/SunriseStudio.Projects/ProjectBuilder.RootManifests.cs index a9540285..e65dee7e 100644 --- a/src/SunriseStudio.Projects/ProjectBuilder.RootManifests.cs +++ b/src/SunriseStudio.Projects/ProjectBuilder.RootManifests.cs @@ -38,7 +38,7 @@ private sealed record RootManifestAsset(ushort PackageId, int EntryIndex, uint R */ private static IReadOnlyList PlanRootManifests(PackageCatalog catalog, IReadOnlyList inputs, IReadOnlyList added, - IReadOnlyDictionary edited) + IReadOnlyDictionary edited, IReadOnlyList activities) { var supplied = inputs.Where(input => input.Reference == PackageManifest.ClassId && TagView.FitsThrough(input.Data, 0, "RootTag")) @@ -55,6 +55,8 @@ private static IReadOnlyList PlanRootManifests(PackageCatalog input.Data.Length, $"w64_sunrise_{input.PackageId:x4}_0", input.PackageId, input.EntryIndex) { TypeInfo = input.TypeInfo }; } var edges = PointerEdges(added.Select(asset => (asset.Tag, asset.Data)), added).ToHashSet(); + foreach (var activity in activities) + edges.Add((activity.Tag(), activity.MapRootTag)); foreach (var asset in added) if (authored.ContainsKey(asset.Class) && asset.Class != asset.Tag) edges.Add((asset.Tag, asset.Class)); diff --git a/src/SunriseStudio.Projects/ProjectBuilder.cs b/src/SunriseStudio.Projects/ProjectBuilder.cs index 593f8adc..38a49a9d 100644 --- a/src/SunriseStudio.Projects/ProjectBuilder.cs +++ b/src/SunriseStudio.Projects/ProjectBuilder.cs @@ -27,6 +27,7 @@ public static ProjectBuildResult Build(StudioProject project, PackageCatalog cat var config = project.CompileConfigBindings(catalog); var tags = CompileContent(project, catalog, tagSchema, project.AddedAssets.Where(x => x.Native is not null) .Select(x => x.Native!.PackageId).Concat(objects.GeneratedAssets.Select(x => x.Native.PackageId))); + var activities = project.CompileActivities(catalog); if (project.Changes.Count == 0 && objects.Assets.Count == 0 && config.Assets.Count == 0 && project.AddedAssets.Count == 0 && objects.GeneratedAssets.Count == 0 && tags.Count == 0) throw new InvalidOperationException("The project has no changes to build."); @@ -38,17 +39,19 @@ public static ProjectBuildResult Build(StudioProject project, PackageCatalog cat var addedTags = project.AddedAssets.Where(asset => asset.Native is not null) .Select(asset => TagHashes.Make(asset.Native!.PackageId, asset.Native!.EntryIndex!.Value)).ToHashSet(); foreach (uint tag in project.Changes.Select(change => change.TagHash).Union(objects.Assets.Keys) - .Union(config.Assets.Keys).Where(tag => !addedTags.Contains(tag)).Order()) + .Union(config.Assets.Keys).Union(activities.Keys).Where(tag => !addedTags.Contains(tag)).Order()) { if (!catalog.TryGetEntry(tag, out _)) throw new InvalidDataException($"Original asset {tag:X8} is missing."); - byte[] data = config.Assets.TryGetValue(tag, out var configured) ? configured + byte[] data = activities.TryGetValue(tag, out var registered) ? registered + : config.Assets.TryGetValue(tag, out var configured) ? configured : objects.Assets.TryGetValue(tag, out var compiled) ? compiled.ToArray() : project.ReadAsset(tag, catalog); // An entry equal to its installed original needs no patch. if (!data.AsSpan().SequenceEqual(catalog.ReadOriginal(tag))) edited[tag] = data; } var added = project.AddedAssets.Where(x => x.Native is not null) - .Select(x => (Asset: x, Data: config.Assets.TryGetValue(TagHashes.Make(x.Native!.PackageId, x.Native!.EntryIndex!.Value), out var configured) + .Select(x => (Asset: x, Data: activities.TryGetValue(TagHashes.Make(x.Native!.PackageId, x.Native!.EntryIndex!.Value), out var registered) ? registered + : config.Assets.TryGetValue(TagHashes.Make(x.Native!.PackageId, x.Native!.EntryIndex!.Value), out var configured) ? configured : project.ReadAddedAsset(x.Id, catalog))).ToArray(); var reserved = added.Select(item => item.Asset.Native!.PackageId).ToHashSet(); if (objects.GeneratedAssets.Any(asset => reserved.Contains(asset.Native.PackageId))) @@ -74,8 +77,8 @@ public static ProjectBuildResult Build(StudioProject project, PackageCatalog cat addedEntries = [.. addedEntries, .. tags.Select(tag => new AddedEntry(TagFileId(tag.Name), tag.TagHash, tag.ClassId, tag.Data, tag.WideHash == 0 ? WideHashAliases.Empty : new([tag.WideHash]), tag.TypeInfo))]; var rootManifests = PlanRootManifests(catalog, [.. added.Select(item => RootManifestInput.Of(item.Asset, item.Data)), - .. tags.Select(RootManifestInput.Of)], addedEntries, edited); - var manifests = PlanManifests(catalog, edited, addedEntries); + .. tags.Select(RootManifestInput.Of)], addedEntries, edited, project.AddedActivities); + var manifests = PlanManifests(catalog, edited, addedEntries, project.AddedActivities); foreach (var (tag, data) in manifests.Data) edited.Add(tag, data); var replacements = new Dictionary>(StringComparer.OrdinalIgnoreCase); foreach (var (tag, data) in edited) @@ -85,7 +88,7 @@ public static ProjectBuildResult Build(StudioProject project, PackageCatalog cat if (!replacements.TryGetValue(source, out var group)) replacements.Add(source, group = []); group.Add(entry.EntryIndex, data); } - var dependencies = PlanDependencies(catalog, edited, generated, addedEntries); + var dependencies = PlanDependencies(catalog, edited, generated, addedEntries, project.AddedActivities); var changedMisc = dependencies.Misc.Where(pair => !pair.Value.AsSpan().SequenceEqual(PackageWriter.ReadMisc(pair.Key))) .ToDictionary(StringComparer.OrdinalIgnoreCase); // Checked before any folder is made, so a no-op build leaves nothing behind. @@ -334,13 +337,13 @@ private sealed record ManifestPlan(Dictionary Data, List edited, - IReadOnlyList added) + IReadOnlyList added, IReadOnlyList activities) { var plan = new ManifestPlan([], []); var resident = added.Where(asset => PackageNativeDependencies.IsResident(asset.TypeInfo)).ToArray(); var edges = PointerEdges(edited.Select(pair => (pair.Key, pair.Value)) .Concat(resident.Select(asset => (asset.Tag, asset.Data))), resident); - var nativeEdges = NativeDependencyEdges(catalog, edited, added); + var nativeEdges = NativeDependencyEdges(catalog, edited, added).Concat(ActivityEdges(activities)).ToHashSet(); var socketDependencies = PlanSocketDependencies(catalog, edited, added); var sources = edges.Concat(nativeEdges).Select(edge => edge.From).Where(edited.ContainsKey).ToHashSet(); if (sources.Count == 0 && socketDependencies.Count == 0) return plan; @@ -435,7 +438,7 @@ private sealed record DependencyPlan(Dictionary Misc, List edited, - IReadOnlyList generated, IReadOnlyList added) + IReadOnlyList generated, IReadOnlyList added, IReadOnlyList activities) { var misc = new Dictionary(StringComparer.OrdinalIgnoreCase); var rows = new List(); @@ -494,7 +497,7 @@ bool Join(uint tag, uint source, (string Path, int Record) record) var native = NativeDependencyEdges(catalog, edited, added); var edges = PointerEdges(edited.Select(pair => (pair.Key, pair.Value)) .Concat(generated.Select(asset => (asset.TagHash, asset.Data))) - .Concat(added.Select(asset => (asset.Tag, asset.Data))), added).Concat(native).Distinct().ToArray(); + .Concat(added.Select(asset => (asset.Tag, asset.Data))), added).Concat(native).Concat(ActivityEdges(activities)).Distinct().ToArray(); bool Lists((string Path, int Record) record, uint tag) => tables[record.Path].Table.Records[record.Record].Lists(TagHashes.Split(tag).PackageId, TagHashes.Split(tag).EntryIndex); for (bool changed = true; changed;) diff --git a/src/SunriseStudio.Projects/ProjectModels.cs b/src/SunriseStudio.Projects/ProjectModels.cs index d2306095..367fc02b 100644 --- a/src/SunriseStudio.Projects/ProjectModels.cs +++ b/src/SunriseStudio.Projects/ProjectModels.cs @@ -23,14 +23,18 @@ public sealed record ProjectAssetAddition(string Name, byte[] Data, NativeAssetMetadata? Native = null, uint? BaseTagHash = null); public sealed record ProjectAssetEdits(IReadOnlyDictionary Assets, - IReadOnlyDictionary? AddedAssets = null); + IReadOnlyDictionary? AddedAssets = null) +{ + /** Null keeps registrations; a list replaces them in the same transaction as their assets. */ + public IReadOnlyList? AddedActivities { get; init; } +} /** Undo holds reconstructed data in memory; derived assets still save only base-relative deltas. */ public sealed record AddedAssetSnapshot(AddedProjectAsset Asset, byte[] Data); /** * Mod stays null and unwritten until set, so older Studio builds still open the file. Versions: - * object edits 2, wide hashes 3, config bindings 4, names 5, groups 6, group collision parts 7. + * object edits 2, wide hashes 3, config bindings 4, names 5, groups 6, group collision parts 7, activities 8. */ public sealed record ProjectManifest(int Version, string Name, IReadOnlyList Changes, IReadOnlyList AddedAssets, @@ -43,6 +47,8 @@ public sealed record ProjectManifest(int Version, string Name, public IReadOnlyList? ObjectNames { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList? ObjectGroups { get; init; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? AddedActivities { get; init; } } /** diff --git a/src/SunriseStudio.Projects/ProjectTransactions.cs b/src/SunriseStudio.Projects/ProjectTransactions.cs index 93be8de3..7ef0ebe0 100644 --- a/src/SunriseStudio.Projects/ProjectTransactions.cs +++ b/src/SunriseStudio.Projects/ProjectTransactions.cs @@ -97,10 +97,13 @@ private IReadOnlyList CommitTransaction(IReadOnlyList value.TagHash).ToArray(), - AddedAssets = assets.ToArray(), ObjectEdits = objectStates is null ? baseline.ObjectEdits : objects }, + AddedAssets = assets.ToArray(), ObjectEdits = objectStates is null ? baseline.ObjectEdits : objects, + AddedActivities = activities.Count == 0 ? null : Array.AsReadOnly(activities.ToArray()) }, writes, obsolete); return created.AsReadOnly(); } diff --git a/src/SunriseStudio.Projects/StudioProject.cs b/src/SunriseStudio.Projects/StudioProject.cs index fe0860eb..2941819e 100644 --- a/src/SunriseStudio.Projects/StudioProject.cs +++ b/src/SunriseStudio.Projects/StudioProject.cs @@ -11,7 +11,7 @@ public sealed partial class StudioProject { public const string ProjectFileName = "sunrise.project.json"; // The newest manifest version this build reads and writes. - public const int ManifestVersion = 7; + public const int ManifestVersion = 8; // A whole ported region lists about 76,000 assets, about 50 MB of manifest. private const int MaximumManifestBytes = 128 * 1024 * 1024; private ProjectManifest manifest; @@ -65,6 +65,11 @@ public static StudioProject Open(string manifestOrFolder) || data.Version == 1 && data.ObjectEdits is not null || data.Version == 2 && data.ObjectEdits is null) throw new InvalidDataException("Unsupported project manifest."); foreach (var edit in data.ObjectEdits ?? []) edit.Validate(); + if (data.AddedActivities is not null && data.Version < 8) + throw new InvalidDataException("Activity registrations require project manifest version 8."); + ValidateActivities(data.AddedActivities ?? [], data.AddedAssets); + data = data with { AddedActivities = data.AddedActivities is { Count: > 0 } + ? Array.AsReadOnly(data.AddedActivities.ToArray()) : null }; if ((data.ObjectEdits ?? []).Select(edit => edit.Key).Distinct().Count() != (data.ObjectEdits?.Count ?? 0)) throw new InvalidDataException("Project contains two edits of one object."); if (data.Changes.Select(x => x.TagHash).Distinct().Count() != data.Changes.Count @@ -315,14 +320,16 @@ private static ProjectManifest Versioned(ProjectManifest value) bool names = value.ObjectNames is { Count: > 0 }; bool groups = value.ObjectGroups is { Count: > 0 }; bool parts = groups && value.ObjectGroups!.Any(group => group.CollisionParts is not null); - int version = parts ? 7 : groups ? 6 : names ? 5 : bindings ? 4 : aliases ? 3 : objects ? 2 : 1; + bool activities = value.AddedActivities is { Count: > 0 }; + int version = activities ? 8 : parts ? 7 : groups ? 6 : names ? 5 : bindings ? 4 : aliases ? 3 : objects ? 2 : 1; if (value.Version == version && ReferenceEquals(assets, value.AddedAssets) && (objects || value.ObjectEdits is null) && (bindings || value.ConfigBindings is null) - && (names || value.ObjectNames is null) && (groups || value.ObjectGroups is null)) return value; + && (names || value.ObjectNames is null) && (groups || value.ObjectGroups is null) + && (activities || value.AddedActivities is null)) return value; return value with { Version = version, AddedAssets = assets, ObjectEdits = objects ? value.ObjectEdits : null, ConfigBindings = bindings ? value.ConfigBindings : null, ObjectNames = names ? value.ObjectNames : null, - ObjectGroups = groups ? value.ObjectGroups : null }; + ObjectGroups = groups ? value.ObjectGroups : null, AddedActivities = activities ? value.AddedActivities : null }; } private static byte[] SerializeManifest(ProjectManifest value) diff --git a/tests/SunriseStudio.Activity.Tests/ActivityFixture.cs b/tests/SunriseStudio.Activity.Tests/ActivityFixture.cs new file mode 100644 index 00000000..bcec5e29 --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/ActivityFixture.cs @@ -0,0 +1,155 @@ +using System.Buffers.Binary; +using System.Text; +using SunriseStudio.Authoring; +using SunriseStudio.Packages; + +internal static class ActivityFixture +{ + internal const uint Base = 0x80A00000, TemplateHash = 0x12345678; + internal static readonly uint Bubble = ActivityRegistrationIdentity.Hash("bubble"); + internal static byte[] Definitions() + { + var b = new Bytes(136); var positions = new List(); + for (int i = 0; i < 2; i++) + { + int pos = b.Object(0x80807711, 232); positions.Add(pos); + b.U32(pos, TemplateHash + (uint)i); b.U32(pos + 96, 0xFFFF); b.U32(pos + 120, 4); + b.U32(pos + 152, uint.MaxValue); b.U32(pos + 216, 0x0009FFFF); b.U32(pos + 220, 0x0109ED6B); b.U32(pos + 224, 0xFFFFFF02); + int matcher = b.Object(0x8080773D, 72); + uint[] words = [uint.MaxValue, 0x811C9DC5, 1, 3, 3, 0x100, 0, 0, 0, 0, 0xFFFF0000, 0xFFFF, 0, 0, 0, uint.MaxValue, 0, 0]; + for (int j = 0; j < words.Length; j++) b.U32(matcher + j * 4, words[j]); + b.I64(pos + 32, matcher - pos - 32); + // Internal, external, backward and null pointers exercise the fixed-record program. + b.I64(pos + 16, 120 - 16); b.I64(pos + 208, matcher - pos - 208); + int text = b.Add(Encoding.ASCII.GetBytes("template\0")); b.I64(pos + 104, text - pos - 104); + } + int index = b.Array(8, 0x808076FC, 16, 2); + for (int i = 0; i < 2; i++) { b.U32(index + i * 16, TemplateHash + (uint)i); b.I64(index + i * 16 + 8, positions[i] - index - i * 16 - 8); } + return b.Finish(); + } + + internal static byte[] Clients() + { + var b = new Bytes(120); int index = b.Array(8, 0x80805E15, 16, 2); + int[] positions = [b.Object(0x80805E18, 136), b.Object(0x80805E18, 136)]; + for (int i = 0; i < 2; i++) + { + int pos = positions[i]; b.U32(index + i * 16, TemplateHash + (uint)i); b.I64(index + i * 16 + 8, pos - index - i * 16 - 8); + b.U32(pos + 8, 0xFFFF); b.U32(pos + 60, uint.MaxValue); b.U32(pos + 64, 0x811C9DC5); b.U32(pos + 88, uint.MaxValue); + b.U32(pos + 128, 1); b.I64(pos + 32, 128 - 32); + } + int display = b.Array(24, 0x80805E23, 36, 1); + uint[] words = [0xFFFF, 0xFFFF, 0x811C9DC5, 0xFFFF, 0x811C9DC5, 0xFFFF, 0x811C9DC5, uint.MaxValue, 0x811C9DC5]; + for (int i = 0; i < words.Length; i++) b.U32(display + i * 4, words[i]); + foreach (int pos in positions) b.I64(pos, display - pos); + return b.Finish(); + } + + internal static byte[] Types(bool client) + { + var b = new Bytes(24); int stride = client ? 128 : 16; + int at = b.Array(8, client ? 0x80805F40U : 0x80807778U, stride, 54); + for (int i = 0; i < 54; i++) { b.U32(at + i * stride, (uint)i + 1); if (client) b.U8(at + i * stride + 120, i == 18 ? (byte)0 : (byte)6); } + if (!client) { b.U8(at + 15 * stride + 10, 1); b.U8(at + 16 * stride + 10, 1); } + return b.Finish(); + } + + internal static byte[] Scenario() + { + var b = new Bytes(140); b.U32(8, ActivityRegistrationIdentity.Hash("template")); + b.U32(28, 0x811C9DC5); b.U32(32, ActivityRegistrationIdentity.Hash("map_test")); + b.U32(40, uint.MaxValue); b.U32(56, Base + 7); b.U32(120, uint.MaxValue); b.U32(128, Base + 8); + int symbol = b.Array(64, 0x8080924A, 16, 2); + b.U32(symbol, ActivityRegistrationIdentity.Hash("template")); b.U32(symbol + 16, ActivityRegistrationIdentity.Hash("late")); + int bubble = b.Array(80, 0x8080924D, 24, 1); b.U32(bubble, Bubble); + int state = b.Array(bubble + 8, 0x8080924F, 76, 1); + b.U32(state, 1); b.U32(state + 4, ActivityRegistrationIdentity.Hash("default")); b.U32(state + 12, 1); + b.U32(state + 32, 1); b.U32(state + 64, Bubble); b.U32(state + 68, Base + 4); + byte[] text = Encoding.ASCII.GetBytes("map_test\0template\0late\0"); + // "late" is a suffix of template; the canonical pool shares it. + text = Encoding.ASCII.GetBytes("map_test\0template\0"); + int marker = b.Add(new byte[12]); b.U32(marker, 0x80800065); b.I64(marker + 4, text.Length); + int tail = b.Add(text); b.I64(48, tail - 48); b.I64(symbol + 8, tail + 9 - symbol - 8); b.I64(symbol + 24, tail + 13 - symbol - 24); + return b.Finish(); + } + + internal static byte[] Slice() + { + var b = new Bytes(40); b.I64(8, 32); b.U32(20, Base + 5); b.U32(28, 0x80800065); b.I64(32, 9); + b.Add(Encoding.ASCII.GetBytes("map_test\0")); return b.Finish(); + } + + internal static byte[] Manifest(uint tag, uint root, ushort package, int[] entries) + { + var b = new Bytes(48); b.U32(8, tag); b.U32(12, root); + int group = b.Array(16, 0x80809EFB, 40, 1); b.U16(group, package); + int list = b.Array(group + 24, 0x8080000A, 2, entries.Length); + for (int i = 0; i < entries.Length; i++) b.U16(list + i * 2, (ushort)entries[i]); + return b.Finish(); + } + + internal static void Create(string folder) + { + string keyFolder = Path.Combine(folder, "bin", "x64", "Sunrise", "exports"); Directory.CreateDirectory(keyFolder); + byte[] key = new byte[60]; "SRPKKEYS"u8.CopyTo(key); BinaryPrimitives.WriteUInt32LittleEndian(key.AsSpan(8), 1); + BinaryPrimitives.WriteUInt32LittleEndian(key.AsSpan(12), 86657); File.WriteAllBytes(Path.Combine(keyFolder, "package_keys.bin"), key); + string packages = Path.Combine(folder, "packages"); Directory.CreateDirectory(packages); + var entries = Enumerable.Range(0, 14).Select(_ => new AuthoredPackageEntry(0, 0, [])).ToArray(); + void Entry(int i, uint cls, byte[] data, bool root = false, string? name = null) => entries[i] = new(cls, root ? 0x200AU : 0x100AU, data, name); + var b = new Bytes(32); b.U32(8, ActivityRegistrationIdentity.Hash("template")); int refs = b.Array(16, 0x80808491, 4, 2); + b.U32(refs, Base + 1); b.U32(refs + 4, Base + 9); Entry(0, 0x80808AAE, b.Finish(), true, "template"); + Entry(1, 0x80809994, Scenario(), true, "template:scenario_client"); + b = new Bytes(32); b.U32(8, Base + 3); b.U32(12, Base + 7); refs = b.Array(16, 0x80807D53, 16, 1); b.U32(refs, uint.MaxValue); + Entry(2, 0x808091DE, b.Finish(), true, "map:map_test:root"); + b = new Bytes(48); int keys = b.Array(16, 0x808098C4, 24, 1); b.U32(keys, 1); b.U32(keys + 8, Bubble); + int bubble = b.Array(32, 0x808098C2, 80, 1); b.U32(bubble, Bubble); b.U32(bubble + 40, 1); + int mapText = b.Add(Encoding.ASCII.GetBytes("map_test\0")); b.I64(8, mapText - 8); Entry(3, 0x80809962, b.Finish()); + Entry(4, 0x8080925B, Slice()); + b = new Bytes(56); refs = b.Array(40, 0x80809260, 4, 1); b.U32(refs, Base + 6); Entry(5, 0x8080925E, b.Finish(), true); + b = new Bytes(72); b.U32(8, ActivityRegistrationIdentity.Hash("map_test")); b.U32(12, 123); Entry(6, 0x80809462, b.Finish()); + Entry(7, 0x80809780, new Bytes(24).Finish()); Entry(8, 0x80809440, new Bytes(24).Finish()); Entry(9, 0x80809BA3, new Bytes(48).Finish()); + int[] roots = [0, 1, 2, 5]; + for (int i = 0; i < roots.Length; i++) Entry(10 + i, PackageManifest.ClassId, + Manifest(Base + 10 + (uint)i, Base + (uint)roots[i], 0x100, Enumerable.Range(0, 14).ToArray())); + PackageWriter.WriteNew(Path.Combine(packages, "w64_activity_0100_0.pkg"), 0x100, entries); + var globals = Enumerable.Range(0, 0x1D66).Select(_ => new AuthoredPackageEntry(0, 0, [])).ToArray(); + globals[0] = new(0x80809F00, 0x200A, new Bytes(24).Finish(), "investment_globals"); + globals[0x1CF0] = new(0x808076F0, 0x100A, Definitions()); globals[0x1D35] = new(0x80805E0A, 0x100A, Clients()); + globals[0x1CE8] = new(0x80807773, 0x100A, Types(false)); globals[0x1D64] = new(0x80805F3C, 0x100A, Types(true)); + globals[0x1D65] = new(PackageManifest.ClassId, 0x100A, Manifest(0x81327D65, 0x81326000, 0x593, [0, 0x1CF0, 0x1D35, 0x1D65])); + string path = Path.Combine(packages, "w64_investment_globals_0593_0.pkg"); + PackageWriter.WriteNew(path, 0x593, globals); + string patch = Path.Combine(Path.GetDirectoryName(folder)!, "w64_investment_globals_0593_1.pkg"); + PackageWriter.WritePatch(path, patch, new Dictionary(), misc: Dependencies()); + File.Copy(patch, Path.Combine(packages, Path.GetFileName(patch))); + } + + private static byte[] Dependencies() + { + var b = new Bytes(128); b.I64(0, 128); b.I64(48, 1); b.I64(64, 1); b.I64(72, 96 - 72); + b.U32(92, 0x80809FBD); b.I64(96, 1); b.U32(104, 0x8080000B); b.U32(112, 0x80000000); + // One dependency group containing the two installed activity tables. + b.Add([1, 0, 0x93, 5, 2, 0, 0xF0, 0x3C, 0x35, 0x3D]); + return b.Raw(); + } + + internal sealed class Bytes(int size) + { + private readonly List bytes = new(new byte[size]); + internal int Add(byte[] data) { int at = bytes.Count; bytes.AddRange(data); return at; } + internal void U8(int at, byte value) => bytes[at] = value; + internal void U16(int at, ushort value) => Put(at, BitConverter.GetBytes(value)); + internal void U32(int at, uint value) => Put(at, BitConverter.GetBytes(value)); + internal void I64(int at, long value) => Put(at, BitConverter.GetBytes(value)); + private void Put(int at, byte[] data) { for (int i = 0; i < data.Length; i++) bytes[at + i] = data[i]; } + internal int Object(uint cls, int length) { while ((bytes.Count + 4) % 8 != 0) bytes.Add(0); int at = Add(new byte[4]); U32(at, cls); return Add(new byte[length]); } + internal int Array(int field, uint cls, int stride, int count) + { + while (bytes.Count % 16 != 0) bytes.Add(0); + int header = Add(new byte[32]); U32(header + 12, 0x80809FBD); I64(header + 16, count); U32(header + 24, cls); + I64(field, count); I64(field + 8, header + 16 - field - 8); return Add(new byte[count * stride]); + } + internal byte[] Raw() => bytes.ToArray(); + internal byte[] Finish() { I64(0, bytes.Count); return Raw(); } + } +} diff --git a/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs b/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs new file mode 100644 index 00000000..099020ff --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs @@ -0,0 +1,45 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Text; +using System.Text.Json; +using SunriseStudio.Authoring; +using SunriseStudio.Packages; +using SunriseStudio.Projects; + +internal static class InstalledChecks +{ + internal static void Run(string game, string? keys, string root) + { + using var catalog = PackageCatalog.Open(game, keys, cacheOptions: new() { Enabled = false }); + byte[] definitions = catalog.ReadOriginal(ActivityRegistrationTables.DefinitionTag), clients = catalog.ReadOriginal(ActivityRegistrationTables.ClientTag); + var template = ActivityRegistrationTables.ReadDefinitions(definitions).Single(row => row.Hash == 0x953F1741); // Luna free roam + uint source = catalog.NamedTags.First(row => row.ClassHash == 0x80808AAE && row.Name == template.Name).TagHash; + byte[] sourceRoot = catalog.ReadOriginal(source); + uint scenarioTag = BinaryPrimitives.ReadUInt32LittleEndian(sourceRoot.AsSpan(64)); + byte[] scenario = catalog.ReadOriginal(scenarioTag); + int stemAt = checked(48 + (int)BinaryPrimitives.ReadInt64LittleEndian(scenario.AsSpan(48))); + string stem = Encoding.ASCII.GetString(scenario, stemAt, Array.IndexOf(scenario, (byte)0, stemAt) - stemAt); + uint map = catalog.NamedTags.First(row => row.ClassHash == 0x808091DE && row.Name == "map:" + stem + ":root").TagHash; + ushort package = Enumerable.Range(0x100, 0xC00).Select(value => (ushort)value).First(value => !catalog.ContainsInstalledPackage(value)); + var project = StudioProject.Create(Path.Combine(root, "installed-project"), "Installed activity read-only check"); + project.ActivityRegistrationCompiler = ActivityRegistrationCompiler.Default; + var recipe = new AddedActivity(template.Hash, "studio_registration_check", "Registration check", template.Type, template.Destination, map, stem, package, 0); + var plan = ActivityRegistrationCompiler.Prepare(project, catalog, recipe); + var tables = ActivityRegistrationTables.Append(definitions, clients, [plan.Row]); + string output = Path.Combine(root, "installed-parity"); Directory.CreateDirectory(output); + foreach (var (name, bytes) in new[] { ("definitions.input", definitions), ("clients.input", clients), + ("definitions.actual", tables.Definitions), ("clients.actual", tables.Clients) }) File.WriteAllBytes(Path.Combine(output, name + ".bin"), bytes); + File.WriteAllText(Path.Combine(output, "request.json"), JsonSerializer.Serialize(new { template = template.Hash, hash = plan.Row.Hash, name = recipe.InternalName })); + if (Environment.GetEnvironmentVariable("WORLD_STUDIO_ORACLE") is { } oracle) + { + var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("PYTHON") ?? "python") { UseShellExecute = false }; + foreach (string arg in new[] { "-I", Path.Combine(AppContext.BaseDirectory, "oracle.py"), oracle, output, "--installed" }) start.ArgumentList.Add(arg); + using var process = Process.Start(start)!; process.WaitForExit(); + if (process.ExitCode != 0) throw new InvalidDataException("Installed Python table parity failed."); + } + project.ApplyTransaction(plan.Additions, _ => new(new Dictionary { + [ActivityRegistrationTables.DefinitionTag] = tables.Definitions, [ActivityRegistrationTables.ClientTag] = tables.Clients }) { AddedActivities = [recipe] }, catalog); + var compiled = project.CompileActivities(catalog); + Console.WriteLine($"activity installed-originals={ActivityRegistrationTables.ReadDefinitions(definitions).Count} appended={ActivityRegistrationTables.ReadDefinitions(tables.Definitions).Count} assets={plan.Additions.Count} deterministic-compile={compiled.Count} output={output}"); + } +} diff --git a/tests/SunriseStudio.Activity.Tests/Program.cs b/tests/SunriseStudio.Activity.Tests/Program.cs new file mode 100644 index 00000000..0fa09327 --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/Program.cs @@ -0,0 +1,162 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text.Json; +using SunriseStudio.Authoring; +using SunriseStudio.Editor; +using SunriseStudio.Editor.Creation; +using SunriseStudio.Packages; +using SunriseStudio.Projects; +using SunriseStudio.Scene; + +string root = Path.Combine(Environment.GetEnvironmentVariable("SUNRISE_ACTIVITY_OUTPUT") ?? Path.GetTempPath(), "activity-" + Guid.NewGuid().ToString("N")); +Directory.CreateDirectory(root); +int checks = 0; +void Check(bool condition, string message) { checks++; if (!condition) throw new InvalidDataException(message); } +void Reject(Action action, string message) +{ + checks++; + try { action(); } catch (InvalidDataException) { return; } + throw new InvalidDataException(message); +} +try +{ + byte[] definitions = ActivityFixture.Definitions(), clients = ActivityFixture.Clients(); + var addition = new ActivityTableAddition(ActivityFixture.TemplateHash, 0x87654321, "new_activity", 9, 2); + var tables = ActivityRegistrationTables.Append(definitions, clients, [addition]); + Check(ActivityRegistrationTables.ReadDefinitions(tables.Definitions).Count == 3, "Definition append failed."); + Check(ActivityRegistrationTables.ReadClients(tables.Clients).Count == 3, "Client append failed."); + Check(ActivityRegistrationTables.ReadDefinitions(tables.Definitions).Take(2).SequenceEqual(ActivityRegistrationTables.ReadDefinitions(definitions)), "Original definitions changed."); + Check(tables.Definitions.AsSpan(24, definitions.Length - 24).SequenceEqual(definitions.AsSpan(24)), "Original policy bytes changed."); + Check(tables.Clients.AsSpan(40, clients.Length - 40).SequenceEqual(clients.AsSpan(40)), "Original client bytes changed."); + Reject(() => ActivityRegistrationTables.Append(definitions, clients, [addition with { TemplateHash = 99 }]), "Missing template accepted."); + Reject(() => ActivityRegistrationTables.Append(definitions, clients, [addition with { Hash = ActivityFixture.TemplateHash }]), "Hash collision accepted."); + Reject(() => ActivityRegistrationTables.Append(definitions, clients, [addition with { Name = "Bad-Name" }]), "Invalid name accepted."); + Reject(() => ActivityRegistrationTables.Append(definitions, clients, [addition, addition]), "Duplicate registration accepted."); + var maximum = Enumerable.Range(0, 4093).Select(i => addition with { Hash = 0x66000000 + (uint)i, Name = "capacity_" + i }).ToArray(); + var full = ActivityRegistrationTables.Append(definitions, clients, maximum); + Check(ActivityRegistrationTables.ReadDefinitions(full.Definitions).Count == 4095 && ActivityRegistrationTables.ReadClients(full.Clients).Count == 4095, "Maximum catalog did not decode."); + Reject(() => ActivityRegistrationTables.Append(full.Definitions, full.Clients, [addition]), "Catalog capacity overflow accepted."); + var broken = definitions.ToArray(); BinaryPrimitives.WriteInt64LittleEndian(broken.AsSpan(16), long.MaxValue); + Reject(() => ActivityRegistrationTables.ReadDefinitions(broken), "Overflowing index accepted."); + foreach (byte type in ActivityRegistrationCompiler.ProvenTypes.Keys) ActivityRegistrationCompiler.ValidateType(ActivityFixture.Types(false), ActivityFixture.Types(true), type); + foreach (byte type in new byte[] { 1, 16, 18, 53 }) Reject(() => ActivityRegistrationCompiler.ValidateType(ActivityFixture.Types(false), ActivityFixture.Types(true), type), "Unproven/PvP/orbit type accepted."); + byte[] scenario = ActivityFixture.Scenario(); + byte[] rebound = ActivityRegistrationIdentity.RebindScenario(scenario, "template", "new_activity", "map_copy"); + byte[] slice = ActivityRegistrationIdentity.RebindSlice(ActivityFixture.Slice(), "map_copy", ActivityFixture.Base + 5); + var text = ActivityRegistrationIdentity.LocalizedText(new Dictionary { [ActivityRegistrationIdentity.Hash("map_copy")] = "New World é" }, 0x80A00001); + var parity = new Dictionary { ["definitions"] = tables.Definitions, ["clients"] = tables.Clients, + ["scenario"] = rebound, ["slice"] = slice, ["text-container"] = text.Container, ["text-data"] = text.Data }; + foreach (var (key, bytes) in parity) File.WriteAllBytes(Path.Combine(root, key + ".actual.bin"), bytes); + File.WriteAllBytes(Path.Combine(root, "definitions.input.bin"), definitions); File.WriteAllBytes(Path.Combine(root, "clients.input.bin"), clients); + File.WriteAllBytes(Path.Combine(root, "scenario.input.bin"), scenario); File.WriteAllBytes(Path.Combine(root, "slice.input.bin"), ActivityFixture.Slice()); + string? oracle = Environment.GetEnvironmentVariable("WORLD_STUDIO_ORACLE"); + if (oracle is not null) + { + var process = new ProcessStartInfo(Environment.GetEnvironmentVariable("PYTHON") ?? "python") { UseShellExecute = false }; + foreach (string arg in new[] { "-I", Path.Combine(AppContext.BaseDirectory, "oracle.py"), oracle, root }) process.ArgumentList.Add(arg); + using var child = Process.Start(process)!; child.WaitForExit(); Check(child.ExitCode == 0, "Python parity oracle failed."); + foreach (var (key, bytes) in parity) Check(bytes.AsSpan().SequenceEqual(File.ReadAllBytes(Path.Combine(root, key + ".expected.bin"))), key + " differs from Python."); + } + string goldenPath = Path.Combine(AppContext.BaseDirectory, "registration-parity.json"); + if (File.Exists(goldenPath)) + { + var golden = JsonSerializer.Deserialize>(File.ReadAllText(goldenPath))!; + foreach (var (key, bytes) in parity) Check(Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant() == golden[key], key + " differs from frozen Python golden."); + } + else Check(oracle is not null, "Frozen parity golden is missing."); + using (var golden = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "activity_registration_golden.json")))) + { + var display = ActivityRegistrationTables.ReadClients(clients)[0]; + int at = display.Offset + (int)BinaryPrimitives.ReadInt64LittleEndian(clients.AsSpan(display.Offset)); + Check(Convert.ToHexString(SHA256.HashData(clients.AsSpan(at, 36))).ToLowerInvariant() + == golden.RootElement.GetProperty("children").GetProperty("empty_display").GetProperty("body_sha256").GetString(), "Native display profile differs from golden."); + int record = ActivityRegistrationTables.ReadDefinitions(definitions)[0].Offset; + at = record + 32 + (int)BinaryPrimitives.ReadInt64LittleEndian(definitions.AsSpan(record + 32)); + Check(Convert.ToHexString(SHA256.HashData(definitions.AsSpan(at, 72))).ToLowerInvariant() + == golden.RootElement.GetProperty("children").GetProperty("matchmaking").GetProperty("body_sha256").GetString(), "Native matchmaking profile differs from golden."); + } + string install = Path.Combine(root, "install"); ActivityFixture.Create(install); + using var workspace = new StudioWorkspace { CacheOptions = new() { Enabled = false } }; + void Wait() + { + var watch = Stopwatch.StartNew(); + while (workspace.IsBusy && watch.Elapsed < TimeSpan.FromSeconds(60)) { workspace.Poll(); Thread.Sleep(1); } + workspace.Poll(); Check(!workspace.IsBusy && workspace.Error.Length == 0, "Workspace: " + workspace.Error); + } + workspace.OpenInstallation(install); Wait(); + workspace.Select(ActivityFixture.Base); Wait(); + workspace.CreateProject(Path.Combine(root, "project"), "Activity fixture"); Wait(); + var workflow = new ActivityRegistrationWorkflow(workspace); + CreationField Field(string name) => workflow.Fields.Single(field => field.Label == name); + Field("Template activity").Tag = ActivityFixture.Base; + Field("Map root").Tag = ActivityFixture.Base + 2; + workflow.Update(workspace); + Field("Internal name").Text = "new_activity"; Field("Display name").Text = "New World"; + Check(workflow.Problems(workspace).Count == 0, string.Join("; ", workflow.Problems(workspace))); + Check(CreationTypes.For(CreationTypes.ActivityKey, CreationMode.New).Available, "Activity creation is blocked."); + workflow.Create(workspace); Wait(); + var project = workspace.Project!; var catalog = workspace.Catalog!; + Check(project.AddedActivities.Count == 1 && project.Changes.Count == 2, "Registration did not atomically publish its two deltas and recipe."); + Check(JsonDocument.Parse(File.ReadAllBytes(project.ManifestPath)).RootElement.GetProperty("version").GetInt32() == 8, "Manifest version did not advance."); + var recipe = project.AddedActivities[0]; + byte[] savedManifest = File.ReadAllBytes(project.ManifestPath); + Reject(() => project.ApplyTransaction([], _ => new(new Dictionary()) { AddedActivities = [recipe with { InternalName = "invalid name" }] }, catalog), + "Invalid registration transaction succeeded."); + Check(File.ReadAllBytes(project.ManifestPath).AsSpan().SequenceEqual(savedManifest), "Failed registration changed the manifest."); + var compiled = project.CompileActivities(catalog); int expectedAssets = project.AddedAssets.Count; + var info = new AssetSceneLoader(catalog).DescribeScenario(recipe.Tag(1)); + Check(info.Bubbles.Count == 1 && info.Bubbles[0].States.Count == 1, "Studio scenario reader failed."); + uint container = BinaryPrimitives.ReadUInt32LittleEndian(compiled[recipe.Tag(1)].AsSpan(40)); + Check(LocalizedStrings.LoadBanks(catalog, [container]).Get(container, ActivityRegistrationIdentity.Hash(recipe.ScenarioStem)) == "New World", "Studio localized-string reader failed."); + workspace.Undo(); Wait(); Check(project.AddedActivities.Count == 0 && project.AddedAssets.Count == 0 && project.Changes.Count == 0, "Undo left a partial registration."); + workspace.Redo(); Wait(); Check(project.AddedActivities.Count == 1 && project.AddedAssets.Count == expectedAssets, "Redo lost the recipe or assets."); + _ = project.CompileActivities(catalog); + var reopen = StudioProject.Open(project.ManifestPath); reopen.ActivityRegistrationCompiler = ActivityRegistrationCompiler.Default; + Check(reopen.CompileActivities(catalog).Count == compiled.Count, "Reopened recipe failed to compile."); + var missing = recipe with { TemplateActivity = 0x77777777 }; + Reject(() => ActivityRegistrationCompiler.Prepare(project, catalog, missing), "Non-installed template accepted."); + var invalidName = recipe with { InternalName = new string('a', 40) }; + Reject(invalidName.Validate, "Oversized internal name accepted."); + Reject(() => (recipe with { ScenarioStem = new string('a', 55) }).Validate(), "Oversized native map name accepted."); + var secondWorkflow = new ActivityRegistrationWorkflow(workspace); + secondWorkflow.Fields.Single(field => field.Label == "Template activity").Tag = recipe.Tag(); + // Required fields filled to reach semantic validation of the non-installed source. + foreach (var field in secondWorkflow.Fields.Where(field => field.Kind == CreationFieldKind.Text)) field.Text = "test"; + secondWorkflow.Fields.Single(field => field.Label == "Map root").Tag = ActivityFixture.Base + 2; + secondWorkflow.Fields.Single(field => field.Label == "Template row").Text = "12345678"; + secondWorkflow.Fields.Single(field => field.Label == "Type").Text = "9"; + secondWorkflow.Fields.Single(field => field.Label == "Destination index").Text = "2"; + Check(secondWorkflow.Problems(workspace).Any(problem => problem.Contains("installed template", StringComparison.Ordinal)), "Workflow accepted a project template."); + string manifestBefore = File.ReadAllText(project.ManifestPath); + var built = ProjectBuilder.Build(project, catalog, Path.Combine(root, "build")); + Check(File.ReadAllText(project.ManifestPath) == manifestBefore, "Build changed the source project."); + string verification = Path.Combine(root, "readback", "packages"); Directory.CreateDirectory(verification); + foreach (string path in Directory.EnumerateFiles(catalog.PackageDirectory, "*.pkg").Concat(built.PackageFiles)) File.Copy(path, Path.Combine(verification, Path.GetFileName(path)), true); + using var readback = PackageCatalog.Open(Path.GetDirectoryName(verification)!, cacheOptions: new() { Enabled = false }); + foreach (var (tag, bytes) in compiled) Check(readback.Read(tag).AsSpan().SequenceEqual(bytes), $"Package readback differs at {tag:X8}."); + Check(ActivityRegistrationTables.ReadDefinitions(readback.Read(ActivityRegistrationTables.DefinitionTag)).Count == 3, "Built table did not decode."); + Check(PackageManifest.Read(readback.Read(0x81327D65)).Lists(recipe.Tag()), "Investment globals manifest missed the name-based activity dependency."); + using var receipt = JsonDocument.Parse(File.ReadAllBytes(built.ReceiptPath)); + Check(receipt.RootElement.GetProperty("dependencyEdits").GetArrayLength() >= expectedAssets, "Dependency records missed registration assets."); + Check(receipt.RootElement.GetProperty("addedAssetsInNoRecord").GetArrayLength() == 0, "Registration has unlisted assets."); + Check(new AssetSceneLoader(readback).DescribeScenario(recipe.Tag(1)).Bubbles.Count == 1, "Built scenario did not decode."); + Check(readback.NamedTags.Any(row => row.TagHash == recipe.Tag() && row.Name == recipe.InternalName), "Activity native name was not published."); + var copied = StudioProject.Create(Path.Combine(root, "copy-project"), "Whole map copy"); + copied.ActivityRegistrationCompiler = ActivityRegistrationCompiler.Default; + copied.AddDerivedAsset("map-copy.bin", ActivityFixture.Base + 2, catalog.ReadOriginal(ActivityFixture.Base + 2), + new(0xAAA, 0x808091DE, 0x200A, "map:map_copy:root", 0), catalog); + var copiedRecipe = recipe with { PackageId = 0xAAA, FirstEntryIndex = 1, MapRootTag = 0x81D54000, ScenarioStem = "map_copy", InternalName = "copied_activity" }; + var copiedPlan = ActivityRegistrationCompiler.Prepare(copied, catalog, copiedRecipe); + var copiedTables = ActivityRegistrationTables.Append(definitions, clients, [copiedPlan.Row]); + copied.ApplyTransaction(copiedPlan.Additions, _ => new(new Dictionary { [ActivityRegistrationTables.DefinitionTag] = copiedTables.Definitions, + [ActivityRegistrationTables.ClientTag] = copiedTables.Clients }) { AddedActivities = [copiedRecipe] }, catalog); + Check(copied.CompileActivities(catalog).Count == copiedPlan.Additions.Count + 2, "Whole-map copy registration failed."); + var copyBuild = ProjectBuilder.Build(copied, catalog, Path.Combine(root, "copy-build")); + using var copyReceipt = JsonDocument.Parse(File.ReadAllBytes(copyBuild.ReceiptPath)); + Check(copyReceipt.RootElement.GetProperty("addedAssetsInNoRecord").GetArrayLength() == 0, "Named map root has no dependency record."); + int gameArg = Array.IndexOf(args, "--game-root"), keysArg = Array.IndexOf(args, "--key-source"); + if (gameArg >= 0) InstalledChecks.Run(args[gameArg + 1], keysArg >= 0 ? args[keysArg + 1] : null, root); + Console.WriteLine($"activity checks={checks} tables=byte-identical scenario=byte-identical text=byte-identical transaction=pass package-readback=pass output={root}"); +} +catch (Exception error) { Console.Error.WriteLine(error); Console.Error.WriteLine("Fixture output: " + root); Environment.ExitCode = 1; } diff --git a/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj b/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj new file mode 100644 index 00000000..32489485 --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net9.0-windows + + + + + + + diff --git a/tests/SunriseStudio.Activity.Tests/activity_registration_golden.json b/tests/SunriseStudio.Activity.Tests/activity_registration_golden.json new file mode 100644 index 00000000..1b6508df --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/activity_registration_golden.json @@ -0,0 +1,45 @@ +{ + "source": { + "image_sha256": "58323a5e77bc1d77b7c10817e30a1a91361b9794b49ef43073de273d6c46cf90", + "investment_table_sha256": "e0e4228aecd327a7ccb721891bf014286d9a9200e921f30b6a13ef7959ec6edf", + "client_table_sha256": "a26e90af58ddafa9093c5954bd93d68b1bd92a05e34b3468aa881ae4b6e667c8", + "evidence": "Pinned native reflection in docs/schema_registry.json and installed 0593 table bodies; body hashes were captured before constructor implementation." + }, + "children": { + "matchmaking": { + "class": "8080773D", "size": 72, + "program_rva": "3B90658", + "program_sha256": "e476ed10ef90c4e7c04426802c611891e835bff42f2b07cc94661dacf248c5de", + "body_sha256": "5ccba55c27586f16d3f399271aa0cfe09910e7eb03c2e4cb7a0b0d56871df903", + "precedent_count": 652 + }, + "investment_generic": { + "class": "8080773A", "size": 16, + "program_rva": "3B24B68", + "program_sha256": "249e06162585afdba9d6becfe2700c11bcfc4656b80ed1e1099058cc969bdb5d", + "body_sha256": "374708fff7719dd5979ec875d56cd2286f6d3cf7ec317a3b25632aab28ec37bb", + "precedent_count": 1170 + }, + "client_generic": { + "class": "80805E21", "size": 40, + "program_rva": "3B3C988", + "program_sha256": "63f0b2a119d084af62b6133941cb0533b94c8d6f97946da3369e97ebf1b9b849", + "body_sha256": "366ca2bdc0f4d02cc7313fbcf92554389be996f5aebc1201b81647b45690f662", + "precedent_count": 873 + }, + "client_sidecar": { + "class": "80805EB9", "size": 48, + "program_rva": "3B29968", + "program_sha256": "edba4606df30f456202c69341955214952213728f1a3fe357e1da0842f73dbe3", + "body_sha256": "17b0761f87b081d5cf10757ccc89f12be355c70e2e29df288b65b30710dcbcd1", + "precedent_count": 950 + }, + "empty_display": { + "class": "80805E23", "size": 36, + "program_rva": "3B62910", + "program_sha256": "69bb0e2acc3ca876b4a758691cfd166a5f0a84f94b859e7a24ea444457dd8c8e", + "body_sha256": "0be65a6d215a414f977d7f578193eb49a6e89dfdcc0e945fa77b4f726ee877cb", + "precedent_count": 6 + } + } +} diff --git a/tests/SunriseStudio.Activity.Tests/oracle.py b/tests/SunriseStudio.Activity.Tests/oracle.py new file mode 100644 index 00000000..7c050f27 --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/oracle.py @@ -0,0 +1,38 @@ +"""Run the read-only World Studio oracle under python -I on synthetic C# fixtures.""" +import hashlib +import json +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(sys.argv[1]).resolve())) +import activity_definitions as definitions +import activity_client as client +import standalone_activity +import localized_strings +from bubble_allocation import name_hash + +out = Path(sys.argv[2]) +read = lambda name: (out / (name + '.input.bin')).read_bytes() +if '--installed' in sys.argv: + request = json.loads((out / 'request.json').read_text()) + addition = definitions.Addition(request['template'], request['hash'], request['name']) + inv, _ = definitions.append(read('definitions'), [addition]) + cli, _ = client.append(read('clients'), [row.definition_hash for row in definitions.decode(read('definitions'))], [addition]) + for name, raw in dict(definitions=inv, clients=cli).items(): + assert raw == (out / (name + '.actual.bin')).read_bytes(), name + ' installed parity differs' + print('Python oracle: both installed-table appends match byte for byte.') + sys.exit(0) +addition = definitions.Addition(0x12345678, 0x87654321, 'new_activity') +inv, _ = definitions.append(read('definitions'), [addition]) +cli, _ = client.append(read('clients'), [row.definition_hash for row in definitions.decode(read('definitions'))], [addition]) +scenario, _ = standalone_activity.rebind_scenario(read('scenario'), 'template', 'new_activity', 'map_copy') +slice_data = standalone_activity.rebind_slice(read('slice'), 'map_copy', 0x80A00005) +container, data = localized_strings.build({name_hash('map_copy'): 'New World é'}) +container = localized_strings.encode_container([name_hash('map_copy')], [0x80A00001] * 13) +results = dict(definitions=inv, clients=cli, scenario=scenario, slice=slice_data, + **{'text-container': container, 'text-data': data}) +for name, raw in results.items(): + (out / (name + '.expected.bin')).write_bytes(raw) + assert raw == (out / (name + '.actual.bin')).read_bytes(), name + ' parity differs' +(out / 'registration-parity.json').write_text(json.dumps({key: hashlib.sha256(raw).hexdigest() for key, raw in results.items()}, indent=2) + '\n') +print('Python oracle: six complete synthetic payloads match byte for byte.') diff --git a/tests/SunriseStudio.Activity.Tests/registration-parity.json b/tests/SunriseStudio.Activity.Tests/registration-parity.json new file mode 100644 index 00000000..eefd649c --- /dev/null +++ b/tests/SunriseStudio.Activity.Tests/registration-parity.json @@ -0,0 +1,8 @@ +{ + "definitions": "7611ad4152ab7f3134cbffc9dfd6a7209d216d6d786acf5039e8099a0310caec", + "clients": "854be8c5d0523206f411adac2542aa90e703f5be665a67a6dcc45efafb974948", + "scenario": "0b0aaa62e4d545fb6cc74056723d45b4c8f23c542f8acbb72f1fd61287a2ef60", + "slice": "6f20d12d1e7c239f0ce4c9a8b92b0fd03630bcd5ff23564fefd887ac0645d9a5", + "text-container": "df1bef99b3a6a284a966111963c652a496897d79138cd71d7215bdd50930267f", + "text-data": "f5cf9c493bab7fa8ae5923d897d15e7d1ce839f9f2e73eee1b58e2e6fb819a4a" +} diff --git a/verify.ps1 b/verify.ps1 index 0eba0c48..b9771942 100644 --- a/verify.ps1 +++ b/verify.ps1 @@ -46,6 +46,7 @@ if ($Game -and -not $SkipBuild) { # Each check program and its target framework, in run order. $studioChecks = [ordered]@{ + 'Activity.Tests' = 'net9.0-windows' 'Projects.Tests' = 'net9.0'; 'Formats.Tests' = 'net9.0'; 'Missions.Tests' = 'net9.0'; 'Cui.Tests' = 'net9.0' 'Cui.Gpu.Tests' = 'net9.0-windows'; 'Investment.Tests' = 'net9.0-windows'; 'Live.Tests' = 'net9.0-windows' 'LiveBinding.Tests' = 'net9.0-windows'; 'LivePose.Tests' = 'net9.0-windows'; 'Audio.Tests' = 'net9.0-windows' @@ -59,6 +60,7 @@ $studioChecks = [ordered]@{ } # The arguments each check takes with -Game; checks not listed take none. $gameArgs = @{ + 'Activity.Tests' = @('--game-root', $Game) 'Cui.Gpu.Tests' = @('--game-root', $Game, '--output', (Join-Path $Output 'cui-fonts')) 'Investment.Tests' = @('--game-root', $Game, '--ui', (Join-Path $Output 'features/investment-stat-authoring.png')) 'LivePose.Tests' = @('--game', $Game); 'Animation.Tests' = @('--game', $Game); 'Tags.Tests' = @('--game', $Game, '--tft', '5') From 5d7bca7fcc7bc9c1a6f1c24dfd48778e41812c42 Mon Sep 17 00:00:00 2001 From: Techno453 Date: Wed, 21 Oct 2026 10:31:00 -0600 Subject: [PATCH 2/4] Write activity arrays through the shared NativeArrays helper ActivityBytes keeps its padded and tight placements but frames every array through NativeArrays, the same file in every world-authoring branch that appends typed arrays, so merging them dedupes it. The bytes are unchanged. --- .../ActivityRegistrationTables.cs | 7 ++- src/SunriseStudio.Formats/NativeArrays.cs | 62 +++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 src/SunriseStudio.Formats/NativeArrays.cs diff --git a/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs b/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs index 189f0140..3007c654 100644 --- a/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs +++ b/src/SunriseStudio.Authoring/ActivityRegistrationTables.cs @@ -1,5 +1,6 @@ using System.Buffers.Binary; using System.Text; +using SunriseStudio.Formats; namespace SunriseStudio.Authoring; @@ -184,9 +185,9 @@ internal int[] Array(int field, uint cls, int stride, byte[] rows, bool tight = { if (rows.Length == 0) { I64(field, 0); I64(field + 8, 0); return []; } int count = rows.Length / stride; - int first = tight ? (Length + 35) & ~15 : ((Length + 15) & ~15) + 32; - Add(new byte[first - Length]); U32(first - 20, 0x80809FBD); I64(first - 16, count); U32(first - 8, cls); - Add(rows); I64(field, count); I64(field + 8, first - field - 24); + int first = tight ? NativeArrays.NativeStart(Length) : NativeArrays.PaddedStart(Length); + Add(new byte[first - Length]); Add(rows); + NativeArrays.Frame(stream.GetBuffer().AsSpan(0, Length), field, cls, count, first); return Enumerable.Range(0, count).Select(i => first + i * stride).ToArray(); } internal byte[] Finish() { I64(0, Length); ActivityRegistrationTables.Require(Length <= 4 * 1024 * 1024, "Activity resource exceeds capacity."); return stream.ToArray(); } diff --git a/src/SunriseStudio.Formats/NativeArrays.cs b/src/SunriseStudio.Formats/NativeArrays.cs new file mode 100644 index 00000000..80e8ace9 --- /dev/null +++ b/src/SunriseStudio.Formats/NativeArrays.cs @@ -0,0 +1,62 @@ +using System.Buffers.Binary; + +namespace SunriseStudio.Formats; + +/** + * Typed native arrays: rows follow {marker 0x80809FBD, u64 count, u32 class, u32 0}, and the owner's + * {u64 count, i64 relative} descriptor puts the first row at descriptor + 24 + relative. No rows is a zero descriptor. + */ +public static class NativeArrays +{ + /** The word 20 bytes before the first row of every typed array. */ + public const uint Marker = 0x80809FBD; + + /** First row of an array appended at end in the installed placement: align16(end + 20). */ + public static int NativeStart(int end) => checked((end + 35) & ~15); + + /** First row of an array appended at end after 12 zero bytes and the prefix (World Studio map_definition.append_array). */ + public static int PaddedStart(int end) => checked(((end + 15) & ~15) + 32); + + /** Writes the prefix before first and points the descriptor at it; the rows are the caller's. */ + public static void Frame(Span payload, int descriptor, uint type, int count, int first) + { + if (count < 0 || first < 20 || descriptor < 0 || descriptor > payload.Length - 16 || first > payload.Length) + throw new InvalidDataException("A typed array leaves its payload."); + BinaryPrimitives.WriteUInt32LittleEndian(payload[(first - 20)..], Marker); + BinaryPrimitives.WriteInt64LittleEndian(payload[(first - 16)..], count); + BinaryPrimitives.WriteUInt32LittleEndian(payload[(first - 8)..], type); + BinaryPrimitives.WriteUInt32LittleEndian(payload[(first - 4)..], 0); + BinaryPrimitives.WriteInt64LittleEndian(payload[descriptor..], count); + BinaryPrimitives.WriteInt64LittleEndian(payload[(descriptor + 8)..], first - descriptor - 24); + } + + /** + * Copies source with rows appended in the installed placement and the size word at +0 updated. + * No rows leaves a zero descriptor, the size and every other byte as they were; first is then -1. + */ + public static byte[] AppendNative(byte[] source, int descriptor, uint type, IReadOnlyList rows, out int first) => + Append(source, descriptor, type, rows, NativeStart(source.Length), out first); + + /** AppendNative with World Studio's padded placement. */ + public static byte[] AppendPadded(byte[] source, int descriptor, uint type, IReadOnlyList rows, out int first) => + Append(source, descriptor, type, rows, PaddedStart(source.Length), out first); + + private static byte[] Append(byte[] source, int descriptor, uint type, IReadOnlyList rows, int start, out int first) + { + if (descriptor < 0 || descriptor > source.Length - 16) throw new InvalidDataException("A typed array leaves its payload."); + if (rows.Count == 0) + { + byte[] empty = source.ToArray(); + empty.AsSpan(descriptor, 16).Clear(); + first = -1; + return empty; + } + byte[] output = new byte[checked(start + rows.Sum(row => row.Length))]; + source.CopyTo(output, 0); + int at = first = start; + foreach (byte[] row in rows) { row.CopyTo(output, at); at += row.Length; } + Frame(output, descriptor, type, rows.Count, start); + BinaryPrimitives.WriteInt64LittleEndian(output, output.Length); + return output; + } +} From c72d95d51bc9f50574c92d5203eaa6152a92e100 Mon Sep 17 00:00:00 2001 From: Techno453 Date: Wed, 21 Oct 2026 10:31:00 -0600 Subject: [PATCH 3/4] Name activity registrations as a version 8 manifest feature Version 8 now lists the features a manifest holds by name, so this and the other world-authoring features can merge in any order. A build refuses a manifest naming a feature it does not know. --- src/SunriseStudio.Projects/ProjectModels.cs | 19 +++++++++- src/SunriseStudio.Projects/StudioProject.cs | 36 ++++++++++++++++--- tests/SunriseStudio.Activity.Tests/Program.cs | 9 ++++- 3 files changed, 57 insertions(+), 7 deletions(-) diff --git a/src/SunriseStudio.Projects/ProjectModels.cs b/src/SunriseStudio.Projects/ProjectModels.cs index 367fc02b..467bb54d 100644 --- a/src/SunriseStudio.Projects/ProjectModels.cs +++ b/src/SunriseStudio.Projects/ProjectModels.cs @@ -34,13 +34,19 @@ public sealed record AddedAssetSnapshot(AddedProjectAsset Asset, byte[] Data); /** * Mod stays null and unwritten until set, so older Studio builds still open the file. Versions: - * object edits 2, wide hashes 3, config bindings 4, names 5, groups 6, group collision parts 7, activities 8. + * object edits 2, wide hashes 3, config bindings 4, names 5, groups 6, group collision parts 7, + * named features 8: Features lists each ProjectFeatures name the manifest holds. */ public sealed record ProjectManifest(int Version, string Name, IReadOnlyList Changes, IReadOnlyList AddedAssets, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] ModMetadata? Mod = null, [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyList? ObjectEdits = null) { + /** Version 8 feature names in ordinal order; null below version 8. */ + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public IReadOnlyList? Features { get; init; } + /** True when the manifest names the version 8 feature. */ + public bool HasFeature(string name) => Features?.Contains(name, StringComparer.Ordinal) == true; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyList? ConfigBindings { get; init; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -51,6 +57,17 @@ public sealed record ProjectManifest(int Version, string Name, public IReadOnlyList? AddedActivities { get; init; } } +/** + * Version 8 names each feature a manifest holds instead of taking a number per feature, so features merge in any + * order. A build refuses a manifest naming a feature it does not know, because saving would drop its data. + */ +public static class ProjectFeatures +{ + public const string AddedActivities = "added-activities"; + /** Every feature this build reads and writes. */ + public static IReadOnlyList Known { get; } = [AddedActivities]; +} + /** * Editor objects that select and transform together; the build never reads it. * Members keep the whole target, because the key alone cannot find a scene object again. diff --git a/src/SunriseStudio.Projects/StudioProject.cs b/src/SunriseStudio.Projects/StudioProject.cs index 2941819e..2e3ff496 100644 --- a/src/SunriseStudio.Projects/StudioProject.cs +++ b/src/SunriseStudio.Projects/StudioProject.cs @@ -58,14 +58,17 @@ public static StudioProject Open(string manifestOrFolder) string path = Path.Combine(folder, ProjectFileName); ProjectPaths.RejectLinks(path); if (new FileInfo(path).Length > MaximumManifestBytes) throw new InvalidDataException("Project manifest is too large."); - var data = JsonSerializer.Deserialize(File.ReadAllBytes(path), ProjectJson.Options) + byte[] json = File.ReadAllBytes(path); + RequireKnownFeatures(json); + var data = JsonSerializer.Deserialize(json, ProjectJson.Options) ?? throw new InvalidDataException("Project manifest is empty."); if (data.Version > ManifestVersion) throw new InvalidDataException("This project needs a newer Sunrise Studio."); if (data.Version < 1 || string.IsNullOrWhiteSpace(data.Name) || data.Changes is null || data.AddedAssets is null || data.Version == 1 && data.ObjectEdits is not null || data.Version == 2 && data.ObjectEdits is null) throw new InvalidDataException("Unsupported project manifest."); + RequireFeatures(data); foreach (var edit in data.ObjectEdits ?? []) edit.Validate(); - if (data.AddedActivities is not null && data.Version < 8) + if (data.AddedActivities is not null && !data.HasFeature(ProjectFeatures.AddedActivities)) throw new InvalidDataException("Activity registrations require project manifest version 8."); ValidateActivities(data.AddedActivities ?? [], data.AddedAssets); data = data with { AddedActivities = data.AddedActivities is { Count: > 0 } @@ -321,17 +324,40 @@ private static ProjectManifest Versioned(ProjectManifest value) bool groups = value.ObjectGroups is { Count: > 0 }; bool parts = groups && value.ObjectGroups!.Any(group => group.CollisionParts is not null); bool activities = value.AddedActivities is { Count: > 0 }; - int version = activities ? 8 : parts ? 7 : groups ? 6 : names ? 5 : bindings ? 4 : aliases ? 3 : objects ? 2 : 1; - if (value.Version == version && ReferenceEquals(assets, value.AddedAssets) + var features = new List(); + if (activities) features.Add(ProjectFeatures.AddedActivities); + features.Sort(StringComparer.Ordinal); + int version = features.Count > 0 ? 8 : parts ? 7 : groups ? 6 : names ? 5 : bindings ? 4 : aliases ? 3 : objects ? 2 : 1; + if (value.Version == version && ReferenceEquals(assets, value.AddedAssets) && (value.Features ?? []).SequenceEqual(features) && (objects || value.ObjectEdits is null) && (bindings || value.ConfigBindings is null) && (names || value.ObjectNames is null) && (groups || value.ObjectGroups is null) && (activities || value.AddedActivities is null)) return value; - return value with { Version = version, AddedAssets = assets, + return value with { Version = version, Features = features.Count == 0 ? null : features.AsReadOnly(), AddedAssets = assets, ObjectEdits = objects ? value.ObjectEdits : null, ConfigBindings = bindings ? value.ConfigBindings : null, ObjectNames = names ? value.ObjectNames : null, ObjectGroups = groups ? value.ObjectGroups : null, AddedActivities = activities ? value.AddedActivities : null }; } + /** A manifest naming a feature this build does not know is refused before its fields are read. */ + private static void RequireKnownFeatures(byte[] json) + { + using var document = JsonDocument.Parse(json); + if (document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty("features", out var features) && features.ValueKind == JsonValueKind.Array + && features.EnumerateArray().Any(name => name.ValueKind == JsonValueKind.String + && !ProjectFeatures.Known.Contains(name.GetString()!, StringComparer.Ordinal))) + throw new InvalidDataException("This project needs a newer Sunrise Studio."); + } + + /** Features belong to version 8, each named once. */ + private static void RequireFeatures(ProjectManifest data) + { + if (data.Features is null) return; + if (data.Version < 8) throw new InvalidDataException("Named features require project manifest version 8."); + if (data.Features.Any(name => name is null) || data.Features.Distinct(StringComparer.Ordinal).Count() != data.Features.Count) + throw new InvalidDataException("Unsupported project manifest."); + } + private static byte[] SerializeManifest(ProjectManifest value) { byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(value, ProjectJson.Options); diff --git a/tests/SunriseStudio.Activity.Tests/Program.cs b/tests/SunriseStudio.Activity.Tests/Program.cs index 0fa09327..5176acfb 100644 --- a/tests/SunriseStudio.Activity.Tests/Program.cs +++ b/tests/SunriseStudio.Activity.Tests/Program.cs @@ -98,9 +98,16 @@ void Wait() workflow.Create(workspace); Wait(); var project = workspace.Project!; var catalog = workspace.Catalog!; Check(project.AddedActivities.Count == 1 && project.Changes.Count == 2, "Registration did not atomically publish its two deltas and recipe."); - Check(JsonDocument.Parse(File.ReadAllBytes(project.ManifestPath)).RootElement.GetProperty("version").GetInt32() == 8, "Manifest version did not advance."); + using (var manifest = JsonDocument.Parse(File.ReadAllBytes(project.ManifestPath))) + Check(manifest.RootElement.GetProperty("version").GetInt32() == 8 && manifest.RootElement.GetProperty("features").EnumerateArray() + .Select(name => name.GetString()).SequenceEqual([ProjectFeatures.AddedActivities]), "Manifest version did not advance with its feature."); var recipe = project.AddedActivities[0]; byte[] savedManifest = File.ReadAllBytes(project.ManifestPath); + var later = System.Text.Json.Nodes.JsonNode.Parse(savedManifest)!; + later["features"] = new System.Text.Json.Nodes.JsonArray(ProjectFeatures.AddedActivities, "later-feature"); + string laterPath = Path.Combine(root, "later-project", StudioProject.ProjectFileName); + Directory.CreateDirectory(Path.GetDirectoryName(laterPath)!); File.WriteAllText(laterPath, later.ToJsonString()); + Reject(() => StudioProject.Open(laterPath), "A manifest naming an unknown feature opened."); Reject(() => project.ApplyTransaction([], _ => new(new Dictionary()) { AddedActivities = [recipe with { InternalName = "invalid name" }] }, catalog), "Invalid registration transaction succeeded."); Check(File.ReadAllBytes(project.ManifestPath).AsSpan().SequenceEqual(savedManifest), "Failed registration changed the manifest."); From ad6811bb032bf6f6307107ce9aca55e08e6c00e3 Mon Sep 17 00:00:00 2001 From: Techno453 Date: Wed, 21 Oct 2026 10:31:00 -0600 Subject: [PATCH 4/4] Keep the activity parity oracle out of the repository The frozen hashes and the golden profile stay and run every time. The Python oracle now lives in the lab; WORLD_STUDIO_SOURCE and SUNRISE_PARITY_DRIVERS name it, and the live comparison is skipped when they are unset. --- .../InstalledChecks.cs | 5 ++- tests/SunriseStudio.Activity.Tests/Program.cs | 12 ++++-- .../SunriseStudio.Activity.Tests.csproj | 1 - tests/SunriseStudio.Activity.Tests/oracle.py | 38 ------------------- 4 files changed, 12 insertions(+), 44 deletions(-) delete mode 100644 tests/SunriseStudio.Activity.Tests/oracle.py diff --git a/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs b/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs index 099020ff..9ac12ff0 100644 --- a/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs +++ b/tests/SunriseStudio.Activity.Tests/InstalledChecks.cs @@ -30,10 +30,11 @@ internal static void Run(string game, string? keys, string root) foreach (var (name, bytes) in new[] { ("definitions.input", definitions), ("clients.input", clients), ("definitions.actual", tables.Definitions), ("clients.actual", tables.Clients) }) File.WriteAllBytes(Path.Combine(output, name + ".bin"), bytes); File.WriteAllText(Path.Combine(output, "request.json"), JsonSerializer.Serialize(new { template = template.Hash, hash = plan.Row.Hash, name = recipe.InternalName })); - if (Environment.GetEnvironmentVariable("WORLD_STUDIO_ORACLE") is { } oracle) + if (Environment.GetEnvironmentVariable("WORLD_STUDIO_SOURCE") is { Length: > 0 } oracle + && Environment.GetEnvironmentVariable("SUNRISE_PARITY_DRIVERS") is { Length: > 0 } drivers) { var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("PYTHON") ?? "python") { UseShellExecute = false }; - foreach (string arg in new[] { "-I", Path.Combine(AppContext.BaseDirectory, "oracle.py"), oracle, output, "--installed" }) start.ArgumentList.Add(arg); + foreach (string arg in new[] { "-I", Path.Combine(drivers, "activity_oracle.py"), oracle, output, "--installed" }) start.ArgumentList.Add(arg); using var process = Process.Start(start)!; process.WaitForExit(); if (process.ExitCode != 0) throw new InvalidDataException("Installed Python table parity failed."); } diff --git a/tests/SunriseStudio.Activity.Tests/Program.cs b/tests/SunriseStudio.Activity.Tests/Program.cs index 5176acfb..226c7eb2 100644 --- a/tests/SunriseStudio.Activity.Tests/Program.cs +++ b/tests/SunriseStudio.Activity.Tests/Program.cs @@ -50,11 +50,17 @@ void Reject(Action action, string message) foreach (var (key, bytes) in parity) File.WriteAllBytes(Path.Combine(root, key + ".actual.bin"), bytes); File.WriteAllBytes(Path.Combine(root, "definitions.input.bin"), definitions); File.WriteAllBytes(Path.Combine(root, "clients.input.bin"), clients); File.WriteAllBytes(Path.Combine(root, "scenario.input.bin"), scenario); File.WriteAllBytes(Path.Combine(root, "slice.input.bin"), ActivityFixture.Slice()); - string? oracle = Environment.GetEnvironmentVariable("WORLD_STUDIO_ORACLE"); - if (oracle is not null) + // The oracle and World Studio live outside this repository; WORLD_STUDIO_SOURCE and SUNRISE_PARITY_DRIVERS name them. + string? oracle = Environment.GetEnvironmentVariable("WORLD_STUDIO_SOURCE"), drivers = Environment.GetEnvironmentVariable("SUNRISE_PARITY_DRIVERS"); + if (string.IsNullOrWhiteSpace(oracle) || string.IsNullOrWhiteSpace(drivers)) + { + oracle = null; + Console.WriteLine("SKIP activity python-parity: set WORLD_STUDIO_SOURCE and SUNRISE_PARITY_DRIVERS; frozen hashes still run."); + } + else { var process = new ProcessStartInfo(Environment.GetEnvironmentVariable("PYTHON") ?? "python") { UseShellExecute = false }; - foreach (string arg in new[] { "-I", Path.Combine(AppContext.BaseDirectory, "oracle.py"), oracle, root }) process.ArgumentList.Add(arg); + foreach (string arg in new[] { "-I", Path.Combine(drivers, "activity_oracle.py"), oracle, root }) process.ArgumentList.Add(arg); using var child = Process.Start(process)!; child.WaitForExit(); Check(child.ExitCode == 0, "Python parity oracle failed."); foreach (var (key, bytes) in parity) Check(bytes.AsSpan().SequenceEqual(File.ReadAllBytes(Path.Combine(root, key + ".expected.bin"))), key + " differs from Python."); } diff --git a/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj b/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj index 32489485..e7d32f62 100644 --- a/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj +++ b/tests/SunriseStudio.Activity.Tests/SunriseStudio.Activity.Tests.csproj @@ -6,6 +6,5 @@ - diff --git a/tests/SunriseStudio.Activity.Tests/oracle.py b/tests/SunriseStudio.Activity.Tests/oracle.py deleted file mode 100644 index 7c050f27..00000000 --- a/tests/SunriseStudio.Activity.Tests/oracle.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Run the read-only World Studio oracle under python -I on synthetic C# fixtures.""" -import hashlib -import json -from pathlib import Path -import sys - -sys.path.insert(0, str(Path(sys.argv[1]).resolve())) -import activity_definitions as definitions -import activity_client as client -import standalone_activity -import localized_strings -from bubble_allocation import name_hash - -out = Path(sys.argv[2]) -read = lambda name: (out / (name + '.input.bin')).read_bytes() -if '--installed' in sys.argv: - request = json.loads((out / 'request.json').read_text()) - addition = definitions.Addition(request['template'], request['hash'], request['name']) - inv, _ = definitions.append(read('definitions'), [addition]) - cli, _ = client.append(read('clients'), [row.definition_hash for row in definitions.decode(read('definitions'))], [addition]) - for name, raw in dict(definitions=inv, clients=cli).items(): - assert raw == (out / (name + '.actual.bin')).read_bytes(), name + ' installed parity differs' - print('Python oracle: both installed-table appends match byte for byte.') - sys.exit(0) -addition = definitions.Addition(0x12345678, 0x87654321, 'new_activity') -inv, _ = definitions.append(read('definitions'), [addition]) -cli, _ = client.append(read('clients'), [row.definition_hash for row in definitions.decode(read('definitions'))], [addition]) -scenario, _ = standalone_activity.rebind_scenario(read('scenario'), 'template', 'new_activity', 'map_copy') -slice_data = standalone_activity.rebind_slice(read('slice'), 'map_copy', 0x80A00005) -container, data = localized_strings.build({name_hash('map_copy'): 'New World é'}) -container = localized_strings.encode_container([name_hash('map_copy')], [0x80A00001] * 13) -results = dict(definitions=inv, clients=cli, scenario=scenario, slice=slice_data, - **{'text-container': container, 'text-data': data}) -for name, raw in results.items(): - (out / (name + '.expected.bin')).write_bytes(raw) - assert raw == (out / (name + '.actual.bin')).read_bytes(), name + ' parity differs' -(out / 'registration-parity.json').write_text(json.dumps({key: hashlib.sha256(raw).hexdigest() for key, raw in results.items()}, indent=2) + '\n') -print('Python oracle: six complete synthetic payloads match byte for byte.')