// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // 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 { BlockInteraction, BlockPlacement, BlockRules as Rules, Face, Position, SharedBlock, 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]; } // the face of the six someone looking at yaw and pitch looks most toward, like minecraft's getNearestLookingDirection. // pitch above 0 looks up, the way the camera aims export function looking_face(yaw: number, pitch: number): Face { const cos_pitch = Math.cos(pitch); const x = -Math.sin(yaw) * cos_pitch; const y = Math.sin(pitch); const z = -Math.cos(yaw) * cos_pitch; const [ax, ay, az] = [Math.abs(x), Math.abs(y), Math.abs(z)]; if (ay >= ax && ay >= az) return y > 0 ? "top" : "bottom"; if (ax >= az) return x > 0 ? "east" : "west"; return z > 0 ? "south" : "north"; } // 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)!; } // the most blocks one change can tell of changes, counting the ones those set off, before the rest are dropped. a // loop between two rules would otherwise never stop export const MAX_NEIGHBOR_UPDATES = 65536; export class BlockRules { #rules = new Map(); // blocks waiting to hear of a change, 6 numbers each: where the block is, then where the change was #queue: number[] = []; // changes going on. the queue waits until they're all done, see change #changing = 0; // run runs a mod's code, reporting what it throws instead of letting it take the game down. get_block reads the // side's world. told runs for each block told of a change once its rules have, where the server runs its // components' on_neighbor_change constructor( readonly run: (mod: string, what: string, fn: () => T) => T | undefined, readonly get_block: SharedWorld["get_block"], readonly told?: (x: number, y: number, z: number, from: Position) => void, ) {} 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 looking at yaw and pitch 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. undefined when a rule says it can't go there placement_value( block: BlockRegistry, yaw: number, pitch: number, where: Omit, ): number | undefined { let value = default_placement_value(block, yaw); const placement: BlockPlacement = { ...where, facing: horizontal_facing(yaw), looking: looking_face(yaw, pitch), }; 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), ); if (states === false) return undefined; 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; } // a player right clicked the block at x y z: its rules' on_interact, every one of them. returns whether any did // something. what they change goes through the side's world, so on a client it's a guess the server corrects interact( block: BlockRegistry, x: number, y: number, z: number, interaction: Omit, yaw: number, ): boolean { const at = { x, y, z, id: block.id }; const full: BlockInteraction = { ...interaction, facing: horizontal_facing(yaw) }; let handled = false; for (const { mod, id, rules, params } of this.#of(block)) { if (!rules.on_interact) continue; handled = this.run(mod, `${id} on_interact`, () => rules.on_interact!(at, params, full)) === true || handled; } return handled; } // tells the blocks beside x y z it changed, so they can change with it like a fence joining it. the world's // set_state calls this again for what they change, until nothing changes. see neighbor_changed notify_neighbors(x: number, y: number, z: number) { for (const [dx, dy, dz] of NEIGHBORS) this.#queue.push(x + dx, y + dy, z + dz, x, y, z); this.#settle(); } // tells the block at x y z the one at from changed: its rules' on_neighbor_change, then told. blocks hear in the // order they were told, the same on every side, once the change that told them is done. a queue instead of // calling them right away, so a long chain of changes doesn't grow the stack neighbor_changed(x: number, y: number, z: number, from: Position) { this.#queue.push(x, y, z, from.x, from.y, from.z); this.#settle(); } // runs a change to the world, holding back the blocks it tells until it's done, so they hear of all of it: one // told in a block's on_break hears once it's gone. the outermost change tells them all before it returns, so its // caller sees a settled world change(fn: () => T): T { this.#changing++; try { return fn(); } finally { this.#changing--; this.#settle(); } } // tells the blocks waiting, and the ones they set off, unless a change is still going on #settle() { if (this.#changing > 0) return; this.#changing++; const queue = this.#queue; try { for (let i = 0; i < queue.length; i += 6) { if (i === MAX_NEIGHBOR_UPDATES * 6) { console.warn( `one change told blocks of changes ${MAX_NEIGHBOR_UPDATES} times and was stopped, last the ` + `block at ${queue[i - 6]} ${queue[i - 5]} ${queue[i - 4]}`, ); break; } this.#tell(queue[i], queue[i + 1], queue[i + 2], { x: queue[i + 3], y: queue[i + 4], z: queue[i + 5] }); } } finally { queue.length = 0; this.#changing--; } } #tell(x: number, y: number, z: number, from: Position) { const id = this.get_block(x, y, z); const block = id && EverythingRegistry.get("blocks", id); if (!block) return; // what's there now, read only for rules that want it let neighbor: SharedBlock | undefined; for (const { mod, id: rules_id, rules, params } of this.#of(block)) { if (!rules.on_neighbor_change) continue; const changed = neighbor ??= { ...from, id: this.get_block(from.x, from.y, from.z) ?? "bworld:air" }; const at = { x, y, z, id }; this.run(mod, `${rules_id} on_neighbor_change`, () => rules.on_neighbor_change!(at, params, changed)); } this.told?.(x, y, z, from); } }