'
+ dependsOn 'fixturesClasses'
+ classpath = sourceSets.fixtures.runtimeClasspath
+ mainClass = 'kamkeel.npcs.fixtures.FixtureGenerator'
+ // Off the project dir, because CustomNpcs.getWorldSaveDirectory() resolves "." and
+ // a stray relative write would land in the repo root.
+ workingDir = project.buildDir
+ doFirst {
+ // Resolved against the project directory, not workingDir, so -Pout=build/x means what it
+ // looks like rather than build/build/x.
+ def out = project.hasProperty('out') ? project.file(project.property('out'))
+ : new File(project.buildDir, 'scribe-fixtures')
+ args = [out.absolutePath]
+ if (project.hasProperty('worlds')) {
+ args += ['--worlds', project.property('worlds')]
+ }
+ }
+}
+
// ============================================================================
// TypeScript Definition Generation Task
// Generates .d.ts files from Java API sources for scripting IDE support
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Case.java b/src/fixtures/java/kamkeel/npcs/fixtures/Case.java
new file mode 100644
index 000000000..490d8f7cf
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/Case.java
@@ -0,0 +1,21 @@
+package kamkeel.npcs.fixtures;
+
+/**
+ * One piece of content, the category it belongs in, and why it exists.
+ *
+ * The note is the part that does not survive serialization. A directory of numbered files says
+ * nothing about which one is the dialog whose availability is gated four ways, and the next person
+ * to need that case will otherwise author a second one.
+ */
+public final class Case {
+
+ public final String category;
+ public final T value;
+ public final String note;
+
+ public Case(String category, T value, String note) {
+ this.category = category;
+ this.value = value;
+ this.note = note;
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java
new file mode 100644
index 000000000..497242782
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureGenerator.java
@@ -0,0 +1,118 @@
+package kamkeel.npcs.fixtures;
+
+import kamkeel.npcs.fixtures.worlds.DefaultsWorld;
+import kamkeel.npcs.fixtures.worlds.EdgeWorld;
+import kamkeel.npcs.fixtures.worlds.LegacyWorld;
+import kamkeel.npcs.fixtures.worlds.MaximalWorld;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Generates CustomNPC+ save data offline, for use as test fixtures.
+ *
+ * The point is that the bytes are written by CustomNPC+ itself. Hand-authoring a
+ * {@code factions.dat} that looks right is easy and proves nothing: it asserts what its author
+ * believed the format to be. Everything here goes through the shipping data classes' own
+ * serialization, so a fixture is evidence about the format rather than about the author.
+ *
+ *
Usage: {@code gradlew scribeFixtures -Pout=
[-Pworlds=maximal,edge]}
+ */
+public final class FixtureGenerator {
+
+ private static final List ALL = Arrays.asList(
+ new MaximalWorld(),
+ new DefaultsWorld(),
+ new EdgeWorld(),
+ new LegacyWorld());
+
+ public static void main(String[] args) throws Exception {
+ if (args.length < 1) {
+ System.err.println("usage: FixtureGenerator [--worlds a,b,c]");
+ System.exit(2);
+ }
+ File out = new File(args[0]).getAbsoluteFile();
+
+ List selected = new ArrayList(ALL);
+ for (int i = 1; i < args.length - 1; i++) {
+ if ("--worlds".equals(args[i])) {
+ selected = select(args[i + 1]);
+ }
+ }
+
+ System.out.println("[fixtures] bootstrapping Minecraft");
+ Fixtures.bootMinecraft();
+
+ Manifest manifest = new Manifest();
+ recordKnownWarnings(manifest);
+
+ int normalized = 0;
+ for (FixtureWorld world : selected) {
+ WorldWriter writer = new WorldWriter(out, world.name(), manifest);
+ manifest.world(world.name(), world.purpose());
+ int before = manifest.count();
+ world.build(writer);
+ normalized += writer.normalizedCount();
+ System.out.println("[fixtures] " + pad(world.name())
+ + (manifest.count() - before) + " files");
+ }
+
+ manifest.write(new File(out, "manifest.json"));
+ Readme.write(new File(out, "README.md"), selected, manifest);
+
+ System.out.println("[fixtures] " + manifest.count() + " files total -> " + out);
+ System.out.println("[fixtures] dialogs " + manifest.countOf("dialog")
+ + ", quests " + manifest.countOf("quest"));
+ // Reported every run so the one normalization cannot quietly spread to other keys.
+ System.out.println("[fixtures] " + normalized + " wall-clock values pinned (TimePast)");
+ }
+
+ /**
+ * Facts a consumer cannot get from the bytes, and would otherwise learn from a flaky test.
+ *
+ * Each was found by reading the writer, not by guessing.
+ */
+ private static void recordKnownWarnings(Manifest manifest) {
+ manifest.warn("NORMALIZED: TimePast is pinned to 0 in every document. PlayerMail.writeNBT "
+ + "stamps it with System.currentTimeMillis() - time, and a PlayerMail hangs off every "
+ + "dialog and every quest whether or not mail was configured -- so left alone, every "
+ + "file here would differ between two runs and a version-controlled corpus would churn "
+ + "completely on each regeneration. This is the ONLY key these fixtures rewrite after "
+ + "CustomNPC+ produced it. Nothing reads the value back except a live-clock display.");
+ manifest.warn("Quest.writeToNBTPartial writes NextQuestTitle from the live QuestController, "
+ + "which is empty offline, so NextQuestTitle is written as the value set on the object "
+ + "rather than resolved from the target quest. NextQuestId is the real link.");
+ manifest.warn("PlayerMail.writeNBT writes MailQuestTitle only when the quest resolves in the "
+ + "live QuestController. Offline it never resolves, so the key is absent.");
+ manifest.warn("These worlds hold no level.dat and no region files. They are the customnpcs/ "
+ + "directory of a world, which is the part CustomNPC+ owns.");
+ }
+
+ private static List select(String csv) {
+ Map byName = new LinkedHashMap();
+ for (FixtureWorld w : ALL) {
+ byName.put(w.name(), w);
+ }
+ List selected = new ArrayList();
+ for (String name : csv.split(",")) {
+ FixtureWorld w = byName.get(name.trim());
+ if (w == null) {
+ throw new IllegalArgumentException("No such world: " + name + " (have " + byName.keySet() + ")");
+ }
+ selected.add(w);
+ }
+ return selected;
+ }
+
+ private static String pad(String name) {
+ StringBuilder sb = new StringBuilder(name);
+ while (sb.length() < 12) {
+ sb.append(' ');
+ }
+ return sb.toString();
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java
new file mode 100644
index 000000000..f336ad877
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/FixtureWorld.java
@@ -0,0 +1,13 @@
+package kamkeel.npcs.fixtures;
+
+/** One generated world. Each answers a different question, so tests can load only what they need. */
+public interface FixtureWorld {
+
+ /** Directory name, and the name a test refers to. */
+ String name();
+
+ /** What this world is for. Goes into the manifest, because a folder of ids explains nothing. */
+ String purpose();
+
+ void build(WorldWriter out);
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java b/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java
new file mode 100644
index 000000000..92d4c8f15
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/Fixtures.java
@@ -0,0 +1,161 @@
+package kamkeel.npcs.fixtures;
+
+import cpw.mods.fml.common.Loader;
+import net.minecraft.init.Bootstrap;
+import net.minecraft.init.Items;
+import net.minecraft.item.Item;
+import net.minecraft.item.ItemStack;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.nbt.NBTTagList;
+import net.minecraft.nbt.NBTTagString;
+import noppes.npcs.NoppesUtilServer;
+import sun.misc.Unsafe;
+
+import java.lang.reflect.Field;
+
+/**
+ * Shared machinery for the fixture generator: bringing Minecraft far enough up to serialize, and
+ * building the item stacks the content refers to.
+ *
+ * Nothing here decides what a fixture contains. That lives in the world builders.
+ */
+public final class Fixtures {
+
+ /**
+ * A fixed instant, used everywhere a fixture wants a timestamp.
+ *
+ *
2021-03-14T01:59:26Z. Any constant would do; what matters is that it is a constant, so
+ * two runs of the generator produce the same bytes and a diff means something changed.
+ */
+ public static final long EPOCH = 1615687166000L;
+
+ private static boolean booted;
+
+ private Fixtures() {
+ }
+
+ /**
+ * Registers vanilla blocks and items so item stacks can be serialized.
+ *
+ *
{@link Item#itemRegistry} is Forge's {@code FMLControlledNamespacedRegistry}, and
+ * {@link noppes.npcs.NoppesUtilServer#writeItem} asks it for a registry name -- so a stack
+ * written before this call would be saved as {@code minecraft:air} rather than failing, which
+ * is the quiet kind of wrong.
+ */
+ public static void bootMinecraft() {
+ if (booted) {
+ return;
+ }
+ installBareLoader();
+ Bootstrap.func_151354_b();
+ booted = true;
+ verifyRegistry();
+ }
+
+ /**
+ * Makes {@code Loader.instance()} answerable without launching FML.
+ *
+ *
Registering an item goes {@code FMLControlledNamespacedRegistry.addObject} ->
+ * {@code GameData.register} -> {@code GameData.addPrefix}, and addPrefix asks
+ * {@code Loader.instance().activeModContainer()} which namespace to use. Reaching that
+ * normally constructs a {@code Loader}, whose constructor builds a {@code ModClassLoader} and
+ * casts its parent to LaunchWrapper's {@code LaunchClassLoader} -- which fails outside a
+ * LaunchWrapper launch, and is where this generator first stopped.
+ *
+ *
So the singleton is filled with an allocated-but-unconstructed Loader. Its
+ * {@code modController} is null, {@code activeModContainer()} returns null, and addPrefix
+ * takes its own documented branch: "no mod container, assume minecraft". That is
+ * exactly the branch real vanilla registration takes, because no mod is active while
+ * {@code Item.registerItems()} runs.
+ *
+ *
Nothing about the naming rule is reimplemented here -- Forge still computes it. What this
+ * removes is only the classloader assumption. {@link #verifyRegistry()} then checks the result
+ * against what real CustomNPC+ save files contain, so the shortcut is measured rather than
+ * trusted. On the registration path {@code Loader} is touched at that one call and nowhere
+ * else; the other uses in GameData are world remapping and mod-declared substitutions.
+ */
+ private static void installBareLoader() {
+ try {
+ Field instance = Loader.class.getDeclaredField("instance");
+ instance.setAccessible(true);
+ if (instance.get(null) != null) {
+ return;
+ }
+ Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
+ theUnsafe.setAccessible(true);
+ Unsafe unsafe = (Unsafe) theUnsafe.get(null);
+ instance.set(null, unsafe.allocateInstance(Loader.class));
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Could not install a bare FML Loader. Without it the item registry cannot be "
+ + "populated outside a LaunchWrapper launch.", e);
+ }
+ }
+
+ /**
+ * Checks that registration produced the names real save files contain.
+ *
+ *
{@code minecraft:diamond}, not {@code diamond}: the prefix comes from Forge, and a
+ * generator that quietly lost it would emit fixtures that every reader tested against them
+ * would then agree with. The expected values here were read out of the CustomNPC+ worlds in
+ * {@code run/saves/}, not from the code that produces them.
+ */
+ private static void verifyRegistry() {
+ String diamond = Item.itemRegistry.getNameForObject(Items.diamond);
+ if (!"minecraft:diamond".equals(diamond)) {
+ throw new IllegalStateException("Item registry produced '" + diamond
+ + "' where real CustomNPC+ saves contain 'minecraft:diamond'. Item stacks in these "
+ + "fixtures would not match anything the mod writes.");
+ }
+ NBTTagCompound probe = new NBTTagCompound();
+ NoppesUtilServer.writeItem(new ItemStack(Items.golden_apple, 2, 1), probe);
+ if (!"minecraft:golden_apple".equals(probe.getString("id"))
+ || probe.getByte("Count") != 2
+ || probe.getShort("Damage") != 1) {
+ throw new IllegalStateException(
+ "NoppesUtilServer.writeItem produced " + probe + ", which is not an item stack.");
+ }
+ }
+
+ /** A stack of a vanilla item, by registry name, so the fixture reads as what it is. */
+ public static ItemStack item(String registryName, int count, int damage) {
+ Item item = (Item) Item.itemRegistry.getObject(registryName);
+ if (item == null) {
+ throw new IllegalArgumentException("No such item: " + registryName);
+ }
+ return new ItemStack(item, count, damage);
+ }
+
+ public static ItemStack item(String registryName, int count) {
+ return item(registryName, count, 0);
+ }
+
+ /**
+ * A stack carrying custom NBT, which is the case that matters most to Scribe: item state above
+ * (id, damage) is what the Flattening and Data Components rearranged.
+ */
+ public static ItemStack namedItem(String registryName, int count, int damage, String displayName) {
+ ItemStack stack = item(registryName, count, damage);
+ NBTTagCompound display = new NBTTagCompound();
+ display.setString("Name", displayName);
+ NBTTagList lore = new NBTTagList();
+ lore.appendTag(new NBTTagString("Written by the Scribe fixture generator"));
+ display.setTag("Lore", lore);
+
+ NBTTagCompound tag = new NBTTagCompound();
+ tag.setTag("display", display);
+ tag.setBoolean("Unbreakable", true);
+ tag.setInteger("RepairCost", 7);
+ stack.stackTagCompound = tag;
+ return stack;
+ }
+
+ /**
+ * A stack whose identity is a pre-Flattening variant -- damage as a variant selector rather
+ * than durability. Scribe converts these through a table that throws on a gap, so a fixture
+ * holding one is the only way to find out which entries the table is still missing.
+ */
+ public static ItemStack variant(String registryName, int count, int variantDamage) {
+ return item(registryName, count, variantDamage);
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java b/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java
new file mode 100644
index 000000000..ac719112d
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/Manifest.java
@@ -0,0 +1,159 @@
+package kamkeel.npcs.fixtures;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * An index of what was generated, why, and where it landed.
+ *
+ *
Deliberately not a second copy of the data. The files are the fixture; this says which file
+ * holds which case, so a test can pick the one it needs without opening twenty of them, and so a
+ * reviewer can see the intent that a compound of integers does not carry.
+ */
+public final class Manifest {
+
+ /** One generated file. */
+ public static final class Entry {
+ final String world;
+ final String system;
+ final String id;
+ final String path;
+ final String note;
+
+ Entry(String world, String system, String id, String path, String note) {
+ this.world = world;
+ this.system = system;
+ this.id = id;
+ this.path = path;
+ this.note = note;
+ }
+ }
+
+ private final List entries = new ArrayList();
+ private final Set warnings = new LinkedHashSet();
+ private final List worlds = new ArrayList();
+
+ public void world(String name, String purpose) {
+ worlds.add(new String[]{name, purpose});
+ }
+
+ public void record(String world, String system, String id, String path, String note) {
+ entries.add(new Entry(world, system, id, path, note));
+ }
+
+ /**
+ * Records something a consumer of these fixtures has to know and could not discover from the
+ * bytes -- above all, the places CustomNPC+ writes a value that changes between runs.
+ */
+ public void warn(String warning) {
+ warnings.add(warning);
+ }
+
+ public Set warnings() {
+ return warnings;
+ }
+
+ public int count() {
+ return entries.size();
+ }
+
+ public int countOf(String system) {
+ int n = 0;
+ for (Entry e : entries) {
+ if (e.system.equals(system)) {
+ n++;
+ }
+ }
+ return n;
+ }
+
+ public void write(File file) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ sb.append("{\n");
+ sb.append(" \"generatedBy\": \"CustomNPC+ scribeFixtures\",\n");
+ sb.append(" \"note\": \"The files are the fixture. This index records intent and location, ");
+ sb.append("not a second copy of the data. Readable renderings of every .dat sit under ");
+ sb.append("/_readable/, written by CustomNPC+'s own NBTJsonUtil.\",\n");
+
+ sb.append(" \"warnings\": [\n");
+ int wi = 0;
+ for (String w : warnings) {
+ sb.append(" ").append(quote(w));
+ sb.append(++wi < warnings.size() ? ",\n" : "\n");
+ }
+ sb.append(" ],\n");
+
+ sb.append(" \"worlds\": {\n");
+ for (int i = 0; i < worlds.size(); i++) {
+ String[] w = worlds.get(i);
+ sb.append(" ").append(quote(w[0])).append(": ").append(quote(w[1]));
+ sb.append(i + 1 < worlds.size() ? ",\n" : "\n");
+ }
+ sb.append(" },\n");
+
+ sb.append(" \"entries\": [\n");
+ for (int i = 0; i < entries.size(); i++) {
+ Entry e = entries.get(i);
+ sb.append(" {");
+ sb.append("\"world\": ").append(quote(e.world));
+ sb.append(", \"system\": ").append(quote(e.system));
+ sb.append(", \"id\": ").append(quote(e.id));
+ sb.append(", \"path\": ").append(quote(e.path));
+ sb.append(", \"note\": ").append(quote(e.note));
+ sb.append("}");
+ sb.append(i + 1 < entries.size() ? ",\n" : "\n");
+ }
+ sb.append(" ]\n");
+ sb.append("}\n");
+
+ Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
+ try {
+ out.write(sb.toString());
+ } finally {
+ out.close();
+ }
+ }
+
+ /**
+ * JSON string escaping. Hand-rolled rather than pulled from a library because the manifest is
+ * the one file here that is not written by CustomNPC+, so it should have no dependency that
+ * could change what it produces between environments.
+ */
+ private static String quote(String s) {
+ StringBuilder sb = new StringBuilder("\"");
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ switch (c) {
+ case '"':
+ sb.append("\\\"");
+ break;
+ case '\\':
+ sb.append("\\\\");
+ break;
+ case '\n':
+ sb.append("\\n");
+ break;
+ case '\r':
+ sb.append("\\r");
+ break;
+ case '\t':
+ sb.append("\\t");
+ break;
+ default:
+ if (c < 0x20 || c > 0x7E) {
+ sb.append(String.format("\\u%04x", (int) c));
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ return sb.append('"').toString();
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java b/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java
new file mode 100644
index 000000000..cb5602a02
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/Normalize.java
@@ -0,0 +1,73 @@
+package kamkeel.npcs.fixtures;
+
+import net.minecraft.nbt.NBTBase;
+import net.minecraft.nbt.NBTTagCompound;
+import net.minecraft.nbt.NBTTagList;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Replaces the values CustomNPC+ writes from the wall clock with a constant.
+ *
+ * This is the one place a generated file departs from what the mod would write, and it exists
+ * because of a specific property of one writer. {@code PlayerMail.writeNBT} does:
+ *
+ *
compound.setLong("TimePast", System.currentTimeMillis() - time);
+ *
+ * and a {@code PlayerMail} hangs off every dialog and every quest whether or not any mail was
+ * configured -- so every dialog and quest file differs between two runs, on that one key.
+ *
+ *
Why normalize rather than document and accept. There is no "the" value here to be
+ * faithful to; the mod writes a different one every second. Left alone, regenerating rewrites all
+ * 70-odd files, so a corpus held in version control churns completely on every run and a real
+ * change is invisible in the noise. Pinning it to zero makes the corpus byte-reproducible, which
+ * is what lets a diff mean something.
+ *
+ *
Zero is also the honest value: {@code TimePast} means "how long ago, relative to now", and a
+ * file on disk has no now. Nothing reads it back -- {@code PlayerMail.readNBT} loads
+ * {@code timePast} and the field is only used for display against a live clock.
+ *
+ *
Every key touched is listed here rather than matched by pattern, and the count is reported,
+ * so this can never quietly grow to cover a field that actually matters.
+ */
+public final class Normalize {
+
+ /** Keys written from the wall clock. Exhaustive, and each one deliberate. */
+ private static final List WALL_CLOCK_KEYS = Arrays.asList("TimePast");
+
+ private Normalize() {
+ }
+
+ /** Rewrites wall-clock keys in place, at any depth. Returns how many were changed. */
+ public static int wallClock(NBTTagCompound compound) {
+ int changed = 0;
+ for (String key : keysOf(compound)) {
+ NBTBase tag = compound.getTag(key);
+ if (tag == null) {
+ continue;
+ }
+ if (WALL_CLOCK_KEYS.contains(key) && tag.getId() == 4) {
+ compound.setLong(key, 0L);
+ changed++;
+ } else if (tag.getId() == 10) {
+ changed += wallClock((NBTTagCompound) tag);
+ } else if (tag.getId() == 9) {
+ NBTTagList list = (NBTTagList) tag;
+ if (list.func_150303_d() == 10) {
+ for (int i = 0; i < list.tagCount(); i++) {
+ // getCompoundTagAt returns the live entry, so this edits in place.
+ changed += wallClock(list.getCompoundTagAt(i));
+ }
+ }
+ }
+ }
+ return changed;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static List keysOf(NBTTagCompound compound) {
+ return new ArrayList(compound.func_150296_c());
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java b/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java
new file mode 100644
index 000000000..522f9d05d
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/Readme.java
@@ -0,0 +1,79 @@
+package kamkeel.npcs.fixtures;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.List;
+
+/** Writes the README that ships beside the generated worlds. */
+public final class Readme {
+
+ private Readme() {
+ }
+
+ public static void write(File file, List worlds, Manifest manifest) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ sb.append("# CustomNPC+ fixtures\n\n");
+ sb.append("Generated by `gradlew scribeFixtures` in the CustomNPC+ repository, on the\n");
+ sb.append("`scribe` branch. Do not edit by hand -- regenerate.\n\n");
+
+ sb.append("## What these are\n\n");
+ sb.append("Real CustomNPC+ save data, written by CustomNPC+'s own serialization running\n");
+ sb.append("against a bootstrapped-but-unlaunched Minecraft. No world was played to produce\n");
+ sb.append("them and no byte here was hand-authored.\n\n");
+ sb.append("That distinction is the whole point. A hand-written `factions.dat` asserts what\n");
+ sb.append("its author believed the format to be, so a reader tested against it only proves\n");
+ sb.append("it agrees with that belief. These files are evidence about the format itself.\n\n");
+
+ sb.append("## Layout\n\n");
+ sb.append("```\n");
+ for (FixtureWorld world : worlds) {
+ sb.append(world.name()).append("/\n");
+ sb.append(" customnpcs/ <- exactly a CustomNPC+ world directory, and nothing else\n");
+ sb.append(" _readable/ <- NBTJsonUtil renderings of the .dat files, for humans\n");
+ }
+ sb.append("manifest.json <- which file holds which case, and why\n");
+ sb.append("```\n\n");
+ sb.append("`customnpcs/` can be dropped straight into a save directory. `_readable/` is a\n");
+ sb.append("debugging aid: it is CustomNPC+'s own JSON rendering, which suffixes scalars\n");
+ sb.append("with their type (`5b`, `5L`, `1.0f`) and so is deliberately not strict JSON.\n\n");
+
+ sb.append("## The worlds\n\n");
+ for (FixtureWorld world : worlds) {
+ sb.append("- **`").append(world.name()).append("`** -- ").append(world.purpose()).append("\n");
+ }
+ sb.append("\n");
+
+ sb.append("## Two formats, not one\n\n");
+ sb.append("- **`.dat`** -- gzipped NBT, written with `CompressedStreamTools`. Factions,\n");
+ sb.append(" custom effects, recipes, magic, animations, linked items, tags, and the rest.\n");
+ sb.append("- **Dialogs and quests are not `.dat`.** They are `NBTJsonUtil` text files at\n");
+ sb.append(" `customnpcs/dialogs//.json`. The directory *is* the category and\n");
+ sb.append(" the filename *is* the id -- neither appears inside the file, because\n");
+ sb.append(" `saveDialog` writes `writeToNBTPartial`, which omits `DialogId`.\n\n");
+
+ sb.append("## Reproducibility\n\n");
+ sb.append("Regenerating produces byte-identical output, with the exceptions below. Those\n");
+ sb.append("are properties of CustomNPC+'s writers, not of this generator.\n\n");
+ for (String warning : manifest.warnings()) {
+ sb.append("- ").append(warning).append("\n");
+ }
+ sb.append("\n");
+
+ sb.append("## Totals\n\n");
+ sb.append("`").append(manifest.count()).append("` files: ");
+ sb.append(manifest.countOf("dialog")).append(" dialogs, ");
+ sb.append(manifest.countOf("quest")).append(" quests, ");
+ sb.append(manifest.count() - manifest.countOf("dialog") - manifest.countOf("quest"));
+ sb.append(" other documents.\n");
+
+ Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
+ try {
+ out.write(sb.toString());
+ } finally {
+ out.close();
+ }
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java b/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java
new file mode 100644
index 000000000..225ebd01a
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/WorldWriter.java
@@ -0,0 +1,189 @@
+package kamkeel.npcs.fixtures;
+
+import net.minecraft.nbt.CompressedStreamTools;
+import net.minecraft.nbt.NBTTagCompound;
+import noppes.npcs.NoppesStringUtils;
+import noppes.npcs.controllers.data.Dialog;
+import noppes.npcs.controllers.data.Quest;
+import noppes.npcs.util.NBTJsonUtil;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+
+/**
+ * Writes one CustomNPC+ world.
+ *
+ * What is authoritative and what is copied. Every byte of content here comes from
+ * CustomNPC+'s own {@code writeToNBT} / {@code writeNBT} and from {@link NBTJsonUtil} and
+ * {@link CompressedStreamTools}. What this class supplies is only where the file goes and what
+ * it is called, because the controllers reach that through
+ * {@code CustomNpcs.getWorldSaveDirectory()}, which returns null without a running server, and
+ * because every {@code save*} fires {@code SyncController.syncUpdate} into a network stack that
+ * does not exist offline.
+ *
+ *
So each method below names the controller and method it was copied from. If a layout changes
+ * upstream, that reference is where to look. The layout logic is a handful of lines per system;
+ * the serialization, which is the part a fixture actually asserts, is never reimplemented.
+ *
+ *
The generated {@code /customnpcs/} directory is exactly a CustomNPC+ world and holds
+ * nothing else. Readable renderings of the binary files go in a sibling {@code _readable/} tree so
+ * that dropping {@code customnpcs/} into a real save is safe.
+ */
+public final class WorldWriter {
+
+ private final String world;
+ private final File root;
+ private final File customnpcs;
+ private final File readable;
+ private final Manifest manifest;
+ private int normalized;
+
+ public WorldWriter(File outputRoot, String world, Manifest manifest) {
+ this.world = world;
+ this.root = new File(outputRoot, world);
+ this.customnpcs = new File(root, "customnpcs");
+ this.readable = new File(root, "_readable");
+ this.manifest = manifest;
+ mkdirs(customnpcs);
+ mkdirs(readable);
+ }
+
+ public String world() {
+ return world;
+ }
+
+ // ------------------------------------------------------------------
+ // Dialogs -- DialogController.saveDialog / loadCategoryDir
+ //
+ // The directory is the category and the filename is the id. Neither appears inside the file:
+ // saveDialog writes writeToNBTPartial, which omits DialogId, and loadCategoryDir recovers the
+ // id by parsing the filename. A dialog's identity is where it sits.
+ // ------------------------------------------------------------------
+ public void dialog(String category, Dialog dialog, String note) {
+ String dir = NoppesStringUtils.cleanFileName(category);
+ File file = new File(new File(customnpcs, "dialogs"), dir + "/" + dialog.id + ".json");
+ writeJson(file, dialog.writeToNBTPartial(new NBTTagCompound()));
+ manifest.record(world, "dialog", String.valueOf(dialog.id), rel(file), note);
+ }
+
+ // ------------------------------------------------------------------
+ // Quests -- QuestController.saveQuest / loadCategoryDir
+ //
+ // Same shape as dialogs, and the same identity rule.
+ // ------------------------------------------------------------------
+ public void quest(String category, Quest quest, String note) {
+ String dir = NoppesStringUtils.cleanFileName(category);
+ File file = new File(new File(customnpcs, "quests"), dir + "/" + quest.id + ".json");
+ writeJson(file, quest.writeToNBTPartial(new NBTTagCompound()));
+ manifest.record(world, "quest", String.valueOf(quest.id), rel(file), note);
+ }
+
+ /**
+ * A dialog written from a compound rather than from a {@link Dialog}.
+ *
+ * Only for the legacy world, which ages a document by removing keys a newer CustomNPC+
+ * added. The compound still comes from CustomNPC+'s writer; what is synthesized is the
+ * subtraction. Every caller must say in its note which keys it removed and why.
+ */
+ public void dialogRaw(String category, int id, NBTTagCompound compound, String note) {
+ String dir = NoppesStringUtils.cleanFileName(category);
+ File file = new File(new File(customnpcs, "dialogs"), dir + "/" + id + ".json");
+ writeJson(file, compound);
+ manifest.record(world, "dialog", String.valueOf(id), rel(file), note);
+ }
+
+ /** As {@link #dialogRaw}, for quests. */
+ public void questRaw(String category, int id, NBTTagCompound compound, String note) {
+ String dir = NoppesStringUtils.cleanFileName(category);
+ File file = new File(new File(customnpcs, "quests"), dir + "/" + id + ".json");
+ writeJson(file, compound);
+ manifest.record(world, "quest", String.valueOf(id), rel(file), note);
+ }
+
+ /**
+ * A gzipped NBT document at the root of the world.
+ *
+ *
The shape every {@code .dat} controller uses -- FactionController.saveFactions,
+ * CustomEffectController.saveCustomEffects, GlobalDataController.save and the rest: build one
+ * compound, {@code CompressedStreamTools.writeCompressed} it, rotate the previous file to
+ * {@code _old}. The rotation is not reproduced, because a generated world has no previous file
+ * and inventing a {@code .dat_old} would be inventing history.
+ */
+ public void dat(String system, String fileName, NBTTagCompound compound, String note) {
+ File file = new File(customnpcs, fileName);
+ mkdirs(file.getParentFile());
+ normalized += Normalize.wallClock(compound);
+ try {
+ OutputStream out = new FileOutputStream(file);
+ try {
+ CompressedStreamTools.writeCompressed(compound, out);
+ } finally {
+ out.close();
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed writing " + file, e);
+ }
+ renderReadable(fileName, compound);
+ manifest.record(world, system, fileName, rel(file), note);
+ }
+
+ /** A JSON document at an explicit path under {@code customnpcs/}, for the per-player records. */
+ public void json(String system, String id, String relativePath, NBTTagCompound compound, String note) {
+ File file = new File(customnpcs, relativePath);
+ writeJson(file, compound);
+ manifest.record(world, system, id, rel(file), note);
+ }
+
+ private void writeJson(File file, NBTTagCompound compound) {
+ mkdirs(file.getParentFile());
+ normalized += Normalize.wallClock(compound);
+ try {
+ NBTJsonUtil.SaveFile(file, compound);
+ } catch (Exception e) {
+ throw new IllegalStateException("Failed writing " + file, e);
+ }
+ }
+
+ /** How many wall-clock values were pinned in this world. See {@link Normalize}. */
+ public int normalizedCount() {
+ return normalized;
+ }
+
+ /**
+ * Writes CustomNPC+'s own JSON rendering of a binary document beside the world, for reading.
+ *
+ *
Not a fixture and not parseable as strict JSON -- NBTJsonUtil suffixes scalars with their
+ * type ({@code 5b}, {@code 5L}, {@code 1.0f}), which is exactly what makes it worth having:
+ * the widths are visible, and a fixture whose value silently became a byte shows up here.
+ */
+ private void renderReadable(String fileName, NBTTagCompound compound) {
+ File file = new File(readable, fileName + ".txt");
+ mkdirs(file.getParentFile());
+ try {
+ Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
+ try {
+ out.write(NBTJsonUtil.Convert(compound));
+ } finally {
+ out.close();
+ }
+ } catch (IOException e) {
+ throw new IllegalStateException("Failed writing " + file, e);
+ }
+ }
+
+ private String rel(File file) {
+ String base = root.getAbsolutePath();
+ String path = file.getAbsolutePath();
+ return path.startsWith(base) ? path.substring(base.length() + 1).replace('\\', '/') : path;
+ }
+
+ private static void mkdirs(File dir) {
+ if (dir != null && !dir.exists() && !dir.mkdirs()) {
+ throw new IllegalStateException("Could not create " + dir);
+ }
+ }
+}
diff --git a/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java b/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java
new file mode 100644
index 000000000..e43b959d0
--- /dev/null
+++ b/src/fixtures/java/kamkeel/npcs/fixtures/content/DialogFixtures.java
@@ -0,0 +1,484 @@
+package kamkeel.npcs.fixtures.content;
+
+import kamkeel.npcs.fixtures.Case;
+import kamkeel.npcs.fixtures.Fixtures;
+import net.minecraft.nbt.NBTTagCompound;
+import noppes.npcs.constants.EnumAvailabilityDialog;
+import noppes.npcs.constants.EnumAvailabilityFaction;
+import noppes.npcs.constants.EnumAvailabilityFactionType;
+import noppes.npcs.constants.EnumAvailabilityQuest;
+import noppes.npcs.constants.EnumDayTime;
+import noppes.npcs.constants.EnumOptionType;
+import noppes.npcs.controllers.data.Dialog;
+import noppes.npcs.controllers.data.DialogImage;
+import noppes.npcs.controllers.data.DialogOption;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Dialogs, built by axis rather than by example.
+ *
+ *
A dialog has about forty fields across six sub-objects, and picking a few realistic-looking
+ * ones covers the fields the author happened to think of. So each block below walks one axis to
+ * its ends -- every enum constant, every slot, both sides of every boolean -- and the id ranges
+ * are reserved per axis so a new case does not renumber the others.
+ *
+ *
Ranges: 1-9 basics, 10-29 options, 30-59 availability, 60-79 appearance, 80-89 images,
+ * 90-99 mail / quest link / faction rewards.
+ */
+public final class DialogFixtures {
+
+ private DialogFixtures() {
+ }
+
+ public static List> maximal() {
+ List> out = new ArrayList>();
+ basics(out);
+ options(out);
+ availability(out);
+ appearance(out);
+ images(out);
+ attachments(out);
+ return out;
+ }
+
+ // ------------------------------------------------------------------ basics
+
+ private static void basics(List> out) {
+ Dialog bare = dialog(1, "Bare", "");
+ out.add(new Case