Files
bworld/server/game/game_server.ts
T
2026-11-21 09:16:51 -03:00

2787 lines
104 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
AIR,
BREAK_STAGES,
CHUNK_SIZE,
FACE_OFFSETS,
Faces,
faces,
ID_MASK,
PLAYER_WIDTH,
TICK_DELTA,
TICKS_PER_SECOND,
} from "@/common/constants.ts";
import { BlockRegistry, EverythingRegistry, is_fluid_block, ItemRegistry } from "@/common/everything_registry.ts";
import { FluidFlow } from "./fluids.ts";
import { contained_fluid, Container, ItemData, ItemStack } from "@/common/inventory.ts";
import {
AIR_ID,
ClientMessage,
MAX_CHAT_LENGTH,
MAX_NAME_LENGTH,
PROTOCOL_VERSION,
ServerMessage,
} from "@/common/protocol.ts";
import type { ModListing, RecipeBook } from "@/common/mod_loader.ts";
import type { WorldgenSetup } from "@/common/generation.ts";
import type { WorldgenBundle } from "@/common/worldgen_bundle.ts";
import type { WorldgenPool } from "./worldgen_pool.ts";
import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "@/common/chunk_streaming.ts";
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "@/common/time.ts";
import {
block_states,
box_overlaps_block,
can_place,
can_stand_on,
chunk_key,
display_name,
fluid_block,
is_waterlogged,
placement_target,
set_state_value,
waterlog_placement,
} from "@/common/utils.ts";
import { collision_shape_at, raycast_blocks, type Shape, shape_at } 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, Position, SchematicPlacement, 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, placed_schematic, type RegisteredSchematic } from "./schematics.ts";
import {
argument,
type ArgumentType,
block,
choice,
type CommandContext,
CommandError,
type CommandFunction,
CommandNode,
fluid,
integer,
item,
json,
literal,
number,
word,
} from "@/common/commands.ts";
import { biome_ids, get_biome } from "@/common/worldgen/biomes.ts";
import type { GameLoop } from "./game_loop.ts";
import { update_crafting_result } from "./crafting.ts";
import type { Menu } from "./menu.ts";
import { MACHINE_CONN, SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { ScheduledTicks } from "./scheduled_ticks.ts";
import type { WorldSave, WorldSource } from "./saves.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
ITEM_ENTITY_TYPE,
ITEM_SIZE,
ItemEntity,
PLAYER_DROP_PICKUP_DELAY,
type SavedItemEntity,
} from "./entity/item_entity.ts";
import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts";
import { NaturalSpawner } from "./natural_spawner.ts";
import { create_entity, entity_type_ids, load_entity } from "./entity/entity_types.ts";
import { damage_source, type DamageSource, type Entity, type SavedEntity } from "./entity/entity.ts";
import { effect_type, effect_type_ids, EffectInstance } from "./entity/effects.ts";
import { ATTRIBUTES } from "./entity/attributes.ts";
// how much further than their reach attributes the server lets a player use blocks and hit entities, for where they
// moved since their client aimed
const REACH_LEEWAY = 2;
// how far past a player's box items get picked up from, sideways and up or down, like minecraft
const PICKUP_REACH_XZ = 1;
const PICKUP_REACH_Y = 0.5;
// tiles further than this many chunks from every player don't tick
const SIMULATION_DISTANCE = 6;
const MAX_GIVE = 64 * 36;
// the most blocks one /fill changes, so it can't hold up the game for long
const MAX_FILL_VOLUME = 1 << 15;
// /locatebiome looks at columns this far apart, out to this far, like minecraft's
const LOCATE_STEP = 32;
const LOCATE_RADIUS = 6400;
// the most suggestions sent for one request
const MAX_SUGGESTIONS = 100;
// falls up to this many blocks don't hurt, like minecraft
const SAFE_FALL = 3;
// faster than walking (4.3 blocks a second) and slower than sprinting (5.6)
const SPRINT_SPEED = 5;
// moving further than this at once is a teleport, not a fall
const TELEPORT_DISTANCE = 20;
// how close feet have to be to a block's top to stand on it
const GROUND_EPSILON = 0.02;
// the most mornings run at once after time jumps forward, the rest are skipped
const MAX_CATCH_UP_DAYS = 64;
// how long a client gets between welcome and ready to download and load everything
const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND;
// the furthest the server sends chunks around a player, and what players who don't say get, until /viewdistance
// changes it
const SERVER_VIEW_DISTANCE = 16;
// how long a tick can spend building chunks for players, the rest go out on the next ticks
const CHUNK_SEND_BUDGET_MS = 20;
// with a worldgen pool, how many of the chunks each player is waiting for it's asked for at once, nearest first. a
// few ticks of sending ahead, without filling the world's raw chunk cache with ones that won't be sent for a while
const WORLDGEN_REQUEST_WINDOW = 64;
// everything the game server needs from whatever runs it
export interface GameHost {
// text is a json message, bytes a binary one (level_chunk)
send(conn: number, data: string | Uint8Array<ArrayBuffer>): void;
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)
export interface SavedLevel {
version: 5;
seed: string;
// world time in ticks
time: number;
tiles: Tile[];
// the ticks blocks scheduled that haven't run, in the order they'll run, see ServerWorld.schedule_tick. ticks_left
// is 0 or less for ones waiting for a player to come near
scheduled_ticks: [x: number, y: number, z: number, id: string, ticks_left: number, priority: number][];
// every ctx.containers container, by id
containers: Record<string, (ItemData | null)[]>;
players: Record<string, SavedPlayer>;
// every entity, see entity/entity.ts. version 4 had only items, with their own fields
entities: SavedEntity[];
// ctx.storage of every mod, by mod id
mod_storage: Record<string, Record<string, unknown>>;
}
// the loaded mods, see load_mods.ts
export interface GameMods {
listings: ModListing[];
recipes: RecipeBook;
worldgen: WorldgenSetup;
runtime: ModRuntime;
}
export class GameServer {
world: ServerWorld;
#host: GameHost;
#players = new Map<number, ServerPlayer>();
// connections that got welcome and are downloading mods, by conn
#pending = new Map<number, { name: unknown; since: number }>();
// which player gets chunks first next tick, so one with a lot to load doesn't always use up the budget
#next_chunk_player = 0;
#saved_players: Record<string, SavedPlayer> = {};
#tick = 0;
// see ServerWorld.schedule_tick, due on game ticks
#scheduled = new ScheduledTicks();
// the last morning new day handlers ran for
#day = 0;
#mods: GameMods;
// ctx.containers, saved with the world
containers = new Map<string, Container>();
// by id, what ctx.schematics.register added for place
readonly schematics = new Map<string, RegisteredSchematic>();
// everything in the world that isn't a block or a player
entities: EntityManager;
mods: ModRuntime;
recipes: RecipeBook;
// monsters spawning on their own near players, see natural_spawner.ts
spawner: NaturalSpawner;
// water and other fluids flowing, see fluids.ts
fluids: FluidFlow;
// minecraft's doMobSpawning game rule. tests turn it off so nothing turns up they didn't put there
do_mob_spawning = true;
// what runs tick(), for /tps. tests call tick() themselves
loop?: GameLoop;
// SERVER_VIEW_DISTANCE, or what /viewdistance set it to. not saved, it's for testing
view_distance = SERVER_VIEW_DISTANCE;
// how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed
chunk_send_budget_ms = CHUNK_SEND_BUDGET_MS;
// what a worldgen worker needs to generate the same chunks as this game, see start_game
worldgen_bundle?: WorldgenBundle;
// generates chunks off the game's thread, see use_worldgen_pool. without it, they're generated when needed
worldgen_pool?: WorldgenPool;
// world.fallbacks each second for the last minute, for /tps
#fallback_history: number[] = [];
constructor(host: GameHost, save: WorldSource | undefined, default_seed: string, mods: GameMods) {
this.#host = host;
this.#mods = mods;
this.mods = mods.runtime;
this.recipes = mods.recipes;
this.spawner = new NaturalSpawner(mods.recipes.spawns);
const saved: SavedLevel | SavedLevelV4 | undefined = save?.level ? JSON.parse(save.level) : undefined;
if (saved && saved.version !== 5 && saved.version !== 4) {
throw new Error(
`The world was saved in format ${
(saved as { version: unknown }).version
}, this server only loads formats 4 and 5`,
);
}
this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen);
this.fluids = new FluidFlow({
value_at: (x, y, z) => {
if (!this.world.shape.contains(y)) return undefined;
const loaded = this.world.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
return loaded ? this.world.get_block_value(x, y, z) : undefined;
},
block: (nid) => EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid),
nid: (id) => this.world.block_ids[id],
set_block: (x, y, z, id, state) => {
// a level changing is only a state, the block's components don't see it come and go
if (id === this.world.get_block_id(x, y, z)) this.set_block_state(x, y, z, state);
else this.set_block(x, y, z, id, undefined, state);
},
});
// deno-lint-ignore no-this-alias
const game = this;
this.entities = new EntityManager({
get world() {
return game.world;
},
get current_tick() {
return game.#tick;
},
players: () => this.players(),
send: (player, message) => this.#send(player, message),
before_hurt: (entity, amount, source) =>
this.mods.before_damage(entity, entity instanceof ServerPlayer ? entity : undefined, amount, source),
after_hurt: (entity, amount, source) =>
this.mods.after_damage(entity, entity instanceof ServerPlayer ? entity : undefined, amount, source),
on_entity_death: (entity, source) => {
if (entity instanceof ServerPlayer) this.#kill(entity, source);
},
stands_on: (entity, x, y, z) => {
const id = this.world.get_block_id(x, y, z);
const components = this.mods.components_with(id, "on_entity_stand");
if (components.length === 0) return;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
if (entity.removed) return;
run_guarded(
mod,
`${component_id} on_entity_stand`,
() => component.on_entity_stand!(block, params, entity_ref(entity)),
);
}
},
inside_blocks: (entity) => this.#inside_blocks(entity),
entity_loot: (entity, source) => {
const table = EverythingRegistry.get<EntityJson>("entities", entity.type)?.loot_table;
if (!table) return [];
const killer = source.attacker instanceof ServerPlayer ? source.attacker : undefined;
return this.roll_loot(table, {
position: { x: entity.x, y: entity.y, z: entity.z },
entity: entity_ref(entity),
killed_by_player: source.by_player === true,
player: killer && this.mods.player(killer),
tool: killer && this.mods.player(killer).held_item,
});
},
});
this.mods.storage = saved?.mod_storage ?? {};
if (save) this.world.use_saved_chunks(save.chunks);
this.world.time = saved?.time ?? 0;
this.#day = this.world.day;
for (const [id, items] of Object.entries(saved?.containers ?? {})) {
const container = new Container(items.length);
container.load(items);
this.containers.set(id, container);
}
for (const tile of saved?.tiles ?? []) this.world.add_tile({ ...tile });
for (const [x, y, z, id, ticks_left, priority] of saved?.scheduled_ticks ?? []) {
// unless its mod is gone
const nid = this.world.block_ids[id];
if (nid !== undefined) this.#scheduled.add(x, y, z, nid, ticks_left, priority);
}
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
this.#saved_players = saved?.players ?? {};
// a new world is saved straight away
this.world.dirty = !saved;
this.#register_commands();
// players without the chunk get the block with it when they do, like minecraft
this.world.on_block_change = (x, y, z, id, state) => {
this.fluids.changed(x, y, z, this.#tick);
const data = JSON.stringify(
(state
? { type: "set_block", x, y, z, id, state }
: { type: "set_block", x, y, z, id }) satisfies ServerMessage,
);
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) {
this.#host.send(player.conn, data);
}
}
};
this.world.on_client_data_change = (x, y, z, changed) => {
const data = JSON.stringify({ type: "block_data", x, y, z, data: changed } satisfies ServerMessage);
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) {
this.#host.send(player.conn, data);
}
}
};
}
// connections
on_connect(_conn: number) {}
on_disconnect(conn: number) {
this.#pending.delete(conn);
const player = this.#players.get(conn);
if (!player) {
return;
}
this.#close_menu(player);
this.#saved_players[player.name] = player.save_player();
this.world.dirty = true;
this.#players.delete(conn);
// mobs after them give up
player.remove();
this.entities.stop_tracking(player);
this.mods.after.player_leave.emit({ player: this.mods.player(player) });
this.#broadcast({ type: "player_leave", id: player.id });
this.#broadcast({ type: "chat", text: `${player.name} left` });
console.log(`${player.name} left (${this.#players.size} online)`);
}
on_message(conn: number, data: string) {
let message: ClientMessage;
try {
message = JSON.parse(data);
} catch {
return;
}
if (typeof message !== "object" || message === null) {
return;
}
const player = this.#players.get(conn);
if (!player) {
this.#handshake(conn, message);
return;
}
this.#handle(player, message);
this.#sync(player);
}
// game loop, the host calls this TICKS_PER_SECOND times a second
tick() {
this.#tick += 1;
this.world.time += 1;
const second = this.#tick % TICKS_PER_SECOND === 0;
if (second) {
this.#broadcast({ type: "time", time: this.world.time });
}
this.#run_scheduled_ticks();
// the tiles near players that tick, picked before any runs so one that a handler adds waits for the next tick
const ticking: Tile[] = [];
if (this.world.has_ticking_tiles) {
for (const [chunk_x, chunk_z] of this.#chunks_near_players().values()) {
for (const tile of this.world.ticking_tiles(chunk_x, chunk_z)) ticking.push(tile);
}
}
for (const tile of ticking) {
// a handler that ran before it broke it or turned its ticking off
if (!this.world.ticks(tile)) {
continue;
}
const block = this.mods.block_ref(tile.x, tile.y, tile.z, tile.id);
for (const { mod, id, component, params } of this.mods.ticking_components_of(tile.id)) {
if (component.on_tick) {
run_guarded(mod, `${id} on_tick`, () => component.on_tick!(block, params, TICK_DELTA));
}
if (second && component.on_second) {
run_guarded(mod, `${id} on_second`, () => component.on_second!(block, params, 1));
}
}
// tile data can change on any tick, saving is cheap enough to not track it exactly
this.world.dirty = true;
}
this.#new_days();
this.fluids.tick(this.#tick);
this.#tick_vitals();
for (const player of this.#players.values()) this.#tick_using(player);
this.#tick_entities();
this.mods.tick();
this.#tick_menus();
this.mods.check_watched_containers();
for (const [conn, pending] of this.#pending) {
if (this.#tick - pending.since > READY_TIMEOUT_TICKS) {
this.#pending.delete(conn);
this.#reject(conn, "Took too long to load the server's mods");
}
}
this.entities.sync();
for (const player of this.#players.values()) {
this.#sync_worn(player);
this.#sync(player);
}
this.#request_chunks();
this.#send_chunks();
if (second) {
this.#fallback_history.push(this.world.fallbacks);
if (this.#fallback_history.length > 60) this.#fallback_history.shift();
}
}
// runs the block's components' on_scheduled_tick in delay ticks, see ServerWorld.schedule_tick
schedule_tick(x: number, y: number, z: number, delay: number, priority: number) {
const nid = this.world.get_block_nid(x, y, z);
if (nid === AIR) return;
this.#scheduled.add(x, y, z, nid, this.#tick + delay, priority);
this.world.dirty = true;
}
has_scheduled_tick(x: number, y: number, z: number) {
return this.#scheduled.has(x, y, z, this.world.get_block_nid(x, y, z));
}
// the scheduled ticks due near players, all taken before any runs, so one a handler schedules waits for its tick
#run_scheduled_ticks() {
const due = this.#scheduled.take_due(
this.#tick,
(chunk_x, chunk_z) => this.#near_any_player(chunk_x * CHUNK_SIZE, chunk_z * CHUNK_SIZE),
);
for (const { x, y, z, nid } of due) {
// another kind of block took its place
if (this.world.get_block_nid(x, y, z) !== nid) continue;
const id = this.world.get_block_id(x, y, z);
const components = this.mods.components_with(id, "on_scheduled_tick");
if (components.length === 0) continue;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_scheduled_tick`,
() => component.on_scheduled_tick!(block, params),
);
}
}
if (due.length > 0) this.world.dirty = true;
}
// level.json and the chunks generated or changed since the last save
save(): Required<WorldSave> {
for (const player of this.#players.values()) {
this.#saved_players[player.name] = player.save_player();
}
const level: SavedLevel = {
version: 5,
seed: this.world.seed,
time: this.world.time,
tiles: [...this.world.tiles.values()].map((tile) => ({ ...tile })),
scheduled_ticks: this.#scheduled.all().map((tick) => [
tick.x,
tick.y,
tick.z,
EverythingRegistry.get_by_id<BlockRegistry>("blocks", tick.nid)!.id,
tick.due - this.#tick,
tick.priority,
]),
containers: Object.fromEntries(
[...this.containers].map(([id, container]) => [id, container.to_data()]),
),
players: this.#saved_players,
entities: this.entities.save(),
mod_storage: this.mods.storage,
};
this.world.dirty = false;
return { level: JSON.stringify(level), chunks: this.world.save_chunks() };
}
// used by block behaviors and mods
get current_tick() {
return this.#tick;
}
// the furthest the server sends chunks to anyone, for now. players who asked for more get more, up to it
set_view_distance(distance: number) {
this.view_distance = distance;
for (const player of this.players()) {
player.chunks.view_distance = view_distance(player.requested_view_distance, distance);
this.#update_view(player, true);
}
}
players(): ServerPlayer[] {
return [...this.#players.values()];
}
give(player: ServerPlayer, id: string, count: number, data?: unknown) {
// split into stacks so max stack sizes are respected
let left = count;
while (left > 0) {
const stack = new ItemStack(id);
// first, a full fluid container stacks to fewer
if (data !== undefined) stack.data = structuredClone(data);
stack.amount = Math.min(left, stack.max_amount);
left -= stack.amount;
this.give_stack(player, stack);
}
}
// into the inventory, whatever doesn't fit drops at the player's feet
give_stack(player: ServerPlayer, stack: ItemStack) {
if (player.inventory.add_item(stack) > 0) {
this.spawn_item(player.x, player.y, player.z, stack, PLAYER_DROP_PICKUP_DELAY);
}
}
spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity {
const entity = this.entities.spawn_item(x, y, z, stack, pickup_delay);
this.world.dirty = true;
return entity;
}
// like minecraft's Block.popResource: from a bit off the block's middle, flying up and out a little
pop_item(x: number, y: number, z: number, stack: ItemStack) {
const spread = () => (Math.random() - 0.5) * 0.5;
const entity = this.spawn_item(
x + 0.5 + spread(),
y + 0.5 - ITEM_SIZE / 2 + spread(),
z + 0.5 + spread(),
stack,
BLOCK_DROP_PICKUP_DELAY,
);
entity.vx = (Math.random() - 0.5) * 4;
entity.vy = 4;
entity.vz = (Math.random() - 0.5) * 4;
return entity;
}
// out of the player's face the way they're looking, like minecraft's Player.drop
throw_item(player: ServerPlayer, stack: ItemStack) {
const entity = this.spawn_item(
player.x,
player.y + player.eye_height - 0.3,
player.z,
stack,
PLAYER_DROP_PICKUP_DELAY,
);
// minecraft's numbers are per tick
const speed = 0.3 * TICKS_PER_SECOND;
const cos_pitch = Math.cos(player.pitch);
const spread_angle = Math.random() * Math.PI * 2;
const spread = Math.random() * 0.02 * TICKS_PER_SECOND;
entity.vx = -Math.sin(player.yaw) * cos_pitch * speed + Math.cos(spread_angle) * spread;
entity.vy = Math.sin(player.pitch) * speed + (0.1 + (Math.random() - Math.random()) * 0.1) * TICKS_PER_SECOND;
entity.vz = -Math.cos(player.yaw) * cos_pitch * speed + Math.sin(spread_angle) * spread;
return entity;
}
item_entities(): ItemEntity[] {
return this.entities.all().filter((entity) => entity instanceof ItemEntity);
}
// in chat, or above their hotbar for a moment with overlay, see MessageOptions
send_chat(player: ServerPlayer, text: string, overlay = false) {
this.#send(player, overlay ? { type: "chat", text, overlay } : { type: "chat", text });
}
// a mod's server phase to its client phase, see ctx.net
send_mod_message(player: ServerPlayer, channel: string, data: unknown) {
this.#send(player, { type: "mod", channel, data });
}
teleport(player: ServerPlayer, x: number, y: number, z: number) {
Object.assign(player, { x, y, z });
player.fall_distance = 0;
player.stop_knockback();
this.#place(player);
}
// tells their client where they are now (and how fast they're going, while the server moves them), and everyone
// else where they are
#place(player: ServerPlayer, motion?: [number, number, number]) {
const { x, y, z } = player;
player.teleport_id += 1;
this.#send(player, { type: "teleport", id: player.teleport_id, x, y, z, ...(motion && { motion }) });
this.#update_view(player);
this.#broadcast(player_move(player), player);
}
set_time(time: number) {
this.world.time = time;
this.world.dirty = true;
this.#broadcast({ type: "time", time });
// going back in time doesn't repeat mornings, going forward runs the ones skipped (see #new_days)
this.#day = Math.min(this.#day, this.world.day);
}
// every morning that came since the last tick, usually none or one. /time can skip many
#new_days() {
const today = this.world.day;
if (today <= this.#day) {
return;
}
const first = Math.max(this.#day + 1, today - MAX_CATCH_UP_DAYS + 1);
for (let day = first; day <= today; day++) {
this.#new_day(day);
}
this.#day = today;
}
// every block with data runs on_new_day, wherever it is, so crops grow while nobody's around. blocks without data,
// like ones world generation made, run it near players, like the blocks minecraft random ticks
#new_day(day: number) {
const run = (x: number, y: number, z: number, block_id: string) => {
const components = this.mods.components_of(block_id).filter(({ component }) => component.on_new_day);
if (components.length === 0) {
return;
}
const block = this.mods.block_ref(x, y, z, block_id);
for (const { mod, id, component, params } of components) {
run_guarded(mod, `${id} on_new_day`, () => component.on_new_day!(block, params, day));
}
};
// found before any runs, so a block one of them places, like a cactus growing, waits for tomorrow
const without_data = this.#blocks_without_data_near_players();
for (const tile of [...this.world.tiles.values()]) {
if (tile.mod_data !== undefined) {
run(tile.x, tile.y, tile.z, tile.id);
}
}
for (const [x, y, z, block_id] of without_data) {
// unless an earlier one changed it, or gave it data and it ran above
if (this.world.get_block_id(x, y, z) === block_id && this.world.get_tile(x, y, z)?.mod_data === undefined) {
run(x, y, z, block_id);
}
}
this.mods.after.new_day.emit({ day });
this.world.dirty = true;
}
// changes a block's state bits without replacing it, see ServerWorld.get_block_value: its on_state_change, then the
// blocks beside it hear of it, unless update_neighbors is false
set_block_state(x: number, y: number, z: number, state: number, update_neighbors = true) {
const id = this.world.get_block_id(x, y, z);
const value = this.world.get_block_value(x, y, z);
if (id === AIR_ID || value >>> 16 === state) return;
this.mods.rules.change(() => {
const components = this.mods.components_with(id, "on_state_change");
// only worked out for blocks that want it, states change often
const before = components.length > 0 ? block_states(value, this.world.get_block_info(x, y, z)!) : undefined;
this.world.set_block(x, y, z, id, state);
if (before) {
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_state_change`,
() => component.on_state_change!(block, params, before),
);
}
}
if (update_neighbors) this.mods.rules.notify_neighbors(x, y, z);
});
}
// replaces a block: the old one's on_break, then the new one's on_create, then the blocks beside it hear of it
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
this.mods.rules.change(() => {
this.#replace_block(x, y, z, id, state, player);
this.#create_block(x, y, z, id);
this.mods.rules.notify_neighbors(x, y, z);
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was
// dug
if (this.world.shape.contains(y + 1)) {
const above = this.world.get_block_info(x, y + 1, z);
if (above && !can_stand_on(above, id)) {
this.destroy_block(x, y + 1, z, player);
}
}
});
}
// the old block's on_break, then the new one without a tile. nothing else hears of it yet
#replace_block(x: number, y: number, z: number, id: string, state?: number, player?: ServerPlayer) {
const old_id = this.world.get_block_id(x, y, z);
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
if (old_id !== AIR_ID) {
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
if (components.length > 0) {
const block = this.mods.block_ref(x, y, z, old_id);
const player_api = player && this.mods.player(player);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(mod, `${component_id} on_break`, () => component.on_break!(block, params, player_api));
}
}
}
this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state);
}
// its components' on_create
#create_block(x: number, y: number, z: number, id: string) {
if (id === AIR_ID) return;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
}
}
}
// the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress
#break_stages = new Map<string, number>();
// cracks on the block at x y z, 0 to 1 of the way to broken, for every player who has its chunk. undefined takes them
// off. only a change of stage is sent, so a drill can set it every tick
set_break_progress(x: number, y: number, z: number, progress: number | undefined) {
const key = `${x} ${y} ${z}`;
const stage = progress === undefined
? undefined
: Math.round(Math.max(0, Math.min(1, progress)) * BREAK_STAGES);
if (this.#break_stages.get(key) === stage) return;
if (stage === undefined) this.#break_stages.delete(key);
else this.#break_stages.set(key, stage);
const message: ServerMessage = { type: "break_progress", x, y, z, ...(stage !== undefined && { stage }) };
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) this.#send(player, message);
}
}
// a script pushing a player, see Player.push. their client moves them, so it's added there, unless the server is
// moving them while they're knocked back
push_player(player: ServerPlayer, x: number, y: number, z: number) {
if (player.knockback_ticks === undefined) {
this.#send(player, { type: "push", motion: [x, y, z] });
return;
}
player.vx += x;
player.vy += y;
player.vz += z;
}
// the player machines use items as, made the first time. it's never online or in the world
#machine_player: ServerPlayer | undefined;
// uses stack on face of the block at x y z like a player holding it would, see ServerWorld.use_item_on: as a player
// standing in the middle of the block in front of that face, looking at it. what it holds after, and anything else
// it was given
use_item_on(stack: ItemStack, x: number, y: number, z: number, face: Faces) {
const player = this.#machine_player ??= new ServerPlayer(this.entities, MACHINE_CONN, "[machine]", 0);
const { x: dx, y: dy, z: dz } = FACE_OFFSETS[face];
player.set_position(x + 0.5 + dx, y + 0.5 + dy - player.eye_height, z + 0.5 + dz);
// facing back the other way, see horizontal_facing
player.yaw = dx || dz ? Math.atan2(dx, dz) : 0;
player.pitch = -dy * Math.PI / 2;
player.sneaking = false;
player.using = undefined;
player.selected_slot = 0;
player.inventory.clear();
player.inventory.set_item(0, stack);
this.#use_block(player, x, y, z, face, [0.5 + dx / 2, 0.5 + dy / 2, 0.5 + dz / 2]);
const items = Array.from({ length: player.inventory.size }, (_, slot) => player.inventory.get_item(slot));
player.inventory.clear();
return { held: items[0], given: items.slice(1).filter((item) => item !== undefined) };
}
// what a loot table gives, ready to drop. a table that can't be rolled is logged and gives nothing, so a broken
// table never stops a block breaking or a mob dying
roll_loot(table: string, context: LootContext): ItemStack[] {
try {
return this.mods.loot.roll(table, context).map(new_stack);
} catch (e) {
console.error(`Couldn't roll loot table ${table}:`, e);
return [];
}
}
// breaks a block the way breaking it by hand does: its components' on_break, then what it drops, which it returns.
// without the right tool of a high enough tier (or without a player) blocks that need one drop nothing, unless a
// machine breaks it as if it had one (harvest). collect returns the drops without dropping them
destroy_block(
x: number,
y: number,
z: number,
player?: ServerPlayer,
how: { harvest?: boolean; collect?: boolean } = {},
): ItemStack[] | undefined {
const info = this.world.get_block_info(x, y, z);
if (!info) {
return undefined;
}
const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? "");
const tool = held?.tool;
const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0);
const drops = how.harvest || !info.requires_tool || right_tool;
const value = this.world.get_block_value(x, y, z);
// rolled while it's still there, for its states
const loot = drops && info.loot_table
? this.roll_loot(info.loot_table, {
position: { x: x + 0.5, y: y + 0.5, z: z + 0.5 },
block: { id: info.id, x, y, z, states: block_states(value, info) },
player: player && this.mods.player(player),
tool: player && this.mods.player(player).held_item,
})
: drops && info.drop_table
? [new ItemStack(info.drop_table)]
: [];
// a waterlogged block leaves its fluid behind, a source
const fluid = is_waterlogged(value, info) ? fluid_block(value, info) : undefined;
this.set_block(x, y, z, fluid?.id ?? AIR_ID, player);
if (!how.collect) { for (const stack of loot) this.pop_item(x, y, z, stack); }
return loot;
}
get_or_create_tile(x: number, y: number, z: number): Tile {
let tile = this.world.get_tile(x, y, z);
if (!tile) {
tile = { id: this.world.get_block_id(x, y, z), x, y, z };
this.world.add_tile(tile);
}
return tile;
}
// BlockRef.data's setter
set_tile_data(x: number, y: number, z: number, data: unknown) {
const tile = this.get_or_create_tile(x, y, z);
tile.mod_data = data;
this.#update_ticking(tile);
this.world.dirty = true;
}
// BlockRef.set_client_data. a block without a tile only gets one when a field is set, not removed
set_tile_client_data(x: number, y: number, z: number, field: string, value: unknown) {
if (this.world.get_block_id(x, y, z) === AIR_ID) {
return;
}
const tile = value === undefined ? this.world.get_tile(x, y, z) : this.get_or_create_tile(x, y, z);
if (tile) this.world.set_tile_client_data(tile, field, value);
}
// a component turning ticking off for one block, or back on, see BlockRef.set_ticking. it stays off when saved
set_tile_ticking(x: number, y: number, z: number, ticking: boolean) {
if (this.world.get_block_id(x, y, z) === AIR_ID) {
return;
}
// ticking is on unless a tile says it's off
const tile = ticking ? this.world.get_tile(x, y, z) : this.get_or_create_tile(x, y, z);
if (!tile) {
return;
}
if (ticking) delete tile.ticking;
else tile.ticking = false;
this.#update_ticking(tile);
this.world.dirty = true;
}
// which of the tiles loaded with the world tick, which needs every mod's components registered first
find_ticking_tiles() {
for (const tile of this.world.tiles.values()) this.#update_ticking(tile);
}
// a tile ticks while it has data, its block has components with on_tick or on_second, and they haven't turned it off
#update_ticking(tile: Tile) {
const ticks = tile.mod_data !== undefined && tile.ticking !== false &&
this.mods.ticking_components_of(tile.id).length > 0;
this.world.set_ticks(tile, ticks);
}
// containers
create_container(size: number): { id: string; container: Container } {
const id = crypto.randomUUID();
const container = new Container(size);
this.containers.set(id, container);
this.world.dirty = true;
return { id, container };
}
// anyone with a menu showing it gets it closed
delete_container(id: string) {
const container = this.containers.get(id);
if (!container) {
return;
}
this.containers.delete(id);
this.world.dirty = true;
for (const player of this.#players.values()) {
if (player.menu?.uses(container)) {
this.close_menu(player);
}
}
}
// /fill: every block between two corners, both included, replaced with id. like a schematic, they all change before
// any of them hears of it. throws for a box that's too big, and says how many blocks it changed
fill(from: Position, to: Position, id: string): number {
const [x0, x1] = [Math.min(from.x, to.x), Math.max(from.x, to.x)];
const [y0, y1] = [Math.min(from.y, to.y), Math.max(from.y, to.y)];
const [z0, z1] = [Math.min(from.z, to.z), Math.max(from.z, to.z)];
const volume = (x1 - x0 + 1) * (y1 - y0 + 1) * (z1 - z0 + 1);
if (volume > MAX_FILL_VOLUME) {
throw new Error(`fill changes up to ${MAX_FILL_VOLUME} blocks, and that box has ${volume}`);
}
const placed: Position[] = [];
for (let y = y0; y <= y1; y++) {
if (!this.world.shape.contains(y)) continue;
for (let z = z0; z <= z1; z++) {
for (let x = x0; x <= x1; x++) placed.push({ x, y, z });
}
}
this.mods.rules.change(() => {
for (const { x, y, z } of placed) this.#replace_block(x, y, z, id);
for (const { x, y, z } of placed) this.#create_block(x, y, z, id);
});
for (const { x, y, z } of placed) this.mods.rules.notify_neighbors(x, y, z);
return placed.length;
}
// 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)));
}
// see ctx.schematics.place. the blocks all change before any of them hears of it, so a door's halves or a torch's
// wall are both there by then
place_schematic(id: string, placement: SchematicPlacement) {
const registered = this.schematics.get(id);
if (!registered) throw new Error(`there's no schematic ${id}`);
const { blocks, entities } = placed_schematic(registered, placement);
const placed = blocks.filter(({ y }) => this.world.shape.contains(y));
this.mods.rules.change(() => {
for (const { x, y, z, id, state } of placed) this.#replace_block(x, y, z, id, state);
for (const { x, y, z, id, block } of placed) {
if (id === AIR_ID) continue;
// TODO: import_data, so blocks can make what their data points to, like a chest's container
if (block.data !== undefined) this.set_tile_data(x, y, z, structuredClone(block.data));
for (const [field, value] of Object.entries(block.client_data ?? {})) {
this.set_tile_client_data(x, y, z, field, structuredClone(value));
}
if (block.data === undefined && block.client_data === undefined) this.#create_block(x, y, z, id);
}
});
// each on its own, a big schematic tells more blocks than one change can
for (const { x, y, z } of placed) this.mods.rules.notify_neighbors(x, y, z);
const seat = (vehicle: Entity) => {
for (const passenger of vehicle.passengers) {
vehicle.position_passenger(passenger);
seat(passenger);
}
};
for (const saved of entities) {
const entity = load_entity(this.entities, saved);
if (!entity) continue;
seat(entity);
this.entities.add_entity(entity);
}
}
// menus
// the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter
next_menu_id(player: ServerPlayer): number {
player.menu_id = player.menu_id % 100 + 1;
return player.menu_id;
}
// replaces whatever they had open
open_menu(player: ServerPlayer, menu: Menu) {
this.#close_menu(player);
player.menu = menu;
const data = menu.data_values();
this.#send(player, {
type: "open_menu",
id: menu.id,
menu_type: menu.type,
title: menu.title,
open_data: menu.open_data,
slots: menu.slot_info(),
fluid_slots: menu.fluid_slot_info(),
data,
});
player.sent.set("menu_data", JSON.stringify(data));
player.sent.delete("menu_content");
player.sent.delete("menu_tanks");
}
// closes it for the player too, not just on the server
close_menu(player: ServerPlayer) {
const menu = player.menu;
if (!menu) {
return;
}
this.#close_menu(player);
this.#send(player, { type: "close_menu", id: menu.id });
}
// version 2 saves had chests and furnaces in the engine, with their fields in data and their items in
// containers.main. the components keep those fields and put the items in a ctx.containers container
// messages
// hello -> welcome, then ready -> join. see docs/modding/networking/index.md
#handshake(conn: number, message: ClientMessage) {
if (message.type === "hello") {
if (this.#pending.has(conn)) {
return;
}
if (message.protocol !== PROTOCOL_VERSION) {
this.#reject(
conn,
`This server needs a game version with protocol ${PROTOCOL_VERSION}, yours has ${
message.protocol ?? "none"
}. Reload the page to update.`,
);
return;
}
this.#pending.set(conn, { name: message.name, since: this.#tick });
this.#host.send(
conn,
JSON.stringify(
{
type: "welcome",
protocol: PROTOCOL_VERSION,
mods: this.#mods.listings,
} satisfies ServerMessage,
),
);
return;
}
if (message.type === "ready") {
const pending = this.#pending.get(conn);
if (!pending) {
return;
}
this.#pending.delete(conn);
this.#join(conn, pending.name, message.view_distance);
}
}
#reject(conn: number, reason: string) {
this.#host.send(conn, JSON.stringify({ type: "rejected", reason } satisfies ServerMessage));
this.#host.close(conn);
}
#join(conn: number, raw_name: unknown, requested_view_distance: unknown) {
const player = new ServerPlayer(
this.entities,
conn,
this.#unique_name(raw_name),
view_distance(requested_view_distance, this.view_distance),
() => this.recipes.shaped,
);
if (is_int(requested_view_distance)) player.requested_view_distance = requested_view_distance;
const saved = this.#saved_players[player.name];
if (saved) {
player.load_player(saved);
} else {
Object.assign(player, this.world.spawn_point());
}
this.mods.extend_player_menu(player);
this.#send(player, {
type: "join",
id: player.id,
name: player.name,
players: [...this.#players.values()].map((p) => p.player_info()),
entities: this.entities.start_tracking(player),
blocks: this.world.block_table(),
shape: this.world.shape,
spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch },
selected_slot: player.selected_slot,
player_menu: player.inventory_menu.extra.map(({ x, y, icon }) => ({ x, y, ...(icon ? { icon } : {}) })),
time: this.world.time,
});
this.#players.set(conn, player);
// what they wear themselves, the others get it with player_join
player.worn_sent = JSON.stringify(player.worn_list());
if (player.worn_sent !== "[]") {
this.#send(player, { type: "player_worn", id: player.id, worn: player.worn_list() });
}
// and their own skin, from when they last played
if (player.skin) {
this.#send(player, {
type: "player_skin",
id: player.id,
skin: player.skin,
slim: player.slim || undefined,
});
}
// the chunks come with the next ticks
this.#update_view(player);
this.#sync(player);
this.#broadcast({ type: "player_join", player: player.player_info() }, player);
this.#broadcast({ type: "chat", text: `${player.name} joined` });
this.mods.after.player_join.emit({ player: this.mods.player(player) });
console.log(`${player.name} joined (${this.#players.size} online)`);
}
#handle(player: ServerPlayer, message: ClientMessage) {
switch (message.type) {
case "move": {
const { x, y, z, yaw, pitch } = message;
if (![x, y, z, yaw, pitch].every(is_number)) {
return;
}
// the server is moving them, or it's from before the last time it did
const stale = is_number(message.teleport) && message.teleport < player.teleport_id;
if (player.knockback_ticks !== undefined || stale) {
return;
}
this.#on_move(player, x, y, z);
Object.assign(player, { x, y, z, yaw, pitch });
player.set_swimming(message.swimming === true);
player.sneaking = message.sneaking === true;
this.#broadcast(player_move(player), player);
this.#update_view(player);
this.#inside_blocks(player);
break;
}
case "view_distance":
if (is_int(message.distance)) {
player.requested_view_distance = message.distance;
player.chunks.view_distance = view_distance(message.distance, this.view_distance);
this.#update_view(player, true);
}
break;
case "chunk_batch_received":
if (is_number(message.chunks_per_tick)) {
player.chunks.on_batch_received(message.chunks_per_tick);
}
break;
case "break_block":
if (is_block_position(this.world.shape, message.x, message.y, message.z)) {
this.#break_block(player, message.x, message.y, message.z);
}
this.#ack(player, message.seq);
break;
case "hit_block":
if (is_block_position(this.world.shape, message.x, message.y, message.z)) {
this.#hit_block(player, message.x, message.y, message.z);
}
break;
case "attack_entity":
if (typeof message.id === "string") {
this.#attack_entity(player, message.id);
}
break;
case "swing":
player.attack_strength_ticker = 0;
break;
case "use_item":
// a client that hadn't heard it's using an item yet, still clicking
if (!player.using) this.#use_item(player);
break;
case "release_use":
this.#release_using(player);
break;
case "use_block":
if (
is_block_position(this.world.shape, message.x, message.y, message.z) && faces.includes(message.face)
) {
if (player.using) {
// a client that hadn't heard it's using an item yet: what it guessed the click did, it didn't
this.#correct_use(player, message.x, message.y, message.z, message.face);
} else {
this.#use_block(
player,
message.x,
message.y,
message.z,
message.face,
hit_on_block(message.hit),
);
}
}
this.#ack(player, message.seq);
break;
case "scroll_block":
if (
is_block_position(this.world.shape, message.x, message.y, message.z) &&
faces.includes(message.face) &&
is_int(message.amount) && message.amount !== 0
) {
const { x, y, z, face, amount } = message;
this.#scroll_block(player, x, y, z, face, hit_on_block(message.hit), amount);
}
break;
case "select_slot":
if (is_int(message.slot) && message.slot >= 0 && message.slot < 9) {
if (message.slot !== player.selected_slot) player.attack_strength_ticker = 0;
player.selected_slot = message.slot;
}
break;
case "click":
this.#click(player, message.menu, message.slot, message.button, message.shift === true);
break;
case "click_fluid": {
const menu = player.menu;
const slot = menu && message.menu === menu.id && is_int(message.slot)
? menu.fluid_slots[message.slot]
: undefined;
if (slot) {
slot.click();
this.world.dirty = true;
}
break;
}
case "drop_item":
this.#drop_item(player, message.menu, message.slot, message.all === true);
break;
case "menu_button":
if (player.menu && message.menu === player.menu.id && is_int(message.button)) {
this.mods.menu_button(player, player.menu, message.button);
}
break;
case "close_menu":
// one that's already gone, the server closed it, or menu 0: the inventory screen
if (message.menu === (player.menu?.id ?? 0)) {
this.#close_menu(player);
}
break;
case "chat":
this.#chat(player, message.text);
break;
case "suggest":
this.#suggest(player, message.id, message.text);
break;
case "mod":
if (typeof message.channel === "string") {
this.mods.receive(player, message.channel, message.data);
}
break;
}
}
#break_block(player: ServerPlayer, x: number, y: number, z: number) {
const info = this.world.get_block_info(x, y, z);
// air, or something like water that can't be broken outside creative
if (!info || (info.toughness === undefined && !player.creative) || !this.#in_reach(player, x, y, z)) {
this.#correct(player, x, y, z);
return;
}
const event = {
player: this.mods.player(player),
block: this.mods.block_ref(x, y, z, info.id),
item: this.mods.player(player).held_item,
};
const before = { ...event, cancel: false };
this.mods.before.block_break.emit(before);
if (before.cancel) {
this.#correct(player, x, y, z);
return;
}
// creative breaks drop nothing, since placing doesn't use anything up
this.destroy_block(x, y, z, player, { collect: player.creative });
player.vitals.add_exhaustion(EXHAUSTION.break_block);
this.mods.after.block_break.emit(event);
}
#hit_block(player: ServerPlayer, x: number, y: number, z: number) {
const info = this.world.get_block_info(x, y, z);
if (!info || !this.#in_reach(player, x, y, z)) {
return;
}
const components = this.mods.components_of(info.id).filter(({ component }) => component.on_click);
if (components.length === 0) {
return;
}
const block = this.mods.block_ref(x, y, z, info.id);
const player_api = this.mods.player(player);
for (const { mod, id, component, params } of components) {
run_guarded(mod, `${id} on_click`, () => component.on_click!(block, params, player_api));
}
}
// left click on an entity or another player: hurts them with the player's attack_damage and pushes them away.
// they can't be hurt again for a moment, see LivingEntity.hurt
#attack_entity(player: ServerPlayer, id: string) {
// like minecraft, any swing starts the cooldown over, hit or not. their client does the same for its indicator
const strength = player.attack_strength();
player.attack_strength_ticker = 0;
const entity = this.entities.get_entity(id) ?? this.players().find((other) => other.id === id);
if (
!(entity instanceof LivingEntity) || entity === player || !entity.alive || !player.alive ||
!this.#entity_in_reach(player, entity)
) {
return;
}
const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const;
// like minecraft, attacking again before the attack speed allows hits weaker
const damage = player.attribute(ATTRIBUTES.attack_damage) * (0.2 + strength * strength * 0.8);
if (entity.hurt(damage, source)) {
player.vitals.add_exhaustion(EXHAUSTION.attack);
}
}
// right click at nothing: eating, or the item's on_use
#use_item(player: ServerPlayer): boolean {
return this.#eat(player) || this.#use_item_components(player, undefined);
}
// the held item's on_use handlers, with the block it was used on if it was, returns whether it has any
#use_item_components(player: ServerPlayer, target: UseTarget | undefined): boolean {
const held = player.held_item;
if (!held) {
return false;
}
const components = this.mods.item_components_of(held.type_id).filter(({ component }) => component.on_use);
if (components.length === 0) {
return false;
}
const player_api = this.mods.player(player);
const item = player_api.held_item!;
for (const { mod, id, component, params } of components) {
run_guarded(mod, `${id} on_use`, () => component.on_use!(item, params, player_api, target));
}
return true;
}
// a script's start_using: the held item is used over time from now, while they hold use
start_using(player: ServerPlayer, duration: number) {
const held = player.held_item;
if (!held) throw new Error("start_using needs an item in their hand");
player.using = { slot: player.selected_slot, type_id: held.type_id, ticks: 0, duration };
}
// the held item's on_use_tick handlers every tick it's used, and on_finish_using once it's used for its duration.
// switching away from it, or it being used up, dropped or swapped, stops it without either, like minecraft
#tick_using(player: ServerPlayer) {
const using = player.using;
if (!using) return;
if (!player.alive || player.selected_slot !== using.slot || player.held_item?.type_id !== using.type_id) {
player.using = undefined;
return;
}
using.ticks += 1;
this.#run_using(player, "on_use_tick", using.ticks);
// a handler can stop it, or start it over
if (player.using === using && using.duration !== -1 && using.ticks >= using.duration) {
player.using = undefined;
this.#run_using(player, "on_finish_using");
}
}
// they let go of use: on_release_using with how long they used it, when they were using something
#release_using(player: ServerPlayer) {
const using = player.using;
if (!using) return;
player.using = undefined;
if (player.selected_slot === using.slot && player.held_item?.type_id === using.type_id) {
this.#run_using(player, "on_release_using", using.ticks);
}
}
#run_using(player: ServerPlayer, handler: "on_use_tick" | "on_release_using" | "on_finish_using", ticks = 0) {
const player_api = this.mods.player(player);
const item = player_api.held_item;
if (!item) return;
for (const { mod, id, component, params } of this.mods.item_components_of(item.id)) {
const run = component[handler];
if (run) run_guarded(mod, `${id} ${handler}`, () => run(item, params, player_api, ticks));
}
}
// what a client may have guessed clicking face of the block at x y z did, to the block and to where a block would
// be placed, put back to what's really there
#correct_use(player: ServerPlayer, x: number, y: number, z: number, face: Faces) {
const target = placement_target(x, y, z, FACE_OFFSETS[face], this.world.get_block_info(x, y, z));
this.#correct(player, x, y, z);
this.#correct(player, target.x, target.y, target.z);
}
// the mouse wheel turned at a scrollable block in reach: its components' on_scroll
#scroll_block(
player: ServerPlayer,
x: number,
y: number,
z: number,
face: Faces,
hit: [number, number, number],
amount: number,
) {
const info = this.world.get_block_info(x, y, z);
if (!info?.scrollable || !this.#in_reach(player, x, y, z)) return;
const block = this.mods.block_ref(x, y, z, info.id);
const player_api = this.mods.player(player);
const scroll = { amount, face, hit };
for (const { mod, id, component, params } of this.mods.components_with(info.id, "on_scroll")) {
run_guarded(mod, `${id} on_scroll`, () => component.on_scroll!(block, params, player_api, scroll));
}
}
#use_block(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) {
const info = this.world.get_block_info(x, y, z);
const target = placement_target(x, y, z, FACE_OFFSETS[face], info);
const [tx, ty, tz] = [target.x, target.y, target.z];
if (!info || !this.#in_reach(player, x, y, z)) {
this.#correct_use(player, x, y, z, face);
return;
}
const player_api = this.mods.player(player);
const value = this.world.get_block_value(x, y, z);
const held_slot = player.inventory.get_slot(player.selected_slot);
const held = EverythingRegistry.get<ItemRegistry>("items", held_slot.type_id ?? "");
// an item aimed at fluids, like a bucket, uses the fluid in a waterlogged block instead of the block
const used = (held?.targets_fluids && fluid_block(value, info)) || info;
const block = this.mods.block_ref(x, y, z, used.id);
const interact = { player: player_api, block, item: player_api.held_item };
const before_interact = { ...interact, cancel: false };
this.mods.before.block_interact.emit(before_interact);
if (before_interact.cancel) {
// the client may have guessed the shared rules' on_interact, or a placement
this.#correct_use(player, x, y, z, face);
return;
}
// the shared rules first, the ones the client guessed, then the server phase's. sneaking with an item skips the
// block, like minecraft's secondary use, so a block can be placed against a chest
const sneaking = player.sneaking;
let handled = false;
if (!(sneaking && held_slot.has_item())) {
const interaction = { face, hit: [hit[0], hit[1], hit[2]] as [number, number, number], sneaking };
handled = this.mods.rules.interact(used, x, y, z, interaction, player.yaw);
for (const { mod, id: component_id, component, params } of this.mods.components_of(used.id)) {
if (component.on_interact) {
handled = run_guarded(mod, `${component_id} on_interact`, () =>
component.on_interact!(block, params, player_api)) ===
true || handled;
}
}
}
if (handled) {
this.mods.after.block_interact.emit(interact);
// the client guessed the shared rules' on_interact from what it sees, which might not be what's here. it didn't
// guess a placement for interactive blocks, but it might have for others
this.#correct_use(player, x, y, z, face);
return;
}
// an item that does something when used does that instead of being placed
if (this.#use_item_components(player, { block, face, hit: [hit[0], hit[1], hit[2]] })) {
this.#correct(player, tx, ty, tz);
return;
}
// placing a fluid, like a water bucket, into a block that can hold it fills it, like minecraft's
if (held?.block_id && info.waterloggable === held.block_id && !is_waterlogged(value, info)) {
this.#waterlog(player, x, y, z, face, hit);
return;
}
// place the held block against the face, or into the clicked block if it's replaceable. food that can be planted,
// like a potato on farmland, is planted, and eaten when it can't be
const placeable = held?.block_id !== undefined && this.world.shape.contains(ty) &&
can_place(
EverythingRegistry.get<BlockRegistry>("blocks", held.block_id),
this.world.get_block_info(tx, ty, tz),
this.world.get_block_value(tx, ty, tz),
this.world.get_block_id(tx, ty - 1, tz),
);
if (!placeable || !held?.block_id) {
this.#eat(player);
this.#correct(player, tx, ty, tz);
return;
}
// solid blocks can't go where a mob or player is, the one placing it included, like minecraft
const placing = EverythingRegistry.get<BlockRegistry>("blocks", held.block_id)!;
const ruled_value = this.mods.rules.placement_value(placing, player.yaw, player.pitch, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
sneaking: player.sneaking,
item: held_slot.type_id!,
});
// its rules say it can't go there
if (ruled_value === undefined) {
this.#correct(player, tx, ty, tz);
return;
}
// put into a source of the fluid it can hold, it holds it
const placed_value = waterlog_placement(
ruled_value,
placing,
this.world.get_block_value(tx, ty, tz),
this.world.get_block_info(tx, ty, tz),
);
const state = placed_value >>> 16;
if (placing?.has_collision && this.#occupied(tx, ty, tz, collision_shape_at(placing, placed_value))) {
this.#correct(player, tx, ty, tz);
return;
}
const place = this.#place_event(player, { id: held.block_id, x: tx, y: ty, z: tz }, face, hit);
if (!place) return;
this.set_block(tx, ty, tz, held.block_id, player, state);
if (!player.creative) held_slot.amount = held_slot.amount! - 1;
this.mods.after.block_place.emit(place);
}
// the held fluid poured into the block at x y z, which can hold it. it's placing the fluid as far as mods can tell,
// so a bucket empties like it does placing water anywhere else
#waterlog(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) {
const held_slot = player.inventory.get_slot(player.selected_slot);
const place = this.#place_event(
player,
{ id: this.world.get_block_info(x, y, z)!.waterloggable!, x, y, z },
face,
hit,
);
if (!place) return;
const info = this.world.get_block_info(x, y, z)!;
this.set_block_state(
x,
y,
z,
set_state_value(this.world.get_block_value(x, y, z), info, "waterlogged", 1)! >>> 16,
);
if (!player.creative) held_slot.amount = held_slot.amount! - 1;
this.mods.after.block_place.emit(place);
}
// the event for a player placing a block, after mods had the chance to cancel it. undefined when one did, and the
// player is told what's really there
#place_event(
player: ServerPlayer,
block: { id: string; x: number; y: number; z: number },
face: Faces,
hit: number[],
) {
const player_api = this.mods.player(player);
const place = {
player: player_api,
block,
face,
hit: [hit[0], hit[1], hit[2]] as const,
item: player_api.held_item,
};
const before = { ...place, cancel: false };
this.mods.before.block_place.emit(before);
if (before.cancel) {
this.#correct(player, block.x, block.y, block.z);
return undefined;
}
return place;
}
// whether a mob's or player's collision box overlaps a block with that shape at x, y, z
#occupied(x: number, y: number, z: number, shape: Shape) {
return this.players().some((player) =>
box_overlaps_block(
{ x: player.x, y: player.y, z: player.z, width: PLAYER_WIDTH, height: player.height },
x,
y,
z,
shape,
)
) || this.entities.entities_near(x + 0.5, y, z + 0.5, 3).some((entity) =>
entity instanceof Mob && box_overlaps_block(entity, x, y, z, shape)
);
}
#drop_item(player: ServerPlayer, id: unknown, slot: unknown, all: boolean) {
const menu = player.container_menu;
if (id !== menu.id || !is_int(slot)) {
return;
}
const thrown = menu.drop(slot, all);
if (thrown) {
this.throw_item(player, thrown);
this.world.dirty = true;
}
}
// clicks for a menu that's already closed are ignored, like minecraft's
#click(player: ServerPlayer, id: unknown, slot: unknown, button: unknown, shift: boolean) {
const menu = player.container_menu;
if (id !== menu.id || !is_int(slot) || !is_int(button) || slot < 0 || slot >= menu.slots.length) {
return;
}
if (shift) {
menu.quick_move(slot);
} else {
menu.click(slot, button, player.cursor);
}
if (menu !== player.inventory_menu) {
this.world.dirty = true;
}
}
#chat(player: ServerPlayer, raw: unknown) {
if (typeof raw !== "string") {
return;
}
const text = raw.trim().slice(0, MAX_CHAT_LENGTH);
if (text.length === 0) {
return;
}
if (text.startsWith("/")) {
this.#command(player, text);
return;
}
const before = { player: this.mods.player(player), message: text, cancel: false };
this.mods.before.chat_send.emit(before);
const message = String(before.message).slice(0, MAX_CHAT_LENGTH);
if (before.cancel || message.length === 0) {
return;
}
console.log(`<${player.name}> ${message}`);
this.#broadcast({ type: "chat", from: player.name, text: message });
this.mods.after.chat_send.emit({ player: before.player, message });
}
// what typed commands run as
#command_source(player: ServerPlayer): ServerCommandSource {
const api = this.mods.player(player);
return { player: api, server_player: player, send_message: (text) => this.send_chat(player, text) };
}
#command(player: ServerPlayer, text: string) {
const input = text.slice(1);
try {
this.mods.commands.execute(input, this.#command_source(player));
} catch (e) {
if (e instanceof CommandError) {
this.send_chat(player, e.message);
return;
}
// a bug in whoever made the command, not something the player did
const name = input.split(" ")[0];
console.error(`[${this.mods.command_owners.get(name) ?? "?"}] /${name} threw:`, e);
this.send_chat(player, `Something went wrong running /${name}`);
}
}
// what could come next while they type a command, see common/commands.ts
#suggest(player: ServerPlayer, id: unknown, text: unknown) {
if (!is_int(id) || typeof text !== "string" || !text.startsWith("/") || text.length > MAX_CHAT_LENGTH) {
return;
}
const { start, suggestions } = this.mods.commands.suggest(text.slice(1), this.#command_source(player));
this.#send(player, {
type: "suggestions",
id,
start: start + 1,
suggestions: suggestions.slice(0, MAX_SUGGESTIONS),
});
}
// like minecraft's /locate biome: columns LOCATE_STEP apart, in square rings out from x, z, each from its ground
// down. the closest in the first ring that has one
#locate_biome(biome: string, x: number, z: number) {
for (let ring = 0; ring * LOCATE_STEP <= LOCATE_RADIUS; ring++) {
let best: { x: number; y: number; z: number; distance: number } | undefined;
for (let dx = -ring; dx <= ring; dx++) {
for (let dz = -ring; dz <= ring; dz++) {
if (Math.max(Math.abs(dx), Math.abs(dz)) !== ring) continue;
const [cx, cz] = [x + dx * LOCATE_STEP, z + dz * LOCATE_STEP];
const distance = Math.hypot(dx, dz);
if (best && distance >= best.distance) continue;
const y = this.world.locate_biome(biome, cx, cz);
if (y !== undefined) best = { x: cx, y, z: cz, distance };
}
}
if (best) return best;
}
return undefined;
}
// the engine's own commands, registered like mods' so they're in /help and suggested the same way
#register_commands() {
const register = (node: CommandNode<ServerCommandSource>) => this.mods.register_command("cubi", node);
// TODO: only let operators do this
// with data, any json, like { "damage": 10 } on a tool, or a fluid container full of a fluid with its data
const give = (context: CommandContext<ServerCommandSource>, count: number, data?: unknown) => {
const id = context.get<string>("item");
this.give(context.source.server_player, id, count, data);
const fluid = contained_fluid(id, data);
const of = fluid ? ` of ${this.mods.fluid_rules.name(fluid)}` : "";
context.source.send_message(`Gave ${count} ${display_name(id)}${of}`);
};
const give_full = (context: CommandContext<ServerCommandSource>, data?: unknown) => {
const id = context.get<string>("item");
if (!EverythingRegistry.get<ItemRegistry>("items", id)?.fluid_container) {
throw new CommandError(`${display_name(id)} doesn't hold fluids`);
}
const fluid = { id: context.get<string>("fluid"), ...(data === undefined ? {} : { data }) };
give(context, context.get<number>("count"), { fluid });
};
register(
literal<ServerCommandSource>("give").describe("Gives you an item").then(
argument<string, ServerCommandSource>("item", item())
.executes((context) => give(context, 1))
.then(
argument<number, ServerCommandSource>("count", integer(1, MAX_GIVE))
.executes((context) => give(context, context.get<number>("count")))
.then(
literal<ServerCommandSource>("fluid").then(
argument<string, ServerCommandSource>("fluid", fluid())
.executes((context) => give_full(context))
.then(
argument<unknown, ServerCommandSource>("fluid_data", json())
.executes((context) => give_full(context, context.get("fluid_data"))),
),
),
)
.then(
argument<unknown, ServerCommandSource>("data", json())
.executes((context) =>
give(context, context.get<number>("count"), context.get("data"))
),
),
),
),
);
const set_time = (context: CommandContext<ServerCommandSource>, time: number) => {
this.set_time(time);
this.#broadcast({
type: "chat",
text: `${context.source.server_player.name} set the time to ${format_clock(this.world.time)}`,
});
};
register(
literal<ServerCommandSource>("time")
.describe("Shows or changes the time of day")
.executes((context) =>
context.source.send_message(`${format_clock(this.world.time)} (tick ${this.world.time})`)
)
.then(
literal<ServerCommandSource>("set")
.then(
argument<string, ServerCommandSource>("time_of_day", choice(Object.keys(TIMES_OF_DAY)))
.executes((context) => {
// the next time it's that time of day, so days keep counting up
const now = this.world.time;
const target = now - time_of_day(now) +
TIMES_OF_DAY[context.get<string>("time_of_day")];
set_time(context, target >= now ? target : target + CYCLE_TICKS);
}),
)
.then(
argument<number, ServerCommandSource>("ticks", integer(0))
.executes((context) => set_time(context, context.get<number>("ticks"))),
),
)
.then(
literal<ServerCommandSource>("add").then(
argument<number, ServerCommandSource>("ticks", integer())
.executes((context) =>
set_time(context, Math.max(0, this.world.time + context.get<number>("ticks")))
),
),
),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("summon").describe("Spawns an entity where you are").then(
argument<string, ServerCommandSource>("entity", word())
.suggests((partial) =>
entity_type_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text }))
)
.executes((context) => {
const id = context.get<string>("entity");
const entity = entity_type_ids().includes(id) ? create_entity(this.entities, id) : undefined;
if (!entity) throw new CommandError(`There's no entity ${id}`);
const player = context.source.server_player;
entity.set_position(player.x, player.y, player.z);
entity.yaw = entity.head_yaw = player.yaw;
this.entities.add_entity(entity);
context.source.send_message(`Summoned ${id}`);
}),
),
);
// TODO: only let operators do this
const add_effect = (context: CommandContext<ServerCommandSource>, seconds: number) => {
const id = context.get<string>("effect");
const type = effect_type(id);
if (!type) throw new CommandError(`There's no effect ${id}`);
context.source.server_player.add_effect(new EffectInstance(type, seconds * TICKS_PER_SECOND));
context.source.send_message(`Gave ${display_name(id)} for ${seconds} seconds`);
};
register(
literal<ServerCommandSource>("effect").describe("Gives you a status effect").then(
argument<string, ServerCommandSource>("effect", word())
.suggests((partial) =>
effect_type_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text }))
)
.executes((context) => add_effect(context, 30))
.then(
argument<number, ServerCommandSource>("seconds", integer(1, 1_000_000))
.executes((context) => add_effect(context, context.get<number>("seconds"))),
),
),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("tp").describe("Teleports you to x y z").then(
argument<number, ServerCommandSource>("x", number()).then(
argument<number, ServerCommandSource>("y", number()).then(
argument<number, ServerCommandSource>("z", number()).executes((context) => {
const [x, y, z] = ["x", "y", "z"].map((axis) => context.get<number>(axis));
this.teleport(context.source.server_player, x, y, z);
context.source.send_message(`Teleported to ${x} ${y} ${z}`);
}),
),
),
),
);
// 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 or going on to next. each corner's
// three suggest the block the player is looking at: all of it at its x, what's left at y and z
const coordinates = (
names: string[],
next: CommandFunction<ServerCommandSource> | CommandNode<ServerCommandSource>,
index = 0,
): CommandNode<ServerCommandSource> => {
const [name, ...rest] = names;
const node = argument<number, ServerCommandSource>(name, integer());
node.suggests((partial, source) => {
const target = this.#targeted_block(source.server_player);
const text = target?.slice(index % 3).join(" ");
return text?.startsWith(partial) ? [{ text }] : [];
});
if (rest.length) return node.then(coordinates(rest, next, index + 1));
return next instanceof CommandNode ? node.then(next) : node.executes(next);
};
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))),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("placeschematic")
.describe("Places a schematic with its lowest corner at x y z")
.then(
argument<string, ServerCommandSource>("schematic", word())
.suggests((partial) =>
[...this.schematics.keys()].filter((id) => id.startsWith(partial)).map((text) => ({ text }))
)
.then(coordinates(["x", "y", "z"], (context) => {
const id = context.get<string>("schematic");
if (!this.schematics.has(id)) throw new CommandError(`There's no schematic ${id}`);
const [x, y, z] = ["x", "y", "z"].map((axis) => context.get<number>(axis));
try {
this.place_schematic(id, { position: { x, y, z } });
} catch (e) {
throw new CommandError(`Couldn't place it: ${(e as Error).message}`);
}
context.source.send_message(`Placed ${id} at ${x} ${y} ${z}`);
})),
),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("fill")
.describe("Fills the blocks between two corners with a block")
.then(coordinates(
["x1", "y1", "z1", "x2", "y2", "z2"],
argument<string, ServerCommandSource>("block", block_or_air()).executes((context) => {
const [from, to] = corners(context);
const id = context.get<string>("block");
let count: number;
try {
count = this.fill(from, to, id);
} catch (e) {
throw new CommandError(`Couldn't fill it: ${(e as Error).message}`);
}
context.source.send_message(`Filled ${count} blocks with ${display_name(id)}`);
}),
)),
);
register(
literal<ServerCommandSource>("locatebiome").describe("Finds the nearest biome of a kind").then(
argument<string, ServerCommandSource>("biome", word())
.suggests((partial) => biome_ids().filter((id) => id.startsWith(partial)).map((text) => ({ text })))
.executes((context) => {
const id = context.get<string>("biome");
if (!get_biome(id)) throw new CommandError(`There's no biome ${id}`);
const player = context.source.server_player;
const found = this.#locate_biome(id, Math.floor(player.x), Math.floor(player.z));
if (!found) {
throw new CommandError(`There's no ${display_name(id)} within ${LOCATE_RADIUS} blocks`);
}
const distance = Math.round(Math.hypot(found.x - player.x, found.z - player.z));
context.source.send_message(
`The nearest ${
display_name(id)
} is at ${found.x} ${found.y} ${found.z}, ${distance} blocks away`,
);
}),
),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("fly").describe("Toggles flying").executes((context) => {
const player = context.source.server_player;
player.flying = !player.flying;
player.fall_distance = 0;
context.source.send_message(player.flying ? "You can fly" : "You can't fly anymore");
}),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("creative")
.describe("Toggles placing blocks without using them up and breaking any block instantly")
.executes((context) => {
const player = context.source.server_player;
player.creative = !player.creative;
context.source.send_message(player.creative ? "You're in creative" : "You're out of creative");
}),
);
// TODO: only let operators do this
register(
literal<ServerCommandSource>("viewdistance").describe("Shows or changes the server's view distance")
.executes((context) => {
context.source.send_message(`The view distance is ${this.view_distance} chunks`);
})
.then(
argument<number, ServerCommandSource>("chunks", integer(MIN_VIEW_DISTANCE, MAX_VIEW_DISTANCE))
.executes((context) => {
this.set_view_distance(context.get<number>("chunks"));
context.source.send_message(`Set the view distance to ${this.view_distance} chunks`);
}),
),
);
register(
literal<ServerCommandSource>("tps").describe("Shows how the game loop keeps up").executes((context) => {
if (!this.loop) {
context.source.send_message("The game loop isn't running");
return;
}
const { tps, mspt, skipped } = this.loop.stats;
context.source.send_message(
`${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` +
`${skipped} skipped since starting`,
);
const pool = this.worldgen_pool;
const last_minute = this.world.fallbacks - (this.#fallback_history[0] ?? 0);
context.source.send_message(
pool
? `Worldgen: ${pool.workers} workers, ${pool.queued} chunks waiting, ${pool.generated} generated. ` +
`${last_minute} chunks generated on the game thread in the last minute`
: `Worldgen: on the game thread, ${last_minute} chunks in the last minute`,
);
}),
);
register(
literal<ServerCommandSource>("skin")
.describe(
"Changes your skin to a 64x64 png from the web, slim for 3 pixel wide arms. " +
"Back to the default without a url",
)
.executes((context) => {
this.set_skin(context.source.server_player, undefined, false);
context.source.send_message("Your skin is back to the default");
})
.then(
argument<string, ServerCommandSource>("url", word())
.executes((context) =>
this.#download_skin(context.source.server_player, context.get<string>("url"), false)
)
.then(
argument<string, ServerCommandSource>("model", choice(["slim", "normal"]))
.executes((context) =>
this.#download_skin(
context.source.server_player,
context.get<string>("url"),
context.get<string>("model") === "slim",
)
),
),
),
);
// every command's usage, or one's. aliases like /mod:name aren't listed twice
const commands = this.mods.commands;
const help = (context: CommandContext<ServerCommandSource>, only?: string) => {
const nodes = commands.root.children.filter((node) =>
!node.name.includes(":") && (!only || node.name === only)
);
if (nodes.length === 0) throw new CommandError(`There's no command /${only}`);
for (const node of nodes) {
const usage = `/${commands.usage(node, context.source)}`;
context.source.send_message(node.description ? `${usage} - ${node.description}` : usage);
}
};
register(
literal<ServerCommandSource>("help")
.describe("Lists commands")
.executes((context) => help(context))
.then(
argument<string, ServerCommandSource>("command", word())
.suggests((partial) =>
commands.root.children
.filter((node) => !node.name.includes(":") && node.name.startsWith(partial))
.map((node) => ({ text: node.name }))
)
.executes((context) => help(context, context.get<string>("command"))),
),
);
}
// a base64 png, or undefined for the default skin, and whether it's for the slim model. everyone is told, the
// player too
set_skin(player: ServerPlayer, skin: string | undefined, slim: boolean) {
player.skin = skin;
player.slim = slim;
this.world.dirty = true;
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] = corners(context);
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) {
throw new CommandError("Your last skin is still downloading");
}
player.downloading_skin = true;
this.send_chat(player, "Downloading your skin...");
const online = () => this.#players.get(player.conn) === player;
this.#host.download(url, MAX_SKIN_BYTES)
.then((bytes) => {
const problem = skin_problem(bytes);
if (problem) {
throw new Error(problem);
}
if (online()) {
this.set_skin(player, encode_skin(bytes), slim);
this.send_chat(player, "Skin changed");
}
})
.catch((e) => {
if (online()) {
this.send_chat(player, `Couldn't change your skin: ${e instanceof Error ? e.message : e}`);
}
})
.finally(() => player.downloading_skin = false);
}
#close_menu(player: ServerPlayer) {
const menu = player.menu;
player.menu = undefined;
for (const fn of menu?.on_close ?? []) fn();
player.sent.delete("menu_content");
player.sent.delete("menu_tanks");
player.sent.delete("menu_data");
// the crafting grid and whatever the cursor holds go back into the inventory
for (let i = 0; i < 9; i++) {
const item = player.crafting.get_item(i);
if (item) {
player.crafting.set_item(i, undefined);
this.give_stack(player, item);
}
}
update_crafting_result(player.crafting, this.recipes.shaped);
if (player.cursor.item) {
const item = player.cursor.item;
player.cursor.item = undefined;
this.give_stack(player, item);
}
}
// health and hunger, see vitals.ts
// hurts a player, killing them at 0. cause is for mods and the death message, like "fall"
damage_player(player: ServerPlayer, amount: number, cause: string) {
player.hurt(amount, damage_source(cause));
}
heal_player(player: ServerPlayer, amount: number) {
player.heal(amount);
}
// they start over at spawn. what happens to what they carried is up to mods' player_death, which runs while
// they're still where they died
#kill(player: ServerPlayer, source: DamageSource) {
const cause = source.cause;
this.close_menu(player);
this.mods.after.player_death.emit({ player: this.mods.player(player), cause });
this.#broadcast({ type: "chat", text: death_message(player.name, source) });
player.vitals.reset();
player.revive();
const spawn = this.world.spawn_point();
this.teleport(player, spawn.x, spawn.y, spawn.z);
this.world.dirty = true;
}
#tick_vitals() {
for (const player of this.#players.values()) {
// burning, effects, falling out of the world, and being knocked back. like entities, not while the chunk
// they're in is still being generated, see #tick_entities
const knocked_back = player.knockback_ticks !== undefined;
if (this.#generated_at(player.x, player.z)) player.tick();
if (knocked_back && player.alive) {
// the last one hands what's left of the slide to their client
this.#place(player, [player.vx, player.vy, player.vz]);
if (player.knockback_ticks === undefined) player.stop_knockback();
}
player.vitals.tick(
player.health,
player.max_health,
(amount) => this.heal_player(player, amount),
(amount) => this.damage_player(player, amount, "starve"),
);
}
}
// what moving costs and does: sprinting and swimming tire, jumping too, and landing after a fall hurts
#on_move(player: ServerPlayer, x: number, y: number, z: number) {
const dx = x - player.x;
const dy = y - player.y;
const dz = z - player.z;
const ticks = Math.max(1, this.#tick - player.last_move_tick);
player.last_move_tick = this.#tick;
const horizontal = Math.hypot(dx, dz);
// knockback only lifts them off the ground
player.on_ground = this.#on_ground(x, y, z);
// teleports and the first move after joining aren't walking
if (horizontal > TELEPORT_DISTANCE || Math.abs(dy) > TELEPORT_DISTANCE) {
player.fall_distance = 0;
return;
}
if (player.flying) {
player.fall_distance = 0;
return;
}
const vitals = player.vitals;
const in_fluid = this.#in_fluid(x, y, z);
const sprinting = horizontal / (ticks * TICK_DELTA) > SPRINT_SPEED;
if (in_fluid) {
vitals.add_exhaustion(EXHAUSTION.swim_per_block * (horizontal + Math.abs(dy)));
player.fall_distance = 0;
} else if (sprinting) {
vitals.add_exhaustion(EXHAUSTION.sprint_per_block * horizontal);
}
if (dy > 0 && !in_fluid && this.#on_ground(player.x, player.y, player.z)) {
vitals.add_exhaustion(sprinting ? EXHAUSTION.sprint_jump : EXHAUSTION.jump);
}
if (dy < 0 && !in_fluid) {
player.fall_distance -= dy;
}
if (player.on_ground) {
const damage = Math.ceil(player.fall_distance - SAFE_FALL);
player.fall_distance = 0;
if (damage > 0) {
this.damage_player(player, damage, "fall");
}
}
}
// the components of every block an entity's box is in see it, after it moved. players move on their clients, so
// theirs is after each move they send
#inside_blocks(entity: Entity) {
const { x, y, z } = entity;
physics.blocks_inside(entity, (bx, by, bz) => {
// a block before this one killed it, took it away or moved it somewhere else
if (entity.removed || (entity instanceof LivingEntity && entity.dead)) return;
if (entity.x !== x || entity.y !== y || entity.z !== z) return;
const id = this.world.get_block_id(bx, by, bz);
const components = this.mods.components_with(id, "on_entity_inside");
if (components.length === 0) return;
const block = this.mods.block_ref(bx, by, bz, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_entity_inside`,
() => component.on_entity_inside!(block, params, entity_ref(entity)),
);
}
});
}
// feet on top of something solid, anywhere under the player's box: a thin box just under their feet touches a
// block's collision shape. shapes, not whole blocks, so standing on a fence, a slab or a path counts too
#on_ground(x: number, y: number, z: number) {
const under_feet = {
x,
y: y - GROUND_EPSILON,
z,
vx: 0,
vy: 0,
vz: 0,
width: PLAYER_WIDTH,
height: GROUND_EPSILON,
};
return !physics.box_is_free(under_feet, 0, 0, 0, (bx, by, bz) => this.world.collision_shape(bx, by, bz));
}
// in fluid, a waterlogged block's too
#in_fluid(x: number, y: number, z: number) {
const [bx, by, bz] = [Math.floor(x), Math.floor(y), Math.floor(z)];
return fluid_block(this.world.get_block_value(bx, by, bz), this.world.get_block_info(bx, by, bz)) !==
undefined;
}
// right click with food: it's eaten if they're hungry, or it's always edible
#eat(player: ServerPlayer): boolean {
const slot = player.inventory.get_slot(player.selected_slot);
const food = EverythingRegistry.get<ItemRegistry>("items", slot.type_id ?? "")?.food;
if (!food || (!food.always_edible && !player.vitals.can_eat())) {
return false;
}
player.vitals.eat(food.nutrition, food.saturation_modifier);
slot.amount = slot.amount! - 1;
if (food.returns) {
const left = new ItemStack(food.returns);
if (slot.has_item()) {
this.give_stack(player, left);
} else {
slot.set_item(left);
}
}
return true;
}
// entities, see entity/
// whether the chunks within a block of x, z (what an entity there touches) can be built without generating anything
// here. always without a worldgen pool, which is what anything ticking there would otherwise wait for
#generated_at(x: number, z: number) {
if (!this.worldgen_pool) return true;
for (let cx = Math.floor((x - 1) / CHUNK_SIZE); cx <= Math.floor((x + 1) / CHUNK_SIZE); cx++) {
for (let cz = Math.floor((z - 1) / CHUNK_SIZE); cz <= Math.floor((z + 1) / CHUNK_SIZE); cz++) {
if (!this.world.can_build(cx, cz)) return false;
}
}
return true;
}
// like minecraft: entities only move near players, and players pick up items by walking into them. with a worldgen
// pool, only where the chunk is generated too, like minecraft's entities in chunks that aren't loaded: one that
// just got somewhere new, like a teleported player, waits for the pool instead of the game generating it here
#tick_entities() {
if (this.do_mob_spawning) this.spawner.tick(this, SIMULATION_DISTANCE);
this.entities.tick((entity) =>
this.#near_any_player(entity.x, entity.z) && this.#generated_at(entity.x, entity.z)
);
const items = this.item_entities();
for (const player of this.#players.values()) {
for (const entity of items) {
if (!entity.removed && entity.pickup_delay === 0 && this.#can_pick_up(player, entity)) {
this.#pick_up(player, entity);
}
}
}
if (this.entities.count > 0) {
this.world.dirty = true;
}
}
// the player's box grown by the pickup reach touches the item's box
#can_pick_up(player: ServerPlayer, entity: ItemEntity) {
const reach_xz = PLAYER_WIDTH / 2 + PICKUP_REACH_XZ + ITEM_SIZE / 2;
return Math.abs(player.x - entity.x) <= reach_xz && Math.abs(player.z - entity.z) <= reach_xz &&
entity.y + ITEM_SIZE >= player.y - PICKUP_REACH_Y &&
entity.y <= player.y + player.height + PICKUP_REACH_Y;
}
// as much as fits, the rest stays on the ground
#pick_up(player: ServerPlayer, entity: ItemEntity) {
if (player.inventory.add_item(entity.item) === 0) {
this.entities.take_item(entity, player.id);
}
}
// helpers
// the open menus' still_valid and on_tick
#tick_menus() {
for (const player of this.#players.values()) {
const menu = player.menu;
if (!menu) continue;
if (!menu.still_valid.every((valid) => valid())) {
this.close_menu(player);
continue;
}
for (const fn of menu.on_tick) fn();
}
}
// sends whatever changed since last time
#sync(player: ServerPlayer) {
const sync = (key: string, value: unknown, message: () => ServerMessage) => {
const json = JSON.stringify(value);
if (player.sent.get(key) !== json) {
player.sent.set(key, json);
this.#send(player, message());
}
};
// with lore, so it's resent when only the lore changed
const inventory = player.inventory.to_synced_data();
sync("inventory", inventory, () => ({ type: "container", container: "inventory", items: inventory }));
const crafting = player.crafting.to_synced_data();
sync("crafting", crafting, () => ({ type: "container", container: "crafting", items: crafting }));
const cursor = player.cursor.item?.to_synced_data() ?? null;
sync("cursor", cursor, () => ({ type: "cursor", item: cursor }));
const extra = player.inventory_menu.extra;
if (extra.length > 0) {
const items = extra.map((slot) => slot.container.get_item(slot.index)?.to_synced_data() ?? null);
sync("extra", items, () => ({ type: "container", container: "extra", items }));
}
// like minecraft, losing max health, like a curio's modifier going away, takes the health over it
if (player.health > player.max_health) player.health = player.max_health;
const { food, saturation } = player.vitals;
const { health, max_health } = player;
// in bubbles' halves like hunger, so it's only sent when a bubble changes, not every tick under water
const air = Math.max(0, Math.ceil(player.air / player.max_air * 20));
sync(
"vitals",
[health, max_health, food, saturation, air],
() => ({ type: "vitals", health, max_health, food, saturation, air }),
);
const attributes = {
attack_speed: player.attribute(ATTRIBUTES.attack_speed),
block_interaction_range: player.attribute(ATTRIBUTES.block_interaction_range),
entity_interaction_range: player.attribute(ATTRIBUTES.entity_interaction_range),
};
sync("attributes", attributes, () => ({ type: "attributes", ...attributes }));
const using = player.using !== undefined;
sync("using_item", using, () => ({ type: "using_item", using }));
const flying = player.flying;
sync("flying", flying, () => ({ type: "flying", flying }));
const creative = player.creative;
sync("creative", creative, () => ({ type: "creative", creative }));
const effects = [...player.effects.values()]
.filter((effect) => effect.show_icon)
.map(({ type, amplifier, duration }) => ({ id: type.id, amplifier, duration }));
// by when they end, which stays the same while they count down
const ends = effects.map((
{ id, amplifier, duration },
) => [id, amplifier, duration < 0 ? -1 : this.#tick + duration]);
sync("effects", ends, () => ({ type: "effects", effects }));
const menu = player.menu;
if (menu) {
const items = menu.content();
sync("menu_content", items, () => ({ type: "menu_content", id: menu.id, items }));
if (menu.fluid_slots.length > 0) {
const tanks = menu.tanks();
sync("menu_tanks", tanks, () => ({ type: "menu_tanks", id: menu.id, tanks }));
}
const data = menu.data_values();
sync("menu_data", data, () => ({ type: "menu_data", id: menu.id, data }));
}
}
// what a player wears that shows, to everyone when it changed
#sync_worn(player: ServerPlayer) {
const worn = player.worn_list();
const json = JSON.stringify(worn);
if (json === player.worn_sent) return;
player.worn_sent = json;
this.#broadcast({ type: "player_worn", id: player.id, worn });
}
// tell the player what's really at a position, undoing anything their client guessed
// the client's break_block or use_block with seq is handled, after the set_blocks it caused, even when it's
// ignored: the client holds back what the server says about the blocks it guessed until this comes
#ack(player: ServerPlayer, seq: unknown) {
if (is_int(seq) && seq > 0) {
this.#send(player, { type: "block_ack", seq });
}
}
#correct(player: ServerPlayer, x: number, y: number, z: number) {
if (!this.world.shape.contains(y) || !player.chunks.has_block(x, z)) {
return;
}
// with its states, or the client would show it at its defaults, like a fence that lost its connections
const id = this.world.get_block_id(x, y, z);
const state = this.world.get_block_value(x, y, z) >>> 16;
this.#send(player, state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id });
}
// chunks
// after the player moved or their view distance changed: tells their client the new center and which chunks to
// drop, the chunks that came into view go out in #send_chunks
#update_view(player: ServerPlayer, force = false) {
const { moved, forget } = player.chunks.move_to(player.x, player.z, force);
if (!moved) {
return;
}
const center = player.chunks.center!;
this.#send(player, { type: "set_center_chunk", x: center.x, z: center.z });
for (const [x, z] of forget) {
this.#send(player, { type: "forget_level_chunk", x, z });
}
}
// generates chunks in a pool's workers from now on: what players need goes to it, and only chunks it has made the
// parts of are sent (see #request_chunks). undefined goes back to generating on this thread
use_worldgen_pool(pool: WorldgenPool | undefined) {
this.worldgen_pool = pool;
if (pool) pool.on_chunk = (x, z, raw) => this.world.add_raw(x, z, raw);
}
// generates what's needed before players come with the pool, instead of on this thread when they do: the spawn
// search's chunks
async warm_up() {
const pool = this.worldgen_pool;
if (!pool) return;
// what the chunks in it are built from, their neighbors' spills too. saved chunks need nothing
const reach = SPAWN_AREA_CHUNKS - 1;
const needed = new Map<string, [number, number]>();
for (let x = -reach; x <= reach; x++) {
for (let z = -reach; z <= reach; z++) {
for (const [rx, rz] of this.world.raws_needed(x, z)) needed.set(`${rx},${rz}`, [rx, rz]);
}
}
await pool.prefetch([...needed.values()]);
this.world.spawn_point();
}
// asks the pool for the raw chunks the nearest chunks each player is waiting for are built from, nearest first.
// what nobody is waiting for any more is dropped from its queue
#request_chunks() {
const pool = this.worldgen_pool;
if (!pool) return;
const wanted = new Map<number, { x: number; z: number; priority: number }>();
for (const player of this.#players.values()) {
const center = player.chunks.center;
if (!center) continue;
for (const [cx, cz] of player.chunks.nearest_pending(WORLDGEN_REQUEST_WINDOW)) {
const priority = (cx - center.x) ** 2 + (cz - center.z) ** 2;
for (const [x, z] of this.world.raws_needed(cx, cz)) {
const key = chunk_key(x, z);
const known = wanted.get(key);
if (!known || priority < known.priority) wanted.set(key, { x, z, priority });
}
}
}
pool.want(wanted);
}
// every player's next batch, like minecraft's PlayerChunkSender. building chunks is the slow part, so they share
// a time budget and whoever didn't get theirs goes first next tick
#send_chunks() {
const players = [...this.#players.values()];
if (players.length === 0) {
return;
}
const start = performance.now();
const can_send = () => performance.now() - start < this.chunk_send_budget_ms;
// with a pool, only chunks it has made the parts of, the rest wait for it instead of being generated here.
// without one, each is built as it's picked, so the time it takes counts against the budget for the next
const ready = this.worldgen_pool
? (x: number, z: number) => this.world.can_build(x, z)
: (x: number, z: number) => (this.world.build(x, z), true);
const first = this.#next_chunk_player % players.length;
for (let i = 0; i < players.length; i++) {
const player = players[(first + i) % players.length];
if (!can_send()) {
this.#next_chunk_player = first + i;
return;
}
const batch = player.chunks.next_batch(can_send, ready);
if (batch.length === 0) {
continue;
}
this.#send(player, { type: "chunk_batch_start" });
for (const [x, z] of batch) {
this.#host.send(player.conn, this.world.level_chunk(x, z));
for (const tile of this.world.client_tiles(x, z)) {
this.#send(player, {
type: "block_data",
x: tile.x,
y: tile.y,
z: tile.z,
data: tile.client_data!,
});
}
}
this.#send(player, { type: "chunk_batch_finished", size: batch.length });
}
this.#next_chunk_player = first + 1;
}
// the block the player's crosshair is on, like their client's pick: the boxes it's drawn with, past fluids, as far
// as they can reach
#targeted_block(player: ServerPlayer): [number, number, number] | undefined {
const { eye_position: eye, look_direction: look } = this.mods.player(player);
const hit = raycast_blocks(
[eye.x, eye.y, eye.z],
[look.x, look.y, look.z],
player.attribute(ATTRIBUTES.block_interaction_range),
(x, y, z) => {
const block = this.world.get_block_info(x, y, z);
if (!block || is_fluid_block(block)) return undefined;
return shape_at(block, this.world.get_block_value(x, y, z));
},
);
return hit && [hit.x, hit.y, hit.z];
}
// from the eyes to the block's middle
#in_reach(player: ServerPlayer, x: number, y: number, z: number) {
const dx = x + 0.5 - player.x;
const dy = y + 0.5 - (player.y + player.eye_height);
const dz = z + 0.5 - player.z;
const reach = player.attribute(ATTRIBUTES.block_interaction_range) + REACH_LEEWAY;
return dx * dx + dy * dy + dz * dz <= reach * reach;
}
// from the eyes to the closest point of its box
#entity_in_reach(player: ServerPlayer, entity: LivingEntity) {
const eye_y = player.y + player.eye_height;
const half = entity.width / 2;
const dx = Math.max(entity.x - half - player.x, 0, player.x - entity.x - half);
const dy = Math.max(entity.y - eye_y, 0, eye_y - entity.y - entity.height);
const dz = Math.max(entity.z - half - player.z, 0, player.z - entity.z - half);
const reach = player.attribute(ATTRIBUTES.entity_interaction_range) + REACH_LEEWAY;
return dx * dx + dy * dy + dz * dz <= reach * reach;
}
// the blocks within SIMULATION_DISTANCE of a player that have on_new_day and no data, in chunks that are built
#blocks_without_data_near_players(): [number, number, number, string][] {
const wanted = new Uint8Array(ID_MASK + 1);
for (const [id, nid] of Object.entries(this.world.block_ids)) {
if (this.mods.components_of(id).some(({ component }) => component.on_new_day)) wanted[nid] = 1;
}
if (!wanted.includes(1)) {
return [];
}
const found: [number, number, number, string][] = [];
for (const [cx, cz] of this.#chunks_near_players().values()) {
for (const [x, y, z] of this.world.find_blocks(cx, cz, wanted)) {
if (this.world.get_tile(x, y, z)?.mod_data === undefined) {
found.push([x, y, z, this.world.get_block_id(x, y, z)]);
}
}
}
return found;
}
// the chunks within SIMULATION_DISTANCE of a player, by chunk_key, with their coordinates
#chunks_near_players(): Map<number, [number, number]> {
const chunks = new Map<number, [number, number]>();
for (const player of this.#players.values()) {
const px = Math.floor(player.x / CHUNK_SIZE);
const pz = Math.floor(player.z / CHUNK_SIZE);
for (let cx = px - SIMULATION_DISTANCE; cx <= px + SIMULATION_DISTANCE; cx++) {
for (let cz = pz - SIMULATION_DISTANCE; cz <= pz + SIMULATION_DISTANCE; cz++) {
chunks.set(chunk_key(cx, cz), [cx, cz]);
}
}
}
return chunks;
}
#near_any_player(x: number, z: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
for (const player of this.#players.values()) {
const px = Math.floor(player.x / CHUNK_SIZE);
const pz = Math.floor(player.z / CHUNK_SIZE);
if (Math.max(Math.abs(px - chunk_x), Math.abs(pz - chunk_z)) <= SIMULATION_DISTANCE) {
return true;
}
}
return false;
}
#unique_name(name: unknown): string {
const cleaned = typeof name === "string" ? name.replace(/[^A-Za-z0-9_]/g, "").slice(0, MAX_NAME_LENGTH) : "";
const base = cleaned || `player${Math.floor(Math.random() * 10000)}`;
const taken = new Set([...this.#players.values()].map((p) => p.name));
let final = base;
let i = 2;
while (taken.has(final)) {
final = `${base}${i}`;
i += 1;
}
return final;
}
#send(player: ServerPlayer, message: ServerMessage) {
if (player.conn === MACHINE_CONN) return;
this.#host.send(player.conn, JSON.stringify(message));
}
#broadcast(message: ServerMessage, except?: ServerPlayer) {
const data = JSON.stringify(message);
for (const player of this.#players.values()) {
if (player !== except) {
this.#host.send(player.conn, data);
}
}
}
}
// a block id, or air, which isn't a registered block, for clearing with /fill
function block_or_air(): ArgumentType<string> {
const blocks = block();
return {
parse: (text) => text === "air" || text === AIR_ID ? AIR_ID : blocks.parse(text, undefined),
suggest(partial) {
const air = AIR_ID.startsWith(partial) || "air".startsWith(partial);
return [...(air ? [{ text: AIR_ID }] : []), ...blocks.suggest!(partial, undefined)];
},
};
}
// the two corners from x1 y1 z1 x2 y2 z2 arguments, for /fill and /exportschematic
function corners(context: CommandContext<ServerCommandSource>): [Position, Position] {
const corner = (n: string) => ({
x: context.get<number>(`x${n}`),
y: context.get<number>(`y${n}`),
z: context.get<number>(`z${n}`),
});
return [corner("1"), corner("2")];
}
function is_number(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
}
function is_int(value: unknown): value is number {
return Number.isInteger(value);
}
// what a player asked for, up to the server's
function view_distance(requested: unknown, server: number): number {
if (!is_int(requested)) {
return server;
}
return Math.min(server, Math.max(MIN_VIEW_DISTANCE, Math.min(MAX_VIEW_DISTANCE, requested)));
}
// where on a block a client says it clicked or looks, 0 to 1 on each axis. the middle when it doesn't say, or says
// something that isn't on it
function hit_on_block(hit: unknown): [number, number, number] {
return Array.isArray(hit) && hit.length === 3 && hit.every((v) => typeof v === "number" && v >= 0 && v <= 1)
? [hit[0], hit[1], hit[2]]
: [0.5, 0.5, 0.5];
}
// messages are parsed json, so the types in ClientMessage are only what a well behaved client sends
function is_block_position(shape: WorldShape, x: unknown, y: unknown, z: unknown): boolean {
return is_int(x) && is_int(y) && is_int(z) && shape.contains(y) &&
Math.abs(x) < 30000 * CHUNK_SIZE && Math.abs(z) < 30000 * CHUNK_SIZE;
}
// level.json version 4, which only had items on the ground
interface SavedLevelV4 extends Omit<SavedLevel, "version" | "entities"> {
version: 4;
entities: {
x: number;
y: number;
z: number;
vx: number;
vy: number;
vz: number;
item: SavedItemEntity["item"];
age: number;
pickup_delay: number;
}[];
}
function upgrade_v4_entities(entities: SavedLevelV4["entities"]): SavedEntity[] {
return (entities ?? []).map((entity): SavedItemEntity => ({
id: ITEM_ENTITY_TYPE,
uuid: crypto.randomUUID(),
pos: [entity.x, entity.y, entity.z],
motion: [entity.vx, entity.vy, entity.vz],
rotation: [0, 0],
item: entity.item,
age: entity.age,
pickup_delay: entity.pickup_delay,
}));
}
// what everyone's told when someone dies
function death_message(name: string, source: DamageSource) {
switch (source.cause) {
case "player_attack":
return source.attacker instanceof ServerPlayer
? `${name} was slain by ${source.attacker.name}`
: `${name} died`;
case "fall":
return `${name} hit the ground too hard`;
case "void":
return `${name} fell out of the world`;
case "starve":
return `${name} starved to death`;
// standing on something hot, like a lit stove
case "hot_floor":
return `${name} discovered the floor was lava`;
default:
return `${name} died`;
}
}
// the states a block is placed with: its defaults, and a "facing" state turned towards whoever placed it, like
// minecraft's getStateForPlacement with getHorizontalDirection().getOpposite(). facing is 0 north, 1 east, 2 south,
// 3 west, and variants turn the model with it (its north side is the front, like cubi:cube's). they look along
// (-sin yaw, -cos yaw), so the way back to them is (sin yaw, cos yaw)
// where a player is now, for everyone else
function player_move(player: ServerPlayer): ServerMessage {
const { id, x, y, z, yaw, pitch } = player;
return { type: "player_move", id, x, y, z, yaw, pitch, ...(player.swimming && { swimming: true }) };
}