Shared state between client and server

This commit is contained in:
2026-10-03 18:45:07 -03:00
parent 63e6248f9f
commit 7417bfd5f1
24 changed files with 656 additions and 193 deletions
+10 -75
View File
@@ -22,16 +22,7 @@ import type { ModListing, RecipeBook } from "$/common/mod_loader.ts";
import type { WorldgenSetup } from "$/common/generation.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_value,
box_overlaps_block,
can_place,
can_stand_on,
default_block_value,
display_name,
placement_target,
set_state_value,
} from "$/common/utils.ts";
import { box_overlaps_block, can_place, can_stand_on, display_name, placement_target } from "$/common/utils.ts";
import { collision_shape_at, type Shape } from "$/common/block_shapes.ts";
import { EXHAUSTION } from "./vitals.ts";
import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
@@ -550,26 +541,9 @@ export class GameServer {
}
}
// tells the blocks around one that changed, so they can change with it like a fence connecting to it: their
// components' on_neighbor_change, like minecraft's updateShape
// tells the blocks around one that changed, so they can change with it like a fence joining it, see BlockRules
#notify_neighbors(x: number, y: number, z: number) {
const neighbor = { x, y, z, id: this.world.get_block_id(x, y, z) };
for (const [dx, dy, dz] of NEIGHBORS) {
const [nx, ny, nz] = [x + dx, y + dy, z + dz];
if (ny < 0 || ny >= CHUNK_HEIGHT) continue;
const id = this.world.get_block_id(nx, ny, nz);
if (id === AIR_ID) continue;
const components = this.mods.components_of(id).filter(({ component }) => component.on_neighbor_change);
if (components.length === 0) continue;
const block = this.mods.block_ref(nx, ny, nz, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_neighbor_change`,
() => component.on_neighbor_change!(block, params, neighbor),
);
}
}
this.mods.rules.notify_neighbors((bx, by, bz) => this.world.get_block_id(bx, by, bz), x, y, z);
}
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
@@ -1039,7 +1013,13 @@ export class GameServer {
}
// 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 value = this.#placement_value(placing, player, { x: tx, y: ty, z: tz, face, hit });
const value = this.mods.rules.placement_value(placing, player.yaw, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
});
const state = value >>> 16;
if (placing?.has_collision && this.#occupied(tx, ty, tz, collision_shape_at(placing, value))) {
this.#correct(player, tx, ty, tz);
@@ -1065,40 +1045,6 @@ export class GameServer {
this.mods.after.block_place.emit(place);
}
// the block's value with the states a player placing it gets: its defaults, facing them when it has a facing,
// then what its components' state_for_placement say, like minecraft's getStateForPlacement
#placement_value(
block: BlockRegistry,
player: ServerPlayer,
where: { x: number; y: number; z: number; face: Faces; hit: number[] },
): number {
const facing = placed_state(block.id, player);
let value = facing === undefined ? default_block_value(0, block) : block_value(0, facing);
const components = this.mods.components_of(block.id).filter(({ component }) => component.state_for_placement);
if (components.length === 0) return value;
const placement = {
...where,
hit: [where.hit[0], where.hit[1], where.hit[2]] as const,
player: this.mods.player(player),
};
for (const { mod, id, component, params } of components) {
const states = run_guarded(
mod,
`${id} state_for_placement`,
() => component.state_for_placement!(placement, params),
);
for (const [name, state] of Object.entries(states ?? {})) {
const known = block.states?.find((s) => s.name === name);
if (known && Number.isInteger(state) && state >= 0 && state < 2 ** known.bits) {
value = set_state_value(value, block, name, state)!;
} else {
console.warn(`${id} state_for_placement: ${block.id} has no state ${name} that fits ${state}`);
}
}
}
return value;
}
// 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) =>
@@ -1992,17 +1938,6 @@ function death_message(name: string, source: DamageSource) {
// 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 engine:cube's). they look along
// (-sin yaw, -cos yaw), so the way back to them is (sin yaw, cos yaw)
// the 6 blocks beside one
const NEIGHBORS = [[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]] as const;
function placed_state(block_id: string, player: ServerPlayer): number | undefined {
const info = EverythingRegistry.get<BlockRegistry>("blocks", block_id);
if (!info?.states?.some((state) => state.name === "facing" && state.bits >= 2)) return undefined;
const quarter = Math.round((Math.PI - player.yaw) / (Math.PI / 2));
const facing = ((quarter % 4) + 4) % 4;
return set_state_value(default_block_value(0, info), info, "facing", facing)! >>> 16;
}
// where a player is now, for everyone else
function player_move(player: ServerPlayer): ServerMessage {
const { id, x, y, z, yaw, pitch } = player;
+7 -1
View File
@@ -9,7 +9,13 @@ export type HostToGame =
save: WorldSave;
default_seed: string;
// in load order, with the scripts' code since the worker can't read files
mods: { listing: ModListing; data: ModData; server_code?: string; worldgen_code?: string }[];
mods: {
listing: ModListing;
data: ModData;
server_code?: string;
worldgen_code?: string;
shared_code?: string;
}[];
}
| { type: "connect"; conn: number }
| { type: "message"; conn: number; data: string }
+8
View File
@@ -16,6 +16,7 @@ export interface ServerModSource {
// importable urls of the scripts: data: urls in the worker, file urls in tests
server_url?: string;
worldgen_url?: string;
shared_url?: string;
}
export async function start_game(
@@ -44,6 +45,13 @@ export async function start_game(
runtime,
});
// every mod's shared rules first, so server scripts can count on any mod's being there
await runtime.load_shared_scripts(
game,
mods.flatMap((mod) =>
mod.shared_url ? [{ mod: mod.listing.id, version: mod.listing.version, url: mod.shared_url }] : []
),
);
await runtime.load_scripts(
game,
mods.flatMap((mod) =>
+48 -6
View File
@@ -4,6 +4,8 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import { covers_face } from "$/common/block_shapes.ts";
import { BlockRules } from "$/common/block_rules.ts";
import type { SharedContext } from "$/common/mod_api/shared.ts";
import { tag_api } from "$/common/tags.ts";
import type {
BlockComponent,
@@ -112,6 +114,8 @@ interface Timer {
export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>();
// what shared scripts registered, see common/block_rules.ts
rules = new BlockRules(run_guarded);
item_components = new Map<string, { mod: string; component: ItemComponent }>();
effect_components = new Map<string, { mod: string; component: EffectComponent }>();
// every command, the engine's and mods', see common/commands.ts
@@ -208,6 +212,44 @@ export class ModRuntime {
game!: GameServer;
// imports each server script and calls its setup, in load order
// shared scripts, the block rules clients run too. their world is the server's
async load_shared_scripts(game: GameServer, scripts: { mod: string; version: string; url: string }[]) {
this.game = game;
for (const { mod, version, url } of scripts) {
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the shared script doesn't export a setup function");
}
const { world } = this.#context(mod, version);
const ctx: SharedContext = {
mod: { id: mod, version },
side: "server",
tags: tag_api(),
world: {
get_block: world.get_block,
get_state: world.get_state,
set_state: world.set_state,
is_face_sturdy: world.is_face_sturdy,
},
components: {
register_block: (id, rules) => {
if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup");
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `component ${id} must be in the namespace "${mod}"`);
}
this.rules.register(mod, id, rules);
},
},
};
running_mod = mod;
try {
await module.setup(ctx);
} finally {
running_mod = "";
}
}
}
async load_scripts(game: GameServer, scripts: { mod: string; version: string; url: string }[]) {
this.game = game;
for (const { mod, version, url } of scripts) {
@@ -286,7 +328,7 @@ export class ModRuntime {
for (const [id, block] of EverythingRegistry.entries<{ components?: Record<string, unknown> }>("blocks")) {
for (const component of Object.keys(block.components ?? {})) {
if (!this.block_components.has(component)) {
if (!this.block_components.has(component) && !this.rules.has(component)) {
throw new ModLoadError(
id.split(":")[0],
`block ${id} uses component ${component}, which nothing registered`,
@@ -366,11 +408,11 @@ export class ModRuntime {
// components on a block, with their params from its json
components_of(block_id: string): { mod: string; id: string; component: BlockComponent; params: unknown }[] {
const block = EverythingRegistry.get<{ components?: Record<string, unknown> }>("blocks", block_id);
return Object.entries(block?.components ?? {}).map(([id, params]) => ({
...this.block_components.get(id)!,
id,
params,
}));
// components that only have shared rules have nothing here
return Object.entries(block?.components ?? {}).flatMap(([id, params]) => {
const registered = this.block_components.get(id);
return registered ? [{ ...registered, id, params }] : [];
});
}
// components on an item, with their params from its json
+1
View File
@@ -85,6 +85,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
// the worker has no file access, so the host sends the code and it's imported from memory
server_url: mod.server_code ? data_url(mod.server_code) : undefined,
worldgen_url: mod.worldgen_code ? data_url(mod.worldgen_code) : undefined,
shared_url: mod.shared_code ? data_url(mod.shared_code) : undefined,
})),
);
} catch (e) {
+1
View File
@@ -117,6 +117,7 @@ export async function start_host(options: HostOptions): Promise<Host> {
data: bmod.data,
server_code: bmod.scripts.server,
worldgen_code: bmod.scripts.worldgen,
shared_code: bmod.scripts.shared,
})),
} satisfies HostToGame,
save.chunks.map((chunk) => chunk.data.buffer),