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
+94
View File
@@ -0,0 +1,94 @@
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
import type { BlockPlacement, BlockRules as Rules, SharedWorld } from "./mod_api/shared.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
import { default_block_value, set_state_value } from "./utils.ts";
// the 6 blocks beside one
export const NEIGHBORS = [[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]] as const;
// the horizontal faces in the order of a 2 bit facing state's values, the way a block's y turns it
export const FACINGS = ["north", "east", "south", "west"] as const;
// the way someone looking at yaw looks, along the ground. yaw 0 looks north (-z), like the camera
export function horizontal_facing(yaw: number): typeof FACINGS[number] {
const quarter = Math.round(-yaw / (Math.PI / 2));
return FACINGS[((quarter % 4) + 4) % 4];
}
// a block's value as a player looking at yaw places it before any rules: its default states, and a 2 bit facing
// turned towards them, like a furnace
export function default_placement_value(block: BlockRegistry, yaw: number): number {
const value = default_block_value(0, block);
if (!block.states?.some((state) => state.name === "facing" && state.bits >= 2)) return value;
const toward = FACINGS.indexOf(horizontal_facing(yaw)) ^ 2;
return set_state_value(value, block, "facing", toward)!;
}
export class BlockRules {
#rules = new Map<string, { mod: string; rules: Rules }>();
// runs a mod's code, reporting what it throws instead of letting it take the game down
constructor(readonly run: <T>(mod: string, what: string, fn: () => T) => T | undefined) {}
register(mod: string, id: string, rules: Rules) {
if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`);
this.#rules.set(id, { mod, rules });
}
has(id: string) {
return this.#rules.has(id);
}
// the rules a block's components have, with each one's params from the block's json
#of(block: BlockRegistry) {
return Object.entries(block.components ?? {}).flatMap(([id, params]) => {
const entry = this.#rules.get(id);
return entry ? [{ ...entry, id, params }] : [];
});
}
// the block's value with the states a player placing it gets: its defaults facing them (default_placement_value),
// then what its rules' state_for_placement say. states that don't exist or don't fit are left alone
placement_value(block: BlockRegistry, yaw: number, where: Omit<BlockPlacement, "facing">): number {
let value = default_placement_value(block, yaw);
const placement: BlockPlacement = { ...where, facing: horizontal_facing(yaw) };
for (const { mod, id, rules, params } of this.#of(block)) {
if (!rules.state_for_placement) continue;
const states = this.run(
mod,
`${id} state_for_placement`,
() => rules.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(
`[${mod}] ${id} state_for_placement: ${block.id} has no state ${name} that fits ${state}`,
);
}
}
}
return value;
}
// tells the blocks beside x y z it changed, so they can change with it like a fence joining it: their rules'
// on_neighbor_change. the world's set_state calls this again for what they change, until nothing changes
notify_neighbors(get_block: SharedWorld["get_block"], x: number, y: number, z: number) {
const neighbor = { x, y, z, id: get_block(x, y, z) ?? "bworld:air" };
for (const [dx, dy, dz] of NEIGHBORS) {
const [nx, ny, nz] = [x + dx, y + dy, z + dz];
const id = get_block(nx, ny, nz);
const block = id && EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) continue;
for (const { mod, id: rules_id, rules, params } of this.#of(block)) {
if (!rules.on_neighbor_change) continue;
const at = { x: nx, y: ny, z: nz, id };
this.run(mod, `${rules_id} on_neighbor_change`, () => rules.on_neighbor_change!(at, params, neighbor));
}
}
}
}
+2 -2
View File
@@ -37,8 +37,8 @@ const MAX_UNZIPPED_BYTES = 64 * 1024 * 1024;
// written into every entry, so packing the same mod twice gives the same bytes and the same hash
const FIXED_TIME = new Date(Date.UTC(2020, 0, 1));
export type ScriptSide = "server" | "client" | "worldgen";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen"];
export type ScriptSide = "server" | "client" | "worldgen" | "shared";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared"];
export interface Bmod {
manifest: ManifestJson;
+1 -14
View File
@@ -49,12 +49,7 @@ export interface BlockComponent<P = any> {
on_second?(block: BlockRef, params: P, dt: number): void;
// every morning at 06:00, for every block with data in the world, near a player or not. day is ServerWorld.day
on_new_day?(block: BlockRef, params: P, day: number): void;
// a block next to it (on any of the 6 sides) was placed, broken or changed its states, like minecraft's
// updateShape. neighbor is where, and what's there now
on_neighbor_change?(block: BlockRef, params: P, neighbor: Position & { readonly id: Id }): void;
// the states it's placed with when a player places it, like minecraft's getStateForPlacement. states it doesn't
// return keep their defaults, and a 2 bit "facing" faces the player
state_for_placement?(placement: BlockPlacement, params: P): Record<string, number> | void;
// placing and neighbor rules are in shared scripts, see BlockRules in bworld/shared
}
// deno-lint-ignore no-explicit-any
@@ -149,14 +144,6 @@ export interface BlockPlaceEvent {
readonly item: ItemStack | undefined;
}
// a player placing a block at x y z by clicking face of the block next to it, at hit (0 to 1 on each axis of that
// block), like minecraft's BlockPlaceContext
export interface BlockPlacement extends Position {
readonly player: Player;
readonly face: Face;
readonly hit: readonly [number, number, number];
}
export interface BlockInteractEvent {
readonly player: Player;
readonly block: BlockRef;
+53
View File
@@ -48,3 +48,56 @@ export type Unsubscribe = () => void;
export interface EventSignal<T> {
subscribe(handler: (event: T) => void): Unsubscribe;
}
// shared scripts: block rules that run on the server and on every client, so a client places blocks the way the
// server will, like minecraft's Block code that both sides run. see docs/modding/gettingstarted/modfiles.md
export interface SharedContext {
readonly mod: ModInfo;
// which one this is running on. the server's say is final, clients only guess ahead of it
readonly side: "server" | "client";
readonly tags: TagApi;
// the world rules look at and change. on a client it's what that client sees, and what rules change there is a
// guess until the server says what really happened. only for use in rules, not during setup
readonly world: SharedWorld;
readonly components: {
// the rules of a block component, the same id the server script registers the rest of it under
// deno-lint-ignore no-explicit-any
register_block<P = any>(id: Id, rules: BlockRules<P>): void;
};
}
export interface SharedWorld {
// undefined when the chunk isn't loaded, "bworld:air" for air
get_block(x: number, y: number, z: number): Id | undefined;
get_state(x: number, y: number, z: number, name: string): number | undefined;
// changing what a block is tells the blocks beside it, see BlockRules.on_neighbor_change
set_state(x: number, y: number, z: number, name: string, value: number): boolean;
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
// shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
}
// a block in the world, for rules
export interface SharedBlock extends Position {
readonly id: Id;
}
// a player placing a block at x y z by clicking face of the block next to it, at hit (0 to 1 on each axis of that
// block), like minecraft's BlockPlaceContext. facing is the way the player looks, along the ground
export interface BlockPlacement extends Position {
readonly face: Face;
readonly hit: readonly [number, number, number];
readonly facing: "north" | "east" | "south" | "west";
}
// P is the component's params from the block json
// deno-lint-ignore no-explicit-any
export interface BlockRules<P = any> {
// the states it's placed with when a player places it, like minecraft's getStateForPlacement. states it doesn't
// return keep their defaults, and a 2 bit "facing" faces the player
state_for_placement?(placement: BlockPlacement, params: P): Record<string, number> | void;
// a block next to it (on any of the 6 sides) was placed, broken or changed its states, like minecraft's
// updateShape. neighbor is where, and what's there now
on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void;
}
+4 -2
View File
@@ -36,7 +36,7 @@ export interface ManifestJson {
authors?: string[];
game_version?: string;
dependencies?: { id: string; version: string }[];
scripts?: { server?: string; client?: string; worldgen?: string };
scripts?: { server?: string; client?: string; worldgen?: string; shared?: string };
credits?: string;
}
@@ -449,7 +449,9 @@ export function validate_manifest(json: unknown, folder_name: string): Problems
problems.push("scripts must be an object");
} else {
for (const [side, path] of Object.entries(json.scripts)) {
if (!["server", "client", "worldgen"].includes(side)) problems.push(`unknown script "${side}"`);
if (!["server", "client", "worldgen", "shared"].includes(side)) {
problems.push(`unknown script "${side}"`);
}
if (typeof path !== "string") problems.push(`scripts.${side} must be a path`);
}
}