Files
bworld/docs/modding/blocks/components.md
T

23 KiB
Raw Blame History

Block Components

A block's JSON says what it is. Components say what it does. A component is a set of handlers a server script registers under an id. Any block that lists that id in its components gets that behavior, with its own parameters.

This is how every block that does something works, including the base game's chests, furnaces and crops. One component can serve many blocks: every block with bworld:storage is a chest, with its own number of rows.

Using a Component

List it in the block's components, with its parameters:

"components": {
	"bworld:storage": { "rows": 3 }
}

A block can list several. Their handlers run in the listed order.

Registering a Component

In the server script:

import type { ServerContext } from "bworld/server";

interface OxidizesParams {
	seconds: number;
	into: string;
}

export function setup(ctx: ServerContext) {
	ctx.components.register_block<OxidizesParams>("copper_tools:oxidizes", {
		on_create(block) {
			block.data = { age: 0 };
		},
		on_second(block, params) {
			block.data.age += 1;
			if (block.data.age >= params.seconds) {
				ctx.world.set_block(block.x, block.y, block.z, params.into);
			}
		},
	});
}
"components": {
	"copper_tools:oxidizes": { "seconds": 600, "into": "copper_tools:oxidized_copper_block" }
}

Items have components the same way, and so do status effects.

Components can only be registered during setup, and only in the mod's own namespace. Once every mod's setup has run, a block or item that lists a component nobody registered stops the server from starting, naming the block and the 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_scroll(block, params, player, scroll) A player turns the mouse wheel looking at it. See 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 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.
on_state_change(block, params, before) Its own states change without it being replaced, by set_state or a rule. See Changes.
on_scheduled_tick(block, params) A tick it asked for comes. See Scheduled Ticks.
on_entity_stand(block, params, entity) An entity standing on it moves, every tick it does. See Entities on It.
fluid_handler(block, params, face?) Something reaches for its tanks from face. See Fluid Handlers. a FluidHandler, or undefined

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 and the client data functions its part clients see, biome and season are its column's (see Seasons) and set_ticking turns its ticking off and on. params is what the block's JSON lists for this component, and dt is in seconds.

Entities on It

on_entity_stand runs every tick an entity moves while it stands on the block, like Minecraft's updateEntityAfterFallOn, with an EntityRef to it. Items lying still move every tick too, so it runs for them while they lie there. The block is the one under the entity's feet, or the one its feet are in when that one's floor is lower than a whole block, like a basin's. Create's basin takes in the items dropped into it this way, without ticking or looking for them:

ctx.components.register_block("create:basin", {
	on_entity_stand(block, _params, entity) {
		const item = entity.get_item();
		if (item) entity.set_item(insert(block, item));
	},
});

Changes

on_neighbor_change is the server's side of the rule 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 fluid'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.

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 registered in the mod's shared script instead, under the same id, because clients run them too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the server answers. A component can have rules, handlers, or both, and a block can list one that only has rules.

import type { SharedContext } from "bworld/shared";

export function setup(ctx: SharedContext) {
	ctx.components.register_block("copper_tools:pipe", {
		state_for_placement(placement, params) {/* ... */},
		on_neighbor_change(block, params, neighbor) {/* ... */},
		on_interact(block, params, interaction) {/* ... */},
	});
}
Rule Called when Returns
state_for_placement(placement, params) A player is about to place it. States to place it with, or false when it can't go there
on_neighbor_change(block, params, neighbor) A block on one of its 6 sides is placed, broken or changes its states.
on_interact(block, params, interaction) A player right clicks it. true if it did something

Here block is { id, x, y, z }, without tile data, which clients never have. ctx.world in a shared script has get_block, get_state, set_state, is_face_sturdy, biome_at and season_at (see 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, and ctx.blocks.solid(id) whether it's solid.

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).

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 covers the whole side. Stone's sides are, a slab's sides and plants aren't.

Placing

state_for_placement picks the states a block is placed with, like Minecraft's getStateForPlacement. placement is { x, y, z, item, face, hit, facing, looking, sneaking }: where it's going, the item placing it (the block's own, or another whose places is this block, like Minecraft's getItemInHand), the face of the block that was clicked, where on that block the click was (from 0 to 1 on each axis), the way the player looks along the ground, the face of the six they look most toward, "top" or "bottom" too, like getNearestLookingDirection, and whether they're sneaking, for blocks that sneaking places the other way round. It returns states by name, and the rest keep their defaults, except that a 2 bit facing already faces the player. Returning false means it can't go there at all, like a large cogwheel right beside another cogwheel, and nothing is placed, like getStateForPlacement returning null. It runs before the server checks that no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked onto the upper half of a block's side hangs in the top half:

state_for_placement(placement): Record<string, number> {
	if (placement.face !== "top" && placement.face !== "bottom") {
		return { facing: ["north", "east", "south", "west"].indexOf(placement.face), half: placement.hit[1] > 0.5 ? 1 : 0 };
	}
	return { half: placement.face === "top" ? 0 : 1 };
},

A fence's placement looks at its neighbors, so it's joined from the start, and its on_neighbor_change keeps it joined after. Both are in mods/bworld/scripts/shared.ts.

Interacting

When a player right clicks a block, every component's on_interact runs: the rules' first, then the handlers'. If any of them returns true, the click was handled and nothing else happens. Otherwise the held item is used or placed, as if the block had no components.

A rule's on_interact also runs on the clicking player's client, so they see what it does right away instead of waiting for the server, like a trapdoor opening. It's for clicks that only change states with ctx.world.set_state, like Minecraft's useWithoutItem: anything that needs the server, like opening a screen, giving items or tile data, goes in the handler. interaction is { face, hit, facing, sneaking }: the face that was clicked, where on it (from 0 to 1 on each axis), the way the player looks along the ground, and whether they're sneaking. A player sneaking with an item in hand doesn't interact at all: no on_interact runs, and the item is used or placed against the block instead. The trapdoor's is in mods/bworld/scripts/shared.ts:

on_interact(block) {
	const open = ctx.world.get_state(block.x, block.y, block.z, "open") ?? 0;
	return ctx.world.set_state(block.x, block.y, block.z, "open", open ? 0 : 1);
},

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 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:

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 ticks from the start sets block.data in on_create, like copper_tools:oxidizes above.

A block that only has work some of the time turns its ticking off with block.set_ticking(false), like a machine with nothing to make, so the server doesn't spend time on it every tick. It stays off, even when the world is saved and loaded, until something turns it back on: its own on_interact, or any other script with ctx.world.set_block_ticking(x, y, z, true), like a pipe bringing it something to work on. Breaking or replacing the block forgets it.

on_tick(block) {
	if (!has_work(block)) {
		block.set_ticking(false);
		return;
	}
	// ...
},

on_new_day runs for every block with tile data in the whole world, near a player or not, so crops keep growing while nobody's around. Blocks without tile data, like the cacti world generation makes, run it too, but only within 6 chunks of a player, like the blocks Minecraft random ticks. Blocks one of them places that morning, like a cactus growing a 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:

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.

The Base Game's Components

mods/bworld/scripts/server.ts registers these, and any mod that depends on bworld can use them:

Component Params What it does
bworld:storage rows A chest: rows × 9 slots, dropped when it's broken.
bworld:shipping_bin rows Like bworld:storage, and every morning at 06:00 sells what's in it that has a sell value for coins.
bworld:furnace none Smelts with furnace and fuel recipes. Needs lit and facing states, see blocks/furnace.json.
bworld:smithing_table none Upgrades tools with bworld:smithing recipes.
bworld:stonecutter none Cuts one item into another with bworld:stonecutting recipes, picked from a list.
bworld:hoeable tool, into Right clicking with a tool of type tool turns it into into, like a hoe on grass.
bworld:farmland none Watered with the watering can, dries out every morning.
bworld:crop see Crops Grows a stage every morning its farmland was watered.
bworld:crop_top see Crops The top half of a two block crop, like rice.
bworld:water_source none Refills the watering can.
bworld:fishable loot_table? The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is loot_table, bworld:gameplay/fishing when not given, built from the fish whose fluid is this block.
bworld:trapdoor none Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs facing (2 bits), half and open states, see blocks/oak_trapdoor.json.
bworld:fence connects_to Joins the blocks in the tag connects_to and sturdy sides of other blocks, except leaves. Needs the north, east, south and west states.

Item components work the same way, see Items.