Files
bworld/server/game/schematics.ts
T
2026-11-15 19:01:40 -03:00

228 lines
9.6 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// exporting a box of the world as a schematic, and where a registered one's blocks and entities go when it's placed.
// see common/schematic.ts and ctx.schematics
import type { GameServer } from "./game_server.ts";
import type { SavedEntity } from "./entity/entity.ts";
import { has_entity_type } from "./entity/entity_types.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import type { SchematicPlacement } from "@/common/mod_api/server.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,
schematic_problems,
type SchematicBlock,
type SchematicEntity,
type SchematicPaletteEntry,
} from "@/common/schematic.ts";
import { block_states, get_state_value, set_state_value, value_with_states, wrap_angle } 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)
),
};
}
// a schematic ctx.schematics.register checked, with its palette as this world's block values
export interface RegisteredSchematic {
schematic: Schematic;
palette: { id: string; value: number }[];
}
// a copy of the schematic, checked once so placing it can't fail halfway. throws saying what's wrong with it
export function prepare_schematic(game: GameServer, json: Schematic): RegisteredSchematic {
const problems = schematic_problems(json);
if (problems.length > 0) throw new Error(problems.slice(0, 5).join(", "));
const schematic = structuredClone(json);
const volume = schematic.size[0] * schematic.size[1] * schematic.size[2];
if (volume > MAX_SCHEMATIC_VOLUME) {
throw new Error(`a schematic holds up to ${MAX_SCHEMATIC_VOLUME} blocks, and this one is ${volume}`);
}
const palette = schematic.palette.map(({ id, s }) => {
if (id === AIR_ID) return { id, value: AIR };
const info = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!info) throw new Error(`it has ${id}, which isn't a block`);
return { id, value: value_with_states(game.world.block_ids[id], info, s ?? {}) };
});
for (const { i, p } of schematic.blocks) {
if (i >= palette.length) {
throw new Error(`the block at ${p.join(" ")} is palette entry ${i}, there are ${palette.length}`);
}
if (p.some((v, axis) => v >= schematic.size[axis])) {
throw new Error(`the block at ${p.join(" ")} is outside its size`);
}
}
for (const { id } of schematic.entities) {
if (!has_entity_type(id)) throw new Error(`it has ${id}, which isn't an entity`);
}
return { schematic, palette };
}
// a block a placement puts in the world, with its state bits turned
export interface PlacedBlock {
x: number;
y: number;
z: number;
id: string;
state: number;
block: SchematicBlock;
}
// how a placement turns the schematic: mirrored first, then turned clockwise this many quarters
interface Turn {
quarters: number;
mirror?: "x" | "z";
}
// where a schematic's blocks and its entities go for a placement, see SchematicPlacement and STRUCTURES.md. the
// entities as saved entities, ready to load. throws for a placement that isn't one
export function placed_schematic(
{ schematic, palette }: RegisteredSchematic,
placement: SchematicPlacement,
): { blocks: PlacedBlock[]; entities: SavedEntity[] } {
const [ox, oy, oz] = whole_position(placement?.position, "position");
const [px, , pz] = placement.position_pivot === undefined
? [0, 0, 0]
: whole_position(placement.position_pivot, "position_pivot");
const { rotation = 0, mirror } = placement;
if (![0, 90, 180, 270].includes(rotation)) throw new Error(`rotation is 0, 90, 180 or 270, not ${rotation}`);
if (mirror !== undefined && mirror !== "x" && mirror !== "z") {
throw new Error(`mirror is "x", "z" or left out, not ${mirror}`);
}
const turn: Turn = { quarters: rotation / 90, mirror };
const states = palette.map(({ value }) => turned_value(value, turn) >>> 16);
const blocks = schematic.blocks.map((block) => {
const [x, y, z] = block.p;
const [tx, tz] = turned_xz(x - px, z - pz, turn);
return { x: ox + px + tx, y: oy + y, z: oz + pz + tz, id: palette[block.i].id, state: states[block.i], block };
});
// they turn around the middle of the pivot's block, like the blocks do
const entities = schematic.entities.map(({ p: [x, y, z], id, data }) => {
const [tx, tz] = turned_xz(x - px - 0.5, z - pz - 0.5, turn);
const saved = turned_entity({ ...structuredClone(data), id } as SavedEntity, turn);
saved.pos = [ox + px + 0.5 + tx, oy + y, oz + pz + 0.5 + tz];
return saved;
});
return { blocks, entities };
}
function whole_position(position: Position | undefined, name: string): [number, number, number] {
const xyz = [position?.x, position?.y, position?.z];
if (!xyz.every(Number.isFinite)) throw new Error(`${name} needs a number for each of x, y and z`);
return xyz.map((v) => Math.floor(v!)) as [number, number, number];
}
function turned_xz(x: number, z: number, turn: Turn): [number, number] {
if (turn.mirror === "x") x = -x;
if (turn.mirror === "z") z = -z;
for (let i = 0; i < turn.quarters; i++) [x, z] = [-z, x];
return [x, z];
}
// only a state named facing turns: 0 north, 1 east, 2 south, 3 west. up and down (4 and 5) stay
function turned_value(value: number, turn: Turn): number {
const nid = value & ID_MASK;
const info = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
const bits = info?.states?.find((s) => s.name === "facing")?.bits;
if (!info || bits === undefined) return value;
let facing = get_state_value(value, info, "facing")!;
if (facing >= 4) return value;
if (turn.mirror === "x" && facing % 2 === 1) facing = 4 - facing;
if (turn.mirror === "z" && facing % 2 === 0) facing = 2 - facing;
facing = (facing + turn.quarters) % 4;
return facing < 2 ** bits ? set_state_value(value, info, "facing", facing)! : value;
}
// with its yaw and its passengers' turned. yaw 0 looks north, -π/2 east
function turned_entity(saved: SavedEntity, turn: Turn): SavedEntity {
if (Array.isArray(saved.rotation) && Number.isFinite(saved.rotation[0])) {
let yaw = saved.rotation[0];
if (turn.mirror === "x") yaw = -yaw;
if (turn.mirror === "z") yaw = Math.PI - yaw;
saved.rotation = [wrap_angle(yaw - turn.quarters * Math.PI / 2), saved.rotation[1]];
}
if (Array.isArray(saved.passengers)) saved.passengers = saved.passengers.map((p) => turned_entity(p, turn));
return saved;
}