Export schematics

This commit is contained in:
2026-11-15 18:41:22 -03:00
parent 2fa109026c
commit 59bfed58bf
18 changed files with 511 additions and 26 deletions
+51 -1
View File
@@ -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<Uint8Array>;
// keeps an exported schematic in a new file, for whoever runs the server, resolving to where it is
write_schematic(bytes: Uint8Array<ArrayBuffer>): Promise<string>;
}
// 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<string> {
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<ServerCommandSource>,
): CommandNode<ServerCommandSource> => {
const [name, ...rest] = names;
const node = argument<number, ServerCommandSource>(name, integer());
return rest.length ? node.then(coordinates(rest, run)) : node.executes(run);
};
register(
literal<ServerCommandSource>("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<ServerCommandSource>("locatebiome").describe("Finds the nearest biome of a kind").then(
argument<string, ServerCommandSource>("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<ServerCommandSource>) {
const player = context.source.server_player;
const [from, to] = ["1", "2"].map((corner) => ({
x: context.get<number>(`x${corner}`),
y: context.get<number>(`y${corner}`),
z: context.get<number>(`z${corner}`),
}));
let writing: Promise<string>;
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) {
+6 -2
View File
@@ -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<ArrayBuffer> };
+21
View File
@@ -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");
+95
View File
@@ -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<number, number>();
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<BlockRegistry>("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<string, unknown> {
if (!saved.passengers) return saved;
return {
...saved,
passengers: saved.passengers.map(({ uuid: _uuid, ...passenger }) =>
without_passenger_uuids(passenger as SavedEntity)
),
};
}
+32 -17
View File
@@ -19,22 +19,43 @@ const CHUNK_READ_TIMEOUT_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// downloads waiting for the host, by id
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => 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<number, { resolve: (value: never) => 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<T>(message: (id: number) => GameToHost): Promise<T> {
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<HostToGame>) => {
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<HostToGame, { type: "init" }>) {
{
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,
+20
View File
@@ -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<Host> {
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<Host> {
};
}
// 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<string> {
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<Uint8Array> {
let parsed: URL;