Shared state between client and server
This commit is contained in:
+15
-5
@@ -4,7 +4,8 @@ import type { Client } from "./client.ts";
|
||||
import type { BlockHitResult } from "./level/client_level.ts";
|
||||
import type { Container } from "$/common/inventory.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { box_overlaps_block, can_place, default_block_value, placement_target } from "$/common/utils.ts";
|
||||
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
|
||||
import { block_rules, predict_neighbors } from "./mods.ts";
|
||||
import { collision_shape_at } from "$/common/block_shapes.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||
@@ -42,6 +43,7 @@ export class MultiPlayerGameMode {
|
||||
if (this.destroy_progress >= this.destroy_time) {
|
||||
// show it right away, the server decides drops and corrects us if it disagrees
|
||||
this.client.level.break_block(hit.x, hit.y, hit.z);
|
||||
predict_neighbors(hit.x, hit.y, hit.z);
|
||||
this.client.connection.send({ type: "break_block", x: hit.x, y: hit.y, z: hit.z });
|
||||
this.destroy_progress = 0;
|
||||
this.destroy_time = 0;
|
||||
@@ -74,13 +76,21 @@ export class MultiPlayerGameMode {
|
||||
const place_block = place_id !== undefined
|
||||
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
|
||||
: undefined;
|
||||
// with the states the server will give it, see BlockRules.placement_value
|
||||
const value = place_block &&
|
||||
block_rules.placement_value(place_block, this.client.player.yaw, {
|
||||
...target,
|
||||
face: hit.face,
|
||||
hit: hit.hit,
|
||||
});
|
||||
const placeable = place_id !== undefined && can_place(
|
||||
place_block,
|
||||
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
|
||||
below_id,
|
||||
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block));
|
||||
) && !(place_block?.has_collision && this.#occupied(target.x, target.y, target.z, place_block, value!));
|
||||
if (!block_info.interactive && place_id && placeable) {
|
||||
level.add_block({ ...target, id: place_id });
|
||||
level.add_block({ ...target, id: place_id }, value! >>> 16);
|
||||
predict_neighbors(target.x, target.y, target.z);
|
||||
const slot = this.#held_slot();
|
||||
slot.amount = slot.amount! - 1;
|
||||
}
|
||||
@@ -118,8 +128,8 @@ export class MultiPlayerGameMode {
|
||||
|
||||
// whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs
|
||||
// are the mod entities that aren't scripted, players are this one and the others
|
||||
#occupied(x: number, y: number, z: number, block: BlockRegistry) {
|
||||
const shape = collision_shape_at(block, default_block_value(0, block));
|
||||
#occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) {
|
||||
const shape = collision_shape_at(block, value);
|
||||
for (const entity of this.client.level.entities.values()) {
|
||||
const json = entity instanceof RemoteEntity
|
||||
? EverythingRegistry.get<EntityJson>("entities", entity.type)
|
||||
|
||||
+89
-1
@@ -5,7 +5,10 @@ import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/e
|
||||
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
|
||||
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
||||
import { display_name } from "$/common/utils.ts";
|
||||
import { display_name, get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "$/common/block_shapes.ts";
|
||||
import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import type { Client } from "./client.ts";
|
||||
@@ -38,6 +41,59 @@ export function receive_mod_message(channel: string, data: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
|
||||
export let block_rules = new BlockRules(run_mod);
|
||||
// whether shared scripts are being set up, the only time they can register rules
|
||||
let rules_setup = false;
|
||||
|
||||
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
|
||||
try {
|
||||
return fn();
|
||||
} catch (e) {
|
||||
console.error(`[${mod}] ${what} threw:`, e);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// the world shared rules see on this client: what it shows. what they change is a guess the server corrects
|
||||
const rules_world: SharedWorld = {
|
||||
get_block(x, y, z) {
|
||||
const nid = client?.level.get_block(x, y, z);
|
||||
if (nid === undefined) return undefined;
|
||||
if (nid === AIR) return AIR_ID;
|
||||
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
|
||||
},
|
||||
get_state(x, y, z, name) {
|
||||
const level = client?.level;
|
||||
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
|
||||
if (!info?.states?.some((state) => state.name === name)) return undefined;
|
||||
return get_state_value(level!.get_block_value(x, y, z), info, name);
|
||||
},
|
||||
set_state(x, y, z, name, value) {
|
||||
const level = client?.level;
|
||||
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("blocks", level.get_block(x, y, z));
|
||||
if (!info?.states?.some((state) => state.name === name)) return false;
|
||||
const old_value = level!.get_block_value(x, y, z);
|
||||
const new_value = set_state_value(old_value, info, name, value);
|
||||
if (new_value === undefined) return false;
|
||||
if (new_value !== old_value) {
|
||||
level!.add_block({ x, y, z, id: info.id }, new_value >>> 16);
|
||||
predict_neighbors(x, y, z);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
is_face_sturdy(x, y, z, face) {
|
||||
const shape = client?.level.collision_shape(x, y, z) ?? false;
|
||||
return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face);
|
||||
},
|
||||
};
|
||||
|
||||
// this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will
|
||||
// on the server
|
||||
export function predict_neighbors(x: number, y: number, z: number) {
|
||||
block_rules.notify_neighbors(rules_world.get_block, x, y, z);
|
||||
}
|
||||
|
||||
// the loaded mods' recipes, and their names by id
|
||||
let recipe_book = new RecipeBook();
|
||||
const mod_names = new Map<string, string>();
|
||||
@@ -77,6 +133,19 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
||||
mod_names.clear();
|
||||
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
||||
|
||||
// every mod's shared rules first, so client scripts can count on any mod's being there
|
||||
block_rules = new BlockRules(run_mod);
|
||||
rules_setup = true;
|
||||
for (const [i, bmod] of bmods.entries()) {
|
||||
if (!bmod.scripts.shared) continue;
|
||||
const module = await import(script_url(bmod.scripts.shared));
|
||||
if (typeof module.setup !== "function") {
|
||||
throw new ModLoadError(bmod.manifest.id, "the shared script doesn't export a setup function");
|
||||
}
|
||||
await module.setup(shared_context(listings[i]));
|
||||
}
|
||||
rules_setup = false;
|
||||
|
||||
for (const [i, bmod] of bmods.entries()) {
|
||||
if (!bmod.scripts.client) continue;
|
||||
const module = await import(script_url(bmod.scripts.client));
|
||||
@@ -91,6 +160,25 @@ function script_url(code: string) {
|
||||
return code_url(new TextEncoder().encode(code));
|
||||
}
|
||||
|
||||
function shared_context(listing: ModListing): SharedContext {
|
||||
const mod = listing.id;
|
||||
return {
|
||||
mod: { id: mod, version: listing.version },
|
||||
side: "client",
|
||||
tags: tag_api(),
|
||||
world: rules_world,
|
||||
components: {
|
||||
register_block(id, rules) {
|
||||
if (!id.startsWith(`${mod}:`)) {
|
||||
throw new Error(`[${mod}] component ${id} must be in the namespace "${mod}"`);
|
||||
}
|
||||
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
||||
block_rules.register(mod, id, rules);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function client_context(listing: ModListing): ClientContext {
|
||||
const mod = listing.id;
|
||||
const not_yet = (name: string, where: string) =>
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"bworld/server": "./common/mod_api/server.ts",
|
||||
"bworld/client": "./common/mod_api/client.ts",
|
||||
"bworld/worldgen": "./common/mod_api/worldgen.ts",
|
||||
"bworld/shared": "./common/mod_api/shared.ts",
|
||||
"@gfx/canvas-wasm": "jsr:@gfx/canvas-wasm@^0.4.2",
|
||||
"@paulaboks/rng": "jsr:@paulaboks/rng@^0.0.3",
|
||||
"@std/assert": "jsr:@std/assert@^1.0.0",
|
||||
|
||||
@@ -59,21 +59,45 @@ component.
|
||||
|
||||
## Handlers
|
||||
|
||||
| Handler | Called when | Returns |
|
||||
| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- |
|
||||
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
|
||||
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
|
||||
| `on_click(block, params, player)` | A player starts hitting it. | |
|
||||
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
|
||||
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
|
||||
| `on_second(block, params, dt)` | Every second, near a player. | |
|
||||
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | |
|
||||
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
|
||||
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with |
|
||||
| Handler | Called when | Returns |
|
||||
| ------------------------------------ | ----------------------------------------------------------------- | -------------------------- |
|
||||
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
|
||||
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
|
||||
| `on_click(block, params, player)` | A player starts hitting it. | |
|
||||
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
|
||||
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
|
||||
| `on_second(block, params, dt)` | Every second, near a player. | |
|
||||
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | |
|
||||
|
||||
`block` is `{ id, x, y, z, data }`, where `data` is the block's [tile data](tiledata.md). `params` is what the block's
|
||||
JSON lists for this component, and `dt` is in seconds.
|
||||
|
||||
## Rules
|
||||
|
||||
A component's rules decide a block's states from where it's placed and what's around it. They're registered in the mod's
|
||||
[shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients run them too: that's
|
||||
how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the server
|
||||
answers. A component can have rules, handlers, or both, and a block can list one that only has rules.
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.components.register_block("copper_tools:pipe", {
|
||||
state_for_placement(placement, params) {/* ... */},
|
||||
on_neighbor_change(block, params, neighbor) {/* ... */},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
| Rule | Called when | Returns |
|
||||
| --------------------------------------------- | ---------------------------------------------------------------------- | ----------------------- |
|
||||
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with |
|
||||
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
|
||||
|
||||
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has
|
||||
`get_block`, `get_state`, `set_state` and `is_face_sturdy`, and only works inside rules.
|
||||
|
||||
### Neighbors
|
||||
|
||||
`on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is
|
||||
@@ -87,10 +111,11 @@ a slab's sides and plants aren't.
|
||||
### Placing
|
||||
|
||||
`state_for_placement` picks the states a block is placed with, like Minecraft's `getStateForPlacement`. `placement` is
|
||||
`{ x, y, z, player, face, hit }`: where it's going, the face of the block that was clicked, and where on that block the
|
||||
click was, from 0 to 1 on each axis. It returns states by name, and the rest keep their defaults, except that a 2 bit
|
||||
`facing` already faces the player. It runs before the server checks that no one is in the way, so that's checked against
|
||||
the shape the block will really have. A trapdoor clicked onto the upper half of a block's side hangs in the top half:
|
||||
`{ x, y, z, face, hit, facing }`: where it's going, the face of the block that was clicked, where on that block the
|
||||
click was (from 0 to 1 on each axis), and the way the player looks along the ground. It returns states by name, and the
|
||||
rest keep their defaults, except that a 2 bit `facing` already faces the player. It runs before the server checks that
|
||||
no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked onto the upper
|
||||
half of a block's side hangs in the top half:
|
||||
|
||||
```ts
|
||||
state_for_placement(placement): Record<string, number> {
|
||||
@@ -101,7 +126,8 @@ state_for_placement(placement): Record<string, number> {
|
||||
},
|
||||
```
|
||||
|
||||
Clients guess blocks are placed with their defaults, and the server corrects them right after.
|
||||
A fence's placement looks at its neighbors, so it's joined from the start, and its `on_neighbor_change` keeps it joined
|
||||
after. Both are in `mods/bworld/scripts/shared.ts`.
|
||||
|
||||
### Interacting
|
||||
|
||||
@@ -127,18 +153,18 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
|
||||
|
||||
`mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them:
|
||||
|
||||
| Component | Params | What it does |
|
||||
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
|
||||
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
|
||||
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
|
||||
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
|
||||
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
|
||||
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
|
||||
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
|
||||
| `bworld:water_source` | none | Refills the watering can. |
|
||||
| `bworld:fishable` | none | Can be fished in with the fishing rod. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's. Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
|
||||
| Component | Params | What it does |
|
||||
| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
|
||||
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
|
||||
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
|
||||
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
|
||||
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
|
||||
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
|
||||
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
|
||||
| `bworld:water_source` | none | Refills the watering can. |
|
||||
| `bworld:fishable` | none | Can be fished in with the fishing rod. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (its rules are in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
|
||||
|
||||
Item components work the same way, see [Items](../items/index.md#item-components).
|
||||
|
||||
@@ -9,10 +9,11 @@ Clients send what the player is _trying_ to do: "break the block at x, y, z", "u
|
||||
slot 3". The server checks it (reach, the item being held, container rules), runs mod logic, and sends back what
|
||||
happened.
|
||||
|
||||
For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away. When the
|
||||
server disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is
|
||||
undone. Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other
|
||||
than placing.
|
||||
For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away, with the
|
||||
states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does. When the server
|
||||
disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is undone.
|
||||
Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other than
|
||||
placing.
|
||||
|
||||
```
|
||||
server process browser
|
||||
@@ -21,18 +22,20 @@ than placing.
|
||||
│ ┌───────────────────────────────────┐ │ ws │ + mods' client scripts │
|
||||
│ │ game server worker │◄├──────────┤► │
|
||||
│ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │
|
||||
│ │ + mods' server scripts │ │ chunks └──────────────────────────────────┘
|
||||
│ │ + mods' server scripts │ │ chunks │ + mods' shared scripts │
|
||||
│ │ + mods' shared scripts │ │ └──────────────────────────────────┘
|
||||
│ │ + mods' worldgen scripts │ │
|
||||
│ └───────────────────────────────────┘ │
|
||||
└───────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## The Three Scripts
|
||||
## The Four Scripts
|
||||
|
||||
| Script | Runs on | Sent to players | For |
|
||||
| ---------- | -------------------------------- | --------------- | ------------------------------------------------------------------- |
|
||||
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
|
||||
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
|
||||
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
|
||||
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
|
||||
|
||||
Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and
|
||||
@@ -73,6 +76,34 @@ can't change the world or inventories.
|
||||
Client code is visible to players and can be changed by them. Never trust it for anything that matters. See
|
||||
[Security](security.md).
|
||||
|
||||
### Shared Scripts
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.components.register_block("copper_tools:pipe", {
|
||||
state_for_placement(placement) {/* ... */},
|
||||
on_neighbor_change(block, params, neighbor) {/* ... */},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Shared scripts hold a block component's rules, the code Minecraft runs on both sides: what states a block is placed with
|
||||
(`state_for_placement`) and how it changes with the blocks beside it (`on_neighbor_change`). See
|
||||
[Block Components](../blocks/components.md#placing). The server script registers the rest of the same component, like
|
||||
its `on_interact`, under the same id.
|
||||
|
||||
On the server they run on the real world. On a client they run on what that client shows, when its player places or
|
||||
breaks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and the
|
||||
server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs a
|
||||
flicker. `ctx.side` says which one it's running on.
|
||||
|
||||
`setup` runs before the server or client script on each side, for every mod first, so their scripts can count on any
|
||||
mod's rules being there. Rules can only be registered during `setup`, and `ctx.world` only works in them.
|
||||
|
||||
Shared code is sent to players like client code, so it's for rules anyone may read, never anti-cheat or secrets.
|
||||
|
||||
### Worldgen Scripts
|
||||
|
||||
Worldgen scripts register features that run on every chunk the server generates. They must be deterministic: the same
|
||||
@@ -90,6 +121,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
|
||||
| Entities | yes | near the player |
|
||||
| `ctx.storage` | yes | no |
|
||||
| Server script code | yes | **never** |
|
||||
| Shared script code | yes | yes, and runs it |
|
||||
|
||||
When a client needs to see something only the server has, the server has to send it: open a
|
||||
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Mod Files
|
||||
|
||||
A mod is a folder with a `manifest.json`, some data files, textures, and up to three scripts. The build packs it into a
|
||||
A mod is a folder with a `manifest.json`, some data files, textures, and up to four scripts. The build packs it into a
|
||||
single `.bmod` file, which is what servers load.
|
||||
|
||||
## Layout
|
||||
@@ -25,6 +25,7 @@ mods/
|
||||
scripts/
|
||||
server.ts # game logic, never sent to players
|
||||
client.ts # sent to players
|
||||
shared.ts # block rules, run on the server and sent to players
|
||||
worldgen.ts # terrain features, never sent to players
|
||||
```
|
||||
|
||||
@@ -55,7 +56,8 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
|
||||
"scripts": {
|
||||
"server": "scripts/server.ts",
|
||||
"client": "scripts/client.ts",
|
||||
"worldgen": "scripts/worldgen.ts"
|
||||
"worldgen": "scripts/worldgen.ts",
|
||||
"shared": "scripts/shared.ts"
|
||||
},
|
||||
"credits": "CREDITS.md"
|
||||
}
|
||||
@@ -71,7 +73,7 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
|
||||
| `authors` | no | A list of names. |
|
||||
| `game_version` | no | The bworld versions the mod works with, as a semver range. Not checked yet. |
|
||||
| `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. |
|
||||
| `scripts` | no | Paths to the `server`, `client` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
|
||||
| `scripts` | no | Paths to the `server`, `client`, `shared` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
|
||||
| `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. |
|
||||
|
||||
List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It
|
||||
@@ -90,8 +92,8 @@ so they can import other files and packages, but code imported by several script
|
||||
|
||||
When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own
|
||||
imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in
|
||||
this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client` and
|
||||
`bworld/worldgen`:
|
||||
this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client`,
|
||||
`bworld/shared` and `bworld/worldgen`:
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "bworld/server";
|
||||
@@ -114,6 +116,7 @@ copper_tools.bmod
|
||||
scripts/server.js # each script bundled into one module
|
||||
scripts/client.js
|
||||
scripts/worldgen.js
|
||||
scripts/shared.js
|
||||
textures/<name>.png
|
||||
credits.md
|
||||
```
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"credits": "CREDITS.md",
|
||||
"scripts": {
|
||||
"server": "scripts/server.ts",
|
||||
"client": "scripts/client.ts"
|
||||
"client": "scripts/client.ts",
|
||||
"shared": "scripts/shared.ts"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ export function setup(ctx: ServerContext) {
|
||||
register_storage(ctx);
|
||||
register_furnace(ctx);
|
||||
register_smithing_table(ctx);
|
||||
register_fence(ctx);
|
||||
register_trapdoor(ctx);
|
||||
register_farming(ctx);
|
||||
register_fishing(ctx);
|
||||
@@ -30,50 +29,9 @@ function register_hoeable(ctx: ServerContext) {
|
||||
});
|
||||
}
|
||||
|
||||
// the sides a fence connects on, and the face of the block there it connects to
|
||||
const FENCE_SIDES = [
|
||||
{ state: "north", dx: 0, dz: -1, face: "south" },
|
||||
{ state: "east", dx: 1, dz: 0, face: "west" },
|
||||
{ state: "south", dx: 0, dz: 1, face: "north" },
|
||||
{ state: "west", dx: -1, dz: 0, face: "east" },
|
||||
] as const;
|
||||
|
||||
// a fence joins the fences beside it and the full sides of solid blocks, like minecraft's FenceBlock.connectsTo.
|
||||
// "connects_to" is the tag of fences it joins, so wooden fences don't join other kinds. leaves are full blocks but
|
||||
// fences don't join them, like minecraft
|
||||
function register_fence(ctx: ServerContext) {
|
||||
const connect = (block: BlockRef, params: { connects_to: string }) => {
|
||||
for (const side of FENCE_SIDES) {
|
||||
const [x, y, z] = [block.x + side.dx, block.y, block.z + side.dz];
|
||||
const id = ctx.world.get_block(x, y, z);
|
||||
const joins = id !== undefined && (
|
||||
ctx.tags.has("blocks", params.connects_to, id) ||
|
||||
(!ctx.tags.has("blocks", "bworld:leaves", id) && ctx.world.is_face_sturdy(x, y, z, side.face))
|
||||
);
|
||||
ctx.world.set_state(block.x, block.y, block.z, side.state, joins ? 1 : 0);
|
||||
}
|
||||
};
|
||||
ctx.components.register_block<{ connects_to: string }>("bworld:fence", {
|
||||
on_create: connect,
|
||||
on_neighbor_change: connect,
|
||||
});
|
||||
}
|
||||
|
||||
// the facing state's values, the way a block's y turns it
|
||||
const FACINGS = ["north", "east", "south", "west"];
|
||||
|
||||
// a trapdoor opens and closes when right clicked, like a wooden one in minecraft. placed against the side of a block
|
||||
// it hangs from that block, in the half of the side that was clicked. placed on top of a block it lies in the bottom
|
||||
// half, and under one in the top half, swinging open away from the player, like minecraft's TrapDoorBlock
|
||||
// a trapdoor opens and closes when right clicked, like a wooden one in minecraft. how it's placed is in shared.ts
|
||||
function register_trapdoor(ctx: ServerContext) {
|
||||
ctx.components.register_block("bworld:trapdoor", {
|
||||
state_for_placement(placement): Record<string, number> {
|
||||
if (placement.face !== "top" && placement.face !== "bottom") {
|
||||
return { facing: FACINGS.indexOf(placement.face), half: placement.hit[1] > 0.5 ? 1 : 0 };
|
||||
}
|
||||
// facing already faces the player
|
||||
return { half: placement.face === "top" ? 0 : 1 };
|
||||
},
|
||||
on_interact(block) {
|
||||
const open = ctx.world.get_state(block.x, block.y, block.z, "open") ?? 0;
|
||||
ctx.world.set_state(block.x, block.y, block.z, "open", open ? 0 : 1);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// the base game's block rules: how blocks are placed and how they change with the blocks beside them. they run on the
|
||||
// server and on every client, so players see a fence join or a trapdoor turn the moment they place it
|
||||
import type { SharedBlock, SharedContext } from "bworld/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
register_fence(ctx);
|
||||
register_trapdoor(ctx);
|
||||
}
|
||||
|
||||
// the sides a fence connects on, and the face of the block there it connects to
|
||||
const FENCE_SIDES = [
|
||||
{ state: "north", dx: 0, dz: -1, face: "south" },
|
||||
{ state: "east", dx: 1, dz: 0, face: "west" },
|
||||
{ state: "south", dx: 0, dz: 1, face: "north" },
|
||||
{ state: "west", dx: -1, dz: 0, face: "east" },
|
||||
] as const;
|
||||
|
||||
// a fence joins the fences beside it and the full sides of solid blocks, like minecraft's FenceBlock.connectsTo.
|
||||
// "connects_to" is the tag of fences it joins, so wooden fences don't join other kinds. leaves are full blocks but
|
||||
// fences don't join them, like minecraft
|
||||
function register_fence(ctx: SharedContext) {
|
||||
const sides = (x: number, y: number, z: number, params: { connects_to: string }) => {
|
||||
const states: Record<string, number> = {};
|
||||
for (const side of FENCE_SIDES) {
|
||||
const [nx, nz] = [x + side.dx, z + side.dz];
|
||||
const id = ctx.world.get_block(nx, y, nz);
|
||||
const joins = id !== undefined && (
|
||||
ctx.tags.has("blocks", params.connects_to, id) ||
|
||||
(!ctx.tags.has("blocks", "bworld:leaves", id) && ctx.world.is_face_sturdy(nx, y, nz, side.face))
|
||||
);
|
||||
states[side.state] = joins ? 1 : 0;
|
||||
}
|
||||
return states;
|
||||
};
|
||||
ctx.components.register_block<{ connects_to: string }>("bworld:fence", {
|
||||
state_for_placement: (placement, params) => sides(placement.x, placement.y, placement.z, params),
|
||||
on_neighbor_change(block: SharedBlock, params) {
|
||||
for (const [state, value] of Object.entries(sides(block.x, block.y, block.z, params))) {
|
||||
ctx.world.set_state(block.x, block.y, block.z, state, value);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// the facing state's values, the way a block's y turns it
|
||||
const FACINGS = ["north", "east", "south", "west"];
|
||||
|
||||
// placed against the side of a block, a trapdoor hangs from that block, in the half of the side that was clicked.
|
||||
// placed on top of a block it lies in the bottom half, and under one in the top half, swinging open away from the
|
||||
// player, like minecraft's TrapDoorBlock
|
||||
function register_trapdoor(ctx: SharedContext) {
|
||||
ctx.components.register_block("bworld:trapdoor", {
|
||||
state_for_placement(placement): Record<string, number> {
|
||||
if (placement.face !== "top" && placement.face !== "bottom") {
|
||||
return { facing: FACINGS.indexOf(placement.face), half: placement.hit[1] > 0.5 ? 1 : 0 };
|
||||
}
|
||||
// facing already faces the player
|
||||
return { half: placement.face === "top" ? 0 : 1 };
|
||||
},
|
||||
});
|
||||
}
|
||||
+10
-75
@@ -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;
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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),
|
||||
|
||||
+2
-1
@@ -43,7 +43,7 @@ Deno.test("packing a mod keeps its data, scripts, textures and credits, and give
|
||||
|
||||
const bworld = read_bmod(Deno.readFileSync(`${folder}/bworld.bmod`), "bworld.bmod");
|
||||
assertEquals(bworld.data.blocks.length, [...Deno.readDirSync("mods/bworld/blocks")].length);
|
||||
assertEquals(Object.keys(bworld.scripts), ["server", "client"]);
|
||||
assertEquals(Object.keys(bworld.scripts), ["server", "client", "shared"]);
|
||||
|
||||
Deno.removeSync(sources, { recursive: true });
|
||||
Deno.removeSync(folder, { recursive: true });
|
||||
@@ -115,6 +115,7 @@ Deno.test("the server loads every .bmod in its folder, dependencies first, and p
|
||||
const copy = read_bmod(mod.client_bytes, mod.listing.file);
|
||||
assertEquals(copy.scripts.server, undefined, "server scripts never go to players");
|
||||
assertEquals(copy.scripts.worldgen, undefined, "players get the world from the server, not its generator");
|
||||
assertEquals(copy.scripts.shared, mod.bmod.scripts.shared, "players run the shared rules too");
|
||||
assertEquals(copy.data, mod.bmod.data);
|
||||
}
|
||||
assert(mods[1].bmod.scripts.server, "the server still has it");
|
||||
|
||||
@@ -40,6 +40,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
|
||||
},
|
||||
server_url: url(scripts.server),
|
||||
worldgen_url: url(scripts.worldgen),
|
||||
shared_url: url(scripts.shared),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// shared scripts' block rules run on clients too, so what a client shows the moment it places or breaks a block is
|
||||
// what the server ends up with
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import { collision_shape_at, covers_face } from "$/common/block_shapes.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import type { Face, SharedWorld } from "$/common/mod_api/shared.ts";
|
||||
import { setup as setup_shared } from "$/mods/bworld/scripts/shared.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
type Game = Awaited<ReturnType<typeof test_game>>;
|
||||
const AREA = { x: [-3, 3], y: [99, 101], z: [-3, 3] };
|
||||
|
||||
// every block in the area, as id and state bits
|
||||
function blocks_in(get: (x: number, y: number, z: number) => [string, number]) {
|
||||
const out: string[] = [];
|
||||
for (let x = AREA.x[0]; x <= AREA.x[1]; x++) {
|
||||
for (let y = AREA.y[0]; y <= AREA.y[1]; y++) {
|
||||
for (let z = AREA.z[0]; z <= AREA.z[1]; z++) out.push(`${x} ${y} ${z} ${get(x, y, z).join(" ")}`);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function state(t: Game, x: number, y: number, z: number, name: string) {
|
||||
return get_state_value(t.game.world.get_block_value(x, y, z), t.game.world.get_block_info(x, y, z)!, name);
|
||||
}
|
||||
|
||||
function server_blocks(t: Game) {
|
||||
return blocks_in((x, y, z) => [t.game.world.get_block_id(x, y, z), t.game.world.get_block_value(x, y, z) >>> 16]);
|
||||
}
|
||||
|
||||
// a client: its copy of the area, and the bworld shared script's rules running on it the way client/mods.ts does
|
||||
function client_of(t: Game) {
|
||||
const copy = new Map<string, [string, number]>();
|
||||
for (const line of server_blocks(t)) {
|
||||
const [x, y, z, id, state] = line.split(" ");
|
||||
copy.set(`${x} ${y} ${z}`, [id, Number(state)]);
|
||||
}
|
||||
const at = (x: number, y: number, z: number) => copy.get(`${x} ${y} ${z}`);
|
||||
const info = (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
|
||||
const rules = new BlockRules((_mod, _what, fn) => fn());
|
||||
const world: SharedWorld = {
|
||||
get_block: (x, y, z) => at(x, y, z)?.[0],
|
||||
get_state(x, y, z, name) {
|
||||
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
||||
const block = info(id);
|
||||
return block?.states?.some((s) => s.name === name) ? get_state_value(state << 16, block, name) : undefined;
|
||||
},
|
||||
set_state(x, y, z, name, value) {
|
||||
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
||||
const block = info(id);
|
||||
if (!block?.states?.some((s) => s.name === name)) return false;
|
||||
const changed = set_state_value(state << 16, block, name, value)! >>> 16;
|
||||
if (changed !== state) {
|
||||
copy.set(`${x} ${y} ${z}`, [id, changed]);
|
||||
rules.notify_neighbors(world.get_block, x, y, z);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
is_face_sturdy(x, y, z, face: Face) {
|
||||
const [id, state] = at(x, y, z) ?? [AIR_ID, 0];
|
||||
const block = info(id);
|
||||
return block !== undefined && covers_face(collision_shape_at(block, state << 16), face);
|
||||
},
|
||||
};
|
||||
setup_shared({
|
||||
mod: { id: "bworld", version: "test" },
|
||||
side: "client",
|
||||
tags: tag_api(),
|
||||
world,
|
||||
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
|
||||
});
|
||||
|
||||
return {
|
||||
// what game_mode does when this client places held against face of x y z, at hit
|
||||
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
||||
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit });
|
||||
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
|
||||
rules.notify_neighbors(world.get_block, x, y, z);
|
||||
},
|
||||
break(x: number, y: number, z: number) {
|
||||
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
|
||||
rules.notify_neighbors(world.get_block, x, y, z);
|
||||
},
|
||||
blocks: () => blocks_in((x, y, z) => at(x, y, z)!),
|
||||
};
|
||||
}
|
||||
|
||||
// alice on a stone floor at y 99, south of 0 100 0, holding id
|
||||
async function setup(id: string, yaw = 0) {
|
||||
const t = await test_game("mods");
|
||||
t.join(1, "alice");
|
||||
for (let x = AREA.x[0]; x <= AREA.x[1]; x++) {
|
||||
for (let z = AREA.z[0]; z <= AREA.z[1]; z++) {
|
||||
t.game.set_block(x, 99, z, "bworld:stone");
|
||||
for (let y = 100; y <= AREA.y[1]; y++) t.game.set_block(x, y, z, AIR_ID);
|
||||
}
|
||||
}
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw, pitch: 0 });
|
||||
t.send(1, { type: "chat", text: `/give ${id} 64` });
|
||||
t.send(1, { type: "select_slot", slot: 0 });
|
||||
const use = (x: number, y: number, z: number, face: Face, hit: [number, number, number]) =>
|
||||
t.send(1, { type: "use_block", x, y, z, face, hit });
|
||||
return { t, use };
|
||||
}
|
||||
|
||||
Deno.test("a client places a fence joined to the fences and walls beside it, the same as the server", async () => {
|
||||
const { t, use } = await setup("bworld:oak_fence");
|
||||
t.game.set_block(-1, 100, 0, "bworld:oak_fence");
|
||||
t.game.set_block(0, 100, -1, "bworld:stone");
|
||||
t.game.set_block(1, 100, 0, "bworld:leaves");
|
||||
const client = client_of(t);
|
||||
|
||||
client.place("bworld:oak_fence", 0, 100, 0, 0, "top", [0.5, 1, 0.5]);
|
||||
use(0, 99, 0, "top", [0.5, 1, 0.5]);
|
||||
assertEquals(client.blocks(), server_blocks(t));
|
||||
// it joined the fence and the stone, and the fence joined it back
|
||||
assertEquals(state(t, 0, 100, 0, "west"), 1);
|
||||
assertEquals(state(t, 0, 100, 0, "north"), 1);
|
||||
assertEquals(state(t, -1, 100, 0, "east"), 1);
|
||||
|
||||
// breaking it lets go of the one beside it, on both
|
||||
client.break(0, 100, 0);
|
||||
t.send(1, { type: "break_block", x: 0, y: 100, z: 0 });
|
||||
assertEquals(client.blocks(), server_blocks(t));
|
||||
assertEquals(state(t, -1, 100, 0, "east"), 0);
|
||||
});
|
||||
|
||||
Deno.test("a client places a trapdoor turned and in the half the server puts it", async () => {
|
||||
const { t, use } = await setup("bworld:oak_trapdoor", Math.PI / 2);
|
||||
t.game.set_block(0, 100, 0, "bworld:stone");
|
||||
const client = client_of(t);
|
||||
|
||||
// on the upper half of the stone's east side, and on top of the floor facing alice, who looks west
|
||||
client.place("bworld:oak_trapdoor", 1, 100, 0, Math.PI / 2, "east", [1, 0.8, 0.5]);
|
||||
use(0, 100, 0, "east", [1, 0.8, 0.5]);
|
||||
client.place("bworld:oak_trapdoor", 0, 100, 2, Math.PI / 2, "top", [0.5, 1, 0.5]);
|
||||
use(0, 99, 2, "top", [0.5, 1, 0.5]);
|
||||
assertEquals(client.blocks(), server_blocks(t));
|
||||
assertEquals(state(t, 1, 100, 0, "half"), 1);
|
||||
assertEquals(state(t, 0, 100, 2, "facing"), 1);
|
||||
});
|
||||
+7
-2
@@ -6,8 +6,13 @@ import { type Bmod, BMOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_bmod }
|
||||
import type { ManifestJson } from "$/common/mod_data.ts";
|
||||
import { load_and_check, type LoadedMod } from "./check_mods.ts";
|
||||
|
||||
// what each script is bundled for: the server runs in deno, clients in browsers, worldgen in both
|
||||
const PLATFORMS: Record<ScriptSide, "deno" | "browser"> = { server: "deno", client: "browser", worldgen: "browser" };
|
||||
// what each script is bundled for: the server runs in deno, clients in browsers, worldgen and shared in both
|
||||
const PLATFORMS: Record<ScriptSide, "deno" | "browser"> = {
|
||||
server: "deno",
|
||||
client: "browser",
|
||||
worldgen: "browser",
|
||||
shared: "browser",
|
||||
};
|
||||
|
||||
// a mod that passed check-mods, as .bmod bytes
|
||||
export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>> {
|
||||
|
||||
Reference in New Issue
Block a user