diff --git a/MODS.md b/MODS.md
index 96e535a..245678f 100644
--- a/MODS.md
+++ b/MODS.md
@@ -80,6 +80,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
- [Commands](docs/modding/misc/commands.md)
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
+- [Schematics](docs/modding/misc/schematics.md): saving a box of the world, blocks, data and entities, to a file
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
doesn't cover yet
diff --git a/STRUCTURES.md b/STRUCTURES.md
index d9752e2..9fb96c2 100644
--- a/STRUCTURES.md
+++ b/STRUCTURES.md
@@ -11,7 +11,8 @@ Schematics are json data, encoded and decoded with MessagePack (@std/msgpack), t
On the schematic the objects have `i`, `s` and `p` keys, these correspond to `index`, `state` and `position`, they are
shorten to save on bytes on msgpack
-The data on palette.palette[number].data is from BlockComponent.export_data
+The data on blocks[number].data is from BlockComponent.export_data. A block's client data, like the item a cutting board
+holds, goes in blocks[number].client_data. `id` is left out of exported schematics, it's set when one is registered
Example:
@@ -41,7 +42,7 @@ Example:
{
"i": 2,
"p": [1, 1, 0],
- "data": { "items": [] }
+ "data": { "progress": 0, "container": [{ "id": "bworld:coal", "count": 5 }, null, null] }
}
],
"entities": [
@@ -108,9 +109,13 @@ Entities get their position turned the same way as blocks, and their yaw with it
### Saving schematics
+Built, see `docs/modding/misc/schematics.md`:
+
```typescript
-ctx.schematics.export(dimension, from, to); // saves the schematic file to a temporary directory and prints the location on the chat for the player
+// writes a .cbsm file to the system's temporary directory and resolves to its path
+ctx.schematics.export(from, to);
```
-And a `/exportschematic [x1] [y1] [z1] [x2] [y2] [z2]` command that calls ctx.schematics.export on the player's
-dimension
+It has no dimension argument yet, since a server only has one world. `/exportschematic x1 y1 z1 x2 y2 z2` calls it and
+tells the player the path in chat. The game worker can't write files, so the host writes it (`write_schematic` in
+`server/game/host_protocol.ts`).
diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts
index cff05f8..0952f1a 100644
--- a/common/mod_api/server.ts
+++ b/common/mod_api/server.ts
@@ -49,6 +49,7 @@ export interface ServerContext {
world: ServerWorld;
players: PlayerList;
containers: ContainerApi;
+ schematics: SchematicApi;
items: ItemApi;
blocks: BlockApi;
// every fluid, named and colored by its rules, and fluid handlers, see docs/modding/resources/fluids.md
@@ -118,6 +119,11 @@ export interface BlockComponent
{
// particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none
// there. see ServerFluidApi.block_handler
fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined;
+ // its tile data the way it's kept outside the world, in a schematic, like neoforge's
+ // BlockEntity.saveWithoutMetadata: what lives elsewhere written in, like its container's items in place of the
+ // container's id. any json value. the first of its components that returns something other than undefined gives
+ // it, and a block without any keeps its data as it is
+ export_data?(block: BlockRef, params: P): unknown;
// placing and neighbor rules are in shared phases, see BlockRules in cubi/shared
}
@@ -565,6 +571,14 @@ export interface ContainerApi {
delete(id: string): void;
}
+// see docs/modding/misc/schematics.md
+export interface SchematicApi {
+ // the blocks between two corners, both of them in it, with their tile data (see BlockComponent.export_data) and
+ // the entities whose feet are in that box, written to a .cbsm file the host keeps in a temporary directory, like
+ // create's schematic and quill. resolves to where the file is. throws for a box of more than 1048576 blocks (2^20)
+ export(from: Position, to: Position): Promise;
+}
+
export interface ItemApi {
exists(id: Id): boolean;
// every item, in load order
diff --git a/common/schematic.ts b/common/schematic.ts
new file mode 100644
index 0000000..4e41996
--- /dev/null
+++ b/common/schematic.ts
@@ -0,0 +1,64 @@
+// SPDX-FileCopyrightText: 2026 Paula Wisnievski
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// schematics: blocks and entities from a box of the world, kept to be placed again somewhere else. a .cbsm file is
+// one encoded with msgpack. the short keys (i, s, p) are there to keep files small, see STRUCTURES.md
+import { decode, encode } from "@std/msgpack";
+
+export const SCHEMATIC_EXTENSION = ".cbsm";
+
+export interface SchematicFile {
+ format_version: 1;
+ schematic: Schematic;
+}
+
+export interface Schematic {
+ // set once it's registered. an exported one doesn't have one yet
+ id?: string;
+ // blocks along x, y and z
+ size: [number, number, number];
+ palette: SchematicPaletteEntry[];
+ // every position in the box, air too, so placing it clears what was there
+ blocks: SchematicBlock[];
+ entities: SchematicEntity[];
+}
+
+export interface SchematicPaletteEntry {
+ id: string;
+ // its states by name, left out for a block without any
+ s?: Record;
+}
+
+export interface SchematicBlock {
+ // its entry in the palette
+ i: number;
+ // from the box's lowest corner
+ p: [number, number, number];
+ // its tile data, the way its components' export_data give it
+ data?: unknown;
+ // the part of its tile data clients see, like the item a cutting board holds
+ client_data?: Record;
+}
+
+export interface SchematicEntity {
+ // where its feet are, from the box's lowest corner
+ p: [number, number, number];
+ id: string;
+ // everything else the entity saves, without its uuid, so each one placed gets a new one
+ data: Record;
+}
+
+export function encode_schematic(schematic: Schematic): Uint8Array {
+ const file: SchematicFile = { format_version: 1, schematic };
+ // msgpack can't encode undefined, which tile data and entities can have in them. as json they're left out
+ return encode(JSON.parse(JSON.stringify(file))) as Uint8Array;
+}
+
+// throws for anything that isn't a schematic file of a format this knows
+export function decode_schematic(bytes: Uint8Array): Schematic {
+ const file = decode(bytes) as Partial | null;
+ if (file?.format_version !== 1 || typeof file.schematic !== "object" || file.schematic === null) {
+ throw new Error("isn't a schematic, or is one of a format this game doesn't know");
+ }
+ return file.schematic;
+}
diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md
index bece134..c4e453b 100644
--- a/docs/modding/blocks/components.md
+++ b/docs/modding/blocks/components.md
@@ -74,6 +74,7 @@ the block and the component.
| `on_scheduled_tick(block, params)` | A tick it asked for comes. See [Scheduled Ticks](#scheduled-ticks). | |
| `on_entity_stand(block, params, entity)` | An entity standing on it moves, every tick it does. See [Entities on It](#entities-on-it). | |
| `fluid_handler(block, params, face?)` | Something reaches for its tanks from `face`. See [Fluid Handlers](../resources/fluids.md#fluid-handlers). | a `FluidHandler`, or `undefined` |
+| `export_data(block, params)` | It goes into a schematic. See [Schematics](../misc/schematics.md#block-data). | its data for the schematic |
`block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the
block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome`
diff --git a/docs/modding/blocks/tiledata.md b/docs/modding/blocks/tiledata.md
index d79d119..28581d0 100644
--- a/docs/modding/blocks/tiledata.md
+++ b/docs/modding/blocks/tiledata.md
@@ -56,6 +56,9 @@ ctx.components.register_block("copper_tools:crate", {
The base game's `bworld:storage` does exactly this, see `mods/bworld/scripts/server.ts`.
+The container's id means nothing outside the world, so a block like this should also have an `export_data` that writes
+its items in, for when it's saved into a [schematic](../misc/schematics.md#block-data).
+
## Client Data
Client data is the part of a block's data its clients see too, like how fast a shaft turns. It's kept by field, each any
diff --git a/docs/modding/misc/schematics.md b/docs/modding/misc/schematics.md
new file mode 100644
index 0000000..5fcfc13
--- /dev/null
+++ b/docs/modding/misc/schematics.md
@@ -0,0 +1,58 @@
+# Schematics
+
+A schematic is a box of the world saved to a file: its blocks with their states and data, and the entities in it, to be
+placed again somewhere else. Schematic files end in `.cbsm` and are [MessagePack](https://msgpack.org), see
+`common/schematic.ts` for their format.
+
+Only exporting is built so far. Placing schematics, and mods shipping their own, are planned in `STRUCTURES.md`.
+
+## Exporting
+
+`/exportschematic x1 y1 z1 x2 y2 z2` saves the blocks between two corners, both of them included, in any order. The
+server writes the file to its system's temporary directory and tells the player where it is, so it's for whoever runs
+the server to pick up.
+
+Scripts do the same in the server phase:
+
+```ts
+const path = await ctx.schematics.export({ x: 0, y: 64, z: 0 }, { x: 15, y: 80, z: 15 });
+ctx.log(`saved to ${path}`);
+```
+
+A schematic holds up to 1048576 blocks (2^20), a box of 128 by 64 by 128. A bigger box throws right away.
+
+What goes in:
+
+- Every block in the box, air too, so placing it clears what was there. Blocks with the same states share one entry in
+ the palette.
+- Each block's [tile data](../blocks/tiledata.md), see [Block Data](#block-data), and its
+ [client data](../blocks/tiledata.md#client-data), like the item a cutting board holds.
+- Entities whose feet are in the box, with what they ride and what rides them, without their uuids, so each copy placed
+ gets new ones. Players aren't entities, so they're never in one.
+
+Positions are from the box's lowest corner.
+
+## Block Data
+
+Tile data goes into a schematic as it is, which is right for plain fields like a furnace's progress. Data that only
+means something in this world, like the id of a [container](../inventories/containers.md), needs an `export_data`
+handler that writes what it points to in:
+
+```ts
+ctx.components.register_block("copper_tools:crate", {
+ export_data(block) {
+ const container = ctx.containers.get(block.data.container);
+ if (!container) return block.data;
+ const items = [];
+ for (let slot = 0; slot < container.size; slot++) items.push(container.get(slot) ?? null);
+ return { ...block.data, container: items };
+ },
+});
+```
+
+It returns any JSON value, and leaves the block's own data alone. Like NeoForge's `BlockEntity.saveWithoutMetadata`,
+it's what the block is outside the world. The first of a block's components whose `export_data` returns something other
+than `undefined` decides, and a block without any keeps its data as it is.
+
+The base game's chests, furnaces, crabpots, worm bins and cooking pots do this, with `export_container_data` in
+`mods/bworld/scripts/block_containers.ts`.
diff --git a/mods/bworld/scripts/block_containers.ts b/mods/bworld/scripts/block_containers.ts
new file mode 100644
index 0000000..7e45c8b
--- /dev/null
+++ b/mods/bworld/scripts/block_containers.ts
@@ -0,0 +1,18 @@
+// SPDX-FileCopyrightText: 2026 Paula Wisnievski
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type { BlockRef, ServerContext } from "cubi/server";
+
+// export_data for a block that keeps its items in a container whose id is its data's "container", like a chest: its
+// data with the items in place of the id, one for each slot and null for an empty one, so a schematic has them. its
+// data as it is when it has no container yet
+export function export_container_data(ctx: ServerContext, block: BlockRef): unknown {
+ const container = block.data?.container && ctx.containers.get(block.data.container);
+ if (!container) return block.data;
+ const items = [];
+ for (let slot = 0; slot < container.size; slot++) {
+ const item = container.get(slot);
+ items.push(item ? { id: item.id, count: item.count, data: item.data } : null);
+ }
+ return { ...block.data, container: items };
+}
diff --git a/mods/bworld/scripts/cooking.ts b/mods/bworld/scripts/cooking.ts
index 7a88e89..6910bfb 100644
--- a/mods/bworld/scripts/cooking.ts
+++ b/mods/bworld/scripts/cooking.ts
@@ -8,6 +8,7 @@
import type { BlockRef, Container, ItemStack, ServerContext } from "cubi/server";
import { COOKING, type CookingRecipe, CUTTING, type CuttingRecipe, INGREDIENT_SLOTS } from "./cooking_recipes.ts";
+import { export_container_data } from "./block_containers.ts";
// stove
@@ -168,6 +169,7 @@ export function register_cooking_pot(ctx: ServerContext) {
};
ctx.components.register_block("bworld:cooking_pot", {
+ export_data: (block) => export_container_data(ctx, block),
on_create(block) {
pot_data(block);
},
diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts
index f847a28..a6b9100 100644
--- a/mods/bworld/scripts/server.ts
+++ b/mods/bworld/scripts/server.ts
@@ -14,6 +14,7 @@ import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES } from "./shared.
import { JUICING, type JuicingRecipe } from "./juicing.ts";
import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts";
import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts";
+import { export_container_data } from "./block_containers.ts";
export function server(ctx: ServerContext) {
register_hoeable(ctx);
@@ -143,6 +144,7 @@ function register_storage(ctx: ServerContext) {
});
ctx.components.register_block<{ rows: number }>("bworld:storage", {
+ export_data: (block) => export_container_data(ctx, block),
on_create(block, params) {
block_container(ctx, block, params.rows * 9);
},
@@ -175,6 +177,7 @@ function register_shipping_bin(ctx: ServerContext, storage_menu: ReturnType coin_value(b) - coin_value(a));
ctx.components.register_block<{ rows: number }>("bworld:shipping_bin", {
+ export_data: (block) => export_container_data(ctx, block),
on_create(block, params) {
block_container(ctx, block, params.rows * 9);
},
@@ -252,6 +255,7 @@ function register_furnace(ctx: ServerContext) {
};
ctx.components.register_block("bworld:furnace", {
+ export_data: (block) => export_container_data(ctx, block),
on_create(block) {
furnace_data(block);
},
@@ -344,6 +348,7 @@ function register_crabpot(ctx: ServerContext) {
});
ctx.components.register_block("bworld:crabpot", {
+ export_data: (block) => export_container_data(ctx, block),
on_interact(block, _params, player) {
menu_type.open(player, block);
return true;
@@ -416,6 +421,7 @@ function register_worm_bin(ctx: ServerContext) {
});
ctx.components.register_block("bworld:worm_bin", {
+ export_data: (block) => export_container_data(ctx, block),
// its container is its tile data, so its mornings come anywhere in the world, like a crop's
on_create(block) {
block_container(ctx, block, WORM_BIN_SIZE);
diff --git a/server/game/game_server.ts b/server/game/game_server.ts
index ac15527..c31be34 100644
--- a/server/game/game_server.ts
+++ b/server/game/game_server.ts
@@ -47,13 +47,16 @@ import { collision_shape_at, type Shape } from "@/common/block_shapes.ts";
import { physics } from "@/common/physics.ts";
import { EXHAUSTION } from "./vitals.ts";
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
-import type { LootContext, UseTarget } from "@/common/mod_api/server.ts";
+import type { LootContext, Position, UseTarget } from "@/common/mod_api/server.ts";
import type { EntityJson } from "@/common/mod_data.ts";
+import { encode_schematic } from "@/common/schematic.ts";
+import { capture_schematic } from "./schematics.ts";
import {
argument,
choice,
type CommandContext,
CommandError,
+ type CommandFunction,
type CommandNode,
fluid,
integer,
@@ -132,6 +135,8 @@ export interface GameHost {
close(conn: number): void;
// fetches a url, failing with a message for players when it can't or it's more than max_bytes
download(url: string, max_bytes: number): Promise;
+ // keeps an exported schematic in a new file, for whoever runs the server, resolving to where it is
+ write_schematic(bytes: Uint8Array): Promise;
}
// level.json, everything saved but the blocks, which are in region files (see saves.ts)
@@ -911,6 +916,14 @@ export class GameServer {
}
}
+ // schematics
+
+ // the box between two corners as a schematic in a file the host writes, see ctx.schematics.export. throws right
+ // away for a box that's too big
+ export_schematic(from: Position, to: Position): Promise {
+ return this.#host.write_schematic(encode_schematic(capture_schematic(this, from, to)));
+ }
+
// menus
// the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter
@@ -1772,6 +1785,22 @@ export class GameServer {
),
);
+ // TODO: only let operators do this, it writes files on the server's disk
+ // whole number arguments one after another, the last one running it
+ const coordinates = (
+ names: string[],
+ run: CommandFunction,
+ ): CommandNode => {
+ const [name, ...rest] = names;
+ const node = argument(name, integer());
+ return rest.length ? node.then(coordinates(rest, run)) : node.executes(run);
+ };
+ register(
+ literal("exportschematic")
+ .describe("Saves the blocks between two corners as a schematic file on the server")
+ .then(coordinates(["x1", "y1", "z1", "x2", "y2", "z2"], (context) => this.#export_schematic(context))),
+ );
+
register(
literal("locatebiome").describe("Finds the nearest biome of a kind").then(
argument("biome", word())
@@ -1906,6 +1935,27 @@ export class GameServer {
this.#broadcast({ type: "player_skin", id: player.id, skin, slim: slim || undefined });
}
+ // /exportschematic. the host writes the file, so the player hears back where it is a little later
+ #export_schematic(context: CommandContext) {
+ const player = context.source.server_player;
+ const [from, to] = ["1", "2"].map((corner) => ({
+ x: context.get(`x${corner}`),
+ y: context.get(`y${corner}`),
+ z: context.get(`z${corner}`),
+ }));
+ let writing: Promise;
+ try {
+ writing = this.export_schematic(from, to);
+ } catch (e) {
+ throw new CommandError(`Couldn't export it: ${(e as Error).message}`);
+ }
+ const online = () => this.#players.get(player.conn) === player;
+ writing.then(
+ (path) => online() && this.send_chat(player, `Saved the schematic to ${path}`),
+ (e) => online() && this.send_chat(player, `Couldn't save the schematic: ${(e as Error).message}`),
+ );
+ }
+
// the host downloads it, which takes a while, so the player hears back later
#download_skin(player: ServerPlayer, url: string, slim: boolean) {
if (player.downloading_skin) {
diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts
index f29787d..39df0ba 100644
--- a/server/game/host_protocol.ts
+++ b/server/game/host_protocol.ts
@@ -33,7 +33,9 @@ export type HostToGame =
// save now and say when it's done, for shutting down
| { type: "shutdown" }
// answers download, with the bytes or why it failed
- | { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string };
+ | { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string }
+ // answers write_schematic, with where the file is or why it couldn't be written
+ | { type: "wrote_schematic"; id: number; path?: string; error?: string };
export type GameToHost =
| { type: "ready"; seed: string }
@@ -46,4 +48,6 @@ export type GameToHost =
// the game waits on buffer for a saved chunk, see READ_WAITING
| { type: "read_chunk"; x: number; z: number; buffer: SharedArrayBuffer }
// the worker can't use the network, so the host fetches urls for it, like skins
- | { type: "download"; id: number; url: string; max_bytes: number };
+ | { type: "download"; id: number; url: string; max_bytes: number }
+ // an exported schematic, which the host writes to a new file in a temporary directory, see ctx.schematics.export
+ | { type: "write_schematic"; id: number; bytes: Uint8Array };
diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts
index d9fc378..682ea62 100644
--- a/server/game/mod_runtime.ts
+++ b/server/game/mod_runtime.ts
@@ -530,6 +530,24 @@ export class ModRuntime {
return undefined;
}
+ // the tile data of the block at x y z for a schematic: what the first of its components with export_data that
+ // returns something gives, or else a copy of its data
+ export_block_data(x: number, y: number, z: number, id: string): unknown {
+ const components = this.components_with(id, "export_data");
+ if (components.length > 0) {
+ const block = this.block_ref(x, y, z, id);
+ for (const { mod, id: component_id, component, params } of components) {
+ const data = run_guarded(
+ mod,
+ `${component_id} export_data`,
+ () => component.export_data!(block, params),
+ );
+ if (data !== undefined) return structuredClone(data);
+ }
+ }
+ return structuredClone(this.game.world.get_tile(x, y, z)?.mod_data);
+ }
+
// the block at x y z was told the one at from changed, and its rules have had their say: its components'
// on_neighbor_change
#neighbor_changed(x: number, y: number, z: number, from: Position) {
@@ -1041,6 +1059,9 @@ export class ModRuntime {
},
delete: (id) => game().delete_container(id),
},
+ schematics: {
+ export: (from, to) => game().export_schematic(from, to),
+ },
menus: {
extend_player_menu: (build) => {
register.running("player menu slot");
diff --git a/server/game/schematics.ts b/server/game/schematics.ts
new file mode 100644
index 0000000..7cf3b37
--- /dev/null
+++ b/server/game/schematics.ts
@@ -0,0 +1,95 @@
+// SPDX-FileCopyrightText: 2026 Paula Wisnievski
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// exporting a box of the world as a schematic, see common/schematic.ts and ctx.schematics
+import type { GameServer } from "./game_server.ts";
+import type { SavedEntity } from "./entity/entity.ts";
+import type { Position } from "@/common/mod_api/shared.ts";
+import { AIR, ID_MASK } from "@/common/constants.ts";
+import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
+import { AIR_ID } from "@/common/protocol.ts";
+import type { Schematic, SchematicBlock, SchematicEntity, SchematicPaletteEntry } from "@/common/schematic.ts";
+import { block_states } from "@/common/utils.ts";
+
+// the most blocks one schematic can hold, 2^20, so an export can't hold up the game for long
+export const MAX_SCHEMATIC_VOLUME = 1 << 20;
+
+// the blocks between two corners, both of them in it, with their tile data, and the entities whose feet are in the
+// box. positions in it are from the box's lowest corner. throws for a box that's too big
+export function capture_schematic(game: GameServer, from: Position, to: Position): Schematic {
+ for (const corner of [from, to]) {
+ if (![corner?.x, corner?.y, corner?.z].every(Number.isFinite)) {
+ throw new Error("a schematic's corners need a number for each of x, y and z");
+ }
+ }
+ const [x0, x1] = [Math.floor(Math.min(from.x, to.x)), Math.floor(Math.max(from.x, to.x))];
+ const [y0, y1] = [Math.floor(Math.min(from.y, to.y)), Math.floor(Math.max(from.y, to.y))];
+ const [z0, z1] = [Math.floor(Math.min(from.z, to.z)), Math.floor(Math.max(from.z, to.z))];
+ const size: [number, number, number] = [x1 - x0 + 1, y1 - y0 + 1, z1 - z0 + 1];
+ const volume = size[0] * size[1] * size[2];
+ if (volume > MAX_SCHEMATIC_VOLUME) {
+ throw new Error(`a schematic holds up to ${MAX_SCHEMATIC_VOLUME} blocks, and that box has ${volume}`);
+ }
+
+ const world = game.world;
+ const palette: SchematicPaletteEntry[] = [];
+ // palette entries by block value, the id with its state bits
+ const entries = new Map();
+ const blocks: SchematicBlock[] = [];
+ for (let y = y0; y <= y1; y++) {
+ for (let z = z0; z <= z1; z++) {
+ for (let x = x0; x <= x1; x++) {
+ const value = world.get_block_value(x, y, z);
+ let i = entries.get(value);
+ if (i === undefined) {
+ i = palette.length;
+ entries.set(value, i);
+ palette.push(palette_entry(value));
+ }
+ const block: SchematicBlock = { i, p: [x - x0, y - y0, z - z0] };
+ const tile = world.get_tile(x, y, z);
+ if (tile) {
+ const data = game.mods.export_block_data(x, y, z, tile.id);
+ if (data !== undefined) block.data = data;
+ if (tile.client_data) block.client_data = structuredClone(tile.client_data);
+ }
+ blocks.push(block);
+ }
+ }
+ }
+
+ // ones riding something are in what they ride's passengers, like in a save
+ const entities: SchematicEntity[] = [];
+ for (const entity of game.entities.all()) {
+ if (entity.vehicle || !entity.persistent) continue;
+ if (entity.x < x0 || entity.x >= x1 + 1 || entity.y < y0 || entity.y >= y1 + 1) continue;
+ if (entity.z < z0 || entity.z >= z1 + 1) continue;
+ const { id, uuid: _uuid, pos: _pos, ...data } = entity.save();
+ entities.push({
+ p: [entity.x - x0, entity.y - y0, entity.z - z0],
+ id,
+ data: without_passenger_uuids(data as SavedEntity),
+ });
+ }
+
+ return { size, palette, blocks, entities };
+}
+
+function palette_entry(value: number): SchematicPaletteEntry {
+ const nid = value & ID_MASK;
+ const block = nid === AIR ? undefined : EverythingRegistry.get_by_id("blocks", nid);
+ if (!block) return { id: AIR_ID };
+ const states = block_states(value, block);
+ return Object.keys(states).length ? { id: block.id, s: states } : { id: block.id };
+}
+
+// each placed copy gets new ones
+function without_passenger_uuids(saved: SavedEntity): Record {
+ if (!saved.passengers) return saved;
+ return {
+ ...saved,
+ passengers: saved.passengers.map(({ uuid: _uuid, ...passenger }) =>
+ without_passenger_uuids(passenger as SavedEntity)
+ ),
+ };
+}
diff --git a/server/game/worker.ts b/server/game/worker.ts
index 3570154..b45f97a 100644
--- a/server/game/worker.ts
+++ b/server/game/worker.ts
@@ -19,22 +19,43 @@ const CHUNK_READ_TIMEOUT_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise | undefined;
-// downloads waiting for the host, by id
-const downloads = new Map void; reject: (error: Error) => void }>();
-let next_download = 1;
+// what the game asked the host for and waits on, downloads and schematic files, by id
+const requests = new Map void; reject: (error: Error) => void }>();
+let next_request = 1;
// where the host puts saved chunks, grown when one doesn't fit
let chunk_buffer = new SharedArrayBuffer(READ_HEADER + 256 * 1024);
function post(message: GameToHost) {
- // the chunks are moved to the host, not copied
+ // the chunks and other bytes are moved to the host, not copied
const transfer = message.type === "save"
? message.save.chunks.map((chunk) => chunk.data.buffer)
: message.type === "send" && typeof message.data !== "string"
? [message.data.buffer]
+ : message.type === "write_schematic"
+ ? [message.bytes.buffer]
: [];
self.postMessage(message, transfer);
}
+function request(message: (id: number) => GameToHost): Promise {
+ return new Promise((resolve, reject) => {
+ const id = next_request++;
+ requests.set(id, { resolve: resolve as (value: never) => void, reject });
+ post(message(id));
+ });
+}
+
+// the host's answer to a request, with what was asked for, or undefined and why not
+function answer(id: number, value: unknown, error: string) {
+ const pending = requests.get(id);
+ requests.delete(id);
+ if (value !== undefined) {
+ pending?.resolve(value as never);
+ } else {
+ pending?.reject(new Error(error));
+ }
+}
+
// a saved chunk from the host. the game waits for it, like minecraft's server waits for a chunk it needs right away,
// which takes much less than generating it
function read_chunk(x: number, z: number): Uint8Array | undefined {
@@ -69,13 +90,11 @@ self.onmessage = async (event: MessageEvent) => {
return;
}
if (message.type === "downloaded") {
- const pending = downloads.get(message.id);
- downloads.delete(message.id);
- if (message.bytes) {
- pending?.resolve(message.bytes);
- } else {
- pending?.reject(new Error(message.error ?? "Couldn't download it"));
- }
+ answer(message.id, message.bytes, message.error ?? "Couldn't download it");
+ return;
+ }
+ if (message.type === "wrote_schematic") {
+ answer(message.id, message.path, message.error ?? "Couldn't write it");
return;
}
@@ -107,12 +126,8 @@ async function init(message: Extract) {
{
send: (conn, data) => post({ type: "send", conn, data }),
close: (conn) => post({ type: "close", conn }),
- download: (url, max_bytes) =>
- new Promise((resolve, reject) => {
- const id = next_download++;
- downloads.set(id, { resolve, reject });
- post({ type: "download", id, url, max_bytes });
- }),
+ download: (url, max_bytes) => request((id) => ({ type: "download", id, url, max_bytes })),
+ write_schematic: (bytes) => request((id) => ({ type: "write_schematic", id, bytes })),
},
{ level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } },
message.default_seed,
diff --git a/server/host.ts b/server/host.ts
index 24c6a54..d8e82de 100644
--- a/server/host.ts
+++ b/server/host.ts
@@ -10,6 +10,7 @@ import { load_mods } from "./load_mods.ts";
import { list_chunks, read_chunk, write_chunks } from "./regions.ts";
import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts";
import type { SavedChunk } from "./game/saves.ts";
+import { SCHEMATIC_EXTENSION } from "@/common/schematic.ts";
const MAX_MESSAGE_SIZE = 4096;
// in build/, see build.ts
@@ -141,6 +142,17 @@ export async function start_host(options: HostOptions): Promise {
post({ type: "downloaded", id: message.id, error: e instanceof Error ? e.message : String(e) }),
);
break;
+ case "write_schematic":
+ write_schematic(message.bytes).then(
+ (path) => post({ type: "wrote_schematic", id: message.id, path }),
+ (e) =>
+ post({
+ type: "wrote_schematic",
+ id: message.id,
+ error: e instanceof Error ? e.message : String(e),
+ }),
+ );
+ break;
}
};
game.onerror = (event) => {
@@ -242,6 +254,14 @@ export async function start_host(options: HostOptions): Promise {
};
}
+// an exported schematic in a new file in the system's temporary directory, for whoever runs the server to pick up.
+// returns where it is
+async function write_schematic(bytes: Uint8Array): Promise {
+ const path = await Deno.makeTempFile({ prefix: "schematic_", suffix: SCHEMATIC_EXTENSION });
+ await Deno.writeFile(path, bytes);
+ return path;
+}
+
// for the game worker, which has no network access. errors are told to players, so they say what went wrong simply
async function download(url: string, max_bytes: number): Promise {
let parsed: URL;
diff --git a/tests/helpers.ts b/tests/helpers.ts
index f20628f..7499956 100644
--- a/tests/helpers.ts
+++ b/tests/helpers.ts
@@ -109,6 +109,8 @@ export async function test_game(
const closed = new Set();
// what host.download gives back, by url. other urls fail
const downloads = new Map();
+ // what host.write_schematic was given, by the path it answered with
+ const schematics = new Map();
const host = {
// chunks come out decoded, as { type: "level_chunk", x, z, blocks, biomes }
send: (conn: number, data: string | Uint8Array) => {
@@ -124,6 +126,11 @@ export async function test_game(
const bytes = downloads.get(url);
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it"));
},
+ write_schematic(bytes: Uint8Array) {
+ const path = `memory/schematic_${schematics.size + 1}.cbsm`;
+ schematics.set(path, bytes);
+ return Promise.resolve(path);
+ },
};
const chunks = new MemoryChunks();
if (save) chunks.add(save.chunks);
@@ -157,7 +164,7 @@ export async function test_game(
send(conn, { type: "ready" });
return take(conn).find((m) => m.type === "join");
};
- return { game, take, send, join, closed, downloads };
+ return { game, take, send, join, closed, downloads, schematics };
}
// the block id and state bits at x, y, z in the chunks among messages, read the way a client does with the table
diff --git a/tests/schematic_test.ts b/tests/schematic_test.ts
new file mode 100644
index 0000000..64d6098
--- /dev/null
+++ b/tests/schematic_test.ts
@@ -0,0 +1,101 @@
+// SPDX-FileCopyrightText: 2026 Paula Wisnievski
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// exporting a box of the world as a schematic file, with /exportschematic
+import { assert, assertEquals } from "@std/assert";
+import { decode_schematic, type Schematic } from "@/common/schematic.ts";
+import { create_entity } from "@/server/game/entity/entity_types.ts";
+import { new_stack } from "@/server/game/mod_runtime.ts";
+import { set_state_value } from "@/common/utils.ts";
+import { stone_floor, test_game } from "./helpers.ts";
+
+// deno-lint-ignore no-explicit-any
+type Msg = any;
+
+async function setup() {
+ const t = await test_game("mods");
+ t.join(1, "alice");
+ stone_floor(t.game);
+ t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
+ t.take(1);
+ // runs the command and waits for the host to write the file. the schematic, or undefined and what the player was
+ // told
+ const export_schematic = async (args: string) => {
+ t.send(1, { type: "chat", text: `/exportschematic ${args}` });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const chat = t.take(1).filter((m: Msg) => m.type === "chat").map((m: Msg) => m.text as string);
+ const path = chat.map((text) => text.match(/^Saved the schematic to (.+)$/)?.[1]).find((path) => path);
+ const bytes = path ? t.schematics.get(path) : undefined;
+ return { schematic: bytes && decode_schematic(bytes), chat };
+ };
+ return { ...t, export_schematic };
+}
+
+// the palette entry of the block at p, from the box's lowest corner
+function block_at(schematic: Schematic, p: [number, number, number]) {
+ const block = schematic.blocks.find((block) => block.p.every((v, i) => v === p[i]));
+ assert(block, `nothing at ${p}`);
+ return { ...schematic.palette[block.i], data: block.data };
+}
+
+Deno.test("a schematic has every block in the box with its states, air too, from the lowest corner", async () => {
+ const t = await setup();
+ t.game.set_block(2, 100, 1, "bworld:oak_planks");
+ t.game.set_block(1, 101, 1, "bworld:furnace");
+ const furnace_value = t.game.world.get_block_value(1, 101, 1);
+ const facing_west = set_state_value(furnace_value, t.game.world.get_block_info(1, 101, 1)!, "facing", 3)!;
+ t.game.set_block_state(1, 101, 1, facing_west >>> 16);
+
+ // the corners in any order
+ const { schematic } = await t.export_schematic("2 101 1 1 100 2");
+ assert(schematic);
+ assertEquals(schematic.size, [2, 2, 2]);
+ assertEquals(schematic.blocks.length, 8);
+ assertEquals(block_at(schematic, [1, 0, 0]).id, "bworld:oak_planks");
+ const furnace = block_at(schematic, [0, 1, 0]);
+ assertEquals(furnace.id, "bworld:furnace");
+ assertEquals(furnace.s?.facing, 3);
+ assertEquals(block_at(schematic, [0, 0, 1]).id, "cubi:air");
+ // blocks with the same states share their entry
+ assertEquals(new Set(schematic.palette.map((entry) => JSON.stringify(entry))).size, schematic.palette.length);
+});
+
+Deno.test("a chest's items are written into its data in place of its container's id", async () => {
+ const t = await setup();
+ t.game.set_block(1, 100, 1, "bworld:chest");
+ const id = (t.game.world.get_tile(1, 100, 1)?.mod_data as { container: string }).container;
+ t.game.containers.get(id)!.set_item(2, new_stack({ id: "bworld:coal", count: 5 }));
+
+ const { schematic } = await t.export_schematic("1 100 1 1 100 1");
+ const items = (block_at(schematic!, [0, 0, 0]).data as { container: unknown[] }).container;
+ assertEquals(items[2], { id: "bworld:coal", count: 5 });
+ assertEquals(items[0], null);
+ // exporting doesn't change the chest
+ assertEquals(t.game.containers.get(id)!.get_item(2)?.amount, 5);
+});
+
+Deno.test("a schematic has the entities whose feet are in the box, without their uuids", async () => {
+ const t = await setup();
+ const spawn = (x: number, z: number) => {
+ const chicken = create_entity(t.game.entities, "bworld:chicken")!;
+ chicken.set_position(x, 100, z);
+ t.game.entities.add_entity(chicken);
+ };
+ spawn(1.5, 1.25);
+ spawn(5.5, 1.5);
+
+ const { schematic } = await t.export_schematic("1 100 1 2 101 2");
+ assertEquals(schematic!.entities.length, 1);
+ const [chicken] = schematic!.entities;
+ assertEquals(chicken.id, "bworld:chicken");
+ assertEquals(chicken.p, [0.5, 0, 0.25]);
+ assertEquals(chicken.data.uuid, undefined);
+});
+
+Deno.test("a box with too many blocks isn't exported", async () => {
+ const t = await setup();
+ const { schematic, chat } = await t.export_schematic("0 0 0 1000 200 1000");
+ assertEquals(schematic, undefined);
+ assert(chat.some((text) => text.startsWith("Couldn't export it")), chat.join("\n"));
+ assertEquals(t.schematics.size, 0);
+});