Compare commits

...
14 Commits
Author SHA1 Message Date
paula 31ae2973d7 Finish verdigris for now 2026-10-22 20:07:00 -03:00
paula 4cd29a17b3 Repeater 2026-10-22 19:55:59 -03:00
paula 1b30d71a47 Doors working with verdigris 2026-10-22 17:02:14 -03:00
paula 20e6ac6fbb Verdigris torch 2026-10-22 16:31:09 -03:00
paula db0589d965 Verdigris working ! 2026-10-22 15:51:40 -03:00
paula 6af6c52673 Verdigris wire and lever 2026-10-22 13:43:57 -03:00
paula 0d80e85dec Verdigris wire model 2026-10-22 12:57:05 -03:00
paula b5777c84d3 Verdigris textures 2026-10-21 15:08:28 -03:00
paula 0bc66c21b9 ctx.blocks.solid(id) api 2026-10-20 14:22:11 -03:00
paula 987e7a0f9a Real ctx.world.is_loaded implementation 2026-10-20 14:00:21 -03:00
paula 2c1eaf5735 Fix tags test 2026-10-20 13:53:53 -03:00
paula 1c2dcd0dbc Scheduled ticks !! 2026-10-20 13:50:35 -03:00
paula 77cd327f94 Neighbor Updates as a Queue 2026-10-20 13:40:44 -03:00
paula 0af35d1e17 New hooks 2026-10-20 13:22:03 -03:00
108 changed files with 6456 additions and 376 deletions
+5 -3
View File
@@ -307,7 +307,9 @@ crushing, fan processing, steam, fluid splashes. Optional for gameplay, so it ca
**R10. In-world text and boxes** (P3). Create's value boxes (the number on a scroll value, filter slots on a block's
side) and goggles' overlay. A small API for drawing a label or an item at a point in the world, and a HUD element API,
which is in bworld's types but throws today.
which is in bworld's types but throws today. Setting a scroll value is built, the way 0.5.0.j does it: a block with
`"scrollable": true` gets the mouse wheel as `on_scroll`, and `send_message(text, { overlay: true })` shows the value
above the hotbar until the box can show it (see [Scrolling](docs/modding/blocks/components.md#scrolling)).
**R11. 3D in GUIs** (P3). Drawing a model or block in a screen, turned and animated, for the recipe viewer's Create
categories (a press pressing over its recipe, like `compat/jei`), goggles and ponder.
@@ -581,8 +583,8 @@ Check: a steam engine on a tank boiler, fed by a pump from water and heated by b
- S3, in `mods/bworld` first.
- Redstone link, nixie tube, display link and display board, threshold switch, smart observer, analog lever, pulse
repeater, extender and timer, powered latch and toggle latch, contact, desk bell, sequenced gearshift. Clutch and
gearshift switch to real signals.
extender and timer, powered latch and toggle latch, contact, desk bell, sequenced gearshift. The pulse repeater is
bworld's now. Clutch and gearshift switch to real signals.
Check: a factory that stops when a vault is full and shows its count on a display board.
+1
View File
@@ -40,6 +40,7 @@ deno task build && deno task server # packs the mods and starts a se
show items
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns
- [Crops](docs/modding/blocks/crops.md): farming without writing code
- [Verdigris](docs/modding/blocks/verdigris.md): blocks that make and use signals, like levers, torches and doors
**Items**
+7 -2
View File
@@ -25,7 +25,7 @@ import { back_to_title } from "./gui/title_screen.ts";
import { TICK_DELTA } from "$/common/constants.ts";
import { Container } from "$/common/inventory.ts";
import { PLAYER_MENU } from "$/common/protocol.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityJson } from "$/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
@@ -365,7 +365,12 @@ export class Client {
const previous = inventories.hotbar_selected;
const scroll = InputManager.get_wheel_delta();
if (scroll > 0) {
// at a block that takes the mouse wheel, like a pulse repeater's delay, it goes to the block instead
const hit = this.hit_result;
if (scroll !== 0 && hit && EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)?.scrollable) {
const { x, y, z, face } = hit;
this.connection.send({ type: "scroll_block", x, y, z, face, hit: hit.hit, amount: scroll < 0 ? 1 : -1 });
} else if (scroll > 0) {
inventories.hotbar_selected = Math.min(8, inventories.hotbar_selected + 1);
} else if (scroll < 0) {
inventories.hotbar_selected = Math.max(0, inventories.hotbar_selected - 1);
+30 -6
View File
@@ -33,6 +33,10 @@ const AIR_ROW_SPACING = 10;
const HELD_NAME_MS = 2000;
const HELD_NAME_FADE_MS = 500;
const HELD_NAME_GAP = 12;
// a server's overlay message, see MessageOptions.overlay: above the held item's name, for as long as minecraft's
const OVERLAY_MS = 3000;
const OVERLAY_FADE_MS = 500;
const OVERLAY_GAP = 4;
const CROSSHAIR_SIZE = 15;
// under the crosshair so it shows on bright sky and snow, minecraft inverts the colors behind it instead
const CROSSHAIR_SHADOW: [number, number, number, number] = [0, 0, 0, 0.4];
@@ -53,12 +57,21 @@ export class Hud {
// what was held last frame, as slot and item id, and when the held item last changed
#held = "";
#held_since = -Infinity;
#overlay = "";
#overlay_since = -Infinity;
// shows text above the hotbar for a moment, see MessageOptions.overlay
show_overlay(text: string) {
this.#overlay = text;
this.#overlay_since = performance.now();
}
render(client: Client) {
this.#render_hotbar(client.player.inventories);
this.#render_vitals(client);
const top = Math.min(icons_y() - heart_rows_height(client.player.max_health), air_y(client.player));
this.#render_held_name(client.player.inventories, top);
this.#render_overlay(top);
this.#render_crosshair(client);
this.#render_info(client);
client.chat.render(false, top - HELD_NAME_GAP);
@@ -97,12 +110,16 @@ export class Hud {
return;
}
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
const name = display_name(item.type_id);
const x = (canvas.width - measure_text(name, TEXT_SCALE)) / 2;
const y = top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
// a shadow so it reads over bright sky and snow
draw_text(name, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
draw_text(name, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
draw_centered(display_name(item.type_id), top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE, alpha);
}
// top is the top of the hearts, like for the held item's name, which it goes above
#render_overlay(top: number) {
const shown_for = performance.now() - this.#overlay_since;
if (shown_for > OVERLAY_MS) return;
const alpha = Math.min(1, (OVERLAY_MS - shown_for) / OVERLAY_FADE_MS);
const y = top - HELD_NAME_GAP - OVERLAY_GAP * GUI_SCALE - TEXT_HEIGHT * TEXT_SCALE * 2;
draw_centered(this.#overlay, y, alpha);
}
// hearts on the left and hunger on the right like minecraft, each icon 2 points. saturation is appleskin's outline
@@ -193,6 +210,13 @@ export class Hud {
}
}
// text across the middle of the screen at y, with a shadow so it reads over bright sky and snow
function draw_centered(text: string, y: number, alpha: number) {
const x = (canvas.width - measure_text(text, TEXT_SCALE)) / 2;
draw_text(text, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
draw_text(text, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
}
function hotbar_position() {
return {
x: Math.round((canvas.width - HOTBAR_WIDTH * GUI_SCALE) / 2),
+26 -20
View File
@@ -10,7 +10,7 @@ import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/commo
import { type Bmod, read_bmod } from "$/common/bmod.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 { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } 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";
@@ -50,23 +50,6 @@ 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;
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
// which blocks have them when the level starts
let client_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) {
@@ -105,10 +88,27 @@ const rules_world: SharedWorld = {
},
};
// 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, rules_world.get_block);
// whether shared scripts are being set up, the only time they can register rules
let rules_setup = false;
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
// which blocks have them when the level starts
let client_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;
}
}
// 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);
block_rules.notify_neighbors(x, y, z);
}
// the loaded mods' recipes, and their names by id
@@ -162,7 +162,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
loading_mod(bmod.manifest.id, bmod.manifest.engine_access ?? false, fn);
// every mod's shared rules first, so client scripts can count on any mod's being there
block_rules = new BlockRules(run_mod);
block_rules = new BlockRules(run_mod, rules_world.get_block);
rules_setup = true;
for (const [i, bmod] of bmods.entries()) {
const code = bmod.scripts.shared;
@@ -205,6 +205,12 @@ function blocks_api(mod: string): SharedContext["blocks"] {
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
return structuredClone(block.components ?? {});
},
solid(id) {
if (id === AIR_ID) return false;
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
return is_solid(block);
},
};
}
+2 -1
View File
@@ -223,7 +223,8 @@ export class ClientPacketListener {
level.set_center(message.x, message.z);
break;
case "chat":
client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
if (message.overlay) client.game_renderer.hud.show_overlay(message.text);
else client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
break;
case "suggestions":
if (client.screen instanceof GuiChat) {
+87 -17
View File
@@ -4,7 +4,15 @@
// 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, SharedWorld } from "./mod_api/shared.ts";
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";
@@ -42,11 +50,25 @@ export function default_placement_value(block: BlockRegistry, yaw: number): numb
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<string, { mod: string; rules: Rules }>();
// 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;
// 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) {}
// 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: <T>(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`);
@@ -123,20 +145,68 @@ export class BlockRules {
return handled;
}
// 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));
}
// 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<T>(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<BlockRegistry>("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);
}
}
+37
View File
@@ -6,6 +6,7 @@
// (getCollisionShape). blocks get theirs from the boxes of their model, or set "shape" like minecraft's Block.box
import {
block_parts,
DEFAULT_MODEL,
element_rotation,
find_model,
looks_by_state,
@@ -219,6 +220,42 @@ export function covers_face(shape: Shape, face: "west" | "east" | "bottom" | "to
return true;
}
// whether the block is solid like stone: drawn in the solid layer, and a whole block to bump into in every state. it's
// what passes signals on, see BlockApi.solid. glass, leaves, slabs and chests aren't. worked out once per block from
// every collision shape, shape and model its variants can give it, so one that no state shows counts too. blocks made
// of parts aren't
export function is_solid(block: BlockRegistry): boolean {
let solid = solid_cache.get(block);
if (solid === undefined) {
solid = whole_in_every_state(block);
solid_cache.set(block, solid);
}
return solid;
}
const solid_cache = new WeakMap<BlockRegistry, boolean>();
function whole_in_every_state(block: BlockRegistry) {
if ((block.render_layer ?? "solid") !== "solid" || !block.has_collision || block.parts) return false;
const looks = [block, ...Object.values(block.variants ?? {})];
const whole = (shape: Shape) =>
shape.some((box) => [0, 1, 2].every((axis) => box[axis] <= FLAT && box[axis + 3] >= 1 - FLAT));
// a state bumps into its collision_shape, or its shape, or its model's boxes, the first it has. the block's own is
// there in every state its variants don't set one, so what comes after it never shows
if (!looks.every((look) => !look.collision_shape || whole(pixel_shape(look.collision_shape, 0, COLLISION_TOP)))) {
return false;
}
if (block.collision_shape) return true;
if (!looks.every((look) => !look.shape || whole(pixel_shape(look.shape)))) return false;
if (block.shape) return true;
const models = Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
return looks.every((look) => {
const model = find_model(look.model ?? block.model ?? DEFAULT_MODEL, models);
// drawn as a cube when its model is missing, see block_shape
return !model || whole(model_shape(model));
});
}
function clamp(box: number[], top = 1): Box {
const c = box.map((v, i) => Math.min(Math.max(v, 0), i % 3 === 1 ? top : 1));
return [c[0], c[1], c[2], c[3], c[4], c[5]];
+2
View File
@@ -145,6 +145,8 @@ export interface BlockRegistry {
// right clicking it does something instead of placing a block, clients don't predict placing against it.
// behavior runs on the server, see server/game/blocks.ts
interactive?: boolean;
// the mouse wheel turned while looking at it goes to its components' on_scroll instead of the hotbar
scrollable?: boolean;
// placing a block into it replaces it, like water
replaceable?: boolean;
// the blocks (ids or #tags) it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when
+2
View File
@@ -56,6 +56,8 @@ export interface ClientContext {
// the components its json lists and their params, a copy, like the server's ctx.blocks.components. for showing
// what a component does, like what a crab pot catches
components(id: Id): Record<Id, unknown>;
// whether it's solid like stone, like the server's ctx.blocks.solid
solid(id: Id): boolean;
};
// the mods' loot table files (see docs/modding/resources/loot_tables.md), to show what they give. tables server
// scripts make with ctx.loot.register_table aren't here
+53 -3
View File
@@ -67,10 +67,22 @@ export interface BlockComponent<P = any> {
on_click?(block: BlockRef, params: P, player: Player): void;
// return true if it did something, so no block gets placed
on_interact?(block: BlockRef, params: P, player: Player): boolean;
// the player turned the mouse wheel while looking at it, for a block whose json has "scrollable": true, like a
// setting turned up and down. the wheel doesn't change their hotbar slot then
on_scroll?(block: BlockRef, params: P, player: Player, scroll: BlockScroll): void;
on_tick?(block: BlockRef, params: P, dt: number): void;
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 on one of its 6 sides was placed, broken or changed its states, like neoforge's neighborChanged. after
// the shared rules' on_neighbor_change, so it sees what they changed, and can do what rules can't: read tile data,
// change other blocks. neighbor is where, and what's there now
on_neighbor_change?(block: BlockRef, params: P, neighbor: { readonly id: Id } & Position): void;
// its own states changed without it being replaced, by set_state or a rule, like a clutch another mod powers.
// before is what they were. it runs right away, before the blocks beside it hear of the change
on_state_change?(block: BlockRef, params: P, before: Readonly<Record<string, number>>): void;
// the tick ServerWorld.schedule_tick asked for came, like neoforge's tick from scheduleTick
on_scheduled_tick?(block: BlockRef, params: P): void;
// placing and neighbor rules are in shared scripts, see BlockRules in bworld/shared
}
@@ -232,7 +244,8 @@ export interface ServerAfterEvents {
// world and players
export interface ServerWorld {
get_block(x: number, y: number, z: number): Id | undefined; // undefined when the chunk isn't loaded
// generates the chunk if it never was, which takes a while, see is_loaded
get_block(x: number, y: number, z: number): Id | undefined;
set_block(x: number, y: number, z: number, id: Id): boolean; // runs on_break / on_create, synced to everyone
// like breaking it by hand without a tool: on_break, then its drops, which it returns (copies). undefined when there
// was nothing to break. see BreakOptions for machines breaking it
@@ -241,7 +254,19 @@ export interface ServerWorld {
// destroyBlockProgress: a drill getting through it. undefined takes them off, and so does the block changing
set_break_progress(x: number, y: number, z: number, progress: number | undefined): void;
get_state(x: number, y: number, z: number, name: string): number | undefined;
set_state(x: number, y: number, z: number, name: string, value: number): boolean;
// update_neighbors false changes the state without telling the blocks around it, for a script that tells them
// itself, like a wire telling each block beside its whole length once. on_state_change still runs
set_state(x: number, y: number, z: number, name: string, value: number, options?: SetStateOptions): boolean;
// tells the block at x y z that the one at from changed, running its rules' and components' on_neighbor_change,
// like neoforge's neighborChanged. for a block whose effect on others changed without it changing, or for blocks
// it reaches that aren't beside it. it hears once the change going on is done, like the blocks beside one do
neighbor_changed(x: number, y: number, z: number, from: Position): void;
// runs the block's components' on_scheduled_tick in delay ticks (at least 1), if the same kind of block is still
// there, like neoforge's scheduleTick. one per block: scheduling while one waits does nothing. of those due on the
// same tick, lower priority (-8 to 7, 0 when not given) runs first, then the order they were scheduled in. saved
// with the world. they only run within 6 chunks of a player, the rest wait until one comes near
schedule_tick(x: number, y: number, z: number, delay: number, priority?: number): void;
has_scheduled_tick(x: number, y: number, z: 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;
@@ -279,6 +304,8 @@ export interface ServerWorld {
// which way the liquid at x y z flows, a vector 1 long, or 0 0 0 where it's still or there's none, like minecraft's
// FluidState.getFlow: toward lower cells of it beside it, and down where it falls. for what it pushes, like a wheel
liquid_flow(x: number, y: number, z: number): Position;
// whether the chunk the column is in was ever generated, so reading its blocks generates nothing. for code that
// reaches far, like a walk along something long, which can stop at the rest: nobody has built anything there
is_loaded(x: number, z: number): boolean;
// the column's biome, like "bworld:plains", and that biome's season. in chunks that aren't loaded it's what
// generation makes there, which takes a while the first time
@@ -294,6 +321,26 @@ export interface ServerWorld {
set_time(time: number): void;
}
// the mouse wheel turned at a block, see BlockComponent.on_scroll
export interface BlockScroll {
// how many notches, more than 0 turned up and less than 0 down
readonly amount: number;
readonly face: Face;
// where on the block they look, 0 to 1 on each axis, like BlockInteraction's
readonly hit: readonly [number, number, number];
}
export interface MessageOptions {
// shows it above their hotbar for a moment instead of in chat, like neoforge's overlay messages. for something
// that changes as they do it, like a setting they're scrolling through
overlay?: boolean;
}
export interface SetStateOptions {
// true when not given
update_neighbors?: boolean;
}
// how a machine breaks a block, see ServerWorld.break_block
export interface BreakOptions {
// it drops what it would for the right tool, though nothing holds one, like create's drills and saws
@@ -360,7 +407,7 @@ export interface Player {
readonly held_item: ItemStack | undefined;
// what doesn't fit in the inventory drops at their feet
give_item(id: Id, count?: number, data?: unknown): void;
send_message(text: string): void;
send_message(text: string, options?: MessageOptions): void;
// items drawn on them, under a key so each mod keeps its own list, like "bworld:curios". replaces what that key
// had, [] clears it. only items whose json has worn show. not saved: set it again when they join
set_worn(key: string, items: ItemStack[]): void;
@@ -482,6 +529,9 @@ export interface BlockApi {
toughness(id: Id): number;
// the components its json lists and their params, a copy, like ItemApi.components
components(id: Id): Record<Id, unknown>;
// whether it's solid like stone: drawn in the solid layer, and a whole block to bump into in every state. glass,
// leaves, slabs and chests aren't. what passes signals on, and what wire turns corners around. false for air
solid(id: Id): boolean;
}
export interface RecipeApi {
+2
View File
@@ -72,6 +72,8 @@ export interface SharedContext {
exists(id: Id): boolean;
// the components its json lists and their params, a copy
components(id: Id): Record<Id, unknown>;
// whether it's solid like stone, like the server's ctx.blocks.solid
solid(id: Id): boolean;
};
readonly components: {
// the rules of a block component, the same id the server script registers the rest of it under
+4 -1
View File
@@ -81,6 +81,7 @@ export interface BlockJson {
drops?: string;
item?: boolean;
interactive?: boolean;
scrollable?: boolean;
replaceable?: boolean;
place_on?: string[];
place_in?: string[];
@@ -320,6 +321,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (block.loot_table !== undefined) json.loot_table = block.loot_table;
if (!has_item) json.item = false;
if (block.interactive) json.interactive = true;
if (block.scrollable) json.scrollable = true;
if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable;
if (block.place_on) json.place_on = block.place_on;
if (block.place_in) json.place_in = block.place_in;
@@ -370,6 +372,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.drops !== undefined) block.drop_table = json.drops;
if (json.loot_table !== undefined) block.loot_table = json.loot_table;
if (json.interactive) block.interactive = true;
if (json.scrollable) block.scrollable = true;
if (json.replaceable ?? json.liquid) block.replaceable = true;
if (json.place_on) block.place_on = json.place_on;
if (json.place_in) block.place_in = json.place_in;
@@ -666,7 +669,7 @@ export function validate_block(json: unknown): Problems {
}
}
problems.push(...validate_text(json.name, "name"));
for (const key of ["cull_same", "transparent", "collision", "item", "interactive", "replaceable"]) {
for (const key of ["cull_same", "transparent", "collision", "item", "interactive", "scrollable", "replaceable"]) {
if (json[key] !== undefined && typeof json[key] !== "boolean") problems.push(`${key} must be true or false`);
}
if (json.tint !== undefined) {
+14 -2
View File
@@ -10,7 +10,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 23;
export const PROTOCOL_VERSION = 24;
export interface PlayerInfo {
id: string;
@@ -123,6 +123,17 @@ export type ClientMessage =
// right click on a block: interact with it, or place the held block against `face`. hit is where on the block it
// clicked, 0 to 1 on each axis, like minecraft's click location. seq is like break_block's
| { type: "use_block"; x: number; y: number; z: number; face: Faces; hit?: [number, number, number]; seq?: number }
// the mouse wheel turned while looking at a scrollable block, see BlockRegistry.scrollable. amount is how many
// notches, up above 0. face and hit are like use_block's
| {
type: "scroll_block";
x: number;
y: number;
z: number;
face: Faces;
hit: [number, number, number];
amount: number;
}
| { type: "select_slot"; slot: number }
// a slot of the open menu, or of menu 0 when none is. shift moves the stack to the other part of the menu instead,
// like minecraft's quick move. clicks for a menu that isn't open any more are ignored
@@ -224,7 +235,8 @@ export type ServerMessage =
// fields of a block's client data, see BlockRef.set_client_data. to the players who have the chunk: every field
// right after it, then each field when it changes. null when a field is gone, and every field when the block is
| { type: "block_data"; x: number; y: number; z: number; data: Record<string, unknown> }
| { type: "chat"; from?: string; text: string }
// overlay shows it above the hotbar for a moment instead of in chat, like how long a pulse repeater waits
| { type: "chat"; from?: string; text: string; overlay?: boolean }
// the player is here now. with motion, they're moving that fast (blocks per second) too: the server is moving them,
// like when knocked back, and the client keeps going that way until the next one. id counts up, see move
| { type: "teleport"; id: number; x: number; y: number; z: number; motion?: [number, number, number] }
+6 -3
View File
@@ -105,9 +105,12 @@ export function get_state_value(value: number, block_info: BlockRegistry, name:
// every state of a block value by name, like { age: 7 }
export function block_states(value: number, block_info: BlockRegistry): Record<string, number> {
return Object.fromEntries(
(block_info.states ?? []).map((s) => [s.name, get_state_value(value, block_info, s.name)!]),
);
if (!block_info.states) return {};
if (!block_info.compiled_states) compile_block_states(block_info);
const state_bits = value >>> STATE_SHIFT;
const states: Record<string, number> = {};
for (const s of block_info.compiled_states!) states[s.name] = (state_bits & s.mask) >>> s.shift;
return states;
}
export function set_state_value(value: number, block_info: BlockRegistry, name: string, new_value: number) {
+108 -10
View File
@@ -59,21 +59,70 @@ 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. See [Ticking](#ticking) for where. | |
| 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_scroll(block, params, player, scroll)` | A player turns the mouse wheel looking at it. See [Scrolling](#scrolling). | |
| `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. See [Ticking](#ticking) for where. | |
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. See [Changes](#changes). | |
| `on_state_change(block, params, before)` | Its own states change without it being replaced, by `set_state` or a rule. See [Changes](#changes). | |
| `on_scheduled_tick(block, params)` | A tick it asked for comes. See [Scheduled Ticks](#scheduled-ticks). | |
`block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the
block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome`
and `season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)) and `set_ticking` turns its
[ticking](#ticking) off and on. `params` is what the block's JSON lists for this component, and `dt` is in seconds.
### Changes
`on_neighbor_change` is the server's side of the [rule](#neighbors) with the same name, like NeoForge's
`neighborChanged`: `neighbor` is `{ x, y, z, id }` of the block that changed. It runs after the block's rules have had
their say, so it sees the states they set, and it can do what rules can't, like reading tile data or breaking the block
when what it hangs from is gone. A block whose states follow from its neighbors, like a fence, uses the rule instead, so
clients see it change right away.
`on_state_change` runs when the block's states change and it stays the same block: a script's `ctx.world.set_state`, a
rule, a liquid's level. `before` is every state as it was, by name, and `ctx.world.get_state` gives what they are now.
It's how a block reacts to a state something else sets on it, like a machine another mod's script turns off. It runs
right away, before the blocks beside it are told, like `on_create`. Replacing the block with `set_block` runs `on_break`
and `on_create` instead, and setting a state to what it already is runs nothing.
```ts
ctx.components.register_block("copper_tools:bell", {
on_state_change(block, _params, before) {
const rung = ctx.world.get_state(block.x, block.y, block.z, "rung");
if (rung === 1 && before.rung === 0) ring(block);
},
});
```
The blocks beside one that changed don't hear of it while the change is going on. They wait in a queue and hear in the
order they were told, once the change is done, along with the ones they set off. The world is settled again by the time
the outermost change returns, so a script that places a fence in `on_tick` sees it joined right after. One that places
it in `on_neighbor_change`, which runs while another change is settling, sees it joined once that's done. Blocks a
handler tells while its block is being broken, in `on_break`, hear once it's gone. A change can tell blocks 65,536 times
before it's stopped and the server logs where, so blocks that keep setting each other off can't hang the server.
Two more things in `ctx.world` are for blocks that tell others themselves:
- `ctx.world.neighbor_changed(x, y, z, from)` tells the block at `x y z` that the one at `from` changed, running its
rules' and components' `on_neighbor_change`, like NeoForge's `neighborChanged`. It's for a block whose effect on
others changed without it changing, or for blocks it reaches that aren't beside it, like the far end of something it's
joined to.
- `ctx.world.set_state(x, y, z, name, value, { update_neighbors: false })` changes a state without telling the blocks
around it, for a script that tells them itself, so a long line of blocks changing together tells each block beside it
once instead of once per block. `on_state_change` still runs.
Code that reaches far from a block, like a walk along something long, checks `ctx.world.is_loaded(x, z)` before it reads
a column: whether that column's chunk was ever generated. Reading a block anywhere else generates its chunk on the spot,
which takes a while, and nobody can have built anything there, so a walk stops at those chunks. A chunk that's saved but
not in memory counts as loaded, and reading it reads it from the save.
## Rules
A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're
@@ -103,13 +152,15 @@ Here `block` is `{ id, x, y, z }`, without tile data, which clients never have.
`get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see
[Seasons](../worldgen/biomes.md#seasons)), and only works inside rules. `ctx.blocks.components(id)` gives any block's
components and their params, like on the server, for rules that look at what's around them, like a shaft lining up with
the axle of the block it's placed against.
the axle of the block it's placed against, and `ctx.blocks.solid(id)` whether it's [solid](index.md#solid-blocks).
### Neighbors
`on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is
`{ x, y, z, id }` of the block that changed. A fence sets its `north`, `east`, `south` and `west` states from it.
Setting a state to what it already is changes nothing and tells no one, so blocks answering each other this way settle.
The blocks a change tells hear of it one after another, in the same order on the server and on clients, once the change
is done (see [Changes](#changes)).
`ctx.world.is_face_sturdy(x, y, z, face)` says whether a block's side is something to attach to, like Minecraft's
`isFaceSturdy`: its [collision shape](../resources/models.md#collision-shapes) covers the whole side. Stone's sides are,
@@ -164,6 +215,24 @@ on_interact(block) {
Give a block `"interactive": true` when right clicking it always does something, like opening a screen. Otherwise
clients guess that the click places the held block and show it for a moment before the server corrects them.
### Scrolling
A block whose JSON has `"scrollable": true` takes the mouse wheel: a player turning it while looking at the block, in
reach, runs its components' `on_scroll` on the server, and their hotbar slot stays where it is. It's for a setting that
goes up and down, like how long the pulse repeater waits. `scroll` is `{ amount, face, hit }`: how many notches, more
than 0 for up, and the face and point they look at, like `on_interact`'s. Clients don't guess what it does, so keep what
it changes in states or [client data](tiledata.md#client-data) for them to see, and show the new value with
`player.send_message(text, { overlay: true })`, which puts it above their hotbar for a moment. The pulse repeater's is
in `mods/bworld/scripts/verdigris/devices.ts`:
```ts
on_scroll(block, _params, player, scroll) {
const delay = Math.max(0, Math.min(PULSE_DELAYS.length - 1, state(block, "delay") + scroll.amount));
set(block, "delay", delay);
player.send_message(`Delay: ${delay_text(PULSE_DELAYS[delay])}`, { overlay: true });
},
```
### Ticking
`on_tick` and `on_second` only run for blocks that **have tile data**, within 6 chunks of a player. So a component that
@@ -191,6 +260,35 @@ of a player, like the blocks Minecraft random ticks. Blocks one of them places t
block taller, wait for the next one. When time jumps forward past several mornings, like with `/time add`, each of them
runs, up to the last 64.
### Scheduled Ticks
A block that needs to do something a few ticks from now, like a button popping back out or a signal passing on after a
delay, asks for a tick instead of ticking all the time, like NeoForge's `scheduleTick`. It costs nothing while it waits,
and the block needs no tile data:
```ts
ctx.components.register_block("copper_tools:button", {
on_interact(block) {
ctx.world.set_state(block.x, block.y, block.z, "pressed", 1);
ctx.world.schedule_tick(block.x, block.y, block.z, 20);
return true;
},
on_scheduled_tick(block) {
ctx.world.set_state(block.x, block.y, block.z, "pressed", 0);
},
});
```
`ctx.world.schedule_tick(x, y, z, delay, priority?)` runs the block's `on_scheduled_tick` in `delay` ticks, at least 1.
A block has one at a time: scheduling while one waits does nothing, and `ctx.world.has_scheduled_tick(x, y, z)` says
whether one does. Its own `on_scheduled_tick` can schedule the next one, like a clock. Of the ticks due on the same
tick, the lower `priority` runs first, from -8 to 7 and 0 when not given, then the one scheduled first. If another kind
of block has taken its place by then, the tick is dropped.
Scheduled ticks run within 6 chunks of a player, like `on_tick`. Farther away they wait, and run as soon as a player
comes near. They're saved with the world, with how many ticks each had left, so they pick up where they were. At most
65,536 run in one tick, and the rest run first in the next.
The server runs a fixed 20 ticks a second. When a tick takes too long, up to ten of the next ones run back to back to
catch up. If it's further behind than that, it skips the rest and logs a warning. `/tps` shows how it's keeping up.
+9
View File
@@ -64,6 +64,7 @@ there will be holes in the world behind them.
| `loot_table` | none | A [loot table](../resources/loot_tables.md) it drops from when broken instead, with its states and the tool. Not with `drops`. |
| `item` | `true` | Also register an item that places it, with the same id. To give that item more, see [Block Items](../items/index.md#block-items). |
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
| `scrollable` | `false` | The mouse wheel turned while looking at it goes to its components' `on_scroll` instead of the hotbar, see [Scrolling](components.md#scrolling). |
| `replaceable` | `false` | Placing a block into it replaces it, like water. Liquids default to `true`. |
| `place_in` | see meaning | Block ids or [tags](../resources/tags.md) it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | Block ids or [tags](../resources/tags.md) it can stand on, like `["bworld:hoed_dirt"]` for crops or `["#bworld:logs"]`. See [below](#placement). |
@@ -75,6 +76,14 @@ there will be holes in the world behind them.
A block's definition goes to every player, since clients need it to draw the block, time breaking and collide with it.
It can't hold functions.
### Solid Blocks
A block is solid when it's drawn in the `solid` layer and entities bump into a whole block in every state: stone,
planks, logs and furnaces are, glass, leaves, slabs, chests and fences aren't. Every variant counts, even one that no
state shows, and blocks made of `parts` never are. Scripts on every side ask with `ctx.blocks.solid(id)`, which is
`false` for air and throws for a block that doesn't exist. It's worked out once per block, so it's cheap enough to ask
for every block a walk goes through, unlike `ctx.world.is_face_sturdy`, which looks at the block at a position.
## Mining
Breaking takes `mining.toughness` seconds by hand. A tool whose type matches `mining.tool` breaks it `tool.speed` times
+2 -1
View File
@@ -31,7 +31,8 @@ ctx.world.set_state(x, y, z, "age", age + 1);
`get_state` is `undefined` where there's no block, and `set_state` does nothing there and returns `false`. Both throw
for a state the block doesn't have, and `set_state` for a value that doesn't fit its bits. Changes are synced to
everyone who can see the block. Unlike `set_block`, it doesn't run `on_break` or `on_create`, and the block keeps its
tile data.
tile data. It runs the block's [`on_state_change`](components.md#changes) instead, and tells the blocks beside it,
unless it's given `{ update_neighbors: false }`.
## Variants
+132
View File
@@ -0,0 +1,132 @@
# Verdigris
Verdigris is the base game's redstone: power from 0 to 15 that wire carries from the blocks that make it to the blocks
that use it. A block joins in by listing the base game's [components](components.md) in its JSON:
`bworld:verdigris_source` to give power and `bworld:verdigris_input` to take it. Neither needs code. What a block gives
or takes is one of its [states](states.md), so it's saved, sent to players and drawn with variants like any other state,
and no script calls another mod's. A block that does something when it's powered, like a door opening, reacts to its
input's state in its own component's `on_state_change`.
## How Power Works
Every block gives some power out of each of its 6 sides, 0 for most.
- A **source** gives power out of some of its sides. Some of those are **strong**, and also power a solid block there.
- A [solid block](index.md#solid-blocks), like stone, makes no power, but it's powered by the strong sides pointing into
it and by wire lying on it, and gives that to the blocks around it. That's how a lever on one side of a wall opens a
door on the other. Wire lying on a solid block only takes what strong sides give it, not what other wire does, so a
wire can't keep itself on through the block it lies on.
- **Wire** carries power. Every wire joined to another is one net with one power, the most anything gives into any of
it, however long it is. It joins the sides of blocks that make or take power, and gives its power to the blocks it
lies on and the blocks it joins, not to ones it only runs past.
- An **input** takes power from each of its sides: what the block there gives out of that side, that block's power if
it's solid, or a wire's power when the wire lies on it or joins it. It's powered when any of them gives it more than
0.
## Sides
Both components name a block's sides by face: `north`, `east`, `south`, `west`, `top` and `bottom`. A block that points
somewhere can say `facing`, and then also name `front`, `back` and `sides`, the four around the way it points.
`facing` is a state's name. With 2 bits it's read as `north`, `east`, `south` and `west`, and with 3 bits as those, then
`top` and `bottom`. For a block on a floor, wall or ceiling, like a lever, it's
`{ "face": "face", "facing": "facing" }`: `face` 0 is the floor, where it points up, 1 a wall, where it points the way
`facing` says, and 2 the ceiling, where it points down. Its `back` is the block it's on.
## `bworld:verdigris_source`
| Param | Default | Meaning |
| ---------- | ---------- | ------------------------------------------------------------------------- |
| `power` | | The power it gives, 0 to 15: a number, or the name of a state that has it |
| `when` | | A 1 bit state. It only gives power while that's 1 |
| `facing` | | Which way it points, see [Sides](#sides) |
| `out` | every side | The sides it gives power out of |
| `strong` | none | The sides that also power a solid block there |
| `connects` | `out` | The sides wire joins |
Change the states it reads with `ctx.world.set_state` and the blocks beside it hear of it. The component tells the
blocks around the solid blocks its strong sides power, which aren't beside it.
The verdigris block gives 15 out of every side, always:
```json
"components": { "bworld:verdigris_source": { "power": 15 } }
```
The lever gives 15 while it's `powered`, out of every side, and strongly into the block it's on. Its own component flips
`powered` when it's right clicked:
```json
"bworld:verdigris_source": {
"power": 15,
"when": "powered",
"facing": { "face": "face", "facing": "facing" },
"strong": ["back"]
}
```
The torch gives power out of every side but the block it's on, and strongly into the block above it:
```json
"bworld:verdigris_source": {
"power": 15,
"when": "lit",
"facing": "facing",
"out": ["front", "sides"],
"strong": ["top"]
}
```
## `bworld:verdigris_input`
| Param | Default | Meaning |
| ---------- | ---------- | ------------------------------------------------------------- |
| `state` | | A 1 bit state it keeps whether it's powered in: 1 while it is |
| `facing` | | Which way it points, see [Sides](#sides) |
| `in` | every side | The sides it takes power from |
| `connects` | `in` | The sides wire joins |
The component works out its input when the block is placed and whenever a block beside it changes, and sets the state,
which does nothing when it's already right. It's on or off: a state for how much power comes in isn't supported yet.
A trapdoor lists it with a `powered` state:
```json
"components": {
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
```
and its server component opens it when `powered` changes, so one opened or closed by hand stays that way until the power
does:
```ts
ctx.components.register_block("bworld:trapdoor", {
on_state_change(block, _params, before) {
const powered = ctx.world.get_state(block.x, block.y, block.z, "powered");
if (powered !== before.powered) ctx.world.set_state(block.x, block.y, block.z, "open", powered ? 1 : 0);
},
});
```
## Both
A block can list both, like the pulse repeater, which takes power from behind it and gives it out of its front. Its
component sets `powering` with a [scheduled tick](components.md#scheduled-ticks) once its delay is up:
```json
"bworld:verdigris_source": {
"power": 15,
"when": "powering",
"facing": "facing",
"out": ["front"],
"strong": ["front"],
"connects": ["front", "back"]
},
"bworld:verdigris_input": { "state": "powered", "facing": "facing", "in": ["back"] }
```
Wire joins a side when either component's `connects` names it. A block whose output leads back to its own input, like an
inverter wired to itself, flips back and forth until the [neighbor update limit](components.md#changes) stops it, unless
it waits a scheduled tick between flips. The torch waits 2 ticks, and burns out for a while when it flips too often.
+1 -1
View File
@@ -29,7 +29,7 @@ interface Player {
readonly held_item: ItemStack | undefined;
give_item(id: string, count?: number, data?: unknown): void; // what doesn't fit drops at their feet
send_message(text: string): void;
send_message(text: string, options?: { overlay?: boolean }): void; // in chat, or above the hotbar with overlay
set_worn(key: string, items: ItemStack[]): void; // what's drawn on them, see Worn Items
teleport(x: number, y: number, z: number): void;
+32
View File
@@ -2237,3 +2237,35 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
# Create
https://github.com/Creators-of-Create/Create by simibubi and the Create team. The pulse repeater's textures
(`pulse_repeater_*.png`) and model (`models/pulse_repeater.json`) come from its version 0.5.0.j for Minecraft 1.19.3,
whose only license was this one:
license:
```
MIT License
Copyright (c) 2019 simibubi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:acacia_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:acacia_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:birch_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:birch_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:cherry_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:cherry_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:dark_oak_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:oak_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:jungle_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:jungle_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"format_version": 1,
"block": {
"id": "bworld:lever",
"textures": { "lever": "bworld:lever", "base": "bworld:cobblestone" },
"model": "bworld:lever",
"render_layer": "cutout",
"collision": false,
"interactive": true,
"mining": { "toughness": 0.5 },
"drops": "bworld:lever",
"states": [
{ "name": "face", "bits": 2, "default": 0 },
{ "name": "facing", "bits": 2, "default": 0 },
{ "name": "powered", "bits": 1, "default": 0 }
],
"variants": {
"powered=1": { "model": "bworld:lever_on" },
"face=0,facing=1": { "y": 90 },
"face=0,facing=2": { "y": 180 },
"face=0,facing=3": { "y": 270 },
"face=1,facing=0": { "x": 90 },
"face=1,facing=1": { "x": 90, "y": 90 },
"face=1,facing=2": { "x": 90, "y": 180 },
"face=1,facing=3": { "x": 90, "y": 270 },
"face=2,facing=0": { "x": 180, "y": 180 },
"face=2,facing=1": { "x": 180, "y": 270 },
"face=2,facing=2": { "x": 180 },
"face=2,facing=3": { "x": 180, "y": 90 }
},
"components": {
"bworld:verdigris_source": {
"power": 15,
"when": "powered",
"facing": { "face": "face", "facing": "facing" },
"strong": ["back"]
},
"bworld:lever": {}
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:oak_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:oak_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+64
View File
@@ -0,0 +1,64 @@
{
"format_version": 1,
"block": {
"id": "bworld:pulse_repeater",
"textures": {
"base": "bworld:pulse_repeater_base",
"top": "bworld:pulse_repeater_idle",
"torch": "bworld:verdigris_torch_off"
},
"model": "bworld:pulse_repeater",
"item_model": "bworld:pulse_repeater_item",
"render_layer": "cutout",
"shape": [[0, 0, 0, 16, 2, 16]],
"mining": { "toughness": 0 },
"drops": "bworld:pulse_repeater",
"interactive": true,
"scrollable": true,
"states": [
{ "name": "facing", "bits": 2, "default": 0 },
{ "name": "powered", "bits": 1, "default": 0 },
{ "name": "powering", "bits": 1, "default": 0 },
{ "name": "inverted", "bits": 1, "default": 0 },
{ "name": "delay", "bits": 8, "default": 0 }
],
"variants": {
"powered=1,powering=1": {
"textures": {
"base": "bworld:pulse_repeater_base",
"top": "bworld:pulse_repeater_powered_powering",
"torch": "bworld:verdigris_torch"
}
},
"powered=1": {
"textures": {
"base": "bworld:pulse_repeater_base",
"top": "bworld:pulse_repeater_powered",
"torch": "bworld:verdigris_torch_off"
}
},
"powering=1": {
"textures": {
"base": "bworld:pulse_repeater_base",
"top": "bworld:pulse_repeater_powering",
"torch": "bworld:verdigris_torch"
}
},
"facing=1": { "y": 90 },
"facing=2": { "y": 180 },
"facing=3": { "y": 270 }
},
"components": {
"bworld:verdigris_source": {
"power": 15,
"when": "powering",
"facing": "facing",
"out": ["front"],
"strong": ["front"],
"connects": ["front", "back"]
},
"bworld:verdigris_input": { "state": "powered", "facing": "facing", "in": ["back"] },
"bworld:pulse_repeater": {}
}
}
}
+7 -1
View File
@@ -30,6 +30,11 @@
"name": "hinge",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -92,7 +97,8 @@
"drops": "bworld:spruce_door",
"interactive": true,
"components": {
"bworld:door": { "pairs_with": "bworld:wooden_doors" }
"bworld:door": { "pairs_with": "bworld:wooden_doors" },
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+7 -1
View File
@@ -22,6 +22,11 @@
"name": "open",
"bits": 1,
"default": 0
},
{
"name": "powered",
"bits": 1,
"default": 0
}
],
"variants": {
@@ -51,7 +56,8 @@
"drops": "bworld:spruce_trapdoor",
"interactive": true,
"components": {
"bworld:trapdoor": {}
"bworld:trapdoor": {},
"bworld:verdigris_input": { "state": "powered" }
}
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"format_version": 1,
"block": {
"id": "bworld:verdigris_block",
"textures": "bworld:verdigris_block",
"mining": {
"toughness": 5,
"tool": "pickaxe",
"requires_tool": true
},
"drops": "bworld:verdigris_block",
"components": {
"bworld:verdigris_source": { "power": 15 }
}
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"format_version": 1,
"block": {
"id": "bworld:verdigris_torch",
"textures": { "torch": "bworld:verdigris_torch" },
"model": "bworld:verdigris_torch",
"render_layer": "cutout",
"collision": false,
"shape": [[6, 0, 6, 10, 11, 10]],
"mining": { "toughness": 0 },
"drops": "bworld:verdigris_torch",
"states": [
{ "name": "facing", "bits": 3, "default": 4 },
{ "name": "lit", "bits": 1, "default": 1 }
],
"variants": {
"lit=0": { "textures": { "torch": "bworld:verdigris_torch_off" } },
"facing=0": { "model": "bworld:verdigris_wall_torch", "shape": [[6, 3, 11, 10, 14, 16]] },
"facing=1": { "model": "bworld:verdigris_wall_torch", "y": 90, "shape": [[6, 3, 11, 10, 14, 16]] },
"facing=2": { "model": "bworld:verdigris_wall_torch", "y": 180, "shape": [[6, 3, 11, 10, 14, 16]] },
"facing=3": { "model": "bworld:verdigris_wall_torch", "y": 270, "shape": [[6, 3, 11, 10, 14, 16]] }
},
"components": {
"bworld:verdigris_source": {
"power": 15,
"when": "lit",
"facing": "facing",
"out": ["front", "sides"],
"strong": ["top"]
},
"bworld:verdigris_torch": {}
}
}
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
{
"format_version": 1,
"item": {
"id": "bworld:verdigris",
"texture": "bworld:verdigris",
"places": "bworld:verdigris_wire"
}
}
@@ -0,0 +1,97 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"conditions": [
{
"condition": "block_state",
"states": {
"north": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"east": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"south": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"west": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"top": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
},
{
"conditions": [
{
"condition": "block_state",
"states": {
"bottom": 1
}
}
],
"entries": [
{
"item": "bworld:verdigris"
}
]
}
]
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"format_version": 1,
"model": {
"id": "bworld:lever",
"elements": [
{
"from": [5, 0, 4],
"to": [11, 3, 12],
"faces": {
"top": {
"texture": "#base"
},
"bottom": {
"texture": "#base"
},
"north": {
"texture": "#base"
},
"south": {
"texture": "#base"
},
"west": {
"texture": "#base"
},
"east": {
"texture": "#base"
}
}
},
{
"from": [7, 1, 7],
"to": [9, 11, 9],
"rotation": {
"origin": [8, 1, 8],
"axis": "x",
"angle": -45
},
"faces": {
"top": {
"texture": "#lever",
"uv": [7, 6, 9, 8]
},
"north": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"south": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"west": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"east": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
}
}
}
]
}
}
+63
View File
@@ -0,0 +1,63 @@
{
"format_version": 1,
"model": {
"id": "bworld:lever_on",
"elements": [
{
"from": [5, 0, 4],
"to": [11, 3, 12],
"faces": {
"top": {
"texture": "#base"
},
"bottom": {
"texture": "#base"
},
"north": {
"texture": "#base"
},
"south": {
"texture": "#base"
},
"west": {
"texture": "#base"
},
"east": {
"texture": "#base"
}
}
},
{
"from": [7, 1, 7],
"to": [9, 11, 9],
"rotation": {
"origin": [8, 1, 8],
"axis": "x",
"angle": 45
},
"faces": {
"top": {
"texture": "#lever",
"uv": [7, 6, 9, 8]
},
"north": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"south": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"west": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
},
"east": {
"texture": "#lever",
"uv": [7, 6, 9, 16]
}
}
}
]
}
}
@@ -1,13 +1,7 @@
{
"format_version": 1,
"model": {
"id": "create:block_diodes_pulse_repeater",
"textures": {
"4": "create:block_diodes_brass_diode_base",
"particle": "create:block_diodes_brass_diode_base",
"top": "create:block_diodes_pulse_repeater_idle",
"torch": "bworld:redstone_torch_off"
},
"id": "bworld:pulse_repeater",
"elements": [
{
"from": [5, 2.1, 5],
@@ -24,12 +18,12 @@
"from": [0, 0, 0],
"to": [16, 2, 16],
"faces": {
"north": { "texture": "#4", "uv": [0, 14, 16, 16] },
"east": { "texture": "#4", "uv": [0, 0, 2, 16], "rotation": 270 },
"south": { "texture": "#4", "uv": [0, 0, 16, 2], "rotation": 180 },
"west": { "texture": "#4", "uv": [14, 0, 16, 16], "rotation": 90 },
"north": { "texture": "#base", "uv": [0, 14, 16, 16] },
"east": { "texture": "#base", "uv": [0, 0, 2, 16], "rotation": 270 },
"south": { "texture": "#base", "uv": [0, 0, 16, 2], "rotation": 180 },
"west": { "texture": "#base", "uv": [14, 0, 16, 16], "rotation": 90 },
"top": { "texture": "#top", "uv": [0, 0, 16, 16] },
"bottom": { "texture": "#4", "uv": [0, 0, 16, 16] }
"bottom": { "texture": "#base", "uv": [0, 0, 16, 16] }
}
},
{
@@ -48,13 +42,7 @@
"west": { "texture": "#torch", "uv": [6, 5, 10, 11] }
}
},
{
"from": [7, 6, 1],
"to": [9, 7, 3],
"faces": {
"top": { "texture": "#torch", "uv": [7, 6, 9, 8] }
}
}
{ "from": [7, 6, 1], "to": [9, 7, 3], "faces": { "top": { "texture": "#torch", "uv": [7, 6, 9, 8] } } }
],
"display": {
"gui": { "rotation": [30, 45, 0], "translation": [0, 2.5, 0], "scale": [0.625, 0.625, 0.625] },
@@ -0,0 +1,8 @@
{
"format_version": 1,
"model": {
"id": "bworld:pulse_repeater_item",
"parent": "bworld:pulse_repeater",
"textures": { "top": "bworld:pulse_repeater_item" }
}
}
+35
View File
@@ -0,0 +1,35 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_torch",
"elements": [
{
"from": [7, 0, 7],
"to": [9, 10, 9],
"shade": false,
"faces": {
"top": { "texture": "#torch", "uv": [7, 6, 9, 8] },
"bottom": { "texture": "#torch", "uv": [7, 14, 9, 16] }
}
},
{
"from": [7, 0, 0],
"to": [9, 16, 16],
"shade": false,
"faces": {
"west": { "texture": "#torch", "uv": [0, 0, 16, 16] },
"east": { "texture": "#torch", "uv": [0, 0, 16, 16] }
}
},
{
"from": [0, 0, 7],
"to": [16, 16, 9],
"shade": false,
"faces": {
"north": { "texture": "#torch", "uv": [0, 0, 16, 16] },
"south": { "texture": "#torch", "uv": [0, 0, 16, 16] }
}
}
]
}
}
@@ -0,0 +1,38 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wall_torch",
"elements": [
{
"from": [7, 3, 15],
"to": [9, 13, 17],
"rotation": { "origin": [8, 3, 16], "axis": "x", "angle": -22.5 },
"shade": false,
"faces": {
"top": { "texture": "#torch", "uv": [7, 6, 9, 8] },
"bottom": { "texture": "#torch", "uv": [7, 14, 9, 16] }
}
},
{
"from": [7, 3, 8],
"to": [9, 19, 24],
"rotation": { "origin": [8, 3, 16], "axis": "x", "angle": -22.5 },
"shade": false,
"faces": {
"west": { "texture": "#torch", "uv": [0, 0, 16, 16] },
"east": { "texture": "#torch", "uv": [0, 0, 16, 16] }
}
},
{
"from": [0, 3, 15],
"to": [16, 19, 17],
"rotation": { "origin": [8, 3, 16], "axis": "x", "angle": -22.5 },
"shade": false,
"faces": {
"north": { "texture": "#torch", "uv": [0, 0, 16, 16] },
"south": { "texture": "#torch", "uv": [0, 0, 16, 16] }
}
}
]
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_arm",
"elements": [
{
"from": [7, 0, 0],
"to": [9, 0.25, 7],
"faces": {
"top": {
"texture": "#wire"
}
}
}
]
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_arm_east",
"elements": [
{
"from": [9, 0, 7],
"to": [16, 0.25, 9],
"faces": {
"top": {
"texture": "#wire"
}
}
}
]
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_center",
"elements": [
{
"from": [7, 0, 7],
"to": [9, 0.25, 9],
"faces": {
"top": {
"texture": "#wire"
}
}
}
]
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_out",
"elements": [
{
"from": [7, 0, -0.25],
"to": [9, 0.25, 7],
"faces": {
"top": {
"texture": "#wire"
}
}
}
]
}
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"model": {
"id": "bworld:verdigris_wire_out_east",
"elements": [
{
"from": [9, 0, 7],
"to": [16.25, 0.25, 9],
"faces": {
"top": {
"texture": "#wire"
}
}
}
]
}
}
+35 -1
View File
@@ -7,6 +7,7 @@ import { register_curios } from "./curios.ts";
import { register_effects } from "./effects.ts";
import { register_fishing } from "./fishing.ts";
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
import { register_verdigris } from "./verdigris/server.ts";
export function setup(ctx: ServerContext) {
register_hoeable(ctx);
@@ -21,10 +22,12 @@ export function setup(ctx: ServerContext) {
register_farming(ctx);
register_fishing(ctx);
register_door(ctx);
register_trapdoor(ctx);
register_buckets(ctx);
register_curios(ctx);
register_effects(ctx);
register_growable_block(ctx);
register_verdigris(ctx);
}
// right clicking with a type of tool turns the block into another, like any hoe on grass
@@ -880,7 +883,9 @@ function register_growable_block(ctx: ServerContext) {
// doors are two blocks, a lower and an upper half, see register_door in shared.ts. one is only placed with air above
// it, where the upper half goes, and breaking either half takes the other away with it. only the half that was broken
// drops the door, the other is just taken away
// drops the door, the other is just taken away. a door is open while either half is powered, which each keeps in its
// powered state (see bworld:verdigris_input). it only follows the power changing, so one opened or closed by hand
// stays that way until it does
const DOOR = "bworld:door";
function register_door(ctx: ServerContext) {
@@ -896,6 +901,11 @@ function register_door(ctx: ServerContext) {
ctx.world.set_state(x, y + 1, z, state, ctx.world.get_state(x, y, z, state) ?? 0);
}
ctx.world.set_state(x, y + 1, z, "half", 1);
// it took its open state from the lower half, but it can be the half that's powered
if (ctx.world.get_state(x, y + 1, z, "powered")) {
ctx.world.set_state(x, y, z, "open", 1);
ctx.world.set_state(x, y + 1, z, "open", 1);
}
});
// the halves being taken away, so the other half's on_break doesn't take the first away again
@@ -914,5 +924,29 @@ function register_door(ctx: ServerContext) {
for (const half of halves) breaking.delete(half);
}
},
on_state_change(block, _params, before) {
const { x, y, z } = block;
const powered = ctx.world.get_state(x, y, z, "powered");
if (powered === before.powered) return;
const other = ctx.world.get_state(x, y, z, "half") ? y - 1 : y + 1;
const paired = ctx.world.get_block(x, other, z) === block.id;
const other_powered = paired && ctx.world.get_state(x, other, z, "powered") === 1;
const open = powered === 1 || other_powered;
if (open === (before.powered === 1 || other_powered)) return;
ctx.world.set_state(x, y, z, "open", open ? 1 : 0);
if (paired) ctx.world.set_state(x, other, z, "open", open ? 1 : 0);
},
});
}
// a trapdoor is open while it's powered, which it keeps in its powered state (see bworld:verdigris_input). it only
// follows the power changing, so one opened or closed by hand stays that way until it does. the rest of it is in
// shared.ts
function register_trapdoor(ctx: ServerContext) {
ctx.components.register_block("bworld:trapdoor", {
on_state_change(block, _params, before) {
const powered = ctx.world.get_state(block.x, block.y, block.z, "powered");
if (powered !== before.powered) ctx.world.set_state(block.x, block.y, block.z, "open", powered ? 1 : 0);
},
});
}
+2
View File
@@ -5,11 +5,13 @@
// server and on every client, so players see a fence join or a trapdoor turn the moment they place it, and a trapdoor
// or a door open the moment they click it
import type { SharedBlock, SharedContext } from "bworld/shared";
import { register_verdigris_rules } from "./verdigris/shared.ts";
export function setup(ctx: SharedContext) {
register_fence(ctx);
register_trapdoor(ctx);
register_door(ctx);
register_verdigris_rules(ctx);
}
// the sides a fence connects on, and the face of the block there it connects to
+160
View File
@@ -0,0 +1,160 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the blocks that make and use signals. what they give out is their bworld:verdigris_source params, this is what makes
// their states change
import type { BlockRef, Face, Position, ServerContext } from "bworld/server";
import { power_from } from "./inputs.ts";
import type { SignalReader } from "./signals.ts";
import { type FacingParam, front_of, OPPOSITE, pack, step } from "./sides.ts";
// a lever's face and facing states, see FacingParam
const LEVER_FACING: FacingParam = { face: "face", facing: "facing" };
// how many ticks a torch takes to go out or light after the block it's on changes
const TORCH_DELAY = 2;
// a torch that goes out more than TORCH_BURNOUT times in TORCH_BURNOUT_WINDOW ticks stays out for TORCH_BURNOUT_TICKS,
// so a fast torch clock can't cost the server much
const TORCH_BURNOUT = 8;
const TORCH_BURNOUT_WINDOW = 60;
const TORCH_BURNOUT_TICKS = 160;
// how long a pulse repeater's pulse lasts, in ticks
const PULSE_TICKS = 2;
// the delays a pulse repeater's delay state picks from, in ticks: scrolled through a tick at a time below a second, a
// second at a time below a minute, then a minute at a time up to an hour
export const PULSE_DELAYS: readonly number[] = [
...Array.from({ length: 18 }, (_, i) => 2 + i),
...Array.from({ length: 59 }, (_, i) => 20 + i * 20),
...Array.from({ length: 60 }, (_, i) => 1200 + i * 1200),
];
// switched on and off by right clicking it, and it breaks when what it's on goes
export function register_lever(ctx: ServerContext) {
ctx.components.register_block("bworld:lever", {
on_interact(block) {
const powered = ctx.world.get_state(block.x, block.y, block.z, "powered");
ctx.world.set_state(block.x, block.y, block.z, "powered", powered ? 0 : 1);
return true;
},
on_neighbor_change(block, _params, neighbor) {
const front = front_of(LEVER_FACING, (name) => ctx.world.get_state(block.x, block.y, block.z, name));
breaks_without(ctx, block, OPPOSITE[front], neighbor);
},
});
}
// out while the block it's on is powered, lit while it isn't, TORCH_DELAY ticks after that changes, and burnt out for a
// while when that's too often. which ticks it went out on and how long it's burnt out for are only kept in memory, so a
// restart forgets them
export function register_torch(ctx: ServerContext, world: SignalReader) {
const went_out = new Map<number, number[]>();
const burnt_until = new Map<number, number>();
const back = (block: Position) =>
OPPOSITE[front_of("facing", (name) => ctx.world.get_state(block.x, block.y, block.z, name))];
const powered = (block: Position) => power_from(world, block.x, block.y, block.z, back(block)) > 0;
// it's lit while powered or out while not, so it changes TORCH_DELAY ticks from now, unless it already will
const check = (block: Position) => {
const lit = ctx.world.get_state(block.x, block.y, block.z, "lit") === 1;
if (lit === powered(block) && !ctx.world.has_scheduled_tick(block.x, block.y, block.z)) {
ctx.world.schedule_tick(block.x, block.y, block.z, TORCH_DELAY);
}
};
// the ticks the torch at key went out on lately, without the ones too long ago to count
const lately = (key: number, now: number) =>
(went_out.get(key) ?? []).filter((tick) => tick > now - TORCH_BURNOUT_WINDOW);
ctx.components.register_block("bworld:verdigris_torch", {
on_create: check,
on_break(block) {
const key = pack(block.x, block.y, block.z);
went_out.delete(key);
burnt_until.delete(key);
},
on_neighbor_change(block, _params, neighbor) {
if (!breaks_without(ctx, block, back(block), neighbor)) check(block);
},
on_scheduled_tick(block) {
const key = pack(block.x, block.y, block.z);
const now = ctx.system.current_tick;
const lit = ctx.world.get_state(block.x, block.y, block.z, "lit") === 1;
if (lit && powered(block)) {
ctx.world.set_state(block.x, block.y, block.z, "lit", 0);
const ticks = [...lately(key, now), now];
went_out.set(key, ticks);
if (ticks.length > TORCH_BURNOUT) {
burnt_until.set(key, now + TORCH_BURNOUT_TICKS);
ctx.world.schedule_tick(block.x, block.y, block.z, TORCH_BURNOUT_TICKS);
}
} else if (!lit && !powered(block)) {
// a block has one tick waiting at most, so when going out set off a sooner one, the one that ends the
// burnout was dropped, and this one waits out the rest
const until = burnt_until.get(key) ?? now;
if (until > now) {
ctx.world.schedule_tick(block.x, block.y, block.z, until - now);
return;
}
burnt_until.delete(key);
const ticks = lately(key, now);
if (ticks.length > 0) went_out.set(key, ticks);
else went_out.delete(key);
ctx.world.set_state(block.x, block.y, block.z, "lit", 1);
}
},
});
}
// once the block behind it is powered, it waits its delay and then gives a PULSE_TICKS pulse out of its front. it
// pulses once each time that block is powered, and while it's counting down or pulsing it doesn't start again. powering
// is its output, so inverted it's on, and the pulse turns it off. right clicking it inverts it, and scrolling the mouse
// wheel at it changes its delay
export function register_pulse_repeater(ctx: ServerContext) {
const state = (block: Position, name: string) => ctx.world.get_state(block.x, block.y, block.z, name) ?? 0;
const set = (block: Position, name: string, value: number) =>
ctx.world.set_state(block.x, block.y, block.z, name, value);
ctx.components.register_block("bworld:pulse_repeater", {
on_interact(block) {
set(block, "inverted", 1 - state(block, "inverted"));
set(block, "powering", 1 - state(block, "powering"));
return true;
},
on_scroll(block, _params, player, scroll) {
const delay = Math.max(0, Math.min(PULSE_DELAYS.length - 1, state(block, "delay") + scroll.amount));
set(block, "delay", delay);
player.send_message(`Delay: ${delay_text(PULSE_DELAYS[delay])}`, { overlay: true });
},
on_neighbor_change(block, _params, neighbor) {
breaks_without(ctx, block, "bottom", neighbor);
},
on_state_change(block, _params, before) {
const started = state(block, "powered") === 1 && before.powered === 0;
if (started && !ctx.world.has_scheduled_tick(block.x, block.y, block.z)) {
ctx.world.schedule_tick(block.x, block.y, block.z, PULSE_DELAYS[state(block, "delay")]);
}
},
// its delay is up and the pulse starts, or the pulse is over
on_scheduled_tick(block) {
const inverted = state(block, "inverted");
const pulsing = state(block, "powering") !== inverted;
set(block, "powering", pulsing ? inverted : 1 - inverted);
if (!pulsing) ctx.world.schedule_tick(block.x, block.y, block.z, PULSE_TICKS);
},
});
}
// a delay in ticks the way a player reads it: ticks below a second, then seconds, then minutes
function delay_text(ticks: number) {
if (ticks < 20) return `${ticks} ticks`;
const [count, unit] = ticks < 1200 ? [ticks / 20, "second"] : [ticks / 1200, "minute"];
return `${count} ${unit}${count === 1 ? "" : "s"}`;
}
// breaks a block that hangs from the block toward face when the neighbor that changed is that block and its face isn't
// something to attach to anymore. whether it broke
function breaks_without(ctx: ServerContext, block: BlockRef, face: Face, neighbor: Position) {
const [x, y, z] = step(block.x, block.y, block.z, face);
if (neighbor.x !== x || neighbor.y !== y || neighbor.z !== z) return false;
if (ctx.world.is_face_sturdy(x, y, z, OPPOSITE[face])) return false;
ctx.world.break_block(block.x, block.y, block.z);
return true;
}
+35
View File
@@ -0,0 +1,35 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the power blocks take in, see docs/modding/blocks/verdigris.md: a source's output, a solid block's power, and the
// power of wire that lies on them or joins them
import type { Face } from "bworld/shared";
import { block_power, type InputParams, MAX_POWER, output, sides_of, type SignalReader, WIRE } from "./signals.ts";
import { OPPOSITE, step } from "./sides.ts";
import { wire_at } from "./wires.ts";
// the power going into the block at x y z from the one toward face: that one's output on that side, its power if it's
// solid, or its power if it's wire lying on this block or joining it. wire that only runs past gives none
export function power_from(world: SignalReader, x: number, y: number, z: number, face: Face) {
const [nx, ny, nz] = step(x, y, z, face);
const id = world.get_block(nx, ny, nz);
if (id === undefined) return 0;
if (id === WIRE) {
const wire = wire_at(world, nx, ny, nz);
const toward = OPPOSITE[face];
const gives = wire !== undefined &&
(wire.faces.includes(toward) || wire.out.some(([, direction]) => direction === toward));
return gives ? world.get_state(nx, ny, nz, "power") ?? 0 : 0;
}
return Math.max(output(world, nx, ny, nz, id, OPPOSITE[face]), block_power(world, nx, ny, nz, id));
}
// the most power going into the input at x y z from the sides it takes power from
export function input_power(world: SignalReader, x: number, y: number, z: number, params: InputParams) {
let most = 0;
for (const face of sides_of(world, x, y, z, params, params.in)) {
most = Math.max(most, power_from(world, x, y, z, face));
if (most === MAX_POWER) break;
}
return most;
}
+97
View File
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// which faces of its cell a wire covers and what it joins. a wire cell covers some of its six faces, each lying on the
// block on that side, and the wire on two faces that meet joins at that edge. a face's other directions lead out of the
// cell, and its arm_ states say which of those it joins. the shared rule sets them the same on the server and clients,
// and works out a join between two cells the same from either end
import type { Face } from "bworld/shared";
import { AIR, type BlockReader, connects, WIRE } from "./signals.ts";
import { DIRECTIONS, FACES, OPPOSITE, step } from "./sides.ts";
// how many arm_ states a wire has, so how many ways out of its cell its faces can have between them
export const MAX_ARMS = 6;
// whether the wire at x y z covers face of its cell. false when there's no wire
export function covers(world: BlockReader, x: number, y: number, z: number, face: Face) {
return world.get_block(x, y, z) === WIRE && world.get_state(x, y, z, face) === 1;
}
// the faces of its cell the wire at x y z covers, in FACES' order
export function faces_of(world: BlockReader, x: number, y: number, z: number): Face[] {
return world.get_block(x, y, z) === WIRE ? FACES.filter((face) => world.get_state(x, y, z, face) === 1) : [];
}
// the ways out of a cell covering faces: each face's directions toward faces it doesn't cover, which can lead to
// another cell. in FACES' order, then DIRECTIONS', which is the order of the arm_ states
export function ways_out(faces: readonly Face[]): [Face, Face][] {
return faces.flatMap((face) =>
DIRECTIONS[face].filter((direction) => !faces.includes(direction)).map((direction): [Face, Face] => [
face,
direction,
])
);
}
// whether one wire cell can cover all of faces: its ways out have to fit in its arm_ states. that leaves out two
// opposite faces with nothing joining them, and three or four faces all the way around the cell
export function can_cover(faces: readonly Face[]) {
return faces.length > 0 && ways_out(faces).length <= MAX_ARMS;
}
// what the wire on face of the cell at x y z joins toward direction, out of its cell: the same face of the next cell
// ("straight"), the next face of the block it lies on, around that block's edge ("edge"), or a block that makes or
// takes power ("block"). wire doesn't block the way around an edge, only the faces it covers matter
export type WayOut = "straight" | "edge" | "block";
export function joins_out(
world: BlockReader,
x: number,
y: number,
z: number,
face: Face,
direction: Face,
): WayOut | undefined {
const next = step(x, y, z, direction);
const id = world.get_block(...next);
if (id === undefined) return undefined;
if (id === WIRE) {
if (covers(world, ...next, face)) return "straight";
} else if (id !== AIR) {
return connects(world, ...next, id, OPPOSITE[direction]) ? "block" : undefined;
}
return covers(world, ...around_edge(x, y, z, face, direction), OPPOSITE[direction]) ? "edge" : undefined;
}
// the cell past the edge of the block the wire on face lies on, toward direction: where the wire on that block's next
// face is
export function around_edge(x: number, y: number, z: number, face: Face, direction: Face) {
return step(...step(x, y, z, face), direction);
}
// the wire cell a way out joins, undefined when it joins a block that isn't wire or nothing
export function joined_cell(world: BlockReader, x: number, y: number, z: number, face: Face, direction: Face) {
return cell_through(joins_out(world, x, y, z, face, direction), x, y, z, face, direction);
}
// the wire cell a way out that joins way leads to, undefined for a block that isn't wire or nothing
export function cell_through(way: WayOut | undefined, x: number, y: number, z: number, face: Face, direction: Face) {
if (way === "straight") return step(x, y, z, direction);
if (way === "edge") return around_edge(x, y, z, face, direction);
return undefined;
}
// the arm_ states of a wire cell at x y z covering faces, from what's around it
export function arms_of(world: BlockReader, x: number, y: number, z: number, faces: readonly Face[]) {
const arms: Record<string, number> = {};
for (let i = 0; i < MAX_ARMS; i++) arms[`arm_${i}`] = 0;
ways_out(faces).forEach(([face, direction], i) => {
arms[`arm_${i}`] = joins_out(world, x, y, z, face, direction) ? 1 : 0;
});
return arms;
}
// a wire cell's face states for faces, all six
export function face_states(faces: readonly Face[]) {
return Object.fromEntries(FACES.map((face) => [face, faces.includes(face) ? 1 : 0]));
}
+148
View File
@@ -0,0 +1,148 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// verdigris's components: the wire, which keeps its net's power through the net index, sources, inputs, and the devices
import type { BlockRef, Face, Position, ServerContext } from "bworld/server";
import { register_lever, register_pulse_repeater, register_torch } from "./devices.ts";
import { arms_of, around_edge, can_cover, covers, face_states, faces_of, MAX_ARMS } from "./joins.ts";
import { input_power } from "./inputs.ts";
import {
type BlockReader,
type InputParams,
params_lookup,
type SignalReader,
type SourceParams,
strong_sides,
} from "./signals.ts";
import { DIRECTIONS, FACES, OPPOSITE, step } from "./sides.ts";
import { NetIndex, type SignalWorld, tell_around_below, wire_at } from "./wires.ts";
// a wire's states that are its shape: the faces it covers and its arms. its power changing isn't
const SHAPE_STATES = [...FACES, ...Array.from({ length: MAX_ARMS }, (_, i) => `arm_${i}`)];
export function register_verdigris(ctx: ServerContext) {
const world = signal_world(ctx);
const nets = new NetIndex(world);
ctx.components.register_block("bworld:verdigris_wire", {
on_create(block) {
tell_around_edges(world, block);
nets.created(block.x, block.y, block.z);
},
on_break(block) {
const wire = wire_at(world, block.x, block.y, block.z);
tell_around_edges(world, block);
if (wire && ctx.world.get_state(block.x, block.y, block.z, "power")) tell_around_below(world, wire);
nets.breaking(block.x, block.y, block.z);
},
on_neighbor_change(block, _params, neighbor) {
if (lose_face(ctx, world, block, neighbor)) return;
nets.beside_changed(block.x, block.y, block.z, neighbor);
},
// it lost a face, or its rule joined or let go of something, which can join two nets or split one
on_state_change(block, _params, before) {
if (nets.setting_power) return;
const changed = SHAPE_STATES.some((name) =>
ctx.world.get_state(block.x, block.y, block.z, name) !== before[name]
);
if (changed) nets.reshaped(block.x, block.y, block.z);
},
});
// the engine tells the blocks beside a source when it changes. these tell the blocks around the solid blocks its
// strong sides power, which nothing else would. on_state_change tells them for the sides it had and has, in case it
// turned
ctx.components.register_block("bworld:verdigris_source", {
on_create: (block) => tell_through(world, block, strong_sides(world, block.x, block.y, block.z, block.id)),
on_break: (block) => tell_through(world, block, strong_sides(world, block.x, block.y, block.z, block.id)),
on_state_change(block, _params, before) {
const was: BlockReader = {
...world,
get_state: (x, y, z, name) =>
x === block.x && y === block.y && z === block.z ? before[name] : world.get_state(x, y, z, name),
};
const sides = new Set([
...strong_sides(was, block.x, block.y, block.z, block.id),
...strong_sides(world, block.x, block.y, block.z, block.id),
]);
tell_through(world, block, [...sides]);
},
});
// keeps whether the block is powered in its state, for the block's own component to react to in on_state_change.
// setting it to what it is does nothing, so most changes around it cost a few reads
ctx.components.register_block<InputParams>("bworld:verdigris_input", {
on_create: (block, params) => set_input(ctx, world, block, params),
on_neighbor_change: (block, params) => set_input(ctx, world, block, params),
});
register_lever(ctx);
register_torch(ctx, world);
register_pulse_repeater(ctx);
}
function set_input(ctx: ServerContext, world: SignalReader, block: BlockRef, params: InputParams) {
const powered = input_power(world, block.x, block.y, block.z, params) > 0 ? 1 : 0;
ctx.world.set_state(block.x, block.y, block.z, params.state, powered);
}
// the wires on the next faces of the blocks a wire lies on, which it joins or could join around their edges. they
// aren't among the six blocks beside it the engine tells
function tell_around_edges(world: SignalWorld, block: BlockRef) {
const faces = faces_of(world, block.x, block.y, block.z);
for (const face of faces) {
for (const direction of DIRECTIONS[face]) {
if (faces.includes(direction)) continue;
const [x, y, z] = around_edge(block.x, block.y, block.z, face, direction);
if (covers(world, x, y, z, OPPOSITE[direction])) world.neighbor_changed(x, y, z, block);
}
}
}
// the face of a wire that lay on the block that changed, when that block's face isn't something to lie on anymore: the
// wire comes off it and drops it, or breaks when what's left can't be one cell. whether it did
function lose_face(ctx: ServerContext, world: SignalWorld, block: BlockRef, neighbor: Position) {
const faces = faces_of(world, block.x, block.y, block.z);
const face = faces.find((face) => {
const [x, y, z] = step(block.x, block.y, block.z, face);
return x === neighbor.x && y === neighbor.y && z === neighbor.z;
});
if (!face || ctx.world.is_face_sturdy(neighbor.x, neighbor.y, neighbor.z, OPPOSITE[face])) return false;
const left = faces.filter((other) => other !== face);
if (!can_cover(left)) {
ctx.world.break_block(block.x, block.y, block.z);
return true;
}
// the wires it joins around the edges of the face it loses aren't beside it, and the engine doesn't tell them
tell_around_edges(world, block);
ctx.world.drop_item(block.x, block.y, block.z, { id: "bworld:verdigris", count: 1 });
const states = { ...face_states(left), ...arms_of(world, block.x, block.y, block.z, left) };
for (const [name, value] of Object.entries(states)) ctx.world.set_state(block.x, block.y, block.z, name, value);
return true;
}
// the blocks around each solid block toward those faces of the block, powered through it
function tell_through(world: SignalWorld, block: BlockRef, faces: readonly Face[]) {
for (const face of faces) {
const [sx, sy, sz] = step(block.x, block.y, block.z, face);
const id = world.get_block(sx, sy, sz);
if (id === undefined || !world.solid(id)) continue;
for (const around of FACES) {
if (around === OPPOSITE[face]) continue;
world.neighbor_changed(...step(sx, sy, sz, around), { x: sx, y: sy, z: sz });
}
}
}
function signal_world(ctx: ServerContext): SignalWorld {
return {
// a chunk that was never generated holds nothing anyone built, and reading it would generate it
get_block: (x, y, z) => ctx.world.is_loaded(x, z) ? ctx.world.get_block(x, y, z) : undefined,
get_state: (x, y, z, name) => ctx.world.get_state(x, y, z, name),
source: params_lookup<SourceParams>(ctx.blocks, "bworld:verdigris_source"),
input: params_lookup<InputParams>(ctx.blocks, "bworld:verdigris_input"),
solid: (id) => ctx.blocks.solid(id),
set_power: (x, y, z, power) => ctx.world.set_state(x, y, z, "power", power, { update_neighbors: false }),
neighbor_changed: (x, y, z, from) => ctx.world.neighbor_changed(x, y, z, from),
};
}
+79
View File
@@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// verdigris placement and joins. rules, so a player sees a wire join or a lever turn to the wall the moment they place
// it. power, delays and clicks are the server's, see server.ts
import type { BlockPlacement, Face, SharedContext } from "bworld/shared";
import { arms_of, can_cover, face_states, faces_of } from "./joins.ts";
import { type BlockReader, type InputParams, params_lookup, type SourceParams } from "./signals.ts";
import { FACES, OPPOSITE, step } from "./sides.ts";
export function register_verdigris_rules(ctx: SharedContext) {
const world = join_reader(ctx);
// lies on the face it's placed against, joined to what's around it. placed into a cell that has wire already, the
// wire there covers that face too, keeping its power
ctx.components.register_block("bworld:verdigris_wire", {
state_for_placement(placement) {
const face = hangs_from(ctx, placement);
if (!face) return false;
const { x, y, z } = placement;
const covered = faces_of(world, x, y, z);
const faces = FACES.filter((other) => other === face || covered.includes(other));
if (covered.includes(face) || !can_cover(faces)) return false;
const power = covered.length > 0 ? world.get_state(x, y, z, "power") ?? 0 : 0;
return { ...face_states(faces), ...arms_of(world, x, y, z, faces), power };
},
on_neighbor_change(block) {
const { x, y, z } = block;
for (const [name, arm] of Object.entries(arms_of(world, x, y, z, faces_of(world, x, y, z)))) {
ctx.world.set_state(x, y, z, name, arm);
}
},
});
// on a floor, on a wall pointing out of it, or on a ceiling. on a floor or ceiling, facing faces the player
ctx.components.register_block("bworld:lever", {
state_for_placement(placement): Record<string, number> | false {
const side = hangs_from(ctx, placement);
if (!side) return false;
if (side === "bottom") return { face: 0 };
if (side === "top") return { face: 2 };
return { face: 1, facing: FACES.indexOf(OPPOSITE[side]) };
},
});
// on a floor, its front the way the player placing it looks, so it gives power away from them
ctx.components.register_block("bworld:pulse_repeater", {
state_for_placement(placement) {
const { x, y, z } = placement;
return ctx.world.is_face_sturdy(x, y - 1, z, "top") ? { facing: FACES.indexOf(placement.facing) } : false;
},
});
// on a floor pointing up, or on a wall pointing out of it. not under a ceiling
ctx.components.register_block("bworld:verdigris_torch", {
state_for_placement(placement) {
const side = hangs_from(ctx, placement);
if (!side || side === "top") return false;
return { facing: FACES.indexOf(OPPOSITE[side]) };
},
});
}
// the face toward the block a wire, lever or torch placed there hangs from: the one it's placed against, if that
// block's face is something to attach to
function hangs_from(ctx: SharedContext, placement: BlockPlacement): Face | undefined {
const side = OPPOSITE[placement.face];
const [x, y, z] = step(placement.x, placement.y, placement.z, side);
return ctx.world.is_face_sturdy(x, y, z, placement.face) ? side : undefined;
}
function join_reader(ctx: SharedContext): BlockReader {
return {
get_block: (x, y, z) => ctx.world.get_block(x, y, z),
get_state: (x, y, z, name) => ctx.world.get_state(x, y, z, name),
source: params_lookup<SourceParams>(ctx.blocks, "bworld:verdigris_source"),
input: params_lookup<InputParams>(ctx.blocks, "bworld:verdigris_input"),
};
}
+81
View File
@@ -0,0 +1,81 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// faces, and the directions along them a wire lying on one runs
import type { Face } from "bworld/shared";
// the six faces in the order of a 3 bit facing state's values: a 2 bit facing's four, then top and bottom
export const FACES: readonly Face[] = ["north", "east", "south", "west", "top", "bottom"];
// one block toward each face
export const FACE_OFFSETS: Readonly<Record<Face, readonly [number, number, number]>> = {
north: [0, 0, -1],
east: [1, 0, 0],
south: [0, 0, 1],
west: [-1, 0, 0],
top: [0, 1, 0],
bottom: [0, -1, 0],
};
export const OPPOSITE: Readonly<Record<Face, Face>> = {
north: "south",
east: "west",
south: "north",
west: "east",
top: "bottom",
bottom: "top",
};
// the block toward face from x y z
export function step(x: number, y: number, z: number, face: Face): [number, number, number] {
const [dx, dy, dz] = FACE_OFFSETS[face];
return [x + dx, y + dy, z + dz];
}
// a position as one number, so maps and sets of them don't make a string each: x and z in 21 bits and y in 8, further
// than chunk_key lets a world go
export function pack(x: number, y: number, z: number) {
return ((x + 2 ** 20) * 2 ** 21 + z + 2 ** 20) * 256 + y;
}
export function unpack(key: number): [number, number, number] {
const y = key % 256;
const xz = (key - y) / 256;
const z = xz % 2 ** 21;
return [(xz - z) / 2 ** 21 - 2 ** 20, y, z - 2 ** 20];
}
// which way a block points, from its states: the name of a facing state, read as FACES' values with 2 bits or 3, or
// a face and facing state for blocks on a floor, wall or ceiling, like a lever. face 0 is the floor, where it points
// up, 1 a wall, where it points the way facing says, and 2 the ceiling, where it points down
export type FacingParam = string | { face: string; facing: string };
export function front_of(facing: FacingParam, state: (name: string) => number | undefined): Face {
if (typeof facing === "string") return FACES[state(facing) ?? 0];
const on = state(facing.face) ?? 0;
return on === 0 ? "top" : on === 2 ? "bottom" : FACES[state(facing.facing) ?? 0];
}
// a block's sides as components name them: faces, or front, back and sides, the four around the way it points
export type SideName = Face | "front" | "back" | "sides";
export function named_sides(names: readonly SideName[], front: Face | undefined): Face[] {
return names.flatMap((name): readonly Face[] => {
if (name === "front") return front ? [front] : [];
if (name === "back") return front ? [OPPOSITE[front]] : [];
if (name === "sides") return front ? FACES.filter((face) => face !== front && face !== OPPOSITE[front]) : [];
return [name];
});
}
// the 4 directions along a wire on each face of its cell, in the order its arm_ states take them (see ways_out in
// joins.ts). they're the same on every face: a floor's north, east, south and west, turned the way the floor turns
// onto that face, so a wire is drawn the same few pieces turned by face. on a wall 0 is always down and 2 up
export const DIRECTIONS: Readonly<Record<Face, readonly [Face, Face, Face, Face]>> = {
north: ["bottom", "west", "top", "east"],
east: ["bottom", "north", "top", "south"],
south: ["bottom", "east", "top", "west"],
west: ["bottom", "south", "top", "north"],
top: ["south", "east", "north", "west"],
bottom: ["north", "east", "south", "west"],
};
+143
View File
@@ -0,0 +1,143 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the power blocks give each other, see docs/modding/blocks/verdigris.md. every signal is a block state, so this only
// reads states, through a small world instead of ctx so it runs the same in shared scripts, server scripts and tests
import type { Face, Id } from "bworld/shared";
import { FACES, type FacingParam, front_of, named_sides, OPPOSITE, type SideName, step } from "./sides.ts";
export const WIRE = "bworld:verdigris_wire";
export const AIR = "bworld:air";
export const MAX_POWER = 15;
// a bworld:verdigris_source's params, the block json's: something that gives power out of some of its sides
export interface SourceParams {
// the state holding the power it gives, 0 to 15, or always this much
power: string | number;
// a 1 bit state it only gives power while it's 1
when?: string;
facing?: FacingParam;
// the sides it gives power out of, every side when not set
out?: SideName[];
// the ones of those that also power a solid block there
strong?: SideName[];
// the sides wire joins, out when not set
connects?: SideName[];
}
// a bworld:verdigris_input's params: something that keeps whether it's powered in one of its states
export interface InputParams {
// a 1 bit state, 1 while it's powered
state: string;
facing?: FacingParam;
// the sides it takes power from, every side when not set
in?: SideName[];
// the sides wire joins, in when not set
connects?: SideName[];
}
export interface BlockReader {
// undefined where there's nothing to read, like a chunk that was never generated
get_block(x: number, y: number, z: number): Id | undefined;
get_state(x: number, y: number, z: number, name: string): number | undefined;
// its bworld:verdigris_source params, undefined for a block that isn't one
source(id: Id): SourceParams | undefined;
// its bworld:verdigris_input params, undefined for a block that isn't one
input(id: Id): InputParams | undefined;
}
export interface SignalReader extends BlockReader {
// whether it's solid for power: a block that's powered and passes it on, see ctx.blocks.solid
solid(id: Id): boolean;
}
// blocks' params for one component from ctx.blocks, like bworld:verdigris_source's, looked up once per block, since
// components don't change
export function params_lookup<P>(blocks: { components(id: Id): Record<Id, unknown> }, component: Id) {
const params = new Map<Id, P | undefined>();
return (id: Id): P | undefined => {
if (id === AIR) return undefined;
if (!params.has(id)) params.set(id, blocks.components(id)[component] as P | undefined);
return params.get(id);
};
}
// the faces a source's or input's list of sides names, for the block at x y z
export function sides_of(
world: BlockReader,
x: number,
y: number,
z: number,
params: { facing?: FacingParam },
names?: SideName[],
): readonly Face[] {
if (!names) return FACES;
const front = params.facing === undefined
? undefined
: front_of(params.facing, (name) => world.get_state(x, y, z, name));
return named_sides(names, front);
}
// the power the source at x y z gives out of its side toward face, strong or not
function gives(world: BlockReader, x: number, y: number, z: number, params: SourceParams, face: Face, strong: boolean) {
if (params.when !== undefined && !world.get_state(x, y, z, params.when)) return 0;
const sides = strong ? params.strong ?? [] : params.out;
if (!sides_of(world, x, y, z, params, sides).includes(face)) return 0;
const power = typeof params.power === "number" ? params.power : world.get_state(x, y, z, params.power) ?? 0;
return Math.min(power, MAX_POWER);
}
// the power the block at x y z gives out of its side toward face. 0 for a block that isn't a source
export function output(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const params = world.source(id);
return params ? gives(world, x, y, z, params, face, false) : 0;
}
// what output gives that also powers a solid block there
export function strong_output(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const params = world.source(id);
return params ? gives(world, x, y, z, params, face, true) : 0;
}
// the faces of the source at x y z that power a solid block there, as its states are now
export function strong_sides(world: BlockReader, x: number, y: number, z: number, id: Id): readonly Face[] {
const params = world.source(id);
return params?.strong ? sides_of(world, x, y, z, params, params.strong) : [];
}
// whether wire joins the side toward face of the block at x y z: a source's or an input's connects
export function connects(world: BlockReader, x: number, y: number, z: number, id: Id, face: Face) {
const source = world.source(id);
if (source && sides_of(world, x, y, z, source, source.connects ?? source.out).includes(face)) return true;
const input = world.input(id);
return input !== undefined && sides_of(world, x, y, z, input, input.connects ?? input.in).includes(face);
}
// the power a solid block gets from the strong sides pointing into it. wire powers it too, but not for wire: a net
// would hold itself on through any block it lies on
export function solid_power(world: SignalReader, x: number, y: number, z: number, id: Id) {
if (!world.solid(id)) return 0;
let most = 0;
for (const face of FACES) {
const [nx, ny, nz] = step(x, y, z, face);
const beside = world.get_block(nx, ny, nz);
if (beside === undefined || beside === WIRE) continue;
most = Math.max(most, strong_output(world, nx, ny, nz, beside, OPPOSITE[face]));
if (most === MAX_POWER) break;
}
return most;
}
// the power a solid block has for anything but wire: solid_power, and the power of the wire lying on it
export function block_power(world: SignalReader, x: number, y: number, z: number, id: Id) {
if (!world.solid(id)) return 0;
let most = solid_power(world, x, y, z, id);
for (const face of FACES) {
if (most === MAX_POWER) break;
const [nx, ny, nz] = step(x, y, z, face);
if (world.get_block(nx, ny, nz) === WIRE && world.get_state(nx, ny, nz, OPPOSITE[face]) === 1) {
most = Math.max(most, world.get_state(nx, ny, nz, "power") ?? 0);
}
}
return most;
}
+327
View File
@@ -0,0 +1,327 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// wire nets: a wire cell and every wire cell it reaches through its joins are one net, and they all have the same
// power, the most any block gives into any of them. a cell's faces always join each other, so it's one piece of one
// net. NetIndex keeps the nets between changes
import type { Face } from "bworld/shared";
import { cell_through, faces_of, joins_out, ways_out } from "./joins.ts";
import { type BlockReader, MAX_POWER, output, type SignalReader, solid_power } from "./signals.ts";
import { FACES, OPPOSITE, pack, step, unpack } from "./sides.ts";
export interface SignalWorld extends SignalReader {
// sets a wire's power without telling the blocks around it, see ServerWorld.set_state's update_neighbors
set_power(x: number, y: number, z: number, power: number): void;
// see ServerWorld.neighbor_changed
neighbor_changed(x: number, y: number, z: number, from: { x: number; y: number; z: number }): void;
}
export interface Wire {
readonly x: number;
readonly y: number;
readonly z: number;
// the faces of its cell it covers
readonly faces: readonly Face[];
// the ways out of its cell it joins, each a face and a direction, see ways_out
readonly out: readonly [Face, Face][];
}
// the wire at x y z, undefined when there's none
export function wire_at(world: BlockReader, x: number, y: number, z: number): Wire | undefined {
const faces = faces_of(world, x, y, z);
if (faces.length === 0) return undefined;
return { x, y, z, faces, out: ways_out(faces).filter((_, i) => world.get_state(x, y, z, `arm_${i}`) === 1) };
}
// the blocks a wire's faces lie on
function below(wire: Wire) {
return wire.faces.map((face) => ({ face, at: step(wire.x, wire.y, wire.z, face) }));
}
// the blocks around the blocks a wire lies on, told when it's gone with power, since nothing else tells them they're
// no longer powered through
export function tell_around_below(world: SignalWorld, wire: Wire) {
for (const { at } of below(wire)) {
const from = { x: at[0], y: at[1], z: at[2] };
world.neighbor_changed(...at, wire);
for (const face of FACES) {
const around = step(...at, face);
if (around[0] !== wire.x || around[1] !== wire.y || around[2] !== wire.z) {
world.neighbor_changed(...around, from);
}
}
}
}
// a wire cell in a net, with what its ways out joined when it was read: wire cells, packed, and the directions of
// blocks that aren't wire
interface Cell {
readonly wire: Wire;
readonly joins: readonly number[];
readonly blocks: readonly Face[];
}
interface Net {
// by packed position
readonly cells: Map<number, Cell>;
// the power going into each of its cells that gets some from outside it, see #input
readonly inputs: Map<number, number>;
// the most of inputs, which each of its cells has
power: number;
}
function most(inputs: Map<number, number>) {
let power = 0;
for (const input of inputs.values()) power = Math.max(power, input);
return power;
}
// the nets of the wire cells anything has touched, kept between changes so most changes cost a few reads instead of a
// the nets of the wire cells anything has touched, kept between changes so most changes cost a few reads instead of a
// walk. it's only in memory, and a cell it doesn't have is walked the first time anything touches it, so it can't hold
// anything the world doesn't. the wire's server hooks call created, breaking, reshaped and beside_changed
export class NetIndex {
readonly #world: SignalWorld;
// each cell's net, by packed position
readonly #nets = new Map<number, Net>();
// cells of nets that were forgotten, to walk again, see #settle
readonly #stale: number[] = [];
#setting = false;
constructor(world: SignalWorld) {
this.#world = world;
}
// whether it's setting wires' power, which changes no net's shape
get setting_power() {
return this.#setting;
}
// a wire was placed at x y z: it and the nets of the cells it joins are one net
created(x: number, y: number, z: number) {
this.#settle();
if (this.#nets.has(pack(x, y, z))) return;
const cell = this.#read(x, y, z);
if (cell) this.#link(x, y, z, cell, undefined);
}
// the wire at x y z is breaking: its net is forgotten, and what's left of it is walked again once it's gone, by the
// first cell of it that hears
breaking(x: number, y: number, z: number) {
const key = pack(x, y, z);
const net = this.#nets.get(key);
if (net) this.#forget(net, key);
}
// the wire at x y z covers other faces or joins other things. letting go of a cell can split its net, so the net is
// walked again. otherwise the nets of the cells it joins now are joined to it
reshaped(x: number, y: number, z: number) {
this.#settle();
const key = pack(x, y, z);
const net = this.#nets.get(key);
const cell = this.#read(x, y, z);
if (net && cell && net.cells.get(key)!.joins.every((joined) => cell.joins.includes(joined))) {
this.#link(x, y, z, cell, net);
return;
}
if (net) this.#forget(net);
else this.#stale.push(key);
this.#settle();
}
// the block at beside changed, which can change what the wire cell at x y z gets from outside, and so its net's
// power. one where a way out of it leads can change what that joins without changing its arm_ state, like a lever
// placed in the cell a join went around an edge through, so the cell is read again
beside_changed(x: number, y: number, z: number, beside: { x: number; y: number; z: number }) {
this.#settle();
const key = pack(x, y, z);
const net = this.#nets.get(key);
if (!net) {
this.#stale.push(key);
this.#settle();
return;
}
const cell = net.cells.get(key)!;
const changed = pack(beside.x, beside.y, beside.z);
if (cell.wire.out.some(([, direction]) => pack(...step(x, y, z, direction)) === changed)) {
this.reshaped(x, y, z);
return;
}
const input = this.#input(cell);
if (input === (net.inputs.get(key) ?? 0)) return;
if (input > 0) net.inputs.set(key, input);
else net.inputs.delete(key);
const power = most(net.inputs);
if (power === net.power) return;
net.power = power;
this.#set_power(net, [...net.cells.values()]);
}
// makes cell, at x y z, one net with the cells it joins, and works out its input again. was is its net before,
// undefined for a new wire. the cells that don't have the net's power get it, and nothing else is written
#link(x: number, y: number, z: number, cell: Cell, was: Net | undefined) {
const key = pack(x, y, z);
// a cell it joins that isn't in a net yet is walked first. if that walk got here, it saw to everything
for (const joined of cell.joins) if (!this.#nets.has(joined)) this.#stale.push(joined);
this.#settle();
if (this.#nets.get(key) !== was) return;
const nets = new Set<Net>();
if (was) nets.add(was);
for (const joined of cell.joins) {
const net = this.#nets.get(joined);
if (net) nets.add(net);
}
const input = this.#input(cell);
let power = input;
for (const net of nets) {
for (const [at, given] of net.inputs) if (at !== key) power = Math.max(power, given);
}
// found before the nets are joined, when it's still known which had which power
const changed: Cell[] = [];
for (const net of nets) {
if (net.power === power) continue;
for (const [at, other] of net.cells) if (at !== key) changed.push(other);
}
if (was ? was.power !== power : (this.#world.get_state(x, y, z, "power") ?? 0) !== power) changed.push(cell);
let net: Net = { cells: new Map(), inputs: new Map(), power };
for (const other of nets) if (other.cells.size > net.cells.size) net = other;
for (const other of nets) if (other !== net) this.#absorb(net, other);
net.cells.set(key, cell);
this.#nets.set(key, net);
if (input > 0) net.inputs.set(key, input);
else net.inputs.delete(key);
net.power = power;
this.#set_power(net, changed);
}
// takes net out of the index, and puts its cells but except in #stale to walk again
#forget(net: Net, except?: number) {
for (const key of net.cells.keys()) {
this.#nets.delete(key);
if (key !== except) this.#stale.push(key);
}
}
// puts from's cells in net
#absorb(net: Net, from: Net) {
for (const [key, cell] of from.cells) {
net.cells.set(key, cell);
this.#nets.set(key, net);
}
for (const [key, input] of from.inputs) net.inputs.set(key, input);
}
// walks from each cell in #stale that no walk has reached since it was put there, then gives the cells of the nets
// those walks found that don't have their net's power
#settle() {
if (this.#stale.length === 0) return;
const found = new Set<Net>();
while (this.#stale.length > 0) {
const key = this.#stale.pop()!;
if (!this.#nets.has(key)) this.#walk(key, found);
}
for (const net of found) {
this.#set_power(
net,
[...net.cells.values()].filter(({ wire }) =>
(this.#world.get_state(wire.x, wire.y, wire.z, "power") ?? 0) !== net.power
),
);
}
}
// indexes the net of the wire at start, walked from there, and adds it to found. a cell another net has takes that
// net along: one found by this settle is taken whole, and one from before is forgotten and its other cells walked
// again. a walk only reaches another net while two cells' arms don't agree yet, between one changing and the other
#walk(start: number, found: Set<Net>) {
const net: Net = { cells: new Map(), inputs: new Map(), power: 0 };
const seen = new Set([start]);
const queue = [start];
while (queue.length > 0) {
const key = queue.pop()!;
const other = this.#nets.get(key);
if (other === net) continue;
if (other && found.has(other)) {
this.#absorb(net, other);
found.delete(other);
continue;
}
if (other) this.#forget(other);
const cell = this.#read(...unpack(key));
if (!cell) continue;
net.cells.set(key, cell);
this.#nets.set(key, net);
const input = this.#input(cell);
if (input > 0) net.inputs.set(key, input);
for (const joined of cell.joins) {
if (seen.has(joined)) continue;
seen.add(joined);
queue.push(joined);
}
}
if (net.cells.size === 0) return;
net.power = most(net.inputs);
found.add(net);
}
// the cell at x y z as it is now, undefined when there's no wire
#read(x: number, y: number, z: number): Cell | undefined {
const wire = wire_at(this.#world, x, y, z);
if (!wire) return undefined;
const joins: number[] = [];
const blocks: Face[] = [];
for (const [face, direction] of wire.out) {
const way = joins_out(this.#world, x, y, z, face, direction);
if (way === "block") blocks.push(direction);
const next = cell_through(way, x, y, z, face, direction);
if (next) joins.push(pack(...next));
}
return { wire, joins, blocks };
}
// the power going into a cell from outside its net: from each block it lies on, a source's output on that side or a
// solid block's power, and from the blocks that aren't wire it joins
#input({ wire, blocks }: Cell) {
const world = this.#world;
let power = 0;
for (const { face, at } of below(wire)) {
const id = world.get_block(...at);
if (id !== undefined) {
power = Math.max(power, output(world, ...at, id, OPPOSITE[face]), solid_power(world, ...at, id));
}
if (power === MAX_POWER) return power;
}
for (const direction of blocks) {
const at = step(wire.x, wire.y, wire.z, direction);
const id = world.get_block(...at);
if (id !== undefined) power = Math.max(power, output(world, ...at, id, OPPOSITE[direction]));
if (power === MAX_POWER) return power;
}
return power;
}
// sets each of cells to its net's power, then tells each block that gives power to once: the blocks they join, the
// blocks they lie on and the blocks around those, which are powered through them
#set_power(net: Net, cells: readonly Cell[]) {
this.#setting = true;
try {
for (const { wire } of cells) this.#world.set_power(wire.x, wire.y, wire.z, net.power);
} finally {
this.#setting = false;
}
const told = new Set<number>();
const tell = (at: [number, number, number], from: { x: number; y: number; z: number }) => {
const key = pack(...at);
if (told.has(key) || this.#nets.get(key) === net) return;
told.add(key);
this.#world.neighbor_changed(...at, from);
};
for (const { wire, blocks } of cells) {
for (const direction of blocks) tell(step(wire.x, wire.y, wire.z, direction), wire);
for (const { at } of below(wire)) {
tell(at, wire);
for (const face of FACES) tell(step(...at, face), { x: at[0], y: at[1], z: at[2] });
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 301 B

Before

Width:  |  Height:  |  Size: 313 B

After

Width:  |  Height:  |  Size: 313 B

Before

Width:  |  Height:  |  Size: 310 B

After

Width:  |  Height:  |  Size: 310 B

Before

Width:  |  Height:  |  Size: 320 B

After

Width:  |  Height:  |  Size: 320 B

Before

Width:  |  Height:  |  Size: 314 B

After

Width:  |  Height:  |  Size: 314 B

Before

Width:  |  Height:  |  Size: 319 B

After

Width:  |  Height:  |  Size: 319 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 451 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 B

-70
View File
@@ -1,70 +0,0 @@
{
"format_version": 1,
"block": {
"id": "create:pulse_repeater",
"textures": {},
"model": "create:block_diodes_pulse_repeater",
"variants": {
"facing=1,inverted=0,powered=0,powering=0": { "model": "create:block_diodes_pulse_repeater", "y": 270 },
"facing=1,inverted=0,powered=0,powering=1": { "model": "create:block_pulse_repeater_powering", "y": 270 },
"facing=1,inverted=0,powered=1,powering=0": { "model": "create:block_pulse_repeater_powered", "y": 270 },
"facing=1,inverted=0,powered=1,powering=1": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 270
},
"facing=1,inverted=1,powered=0,powering=0": { "model": "create:block_pulse_repeater_powering", "y": 270 },
"facing=1,inverted=1,powered=0,powering=1": { "model": "create:block_diodes_pulse_repeater", "y": 270 },
"facing=1,inverted=1,powered=1,powering=0": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 270
},
"facing=1,inverted=1,powered=1,powering=1": { "model": "create:block_pulse_repeater_powered", "y": 270 },
"facing=0,inverted=0,powered=0,powering=0": { "model": "create:block_diodes_pulse_repeater", "y": 180 },
"facing=0,inverted=0,powered=0,powering=1": { "model": "create:block_pulse_repeater_powering", "y": 180 },
"facing=0,inverted=0,powered=1,powering=0": { "model": "create:block_pulse_repeater_powered", "y": 180 },
"facing=0,inverted=0,powered=1,powering=1": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 180
},
"facing=0,inverted=1,powered=0,powering=0": { "model": "create:block_pulse_repeater_powering", "y": 180 },
"facing=0,inverted=1,powered=0,powering=1": { "model": "create:block_diodes_pulse_repeater", "y": 180 },
"facing=0,inverted=1,powered=1,powering=0": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 180
},
"facing=0,inverted=1,powered=1,powering=1": { "model": "create:block_pulse_repeater_powered", "y": 180 },
"facing=2,inverted=0,powered=0,powering=0": { "model": "create:block_diodes_pulse_repeater" },
"facing=2,inverted=0,powered=0,powering=1": { "model": "create:block_pulse_repeater_powering" },
"facing=2,inverted=0,powered=1,powering=0": { "model": "create:block_pulse_repeater_powered" },
"facing=2,inverted=0,powered=1,powering=1": { "model": "create:block_pulse_repeater_powered_powering" },
"facing=2,inverted=1,powered=0,powering=0": { "model": "create:block_pulse_repeater_powering" },
"facing=2,inverted=1,powered=0,powering=1": { "model": "create:block_diodes_pulse_repeater" },
"facing=2,inverted=1,powered=1,powering=0": { "model": "create:block_pulse_repeater_powered_powering" },
"facing=2,inverted=1,powered=1,powering=1": { "model": "create:block_pulse_repeater_powered" },
"facing=3,inverted=0,powered=0,powering=0": { "model": "create:block_diodes_pulse_repeater", "y": 90 },
"facing=3,inverted=0,powered=0,powering=1": { "model": "create:block_pulse_repeater_powering", "y": 90 },
"facing=3,inverted=0,powered=1,powering=0": { "model": "create:block_pulse_repeater_powered", "y": 90 },
"facing=3,inverted=0,powered=1,powering=1": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 90
},
"facing=3,inverted=1,powered=0,powering=0": { "model": "create:block_pulse_repeater_powering", "y": 90 },
"facing=3,inverted=1,powered=0,powering=1": { "model": "create:block_diodes_pulse_repeater", "y": 90 },
"facing=3,inverted=1,powered=1,powering=0": {
"model": "create:block_pulse_repeater_powered_powering",
"y": 90
},
"facing=3,inverted=1,powered=1,powering=1": { "model": "create:block_pulse_repeater_powered", "y": 90 }
},
"states": [
{ "name": "facing", "bits": 2, "default": 0 },
{ "name": "inverted", "bits": 1, "default": 0 },
{ "name": "powered", "bits": 1, "default": 0 },
{ "name": "powering", "bits": 1, "default": 0 }
],
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:pulse_repeater",
"item_model": "create:item_pulse_repeater"
}
}
+4 -1
View File
@@ -29,4 +29,7 @@ turn it. Each block's fields there replace the ones the importer would write.
`block/radial_chassis_side_x` would both be `create:block_radial_chassis_side_x`.
Its `skip` leaves out the crimson and warped windows and window panes, and their models and textures, since bworld won't
have those woods.
have those woods. It leaves out the pulse repeater too, which is bworld's now
(`mods/bworld/blocks/pulse_repeater.json`): its id becomes bworld's, and so does the texture of the `indicator` model,
which uses the pulse repeater's. Its `textures` and `ids` also turn Minecraft's redstone torch into bworld's verdigris
torch.
+10 -1
View File
@@ -2,8 +2,17 @@
"models": {
"create:block/radial_chassis/": "create:block/radial_chassis/template_"
},
"textures": {
"minecraft:block/redstone_torch": "bworld:verdigris_torch",
"minecraft:block/redstone_torch_off": "bworld:verdigris_torch_off",
"create:block/diodes/pulse_repeater/idle": "bworld:pulse_repeater_idle"
},
"ids": {
"minecraft:redstone_torch": "bworld:verdigris_torch"
},
"skip": [
"crimson",
"warped"
"warped",
"pulse_repeater"
]
}
@@ -2,7 +2,7 @@
"format_version": 1,
"model": {
"id": "create:block_diodes_indicator",
"textures": { "flexpeater_off": "create:block_diodes_pulse_repeater_idle" },
"textures": { "flexpeater_off": "bworld:pulse_repeater_idle" },
"elements": [
{
"from": [3.96875, 1.96875, 3.96875],
@@ -4,7 +4,7 @@
"id": "create:block_diodes_latch_off",
"textures": {
"top": "create:block_diodes_powered_toggle_latch_idle",
"torch": "bworld:redstone_torch_off",
"torch": "bworld:verdigris_torch_off",
"smooth_stone": "bworld:smooth_stone",
"particle": "bworld:smooth_stone",
"base": "bworld:cobblestone",
@@ -5,7 +5,7 @@
"textures": {
"5": "create:block_diodes_powered_toggle_latch_powered_powering",
"top": "create:block_diodes_powered_toggle_latch_idle",
"torch": "bworld:redstone_torch",
"torch": "bworld:verdigris_torch",
"smooth_stone": "bworld:smooth_stone",
"particle": "bworld:smooth_stone",
"base": "bworld:cobblestone",
@@ -5,7 +5,7 @@
"textures": {
"4": "create:block_diodes_brass_diode_base",
"top": "create:block_diodes_pulse_extender_idle",
"torch": "bworld:redstone_torch_off",
"torch": "bworld:verdigris_torch_off",
"particle": "create:block_diodes_brass_diode_base"
},
"elements": [
@@ -3,6 +3,6 @@
"model": {
"id": "create:block_pulse_extender_powered_powering",
"parent": "create:block_diodes_pulse_extender",
"textures": { "top": "create:block_diodes_pulse_extender_powered_powering", "torch": "bworld:redstone_torch" }
"textures": { "top": "create:block_diodes_pulse_extender_powered_powering", "torch": "bworld:verdigris_torch" }
}
}
@@ -3,6 +3,6 @@
"model": {
"id": "create:block_pulse_extender_powering",
"parent": "create:block_diodes_pulse_extender",
"textures": { "top": "create:block_diodes_pulse_extender_powering", "torch": "bworld:redstone_torch" }
"textures": { "top": "create:block_diodes_pulse_extender_powering", "torch": "bworld:verdigris_torch" }
}
}
@@ -1,8 +0,0 @@
{
"format_version": 1,
"model": {
"id": "create:block_pulse_repeater_powered",
"parent": "create:block_diodes_pulse_repeater",
"textures": { "top": "create:block_diodes_pulse_repeater_powered" }
}
}
@@ -1,8 +0,0 @@
{
"format_version": 1,
"model": {
"id": "create:block_pulse_repeater_powered_powering",
"parent": "create:block_diodes_pulse_repeater",
"textures": { "top": "create:block_diodes_pulse_repeater_powered_powering", "torch": "bworld:redstone_torch" }
}
}
@@ -1,8 +0,0 @@
{
"format_version": 1,
"model": {
"id": "create:block_pulse_repeater_powering",
"parent": "create:block_diodes_pulse_repeater",
"textures": { "top": "create:block_diodes_pulse_repeater_powering", "torch": "bworld:redstone_torch" }
}
}
@@ -1,8 +0,0 @@
{
"format_version": 1,
"model": {
"id": "create:item_pulse_repeater",
"parent": "create:block_diodes_pulse_repeater",
"textures": { "top": "create:block_diodes_pulse_repeater_item" }
}
}
@@ -24,7 +24,6 @@
"create:redstone_link",
"create:analog_lever",
"create:placard",
"create:pulse_repeater",
"create:pulse_extender",
{ "id": "#bworld:banners", "required": false },
{ "id": "#bworld:signs", "required": false }
@@ -3,9 +3,9 @@
"tag": {
"values": [
{ "id": "bworld:redstone_wire", "required": false },
{ "id": "bworld:redstone_torch", "required": false },
"bworld:verdigris_torch",
{ "id": "bworld:repeater", "required": false },
{ "id": "bworld:lever", "required": false },
"bworld:lever",
{ "id": "bworld:comparator", "required": false },
{ "id": "bworld:observer", "required": false },
{ "id": "bworld:redstone_wall_torch", "required": false },
+163 -46
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
AIR,
BREAK_STAGES,
CHUNK_HEIGHT,
CHUNK_SIZE,
@@ -68,6 +69,7 @@ import type { Menu } from "./menu.ts";
import { MACHINE_CONN, SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
import { ScheduledTicks } from "./scheduled_ticks.ts";
import type { WorldSave, WorldSource } from "./saves.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
@@ -137,6 +139,9 @@ export interface SavedLevel {
// world time in ticks
time: number;
tiles: Tile[];
// the ticks blocks scheduled that haven't run, in the order they'll run, see ServerWorld.schedule_tick. ticks_left
// is 0 or less for ones waiting for a player to come near
scheduled_ticks: [x: number, y: number, z: number, id: string, ticks_left: number, priority: number][];
// every ctx.containers container, by id
containers: Record<string, (ItemData | null)[]>;
players: Record<string, SavedPlayer>;
@@ -164,6 +169,8 @@ export class GameServer {
#next_chunk_player = 0;
#saved_players: Record<string, SavedPlayer> = {};
#tick = 0;
// see ServerWorld.schedule_tick, due on game ticks
#scheduled = new ScheduledTicks();
// the last morning new day handlers ran for
#day = 0;
#mods: GameMods;
@@ -260,6 +267,11 @@ export class GameServer {
this.containers.set(id, container);
}
for (const tile of saved?.tiles ?? []) this.world.add_tile({ ...tile });
for (const [x, y, z, id, ticks_left, priority] of saved?.scheduled_ticks ?? []) {
// unless its mod is gone
const nid = this.world.block_ids[id];
if (nid !== undefined) this.#scheduled.add(x, y, z, nid, ticks_left, priority);
}
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
this.#saved_players = saved?.players ?? {};
// a new world is saved straight away
@@ -344,6 +356,8 @@ export class GameServer {
this.#broadcast({ type: "time", time: this.world.time });
}
this.#run_scheduled_ticks();
// the tiles near players that tick, picked before any runs so one that a handler adds waits for the next tick
const ticking: Tile[] = [];
if (this.world.has_ticking_tiles) {
@@ -399,6 +413,42 @@ export class GameServer {
}
}
// runs the block's components' on_scheduled_tick in delay ticks, see ServerWorld.schedule_tick
schedule_tick(x: number, y: number, z: number, delay: number, priority: number) {
const nid = this.world.get_block_nid(x, y, z);
if (nid === AIR) return;
this.#scheduled.add(x, y, z, nid, this.#tick + delay, priority);
this.world.dirty = true;
}
has_scheduled_tick(x: number, y: number, z: number) {
return this.#scheduled.has(x, y, z, this.world.get_block_nid(x, y, z));
}
// the scheduled ticks due near players, all taken before any runs, so one a handler schedules waits for its tick
#run_scheduled_ticks() {
const due = this.#scheduled.take_due(
this.#tick,
(chunk_x, chunk_z) => this.#near_any_player(chunk_x * CHUNK_SIZE, chunk_z * CHUNK_SIZE),
);
for (const { x, y, z, nid } of due) {
// another kind of block took its place
if (this.world.get_block_nid(x, y, z) !== nid) continue;
const id = this.world.get_block_id(x, y, z);
const components = this.mods.components_with(id, "on_scheduled_tick");
if (components.length === 0) continue;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_scheduled_tick`,
() => component.on_scheduled_tick!(block, params),
);
}
}
if (due.length > 0) this.world.dirty = true;
}
// level.json and the chunks generated or changed since the last save
save(): Required<WorldSave> {
for (const player of this.#players.values()) {
@@ -409,6 +459,14 @@ export class GameServer {
seed: this.world.seed,
time: this.world.time,
tiles: [...this.world.tiles.values()].map((tile) => ({ ...tile })),
scheduled_ticks: this.#scheduled.all().map((tick) => [
tick.x,
tick.y,
tick.z,
EverythingRegistry.get_by_id<BlockRegistry>("blocks", tick.nid)!.id,
tick.due - this.#tick,
tick.priority,
]),
containers: Object.fromEntries(
[...this.containers].map(([id, container]) => [id, container.to_data()]),
),
@@ -504,8 +562,9 @@ export class GameServer {
return this.entities.all().filter((entity) => entity instanceof ItemEntity);
}
send_chat(player: ServerPlayer, text: string) {
this.#send(player, { type: "chat", text });
// in chat, or above their hotbar for a moment with overlay, see MessageOptions
send_chat(player: ServerPlayer, text: string, overlay = false) {
this.#send(player, overlay ? { type: "chat", text, overlay } : { type: "chat", text });
}
// a mod's server script to its client script, see ctx.net
@@ -581,54 +640,73 @@ export class GameServer {
this.world.dirty = true;
}
// changes a block's state bits without anything else happening, see ServerWorld.get_block_value
set_block_state(x: number, y: number, z: number, state: number) {
// changes a block's state bits without replacing it, see ServerWorld.get_block_value: its on_state_change, then the
// blocks beside it hear of it, unless update_neighbors is false
set_block_state(x: number, y: number, z: number, state: number, update_neighbors = true) {
const id = this.world.get_block_id(x, y, z);
if (id !== AIR_ID && this.world.get_block_value(x, y, z) >>> 16 !== state) {
const value = this.world.get_block_value(x, y, z);
if (id === AIR_ID || value >>> 16 === state) return;
this.mods.rules.change(() => {
const components = this.mods.components_with(id, "on_state_change");
// only worked out for blocks that want it, states change often
const before = components.length > 0 ? block_states(value, this.world.get_block_info(x, y, z)!) : undefined;
this.world.set_block(x, y, z, id, state);
this.#notify_neighbors(x, y, z);
}
}
// 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) {
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) {
const old_id = this.world.get_block_id(x, y, z);
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
if (old_id !== AIR_ID) {
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
if (components.length > 0) {
const block = this.mods.block_ref(x, y, z, old_id);
const player_api = player && this.mods.player(player);
if (before) {
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(mod, `${component_id} on_break`, () => component.on_break!(block, params, player_api));
run_guarded(
mod,
`${component_id} on_state_change`,
() => component.on_state_change!(block, params, before),
);
}
}
}
if (update_neighbors) this.mods.rules.notify_neighbors(x, y, z);
});
}
this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state);
if (id !== AIR_ID) {
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
// replaces a block: the old one's on_break, then the new one's on_create, then the blocks beside it hear of it
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
this.mods.rules.change(() => {
const old_id = this.world.get_block_id(x, y, z);
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
if (old_id !== AIR_ID) {
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
if (components.length > 0) {
const block = this.mods.block_ref(x, y, z, old_id);
const player_api = player && this.mods.player(player);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_break`,
() => component.on_break!(block, params, player_api),
);
}
}
}
}
this.#notify_neighbors(x, y, z);
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was dug
if (y + 1 < CHUNK_HEIGHT) {
const above = this.world.get_block_info(x, y + 1, z);
if (above && !can_stand_on(above, id)) {
this.destroy_block(x, y + 1, z, player);
this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state);
if (id !== AIR_ID) {
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
}
}
}
}
this.mods.rules.notify_neighbors(x, y, z);
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was
// dug
if (y + 1 < CHUNK_HEIGHT) {
const above = this.world.get_block_info(x, y + 1, z);
if (above && !can_stand_on(above, id)) {
this.destroy_block(x, y + 1, z, player);
}
}
});
}
// the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress
@@ -1015,16 +1093,27 @@ export class GameServer {
// a client that hadn't heard it's using an item yet: what it guessed the click did, it didn't
this.#correct_use(player, message.x, message.y, message.z, message.face);
} else {
// the middle of the block when a client doesn't say, or says something that isn't on it
const hit = Array.isArray(message.hit) && message.hit.length === 3 &&
message.hit.every((v) => typeof v === "number" && v >= 0 && v <= 1)
? message.hit
: [0.5, 0.5, 0.5];
this.#use_block(player, message.x, message.y, message.z, message.face, hit);
this.#use_block(
player,
message.x,
message.y,
message.z,
message.face,
hit_on_block(message.hit),
);
}
}
this.#ack(player, message.seq);
break;
case "scroll_block":
if (
is_block_position(message.x, message.y, message.z) && faces.includes(message.face) &&
is_int(message.amount) && message.amount !== 0
) {
const { x, y, z, face, amount } = message;
this.#scroll_block(player, x, y, z, face, hit_on_block(message.hit), amount);
}
break;
case "select_slot":
if (is_int(message.slot) && message.slot >= 0 && message.slot < 9) {
if (message.slot !== player.selected_slot) player.attack_strength_ticker = 0;
@@ -1200,6 +1289,26 @@ export class GameServer {
this.#correct(player, target.x, target.y, target.z);
}
// the mouse wheel turned at a scrollable block in reach: its components' on_scroll
#scroll_block(
player: ServerPlayer,
x: number,
y: number,
z: number,
face: Faces,
hit: [number, number, number],
amount: number,
) {
const info = this.world.get_block_info(x, y, z);
if (!info?.scrollable || !this.#in_reach(player, x, y, z)) return;
const block = this.mods.block_ref(x, y, z, info.id);
const player_api = this.mods.player(player);
const scroll = { amount, face, hit };
for (const { mod, id, component, params } of this.mods.components_with(info.id, "on_scroll")) {
run_guarded(mod, `${id} on_scroll`, () => component.on_scroll!(block, params, player_api, scroll));
}
}
#use_block(player: ServerPlayer, x: number, y: number, z: number, face: Faces, hit: number[]) {
const info = this.world.get_block_info(x, y, z);
const target = placement_target(x, y, z, FACE_OFFSETS[face], info);
@@ -2314,6 +2423,14 @@ function view_distance(requested: unknown, server: number): number {
return Math.min(server, Math.max(MIN_VIEW_DISTANCE, Math.min(MAX_VIEW_DISTANCE, requested)));
}
// where on a block a client says it clicked or looks, 0 to 1 on each axis. the middle when it doesn't say, or says
// something that isn't on it
function hit_on_block(hit: unknown): [number, number, number] {
return Array.isArray(hit) && hit.length === 3 && hit.every((v) => typeof v === "number" && v >= 0 && v <= 1)
? [hit[0], hit[1], hit[2]]
: [0.5, 0.5, 0.5];
}
// messages are parsed json, so the types in ClientMessage are only what a well behaved client sends
function is_block_position(x: unknown, y: unknown, z: unknown): boolean {
return is_int(x) && is_int(y) && is_int(z) && y >= 0 && y < CHUNK_HEIGHT &&
+66 -9
View File
@@ -7,8 +7,8 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { block_states, get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts";
import { LootTables } from "./loot.ts";
import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
import { AIR, faces, ID_MASK } from "$/common/constants.ts";
import { collision_shape_at, covers_face, is_solid, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
import { AIR, CHUNK_SIZE, faces, ID_MASK } from "$/common/constants.ts";
import { physics } from "$/common/physics.ts";
import { clock } from "$/common/time.ts";
import { BlockRules } from "$/common/block_rules.ts";
@@ -34,6 +34,7 @@ import type {
MenuType,
Player,
PlayerMenuBuilder,
Position,
ServerAfterEvents,
ServerBeforeEvents,
ServerContext,
@@ -57,6 +58,7 @@ import {
} from "$/common/commands.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts";
import { MAX_PRIORITY, MIN_PRIORITY } from "./scheduled_ticks.ts";
import type { ServerPlayer } from "./player.ts";
import { Menu, type MenuSlot } from "./menu.ts";
import { damage_source, type Entity } from "./entity/entity.ts";
@@ -143,8 +145,12 @@ 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);
// what shared scripts registered, see common/block_rules.ts, running on the game's world
rules = new BlockRules(
run_guarded,
(x, y, z) => this.game.world.get_block_id(x, y, z),
(x, y, z, from) => this.#neighbor_changed(x, y, z, from),
);
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
@@ -479,6 +485,38 @@ export class ModRuntime {
}
#ticking_components_of = new Map<string, BlockComponentOf[]>();
// the ones with a handler, for handlers that run often, like on_neighbor_change. cached like components_of
components_with(block_id: string, handler: keyof BlockComponent): readonly BlockComponentOf[] {
let of_handler = this.#components_with.get(handler);
if (!of_handler) this.#components_with.set(handler, of_handler = new Map());
let components = of_handler.get(block_id);
if (!components) {
components = this.components_of(block_id).filter(({ component }) => component[handler]);
of_handler.set(block_id, components);
}
return components;
}
#components_with = new Map<keyof BlockComponent, Map<string, BlockComponentOf[]>>();
// the block at x y z was told the one at from changed, and its rules have had their say: its components'
// on_neighbor_change
#neighbor_changed(x: number, y: number, z: number, from: Position) {
const world = this.game.world;
// read again, a rule's state change can have had a component replace it
const id = world.get_block_id(x, y, z);
const components = this.components_with(id, "on_neighbor_change");
if (components.length === 0) return;
const block = this.block_ref(x, y, z, id);
const neighbor = { ...from, id: world.get_block_id(from.x, from.y, from.z) };
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),
);
}
}
// components on an item, with their params from its json
item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] {
const item = EverythingRegistry.get<ItemRegistry>("items", item_id);
@@ -604,6 +642,7 @@ export class ModRuntime {
this.block_components.set(id, { mod, component: component as BlockComponent });
this.#components_of.clear();
this.#ticking_components_of.clear();
this.#components_with.clear();
},
register_item: (id, component) => {
setup_only("components");
@@ -694,7 +733,7 @@ export class ModRuntime {
const info = state_owner(id, name);
return get_state_value(game().world.get_block_value(x, y, z), info, name);
},
set_state: (x, y, z, name, value) => {
set_state: (x, y, z, name, value, options) => {
const id = game().world.get_block_id(x, y, z);
if (id === AIR_ID) return false;
const info = state_owner(id, name);
@@ -703,9 +742,21 @@ export class ModRuntime {
throw new Error(`${id} state "${name}" has ${bits} bits, ${value} doesn't fit`);
}
const new_value = set_state_value(game().world.get_block_value(x, y, z), info, name, value)!;
game().set_block_state(x, y, z, new_value >>> 16);
game().set_block_state(x, y, z, new_value >>> 16, options?.update_neighbors !== false);
return true;
},
neighbor_changed: (x, y, z, from) =>
this.rules.neighbor_changed(x, y, z, { x: from.x, y: from.y, z: from.z }),
schedule_tick: (x, y, z, delay, priority = 0) => {
if (!Number.isInteger(delay) || delay < 1) {
throw new Error(`a tick is scheduled at least 1 tick ahead, in whole ticks, not ${delay}`);
}
if (!Number.isInteger(priority) || priority < MIN_PRIORITY || priority > MAX_PRIORITY) {
throw new Error(`a tick's priority is ${MIN_PRIORITY} to ${MAX_PRIORITY}, not ${priority}`);
}
game().schedule_tick(x, y, z, delay, priority);
},
has_scheduled_tick: (x, y, z) => game().has_scheduled_tick(x, y, z),
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
get_block_ref: (x, y, z) => {
@@ -797,7 +848,7 @@ export class ModRuntime {
// without any -0
return { x: fx + 0, y: fy + 0, z: fz + 0 };
},
is_loaded: () => true,
is_loaded: (x, z) => game().world.is_generated(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)),
biome_at: (x, z) => game().world.biome_at(Math.floor(x), Math.floor(z)),
season_at: (x, z) =>
biome_season(game().world.biome_at(Math.floor(x), Math.floor(z)), game().world.time),
@@ -868,6 +919,12 @@ export class ModRuntime {
if (!block) throw new Error(`unknown block ${id}`);
return structuredClone(block.components ?? {});
},
solid: (id) => {
if (id === AIR_ID) return false;
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`unknown block ${id}`);
return is_solid(block);
},
},
recipes: {
furnace_result: (input) => {
@@ -1326,8 +1383,8 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`);
game.give(player, id, count, data);
},
send_message(text) {
game.send_chat(player, String(text));
send_message(text, options) {
game.send_chat(player, String(text), options?.overlay === true);
},
set_worn(key, items) {
if (typeof key !== "string" || key.length === 0) throw new Error('set_worn needs a key, like "mymod:hats"');
+143
View File
@@ -0,0 +1,143 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// ticks blocks asked for some ticks ahead, see ServerWorld.schedule_tick. kept by chunk and grouped by when they're due,
// so a tick costs nothing until it's due, and a chunk with none due is passed over with one comparison
import { CHUNK_SIZE } from "$/common/constants.ts";
import { chunk_key } from "$/common/utils.ts";
import { index_in_chunk } from "./world.ts";
// the most that run in one tick. the rest run first the next
export const MAX_SCHEDULED_TICKS = 65536;
// priorities go from -8 to 7, so with 8 added one fits in 4 bits under the due tick
export const MIN_PRIORITY = -8;
export const MAX_PRIORITY = 7;
export interface ScheduledTick {
readonly x: number;
readonly y: number;
readonly z: number;
// the numeric id of the block it was scheduled for. it's dropped if another kind of block is there when it's due
readonly nid: number;
readonly due: number;
readonly priority: number;
// due * 16 + priority + 8: smaller runs first
readonly key: number;
// counts up with every tick scheduled, so of ticks with the same key the first scheduled runs first
readonly order: number;
// nid * 65536 + index in chunk, which is one per block, see ChunkTicks.waiting
readonly block: number;
}
class ChunkTicks {
// by key, each in the order they were scheduled
groups = new Map<number, ScheduledTick[]>();
// the keys of groups, smallest first. only a few, since delays are short
keys: number[] = [];
// ScheduledTick.block of every tick waiting here, so the same block can't wait twice
waiting = new Set<number>();
constructor(readonly x: number, readonly z: number) {}
add(tick: ScheduledTick) {
this.waiting.add(tick.block);
const group = this.groups.get(tick.key);
if (group) {
group.push(tick);
return;
}
this.groups.set(tick.key, [tick]);
// usually later than every other
let i = this.keys.length;
while (i > 0 && this.keys[i - 1] > tick.key) i--;
this.keys.splice(i, 0, tick.key);
}
// takes out every tick that runs before or with the tick with this key and order
remove_through(key: number, order: number) {
while (this.keys.length > 0 && this.keys[0] <= key) {
const group = this.groups.get(this.keys[0])!;
let taken = group.length;
if (this.keys[0] === key) {
taken = 0;
while (taken < group.length && group[taken].order <= order) taken++;
}
for (let i = 0; i < taken; i++) this.waiting.delete(group[i].block);
if (taken < group.length) {
group.splice(0, taken);
return;
}
this.groups.delete(this.keys[0]);
this.keys.shift();
}
}
}
export class ScheduledTicks {
#chunks = new Map<number, ChunkTicks>();
#order = 0;
// adds a tick for the block nid at x y z on tick due, unless one already waits for it there
add(x: number, y: number, z: number, nid: number, due: number, priority: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const key = chunk_key(chunk_x, chunk_z);
let chunk = this.#chunks.get(key);
const block = block_key(x, y, z, chunk_x, chunk_z, nid);
if (chunk?.waiting.has(block)) return;
if (!chunk) this.#chunks.set(key, chunk = new ChunkTicks(chunk_x, chunk_z));
const order = this.#order++;
chunk.add({ x, y, z, nid, due, priority, key: due * 16 + priority + 8, order, block });
}
has(x: number, y: number, z: number, nid: number) {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.#chunks.get(chunk_key(chunk_x, chunk_z));
return chunk?.waiting.has(block_key(x, y, z, chunk_x, chunk_z, nid)) ?? false;
}
// takes the ticks due by now in the chunks near says are near players, at most max, in the order they run: by
// due tick, then priority, then the order they were scheduled in. what's left over stays, and runs first next time
take_due(now: number, near: (chunk_x: number, chunk_z: number) => boolean, max = MAX_SCHEDULED_TICKS) {
const due_before = (now + 1) * 16;
const chunks: ChunkTicks[] = [];
const due: ScheduledTick[] = [];
for (const chunk of this.#chunks.values()) {
if (chunk.keys[0] >= due_before || !near(chunk.x, chunk.z)) continue;
chunks.push(chunk);
for (const key of chunk.keys) {
if (key >= due_before) break;
for (const tick of chunk.groups.get(key)!) due.push(tick);
}
}
if (due.length === 0) return due;
due.sort(run_order);
if (due.length > max) due.length = max;
const last = due[due.length - 1];
for (const chunk of chunks) {
chunk.remove_through(last.key, last.order);
if (chunk.waiting.size === 0) this.#chunks.delete(chunk_key(chunk.x, chunk.z));
}
return due;
}
// every tick waiting, in the order they'd run, for saving
all(): ScheduledTick[] {
const all: ScheduledTick[] = [];
for (const chunk of this.#chunks.values()) {
for (const group of chunk.groups.values()) all.push(...group);
}
return all.sort(run_order);
}
}
function run_order(a: ScheduledTick, b: ScheduledTick) {
return a.key - b.key || a.order - b.order;
}
// a block's place in its chunk, under 65536 since chunks are 256 tall, with its numeric id above
function block_key(x: number, y: number, z: number, chunk_x: number, chunk_z: number, nid: number) {
return nid * 65536 + index_in_chunk(x, y, z, chunk_x, chunk_z);
}
+8 -1
View File
@@ -272,6 +272,13 @@ export class ServerWorld {
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
}
// whether the chunk was ever generated: it's kept, or saved, so reading it generates nothing. it may not be in
// memory, then reading it decodes it from the save
is_generated(chunk_x: number, chunk_z: number) {
const key = chunk_key(chunk_x, chunk_z);
return this.#chunks.has(key) || this.#is_saved(key);
}
// counts as using the chunk so it's kept longer, if it's there. returns whether it is, see has_chunk
keep_chunk(chunk_x: number, chunk_z: number) {
return this.#chunks.get(chunk_key(chunk_x, chunk_z)) !== undefined;
@@ -733,7 +740,7 @@ function fallback_caller(stack: string) {
return match ? `${match[1] ?? "?"} ${match[2]}` : outside;
}
function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
export function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE);
}
+23 -1
View File
@@ -9,11 +9,12 @@ import {
collision_shape_at,
EMPTY_SHAPE,
FULL_SHAPE,
is_solid,
model_shape,
raycast_blocks,
type Shape,
} from "$/common/block_shapes.ts";
import { block_from_json, validate_block } from "$/common/mod_data.ts";
import { block_from_json, type BlockJson, validate_block } from "$/common/mod_data.ts";
import { move_body } from "$/common/physics.ts";
import { box_overlaps_block } from "$/common/utils.ts";
@@ -173,3 +174,24 @@ Deno.test("an x turn turns a model's shape with it", () => {
// then y turns the south half to the west
assertEquals(model_shape(slab, 90, 90), [[0, 0, 0, 0.5, 1, 1]]);
});
Deno.test("a solid block is drawn in the solid layer and is a whole block to bump into, whatever its states", () => {
const block = (json: Partial<BlockJson>) =>
block_from_json({ id: "test:block", textures: "test:stone", ...json }).block;
const states = [{ name: "age", bits: 1, default: 0 }];
assert(is_solid(block({})));
assert(
is_solid(block({ states, variants: { "age=1": { y: 90, textures: "test:mossy" } } })),
"turned, other textures",
);
assert(!is_solid(block({ render_layer: "cutout" })), "like leaves");
assert(!is_solid(block({ render_layer: "translucent" })), "like glass");
assert(!is_solid(block({ collision: false })));
assert(!is_solid(block({ shape: [[0, 0, 0, 16, 8, 16]] })), "like a slab");
assert(!is_solid(block({ states, variants: { "age=1": { model: "engine:cross" } } })), "not in one of its states");
assert(!is_solid(block({ states, variants: { "age=1": { collision_shape: [[0, 0, 0, 16, 8, 16]] } } })));
assert(
is_solid(block({ shape: [[0, 0, 0, 16, 8, 16]], collision_shape: [[0, 0, 0, 16, 16, 16]] })),
"what it bumps into counts",
);
});
+101 -2
View File
@@ -2,17 +2,23 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { resolve, toFileUrl } from "@std/path";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { load_and_check, load_order } from "$/tools/check_mods.ts";
import { mod_data } from "$/common/mod_check.ts";
import type { ServerModSource } from "$/server/game/load_mods.ts";
import { GameServer } from "$/server/game/game_server.ts";
import { start_game } from "$/server/game/load_mods.ts";
import { apply_config } from "$/server/load_bmods.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { AIR_ID, PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { SavedChunk, SavedChunks, WorldSave } from "$/server/game/saves.ts";
import { BlockRules } from "$/common/block_rules.ts";
import { collision_shape_at, covers_face, is_solid } from "$/common/block_shapes.ts";
import { tag_api } from "$/common/tags.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";
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
// mods/ is kept, since tests change the temporary folders they make between games
@@ -184,3 +190,96 @@ export const container_items = (messages: Msg[], container: string) =>
// what the open menu's data last was among messages
export const menu_data = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_data")?.data;
// a box of blocks, by the lowest and highest of each coordinate in it
export interface Area {
x: [number, number];
y: [number, number];
z: [number, number];
}
// every block in the area, as id and state bits
function blocks_in(area: Area, 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;
}
export function server_blocks(game: GameServer, area: Area) {
return blocks_in(area, (x, y, z) => [game.world.get_block_id(x, y, z), 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
export function client_of(game: GameServer, area: Area) {
const copy = new Map<string, [string, number]>();
for (const line of server_blocks(game, area)) {
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(), (x, y, z) => at(x, y, z)?.[0]);
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(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);
},
biome_at: () => undefined,
season_at: () => undefined,
};
setup_shared({
mod: { id: "bworld", version: "test" },
side: "client",
tags: tag_api(),
blocks: {
exists: (id) => info(id) !== undefined,
components: (id) => structuredClone(info(id)!.components ?? {}),
solid: (id) => id !== AIR_ID && is_solid(info(id)!),
},
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, 0, { x, y, z, face, hit, sneaking: false });
// its rules say it can't go there
if (value === undefined) return;
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
rules.notify_neighbors(x, y, z);
},
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit, sneaking: false }, yaw);
},
break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
rules.notify_neighbors(x, y, z);
},
blocks: () => blocks_in(area, (x, y, z) => at(x, y, z)!),
};
}
+252
View File
@@ -0,0 +1,252 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the server's side of a block hearing about changes: its components' on_neighbor_change, after the shared rules, and
// on_state_change when its own states change. blocks hear of changes through a queue, once the change is done
import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "$/common/protocol.ts";
import { MAX_NEIGHBOR_UPDATES } from "$/common/block_rules.ts";
import { get_state_value } from "$/common/utils.ts";
import type { GameServer } from "$/server/game/game_server.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
const at = ({ x, y, z }: { x: number; y: number; z: number }) => x + " " + y + " " + z;
ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block, _params, neighbor) {
const seen = ctx.world.get_state(block.x, block.y, block.z, "seen");
log(["neighbor", at(block), neighbor.id, at(neighbor), seen]);
},
on_state_change(block, _params, before) {
const { x, y, z } = block;
const now = { seen: ctx.world.get_state(x, y, z, "seen"), count: ctx.world.get_state(x, y, z, "count") };
log(["state", at(block), before, now]);
},
});
// hangs from the block above and falls when it's gone, which only a server handler can do
ctx.components.register_block("testmod:lantern", {
on_neighbor_change(block) {
if (ctx.world.get_block(block.x, block.y + 1, block.z) === "bworld:air") {
ctx.world.break_block(block.x, block.y, block.z);
}
},
});
// tells the block two to the east when it's broken, which isn't beside it
ctx.components.register_block("testmod:tether", {
on_break(block) { ctx.world.neighbor_changed(block.x + 2, block.y, block.z, block); },
});
ctx.commands.register("state", {
description: "", usage: "",
run([x, y, z, name, value, quiet]) {
const options = quiet === "quiet" ? { update_neighbors: false } : undefined;
ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value), options);
},
});
ctx.commands.register("tell", {
description: "", usage: "",
run(args) {
const [x, y, z, fx, fy, fz] = args.map(Number);
ctx.world.neighbor_changed(x, y, z, { x: fx, y: fy, z: fz });
},
});
}
`;
const SHARED_SCRIPT = `
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
// marks the watcher once anything beside it changes
ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); },
});
// passes a count back and forth with a relay beside it, one higher each time, up to 10000
ctx.components.register_block("testmod:relay", {
on_neighbor_change(block, _params, neighbor) {
if (neighbor.id !== "testmod:relay") return;
const theirs = ctx.world.get_state(neighbor.x, neighbor.y, neighbor.z, "count")!;
const mine = ctx.world.get_state(block.x, block.y, block.z, "count")!;
if (theirs >= mine && theirs < 10000) ctx.world.set_state(block.x, block.y, block.z, "count", theirs + 1);
},
});
// flips whenever anything beside it changes, so two side by side never stop
ctx.components.register_block("testmod:flipper", {
on_neighbor_change(block) {
const on = ctx.world.get_state(block.x, block.y, block.z, "on")!;
ctx.world.set_state(block.x, block.y, block.z, "on", 1 - on);
},
});
}
`;
function test_mods() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_neighbors_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
write("manifest.json", {
format_version: 1,
id: "testmod",
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
});
const block = (name: string, states: unknown[] = []) =>
write(`blocks/${name}.json`, {
format_version: 1,
block: {
id: `testmod:${name}`,
textures: "bworld:stone",
mining: { toughness: 1 },
states,
components: { [`testmod:${name}`]: {} },
},
});
block("watcher", [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }]);
block("lantern");
block("tether");
block("relay", [{ name: "count", bits: 14, default: 0 }]);
block("flipper", [{ name: "on", bits: 1, default: 0 }]);
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
return dir;
}
async function setup() {
const dir = test_mods();
const { game, send, join } = await test_game(dir);
join(1, "alice");
stone_floor(game);
send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: 0, pitch: 0 });
// what happened since it was last called
const log = () => {
const events = (game.mods.storage.testmod?.log ?? []) as unknown[];
delete game.mods.storage.testmod?.log;
return events;
};
const command = (text: string) => send(1, { type: "chat", text });
const cleanup = () => Deno.removeSync(dir, { recursive: true });
return { game, log, command, cleanup };
}
function state(game: GameServer, x: number, y: number, z: number, name: string) {
return get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
}
Deno.test("a component's on_neighbor_change runs after the block's rules, and can change the world", async () => {
const { game, log, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
log();
game.set_block(1, 100, 0, "bworld:stone");
assertEquals(log(), [
["state", "0 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
// the rule had marked it already
["neighbor", "0 100 0", "bworld:stone", "1 100 0", 1],
]);
game.set_block(1, 100, 0, AIR_ID);
assertEquals(log(), [["neighbor", "0 100 0", AIR_ID, "1 100 0", 1]], "the block that changed is what's there now");
game.set_block(3, 101, 0, "bworld:stone");
game.set_block(3, 100, 0, "testmod:lantern");
game.set_block(4, 100, 0, "bworld:stone");
assertEquals(game.world.get_block_id(3, 100, 0), "testmod:lantern");
game.set_block(3, 101, 0, AIR_ID);
assertEquals(game.world.get_block_id(3, 100, 0), AIR_ID, "it fell once what it hung from was gone");
cleanup();
});
Deno.test("on_state_change gets the states from before, when a script or a rule changes them", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
log();
command("/state 0 100 0 count 3");
assertEquals(log(), [["state", "0 100 0", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]);
command("/state 0 100 0 count 3");
assertEquals(log(), [], "setting a state to what it is changes nothing");
// a rule
game.set_block(0, 101, 0, "bworld:stone");
assertEquals(log()[0], ["state", "0 100 0", { seen: 0, count: 3 }, { seen: 1, count: 3 }]);
// replacing it is a new block, not a state change
game.set_block(0, 100, 0, "testmod:watcher");
assertEquals(log(), []);
assertEquals(game.world.get_block_value(0, 100, 0) >>> 16, 0);
cleanup();
});
Deno.test("a script can tell any block of a change, and one told in on_break hears once the block is gone", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(2, 100, 0, "testmod:watcher");
game.set_block(0, 100, 0, "testmod:tether");
log();
game.set_block(0, 100, 0, AIR_ID);
assertEquals(log(), [
// its rule and its component heard
["state", "2 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
["neighbor", "2 100 0", AIR_ID, "0 100 0", 1],
]);
// right away, when nothing else is changing
command("/tell 2 100 0 2 100 5");
assertEquals(log(), [["neighbor", "2 100 0", "bworld:air", "2 100 5", 1]]);
cleanup();
});
Deno.test("update_neighbors false changes a state without telling anyone, but on_state_change runs", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
game.set_block(1, 100, 0, "testmod:watcher");
log();
command("/state 0 100 0 count 5 quiet");
assertEquals(log(), [["state", "0 100 0", { seen: 1, count: 0 }, { seen: 1, count: 5 }]]);
command("/state 0 100 0 count 6");
assert(
log().some((event) =>
JSON.stringify(event) === JSON.stringify(["neighbor", "1 100 0", "testmod:watcher", "0 100 0", 1])
),
);
cleanup();
});
Deno.test("a chain of 10000 changes, each setting off the next, runs to the end", async () => {
const { game, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:relay");
game.set_block(1, 100, 0, "testmod:relay");
const counts = [state(game, 0, 100, 0, "count")!, state(game, 1, 100, 0, "count")!];
assertEquals(Math.max(...counts), 10000);
assertEquals(Math.min(...counts), 9999);
cleanup();
});
Deno.test("blocks that keep setting each other off are stopped, and the server says where", async () => {
const { game, log, cleanup } = await setup();
const warn = console.warn;
const warnings: string[] = [];
console.warn = (...args: unknown[]) => warnings.push(args.join(" "));
try {
game.set_block(0, 100, 0, "testmod:flipper");
game.set_block(1, 100, 0, "testmod:flipper");
} finally {
console.warn = warn;
}
assertEquals(warnings.length, 1);
assert(warnings[0].includes(String(MAX_NEIGHBOR_UPDATES)), warnings[0]);
const [x, y, z] = warnings[0].match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assert(Math.abs(x - 0.5) <= 1.5 && Math.abs(y - 100) <= 1 && Math.abs(z) <= 1, "beside the flippers");
// the next change goes as usual
game.set_block(0, 100, 3, "testmod:watcher");
log();
game.set_block(1, 100, 3, "bworld:stone");
assertEquals(log().length, 2);
cleanup();
});
+193
View File
@@ -0,0 +1,193 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// ticks blocks schedule ahead with ctx.world.schedule_tick: when and in what order they run, and that they last
import { assert, assertEquals } from "@std/assert";
import { ScheduledTicks } from "$/server/game/scheduled_ticks.ts";
import type { WorldSave } from "$/server/game/saves.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
ctx.components.register_block("testmod:clock", {
on_scheduled_tick(block) { log([block.x, ctx.system.current_tick]); },
});
// ticks 3 times, 2 ticks apart, scheduling each next one from the last
ctx.components.register_block("testmod:pulser", {
on_scheduled_tick(block) {
const { x, y, z } = block;
const count = ctx.world.get_state(x, y, z, "count")! + 1;
ctx.world.set_state(x, y, z, "count", count);
log([x, ctx.system.current_tick]);
if (count < 3) ctx.world.schedule_tick(x, y, z, 2);
},
});
ctx.commands.register("schedule", {
description: "", usage: "",
run(args) {
const [x, y, z, delay, priority] = args.map(Number);
try {
ctx.world.schedule_tick(x, y, z, delay, args[4] === undefined ? undefined : priority);
} catch (e) {
log(["error", (e as Error).message]);
}
},
});
ctx.commands.register("scheduled", {
description: "", usage: "",
run([x, y, z]) { log(["scheduled", ctx.world.has_scheduled_tick(Number(x), Number(y), Number(z))]); },
});
}
`;
function test_mods() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_scheduled_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
write("manifest.json", {
format_version: 1,
id: "testmod",
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
});
const block = (name: string, states: unknown[] = []) =>
write(`blocks/${name}.json`, {
format_version: 1,
block: {
id: `testmod:${name}`,
textures: "bworld:stone",
mining: { toughness: 1 },
states,
components: { [`testmod:${name}`]: {} },
},
});
block("clock");
block("pulser", [{ name: "count", bits: 2, default: 0 }]);
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
return dir;
}
async function setup(dir = test_mods(), save?: WorldSave) {
const { game, send, join } = await test_game(dir, save);
join(1, "alice");
stone_floor(game);
send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: 0, pitch: 0 });
// what happened since it was last called
const log = () => {
const events = (game.mods.storage.testmod?.log ?? []) as unknown[];
delete game.mods.storage.testmod?.log;
return events;
};
const command = (text: string) => send(1, { type: "chat", text });
const ticks = (n: number) => {
for (let i = 0; i < n; i++) game.tick();
};
const cleanup = () => Deno.removeSync(dir, { recursive: true });
return { game, dir, log, command, ticks, cleanup };
}
Deno.test("scheduled ticks run when they're due, by priority, then in the order they were scheduled", async () => {
const { game, log, command, ticks, cleanup } = await setup();
for (let x = 0; x < 5; x++) game.set_block(x, 100, 0, "testmod:clock");
const start = game.current_tick;
command("/schedule 0 100 0 3");
command("/schedule 1 100 0 2");
command("/schedule 2 100 0 2 -1");
command("/schedule 3 100 0 2");
command("/schedule 4 100 0 1");
ticks(4);
assertEquals(log(), [[4, start + 1], [2, start + 2], [1, start + 2], [3, start + 2], [0, start + 3]]);
cleanup();
});
Deno.test("a block waits for one tick at a time, and can schedule its next one from it", async () => {
const { game, log, command, ticks, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:clock");
const start = game.current_tick;
command("/scheduled 0 100 0");
command("/schedule 0 100 0 5");
command("/schedule 0 100 0 1");
command("/scheduled 0 100 0");
ticks(5);
assertEquals(log(), [["scheduled", false], ["scheduled", true], [0, start + 5]], "the second did nothing");
game.set_block(1, 100, 0, "testmod:pulser");
command("/schedule 1 100 0 2");
ticks(10);
assertEquals(log(), [[1, start + 7], [1, start + 9], [1, start + 11]]);
command("/scheduled 1 100 0");
assertEquals(log(), [["scheduled", false]]);
command("/schedule 0 100 0 0");
command("/schedule 0 100 0 1 8");
assertEquals(log().map((event) => (event as string[])[0]), ["error", "error"]);
cleanup();
});
Deno.test("a tick is dropped when another kind of block takes its place", async () => {
const { game, log, command, ticks, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:clock");
command("/schedule 0 100 0 2");
game.set_block(0, 100, 0, "bworld:stone");
command("/scheduled 0 100 0");
ticks(2);
game.set_block(0, 100, 0, "testmod:clock");
ticks(3);
assertEquals(log(), [["scheduled", false]], "the stone hasn't one, and it was gone by the clock put back after");
cleanup();
});
Deno.test("ticks far from every player wait until one comes near", async () => {
const { game, log, command, ticks, cleanup } = await setup();
game.set_block(16 * 20, 100, 0, "testmod:clock");
command(`/schedule ${16 * 20} 100 0 1`);
ticks(5);
assertEquals(log(), []);
game.teleport(game.players()[0], 16 * 20 + 0.5, 101, 0.5);
ticks(1);
assertEquals(log(), [[16 * 20, game.current_tick]]);
cleanup();
});
Deno.test("ticks waiting when the world is saved run where they left off after it's loaded", async () => {
const { game, dir, command, ticks } = await setup();
game.set_block(0, 100, 0, "testmod:clock");
game.set_block(1, 100, 0, "testmod:clock");
game.set_block(16 * 20, 100, 0, "testmod:clock");
command("/schedule 0 100 0 10");
command("/schedule 1 100 0 10 -1");
command(`/schedule ${16 * 20} 100 0 1`);
ticks(4);
const saved = game.save();
const again = await setup(dir, saved);
const start = again.game.current_tick;
again.ticks(5);
assertEquals(again.log(), []);
again.ticks(1);
assertEquals(again.log(), [[1, start + 6], [0, start + 6]]);
// the far one had been due for 3 ticks, and still waits
again.game.teleport(again.game.players()[0], 16 * 20 + 0.5, 101, 0.5);
again.ticks(1);
assertEquals(again.log(), [[16 * 20, start + 7]]);
again.cleanup();
});
Deno.test("past the most that run in a tick, the rest run first the next", () => {
const ticks = new ScheduledTicks();
const near = () => true;
for (let x = 0; x < 5; x++) ticks.add(x, 100, 0, 1, 10, 0);
ticks.add(0, 100, 20, 1, 11, -8);
const taken = (now: number) => ticks.take_due(now, near, 3).map((tick) => `${tick.x} ${tick.z}`);
assertEquals(taken(9), []);
assertEquals(taken(10), ["0 0", "1 0", "2 0"]);
assertEquals(taken(11), ["3 0", "4 0", "0 20"]);
assertEquals(taken(12), []);
assert(!ticks.has(0, 100, 0, 1));
});

Some files were not shown because too many files have changed in this diff Show More