481 lines
19 KiB
TypeScript
481 lines
19 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import { resolve, toFileUrl } from "@std/path";
|
|
import {
|
|
type BlockRegistry,
|
|
EverythingRegistry,
|
|
light_tables,
|
|
type RenderLayer,
|
|
} from "@/common/everything_registry.ts";
|
|
import { load_and_check, load_order } from "@/tools/check_mods.ts";
|
|
import { mod_data } from "@/common/mod_check.ts";
|
|
import type { ServerModSource } from "@/server/game/load_mods.ts";
|
|
import { GameServer } from "@/server/game/game_server.ts";
|
|
import { start_game } from "@/server/game/load_mods.ts";
|
|
import { apply_config, load_mods } from "@/server/load_mods.ts";
|
|
import { load_client_mods } from "@/client/mods.ts";
|
|
import { read_mod } from "@/common/mod.ts";
|
|
import { pack_mod } from "@/tools/pack_mod.ts";
|
|
import { AIR_ID, PROTOCOL_VERSION } from "@/common/protocol.ts";
|
|
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
|
|
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
|
|
import { ChunkColumn, column_heights, section_index, SECTION_VOLUME } from "@/common/section.ts";
|
|
import { WorldShape, type WorldShapeJson } from "@/common/world_shape.ts";
|
|
import type { LayerMesh, SectionMesh, ToChunkWorker } from "@/client/workers/chunk_messages.ts";
|
|
import type { ModelJson } from "@/common/block_models.ts";
|
|
import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts";
|
|
import { FluidRules } from "@/common/fluids.ts";
|
|
import { BlockRules } from "@/common/block_rules.ts";
|
|
import { collision_shape_at, covers_face } from "@/common/block_shapes.ts";
|
|
import { get_state_value, set_state_value } from "@/common/utils.ts";
|
|
import type { Face, SharedWorld } from "@/common/mod_api/shared.ts";
|
|
import { shared as setup_shared } from "@/mods/bworld/scripts/shared.ts";
|
|
import { shared_context } from "@/common/shared_context.ts";
|
|
import { RecipeBook } from "@/common/mod_loader.ts";
|
|
import type { EntityJson } from "@/common/mod_data.ts";
|
|
import { mod_entity_factory } from "@/server/game/entity/mod_entity.ts";
|
|
import type { Mob } from "@/server/game/entity/mob.ts";
|
|
|
|
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
|
|
// mods/ is kept, since tests change the temporary folders they make between games
|
|
let repo_mods: ServerModSource[] | undefined;
|
|
|
|
// mods straight from their source folders, skipping the build: scripts are imported as typescript. each call gets its
|
|
// own copy, so a test that changes what it got can't change another test's
|
|
export async function mod_sources(mods_dir: string): Promise<ServerModSource[]> {
|
|
if (resolve(mods_dir) !== resolve("mods")) return await read_mod_sources(mods_dir);
|
|
// other games in mods/, the ones with a default dimension of their own, are left out: tests play bworld
|
|
repo_mods ??= (await read_mod_sources(mods_dir)).filter((mod) =>
|
|
mod.listing.id === "bworld" || !mod.data.dimensions?.some((json) => json.default)
|
|
);
|
|
return structuredClone(repo_mods);
|
|
}
|
|
|
|
async function read_mod_sources(mods_dir: string): Promise<ServerModSource[]> {
|
|
const mods = await load_and_check(mods_dir);
|
|
const errors = mods.flatMap((mod) => mod.report.errors.map((e) => `${mod.id}: ${e}`));
|
|
if (errors.length) throw new Error(errors.join("\n"));
|
|
return load_order(mods).map((mod) => {
|
|
const main = mod.manifest?.main as string | undefined;
|
|
return {
|
|
listing: {
|
|
id: mod.id,
|
|
name: String(mod.manifest?.name),
|
|
version: String(mod.manifest?.version),
|
|
sha256: "source",
|
|
file: `mods/${mod.id}.cubi`,
|
|
size: 0,
|
|
...(mod.manifest?.engine_access === true ? { engine_access: true } : {}),
|
|
},
|
|
data: mod_data(mod),
|
|
url: main ? toFileUrl(resolve(mod.dir, main)).href : undefined,
|
|
};
|
|
});
|
|
}
|
|
|
|
// saved chunks kept in memory, the last saved where a chunk is saved more than once
|
|
class MemoryChunks implements SavedChunks {
|
|
#chunks = new Map<string, SavedChunk>();
|
|
|
|
get list(): [number, number][] {
|
|
return [...this.#chunks.values()].map(({ x, z }) => [x, z]);
|
|
}
|
|
|
|
read(x: number, z: number) {
|
|
return this.#chunks.get(`${x},${z}`)?.data;
|
|
}
|
|
|
|
add(chunks: SavedChunk[]) {
|
|
for (const chunk of chunks) this.#chunks.set(`${chunk.x},${chunk.z}`, chunk);
|
|
}
|
|
}
|
|
|
|
// a game with an in memory host that remembers what it sent to each connection. the seed has low, dry land around
|
|
// 0, 0, where players spawn and where tests build things. config changes mods' settings, by mod id, like a server's
|
|
// config/<mod id>.json files
|
|
export async function test_game(
|
|
mods_dir: string,
|
|
save?: WorldSave,
|
|
seed = "test-seed-90",
|
|
config: Record<string, Record<string, unknown>> = {},
|
|
) {
|
|
EverythingRegistry.clear();
|
|
const mods = await mod_sources(mods_dir);
|
|
for (const mod of mods) {
|
|
if (!config[mod.listing.id]) continue;
|
|
const changed = apply_config(mod.data.config ?? {}, config[mod.listing.id]);
|
|
if (changed.problems.length) throw new Error(`${mod.listing.id}: ${changed.problems.join("; ")}`);
|
|
mod.data.config = changed.config;
|
|
}
|
|
const outbox = new Map<number, unknown[]>();
|
|
const closed = new Set<number>();
|
|
// what host.download gives back, by url. other urls fail
|
|
const downloads = new Map<string, Uint8Array>();
|
|
// what host.write_schematic was given, by the path it answered with
|
|
const schematics = new Map<string, Uint8Array>();
|
|
const host = {
|
|
// chunks come out decoded, as { type: "level_chunk", x, z, blocks, biomes }
|
|
send: (conn: number, data: string | Uint8Array) => {
|
|
if (!outbox.has(conn)) outbox.set(conn, []);
|
|
outbox.get(conn)!.push(
|
|
typeof data === "string" ? JSON.parse(data) : { type: "level_chunk", ...decode_level_chunk(data) },
|
|
);
|
|
},
|
|
close(conn: number) {
|
|
closed.add(conn);
|
|
},
|
|
download(url: string) {
|
|
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);
|
|
const game: GameServer = await start_game(
|
|
host,
|
|
{ level: save?.level, chunks },
|
|
seed,
|
|
mods,
|
|
);
|
|
// what it saves is read back from memory, like a host's region files
|
|
const save_game = game.save.bind(game);
|
|
game.save = () => {
|
|
const saved = save_game();
|
|
chunks.add(saved.chunks);
|
|
return saved;
|
|
};
|
|
game.chunk_send_budget_ms = Infinity;
|
|
// tests that want natural spawning turn it back on
|
|
game.do_mob_spawning = false;
|
|
// deno-lint-ignore no-explicit-any
|
|
const take = (conn: number): any[] => {
|
|
const messages = outbox.get(conn) ?? [];
|
|
outbox.set(conn, []);
|
|
return messages;
|
|
};
|
|
const send = (conn: number, message: unknown) => game.on_message(conn, JSON.stringify(message));
|
|
// the whole handshake: hello, welcome, ready, join. returns join
|
|
const join = (conn: number, name: string) => {
|
|
game.on_connect(conn);
|
|
send(conn, { type: "hello", name, protocol: PROTOCOL_VERSION });
|
|
send(conn, { type: "ready" });
|
|
return take(conn).find((m) => m.type === "join");
|
|
};
|
|
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
|
|
// join sent. undefined when no chunk there was sent
|
|
export function sent_block(
|
|
// deno-lint-ignore no-explicit-any
|
|
messages: any[],
|
|
join: { blocks: string[]; shape: { min_y: number } },
|
|
x: number,
|
|
y: number,
|
|
z: number,
|
|
) {
|
|
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
|
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
|
const chunk = messages.findLast((m) => m.type === "level_chunk" && m.x === chunk_x && m.z === chunk_z);
|
|
if (!chunk) return undefined;
|
|
const value = chunk.sections[(y - join.shape.min_y) >> 4].get(section_index(x, y, z));
|
|
return [join.blocks[value & ID_MASK], value >>> 16];
|
|
}
|
|
|
|
// a chunk worker set up the way the client sets one up, with the loaded mods' blocks. models are the mods' block models
|
|
// and visuals the blocks with them, see ToChunkWorker's init
|
|
export function chunk_worker(
|
|
shape: WorldShapeJson,
|
|
models: Record<string, ModelJson> = {},
|
|
visuals: [number, boolean][] = [],
|
|
): Worker {
|
|
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
|
|
worker.postMessage({
|
|
type: "init",
|
|
shape,
|
|
// with the registry's gaps, like the client sends it
|
|
blocks_registry: EverythingRegistry.get_registry<BlockRegistry>("blocks").map((block) =>
|
|
JSON.parse(JSON.stringify(block))
|
|
),
|
|
models,
|
|
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
|
|
image: { width: 1024, height: 1024 },
|
|
visuals,
|
|
});
|
|
return worker;
|
|
}
|
|
|
|
// the sections of the middle one of 3x3 chunks meshed by a chunk worker, asked for the way the client asks: all of
|
|
// them, or the indexes in options.sections. the chunks are each block's value in one array, y from the bottom of the
|
|
// world then z then x, null where there's none, all of one biome whose grass, foliage and water colors are each chunk's
|
|
// options.biome_colors. what comes back is each section's mesh, and all of them put together:
|
|
// their layers' quads one after another, their light, their visuals with indexes in the whole chunk (like an array's)
|
|
// and the bounds of them all
|
|
export async function mesh_column(
|
|
worker: Worker,
|
|
shape: WorldShapeJson,
|
|
chunks: (Uint32Array | null)[],
|
|
options: {
|
|
chunk_x?: number;
|
|
chunk_z?: number;
|
|
biome_colors?: (Uint32Array | null)[];
|
|
camera?: number[];
|
|
sections?: number[];
|
|
} = {},
|
|
) {
|
|
const { opacity } = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
|
|
const columns = chunks.map((blocks) =>
|
|
blocks && ChunkColumn.from_flat(0, 0, new WorldShape(shape), blocks, new Array(CHUNK_AREA).fill(""))
|
|
);
|
|
const count = columns[4]!.sections.length;
|
|
const indexes = options.sections ?? Array.from({ length: count }, (_, index) => index);
|
|
// with the section below and above them, like ClientLevel.request_meshes
|
|
const first = Math.max(0, Math.min(...indexes) - 1);
|
|
const end = Math.min(count, Math.max(...indexes) + 2);
|
|
const message: ToChunkWorker = {
|
|
type: "mesh",
|
|
chunk_x: options.chunk_x ?? 0,
|
|
chunk_z: options.chunk_z ?? 0,
|
|
sections: indexes.map((index) => ({ index, version: 1 })),
|
|
first,
|
|
chunks: columns.map((column) => column?.sections.slice(first, end).map((section) => section.data) ?? null),
|
|
sky: columns.map((column) => column && column_heights(column, opacity).slice(CHUNK_AREA)),
|
|
biomes: columns.map((column) => column?.biomes.sections.slice(first, end) ?? null),
|
|
biome_colors: options.biome_colors ?? chunks.map(() => null),
|
|
camera: options.camera ?? [0, 0, 0],
|
|
};
|
|
const sections = await new Promise<SectionMesh[]>((resolve) => {
|
|
worker.onmessage = (e) => resolve(e.data.sections);
|
|
worker.postMessage(message);
|
|
});
|
|
|
|
const layer = (name: RenderLayer): LayerMesh => {
|
|
const meshes = sections.map((section) => section[name]);
|
|
const vertices = new Uint8Array(meshes.reduce((sum, mesh) => sum + mesh.vertices.length, 0));
|
|
let at = 0;
|
|
for (const mesh of meshes) {
|
|
vertices.set(mesh.vertices, at);
|
|
at += mesh.vertices.length;
|
|
}
|
|
return { vertices, quad_count: meshes.reduce((sum, mesh) => sum + mesh.quad_count, 0) };
|
|
};
|
|
return {
|
|
sections,
|
|
solid: layer("solid"),
|
|
cutout: layer("cutout"),
|
|
translucent: layer("translucent"),
|
|
light: sections.map((section) => section.light),
|
|
visuals: Uint32Array.from(
|
|
sections.flatMap(({ index, visuals }) =>
|
|
[...visuals].map((value, i) => i % 2 === 0 ? index * SECTION_VOLUME + value : value)
|
|
),
|
|
),
|
|
min_y: Math.min(...sections.map((section) => section.min_y)),
|
|
max_y: Math.max(...sections.map((section) => section.max_y)),
|
|
};
|
|
}
|
|
|
|
// a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100
|
|
export function stone_floor(game: GameServer, radius = 3) {
|
|
for (let x = -radius; x <= radius; x++) {
|
|
for (let z = -radius; z <= radius; z++) game.set_block(x, 99, z, "bworld:stone");
|
|
}
|
|
}
|
|
|
|
// what the base game's terrain is made of underground, for ores in tests to replace
|
|
export const GROUND_BLOCKS = "#bworld:raw_rocks";
|
|
|
|
// the cubi: textures mods can use without a build
|
|
export const ENGINE_TEXTURES = ["cubi:missing", ...Array.from({ length: 9 }, (_, i) => `cubi:break_${i}`)];
|
|
|
|
// registers a folder of mod sources the way a player gets them: packed, loaded by a server, which adds the blocks
|
|
// content phases register, and the copies it serves loaded on the client
|
|
export async function load_as_player(sources: string) {
|
|
const folder = Deno.makeTempDirSync({ prefix: "bworld_player_mods_" });
|
|
try {
|
|
for (const mod of await load_and_check(sources)) {
|
|
Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
|
|
}
|
|
const mods = await load_mods(folder, ENGINE_TEXTURES);
|
|
EverythingRegistry.clear();
|
|
await load_client_mods(
|
|
mods.map((mod) => mod.listing),
|
|
mods.map((mod) => read_mod(mod.client_bytes, mod.listing.file)),
|
|
);
|
|
} finally {
|
|
Deno.removeSync(folder, { recursive: true });
|
|
}
|
|
}
|
|
|
|
// the base game, and a mod after it with these recipes
|
|
export function recipes_mod(recipes: Record<string, unknown>) {
|
|
const dir = Deno.makeTempDirSync({ prefix: "bworld_recipes_" });
|
|
copy_dir("mods/bworld", `${dir}/bworld`);
|
|
const write = (path: string, json: unknown) => {
|
|
Deno.mkdirSync(`${dir}/kiln/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
|
|
Deno.writeTextFileSync(`${dir}/kiln/${path}`, JSON.stringify(json));
|
|
};
|
|
write("manifest.json", {
|
|
format_version: 1,
|
|
id: "kiln",
|
|
name: "Kiln",
|
|
version: "1.0.0",
|
|
dependencies: [{ id: "bworld", version: "*" }],
|
|
});
|
|
for (const [name, recipe] of Object.entries(recipes)) write(`recipes/${name}.json`, { format_version: 1, recipe });
|
|
return dir;
|
|
}
|
|
|
|
export function copy_dir(from: string, to: string) {
|
|
if (Deno.statSync(from).isDirectory) {
|
|
Deno.mkdirSync(to, { recursive: true });
|
|
for (const entry of Deno.readDirSync(from)) copy_dir(`${from}/${entry.name}`, `${to}/${entry.name}`);
|
|
} else {
|
|
Deno.copyFileSync(from, to);
|
|
}
|
|
}
|
|
|
|
// menus, see server/game/menu.ts. menu 0 is the player's inventory (slots 0-35) and crafting grid (36-45)
|
|
// deno-lint-ignore no-explicit-any
|
|
type Msg = any;
|
|
|
|
// the last menu opened among messages
|
|
export const opened_menu = (messages: Msg[]) => messages.findLast((m) => m.type === "open_menu");
|
|
|
|
// what the open menu's slots last held among messages, by menu slot index
|
|
export const menu_items = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_content")?.items;
|
|
|
|
// what a container, like "inventory", last held among messages
|
|
export const container_items = (messages: Msg[], container: string) =>
|
|
messages.findLast((m) => m.type === "container" && m.container === container)?.items;
|
|
|
|
// what the open menu's data last was among messages
|
|
export const menu_data = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_data")?.data;
|
|
|
|
// a box of blocks, by the lowest and highest of each coordinate in it
|
|
export interface Area {
|
|
x: [number, number];
|
|
y: [number, number];
|
|
z: [number, number];
|
|
}
|
|
|
|
// every block in the area, as id and state bits
|
|
function blocks_in(area: Area, get: (x: number, y: number, z: number) => [string, number]) {
|
|
const out: string[] = [];
|
|
for (let x = area.x[0]; x <= area.x[1]; x++) {
|
|
for (let y = area.y[0]; y <= area.y[1]; y++) {
|
|
for (let z = area.z[0]; z <= area.z[1]; z++) out.push(`${x} ${y} ${z} ${get(x, y, z).join(" ")}`);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
export function server_blocks(game: GameServer, area: Area) {
|
|
return blocks_in(area, (x, y, z) => [game.world.get_block_id(x, y, z), game.world.get_block_value(x, y, z) >>> 16]);
|
|
}
|
|
|
|
// a client: its copy of the area, and the bworld shared phase's rules running on it the way client/mods.ts does
|
|
export function client_of(game: GameServer, area: Area) {
|
|
const copy = new Map<string, [string, number]>();
|
|
for (const line of server_blocks(game, area)) {
|
|
const [x, y, z, id, state] = line.split(" ");
|
|
copy.set(`${x} ${y} ${z}`, [id, Number(state)]);
|
|
}
|
|
const at = (x: number, y: number, z: number) => copy.get(`${x} ${y} ${z}`);
|
|
const info = (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id);
|
|
|
|
const rules = new BlockRules((_mod, _what, fn) => fn(), (x, y, z) => at(x, y, z)?.[0]);
|
|
const recipes = new RecipeBook();
|
|
const world: SharedWorld = {
|
|
get_block: (x, y, z) => at(x, y, z)?.[0],
|
|
get_state(x, y, z, name) {
|
|
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
|
const block = info(id);
|
|
return block?.states?.some((s) => s.name === name) ? get_state_value(state << 16, block, name) : undefined;
|
|
},
|
|
set_state(x, y, z, name, value) {
|
|
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
|
const block = info(id);
|
|
if (!block?.states?.some((s) => s.name === name)) return false;
|
|
const changed = set_state_value(state << 16, block, name, value)! >>> 16;
|
|
if (changed !== state) {
|
|
copy.set(`${x} ${y} ${z}`, [id, changed]);
|
|
rules.notify_neighbors(x, y, z);
|
|
}
|
|
return true;
|
|
},
|
|
is_face_sturdy(x, y, z, face: Face) {
|
|
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
|
const block = info(id);
|
|
return block !== undefined && covers_face(collision_shape_at(block, state << 16), face);
|
|
},
|
|
biome_at: () => undefined,
|
|
season_at: () => undefined,
|
|
};
|
|
setup_shared(shared_context({ id: "bworld", version: "test" }, {
|
|
side: "client",
|
|
world,
|
|
block_rules: rules,
|
|
fluid_rules: new FluidRules((_mod, _what, fn) => fn()),
|
|
// its recipes aren't looked at here
|
|
recipes: () => recipes,
|
|
running: () => true,
|
|
}));
|
|
|
|
return {
|
|
// what game_mode does when this client places held against face of x y z, at hit
|
|
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
|
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false, item: id });
|
|
// its rules say it can't go there
|
|
if (value === undefined) return;
|
|
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
|
|
rules.notify_neighbors(x, y, z);
|
|
},
|
|
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
|
|
interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
|
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit, sneaking: false }, yaw);
|
|
},
|
|
break(x: number, y: number, z: number) {
|
|
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
|
|
rules.notify_neighbors(x, y, z);
|
|
},
|
|
blocks: () => blocks_in(area, (x, y, z) => at(x, y, z)!),
|
|
};
|
|
}
|
|
|
|
// a mob made straight from entity json fields, with no goals, so it only does what a test makes it do. 0.6 wide and
|
|
// 1.8 tall unless fields say otherwise, with its feet at x y z
|
|
export function test_mob(game: GameServer, fields: Partial<EntityJson>, x: number, y: number, z: number): Mob {
|
|
const json: EntityJson = {
|
|
id: "test:mob",
|
|
texture: "cubi:missing",
|
|
behavior: "test:still",
|
|
width: 0.6,
|
|
height: 1.8,
|
|
...fields,
|
|
};
|
|
const mob = mod_entity_factory(json, new Map([["test:still", () => {}]]))(game.entities) as Mob;
|
|
mob.set_position(x, y, z);
|
|
game.entities.add_entity(mob);
|
|
return mob;
|
|
}
|
|
|
|
// what console.error got while fn ran
|
|
export async function errors_during(fn: () => unknown): Promise<string[]> {
|
|
const errors: string[] = [];
|
|
const original = console.error;
|
|
console.error = (...args: unknown[]) => errors.push(args.map(String).join(" "));
|
|
try {
|
|
await fn();
|
|
} finally {
|
|
console.error = original;
|
|
}
|
|
return errors;
|
|
}
|