Files
bworld/mods/create/scripts/server.ts
T

452 lines
18 KiB
TypeScript

// 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 generators that turn it (the hand crank,
// the creative motor and the water wheel), the mechanical press and the basin
import type { BlockRef, EntityRef, FluidStack, Id, ItemStack, ServerContext } from "bworld/server";
import {
actual_speed,
along,
face_axis,
FACE_OFFSETS,
FACINGS,
kinetic_shape,
type KineticParams,
OPPOSITE,
type Pos,
positive,
source_face,
} 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 { COMPACTING, PRESSING, type ProcessingRecipe, roll_results } from "./recipes/processing.ts";
import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts";
import {
apply_basin_recipe,
BASIN_TANK_CAPACITY,
BASIN_TANKS,
type BasinContents,
insert_item,
} from "./processing/basin.ts";
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, and whether its network is
// overstressed its "overstressed" client data, which its visual turns it by
interface KineticData {
source?: Pos;
network?: string;
}
// 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;
}
// how long a crank keeps turning after each click, in ticks. holding use clicks every 4
const CRANK_USE_TICKS = 10;
interface CrankData extends KineticData {
// ticks left turning
in_use?: number;
// turned the other way, by sneaking
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;
// it's pressing into the basin under it, not on an item on the ground
basin?: boolean;
// ticks until it looks for something to press again
scan?: number;
}
export function setup(ctx: ServerContext) {
const config: Config = ctx.config;
const world = kinetic_world(ctx, config);
// the ones that take more ingredients first, so a recipe isn't beaten by one that takes part of what it does, like
// BasinOperatingBlockEntity.getMatchingRecipes
const compacting = [...ctx.recipes.all<ProcessingRecipe>(COMPACTING.id)]
.sort((a, b) => b.ingredients.length - a.ingredients.length);
ctx.components.register_block<KineticParams>("create:kinetic", {
on_create(block) {
handle_added(world, [block.x, block.y, block.z]);
},
on_break(block) {
handle_removed(world, [block.x, block.y, block.z]);
},
// states that change how it turns things, like a clutch being powered or a chain drive joining a line, take it
// out and put it back, like Create's detachKinetics and attachKinetics on a change that isn't
// areStatesKineticallyEquivalent
on_state_change(block, params, before) {
const now = kinetic_shape(params, (name) => ctx.world.get_state(block.x, block.y, block.z, name));
if (JSON.stringify(now) === JSON.stringify(kinetic_shape(params, (name) => before[name]))) return;
handle_removed(world, [block.x, block.y, block.z]);
handle_added(world, [block.x, block.y, block.z]);
},
});
// a shaft or cog right clicked with a casing becomes the encased one, by the casing's id, turned the same way. an
// encased cog gets an axle out of its casing toward each axle beside it. the casing isn't used up. like
// EncasableBlock.tryEncase and handleEncasing
ctx.components.register_block<Record<Id, Id>>("create:encasable", {
on_interact(block, params, player) {
const into = params[player.held_item?.id ?? ""];
const node = world.get(block.x, block.y, block.z);
if (!into || !node) return false;
const own = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams;
const encased = ctx.blocks.components(into)["create:kinetic"] as KineticParams;
const states = {
[encased.axis ?? "axis"]: ctx.world.get_state(block.x, block.y, block.z, own.axis ?? "axis")!,
};
for (const side of FACINGS) {
if (!encased.shaft_states || face_axis(side) !== node.axis) continue;
const [dx, dy, dz] = FACE_OFFSETS[side];
const axle = world.get(block.x + dx, block.y + dy, block.z + dz)?.shafts.includes(OPPOSITE[side]);
states[encased.shaft_states[positive(side) ? 0 : 1]] = axle ? 1 : 0;
}
ctx.world.set_block(block.x, block.y, block.z, into, states);
return true;
},
});
// 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<GeneratorParams>("create:hand_crank", {
on_interact(block, params, player) {
const data: CrankData = block.data ?? {};
const backwards = player.is_sneaking();
const changed = !data.in_use || backwards !== (data.backwards ?? false);
block.data = { ...data, in_use: CRANK_USE_TICKS, backwards };
block.set_ticking(true);
if (changed) update_generated(world, [block.x, block.y, block.z]);
player.add_exhaustion(params.speed * config.crank_hunger);
return true;
},
on_tick(block) {
const data: CrankData = block.data ?? {};
const in_use = Math.max(0, (data.in_use ?? 0) - 1);
block.data = { ...data, in_use };
if (in_use > 0) return;
block.set_ticking(false);
update_generated(world, [block.x, block.y, block.z]);
},
});
// 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, compacting);
register_basin(ctx);
}
// holds items dropped into it and fluid poured in, like create's BasinBlock: an item that lands in it goes in, and an
// empty hand takes every item out. its tanks are its fluid handler, which a full fluid container used on it empties
// into and an empty one fills from. what's in it is its "items" and "tanks" client data, kept nowhere else, which its
// visual draws. breaking it drops the items, and the fluid is lost
function register_basin(ctx: ServerContext) {
const items_of = (block: BlockRef) => basin_contents(block).items;
const set_items = (block: BlockRef, items: readonly ItemStack[]) => set_basin(block, { items });
const tanks = (block: BlockRef) =>
ctx.fluids.tank_handler({
tanks: BASIN_TANKS,
capacity: BASIN_TANK_CAPACITY,
get: () => basin_contents(block).tanks,
set: (tanks) => set_basin(block, { tanks }),
});
ctx.components.register_block("create:basin", {
on_entity_stand(block, _params, entity) {
const stack = entity.get_item();
if (!stack) return;
const { items, inserted } = insert_item(items_of(block), stack, ctx.items.max_stack(stack.id, stack.data));
if (inserted === 0) return;
set_items(block, items);
entity.set_item({ ...stack, count: stack.count - inserted });
},
on_interact(block, _params, player) {
const held = player.held_item;
if (!held) {
const { items, outputs } = basin_contents(block);
for (const item of [...items, ...outputs]) player.give_item(item.id, item.count, item.data);
set_basin(block, { items: [], outputs: [] });
return true;
}
// anything else is used or placed as if the basin weren't there
if (ctx.items.fluid_capacity(held.id) === undefined) return false;
ctx.fluids.interact(player, tanks(block));
// a fluid container is used up on the basin even when nothing fits, like create's
return true;
},
on_break(block) {
const { items, outputs } = basin_contents(block);
for (const item of [...items, ...outputs]) ctx.world.drop_item(block.x, block.y, block.z, item);
},
fluid_handler: (block) => tanks(block),
});
}
// what's in a basin, its "items", "outputs" and "tanks" client data, which its visual draws, and nowhere else
function basin_contents(block: BlockRef): BasinContents {
return {
items: block.get_client_data<ItemStack[]>("items") ?? [],
outputs: block.get_client_data<ItemStack[]>("outputs") ?? [],
tanks: block.get_client_data<FluidStack[]>("tanks") ?? [],
};
}
// changes the parts of what's in a basin given, an empty one taking its field away
function set_basin(block: BlockRef, contents: Partial<BasinContents>) {
for (const [field, list] of Object.entries(contents)) {
block.set_client_data(field, list.length > 0 ? list : undefined);
}
}
// presses items lying on the ground under it while it turns, like create's MechanicalPressBlockEntity pressing in the
// world: it looks for one it has a recipe for every SCAN_TICKS, then comes down on it, faster the faster it turns. a
// lone item turns into what it's pressed into, and from a stack one at a time is, landing beside the rest. with a
// basin two blocks under it, it presses into that instead, making a compacting recipe in it each time, like
// MechanicalPressBlockEntity as a BasinOperatingBlockEntity. it only ticks while it turns
function register_press(ctx: ServerContext, compacting: ProcessingRecipe[]) {
const pressing_for = (item: Id) => ctx.recipes.find<ProcessingRecipe>(PRESSING.id, item);
// the basin two blocks under it, with a block between for the head to come down through, like
// BasinOperatingBlockEntity.getBasin
const basin_under = (block: BlockRef) => {
const basin = ctx.world.get_block_ref(block.x, block.y - 2, block.z);
return basin && "create:basin" in ctx.blocks.components(basin.id) ? basin : undefined;
};
// the basin once the first compacting recipe that can be is made in it, undefined when none can. its results are
// rolled when it's made for real, and all of them have to fit for it to be made at all
const compact = (basin: BlockRef, roll: boolean) => {
const contents = basin_contents(basin);
for (const recipe of compacting) {
const made = apply_basin_recipe(
contents,
{ ...recipe, results: roll ? roll_results(recipe) : recipe.results },
(item) => ctx.items.max_stack(item.id, item.data),
(a, b) => ctx.fluids.same(a, b),
);
if (made) return made;
}
};
// the items lying in the block under it, a bit in from its sides when looking for one, like create's
const items_under = (block: BlockRef, inset: number) =>
ctx.world.entities_in(
{ x: block.x + inset, y: block.y - 1 + inset, z: block.z + inset },
{ x: block.x + 1 - inset, y: block.y - inset, z: block.z + 1 - inset },
"bworld:item",
).filter((item) => item.on_ground && pressing_for(item.get_item()!.id));
const press = (item: EntityRef) => {
const stack = item.get_item()!;
const results = roll_results(pressing_for(stack.id)!);
const { x, y, z } = item.position;
if (stack.count === 1) {
const [first, ...rest] = results;
item.set_item(first);
for (const extra of rest) {
const { x: vx, y: vy, z: vz } = item.velocity;
ctx.world.spawn_item(x, y, z, extra).push(vx, vy, vz);
}
return;
}
const scatter = () => (Math.random() - 0.5) * 2;
for (const result of results) ctx.world.spawn_item(x, y, z, result).push(scatter(), scatter(), scatter());
item.set_item({ ...stack, count: stack.count - 1 });
};
ctx.components.register_block("create:mechanical_press", {
on_tick(block) {
const data: PressData = block.data ?? {};
const rate = cycle_rate(actual_speed(block));
if (data.pressing === undefined) {
// a block that starts turning ticks again, see kinetic_world
if (rate === 0) {
block.set_ticking(false);
return;
}
// over a basin it only presses into that
const scan = (data.scan ?? 1) - 1;
const basin = scan <= 0 ? basin_under(block) : undefined;
const found = scan <= 0 &&
(basin ? compact(basin, false) !== undefined : items_under(block, 0.125).length > 0);
const mode = basin ? { basin: true } : {};
block.data = { ...data, scan: scan <= 0 ? SCAN_TICKS : scan, ...(found && { pressing: 0, ...mode }) };
if (found) block.set_client_data("press", { steps: 0, rate, ...mode } satisfies PressShown);
return;
}
const steps = data.pressing;
if (steps === PRESS_AT && rate > 0) {
// what's in the basin could have changed since it started
const basin = data.basin ? basin_under(block) : undefined;
const made = basin && compact(basin, true);
if (basin && made) set_basin(basin, made);
else if (!data.basin) {
const [item] = items_under(block, 0);
if (item) press(item);
}
}
// done, and it looks again straight away, for the rest of a stack
if (steps > CYCLE) {
const { pressing: _, scan: __, basin: ___, ...rest } = data;
block.data = rest;
block.set_client_data("press", undefined);
return;
}
// it stops at the bottom to press on the next tick, however fast it's going
const next = steps < PRESS_AT && steps + rate >= PRESS_AT ? PRESS_AT : steps + rate;
block.data = { ...data, pressing: next };
if (block.get_client_data<PressShown>("press")?.rate !== rate) {
const mode = data.basin ? { basin: true } : {};
block.set_client_data("press", { steps: next, rate, ...mode } satisfies PressShown);
}
if (rate === 0) block.set_ticking(false);
},
});
}
// 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?: 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 GeneratorParams | undefined,
motor: components["create:creative_motor"] as GeneratorParams | undefined,
wheel: components["create:water_wheel"] as GeneratorParams | undefined,
};
params.set(id, found);
}
return found;
};
const block_at = (at: Pos): BlockRef => {
const block = ctx.world.get_block_ref(...at);
if (!block) throw new Error(`there's no kinetic block at ${at.join(" ")}`);
return block;
};
return {
get(x, y, z) {
const block = ctx.world.get_block_ref(x, y, z);
if (!block) return undefined;
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 & 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,
y,
z,
...shape,
speed: block.get_client_data<number>("speed") ?? 0,
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) {
const block = block_at(at);
// machines stop ticking while they're still, like a press, and start again once they turn
if (speed !== 0 && !block.get_client_data("speed")) block.set_ticking(true);
block.set_client_data("speed", speed === 0 ? undefined : speed);
// the side its speed comes from decides how a gearbox's or clutch's axles turn, which its visual shows
const { gearbox, split } = params_of(block.id).kinetic!;
if (gearbox || split) {
block.set_client_data("source", source_face({ x: at[0], y: at[1], z: at[2], source }));
}
const { source: _, network: __, ...rest }: KineticData = block.data ?? {};
block.data = { ...rest, ...(source && { source }), ...(network !== undefined && { network }) };
},
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,
};
}