delvewright_dsl/prefab.rs
1//! The prefab metadata document (`<id>.json`, beside the structure `.nbt`) —
2//! the **one** definition of its shape.
3//!
4//! A prefab is a *pair* of files: a gzip-framed structure template and this
5//! sibling JSON that says what the template is, where its anchors and sockets
6//! are, how lit it is, what it claims about the space inside it, and what
7//! regenerates it. Both halves are produced and consumed by several tools of
8//! several ages — the grammar back end and the hand-written generators write the
9//! pair from scratch, `delvec prefab` reads it and writes it back after every
10//! admission step, `delvec` reads it to plan a world, `delvec render` reads it to
11//! aim a camera — so the document's shape is defined once, here, and every one
12//! of them reads that definition instead of a copy of it.
13//!
14//! # Why the definition lives in the DSL crate
15//!
16//! Not because prefab metadata is DSL surface — it is a library-asset document —
17//! but because this is the only crate every reader can depend on. `delvec` is
18//! published to crates.io and may only depend on published crates, and this crate
19//! is the one it already depends on. The alternative was a copy inside `delvec`,
20//! which is what existed and what this module replaces. The crate already owns
21//! the document's `lighting` block ([`crate::registry::Lighting`], whose field
22//! names are this file's field names) and the anchor surface DSL validation
23//! resolves refs against ([`crate::registry::AnchorRegistry`]), so the document's
24//! remaining blocks join a shape that was already half here.
25//!
26//! # Reading is total, writing preserves
27//!
28//! Every field a producer may legitimately omit is `Option`/`default` and is
29//! omitted (never `null`) on write, so a legacy prefab that predates a field
30//! still loads and a piece that has never been probed does not have to invent a
31//! measurement. Field order is the emission order, and it is the order the
32//! library's checked-in prefabs already use, so a reviewer diffing a generated
33//! piece against a hand-built one sees only values change.
34//!
35//! Keys this version has never heard of are **kept**, in [`PrefabMeta::extra`]
36//! and [`Anchor::extra`], and written back out. That is not politeness to the
37//! future; it is the only behaviour that is neither an outage nor silent data
38//! loss. See the `deny_unknown_fields` note below.
39//!
40//! # `deny_unknown_fields`, decided rather than inherited
41//!
42//! The attribute is right on a document whose reader is also its **owner**: a
43//! campaign stage document is authored against a versioned schema, a typo there
44//! is the bug the attribute exists to catch, and forward compatibility is
45//! handled by the `dsl_version` fence instead. Every stage struct in
46//! [`crate::stages`] keeps it for exactly that reason.
47//!
48//! It is wrong on a **consumer that is not the owner**, which is what every
49//! reader of this document is. Here a new key is not a typo — it is a newer
50//! producer meeting an older reader, which happens on every mixed-version pair
51//! of engine and content library. Refusing turns a forward addition into a hard
52//! failure at the layer with the least context; the compiler's private copy of
53//! this shape did exactly that, and the first grammar-exported prefab carrying a
54//! new key would have failed every campaign build.
55//!
56//! Tolerating alone is not the fix either, because a tool that reads this
57//! document, edits one block and writes it back deletes everything it does not
58//! model — and does so while every test it has passes. That is not
59//! hypothetical: `license.generated_by` was dropped that way once, and
60//! `waterline_y` — a field five shipped island prefabs carry and the
61//! ocean-horizon placement check keys off — was being dropped that way at the
62//! time this module was written.
63//!
64//! So the rule is: **this document's structs neither refuse an unknown key nor
65//! discard it.** They keep it, and the reader that wants to say something about
66//! it says it as a diagnostic (`DW0543`) rather than as a parse failure. The
67//! blocks whose own definition lives elsewhere are the exception and say why at
68//! their field.
69
70use std::collections::BTreeMap;
71use std::path::Path;
72
73use schemars::JsonSchema;
74use serde::{Deserialize, Serialize};
75
76use crate::registry::Lighting;
77use crate::split::TileSet;
78
79/// The one `.json` in a prefab library that is **not** a prefab document:
80/// the pool declaration (`{"pools": {...}}`), read by the compiler's registry.
81///
82/// Named once because more than one tool walks the library directory — the
83/// registry, `delvec view`'s page builder, `delvec render batch` — and each of
84/// them opens every `.json` it finds. A walker that does not know this name
85/// hands a pool file to [`PrefabMeta::from_json`] and reports it as a malformed
86/// prefab, which is a true statement about the bytes and a wrong one about the
87/// file.
88pub const POOLS_FILE: &str = "pools.json";
89
90/// What the exported prefab-metadata schema tells its reader the document IS —
91/// stated on the schema rather than only in a reference document, because the
92/// schema is what an author actually opens.
93const SCHEMA_DESCRIPTION: &str = "\
94A prefab's sibling metadata file, `<prefab-id>.json`, beside the structure \
95`.nbt` in a prefab library.
96
97A LIBRARY ASSET, NOT A CAMPAIGN STAGE DOCUMENT. It carries no `dsl_version`, no \
98`campaign_id` and no `stage`; it is not authored against the campaign DSL's \
99staging (ADR-0002) and is therefore absent from `--stage all`.
100
101Three of its declarations are the piece's claims about its own outside, and \
102they are different claims rather than one claim written three ways \
103(spec-0060 §4):
104
105 `walk_y` the piece's own walk plane, in local y. Owed on every base. \
106It is the number an area's origin is DERIVED from where the horizon's datum is \
107a walk plane, so it has no default: a default would be right for the tileset it \
108was copied from and silently wrong for every other. Missing, a campaign that \
109seats the piece is refused with `DW0886`.
110
111 `waterline_y` the local y of the piece's TOP AUTHORED WATER BLOCK. Owed only \
112where the piece really writes water that meets a sea. It is a claim about the \
113bytes and is checked against them (`DW0887`), and its placement is checked \
114against sea level (`DW0344`). A piece that authors no water has no waterline to \
115state, and writing one anyway is a fiction the engine refuses.
116
117 `shown_faces` which of the piece's six sides are finished exterior surface. \
118Absent means NO side is shown, which is the strict answer: a piece authored to \
119be buried writes nothing here, and what discharges its obligation is the world \
120burying it (`DW0885`).
121
122Keys this engine does not model are KEPT and written back out, so a newer \
123producer meeting an older reader is a `DW0543` warning rather than a parse \
124failure. The `lighting` block is the one exception and refuses a key it does \
125not know.
126";
127
128/// A prefab's sibling metadata file.
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
130pub struct PrefabMeta {
131 /// The DSL prefab id, `prefab/<id>`.
132 pub prefab_id: String,
133 /// The structure-template reference, for a piece whose blocks fit one
134 /// template.
135 ///
136 /// Exactly one of this and [`Self::structure_set`] is present — see the
137 /// type's own note on the two packagings, and [`Self::from_json`], which is
138 /// where "exactly one" is enforced.
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub structure: Option<StructureMeta>,
141 /// The tile set, for a piece whose blocks did not fit one template.
142 ///
143 /// **Packaging, not authoring.** A zone past the 48-per-axis structure cap
144 /// ships as several `.nbt` files plus this manifest; everything else about
145 /// the document — the id, the zone-local `anchors`, the `connectors`, the
146 /// one `lighting` block, the one provenance row — is what it is for a
147 /// single-template piece, because it describes the same building. Nothing
148 /// that refers to a piece may ask which of the two it is: read
149 /// [`Self::templates`].
150 ///
151 /// This was a second document type (`TileSetMeta`, in the schem crate),
152 /// field-for-field this one with `structure` swapped for `structure_set`.
153 /// The copy had already lost `waterline_y`, so a tiled shore could not
154 /// declare the waterline the ocean-horizon invariant (`DW0344`) keys off and
155 /// went silently unchecked. One document is what makes that class of drift
156 /// unrepresentable.
157 #[serde(default, skip_serializing_if = "Option::is_none")]
158 pub structure_set: Option<TileSet>,
159 /// Named anchors, keyed by DSL anchor name. `{}` for a piece that declares
160 /// none.
161 #[serde(default)]
162 pub anchors: BTreeMap<String, Anchor>,
163 /// Jigsaw sockets. `[]` for a piece that is placed directly rather than
164 /// drawn from a pool.
165 #[serde(default)]
166 pub connectors: Vec<Connector>,
167 /// The lighting declaration.
168 ///
169 /// Absent means legacy metadata that predates the field, which is a
170 /// different claim from `{"profile": "unmeasured"}` — the positive statement
171 /// that a measurement is owed.
172 ///
173 /// The block's own shape is [`Lighting`], and it is **the one part of this
174 /// document that still refuses a key it does not know**. Its job is a rule
175 /// about values — a measured profile must carry its measurement, an
176 /// `unmeasured` one must not — so a misspelled measurement key there is a
177 /// claim quietly becoming its own absence, which the profile/measurement
178 /// agreement alone does not catch for `rationale` or `method`. The cost is
179 /// real and is stated where an author will meet it
180 /// (`docs/reference/prefab-procedure.md` §9): a key added inside `lighting`
181 /// is a hard parse failure for an older engine, so adding one is a
182 /// `dsl_version` matter rather than a metadata edit.
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub lighting: Option<Lighting>,
185 /// Licence, provenance prose, and the machine-readable provenance row.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub license: Option<License>,
188 /// **The local y of this piece's own walk plane** — the cell a body's feet
189 /// occupy when it stands on the piece's principal floor (spec-0060 §4).
190 ///
191 /// This is the number an area's origin is DERIVED from on a horizon whose
192 /// datum is a walk plane: an `ocean` world's walk plane is `SEA_LEVEL + 1`,
193 /// so an area seating this piece is placed at `walk_ref_y - walk_y` and the
194 /// piece stands one block above the sea, which is the vanilla-normal beach
195 /// relationship. A keep interior declaring `1` is seated at 62 and stands
196 /// dry at 63; an island piece declaring `3` is seated at 60.
197 ///
198 /// **It has no default, and that is the decision** (spec-0060 §4.1). A
199 /// default is the retired global datum wearing a different name: it would
200 /// be right for the one tileset it was copied from and silently wrong for
201 /// every other, and the piece that lands under the sea because of it floods
202 /// on boot with nothing looking. A piece a campaign seats without one is
203 /// `DW0886`.
204 ///
205 /// It is a MEASUREMENT of the piece, so it is written by the generator that
206 /// built the piece and never typed by hand
207 /// (`CLAUDE.md`: a census derivable from the object is never hand-written).
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub walk_y: Option<i32>,
210 /// The local y of this piece's **top authored water block** — its waterline
211 /// — for open-air pieces built to a tileset convention that authors a sea.
212 ///
213 /// Two rules read it, and they ask different questions. `DW0887` asks
214 /// whether the claim is TRUE — whether the piece's own bytes put a water
215 /// block at that plane and none above it — and refuses a declaration that
216 /// is a fiction wherever the document and its `.nbt` are read together.
217 /// `DW0344` asks whether the PLACEMENT honours it: in a `horizon: ocean`
218 /// world the declared waterline must land at world sea level.
219 ///
220 /// Absent for pieces that author no sea, which neither rule then judges. A
221 /// piece that authors water and declares nothing is not refused by
222 /// `DW0887`; under `ocean` its placement is `DW0344`'s subject and under
223 /// `void` its runoff is `DW0318`'s.
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub waterline_y: Option<i32>,
226 /// **The sides of this piece the player is meant to see** — the piece's own
227 /// claim that a given face is finished exterior surface rather than the cut
228 /// edge of something that belongs inside a hill.
229 ///
230 /// Local side names, in the piece's own frame, from the same six-word
231 /// vocabulary [`ContractFace::dir`] uses: `east` `west` `up` `down` `south`
232 /// `north`. They turn with the placement, so a piece rotated a quarter turn
233 /// shows the side it was built to show.
234 ///
235 /// It is the third thing a piece says about its own outside, and the three
236 /// are different claims about the same object rather than one claim written
237 /// three ways: [`Self::waterline_y`] says where the piece meets the sea,
238 /// [`SpatialContract::faces`] says where a body crosses a side, and this
239 /// says which sides are finished. None of the others can stand in for it —
240 /// a cave with a mouth declares one `walk` face and is still a block of rock
241 /// on the other five — which is why `DW0885` reads this and not them.
242 ///
243 /// **Absent means no side is shown**, and that is the load-bearing default:
244 /// a piece authored to be buried is exactly a piece that writes nothing
245 /// here, so the silence has to be the strict answer or the defect declares
246 /// itself by omission. What discharges the obligation for such a piece is
247 /// the world burying it, which is geometry the declaration cannot fake.
248 #[serde(default, skip_serializing_if = "Vec::is_empty")]
249 pub shown_faces: Vec<String>,
250 /// The piece's spatial contract, when it declares one.
251 ///
252 /// Absent means legacy metadata — the piece makes no spatial claim — exactly
253 /// as an absent `lighting` block differs from `unmeasured`.
254 #[serde(default, skip_serializing_if = "Option::is_none")]
255 pub spatial_contract: Option<SpatialContract>,
256 /// **The size class of box this piece is built to fill** — a name from the
257 /// metrics table's `size-class.*` ladder (spec-0050 §5).
258 ///
259 /// Optional for the library at large, and that is deliberate rather than
260 /// lax: every piece in the library predates the field, and `DW0848` binds
261 /// only where the claim is made. What is *not* optional is the claim being
262 /// true — a piece declaring a class its own bytes could serve no box of is
263 /// refused at admission and again wherever a detail plan consumes it, so a
264 /// pre-check-era piece cannot be consumed unjudged.
265 ///
266 /// Absent means what absence means everywhere in this document: the claim is
267 /// not made. A piece bound by a `details[]` row is still checked for exact
268 /// frame equality (`DW0843`) whether or not it declares — that is the
269 /// consumer's exact check, and this is the library's approximate one.
270 #[serde(default, skip_serializing_if = "Option::is_none")]
271 pub footprint_class: Option<String>,
272 /// Every top-level key this version does not model, kept verbatim so that
273 /// reading and writing the document is not the same as editing it.
274 ///
275 /// A reader that wants to report one has it in hand; a reader that does not
276 /// care carries it through. Emitted after the modelled keys, in key order.
277 #[serde(flatten)]
278 pub extra: BTreeMap<String, serde_json::Value>,
279}
280
281/// A piece's declared spaces, out-of-walk regions and edges, **already
282/// resolved**: every box is a local cell range of these exact bytes.
283///
284/// Resolved rather than parametric on purpose. A grammar program's declarations
285/// are scope-bound and mean different boxes at different parameters, so the only
286/// contract that can describe *this* `.nbt` is the one its own expansion
287/// produced. That is also what lets a hand-built piece carry the same block: it
288/// has no parameters to resolve, so the two routes write the same shape and one
289/// reader serves both.
290#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
291pub struct SpatialContract {
292 /// The space a body enters at.
293 pub entry: String,
294 /// Named spaces.
295 #[serde(default)]
296 pub spaces: BTreeMap<String, ContractSpace>,
297 /// Named standable-but-out-of-walk regions.
298 #[serde(default)]
299 pub no_body: BTreeMap<String, ContractNoBody>,
300 /// The graph, in declaration order.
301 #[serde(default)]
302 pub edges: Vec<ContractEdge>,
303 /// **The piece's face contract**: every `exterior` edge, as the side of the
304 /// piece it is on and the opening it leaves there.
305 ///
306 /// Derived from the edges and the blocks at export time and written out, so
307 /// that assembly can ask whether two pieces fit without opening either
308 /// `.nbt`. It is the thing an `exterior` edge IS from the outside: an edge
309 /// with no cells is a claim nothing can mate with, and one whose opening
310 /// does not answer its neighbour's is two pieces that were each approved
311 /// alone and do not assemble.
312 #[serde(default, skip_serializing_if = "Vec::is_empty")]
313 pub faces: Vec<ContractFace>,
314 /// The author's acknowledgement that this piece is mostly out-of-walk.
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub no_body_majority_ack: Option<String>,
317}
318
319/// `DW0848`: a piece's declared footprint class disagrees with its bytes.
320pub const DW_FOOTPRINT_CLASS: crate::DwCode = crate::DwCode::new("DW0848", crate::ExitTier::Build);
321
322/// **Judge a piece's declared `footprint_class` against its own structure
323/// size.**
324///
325/// One authority with two doors, on the pattern spec-0036 §1c fixed for the
326/// spatial contract: `delvec prefab audit` asks it at the admission event, where
327/// the library's integrity lives, and `delvec::compiler::detail` asks it
328/// again wherever a `detail-plan` row consumes the piece. Two implementations
329/// that agreed until they did not is the failure this shape removes.
330///
331/// What it asks, and each half is a fact about the geometry rather than a
332/// preference:
333///
334/// 1. **The name is in the table** — otherwise `DW0812`, as for any document
335/// naming a table entry.
336/// 2. **The horizontal extents could be a box of that class.** A detail frame's
337/// footprint IS its box's footprint (`Frame::of` grows the play space
338/// downward only), so a piece whose `x` or `z` falls outside the class's
339/// `min_footprint..=max_footprint` could fill no box of it.
340/// 3. **They sit on the kit grid.** A site-plan box's extent is a multiple of
341/// the grid quantum (`DW0825`), so a piece off the grid could fill no box at
342/// all, of any class.
343/// 4. **The height leaves the class its clearance.** A frame is the play space
344/// plus one floor course, so a piece under `min_clearance + 1` is short of
345/// the shallowest box of its class.
346///
347/// Returns `None` for a piece that declares no class — which is the honest
348/// answer, and why the caller states how many pieces declared one against how
349/// many it examined.
350#[must_use]
351pub fn check_footprint_class(
352 meta: &PrefabMeta,
353 stage: &str,
354 path: &str,
355 reads: &mut crate::metrics::Reads,
356) -> Option<crate::Diagnostic> {
357 let named = meta.footprint_class.as_deref()?;
358 let table = crate::metrics::Metrics::table();
359 let entry = match table.resolve(crate::metrics::MetricKind::SizeClass, named) {
360 Ok(e) => e,
361 Err(unknown) => return Some(unknown.diagnostic(stage, path)),
362 };
363 let crate::metrics::MetricValue::SizeClass(class) = *entry.value(reads) else {
364 return None; // an internal table defect, which `Metrics::self_check` owns.
365 };
366 let size = meta.size();
367 let grid = table.grid(reads);
368 let q = grid.map_or(1, |g| i64::from(g.quantum).max(1));
369 let (sx, sy, sz) = (i64::from(size[0]), i64::from(size[1]), i64::from(size[2]));
370 let (minf, maxf) = (class.min_footprint, class.max_footprint);
371 let mut why: Vec<String> = Vec::new();
372 if sx < i64::from(minf[0]) || sx > i64::from(maxf[0]) {
373 why.push(format!(
374 "its x extent is {sx}, and a `{named}` box is {}..={} on x",
375 minf[0], maxf[0]
376 ));
377 }
378 if sz < i64::from(minf[1]) || sz > i64::from(maxf[1]) {
379 why.push(format!(
380 "its z extent is {sz}, and a `{named}` box is {}..={} on z",
381 minf[1], maxf[1]
382 ));
383 }
384 if sx % q != 0 || sz % q != 0 {
385 why.push(format!(
386 "its footprint {sx}x{sz} is off the kit grid, whose quantum is {q} — every site-plan \
387 box's extent is a multiple of it (`DW0825`)"
388 ));
389 }
390 let least = i64::from(class.min_clearance) + 1;
391 if sy < least {
392 why.push(format!(
393 "it is {sy} cells tall, and the shallowest `{named}` frame is {least} — {} of \
394 clearance plus the one floor course a piece owns",
395 class.min_clearance
396 ));
397 }
398 if why.is_empty() {
399 return None;
400 }
401 Some(crate::Diagnostic::error(
402 DW_FOOTPRINT_CLASS,
403 stage,
404 path,
405 format!(
406 "`{id}` declares `footprint_class: \"{named}\"` and its own bytes could serve no box \
407 of that class: {why}. The declaration is a claim about what this piece is FOR, and a \
408 site plan hands a piece the exact frame of the box it fills — so a piece whose \
409 extents no box of the class can have is a piece no `details[]` row could ever bind. \
410 Either correct the class name, or rebuild the piece to a frame of the class it \
411 claims. Structure size is {sx}x{sy}x{sz}.",
412 id = meta.prefab_id,
413 why = why.join("; "),
414 ),
415 ))
416}
417
418/// One face of the piece's face contract.
419#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
420pub struct ContractFace {
421 /// The space the way in or out belongs to.
422 pub space: String,
423 /// The edge's class: `walk` | `stair` | `drop` | `barred` | `vision`.
424 pub class: String,
425 /// Which side of the piece: `east` | `west` | `up` | `down` | `south` |
426 /// `north`.
427 pub dir: String,
428 /// The opening, as an inclusive local cell range flat in the face's own
429 /// axis.
430 pub opening: Region,
431}
432
433/// One entry of `spatial_contract.spaces`.
434#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
435pub struct ContractSpace {
436 /// `enclosed` | `open_top` | `open`.
437 pub envelope: String,
438 /// The cells it covers.
439 pub boxes: Vec<Region>,
440}
441
442/// One entry of `spatial_contract.no_body`.
443#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
444pub struct ContractNoBody {
445 /// Why these cells are out of play, in the author's words. Which exemption
446 /// the region qualifies for is a fact about the blocks and is not recorded
447 /// here.
448 pub reason: String,
449 /// The cells it covers.
450 pub boxes: Vec<Region>,
451}
452
453/// One entry of `spatial_contract.edges`.
454#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
455pub struct ContractEdge {
456 /// A declared space name, or `exterior`.
457 pub a: String,
458 /// A declared space name, or `exterior`.
459 pub b: String,
460 /// `walk` | `stair` | `drop` | `barred` | `vision`.
461 pub class: String,
462 /// The declared level change, on the classes that carry one.
463 #[serde(default, skip_serializing_if = "Option::is_none")]
464 pub rise: Option<i64>,
465 /// The opening or transit volume, when the edge declares one.
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub via: Option<ContractVolume>,
468 /// The bar, on a `barred` edge.
469 #[serde(default, skip_serializing_if = "Option::is_none")]
470 pub bar: Option<ContractBar>,
471 /// **The contingency**, on a traversal edge that content opens: the region
472 /// the edge is severed by as built, and which direction opening it goes.
473 ///
474 /// Absent on every edge that is what it claims to be as shipped, which is
475 /// why a piece that declares none writes no key at all and its metadata is
476 /// byte-for-byte what it was.
477 #[serde(default, skip_serializing_if = "Option::is_none")]
478 pub way: Option<ContractWay>,
479}
480
481/// A contingent edge's way: the region that decides whether the edge is
482/// crossable, and which direction opening it moves in.
483///
484/// The dual of [`ContractBar`], and the reason `bar` is not extended in place:
485/// an existing piece's metadata says `bar` and keeps saying `bar`. The
486/// **checker** normalises the two into one prover; the document keeps both
487/// spellings, so nothing already written moves a byte.
488#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
489pub struct ContractWay {
490 /// `laid` — the region is empty as built and opening fills it with
491 /// [`block`](ContractWay::block); or `cleared` — the region stands in
492 /// `block` as built and opening voids it.
493 pub opens: String,
494 /// The region's name, which is what content addresses.
495 pub region: String,
496 /// The cells it covers.
497 pub boxes: Vec<Region>,
498 /// The palette role the way is made of, in the author's own vocabulary.
499 ///
500 /// Provenance for a reader, and never a second authority: what an opening
501 /// writes is [`block`](ContractWay::block), because a role name means
502 /// nothing outside the program that bound it. Recorded because a reviewer
503 /// reading this document otherwise has no way back to the declaration —
504 /// `minecraft:oak_planks` says what the cells become and `"tread"` says
505 /// what the author called it.
506 ///
507 /// Optional for the reason [`License::generated_by`] is: a role is a
508 /// *program's* vocabulary, so an expansion always has one and a hand-built
509 /// or ingested piece — which names its blocks directly — has none at all.
510 /// Writing an invented role there would be a fact about nothing.
511 ///
512 /// [`ContractBar`] carries no such field, and deliberately: adding one
513 /// would move the exported bytes of every piece that already declares a
514 /// bar, which spec-0042 §2.3 forbids. The checker reads neither.
515 #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub role: Option<String>,
517 /// The block state the way is made of: what a `laid` way is filled with,
518 /// and what a `cleared` way stands in.
519 pub block: String,
520}
521
522/// An edge's own volume — an opening, a stair's treads, a fall column.
523#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
524pub struct ContractVolume {
525 /// The region's name, which is what content binds to.
526 pub region: String,
527 /// The cells it covers.
528 pub boxes: Vec<Region>,
529}
530
531/// A `barred` edge's bar: the region that stands in the way, and its block.
532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
533pub struct ContractBar {
534 /// The region's name.
535 pub region: String,
536 /// The cells it covers.
537 pub boxes: Vec<Region>,
538 /// The block state the bar is built from.
539 pub block: String,
540}
541
542/// The `structure` block: which file, how big, for which MC version.
543#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
544pub struct StructureMeta {
545 /// The `.nbt` filename, relative to this metadata file.
546 pub file: String,
547 /// The datapack structure id (a path segment).
548 pub id: String,
549 /// Structure extent `[x, y, z]`.
550 pub size: [i32; 3],
551 /// The MC data version the structure targets (ADR-0009).
552 pub data_version: i32,
553 /// Provenance breadcrumb: what wrote the `.nbt`.
554 #[serde(default, skip_serializing_if = "Option::is_none")]
555 pub generator: Option<String>,
556}
557
558/// One structure template a piece's blocks arrive in, and where in the piece it
559/// sits.
560///
561/// **The unit every placer works in.** A single-template prefab has exactly one,
562/// at `offset` `[0, 0, 0]`; a tiled zone has one per tile at its manifest
563/// offset. Nothing that places, stamps or reads a piece's blocks needs to know
564/// which of the two it was handed — that is the whole point of the type, and the
565/// reason [`PrefabMeta::templates`] is the only way to reach a `.nbt` filename.
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567pub struct PieceTemplate<'a> {
568 /// The datapack structure id (a path segment).
569 pub id: &'a str,
570 /// The `.nbt` filename, relative to the metadata file.
571 pub file: &'a str,
572 /// This template's origin in **piece-local** coordinates — add it to a
573 /// template-local cell to get the piece cell. `[0, 0, 0]` for a
574 /// single-template piece.
575 pub offset: [i32; 3],
576 /// The template's extent `[x, y, z]`.
577 pub size: [i32; 3],
578}
579
580/// **What an anchor is FOR**, when the compiler has to find it without being
581/// told its name (spec-0046).
582///
583/// A closed vocabulary the compiler owns, and deliberately small: a role is
584/// added by the change that teaches the compiler to resolve it, never by a
585/// producer that wants a label. Deserialising is therefore the whole
586/// validation — a term this engine does not know is a `serde` error naming the
587/// terms it does, which the prefab registry reports as `DW0346` against the
588/// file that wrote it, rather than a string ridden through into a resolution
589/// that silently never matches.
590///
591/// Distinct from [`ContractWay::role`], which is a *palette* role in a
592/// program's own vocabulary and means nothing outside it. This one is the
593/// engine's vocabulary, which is exactly why it is closed.
594#[derive(
595 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
596)]
597#[serde(rename_all = "kebab-case")]
598pub enum AnchorRole {
599 /// **The cell a body arrives at when it enters the area this piece is
600 /// placed in.** One per area: `setworldspawn`, the class-apply teleport,
601 /// first-join placement, inter-area transport, the POV planner's first
602 /// frame and the trap-safety start set all resolve it.
603 Entry,
604}
605
606impl AnchorRole {
607 /// Every term in the vocabulary, in declaration order — what a refusal
608 /// lists, so the message cannot drift from the type.
609 pub const ALL: &'static [AnchorRole] = &[AnchorRole::Entry];
610
611 /// The term as it is written in a document.
612 pub fn as_str(self) -> &'static str {
613 match self {
614 AnchorRole::Entry => "entry",
615 }
616 }
617
618 /// The terms a refusal lists, comma-separated — one rendering, so a message
619 /// written at a command line and a message written by the prefab registry
620 /// cannot name different vocabularies.
621 pub fn vocabulary() -> String {
622 AnchorRole::ALL
623 .iter()
624 .map(|r| format!("`{r}`"))
625 .collect::<Vec<_>>()
626 .join(", ")
627 }
628}
629
630/// A role typed at a command line is the same closed vocabulary a role written
631/// into a document is, read from the same table — so `delvec prefab anchor
632/// --role` refuses exactly what deserialising the document refuses, by name,
633/// and the two cannot come to know different terms.
634impl std::str::FromStr for AnchorRole {
635 type Err = String;
636
637 fn from_str(s: &str) -> Result<AnchorRole, String> {
638 AnchorRole::ALL
639 .iter()
640 .copied()
641 .find(|r| r.as_str() == s)
642 .ok_or_else(|| {
643 format!(
644 "unknown anchor role `{s}` — the engine's vocabulary is {}",
645 AnchorRole::vocabulary()
646 )
647 })
648 }
649}
650
651impl std::fmt::Display for AnchorRole {
652 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
653 f.write_str(self.as_str())
654 }
655}
656
657/// One entry of the `anchors` map.
658///
659/// A point anchor carries `pos` (+ optionally `facing`); a gate anchor carries a
660/// `region` (+ optionally `block`); a trap anchor also carries the hardware the
661/// prefab pre-wired for it. All of those are the same object class — a named
662/// place in a piece — so they live in one type and each writes only the keys it
663/// means.
664#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
665pub struct Anchor {
666 /// Local cell `[x, y, z]`, relative to the structure origin.
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub pos: Option<[i32; 3]>,
669 /// Cardinal facing keyword.
670 #[serde(default, skip_serializing_if = "Option::is_none")]
671 pub facing: Option<String>,
672 /// **What this anchor is for**, when the compiler has to find it without
673 /// being told its name (spec-0046).
674 ///
675 /// A campaign addresses an anchor by its name, and for everything a
676 /// campaign addresses that is the whole story. The entry point is the one
677 /// place a campaign does *not* name — the compiler has to find it — and
678 /// finding it by matching a spelling is a fact about the producer that
679 /// wrote the piece rather than about the piece. So the piece declares it,
680 /// every producer can write it, and none has to agree with another about
681 /// how it is spelled.
682 ///
683 /// Absent on every piece that predates the role, which is what keeps the
684 /// shipped library building byte-for-byte what it built before: the
685 /// compiler falls back to the name list when no anchor in an area declares
686 /// a role.
687 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub role: Option<AnchorRole>,
689 /// Local cell range, for a gate anchor.
690 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub region: Option<Region>,
692 /// Block id filling a gate region (e.g. `minecraft:iron_bars`).
693 #[serde(default, skip_serializing_if = "Option::is_none")]
694 pub block: Option<String>,
695 /// **Which element of the piece's spatial contract this anchor lands in** —
696 /// `space:<name>`, `no_body:<name>`, `via:<name>` or `bar:<name>`.
697 ///
698 /// A campaign binds content to an anchor by name; what says whether that
699 /// place is play space, a door or exterior dressing is the contract, and a
700 /// reader who has only the anchor list cannot tell. Absent on a piece that
701 /// declares no contract, and on an anchor that lands in nothing the contract
702 /// accounts for — which is a finding the checker raises rather than a
703 /// silence.
704 #[serde(default, skip_serializing_if = "Option::is_none")]
705 pub resolves_to: Option<String>,
706 /// The pre-wired dispenser socket cell (local coords) for an `anchor/trap`
707 /// marker. `pos` is the trap's trigger/hazard cell (the plate, tripwire or
708 /// chest modelled as the hazard); `dispenser` is the separate cell holding
709 /// the empty dispenser whose payload is filled at compile time. Absent for
710 /// every non-trap anchor.
711 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub dispenser: Option<[i32; 3]>,
713 /// The block the prefab wired as this `anchor/trap`'s **trigger** — the
714 /// plate or tripwire sitting on `pos` — with its full blockstate exactly as
715 /// authored (`minecraft:oak_pressure_plate[powered=false]`), because
716 /// flag-gating a trap physically removes and restores this block and must
717 /// put back what was there. The gate-anchor `block` above is the same
718 /// contract for a sealed gate. Absent for every non-trap anchor.
719 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub trigger_block: Option<String>,
721 /// **One line of prose about this place, for a person reading the piece.**
722 ///
723 /// The engine never reads it: nothing routes, places, lights or refuses
724 /// anything because of what it says. It is modelled all the same, because
725 /// a document whose only reader is a machine is a document a person cannot
726 /// review, and a producer that writes the key unmodelled makes every build
727 /// report `DW0543` — "this library is newer than this engine" — about a
728 /// sentence. A tripwire that fires on the normal state of the tree is not a
729 /// tripwire.
730 ///
731 /// It is prose, so it is deliberately unconstrained and deliberately not
732 /// inventoried for translation: it is addressed to whoever opens the `.json`,
733 /// never to a player.
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub note: Option<String>,
736 /// Every anchor key this version does not model, kept verbatim. The anchor
737 /// block is where this document has grown most often — `resolves_to`,
738 /// `dispenser` and `trigger_block` were each a new key on a shipped
739 /// document — so it captures for the same reason [`PrefabMeta::extra`]
740 /// does.
741 #[serde(flatten)]
742 pub extra: BTreeMap<String, serde_json::Value>,
743}
744
745impl Anchor {
746 /// The point-anchor shape: a cell and a facing.
747 pub fn point(pos: [i32; 3], facing: impl Into<String>) -> Anchor {
748 Anchor {
749 pos: Some(pos),
750 facing: Some(facing.into()),
751 ..Anchor::default()
752 }
753 }
754
755 /// Declare what this anchor is for ([`Anchor::role`]).
756 pub fn with_role(mut self, role: AnchorRole) -> Anchor {
757 self.role = Some(role);
758 self
759 }
760}
761
762/// A gate anchor's region and fill block, in **piece-local** coordinates — the
763/// answer [`PrefabMeta::gate_anchor`] gives, and the only shape either reader
764/// works from.
765#[derive(Debug, Clone, PartialEq, Eq)]
766pub struct GateAnchor {
767 /// Low corner of the region, piece-local.
768 pub from: [i32; 3],
769 /// High corner of the region, piece-local, inclusive.
770 pub to: [i32; 3],
771 /// The block the region is filled with and cleared of.
772 pub block: String,
773}
774
775impl GateAnchor {
776 /// The region as a reader sees it in a diagnostic.
777 fn extent(&self) -> String {
778 format!(
779 "[{},{},{}]..[{},{},{}]",
780 self.from[0], self.from[1], self.from[2], self.to[0], self.to[1], self.to[2]
781 )
782 }
783}
784
785/// The contract-element name a `bar:<region>` [`Anchor::resolves_to`] carries,
786/// and nothing else's. Every other element kind is a place a body stands, looks
787/// through or walks over — not a thing content fills.
788fn bar_name(resolves_to: &str) -> Option<&str> {
789 resolves_to.strip_prefix("bar:")
790}
791
792/// The one box `boxes` exactly fills, or `None` when they do not fill one.
793///
794/// A contract region is a **list** of boxes, and a gate is a **single** box: the
795/// compiler fills it and clears it as one region, and every consumer of a
796/// resolved gate — the assembler that voids it, the seal that rebuilds it, the
797/// nav model that walks through it — is written against two corners. So the
798/// question is not "what box contains these" but "do these BE a box": a bounding
799/// box that the members do not fill would hand every one of those consumers
800/// cells the contract never called bar, and the assembler would delete them.
801///
802/// Exact, not approximate: the members must be pairwise disjoint and their
803/// volumes must sum to the bounding box's. A doorway declared as a lintel row
804/// plus the two jambs under it is one box and passes; a doorway plus a
805/// threshold nub hanging off its corner is not, and is refused.
806fn one_box(boxes: &[Region]) -> Option<Region> {
807 let first = boxes.first()?;
808 let mut from = first.from;
809 let mut to = first.to;
810 for b in &boxes[1..] {
811 for a in 0..3 {
812 from[a] = from[a].min(b.from[a]).min(b.to[a]);
813 to[a] = to[a].max(b.from[a]).max(b.to[a]);
814 }
815 }
816 let vol = |f: [i32; 3], t: [i32; 3]| -> i64 {
817 (0..3)
818 .map(|a| i64::from(t[a] - f[a]) + 1)
819 .try_fold(1i64, |acc, n| if n > 0 { acc.checked_mul(n) } else { None })
820 .unwrap_or(0)
821 };
822 let total: i64 = boxes.iter().map(|b| vol(b.from, b.to)).sum();
823 if total != vol(from, to) {
824 return None;
825 }
826 for (i, a) in boxes.iter().enumerate() {
827 for b in &boxes[i + 1..] {
828 if (0..3).all(|k| a.from[k] <= b.to[k] && b.from[k] <= a.to[k]) {
829 return None;
830 }
831 }
832 }
833 Some(Region { from, to })
834}
835
836/// Where an anchor is and what it is for — the parts of an anchor an editing
837/// tool declares.
838///
839/// Deliberately a different type from [`Anchor`]: the whole anchor is what a
840/// caller must not be able to hand an editing step, because constructing one
841/// means filling in — and therefore erasing — the hardware, provenance and
842/// unknown keys the caller knows nothing about. See [`PrefabMeta::edit_anchor`].
843#[derive(Debug, Clone, Default, PartialEq)]
844pub struct AnchorEdit {
845 /// Local cell `[x, y, z]`, for a point anchor.
846 pub pos: Option<[i32; 3]>,
847 /// Cardinal facing keyword.
848 pub facing: Option<String>,
849 /// Local cell range, for a gate anchor.
850 pub region: Option<Region>,
851 /// Block id filling a gate region.
852 pub block: Option<String>,
853 /// **What the anchor is for** ([`Anchor::role`]), tri-state because the
854 /// place and the purpose are two properties and an edit may speak about
855 /// either without speaking about the other:
856 ///
857 /// * `None` — the edit says nothing about the role, so an existing one is
858 /// kept. Moving a cell is not a statement that the piece stopped being
859 /// the place a party arrives at, and silently answering it as one is the
860 /// deletion this type exists to prevent.
861 /// * `Some(None)` — the edit says the anchor has **no** role, and an
862 /// existing one is removed. This is the remedy `DW0804` prescribes when
863 /// two anchors in one area both claim a role, and it is reachable here
864 /// rather than only by hand-editing the document.
865 /// * `Some(Some(role))` — the anchor is declared to have that role.
866 pub role: Option<Option<AnchorRole>>,
867}
868
869/// An inclusive local cell range.
870#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
871pub struct Region {
872 /// Low corner `[x, y, z]`.
873 pub from: [i32; 3],
874 /// High corner `[x, y, z]`.
875 pub to: [i32; 3],
876}
877
878/// One jigsaw socket declared by a prefab.
879///
880/// `local_pos` is the socket's wall cell (bottom-centre of the opening) in the
881/// prefab's local coordinates; `facing` is the cardinal direction the opening
882/// faces outward. Two sockets mate by placing the child so its socket sits one
883/// block beyond the parent's, facing the opposite way.
884#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
885pub struct Connector {
886 /// Jigsaw `name`.
887 pub name: String,
888 /// Jigsaw `target`.
889 pub target: String,
890 /// The socket's wall cell, local coords `[x, y, z]`.
891 pub local_pos: [i32; 3],
892 /// Cardinal direction the opening faces outward.
893 pub facing: String,
894 /// Opening extent `[width, height]`.
895 pub opening: [i32; 2],
896 /// Jigsaw joint.
897 pub joint: String,
898}
899
900/// The profile of a prefab whose light nothing has measured.
901pub const UNMEASURED: &str = "unmeasured";
902
903/// The `license` block: the human half and the machine half of provenance.
904#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
905pub struct License {
906 /// Where the asset came from (`original`, or a named upstream).
907 pub source: String,
908 /// SPDX id (ADR-0013).
909 pub spdx: String,
910 /// Human note.
911 pub note: String,
912 /// Human-readable provenance sentence.
913 pub provenance: String,
914 /// The machine-readable provenance row: what regenerates these exact bytes.
915 ///
916 /// Absent for a piece nothing can regenerate — an ingested community build,
917 /// or a hand-edited one. Present, it is the ADR-0006 claim in a form a tool
918 /// can act on rather than a sentence a human can read.
919 #[serde(default, skip_serializing_if = "Option::is_none")]
920 pub generated_by: Option<GeneratedBy>,
921}
922
923/// Everything needed to reproduce the `.nbt` byte for byte (ADR-0006).
924///
925/// **Every input that reaches the bytes, and nothing that does not.** A record
926/// missing one of them is worse than no record: it names a set of inputs, and a
927/// re-expansion from that set produces a different artifact while the document
928/// claims byte reproducibility. The set is the source program, the overrides
929/// applied to it, the region and the seed.
930#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
931pub struct GeneratedBy {
932 /// The back end that produced the bytes.
933 pub generator: String,
934 /// The source program's name.
935 pub program: String,
936 /// `sha256:<64 hex>` over the canonical JSON of the program **as expanded**
937 /// — the source document with [`Self::params`] and [`Self::roles`] already
938 /// applied. It is therefore the checksum of the reproduction rather than a
939 /// second statement of it: apply the overrides to the named document and
940 /// this is the hash you must get.
941 pub program_hash: String,
942 /// The expansion seed.
943 pub seed: u64,
944 /// The region the program was expanded over, `[x, y, z]`. An independent
945 /// input: the same program at the same seed over a different box is a
946 /// different building.
947 pub region: [i32; 3],
948 /// Integer parameters overridden on the way in (`delvec grammar expand
949 /// --param`), by name. Empty — and absent from the document — where the
950 /// program was expanded as written.
951 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
952 pub params: BTreeMap<String, i64>,
953 /// Palette roles rebound on the way in (`--role`), by name, each the block
954 /// state as the caller wrote it. The axis frame is not recorded because it
955 /// is not an input: a rebind inherits the frame of the binding it replaces,
956 /// which the named source document already carries.
957 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
958 pub roles: BTreeMap<String, String>,
959}
960
961impl PrefabMeta {
962 /// Parse metadata from JSON text.
963 ///
964 /// **The one reader of both packagings.** "Which shape is this" has exactly
965 /// two answers and no third, so a document declaring neither block, or both,
966 /// is refused here rather than handed half-read to a step that will place
967 /// some of its blocks. A tile set is validated as it is read
968 /// ([`TileSet::validate`]) for the same reason: a manifest that does not
969 /// tile its own volume reassembles into a building with a hole in it and
970 /// reports success.
971 pub fn from_json(text: &str) -> Result<PrefabMeta, String> {
972 let meta: PrefabMeta =
973 serde_json::from_str(text).map_err(|e| format!("invalid prefab metadata: {e}"))?;
974 match (&meta.structure, &meta.structure_set) {
975 (None, None) => {
976 return Err("prefab metadata has neither a `structure` block nor a \
977 `structure_set` block — it does not say what blocks it describes"
978 .to_string());
979 }
980 (Some(_), Some(_)) => {
981 return Err(
982 "prefab metadata has BOTH a `structure` block and a `structure_set` \
983 block — a piece's blocks arrive one way or the other, and a reader \
984 cannot be asked which one is the building"
985 .to_string(),
986 );
987 }
988 (None, Some(set)) => set
989 .validate()
990 .map_err(|e| format!("`structure_set`: {e}"))?,
991 (Some(_), None) => {}
992 }
993 Ok(meta)
994 }
995
996 /// Every structure template this piece's blocks arrive in, in a
997 /// deterministic order (grid order for a tile set).
998 ///
999 /// Empty only for a value built in code that declares neither block, which
1000 /// [`Self::from_json`] refuses — nothing read from disk is in that state.
1001 pub fn templates(&self) -> Vec<PieceTemplate<'_>> {
1002 if let Some(s) = &self.structure {
1003 return vec![PieceTemplate {
1004 id: &s.id,
1005 file: &s.file,
1006 offset: [0, 0, 0],
1007 size: s.size,
1008 }];
1009 }
1010 self.structure_set
1011 .iter()
1012 .flat_map(|set| {
1013 set.parts.iter().map(|p| PieceTemplate {
1014 id: &p.id,
1015 file: &p.file,
1016 offset: p.offset,
1017 size: p.size,
1018 })
1019 })
1020 .collect()
1021 }
1022
1023 /// The piece's extent `[x, y, z]` — the WHOLE building, whichever packaging
1024 /// its blocks arrived in. `[0, 0, 0]` only for the value
1025 /// [`Self::templates`] documents as unreachable from disk.
1026 pub fn size(&self) -> [i32; 3] {
1027 match (&self.structure, &self.structure_set) {
1028 (Some(s), _) => s.size,
1029 (None, Some(set)) => set.size,
1030 (None, None) => [0, 0, 0],
1031 }
1032 }
1033
1034 /// The MC data version the piece's templates target (ADR-0009), when it
1035 /// declares one.
1036 pub fn data_version(&self) -> Option<i32> {
1037 match (&self.structure, &self.structure_set) {
1038 (Some(s), _) => Some(s.data_version),
1039 (None, Some(set)) => Some(set.data_version),
1040 (None, None) => None,
1041 }
1042 }
1043
1044 /// True when the piece's blocks arrive as several templates — a fact about
1045 /// packaging that only a tool reporting on packaging may ask.
1046 pub fn is_tiled(&self) -> bool {
1047 self.structure_set.is_some()
1048 }
1049
1050 /// The filename stem the piece's files are named from — the single
1051 /// template's `id`, or the tile set's `base`. They are the same concept
1052 /// under two keys, so a diagnostic that wants to name the piece's document
1053 /// asks here rather than reaching into one packaging.
1054 pub fn base(&self) -> &str {
1055 match (&self.structure, &self.structure_set) {
1056 (Some(s), _) => &s.id,
1057 (None, Some(set)) => &set.base,
1058 (None, None) => "",
1059 }
1060 }
1061
1062 /// The tile grid `[x, y, z]`; `[1, 1, 1]` for a piece that fit one
1063 /// template. Packaging, like [`Self::is_tiled`].
1064 pub fn grid(&self) -> [i32; 3] {
1065 self.structure_set
1066 .as_ref()
1067 .map_or([1, 1, 1], |set| set.grid)
1068 }
1069
1070 /// Read the document at `path`, or `Ok(None)` when there is no file there.
1071 pub fn read(path: &Path) -> Result<Option<PrefabMeta>, String> {
1072 if !path.exists() {
1073 return Ok(None);
1074 }
1075 let text =
1076 std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
1077 PrefabMeta::from_json(&text).map(Some)
1078 }
1079
1080 /// Load `<nbt_path>.json` (the sibling metadata), or `Ok(None)` when absent.
1081 pub fn beside_nbt(nbt_path: &Path) -> Result<Option<PrefabMeta>, String> {
1082 let json_path = nbt_path.with_extension("json");
1083 if !json_path.exists() {
1084 return Ok(None);
1085 }
1086 let text = std::fs::read_to_string(&json_path)
1087 .map_err(|e| format!("read {}: {e}", json_path.display()))?;
1088 Ok(Some(PrefabMeta::from_json(&text)?))
1089 }
1090
1091 /// Serialize as canonical pretty JSON with a trailing newline.
1092 pub fn to_json(&self) -> String {
1093 serde_json::to_string_pretty(self).expect("prefab metadata serializes") + "\n"
1094 }
1095
1096 /// The JSON Schema of this document, for `delvec schema --stage
1097 /// prefab-metadata`.
1098 ///
1099 /// **Deliberately not part of `--stage all`.** `all` is the campaign DSL's
1100 /// staged documents, and the gallery's coverage gate enumerates its units
1101 /// from exactly that export: a library-asset document folded into it would
1102 /// demand a gallery *stage-document* binding for every field of a file no
1103 /// stage document contains. A prefab's declarations are proven where they
1104 /// are read — `shown_faces` by the exposure ledger, `walk_y` and
1105 /// `waterline_y` by the seating and waterline bindings — which is a binding
1106 /// a schema unit could not give them.
1107 ///
1108 /// It is exported anyway, and for the reason the walk record is: this is
1109 /// the command an author is told to run to see the shape of a document they
1110 /// must write, and a piece's metadata is one of those.
1111 pub fn schema() -> serde_json::Value {
1112 let mut v = serde_json::to_value(schemars::schema_for!(PrefabMeta))
1113 .expect("the prefab-metadata schema serializes to JSON");
1114 if let Some(obj) = v.as_object_mut() {
1115 obj.insert(
1116 "title".into(),
1117 serde_json::Value::String("<prefab-id>.json (prefab metadata)".into()),
1118 );
1119 obj.insert(
1120 "description".into(),
1121 serde_json::Value::String(SCHEMA_DESCRIPTION.into()),
1122 );
1123 }
1124 v
1125 }
1126
1127 /// Every key of this document — top level and per anchor — that this version
1128 /// does not model, as `(where, key)` pairs in a stable order.
1129 ///
1130 /// `where` is `""` for a top-level key and the anchor's name for an anchor
1131 /// key. A reader that wants to say something about a key it kept asks here;
1132 /// nothing has to re-open the file to find out.
1133 pub fn unknown_keys(&self) -> Vec<(&str, &str)> {
1134 let mut out: Vec<(&str, &str)> = self
1135 .extra
1136 .keys()
1137 .map(|k| ("", k.as_str()))
1138 .collect::<Vec<_>>();
1139 for (name, anchor) in &self.anchors {
1140 for key in anchor.extra.keys() {
1141 out.push((name.as_str(), key.as_str()));
1142 }
1143 }
1144 out
1145 }
1146
1147 /// A minimal skeleton for a freshly admitted external piece.
1148 pub fn skeleton(
1149 id: &str,
1150 size: [i32; 3],
1151 data_version: i32,
1152 generator: &str,
1153 license: License,
1154 ) -> PrefabMeta {
1155 PrefabMeta {
1156 prefab_id: format!("prefab/{id}"),
1157 structure: Some(StructureMeta {
1158 file: format!("{id}.nbt"),
1159 id: id.to_string(),
1160 size,
1161 data_version,
1162 generator: Some(generator.to_string()),
1163 }),
1164 structure_set: None,
1165 anchors: BTreeMap::new(),
1166 connectors: Vec::new(),
1167 lighting: Some(Lighting {
1168 method: Some("not yet probed".to_string()),
1169 ..Lighting::unmeasured()
1170 }),
1171 license: Some(license),
1172 // A freshly admitted piece states no walk plane, for the reason
1173 // `walk_y` has no default: the number is a measurement of the piece
1174 // its generator made, and the admission step that converts a
1175 // stranger's `.nbt` did not build the piece and has no walk plane
1176 // to report. A campaign that seats such a piece on a horizon whose
1177 // datum needs one is `DW0886`, which is where the author learns.
1178 walk_y: None,
1179 waterline_y: None,
1180 // A freshly admitted piece shows nothing, for the same reason it
1181 // claims no size class: which of its sides are finished surface is
1182 // the author's claim about what the piece is FOR, and reading it off
1183 // the bytes would be this document inferring intent from material.
1184 shown_faces: Vec::new(),
1185 spatial_contract: None,
1186 // A freshly admitted piece makes no claim about which size class of
1187 // box it fills, and inventing one from its bytes would be the
1188 // inference this document does not do: the claim is the author's.
1189 footprint_class: None,
1190 extra: BTreeMap::new(),
1191 }
1192 }
1193
1194 /// Annotate a named anchor's **place and purpose**, creating the anchor
1195 /// when it is not there yet.
1196 ///
1197 /// An anchor is an object, not a value. A tool that names where the anchor
1198 /// is has said nothing about the hardware the prefab wired at it
1199 /// ([`Anchor::dispenser`], [`Anchor::trigger_block`]), about which contract
1200 /// element an exporter resolved it into ([`Anchor::resolves_to`]), or about
1201 /// any key this version has never heard of ([`Anchor::extra`]) — so none of
1202 /// those is touched. Replacing the whole anchor instead is the same silent
1203 /// deletion this type exists to prevent at the top level, one level down,
1204 /// and on the block of the document that has grown most often.
1205 ///
1206 /// The place itself is one property expressed two ways — a cell or a region
1207 /// — so an edit redeclares all four of its fields together and a `pos` does
1208 /// supersede a stale `region`.
1209 ///
1210 /// The **role** is a fifth field and not a fifth way of saying where: what
1211 /// an anchor is for is a property of the anchor, so it is written when the
1212 /// edit speaks about it, cleared when the edit says it has none, and left
1213 /// alone when the edit says nothing ([`AnchorEdit::role`]).
1214 pub fn edit_anchor(&mut self, name: &str, edit: AnchorEdit) {
1215 let anchor = self.anchors.entry(name.to_string()).or_default();
1216 anchor.pos = edit.pos;
1217 anchor.facing = edit.facing;
1218 anchor.region = edit.region;
1219 anchor.block = edit.block;
1220 if let Some(role) = edit.role {
1221 anchor.role = role;
1222 }
1223 }
1224
1225 /// **The ONE authority on the region and block a gate anchor names**, in
1226 /// piece-local coordinates.
1227 ///
1228 /// A gate anchor is declared in one of two forms, and the compiler must read
1229 /// both identically:
1230 ///
1231 /// * **explicitly** — the anchor carries its own [`region`](Anchor::region)
1232 /// and [`block`](Anchor::block), which is how a hand-authored piece has
1233 /// always written one;
1234 /// * **through the piece's spatial contract** — the anchor carries a
1235 /// [`resolves_to`](Anchor::resolves_to) of `bar:<region>`, which is what an
1236 /// exporter writes. The cells and the block already live in that edge's
1237 /// [`ContractBar`], so repeating them on the anchor would be a second
1238 /// authority for one fact, and the exporter rightly does not.
1239 ///
1240 /// Nothing derived either form from the other, and the whole compiler read
1241 /// only the first. A piece declaring its gates the second way therefore had
1242 /// no gate at all: the anchor resolved to a bare point, every verb that fills
1243 /// or clears a gate was refused (`DW0343`), and the information the refusal
1244 /// asked for was sitting in the same document.
1245 ///
1246 /// Both readers ask this function and nothing else — the planner, which
1247 /// resolves the anchor to world cells, and
1248 /// [`AnchorRegistry`](crate::AnchorRegistry)'s prefab implementation, which
1249 /// answers whether the compiler can fill it — so the two cannot come to
1250 /// disagree about what a gate is or where it stands.
1251 ///
1252 /// Three answers, and the third is the one that earns the `Result`:
1253 ///
1254 /// * `Ok(None)` — not a gate anchor. A point anchor, a trap anchor, or an
1255 /// anchor whose `resolves_to` names a space, a `no_body` region, a `via`
1256 /// volume or a `way`. None of those is a thing content fills or clears.
1257 /// * `Ok(Some(gate))` — a gate, and here is the box and the block.
1258 /// * `Err(why)` — declared as a gate and **not resolvable to one fillable
1259 /// box**. Refused rather than guessed, because every alternative writes
1260 /// blocks somewhere the document did not ask for. `why` is a clause the
1261 /// caller folds into its own diagnostic.
1262 ///
1263 /// A `way` is deliberately not a gate here. Its
1264 /// [`opens`](ContractWay::opens) is a direction — `laid` cells are absent as
1265 /// built and appear when opened, `cleared` cells stand and are voided — and
1266 /// the single-region gate model carries no direction to put it in. Reading
1267 /// one as a gate would silently pick a direction for the author.
1268 pub fn gate_anchor(&self, name: &str) -> Result<Option<GateAnchor>, String> {
1269 let Some(anchor) = self.anchors.get(name) else {
1270 return Ok(None);
1271 };
1272 let contract_bar = match anchor.resolves_to.as_deref().and_then(bar_name) {
1273 Some(region) => Some(self.contract_bar(name, region)?),
1274 None => None,
1275 };
1276 match (&anchor.region, contract_bar) {
1277 (None, None) => Ok(None),
1278 // The contract form. The block is the contract's, which is the block
1279 // the piece was actually built out of.
1280 (None, Some(bar)) => Ok(Some(bar)),
1281 // The explicit form, unchanged since it was the only one. A region
1282 // with no `block` is what `DW0343` has always refused: the compiler
1283 // is being asked to fill cells with a block nothing names.
1284 (Some(region), None) => match &anchor.block {
1285 Some(block) => Ok(Some(GateAnchor {
1286 from: region.from,
1287 to: region.to,
1288 block: block.clone(),
1289 })),
1290 None => Err(format!(
1291 "gate anchor `{name}` declares a `region` and no `block`, so nothing says \
1292 what the region is filled with"
1293 )),
1294 },
1295 // Both forms. Agreement is fine and is what a piece that was
1296 // hand-authored and later exported looks like; a disagreement is
1297 // refused rather than resolved by precedence, because whichever one
1298 // this function preferred would be a rule no reader of the document
1299 // could see.
1300 (Some(region), Some(bar)) => {
1301 let explicit = GateAnchor {
1302 from: region.from,
1303 to: region.to,
1304 block: anchor.block.clone().unwrap_or_default(),
1305 };
1306 if explicit == bar {
1307 return Ok(Some(bar));
1308 }
1309 Err(format!(
1310 "gate anchor `{name}` declares a `region` and also resolves into contract bar \
1311 `{bar_region}`, and the two disagree — the anchor says {ea} filled with \
1312 `{eb}`, the bar says {ba} filled with `{bb}`. One place stands in one way: \
1313 delete the anchor's `region`/`block` and let the contract say it, or correct \
1314 the contract",
1315 bar_region = anchor
1316 .resolves_to
1317 .as_deref()
1318 .and_then(bar_name)
1319 .unwrap_or_default(),
1320 ea = explicit.extent(),
1321 eb = explicit.block,
1322 ba = bar.extent(),
1323 bb = bar.block,
1324 ))
1325 }
1326 }
1327 }
1328
1329 /// The bar `region` of this piece's spatial contract, as one fillable box.
1330 fn contract_bar(&self, anchor: &str, region: &str) -> Result<GateAnchor, String> {
1331 let bar = self
1332 .spatial_contract
1333 .as_ref()
1334 .into_iter()
1335 .flat_map(|c| c.edges.iter())
1336 .filter_map(|e| e.bar.as_ref())
1337 .find(|b| b.region == region)
1338 .ok_or_else(|| {
1339 format!(
1340 "gate anchor `{anchor}` resolves into contract bar `{region}`, and this \
1341 piece's spatial contract declares no bar of that name — the anchor's \
1342 `resolves_to` is written from the contract, so the two have come apart. \
1343 Re-export the piece"
1344 )
1345 })?;
1346 let one = one_box(&bar.boxes).ok_or_else(|| {
1347 format!(
1348 "gate anchor `{anchor}` resolves into contract bar `{region}`, whose {n} boxes do \
1349 not fill their own bounding box — so there is no single region the compiler can \
1350 fill or clear without writing blocks into cells the contract does not call bar. \
1351 Declare the bar as one box, or as boxes that tile one",
1352 n = bar.boxes.len()
1353 )
1354 })?;
1355 Ok(GateAnchor {
1356 from: one.from,
1357 to: one.to,
1358 block: bar.block.clone(),
1359 })
1360 }
1361
1362 /// Append a socket connector (idempotent by `local_pos` + `facing`).
1363 pub fn add_connector(&mut self, c: Connector) {
1364 if !self
1365 .connectors
1366 .iter()
1367 .any(|x| x.local_pos == c.local_pos && x.facing == c.facing)
1368 {
1369 self.connectors.push(c);
1370 }
1371 }
1372}
1373
1374#[cfg(test)]
1375mod tests {
1376 use super::*;
1377
1378 /// The whole reason this type is not two types: an editing tool reads a
1379 /// document, changes one block of it, and writes it back. Anything it does
1380 /// not model is deleted, and nothing says so.
1381 #[test]
1382 fn a_read_modify_write_round_trip_keeps_every_field() {
1383 let text = r#"{
1384 "prefab_id": "prefab/chapel-ward",
1385 "structure": {
1386 "file": "chapel-ward.nbt",
1387 "id": "chapel-ward",
1388 "size": [16, 9, 26],
1389 "data_version": 4671,
1390 "generator": "crates/delvec/src/grammar"
1391 },
1392 "anchors": {
1393 "anchor/bell": { "pos": [3, 1, 4], "facing": "north" },
1394 "anchor/ward": { "region": { "from": [0, 0, 0], "to": [2, 2, 2] }, "block": "minecraft:stone" }
1395 },
1396 "connectors": [],
1397 "lighting": { "profile": "unmeasured" },
1398 "license": {
1399 "source": "original",
1400 "spdx": "GPL-3.0-or-later",
1401 "note": "n",
1402 "provenance": "p",
1403 "generated_by": {
1404 "generator": "grammar",
1405 "program": "bell_chapel_ward",
1406 "program_hash": "sha256:00",
1407 "seed": 1,
1408 "region": [11, 6, 13]
1409 }
1410 },
1411 "waterline_y": 2
1412}
1413"#;
1414 let mut meta = PrefabMeta::from_json(text).unwrap();
1415 meta.lighting = Some(Lighting {
1416 profile: crate::registry::LightingProfile::Dark,
1417 measured_min_light: Some(0),
1418 measured: Some("2026-08-11".to_string()),
1419 rationale: None,
1420 method: Some("static estimate".to_string()),
1421 });
1422 let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1423 let before: serde_json::Value = serde_json::from_str(text).unwrap();
1424 assert_eq!(
1425 after["license"]["generated_by"], before["license"]["generated_by"],
1426 "the provenance row must survive an edit to an unrelated block"
1427 );
1428 assert_eq!(after["anchors"], before["anchors"]);
1429 assert_eq!(after["structure"], before["structure"]);
1430 assert_eq!(
1431 after["waterline_y"], before["waterline_y"],
1432 "a declared waterline must survive an edit to an unrelated block"
1433 );
1434 }
1435
1436 /// The same guarantee for a key no version of this type has ever heard of.
1437 /// This is the general form of the `waterline_y` and `generated_by` losses:
1438 /// the type cannot enumerate what has not been invented, so it keeps it.
1439 #[test]
1440 fn a_key_this_version_does_not_model_survives_the_round_trip() {
1441 let text = r#"{
1442 "prefab_id": "prefab/x",
1443 "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1444 "anchors": { "anchor/a": { "pos": [1, 1, 1], "acoustics": "reverberant" } },
1445 "connectors": [],
1446 "lighting": { "profile": "unmeasured" },
1447 "from_the_future": { "nested": [1, 2, 3] }
1448}
1449"#;
1450 let mut meta = PrefabMeta::from_json(text).unwrap();
1451 assert_eq!(
1452 meta.unknown_keys(),
1453 vec![("", "from_the_future"), ("anchor/a", "acoustics")],
1454 "both unknown keys must be reportable, top level and per anchor"
1455 );
1456 meta.connectors.push(Connector {
1457 name: "keep:socket".to_string(),
1458 target: "keep:socket".to_string(),
1459 local_pos: [0, 0, 0],
1460 facing: "north".to_string(),
1461 opening: [3, 3],
1462 joint: "aligned".to_string(),
1463 });
1464 let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1465 let before: serde_json::Value = serde_json::from_str(text).unwrap();
1466 assert_eq!(after["from_the_future"], before["from_the_future"]);
1467 assert_eq!(
1468 after["anchors"]["anchor/a"]["acoustics"],
1469 before["anchors"]["anchor/a"]["acoustics"]
1470 );
1471 }
1472
1473 /// The same guarantee **inside** an anchor, which is where the document's
1474 /// round trip is finest-grained and where the top-level guarantee above says
1475 /// nothing at all.
1476 ///
1477 /// An editing step that re-annotates an anchor already on the piece names
1478 /// only where it is. The dispenser cell the prefab wired, the trigger block
1479 /// it must put back, the contract element the exporter resolved, and a key
1480 /// no version has heard of are all properties of the anchor and not of the
1481 /// edit — so all four survive, and only the place changes.
1482 #[test]
1483 fn re_annotating_an_anchor_keeps_the_hardware_the_piece_carries() {
1484 let text = r#"{
1485 "prefab_id": "prefab/trap-room",
1486 "structure": { "file": "trap-room.nbt", "id": "trap-room", "size": [7, 5, 7], "data_version": 4671 },
1487 "anchors": {
1488 "anchor/trap": {
1489 "pos": [3, 1, 3],
1490 "facing": "north",
1491 "resolves_to": "space:hall",
1492 "dispenser": [3, 2, 4],
1493 "trigger_block": "minecraft:oak_pressure_plate[powered=false]",
1494 "acoustics": "reverberant"
1495 }
1496 },
1497 "connectors": [],
1498 "lighting": { "profile": "unmeasured" }
1499}
1500"#;
1501 let mut meta = PrefabMeta::from_json(text).unwrap();
1502 meta.edit_anchor(
1503 "anchor/trap",
1504 AnchorEdit {
1505 pos: Some([4, 1, 3]),
1506 facing: Some("south".to_string()),
1507 ..AnchorEdit::default()
1508 },
1509 );
1510 let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1511 let a = &after["anchors"]["anchor/trap"];
1512 assert_eq!(
1513 a["pos"],
1514 serde_json::json!([4, 1, 3]),
1515 "the place is edited"
1516 );
1517 assert_eq!(a["facing"], serde_json::json!("south"));
1518 assert_eq!(
1519 a["dispenser"],
1520 serde_json::json!([3, 2, 4]),
1521 "the pre-wired dispenser cell is the piece's hardware, not the edit's"
1522 );
1523 assert_eq!(
1524 a["trigger_block"],
1525 serde_json::json!("minecraft:oak_pressure_plate[powered=false]"),
1526 "flag-gating a trap has to put this exact block back"
1527 );
1528 assert_eq!(a["resolves_to"], serde_json::json!("space:hall"));
1529 assert_eq!(
1530 a["acoustics"],
1531 serde_json::json!("reverberant"),
1532 "a key this version does not model is the anchor's too"
1533 );
1534
1535 // A gate anchor's region and a point anchor's cell are one property, so
1536 // naming the cell supersedes the region rather than leaving both.
1537 meta.edit_anchor(
1538 "anchor/gate",
1539 AnchorEdit {
1540 region: Some(Region {
1541 from: [0, 0, 0],
1542 to: [1, 2, 0],
1543 }),
1544 block: Some("minecraft:iron_bars".to_string()),
1545 ..AnchorEdit::default()
1546 },
1547 );
1548 meta.edit_anchor(
1549 "anchor/gate",
1550 AnchorEdit {
1551 pos: Some([0, 1, 0]),
1552 ..AnchorEdit::default()
1553 },
1554 );
1555 let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1556 let g = &after["anchors"]["anchor/gate"];
1557 assert_eq!(g["pos"], serde_json::json!([0, 1, 0]));
1558 assert!(g.get("region").is_none(), "{g}");
1559 assert!(g.get("block").is_none(), "{g}");
1560 }
1561
1562 /// A tiled zone's manifest is a prefab document like any other: it is read,
1563 /// one block of it is edited, and it is written back whole — and the keys
1564 /// this version does not model survive.
1565 ///
1566 /// It used to be a *second type* (`TileSetMeta`), field-for-field this one.
1567 /// The copy is what this test is really about: the same round trip, on the
1568 /// same struct, is what makes a block added here reach both packagings.
1569 #[test]
1570 fn a_tile_set_manifest_round_trips_through_an_edit() {
1571 let text = r#"{
1572 "prefab_id": "prefab/notre-dame",
1573 "structure_set": {
1574 "base": "notre-dame",
1575 "size": [31, 48, 93],
1576 "part_max": 48,
1577 "grid": [1, 1, 2],
1578 "data_version": 4671,
1579 "generator": "crates/delvec/src/grammar",
1580 "parts": [
1581 { "file": "notre-dame.x0y0z0.nbt", "id": "a", "grid_index": [0,0,0], "offset": [0,0,0], "size": [31,48,48] },
1582 { "file": "notre-dame.x0y0z1.nbt", "id": "b", "grid_index": [0,0,1], "offset": [0,0,48], "size": [31,48,45] }
1583 ]
1584 },
1585 "anchors": { "anchor/crossing": { "pos": [15, 1, 56], "facing": "south" } },
1586 "connectors": [],
1587 "lighting": { "profile": "unmeasured" },
1588 "waterline_y": 12,
1589 "license": {
1590 "source": "original",
1591 "spdx": "GPL-3.0-or-later",
1592 "note": "n",
1593 "provenance": "p",
1594 "generated_by": {
1595 "generator": "grammar",
1596 "program": "nd",
1597 "program_hash": "sha256:00",
1598 "seed": 1,
1599 "region": [3, 3, 3]
1600 }
1601 },
1602 "a_key_no_engine_models": { "kept": true }
1603}
1604"#;
1605 let mut meta = PrefabMeta::from_json(text).unwrap();
1606 assert!(meta.is_tiled());
1607 assert_eq!(meta.size(), [31, 48, 93]);
1608 assert_eq!(meta.data_version(), Some(4671));
1609 assert_eq!(meta.license.as_ref().unwrap().spdx, "GPL-3.0-or-later");
1610 // The whole point of one document: a block the copy had lost is here.
1611 assert_eq!(meta.waterline_y, Some(12));
1612
1613 // The templates, in grid order, with their piece-local offsets.
1614 let templates = meta.templates();
1615 assert_eq!(templates.len(), 2);
1616 assert_eq!(templates[0].file, "notre-dame.x0y0z0.nbt");
1617 assert_eq!(templates[0].offset, [0, 0, 0]);
1618 assert_eq!(templates[1].id, "b");
1619 assert_eq!(templates[1].offset, [0, 0, 48]);
1620 assert_eq!(templates[1].size, [31, 48, 45]);
1621
1622 meta.lighting = Some(Lighting {
1623 profile: crate::registry::LightingProfile::Lit,
1624 measured_min_light: Some(6),
1625 measured: Some(String::new()),
1626 rationale: None,
1627 method: Some("static estimate".to_string()),
1628 });
1629 let after: serde_json::Value = serde_json::from_str(&meta.to_json()).unwrap();
1630 let before: serde_json::Value = serde_json::from_str(text).unwrap();
1631 assert_eq!(after["license"], before["license"]);
1632 assert_eq!(after["structure_set"], before["structure_set"]);
1633 assert_eq!(after["anchors"], before["anchors"]);
1634 assert_eq!(after["waterline_y"], before["waterline_y"]);
1635 assert_eq!(after["lighting"]["profile"], "lit");
1636 assert!(
1637 after.get("structure").is_none(),
1638 "a tiled document must not grow an empty `structure` key: {after}"
1639 );
1640 // Reading is total here too: a key this version has never heard of
1641 // survives an edit rather than being deleted by the tool that made it.
1642 assert_eq!(
1643 after["a_key_no_engine_models"], before["a_key_no_engine_models"],
1644 "an unmodelled key must survive a read-modify-write"
1645 );
1646 }
1647
1648 /// A single-template piece is one template at the origin, so nothing that
1649 /// places blocks has to ask which packaging it was handed.
1650 #[test]
1651 fn a_single_template_piece_is_one_template_at_the_origin() {
1652 let text = r#"{
1653 "prefab_id": "prefab/x",
1654 "structure": { "file": "x.nbt", "id": "x", "size": [3, 4, 5], "data_version": 4671 }
1655}
1656"#;
1657 let meta = PrefabMeta::from_json(text).unwrap();
1658 assert!(!meta.is_tiled());
1659 assert_eq!(meta.size(), [3, 4, 5]);
1660 assert_eq!(
1661 meta.templates(),
1662 vec![PieceTemplate {
1663 id: "x",
1664 file: "x.nbt",
1665 offset: [0, 0, 0],
1666 size: [3, 4, 5],
1667 }]
1668 );
1669 }
1670
1671 /// "Which shape is this" has exactly two answers and no third: a document
1672 /// with neither block, and one with both, are refusals rather than a
1673 /// half-read document handed to a step that places some of its blocks.
1674 #[test]
1675 fn a_document_that_does_not_say_what_blocks_it_describes_is_refused() {
1676 let err = PrefabMeta::from_json(r#"{"prefab_id":"prefab/x"}"#).unwrap_err();
1677 assert!(err.contains("structure_set"), "{err}");
1678 assert!(err.contains("structure"), "{err}");
1679
1680 let both = r#"{
1681 "prefab_id": "prefab/x",
1682 "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1683 "structure_set": {
1684 "base": "x", "size": [3, 3, 3], "part_max": 48, "grid": [1, 1, 1],
1685 "data_version": 4671, "generator": "g",
1686 "parts": [ { "file": "x.x0y0z0.nbt", "id": "x0", "grid_index": [0,0,0], "offset": [0,0,0], "size": [3,3,3] } ]
1687 }
1688}
1689"#;
1690 let err = PrefabMeta::from_json(both).unwrap_err();
1691 assert!(err.contains("BOTH"), "{err}");
1692 }
1693
1694 /// A manifest that does not tile its own zone is refused **by the reader**,
1695 /// so every consumer of the document meets it at the same place — and none
1696 /// of them reassembles a building with a hole in it and reports success.
1697 #[test]
1698 fn a_manifest_that_does_not_tile_its_zone_is_refused_by_the_reader() {
1699 let text = r#"{
1700 "prefab_id": "prefab/holed",
1701 "structure_set": {
1702 "base": "holed", "size": [4, 4, 100], "part_max": 48, "grid": [1, 1, 1],
1703 "data_version": 4671, "generator": "g",
1704 "parts": [ { "file": "holed.x0y0z0.nbt", "id": "h0", "grid_index": [0,0,0], "offset": [0,0,0], "size": [4,4,48] } ]
1705 }
1706}
1707"#;
1708 let err = PrefabMeta::from_json(text).unwrap_err();
1709 assert!(err.contains("cover"), "{err}");
1710 assert!(err.contains("hole"), "{err}");
1711 }
1712
1713 /// A piece nothing has regenerated has no row, and the key is absent rather
1714 /// than `null` — `null` reads as "measured, and the answer is nothing".
1715 #[test]
1716 fn absent_optional_fields_are_omitted_not_nulled() {
1717 let meta = PrefabMeta::skeleton(
1718 "ingested",
1719 [3, 3, 3],
1720 4671,
1721 "delvec prefab (external admission)",
1722 License {
1723 source: "unknown".to_string(),
1724 spdx: "UNKNOWN".to_string(),
1725 note: String::new(),
1726 provenance: String::new(),
1727 generated_by: None,
1728 },
1729 );
1730 let json = meta.to_json();
1731 assert!(!json.contains("generated_by"), "{json}");
1732 assert!(!json.contains("null"), "{json}");
1733 assert!(json.contains("\"connectors\": []"), "{json}");
1734 assert_eq!(PrefabMeta::from_json(&json).unwrap(), meta);
1735 }
1736
1737 /// The role vocabulary is closed **by the type**, so a term this engine does
1738 /// not know is a parse failure naming the terms it does — not a string
1739 /// carried into a resolution that then silently never matches.
1740 ///
1741 /// The mechanism is worth pinning rather than assuming: [`Anchor`] carries
1742 /// a `#[serde(flatten)]` catch-all, which buffers the whole object, and a
1743 /// buffered unknown enum variant is easy to believe would land in `extra`
1744 /// instead of erroring. It does not.
1745 #[test]
1746 fn a_role_outside_the_vocabulary_is_refused_by_name() {
1747 let anchor: Anchor =
1748 serde_json::from_str(r#"{"pos": [1, 2, 3], "role": "entry"}"#).unwrap();
1749 assert_eq!(anchor.role, Some(AnchorRole::Entry));
1750 assert!(anchor.extra.is_empty(), "a modelled key is not `extra`");
1751
1752 let err = serde_json::from_str::<Anchor>(r#"{"pos": [1, 2, 3], "role": "spawn"}"#)
1753 .expect_err("`spawn` is a NAME, and was never a role");
1754 let msg = err.to_string();
1755 assert!(msg.contains("unknown variant"), "{msg}");
1756 for role in AnchorRole::ALL {
1757 assert!(
1758 msg.contains(role.as_str()),
1759 "the refusal lists `{role}`: {msg}"
1760 );
1761 }
1762 }
1763
1764 /// An anchor's `note` is a modelled key, so a piece that explains its own
1765 /// places is not a piece reporting `DW0543` six times a build.
1766 ///
1767 /// Both halves matter and only one is obvious. It must PARSE into the field
1768 /// (or `unknown_keys` reports it, which is the defect), and it must survive
1769 /// a round trip unchanged — a modelled key that serialises back differently
1770 /// would move every prefab document the first time anything rewrote one.
1771 #[test]
1772 fn an_anchor_note_is_modelled_and_is_not_an_unknown_key() {
1773 let text = r#"{
1774 "prefab_id": "prefab/x",
1775 "structure": { "file": "x.nbt", "id": "x", "size": [3, 3, 3], "data_version": 4671 },
1776 "anchors": { "anchor/a": { "pos": [1, 1, 1], "note": "where a wave forms up" } },
1777 "connectors": [],
1778 "lighting": { "profile": "unmeasured" }
1779}
1780"#;
1781 let meta = PrefabMeta::from_json(text).unwrap();
1782 assert_eq!(
1783 meta.anchors["anchor/a"].note.as_deref(),
1784 Some("where a wave forms up")
1785 );
1786 assert_eq!(
1787 meta.unknown_keys(),
1788 Vec::<(&str, &str)>::new(),
1789 "`note` is modelled, so nothing is left for `DW0543` to report"
1790 );
1791 assert_eq!(
1792 serde_json::from_str::<serde_json::Value>(&meta.to_json()).unwrap(),
1793 serde_json::from_str::<serde_json::Value>(text).unwrap()
1794 );
1795 // An anchor that says nothing writes no key: every piece admitted before
1796 // the field stays byte-for-byte what it was.
1797 let plain = serde_json::to_string(&Anchor::point([1, 2, 3], "north")).unwrap();
1798 assert!(!plain.contains("note"), "{plain}");
1799 }
1800
1801 /// An anchor that declares no role writes no key, which is what keeps every
1802 /// piece in the shipped library byte-for-byte what it was (spec-0046 §4.5).
1803 #[test]
1804 fn an_anchor_without_a_role_writes_no_role_key() {
1805 let plain = serde_json::to_string(&Anchor::point([1, 2, 3], "north")).unwrap();
1806 assert!(!plain.contains("role"), "{plain}");
1807 let declared =
1808 serde_json::to_string(&Anchor::point([1, 2, 3], "north").with_role(AnchorRole::Entry))
1809 .unwrap();
1810 assert!(declared.contains(r#""role":"entry""#), "{declared}");
1811 }
1812
1813 /// A role typed at a command line goes through the **same** closed table a
1814 /// role written into a document does, so the two cannot come to know
1815 /// different terms — and a term the engine does not know is refused with
1816 /// both the term and the vocabulary in the message.
1817 #[test]
1818 fn a_role_parsed_from_a_word_is_the_same_vocabulary_as_a_role_read_from_a_document() {
1819 for role in AnchorRole::ALL {
1820 assert_eq!(role.as_str().parse::<AnchorRole>(), Ok(*role));
1821 }
1822 let err = "dispenser".parse::<AnchorRole>().expect_err("not a term");
1823 assert!(err.contains("dispenser"), "{err}");
1824 for role in AnchorRole::ALL {
1825 assert!(err.contains(role.as_str()), "{err}");
1826 }
1827 // The name the compiler once matched is a name and has never been a
1828 // role, so it is refused here exactly as it is refused by `serde`.
1829 assert!("spawn".parse::<AnchorRole>().is_err());
1830 }
1831
1832 /// `edit_anchor`'s role is TRI-state, and the middle state is the one that
1833 /// matters: an edit that says nothing about the role keeps it. A tool that
1834 /// moved an anchor's cell would otherwise delete the piece's entry point,
1835 /// which is the silent deletion [`AnchorEdit`] exists to prevent.
1836 #[test]
1837 fn an_edit_that_says_nothing_about_the_role_keeps_it() {
1838 let mut meta = PrefabMeta::skeleton(
1839 "x",
1840 [3, 3, 3],
1841 4671,
1842 "test",
1843 License {
1844 source: "original".to_string(),
1845 spdx: "GPL-3.0-or-later".to_string(),
1846 note: String::new(),
1847 provenance: String::new(),
1848 generated_by: None,
1849 },
1850 );
1851 let place = |role| AnchorEdit {
1852 pos: Some([1, 1, 1]),
1853 role,
1854 ..AnchorEdit::default()
1855 };
1856
1857 meta.edit_anchor("anchor/a", place(Some(Some(AnchorRole::Entry))));
1858 assert_eq!(meta.anchors["anchor/a"].role, Some(AnchorRole::Entry));
1859
1860 // Silent: kept.
1861 meta.edit_anchor(
1862 "anchor/a",
1863 AnchorEdit {
1864 pos: Some([2, 1, 1]),
1865 ..AnchorEdit::default()
1866 },
1867 );
1868 assert_eq!(meta.anchors["anchor/a"].pos, Some([2, 1, 1]));
1869 assert_eq!(meta.anchors["anchor/a"].role, Some(AnchorRole::Entry));
1870
1871 // Said to have none: removed — the remedy `DW0804` prescribes.
1872 meta.edit_anchor("anchor/a", place(Some(None)));
1873 assert_eq!(meta.anchors["anchor/a"].role, None);
1874 }
1875}