diff --git a/RPGModder.Core/Merge/CommandBranch.cs b/RPGModder.Core/Merge/CommandBranch.cs
new file mode 100644
index 0000000..aa90741
--- /dev/null
+++ b/RPGModder.Core/Merge/CommandBranch.cs
@@ -0,0 +1,11 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// One body of a block (guide 3.6). Marker is null for an unmarked body, as the first body of a
+/// Conditional Branch or a Loop. Body ends with its code 0 node.
+///
+internal sealed record CommandBranch(
+ JObject? Marker,
+ IReadOnlyList Body);
diff --git a/RPGModder.Core/Merge/CommandNode.cs b/RPGModder.Core/Merge/CommandNode.cs
new file mode 100644
index 0000000..399e124
--- /dev/null
+++ b/RPGModder.Core/Merge/CommandNode.cs
@@ -0,0 +1,14 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// One command of a list with what belongs to it (guide 3.6): the continuation lines of its block, its branches, and
+/// the end marker that closes them. The code 0 command that ends a body or the list is a node of its own with
+/// nothing below it. End is kept, and not rebuilt, so a list comes back unchanged (GR-T1).
+///
+internal sealed record CommandNode(
+ JObject Head,
+ IReadOnlyList Continuations,
+ IReadOnlyList Branches,
+ JObject? End);
diff --git a/RPGModder.Core/Merge/CommandTree.cs b/RPGModder.Core/Merge/CommandTree.cs
new file mode 100644
index 0000000..b302221
--- /dev/null
+++ b/RPGModder.Core/Merge/CommandTree.cs
@@ -0,0 +1,279 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Parses a command list into its tree and back (guide 3.6). Structure is indent alone, as in the engine's
+/// Game_Interpreter: a branch marker tests only the branch of its own indent, and skipBranch skips the
+/// deeper commands. The parser is strict, so a list it accepts is walked by the engine the way the tree says, and
+/// anything else is one Atomic value (GR-T2).
+///
+internal static class CommandTree
+{
+ /// The code that ends a body and the list.
+ internal const int EndCode = 0;
+
+ ///
+ /// A list nested deeper than this is one Atomic value. The editor stops far below it, and the bound keeps the
+ /// parser's recursion on a stack of any size.
+ ///
+ internal const int MaxDepth = 100;
+
+ private const string CodeProperty = "code";
+ private const string IndentProperty = "indent";
+
+ /// The blocks of guide 3.6 whose head is followed by lines of its own at the same indent.
+ private static readonly Dictionary ContinuationOf = new()
+ {
+ [101] = 401,
+ [105] = 405,
+ [108] = 408,
+ [205] = 505,
+ [302] = 605,
+ [355] = 655,
+ [357] = 657
+ };
+
+ /// The blocks of guide 3.6 that hold bodies.
+ private static readonly Dictionary Blocks = new()
+ {
+ [102] = new BlockShape(FirstBodyUnmarked: false, Markers: [402, 403], End: 404, OnlyWithMarkers: false),
+ [111] = new BlockShape(FirstBodyUnmarked: true, Markers: [411], End: 412, OnlyWithMarkers: false),
+ [112] = new BlockShape(FirstBodyUnmarked: true, Markers: [], End: 413, OnlyWithMarkers: false),
+ [301] = new BlockShape(FirstBodyUnmarked: false, Markers: [601, 602, 603], End: 604, OnlyWithMarkers: true)
+ };
+
+ /// Codes that only follow their head: a list that starts a node with one is not parsed.
+ private static readonly HashSet Followers = ContinuationOf.Values
+ .Concat(Blocks.Values.SelectMany(shape => shape.Markers.Append(shape.End)))
+ .ToHashSet();
+
+ ///
+ /// The nodes of the list, the final code 0 node last, or null when the list is not well formed: a command
+ /// that is not an object with a whole code and indent, an indent that is not the depth of its
+ /// place, a continuation, marker or end marker without its head, a body or a list without its code 0, or
+ /// anything after the final one.
+ ///
+ internal static IReadOnlyList? Parse(JArray list)
+ {
+ ArgumentNullException.ThrowIfNull(list);
+
+ var reader = new Reader(list);
+ return reader.TryBody(0, out List nodes) && reader.AtEnd ? nodes : null;
+ }
+
+ /// The commands of in order, each a copy with its indent set to its depth (GR-T1).
+ internal static JArray Flatten(IReadOnlyList nodes)
+ {
+ ArgumentNullException.ThrowIfNull(nodes);
+
+ var list = new JArray();
+ Emit(nodes, 0, list);
+ return list;
+ }
+
+ /// The commands of one node at , for comparing nodes and for fingerprints.
+ internal static JArray Flatten(CommandNode node, int depth)
+ {
+ var list = new JArray();
+ Emit([node], depth, list);
+ return list;
+ }
+
+ ///
+ /// GR-T8: indent steps of at most one, markers only after their head, every body terminated and the final
+ /// terminator. These are what checks, so a list is valid when it parses.
+ ///
+ internal static bool Validate(JArray list)
+ {
+ return Parse(list) is not null;
+ }
+
+ internal static bool IsEnd(CommandNode node)
+ {
+ return node.Head.Value(CodeProperty) == EndCode;
+ }
+
+ private static void Emit(IReadOnlyList nodes, int depth, JArray list)
+ {
+ foreach (CommandNode node in nodes)
+ {
+ Add(node.Head, depth, list);
+ foreach (JObject line in node.Continuations)
+ {
+ Add(line, depth, list);
+ }
+
+ foreach (CommandBranch branch in node.Branches)
+ {
+ if (branch.Marker is not null)
+ {
+ Add(branch.Marker, depth, list);
+ }
+
+ Emit(branch.Body, depth + 1, list);
+ }
+
+ if (node.End is not null)
+ {
+ Add(node.End, depth, list);
+ }
+ }
+ }
+
+ private static void Add(JObject command, int depth, JArray list)
+ {
+ var copy = (JObject)command.DeepClone();
+ copy[IndentProperty] = depth;
+ list.Add(copy);
+ }
+
+ private sealed record BlockShape(bool FirstBodyUnmarked, long[] Markers, long End, bool OnlyWithMarkers);
+
+ private sealed class Reader
+ {
+ private readonly JArray _list;
+ private int _position;
+
+ public Reader(JArray list)
+ {
+ _list = list;
+ }
+
+ public bool AtEnd => _position == _list.Count;
+
+ /// The nodes at up to and with the code 0 that ends them.
+ public bool TryBody(int depth, out List nodes)
+ {
+ nodes = new List();
+ if (depth > MaxDepth)
+ {
+ return false;
+ }
+
+ while (CodeAt(_position, depth) is long code)
+ {
+ var head = (JObject)_list[_position];
+ _position++;
+ if (code == EndCode)
+ {
+ nodes.Add(new CommandNode(head, [], [], null));
+ return true;
+ }
+
+ if (!TryNode(head, code, depth, out CommandNode? node))
+ {
+ return false;
+ }
+
+ nodes.Add(node);
+ }
+
+ return false;
+ }
+
+ private bool TryNode(JObject head, long code, int depth, out CommandNode node)
+ {
+ node = new CommandNode(head, [], [], null);
+ if (Followers.Contains(code))
+ {
+ return false;
+ }
+
+ var continuations = new List();
+ if (ContinuationOf.TryGetValue(code, out long continuation))
+ {
+ while (CodeAt(_position, depth) == continuation)
+ {
+ continuations.Add((JObject)_list[_position]);
+ _position++;
+ }
+ }
+
+ var branches = new List();
+ JObject? end = null;
+ if (Blocks.TryGetValue(code, out BlockShape? shape))
+ {
+ if (!TryBlock(shape, depth, branches, out end))
+ {
+ return false;
+ }
+ }
+ else if (CodeAt(_position, depth + 1) is not null)
+ {
+ // GR-T2: a code the parser does not know, with deeper commands after it, holds one unmarked body.
+ if (!TryBody(depth + 1, out List body))
+ {
+ return false;
+ }
+
+ branches.Add(new CommandBranch(null, body));
+ }
+
+ node = new CommandNode(head, continuations, branches, end);
+ return true;
+ }
+
+ private bool TryBlock(BlockShape shape, int depth, List branches, out JObject? end)
+ {
+ end = null;
+ if (shape.OnlyWithMarkers && !IsMarker(shape, CodeAt(_position, depth)))
+ {
+ // Battle Processing without Can Escape or Can Lose has no branches and no end.
+ return true;
+ }
+
+ if (shape.FirstBodyUnmarked)
+ {
+ if (!TryBody(depth + 1, out List first))
+ {
+ return false;
+ }
+
+ branches.Add(new CommandBranch(null, first));
+ }
+
+ while (IsMarker(shape, CodeAt(_position, depth)))
+ {
+ var marker = (JObject)_list[_position];
+ _position++;
+ if (!TryBody(depth + 1, out List body))
+ {
+ return false;
+ }
+
+ branches.Add(new CommandBranch(marker, body));
+ }
+
+ if (CodeAt(_position, depth) != shape.End)
+ {
+ return false;
+ }
+
+ end = (JObject)_list[_position];
+ _position++;
+ return true;
+ }
+
+ private static bool IsMarker(BlockShape shape, long? code)
+ {
+ return code is long value && shape.Markers.Any(marker => marker == value);
+ }
+
+ /// The code of the command at when it is a well-formed command at .
+ private long? CodeAt(int index, int depth)
+ {
+ if (index >= _list.Count ||
+ _list[index] is not JObject command ||
+ command.Property(CodeProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long code } ||
+ command.Property(IndentProperty, StringComparison.Ordinal)?.Value is not JValue { Value: long indent } ||
+ indent != depth)
+ {
+ return null;
+ }
+
+ // A whole number too large for a long is read as a BigInteger, so it is not a code.
+ return code;
+ }
+ }
+}
diff --git a/RPGModder.Core/Merge/Composer.Lists.cs b/RPGModder.Core/Merge/Composer.Lists.cs
new file mode 100644
index 0000000..f4639f6
--- /dev/null
+++ b/RPGModder.Core/Merge/Composer.Lists.cs
@@ -0,0 +1,238 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+public static partial class Composer
+{
+ ///
+ /// Guide 3.6: a command list or a Sequence list that two or more mods edit in different ways is merged with
+ /// vanilla's (GR-T4, GR-T9), and stays one op whose value is the whole merged list (seam 11.5). Runs the mods
+ /// changed in different ways are one LogicClash or SequenceClash for the list, and inserts of more
+ /// than one mod at one gap one OrderAmbiguous. False leaves the cluster to the 2a path, where the list is
+ /// one value: no vanilla list, a list that is not well formed (GR-T2), or a merge some choice would leave invalid
+ /// (GR-T8).
+ ///
+ private static bool TryComposeList(
+ List cluster,
+ BaseRoots bases,
+ ILookup choices,
+ Dictionary priorities,
+ List ops,
+ List<(Collision, CollisionOutcome)> collisions,
+ List diagnostics)
+ {
+ if (cluster.Count != 1 || cluster[0].Variants.Count < 2)
+ {
+ return false;
+ }
+
+ OpGroup group = cluster[0];
+ ChangeKind kind = group.Variants[0].Op.Kind;
+ if (kind is not (ChangeKind.EditCommands or ChangeKind.EditSequence) ||
+ group.Variants.Any(variant => variant.Op.Kind != kind || variant.Op.Value is not JArray) ||
+ group.Variants.SelectMany(variant => variant.ModIds).GroupBy(id => id, StringComparer.Ordinal).Any(ids => ids.Count() > 1) ||
+ bases.ValueAt(group.Key, group.Path) is not JArray vanilla)
+ {
+ return false;
+ }
+
+ // Profile order: the side of the mod earliest in it first, as GR-T7 orders the inserts of one gap.
+ List variants = group.Variants
+ .OrderBy(variant => variant.ModIds.Min(id => priorities[id]))
+ .ThenBy(variant => variant.ModIds.Min(StringComparer.Ordinal), StringComparer.Ordinal)
+ .ToList();
+ Func? run = kind == ChangeKind.EditCommands
+ ? CommandMerge(vanilla, variants)
+ : SequenceMerge(vanilla, variants);
+ if (run is null)
+ {
+ return false;
+ }
+
+ // Each choice is merged once: the check of every choice below holds the first pass and the final one.
+ var results = new Dictionary();
+ ListMergeResult Merge(ListPolicy policy)
+ {
+ if (!results.TryGetValue(policy, out ListMergeResult? result))
+ {
+ result = run(policy);
+ results.Add(policy, result);
+ }
+
+ return result;
+ }
+
+ ListMergeResult found = Merge(ListPolicy.Unresolved);
+ var decisions = new List();
+ (Collision Collision, CollisionOutcome Outcome)? clash = null;
+ if (found.ClashMods.Count > 0)
+ {
+ CollisionKind clashKind = kind == ChangeKind.EditCommands ? CollisionKind.LogicClash : CollisionKind.SequenceClash;
+ Collision collision = ListCollision(clashKind, group, found.ClashMods, found.ClashFingerprint);
+ clash = (collision, Decide(collision, choices, decisions));
+ }
+
+ (Collision Collision, CollisionOutcome Outcome)? order = null;
+ if (found.OrderMods.Count > 0)
+ {
+ Collision collision = ListCollision(CollisionKind.OrderAmbiguous, group, found.OrderMods, found.OrderFingerprint);
+ order = (collision, Decide(collision, choices, decisions));
+ }
+
+ if (kind == ChangeKind.EditCommands && !Policies(found).All(policy => CommandTree.Validate(Merge(policy).List)))
+ {
+ return false;
+ }
+
+ diagnostics.AddRange(decisions);
+ if (clash is not null)
+ {
+ collisions.Add(clash.Value);
+ }
+
+ if (order is not null)
+ {
+ collisions.Add(order.Value);
+ }
+
+ if (clash is { Outcome.Source: ResolutionSource.Unresolved })
+ {
+ // The clash is described by its collision and blocks the plan, so no op stands for the list.
+ return true;
+ }
+
+ CollisionOutcome? clashOutcome = clash?.Outcome;
+ CollisionOutcome? orderOutcome = order?.Outcome;
+ var policy = new ListPolicy(
+ clashOutcome?.Kind,
+ clashOutcome?.Kind == ResolutionKind.PickMod ? clashOutcome.ModId : null,
+ orderOutcome?.Kind == ResolutionKind.PickMod ? orderOutcome.ModId : null);
+ ListMergeResult result = Merge(policy);
+ if (JToken.DeepEquals(result.List, vanilla))
+ {
+ // Nothing of any mod is in the list: a clash kept as vanilla, or changes that undo each other.
+ return true;
+ }
+
+ // Each side is every mod holding one list, so the variant of the first contributor sorts that mod first.
+ Variant lead = variants.First(variant => variant.ModIds.Contains(result.Contributors[0], StringComparer.Ordinal));
+ ops.Add(new MergedOp(lead.Op with { Value = result.List }, result.Contributors));
+ return true;
+ }
+
+ private static Func? CommandMerge(JArray vanilla, List variants)
+ {
+ IReadOnlyList? vanillaNodes = CommandTree.Parse(vanilla);
+ var sides = new List>();
+ foreach (Variant variant in variants)
+ {
+ IReadOnlyList? nodes = CommandTree.Parse((JArray)variant.Op.Value!);
+ if (nodes is null)
+ {
+ return null;
+ }
+
+ sides.Add(new ListSide(nodes, variant.ModIds.Order(StringComparer.Ordinal).ToList()));
+ }
+
+ return vanillaNodes is null ? null : policy => ListMerge.MergeCommands(vanillaNodes, sides, policy);
+ }
+
+ private static Func SequenceMerge(JArray vanilla, List variants)
+ {
+ List vanillaItems = vanilla.ToList();
+ List> sides = variants
+ .Select(variant => new ListSide(((JArray)variant.Op.Value!).ToList(), variant.ModIds.Order(StringComparer.Ordinal).ToList()))
+ .ToList();
+ return policy => ListMerge.MergeSequence(vanillaItems, sides, policy);
+ }
+
+ /// GR-T8: every choice the player could make for the list's collisions, so each one gives a valid list.
+ private static IEnumerable Policies(ListMergeResult found)
+ {
+ List<(ResolutionKind? Kind, string? Mod)> clashChoices = found.ClashMods.Count == 0
+ ? [(null, null)]
+ : [(ResolutionKind.PickVanilla, null), .. found.ClashMods.Select(mod => ((ResolutionKind?)ResolutionKind.PickMod, (string?)mod))];
+ List firstChoices = [null, .. found.OrderMods];
+ foreach ((ResolutionKind? kind, string? mod) in clashChoices)
+ {
+ foreach (string? first in firstChoices)
+ {
+ yield return new ListPolicy(kind, mod, first);
+ }
+ }
+ }
+
+ /// One collision for the list, its mods those of the runs or gaps it covers (seam 11.5).
+ private static Collision ListCollision(CollisionKind kind, OpGroup group, IReadOnlyList mods, string fingerprint)
+ {
+ return new Collision(
+ CollisionId(kind, group.Key, group.Path, mods),
+ kind,
+ group.Key,
+ group.Path,
+ mods,
+ IsBlocking(kind),
+ AllowedFor(kind),
+ fingerprint);
+ }
+
+ /// The vanilla roots of one plan, each file read once.
+ private sealed class BaseRoots
+ {
+ private readonly BaseFileSet _files;
+ private readonly Dictionary _roots = new(StringComparer.Ordinal);
+
+ public BaseRoots(BaseFileSet files)
+ {
+ _files = files;
+ }
+
+ /// Vanilla's value at one place, or null when the file, the record or the path is not there.
+ public JToken? ValueAt(RecordKey key, string path)
+ {
+ if (!_roots.TryGetValue(key.File, out JToken? root))
+ {
+ BaseFile? file = _files.Find(key.File);
+ root = file is not null && ChangeSetBuilder.TryReadBase(file, out JToken? read, out _) ? read : null;
+ _roots.Add(key.File, root);
+ }
+
+ JToken? current = root is null ? null : RecordOf(root, key);
+ foreach (PathSegment segment in MergePath.Parse(path))
+ {
+ if (current is null)
+ {
+ break;
+ }
+
+ current = segment.Name is not null
+ ? (current as JObject)?.Property(segment.Name, StringComparison.Ordinal)?.Value
+ : current is JArray array && segment.Index < array.Count ? array[segment.Index] : null;
+ }
+
+ return current;
+ }
+
+ private static JToken? RecordOf(JToken root, RecordKey key)
+ {
+ if (key.IsWholeFile)
+ {
+ return root;
+ }
+
+ JArray? records = null;
+ if (RecordKey.TryGetIndex(key.Record, out int index))
+ {
+ records = root as JArray;
+ }
+ else if (RecordKey.TryGetEvent(key.Record, out index))
+ {
+ records = (root as JObject)?.Property(RpgDataSchema.EventsProperty, StringComparison.Ordinal)?.Value as JArray;
+ }
+
+ return records is not null && index < records.Count ? records[index] : null;
+ }
+ }
+}
diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs
index 9678e74..eaea843 100644
--- a/RPGModder.Core/Merge/Composer.cs
+++ b/RPGModder.Core/Merge/Composer.cs
@@ -8,10 +8,10 @@ namespace RPGModder.Core.Merge;
///
/// Composes the change sets of every enabled mod into one plan (guide 3.4) and applies the stored choices
-/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only by the two
-/// plugin order defaults, which name profile order. Nothing is merged by text, pattern or load order (GR-C11).
+/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only where a rule
+/// names profile order, as the order defaults. Nothing is merged by text, pattern or load order (GR-C11).
///
-public static class Composer
+public static partial class Composer
{
///
/// The plan, when lane A ran : an IdClash one of its offers settles lists
@@ -61,11 +61,12 @@ public static MergePlan Compose(
var ops = new List();
var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>();
IReadOnlyList offers = remapPlan?.Offers ?? [];
+ var bases = new BaseRoots(baseFiles);
List groups = DropFiller(Group(ordered), changeSets, priorities);
groups = FoldSharedNames(DropPaddingNames(groups, systemRoot), remapPlan, priorities);
foreach (List cluster in Cluster(groups))
{
- ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics);
+ ComposeCluster(cluster, bases, choices, priorities, offers, ops, collisions, diagnostics);
}
foreach (SharedStateId shared in remapPlan?.SharedStateIds ?? [])
@@ -287,6 +288,11 @@ private static List> Cluster(IReadOnlyList groups)
return clusters;
}
+ ///
+ /// The group a group's choice is made with: a whole-file op, else the nearest ancestor path, else the group
+ /// itself. GR-K4: a map's width and height go with its whole data, since tiles a resize lays
+ /// out again are only right with the size they were laid out for.
+ ///
private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Record, string Path), OpGroup> byPlace)
{
if (byPlace.TryGetValue((group.Key.File, RecordKey.WholeFile, ""), out OpGroup? wholeFile))
@@ -294,6 +300,12 @@ private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Rec
return wholeFile;
}
+ if (RpgDataSchema.ResizedListOf(group.Key, group.Path) is string tiles &&
+ byPlace.TryGetValue((group.Key.File, group.Key.Record, tiles), out OpGroup? data))
+ {
+ return data;
+ }
+
foreach (string ancestor in MergePath.Ancestors(group.Path))
{
if (byPlace.TryGetValue((group.Key.File, group.Key.Record, ancestor), out OpGroup? found))
@@ -307,6 +319,7 @@ private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Rec
private static void ComposeCluster(
List cluster,
+ BaseRoots bases,
ILookup choices,
Dictionary priorities,
IReadOnlyList offers,
@@ -314,6 +327,11 @@ private static void ComposeCluster(
List<(Collision, CollisionOutcome)> collisions,
List diagnostics)
{
+ if (TryComposeList(cluster, bases, choices, priorities, ops, collisions, diagnostics))
+ {
+ return;
+ }
+
List mods = cluster
.SelectMany(group => group.Variants)
.SelectMany(variant => variant.ModIds)
@@ -321,7 +339,8 @@ private static void ComposeCluster(
.OrderBy(id => id, StringComparer.Ordinal)
.ToList();
- bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1;
+ // Mods that made one change together, such as two equal resizes with their tiles (GR-K4), do not clash.
+ bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1 && !MadeTogether(cluster);
if (!clash)
{
foreach (OpGroup group in cluster)
@@ -344,11 +363,12 @@ private static void ComposeCluster(
// Unresolved: the plan is not deployable and the clashing ops are described by the collision.
break;
case ResolutionKind.PickMod when cluster.Count > 1 && !IsHeadMod(cluster[0], outcome.ModId!):
- // Choosing a change inside the head keeps every inner change: only the head is dropped, and the
- // inner ops are composed again, so a clash among them becomes a collision of its own (seam 11).
- foreach (List inner in Cluster(cluster.Skip(1).ToList()))
+ // Choosing a change inside the head keeps every inner change: the head is dropped with what only its
+ // mods changed inside it, such as a resize's width and height (GR-K4), and the inner ops are composed
+ // again, so a clash among them becomes a collision of its own (seam 11).
+ foreach (List inner in Cluster(WithoutHeadMods(cluster)))
{
- ComposeCluster(inner, choices, priorities, offers, ops, collisions, diagnostics);
+ ComposeCluster(inner, bases, choices, priorities, offers, ops, collisions, diagnostics);
}
break;
@@ -367,7 +387,7 @@ private static void ComposeCluster(
break;
default:
- // Decide accepts only kinds in Allowed, and no cluster kind of 2a allows another choice.
+ // Decide accepts only kinds in Allowed, and no kind a cluster can carry allows another choice.
throw new UnreachableException($"Resolution {kind} is not applied to {collision.Kind}.");
}
}
@@ -561,6 +581,35 @@ private static bool IsHeadMod(OpGroup head, string modId)
return head.Variants.Any(variant => variant.ModIds.Contains(modId, StringComparer.Ordinal));
}
+ /// Every group holds one variant, and every variant the same mods.
+ private static bool MadeTogether(List cluster)
+ {
+ if (cluster.Any(group => group.Variants.Count != 1))
+ {
+ return false;
+ }
+
+ List first = cluster[0].Variants[0].ModIds.Order(StringComparer.Ordinal).ToList();
+ return cluster.All(group => group.Variants[0].ModIds.Order(StringComparer.Ordinal).SequenceEqual(first, StringComparer.Ordinal));
+ }
+
+ /// The inner groups of a cluster without the variants whose mods all changed the head, empty groups left out.
+ private static List WithoutHeadMods(List cluster)
+ {
+ var inner = new List();
+ foreach (OpGroup group in cluster.Skip(1))
+ {
+ var kept = new OpGroup(group.Key, group.Path);
+ kept.Variants.AddRange(group.Variants.Where(variant => !variant.ModIds.All(id => IsHeadMod(cluster[0], id))));
+ if (kept.Variants.Count > 0)
+ {
+ inner.Add(kept);
+ }
+ }
+
+ return inner;
+ }
+
private static Collision MakeCollision(List cluster, List mods)
{
OpGroup head = cluster[0];
@@ -713,7 +762,7 @@ private static bool IsApplicable(Resolution resolution, Collision collision)
(resolution.ModId is not null && collision.ModIds.Contains(resolution.ModId, StringComparer.Ordinal));
}
- /// The "Blocks deploy until resolved" column of guide 3.5, for slice 2a.
+ /// The "Blocks deploy until resolved" column of guide 3.5.
private static bool IsBlocking(CollisionKind kind)
{
return kind switch
@@ -728,7 +777,7 @@ CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous
}
///
- /// The "Allowed resolutions" column of guide 3.5 for slice 2a, in declaration order. Remap is added by
+ /// The "Allowed resolutions" column of guide 3.5, in declaration order. Remap is added by
/// (2r) and Gate comes with 2c; a SwitchBandConflict is settled by moving the band, never by a choice.
///
private static IReadOnlyList AllowedFor(CollisionKind kind)
@@ -748,7 +797,7 @@ CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.Sequ
}
///
- /// The "Default" column of guide 3.5 for slice 2a. Only the order kinds and StateIdOverlap have one; a
+ /// The "Default" column of guide 3.5. Only the order kinds and StateIdOverlap have one; a
/// BaseMismatch waits for the player to accept that mod (owner decision, 2026-11-12).
///
private static ResolutionKind? DefaultFor(CollisionKind kind)
diff --git a/RPGModder.Core/Merge/DataDiff.cs b/RPGModder.Core/Merge/DataDiff.cs
index e117481..89b542f 100644
--- a/RPGModder.Core/Merge/DataDiff.cs
+++ b/RPGModder.Core/Merge/DataDiff.cs
@@ -12,6 +12,7 @@ internal sealed class DataDiff
private readonly string _fileKey;
private readonly string? _sourceFile;
private readonly List _ops = new();
+ private bool _mapResized;
private DataDiff(string modId, string fileKey, string? sourceFile)
{
@@ -73,6 +74,7 @@ private void CompareRoot(JToken vanilla, JToken modded)
///
private void CompareMap(JObject vanilla, JObject modded)
{
+ _mapResized = RpgDataSchema.IsResized(vanilla, modded);
JToken? vanillaEvents = vanilla[RpgDataSchema.EventsProperty];
if (!RpgDataSchema.IsEventList(vanillaEvents) || modded[RpgDataSchema.EventsProperty] is not JArray moddedEvents)
{
@@ -185,7 +187,7 @@ private void CompareArray(string record, string path, JArray vanilla, JArray mod
case ArrayPolicy.Commands:
Add(record, path, ChangeKind.EditCommands, modded);
break;
- case ArrayPolicy.Positional when vanilla.Count == modded.Count:
+ case ArrayPolicy.Positional when vanilla.Count == modded.Count && !IsResizedTiles(record, path):
for (int index = 0; index < vanilla.Count; index++)
{
CompareValue(record, MergePath.Index(path, index), vanilla[index], modded[index]);
@@ -196,12 +198,18 @@ private void CompareArray(string record, string path, JArray vanilla, JArray mod
CompareKeyed(record, path, vanilla, modded);
break;
default:
- // Atomic, and a Positional array whose length changed (one value until GR-K4 in 2b).
+ // Atomic, and a Positional array whose length changed or a resized map's tiles: one value, and
+ // GR-K4 clusters the map's size with it in Compose.
Add(record, path, ChangeKind.SetLeaf, modded);
break;
}
}
+ private bool IsResizedTiles(string record, string path)
+ {
+ return _mapResized && record == RecordKey.WholeFile && RpgDataSchema.IsTilesPath(path);
+ }
+
private void CompareKeyed(string record, string path, JArray vanilla, JArray modded)
{
int count = Math.Max(vanilla.Count, modded.Count);
diff --git a/RPGModder.Core/Merge/ListMerge.cs b/RPGModder.Core/Merge/ListMerge.cs
new file mode 100644
index 0000000..b5dd1be
--- /dev/null
+++ b/RPGModder.Core/Merge/ListMerge.cs
@@ -0,0 +1,920 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The three-way merge of one list (guide 3.6): a command list as a tree (GR-T3 to GR-T7) and a Sequence list by
+/// its elements (GR-T9). Each side is compared with vanilla on its own by a longest common subsequence, and every
+/// side's changes are then laid on vanilla's items in one pass (GR-T4), never folded pair by pair.
+///
+///
+/// A change is a hunk: a run of vanilla's items one side replaces, possibly with nothing, or a gap it inserts into.
+/// Hunks of two sides overlap when they share a vanilla item, when an insert falls strictly inside the other's run,
+/// or when both insert at one gap. An insert at the edge of another side's run does not overlap it and goes on its
+/// own side of the run. Overlapping hunks form one unit, in vanilla order.
+///
+internal static class ListMerge
+{
+ ///
+ /// The cells of the comparison table one alignment may use. Past it the items between the common start and end
+ /// are one change: the alignment only gets coarser, which can add a clash, never a wrong merge.
+ ///
+ internal const long MaxCells = 4_000_000;
+
+ internal static ListMergeResult MergeCommands(
+ IReadOnlyList vanilla,
+ IReadOnlyList> sides,
+ ListPolicy policy)
+ {
+ ArgumentNullException.ThrowIfNull(vanilla);
+ ArgumentNullException.ThrowIfNull(sides);
+ ArgumentNullException.ThrowIfNull(policy);
+
+ var context = new Context(policy);
+ List merged = new Merger(new CommandRules(context), context).Merge(vanilla, sides);
+ return context.Result(CommandTree.Flatten(merged));
+ }
+
+ internal static ListMergeResult MergeSequence(
+ IReadOnlyList vanilla,
+ IReadOnlyList> sides,
+ ListPolicy policy)
+ {
+ ArgumentNullException.ThrowIfNull(vanilla);
+ ArgumentNullException.ThrowIfNull(sides);
+ ArgumentNullException.ThrowIfNull(policy);
+
+ var context = new Context(policy);
+ List merged = new Merger(new ElementRules(context), context).Merge(vanilla, sides);
+ return context.Result(new JArray(merged.Select(item => item.DeepClone())));
+ }
+
+ ///
+ /// The pairs of one longest common subsequence of and within the
+ /// given ranges, as absolute indexes in order. On a tie the left item is the one left out.
+ ///
+ internal static List<(int Left, int Right)> CommonPairs(int[] left, int leftStart, int leftEnd, int[] right, int rightStart, int rightEnd)
+ {
+ var pairs = new List<(int Left, int Right)>();
+ while (leftStart < leftEnd && rightStart < rightEnd && left[leftStart] == right[rightStart])
+ {
+ pairs.Add((leftStart, rightStart));
+ leftStart++;
+ rightStart++;
+ }
+
+ var tail = new List<(int Left, int Right)>();
+ while (leftEnd > leftStart && rightEnd > rightStart && left[leftEnd - 1] == right[rightEnd - 1])
+ {
+ leftEnd--;
+ rightEnd--;
+ tail.Add((leftEnd, rightEnd));
+ }
+
+ int rows = leftEnd - leftStart;
+ int columns = rightEnd - rightStart;
+ if (rows > 0 && columns > 0 && (long)(rows + 1) * (columns + 1) <= MaxCells)
+ {
+ // suffix[i, j] is the length for left[leftStart + i ..] and right[rightStart + j ..].
+ var suffix = new int[rows + 1, columns + 1];
+ for (int i = rows - 1; i >= 0; i--)
+ {
+ for (int j = columns - 1; j >= 0; j--)
+ {
+ suffix[i, j] = left[leftStart + i] == right[rightStart + j]
+ ? suffix[i + 1, j + 1] + 1
+ : Math.Max(suffix[i + 1, j], suffix[i, j + 1]);
+ }
+ }
+
+ int row = 0;
+ int column = 0;
+ while (row < rows && column < columns)
+ {
+ if (left[leftStart + row] == right[rightStart + column])
+ {
+ pairs.Add((leftStart + row, rightStart + column));
+ row++;
+ column++;
+ }
+ else if (suffix[row + 1, column] >= suffix[row, column + 1])
+ {
+ row++;
+ }
+ else
+ {
+ column++;
+ }
+ }
+ }
+
+ tail.Reverse();
+ pairs.AddRange(tail);
+ return pairs;
+ }
+
+ /// A copy whose object properties are in ordinal order at every depth, so equal values print alike.
+ private static JToken Sorted(JToken token)
+ {
+ return token switch
+ {
+ JObject item => new JObject(item.Properties()
+ .OrderBy(property => property.Name, StringComparer.Ordinal)
+ .Select(property => new JProperty(property.Name, Sorted(property.Value)))),
+ JArray list => new JArray(list.Select(Sorted)),
+ _ => token.DeepClone()
+ };
+ }
+
+ /// What one list merge gathers on its way, through every nested body.
+ private sealed class Context
+ {
+ private readonly Dictionary _keys = new(StringComparer.Ordinal);
+
+ public Context(ListPolicy policy)
+ {
+ Policy = policy;
+ }
+
+ public ListPolicy Policy { get; }
+
+ public SortedSet ClashMods { get; } = new(StringComparer.Ordinal);
+
+ public SortedSet OrderMods { get; } = new(StringComparer.Ordinal);
+
+ public SortedSet Contributors { get; } = new(StringComparer.Ordinal);
+
+ public JArray ClashPrint { get; } = new();
+
+ public JArray OrderPrint { get; } = new();
+
+ ///
+ /// Deep equality as a small number (GR-T3), so items compare as numbers. Property order does not count, as
+ /// for , which groups the variants of one place.
+ ///
+ public int KeyOf(JToken token)
+ {
+ string text = MergeJson.Write(Sorted(token));
+ if (!_keys.TryGetValue(text, out int key))
+ {
+ key = _keys.Count;
+ _keys.Add(text, key);
+ }
+
+ return key;
+ }
+
+ public ListMergeResult Result(JArray list)
+ {
+ return new ListMergeResult(
+ list,
+ ClashMods.ToList(),
+ OrderMods.ToList(),
+ Contributors.ToList(),
+ MergeJson.Sha256Hex(MergeJson.Write(ClashPrint)),
+ MergeJson.Sha256Hex(MergeJson.Write(OrderPrint)));
+ }
+ }
+
+ /// How the items of one kind of list compare, print and, for commands, merge inside.
+ private abstract class Rules
+ {
+ protected Rules(Context context)
+ {
+ Context = context;
+ }
+
+ protected Context Context { get; }
+
+ /// Deep equality as a number (GR-T3).
+ public abstract int Key(T item);
+
+ /// Whether two items with one head can be merged inside, so a changed item is paired by its head.
+ public virtual bool HasHeads => false;
+
+ /// The head as a number; only asked when is true.
+ public virtual int Head(T item)
+ {
+ throw new NotSupportedException();
+ }
+
+ public abstract JArray Print(IEnumerable items);
+
+ ///
+ /// The key of the item and, for a command, of every node in its bodies but the ends, each with its depth below
+ /// .
+ ///
+ public virtual IEnumerable<(int Key, int Depth)> Nested(T item, int depth)
+ {
+ yield return (Key(item), depth);
+ }
+
+ ///
+ /// The keys of the items, nested ones too, that holds fewer times at some depth than
+ /// , and those it holds more times. A node moved to another depth is in both, so a
+ /// copy put deeper never hides one taken away.
+ ///
+ public (HashSet Removed, HashSet Added) Change(IEnumerable vanilla, IEnumerable side)
+ {
+ var change = new Dictionary<(int Key, int Depth), int>();
+ foreach ((int Key, int Depth) item in vanilla.SelectMany(item => Nested(item, 0)))
+ {
+ change[item] = change.GetValueOrDefault(item) - 1;
+ }
+
+ foreach ((int Key, int Depth) item in side.SelectMany(item => Nested(item, 0)))
+ {
+ change[item] = change.GetValueOrDefault(item) + 1;
+ }
+
+ return (
+ change.Where(entry => entry.Value < 0).Select(entry => entry.Key.Key).ToHashSet(),
+ change.Where(entry => entry.Value > 0).Select(entry => entry.Key.Key).ToHashSet());
+ }
+
+ ///
+ /// GR-T6: merges the changes every side made inside one vanilla item whose head it kept. False when the
+ /// changes clash at the item itself, before anything below it was merged.
+ ///
+ public virtual bool TryMergeInside(T vanilla, IReadOnlyList<(ListSide Side, T Item)> sides, out T merged)
+ {
+ merged = vanilla;
+ return false;
+ }
+ }
+
+ private sealed class ElementRules : Rules
+ {
+ public ElementRules(Context context)
+ : base(context)
+ {
+ }
+
+ public override int Key(JToken item)
+ {
+ return Context.KeyOf(item);
+ }
+
+ public override JArray Print(IEnumerable items)
+ {
+ return new JArray(items.Select(Sorted));
+ }
+ }
+
+ private sealed class CommandRules : Rules
+ {
+ private const int Missing = -1;
+
+ private readonly Dictionary _nodeKeys = new(ReferenceEqualityComparer.Instance);
+
+ public CommandRules(Context context)
+ : base(context)
+ {
+ }
+
+ public override int Key(CommandNode item)
+ {
+ if (!_nodeKeys.TryGetValue(item, out int key))
+ {
+ key = Context.KeyOf(CommandTree.Flatten(item, 0));
+ _nodeKeys.Add(item, key);
+ }
+
+ return key;
+ }
+
+ public override bool HasHeads => true;
+
+ public override int Head(CommandNode item)
+ {
+ return Context.KeyOf(item.Head);
+ }
+
+ /// A key is the node at depth 0, so a node keeps its key at any depth and a move between bodies shows.
+ public override IEnumerable<(int Key, int Depth)> Nested(CommandNode item, int depth)
+ {
+ yield return (Key(item), depth);
+ foreach (CommandNode node in item.Branches.SelectMany(branch => branch.Body).Where(node => !CommandTree.IsEnd(node)))
+ {
+ foreach ((int Key, int Depth) inner in Nested(node, depth + 1))
+ {
+ yield return inner;
+ }
+ }
+ }
+
+ public override JArray Print(IEnumerable items)
+ {
+ return new JArray(CommandTree.Flatten(items.ToList()).Select(Sorted));
+ }
+
+ public override bool TryMergeInside(
+ CommandNode vanilla,
+ IReadOnlyList<(ListSide Side, CommandNode Item)> sides,
+ out CommandNode merged)
+ {
+ merged = vanilla;
+
+ // A side that reshaped the branches, or moved a node from one of them into another, changed the whole node,
+ // and the continuations are one value (GR-T6).
+ if (!sides.All(side => SameShape(vanilla, side.Item)) ||
+ sides.Any(side => MovedAcross(vanilla, side.Item)) ||
+ !TryPick(Lines(vanilla), sides.Select(side => Lines(side.Item)).ToList(), out int lines))
+ {
+ return false;
+ }
+
+ var markers = new List();
+ for (int index = 0; index < vanilla.Branches.Count; index++)
+ {
+ int branch = index;
+ if (!TryPick(Single(vanilla.Branches[branch].Marker), sides.Select(side => Single(side.Item.Branches[branch].Marker)).ToList(), out int marker))
+ {
+ return false;
+ }
+
+ markers.Add(marker);
+ }
+
+ if (!TryPick(Single(vanilla.End), sides.Select(side => Single(side.Item.End)).ToList(), out int end))
+ {
+ return false;
+ }
+
+ // Nothing clashes at the node itself, so its parts are taken and its bodies merged.
+ IReadOnlyList continuations = Taken(lines, sides, vanilla, item => item.Continuations, Lines);
+ var branches = new List();
+ for (int index = 0; index < vanilla.Branches.Count; index++)
+ {
+ int branch = index;
+ JObject? marker = Taken(markers[branch], sides, vanilla, item => item.Branches[branch].Marker, item => Single(item.Branches[branch].Marker));
+ List> bodies = sides
+ .Select(side => new ListSide(side.Item.Branches[branch].Body, side.Side.ModIds))
+ .ToList();
+ List body = new Merger(this, Context).Merge(vanilla.Branches[branch].Body, bodies);
+ branches.Add(new CommandBranch(marker, body));
+ }
+
+ JObject? endMarker = Taken(end, sides, vanilla, item => item.End, item => Single(item.End));
+ merged = new CommandNode(vanilla.Head, continuations, branches, endMarker);
+ return true;
+ }
+
+ ///
+ /// The side whose value of one part is taken, or when no side changed it. False when
+ /// two sides changed it in different ways.
+ ///
+ private static bool TryPick(int vanilla, List values, out int winner)
+ {
+ winner = Missing;
+ for (int index = 0; index < values.Count; index++)
+ {
+ if (values[index] == vanilla)
+ {
+ continue;
+ }
+
+ if (winner != Missing && values[winner] != values[index])
+ {
+ return false;
+ }
+
+ if (winner == Missing)
+ {
+ winner = index;
+ }
+ }
+
+ return true;
+ }
+
+ private TPart Taken(
+ int winner,
+ IReadOnlyList<(ListSide Side, CommandNode Item)> sides,
+ CommandNode vanilla,
+ Func part,
+ Func key)
+ {
+ if (winner == Missing)
+ {
+ return part(vanilla);
+ }
+
+ Contribute(winner, sides, key);
+ return part(sides[winner].Item);
+ }
+
+ /// Every side that holds the winning value contributed it.
+ private void Contribute(int winner, IReadOnlyList<(ListSide Side, CommandNode Item)> sides, Func key)
+ {
+ if (winner == Missing)
+ {
+ return;
+ }
+
+ int value = key(sides[winner].Item);
+ foreach ((ListSide side, CommandNode item) in sides)
+ {
+ if (key(item) == value)
+ {
+ Context.Contributors.UnionWith(side.ModIds);
+ }
+ }
+ }
+
+ private static bool SameShape(CommandNode vanilla, CommandNode side)
+ {
+ if (side.Branches.Count != vanilla.Branches.Count || (side.End is null) != (vanilla.End is null))
+ {
+ return false;
+ }
+
+ for (int index = 0; index < vanilla.Branches.Count; index++)
+ {
+ if (!JToken.DeepEquals(MarkerCode(vanilla.Branches[index].Marker), MarkerCode(side.Branches[index].Marker)))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// A node, at any depth, the side removed from one branch and added to another. Asked of one shape only.
+ private bool MovedAcross(CommandNode vanilla, CommandNode side)
+ {
+ List<(HashSet Removed, HashSet Added)> changes = Enumerable.Range(0, vanilla.Branches.Count)
+ .Select(index => Change(vanilla.Branches[index].Body, side.Branches[index].Body))
+ .ToList();
+ for (int from = 0; from < changes.Count; from++)
+ {
+ for (int to = 0; to < changes.Count; to++)
+ {
+ if (from != to && changes[from].Removed.Overlaps(changes[to].Added))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private static JToken? MarkerCode(JObject? marker)
+ {
+ return marker?.Property("code", StringComparison.Ordinal)?.Value;
+ }
+
+ private int Lines(CommandNode node)
+ {
+ return Context.KeyOf(new JArray(node.Continuations));
+ }
+
+ private int Single(JObject? command)
+ {
+ return command is null ? Missing : Context.KeyOf(command);
+ }
+ }
+
+ /// A run of vanilla items one side replaces, or a gap it inserts into when Start equals End.
+ private readonly record struct Hunk(int Side, int Start, int End, int SideStart, int SideEnd, bool Inside);
+
+ private sealed record Unit(List Hunks, int Start, int End);
+
+ private sealed class Merger
+ {
+ private readonly Rules _rules;
+ private readonly Context _context;
+
+ public Merger(Rules rules, Context context)
+ {
+ _rules = rules;
+ _context = context;
+ }
+
+ public List Merge(IReadOnlyList vanilla, IReadOnlyList> sides)
+ {
+ int[] vanillaKeys = vanilla.Select(_rules.Key).ToArray();
+ int[]? vanillaHeads = Heads(vanilla);
+ var hunks = new List();
+ for (int side = 0; side < sides.Count; side++)
+ {
+ hunks.AddRange(Diff(side, vanilla, vanillaKeys, vanillaHeads, sides[side].Items));
+ }
+
+ var merged = new List();
+ int position = 0;
+ foreach (Unit unit in Units(hunks))
+ {
+ for (; position < unit.Start; position++)
+ {
+ merged.Add(vanilla[position]);
+ }
+
+ merged.AddRange(Resolve(unit, vanilla, sides));
+ position = unit.End;
+ }
+
+ for (; position < vanilla.Count; position++)
+ {
+ merged.Add(vanilla[position]);
+ }
+
+ return merged;
+ }
+
+ private int[]? Heads(IReadOnlyList items)
+ {
+ return _rules.HasHeads ? items.Select(_rules.Head).ToArray() : null;
+ }
+
+ ///
+ /// One side's hunks. Within each run the common subsequence left unmatched, items with one head are paired
+ /// again, so a changed node is a change of its own and not part of a larger run (GR-T3).
+ ///
+ private List Diff(int side, IReadOnlyList vanilla, int[] vanillaKeys, int[]? vanillaHeads, IReadOnlyList items)
+ {
+ int[] keys = items.Select(_rules.Key).ToArray();
+ int[]? heads = Heads(items);
+ var hunks = new List();
+ int vanillaAt = 0;
+ int sideAt = 0;
+ foreach ((int left, int right) in CommonPairs(vanillaKeys, 0, vanillaKeys.Length, keys, 0, keys.Length).Append((vanillaKeys.Length, keys.Length)))
+ {
+ if (left > vanillaAt || right > sideAt)
+ {
+ Region(side, vanillaAt, left, sideAt, right, vanillaHeads, heads, hunks);
+ }
+
+ vanillaAt = left + 1;
+ sideAt = right + 1;
+ }
+
+ return JoinMoves(hunks, vanilla, items);
+ }
+
+ private static void Region(int side, int start, int end, int sideStart, int sideEnd, int[]? vanillaHeads, int[]? heads, List hunks)
+ {
+ if (vanillaHeads is null || heads is null)
+ {
+ hunks.Add(new Hunk(side, start, end, sideStart, sideEnd, false));
+ return;
+ }
+
+ // A head pairs a changed node only when it names one node of the run on each side. Two nodes of one head,
+ // as two Show Text with one face, would be paired by a guess, so such a run stays one change.
+ var counts = new Dictionary();
+ for (int index = start; index < end; index++)
+ {
+ (int Vanilla, int Side) count = counts.GetValueOrDefault(vanillaHeads[index]);
+ counts[vanillaHeads[index]] = (count.Vanilla + 1, count.Side);
+ }
+
+ for (int index = sideStart; index < sideEnd; index++)
+ {
+ (int Vanilla, int Side) count = counts.GetValueOrDefault(heads[index]);
+ counts[heads[index]] = (count.Vanilla, count.Side + 1);
+ }
+
+ // A repeated head becomes a negative number of its own, odd for vanilla and even for the side, so it pairs nothing.
+ int[] left = Enumerable.Range(start, end - start)
+ .Select(index => Pairable(counts[vanillaHeads[index]]) ? vanillaHeads[index] : -1 - (2 * index))
+ .ToArray();
+ int[] right = Enumerable.Range(sideStart, sideEnd - sideStart)
+ .Select(index => Pairable(counts[heads[index]]) ? heads[index] : -2 - (2 * index))
+ .ToArray();
+
+ int vanillaAt = start;
+ int sideAt = sideStart;
+ foreach ((int pairLeft, int pairRight) in CommonPairs(left, 0, left.Length, right, 0, right.Length))
+ {
+ int at = start + pairLeft;
+ int sideOf = sideStart + pairRight;
+ if (at > vanillaAt || sideOf > sideAt)
+ {
+ hunks.Add(new Hunk(side, vanillaAt, at, sideAt, sideOf, false));
+ }
+
+ hunks.Add(new Hunk(side, at, at + 1, sideOf, sideOf + 1, true));
+ vanillaAt = at + 1;
+ sideAt = sideOf + 1;
+ }
+
+ if (end > vanillaAt || sideEnd > sideAt)
+ {
+ hunks.Add(new Hunk(side, vanillaAt, end, sideAt, sideEnd, false));
+ }
+ }
+
+ private static bool Pairable((int Vanilla, int Side) count)
+ {
+ return count.Vanilla <= 1 && count.Side <= 1;
+ }
+
+ ///
+ /// A side that removes an item and puts an equal one elsewhere moved it. Every hunk from the one place to the
+ /// other becomes one run, so the move clashes with what another side did in between, and never half applies.
+ /// A node changed in place into a copy of one the side removed counts too: its head paired it, but it moved. So
+ /// does a node moved into or out of another one's body, at any depth: the run reaches the node that holds it.
+ ///
+ private List JoinMoves(List hunks, IReadOnlyList vanilla, IReadOnlyList items)
+ {
+ var removed = new Dictionary();
+ var added = new Dictionary();
+ for (int index = 0; index < hunks.Count; index++)
+ {
+ Hunk hunk = hunks[index];
+ (HashSet gone, HashSet put) = _rules.Change(Slice(vanilla, hunk.Start, hunk.End), Slice(items, hunk.SideStart, hunk.SideEnd));
+ foreach (int key in gone)
+ {
+ removed[key] = Widen(removed, key, index);
+ }
+
+ foreach (int key in put)
+ {
+ added[key] = Widen(added, key, index);
+ }
+ }
+
+ List<(int First, int Last)> spans = removed
+ .Where(entry => added.ContainsKey(entry.Key))
+ .Select(entry => (First: Math.Min(entry.Value.First, added[entry.Key].First), Last: Math.Max(entry.Value.Last, added[entry.Key].Last)))
+ .Where(span => span.First < span.Last)
+ .OrderBy(span => span.First)
+ .ToList();
+ if (spans.Count == 0)
+ {
+ return hunks;
+ }
+
+ var joined = new List();
+ int next = 0;
+ int spanAt = 0;
+ while (next < hunks.Count)
+ {
+ if (spanAt < spans.Count && spans[spanAt].First == next)
+ {
+ int last = spans[spanAt].Last;
+ for (spanAt++; spanAt < spans.Count && spans[spanAt].First <= last; spanAt++)
+ {
+ last = Math.Max(last, spans[spanAt].Last);
+ }
+
+ joined.Add(hunks[next] with { End = hunks[last].End, SideEnd = hunks[last].SideEnd, Inside = false });
+ next = last + 1;
+ }
+ else
+ {
+ joined.Add(hunks[next++]);
+ }
+ }
+
+ return joined;
+ }
+
+ private static (int First, int Last) Widen(Dictionary places, int key, int index)
+ {
+ return places.TryGetValue(key, out (int First, int Last) place) ? (Math.Min(place.First, index), Math.Max(place.Last, index)) : (index, index);
+ }
+
+ /// The hunks joined by overlap, as units in vanilla order; an insert unit comes before a run that starts at its gap.
+ private static List Units(List hunks)
+ {
+ List order = Enumerable.Range(0, hunks.Count)
+ .OrderBy(index => hunks[index].Start)
+ .ThenBy(index => hunks[index].End)
+ .ThenBy(index => hunks[index].Side)
+ .ToList();
+ int[] parent = Enumerable.Range(0, hunks.Count).ToArray();
+
+ int Find(int index)
+ {
+ while (parent[index] != index)
+ {
+ parent[index] = parent[parent[index]];
+ index = parent[index];
+ }
+
+ return index;
+ }
+
+ for (int first = 0; first < order.Count; first++)
+ {
+ Hunk left = hunks[order[first]];
+ for (int second = first + 1; second < order.Count && hunks[order[second]].Start <= left.End; second++)
+ {
+ Hunk right = hunks[order[second]];
+ if (left.Side != right.Side && Overlap(left, right))
+ {
+ parent[Find(order[second])] = Find(order[first]);
+ }
+ }
+ }
+
+ return order
+ .GroupBy(Find)
+ .Select(group => group.Select(index => hunks[index]).ToList())
+ .Select(members => new Unit(members, members.Min(hunk => hunk.Start), members.Max(hunk => hunk.End)))
+ .OrderBy(unit => unit.Start)
+ .ThenBy(unit => unit.End)
+ .ToList();
+ }
+
+ private static bool Overlap(Hunk left, Hunk right)
+ {
+ bool leftGap = left.Start == left.End;
+ bool rightGap = right.Start == right.End;
+ if (leftGap && rightGap)
+ {
+ return left.Start == right.Start;
+ }
+
+ if (leftGap)
+ {
+ return right.Start < left.Start && left.Start < right.End;
+ }
+
+ if (rightGap)
+ {
+ return left.Start < right.Start && right.Start < left.End;
+ }
+
+ return left.Start < right.End && right.Start < left.End;
+ }
+
+ private List Resolve(Unit unit, IReadOnlyList vanilla, IReadOnlyList> sides)
+ {
+ List versions = Versions(unit, vanilla, sides);
+ if (unit.Start == unit.End)
+ {
+ versions = Folded(versions);
+ }
+
+ if (versions.Count == 1)
+ {
+ // GR-T5: one side changed this run, or several changed it the same way.
+ Contribute(versions[0], sides);
+ return versions[0].Items;
+ }
+
+ if (unit.Start == unit.End)
+ {
+ return Ordered(versions, sides);
+ }
+
+ if (unit.Hunks.All(hunk => hunk.Inside && hunk.Start == unit.Start) &&
+ _rules.TryMergeInside(vanilla[unit.Start], unit.Hunks.Select(hunk => (sides[hunk.Side], sides[hunk.Side].Items[hunk.SideStart])).ToList(), out T merged))
+ {
+ return [merged];
+ }
+
+ return Clash(unit, vanilla, versions, sides);
+ }
+
+ ///
+ /// Inserts at one gap that another side's inserts there hold in order: that side's longer run is taken once,
+ /// with the mods of both, so a shared part is never doubled.
+ ///
+ private static List Folded(List versions)
+ {
+ List longest = versions
+ .Where(version => !versions.Any(other => other != version && Within(version.Keys, other.Keys)))
+ .ToList();
+ foreach (Version version in versions.Except(longest))
+ {
+ foreach (Version holder in longest.Where(item => Within(version.Keys, item.Keys)))
+ {
+ holder.Sides.AddRange(version.Sides);
+ }
+ }
+
+ return longest;
+ }
+
+ /// Whether is a subsequence of .
+ private static bool Within(int[] part, int[] whole)
+ {
+ int at = 0;
+ foreach (int key in whole)
+ {
+ if (at < part.Length && part[at] == key)
+ {
+ at++;
+ }
+ }
+
+ return at == part.Length;
+ }
+
+ /// GR-T7: inserts at one gap, distinct ones in profile order, or the chosen mod's first.
+ private List Ordered(List versions, IReadOnlyList> sides)
+ {
+ string? first = _context.Policy.FirstMod;
+ var print = new JArray();
+ var items = new List();
+ foreach (Version version in versions
+ .OrderBy(item => first is not null && item.Sides.Any(side => sides[side].ModIds.Contains(first, StringComparer.Ordinal)) ? 0 : 1)
+ .ThenBy(item => item.Sides.Min()))
+ {
+ Contribute(version, sides);
+ _context.OrderMods.UnionWith(Mods(version, sides));
+ items.AddRange(version.Items);
+ }
+
+ foreach (Version version in ByMods(versions, sides))
+ {
+ print.Add(new JArray(new JArray(Mods(version, sides).ToArray