Compare commits

...
2 Commits
Author SHA1 Message Date
paula 872db88066 Water wheel and creative motor 2026-10-28 21:40:39 -03:00
paula 507e9aab24 Stress for create networks 2026-10-28 21:28:36 -03:00
15 changed files with 597 additions and 77 deletions
+26 -4
View File
@@ -6,8 +6,9 @@ possible, and to stay fast on both the server and the client when a world has th
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed`, `rotating`, `fluid` and
items), R4, R5, R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a
hand crank), Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come
from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
hand crank, creative motor or water wheel, with stress and overstress), Create's pressing recipes, and the mechanical
press pressing items on the ground. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`,
and facts about bworld from its source.
## Sources
@@ -508,8 +509,29 @@ additions: `looking` in `state_for_placement` (`getNearestLookingDirection`), `f
(`getStateForPlacement` returning null), `ctx.blocks` in shared scripts, and `ctx.world.get_block_ref` for changing
another block's data (`getBlockEntity`).
**Chunk borders.** Tile data keeps speeds across unloading. Create tracks unloaded members' stress separately
(`KineticNetwork`'s unloaded stress). Do the same, so a network across an unloaded chunk counts right.
**Stress as built** (`scripts/kinetics/stress.ts`). Impacts and capacities are the config's `stress.impact` and
`stress.capacity` by block id, like `CStress`, with Create's values for the blocks built so far, and 0 for a block that
isn't listed. A network is the blocks whose `network` is the same generator. Each change in `spreading.ts` notes the
networks it touched, and then each of them is walked from its generator and summed. Every block in one that's
overstressed gets `overstressed` client data, which `actual_speed` in `connections.ts` reads as still, for the press and
for visuals, like `getSpeed`. Speeds and spreading are unchanged by it. The totals aren't kept, since only the
stressometer will show them. Both a second generator joining a network and one in it stopping change its capacity
without changing any speed, so a generator's change always reworks its network.
**Generators as built** (`scripts/kinetics/generators.ts`). Each is a component with its speed in params, and a capacity
in the config. `create:creative_motor` turns from when it's placed, at a speed kept in its tile data. Scrolling the
mouse wheel at it (the block is `scrollable`, so it gets `on_scroll`) steps through speeds like 0.5's motor: by 1 near
0, then by 4, 16 and 64, by 1 while sneaking, skipping 0, within `max_speed`, and the speed shows above the hotbar.
Scrolling works anywhere on the block, not only on a value box, and there's no settings board like 6.0's. Its casing is
the block's model and its half shaft turns. `create:water_wheel` scores the fluid flowing past the 4 blocks around it
across its axis with `fluid_flow`, like `determineAndApplyFlowScore`, and turns at its speed whichever way the score
says. It scores again a tick after a neighbour changes, and every second for flow that changes without that (Create does
it every 3 seconds), so a wheel ticks once a second. It can't be placed beside another wheel unless they share an axle,
like `canSurvive`. The large water wheel isn't built, and neither is changing a wheel's planks.
**Chunk borders.** Tile data keeps speeds across unloading. bworld keeps every tile in memory and reloads a chunk when a
block in it is read, so the walk sees a whole network, and Create's separate count of unloaded members' stress
(`KineticNetwork`'s unloaded stress) isn't needed.
## Phases
+6 -1
View File
@@ -18,6 +18,11 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:creative_motor",
"item_model": "create:item_creative_motor"
"item_model": "create:item_creative_motor",
"scrollable": true,
"components": {
"create:kinetic": { "facing": "facing", "shaft": "front" },
"create:creative_motor": { "speed": 16 }
}
}
}
+5 -1
View File
@@ -18,6 +18,10 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:water_wheel",
"item_model": "create:item_water_wheel"
"item_model": "create:item_water_wheel",
"components": {
"create:kinetic": { "facing": "facing" },
"create:water_wheel": { "speed": 8 }
}
}
}
+5 -1
View File
@@ -2,6 +2,10 @@
"format_version": 1,
"config": {
"max_speed": 256,
"crank_hunger": 0.01
"crank_hunger": 0.01,
"stress": {
"impact": { "create:mechanical_press": 8 },
"capacity": { "create:hand_crank": 8, "create:creative_motor": 16384, "create:water_wheel": 32 }
}
}
}
+34 -15
View File
@@ -2,23 +2,36 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// how create's moving blocks are drawn: kinetic blocks turn by the speed the server puts in their "speed" client data,
// as rotating instances, so a block turning steadily costs nothing per frame
// as rotating instances, so a block turning steadily costs nothing per frame. they're still while their network is
// overstressed
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "bworld/client";
import type { Face } from "bworld/shared";
import { type Axis, FACINGS, kinetic_shape, type KineticParams, type KineticShape } from "./kinetics/connections.ts";
import {
actual_speed,
type Axis,
FACINGS,
kinetic_shape,
type KineticParams,
type KineticShape,
OPPOSITE,
} from "./kinetics/connections.ts";
import { head_offset, type PressShown } from "./processing/press.ts";
// a model reaching north turned to reach each way
const facing_turns = (model: string): Record<Face, ModelRef> => ({
north: model,
east: { model, y: 90 },
south: { model, y: 180 },
west: { model, y: 270 },
top: { model, x: 270 },
bottom: { model, x: 90 },
});
// the crank's handle model has its hub on its south side and its grip reaching north, so it's turned to put north
// where the crank faces
const HANDLE = "create:block_hand_crank_handle";
const HANDLE_TURNS: Record<Face, ModelRef> = {
north: HANDLE,
east: { model: HANDLE, y: 90 },
south: { model: HANDLE, y: 180 },
west: { model: HANDLE, y: 270 },
top: { model: HANDLE, x: 270 },
bottom: { model: HANDLE, x: 90 },
};
const HANDLE_TURNS = facing_turns("create:block_hand_crank_handle");
// a half shaft reaching south, from the middle of the block to its side, turned to reach where a block faces
const HALF_SHAFT_TURNS = facing_turns("create:block_shaft_half");
const half_shaft = (facing: Face) => HALF_SHAFT_TURNS[OPPOSITE[facing]];
// how a model made along y is turned to an axis, the way the kinetic blocks' variants turn theirs
const AXIS_TURNS: Record<Axis, { x?: number; y?: number }> = { x: { x: 90, y: 90 }, y: {}, z: { x: 90, y: 180 } };
@@ -34,6 +47,14 @@ export function setup(ctx: ClientContext) {
});
ctx.render.register_visual("create:shaft", plain, { replaces_model: true });
ctx.render.register_visual("create:cogwheel", plain, { replaces_model: true });
// the whole wheel turns, paddles and all, like WaterWheelVisual
ctx.render.register_visual("create:water_wheel", plain, { replaces_model: true });
// its casing is its block's model, and the half shaft out of its front turns, like CreativeMotorRenderer
ctx.render.register_visual("create:creative_motor", (block, instances) => {
const shape = shape_of(block);
return { update: turning(block, instances, shape, half_shaft(shape.facing!)) };
});
// a large cog's teeth are half as far apart as a small one's, so on the blocks where small cogs aren't offset it's
// offset by half of one of its own teeth. its shaft is apart from it and offset like any other, so it lines up with
@@ -104,7 +125,7 @@ export function setup(ctx: ClientContext) {
const ticks = last === undefined ? 0 : time - last;
last = time;
// a quarter of the way to the shaft's speed each tick
velocity += (speed_of(block) * 0.3 - velocity) * Math.min(1, ticks / 4);
velocity += (actual_speed(block) * 0.3 - velocity) * Math.min(1, ticks / 4);
angle = (angle + velocity * ticks) % 360;
handle.set_rotation(shape.axis, 0, angle);
},
@@ -112,15 +133,13 @@ export function setup(ctx: ClientContext) {
}, { replaces_model: true });
}
const speed_of = (block: VisualBlock) => block.get_client_data<number>("speed") ?? 0;
// a model turning around the block's axis at its speed, the block's own when not given. returns what turns it again
// when the speed changes. on every other block it's offset by half a small cog's tooth, so cogs mesh with the ones
// beside them, and on the rest by offset, like KineticBlockEntityVisual.rotationOffset
function turning(block: VisualBlock, instances: Instances, shape: KineticShape, model?: ModelRef, offset = 0) {
const instance = instances.rotating(model);
const angle = should_offset(shape.axis, block) ? 22.5 : offset;
const turn = () => instance.set_rotation(shape.axis, speed_of(block), angle);
const turn = () => instance.set_rotation(shape.axis, actual_speed(block), angle);
turn();
return turn;
}
@@ -7,6 +7,7 @@
import type { Face } from "bworld/shared";
export type Axis = "x" | "y" | "z";
export type Pos = readonly [number, number, number];
// the create:kinetic component's params, from a block's json
export interface KineticParams {
@@ -157,3 +158,22 @@ export function neighbour_positions(block: Kinetic): [number, number, number][]
];
return offsets.map(([dx, dy, dz]) => [block.x + dx, block.y + dy, block.z + dz]);
}
// the kinetic blocks next to node that turn it or that it turns, like getConnectedNeighbours. get is undefined where
// what's there isn't kinetic
export function connected<T extends Kinetic>(
get: (x: number, y: number, z: number) => T | undefined,
node: Kinetic,
): T[] {
return neighbour_positions(node).flatMap(([x, y, z]) => {
const neighbour = get(x, y, z);
const turns = neighbour && (speed_ratio(node, neighbour) !== 0 || speed_ratio(neighbour, node) !== 0);
return turns ? [neighbour] : [];
});
}
// how fast a block acts and is drawn turning, from its client data: its speed, or still while its network is
// overstressed, like KineticBlockEntity.getSpeed
export function actual_speed(block: { get_client_data<T>(field: string): T | undefined }): number {
return block.get_client_data<boolean>("overstressed") ? 0 : block.get_client_data<number>("speed") ?? 0;
}
@@ -0,0 +1,50 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what decides how fast generators turn: water flowing past a water wheel, and the creative motor's speed as it's
// scrolled through. no ctx, so tests can call them directly
import type { Position } from "bworld/shared";
import { AXES, type Axis, face_axis, FACE_OFFSETS, FACINGS, type Pos } from "./connections.ts";
// which way water around a wheel on axis at at turns it: 1 for counterclockwise seen from the axis's positive end, -1
// for the other way, 0 when it's still or the flows cancel out. each of the 4 blocks around it across the axis with
// fluid flowing along a paddle's way round, more than at 60° to it, pushes it one way, like
// WaterWheelBlockEntity.determineAndApplyFlowScore. flow is which way the fluid at x y z flows, 0 0 0 for none
export function flow_score(axis: Axis, [x, y, z]: Pos, flow: (x: number, y: number, z: number) => Position): number {
const along = AXES.indexOf(axis);
let score = 0;
for (const face of FACINGS) {
if (face_axis(face) === axis) continue;
const offset = FACE_OFFSETS[face];
const { x: fx, y: fy, z: fz } = flow(x + offset[0], y + offset[1], z + offset[2]);
// only the part of it across the axis turns the wheel
const across = [fx, fy, fz].map((v, i) => i === along ? 0 : v);
const length = Math.hypot(...across);
if (length === 0) continue;
// the way a paddle there moves turning counterclockwise: the axis crossed with where it is
const unit = [0, 0, 0].map((_, i) => i === along ? 1 : 0);
const moving = [
unit[1] * offset[2] - unit[2] * offset[1],
unit[2] * offset[0] - unit[0] * offset[2],
unit[0] * offset[1] - unit[1] * offset[0],
];
const dot = (across[0] * moving[0] + across[1] * moving[1] + across[2] * moving[2]) / length;
if (Math.abs(dot) > 0.5) score += Math.sign(dot);
}
return Math.sign(score);
}
// the creative motor's speed one notch of the mouse wheel on from current, up when forward: by 1 near 0, and by 4, 16
// and 64 from 4, 32 and 128 rpm on, or always by 1 when fine. it never stops, it skips 0 to turn the other way, and it
// stays within max. like the 0.5 creative motor's step
export function motor_step(current: number, forward: boolean, fine: boolean, max: number): number {
let step = 1;
if (!fine) {
const magnitude = Math.abs(current) - (forward === current > 0 ? 0 : 1);
if (magnitude >= 4) step *= 4;
if (magnitude >= 32) step *= 4;
if (magnitude >= 128) step *= 4;
}
if (current + (forward ? step : -step) === 0) step += 1;
return Math.max(-max, Math.min(max, current + (forward ? step : -step)));
}
+37 -24
View File
@@ -4,24 +4,18 @@
// rotation spreading through what's connected, like create's RotationPropagator: a block that's placed takes the speed
// of what turns it, a generator's speed spreads to everything it turns, the faster of two takes the other's blocks
// over, and a block that would turn two ways at once breaks. each walk is a queue, not recursion, and runs only when
// something changes. no ctx, the world is anything that keeps these, so tests can give their own
import { type Kinetic, neighbour_positions, speed_ratio } from "./connections.ts";
export type Pos = readonly [number, number, number];
// something changes, and then so does stress for the networks it changed. no ctx, the world is anything that keeps
// these, so tests can give their own
import { connected as connected_in, type Kinetic, neighbour_positions, type Pos, speed_ratio } from "./connections.ts";
import { type StressNode, type StressWorld, update_stress } from "./stress.ts";
// a kinetic block as the world keeps it
export interface KineticNode extends Kinetic {
// rpm around its axis, counterclockwise seen from the axis's positive end, like getTheoreticalSpeed
readonly speed: number;
export interface KineticNode extends StressNode {
// the block next to it it gets its speed from. undefined for a still block, and for a generator turning it
readonly source?: Pos;
// the generator its speed comes from, as "x y z", for telling a loop apart from another network meeting it
readonly network?: string;
// the speed it makes itself, 0 for anything that isn't a generator or one that's still, like getGeneratedSpeed
readonly generated: number;
}
export interface KineticWorld {
export interface KineticWorld extends StressWorld {
// undefined when what's there isn't kinetic
get(x: number, y: number, z: number): KineticNode | undefined;
set(at: Pos, speed: number, source: Pos | undefined, network: string | undefined): void;
@@ -33,7 +27,7 @@ export interface KineticWorld {
// a block was placed: it takes the speed of what turns it, and passes it on, like RotationPropagator.handleAdded
export function handle_added(world: KineticWorld, at: Pos) {
spread(world, at);
with_stress(world, undefined, (world) => spread(world, at));
}
// a block is going: what it turned stops, then what's still turning around that spreads back in, like handleRemoved.
@@ -45,14 +39,40 @@ export function handle_removed(world: KineticWorld, at: Pos) {
get: (x, y, z) => x === at[0] && y === at[1] && z === at[2] ? undefined : world.get(x, y, z),
set: (...args) => world.set(...args),
break: (where) => world.break(where),
set_overstressed: (...args) => world.set_overstressed(...args),
max_speed: world.max_speed,
};
restart(without, detach(without, node));
with_stress(without, node.network, (world) => restart(world, detach(world, node)));
}
// a generator's speed changed, like a crank being turned or let go. like GeneratingKineticBlockEntity's
// updateGeneratedRotation
// updateGeneratedRotation. it changes the network's capacity even when its speed stays the same
export function update_generated(world: KineticWorld, at: Pos) {
with_stress(world, world.get(...at)?.network, (world) => generate(world, at));
}
// runs change on world, keeping track of the networks it changes, then works out their stress again. network is the
// one the block that changed is in, whose stress changes even if nothing else in it does
function with_stress(world: KineticWorld, network: string | undefined, change: (world: KineticWorld) => void) {
const networks = new Set<string>(network === undefined ? [] : [network]);
const changed: Pos[] = [];
change({
get: (x, y, z) => world.get(x, y, z),
set(where, speed, source, network) {
const before = world.get(...where)?.network;
if (before !== undefined) networks.add(before);
if (network !== undefined) networks.add(network);
changed.push(where);
world.set(where, speed, source, network);
},
break: (where) => world.break(where),
set_overstressed: (...args) => world.set_overstressed(...args),
max_speed: world.max_speed,
});
update_stress(world, networks, changed);
}
function generate(world: KineticWorld, at: Pos) {
const node = world.get(...at);
if (!node || node.generated === node.speed) return;
const speed = node.generated;
@@ -80,14 +100,7 @@ const same = (a: Pos | undefined, b: Pos) => a !== undefined && a[0] === b[0] &&
const pos_of = (node: Kinetic): Pos => [node.x, node.y, node.z];
const network_of = (at: Pos) => at.join(" ");
// the kinetic blocks next to node that turn it or that it turns, like getConnectedNeighbours
function connected(world: KineticWorld, node: Kinetic): KineticNode[] {
return neighbour_positions(node).flatMap(([x, y, z]) => {
const neighbour = world.get(x, y, z);
const turns = neighbour && (speed_ratio(node, neighbour) !== 0 || speed_ratio(neighbour, node) !== 0);
return turns ? [neighbour] : [];
});
}
const connected = (world: KineticWorld, node: Kinetic) => connected_in((x, y, z) => world.get(x, y, z), node);
// spreads the speed at start to what it's connected to, and on through whatever that changes, like
// propagateNewSource
@@ -146,7 +159,7 @@ function detach(world: KineticWorld, node: Kinetic): Pos[] {
// generators that stopped with what turned them start again with their own speed, like reActivateSource. that's a
// tick later in create, so here it's after the walk that stopped them, when what's turning around them has settled
function restart(world: KineticWorld, generators: Pos[]) {
for (const at of generators) update_generated(world, at);
for (const at of generators) generate(world, at);
}
// stops start and everything that got its speed through it, then lets what's still turning at the edges spread back
+70
View File
@@ -0,0 +1,70 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// stress, like create's KineticNetwork: a network's capacity is what its generators make, each one's capacity × its
// rpm, and its stress what its blocks take, each one's impact × its rpm. when the stress is more than the capacity the
// network is overstressed, and everything in it acts and is drawn still. a network is the blocks that get their speed
// from one generator, found by walking from it when something in it changes, never per tick. every block's tile data
// is kept whether its chunk is loaded or not, so the walk sees all of it and nothing needs counting apart. no ctx
import { connected, type Kinetic, type Pos } from "./connections.ts";
export interface StressNode extends Kinetic {
// rpm around its axis, counterclockwise seen from the axis's positive end, the speed it would turn at if it weren't
// overstressed, like getTheoreticalSpeed
readonly speed: number;
// the generator its speed comes from, as "x y z", which is also how a loop is told apart from another network
// meeting it
readonly network?: string;
// the speed it makes itself, 0 for anything that isn't a generator or one that's still, like getGeneratedSpeed
readonly generated: number;
// what it takes per rpm, like BlockStressValues.getImpact
readonly impact: number;
// what it makes per rpm while it makes a speed, like BlockStressValues.getCapacity
readonly capacity: number;
readonly overstressed: boolean;
}
export interface StressWorld {
get(x: number, y: number, z: number): StressNode | undefined;
set_overstressed(at: Pos, overstressed: boolean): void;
}
// works out again whether each of networks is overstressed, and marks each of its blocks. blocks in changed that
// aren't in a network any more aren't overstressed either
export function update_stress(world: StressWorld, networks: Iterable<string>, changed: Iterable<Pos>) {
for (const network of networks) {
const members = members_of(world, network);
let capacity = 0;
let stress = 0;
for (const node of members) {
if (node.generated !== 0) capacity += node.capacity * Math.abs(node.generated);
stress += node.impact * Math.abs(node.speed);
}
const overstressed = stress > capacity;
for (const node of members) {
if (node.overstressed !== overstressed) world.set_overstressed([node.x, node.y, node.z], overstressed);
}
}
for (const at of changed) {
const node = world.get(...at);
if (node?.overstressed && node.network === undefined) world.set_overstressed(at, false);
}
}
// the blocks in a network, walking out from its generator through the blocks that turn with it
function members_of(world: StressWorld, network: string): StressNode[] {
const [x, y, z] = network.split(" ").map(Number);
const root = world.get(x, y, z);
if (root?.network !== network) return [];
const found = new Set([network]);
const members = [root];
for (let i = 0; i < members.length; i++) {
for (const neighbour of connected((x, y, z) => world.get(x, y, z), members[i])) {
const key = `${neighbour.x} ${neighbour.y} ${neighbour.z}`;
if (neighbour.network !== network || found.has(key)) continue;
found.add(key);
members.push(neighbour);
}
}
return members;
}
+93 -16
View File
@@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's blocks that do something: so far what turns (create:kinetic), the hand crank that turns it, and the
// mechanical press
// create's blocks that do something: so far what turns (create:kinetic), the generators that turn it (the hand crank,
// the creative motor and the water wheel), and the mechanical press
import type { BlockRef, EntityRef, Id, ServerContext } from "bworld/server";
import { along, kinetic_shape, type KineticParams } from "./kinetics/connections.ts";
import { handle_added, handle_removed, type KineticWorld, type Pos, update_generated } from "./kinetics/spreading.ts";
import { actual_speed, along, kinetic_shape, type KineticParams, type Pos } from "./kinetics/connections.ts";
import { flow_score, motor_step } from "./kinetics/generators.ts";
import { handle_added, handle_removed, type KineticWorld, update_generated } from "./kinetics/spreading.ts";
import {
PRESSING,
processing_for,
@@ -18,16 +19,21 @@ import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./proc
interface Config {
max_speed: number;
crank_hunger: number;
// by block id, what each block takes per rpm and what each generator makes per rpm, like create's CStress. 0 for a
// block that isn't there
stress: { impact: Record<Id, number>; capacity: Record<Id, number> };
}
// a kinetic block's tile data, see KineticNode. its speed is its "speed" client data, which its visual turns it by
// a kinetic block's tile data, see KineticNode. its speed is its "speed" client data, and whether its network is
// overstressed its "overstressed" client data, which its visual turns it by
interface KineticData {
source?: Pos;
network?: string;
}
// the create:hand_crank component's params: the rpm it turns at
interface CrankParams {
// a generator's params, for create:hand_crank, create:creative_motor and create:water_wheel: the rpm it turns at, or
// the motor's to start with
interface GeneratorParams {
speed: number;
}
@@ -41,6 +47,16 @@ interface CrankData extends KineticData {
backwards?: boolean;
}
interface MotorData extends KineticData {
// rpm, counterclockwise seen from its shaft's end. its params' speed until it's scrolled
speed?: number;
}
interface WheelData extends KineticData {
// which way the water turns it, see flow_score
flow?: number;
}
interface PressData extends KineticData {
// steps through the cycle while it's pressing, see processing/press.ts
pressing?: number;
@@ -69,7 +85,7 @@ export function setup(ctx: ServerContext) {
// turns while it's being clicked, a little longer each click, and the other way while sneaking, like create's
// HandCrankBlock and HandCrankBlockEntity. turning it makes the player hungry
ctx.components.register_block<CrankParams>("create:hand_crank", {
ctx.components.register_block<GeneratorParams>("create:hand_crank", {
on_interact(block, params, player) {
const data: CrankData = block.data ?? {};
const backwards = player.is_sneaking();
@@ -90,6 +106,48 @@ export function setup(ctx: ServerContext) {
},
});
// turns at any speed, set by scrolling the mouse wheel at it, finer while sneaking, like create's
// CreativeMotorBlockEntity with the 0.5 step
ctx.components.register_block<GeneratorParams>("create:creative_motor", {
on_create(block) {
update_generated(world, [block.x, block.y, block.z]);
},
on_scroll(block, params, player, scroll) {
const data: MotorData = block.data ?? {};
let speed = data.speed ?? params.speed;
for (let i = 0; i < Math.abs(scroll.amount); i++) {
speed = motor_step(speed, scroll.amount > 0, player.is_sneaking(), config.max_speed);
}
player.send_message(`Speed: ${speed} rpm`, { overlay: true });
if (speed === (data.speed ?? params.speed)) return;
block.data = { ...data, speed };
update_generated(world, [block.x, block.y, block.z]);
},
});
// turned by fluid flowing past its sides, see flow_score. it looks again when something beside it changes, a tick
// later once that's settled, and every second, since water can change which way it flows without that, like
// WaterWheelBlock and WaterWheelBlockEntity's lazy tick
const update_flow = (block: BlockRef) => {
const { axis } = world.get(block.x, block.y, block.z)!;
const flow = flow_score(axis, [block.x, block.y, block.z], (x, y, z) => ctx.world.fluid_flow(x, y, z));
const data: WheelData = block.data ?? {};
// kept even when it's 0, so the wheel has data and ticks
if (data.flow === flow) return;
block.data = { ...data, flow };
update_generated(world, [block.x, block.y, block.z]);
};
ctx.components.register_block("create:water_wheel", {
on_create: update_flow,
on_neighbor_change(block) {
if (!ctx.world.has_scheduled_tick(block.x, block.y, block.z)) {
ctx.world.schedule_tick(block.x, block.y, block.z, 1);
}
},
on_scheduled_tick: update_flow,
on_second: update_flow,
});
register_press(ctx, pressing);
}
@@ -127,7 +185,7 @@ function register_press(ctx: ServerContext, recipes: ProcessingRecipe[]) {
ctx.components.register_block("create:mechanical_press", {
on_tick(block) {
const data: PressData = block.data ?? {};
const rate = cycle_rate(block.get_client_data<number>("speed") ?? 0);
const rate = cycle_rate(actual_speed(block));
if (data.pressing === undefined) {
// a block that starts turning ticks again, see kinetic_world
if (rate === 0) {
@@ -163,18 +221,23 @@ function register_press(ctx: ServerContext, recipes: ProcessingRecipe[]) {
});
}
// the world as rotation spreading sees it: blocks with create:kinetic, their speed in client data and where it comes
// from in tile data
// the world as rotation spreading sees it: blocks with create:kinetic, their speed and whether they're overstressed in
// client data, and where their speed comes from in tile data
function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
// components never change once loaded, so each block's are looked up once
const params = new Map<Id, { kinetic?: KineticParams; crank?: CrankParams }>();
const params = new Map<
Id,
{ kinetic?: KineticParams; crank?: GeneratorParams; motor?: GeneratorParams; wheel?: GeneratorParams }
>();
const params_of = (id: Id) => {
let found = params.get(id);
if (!found) {
const components = ctx.blocks.components(id);
found = {
kinetic: components["create:kinetic"] as KineticParams | undefined,
crank: components["create:hand_crank"] as CrankParams | undefined,
crank: components["create:hand_crank"] as GeneratorParams | undefined,
motor: components["create:creative_motor"] as GeneratorParams | undefined,
wheel: components["create:water_wheel"] as GeneratorParams | undefined,
};
params.set(id, found);
}
@@ -190,13 +253,18 @@ function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
get(x, y, z) {
const block = ctx.world.get_block_ref(x, y, z);
if (!block) return undefined;
const { kinetic, crank } = params_of(block.id);
const { kinetic, crank, motor, wheel } = params_of(block.id);
if (!kinetic) return undefined;
const shape = kinetic_shape(kinetic, (name) => ctx.world.get_state(x, y, z, name));
const data: CrankData = block.data ?? {};
// a crank turns counterclockwise seen from its handle, or the other way while sneaking
const data: CrankData & MotorData & WheelData = block.data ?? {};
// a crank turns counterclockwise seen from its handle, or the other way while sneaking, and a motor seen
// from its shaft
const generated = crank && data.in_use && shape.facing
? along(shape.facing, data.backwards ? -crank.speed : crank.speed)
: motor && shape.facing
? along(shape.facing, data.speed ?? motor.speed)
: wheel
? (data.flow ?? 0) * wheel.speed
: 0;
return {
x,
@@ -207,6 +275,9 @@ function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
source: data.source,
network: data.network,
generated,
impact: config.stress.impact[block.id] ?? 0,
capacity: config.stress.capacity[block.id] ?? 0,
overstressed: block.get_client_data<boolean>("overstressed") ?? false,
};
},
set(at, speed, source, network) {
@@ -220,6 +291,12 @@ function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
break(at) {
ctx.world.break_block(...at);
},
set_overstressed(at, overstressed) {
const block = block_at(at);
// like a block that starts turning, see set
if (!overstressed && block.get_client_data("speed")) block.set_ticking(true);
block.set_client_data("overstressed", overstressed || undefined);
},
max_speed: config.max_speed,
};
}
+33 -10
View File
@@ -62,10 +62,18 @@ export function setup(ctx: SharedContext) {
return other.cog === "small" && cog === "small";
});
// a block with a facing faces away from the axle beside it, or toward the player, or away from them while
// sneaking, like DirectionalKineticBlock. one with its axle only in front faces the axle instead, like
// CreativeMotorBlock
const facing_for = (placement: BlockPlacement, shaft: KineticParams["shaft"]): Face => {
const side = axle_beside(placement.x, placement.y, placement.z);
if (side && !placement.sneaking) return shaft === "front" ? side : OPPOSITE[side];
return placement.sneaking ? placement.looking : OPPOSITE[placement.looking];
};
// a block with an axis lines up with the axle it's placed against, or sneaking, with the face it's clicked onto.
// otherwise it points the way the player looks, like RotatedPillarKineticBlock. a block with a facing faces away
// from the axle, or toward the player, or away from them while sneaking, like DirectionalKineticBlock. cogs are
// placed their own way, see cog_axis
// otherwise it points the way the player looks, like RotatedPillarKineticBlock. a block with a facing faces as
// facing_for says. cogs are placed their own way, see cog_axis
ctx.components.register_block<KineticParams>("create:kinetic", {
state_for_placement(placement, params) {
if (params.cog) {
@@ -78,15 +86,10 @@ export function setup(ctx: SharedContext) {
const side = axle_beside(placement.x, placement.y, placement.z, FACINGS.slice(0, 4));
return { [params.facing]: FACINGS.indexOf(side ?? OPPOSITE[placement.facing]) };
}
const side = axle_beside(placement.x, placement.y, placement.z);
if (params.facing !== undefined) {
const facing = side && !placement.sneaking
? OPPOSITE[side]
: placement.sneaking
? placement.looking
: OPPOSITE[placement.looking];
return { [params.facing]: FACINGS.indexOf(facing) };
return { [params.facing]: FACINGS.indexOf(facing_for(placement, params.shaft)) };
}
const side = axle_beside(placement.x, placement.y, placement.z);
const axis = side && !placement.sneaking
? face_axis(side)
: side
@@ -96,6 +99,26 @@ export function setup(ctx: SharedContext) {
},
});
// a wheel's paddles would cut into a wheel beside it, unless that one is on the same axis and beside it along that
// axis, like WaterWheelBlock.canSurvive
const wheel_at = (x: number, y: number, z: number) => {
const id = ctx.world.get_block(x, y, z);
return id !== undefined && ctx.blocks.exists(id) &&
ctx.blocks.components(id)["create:water_wheel"] !== undefined;
};
ctx.components.register_block("create:water_wheel", {
state_for_placement(placement) {
const { x, y, z } = placement;
const axis = face_axis(facing_for(placement, "both"));
const fits = FACINGS.every((side) => {
const [dx, dy, dz] = FACE_OFFSETS[side];
if (!wheel_at(x + dx, y + dy, z + dz)) return true;
return face_axis(side) === axis && beside(x, y, z, side)?.axis === axis;
});
if (!fits) return false;
},
});
// a crank faces away from what it's placed on, unless there's an axle beside it to turn, like HandCrankBlock
ctx.components.register_block("create:hand_crank", {
state_for_placement(placement) {
+120
View File
@@ -0,0 +1,120 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's generators besides the hand crank: the water wheel, turned by water flowing past it, and the creative
// motor, which turns at whatever speed it's scrolled to
import { assert, assertEquals } from "@std/assert";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { flow_score, motor_step } from "$/mods/create/scripts/kinetics/generators.ts";
import { AXIS, FACING, setup, visual_for } from "./helpers.ts";
// the rpm a generator's params say
const speed_of = (id: string, component: string) =>
(EverythingRegistry.get<BlockRegistry>("blocks", id)!.components![component] as { speed: number }).speed;
Deno.test("water flowing along a wheel's paddles turns it, one way or the other, and along its axis doesn't", () => {
// flows by "x y z" around a wheel at 0 0 0 on the z axis
const score = (flows: Record<string, [number, number, number]>) =>
flow_score("z", [0, 0, 0], (x, y, z) => {
const [fx, fy, fz] = flows[`${x} ${y} ${z}`] ?? [0, 0, 0];
return { x: fx, y: fy, z: fz };
});
// seen from the south, over the top toward the east is clockwise, and under the bottom toward the west too
assertEquals(score({ "0 1 0": [1, 0, 0] }), -1);
assertEquals(score({ "0 1 0": [1, 0, 0], "0 -1 0": [-1, 0, 0] }), -1);
assertEquals(score({ "0 1 0": [-1, 0, 0] }), 1);
// falling down its east side
assertEquals(score({ "1 0 0": [0, -1, 0] }), -1);
// both ways at once, along its axis, or straight at it
assertEquals(score({ "0 1 0": [1, 0, 0], "0 -1 0": [1, 0, 0] }), 0);
assertEquals(score({ "0 1 0": [0, 0, 1] }), 0);
assertEquals(score({ "0 1 0": [0, -1, 0] }), 0);
});
Deno.test("a water wheel beside a stream turns what's on its axle, and stops when the water's gone", async () => {
const t = await setup();
// a channel along x at z 1, walled in, with the wheel standing in its south wall on the y axis
for (let x = -4; x <= 4; x++) {
t.game.set_block(x, 100, 2, "bworld:stone");
if (x !== 0) t.game.set_block(x, 100, 0, "bworld:stone");
}
t.game.set_block(-4, 100, 1, "bworld:stone");
t.place(0, 100, 0, "create:water_wheel", "facing", FACING.up);
t.place(0, 101, 0, "create:shaft", "axis", AXIS.y);
assertEquals(t.speed(0, 101, 0), 0);
// flowing east past its north side turns it counterclockwise seen from above
t.game.set_block(-3, 100, 1, "bworld:water");
t.ticks(60);
const speed = speed_of("create:water_wheel", "create:water_wheel");
assertEquals([t.speed(0, 100, 0), t.speed(0, 101, 0)], [speed, speed]);
t.game.set_block(-3, 100, 1, AIR_ID);
t.ticks(100);
assertEquals([t.speed(0, 100, 0), t.speed(0, 101, 0)], [0, 0]);
});
Deno.test("a water wheel can't go beside another one unless they're on the same axle", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give create:water_wheel 64" });
t.send(1, { type: "select_slot", slot: 0 });
// looking north, they face south, on the z axis
t.use(0, 99, 0, "top");
assertEquals(t.state(0, 100, 0, "facing"), FACING.south);
t.use(1, 99, 0, "top");
assertEquals(t.game.world.get_block_id(1, 100, 0), AIR_ID);
t.use(0, 99, -1, "top");
assertEquals(t.game.world.get_block_id(0, 100, -1), "create:water_wheel");
// facing away from the first one's axle, so on the same axis
assertEquals(t.state(0, 100, -1, "facing"), FACING.north);
});
Deno.test("a creative motor's speed goes up by more the faster it is, finer while sneaking, and skips 0", () => {
assertEquals(motor_step(1, true, false, 256), 2);
assert(motor_step(16, true, false, 256) - 16 > motor_step(2, true, false, 256) - 2);
assertEquals(motor_step(16, true, true, 256), 17);
assertEquals(motor_step(1, false, false, 256), -1);
assertEquals(motor_step(-1, true, true, 256), 1);
assertEquals(motor_step(256, true, false, 256), 256);
assertEquals(motor_step(-250, false, false, 256), -256);
});
Deno.test("a creative motor turns what's in front of it, at the speed it's scrolled to", async () => {
const t = await setup();
t.place(1, 100, 0, "create:shaft", "axis", AXIS.x);
t.place(2, 100, 0, "create:shaft", "axis", AXIS.x);
// placed beside an axle, it faces it
t.send(1, { type: "chat", text: "/give create:creative_motor 1" });
t.send(1, { type: "select_slot", slot: 0 });
t.use(0, 99, 0, "top");
assertEquals(t.state(0, 100, 0, "facing"), FACING.east);
// facing east, it turns counterclockwise seen from the east, which is around x
let speed = speed_of("create:creative_motor", "create:creative_motor");
assertEquals([t.speed(1, 100, 0), t.speed(2, 100, 0)], [speed, speed]);
const scroll = (amount: number) =>
t.send(1, { type: "scroll_block", x: 0, y: 100, z: 0, face: "south", hit: [0.5, 0.5, 1], amount });
scroll(1);
speed = motor_step(speed, true, false, 256);
assertEquals(t.speed(2, 100, 0), speed);
// down past 0, the line turns the other way
while (speed > 0) {
scroll(-1);
speed = motor_step(speed, false, false, 256);
}
assertEquals(t.speed(2, 100, 0), speed);
assert(speed < 0);
});
Deno.test("a creative motor is drawn with its half shaft turning out of its front", async () => {
const { visual, turns, data } = await visual_for("create:creative_motor", { facing: FACING.east }, { speed: 16 });
const shaft = () => [...turns].find(([model]) => model.includes("shaft_half"))![1];
assertEquals(shaft().slice(0, 2), ["x", 16]);
assertEquals(turns.has("own"), false);
data.speed = -64;
visual.update!();
assertEquals(shaft()[1], -64);
});
+3 -1
View File
@@ -32,6 +32,8 @@ export async function setup(config: Record<string, unknown> = {}) {
game.set_block(x, y, z, id, undefined, state ? set_state_value(0, info, state, value)! >>> 16 : 0);
};
const speed = (x: number, y: number, z: number) => game.world.get_tile(x, y, z)?.client_data?.speed as number ?? 0;
const overstressed = (x: number, y: number, z: number) =>
game.world.get_tile(x, y, z)?.client_data?.overstressed === true;
const state = (x: number, y: number, z: number, name: string) =>
get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
const use = (x: number, y: number, z: number, face: Face = "south") =>
@@ -44,7 +46,7 @@ export async function setup(config: Record<string, unknown> = {}) {
(EverythingRegistry.get<BlockRegistry>("blocks", "create:hand_crank")!.components!["create:hand_crank"] as {
speed: number;
}).speed;
return { ...t, move, place, speed, state, use, ticks, crank };
return { ...t, move, place, speed, overstressed, state, use, ticks, crank };
}
// create's client script with only what its visuals need, and a block for one to draw that records what its instances
+83 -2
View File
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's kinetics: shafts take the speed of what turns them, a hand crank turns them while it's being clicked, and a
// block that would turn two ways at once breaks
// create's kinetics: shafts take the speed of what turns them, a hand crank turns them while it's being clicked, a
// block that would turn two ways at once breaks, and a network that takes more than its generators make stops
import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "$/common/protocol.ts";
import { test_game } from "../helpers.ts";
@@ -132,6 +132,76 @@ Deno.test("speeds are saved, and a crank still stops after the world is loaded",
assertEquals(speed(3), 0);
});
// a crank making capacity per rpm, and presses taking impact per rpm
const stress = (capacity: number, impact: number) => ({
stress: { capacity: { "create:hand_crank": capacity }, impact: { "create:mechanical_press": impact } },
});
Deno.test("a network whose blocks take more than its generators make is overstressed, all of it", async () => {
// each press takes half of what the crank makes, at any speed
const t = await setup(stress(8, 4));
const over = t.overstressed;
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 100, 0, "create:mechanical_press", "facing", FACING.east);
t.place(2, 100, 0, "create:mechanical_press", "facing", FACING.east);
t.place(3, 100, 0, "create:shaft", "axis", AXIS.x);
t.use(0, 100, 0);
assertEquals([0, 1, 2, 3].map((x) => over(x, 100, 0)), [false, false, false, false]);
// a third is too many, and every block in the network stops, though its speed is kept
t.place(4, 100, 0, "create:mechanical_press", "facing", FACING.east);
assertEquals([0, 1, 2, 3, 4].map((x) => over(x, 100, 0)), [true, true, true, true, true]);
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
// taking it away again is enough
t.game.destroy_block(4, 100, 0);
assertEquals([0, 1, 2, 3].map((x) => over(x, 100, 0)), [false, false, false, false]);
// and blocks that stop turning aren't overstressed any more
t.place(4, 100, 0, "create:mechanical_press", "facing", FACING.east);
t.ticks(40);
assertEquals([0, 1, 2, 3, 4].map((x) => over(x, 100, 0)), [false, false, false, false, false]);
});
Deno.test("a second generator turning a network adds what it makes", async () => {
const t = await setup(stress(8, 6));
const over = t.overstressed;
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
for (let x = 1; x <= 2; x++) t.place(x, 100, 0, "create:mechanical_press", "facing", FACING.east);
t.place(3, 100, 0, "create:hand_crank", "facing", FACING.east);
t.use(0, 100, 0);
assert(over(1, 100, 0));
// sneaking turns this one the same way around x as the first
t.move(true);
t.use(3, 100, 0);
assertEquals([0, 1, 2, 3].map((x) => over(x, 100, 0)), [false, false, false, false]);
// let go, it's overstressed again
for (let i = 0; i < 10; i++) {
t.ticks(4);
t.use(0, 100, 0);
}
assert(over(1, 100, 0));
});
Deno.test("a block takes more the faster it turns", async () => {
// on its own the press takes 3/4 of what the crank makes
const press_behind = async (cog: "create:cogwheel" | "create:large_cogwheel") => {
const t = await setup(stress(8, 6));
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 100, 0, "create:large_cogwheel", "axis", AXIS.x);
t.place(1, 101, 1, "create:cogwheel", "axis", AXIS.x);
// behind the large cog at the crank's speed, or the small one at twice that
const [y, z] = cog === "create:large_cogwheel" ? [100, 0] : [101, 1];
t.place(2, y, z, "create:mechanical_press", "facing", FACING.east);
t.use(0, 100, 0);
assertEquals(Math.abs(t.speed(2, y, z)), cog === "create:large_cogwheel" ? t.crank : 2 * t.crank);
return t.overstressed(2, y, z);
};
assertEquals(await press_behind("create:large_cogwheel"), false);
assertEquals(await press_behind("create:cogwheel"), true);
});
Deno.test("a shaft lines up with the axle it's placed against, and otherwise points the way the player looks", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give create:shaft 64" });
@@ -254,6 +324,17 @@ Deno.test("a shaft is drawn turning around its axis at the speed its client data
assertEquals(turns.get("own")!.slice(0, 2), ["z", -64]);
});
Deno.test("a block in an overstressed network is drawn still", async () => {
const { visual, turns, data } = await visual_for("create:shaft", { axis: AXIS.z }, {
speed: 16,
overstressed: true,
});
assertEquals(turns.get("own")![1], 0);
data.overstressed = undefined;
visual.update!();
assertEquals(turns.get("own")![1], 16);
});
Deno.test("a crank's handle catches up with the speed it turns at, and slows to a stop", async () => {
const { visual, turns, data } = await visual_for("create:hand_crank", { facing: FACING.west }, { speed: -32 });
assertEquals(turns.get("own")!.slice(0, 2), ["x", -32]);
+12 -2
View File
@@ -8,8 +8,8 @@ import { ItemStack } from "$/common/inventory.ts";
import { FACING, setup, visual_for } from "./helpers.ts";
// a press at 1 101 0 along x, turned by a crank on its west side, with the floor two blocks under it
async function press_with_crank() {
const t = await setup();
async function press_with_crank(config?: Record<string, unknown>) {
const t = await setup(config);
t.place(0, 101, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 101, 0, "create:mechanical_press", "facing", FACING.east);
// holding use on the crank, which clicks it every 4 ticks
@@ -40,6 +40,16 @@ Deno.test("a turning press slams down on an ingot lying under it and presses it
assertEquals(t.lying(), { "create:iron_sheet": 1 });
});
Deno.test("an overstressed press doesn't press", async () => {
// it takes more than the crank makes
const t = await press_with_crank({
stress: { capacity: { "create:hand_crank": 1 }, impact: { "create:mechanical_press": 2 } },
});
t.ingots(1);
t.crank(200);
assertEquals(t.lying(), { "bworld:iron_ingot": 1 });
});
Deno.test("from a stack, a press presses one at a time, and each lands beside the rest", async () => {
const t = await press_with_crank();
t.ingots(3);