Compare commits

...
6 Commits
Author SHA1 Message Date
KAMKEEL f0a7a2e698 Write the quest counters the shape the quest classes read
PlayerFixtures wrote extraData.setInteger("Zombie", 14) and its note
claimed that was where kill counts live. QuestKill.getKilled reads
extraData.getTagList("Killed", 10) through NBTTags.getStringIntegerMap
-- a list of Slot/Value compounds. extraData is an opaque compound the
fixture filled by hand, so nothing on either side checked it, and two
of Scribe's migration tests stood on the invented shape for two months.

It writes the real one now, plus the location booleans and a party
quest's group total beside one member's own <playerName>Killed share.

Also a deliberate unreadable case: a quest whose extraData an addon
wrote, with keys no objective kind claims. That case existed by
accident before, as this generator's own defect, and a reader has to
report it rather than drop it.

The counter map is built by hand rather than through NBTTags, so the
fixture states the shape it is asserting -- borrowing the reader's own
helper would agree with it by construction and prove nothing.
2026-08-26 04:15:16 -04:00
KAMKEEL 30f65ca6e0 A shared party dialog objective is always complete
QuestDialog.isPartyCompleted's shared branch builds readValues by recording
only true: a dialog nobody has read is never put in the map at all. The check
underneath returns false only on finding a false, so it never can, and an
empty map returns true besides.

The result is that a party on a shared dialog objective has finished it before
anyone speaks to anybody, and a quest waiting on that objective can be handed
in immediately.

Every required dialog now starts unread, which is the line that was missing.
The loop below it was already right and had nothing to find.

Only the shared mode is affected. All and Leader iterate the dialogs directly
and return false on the first unread one.
2026-08-18 15:23:51 -04:00
KAMKEEL d6d6111803 Merge dev into scribe
Brings in the 1.11.2 version bump and the removal of the shutdown flush that did
not compile. The scribe branch was forked from 8612d444 to avoid that break, so
this is the first point at which it can track dev's tip again.
2026-08-14 00:32:42 -04:00
KAMKEEL b37f57966d Keep the readable renderings out of the world directories
A generated <world>/ is meant to drop straight into a save, and Scribe's smoke
harness copies a data set's contents into a server's world wholesale -- so
anything beside customnpcs/ would be copied in too. The NBTJsonUtil renderings
move to _readable/<world>/ at the output root, which makes each world directory
usable as a cnpc_data_sets overlay with no filtering step.
2026-08-14 00:21:31 -04:00
KAMKEEL 3fc15091fa Cover quests, effects, player records and the world documents
Extends the generator from dialogs and factions to most of what a CustomNPC+
world holds: 146 files where there were 70.

Quests walk every axis -- all six types, all eight repeat modes, both completion
modes, the nine reward slots, the party and profile blocks in both their written
and their omitted form, and each objective kind in depth. Worth recording that a
quest has no availability at all: Quest.readNBTPartial calls
VersionCompatibility.CheckAvailabilityCompatibility, whose name says otherwise,
but that is a generic fill-in-missing-keys pass applied to every ICompatibilty.
Quest declares no Availability field, writeToNBTPartial emits no Availability*
key, and neither does the 1.20 line. Gating belongs to the dialog that offers the
quest.

Custom effects turned out to persist in two places: customeffects.dat is only an
index of {Name, ID}, and each effect is a file under customeffects/ whose
FILENAME is its name -- loadEffectsFromDir overwrites the name key after reading,
so the two can disagree and the file wins. There is a fixture for that, one for
an effect with no name at all (absent from the index, and its file is ".json"),
and one whose script crosses 65535 chars so ScriptContainer splits it across
Script plus ExpandedScript0..N. It splits into two parts; the fixture records
that rather than predicting it.

Player records exercise all fifteen sub-writers, including a quest whose
ExtraData holds the per-objective counters -- the quest itself stores only its
targets, so progress lives nowhere else. Written in both containers, since
ConfigMain.DatFormat picks between JSON and gzipped NBT and a server will have
either. PlayerData.getNBT ends at DBCAddon.instance.writeToNBT, so boot now
constructs the shell addon; without the companion mod every method is a no-op,
which is the state a real server is in.

Also global, tags, transport, banks and spawns. Two shapes there are easy to
miss: a spawn entry numbers its variants as SpawnCompound0..N keys rather than a
list, so they must be probed for; and transport stores a bare int dimension
beside a position, including a modded 7265, which is the signature that stopped
being expressible after 1.16.

Tag.uuid defaults to randomUUID(), so every tag fixture pins one. Two full runs
still diff clean across all 146 files.
2026-08-14 00:20:02 -04:00
KAMKEEL 5f49d28f7c Generate CustomNPC+ save data without launching the game
Scribe needs fixtures to test its readers against, and the only fixtures worth
having are ones CustomNPC+ wrote. A hand-authored factions.dat asserts what its
author believed the format to be, so a reader checked against it proves only
that the two agree.

So this drives the shipping data classes' own writeToNBT/writeNBT against a
bootstrapped-but-unlaunched Minecraft. What is copied rather than executed is
only the layout -- which file, under which directory -- because the controllers
reach that through getWorldSaveDirectory(), which returns null with no server,
and every save* fires SyncController into a network stack that is not there.
Each method names the controller it was copied from.

Two obstacles, both worth recording.

Item stacks needed the registry, and populating it goes through Forge:
FMLControlledNamespacedRegistry -> GameData.addPrefix, which asks
Loader.instance() for the active mod's namespace, and constructing a Loader
casts its classloader to LaunchWrapper's. Rather than reimplement the naming
rule, the singleton is filled with an unconstructed Loader so activeModContainer
returns null and addPrefix takes its own "no mod container, assume minecraft"
branch -- the branch real vanilla registration takes anyway. Verified against
minecraft:diamond as it appears in the worlds under run/saves, so the shortcut
is measured rather than assumed.

Second, nothing was reproducible: PlayerMail.writeNBT stamps TimePast from the
wall clock, and a PlayerMail hangs off every dialog and quest whether or not
mail was configured, so all 67 files differed between runs. Pinned to zero,
which is the only key here rewritten after CustomNPC+ produced it, and the count
is printed every run so it cannot spread quietly. Two runs now diff clean.

Branched from 8612d444 rather than dev, because dev's tip does not compile --
1.11.2-beta1 calls PlayerData.flushEffects() and save(boolean), neither of which
exists -- and because that commit is the baseline Scribe pins as specification.

70 files across four worlds: maximal walks every enum and flag, defaults is what
a fresh world gets, edge is legal content readers get wrong, and legacy ages
documents by removing keys to exercise the upgrade path. Dialogs and factions
so far; the remaining systems follow.
2026-08-14 00:10:02 -04:00
21 changed files with 3094 additions and 0 deletions

No files matched your search

+37
View File
@@ -57,6 +57,43 @@ sourceSets.main.java {
srcDirs += apiDir srcDirs += apiDir
} }
// ============================================================================
// Scribe fixtures -- an offline generator for CustomNPC+ save data.
//
// Its own source set, so nothing here reaches the mod jar. It runs CustomNPC+'s
// own writeToNBT/writeNBT methods against a bootstrapped-but-unlaunched
// Minecraft, and writes the results into a world layout copied from each
// controller. See src/fixtures/README.md.
// ============================================================================
sourceSets {
fixtures {
java.srcDirs = ['src/fixtures/java']
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
runtimeClasspath += sourceSets.main.output + sourceSets.main.runtimeClasspath
}
}
tasks.register('scribeFixtures', JavaExec) {
group 'CustomNPC+'
description 'Generates CustomNPC+ save fixtures for Scribe. -Pout=<dir>, -Pworlds=<a,b>'
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 // TypeScript Definition Generation Task
// Generates .d.ts files from Java API sources for scripting IDE support // Generates .d.ts files from Java API sources for scripting IDE support
@@ -0,0 +1,21 @@
package kamkeel.npcs.fixtures;
/**
* One piece of content, the category it belongs in, and why it exists.
*
* <p>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<T> {
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;
}
}
@@ -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.
*
* <p>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.
*
* <p>Usage: {@code gradlew scribeFixtures -Pout=<dir> [-Pworlds=maximal,edge]}
*/
public final class FixtureGenerator {
private static final List<FixtureWorld> ALL = Arrays.<FixtureWorld>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 <output-dir> [--worlds a,b,c]");
System.exit(2);
}
File out = new File(args[0]).getAbsoluteFile();
List<FixtureWorld> selected = new ArrayList<FixtureWorld>(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.
*
* <p>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<FixtureWorld> select(String csv) {
Map<String, FixtureWorld> byName = new LinkedHashMap<String, FixtureWorld>();
for (FixtureWorld w : ALL) {
byName.put(w.name(), w);
}
List<FixtureWorld> selected = new ArrayList<FixtureWorld>();
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();
}
}
@@ -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);
}
@@ -0,0 +1,168 @@
package kamkeel.npcs.fixtures;
import cpw.mods.fml.common.Loader;
import kamkeel.npcs.addon.DBCAddon;
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.
*
* <p>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.
*
* <p>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.
*
* <p>{@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();
// PlayerData.getNBT ends with DBCAddon.instance.writeToNBT(...), and the field is only set
// by the constructor. DBCAddon is a shell whose methods a companion mod replaces by mixin,
// so every method here is a no-op -- constructing one costs nothing and is what stops a
// player record from throwing on its last line. Without the addon installed this is
// exactly the state a real server is in.
new DBCAddon();
booted = true;
verifyRegistry();
}
/**
* Makes {@code Loader.instance()} answerable without launching FML.
*
* <p>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.
*
* <p>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: <i>"no mod container, assume minecraft"</i>. That is
* exactly the branch real vanilla registration takes, because no mod is active while
* {@code Item.registerItems()} runs.
*
* <p>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.
*
* <p>{@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);
}
}
@@ -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.
*
* <p>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<Entry> entries = new ArrayList<Entry>();
private final Set<String> warnings = new LinkedHashSet<String>();
private final List<String[]> worlds = new ArrayList<String[]>();
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<String> 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("<world>/_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();
}
}
@@ -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.
*
* <p>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:
*
* <pre>compound.setLong("TimePast", System.currentTimeMillis() - time);</pre>
*
* <p>and a {@code PlayerMail} hangs off every dialog and every quest whether or not any mail was
* configured -- so <i>every</i> dialog and quest file differs between two runs, on that one key.
*
* <p><b>Why normalize rather than document and accept.</b> 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.
*
* <p>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.
*
* <p>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<String> 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<String> keysOf(NBTTagCompound compound) {
return new ArrayList<String>(compound.func_150296_c());
}
}
@@ -0,0 +1,81 @@
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<FixtureWorld> 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("/customnpcs/ <- a CustomNPC+ world directory, and nothing else\n");
}
sb.append("_readable/<world>/ <- 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("Each `<world>/` holds `customnpcs/` and nothing else, so it drops straight into\n");
sb.append("a save directory -- or, in Scribe, works as-is as a `cnpc_data_sets` overlay.\n");
sb.append("The readable renderings sit outside the world directories for that reason.\n\n");
sb.append("`_readable/` is a debugging aid, not a fixture: it is CustomNPC+'s own JSON\n");
sb.append("rendering, which suffixes scalars with their type (`5b`, `5L`, `1.0f`) and is\n");
sb.append("therefore deliberately not strict JSON. The widths being visible is the point.\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/<category>/<id>.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();
}
}
}
@@ -0,0 +1,221 @@
package kamkeel.npcs.fixtures;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.controllers.data.CustomEffect;
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.
*
* <p><b>What is authoritative and what is copied.</b> 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 <i>where the file goes and what
* it is called</i>, 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.
*
* <p>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.
*
* <p>The generated {@code <world>/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");
// Outside the world directory, not inside it. A generated <world>/ is meant to be usable
// as a drop-in overlay -- Scribe's smoke harness copies a set's contents straight into a
// server's world -- so it must contain customnpcs/ and nothing else.
this.readable = new File(new File(outputRoot, "_readable"), world);
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);
}
// ------------------------------------------------------------------
// Custom effects -- CustomEffectController.saveCustomEffect / loadEffectsFromDir
//
// The filename is the name: loadEffectsFromDir overwrites whatever `name` the file contained
// with the filename minus .json. An empty category means the effect sits at the root of
// customeffects/, which is what CategoryManager calls Uncategorized -- there is no category
// file anywhere, only the directory.
// ------------------------------------------------------------------
public void effect(String category, CustomEffect effect, String note) {
effect(category, effect.getName(), effect, note);
}
/**
* As {@link #effect}, with the filename stated separately.
*
* <p>Needed because the filename and the {@code name} key are genuinely independent on disk,
* and a fixture proving the loader prefers the filename has to be able to disagree with it.
*/
public void effect(String category, String fileName, CustomEffect effect, String note) {
File dir = new File(customnpcs, "customeffects");
if (category != null && !category.isEmpty()) {
dir = new File(dir, NoppesStringUtils.cleanFileName(category));
}
File file = new File(dir, NoppesStringUtils.cleanFileName(fileName) + ".json");
writeJson(file, effect.writeToNBT(true));
manifest.record(world, "effect", String.valueOf(effect.id), rel(file), note);
}
/**
* A dialog written from a compound rather than from a {@link Dialog}.
*
* <p>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.
*
* <p>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.
*
* <p>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);
}
}
}
@@ -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.
*
* <p>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.
*
* <p>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<Case<Dialog>> maximal() {
List<Case<Dialog>> out = new ArrayList<Case<Dialog>>();
basics(out);
options(out);
availability(out);
appearance(out);
images(out);
attachments(out);
return out;
}
// ------------------------------------------------------------------ basics
private static void basics(List<Case<Dialog>> out) {
Dialog bare = dialog(1, "Bare", "");
out.add(new Case<Dialog>("Basics", bare,
"every field left at its constructor default, with an empty text. The baseline a "
+ "reader's defaults are compared against"));
Dialog plain = dialog(2, "Plain Greeting",
"Hello {player},\n\nWelcome to our village. I hope you enjoy your stay");
out.add(new Case<Dialog>("Basics", plain,
"title and text only, with the {player} placeholder and embedded newlines that "
+ "CustomNPC+'s own default dialog uses"));
Dialog longText = dialog(3, "Long Text", repeat(
"This sentence exists so the stored text crosses the length CustomNPC+ warns about. ", 200));
out.add(new Case<Dialog>("Basics", longText,
"text over 15000 chars, which DialogController logs as an 'Extremely big dialog'. "
+ "Loads normally -- the check is a warning, not a limit"));
Dialog unicode = dialog(4, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES,
Text.CYRILLIC_QUEST + "\n" + Text.RTL + "\n" + Text.ASTRAL);
out.add(new Case<Dialog>("Basics", unicode,
"title and text outside Latin-1, including one astral-plane code point. NBT strings "
+ "are modified UTF-8, so the astral char is stored as a surrogate pair"));
Dialog formatted = dialog(5, Text.SECTION + "6Formatted " + Text.SECTION + "lTitle",
Text.SECTION + "cRed " + Text.SECTION + "aGreen " + Text.SECTION + "r" + "plain");
out.add(new Case<Dialog>("Basics", formatted,
"section-sign colour codes in title and text, which is how all CustomNPC+ content is "
+ "coloured"));
Dialog command = dialog(6, "Runs A Command", "The gate opens.");
command.command = "/say {player} opened the gate";
out.add(new Case<Dialog>("Basics", command,
"DialogCommand set -- a command run on the server when the dialog opens"));
Dialog sounds = dialog(7, "Sounds", "Listen.");
sounds.sound = "customnpcs:dialog.open";
sounds.textSound = "minecraft:random.orb";
sounds.textPitch = 0.75F;
out.add(new Case<Dialog>("Basics", sounds,
"DialogSound plus a non-default TextSound and TextPitch. Note DialogSound is written "
+ "only when non-empty, so the key is absent on every other dialog here"));
}
// ------------------------------------------------------------------ options
private static void options(List<Case<Dialog>> out) {
// One dialog per option type, because the type drives what the other fields mean.
int id = 10;
for (EnumOptionType type : EnumOptionType.values()) {
Dialog d = dialog(id, "Option " + type.name(), "Choose.");
DialogOption option = new DialogOption();
option.title = type.name() + " option";
option.optionType = type;
option.dialogId = type == EnumOptionType.DialogOption ? 2 : -1;
option.optionColor = 0x00FF00;
option.command = type == EnumOptionType.CommandBlock ? "/time set day" : "";
d.options.put(0, option);
out.add(new Case<Dialog>("Options", d,
"a single option of type " + type.name() + " (ordinal " + type.ordinal() + ")"));
id++;
}
Dialog full = dialog(20, "Six Options", "Pick one.");
for (int slot = 0; slot < 6; slot++) {
DialogOption option = new DialogOption();
option.title = "Option in slot " + slot;
option.optionType = EnumOptionType.DialogOption;
option.dialogId = 2;
option.optionColor = 0x100000 * (slot + 1);
full.options.put(slot, option);
}
out.add(new Case<Dialog>("Options", full,
"six options in contiguous slots 0-5, each a different colour"));
// Slots are a map key, not a list index. A reader that treats Options as an ordered list
// silently renumbers this one.
Dialog sparse = dialog(21, "Sparse Slots", "The gaps matter.");
int[] slots = {0, 3, 7, 12};
for (int slot : slots) {
DialogOption option = new DialogOption();
option.title = "Slot " + slot;
option.optionType = EnumOptionType.DialogOption;
option.dialogId = 2;
sparse.options.put(slot, option);
}
out.add(new Case<Dialog>("Options", sparse,
"options at non-contiguous slots 0, 3, 7 and 12. OptionSlot is stored per entry, so "
+ "the gaps survive; a reader treating the list as positional loses them"));
Dialog dangling = dialog(22, "Dangling Option", "Where does this go?");
DialogOption toNowhere = new DialogOption();
toNowhere.title = "To a dialog that is not here";
toNowhere.optionType = EnumOptionType.DialogOption;
toNowhere.dialogId = 999999;
dangling.options.put(0, toNowhere);
out.add(new Case<Dialog>("Options", dangling,
"an option pointing at a dialog id that does not exist in this world. Conversion must "
+ "keep the id rather than resolve it"));
Dialog emptyTitle = dialog(23, "Empty Option Title", "...");
DialogOption blank = new DialogOption();
blank.title = "";
blank.optionType = EnumOptionType.DialogOption;
blank.dialogId = 2;
blank.optionColor = 0;
emptyTitle.options.put(0, blank);
out.add(new Case<Dialog>("Options", emptyTitle,
"an option with an empty title and DialogColor 0. On read, colour 0 is replaced by the "
+ "default 0xe0e0e0 -- so this file does not round-trip, by design upstream"));
}
// ------------------------------------------------------------------ availability
private static void availability(List<Case<Dialog>> out) {
// Every EnumAvailabilityQuest constant, one dialog each. These are the rules whose loss
// makes a gated dialog visible to everybody, so each constant gets its own file.
int id = 30;
for (EnumAvailabilityQuest rule : EnumAvailabilityQuest.values()) {
Dialog d = dialog(id, "Quest rule " + rule.name(), "Gated on a quest.");
d.availability.questAvailable = rule;
d.availability.questId = 1;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityQuest = " + rule.name() + " (ordinal " + rule.ordinal()
+ ") against quest 1"));
id++;
}
// All four quest slots at once, each a different rule and a different target.
Dialog fourQuests = dialog(40, "Four Quest Rules", "Four gates.");
fourQuests.availability.questAvailable = EnumAvailabilityQuest.After;
fourQuests.availability.questId = 1;
fourQuests.availability.quest2Available = EnumAvailabilityQuest.Before;
fourQuests.availability.quest2Id = 2;
fourQuests.availability.quest3Available = EnumAvailabilityQuest.Active;
fourQuests.availability.quest3Id = 3;
fourQuests.availability.quest4Available = EnumAvailabilityQuest.NotAcceptable;
fourQuests.availability.quest4Id = 4;
out.add(new Case<Dialog>("Availability", fourQuests,
"all four AvailabilityQuest slots set to different rules and different quests. The "
+ "case a reader that reads only the first slot passes anyway"));
int dialogRuleId = 41;
for (EnumAvailabilityDialog rule : EnumAvailabilityDialog.values()) {
Dialog d = dialog(dialogRuleId, "Dialog rule " + rule.name(), "Gated on a dialog.");
d.availability.dialogAvailable = rule;
d.availability.dialogId = 2;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityDialog = " + rule.name() + " against dialog 2 -- read tracking"));
dialogRuleId++;
}
Dialog fourDialogs = dialog(44, "Four Dialog Rules", "Four read-gates.");
fourDialogs.availability.dialogAvailable = EnumAvailabilityDialog.After;
fourDialogs.availability.dialogId = 1;
fourDialogs.availability.dialog2Available = EnumAvailabilityDialog.Before;
fourDialogs.availability.dialog2Id = 2;
fourDialogs.availability.dialog3Available = EnumAvailabilityDialog.After;
fourDialogs.availability.dialog3Id = 3;
fourDialogs.availability.dialog4Available = EnumAvailabilityDialog.Before;
fourDialogs.availability.dialog4Id = 4;
out.add(new Case<Dialog>("Availability", fourDialogs,
"all four AvailabilityDialog slots set"));
// Faction rules: type x stance, both slots.
int factionRuleId = 45;
for (EnumAvailabilityFactionType type : EnumAvailabilityFactionType.values()) {
for (EnumAvailabilityFaction stance : EnumAvailabilityFaction.values()) {
if (type == EnumAvailabilityFactionType.Always && stance != EnumAvailabilityFaction.Friendly) {
continue; // Always ignores the stance; one file is enough for it.
}
Dialog d = dialog(factionRuleId, "Faction " + type.name() + " " + stance.name(),
"Gated on standing.");
d.availability.factionAvailable = type;
d.availability.factionStance = stance;
d.availability.factionId = 10;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityFaction = " + type.name() + ", stance " + stance.name()
+ ", against faction 10 (Hidden Watchers)"));
factionRuleId++;
}
}
Dialog bothFactions = dialog(53, "Both Faction Slots", "Two standings.");
bothFactions.availability.factionAvailable = EnumAvailabilityFactionType.Is;
bothFactions.availability.factionStance = EnumAvailabilityFaction.Friendly;
bothFactions.availability.factionId = 0;
bothFactions.availability.faction2Available = EnumAvailabilityFactionType.IsNot;
bothFactions.availability.faction2Stance = EnumAvailabilityFaction.Hostile;
bothFactions.availability.faction2Id = 2;
out.add(new Case<Dialog>("Availability", bothFactions,
"both faction slots, one Is/Friendly and one IsNot/Hostile"));
int daytimeId = 54;
for (EnumDayTime time : EnumDayTime.values()) {
Dialog d = dialog(daytimeId, "Daytime " + time.name(), "Time-gated.");
d.availability.daytime = time;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityDayTime = " + time.name() + " (ordinal " + time.ordinal() + ")"));
daytimeId++;
}
Dialog level = dialog(57, "Min Level", "You look experienced.");
level.availability.minPlayerLevel = 30;
out.add(new Case<Dialog>("Availability", level,
"AvailabilityMinPlayerLevel = 30"));
Dialog everything = dialog(58, "Every Rule At Once", "Nothing gets through this.");
everything.availability.daytime = EnumDayTime.Night;
everything.availability.minPlayerLevel = 99;
everything.availability.dialogAvailable = EnumAvailabilityDialog.After;
everything.availability.dialogId = 1;
everything.availability.dialog2Available = EnumAvailabilityDialog.Before;
everything.availability.dialog2Id = 2;
everything.availability.dialog3Available = EnumAvailabilityDialog.After;
everything.availability.dialog3Id = 3;
everything.availability.dialog4Available = EnumAvailabilityDialog.Before;
everything.availability.dialog4Id = 4;
everything.availability.questAvailable = EnumAvailabilityQuest.After;
everything.availability.questId = 1;
everything.availability.quest2Available = EnumAvailabilityQuest.Active;
everything.availability.quest2Id = 2;
everything.availability.quest3Available = EnumAvailabilityQuest.NotActive;
everything.availability.quest3Id = 3;
everything.availability.quest4Available = EnumAvailabilityQuest.Acceptable;
everything.availability.quest4Id = 4;
everything.availability.factionAvailable = EnumAvailabilityFactionType.Is;
everything.availability.factionStance = EnumAvailabilityFaction.Friendly;
everything.availability.factionId = 0;
everything.availability.faction2Available = EnumAvailabilityFactionType.IsNot;
everything.availability.faction2Stance = EnumAvailabilityFaction.Hostile;
everything.availability.faction2Id = 2;
out.add(new Case<Dialog>("Availability", everything,
"every availability slot set simultaneously -- ten rules plus daytime and level. The "
+ "single densest availability block in these fixtures"));
}
// ------------------------------------------------------------------ appearance
private static void appearance(List<Case<Dialog>> out) {
Dialog flags = dialog(60, "Flags Inverted", "Every boolean off its default.");
flags.hideNPC = true;
flags.showWheel = true;
flags.disableEsc = true;
flags.darkenScreen = false;
flags.showOptionLine = false;
flags.renderGradual = true;
flags.showPreviousBlocks = false;
out.add(new Case<Dialog>("Appearance", flags,
"all seven display booleans flipped away from their defaults. Four of them read back "
+ "as true when their key is absent, so a writer that omits defaults changes "
+ "behaviour"));
Dialog colors = dialog(61, "Colors", "Coloured.");
colors.color = 0x336699;
colors.titleColor = 0xCC3300;
out.add(new Case<Dialog>("Appearance", colors,
"Color and TitleColor off the 0xe0e0e0 default"));
Dialog colorData = dialog(62, "Color Data Enabled", "Full chrome colours.");
colorData.colorData.setEnableColorSettings(true);
colorData.colorData.setLineColor1(0xff112233);
colorData.colorData.setLineColor2(0xff445566);
colorData.colorData.setLineColor3(0xff778899);
colorData.colorData.setSlotColor(0xffaabbcc);
colorData.colorData.setButtonAcceptColor(0xff00ff00);
colorData.colorData.setButtonRejectColor(0xffff0000);
out.add(new Case<Dialog>("Appearance", colorData,
"DialogColorData with ColorSettings enabled and all six colours set. The six keys are "
+ "written ONLY when the flag is on -- see id 63 for the other half"));
Dialog colorDataOff = dialog(63, "Color Data Disabled", "Colours set but not enabled.");
colorDataOff.colorData.setEnableColorSettings(false);
colorDataOff.colorData.setLineColor1(0xff112233);
colorDataOff.colorData.setSlotColor(0xffaabbcc);
out.add(new Case<Dialog>("Appearance", colorDataOff,
"ColorSettings off with colours assigned. Proves the six colour keys are absent from "
+ "the file, so the values are lost upstream and there is nothing to convert"));
Dialog layout = dialog(64, "Layout", "Positioned.");
layout.textWidth = 420;
layout.textHeight = 260;
layout.textOffsetX = -12;
layout.textOffsetY = 34;
layout.titlePos = 2;
layout.titleOffsetX = 8;
layout.titleOffsetY = -6;
layout.optionOffsetX = 5;
layout.optionOffsetY = -5;
layout.optionSpaceX = 3;
layout.optionSpaceY = 14;
layout.npcScale = 2.25F;
layout.npcOffsetX = -40;
layout.npcOffsetY = 18;
out.add(new Case<Dialog>("Appearance", layout,
"every geometry field set, several negative. Fourteen integers and one float that a "
+ "dialog screen has to place things by"));
for (byte alignment = 0; alignment <= 2; alignment++) {
Dialog d = dialog(65 + alignment, "Alignment " + alignment, "Aligned.");
d.alignment = alignment;
out.add(new Case<Dialog>("Appearance", d,
"DialogAlignment = " + alignment + " (0 bottom, 1 top, 2 centre). Stored as a byte, "
+ "not an int -- the one narrow scalar on a dialog"));
}
}
// ------------------------------------------------------------------ images
private static void images(List<Case<Dialog>> out) {
Dialog one = dialog(80, "One Image", "Look.");
one.dialogImages.put(0, image(0, "customnpcs:textures/gui/dialog.png", 1));
out.add(new Case<Dialog>("Images", one,
"a single DialogImage with every field at a non-default"));
Dialog many = dialog(81, "Three Images", "Look again.");
for (int i = 0; i < 3; i++) {
DialogImage img = image(i, "customnpcs:textures/gui/image" + i + ".png", i);
img.x = 10 * i;
img.y = 20 * i;
img.alignment = i;
many.dialogImages.put(i, img);
}
out.add(new Case<Dialog>("Images", many,
"three images with imageType 0, 1 and 2 -- Default, Text and Option"));
Dialog defaults = dialog(82, "Default Image", "An untouched image.");
defaults.dialogImages.put(0, new DialogImage(0));
out.add(new Case<Dialog>("Images", defaults,
"a DialogImage left entirely at its constructor defaults, including an empty texture"));
}
// ------------------------------------------------------------------ attachments
private static void attachments(List<Case<Dialog>> out) {
Dialog quest = dialog(90, "Starts A Quest", "Take this.");
quest.quest = 1;
out.add(new Case<Dialog>("Attachments", quest,
"DialogQuest = 1 -- opening this dialog starts quest 1. The link a conversion that "
+ "drops the field turns into a quest nobody can be given"));
Dialog mail = dialog(91, "Sends Mail", "Check your inbox.");
mail.mail.subject = "A letter from the village";
mail.mail.sender = "Elder Marrow";
mail.mail.time = Fixtures.EPOCH;
mail.mail.beenRead = false;
NBTTagCompound message = new NBTTagCompound();
message.setString("Text", "Thank you for your help.");
mail.mail.message = message;
mail.mail.items[0] = Fixtures.item("minecraft:golden_apple", 3, 1);
mail.mail.items[2] = Fixtures.namedItem("minecraft:diamond_sword", 1, 12, "Villager's Thanks");
out.add(new Case<Dialog>("Attachments", mail,
"DialogMail with subject, sender, a message compound and two of four item slots -- "
+ "one of them a variant damage, one carrying custom NBT. NOTE: TimePast inside "
+ "this compound is not reproducible between runs"));
Dialog reward = dialog(92, "Faction Reward", "The Legion remembers.");
reward.factionOptions.factionId = 14;
reward.factionOptions.factionPoints = 250;
reward.factionOptions.decreaseFactionPoints = false;
reward.factionOptions.faction2Id = 15;
reward.factionOptions.faction2Points = 100;
reward.factionOptions.decreaseFaction2Points = true;
out.add(new Case<Dialog>("Attachments", reward,
"both faction reward slots -- one granting points, one decreasing them"));
Dialog everything = dialog(93, "Everything At Once",
"This dialog exercises every sub-object CustomNPC+ hangs off a dialog.");
everything.quest = 2;
everything.command = "/say done";
everything.sound = "customnpcs:dialog.open";
everything.color = 0x445566;
everything.titleColor = 0x998877;
everything.hideNPC = true;
everything.renderGradual = true;
everything.npcScale = 1.5F;
everything.availability.daytime = EnumDayTime.Day;
everything.availability.minPlayerLevel = 5;
everything.availability.questAvailable = EnumAvailabilityQuest.Before;
everything.availability.questId = 3;
everything.factionOptions.factionId = 0;
everything.factionOptions.factionPoints = 10;
everything.colorData.setEnableColorSettings(true);
everything.colorData.setSlotColor(0xff00ffff);
everything.mail.subject = "Everything";
everything.mail.sender = "The Generator";
everything.mail.time = Fixtures.EPOCH;
everything.mail.items[0] = Fixtures.item("minecraft:emerald", 64);
everything.dialogImages.put(0, image(0, "customnpcs:textures/gui/all.png", 2));
DialogOption opt = new DialogOption();
opt.title = "Continue";
opt.optionType = EnumOptionType.DialogOption;
opt.dialogId = 2;
opt.optionColor = 0xFFAA00;
everything.options.put(0, opt);
out.add(new Case<Dialog>("Attachments", everything,
"one dialog touching every sub-object at once: options, availability, faction rewards, "
+ "colour data, mail, an image and a quest link"));
}
// ------------------------------------------------------------------ helpers
private static Dialog dialog(int id, String title, String text) {
Dialog dialog = new Dialog();
dialog.id = id;
dialog.title = title;
dialog.text = text;
return dialog;
}
private static DialogImage image(int id, String texture, int imageType) {
DialogImage image = new DialogImage(id);
image.texture = texture;
image.x = 12;
image.y = 34;
image.width = 64;
image.height = 48;
image.textureX = 8;
image.textureY = 16;
image.scale = 1.75F;
image.color = 0x88CCFF;
image.selectedColor = 0xFFCC88;
image.alpha = 0.5F;
image.rotation = 45.0F;
image.imageType = imageType;
image.alignment = 1;
return image;
}
static String repeat(String s, int times) {
StringBuilder sb = new StringBuilder(s.length() * times);
for (int i = 0; i < times; i++) {
sb.append(s);
}
return sb.toString();
}
}
@@ -0,0 +1,187 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.EffectScript;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Custom effects, which persist in two places at once.
*
* <p>Each effect is a file at {@code customeffects/<Name>.json} -- or
* {@code customeffects/<Category>/<Name>.json}, where the subdirectory is the category -- written
* with {@code writeToNBT(true)}. <b>The filename is the name</b>: {@code loadEffectsFromDir}
* overwrites whatever {@code name} the file contained with the filename minus {@code .json}, so
* the {@code name} key inside is dead weight and the two can legitimately disagree. There is a
* fixture for that below.
*
* <p>Alongside them, {@code customeffects.dat} is an index of {@code {Name, ID}} pairs plus
* {@code lastID} -- not the effects themselves. An effect whose name is empty is left out of the
* index entirely, which is its own case.
*/
public final class EffectFixtures {
private EffectFixtures() {
}
public static List<Case<CustomEffect>> maximal() {
List<Case<CustomEffect>> out = new ArrayList<Case<CustomEffect>>();
CustomEffect bare = effect(1, "Bare");
out.add(new Case<CustomEffect>("", bare,
"every field at its constructor default. Note menuName defaults to a coloured "
+ "'NEW EFFECT' containing a section sign, so even the bare case is not ASCII"));
CustomEffect full = effect(2, "Fully Configured");
full.menuName = Text.SECTION + "bFully " + Text.SECTION + "6Configured";
full.length = 1200;
full.everyXTick = 10;
full.lossOnDeath = false;
full.icon = "customnpcs:textures/gui/effects.png";
full.iconX = 32;
full.iconY = 48;
full.width = 24;
full.height = 24;
out.add(new Case<CustomEffect>("", full,
"every scalar off its default: a 60-second duration, a 10-tick period, an icon with "
+ "its atlas offsets and size, and lossOnDeath cleared"));
CustomEffect animated = effect(3, "Animated Icon");
animated.animated = true;
animated.frameCount = 8;
animated.frametime = 3;
animated.icon = "customnpcs:textures/gui/anim.png";
out.add(new Case<CustomEffect>("", animated,
"an animated icon -- iconAnimated, iconFrameCount and iconFrameTime. Both counts are "
+ "clamped to a minimum of 1 on read, so zero cannot round-trip"));
CustomEffect tagged = effect(4, "Tagged");
tagged.tagUUIDs.addAll(Arrays.asList(
UUID.fromString("0e5f2b6a-1c3d-4e5f-8a9b-0c1d2e3f4a5b"),
UUID.fromString("1a2b3c4d-5e6f-4071-8293-a4b5c6d7e8f9"),
UUID.fromString("ffffffff-ffff-4fff-bfff-ffffffffffff")));
out.add(new Case<CustomEffect>("", tagged,
"three tag UUIDs. TagController.writeTagUUIDs omits the key entirely when the set is "
+ "empty, so every other effect here has no TagUUIDs key at all"));
CustomEffect scripted = effect(5, "Scripted");
scripted.setScriptHandler(script(
"function onEffectAdd(event) { event.player.message('effect added'); }\n"
+ "function onEffectTick(event) {}\n"
+ "function onEffectRemove(event) {}\n", true, "ECMAScript"));
out.add(new Case<CustomEffect>("", scripted,
"a ScriptData compound carrying ScriptLanguage, ScriptEnabled and a ScriptContent "
+ "unit with three hook functions"));
CustomEffect scriptDisabled = effect(6, "Script Disabled");
scriptDisabled.setScriptHandler(script("function onEffectTick(event) {}", false, "javascript"));
out.add(new Case<CustomEffect>("", scriptDisabled,
"ScriptEnabled false, and a language string that is not the canonical 'ECMAScript' -- "
+ "normalizeLanguage runs on read, not on write"));
CustomEffect hugeScript = effect(7, "Huge Script");
StringBuilder sb = new StringBuilder();
while (sb.length() < 70000) {
sb.append("// a line of script that exists only to push past the 65535 char limit\n");
}
hugeScript.setScriptHandler(script(sb.toString(), true, "ECMAScript"));
out.add(new Case<CustomEffect>("", hugeScript,
"a script over 65535 characters. NBT strings cannot hold that, so ScriptContainer "
+ "splits it across Script plus ExpandedScript0..N, bounded by "
+ "ConfigScript.ExpandedScriptLimit which defaults to 2. Check the written file "
+ "to see how many parts survived -- this fixture exists to record that"));
CustomEffect noName = effect(8, "");
out.add(new Case<CustomEffect>("", noName,
"an EMPTY name. writeMapNBT skips these, so this effect is absent from "
+ "customeffects.dat while its file exists on disk -- and since the filename is "
+ "the name, its file is '.json'. Recorded rather than avoided"));
CustomEffect categorised = effect(10, "In A Category");
out.add(new Case<CustomEffect>("Buffs", categorised,
"an effect inside a category subdirectory. Categories are directories and nothing "
+ "else -- there is no category file and no id stored anywhere"));
CustomEffect unicode = effect(11, "Unicode");
unicode.menuName = Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES;
out.add(new Case<CustomEffect>("Buffs", unicode,
"a non-Latin menu name inside a category"));
CustomEffect extremes = effect(12, "Extremes");
extremes.length = Integer.MAX_VALUE;
extremes.everyXTick = Integer.MAX_VALUE;
extremes.iconX = Integer.MIN_VALUE;
extremes.iconY = Integer.MIN_VALUE;
extremes.width = 0;
extremes.height = 0;
extremes.frameCount = 0;
extremes.frametime = 0;
out.add(new Case<CustomEffect>("", extremes,
"integer boundaries, plus zero width, height, frame count and frame time. Width and "
+ "height fall back to 16 on read only when their key is ABSENT, so an explicit "
+ "zero survives where a missing key does not"));
return out;
}
/**
* The filename for {@link #nameMismatch()}, deliberately unequal to the effect's name field.
*/
public static final String MISMATCH_FILENAME = "Name On Disk";
/**
* An effect whose {@code name} key disagrees with its filename.
*
* <p>Kept out of {@link #maximal()} because it cannot be expressed there: everything in that
* list is written to a file named after the effect, which is what makes a mismatch impossible
* to state. loadEffectsFromDir assigns {@code effect.name} from the filename after reading, so
* the key inside is discarded and a reader that trusts it gets a different answer.
*/
public static CustomEffect nameMismatch() {
CustomEffect mismatched = effect(9, "Name Inside The File");
return mismatched;
}
/** The index document. Copied from CustomEffectController.writeMapNBT. */
public static NBTTagCompound index(List<Case<CustomEffect>> effects, int lastUsedId) {
NBTTagList list = new NBTTagList();
for (Case<CustomEffect> c : effects) {
CustomEffect effect = c.value;
// writeMapNBT skips unnamed effects. Reproduced, because the omission is the contract.
if (!effect.getName().isEmpty()) {
NBTTagCompound entry = new NBTTagCompound();
entry.setString("Name", effect.getName());
entry.setInteger("ID", effect.id);
list.appendTag(entry);
}
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("CustomEffects", list);
compound.setInteger("lastID", lastUsedId);
return compound;
}
private static CustomEffect effect(int id, String name) {
CustomEffect effect = new CustomEffect();
effect.id = id;
effect.name = name;
return effect;
}
private static EffectScript script(String source, boolean enabled, String language) {
EffectScript handler = new EffectScript();
handler.setLanguage(language);
handler.setEnabled(enabled);
ScriptContainer container = new ScriptContainer(handler);
container.script = source;
handler.addScriptUnit(container);
return handler;
}
}
@@ -0,0 +1,153 @@
package kamkeel.npcs.fixtures.content;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.Faction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Factions, and the {@code factions.dat} document that holds them.
*
* <p>Layout copied from FactionController.getNBT: {@code lastID} plus an {@code NPCFactions} list
* of {@link Faction#writeNBT} compounds. The controller iterates a HashMap; this iterates a list,
* so the order is stable between runs. Order is not part of the format -- the loader keys each
* entry on its own {@code Slot} -- but an unstable order would make every regeneration a diff.
*/
public final class FactionFixtures {
private FactionFixtures() {
}
/** The three CustomNPC+ creates for a new world, when factions.dat is absent or empty. */
public static List<Faction> vanillaDefaults() {
return new ArrayList<Faction>(Arrays.asList(
new Faction(0, "Friendly", 0x00DD00, 2000),
new Faction(1, "Neutral", 0xF2DD00, 1000),
new Faction(2, "Aggressive", 0xDD0000, 0)));
}
/**
* Every flag and threshold moved off its default, and the mutual-hostility graph populated.
*
* <p>The three booleans are the interesting part for a port: {@code hideFaction} suppresses the
* standing message, {@code getsAttacked} lets vanilla mobs target members, {@code isPassive}
* stops members retaliating. They are independent, so they get an entry each rather than one
* faction with all three set.
*/
public static List<Faction> maximal() {
List<Faction> factions = vanillaDefaults();
Faction hidden = faction(10, "Hidden Watchers", 0x2B2B2B, 900);
hidden.hideFaction = true;
hidden.neutralPoints = 250;
hidden.friendlyPoints = 2750;
factions.add(hidden);
Faction attacked = faction(11, "Hunted", 0xAA5500, 1200);
attacked.getsAttacked = true;
factions.add(attacked);
Faction passive = faction(12, "Pacifists", 0x55FFFF, 1800);
passive.isPassive = true;
factions.add(passive);
Faction all = faction(13, "Every Flag", 0xFF00FF, 0);
all.hideFaction = true;
all.getsAttacked = true;
all.isPassive = true;
all.neutralPoints = 0;
all.friendlyPoints = 0;
factions.add(all);
// A hostility graph rather than a single edge: the reader has to keep a set per faction,
// and a reader that keeps one integer looks correct until the second entry.
Faction warring = faction(14, "Iron Legion", 0xB0B0B0, 400);
warring.attackFactions.addAll(Arrays.asList(2, 10, 11, 12));
factions.add(warring);
Faction rival = faction(15, "Ash Covenant", 0x7A0000, 600);
rival.attackFactions.addAll(Arrays.asList(14, 0));
factions.add(rival);
// Thresholds inverted -- friendly below neutral. CustomNPC+ does not validate this, and
// Availability and Faction read the boundary differently, so it is worth having on disk.
Faction inverted = faction(16, "Inverted Bands", 0x123456, 1000);
inverted.neutralPoints = 1800;
inverted.friendlyPoints = 200;
factions.add(inverted);
Faction negative = faction(17, "Debtors", 0x000080, -500);
negative.neutralPoints = -1000;
negative.friendlyPoints = -100;
factions.add(negative);
return factions;
}
/** Names and values that are legal, unusual, and have broken a reader somewhere. */
public static List<Faction> edge() {
List<Faction> factions = new ArrayList<Faction>();
factions.add(faction(0, "", 0, 0));
// Built from code points rather than written as literals. This source stays pure ASCII on
// purpose: a generator whose own file gets mojibaked by a CP-1252 toolchain would emit
// fixtures that assert the mojibake, and every reader downstream would agree with it.
Faction unicode = faction(1, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES,
0xFFFFFF, 1000);
factions.add(unicode);
Faction formatting = faction(2,
Text.SECTION + "cRed " + Text.SECTION + "lBold" + Text.SECTION + "r", 0xFF5555, 1000);
factions.add(formatting);
Faction longName = faction(3, repeat("Faction With A Very Long Name ", 12), 0x00FF00, 1000);
factions.add(longName);
Faction extremes = faction(4, "Integer Extremes", 0xFFFFFF, Integer.MAX_VALUE);
extremes.neutralPoints = Integer.MIN_VALUE;
extremes.friendlyPoints = Integer.MAX_VALUE;
extremes.color = -1;
factions.add(extremes);
// Points to factions that are not in this file. A converter that resolves eagerly breaks
// here; one that keeps the id does not.
Faction dangling = faction(5, "Dangling References", 0x808080, 1000);
dangling.attackFactions.addAll(Arrays.asList(9001, -3, 0));
factions.add(dangling);
// A non-contiguous, high id. Nothing requires ids to be dense, and lastID is separate.
factions.add(faction(4096, "Sparse Id", 0x00FFFF, 1000));
return factions;
}
/** The controller-shaped document. Copied from FactionController.getNBT. */
public static NBTTagCompound document(List<Faction> factions, int lastUsedId) {
NBTTagList list = new NBTTagList();
for (Faction faction : factions) {
NBTTagCompound tag = new NBTTagCompound();
faction.writeNBT(tag);
list.appendTag(tag);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", lastUsedId);
compound.setTag("NPCFactions", list);
return compound;
}
private static Faction faction(int id, String name, int color, int defaultPoints) {
return new Faction(id, name, color, defaultPoints);
}
private static String repeat(String s, int times) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append(s);
}
return sb.toString();
}
}
@@ -0,0 +1,180 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Per-player records, and the name/uuid index beside them.
*
* <p>A record is {@code playerdata/<uuid>.json}, written by {@code PlayerData.getNBT}, which
* composes fifteen sub-writers -- dialog, bank, quest, transport, faction, item giver, mail,
* timers, skin overlays, animation, effect, magic, trade, ability and hotbar. Only some are
* populated here; the rest write their empty form, which is itself worth having, since "what an
* untouched sub-record looks like" is a contract too.
*
* <p>{@code playerdatamap.dat} is a flat {@code {Name, UUID}} list. It is a lookup index rebuilt
* by scanning the directory when absent, so it is derived rather than authoritative -- but it is
* what CustomNPC+ reads first.
*
* <p>The record can also be gzipped NBT rather than JSON, chosen by {@code ConfigMain.DatFormat}.
* Both forms are generated, because a reader that only handles the default will meet the other on
* somebody's server.
*/
public final class PlayerFixtures {
private PlayerFixtures() {
}
/** uuid -> display name, in a fixed order so the index document is reproducible. */
public static Map<String, String> roster() {
Map<String, String> roster = new LinkedHashMap<String, String>();
roster.put("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
roster.put("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
roster.put("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
roster.put("00000000-0000-0000-0000-000000000000", "NilUuid");
return roster;
}
public static List<Case<PlayerData>> records() {
List<Case<PlayerData>> out = new ArrayList<Case<PlayerData>>();
PlayerData fresh = player("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
out.add(new Case<PlayerData>("", fresh,
"a player who has done nothing. Every one of the fifteen sub-records writes its empty "
+ "form -- the baseline for what an untouched record contains"));
PlayerData progressed = player("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
progressed.dialogData.dialogsRead.addAll(Arrays.asList(1, 2, 3, 41, 90));
progressed.factionData.factionData.put(0, 1800);
progressed.factionData.factionData.put(1, 1000);
progressed.factionData.factionData.put(2, 0);
progressed.factionData.factionData.put(14, -250);
progressed.questData.finishedQuests.put(1, Fixtures.EPOCH);
progressed.questData.finishedQuests.put(30, Fixtures.EPOCH + 86400000L);
progressed.questData.activeQuests.put(2, questData(2, false));
progressed.questData.activeQuests.put(71, questData(71, true));
progressed.companionID = 4;
progressed.profileSlot = 2;
out.add(new Case<PlayerData>("", progressed,
"read dialogs, standing in four factions including a negative one, two finished "
+ "quests with completion timestamps, and two active quests -- one of them marked "
+ "complete but not turned in. Also a companion id and a non-zero profile slot"));
PlayerData extras = player("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
QuestData withExtras = questData(75, false);
withExtras.extraData.setTag("Killed", killed("Zombie", 14, "Skeleton", 3));
withExtras.extraData.setBoolean("LocationFound", true);
withExtras.extraData.setBoolean("Location2Found", true);
extras.questData.activeQuests.put(75, withExtras);
extras.dialogData.dialogsRead.add(58);
out.add(new Case<PlayerData>("", extras,
"an active quest whose ExtraData holds per-objective progress, in the shapes the "
+ "quest classes actually read. Kill counts are a Killed tag list of Slot/Value "
+ "compounds -- NBTTags.getStringIntegerMap -- not loose integers keyed by mob "
+ "name, and a reached location is a boolean under its own key. The quest stores "
+ "only the targets, so a reader that ignores ExtraData can never show progress"));
PlayerData party = player("11111111-2222-3333-4444-555555555555", "PartyMember");
QuestData shared = questData(76, false);
// The per-player half of a party kill quest: QuestKill keys it by the player's own name
// rather than by slot, so two members of one party each carry their own tally.
shared.extraData.setTag("PartyMemberKilled", killed("Creeper", 2));
shared.extraData.setTag("Killed", killed("Creeper", 5));
party.questData.activeQuests.put(76, shared);
out.add(new Case<PlayerData>("", party,
"a party kill quest, which stores the group total under Killed and each member's own "
+ "share under <playerName>Killed. The second key is composed from a name, so it "
+ "cannot be enumerated from the quest -- only from the party that took it"));
PlayerData foreign = player("22222222-3333-4444-5555-666666666666", "AddonUser");
QuestData unclaimed = questData(77, false);
// ExtraData is an opaque compound: nothing validates its keys, so an addon that stores
// its own progress there produces a file no objective kind here can read. Deliberate,
// and the case a reader has to report rather than silently drop.
unclaimed.extraData.setInteger("dbcaddon:KiCharged", 900);
unclaimed.extraData.setString("dbcaddon:Form", "SuperSaiyan");
foreign.questData.activeQuests.put(77, unclaimed);
out.add(new Case<PlayerData>("", foreign,
"an active quest whose ExtraData holds only keys no objective kind claims, which is "
+ "what an addon writing its own progress leaves behind. Nothing validates this "
+ "compound, so a reader meets it on a real server and has to say so rather than "
+ "drop it"));
PlayerData nil = player("00000000-0000-0000-0000-000000000000", "NilUuid");
nil.dialogData.dialogsRead.add(1);
out.add(new Case<PlayerData>("", nil,
"the nil UUID, which is legal in the file and names no player. A reader that treats "
+ "it as absent rather than as a value diverges here"));
return out;
}
/** PlayerDataController.writeNBT -- a flat Name/UUID list, with no lastID. */
public static NBTTagCompound index(Map<String, String> roster) {
NBTTagList list = new NBTTagList();
for (Map.Entry<String, String> entry : roster.entrySet()) {
NBTTagCompound player = new NBTTagCompound();
// The controller keys the map by NAME and stores the uuid as the value, which is the
// opposite of what the file's key order suggests at a glance.
player.setString("Name", entry.getValue());
player.setString("UUID", entry.getKey());
list.appendTag(player);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("PlayerDataMap", list);
return compound;
}
private static PlayerData player(String uuid, String name) {
PlayerData data = new PlayerData();
data.uuid = uuid;
data.playername = name;
return data;
}
/**
* An entry in a player's active quest list.
*
* <p>{@code QuestData} needs a {@link Quest} to construct, but only writes three keys and
* never touches it -- the quest id is the map key in the enclosing list, not part of the
* entry. So a bare Quest carrying the right id is enough and nothing is invented.
*/
/**
* A counter map in the shape {@code NBTTags.nbtStringIntegerMap} writes and
* {@code getStringIntegerMap} reads: a list of {@code {Slot, Value}} compounds.
*
* <p>Written out by hand rather than through {@code NBTTags} so the fixture states the shape
* it is asserting. A generator that borrows the reader's own helper agrees with it by
* construction and proves nothing about it.
*/
private static NBTTagList killed(Object... slotsAndCounts) {
NBTTagList list = new NBTTagList();
for (int at = 0; at < slotsAndCounts.length; at += 2) {
NBTTagCompound entry = new NBTTagCompound();
entry.setString("Slot", (String) slotsAndCounts[at]);
entry.setInteger("Value", ((Integer) slotsAndCounts[at + 1]).intValue());
list.appendTag(entry);
}
return list;
}
private static QuestData questData(int questId, boolean completed) {
Quest quest = new Quest();
quest.id = questId;
QuestData data = new QuestData(quest);
data.isCompleted = completed;
data.sendAlerts = true;
return data;
}
}
@@ -0,0 +1,445 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.EnumPartyExchange;
import noppes.npcs.constants.EnumPartyObjectives;
import noppes.npcs.constants.EnumPartyRequirements;
import noppes.npcs.constants.EnumProfileSync;
import noppes.npcs.constants.EnumQuestCompletion;
import noppes.npcs.constants.EnumQuestRepeat;
import noppes.npcs.constants.EnumQuestType;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.quests.QuestDialog;
import noppes.npcs.quests.QuestItem;
import noppes.npcs.quests.QuestKill;
import noppes.npcs.quests.QuestLocation;
import noppes.npcs.quests.QuestManual;
import java.util.ArrayList;
import java.util.List;
/**
* Quests, one axis at a time.
*
* <p><b>A quest has no availability.</b> Worth stating because it is easy to conclude otherwise:
* {@code Quest.readNBTPartial} calls {@code VersionCompatibility.CheckAvailabilityCompatibility},
* whose name says availability, and which is in fact a generic "fill in keys this file predates"
* pass applied to every {@code ICompatibilty}. {@code Quest} declares no {@code Availability}
* field, {@code writeToNBTPartial} writes no {@code Availability*} key, and neither does the 1.20
* line. Gating is a property of the dialog that offers the quest.
*
* <p>Ranges: 1-9 the six types, 10-29 repeat and completion, 30-49 rewards, 50-69 party and
* profile, 70-89 objectives in depth, 90-99 combinations.
*/
public final class QuestFixtures {
private QuestFixtures() {
}
public static List<Case<Quest>> maximal() {
List<Case<Quest>> out = new ArrayList<Case<Quest>>();
types(out);
repeatAndCompletion(out);
rewards(out);
partyAndProfile(out);
objectives(out);
combinations(out);
return out;
}
// ------------------------------------------------------------------ types
private static void types(List<Case<Quest>> out) {
int id = 1;
for (EnumQuestType type : EnumQuestType.values()) {
Quest quest = quest(id, "Type " + type.name(), type);
populateObjective(quest, type);
out.add(new Case<Quest>("Types", quest,
"quest type " + type.name() + " (ordinal " + type.ordinal() + ") with its "
+ "objective populated. NOTE: Kill and AreaKill both build a QuestKill and "
+ "write the same keys -- the only thing separating them on disk is Type"));
id++;
}
}
/** Kill and AreaKill differ by Type alone, so they get compared directly. */
private static void populateObjective(Quest quest, EnumQuestType type) {
if (type == EnumQuestType.Item) {
QuestItem items = (QuestItem) quest.questInterface;
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 12));
items.items.items.put(1, Fixtures.namedItem("minecraft:written_book", 1, 0, "Proof"));
items.leaveItems = true;
items.ignoreDamage = true;
items.ignoreNBT = false;
} else if (type == EnumQuestType.Dialog) {
QuestDialog dialogs = (QuestDialog) quest.questInterface;
dialogs.dialogs.put(0, 1);
dialogs.dialogs.put(1, 2);
dialogs.dialogs.put(2, 3);
} else if (type == EnumQuestType.Kill || type == EnumQuestType.AreaKill) {
QuestKill kill = (QuestKill) quest.questInterface;
kill.targets.put("Zombie", 20);
kill.targets.put("Skeleton", 15);
kill.targetType = type == EnumQuestType.AreaKill ? 1 : 0;
kill.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
} else if (type == EnumQuestType.Location) {
QuestLocation location = (QuestLocation) quest.questInterface;
location.location = "Northern Watchtower";
location.location2 = "Sunken Crypt";
location.location3 = "The Long Bridge";
} else if (type == EnumQuestType.Manual) {
QuestManual manual = (QuestManual) quest.questInterface;
manual.manuals.put("Speak to the smith", 1);
manual.manuals.put("Gather reeds", 30);
}
}
// ------------------------------------------------------------------ repeat and completion
private static void repeatAndCompletion(List<Case<Quest>> out) {
int id = 10;
for (EnumQuestRepeat repeat : EnumQuestRepeat.values()) {
Quest quest = quest(id, "Repeat " + repeat.name(), EnumQuestType.Manual);
quest.repeat = repeat;
// The two CUSTOM modes are the only ones that read customCooldown, but it is written
// unconditionally, so setting it everywhere shows that.
quest.customCooldown = 3600000L;
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
out.add(new Case<Quest>("Repeat", quest,
"QuestRepeat = " + repeat.name() + " (ordinal " + repeat.ordinal() + ") with "
+ "CustomCooldown 3600000. MCDAILY/MCWEEKLY count world ticks, RLDAILY/RLWEEKLY "
+ "count wall time, and only MCCUSTOM/RLCUSTOM read the cooldown"));
id++;
}
int completionId = 18;
for (EnumQuestCompletion completion : EnumQuestCompletion.values()) {
Quest quest = quest(completionId, "Completion " + completion.name(), EnumQuestType.Manual);
quest.completion = completion;
quest.completerNpc = completion == EnumQuestCompletion.Npc ? "Quest Giver" : "";
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
out.add(new Case<Quest>("Repeat", quest,
"QuestCompletion = " + completion.name() + ". Npc requires turning in to the named "
+ "NPC; Instant completes the moment the objective is met"));
completionId++;
}
Quest cooldownExtremes = quest(20, "Cooldown Extremes", EnumQuestType.Manual);
cooldownExtremes.repeat = EnumQuestRepeat.RLCUSTOM;
cooldownExtremes.customCooldown = Long.MAX_VALUE;
((QuestManual) cooldownExtremes.questInterface).manuals.put("Wait", 1);
out.add(new Case<Quest>("Repeat", cooldownExtremes,
"CustomCooldown at Long.MAX_VALUE -- the one long on a quest, and the field most "
+ "likely to be narrowed to an int by a reader"));
}
// ------------------------------------------------------------------ rewards
private static void rewards(List<Case<Quest>> out) {
Quest exp = quest(30, "Experience Reward", EnumQuestType.Manual);
exp.rewardExp = 2500;
((QuestManual) exp.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", exp, "RewardExp only"));
Quest items = quest(31, "Item Rewards", EnumQuestType.Manual);
items.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 5));
items.rewardItems.items.put(1, Fixtures.item("minecraft:gold_ingot", 32));
items.rewardItems.items.put(8, Fixtures.namedItem("minecraft:diamond_pickaxe", 1, 3, "Miner's Due"));
((QuestManual) items.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", items,
"three of the nine reward slots filled, including slot 8 and one stack with custom "
+ "NBT. Stored under the Rewards tag as an NpcMiscInventory"));
Quest full = quest(32, "Nine Item Rewards", EnumQuestType.Manual);
String[] nine = {
"minecraft:stone", "minecraft:dirt", "minecraft:oak_stairs", "minecraft:torch",
"minecraft:bread", "minecraft:coal", "minecraft:string", "minecraft:bone",
"minecraft:paper"
};
for (int i = 0; i < nine.length; i++) {
full.rewardItems.items.put(i, Fixtures.item(nine[i], i + 1));
}
((QuestManual) full.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", full,
"all nine reward slots filled, each a different count -- the inventory at capacity"));
Quest random = quest(33, "Random Reward", EnumQuestType.Manual);
random.randomReward = true;
random.rewardItems.items.put(0, Fixtures.item("minecraft:emerald", 1));
random.rewardItems.items.put(1, Fixtures.item("minecraft:redstone", 1));
((QuestManual) random.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", random,
"RandomReward true -- one of the reward slots is granted rather than all of them"));
Quest faction = quest(34, "Faction Reward", EnumQuestType.Manual);
faction.factionOptions.factionId = 14;
faction.factionOptions.factionPoints = 500;
faction.factionOptions.decreaseFactionPoints = false;
faction.factionOptions.faction2Id = 15;
faction.factionOptions.faction2Points = 250;
faction.factionOptions.decreaseFaction2Points = true;
((QuestManual) faction.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", faction,
"both faction reward slots, nested under QuestFactionPoints -- note a dialog writes "
+ "the same FactionOptions keys flat, not nested"));
Quest mail = quest(35, "Mail Reward", EnumQuestType.Manual);
mail.mail.subject = "Your reward";
mail.mail.sender = "The Guild";
mail.mail.time = Fixtures.EPOCH;
NBTTagCompound message = new NBTTagCompound();
message.setString("Text", "Enclosed, with thanks.");
mail.mail.message = message;
mail.mail.items[0] = Fixtures.item("minecraft:gold_nugget", 64);
mail.mail.items[3] = Fixtures.item("minecraft:cake", 1);
((QuestManual) mail.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", mail,
"QuestMail with two of four item slots, including the last slot"));
Quest command = quest(36, "Command On Completion", EnumQuestType.Manual);
command.command = "/give {player} minecraft:diamond 1";
((QuestManual) command.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", command, "QuestCommand with a {player} placeholder"));
Quest chain = quest(37, "Chains To Another", EnumQuestType.Manual);
chain.nextQuestid = 30;
chain.nextQuestTitle = "Experience Reward";
((QuestManual) chain.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", chain,
"NextQuestId 30 with a matching NextQuestTitle. On read CustomNPC+ overwrites the "
+ "title from the live controller and blanks it when the target is missing, so "
+ "the id is the real link and the title is a cache"));
Quest danglingChain = quest(38, "Chains Nowhere", EnumQuestType.Manual);
danglingChain.nextQuestid = 999999;
danglingChain.nextQuestTitle = "A quest that does not exist";
((QuestManual) danglingChain.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", danglingChain,
"NextQuestId pointing at nothing, with a stale title still on disk -- what a world "
+ "looks like after the target quest was deleted"));
}
// ------------------------------------------------------------------ party and profile
private static void partyAndProfile(List<Case<Quest>> out) {
// The party block is written only when AllowParty is true. Both halves matter.
Quest disabled = quest(50, "Party Disabled", EnumQuestType.Manual);
disabled.partyOptions.allowParty = false;
disabled.partyOptions.minPartySize = 4;
disabled.partyOptions.maxPartySize = 8;
((QuestManual) disabled.questInterface).manuals.put("Solo", 1);
out.add(new Case<Quest>("Party", disabled,
"AllowParty false with sizes assigned. Proves the eight party keys are ABSENT from "
+ "the file when the flag is off -- the values are lost upstream, so there is "
+ "nothing for a converter to preserve"));
Quest enabled = quest(51, "Party Enabled", EnumQuestType.Manual);
enabled.partyOptions.allowParty = true;
enabled.partyOptions.onlyParty = true;
enabled.partyOptions.partyRequirements = EnumPartyRequirements.All;
enabled.partyOptions.rewardControl = EnumPartyExchange.Enrolled;
enabled.partyOptions.completeFor = EnumPartyExchange.Valid;
enabled.partyOptions.executeCommand = EnumPartyExchange.All;
enabled.partyOptions.minPartySize = 2;
enabled.partyOptions.maxPartySize = 6;
enabled.partyOptions.objectiveRequirement = EnumPartyObjectives.Leader;
((QuestManual) enabled.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", enabled,
"AllowParty true and all eight party keys set to non-default enum constants"));
int id = 52;
for (EnumPartyRequirements requirement : EnumPartyRequirements.values()) {
Quest quest = quest(id, "Party Requirement " + requirement.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.partyRequirements = requirement;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"PartyRequirements = " + requirement.name() + " (ordinal " + requirement.ordinal() + ")"));
id++;
}
for (EnumPartyExchange exchange : EnumPartyExchange.values()) {
Quest quest = quest(id, "Party Reward " + exchange.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.rewardControl = exchange;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"RewardControl = " + exchange.name() + " (ordinal " + exchange.ordinal() + ")"));
id++;
}
for (EnumPartyObjectives objective : EnumPartyObjectives.values()) {
Quest quest = quest(id, "Party Objective " + objective.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.objectiveRequirement = objective;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"ObjectiveRequirement = " + objective.name() + " (ordinal " + objective.ordinal() + ")"));
id++;
}
Quest profileOff = quest(62, "Profiles Disabled", EnumQuestType.Manual);
profileOff.profileOptions.enableOptions = false;
profileOff.profileOptions.cooldownControl = EnumProfileSync.Shared;
((QuestManual) profileOff.questInterface).manuals.put("Alone", 1);
out.add(new Case<Quest>("Party", profileOff,
"EnableProfiles false with a Shared cooldown assigned -- the two profile keys are "
+ "absent from the file, same shape as the party block"));
int profileId = 63;
for (EnumProfileSync sync : EnumProfileSync.values()) {
Quest quest = quest(profileId, "Profile " + sync.name(), EnumQuestType.Manual);
quest.profileOptions.enableOptions = true;
quest.profileOptions.cooldownControl = sync;
quest.profileOptions.completeControl = sync;
((QuestManual) quest.questInterface).manuals.put("Alone", 1);
out.add(new Case<Quest>("Party", quest,
"EnableProfiles true, CooldownControl and CompleteControl = " + sync.name()));
profileId++;
}
}
// ------------------------------------------------------------------ objectives in depth
private static void objectives(List<Case<Quest>> out) {
Quest emptyKill = quest(70, "Kill Nothing", EnumQuestType.Kill);
out.add(new Case<Quest>("Objectives", emptyKill,
"a Kill quest with an EMPTY target list. isCompleted counts completed targets against "
+ "the target count, so zero of zero passes -- this quest is complete on accept"));
Quest manyKill = quest(71, "Kill Many Kinds", EnumQuestType.Kill);
QuestKill kill = (QuestKill) manyKill.questInterface;
String[] mobs = {"Zombie", "Skeleton", "Creeper", "Spider", "Enderman", "Blaze"};
for (int i = 0; i < mobs.length; i++) {
kill.targets.put(mobs[i], (i + 1) * 10);
}
out.add(new Case<Quest>("Objectives", manyKill,
"six kill targets. Stored as a TreeMap, so the file is alphabetical rather than "
+ "insertion-ordered -- Blaze first, Zombie last"));
Quest customTarget = quest(72, "Kill A Custom NPC", EnumQuestType.Kill);
QuestKill custom = (QuestKill) customTarget.questInterface;
custom.targets.put("Village Elder", 1);
custom.targetType = 1;
custom.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
out.add(new Case<Quest>("Objectives", customTarget,
"TargetType 1 with a CustomTargetType class name -- targets an NPC by display name "
+ "rather than an entity by type"));
Quest emptyItems = quest(73, "Bring Nothing", EnumQuestType.Item);
QuestItem noItems = (QuestItem) emptyItems.questInterface;
noItems.ignoreDamage = true;
noItems.ignoreNBT = true;
noItems.leaveItems = true;
out.add(new Case<Quest>("Objectives", emptyItems,
"an Item quest with no required items and all three matching flags on"));
Quest variantItems = quest(74, "Bring Variants", EnumQuestType.Item);
QuestItem variants = (QuestItem) variantItems.questInterface;
variants.items.items.put(0, Fixtures.variant("minecraft:wool", 8, 14));
variants.items.items.put(1, Fixtures.variant("minecraft:planks", 4, 3));
variants.items.items.put(2, Fixtures.variant("minecraft:dye", 16, 4));
out.add(new Case<Quest>("Objectives", variantItems,
"three pre-Flattening variants -- red wool (14), jungle planks (3) and lapis dye (4). "
+ "Damage is a variant selector here, not durability, and each becomes a distinct "
+ "item after 1.13, so this is the case a variant table has to cover"));
Quest manyDialogs = quest(75, "Read Many Dialogs", EnumQuestType.Dialog);
QuestDialog dialogs = (QuestDialog) manyDialogs.questInterface;
for (int i = 0; i < 5; i++) {
dialogs.dialogs.put(i, 30 + i);
}
out.add(new Case<Quest>("Objectives", manyDialogs,
"five dialog objectives. NOTE the key collision worth knowing about: a Dialog quest "
+ "stores these under QuestDialogs, which is exactly where a pre-split Kill quest "
+ "stored its targets -- see the legacy world"));
Quest oneLocation = quest(76, "One Location", EnumQuestType.Location);
((QuestLocation) oneLocation.questInterface).location = "The Old Well";
out.add(new Case<Quest>("Objectives", oneLocation,
"only the first of three location slots set; the other two are written as empty"));
Quest manuals = quest(77, "Manual Counters", EnumQuestType.Manual);
QuestManual manual = (QuestManual) manuals.questInterface;
manual.manuals.put("Deliver the letter", 1);
manual.manuals.put("Light the beacons", 3);
manual.manuals.put("Survive the night", 1);
out.add(new Case<Quest>("Objectives", manuals,
"three manual counters -- progress a script or an operator advances by hand"));
}
// ------------------------------------------------------------------ combinations
private static void combinations(List<Case<Quest>> out) {
Quest everything = quest(90, "Everything At Once", EnumQuestType.Item);
everything.logText = "Bring the ingots, and be quick about it.";
everything.completeText = "You have my thanks.";
everything.completerNpc = "Quartermaster";
everything.command = "/say {player} finished";
everything.repeat = EnumQuestRepeat.MCCUSTOM;
everything.customCooldown = 172800000L;
everything.completion = EnumQuestCompletion.Instant;
everything.nextQuestid = 1;
everything.nextQuestTitle = "Type Item";
everything.rewardExp = 1000;
everything.randomReward = true;
everything.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 3));
everything.rewardItems.items.put(4, Fixtures.namedItem("minecraft:iron_sword", 1, 5, "Reward"));
everything.factionOptions.factionId = 0;
everything.factionOptions.factionPoints = 75;
everything.partyOptions.allowParty = true;
everything.partyOptions.onlyParty = false;
everything.partyOptions.partyRequirements = EnumPartyRequirements.Valid;
everything.partyOptions.rewardControl = EnumPartyExchange.All;
everything.partyOptions.minPartySize = 2;
everything.partyOptions.maxPartySize = 4;
everything.profileOptions.enableOptions = true;
everything.profileOptions.cooldownControl = EnumProfileSync.Shared;
everything.profileOptions.completeControl = EnumProfileSync.Individual;
everything.mail.subject = "Everything";
everything.mail.sender = "Quartermaster";
everything.mail.time = Fixtures.EPOCH;
everything.mail.items[0] = Fixtures.item("minecraft:emerald", 12);
QuestItem items = (QuestItem) everything.questInterface;
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 20));
items.items.items.put(2, Fixtures.variant("minecraft:wool", 1, 11));
items.leaveItems = false;
items.ignoreDamage = false;
items.ignoreNBT = true;
out.add(new Case<Quest>("Combinations", everything,
"every quest sub-object populated at once: objective, rewards, faction, party, "
+ "profile, mail, chain, cooldown and command"));
Quest bare = quest(91, "Bare", EnumQuestType.Item);
out.add(new Case<Quest>("Combinations", bare,
"every field at its constructor default, for comparison against id 90"));
Quest unicode = quest(92, Text.CYRILLIC_QUEST + " " + Text.EM_DASH + " " + Text.ELEVES,
EnumQuestType.Manual);
unicode.logText = Text.RTL;
unicode.completeText = Text.ASTRAL;
unicode.completerNpc = Text.KATAKANA_FACTION;
((QuestManual) unicode.questInterface).manuals.put(Text.CYRILLIC_QUEST, 1);
out.add(new Case<Quest>("Combinations", unicode,
"non-Latin title, log text, complete text, completer name and objective key. The "
+ "objective key is the interesting one -- it is an NBT map key, not a value"));
}
// ------------------------------------------------------------------ helpers
/**
* Builds a quest with its type applied.
*
* <p>Order matters: {@code setType} replaces {@code questInterface} and stamps it with the
* quest id, so both must be set before the objective is populated.
*/
private static Quest quest(int id, String title, EnumQuestType type) {
Quest quest = new Quest();
quest.id = id;
quest.title = title;
quest.setType(type);
quest.logText = "Objective for " + title + ".";
quest.completeText = "Done: " + title + ".";
return quest;
}
}
@@ -0,0 +1,52 @@
package kamkeel.npcs.fixtures.content;
/**
* Non-ASCII strings the fixtures use, built from code points.
*
* <p>Every source file here is pure ASCII, and this class is why. A generator whose own source has
* been mojibaked by a CP-1252 toolchain emits fixtures that contain the mojibake, and then every
* reader tested against those fixtures agrees with it -- the corruption becomes the specification.
* Writing the code points out removes the whole class of accident, at the cost of one indirection.
*
* <p>The strings themselves matter: CustomNPC+ content is authored by players, in every language,
* with the section sign used for colour codes throughout.
*/
public final class Text {
private Text() {
}
/** The colour-code prefix, U+00A7. Appears in CustomNPC+'s own default effect name. */
public static final String SECTION = cp(0x00A7);
/** U+2014. Punctuation above Latin-1 that a byte-oriented reader truncates. */
public static final String EM_DASH = cp(0x2014);
/** "Eleves" with acute and grave accents -- two-byte UTF-8, still one char in Java. */
public static final String ELEVES = cp(0x00C9, 0x6C, 0x00E8, 0x76, 0x65, 0x73);
/** Katakana for "faction". Three-byte UTF-8, and outside anything CP-1252 can represent. */
public static final String KATAKANA_FACTION = cp(0x30D5, 0x30A1, 0x30AF, 0x30B7, 0x30E7, 0x30F3);
/** Cyrillic "Zadanie" (quest). */
public static final String CYRILLIC_QUEST = cp(0x0417, 0x0430, 0x0434, 0x0430, 0x043D, 0x0438, 0x0435);
/**
* A character outside the Basic Multilingual Plane -- U+1F5FF, the moai. One code point, two
* Java chars, four UTF-8 bytes. NBT strings are modified UTF-8, which encodes this as a
* surrogate pair rather than as one four-byte sequence, so it is the case where a reader that
* treats NBT strings as standard UTF-8 diverges from one that does not.
*/
public static final String ASTRAL = cp(0x1F5FF);
/** A right-to-left string: Arabic for "quest". Exercises no encoding rule, only rendering. */
public static final String RTL = cp(0x0645, 0x0647, 0x0645, 0x0629);
private static String cp(int... codePoints) {
StringBuilder sb = new StringBuilder(codePoints.length);
for (int codePoint : codePoints) {
sb.appendCodePoint(codePoint);
}
return sb.toString();
}
}
@@ -0,0 +1,256 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.Bank;
import noppes.npcs.controllers.data.SpawnData;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.controllers.data.TransportCategory;
import noppes.npcs.controllers.data.TransportLocation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* The world-level {@code .dat} documents: global, tags, transport, banks and spawns.
*
* <p>All five share a shape -- one compound holding a list of entries plus a {@code lastID} -- and
* each list is built here in a fixed order rather than by iterating the controller's HashMap, so
* regeneration is a no-op rather than a reshuffle.
*
* <p>Every document format below is copied from its controller's {@code getNBT}, named per method.
*/
public final class WorldDataFixtures {
private WorldDataFixtures() {
}
// ------------------------------------------------------------------ global.dat
/** GlobalDataController.saveData -- a single integer, and the smallest document CNPC+ writes. */
public static NBTTagCompound global(int itemGiverId) {
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("itemGiverId", itemGiverId);
return compound;
}
// ------------------------------------------------------------------ tags.dat
/**
* Tags. Note {@link Tag#uuid} defaults to {@code randomUUID()}, so every fixture here sets one
* explicitly -- otherwise the corpus would differ on every run and the reproducibility check
* would fail for a reason that has nothing to do with the format.
*/
public static NBTTagCompound tags() {
List<Tag> tags = new ArrayList<Tag>();
tags.add(tag(1, "Boss", 0xFF0000, "3f2504e0-4f89-41d3-9a0c-0305e82c3301", false));
tags.add(tag(2, "Hidden", 0x333333, "3f2504e0-4f89-41d3-9a0c-0305e82c3302", true));
tags.add(tag(3, "", 0x00FF00, "3f2504e0-4f89-41d3-9a0c-0305e82c3303", false));
tags.add(tag(4, Text.KATAKANA_FACTION, 0xFFFFFF,
"3f2504e0-4f89-41d3-9a0c-0305e82c3304", false));
tags.add(tag(5, "Extremes", -1, "ffffffff-ffff-ffff-ffff-ffffffffffff", true));
NBTTagList list = new NBTTagList();
for (Tag tag : tags) {
NBTTagCompound entry = new NBTTagCompound();
tag.writeNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 5);
compound.setTag("NPCTags", list);
return compound;
}
private static Tag tag(int id, String name, int color, String uuid, boolean hidden) {
Tag tag = new Tag();
tag.id = id;
tag.name = name;
tag.color = color;
tag.uuid = UUID.fromString(uuid);
tag.hideTag = hidden;
return tag;
}
// ------------------------------------------------------------------ transport.dat
/**
* Transport locations, grouped into categories.
*
* <p>The one place CustomNPC+ stores a dimension as a bare {@code int} alongside a position --
* which is the signature that stopped being expressible after 1.16, so it is worth having on
* disk in both a vanilla dimension and a modded id.
*/
public static NBTTagCompound transport() {
List<TransportCategory> categories = new ArrayList<TransportCategory>();
TransportCategory overworld = category(1, "Overworld");
overworld.locations.put(1, location(1, "Spawn Plaza", 0.5D, 64.0D, 0.5D, 0, 0));
overworld.locations.put(2, location(2, "Northern Watchtower", -1204.5D, 96.0D, 3311.5D, 1, 0));
overworld.locations.put(3, location(3, "Negative Coordinates",
-30000000.0D, -64.0D, -30000000.0D, 2, 0));
categories.add(overworld);
TransportCategory other = category(2, "Other Dimensions");
other.locations.put(4, location(4, "Nether Hub", 12.0D, 70.0D, -8.0D, 0, -1));
other.locations.put(5, location(5, "The End", 100.0D, 50.0D, 0.0D, 0, 1));
// A modded dimension id, which is the case a numeric-to-key translation table must either
// cover or refuse rather than silently map to the overworld.
other.locations.put(6, location(6, "Modded Dimension", 0.0D, 0.0D, 0.0D, 0, 7265));
categories.add(other);
TransportCategory empty = category(3, "Empty Category");
categories.add(empty);
NBTTagList list = new NBTTagList();
for (TransportCategory category : categories) {
NBTTagCompound entry = new NBTTagCompound();
category.writeNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 6);
compound.setTag("NPCTransportCategories", list);
return compound;
}
private static TransportCategory category(int id, String title) {
TransportCategory category = new TransportCategory();
category.id = id;
category.title = title;
return category;
}
private static TransportLocation location(int id, String name, double x, double y, double z,
int type, int dimension) {
TransportLocation location = new TransportLocation();
location.id = id;
location.name = name;
location.posX = x;
location.posY = y;
location.posZ = z;
location.type = type;
location.dimension = dimension;
return location;
}
// ------------------------------------------------------------------ bank.dat
/** BankController.getNBT -- note the key is "Data" and there is no lastID. */
public static NBTTagCompound banks() {
List<Bank> banks = new ArrayList<Bank>();
Bank basic = bank(1, "Village Bank", 2, 9);
basic.currencyInventory.items.put(0, Fixtures.item("minecraft:emerald", 1));
basic.upgradeInventory.items.put(0, Fixtures.item("minecraft:gold_ingot", 8));
for (int slot = 0; slot < 9; slot++) {
basic.slotTypes.put(slot, slot % 3);
}
banks.add(basic);
Bank bare = bank(2, "", 1, 1);
banks.add(bare);
Bank big = bank(3, "Vault", 6, 54);
big.currencyInventory.items.put(0, Fixtures.namedItem("minecraft:diamond", 64, 0, "Deposit"));
for (int slot = 0; slot < 54; slot++) {
big.slotTypes.put(slot, slot % 4);
}
banks.add(big);
NBTTagList list = new NBTTagList();
for (Bank bank : banks) {
NBTTagCompound entry = new NBTTagCompound();
bank.writeEntityToNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("Data", list);
return compound;
}
private static Bank bank(int id, String name, int startSlots, int maxSlots) {
Bank bank = new Bank();
bank.id = id;
bank.name = name;
bank.startSlots = startSlots;
bank.maxSlots = maxSlots;
return bank;
}
// ------------------------------------------------------------------ spawns.dat
/**
* Natural spawn entries.
*
* <p>The interesting shape here is {@code SpawnCompound<n>}: the per-variant NPC data is
* written as a numbered key rather than a list, so a reader has to probe for
* {@code SpawnCompound0}, {@code SpawnCompound1}, ... rather than iterate. The dimension set
* is written only when non-empty, so the key is absent on most entries.
*/
public static NBTTagCompound spawns() {
List<SpawnData> spawns = new ArrayList<SpawnData>();
SpawnData plains = spawn(1, "Plains Wanderer", 10);
plains.biomes.addAll(Arrays.asList("Plains", "Sunflower Plains", "Forest"));
plains.spawnCompounds.put(0, npcStub("Wanderer"));
spawns.add(plains);
SpawnData variants = spawn(2, "Cave Dweller", 3);
variants.biomes.add("Extreme Hills");
variants.dimensions.addAll(Arrays.asList(0, -1, 7265));
variants.monsterSpawning = true;
variants.animalSpawning = false;
variants.airSpawning = true;
variants.liquidSpawning = true;
variants.spawnHeightMin = 5;
variants.spawnHeightMax = 40;
variants.maxAlive = 12;
variants.cooldownTicks = 600;
variants.attemptsPerCycle = 4;
// Three numbered compounds, which is the shape worth pinning.
variants.spawnCompounds.put(0, npcStub("Dweller A"));
variants.spawnCompounds.put(1, npcStub("Dweller B"));
variants.spawnCompounds.put(2, npcStub("Dweller C"));
spawns.add(variants);
SpawnData bare = spawn(3, "", 0);
spawns.add(bare);
NBTTagList list = new NBTTagList();
for (SpawnData spawn : spawns) {
list.appendTag(spawn.writeNBT(new NBTTagCompound()));
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 3);
compound.setTag("NPCSpawnData", list);
return compound;
}
private static SpawnData spawn(int id, String name, int weight) {
SpawnData spawn = new SpawnData();
spawn.id = id;
spawn.name = name;
spawn.itemWeight = weight;
return spawn;
}
/**
* A stand-in for a stored NPC.
*
* <p>Deliberately not a real {@code EntityCustomNpc}: constructing one needs a World, and a
* spawn entry stores whatever compound it was given without inspecting it. A fixture with a
* full NPC in it belongs with the NPC system, which is not covered here yet -- so this says
* what it is rather than pretending.
*/
private static NBTTagCompound npcStub(String name) {
NBTTagCompound stub = new NBTTagCompound();
stub.setString("Name", name);
stub.setString("FixtureNote", "placeholder -- not a serialized EntityCustomNpc");
return stub;
}
}
@@ -0,0 +1,86 @@
package kamkeel.npcs.fixtures.worlds;
import kamkeel.npcs.fixtures.FixtureWorld;
import kamkeel.npcs.fixtures.WorldWriter;
import kamkeel.npcs.fixtures.content.FactionFixtures;
import noppes.npcs.constants.EnumOptionType;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogOption;
import noppes.npcs.controllers.data.Faction;
import java.util.List;
/**
* What CustomNPC+ writes for a world nobody has edited.
*
* <p>Worth its own world because "the defaults" is a real contract and an easy thing to get subtly
* wrong: a reader that supplies its own idea of a default agrees with this file on every field it
* happens to share and disagrees on the rest, silently. Reproduced from
* FactionController.loadFactions and DialogController.loadDefaultDialogs.
*/
public final class DefaultsWorld implements FixtureWorld {
public String name() {
return "defaults";
}
public String purpose() {
return "exactly what CustomNPC+ creates for a fresh world -- the three default factions and "
+ "the three Villager dialogs -- and nothing else.";
}
public void build(WorldWriter out) {
List<Faction> factions = FactionFixtures.vanillaDefaults();
out.dat("faction", "factions.dat", FactionFixtures.document(factions, 0),
"the three factions FactionController creates when factions.dat is missing or empty: "
+ "Friendly 2000, Neutral 1000, Aggressive 0");
// Copied field for field from DialogController.loadDefaultDialogs.
Dialog start = new Dialog();
start.id = 1;
start.title = "Start";
start.text = "Hello {player}, \n\nWelcome to our village. I hope you enjoy your stay";
Dialog village = new Dialog();
village.id = 2;
village.title = "Ask about village";
village.text = "This village has been around for ages. Enjoy your stay here.";
Dialog who = new Dialog();
who.id = 3;
who.title = "Who are you";
who.text = "I'm a villager here. I have lived in this village my whole life.";
DialogOption toVillage = new DialogOption();
toVillage.title = "Tell me something about this village";
toVillage.dialogId = 2;
toVillage.optionType = EnumOptionType.DialogOption;
DialogOption toWho = new DialogOption();
toWho.title = "Who are you?";
toWho.dialogId = 3;
toWho.optionType = EnumOptionType.DialogOption;
DialogOption goodbye = new DialogOption();
goodbye.title = "Goodbye";
goodbye.optionType = EnumOptionType.QuitOption;
start.options.put(0, toWho);
start.options.put(1, toVillage);
start.options.put(2, goodbye);
DialogOption back = new DialogOption();
back.title = "Back";
back.dialogId = 1;
village.options.put(1, back);
who.options.put(1, back);
out.dialog("Villager", start,
"CustomNPC+'s own default dialog 1, with its three options. Note showWheel is false "
+ "here because the object was never read back -- readNBTPartial defaults an "
+ "absent DialogShowWheel to true, which the writer does not do");
out.dialog("Villager", village, "CustomNPC+'s own default dialog 2");
out.dialog("Villager", who, "CustomNPC+'s own default dialog 3");
}
}
@@ -0,0 +1,86 @@
package kamkeel.npcs.fixtures.worlds;
import kamkeel.npcs.fixtures.FixtureWorld;
import kamkeel.npcs.fixtures.WorldWriter;
import kamkeel.npcs.fixtures.content.FactionFixtures;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.Faction;
import java.util.List;
/**
* Legal content that readers get wrong.
*
* <p>Nothing here is corrupt. Every file is something CustomNPC+ will write and load: empty
* strings, integer extremes, ids that resolve nowhere, names outside Latin-1, and the same id
* living in two categories. The last is the one worth having -- it is what makes "a dialog's
* identity is its id" wrong on its own.
*/
public final class EdgeWorld implements FixtureWorld {
public String name() {
return "edge";
}
public String purpose() {
return "legal but awkward content: empty strings, integer extremes, dangling ids, non-Latin "
+ "names, and one dialog id occupying two categories at once.";
}
public void build(WorldWriter out) {
List<Faction> factions = FactionFixtures.edge();
out.dat("faction", "factions.dat", FactionFixtures.document(factions, 4096),
"empty and non-Latin names, Integer.MIN_VALUE/MAX_VALUE thresholds, colour -1, "
+ "attack lists naming factions that are not in the file, and a sparse id of 4096");
// The same id in two categories. DialogController loads categories directory by
// directory, and on the second occurrence renames the file and reassigns the id -- so
// this world does not survive a load unchanged, which is exactly the behaviour worth
// pinning. Whichever category is read second is decided by File.listFiles order.
Dialog first = new Dialog();
first.id = 1;
first.title = "Start";
first.text = "I am dialog 1 in category A.";
Dialog second = new Dialog();
second.id = 1;
second.title = "Start";
second.text = "I am dialog 1 in category B.";
out.dialog("Category A", first,
"dialog id 1 in the first category. See the note on its twin");
out.dialog("Category B", second,
"dialog id 1 AGAIN, in a second category, with the same title. CustomNPC+ resolves "
+ "this on load by renaming the file and reassigning the id, so a converter that "
+ "keys on the id alone silently merges two distinct dialogs. Which one is "
+ "reassigned depends on File.listFiles order and is not fixed");
Dialog emptyEverything = new Dialog();
emptyEverything.id = 2;
emptyEverything.title = "";
emptyEverything.text = "";
emptyEverything.command = "";
emptyEverything.textSound = "";
out.dialog("Empty", emptyEverything,
"every string field empty, including TextSound, which has a non-empty default. "
+ "DialogSound is absent entirely because the writer omits it when empty");
Dialog extremes = new Dialog();
extremes.id = 3;
extremes.title = "Integer Extremes";
extremes.text = "Every numeric field at a boundary.";
extremes.quest = Integer.MAX_VALUE;
extremes.color = Integer.MIN_VALUE;
extremes.titleColor = -1;
extremes.textWidth = Integer.MAX_VALUE;
extremes.textHeight = Integer.MIN_VALUE;
extremes.textOffsetX = Integer.MIN_VALUE;
extremes.textOffsetY = Integer.MAX_VALUE;
extremes.npcScale = Float.MAX_VALUE;
extremes.textPitch = Float.MIN_VALUE;
extremes.alignment = Byte.MAX_VALUE;
out.dialog("Empty", extremes,
"integer and float fields at their type boundaries, and DialogAlignment at 127 -- "
+ "outside the 0-2 the field documents, because nothing validates it on write");
}
}
@@ -0,0 +1,163 @@
package kamkeel.npcs.fixtures.worlds;
import kamkeel.npcs.fixtures.FixtureWorld;
import kamkeel.npcs.fixtures.WorldWriter;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.EnumAvailabilityQuest;
import noppes.npcs.constants.EnumQuestType;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.quests.QuestKill;
/**
* Documents as an older CustomNPC+ would have left them.
*
* <p><b>Synthesized, and the only world here that is.</b> Every other file in these fixtures is
* whatever CustomNPC+ writes today. These are produced by writing a current document and then
* removing keys and lowering {@code ModRev} -- because producing genuinely old output means
* checking out an old CustomNPC+ and running it, which is worth doing and is not this.
*
* <p>They are still worth having, because the upgrade path is real code with no other test. When a
* loaded document's {@code ModRev} differs from {@code VersionCompatibility.ModRev},
* {@code CheckAvailabilityCompatibility} walks a freshly constructed object's NBT and copies in
* every key the file is missing. A reader that skips that step reads zero for absent integers,
* which is a valid-looking value for most of these fields and a wrong one for all of them.
*
* <p>Each case names exactly what was removed, so the synthesis is auditable rather than implied.
*/
public final class LegacyWorld implements FixtureWorld {
/** Anything below VersionCompatibility.ModRev, which is 23 at the time of writing. */
private static final int OLD_REV = 17;
public String name() {
return "legacy";
}
public String purpose() {
return "documents aged by hand -- keys removed and ModRev lowered -- to exercise the "
+ "default-filling upgrade path. The only synthesized world here; every case names "
+ "which keys it removed.";
}
public void build(WorldWriter out) {
agedDialog(out);
preUpgradeKillQuest(out);
questWithoutAvailability(out);
}
private void agedDialog(WorldWriter out) {
Dialog dialog = new Dialog();
dialog.id = 1;
dialog.title = "Aged Dialog";
dialog.text = "Written by a version that had fewer fields.";
dialog.color = 0x336699;
NBTTagCompound compound = dialog.writeToNBTPartial(new NBTTagCompound());
String[] removed = {
"TextSound", "TextPitch", "TextWidth", "TextHeight", "ShowOptionLine",
"PreviousBlocks", "NPCScale", "Color", "TitleColor", "DialogShowWheel",
"DialogDarkScreen", "Images", "ColorSettings"
};
for (String key : removed) {
compound.removeTag(key);
}
compound.setInteger("ModRev", OLD_REV);
out.dialogRaw("Aged", 1, compound,
"ModRev lowered to " + OLD_REV + " and 13 keys removed: " + join(removed) + ". Ten of "
+ "them have a non-zero default that readNBTPartial restores explicitly, and the "
+ "Color that was set is among the removed ones -- so a reader that does not "
+ "default-fill produces a black dialog with no text sound and a zero scale");
}
/**
* The trap Scribe's own notes record: before the kill/dialog split, a Kill quest stored its
* targets under {@code QuestDialogs} -- the dialog quest's key. QuestKill.readEntityFromNBT
* still falls back to it when {@code QuestKills} is absent. Miss the fallback and every
* pre-upgrade kill quest converts with no targets, which reads as already complete.
*/
private void preUpgradeKillQuest(WorldWriter out) {
Quest quest = new Quest();
quest.id = 1;
quest.title = "Old Kill Quest";
quest.logText = "Cull the pigs.";
quest.setType(EnumQuestType.Kill);
QuestKill kill = (QuestKill) quest.questInterface;
kill.targets.put("Pig", 10);
kill.targets.put("Cow", 4);
kill.targetType = 0;
NBTTagCompound compound = quest.writeToNBTPartial(new NBTTagCompound());
NBTBase targets = compound.getTag("QuestKills");
compound.removeTag("QuestKills");
compound.setTag("QuestDialogs", targets);
compound.setInteger("ModRev", OLD_REV);
out.questRaw("Aged", 1, compound,
"a Kill quest whose targets sit under QuestDialogs instead of QuestKills, which is "
+ "where a pre-split CustomNPC+ put them. QuestKill.readEntityFromNBT falls back "
+ "to that key. A reader without the fallback loads two targets as zero targets, "
+ "and a quest with no targets counts as complete");
}
private void questWithoutAvailability(WorldWriter out) {
Quest quest = new Quest();
quest.id = 2;
quest.title = "Aged Item Quest";
quest.logText = "Bring me three ingots.";
quest.setType(EnumQuestType.Item);
quest.rewardExp = 500;
NBTTagCompound compound = quest.writeToNBTPartial(new NBTTagCompound());
String[] removed = {
"PartyOptions", "ProfileOptions", "CustomCooldown", "RandomReward", "QuestCompletion"
};
for (String key : removed) {
compound.removeTag(key);
}
compound.setInteger("ModRev", OLD_REV);
out.questRaw("Aged", 2, compound,
"ModRev lowered and the newer sub-objects removed: " + join(removed) + ". Party and "
+ "profile options are whole compounds, so this exercises the recursive half of "
+ "CompatabilityFix rather than the flat half");
// A dialog whose quest availability slots were never written at all, which is what every
// document below the availability rework looks like.
Dialog gated = new Dialog();
gated.id = 2;
gated.title = "Gated, Then Aged";
gated.text = "Only for those who finished quest 1.";
gated.availability.questAvailable = EnumAvailabilityQuest.After;
gated.availability.questId = 1;
NBTTagCompound gatedCompound = gated.writeToNBTPartial(new NBTTagCompound());
String[] gatedRemoved = {
"AvailabilityQuest2", "AvailabilityQuest3", "AvailabilityQuest4",
"AvailabilityQuest2Id", "AvailabilityQuest3Id", "AvailabilityQuest4Id"
};
for (String key : gatedRemoved) {
gatedCompound.removeTag(key);
}
gatedCompound.setInteger("ModRev", OLD_REV);
out.dialogRaw("Aged", 2, gatedCompound,
"the first AvailabilityQuest slot set and the other three absent entirely. Their "
+ "defaults are Always/-1, so default-filling and reading-zero happen to agree "
+ "here -- which is why this file is a weak test on its own and a useful one "
+ "beside the aged dialog above, where they disagree");
}
private static String join(String[] keys) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keys.length; i++) {
sb.append(keys[i]);
if (i + 1 < keys.length) {
sb.append(", ");
}
}
return sb.toString();
}
}
@@ -0,0 +1,105 @@
package kamkeel.npcs.fixtures.worlds;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.FixtureWorld;
import kamkeel.npcs.fixtures.WorldWriter;
import kamkeel.npcs.fixtures.content.DialogFixtures;
import kamkeel.npcs.fixtures.content.EffectFixtures;
import kamkeel.npcs.fixtures.content.FactionFixtures;
import kamkeel.npcs.fixtures.content.PlayerFixtures;
import kamkeel.npcs.fixtures.content.QuestFixtures;
import kamkeel.npcs.fixtures.content.WorldDataFixtures;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.Faction;
import noppes.npcs.controllers.data.Quest;
import java.util.List;
/**
* Every field CustomNPC+ can store, moved off its default at least once.
*
* <p>The world a reader is measured against. If a field is written by CustomNPC+ and absent from
* here, that is a gap in the fixtures rather than a decision.
*/
public final class MaximalWorld implements FixtureWorld {
public String name() {
return "maximal";
}
public String purpose() {
return "every storable field moved off its default at least once, with each enum walked to "
+ "all of its constants. The world a reader is measured against.";
}
public void build(WorldWriter out) {
List<Faction> factions = FactionFixtures.maximal();
out.dat("faction", "factions.dat", FactionFixtures.document(factions, 17),
factions.size() + " factions: the three CustomNPC+ defaults, each boolean flag alone "
+ "and all together, a hostility graph, inverted thresholds and negative points");
for (Case<Dialog> c : DialogFixtures.maximal()) {
out.dialog(c.category, c.value, c.note);
}
for (Case<Quest> c : QuestFixtures.maximal()) {
out.quest(c.category, c.value, c.note);
}
List<Case<CustomEffect>> effects = EffectFixtures.maximal();
for (Case<CustomEffect> c : effects) {
out.effect(c.category, c.value, c.note);
}
out.effect("", EffectFixtures.MISMATCH_FILENAME, EffectFixtures.nameMismatch(),
"the name key inside the file says 'Name Inside The File' while the file is called '"
+ EffectFixtures.MISMATCH_FILENAME + ".json'. loadEffectsFromDir overwrites the "
+ "field from the filename after reading, so the filename wins and a reader "
+ "trusting the key gets a different answer");
out.dat("effect", "customeffects.dat", EffectFixtures.index(effects, 12),
"the custom effect INDEX -- {Name, ID} pairs and lastID, not the effects themselves, "
+ "which are the .json files under customeffects/. The unnamed effect is absent "
+ "from this index by design");
out.dat("global", "global.dat", WorldDataFixtures.global(42),
"one integer. The smallest document CustomNPC+ writes, and a useful floor for a "
+ "reader's envelope handling");
out.dat("tag", "tags.dat", WorldDataFixtures.tags(),
"five tags with explicit UUIDs, covering hidden, empty-named, non-Latin and a colour "
+ "of -1. Tag.uuid defaults to randomUUID(), so these are pinned deliberately");
out.dat("transport", "transport.dat", WorldDataFixtures.transport(),
"three categories and six locations, including negative coordinates, the Nether and "
+ "End by numeric id, and a modded dimension 7265 -- the int dimension that "
+ "stopped being expressible after 1.16");
out.dat("bank", "bank.dat", WorldDataFixtures.banks(),
"three banks with currency and upgrade inventories and per-slot types. Keyed under "
+ "'Data' with no lastID, unlike every other document here");
out.dat("spawn", "spawns.dat", WorldDataFixtures.spawns(),
"three natural spawn entries. One carries three numbered SpawnCompound keys rather "
+ "than a list, which a reader has to probe for rather than iterate");
List<Case<PlayerData>> players = PlayerFixtures.records();
for (Case<PlayerData> c : players) {
out.json("player", c.value.uuid, "playerdata/" + c.value.uuid + ".json",
c.value.getNBT(), c.note);
}
// The same record as gzipped NBT, which is what ConfigMain.DatFormat selects instead. Same
// compound, different container -- a reader has to handle both because a server operator
// chooses between them.
PlayerData asDat = players.get(1).value;
out.dat("player", "playerdata/" + asDat.uuid + ".dat", asDat.getNBT(),
"the Progressed player again, written as gzipped NBT rather than JSON. "
+ "ConfigMain.DatFormat picks the container; the compound is identical. Both "
+ "extensions are loaded by PlayerDataController, so both are real");
out.dat("player", "playerdatamap.dat", PlayerFixtures.index(PlayerFixtures.roster()),
"the name/uuid index. Derived rather than authoritative -- CustomNPC+ rebuilds it by "
+ "scanning playerdata/ when the file is missing -- but it is what gets read first");
}
}
@@ -264,6 +264,12 @@ public class QuestDialog extends QuestInterface implements IQuestDialog {
return true; return true;
} else { } else {
HashMap<Integer, Boolean> readValues = new HashMap<>(); HashMap<Integer, Boolean> readValues = new HashMap<>();
// Every required dialog starts unread. Without this the map only ever receives true,
// so the check below cannot find a false and a shared objective is always complete --
// including for a party that has read nothing at all.
for (int dialogId : dialogs.values()) {
readValues.put(dialogId, false);
}
for (UUID uuid : party.getPlayerUUIDs()) { for (UUID uuid : party.getPlayerUUIDs()) {
EntityPlayer player = NoppesUtilServer.getPlayer(uuid); EntityPlayer player = NoppesUtilServer.getPlayer(uuid);
PlayerData playerData; PlayerData playerData;