diff --git a/RPGModder.Core/Merge/AddedIdIndex.cs b/RPGModder.Core/Merge/AddedIdIndex.cs index 7c52c94..cf62088 100644 --- a/RPGModder.Core/Merge/AddedIdIndex.cs +++ b/RPGModder.Core/Merge/AddedIdIndex.cs @@ -5,14 +5,17 @@ namespace RPGModder.Core.Merge; /// /// The ids a change set adds, by kind and scope (GR-R2, GR-R3). An op the builder writes for a record vanilla does /// not have is the only kind of added id: a map event is an AddRecord on event:n of a vanilla map; a -/// map is a whole new MapNNN.json, its MapInfos record, or both. Step 1 lists these two kinds only. +/// map is a whole new MapNNN.json, its MapInfos record, or both; a database record is an +/// AddRecord on id:n of its file. /// internal static class AddedIdIndex { public static IReadOnlyList Of(ModChangeSet changeSet) { var events = new List(); + var records = new List(); var maps = new SortedDictionary(); + var filler = new FillerTest(changeSet); foreach (ChangeOp op in changeSet.Ops) { if (op.Kind != ChangeKind.AddRecord || op.Path.Length != 0 || op.Value is null) @@ -32,9 +35,14 @@ public static IReadOnlyList Of(ModChangeSet changeSet) { events.Add(new AddedId(IdKind.MapEvent, op.Key.File, eventId, op.Value)); } + else if (RpgDataSchema.DatabaseKindOf(op.Key.File) is { } kind && RecordKey.TryGetIndex(op.Key.Record, out int recordId) && recordId > 0) + { + records.Add(new AddedId(kind, "", recordId, op.Value, filler.IsFiller(op.Key, op.Value))); + } } var result = new List(events); + result.AddRange(records); foreach ((int id, (JToken? file, JToken? info)) in maps) { // Both halves are the content, cloned so no op gains a parent; two mods that add one map with one tree entry are one map (GR-R3). @@ -44,12 +52,18 @@ public static IReadOnlyList Of(ModChangeSet changeSet) return result; } - /// True when the change set still adds 's old id; otherwise the entry is inactive (GR-R12). + /// + /// True when the change set still adds 's old id, and not as filler; otherwise the entry + /// is inactive (GR-R12, GR-R7). + /// public static bool IsActive(IdRemap remap, IReadOnlyList added) { - return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId); + return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId && !item.IsFiller); } } -/// One added id and the content that decides whether two mods add the same thing. -internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content); +/// +/// One added id and the content that decides whether two mods add the same thing. Filler (GR-R7) holds its id but +/// never claims it. +/// +internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content, bool IsFiller = false); diff --git a/RPGModder.Core/Merge/BlankRecords.cs b/RPGModder.Core/Merge/BlankRecords.cs new file mode 100644 index 0000000..4288038 --- /dev/null +++ b/RPGModder.Core/Merge/BlankRecords.cs @@ -0,0 +1,142 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Services; + +namespace RPGModder.Core.Merge; + +/// +/// The record the editor writes when a database maximum is raised (GR-R8), with id 0. The MZ shapes are the +/// records the MZ 1.10.0 editor wrote into a default project; the MV shapes are the MZ ones without the fields MV's +/// data format (json_docs.js in the MV core script) does not list, and MV's own animation fields. An unknown +/// engine gets the MV shapes, which both engines read. +/// +internal static class BlankRecords +{ + /// A field of skills and states only the MZ editor writes; the game never reads it. + private const string MessageTypeProperty = "messageType"; + + private const string ParamsProperty = "params"; + + private static readonly Dictionary MzShapes = new(StringComparer.Ordinal) + { + ["actors.json"] = + """{"id":0,"battlerName":"","characterIndex":0,"characterName":"","classId":1,"equips":[0,0,0,0,0],"faceIndex":0,"faceName":"","traits":[],"initialLevel":1,"maxLevel":99,"name":"","nickname":"","note":"","profile":""}""", + ["classes.json"] = + """{"id":0,"expParams":[30,20,30,30],"traits":[{"code":23,"dataId":0,"value":1},{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":22,"dataId":2,"value":0.04},{"code":41,"dataId":1,"value":0},{"code":51,"dataId":1,"value":0},{"code":52,"dataId":1,"value":0}],"learnings":[],"name":"","note":"","params":[]}""", + ["skills.json"] = + """{"id":0,"animationId":0,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"message1":"","message2":"","mpCost":0,"name":"","note":"","occasion":0,"repeats":1,"requiredWtypeId1":0,"requiredWtypeId2":0,"scope":1,"speed":0,"stypeId":1,"successRate":100,"tpCost":0,"tpGain":0,"messageType":1}""", + ["items.json"] = + """{"id":0,"animationId":0,"consumable":true,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"itypeId":1,"name":"","note":"","occasion":0,"price":0,"repeats":1,"scope":7,"speed":0,"successRate":100,"tpGain":0}""", + ["weapons.json"] = + """{"id":0,"animationId":0,"description":"","etypeId":1,"traits":[{"code":31,"dataId":1,"value":0},{"code":22,"dataId":0,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0,"wtypeId":0}""", + ["armors.json"] = + """{"id":0,"atypeId":0,"description":"","etypeId":2,"traits":[{"code":22,"dataId":1,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0}""", + ["enemies.json"] = + """{"id":0,"actions":[{"conditionParam1":0,"conditionParam2":0,"conditionType":0,"rating":5,"skillId":1}],"battlerHue":0,"battlerName":"","dropItems":[{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0}],"exp":0,"traits":[{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":31,"dataId":1,"value":0}],"gold":0,"name":"","note":"","params":[100,0,10,10,10,10,10,10]}""", + ["troops.json"] = + """{"id":0,"members":[],"name":"","pages":[{"conditions":{"actorHp":50,"actorId":1,"actorValid":false,"enemyHp":50,"enemyIndex":0,"enemyValid":false,"switchId":1,"switchValid":false,"turnA":0,"turnB":0,"turnEnding":false,"turnValid":false},"list":[{"code":0,"indent":0,"parameters":[]}],"span":0}]}""", + ["states.json"] = + """{"id":0,"autoRemovalTiming":0,"chanceByDamage":100,"iconIndex":0,"maxTurns":1,"message1":"","message2":"","message3":"","message4":"","minTurns":1,"motion":0,"name":"","note":"","overlay":0,"priority":50,"removeAtBattleEnd":false,"removeByDamage":false,"removeByRestriction":false,"removeByWalking":false,"restriction":0,"stepsToRemove":100,"traits":[],"messageType":1}""", + ["animations.json"] = + """{"id":0,"displayType":0,"effectName":"","flashTimings":[],"name":"","offsetX":0,"offsetY":0,"rotation":{"x":0,"y":0,"z":0},"scale":100,"soundTimings":[],"speed":100,"alignBottom":false}""", + ["tilesets.json"] = + """{"id":0,"flags":[16],"mode":1,"name":"","note":"","tilesetNames":["","","","","","","","",""]}""", + ["commonevents.json"] = + """{"id":0,"list":[{"code":0,"indent":0,"parameters":[]}],"name":"","switchId":1,"trigger":0}""" + }; + + /// + /// The MV animation format: two sprite sheets, a frame list and timings. One empty frame, so the game can play + /// the blank without reading past the list; position 1 is the center. Not pinned against an MV editor. + /// + private const string MvAnimation = + """{"id":0,"animation1Hue":0,"animation1Name":"","animation2Hue":0,"animation2Name":"","frames":[[]],"name":"","position":1,"timings":[]}"""; + + /// The eight parameter curves of a blank class, levels 0 to 99, as the MZ editor writes them. + private static readonly int[][] ClassCurves = + [ + [ + 1, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, + 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000, 2050, 2100, 2150, 2200, 2250, 2300, 2350, + 2400, 2450, 2500, 2550, 2600, 2650, 2700, 2750, 2800, 2850, 2900, 2950, 3000, 3050, 3100, 3150, 3200, 3250, 3300, 3350, + 3400, 3450, 3500, 3550, 3600, 3650, 3700, 3750, 3800, 3850, 3900, 3950, 4000, 4050, 4100, 4150, 4200, 4250, 4300, 4350, + 4400, 4450, 4500, 4550, 4600, 4650, 4700, 4750, 4800, 4850, 4900, 4950, 5000, 5050, 5100, 5150, 5200, 5250, 5300, 5350 + ], + [ + 0, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, + 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, + 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, + 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870, + 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990, 1000, 1010, 1020, 1030, 1040, 1050, 1060, 1070 + ], + [ + 1, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, + 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, + 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89, + 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114, + 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138 + ], + [ + 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, + 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, + 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89, + 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114, + 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138 + ], + [ + 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, + 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, + 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89, + 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114, + 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138 + ], + [ + 0, 16, 18, 19, 20, 21, 23, 24, 25, 26, 28, 29, 30, 31, 33, 34, 35, 36, 38, 39, + 40, 41, 43, 44, 45, 46, 48, 49, 50, 51, 53, 54, 55, 56, 58, 59, 60, 61, 63, 64, + 65, 66, 68, 69, 70, 71, 73, 74, 75, 76, 77, 79, 80, 81, 82, 84, 85, 86, 87, 89, + 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 102, 104, 105, 106, 107, 109, 110, 111, 112, 114, + 115, 116, 117, 119, 120, 121, 122, 124, 125, 126, 127, 129, 130, 131, 132, 134, 135, 136, 137, 138 + ], + [ + 0, 32, 35, 37, 40, 42, 45, 47, 50, 52, 55, 57, 60, 62, 65, 67, 70, 72, 75, 77, + 80, 82, 85, 87, 90, 92, 95, 97, 100, 102, 105, 107, 110, 112, 115, 117, 120, 122, 125, 127, + 130, 132, 135, 137, 140, 142, 145, 147, 150, 152, 155, 157, 160, 162, 165, 167, 170, 172, 175, 177, + 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227, + 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 275, 277 + ], + [ + 0, 32, 35, 37, 40, 42, 45, 47, 50, 52, 55, 57, 60, 62, 65, 67, 70, 72, 75, 77, + 80, 82, 85, 87, 90, 92, 95, 97, 100, 102, 105, 107, 110, 112, 115, 117, 120, 122, 125, 127, + 130, 132, 135, 137, 140, 142, 145, 147, 150, 152, 155, 157, 160, 162, 165, 167, 170, 172, 175, 177, + 180, 182, 185, 187, 190, 192, 195, 197, 200, 202, 205, 207, 210, 212, 215, 217, 220, 222, 225, 227, + 230, 232, 235, 237, 240, 242, 245, 247, 250, 252, 255, 257, 260, 262, 265, 267, 270, 272, 275, 277 + ] + ]; + + /// A new copy of the blank record of , or null for a file that is not a database file. + public static JObject? For(string fileName, RpgMakerEngine? engine) + { + if (!MzShapes.TryGetValue(fileName, out string? text)) + { + return null; + } + + bool mz = engine == RpgMakerEngine.MZ; + if (!mz && fileName == "animations.json") + { + return JObject.Parse(MvAnimation); + } + + var record = JObject.Parse(text); + if (fileName == "classes.json") + { + record[ParamsProperty] = new JArray(ClassCurves.Select(curve => new JArray(curve))); + } + + if (!mz) + { + record.Remove(MessageTypeProperty); + } + + return record; + } +} diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs index 4039bcd..8cccf1b 100644 --- a/RPGModder.Core/Merge/Composer.cs +++ b/RPGModder.Core/Merge/Composer.cs @@ -59,7 +59,7 @@ public static MergePlan Compose( var ops = new List(); var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>(); IReadOnlyList offers = remapPlan?.Offers ?? []; - foreach (List cluster in Cluster(Group(ordered))) + foreach (List cluster in Cluster(DropFiller(Group(ordered), changeSets, priorities))) { ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics); } @@ -112,6 +112,32 @@ private static List Group(List ordered) return groups.Values.ToList(); } + /// + /// GR-R7: filler yields to a real record at the same id and never forms an IdClash. Where every variant + /// adds a database record, the filler variants drop when a real one is there; when none is, only the variant of + /// the mod latest in profile order stays. + /// + private static List DropFiller(List groups, IReadOnlyList changeSets, Dictionary priorities) + { + Dictionary fillers = changeSets.ToDictionary(set => set.ModId, set => new FillerTest(set), StringComparer.Ordinal); + foreach (OpGroup group in groups) + { + if (group.Path.Length != 0 || + group.Variants.Count < 2 || + RpgDataSchema.DatabaseKindOf(group.Key.File) is null || + group.Variants.Any(variant => variant.Op.Kind != ChangeKind.AddRecord)) + { + continue; + } + + List real = group.Variants.Where(variant => !fillers[variant.Op.ModId].IsFiller(group.Key, variant.Op.Value)).ToList(); + List kept = real.Count > 0 ? real : [LatestInProfileOrder(group, priorities)]; + group.Variants.RemoveAll(variant => !kept.Contains(variant)); + } + + return groups; + } + /// /// GR-C2: a group joins the outermost group whose place contains it: a whole-file value, else the shortest /// ancestor path in the same record. The head comes first in each cluster, the rest follow in place order. diff --git a/RPGModder.Core/Merge/FillerTest.cs b/RPGModder.Core/Merge/FillerTest.cs new file mode 100644 index 0000000..b8247dc --- /dev/null +++ b/RPGModder.Core/Merge/FillerTest.cs @@ -0,0 +1,34 @@ +using Newtonsoft.Json.Linq; + +namespace RPGModder.Core.Merge; + +/// +/// GR-R7: an added database record is filler when it has the shape of an editor blank +/// () and its own mod names its id nowhere: no event command, record field, +/// text code, free text or plugin text code. A blank the mod fills while the game runs (an actor named by 303 or +/// drawn by 322) is a real record. The mod's references are read once, at its first blank-shaped record. +/// +internal sealed class FillerTest +{ + private readonly ModChangeSet _changeSet; + private ModReferences? _references; + + public FillerTest(ModChangeSet changeSet) + { + _changeSet = changeSet; + } + + public bool IsFiller(RecordKey key, JToken? record) + { + if (RpgDataSchema.DatabaseKindOf(key.File) is not { } kind || + !RecordKey.TryGetIndex(key.Record, out int id) || + !RpgDataSchema.HasBlankShape(key.File, record)) + { + return false; + } + + // Read as a dual-wield game on no known engine, so an id of either possible kind counts as used. + _references ??= ReferenceMap.Scan(_changeSet, [], dualWield: true, mz: false); + return !_references.Uses(kind, id); + } +} diff --git a/RPGModder.Core/Merge/IdRemapPlanner.cs b/RPGModder.Core/Merge/IdRemapPlanner.cs index 8faae1b..e6d92ef 100644 --- a/RPGModder.Core/Merge/IdRemapPlanner.cs +++ b/RPGModder.Core/Merge/IdRemapPlanner.cs @@ -2,28 +2,37 @@ using RPGModder.Core.Models; using RPGModder.Core.Operations; using RPGModder.Core.Services; +using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace RPGModder.Core.Merge; /// -/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12). Step 1 plans the -/// and kinds. The result does not depend on the order of any -/// input. +/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12): map events, maps and the twelve +/// database kinds. The result does not depend on the order of any input. /// public static class IdRemapPlanner { + /// Trait 55, Slot Type, whose data 1 is Dual Wield (MV and MZ Game_Actor.prototype.isDualWield). + private const int SlotTypeTrait = 55; + + private const int DualWieldSlot = 1; + private const string TraitCode = "code"; + private const string TraitData = "dataId"; + /// Every installed mod, enabled or not, once each. /// The profile's Remaps, every entry, active or not. /// The profile's DeployedMods (GR-R4). /// /// Vanilla's files, for the ids vanilla uses (GR-R5): the map file of every map that gets an event, and, when a - /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not. A clash whose - /// base file is missing cannot move, and a map id whose file vanilla has is never a target and never moves. + /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not; the database + /// file of every kind a mod adds a record to; and, to tell a dual-wield game (trait 55, data 1), the actors, + /// classes, weapons, armors and states. A clash whose base file is missing cannot move, a map id whose file + /// vanilla has is never a target and never moves, and a missing dual-wield file counts as dual wield. /// /// - /// The game's engine, which sets the highest map id a move may give (GR-R6): 2000 for MZ, 999 for MV and for an - /// unknown engine (null). + /// The game's engine, which sets the highest id a move may give (GR-R6): maps 2000 on MZ and 999 otherwise, + /// database records 9999 on MZ and 999 otherwise, events 999. An unknown engine (null) gets MV's limits. /// public static RemapPlan Plan( IReadOnlyList installed, @@ -55,7 +64,7 @@ public static RemapPlan Plan( foreach (RemapMod mod in mods.Where(item => item.Enabled)) { string modId = mod.ChangeSet.ModId; - foreach (AddedId id in added[modId]) + foreach (AddedId id in added[modId].Where(item => !item.IsFiller)) { bool pinned = pins.TryGetValue((modId, id.Kind, id.Scope, id.Id), out int toId); claims.Add(new Claim(mod, id, pinned ? toId : id.Id, pinned, deployed.Contains(modId))); @@ -64,6 +73,8 @@ public static RemapPlan Plan( var targets = new Targets(added.Values.SelectMany(list => list).ToList(), recorded, baseFiles, engine); var references = new Dictionary(StringComparer.Ordinal); + var dualWield = new Lazy(() => IsDualWield(mods, baseFiles)); + StaleReferences(mods, pins, mod => ReferencesOf(mod, dualWield, engine, references), diagnostics); var moves = new List(); var offers = new List(); IEnumerable> groups = claims @@ -82,7 +93,7 @@ public static RemapPlan Plan( (IdKind kind, string scope, _) = group.Key; foreach (Party party in parties) { - party.Classify(kind, claim => ReferencesOf(claim.Mod, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles)); + party.Classify(kind, claim => ReferencesOf(claim.Mod, dualWield, engine, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles)); } // GR-R4 and GR-R10: the parties that cannot move stay; when every party can, the first in order stays. @@ -154,7 +165,7 @@ public static RemapPlan Plan( foreach (IdRemap remap in Sorted(recorded)) { (string ModId, IdKind Kind, string Scope, int FromId) from = (remap.ModId, remap.Kind, remap.Scope, remap.FromId); - if (remap.Kind is not (IdKind.MapEvent or IdKind.Map) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) || + if (!RpgDataSchema.IsRemappable(remap.Kind) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) || !AddedIdIndex.IsActive(remap, added[remap.ModId]) || pins.ContainsKey(from) || !targets.Add((remap.ModId, remap.Kind, remap.Scope, remap.ToId))) { @@ -187,7 +198,38 @@ public static RemapPlan Plan( return pins; } - /// True when vanilla has a record at : a map file or tree record, or a map's event. + /// + /// GR-R12 over GR-R9 (the owner, 2026-11-12): an entry in force still applies when its mod now names the old id + /// where a move cannot follow it (a mod update), since saves already hold the new id. The plan says so with + /// rules.remap_stale_reference, one per entry, in the order of . + /// + private static void StaleReferences( + List mods, + Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins, + Func referencesOf, + List diagnostics) + { + IEnumerable standing = pins.Select(pin => new IdRemap(pin.Key.ModId, pin.Key.Kind, pin.Key.Scope, pin.Key.FromId, pin.Value)); + foreach (IdRemap remap in Sorted(standing)) + { + RemapMod mod = mods.First(item => item.ChangeSet.ModId == remap.ModId); + if (!referencesOf(mod).Blocks(remap.Kind, remap.FromId)) + { + continue; + } + + string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : ""; + diagnostics.Add(new OperationDiagnostic( + DiagnosticCodes.RulesRemapStaleReference, + string.Create( + CultureInfo.InvariantCulture, + $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} was recorded as moved to {remap.ToId}, but the mod now names {remap.FromId} where a move cannot follow it (a script, a note, a formula, a plugin's text code or a value of unclear kind). The entry still applies, so saves keep the record, but that place still reads {remap.FromId}."), + DiagnosticSeverity.Warning, + remap.ModId)); + } + } + + /// True when vanilla has a record at : a map file or tree record, a map's event, a database record. private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet baseFiles) { if (kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null) @@ -198,17 +240,60 @@ private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet b return VanillaList(kind, scope, baseFiles) is JArray list && id < list.Count && list[id].Type != JTokenType.Null; } - /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events. + /// + /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events, the + /// database file for a database kind. + /// private static JArray? VanillaList(IdKind kind, string scope, BaseFileSet baseFiles) { - string file = kind == IdKind.Map ? RpgDataSchema.MapInfosKey : scope; - BaseFile? baseFile = baseFiles.Find(file); - if (baseFile is null || !ChangeSetBuilder.TryReadBase(baseFile, out JToken? root, out _)) + string? file = kind switch + { + IdKind.Map => RpgDataSchema.MapInfosKey, + IdKind.MapEvent => scope, + _ => RpgDataSchema.DatabaseFileOf(kind) + }; + if (file is null || !TryReadBase(baseFiles, file, out JToken? root)) { return null; } - return (kind == IdKind.Map ? root : (root as JObject)?[RpgDataSchema.EventsProperty]) as JArray; + return (kind == IdKind.MapEvent ? (root as JObject)?[RpgDataSchema.EventsProperty] : root) as JArray; + } + + /// + /// True when an actor may wield two weapons, so the second equip slot may hold a weapon: a trait 55 with data 1 + /// in vanilla's or an enabled mod's actors, classes, weapons, armors or states. A file vanilla lacks or that cannot + /// be read counts as dual wield, the side on which fewer ids move. + /// + private static bool IsDualWield(List mods, BaseFileSet baseFiles) + { + IdKind[] kinds = [IdKind.Actor, IdKind.Class, IdKind.Weapon, IdKind.Armor, IdKind.State]; + var files = new HashSet(kinds.Select(kind => RpgDataSchema.DatabaseFileOf(kind)!), StringComparer.Ordinal); + foreach (string file in files) + { + if (!TryReadBase(baseFiles, file, out JToken? root) || HasDualWield(root)) + { + return true; + } + } + + return mods.Where(mod => mod.Enabled) + .SelectMany(mod => mod.ChangeSet.Ops) + .Any(op => files.Contains(op.Key.File) && op.Value is not null && HasDualWield(op.Value)); + } + + private static bool HasDualWield(JToken token) + { + return token is JContainer container && container.DescendantsAndSelf().OfType().Any(item => + item[TraitCode] is JValue { Value: long code } && code == SlotTypeTrait && + item[TraitData] is JValue { Value: long data } && data == DualWieldSlot); + } + + private static bool TryReadBase(BaseFileSet baseFiles, string file, [NotNullWhen(true)] out JToken? root) + { + root = null; + BaseFile? baseFile = baseFiles.Find(file); + return baseFile is not null && ChangeSetBuilder.TryReadBase(baseFile, out root, out _); } /// GR-R3: claims with equal content are one party, because their ops fold into one. @@ -244,11 +329,15 @@ private static bool IsVanillaMapFile(IdKind kind, int id, BaseFileSet baseFiles) return kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null; } - private static ModReferences ReferencesOf(RemapMod mod, Dictionary cache) + private static ModReferences ReferencesOf( + RemapMod mod, + Lazy dualWield, + RpgMakerEngine? engine, + Dictionary cache) { if (!cache.TryGetValue(mod.ChangeSet.ModId, out ModReferences? found)) { - found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts); + found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts, dualWield.Value, engine == RpgMakerEngine.MZ); cache.Add(mod.ChangeSet.ModId, found); } diff --git a/RPGModder.Core/Merge/IdRemapper.cs b/RPGModder.Core/Merge/IdRemapper.cs index 9e1dcc0..c42896f 100644 --- a/RPGModder.Core/Merge/IdRemapper.cs +++ b/RPGModder.Core/Merge/IdRemapper.cs @@ -13,8 +13,8 @@ public static class IdRemapper /// /// Applies the entries of that name this mod and an id it still adds; the others are /// inactive and change nothing (GR-R12). All moves of one mod apply in one pass, so an id moved onto another - /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Step 1 applies the - /// and kinds and ignores the others. + /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Map events, maps and + /// the twelve database kinds move; an entry of another kind changes nothing. /// public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList remaps) { @@ -28,7 +28,7 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList IReadOnlyList added = AddedIdIndex.Of(changeSet); List active = remaps - .Where(remap => remap.ModId == changeSet.ModId && remap.Kind is IdKind.MapEvent or IdKind.Map && AddedIdIndex.IsActive(remap, added)) + .Where(remap => remap.ModId == changeSet.ModId && RpgDataSchema.IsRemappable(remap.Kind) && AddedIdIndex.IsActive(remap, added)) .Distinct() .OrderBy(remap => remap.Kind) .ThenBy(remap => remap.Scope, StringComparer.Ordinal) @@ -38,7 +38,7 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList var table = new RemapTable(); foreach (IdRemap remap in active) { - Dictionary moves = remap.Kind == IdKind.Map ? table.Maps : EventMoves(table, remap.Scope); + Dictionary moves = table.For(remap.Kind, remap.Scope); if (remap.ToId <= 0 || moves.ContainsValue(remap.ToId) || !moves.TryAdd(remap.FromId, remap.ToId)) { // The planner gives each old id one positive target of its own; anything else is a caller bug. @@ -54,8 +54,7 @@ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList } // A stable sort: two ops can share a place when a recorded move lands on an id the mod now adds too. - List ops = changeSet.Ops - .Select(op => ReferenceMap.Rewrite(op, table)) + List ops = ReferenceMap.Rewrite(changeSet, table) .OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps)) .ToList(); @@ -77,15 +76,4 @@ private static string Describe(IdRemap remap) CultureInfo.InvariantCulture, $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} moved to {remap.ToId}."); } - - private static Dictionary EventMoves(RemapTable table, string scope) - { - if (!table.Events.TryGetValue(scope, out Dictionary? moves)) - { - moves = new Dictionary(); - table.Events.Add(scope, moves); - } - - return moves; - } } diff --git a/RPGModder.Core/Merge/MergedFileWriter.cs b/RPGModder.Core/Merge/MergedFileWriter.cs index fa94258..df49225 100644 --- a/RPGModder.Core/Merge/MergedFileWriter.cs +++ b/RPGModder.Core/Merge/MergedFileWriter.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json.Linq; using RPGModder.Core.Models; +using RPGModder.Core.Services; namespace RPGModder.Core.Merge; @@ -10,7 +11,11 @@ namespace RPGModder.Core.Merge; /// public static class MergedFileWriter { - public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId) + /// + /// The game's engine, which picks the blank record that fills a hole in a database file (GR-R8). An unknown + /// engine (null) gets MV's blanks. + /// + public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId, RpgMakerEngine? engine = null) { ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(baseFiles); @@ -56,14 +61,20 @@ public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFi MergeFileKind.Opaque => Copy(file, fileOps, modIds), MergeFileKind.PluginList => new MergedFile(file, MergedFileSource.Text, RenderPluginList(file, fileOps, baseFiles), null, null, modIds), MergeFileKind.ConfigSave => new MergedFile(file, MergedFileSource.Text, RenderConfigSave(file, fileOps, baseFiles), null, null, modIds), - _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, modIds) + _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, engine, modIds) }); } return result; } - private static MergedFile WriteDataFile(string file, List fileOps, BaseFileSet baseFiles, int? systemVersionId, List modIds) + private static MergedFile WriteDataFile( + string file, + List fileOps, + BaseFileSet baseFiles, + int? systemVersionId, + RpgMakerEngine? engine, + List modIds) { BaseFile? baseFile = baseFiles.Find(file); if (baseFile is null) @@ -71,13 +82,21 @@ private static MergedFile WriteDataFile(string file, List fileOps, Bas // GR-M9: a new file is one AddRecord on *, copied as the mod shipped it unless a patch or a remap changed // it. Written as text, it names its mod so lane A takes the casing of that mod's file (seam 4.2 step 2); // a map gets the casing the game loads instead (step 0), because a remapped one has no mod file name. + // A database file with a hole is written as text too, so the hole gets its blank record (GR-R8). ChangeOp added = SingleOp(fileOps, ChangeKind.AddRecord); - return added.SourceFile is null - ? new MergedFile(file, MergedFileSource.Text, MergeJson.Write(Value(added)), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file)) - : new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds); + JToken value = Value(added); + if (added.SourceFile is not null && !HasHoles(file, value)) + { + return new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds); + } + + JToken filled = value.DeepClone(); + FillHoles(file, filled, engine); + return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(filled), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file)); } JToken root = Render(file, baseFile, fileOps); + FillHoles(file, root, engine); if (file == RpgDataSchema.SystemFileKey && systemVersionId is not null) { SetVersionId(root, systemVersionId.Value); @@ -86,6 +105,34 @@ private static MergedFile WriteDataFile(string file, List fileOps, Bas return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(root), null, null, modIds); } + /// + /// GR-R8: a database file gets no null above index 0. Each hole, left by a removed, disabled or moved + /// record, takes the file's blank record with its own id. MapInfos and a map's events keep their holes. + /// + private static void FillHoles(string file, JToken root, RpgMakerEngine? engine) + { + if (root is not JArray records) + { + return; + } + + for (int index = 1; index < records.Count; index++) + { + if (records[index].Type == JTokenType.Null && RpgDataSchema.BlankRecord(file, engine) is { } blank) + { + blank["id"] = index; + records[index] = blank; + } + } + } + + private static bool HasHoles(string file, JToken root) + { + return RpgDataSchema.DatabaseKindOf(file) is not null && + root is JArray records && + records.Skip(1).Any(record => record.Type == JTokenType.Null); + } + /// A replaced opaque file is the bytes of the mod whose id sorts first among those that ship them. private static MergedFile Copy(string file, List fileOps, List modIds) { diff --git a/RPGModder.Core/Merge/ModReferences.cs b/RPGModder.Core/Merge/ModReferences.cs index f432a32..9578181 100644 --- a/RPGModder.Core/Merge/ModReferences.cs +++ b/RPGModder.Core/Merge/ModReferences.cs @@ -3,33 +3,92 @@ namespace RPGModder.Core.Merge; /// What found in one mod: the numbers a remap cannot rewrite. internal sealed class ModReferences { + private readonly Dictionary> _ambiguous = new(); + private readonly HashSet _unknownIds = new(); + private readonly Dictionary> _used = new(); + /// Whole numbers in the change set's free text (GR-R9). public HashSet FreeTextNumbers { get; } = new(); - /// Event ids named by event commands in a common event or a troop, which act on any map (3.11). - public HashSet AmbiguousEventIds { get; } = new(); - - /// Constants Control Variables assigns; with a transfer by variable, one of them may be a map id. + /// Constants Control Variables assigns; with a by-variable command, one of them may be its id. public HashSet VariableConstants { get; } = new(); + /// Random ranges Control Variables assigns, low end first; with a by-variable command, any id in one may be its id. + public List<(long Min, long Max)> VariableRanges { get; } = new(); + /// Whole numbers in the plugin files the mod ships (GR-R11). public HashSet PluginScriptNumbers { get; } = new(); /// - /// True when the mod sends the player or a vehicle to a map named by a variable (201 with p[0] 1, 202 with - /// p[1] 1). + /// The kinds the mod names through a variable: a map (201 with p[0] 1, 202 with p[1] 1), a troop + /// (301 with p[0] 1), an actor (311 to 318 and 326 with p[0] 1). + /// + public HashSet ByVariableKinds { get; } = new(); + + /// + /// Records an id that may be of where a remap cannot tell (3.11): an event command outside + /// a map, the second equip slot of a dual-wield game, a field whose kind sits in a vanilla sibling. /// - public bool UsesVariableTransfer { get; set; } + public void AddAmbiguous(IdKind kind, long id) + { + if (!_ambiguous.TryGetValue(kind, out HashSet? ids)) + { + ids = new HashSet(); + _ambiguous.Add(kind, ids); + } + + ids.Add(id); + } + + /// + /// Records that some id of that only vanilla holds is named where a remap cannot see it: + /// a field whose deciding sibling the mod changed alone, such as a drop whose kind changed and whose + /// dataId did not. + /// + public void AddUnknownId(IdKind kind) + { + _unknownIds.Add(kind); + } + + /// Records an id of the change set names where a remap rewrites it. + public void AddUsed(IdKind kind, long id) + { + if (!_used.TryGetValue(kind, out HashSet? ids)) + { + ids = new HashSet(); + _used.Add(kind, ids); + } + + ids.Add(id); + } + + /// + /// True when the change set may refer to of : a place a remap + /// rewrites, a place of no known kind, or free text (GR-R7). + /// + public bool Uses(IdKind kind, int id) + { + return FreeTextNumbers.Contains(id) || + (_used.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) || + (_ambiguous.TryGetValue(kind, out HashSet? unknown) && unknown.Contains(id)) || + ByVariable(kind, id); + } /// True when the change set refers to where a remap cannot follow it (GR-R9). public bool Blocks(IdKind kind, int id) { - return FreeTextNumbers.Contains(id) || kind switch - { - IdKind.MapEvent => AmbiguousEventIds.Contains(id), - IdKind.Map => UsesVariableTransfer && VariableConstants.Contains(id), - _ => true - }; + return FreeTextNumbers.Contains(id) || + !RpgDataSchema.IsRemappable(kind) || + (_ambiguous.TryGetValue(kind, out HashSet? ids) && ids.Contains(id)) || + _unknownIds.Contains(kind) || + ByVariable(kind, id); + } + + /// True when a by-variable command of may get from a constant or a random range. + private bool ByVariable(IdKind kind, int id) + { + return ByVariableKinds.Contains(kind) && + (VariableConstants.Contains(id) || VariableRanges.Exists(range => range.Min <= id && id <= range.Max)); } /// True when appears in a shipped plugin file, so a move is only offered (GR-R11). diff --git a/RPGModder.Core/Merge/ReferenceMap.cs b/RPGModder.Core/Merge/ReferenceMap.cs index dd03786..6cb1a34 100644 --- a/RPGModder.Core/Merge/ReferenceMap.cs +++ b/RPGModder.Core/Merge/ReferenceMap.cs @@ -1,84 +1,41 @@ using Newtonsoft.Json.Linq; using System.Diagnostics.CodeAnalysis; using System.Globalization; +using System.Text; namespace RPGModder.Core.Merge; /// -/// Where an id is referenced (guide 3.11, reference table), for the two kinds of step 1. reads a -/// change set's free text and the references the table cannot rewrite (GR-R9); moves every -/// reference the table lists. p[n] below is parameters[n] of an event or route command; only values -/// above 0 are ids. Every position was checked against the MV and MZ core scripts. +/// Where an id is referenced (guide 3.11). One walker reads a change set with the rows of : +/// collects what a remap cannot rewrite (GR-R9), moves every reference the +/// rows name. Only whole numbers above 0 are ids. /// internal static class ReferenceMap { - // Route command (inside a moveRoute list): Script. - private const int RouteScript = 45; - - // Event commands. - private const int ConditionalBranch = 111; - private const int ControlVariables = 122; - private const int TransferPlayer = 201; - private const int SetVehicleLocation = 202; - private const int SetEventLocation = 203; - private const int SetMovementRoute = 205; - private const int ShowAnimation = 212; - private const int ShowBalloon = 213; - private const int GetLocationInfo = 285; - private const int Script = 355; - private const int PluginCommandMv = 356; - private const int PluginCommandMz = 357; - private const int ScriptMore = 655; - - // 111 p[0], 122 p[3] and p[4], 201 p[0], 202 p[1], 203 p[1], 285 p[2]: the operand forms the table names. - private const int BranchCharacter = 6; - private const int BranchScript = 12; - private const int OperandConstant = 0; - private const int OperandGameData = 3; - private const int OperandScript = 4; - private const int GameDataCharacter = 5; - private const int DesignationDirect = 0; - private const int DesignationByVariable = 1; - private const int EventLocationExchange = 2; - private const int LocationByCharacter = 2; - private const string NoteProperty = "note"; private const string DamageProperty = "damage"; private const string FormulaProperty = "formula"; - private const string ParentIdProperty = "parentId"; private const string IdProperty = "id"; private const string ParametersProperty = "parameters"; private const string CodeProperty = "code"; + private const int CommentCode = 108; + private const int CommentMoreCode = 408; - /// The System.json places that hold a map id. - private static readonly HashSet StartMapPaths = new(StringComparer.Ordinal) - { - "startMapId", - "boat.startMapId", - "ship.startMapId", - "airship.startMapId" - }; - - /// What in one mod's change set stops a move (GR-R9) or makes it unchecked (GR-R11). - public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts) + /// + /// What in one mod's change set stops a move (GR-R9), makes it unchecked (GR-R11) or uses an id (GR-R7). With + /// , the second equip slot may hold a weapon, so its ids are of no known kind. Without + /// , a row only MZ reads so is of no known kind too. + /// + public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts, bool dualWield, bool mz) { var references = new ModReferences(); + var siblings = new SiblingOps(changeSet); foreach (ChangeOp op in changeSet.Ops) { - if (op.Value is null || MergePath.IsPseudoLeaf(op.Path)) + if (op.Value is not null && !MergePath.IsPseudoLeaf(op.Path)) { - continue; + new Walker(op, siblings, dualWield, mz, hit => Collect(hit, references)).Walk(op.Value); } - - IReadOnlyList segments = MergePath.Parse(op.Path); - string? name = segments.Count > 0 ? segments[^1].Name : null; - string? parent = segments.Count > 1 ? segments[^2].Name : null; - bool isPluginList = op.Key.File == RpgDataSchema.PluginListKey; - var context = new ScanContext(references, RpgDataSchema.IsMapFile(op.Key.File), isPluginList); - - // Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry. - bool inParameters = isPluginList && segments.Count > 0 && segments[0].Name == ParametersProperty; - Visit(op.Value, name, parent, inParameters, context); } foreach (string script in pluginScripts) @@ -90,257 +47,234 @@ public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList p } /// - /// with every listed reference moved by , or the op itself when - /// nothing moved. A whole new file whose content changed loses its source file, so it is written as text. + /// The change set's ops with every reference the rows name moved by , and every added + /// record that moves on its new id. An op nothing moved is returned as it was. A reference of no known kind is + /// left alone: the planner never moves an id a mod names so (GR-R9). The second equip slot is read as an armor, + /// because in a dual-wield game the planner moves neither kind of an id a mod puts there; a row only MZ reads so + /// is read as on MZ, because on any other engine the planner never moves its id. /// - public static ChangeOp Rewrite(ChangeOp op, RemapTable table) + public static IReadOnlyList Rewrite(ModChangeSet changeSet, RemapTable table) { - RecordKey key = op.Key; - JToken? value = op.Value?.DeepClone(); - if (op.Kind == ChangeKind.AddRecord && op.Path.Length == 0) - { - if (key.IsWholeFile && RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.Maps.TryGetValue(mapId, out int newMap)) - { - key = new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile); - } - else if (key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(key.Record, out int infoId) && - table.Maps.TryGetValue(infoId, out int newInfo)) - { - key = key with { Record = RecordKey.ForIndex(newInfo) }; - SetOwnId(value, infoId, newInfo); - } - else if (table.Events.TryGetValue(key.File, out Dictionary? moved) && RecordKey.TryGetEvent(key.Record, out int eventId) && - moved.TryGetValue(eventId, out int newEvent)) - { - key = key with { Record = RecordKey.ForEvent(newEvent) }; - SetOwnId(value, eventId, newEvent); - } - } + var siblings = new SiblingOps(changeSet); + return changeSet.Ops.Select(op => Rewrite(op, table, siblings)).ToList(); + } + private static ChangeOp Rewrite(ChangeOp op, RemapTable table, SiblingOps siblings) + { + JToken? value = op.Value?.DeepClone(); + RecordKey key = op.Kind == ChangeKind.AddRecord && op.Path.Length == 0 ? OwnKey(op.Key, value, table) : op.Key; if (value is not null && !MergePath.IsPseudoLeaf(op.Path)) { // Event references are scoped to the map file the commands sit in, so the op's own file decides. Dictionary? events = table.Events.GetValueOrDefault(op.Key.File); - VisitCommands(value, command => RewriteCommand(command, table.Maps, events)); - if (op.Key.File == RpgDataSchema.MapInfosKey && !op.Key.IsWholeFile) - { - // A map's parent, in the moved map's own record or in a vanilla map the mod hangs under it. - value = RewriteAt(value, op.Path, path => path == ParentIdProperty, table.Maps); - } - else if (op.Key.File == RpgDataSchema.SystemFileKey) - { - value = RewriteAt(value, op.Path, StartMapPaths.Contains, table.Maps); - } + new Walker(op, siblings, dualWield: false, mz: true, hit => Move(hit, table, events)).Walk(value); } - bool changed = key != op.Key || !JToken.DeepEquals(value, op.Value); - if (!changed) + if (key == op.Key && JToken.DeepEquals(value, op.Value)) { return op; } + // A whole new file whose content changed loses its source file, so it is written as text. string? source = op.Kind == ChangeKind.AddRecord && op.Key.IsWholeFile ? null : op.SourceFile; return op with { Key = key, Value = value, SourceFile = source }; } - private static void Visit(JToken token, string? name, string? parent, bool inParameters, ScanContext context) + /// The key an added record moves to, with its own id set: a map file, a tree record, an event or a database record. + private static RecordKey OwnKey(RecordKey key, JToken? value, RemapTable table) { - if (inParameters) + if (key.IsWholeFile) { - AddNumbers(token, context.References.FreeTextNumbers); - return; + return RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.MovesOf(IdKind.Map) is { } maps && maps.TryGetValue(mapId, out int newMap) + ? new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile) + : key; } - switch (token) + Dictionary? moves = null; + Func recordOf = RecordKey.ForIndex; + if (RecordKey.TryGetEvent(key.Record, out int oldId)) { - case JObject item: - if (TryCommand(item, out int code, out JArray? parameters)) - { - ScanCommand(code, parameters, context); - } - - foreach (JProperty property in item.Properties()) - { - bool pluginParameters = context.IsPluginList && property.Name == ParametersProperty; - Visit(property.Value, property.Name, name, pluginParameters, context); - } + moves = table.Events.GetValueOrDefault(key.File); + recordOf = RecordKey.ForEvent; + } + else if (RecordKey.TryGetIndex(key.Record, out oldId)) + { + IdKind? kind = key.File == RpgDataSchema.MapInfosKey ? IdKind.Map : RpgDataSchema.DatabaseKindOf(key.File); + moves = kind is null ? null : table.MovesOf(kind.Value); + } - break; - case JArray list: - foreach (JToken element in list) - { - Visit(element, null, name, false, context); - } + if (moves is null || !moves.TryGetValue(oldId, out int newId)) + { + return key; + } - break; - case JValue { Type: JTokenType.String } text when name == NoteProperty || (name == FormulaProperty && parent == DamageProperty): - AddNumbers(text, context.References.FreeTextNumbers); - break; + if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId) + { + record[IdProperty] = newId; } + + return key with { Record = recordOf(newId) }; } - private static void ScanCommand(int code, JArray parameters, ScanContext context) + private static void Collect(Hit hit, ModReferences references) { - ModReferences references = context.References; - switch (code) + // An Id hit, or a text code the table knows, is a reference a remap rewrites: it stops nothing, but it uses the id. + switch (hit.Use) { - case Script or ScriptMore or PluginCommandMv or RouteScript: - AddNumbers(At(parameters, 0), references.FreeTextNumbers); + case HitUse.Id when hit.Token is JValue value && TryId(value, out int used): + references.AddUsed(hit.Kind, used); + break; + case HitUse.Text or HitUse.Comment when hit.Token is JValue { Value: string text } && text.Contains('\\'): + foreach ((string letters, _, _, int id) in TextCodesIn(text)) + { + if (ReferenceTable.TextCodes.TryGetValue(letters, out IdKind kind)) + { + references.AddUsed(kind, id); + } + else if (hit.Use == HitUse.Text && !ReferenceTable.BuiltInTextCodes.Contains(letters)) + { + // A plugin's code may name an id of any kind, so it is free text (GR-R9); a comment is not read. + references.FreeTextNumbers.Add(id); + } + } + break; - case PluginCommandMz: - AddNumbers(At(parameters, 3), references.FreeTextNumbers); + case HitUse.FreeText: + AddNumbers(hit.Token, references.FreeTextNumbers); break; - case ConditionalBranch when Is(parameters, 0, BranchScript): - AddNumbers(At(parameters, 1), references.FreeTextNumbers); + case HitUse.Ambiguous when hit.Token is JValue value && TryLooseId(value, out int id): + references.AddAmbiguous(hit.Kind, id); break; - case ControlVariables when Is(parameters, 3, OperandScript): - AddNumbers(At(parameters, 4), references.FreeTextNumbers); + case HitUse.UnknownId: + references.AddUnknownId(hit.Kind); break; - case ControlVariables when Is(parameters, 3, OperandConstant): - AddId(At(parameters, 4), references.VariableConstants); + case HitUse.Constant when hit.Token is JValue value && TryId(value, out int constant): + references.VariableConstants.Add(constant); break; - case TransferPlayer when Is(parameters, 0, DesignationByVariable): - case SetVehicleLocation when Is(parameters, 1, DesignationByVariable): - references.UsesVariableTransfer = true; + case HitUse.RandomRange when hit.Token is JArray { Count: 2 } range && range[0] is JValue low && TryInt(low, out int min) && + range[1] is JValue high && TryInt(high, out int max): + references.VariableRanges.Add((Math.Min(min, max), Math.Max(min, max))); + break; + case HitUse.ByVariable: + references.ByVariableKinds.Add(hit.Kind); break; - } - - if (context.IsMapFile) - { - return; - } - - // Outside a map the event commands act on whatever map is loaded, so their ids cannot be rewritten (3.11). - foreach (int index in EventPositions(code, parameters)) - { - AddId(At(parameters, index), references.AmbiguousEventIds); } } - private static void RewriteCommand(JObject command, Dictionary maps, Dictionary? events) + private static void Move(Hit hit, RemapTable table, Dictionary? events) { - if (!TryCommand(command, out int code, out JArray? parameters)) + if (hit.Token is not JValue value) { return; } - if (maps.Count > 0) + if (hit.Use is HitUse.Text or HitUse.Comment) { - if (code == TransferPlayer && Is(parameters, 0, DesignationDirect)) - { - Move(parameters, 1, maps); - } - else if (code == SetVehicleLocation && Is(parameters, 1, DesignationDirect)) + string text = value.Value() ?? ""; + string moved = MoveTextCodes(text, table); + if (!ReferenceEquals(moved, text)) { - Move(parameters, 2, maps); + value.Value = moved; } + + return; } - if (events is not null) + Dictionary? moves = hit.Kind == IdKind.MapEvent ? events : table.MovesOf(hit.Kind); + if (hit.Use == HitUse.Id && moves is not null && TryId(value, out int id) && moves.TryGetValue(id, out int newId)) { - foreach (int index in EventPositions(code, parameters)) - { - Move(parameters, index, events); - } + value.Value = (long)newId; } } - /// The positions of a command that hold an event id of the current map, from the reference table. - private static IEnumerable EventPositions(int code, JArray parameters) + /// + /// with every text code that names a moved id rewritten, or the same instance when none + /// does. A pair of backslashes is a literal backslash, as the game reads it; a code letter matches in either case. + /// + private static string MoveTextCodes(string text, RemapTable table) { - switch (code) + StringBuilder? builder = null; + int copied = 0; + foreach ((string letters, int start, int end, int id) in TextCodesIn(text)) { - case SetEventLocation: - yield return 0; - if (Is(parameters, 1, EventLocationExchange)) - { - yield return 2; - } - - break; - case SetMovementRoute or ShowAnimation or ShowBalloon: - yield return 0; - break; - case ConditionalBranch when Is(parameters, 0, BranchCharacter): - yield return 1; - break; - case ControlVariables when Is(parameters, 3, OperandGameData) && Is(parameters, 4, GameDataCharacter): - yield return 5; - break; - case GetLocationInfo when Is(parameters, 2, LocationByCharacter): - yield return 3; - break; + if (ReferenceTable.TextCodes.TryGetValue(letters, out IdKind kind) && + table.MovesOf(kind) is { } moves && + moves.TryGetValue(id, out int newId)) + { + builder ??= new StringBuilder(text.Length); + builder.Append(text, copied, start - copied).Append(newId.ToString(CultureInfo.InvariantCulture)); + copied = end; + } } + + return builder is null ? text : builder.Append(text, copied, text.Length - copied).ToString(); } - /// Every command object in , including route commands inside a move route. - private static void VisitCommands(JToken token, Action visit) + /// + /// Every text code with a number above 0 in , its letters in upper case. A pair of + /// backslashes is a literal backslash, as the game reads it. Start and End bound the digits. + /// + private static IEnumerable<(string Letters, int Start, int End, int Id)> TextCodesIn(string text) { - switch (token) + for (int index = 0; index < text.Length; index++) { - case JObject item: - visit(item); - foreach (JProperty property in item.Properties()) - { - VisitCommands(property.Value, visit); - } + if (text[index] != '\\') + { + continue; + } - break; - case JArray list: - foreach (JToken element in list) - { - VisitCommands(element, visit); - } + if (index + 1 < text.Length && text[index + 1] == '\\') + { + index++; + continue; + } - break; + if (TryTextCode(text, index, out string letters, out int start, out int end, out int id)) + { + yield return (letters, start, end, id); + index = end; + } } } - /// - /// Moves the map ids at the places accepts, walking down - /// from its own path (relative to the record, as op paths are). - /// - private static JToken RewriteAt(JToken token, string path, Func isPlace, Dictionary maps) + /// A text code at : letters, then digits in brackets, as the message window reads it. + private static bool TryTextCode(string text, int slash, out string letters, out int start, out int end, out int id) { - if (isPlace(path)) + letters = ""; + id = 0; + int open = slash + 1; + while (open < text.Length && char.IsAsciiLetter(text[open])) { - return token is JValue value && TryId(value, out int id) && maps.TryGetValue(id, out int moved) ? new JValue(moved) : token; + open++; } - if (token is not JObject item) + start = open + 1; + end = start; + if (open == slash + 1 || open >= text.Length || text[open] != '[') { - return token; + return false; } - foreach (JProperty property in item.Properties().ToList()) + while (end < text.Length && char.IsAsciiDigit(text[end])) { - property.Value = RewriteAt(property.Value, MergePath.Child(path, property.Name), isPlace, maps); + end++; } - return item; - } - - private static void SetOwnId(JToken? value, int oldId, int newId) - { - if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId) + if (end == start || end >= text.Length || text[end] != ']' || + !int.TryParse(text.AsSpan(start, end - start), NumberStyles.None, CultureInfo.InvariantCulture, out id) || id <= 0) { - record[IdProperty] = newId; + return false; } - } - private static void Move(JArray parameters, int index, Dictionary moves) - { - if (At(parameters, index) is JValue value && TryId(value, out int id) && moves.TryGetValue(id, out int moved)) - { - parameters[index] = moved; - } + letters = text[(slash + 1)..open].ToUpperInvariant(); + return true; } private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] out JArray? parameters) { parameters = item[ParametersProperty] as JArray; code = 0; - return parameters is not null && item[CodeProperty] is JValue { Type: JTokenType.Integer } value && TryInt(value, out code); + return parameters is not null && item[CodeProperty] is JValue value && TryInt(value, out code); } private static JToken? At(JArray parameters, int index) @@ -348,9 +282,9 @@ private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] o return index < parameters.Count ? parameters[index] : null; } - private static bool Is(JArray parameters, int index, int expected) + private static bool Holds(JArray parameters, ParameterTest test) { - return At(parameters, index) is JValue value && TryInt(value, out int actual) && actual == expected; + return At(parameters, test.Index) is JValue value && TryInt(value, out int actual) && actual >= test.Min && actual <= test.Max; } /// An id is a whole number above 0 (reference table). @@ -359,6 +293,30 @@ private static bool TryId(JValue value, out int id) return TryInt(value, out id) && id > 0; } + /// + /// An id the game reads although the editor never writes it so: a whole number stored as a float (3.0) or + /// as a string of digits ("3"), which JavaScript turns into the same array index. + /// + private static bool TryLooseId(JValue value, out int id) + { + id = 0; + switch (value.Value) + { + case long: + return TryId(value, out id); + case double real when real is >= 1 and <= int.MaxValue && real == Math.Floor(real): + id = (int)real; + return true; + case decimal exact when exact is >= 1 and <= int.MaxValue && exact == decimal.Truncate(exact): + id = (int)exact; + return true; + case string text when text.Length > 0 && text[0] != '0' && text.All(char.IsAsciiDigit): + return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out id); + default: + return false; + } + } + private static bool TryInt(JValue value, out int number) { number = 0; @@ -371,14 +329,6 @@ private static bool TryInt(JValue value, out int number) return true; } - private static void AddId(JToken? token, HashSet ids) - { - if (token is JValue value && TryId(value, out int id)) - { - ids.Add(id); - } - } - /// Every whole number in : each run of ASCII digits in its text, and each integer. private static void AddNumbers(JToken? token, HashSet numbers) { @@ -425,5 +375,350 @@ private static void AddNumbers(string text, HashSet numbers) } } - private sealed record ScanContext(ModReferences References, bool IsMapFile, bool IsPluginList); + private enum HitUse + { + /// An id of a known kind, which a remap rewrites. + Id, + + /// + /// An id that may be of or of another kind, or that is not stored as an integer, so a + /// remap cannot follow it. + /// + Ambiguous, + + /// Some id of that only vanilla holds; which one, this walk cannot see. + UnknownId, + + FreeText, + Constant, + + /// A random range's two ends, as a new array of two values. + RandomRange, + + ByVariable, + + /// A string, whose text codes a remap rewrites. + Text, + + /// A string of a comment (108, 408): its text codes are rewritten, but a plugin's code stops nothing. + Comment + } + + private readonly record struct Hit(HitUse Use, IdKind Kind, JToken Token); + + /// + /// The values other ops of the same change set set: the sibling a field row asks for when the op is a single + /// leaf (a drop's dataId without its kind). + /// + private sealed class SiblingOps + { + private readonly ModChangeSet _changeSet; + private Dictionary<(RecordKey Key, string Path), JToken?>? _values; + + public SiblingOps(ModChangeSet changeSet) + { + _changeSet = changeSet; + } + + /// False when the change set has no op there, so the value is vanilla's and unknown here. + public bool TryGet(RecordKey key, string path, out JToken? value) + { + _values ??= _changeSet.Ops + .GroupBy(op => (op.Key, op.Path)) + .ToDictionary(group => group.Key, group => group.Last().Value); + return _values.TryGetValue((key, path), out value); + } + } + + /// + /// One walk over one op's value. The path is kept as segments relative to the record (or to the root of an + /// object file) and turned into a pattern only at a leaf whose name a field row ends in, so a map's tile data + /// builds no strings. + /// + private sealed class Walker + { + private readonly ChangeOp _op; + private readonly SiblingOps _siblings; + private readonly bool _dualWield; + private readonly bool _mz; + private readonly Action _emit; + private bool _inComment; + private readonly string _table; + private readonly bool _isMap; + private readonly List _path; + + public Walker(ChangeOp op, SiblingOps siblings, bool dualWield, bool mz, Action emit) + { + _op = op; + _siblings = siblings; + _dualWield = dualWield; + _mz = mz; + _emit = emit; + _table = RpgDataSchema.TableOf(op.Key.File); + _isMap = RpgDataSchema.IsMapFile(op.Key.File); + _path = MergePath.Parse(op.Path).ToList(); + } + + public void Walk(JToken value) + { + if (_op.Key.File == RpgDataSchema.PluginListKey) + { + WalkPluginList(value); + return; + } + + bool recordsFile = RpgDataSchema.DatabaseKindOf(_op.Key.File) is not null || _op.Key.File == RpgDataSchema.MapInfosKey; + if (_op.Key.IsWholeFile && _path.Count == 0 && recordsFile && value is JArray records) + { + // A whole records file: each element is a record, and paths start again inside it. + foreach (JToken record in records) + { + Visit(record, null, null, isRoot: false); + } + + return; + } + + Visit(value, LastName(_path), null, isRoot: true); + } + + /// Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry. + private void WalkPluginList(JToken value) + { + if (_path.Count > 0 && _path[0].Name == ParametersProperty) + { + _emit(new Hit(HitUse.FreeText, default, value)); + return; + } + + foreach (JToken parameters in value.SelectTokens("$.." + ParametersProperty)) + { + _emit(new Hit(HitUse.FreeText, default, parameters)); + } + } + + /// The token at . + /// The property name of the token, or of its array for an element. + /// The object that holds the token as a property, when it is part of this value. + /// True for the op's own value, whose siblings are other ops. + private void Visit(JToken token, string? name, JObject? parent, bool isRoot) + { + switch (token) + { + case JObject item: + bool wasComment = _inComment; + if (TryCommand(item, out int code, out JArray? parameters)) + { + VisitCommand(code, parameters); + _inComment = code is CommentCode or CommentMoreCode; + } + + foreach (JProperty property in item.Properties()) + { + _path.Add(PathSegment.Property(property.Name)); + Visit(property.Value, property.Name, item, isRoot: false); + _path.RemoveAt(_path.Count - 1); + } + + _inComment = wasComment; + break; + case JArray list when _isMap && _op.Key.IsWholeFile && _path.Count == 1 && _path[0].Name == RpgDataSchema.EventsProperty: + // A whole map's events are records: paths start again inside each one. + _path.Clear(); + foreach (JToken record in list) + { + Visit(record, null, null, isRoot: false); + } + + _path.Add(PathSegment.Property(RpgDataSchema.EventsProperty)); + break; + case JArray list: + for (int index = 0; index < list.Count; index++) + { + _path.Add(PathSegment.At(index)); + Visit(list[index], name, null, isRoot: false); + _path.RemoveAt(_path.Count - 1); + } + + break; + case JValue { Type: JTokenType.String } text: + if (name == NoteProperty || (name == FormulaProperty && _path.Count > 1 && _path[^2].Name == DamageProperty)) + { + _emit(new Hit(HitUse.FreeText, default, text)); + } + + _emit(new Hit(_inComment ? HitUse.Comment : HitUse.Text, default, text)); + if (name is not null && ReferenceTable.MayBeField(name)) + { + VisitField(text, parent, isRoot); + } + + break; + case JValue { Type: JTokenType.Integer or JTokenType.Float } number when name is not null && ReferenceTable.MayBeField(name): + VisitField(number, parent, isRoot); + break; + case JValue { Type: JTokenType.Integer } number when isRoot && name is not null && ReferenceTable.MayBeSibling(name): + VisitSibling(number); + break; + } + } + + private void VisitCommand(int code, JArray parameters) + { + foreach (CommandPlace row in ReferenceTable.Commands(code)) + { + if (!row.When.All(test => Holds(parameters, test))) + { + continue; + } + + JToken? place = At(parameters, row.Index); + switch (row.Use) + { + case PlaceUse.Id when place is JValue value && row.Kind is { } kind && row.MzOnly && !_mz: + // MV reads the parameter another way (285 p[2] 2 is by variable there), so its kind is unknown. + _emit(new Hit(HitUse.Ambiguous, kind, value)); + break; + case PlaceUse.Id when place is JValue value && row.Kind is { } kind: + // Outside a map the event commands act on whatever map is loaded, so their ids are no map's (3.11). + EmitId(kind, value, row.SecondSlot, scoped: kind != IdKind.MapEvent || _isMap); + break; + case PlaceUse.FreeText when place is not null: + _emit(new Hit(HitUse.FreeText, default, place)); + break; + case PlaceUse.Constant when place is not null: + _emit(new Hit(HitUse.Constant, default, place)); + break; + case PlaceUse.RandomRange when place is JValue low && At(parameters, row.Index + 1) is JValue high: + _emit(new Hit(HitUse.RandomRange, default, new JArray(low.DeepClone(), high.DeepClone()))); + break; + case PlaceUse.ByVariable when row.Kind is { } kind: + _emit(new Hit(HitUse.ByVariable, kind, parameters)); + break; + } + } + } + + private void VisitField(JValue number, JObject? parent, bool isRoot) + { + IReadOnlyList rows = ReferenceTable.Fields(_table, Pattern(_path)); + if (rows.Count == 0) + { + return; + } + + int last = _path[^1].Name is null ? _path[^1].Index : 0; + foreach (FieldPlace row in rows.Where(item => last >= item.MinIndex && last <= item.MaxIndex)) + { + if (row.When is null) + { + EmitId(row.Kind, number, row.SecondSlot, scoped: true); + } + else if (!TrySibling(row.When.Sibling, parent, isRoot, out int? sibling)) + { + // The sibling is vanilla's, which this walk cannot see: the id may be of any kind the rows name. + _emit(new Hit(HitUse.Ambiguous, row.Kind, number)); + } + else if (sibling is { } known && row.When.Values.Contains(known)) + { + EmitId(row.Kind, number, row.SecondSlot, scoped: true); + } + } + } + + /// + /// A leaf op that sets only a deciding sibling (a drop's kind): when no op sets the id beside it, the id + /// is vanilla's, and it now names the row's kind without this walk seeing which id it is. + /// + private void VisitSibling(JValue number) + { + IReadOnlyList rows = ReferenceTable.FieldsBySibling(_table, Pattern(_path)); + if (rows.Count == 0 || !TryInt(number, out int sibling)) + { + return; + } + + string parentPath = MergePath.Format(_path.Take(_path.Count - 1)); + foreach (FieldPlace row in rows.Where(item => item.When!.Values.Contains(sibling))) + { + if (!_siblings.TryGet(_op.Key, MergePath.Child(parentPath, ReferenceTable.FieldName(row)), out _)) + { + _emit(new Hit(HitUse.UnknownId, row.Kind, number)); + } + } + } + + /// + /// An id of a known kind, unless the place is no map's, the slot may hold either kind, or the id is not stored + /// as an integer, which a remap does not rewrite. + /// + private void EmitId(IdKind kind, JValue value, bool secondSlot, bool scoped) + { + if (!scoped || value.Type != JTokenType.Integer) + { + _emit(new Hit(HitUse.Ambiguous, kind, value)); + } + else if (secondSlot && _dualWield) + { + _emit(new Hit(HitUse.Ambiguous, IdKind.Weapon, value)); + _emit(new Hit(HitUse.Ambiguous, IdKind.Armor, value)); + } + else + { + _emit(new Hit(HitUse.Id, kind, value)); + } + } + + /// + /// The whole number in the sibling property , null when it holds none. False + /// when the leaf is the op's whole value and no other op sets the sibling. + /// + private bool TrySibling(string name, JObject? parent, bool isRoot, out int? sibling) + { + JToken? token = parent?[name]; + if (parent is null && isRoot && _path.Count > 0) + { + string path = MergePath.Child(MergePath.Format(_path.Take(_path.Count - 1)), name); + if (!_siblings.TryGet(_op.Key, path, out token)) + { + sibling = null; + return false; + } + } + + sibling = token is JValue value && TryInt(value, out int whole) ? whole : null; + return true; + } + + private static string? LastName(List path) + { + for (int index = path.Count - 1; index >= 0; index--) + { + if (path[index].Name is { } name) + { + return name; + } + } + + return null; + } + + private static string Pattern(List path) + { + var builder = new StringBuilder(); + foreach (PathSegment segment in path) + { + if (segment.Name is null) + { + builder.Append("[*]"); + } + else + { + builder.Append(builder.Length == 0 ? "" : ".").Append(segment.Name); + } + } + + return builder.ToString(); + } + } } diff --git a/RPGModder.Core/Merge/ReferenceTable.cs b/RPGModder.Core/Merge/ReferenceTable.cs new file mode 100644 index 0000000..11df4c1 --- /dev/null +++ b/RPGModder.Core/Merge/ReferenceTable.cs @@ -0,0 +1,349 @@ +namespace RPGModder.Core.Merge; + +/// +/// The reference table of guide 3.11 as rows: where an id sits in an event command () and in a +/// record field (), and the text codes that name one (). +/// walks a change set once with these rows, to scan and to rewrite. p[n] is +/// parameters[n]; only values above 0 are ids. Every command row was checked against the MV and MZ core scripts. +/// +internal static class ReferenceTable +{ + private const string Map = RpgDataSchema.MapTable; + private const string Actors = "actors.json"; + private const string Classes = "classes.json"; + private const string Skills = "skills.json"; + private const string Items = "items.json"; + private const string Weapons = "weapons.json"; + private const string Armors = "armors.json"; + private const string Enemies = "enemies.json"; + private const string States = "states.json"; + private const string Troops = "troops.json"; + private const string MapInfos = "mapinfos.json"; + private const string SystemFile = "system.json"; + + /// The files whose records carry traits; an enemy's traits use the same codes. + private static readonly string[] TraitFiles = [Actors, Classes, Weapons, Armors, Enemies, States]; + + private static readonly CommandPlace[] CommandRows = + [ + // Map events: rewritten in the map's own file, ambiguous anywhere else (they act on whatever map is loaded). + Id(IdKind.MapEvent, 203, 0), // Set Event Location + Id(IdKind.MapEvent, 203, 2, Is(1, 2)), // ... exchanged with another event + Id(IdKind.MapEvent, 205, 0), // Set Movement Route + Id(IdKind.MapEvent, 212, 0), // Show Animation + Id(IdKind.MapEvent, 213, 0), // Show Balloon Icon + Id(IdKind.MapEvent, 111, 1, Is(0, 6)), // Conditional Branch: character + Id(IdKind.MapEvent, 122, 5, Is(3, 3), Is(4, 5)), // Control Variables: game data, character + Id(IdKind.MapEvent, 285, 3, Is(2, 2)) with { MzOnly = true }, // Get Location Info: by character (MV: by variable) + + // Maps. + Id(IdKind.Map, 201, 1, Is(0, 0)), // Transfer Player, direct + Id(IdKind.Map, 202, 2, Is(1, 0)), // Set Vehicle Location, direct + ByVariable(IdKind.Map, 201, Is(0, 1)), // Transfer Player by variable + ByVariable(IdKind.Map, 202, Is(1, 1)), // Set Vehicle Location by variable + new(122, 4, PlaceUse.Constant, null, [Is(3, 0)]), // Control Variables: constant, for every by-variable row + new(122, 4, PlaceUse.RandomRange, null, [Is(3, 2)]), // Control Variables: random p[4] to p[5], likewise + + // Items. + Id(IdKind.Item, 126, 0), // Change Items + Id(IdKind.Item, 111, 1, Is(0, 8)), + Id(IdKind.Item, 122, 5, Is(3, 3), Is(4, 0)), + Id(IdKind.Item, 302, 1, Is(0, 0)), // Shop Processing + Id(IdKind.Item, 605, 1, Is(0, 0)), // ... its further goods + + // Weapons. + Id(IdKind.Weapon, 127, 0), // Change Weapons + Id(IdKind.Weapon, 111, 1, Is(0, 9)), + Id(IdKind.Weapon, 111, 3, Is(0, 4), Is(2, 4)), + Id(IdKind.Weapon, 122, 5, Is(3, 3), Is(4, 1)), + Id(IdKind.Weapon, 302, 1, Is(0, 1)), + Id(IdKind.Weapon, 605, 1, Is(0, 1)), + Id(IdKind.Weapon, 319, 2, Is(1, 1)), // Change Equipment, equip type 1 + + // Armors. Equip type 2 is a weapon slot for a dual-wield actor (trait 55), so that row is a second slot. + Id(IdKind.Armor, 128, 0), // Change Armors + Id(IdKind.Armor, 111, 1, Is(0, 10)), + Id(IdKind.Armor, 111, 3, Is(0, 4), Is(2, 5)), + Id(IdKind.Armor, 122, 5, Is(3, 3), Is(4, 2)), + Id(IdKind.Armor, 302, 1, Is(0, 2)), + Id(IdKind.Armor, 605, 1, Is(0, 2)), + new(319, 2, PlaceUse.Id, IdKind.Armor, [Is(1, 2)], SecondSlot: true), + Id(IdKind.Armor, 319, 2, new ParameterTest(1, 3, int.MaxValue)), + + // Skills. + Id(IdKind.Skill, 318, 3), // Change Skill + Id(IdKind.Skill, 339, 2), // Force Action + Id(IdKind.Skill, 111, 3, Is(0, 4), Is(2, 3)), + + // States. + Id(IdKind.State, 313, 3), // Change State + Id(IdKind.State, 333, 2), // Change Enemy State + Id(IdKind.State, 111, 3, Is(0, 4), Is(2, 6)), + Id(IdKind.State, 111, 3, Is(0, 5), Is(2, 1)), + + // Enemies, troops, common events. + Id(IdKind.Enemy, 336, 1), // Enemy Transform + Id(IdKind.Troop, 301, 1, Is(0, 0)), // Battle Processing, direct + ByVariable(IdKind.Troop, 301, Is(0, 1)), // ... by variable + Id(IdKind.CommonEvent, 117, 0), // Common Event + + // Actors. 311 to 318 and 326 name an actor when p[0] is 0, a variable when it is 1. + Id(IdKind.Actor, 129, 0), // Change Party Member + Id(IdKind.Actor, 303, 0), // Name Input Processing + Id(IdKind.Actor, 111, 1, Is(0, 4)), + Id(IdKind.Actor, 122, 5, Is(3, 3), Is(4, 3)), + Id(IdKind.Actor, 311, 1, Is(0, 0)), + Id(IdKind.Actor, 312, 1, Is(0, 0)), + Id(IdKind.Actor, 313, 1, Is(0, 0)), + Id(IdKind.Actor, 314, 1, Is(0, 0)), + Id(IdKind.Actor, 315, 1, Is(0, 0)), + Id(IdKind.Actor, 316, 1, Is(0, 0)), + Id(IdKind.Actor, 317, 1, Is(0, 0)), + Id(IdKind.Actor, 318, 1, Is(0, 0)), + Id(IdKind.Actor, 326, 1, Is(0, 0)), + ByVariable(IdKind.Actor, 311, Is(0, 1)), + ByVariable(IdKind.Actor, 312, Is(0, 1)), + ByVariable(IdKind.Actor, 313, Is(0, 1)), + ByVariable(IdKind.Actor, 314, Is(0, 1)), + ByVariable(IdKind.Actor, 315, Is(0, 1)), + ByVariable(IdKind.Actor, 316, Is(0, 1)), + ByVariable(IdKind.Actor, 317, Is(0, 1)), + ByVariable(IdKind.Actor, 318, Is(0, 1)), + ByVariable(IdKind.Actor, 326, Is(0, 1)), + Id(IdKind.Actor, 319, 0), // Change Equipment + Id(IdKind.Actor, 320, 0), // Change Name + Id(IdKind.Actor, 321, 0), // Change Class + Id(IdKind.Actor, 322, 0), // Change Actor Images + Id(IdKind.Actor, 324, 0), // Change Nickname + Id(IdKind.Actor, 325, 0), // Change Profile + Id(IdKind.Actor, 339, 1, Is(0, 1)), // Force Action by an actor + + // Classes, animations, tilesets. + Id(IdKind.Class, 321, 1), + Id(IdKind.Class, 111, 3, Is(0, 4), Is(2, 2)), + Id(IdKind.Animation, 212, 1), // Show Animation + Id(IdKind.Animation, 337, 1), // Show Battle Animation + Id(IdKind.Tileset, 282, 0), // Change Tileset + + // Free text (GR-R9): a whole number here stops a move of that id, of any kind. + FreeText(355, 0), // Script + FreeText(655, 0), // ... its further lines + FreeText(356, 0), // Plugin Command (MV) + FreeText(357, 3), // Plugin Command (MZ): the arguments + FreeText(45, 0), // Script in a move route + FreeText(111, 1, Is(0, 12)), // Conditional Branch: script + FreeText(122, 4, Is(3, 4)) // Control Variables: script + ]; + + private static readonly FieldPlace[] FieldRows = + [ + // Maps. + new([MapInfos], "parentId", IdKind.Map), + new([SystemFile], "startMapId", IdKind.Map), + new([SystemFile], "boat.startMapId", IdKind.Map), + new([SystemFile], "ship.startMapId", IdKind.Map), + new([SystemFile], "airship.startMapId", IdKind.Map), + + // A map's own fields, and its events' page conditions. + new([Map], "tilesetId", IdKind.Tileset), + new([Map], "encounterList[*].troopId", IdKind.Troop), + new([Map], "pages[*].conditions.itemId", IdKind.Item), + new([Map], "pages[*].conditions.actorId", IdKind.Actor), + + // Database records. + new([Actors], "classId", IdKind.Class), + new([Actors], "equips[*]", IdKind.Weapon, MaxIndex: 0), + new([Actors], "equips[*]", IdKind.Armor, MinIndex: 1, MaxIndex: 1, SecondSlot: true), + new([Actors], "equips[*]", IdKind.Armor, MinIndex: 2), + new([Classes], "learnings[*].skillId", IdKind.Skill), + new([Skills, Items, Weapons], "animationId", IdKind.Animation), + new([Enemies], "actions[*].skillId", IdKind.Skill), + new([Enemies], "actions[*].conditionParam1", IdKind.State, new FieldTest("conditionType", [4])), + new([Enemies], "dropItems[*].dataId", IdKind.Item, new FieldTest("kind", [1])), + new([Enemies], "dropItems[*].dataId", IdKind.Weapon, new FieldTest("kind", [2])), + new([Enemies], "dropItems[*].dataId", IdKind.Armor, new FieldTest("kind", [3])), + new([Troops], "members[*].enemyId", IdKind.Enemy), + new([Troops], "pages[*].conditions.actorId", IdKind.Actor), + + // Traits 13, 14 and 32 name a state; 35 (MZ), 43 and 44 a skill. + new(TraitFiles, "traits[*].dataId", IdKind.State, new FieldTest("code", [13, 14, 32])), + new(TraitFiles, "traits[*].dataId", IdKind.Skill, new FieldTest("code", [35, 43, 44])), + + // Effects 21 and 22 name a state, 43 a skill, 44 a common event. + new([Skills, Items], "effects[*].dataId", IdKind.State, new FieldTest("code", [21, 22])), + new([Skills, Items], "effects[*].dataId", IdKind.Skill, new FieldTest("code", [43])), + new([Skills, Items], "effects[*].dataId", IdKind.CommonEvent, new FieldTest("code", [44])), + + // System: the starting party and the battle test. + new([SystemFile], "partyMembers[*]", IdKind.Actor), + new([SystemFile], "testBattlers[*].actorId", IdKind.Actor), + new([SystemFile], "testBattlers[*].equips[*]", IdKind.Weapon, MaxIndex: 0), + new([SystemFile], "testBattlers[*].equips[*]", IdKind.Armor, MinIndex: 1, MaxIndex: 1, SecondSlot: true), + new([SystemFile], "testBattlers[*].equips[*]", IdKind.Armor, MinIndex: 2), + new([SystemFile], "testTroopId", IdKind.Troop) + ]; + + private static readonly ILookup CommandsByCode = CommandRows.ToLookup(row => row.Code); + + private static readonly Dictionary<(string Table, string Pattern), FieldPlace[]> FieldsByPlace = FieldRows + .SelectMany(row => row.Tables.Select(table => (Table: table, Row: row))) + .GroupBy(pair => (pair.Table, pair.Row.Pattern)) + .ToDictionary(group => group.Key, group => group.Select(pair => pair.Row).ToArray()); + + /// The last property name of every field pattern; a leaf under any other name is no field reference. + private static readonly HashSet FieldNames = new(FieldRows.Select(row => LastName(row.Pattern)), StringComparer.Ordinal); + + /// The rows whose deciding sibling sits at a pattern (dropItems[*].kind for a drop's dataId). + private static readonly Dictionary<(string Table, string Pattern), FieldPlace[]> FieldsBySiblingPlace = FieldRows + .Where(row => row.When is not null) + .SelectMany(row => row.Tables.Select(table => (Table: table, Row: row))) + .GroupBy(pair => (pair.Table, SiblingPattern(pair.Row))) + .ToDictionary(group => group.Key, group => group.Select(pair => pair.Row).ToArray()); + + private static readonly HashSet SiblingNames = + new(FieldRows.Where(row => row.When is not null).Select(row => row.When!.Sibling), StringComparer.Ordinal); + + /// The text codes that name an id inside message text, by their letters: \N[n] is an actor's name. + public static IReadOnlyDictionary TextCodes { get; } = + new Dictionary(StringComparer.Ordinal) { ["N"] = IdKind.Actor }; + + /// + /// The text codes with a number that the MV and MZ message windows read themselves: a variable, an actor, a party + /// member, a color, an icon, a position and a font size. A code with a number and other letters is a plugin's, + /// and may name any id (GR-R9). + /// + public static IReadOnlySet BuiltInTextCodes { get; } = + new HashSet(StringComparer.Ordinal) { "V", "N", "P", "C", "I", "PX", "PY", "FS" }; + + /// The rows for event command . + public static IEnumerable Commands(int code) + { + return CommandsByCode[code]; + } + + /// + /// True when a leaf named (or the elements of an array named so) can be a field + /// reference, so the walker builds its path only then. + /// + public static bool MayBeField(string name) + { + return FieldNames.Contains(name); + } + + /// The rows for a leaf of table whose path has the pattern . + public static IReadOnlyList Fields(string table, string pattern) + { + return FieldsByPlace.TryGetValue((table, pattern), out FieldPlace[]? rows) ? rows : []; + } + + /// True when a leaf named can decide the kind of a field row's id. + public static bool MayBeSibling(string name) + { + return SiblingNames.Contains(name); + } + + /// The rows whose deciding sibling is the leaf of table at . + public static IReadOnlyList FieldsBySibling(string table, string pattern) + { + return FieldsBySiblingPlace.TryGetValue((table, pattern), out FieldPlace[]? rows) ? rows : []; + } + + /// The property name of the id a field row reads (dataId for dropItems[*].dataId). + public static string FieldName(FieldPlace row) + { + return LastName(row.Pattern); + } + + private static CommandPlace Id(IdKind kind, int code, int index, params ParameterTest[] when) + { + return new CommandPlace(code, index, PlaceUse.Id, kind, when); + } + + /// A command that names an id of through a variable (3.11). + private static CommandPlace ByVariable(IdKind kind, int code, params ParameterTest[] when) + { + return new CommandPlace(code, 0, PlaceUse.ByVariable, kind, when); + } + + private static CommandPlace FreeText(int code, int index, params ParameterTest[] when) + { + return new CommandPlace(code, index, PlaceUse.FreeText, null, when); + } + + private static ParameterTest Is(int index, int value) + { + return new ParameterTest(index, value, value); + } + + private static string SiblingPattern(FieldPlace row) + { + int dot = row.Pattern.LastIndexOf('.'); + return (dot < 0 ? "" : row.Pattern[..(dot + 1)]) + row.When!.Sibling; + } + + private static string LastName(string pattern) + { + string trimmed = pattern.EndsWith("[*]", StringComparison.Ordinal) ? pattern[..^3] : pattern; + int dot = trimmed.LastIndexOf('.'); + return dot < 0 ? trimmed : trimmed[(dot + 1)..]; + } +} + +/// What a place of the reference table holds. +internal enum PlaceUse +{ + /// An id of the row's kind; rewritten when that id moves. + Id, + + /// Text a remap cannot rewrite (GR-R9). + FreeText, + + /// A constant Control Variables assigns; with a by-variable row it may be that row's id (3.11). + Constant, + + /// + /// The low end of a random range Control Variables assigns, the next parameter being the high end; with a + /// by-variable row any id in it may be that row's id. + /// + RandomRange, + + /// + /// An id of the row's kind that a variable holds: a transfer or vehicle move to a map, a battle with a troop, an + /// actor of 311 to 318 and 326. + /// + ByVariable +} + +/// +/// One command row: parameter Index of command Code, when every test holds. SecondSlot marks +/// the second equip slot, which holds a weapon for a dual-wield actor. MzOnly marks a row only MZ reads so; +/// on any other engine the id is of no known kind. +/// +internal sealed record CommandPlace( + int Code, + int Index, + PlaceUse Use, + IdKind? Kind, + ParameterTest[] When, + bool SecondSlot = false, + bool MzOnly = false); + +/// Parameter Index holds a whole number from Min to Max. +internal readonly record struct ParameterTest(int Index, int Min, int Max); + +/// +/// One field row: the leaves of Tables whose path pattern is Pattern (relative to the record, or to +/// the root of an object file). A pattern ending in [*] can limit the last index. When asks a sibling +/// property of the leaf for one of its values. +/// +internal sealed record FieldPlace( + string[] Tables, + string Pattern, + IdKind Kind, + FieldTest? When = null, + int MinIndex = 0, + int MaxIndex = int.MaxValue, + bool SecondSlot = false); + +/// The sibling property Sibling holds one of Values. +internal sealed record FieldTest(string Sibling, int[] Values); diff --git a/RPGModder.Core/Merge/RemapPlaces.cs b/RPGModder.Core/Merge/RemapPlaces.cs index 9a46a41..fdccbdb 100644 --- a/RPGModder.Core/Merge/RemapPlaces.cs +++ b/RPGModder.Core/Merge/RemapPlaces.cs @@ -5,7 +5,8 @@ internal static class RemapPlaces { /// /// True when moves the id is about: a map event is the - /// record event:n of its map; a map is its file on * and its MapInfos record. + /// record event:n of its map; a map is its file on * and its MapInfos record; a database + /// record is the record id:n of its file. /// public static bool Settles(IdRemap remap, Collision collision) { @@ -20,7 +21,7 @@ public static bool Settles(IdRemap remap, Collision collision) IdKind.MapEvent => key.File == remap.Scope && key.Record == RecordKey.ForEvent(remap.FromId), IdKind.Map => (key.File == RpgDataSchema.MapKey(remap.FromId) && key.IsWholeFile) || (key.File == RpgDataSchema.MapInfosKey && key.Record == RecordKey.ForIndex(remap.FromId)), - _ => false + _ => RpgDataSchema.DatabaseFileOf(remap.Kind) is { } file && key.File == file && key.Record == RecordKey.ForIndex(remap.FromId) }; } } diff --git a/RPGModder.Core/Merge/RemapPlan.cs b/RPGModder.Core/Merge/RemapPlan.cs index 513bea1..0e761b7 100644 --- a/RPGModder.Core/Merge/RemapPlan.cs +++ b/RPGModder.Core/Merge/RemapPlan.cs @@ -8,7 +8,8 @@ namespace RPGModder.Core.Merge; /// deployed (GR-R12). Offers are moves the planner did not make because the old id appears in a plugin file /// the mod ships (GR-R11); lane A passes them to and appends one when the player /// chooses . Diagnostics holds rules.remap_target_taken, one per -/// recorded entry whose target vanilla now uses; carries them into the plan. +/// recorded entry whose target vanilla now uses, and rules.remap_stale_reference, one per entry in force whose +/// mod now names the old id where a move cannot follow it; carries them into the plan. /// public sealed record RemapPlan( IReadOnlyList Remaps, diff --git a/RPGModder.Core/Merge/RemapTable.cs b/RPGModder.Core/Merge/RemapTable.cs index db03ba6..8e944c1 100644 --- a/RPGModder.Core/Merge/RemapTable.cs +++ b/RPGModder.Core/Merge/RemapTable.cs @@ -3,10 +3,28 @@ namespace RPGModder.Core.Merge; /// One mod's moves, old id to new id, applied together so no move feeds another. internal sealed class RemapTable { - public Dictionary Maps { get; } = new(); + /// The moves of every kind but , whose ids are one per map. + public Dictionary> Global { get; } = new(); /// Event moves by map file key. public Dictionary> Events { get; } = new(StringComparer.Ordinal); - public bool IsEmpty => Maps.Count == 0 && Events.Count == 0; + public bool IsEmpty => Global.Values.All(moves => moves.Count == 0) && Events.Values.All(moves => moves.Count == 0); + + /// The moves of , or null when none of that kind moves. + public Dictionary? MovesOf(IdKind kind) + { + return Global.GetValueOrDefault(kind); + } + + /// The moves an entry of and joins, made on first use. + public Dictionary For(IdKind kind, string scope) + { + if (kind == IdKind.MapEvent) + { + return Events.TryGetValue(scope, out Dictionary? events) ? events : Events[scope] = new Dictionary(); + } + + return Global.TryGetValue(kind, out Dictionary? moves) ? moves : Global[kind] = new Dictionary(); + } } diff --git a/RPGModder.Core/Merge/RpgDataSchema.cs b/RPGModder.Core/Merge/RpgDataSchema.cs index 25d2413..af225d8 100644 --- a/RPGModder.Core/Merge/RpgDataSchema.cs +++ b/RPGModder.Core/Merge/RpgDataSchema.cs @@ -43,18 +43,35 @@ public static class RpgDataSchema /// private const int MapEventIdLimit = 999; + /// + /// The highest database record id the MZ 1.10.0 editor gives (GR-R6): its Change Maximum box stops at 9999, on + /// every database tab. + /// + private const int MzRecordIdLimit = 9999; + + /// + /// The highest database record id a move gives on MV and on an unknown engine (GR-R6). The MV editor was not + /// checked, so this is the lower limit of the editors before it: a move that stays a choice is the safe side. + /// + private const int MvRecordIdLimit = 999; + /// The config save forms 2a decodes (GR-M10); config.save gives merge.config_save_unsupported. private const string MvConfigSave = "config.rpgsave"; private const string MzConfigSave = "config.rmmzsave"; + private const string DataFolder = "data/"; private const string SystemFile = "system.json"; private const string MapInfosFile = "mapinfos.json"; private const string MapPrefix = "data/map"; private const string JsonSuffix = ".json"; /// The policy table name every MapNNN.json shares; no real file name has angle brackets. - private const string MapTable = ""; + internal const string MapTable = ""; + + /// The property of a database record that GR-R7 reads. + private const string NameProperty = "name"; + private const string IdProperty = "id"; private const string PagesPath = "pages"; @@ -65,6 +82,25 @@ public static class RpgDataSchema "config.save" }; + /// The database file of each record kind a remap moves (guide 3.11); the record index is the id. + private static readonly Dictionary DatabaseFiles = new() + { + [IdKind.Item] = "items.json", + [IdKind.Weapon] = "weapons.json", + [IdKind.Armor] = "armors.json", + [IdKind.Skill] = "skills.json", + [IdKind.State] = "states.json", + [IdKind.Enemy] = "enemies.json", + [IdKind.Troop] = "troops.json", + [IdKind.CommonEvent] = "commonevents.json", + [IdKind.Actor] = "actors.json", + [IdKind.Class] = "classes.json", + [IdKind.Animation] = "animations.json", + [IdKind.Tileset] = "tilesets.json" + }; + + private static readonly Dictionary DatabaseKinds = DatabaseFiles.ToDictionary(pair => pair.Value, pair => pair.Key, StringComparer.Ordinal); + /// The database files of guide 3.3: an array whose index is the record id. private static readonly HashSet RecordFiles = new(StringComparer.Ordinal) { @@ -323,19 +359,104 @@ internal static string MapKey(int id) } /// - /// The highest id a remap may give, or null for a kind step 1 does not remap (GR-R6). A null + /// The highest id a remap may give, or null for a kind no step so far remaps (GR-R6). A null /// engine gets MV's limits. /// internal static int? RemapLimit(IdKind kind, RpgMakerEngine? engine) { + bool mz = engine == RpgMakerEngine.MZ; return kind switch { - IdKind.Map => engine == RpgMakerEngine.MZ ? MzMapIdLimit : MvMapIdLimit, + IdKind.Map => mz ? MzMapIdLimit : MvMapIdLimit, IdKind.MapEvent => MapEventIdLimit, + _ when DatabaseFiles.ContainsKey(kind) => mz ? MzRecordIdLimit : MvRecordIdLimit, _ => null }; } + /// True for the kinds a remap moves: map events, maps and the twelve database kinds (steps 1 and 2). + internal static bool IsRemappable(IdKind kind) + { + return kind is IdKind.MapEvent or IdKind.Map || DatabaseFiles.ContainsKey(kind); + } + + /// The key of the database file that holds , or null for a kind with no such file. + internal static string? DatabaseFileOf(IdKind kind) + { + return DatabaseFiles.TryGetValue(kind, out string? name) ? DataFolder + name : null; + } + + /// The record kind of a database file directly inside data/; MapInfos.json is not one. + internal static IdKind? DatabaseKindOf(string fileKey) + { + if (!fileKey.StartsWith(DataFolder, StringComparison.Ordinal) || fileKey.IndexOf('/', DataFolder.Length) >= 0) + { + return null; + } + + return DatabaseKinds.TryGetValue(fileKey[DataFolder.Length..], out IdKind kind) ? kind : null; + } + + /// + /// GR-R7, the shape half of filler: is a database record shaped as the blank the MZ or + /// the MV editor writes when a maximum is raised. Every property but id matches the blank's; a property the + /// blank lacks is empty, and one the record lacks counts as the blank's. adds the use half. + /// + internal static bool HasBlankShape(string fileKey, JToken? record) + { + if (DatabaseKindOf(fileKey) is null || + record is not JObject item || + item[NameProperty] is JValue { Value: string { Length: > 0 } }) + { + return false; + } + + IEnumerable properties = item.Properties().Where(property => property.Name != IdProperty).ToList(); + return BlankRecords.For(FileName(fileKey), RpgMakerEngine.MZ) is { } mz && PropertiesMatch(properties, mz) || + BlankRecords.For(FileName(fileKey), RpgMakerEngine.MV) is { } mv && PropertiesMatch(properties, mv); + } + + private static bool PropertiesMatch(IEnumerable properties, JObject blank) + { + return properties.All(property => blank[property.Name] is { } expected ? MatchesBlank(property.Value, expected) : IsEmpty(property.Value)); + } + + private static bool MatchesBlank(JToken token, JToken blank) + { + return token switch + { + JObject item when blank is JObject shape => PropertiesMatch(item.Properties(), shape), + JArray list when blank is JArray shape => + list.Count == 0 || (list.Count == shape.Count && list.Zip(shape).All(pair => MatchesBlank(pair.First, pair.Second))), + _ => JToken.DeepEquals(token, blank) || (IsEmpty(token) && IsEmpty(blank)) + }; + } + + /// Null, an empty string, false, zero, or a list or object with nothing in it. + private static bool IsEmpty(JToken token) + { + return token switch + { + JValue { Type: JTokenType.Null or JTokenType.Undefined } => true, + JValue { Value: string text } => text.Length == 0, + JValue { Value: bool flag } => !flag, + JValue { Value: long whole } => whole == 0, + JValue { Value: double real } => real == 0, + JValue { Value: decimal exact } => exact == 0, + JContainer container => !container.HasValues, + _ => false + }; + } + + /// + /// GR-R8: a copy of the record that fills a hole in , with id 0, or null + /// for a file whose holes stay null (MapInfos.json, a map's events, any file that is not a database file). + /// + internal static JObject? BlankRecord(string fileKey, RpgMakerEngine? engine) + { + return DatabaseKindOf(fileKey) is null ? null : BlankRecords.For(FileName(fileKey), engine); + } + /// /// A page setting of a map event (seam 11.1): the pages list itself, or anything under one page except /// its command list, which is a LogicClash place. @@ -416,7 +537,8 @@ private static bool LooksLikeRecords(JArray array) return anyRecord; } - private static string TableOf(string fileKey) + /// The name of the policy and reference tables for a file: for a map, else the file name. + internal static string TableOf(string fileKey) { return IsMapFile(fileKey) ? MapTable : FileName(fileKey); } diff --git a/RPGModder.Core/Operations/DiagnosticCodes.cs b/RPGModder.Core/Operations/DiagnosticCodes.cs index 1e0bc4a..b3b0deb 100644 --- a/RPGModder.Core/Operations/DiagnosticCodes.cs +++ b/RPGModder.Core/Operations/DiagnosticCodes.cs @@ -48,6 +48,7 @@ public static class DiagnosticCodes public const string RulesRemapApplied = "rules.remap_applied"; public const string RulesRemapUnchecked = "rules.remap_unchecked"; public const string RulesRemapTargetTaken = "rules.remap_target_taken"; + public const string RulesRemapStaleReference = "rules.remap_stale_reference"; public const string RulesSwitchBandMoved = "rules.switch_band_moved"; public const string RulesSwitchBandExhausted = "rules.switch_band_exhausted"; diff --git a/RPGModder.Tests/Merge/BlankRecordTests.cs b/RPGModder.Tests/Merge/BlankRecordTests.cs new file mode 100644 index 0000000..33c4a94 --- /dev/null +++ b/RPGModder.Tests/Merge/BlankRecordTests.cs @@ -0,0 +1,259 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Services; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +/// TST-15, step 2: filler (GR-R7) and blank records (GR-R8). Content is invented (TST-2). +public sealed class BlankRecordTests +{ + /// + /// The record the RPG Maker MZ 1.10.0 editor wrote for each database tab when its maximum was raised by one, in a + /// project made from the default new project, with id set to 0 and the editor's key order. + /// + private static readonly Dictionary MzEditorRecords = new(StringComparer.Ordinal) + { + ["actors.json"] = + """{"id":0,"battlerName":"","characterIndex":0,"characterName":"","classId":1,"equips":[0,0,0,0,0],"faceIndex":0,"faceName":"","traits":[],"initialLevel":1,"maxLevel":99,"name":"","nickname":"","note":"","profile":""}""", + ["animations.json"] = + """{"id":0,"displayType":0,"effectName":"","flashTimings":[],"name":"","offsetX":0,"offsetY":0,"rotation":{"x":0,"y":0,"z":0},"scale":100,"soundTimings":[],"speed":100,"alignBottom":false}""", + ["armors.json"] = + """{"id":0,"atypeId":0,"description":"","etypeId":2,"traits":[{"code":22,"dataId":1,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0}""", + ["classes.json"] = + """{"id":0,"expParams":[30,20,30,30],"traits":[{"code":23,"dataId":0,"value":1},{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":22,"dataId":2,"value":0.04},{"code":41,"dataId":1,"value":0},{"code":51,"dataId":1,"value":0},{"code":52,"dataId":1,"value":0}],"learnings":[],"name":"","note":"","params":[[1,450,500,550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000,2050,2100,2150,2200,2250,2300,2350,2400,2450,2500,2550,2600,2650,2700,2750,2800,2850,2900,2950,3000,3050,3100,3150,3200,3250,3300,3350,3400,3450,3500,3550,3600,3650,3700,3750,3800,3850,3900,3950,4000,4050,4100,4150,4200,4250,4300,4350,4400,4450,4500,4550,4600,4650,4700,4750,4800,4850,4900,4950,5000,5050,5100,5150,5200,5250,5300,5350],[0,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370,380,390,400,410,420,430,440,450,460,470,480,490,500,510,520,530,540,550,560,570,580,590,600,610,620,630,640,650,660,670,680,690,700,710,720,730,740,750,760,770,780,790,800,810,820,830,840,850,860,870,880,890,900,910,920,930,940,950,960,970,980,990,1000,1010,1020,1030,1040,1050,1060,1070],[1,16,18,19,20,21,23,24,25,26,28,29,30,31,33,34,35,36,38,39,40,41,43,44,45,46,48,49,50,51,53,54,55,56,58,59,60,61,63,64,65,66,68,69,70,71,73,74,75,76,77,79,80,81,82,84,85,86,87,89,90,91,92,94,95,96,97,99,100,101,102,104,105,106,107,109,110,111,112,114,115,116,117,119,120,121,122,124,125,126,127,129,130,131,132,134,135,136,137,138],[0,16,18,19,20,21,23,24,25,26,28,29,30,31,33,34,35,36,38,39,40,41,43,44,45,46,48,49,50,51,53,54,55,56,58,59,60,61,63,64,65,66,68,69,70,71,73,74,75,76,77,79,80,81,82,84,85,86,87,89,90,91,92,94,95,96,97,99,100,101,102,104,105,106,107,109,110,111,112,114,115,116,117,119,120,121,122,124,125,126,127,129,130,131,132,134,135,136,137,138],[0,16,18,19,20,21,23,24,25,26,28,29,30,31,33,34,35,36,38,39,40,41,43,44,45,46,48,49,50,51,53,54,55,56,58,59,60,61,63,64,65,66,68,69,70,71,73,74,75,76,77,79,80,81,82,84,85,86,87,89,90,91,92,94,95,96,97,99,100,101,102,104,105,106,107,109,110,111,112,114,115,116,117,119,120,121,122,124,125,126,127,129,130,131,132,134,135,136,137,138],[0,16,18,19,20,21,23,24,25,26,28,29,30,31,33,34,35,36,38,39,40,41,43,44,45,46,48,49,50,51,53,54,55,56,58,59,60,61,63,64,65,66,68,69,70,71,73,74,75,76,77,79,80,81,82,84,85,86,87,89,90,91,92,94,95,96,97,99,100,101,102,104,105,106,107,109,110,111,112,114,115,116,117,119,120,121,122,124,125,126,127,129,130,131,132,134,135,136,137,138],[0,32,35,37,40,42,45,47,50,52,55,57,60,62,65,67,70,72,75,77,80,82,85,87,90,92,95,97,100,102,105,107,110,112,115,117,120,122,125,127,130,132,135,137,140,142,145,147,150,152,155,157,160,162,165,167,170,172,175,177,180,182,185,187,190,192,195,197,200,202,205,207,210,212,215,217,220,222,225,227,230,232,235,237,240,242,245,247,250,252,255,257,260,262,265,267,270,272,275,277],[0,32,35,37,40,42,45,47,50,52,55,57,60,62,65,67,70,72,75,77,80,82,85,87,90,92,95,97,100,102,105,107,110,112,115,117,120,122,125,127,130,132,135,137,140,142,145,147,150,152,155,157,160,162,165,167,170,172,175,177,180,182,185,187,190,192,195,197,200,202,205,207,210,212,215,217,220,222,225,227,230,232,235,237,240,242,245,247,250,252,255,257,260,262,265,267,270,272,275,277]]}""", + ["commonevents.json"] = + """{"id":0,"list":[{"code":0,"indent":0,"parameters":[]}],"name":"","switchId":1,"trigger":0}""", + ["enemies.json"] = + """{"id":0,"actions":[{"conditionParam1":0,"conditionParam2":0,"conditionType":0,"rating":5,"skillId":1}],"battlerHue":0,"battlerName":"","dropItems":[{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0},{"dataId":1,"denominator":1,"kind":0}],"exp":0,"traits":[{"code":22,"dataId":0,"value":0.95},{"code":22,"dataId":1,"value":0.05},{"code":31,"dataId":1,"value":0}],"gold":0,"name":"","note":"","params":[100,0,10,10,10,10,10,10]}""", + ["items.json"] = + """{"id":0,"animationId":0,"consumable":true,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"itypeId":1,"name":"","note":"","occasion":0,"price":0,"repeats":1,"scope":7,"speed":0,"successRate":100,"tpGain":0}""", + ["skills.json"] = + """{"id":0,"animationId":0,"damage":{"critical":false,"elementId":0,"formula":"0","type":0,"variance":20},"description":"","effects":[],"hitType":0,"iconIndex":0,"message1":"","message2":"","mpCost":0,"name":"","note":"","occasion":0,"repeats":1,"requiredWtypeId1":0,"requiredWtypeId2":0,"scope":1,"speed":0,"stypeId":1,"successRate":100,"tpCost":0,"tpGain":0,"messageType":1}""", + ["states.json"] = + """{"id":0,"autoRemovalTiming":0,"chanceByDamage":100,"iconIndex":0,"maxTurns":1,"message1":"","message2":"","message3":"","message4":"","minTurns":1,"motion":0,"name":"","note":"","overlay":0,"priority":50,"removeAtBattleEnd":false,"removeByDamage":false,"removeByRestriction":false,"removeByWalking":false,"restriction":0,"stepsToRemove":100,"traits":[],"messageType":1}""", + ["tilesets.json"] = + """{"id":0,"flags":[16],"mode":1,"name":"","note":"","tilesetNames":["","","","","","","","",""]}""", + ["troops.json"] = + """{"id":0,"members":[],"name":"","pages":[{"conditions":{"actorHp":50,"actorId":1,"actorValid":false,"enemyHp":50,"enemyIndex":0,"enemyValid":false,"switchId":1,"switchValid":false,"turnA":0,"turnB":0,"turnEnding":false,"turnValid":false},"list":[{"code":0,"indent":0,"parameters":[]}],"span":0}]}""", + ["weapons.json"] = + """{"id":0,"animationId":0,"description":"","etypeId":1,"traits":[{"code":31,"dataId":1,"value":0},{"code":22,"dataId":0,"value":0}],"iconIndex":0,"name":"","note":"","params":[0,0,0,0,0,0,0,0],"price":0,"wtypeId":0}""" + }; + + public static TheoryData DatabaseFiles => new(MzEditorRecords.Keys); + + [Theory] + [MemberData(nameof(DatabaseFiles))] + public void BlankRecord_OnMz_IsTheEditorsRecordInItsKeyOrder(string file) + { + JObject blank = RpgDataSchema.BlankRecord("data/" + file, RpgMakerEngine.MZ)!; + var editor = JObject.Parse(MzEditorRecords[file]); + + Assert.True(JToken.DeepEquals(editor, blank), file); + Assert.Equal(editor.Properties().Select(property => property.Name), blank.Properties().Select(property => property.Name)); + } + + [Theory] + [InlineData(null)] + [InlineData(RpgMakerEngine.MV)] + public void BlankRecord_OnMvOrAnUnknownEngine_DropsWhatMvLacksAndUsesMvAnimations(RpgMakerEngine? engine) + { + foreach (string file in MzEditorRecords.Keys.Where(name => name != "animations.json")) + { + var expected = JObject.Parse(MzEditorRecords[file]); + expected.Remove("messageType"); + Assert.True(JToken.DeepEquals(expected, RpgDataSchema.BlankRecord("data/" + file, engine)), file); + } + + JObject animation = RpgDataSchema.BlankRecord("data/animations.json", engine)!; + Assert.Equal( + "{\"id\":0,\"animation1Hue\":0,\"animation1Name\":\"\",\"animation2Hue\":0,\"animation2Name\":\"\",\"frames\":[[]],\"name\":\"\",\"position\":1,\"timings\":[]}", + animation.ToString(Newtonsoft.Json.Formatting.None)); + } + + [Theory] + [InlineData("data/mapinfos.json")] + [InlineData("data/map001.json")] + [InlineData("data/system.json")] + [InlineData("data/quests.json")] + public void BlankRecord_ForAFileThatKeepsItsHoles_IsNull(string file) + { + Assert.Null(RpgDataSchema.BlankRecord(file, RpgMakerEngine.MZ)); + } + + [Fact] + public void BlankRecord_EachCall_IsANewObject() + { + JObject first = RpgDataSchema.BlankRecord("data/items.json", RpgMakerEngine.MZ)!; + first["name"] = "Changed"; + + Assert.Equal("", RpgDataSchema.BlankRecord("data/items.json", RpgMakerEngine.MZ)!["name"]!.Value()); + } + + public static TheoryData BlankShapeCases => new() + { + { "data/items.json", "{\"id\":3,\"name\":\"\"}", true }, + { "data/items.json", "{\"id\":3,\"name\":\"\",\"note\":\"\",\"extra\":0,\"more\":[]}", true }, + { "data/items.json", "{\"id\":3,\"name\":\"\",\"price\":5}", false }, + { "data/items.json", "{\"id\":3,\"name\":\"\",\"extra\":\"x\"}", false }, + { "data/items.json", "{\"id\":3,\"name\":\"Herb\"}", false }, + { "data/items.json", "{\"id\":3,\"price\":5}", false }, + { "data/actors.json", "{\"id\":3,\"name\":\"\",\"battlerName\":\"Hero\"}", false }, + { "data/actors.json", "{\"id\":3,\"name\":\"\",\"equips\":[]}", true }, + { "data/commonevents.json", "{\"id\":3,\"name\":\"\",\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}]}", true }, + { "data/commonevents.json", "{\"id\":3,\"name\":\"\",\"list\":[{\"code\":117,\"indent\":0,\"parameters\":[1]},{\"code\":0,\"indent\":0,\"parameters\":[]}]}", false }, + { "data/commonevents.json", "{\"id\":3,\"name\":\"\",\"list\":[{\"code\":117,\"indent\":0,\"parameters\":[1]}]}", false }, + { "data/commonevents.json", "{\"id\":3,\"name\":\"\",\"list\":[]}", true }, + { "data/troops.json", "{\"id\":3,\"name\":\"\",\"pages\":[{\"list\":[{\"code\":0,\"indent\":0,\"parameters\":[]}],\"span\":0}]}", true }, + { "data/troops.json", "{\"id\":3,\"name\":\"\",\"pages\":[{\"list\":[{\"code\":0}]},{\"list\":[{\"code\":101},{\"code\":0}]}]}", false }, + + // Maps, map events and the map tree are never filler. + { "data/mapinfos.json", "{\"id\":3,\"name\":\"\"}", false }, + { "data/map001.json", "{\"id\":3,\"name\":\"\",\"pages\":[]}", false } + }; + + [Theory] + [MemberData(nameof(BlankShapeCases))] + public void HasBlankShape_FollowsTheRuleText(string file, string record, bool blank) + { + Assert.Equal(blank, RpgDataSchema.HasBlankShape(file, JToken.Parse(record))); + } + + [Theory] + [MemberData(nameof(DatabaseFiles))] + public void HasBlankShape_EveryEditorBlank_IsTrue(string file) + { + Assert.True(RpgDataSchema.HasBlankShape("data/" + file, JObject.Parse(MzEditorRecords[file]))); + } + + [Theory] + [MemberData(nameof(DatabaseFiles))] + public void HasBlankShape_EveryMvBlank_IsTrue(string file) + { + JObject blank = RpgDataSchema.BlankRecord("data/" + file, RpgMakerEngine.MV)!; + blank["id"] = 3; + + Assert.True(RpgDataSchema.HasBlankShape("data/" + file, blank)); + } + + private static string ItemsAdding(params JToken[] records) + { + return EditItems(items => + { + foreach (JToken record in records) + { + items.Add(record); + } + }); + } + + private static JObject Filler(int id, int price = 0) + { + JObject record = RpgDataSchema.BlankRecord("data/items.json", RpgMakerEngine.MZ)!; + record["id"] = id; + record["price"] = price; + return record; + } + + [Fact] + public void Compose_FillerAgainstARealRecord_YieldsWithoutAClash() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource filler = FileMod("a-tin", Items, ItemsAdding(Filler(3)), 1); + ModSource real = FileMod("b-oak", Items, ItemsAdding(new JObject { ["id"] = 3, ["name"] = "Herb" }), 0); + + MergePlan plan = Compose(bases, filler, real); + + Assert.Empty(plan.Collisions); + Assert.True(plan.IsDeployable); + MergedOp kept = Assert.Single(plan.Ops); + Assert.Equal(["b-oak"], kept.ModIds); + Assert.Equal("Herb", kept.Op.Value!["name"]!.Value()); + } + + [Fact] + public void Compose_FillerFromTwoMods_IsNoClashAndKeepsTheLatestInProfileOrder() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource early = FileMod("a-tin", Items, ItemsAdding(Filler(3)), 0); + ModSource late = FileMod("b-oak", Items, ItemsAdding(new JObject { ["id"] = 3, ["name"] = "" }), 1); + + MergePlan plan = Compose(bases, early, late); + + Assert.Empty(plan.Collisions); + Assert.Equal(["b-oak"], Assert.Single(plan.Ops).ModIds); + } + + [Fact] + public void Compose_BlankShapedRecordWithData_IsRealAndClashes() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource priced = FileMod("a-tin", Items, ItemsAdding(Filler(3, price: 5)), 0); + ModSource herb = FileMod("b-oak", Items, ItemsAdding(new JObject { ["id"] = 3, ["name"] = "Herb" }), 1); + + Collision clash = Assert.Single(Compose(bases, priced, herb).Collisions); + + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.Equal(["a-tin", "b-oak"], clash.ModIds); + } + + [Fact] + public void Compose_TwoRealRecordsBesideFiller_StillClash() + { + BaseFileSet bases = Bases(Base(Items, VanillaItems)); + ModSource filler = FileMod("a-tin", Items, ItemsAdding(Filler(3)), 0); + ModSource herb = FileMod("b-oak", Items, ItemsAdding(new JObject { ["id"] = 3, ["name"] = "Herb" }), 1); + ModSource salve = FileMod("c-elm", Items, ItemsAdding(new JObject { ["id"] = 3, ["name"] = "Salve" }), 2); + + Collision clash = Assert.Single(Compose(bases, filler, herb, salve).Collisions); + + Assert.Equal(CollisionKind.IdClash, clash.Kind); + Assert.Equal(["b-oak", "c-elm"], clash.ModIds); + } + + [Theory] + [InlineData(RpgMakerEngine.MZ, true)] + [InlineData(RpgMakerEngine.MV, false)] + [InlineData(null, false)] + public void Write_HoleBeforeAnAddedRecord_TakesTheBlankRecordOfTheEngine(RpgMakerEngine? engine, bool messageType) + { + const string skills = "data/Skills.json"; + BaseFileSet bases = Bases(Base(skills, "[null,{\"id\":1,\"name\":\"Strike\"}]")); + ModSource mod = FileMod("a-tin", skills, "[null,{\"id\":1,\"name\":\"Strike\"},null,{\"id\":3,\"name\":\"Flare\"}]"); + + MergePlan plan = Compose(bases, mod); + var written = JArray.Parse(Assert.Single(MergedFileWriter.Write(plan, bases, null, engine)).Text!); + + Assert.Equal(JTokenType.Null, written[0].Type); + var hole = (JObject)written[2]; + Assert.Equal(2, hole["id"]!.Value()); + Assert.Equal("", hole["name"]!.Value()); + Assert.Equal(messageType, hole.ContainsKey("messageType")); + Assert.Equal("Flare", written[3]["name"]!.Value()); + } + + [Fact] + public void Write_MapTreeAndMapEvents_KeepTheirHoles() + { + const string infos = "data/MapInfos.json"; + const string infosText = "[null,{\"id\":1,\"name\":\"A\"},null,{\"id\":3,\"name\":\"C\"}]"; + string mapText = EditMap(map => map["events"]![1] = JValue.CreateNull()); + BaseFileSet bases = Bases( + Base(infos, "[null,{\"id\":1,\"name\":\"A\"},{\"id\":2,\"name\":\"B\"},{\"id\":3,\"name\":\"C\"}]"), + Base(Map, VanillaMap)); + ModSource mod = new( + "a-tin", + 0, + [ + new ModFile(infos, "files/MapInfos.json", infosText, Hash(infosText)), + new ModFile(Map, "files/Map001.json", mapText, Hash(mapText)) + ], + [], + []); + + IReadOnlyList files = MergedFileWriter.Write(Compose(bases, mod), bases, null, RpgMakerEngine.MZ); + + Assert.Equal(JTokenType.Null, JArray.Parse(files.Single(file => file.File == "data/mapinfos.json").Text!)[2].Type); + Assert.Equal(JTokenType.Null, JObject.Parse(files.Single(file => file.File == "data/map001.json").Text!)["events"]![1]!.Type); + } +} diff --git a/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs b/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs new file mode 100644 index 0000000..db7c745 --- /dev/null +++ b/RPGModder.Tests/Merge/IdRemapDatabaseTests.cs @@ -0,0 +1,1054 @@ +using Newtonsoft.Json.Linq; +using RPGModder.Core.Merge; +using RPGModder.Core.Models; +using RPGModder.Core.Operations; +using RPGModder.Core.Services; +using static RPGModder.Tests.Merge.MergeTestKit; + +namespace RPGModder.Tests.Merge; + +/// TST-15, step 2: database records. Content is invented (TST-2). +public sealed class IdRemapDatabaseTests +{ + private const string Generic = "[null,{\"id\":1,\"name\":\"One\"},{\"id\":2,\"name\":\"Two\"}]"; + + private static readonly Dictionary FileOfKind = new() + { + [IdKind.Item] = "data/Items.json", + [IdKind.Weapon] = "data/Weapons.json", + [IdKind.Armor] = "data/Armors.json", + [IdKind.Skill] = "data/Skills.json", + [IdKind.State] = "data/States.json", + [IdKind.Enemy] = "data/Enemies.json", + [IdKind.Troop] = "data/Troops.json", + [IdKind.CommonEvent] = "data/CommonEvents.json", + [IdKind.Actor] = "data/Actors.json", + [IdKind.Class] = "data/Classes.json", + [IdKind.Animation] = "data/Animations.json", + [IdKind.Tileset] = "data/Tilesets.json" + }; + + /// + /// A game: the twelve database files with two records each and no trait 55 (so no actor dual-wields), the map + /// and System. overrides replace a file's text, or drop the file when the text is null. + /// + private sealed class Game + { + private readonly Dictionary _vanilla = new(StringComparer.Ordinal); + + public Game(params (string Path, string? Text)[] overrides) + { + foreach (string file in FileOfKind.Values) + { + _vanilla[file] = Generic; + } + + _vanilla[Map] = VanillaMap; + _vanilla[SystemFile] = VanillaSystem; + foreach ((string path, string? text) in overrides) + { + if (text is null) + { + _vanilla.Remove(path); + } + else + { + _vanilla[path] = text; + } + } + + Bases = MergeTestKit.Bases(_vanilla.Select(pair => Base(pair.Key, pair.Value)).ToArray()); + } + + public BaseFileSet Bases { get; } + + /// + /// A mod whose files are vanilla's with applied; it ships the files it touched. A file + /// vanilla lacks starts as the vanilla map for a map file and as an empty database file otherwise. + /// + public RemapMod Mod(string modId, int priority, Action> edit, params string[] scripts) + { + var files = new Dictionary(StringComparer.Ordinal); + edit(path => + { + if (!files.TryGetValue(path, out JToken? root)) + { + string? text = _vanilla.GetValueOrDefault(path); + root = JToken.Parse(text ?? (path.StartsWith("data/Map0", StringComparison.Ordinal) ? VanillaMap : "[null]")); + files[path] = root; + } + + return root; + }); + + var source = new ModSource( + modId, + priority, + files.Select(pair => + { + string text = pair.Value.ToString(); + return new ModFile(pair.Key, "files/" + Path.GetFileName(pair.Key), text, Hash(text)); + }).ToList(), + [], + []); + return new RemapMod(ChangeSetBuilder.Build(source, Bases), true, scripts); + } + + /// a-tin adds record 3 "A" of , b-oak adds record 3 "B" and makes its own edits. + public (RemapMod A, RemapMod B) Clash( + IdKind kind, + Action>? editB = null, + Action>? editA = null, + params string[] scriptsB) + { + RemapMod a = Mod("a-tin", 0, file => + { + AddRecord(file(FileOfKind[kind]), 3, "A"); + editA?.Invoke(file); + }); + RemapMod b = Mod("b-oak", 1, file => + { + AddRecord(file(FileOfKind[kind]), 3, "B"); + editB?.Invoke(file); + }, scriptsB); + return (a, b); + } + } + + private static void AddRecord(JToken file, int id, string name) + { + var records = (JArray)file; + while (records.Count <= id) + { + records.Add(JValue.CreateNull()); + } + + records[id] = new JObject { ["id"] = id, ["name"] = name }; + } + + private static JObject Command(int code, params object[] parameters) + { + return new JObject { ["code"] = code, ["indent"] = 0, ["parameters"] = new JArray(parameters) }; + } + + private static Action> InEvent(JObject command) + { + return file => ((JArray)file(Map)["events"]![1]!["pages"]![0]!["list"]!).Insert(0, command.DeepClone()); + } + + /// Sets the token at ; its last step is a property name, created when missing. + private static Action> Set(string file, string path, string json) + { + return files => + { + JToken root = files(file); + int dot = path.LastIndexOf('.'); + var parent = (JObject)(dot < 0 ? root : root.SelectToken(path[..dot])!); + parent[path[(dot + 1)..]] = JToken.Parse(json); + }; + } + + private static RemapPlan Plan(Game game, params RemapMod[] mods) + { + return Plan(null, game, mods); + } + + private static RemapPlan Plan(RpgMakerEngine? engine, Game game, params RemapMod[] mods) + { + return IdRemapPlanner.Plan(mods, [], [], game.Bases, engine); + } + + private static MergePlan ComposeRemapped(RemapPlan plan, Game game, params RemapMod[] mods) + { + List sets = mods + .Where(mod => mod.Enabled) + .Select(mod => IdRemapper.Apply(mod.ChangeSet, plan.Remaps)) + .ToList(); + return Composer.Compose(sets, [], game.Bases, plan); + } + + private static JToken Written(MergePlan merged, Game game, string file) + { + IReadOnlyList files = MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ); + return JToken.Parse(files.Single(item => string.Equals(item.File, file, StringComparison.OrdinalIgnoreCase)).Text!); + } + + private static string Entry(IdRemap remap) + { + return $"{remap.ModId}|{remap.Kind}|{remap.Scope}|{remap.FromId}>{remap.ToId}"; + } + + private static string Flat(JToken? token) + { + return token!.ToString(Newtonsoft.Json.Formatting.None); + } + + public static TheoryData DatabaseKinds => new(FileOfKind.Keys); + + [Theory] + [MemberData(nameof(DatabaseKinds))] + public void Plan_TwoModsAddingOneRecordId_MovesTheLaterModAndBothDeploy(IdKind kind) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(kind); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal([$"b-oak|{kind}||3>4"], plan.NewEntries.Select(Entry)); + Assert.Empty(merged.Collisions); + Assert.True(merged.IsDeployable); + JToken records = Written(merged, game, FileOfKind[kind]); + Assert.Equal("{\"id\":3,\"name\":\"A\"}", Flat(records[3])); + Assert.Equal("{\"id\":4,\"name\":\"B\"}", Flat(records[4])); + } + + public static TheoryData CommandRows => new() + { + { IdKind.Item, 126, "[3,0,0,1]", "[4,0,0,1]" }, + { IdKind.Item, 111, "[8,3,false]", "[8,4,false]" }, + { IdKind.Item, 122, "[1,1,0,3,0,3,0]", "[1,1,0,3,0,4,0]" }, + { IdKind.Item, 302, "[0,3,0,0,false]", "[0,4,0,0,false]" }, + { IdKind.Item, 605, "[0,3,0,0]", "[0,4,0,0]" }, + { IdKind.Weapon, 127, "[3,0,0,1,false]", "[4,0,0,1,false]" }, + { IdKind.Weapon, 111, "[9,3,false]", "[9,4,false]" }, + { IdKind.Weapon, 111, "[4,1,4,3]", "[4,1,4,4]" }, + { IdKind.Weapon, 122, "[1,1,0,3,1,3,0]", "[1,1,0,3,1,4,0]" }, + { IdKind.Weapon, 302, "[1,3,0,0,false]", "[1,4,0,0,false]" }, + { IdKind.Weapon, 605, "[1,3,0,0]", "[1,4,0,0]" }, + { IdKind.Weapon, 319, "[1,1,3]", "[1,1,4]" }, + { IdKind.Armor, 128, "[3,0,0,1,false]", "[4,0,0,1,false]" }, + { IdKind.Armor, 111, "[10,3,false]", "[10,4,false]" }, + { IdKind.Armor, 111, "[4,1,5,3]", "[4,1,5,4]" }, + { IdKind.Armor, 122, "[1,1,0,3,2,3,0]", "[1,1,0,3,2,4,0]" }, + { IdKind.Armor, 302, "[2,3,0,0,false]", "[2,4,0,0,false]" }, + { IdKind.Armor, 605, "[2,3,0,0]", "[2,4,0,0]" }, + { IdKind.Armor, 319, "[1,2,3]", "[1,2,4]" }, + { IdKind.Armor, 319, "[1,3,3]", "[1,3,4]" }, + { IdKind.Skill, 318, "[0,1,0,3]", "[0,1,0,4]" }, + { IdKind.Skill, 339, "[0,1,3,-1]", "[0,1,4,-1]" }, + { IdKind.Skill, 111, "[4,1,3,3]", "[4,1,3,4]" }, + { IdKind.State, 313, "[0,1,0,3]", "[0,1,0,4]" }, + { IdKind.State, 333, "[0,0,3]", "[0,0,4]" }, + { IdKind.State, 111, "[4,1,6,3]", "[4,1,6,4]" }, + { IdKind.State, 111, "[5,0,1,3]", "[5,0,1,4]" }, + { IdKind.Enemy, 336, "[0,3,false]", "[0,4,false]" }, + { IdKind.Troop, 301, "[0,3,false,false]", "[0,4,false,false]" }, + { IdKind.CommonEvent, 117, "[3]", "[4]" }, + { IdKind.Actor, 129, "[3,0,true]", "[4,0,true]" }, + { IdKind.Actor, 303, "[3,8]", "[4,8]" }, + { IdKind.Actor, 111, "[4,3,0]", "[4,4,0]" }, + { IdKind.Actor, 122, "[1,1,0,3,3,3,0]", "[1,1,0,3,3,4,0]" }, + { IdKind.Actor, 311, "[0,3,0,0,10,false]", "[0,4,0,0,10,false]" }, + { IdKind.Actor, 312, "[0,3,0,0,10]", "[0,4,0,0,10]" }, + { IdKind.Actor, 313, "[0,3,0,1]", "[0,4,0,1]" }, + { IdKind.Actor, 314, "[0,3]", "[0,4]" }, + { IdKind.Actor, 315, "[0,3,0,0,10,false]", "[0,4,0,0,10,false]" }, + { IdKind.Actor, 316, "[0,3,0,0,1,false]", "[0,4,0,0,1,false]" }, + { IdKind.Actor, 317, "[0,3,0,0,0,1]", "[0,4,0,0,0,1]" }, + { IdKind.Actor, 318, "[0,3,0,1]", "[0,4,0,1]" }, + { IdKind.Actor, 326, "[0,3,0,0,10]", "[0,4,0,0,10]" }, + { IdKind.Actor, 319, "[3,1,1]", "[4,1,1]" }, + { IdKind.Actor, 320, "[3,\"Ann\"]", "[4,\"Ann\"]" }, + { IdKind.Actor, 321, "[3,1,false]", "[4,1,false]" }, + { IdKind.Actor, 322, "[3,\"\",0,\"\",0,\"\"]", "[4,\"\",0,\"\",0,\"\"]" }, + { IdKind.Actor, 324, "[3,\"Bold\"]", "[4,\"Bold\"]" }, + { IdKind.Actor, 325, "[3,\"Tall\"]", "[4,\"Tall\"]" }, + { IdKind.Actor, 339, "[1,3,1,-1]", "[1,4,1,-1]" }, + { IdKind.Class, 321, "[1,3,false]", "[1,4,false]" }, + { IdKind.Class, 111, "[4,1,2,3]", "[4,1,2,4]" }, + { IdKind.Animation, 212, "[0,3,false]", "[0,4,false]" }, + { IdKind.Animation, 337, "[-1,3,false]", "[-1,4,false]" }, + { IdKind.Tileset, 282, "[3]", "[4]" }, + + // Same codes, other forms: the 3 is another kind's id, a variable, an enemy index or a constant. + { IdKind.Item, 122, "[1,1,0,3,1,3,0]", "[1,1,0,3,1,3,0]" }, + { IdKind.Item, 302, "[1,3,0,0,false]", "[1,3,0,0,false]" }, + { IdKind.Item, 122, "[1,1,0,0,3]", "[1,1,0,0,3]" }, + { IdKind.Armor, 319, "[1,1,3]", "[1,1,3]" }, + { IdKind.Skill, 111, "[4,1,6,3]", "[4,1,6,3]" }, + { IdKind.State, 111, "[4,1,5,3]", "[4,1,5,3]" }, + { IdKind.Actor, 311, "[1,3,0,0,10,false]", "[1,3,0,0,10,false]" }, + { IdKind.Actor, 312, "[1,3,0,0,10]", "[1,3,0,0,10]" }, + { IdKind.Actor, 313, "[1,3,0,1]", "[1,3,0,1]" }, + { IdKind.Actor, 314, "[1,3]", "[1,3]" }, + { IdKind.Actor, 315, "[1,3,0,0,10,false]", "[1,3,0,0,10,false]" }, + { IdKind.Actor, 316, "[1,3,0,0,1,false]", "[1,3,0,0,1,false]" }, + { IdKind.Actor, 317, "[1,3,0,0,0,1]", "[1,3,0,0,0,1]" }, + { IdKind.Actor, 318, "[1,3,0,1]", "[1,3,0,1]" }, + { IdKind.Actor, 326, "[1,3,0,0,10]", "[1,3,0,0,10]" }, + { IdKind.Item, 302, "[2,3,0,0,false]", "[2,3,0,0,false]" }, + { IdKind.Actor, 339, "[0,3,1,-1]", "[0,3,1,-1]" }, + { IdKind.Troop, 301, "[1,3,false,false]", "[1,3,false,false]" }, + { IdKind.Class, 321, "[3,1,false]", "[3,1,false]" } + }; + + [Theory] + [MemberData(nameof(CommandRows))] + public void Apply_MovedRecord_RewritesEveryCommandRowOfItsKind(IdKind kind, int code, string before, string after) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(kind, InEvent(Command(code, JArray.Parse(before).ToArray()))); + + RemapPlan plan = Plan(game, a, b); + ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, plan.Remaps); + + Assert.Equal([$"b-oak|{kind}||3>4"], plan.NewEntries.Select(Entry)); + ChangeOp edited = Assert.Single(moved.Ops, op => op.Key.Record == "event:1"); + Assert.Equal(after, Flat(edited.Value![0]!["parameters"])); + } + + public static TheoryData FieldRows => new() + { + { IdKind.Class, "data/Actors.json", "[1].classId", "3", "4" }, + { IdKind.Weapon, "data/Actors.json", "[1].equips", "[3,3,3,0,0]", "[4,3,3,0,0]" }, + { IdKind.Armor, "data/Actors.json", "[1].equips", "[3,3,3,0,0]", "[3,4,4,0,0]" }, + { IdKind.Skill, "data/Classes.json", "[1].learnings", "[{\"level\":1,\"note\":\"\",\"skillId\":3}]", "[{\"level\":1,\"note\":\"\",\"skillId\":4}]" }, + { IdKind.Animation, "data/Skills.json", "[1].animationId", "3", "4" }, + { IdKind.Animation, "data/Items.json", "[1].animationId", "3", "4" }, + { IdKind.Animation, "data/Weapons.json", "[1].animationId", "3", "4" }, + { IdKind.Skill, "data/Enemies.json", "[1].actions", Action(4, 3), "[{\"conditionParam1\":3,\"conditionParam2\":0,\"conditionType\":4,\"rating\":5,\"skillId\":4}]" }, + { IdKind.State, "data/Enemies.json", "[1].actions", Action(4, 3), "[{\"conditionParam1\":4,\"conditionParam2\":0,\"conditionType\":4,\"rating\":5,\"skillId\":3}]" }, + { IdKind.Item, "data/Enemies.json", "[1].dropItems", Drop(1), Drop(1).Replace("\"dataId\":3", "\"dataId\":4", StringComparison.Ordinal) }, + { IdKind.Weapon, "data/Enemies.json", "[1].dropItems", Drop(2), Drop(2).Replace("\"dataId\":3", "\"dataId\":4", StringComparison.Ordinal) }, + { IdKind.Armor, "data/Enemies.json", "[1].dropItems", Drop(3), Drop(3).Replace("\"dataId\":3", "\"dataId\":4", StringComparison.Ordinal) }, + { IdKind.Enemy, "data/Troops.json", "[1].members", "[{\"enemyId\":3,\"x\":0,\"y\":0,\"hidden\":false}]", "[{\"enemyId\":4,\"x\":0,\"y\":0,\"hidden\":false}]" }, + { IdKind.Actor, "data/Troops.json", "[1].pages", TroopPage(3), TroopPage(4) }, + { IdKind.State, "data/Actors.json", "[1].traits", Trait(14, 3), Trait(14, 4) }, + { IdKind.Skill, "data/Weapons.json", "[1].traits", Trait(43, 3), Trait(43, 4) }, + { IdKind.Skill, "data/Enemies.json", "[1].traits", Trait(35, 3), Trait(35, 4) }, + { IdKind.State, "data/States.json", "[1].traits", Trait(13, 3), Trait(13, 4) }, + { IdKind.State, "data/Items.json", "[1].effects", Effect(21, 3), Effect(21, 4) }, + { IdKind.Skill, "data/Skills.json", "[1].effects", Effect(43, 3), Effect(43, 4) }, + { IdKind.CommonEvent, "data/Items.json", "[1].effects", Effect(44, 3), Effect(44, 4) }, + { IdKind.Tileset, Map, "tilesetId", "3", "4" }, + { IdKind.Troop, Map, "encounterList", "[{\"regionSet\":[],\"troopId\":3,\"weight\":5}]", "[{\"regionSet\":[],\"troopId\":4,\"weight\":5}]" }, + { IdKind.Item, Map, "events[1].pages[0].conditions.itemId", "3", "4" }, + { IdKind.Actor, Map, "events[1].pages[0].conditions.actorId", "3", "4" }, + { IdKind.Actor, SystemFile, "partyMembers", "[1,3]", "[1,4]" }, + { IdKind.Actor, SystemFile, "testBattlers", Battler(3, "[1,1,1,0,0]"), Battler(4, "[1,1,1,0,0]") }, + { IdKind.Weapon, SystemFile, "testBattlers", Battler(1, "[3,3,3,0,0]"), Battler(1, "[4,3,3,0,0]") }, + { IdKind.Armor, SystemFile, "testBattlers", Battler(1, "[3,3,3,0,0]"), Battler(1, "[3,4,4,0,0]") }, + { IdKind.Troop, SystemFile, "testTroopId", "3", "4" }, + { IdKind.State, "data/Weapons.json", "[1].traits", Trait(32, 3), Trait(32, 4) }, + { IdKind.Skill, "data/Classes.json", "[1].traits", Trait(43, 3), Trait(43, 4) }, + { IdKind.Skill, "data/Classes.json", "[1].traits", Trait(44, 3), Trait(44, 4) }, + { IdKind.State, "data/Armors.json", "[1].traits", Trait(14, 3), Trait(14, 4) }, + { IdKind.State, "data/Items.json", "[1].effects", Effect(22, 3), Effect(22, 4) }, + { IdKind.Actor, "data/Items.json", "[1].description", "\"\\\\N[3] sells this\"", "\"\\\\N[4] sells this\"" }, + + // Same fields, other forms: another condition, drop kind, trait or effect code. + { IdKind.State, "data/Enemies.json", "[1].actions", Action(2, 3), Action(2, 3) }, + { IdKind.Item, "data/Enemies.json", "[1].dropItems", Drop(2), Drop(2) }, + { IdKind.State, "data/Armors.json", "[1].traits", Trait(11, 3), Trait(11, 3) }, + { IdKind.State, "data/Skills.json", "[1].effects", Effect(11, 3), Effect(11, 3) } + }; + + private static string Action(int conditionType, int id) + { + return $"[{{\"conditionParam1\":{id},\"conditionParam2\":0,\"conditionType\":{conditionType},\"rating\":5,\"skillId\":{id}}}]"; + } + + private static string Drop(int kind) + { + return $"[{{\"dataId\":3,\"denominator\":1,\"kind\":{kind}}}]"; + } + + private static string TroopPage(int actorId) + { + return $"[{{\"conditions\":{{\"actorId\":{actorId},\"actorValid\":true}},\"list\":[{{\"code\":0,\"indent\":0,\"parameters\":[]}}],\"span\":0}}]"; + } + + private static string Trait(int code, int dataId) + { + return $"[{{\"code\":{code},\"dataId\":{dataId},\"value\":1}}]"; + } + + private static string Effect(int code, int dataId) + { + return $"[{{\"code\":{code},\"dataId\":{dataId},\"value1\":1,\"value2\":0}}]"; + } + + private static string Battler(int actorId, string equips) + { + return $"[{{\"actorId\":{actorId},\"equips\":{equips},\"level\":1}}]"; + } + + [Theory] + [MemberData(nameof(FieldRows))] + public void Apply_MovedRecord_RewritesEveryFieldRowOfItsKind(IdKind kind, string file, string path, string value, string expected) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(kind, Set(file, path, value)); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal([$"b-oak|{kind}||3>4"], plan.NewEntries.Select(Entry)); + Assert.True(merged.IsDeployable); + Assert.Equal(expected, Flat(Written(merged, game, file).SelectToken(path))); + } + + [Fact] + public void Plan_DropWhoseKindOnlyVanillaHolds_IsAmbiguousAndMovesTheOtherMod() + { + var game = new Game(("data/Enemies.json", "[null,{\"id\":1,\"name\":\"One\",\"dropItems\":[{\"dataId\":1,\"denominator\":1,\"kind\":1}]}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, Set("data/Enemies.json", "[1].dropItems[0].dataId", "3")); + + RemapPlan plan = Plan(game, a, b); + + Assert.Equal(["a-tin|Item||3>4"], plan.NewEntries.Select(Entry)); + Assert.True(ComposeRemapped(plan, game, a, b).IsDeployable); + } + + [Fact] + public void Apply_DropWhoseKindAndIdBothChange_MovesWithItsMod() + { + var game = new Game(("data/Enemies.json", "[null,{\"id\":1,\"name\":\"One\",\"dropItems\":[{\"dataId\":1,\"denominator\":1,\"kind\":2}]}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, files => + { + Set("data/Enemies.json", "[1].dropItems[0].dataId", "3")(files); + Set("data/Enemies.json", "[1].dropItems[0].kind", "1")(files); + }); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal(["b-oak|Item||3>4"], plan.NewEntries.Select(Entry)); + Assert.Equal("{\"dataId\":4,\"denominator\":1,\"kind\":1}", Flat(Written(merged, game, "data/Enemies.json")[1]!["dropItems"]![0])); + } + + [Fact] + public void Plan_DropWhoseKindAloneChanges_IsUnknownAndMovesTheOtherMod() + { + var game = new Game(("data/Enemies.json", "[null,{\"id\":1,\"name\":\"One\",\"dropItems\":[{\"dataId\":3,\"denominator\":1,\"kind\":2}]}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, Set("data/Enemies.json", "[1].dropItems[0].kind", "1")); + + RemapPlan plan = Plan(game, a, b); + + Assert.Equal(["a-tin|Item||3>4"], plan.NewEntries.Select(Entry)); + Assert.True(ComposeRemapped(plan, game, a, b).IsDeployable); + } + + [Fact] + public void Plan_DropWhoseKindAloneChangesToNoId_MovesTheLaterMod() + { + var game = new Game(("data/Enemies.json", "[null,{\"id\":1,\"name\":\"One\",\"dropItems\":[{\"dataId\":3,\"denominator\":1,\"kind\":1}]}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, Set("data/Enemies.json", "[1].dropItems[0].kind", "0")); + + Assert.Equal(["b-oak|Item||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + public static TheoryData LooseIds => new() + { + { "field", "3.0", "a-tin" }, + { "field", "\"3\"", "a-tin" }, + { "command", "3.0", "a-tin" }, + { "command", "\"3\"", "a-tin" }, + + // Not the id 3 in any reading the game makes. + { "field", "3.5", "b-oak" }, + { "field", "\"03\"", "b-oak" }, + { "command", "\"3a\"", "b-oak" } + }; + + [Theory] + [MemberData(nameof(LooseIds))] + public void Plan_IdNotStoredAsAnInteger_IsAmbiguousWhenTheGameReadsItAsTheId(string where, string id, string moved) + { + var game = new Game(); + Action> edit = where == "field" + ? Set("data/Actors.json", "[1].classId", id) + : InEvent(Command(321, 1, JToken.Parse(id), false)); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Class, edit); + + Assert.Equal([$"{moved}|Class||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + public static TheoryData ByVariableRows => new() + { + { IdKind.Troop, 301, "[1,5,false,false]" }, + { IdKind.Actor, 311, "[1,5,0,0,10,false]" }, + { IdKind.Actor, 312, "[1,5,0,0,10]" }, + { IdKind.Actor, 313, "[1,5,0,1]" }, + { IdKind.Actor, 314, "[1,5]" }, + { IdKind.Actor, 315, "[1,5,0,0,10,false]" }, + { IdKind.Actor, 316, "[1,5,0,0,1,false]" }, + { IdKind.Actor, 317, "[1,5,0,0,0,1]" }, + { IdKind.Actor, 318, "[1,5,0,1]" }, + { IdKind.Actor, 326, "[1,5,0,0,10]" } + }; + + /// The command names its id through variable 5, which a Control Variables sets to . + private static Action> ByVariable(int code, string parameters, int constant) + { + return files => + { + InEvent(Command(code, JArray.Parse(parameters).ToArray()))(files); + InEvent(Command(122, 5, 5, 0, 0, constant))(files); + }; + } + + [Theory] + [MemberData(nameof(ByVariableRows))] + public void Plan_ByVariableWithTheOldIdAsAConstant_MovesTheOtherMod(IdKind kind, int code, string parameters) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(kind, ByVariable(code, parameters, 3)); + + Assert.Equal([$"a-tin|{kind}||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(ByVariableRows))] + public void Plan_ByVariableWithOtherConstants_MovesTheLaterMod(IdKind kind, int code, string parameters) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(kind, ByVariable(code, parameters, 7)); + + Assert.Equal([$"b-oak|{kind}||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + public static TheoryData RandomRanges => new() + { + { 1, 5, "a-tin" }, + { 3, 3, "a-tin" }, + { 5, 1, "a-tin" }, + { 4, 9, "b-oak" }, + { 0, 2, "b-oak" } + }; + + [Theory] + [MemberData(nameof(RandomRanges))] + public void Plan_ByVariableWithARandomRange_RefusesWhenTheRangeHoldsTheOldId(int low, int high, string moved) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Troop, files => + { + InEvent(Command(301, 1, 5, false, false))(files); + InEvent(Command(122, 5, 5, 0, 2, low, high))(files); + }); + + Assert.Equal([$"{moved}|Troop||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_RandomRangeWithNoByVariableCommand_MovesTheLaterMod() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Troop, InEvent(Command(122, 5, 5, 0, 2, 1, 5))); + + Assert.Equal(["b-oak|Troop||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_RecordedEntryWhoseModNowNamesTheOldIdInAScript_StillAppliesWithAWarning() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, InEvent(Command(355, "$gameParty.gainItem($dataItems[3], 1)"))); + var recorded = new IdRemap("b-oak", IdKind.Item, "", 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([a, b], [recorded], ["a-tin", "b-oak"], game.Bases, null); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Empty(plan.NewEntries); + Assert.Equal(["b-oak|Item||3>4"], plan.Remaps.Select(Entry)); + OperationDiagnostic warning = Assert.Single(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapStaleReference); + Assert.Equal(DiagnosticSeverity.Warning, warning.Severity); + Assert.Equal("b-oak", warning.Subject); + Assert.True(merged.IsDeployable); + Assert.Equal("B", Written(merged, game, Items)[4]!["name"]!.Value()); + } + + [Fact] + public void Plan_RecordedEntryWithNoFreeText_GivesNoWarning() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item); + var recorded = new IdRemap("b-oak", IdKind.Item, "", 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([a, b], [recorded], ["a-tin", "b-oak"], game.Bases, null); + + Assert.Equal(["b-oak|Item||3>4"], plan.Remaps.Select(Entry)); + Assert.Empty(plan.Diagnostics); + } + + public static TheoryData TextCodes => new() + { + { "Hello \\N[3]", "Hello \\N[4]" }, + { "Hello \\n[3]", "Hello \\n[4]" }, + { "\\N[3] meets \\N[1]", "\\N[4] meets \\N[1]" }, + { "A slash: \\\\N[3]", "A slash: \\\\N[3]" }, + { "A slash, then a code: \\\\\\N[3]", "A slash, then a code: \\\\\\N[4]" }, + { "Party of 3", "Party of 3" } + }; + + [Theory] + [MemberData(nameof(TextCodes))] + public void Apply_MovedActor_RewritesTheNameCodeInMessageText(string before, string after) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Actor, InEvent(Command(401, before))); + + RemapPlan plan = Plan(game, a, b); + ModChangeSet moved = IdRemapper.Apply(b.ChangeSet, plan.Remaps); + + Assert.Equal(["b-oak|Actor||3>4"], plan.NewEntries.Select(Entry)); + Assert.Equal(after, moved.Ops.Single(op => op.Key.Record == "event:1").Value![0]!["parameters"]![0]!.Value()); + } + + [Fact] + public void Plan_Target_SitsAboveFillerOfAnotherMod() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item); + RemapMod filler = game.Mod("c-elm", 2, file => + { + var items = (JArray)file(Items); + AddRecord(items, 3, ""); + AddRecord(items, 4, ""); + AddRecord(items, 5, ""); + }); + + RemapPlan plan = Plan(game, a, b, filler); + MergePlan merged = ComposeRemapped(plan, game, a, b, filler); + + Assert.Equal(["b-oak|Item||3>6"], plan.NewEntries.Select(Entry)); + Assert.Empty(merged.Collisions); + JToken items = Written(merged, game, Items); + Assert.Equal("A", items[3]!["name"]!.Value()); + Assert.Equal("B", items[6]!["name"]!.Value()); + } + + public static TheoryData OwnUses => new() { "303", "322", "text code", "field" }; + + private static Action> OwnUse(string use) + { + return use switch + { + "303" => InEvent(Command(303, 3, 8)), + "322" => InEvent(Command(322, 3, "Hero", 0, "", 0, "")), + "text code" => InEvent(Command(401, "\\N[3] wakes up")), + _ => Set(SystemFile, "partyMembers", "[1,3]") + }; + } + + [Theory] + [MemberData(nameof(OwnUses))] + public void Plan_BlankActorItsOwnModNames_IsRealAndMoves(string use) + { + var game = new Game(); + RemapMod a = game.Mod("a-tin", 0, file => AddRecord(file("data/Actors.json"), 3, "A")); + RemapMod b = game.Mod("b-oak", 1, file => + { + AddRecord(file("data/Actors.json"), 3, ""); + OwnUse(use)(file); + }); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal(["b-oak|Actor||3>4"], plan.NewEntries.Select(Entry)); + Assert.True(merged.IsDeployable); + JToken actors = Written(merged, game, "data/Actors.json"); + Assert.Equal("A", actors[3]!["name"]!.Value()); + Assert.Equal("", actors[4]!["name"]!.Value()); + } + + [Theory] + [InlineData(0, 3)] + [InlineData(2, 1)] + public void Plan_BlankActorItsOwnModPicksByVariable_IsRealAndStays(int operand, int value) + { + var game = new Game(); + RemapMod a = game.Mod("a-tin", 0, file => AddRecord(file("data/Actors.json"), 3, "A")); + RemapMod b = game.Mod("b-oak", 1, file => + { + AddRecord(file("data/Actors.json"), 3, ""); + InEvent(Command(311, 1, 5, 0, 0, 10, false))(file); + InEvent(Command(122, 5, 5, 0, operand, value, 5))(file); + }); + + // Real, and the variable may hold 3, so b-oak cannot move: a-tin does. + Assert.Equal(["a-tin|Actor||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_BlankActorItsOwnModNeverNames_IsFillerAndYields() + { + var game = new Game(); + RemapMod a = game.Mod("a-tin", 0, file => AddRecord(file("data/Actors.json"), 3, "A")); + RemapMod b = game.Mod("b-oak", 1, file => AddRecord(file("data/Actors.json"), 3, "")); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Empty(plan.NewEntries); + Assert.Empty(merged.Collisions); + Assert.Equal("A", Written(merged, game, "data/Actors.json")[3]!["name"]!.Value()); + } + + public static TheoryData MessageCodes => new() + { + { 401, "Take \\II[3]", "a-tin" }, + { 401, "Take \\ii[3]", "a-tin" }, + { 405, "Scroll \\Gold[3]", "a-tin" }, + + // The engines' own codes hold no item id, and comments are not read. + { 401, "Colored \\C[3]", "b-oak" }, + { 401, "Icon \\I[3]", "b-oak" }, + { 401, "Moved \\PX[3]", "b-oak" }, + { 401, "Sized \\FS[3]", "b-oak" }, + { 401, "Count \\V[3]", "b-oak" }, + { 401, "Member \\P[3]", "b-oak" }, + { 401, "Escaped \\\\II[3]", "b-oak" }, + { 108, "Item 3 is \\II[3]", "b-oak" } + }; + + [Theory] + [MemberData(nameof(MessageCodes))] + public void Plan_OldIdInATextCode_RefusesOnlyForAPluginCode(int code, string text, string moved) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, InEvent(Command(code, text))); + + Assert.Equal([$"{moved}|Item||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + private static void AddEvent(JToken map, int id, string name) + { + var events = (JArray)map["events"]!; + var added = (JObject)events[2]!.DeepClone(); + added["id"] = id; + added["name"] = name; + events.Add(added); + } + + [Theory] + [InlineData(RpgMakerEngine.MZ, "b-oak")] + [InlineData(RpgMakerEngine.MV, "a-tin")] + [InlineData(null, "a-tin")] + public void Plan_LocationInfoByCharacter_NamesAnEventOnlyOnMz(RpgMakerEngine? engine, string moved) + { + var game = new Game(); + RemapMod a = game.Mod("a-tin", 0, file => AddEvent(file(Map), 3, "A")); + RemapMod b = game.Mod("b-oak", 1, file => + { + AddEvent(file(Map), 3, "B"); + InEvent(Command(285, 5, 1, 2, 3, 0))(file); + }); + + Assert.Equal([$"{moved}|MapEvent|data/map001.json|3>4"], Plan(engine, game, a, b).NewEntries.Select(Entry)); + } + + private const string DualWieldActors = + "[null,{\"id\":1,\"name\":\"One\",\"traits\":[{\"code\":55,\"dataId\":1,\"value\":1}]},{\"id\":2,\"name\":\"Two\"}]"; + + public static TheoryData SecondSlots => new() { "command", "field", "test battler" }; + + private static Action> SecondSlot(string where) + { + return where switch + { + "command" => InEvent(Command(319, 1, 2, 3)), + "field" => Set("data/Actors.json", "[1].equips", "[1,3,0,0,0]"), + _ => Set(SystemFile, "testBattlers", Battler(1, "[1,3,0,0,0]")) + }; + } + + [Theory] + [MemberData(nameof(SecondSlots))] + public void Plan_SecondSlotInADualWieldGame_IsAmbiguousAndMovesTheOtherMod(string where) + { + var game = new Game(("data/Actors.json", DualWieldActors)); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Armor, SecondSlot(where)); + + Assert.Equal(["a-tin|Armor||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(SecondSlots))] + public void Plan_SecondSlotWithoutTrait55_MovesTheLaterMod(string where) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Armor, SecondSlot(where)); + + Assert.Equal(["b-oak|Armor||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(SecondSlots))] + public void Plan_SecondSlotWeaponInADualWieldGame_IsAmbiguousAndMovesTheOtherMod(string where) + { + var game = new Game(("data/Actors.json", DualWieldActors)); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Weapon, SecondSlot(where)); + + Assert.Equal(["a-tin|Weapon||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(SecondSlots))] + public void Plan_SecondSlotWeaponWithoutTrait55_IsArmorAndMovesTheLaterMod(string where) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Weapon, SecondSlot(where)); + + Assert.Equal(["b-oak|Weapon||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + /// Without its file the game may hold trait 55 anywhere; a clash of the other equip kind shows it. + [Theory] + [InlineData("data/Actors.json", IdKind.Armor)] + [InlineData("data/Classes.json", IdKind.Armor)] + [InlineData("data/Weapons.json", IdKind.Armor)] + [InlineData("data/Armors.json", IdKind.Weapon)] + [InlineData("data/States.json", IdKind.Armor)] + public void Plan_MissingTraitBase_CountsAsDualWield(string file, IdKind kind) + { + var game = new Game((file, null)); + (RemapMod a, RemapMod b) = game.Clash(kind, SecondSlot("command")); + + Assert.Equal([$"a-tin|{kind}||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [InlineData("data/Actors.json")] + [InlineData("data/Classes.json")] + [InlineData("data/Weapons.json")] + [InlineData("data/Armors.json")] + [InlineData("data/States.json")] + public void Plan_Trait55FromAnEnabledMod_CountsAsDualWield(string file) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash( + IdKind.Armor, + files => + { + SecondSlot("command")(files); + Set(file, "[1].traits", Trait(55, 1))(files); + }); + + Assert.Equal(["a-tin|Armor||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_Trait55FromADisabledMod_IsIgnored() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Armor, SecondSlot("command")); + RemapMod off = game.Mod("c-elm", 2, Set("data/Classes.json", "[1].traits", Trait(55, 1))) with { Enabled = false }; + + Assert.Equal(["b-oak|Armor||3>4"], Plan(game, a, b, off).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_TraitCodePastTheLongRange_IsNoDualWieldAndDoesNotThrow() + { + var game = new Game(("data/Classes.json", + "[null,{\"id\":1,\"name\":\"One\",\"traits\":[{\"code\":99999999999999999999,\"dataId\":99999999999999999999,\"value\":1}]},{\"id\":2,\"name\":\"Two\"}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Armor, SecondSlot("command")); + + Assert.Equal(["b-oak|Armor||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + private static string Records(int count) + { + var records = new JArray(JValue.CreateNull()); + for (int id = 1; id < count; id++) + { + records.Add(new JObject { ["id"] = id, ["name"] = "R" + id }); + } + + return records.ToString(Newtonsoft.Json.Formatting.None); + } + + private static (Game Game, RemapMod A, RemapMod B) ClashAt(int id) + { + var game = new Game((Items, Records(id))); + RemapMod a = game.Mod("a-tin", 0, file => AddRecord(file(Items), id, "A")); + RemapMod b = game.Mod("b-oak", 1, file => AddRecord(file(Items), id, "B")); + return (game, a, b); + } + + [Theory] + [InlineData(null)] + [InlineData(RpgMakerEngine.MV)] + public void Plan_RecordPast999OnMvOrAnUnknownEngine_RefusesTheMove(RpgMakerEngine? engine) + { + (Game game, RemapMod a, RemapMod b) = ClashAt(999); + + RemapPlan plan = Plan(engine, game, a, b); + + Assert.Empty(plan.Remaps); + Assert.False(ComposeRemapped(plan, game, a, b).IsDeployable); + } + + [Fact] + public void Plan_MzRecordPast999_MovesTo1000() + { + (Game game, RemapMod a, RemapMod b) = ClashAt(999); + + Assert.Equal(["b-oak|Item||999>1000"], Plan(RpgMakerEngine.MZ, game, a, b).NewEntries.Select(Entry)); + } + + [Fact] + public void Plan_MzRecordPast9999_RefusesTheMove() + { + (Game game, RemapMod a, RemapMod b) = ClashAt(9999); + + Assert.Empty(Plan(RpgMakerEngine.MZ, game, a, b).Remaps); + } + + public static TheoryData FreeTextPlaces => new() { "note", "formula" }; + + private static Action> FreeText(string where) + { + return where == "note" + ? files => files(Items)[3]!["note"] = "" + : Set("data/Skills.json", "[1].damage", "{\"formula\":\"a.atk * 3\",\"type\":1}"); + } + + [Fact] + public void Plan_OldIdInAFormulaLeafOfTheLaterMod_MovesTheEarlierModInstead() + { + var game = new Game(("data/Skills.json", + "[null,{\"id\":1,\"name\":\"One\",\"damage\":{\"formula\":\"0\",\"type\":1}},{\"id\":2,\"name\":\"Two\"}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, Set("data/Skills.json", "[1].damage.formula", "\"a.atk * 3\"")); + + Assert.Equal(["a-tin|Item||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(FreeTextPlaces))] + public void Plan_OldIdInFreeTextOfTheLaterMod_MovesTheEarlierModInstead(string where) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, FreeText(where)); + + Assert.Equal(["a-tin|Item||3>4"], Plan(game, a, b).NewEntries.Select(Entry)); + } + + [Theory] + [MemberData(nameof(FreeTextPlaces))] + public void Plan_OldIdInFreeTextOfBothMods_KeepsTheClashBlocking(string where) + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, FreeText(where), FreeText(where)); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Empty(plan.Remaps); + Assert.Empty(plan.Offers); + Collision clash = Assert.Single(merged.Collisions, item => item.Kind == CollisionKind.IdClash); + Assert.Equal("id:3", clash.Key.Record); + Assert.True(clash.Blocking); + Assert.False(merged.IsDeployable); + } + + [Fact] + public void Plan_OldIdOnlyInAShippedPluginFile_OffersRemapAndTheChosenOfferDeploys() + { + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item, editA: FreeText("note"), scriptsB: "var step = 3;"); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Empty(plan.Remaps); + Assert.Equal(["b-oak|Item||3>4"], plan.Offers.Select(Entry)); + Collision clash = Assert.Single(merged.Collisions); + Assert.Equal([ResolutionKind.PickMod, ResolutionKind.Remap, ResolutionKind.DisableMod], clash.Allowed); + Assert.False(merged.IsDeployable); + + IdRemap chosen = plan.OfferFor(clash, "b-oak")!; + RemapPlan next = IdRemapPlanner.Plan([a, b], [chosen], [], game.Bases, null); + Assert.Equal([chosen], next.Remaps); + Assert.True(ComposeRemapped(next, game, a, b).IsDeployable); + } + + [Fact] + public void Apply_MovedRecord_RewritesAWholeNewMapFile() + { + const string newMap = "data/Map002.json"; + var game = new Game(); + (RemapMod a, RemapMod b) = game.Clash( + IdKind.Item, + files => ((JArray)files(newMap)["events"]![1]!["pages"]![0]!["list"]!).Insert(0, Command(126, 3, 0, 0, 1))); + + RemapPlan plan = Plan(game, a, b); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal(["b-oak|Item||3>4"], plan.NewEntries.Select(Entry)); + Assert.Equal("[4,0,0,1]", Flat(Written(merged, game, newMap)["events"]![1]!["pages"]![0]!["list"]![0]!["parameters"])); + } + + [Fact] + public void Write_NewDatabaseFileWithHoles_FillsThemWithBlankRecords() + { + const string animations = "data/Animations.json"; + var game = new Game((animations, null)); + RemapMod mod = game.Mod("b-oak", 0, file => AddRecord(file(animations), 3, "B")); + + JToken records = Written(ComposeRemapped(Plan(game, mod), game, mod), game, animations); + + Assert.Equal(4, ((JArray)records).Count); + Assert.Equal(JTokenType.Null, records[0]!.Type); + Assert.All([1, 2], id => + { + Assert.Equal(id, records[id]!["id"]!.Value()); + Assert.True(RpgDataSchema.HasBlankShape("data/animations.json", records[id])); + }); + Assert.Equal("B", records[3]!["name"]!.Value()); + } + + [Fact] + public void Write_NewDatabaseFileWithoutHoles_IsTheModsOwnFile() + { + const string animations = "data/Animations.json"; + var game = new Game((animations, null)); + RemapMod mod = game.Mod("b-oak", 0, file => + { + AddRecord(file(animations), 1, "A"); + AddRecord(file(animations), 2, "B"); + }); + + MergePlan merged = ComposeRemapped(Plan(game, mod), game, mod); + MergedFile written = MergedFileWriter.Write(merged, game.Bases, null, RpgMakerEngine.MZ).Single(item => string.Equals(item.File, animations, StringComparison.OrdinalIgnoreCase)); + + Assert.Equal(MergedFileSource.ModFile, written.Source); + } + + [Fact] + public void Plan_RecordedTargetVanillaNowUses_PlansTheRecordAgainWithAWarning() + { + var game = new Game((Items, "[null,{\"id\":1,\"name\":\"One\"},{\"id\":2,\"name\":\"Two\"},null,{\"id\":4,\"name\":\"Four\"}]")); + (RemapMod a, RemapMod b) = game.Clash(IdKind.Item); + var recorded = new IdRemap("b-oak", IdKind.Item, "", 3, 4); + + RemapPlan plan = IdRemapPlanner.Plan([a, b], [recorded], ["a-tin", "b-oak"], game.Bases, null); + MergePlan merged = ComposeRemapped(plan, game, a, b); + + Assert.Equal(["b-oak|Item||3>5"], plan.NewEntries.Select(Entry)); + Assert.Contains(merged.Diagnostics, item => item.Code == DiagnosticCodes.RulesRemapTargetTaken); + Assert.True(merged.IsDeployable); + JToken items = Written(merged, game, Items); + Assert.Equal("Four", items[4]!["name"]!.Value()); + Assert.Equal("B", items[5]!["name"]!.Value()); + } + + [Theory] + [InlineData(IdKind.Switch)] + [InlineData(IdKind.Variable)] + public void Apply_SwitchOrVariableEntry_IsIgnored(IdKind kind) + { + var game = new Game(); + RemapMod mod = game.Mod("b-oak", 0, file => AddRecord(file(Items), 3, "B")); + var entry = new IdRemap("b-oak", kind, "", 3, 9); + + RemapPlan plan = IdRemapPlanner.Plan([mod], [entry], [], game.Bases, null); + + Assert.Empty(plan.Remaps); + Assert.Same(mod.ChangeSet, IdRemapper.Apply(mod.ChangeSet, [entry])); + } +} diff --git a/RPGModder.Tests/Merge/IdRemapTests.cs b/RPGModder.Tests/Merge/IdRemapTests.cs index 5007c3a..97d6fff 100644 --- a/RPGModder.Tests/Merge/IdRemapTests.cs +++ b/RPGModder.Tests/Merge/IdRemapTests.cs @@ -171,7 +171,8 @@ public void Apply_MovedEvent_RewritesEveryEventRowOfTheReferenceTable(int code, FileMod("b-oak", Map, MapWith(NewEvent(3, "Merchant", reference), map => FirstList(map, 1).Insert(0, reference.DeepClone())), 1), MapBases); - RemapPlan plan = Plan(MapBases, first, second); + // The rows as MZ reads them: 285 by character is MZ's only (IdRemapDatabaseTests reads it on MV). + RemapPlan plan = Plan(RpgMakerEngine.MZ, MapBases, first, second); ModChangeSet moved = ApplyOwn(plan, second); Assert.Equal(["b-oak|MapEvent|data/map001.json|3>4"], plan.NewEntries.Select(Entry)); diff --git a/RPGModder.Tests/Merge/MergedFileWriterTests.cs b/RPGModder.Tests/Merge/MergedFileWriterTests.cs index 32f670e..8aaad59 100644 --- a/RPGModder.Tests/Merge/MergedFileWriterTests.cs +++ b/RPGModder.Tests/Merge/MergedFileWriterTests.cs @@ -36,7 +36,7 @@ public void TouchedFile_IsCompactWithVanillaOrder_AndNewPropertiesLast() } [Fact] - public void RemovedRecords_BecomeNull_AndATrailingRunIsCut() + public void RemovedRecords_BecomeBlank_AndATrailingRunIsCut() { const string vanilla = "[null,{\"id\":1},{\"id\":2},{\"id\":3}]"; BaseFileSet bases = Bases(Base("data/Weapons.json", vanilla)); @@ -44,7 +44,8 @@ public void RemovedRecords_BecomeNull_AndATrailingRunIsCut() MergedFile middle = Assert.Single(Write(bases, null, FileMod("a-tin", "data/Weapons.json", "[null,{\"id\":1},null,{\"id\":3}]"))); MergedFile tail = Assert.Single(Write(bases, null, FileMod("a-tin", "data/Weapons.json", "[null,{\"id\":1}]"))); - Assert.Equal("[null,{\"id\":1},null,{\"id\":3}]", middle.Text); + // GR-R8: the hole takes the blank weapon with its own id. + Assert.Equal("[null,{\"id\":1},{\"id\":2,\"animationId\":0,\"description\":\"\",\"etypeId\":1,\"traits\":[{\"code\":31,\"dataId\":1,\"value\":0},{\"code\":22,\"dataId\":0,\"value\":0}],\"iconIndex\":0,\"name\":\"\",\"note\":\"\",\"params\":[0,0,0,0,0,0,0,0],\"price\":0,\"wtypeId\":0},{\"id\":3}]", middle.Text); Assert.Equal("[null,{\"id\":1}]", tail.Text); } @@ -210,7 +211,7 @@ public void VersionId_WithAModChangeToSystem_CarriesBoth() } [Fact] - public void RemovedRecordBeforeAnAddedOne_StaysAsNull() + public void RemovedRecordBeforeAnAddedOne_BecomesBlank() { BaseFileSet bases = Bases(Base(Items, VanillaItems)); ModSource removal = FileMod("a-tin", Items, EditItems(items => items[2] = JValue.CreateNull())); @@ -219,7 +220,8 @@ public void RemovedRecordBeforeAnAddedOne_StaysAsNull() JArray written = JArray.Parse(Assert.Single(Write(bases, null, removal, addition)).Text!); Assert.Equal(4, written.Count); - Assert.Equal(JTokenType.Null, written[2].Type); + Assert.Equal(2, written[2]["id"]!.Value()); + Assert.Equal("", written[2]["name"]!.Value()); Assert.Equal(new JObject { ["id"] = 3 }, written[3]); } diff --git a/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs b/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs index 3b22d42..b650b77 100644 --- a/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs +++ b/RPGModder.Tests/MergeContract/MergedFileWriterContractTests.cs @@ -97,7 +97,7 @@ public void Write_AllOpsDroppedByPickVanilla_OmitsTheFile() } [Fact] - public void Write_RemovedRecords_AreNullInsideAndCutAtTheEnd() + public void Write_RemovedRecords_AreBlankInsideAndCutAtTheEnd() { const string vanillaItems = "[\nnull,\n{\"id\":1,\"name\":\"Herb\",\"price\":50},\n{\"id\":2,\"name\":\"Tonic\",\"price\":100},\n{\"id\":3,\"name\":\"Salve\",\"price\":150}\n]"; @@ -121,7 +121,10 @@ public void Write_RemovedRecords_AreNullInsideAndCutAtTheEnd() MergedFile file = Assert.Single(written); Assert.Equal("data/items.json", file.File); - Assert.Equal("[null,null,{\"id\":2,\"name\":\"Tonic\",\"price\":100}]", file.Text); + // GR-R8: a hole above index 0 takes the blank record; the trailing removal is cut. + Assert.Equal( + "[null," + "{\"id\":1,\"animationId\":0,\"consumable\":true,\"damage\":{\"critical\":false,\"elementId\":0,\"formula\":\"0\",\"type\":0,\"variance\":20},\"description\":\"\",\"effects\":[],\"hitType\":0,\"iconIndex\":0,\"itypeId\":1,\"name\":\"\",\"note\":\"\",\"occasion\":0,\"price\":0,\"repeats\":1,\"scope\":7,\"speed\":0,\"successRate\":100,\"tpGain\":0}" + ",{\"id\":2,\"name\":\"Tonic\",\"price\":100}]", + file.Text); } [Fact]