Hand crank and shafts
This commit is contained in:
@@ -5,8 +5,8 @@ redstone, contraptions, trains, equipment, decoration and schematics. It aims to
|
||||
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||
|
||||
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5,
|
||||
R8, S0, S7, S12, and stonecutting from S9. Facts about Create come from reading `ports/create1.21.1` and
|
||||
`ports/create1.19.3`, and facts about bworld from its source.
|
||||
R8, S0, S7, S12, stonecutting from S9, and the start of P1's kinetics: shafts turned by a hand crank. Facts about Create
|
||||
come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -123,7 +123,8 @@ shared tags to `c`, which is what bworld calls them. A mod's remap file is where
|
||||
|
||||
Block properties (shape, tool, toughness) aren't in any data file: Java mods set them in code. `mod` writes a block for
|
||||
each blockstate with placeholder properties, and a per-mod table fills them in. For Create that table is
|
||||
`mods/create/import/blocks.json`.
|
||||
`mods/create/import/blocks.json`. Built for `blockstate` as `--blocks FILE`: each block's fields in it, like its
|
||||
`components`, replace the ones the importer would write, and a block it names that isn't made is an error.
|
||||
|
||||
**What `model` does today.** It keeps `parent`, since the engine merges parents in when it loads (see
|
||||
[Parents](docs/modding/resources/models.md#parents)), and remaps it like any id. Minecraft's template parents (`cube`,
|
||||
@@ -175,8 +176,8 @@ Create 0.5.0.j's data gives 89 tags: 45 of Create's and 44 of Forge's shared one
|
||||
skipped. Of its 531 stonecutting recipes, 423 are converted. The other 108 cut granite, diorite, deepslate, calcite,
|
||||
tuff and dripstone, which bworld doesn't have yet. Re-importing once it does brings them in.
|
||||
|
||||
**For Create**, `mods/create/import/` keeps the remap file and the commands, and later the block table. Re-running the
|
||||
import is one command, and hand-written files are never in the folders it writes.
|
||||
**For Create**, `mods/create/import/` keeps the remap file, the block table and the commands. Re-running the import is
|
||||
one command, and hand-written files are never in the folders it writes.
|
||||
|
||||
**Vanilla ids in recipes.** Create's recipes use 447 distinct Minecraft ids, like dyes, `minecraft:cobblestone` and
|
||||
`minecraft:netherrack`. Each becomes the bworld id of the same name, or another with the remap file's `ids`. A recipe
|
||||
@@ -465,6 +466,20 @@ visual makes a `rotating` instance with the axis, rpm and an offset that keeps c
|
||||
when the block's coordinates on the two axes that aren't its axis add up to an even number, otherwise 11.25° for large
|
||||
cogs and 0 for the rest. A speed change updates one instance, and nothing else happens per frame.
|
||||
|
||||
**As built** (`scripts/kinetics/`, the shaft and the hand crank). `create:kinetic` takes `axis` (the state with x, y or
|
||||
z) or `facing` (the state with the 6 faces) and `shaft` (`both`, `front` or `back`), and its shared rules place blocks
|
||||
like `RotatedPillarKineticBlock` and `DirectionalKineticBlock`, lining up with an axle beside them. Connections are only
|
||||
axle to axle so far. Spreading is `RotationPropagator`'s, with queues: a block's speed is its `speed` client data, and
|
||||
the block it gets it from and the generator it comes from (`source` and `network`) are tile data. Two things differ:
|
||||
on_break runs while the block is still there, so the walk after a removal treats its place as empty, and generators that
|
||||
stop with what turned them start again right after the walk instead of a tick later (`reActivateSource`). Create's
|
||||
flicker score and its periodic `validateKinetics` aren't ported, since shafts don't tick. `create:hand_crank` turns
|
||||
while it's clicked, for 10 ticks after each click, the other way while sneaking, and costs hunger by the config's
|
||||
`crank_hunger`. Its visual turns the half shaft as a `rotating` instance and eases the handle in `on_frame`, like
|
||||
`HandCrankVisual`. The crank doesn't pop off when its block is taken away yet. It needed three engine additions:
|
||||
`looking` in `state_for_placement` (`getNearestLookingDirection`), `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.
|
||||
|
||||
|
||||
+1
-1
@@ -110,7 +110,7 @@ export class MultiPlayerGameMode {
|
||||
// with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into
|
||||
const place_value = place_block &&
|
||||
waterlog_placement(
|
||||
block_rules.placement_value(place_block, this.client.player.yaw, {
|
||||
block_rules.placement_value(place_block, this.client.player.yaw, this.client.player.pitch, {
|
||||
...target,
|
||||
face: hit.face,
|
||||
hit: hit.hit,
|
||||
|
||||
+14
-8
@@ -196,12 +196,25 @@ function script_url(code: string) {
|
||||
return code_url(new TextEncoder().encode(code));
|
||||
}
|
||||
|
||||
// ctx.blocks, the same in shared and client scripts
|
||||
function blocks_api(mod: string): SharedContext["blocks"] {
|
||||
return {
|
||||
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
||||
components(id) {
|
||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
||||
return structuredClone(block.components ?? {});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function shared_context(listing: ModListing): SharedContext {
|
||||
const mod = listing.id;
|
||||
return {
|
||||
mod: { id: mod, version: listing.version },
|
||||
side: "client",
|
||||
tags: tag_api(),
|
||||
blocks: blocks_api(mod),
|
||||
world: rules_world,
|
||||
components: {
|
||||
register_block(id, rules) {
|
||||
@@ -323,14 +336,7 @@ function client_context(listing: ModListing): ClientContext {
|
||||
EverythingRegistry.get<ItemRegistry>("items", id)?.components ?? {},
|
||||
)),
|
||||
},
|
||||
blocks: {
|
||||
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
||||
components(id) {
|
||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
||||
return structuredClone(block.components ?? {});
|
||||
},
|
||||
},
|
||||
blocks: blocks_api(mod),
|
||||
loot: {
|
||||
table: (id) => structuredClone(EverythingRegistry.get<LootTableJson>("loot_tables", id)),
|
||||
},
|
||||
|
||||
+28
-5
@@ -4,7 +4,7 @@
|
||||
// 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, SharedWorld } from "./mod_api/shared.ts";
|
||||
import type { BlockInteraction, BlockPlacement, BlockRules as Rules, Face, SharedWorld } from "./mod_api/shared.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
|
||||
import { default_block_value, set_state_value } from "./utils.ts";
|
||||
|
||||
@@ -20,6 +20,19 @@ export function horizontal_facing(yaw: number): typeof FACINGS[number] {
|
||||
return FACINGS[((quarter % 4) + 4) % 4];
|
||||
}
|
||||
|
||||
// the face of the six someone looking at yaw and pitch looks most toward, like minecraft's getNearestLookingDirection.
|
||||
// pitch above 0 looks up, the way the camera aims
|
||||
export function looking_face(yaw: number, pitch: number): Face {
|
||||
const cos_pitch = Math.cos(pitch);
|
||||
const x = -Math.sin(yaw) * cos_pitch;
|
||||
const y = Math.sin(pitch);
|
||||
const z = -Math.cos(yaw) * cos_pitch;
|
||||
const [ax, ay, az] = [Math.abs(x), Math.abs(y), Math.abs(z)];
|
||||
if (ay >= ax && ay >= az) return y > 0 ? "top" : "bottom";
|
||||
if (ax >= az) return x > 0 ? "east" : "west";
|
||||
return z > 0 ? "south" : "north";
|
||||
}
|
||||
|
||||
// a block's value as a player looking at yaw places it before any rules: its default states, and a 2 bit facing
|
||||
// turned towards them, like a furnace
|
||||
export function default_placement_value(block: BlockRegistry, yaw: number): number {
|
||||
@@ -52,11 +65,21 @@ export class BlockRules {
|
||||
});
|
||||
}
|
||||
|
||||
// the block's value with the states a player placing it gets: its defaults facing them (default_placement_value),
|
||||
// then what its rules' state_for_placement say. states that don't exist or don't fit are left alone
|
||||
placement_value(block: BlockRegistry, yaw: number, where: Omit<BlockPlacement, "facing">): number {
|
||||
// the block's value with the states a player looking at yaw and pitch placing it gets: its defaults facing them
|
||||
// (default_placement_value), then what its rules' state_for_placement say. states that don't exist or don't fit are
|
||||
// left alone
|
||||
placement_value(
|
||||
block: BlockRegistry,
|
||||
yaw: number,
|
||||
pitch: number,
|
||||
where: Omit<BlockPlacement, "facing" | "looking">,
|
||||
): number {
|
||||
let value = default_placement_value(block, yaw);
|
||||
const placement: BlockPlacement = { ...where, facing: horizontal_facing(yaw) };
|
||||
const placement: BlockPlacement = {
|
||||
...where,
|
||||
facing: horizontal_facing(yaw),
|
||||
looking: looking_face(yaw, pitch),
|
||||
};
|
||||
for (const { mod, id, rules, params } of this.#of(block)) {
|
||||
if (!rules.state_for_placement) continue;
|
||||
const states = this.run(
|
||||
|
||||
@@ -242,6 +242,9 @@ export interface ServerWorld {
|
||||
// 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;
|
||||
get_block_data<T>(x: number, y: number, z: number): T | undefined;
|
||||
// the block the way its components' handlers get it, for changing another block's data or client data, like
|
||||
// minecraft's getBlockEntity. undefined for air
|
||||
get_block_ref(x: number, y: number, z: number): BlockRef | undefined;
|
||||
// BlockRef.set_ticking for a block, for waking one from somewhere else, like a machine getting something to work on
|
||||
set_block_ticking(x: number, y: number, z: number, ticking: boolean): void;
|
||||
// the item a block with item_display shows on top of it, like a block entity renderer: its "item" client data, see
|
||||
|
||||
@@ -66,6 +66,13 @@ export interface SharedContext {
|
||||
// the world rules look at and change. on a client it's what that client sees, and what rules change there is a
|
||||
// guess until the server says what really happened. only for use in rules, not during setup
|
||||
readonly world: SharedWorld;
|
||||
// every block any mod registered, like the server's and clients' ctx.blocks. for rules that look at what's around,
|
||||
// like a shaft lining up with the axle of the block it's placed against
|
||||
readonly blocks: {
|
||||
exists(id: Id): boolean;
|
||||
// the components its json lists and their params, a copy
|
||||
components(id: Id): Record<Id, unknown>;
|
||||
};
|
||||
readonly components: {
|
||||
// the rules of a block component, the same id the server script registers the rest of it under
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -93,12 +100,14 @@ export interface SharedBlock extends Position {
|
||||
}
|
||||
|
||||
// a player placing a block at x y z by clicking face of the block next to it, at hit (0 to 1 on each axis of that
|
||||
// block), like minecraft's BlockPlaceContext. facing is the way the player looks, along the ground, and sneaking
|
||||
// whether they hold the sneak key, for blocks placed another way round when they do
|
||||
// block), like minecraft's BlockPlaceContext. facing is the way the player looks along the ground, and looking the face
|
||||
// of the six they look most toward, up and down too, like getNearestLookingDirection. sneaking is whether they hold the
|
||||
// sneak key, for blocks placed another way round when they do
|
||||
export interface BlockPlacement extends Position {
|
||||
readonly face: Face;
|
||||
readonly hit: readonly [number, number, number];
|
||||
readonly facing: "north" | "east" | "south" | "west";
|
||||
readonly looking: Face;
|
||||
readonly sneaking: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,9 @@ export function setup(ctx: SharedContext) {
|
||||
|
||||
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](../worldgen/biomes.md#seasons)), and only works inside rules.
|
||||
[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.
|
||||
|
||||
### Neighbors
|
||||
|
||||
@@ -116,8 +118,9 @@ 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, face, hit, facing, sneaking }`: where it's going, the face of the block that was clicked, where on that
|
||||
block the click was (from 0 to 1 on each axis), the way the player looks along the ground, and whether they're
|
||||
`{ x, y, z, face, hit, facing, looking, sneaking }`: where it's going, the face of the block that was clicked, where on
|
||||
that block the click was (from 0 to 1 on each axis), 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](../entities/players.md#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. 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
|
||||
|
||||
@@ -22,7 +22,9 @@ ctx.components.register_block("copper_tools:counter", {
|
||||
});
|
||||
```
|
||||
|
||||
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
|
||||
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it. To change another block's data, like a shaft passing
|
||||
its speed to the next one, `ctx.world.get_block_ref(x, y, z)` gives that block the way its own handlers get it, like
|
||||
Minecraft's `getBlockEntity`, or `undefined` for air.
|
||||
|
||||
- Tile data is saved with the world, and goes away when the block is broken or replaced.
|
||||
- It's **never sent to clients**. To show it to a player, give it [client data](#client-data), open a
|
||||
|
||||
@@ -18,6 +18,11 @@
|
||||
"render_layer": "cutout",
|
||||
"mining": { "toughness": 1 },
|
||||
"drops": "create:hand_crank",
|
||||
"item_model": "create:item_hand_crank"
|
||||
"item_model": "create:item_hand_crank",
|
||||
"interactive": true,
|
||||
"components": {
|
||||
"create:kinetic": { "facing": "facing", "shaft": "back" },
|
||||
"create:hand_crank": { "speed": 32 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
"render_layer": "cutout",
|
||||
"mining": { "toughness": 1 },
|
||||
"drops": "create:shaft",
|
||||
"item_model": "create:item_shaft"
|
||||
"item_model": "create:item_shaft",
|
||||
"components": {
|
||||
"create:kinetic": { "axis": "axis" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"config": {
|
||||
"max_speed": 256,
|
||||
"crank_hunger": 0.01
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ importer or `remap.json` and import again:
|
||||
rm -rf mods/create/textures mods/create/models mods/create/blocks mods/create/items mods/create/tags mods/create/recipes
|
||||
deno task import texture ports/create1.19.3/src --namespace create --output mods/create/textures --remap mods/create/import/remap.json
|
||||
deno task import model ports/create1.19.3/src --namespace create --output mods/create/models --remap mods/create/import/remap.json
|
||||
deno task import blockstate ports/create1.19.3/src --namespace create --output mods/create/blocks --remap mods/create/import/remap.json
|
||||
deno task import blockstate ports/create1.19.3/src --namespace create --output mods/create/blocks --remap mods/create/import/remap.json --blocks mods/create/import/blocks.json
|
||||
deno task import item ports/create1.19.3/src --namespace create --output mods/create/items --remap mods/create/import/remap.json
|
||||
deno task import tag ports/create1.19.3/src/generated --namespace create --output mods/create/tags --remap mods/create/import/remap.json
|
||||
deno task import tag ports/create1.19.3/src/generated --namespace forge --output mods/create/tags --remap mods/create/import/remap.json
|
||||
@@ -21,6 +21,10 @@ then tags, then recipes. Forge's shared tags, like `forge:ingots/brass`, become
|
||||
Create's stonecutting ones so far, and the ones that cut a stone bworld doesn't have yet (granite, diorite, deepslate,
|
||||
calcite, tuff, dripstone) are left out until it does.
|
||||
|
||||
Java sets what blocks do in code, so every block gets placeholders (a second to mine with anything, dropping itself).
|
||||
`blocks.json` gives blocks what they have instead, by id, like the components that make a shaft turn and a hand crank
|
||||
turn it. Each block's fields there replace the ones the importer would write.
|
||||
|
||||
`remap.json` gives three of Create's models other names, since `block/radial_chassis/side_x` and
|
||||
`block/radial_chassis_side_x` would both be `create:block_radial_chassis_side_x`.
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"create:shaft": {
|
||||
"components": {
|
||||
"create:kinetic": { "axis": "axis" }
|
||||
}
|
||||
},
|
||||
"create:hand_crank": {
|
||||
"interactive": true,
|
||||
"components": {
|
||||
"create:kinetic": { "facing": "facing", "shaft": "back" },
|
||||
"create:hand_crank": { "speed": 32 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"format_version": 1,
|
||||
"id": "create",
|
||||
"name": "Create",
|
||||
"description": "A port of the Create team's Create. So far its blocks and items, which can be placed and look like Create's, but don't do anything yet.",
|
||||
"description": "A port of the Create team's Create. So far its blocks and items, which can be placed and look like Create's, and shafts turned by a hand crank.",
|
||||
"version": "0.1.0",
|
||||
"authors": [
|
||||
"simibubi and the Create team (original)",
|
||||
@@ -15,5 +15,10 @@
|
||||
"version": "*"
|
||||
}
|
||||
],
|
||||
"credits": "CREDITS.md"
|
||||
"credits": "CREDITS.md",
|
||||
"scripts": {
|
||||
"server": "scripts/server.ts",
|
||||
"client": "scripts/client.ts",
|
||||
"shared": "scripts/shared.ts"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// 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
|
||||
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "bworld/client";
|
||||
import type { Face } from "bworld/shared";
|
||||
import { type Axis, kinetic_shape, type KineticParams, type KineticShape } from "./kinetics/connections.ts";
|
||||
|
||||
// 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 },
|
||||
};
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
const shape_of = (block: VisualBlock): KineticShape => {
|
||||
const params = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams;
|
||||
return kinetic_shape(params, (name) => block.states[name]);
|
||||
};
|
||||
|
||||
const shaft = (block: VisualBlock, instances: Instances) => turning(block, instances, shape_of(block)).visual;
|
||||
ctx.render.register_visual("create:shaft", shaft, { replaces_model: true });
|
||||
|
||||
// the half shaft turns with the speed like any kinetic block, and the handle catches up with it and slows down
|
||||
// with it, like HandCrankVisual's independent angle
|
||||
ctx.render.register_visual("create:hand_crank", (block, instances) => {
|
||||
const shape = shape_of(block);
|
||||
const { visual, speed } = turning(block, instances, shape);
|
||||
const handle = instances.rotating(HANDLE_TURNS[shape.facing!]);
|
||||
// in degrees, and degrees a tick
|
||||
let angle = 0;
|
||||
let velocity = 0;
|
||||
let last: number | undefined;
|
||||
return {
|
||||
...visual,
|
||||
on_frame(time) {
|
||||
const ticks = last === undefined ? 0 : time - last;
|
||||
last = time;
|
||||
// a quarter of the way to the shaft's speed each tick
|
||||
velocity += (speed() * 0.3 - velocity) * Math.min(1, ticks / 4);
|
||||
angle = (angle + velocity * ticks) % 360;
|
||||
handle.set_rotation(shape.axis, 0, angle);
|
||||
},
|
||||
};
|
||||
}, { replaces_model: true });
|
||||
}
|
||||
|
||||
// the block's own model turning around its axis at its speed. offset so cogs mesh with the ones beside them, like
|
||||
// KineticBlockEntityVisual.rotationOffset: turned by half a tooth on every other block
|
||||
function turning(block: VisualBlock, instances: Instances, shape: KineticShape) {
|
||||
const speed = () => block.get_client_data<number>("speed") ?? 0;
|
||||
const instance = instances.rotating();
|
||||
const offset = should_offset(shape.axis, block) ? 22.5 : 0;
|
||||
const turn = () => instance.set_rotation(shape.axis, speed(), offset);
|
||||
turn();
|
||||
const visual: Visual = { update: turn };
|
||||
return { visual, speed };
|
||||
}
|
||||
|
||||
// whether the coordinates across the axis add up to an even number, like KineticBlockEntityVisual.shouldOffset
|
||||
function should_offset(axis: Axis, { x, y, z }: VisualBlock) {
|
||||
const across = (axis === "x" ? 0 : x) + (axis === "y" ? 0 : y) + (axis === "z" ? 0 : z);
|
||||
return across % 2 === 0;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what turns, and what turns what: a kinetic block's axis and the ends of it with an axle, and how fast one block turns
|
||||
// the one next to it, like create's IRotate and RotationPropagator.getRotationSpeedModifier. no ctx, so placement
|
||||
// rules, the server and visuals all read blocks the same way
|
||||
import type { Face } from "bworld/shared";
|
||||
|
||||
export type Axis = "x" | "y" | "z";
|
||||
|
||||
// the create:kinetic component's params, from a block's json
|
||||
export interface KineticParams {
|
||||
// the 2 bit state that says its axis, x, y or z, like a shaft's
|
||||
axis?: string;
|
||||
// or the 3 bit state that says which way it faces, north, east, south, west, up or down, its axis going through
|
||||
// that face, like a crank's
|
||||
facing?: string;
|
||||
// which ends of its axis have an axle that turns the block there: both, or for one with a facing only the end it
|
||||
// faces ("front") or the other ("back"). both when not given
|
||||
shaft?: "both" | "front" | "back";
|
||||
}
|
||||
|
||||
// a 3 bit facing state's values, in the order the importer numbers java's facing
|
||||
export const FACINGS: readonly Face[] = ["north", "east", "south", "west", "top", "bottom"];
|
||||
const AXES: readonly Axis[] = ["x", "y", "z"];
|
||||
|
||||
export const FACE_OFFSETS: Readonly<Record<Face, readonly [number, number, number]>> = {
|
||||
west: [-1, 0, 0],
|
||||
east: [1, 0, 0],
|
||||
bottom: [0, -1, 0],
|
||||
top: [0, 1, 0],
|
||||
north: [0, 0, -1],
|
||||
south: [0, 0, 1],
|
||||
};
|
||||
|
||||
export const OPPOSITE: Readonly<Record<Face, Face>> = {
|
||||
west: "east",
|
||||
east: "west",
|
||||
bottom: "top",
|
||||
top: "bottom",
|
||||
north: "south",
|
||||
south: "north",
|
||||
};
|
||||
|
||||
const FACE_AXIS: Readonly<Record<Face, Axis>> = {
|
||||
west: "x",
|
||||
east: "x",
|
||||
bottom: "y",
|
||||
top: "y",
|
||||
north: "z",
|
||||
south: "z",
|
||||
};
|
||||
|
||||
// the faces at the positive and negative ends of an axis
|
||||
const AXIS_FACES: Readonly<Record<Axis, readonly [Face, Face]>> = {
|
||||
x: ["east", "west"],
|
||||
y: ["top", "bottom"],
|
||||
z: ["south", "north"],
|
||||
};
|
||||
|
||||
// how a block turns
|
||||
export interface KineticShape {
|
||||
axis: Axis;
|
||||
// the faces with an axle
|
||||
shafts: readonly Face[];
|
||||
// the way it faces, for a block with a facing
|
||||
facing?: Face;
|
||||
}
|
||||
|
||||
// a kinetic block where it is
|
||||
export interface Kinetic extends KineticShape {
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly z: number;
|
||||
}
|
||||
|
||||
// a block's shape from its params and its states, read by name
|
||||
export function kinetic_shape(params: KineticParams, state: (name: string) => number | undefined): KineticShape {
|
||||
if (params.facing !== undefined) {
|
||||
const facing = FACINGS[state(params.facing) ?? 0];
|
||||
const shaft = params.shaft ?? "both";
|
||||
const shafts = shaft === "front"
|
||||
? [facing]
|
||||
: shaft === "back"
|
||||
? [OPPOSITE[facing]]
|
||||
: [facing, OPPOSITE[facing]];
|
||||
return { axis: FACE_AXIS[facing], shafts, facing };
|
||||
}
|
||||
const axis = AXES[state(params.axis ?? "axis") ?? 1];
|
||||
return { axis, shafts: AXIS_FACES[axis] };
|
||||
}
|
||||
|
||||
export function face_axis(face: Face): Axis {
|
||||
return FACE_AXIS[face];
|
||||
}
|
||||
|
||||
// a speed turning counterclockwise seen from face, as rpm around face's axis, which is counterclockwise seen from its
|
||||
// positive end. like KineticBlockEntity.convertToDirection
|
||||
export function along(face: Face, speed: number): number {
|
||||
return AXIS_FACES[FACE_AXIS[face]][0] === face ? speed : -speed;
|
||||
}
|
||||
|
||||
// the face of from that to is beside, undefined when they aren't beside each other
|
||||
function face_toward(from: Kinetic, to: Kinetic): Face | undefined {
|
||||
const [dx, dy, dz] = [to.x - from.x, to.y - from.y, to.z - from.z];
|
||||
return (Object.keys(FACE_OFFSETS) as Face[]).find((face) => {
|
||||
const [ox, oy, oz] = FACE_OFFSETS[face];
|
||||
return ox === dx && oy === dy && oz === dz;
|
||||
});
|
||||
}
|
||||
|
||||
// how much faster to turns than from when from turns it, 0 when from doesn't turn it: 1 for axles that meet. like
|
||||
// RotationPropagator.getRotationSpeedModifier
|
||||
export function speed_ratio(from: Kinetic, to: Kinetic): number {
|
||||
const face = face_toward(from, to);
|
||||
if (face && from.shafts.includes(face) && to.shafts.includes(OPPOSITE[face])) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// where the blocks it could turn are, like getPotentialNeighbourLocations
|
||||
export function neighbour_positions(block: Kinetic): [number, number, number][] {
|
||||
return Object.values(FACE_OFFSETS).map(([dx, dy, dz]) => [block.x + dx, block.y + dy, block.z + dz]);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// 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];
|
||||
|
||||
// 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;
|
||||
// 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 {
|
||||
// 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;
|
||||
// breaks it and drops it, like a shaft turned two ways at once. its on_break runs handle_removed
|
||||
break(at: Pos): void;
|
||||
// the fastest anything can turn, like the maxRotationSpeed config
|
||||
readonly max_speed: number;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// a block is going: what it turned stops, then what's still turning around that spreads back in, like handleRemoved.
|
||||
// on_break runs while it's still there, so the walks don't see it
|
||||
export function handle_removed(world: KineticWorld, at: Pos) {
|
||||
const node = world.get(...at);
|
||||
if (!node || node.speed === 0) return;
|
||||
const without: KineticWorld = {
|
||||
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),
|
||||
max_speed: world.max_speed,
|
||||
};
|
||||
restart(without, detach(without, node));
|
||||
}
|
||||
|
||||
// a generator's speed changed, like a crank being turned or let go. like GeneratingKineticBlockEntity's
|
||||
// updateGeneratedRotation
|
||||
export function update_generated(world: KineticWorld, at: Pos) {
|
||||
const node = world.get(...at);
|
||||
if (!node || node.generated === node.speed) return;
|
||||
const speed = node.generated;
|
||||
if (speed === 0) {
|
||||
// something else turns it, so it goes on turning with that
|
||||
if (node.source) return;
|
||||
world.set(at, 0, undefined, undefined);
|
||||
restart(world, detach(world, node));
|
||||
return;
|
||||
}
|
||||
if (node.source && node.speed !== 0 && Math.abs(node.speed) >= Math.abs(speed)) {
|
||||
// something as fast or faster turns it: it goes along, unless it's turning the other way
|
||||
if (Math.sign(node.speed) !== Math.sign(speed)) world.break(at);
|
||||
return;
|
||||
}
|
||||
// it turns everything it's connected to, at its own speed. what it turned before stops first, so its old speed
|
||||
// doesn't meet its new one
|
||||
world.set(at, speed, undefined, network_of(at));
|
||||
const stopped = node.speed !== 0 ? detach(world, node) : [];
|
||||
spread(world, at);
|
||||
restart(world, stopped);
|
||||
}
|
||||
|
||||
const same = (a: Pos | undefined, b: Pos) => a !== undefined && a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
|
||||
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] : [];
|
||||
});
|
||||
}
|
||||
|
||||
// spreads the speed at start to what it's connected to, and on through whatever that changes, like
|
||||
// propagateNewSource
|
||||
function spread(world: KineticWorld, start: Pos) {
|
||||
const queue: Pos[] = [start];
|
||||
for (let i = 0; i < queue.length; i++) {
|
||||
const at = queue[i];
|
||||
const current = world.get(...at);
|
||||
if (!current) continue;
|
||||
for (const neighbour of connected(world, current)) {
|
||||
const new_speed = current.speed * speed_ratio(current, neighbour);
|
||||
const opposite_speed = neighbour.speed * speed_ratio(neighbour, current);
|
||||
if (new_speed === 0 && opposite_speed === 0) continue;
|
||||
|
||||
const against = new_speed !== 0 && neighbour.speed !== 0 &&
|
||||
Math.sign(new_speed) !== Math.sign(neighbour.speed);
|
||||
const too_fast = Math.abs(new_speed) > world.max_speed || Math.abs(opposite_speed) > world.max_speed;
|
||||
if (against || too_fast) {
|
||||
world.break(at);
|
||||
break;
|
||||
}
|
||||
// the neighbour is faster, so it turns this one, which passes that on from here
|
||||
if (Math.abs(opposite_speed) > Math.abs(current.speed)) {
|
||||
world.set(at, opposite_speed, pos_of(neighbour), neighbour.network);
|
||||
queue.push(at);
|
||||
break;
|
||||
}
|
||||
// this one is at least as fast, so it takes over everything the neighbour turns. unless the same generator
|
||||
// turns both, which is a loop: fine while the speeds agree, and this breaks when they don't
|
||||
const loop = current.network === undefined || current.network === neighbour.network;
|
||||
if (Math.abs(new_speed) >= Math.abs(neighbour.speed) && loop) {
|
||||
if (Math.abs(new_speed) > Math.abs(neighbour.speed) * (1 + 1 / 65536)) {
|
||||
world.break(at);
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (Math.abs(new_speed) < Math.abs(neighbour.speed) && Math.abs(neighbour.speed - new_speed) <= 1e-4) {
|
||||
continue;
|
||||
}
|
||||
world.set(pos_of(neighbour), new_speed, at, current.network);
|
||||
queue.push(pos_of(neighbour));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the blocks node turned stop, like the removed or stopped block's part of RotationPropagator.handleRemoved. returns
|
||||
// the generators among them, see restart
|
||||
function detach(world: KineticWorld, node: Kinetic): Pos[] {
|
||||
const at = pos_of(node);
|
||||
return neighbour_positions(node).flatMap((where) =>
|
||||
same(world.get(...where)?.source, at) ? clear(world, where) : []
|
||||
);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// stops start and everything that got its speed through it, then lets what's still turning at the edges spread back
|
||||
// in, like propagateMissingSource. returns the generators in it
|
||||
function clear(world: KineticWorld, start: Pos): Pos[] {
|
||||
const missing = world.get(...start)?.source;
|
||||
const edges: Pos[] = [];
|
||||
const generators: Pos[] = [];
|
||||
const frontier: Pos[] = [start];
|
||||
for (let i = 0; i < frontier.length; i++) {
|
||||
const at = frontier[i];
|
||||
const current = world.get(...at);
|
||||
if (!current) continue;
|
||||
world.set(at, 0, undefined, undefined);
|
||||
if (current.generated !== 0) generators.push(at);
|
||||
for (const neighbour of connected(world, current)) {
|
||||
const where = pos_of(neighbour);
|
||||
if (same(missing, where) || !neighbour.source) continue;
|
||||
if (same(neighbour.source, at)) frontier.push(where);
|
||||
else edges.push(where);
|
||||
}
|
||||
}
|
||||
// an edge can turn out to be part of what stopped, found from another side later
|
||||
const edge = edges.find((at) => world.get(...at)?.source !== undefined);
|
||||
if (edge) spread(world, edge);
|
||||
return generators;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// 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) and the hand crank that turns it
|
||||
import type { BlockRef, 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";
|
||||
|
||||
interface Config {
|
||||
max_speed: number;
|
||||
crank_hunger: number;
|
||||
}
|
||||
|
||||
// a kinetic block's tile data, see KineticNode. its speed is its "speed" 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 {
|
||||
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;
|
||||
}
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
const config: Config = ctx.config;
|
||||
const world = kinetic_world(ctx, config);
|
||||
|
||||
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]);
|
||||
},
|
||||
});
|
||||
|
||||
// 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", {
|
||||
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]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// the world as rotation spreading sees it: blocks with create:kinetic, their speed in client data and where it 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_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,
|
||||
};
|
||||
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 } = 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 generated = crank && data.in_use && shape.facing
|
||||
? along(shape.facing, data.backwards ? -crank.speed : crank.speed)
|
||||
: 0;
|
||||
return {
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
...shape,
|
||||
speed: block.get_client_data<number>("speed") ?? 0,
|
||||
source: data.source,
|
||||
network: data.network,
|
||||
generated,
|
||||
};
|
||||
},
|
||||
set(at, speed, source, network) {
|
||||
const block = block_at(at);
|
||||
block.set_client_data("speed", speed === 0 ? undefined : speed);
|
||||
const { source: _, network: __, ...rest }: KineticData = block.data ?? {};
|
||||
block.data = { ...rest, ...(source && { source }), ...(network !== undefined && { network }) };
|
||||
},
|
||||
break(at) {
|
||||
ctx.world.break_block(...at);
|
||||
},
|
||||
max_speed: config.max_speed,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// how create's blocks are placed, on the server and on every client: kinetic blocks line up with the axles they're
|
||||
// placed against
|
||||
import type { Face, SharedContext } from "bworld/shared";
|
||||
import {
|
||||
face_axis,
|
||||
FACE_OFFSETS,
|
||||
FACINGS,
|
||||
kinetic_shape,
|
||||
type KineticParams,
|
||||
OPPOSITE,
|
||||
} from "./kinetics/connections.ts";
|
||||
|
||||
const AXES = ["x", "y", "z"];
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
// the side of x y z with an axle pointing at it, like getPreferredFacing. undefined when there's none, or when
|
||||
// axles point at it along two axes, since it can't line up with both
|
||||
const axle_beside = (x: number, y: number, z: number): Face | undefined => {
|
||||
let found: Face | undefined;
|
||||
for (const side of FACINGS) {
|
||||
const [dx, dy, dz] = FACE_OFFSETS[side];
|
||||
const [nx, ny, nz] = [x + dx, y + dy, z + dz];
|
||||
const id = ctx.world.get_block(nx, ny, nz);
|
||||
const params = id && ctx.blocks.exists(id)
|
||||
? ctx.blocks.components(id)["create:kinetic"] as KineticParams | undefined
|
||||
: undefined;
|
||||
if (!params) continue;
|
||||
const shape = kinetic_shape(params, (name) => ctx.world.get_state(nx, ny, nz, name));
|
||||
if (!shape.shafts.includes(OPPOSITE[side])) continue;
|
||||
if (found && face_axis(found) !== face_axis(side)) return undefined;
|
||||
found = side;
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
// 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
|
||||
ctx.components.register_block<KineticParams>("create:kinetic", {
|
||||
state_for_placement(placement, params) {
|
||||
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) };
|
||||
}
|
||||
const axis = side && !placement.sneaking
|
||||
? face_axis(side)
|
||||
: side
|
||||
? face_axis(placement.face)
|
||||
: face_axis(placement.looking);
|
||||
return { [params.axis ?? "axis"]: AXES.indexOf(axis) };
|
||||
},
|
||||
});
|
||||
|
||||
// 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) {
|
||||
const side = axle_beside(placement.x, placement.y, placement.z);
|
||||
return { facing: FACINGS.indexOf(side && !placement.sneaking ? OPPOSITE[side] : placement.face) };
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1214,7 +1214,7 @@ export class GameServer {
|
||||
const placing = EverythingRegistry.get<BlockRegistry>("blocks", held.block_id)!;
|
||||
// put into a source of the liquid it can hold, it holds it
|
||||
const placed_value = waterlog_placement(
|
||||
this.mods.rules.placement_value(placing, player.yaw, {
|
||||
this.mods.rules.placement_value(placing, player.yaw, player.pitch, {
|
||||
x: tx,
|
||||
y: ty,
|
||||
z: tz,
|
||||
|
||||
@@ -254,11 +254,12 @@ export class ModRuntime {
|
||||
if (typeof module.setup !== "function") {
|
||||
throw new ModLoadError(mod, "the shared script doesn't export a setup function");
|
||||
}
|
||||
const { world } = this.#context(mod, version, config);
|
||||
const { world, blocks } = this.#context(mod, version, config);
|
||||
const ctx: SharedContext = {
|
||||
mod: { id: mod, version },
|
||||
side: "server",
|
||||
tags: tag_api(),
|
||||
blocks,
|
||||
world: {
|
||||
get_block: world.get_block,
|
||||
get_state: world.get_state,
|
||||
@@ -697,6 +698,10 @@ export class ModRuntime {
|
||||
},
|
||||
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) => {
|
||||
const id = game().world.get_block_id(x, y, z);
|
||||
return id === AIR_ID ? undefined : this.block_ref(x, y, z, id);
|
||||
},
|
||||
set_block_ticking: (x, y, z, ticking) => game().set_tile_ticking(x, y, z, ticking),
|
||||
set_block_item: (x, y, z, item) => {
|
||||
const shown = item && item.count > 0 ? new_stack(item).to_data() : undefined;
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
// 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
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import type { Face } from "$/common/mod_api/shared.ts";
|
||||
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "$/common/mod_api/client.ts";
|
||||
import { setup as setup_client } from "$/mods/create/scripts/client.ts";
|
||||
import { stone_floor, test_game } from "../helpers.ts";
|
||||
|
||||
// facing and axis states, in the order the importer numbers them
|
||||
const FACING = { north: 0, east: 1, south: 2, west: 3, up: 4, down: 5 };
|
||||
const AXIS = { x: 0, y: 1, z: 2 };
|
||||
|
||||
// alice standing south of 0 100 0 on a stone floor, looking north, with nothing in her hands. config changes create's
|
||||
async function setup(config: Record<string, unknown> = {}) {
|
||||
const t = await test_game("mods", undefined, undefined, { create: config });
|
||||
const { game } = t;
|
||||
t.join(1, "alice");
|
||||
stone_floor(game, 6);
|
||||
for (let x = -6; x <= 6; x++) {
|
||||
for (let z = -6; z <= 6; z++) for (let y = 100; y < 104; y++) game.set_block(x, y, z, AIR_ID);
|
||||
}
|
||||
const move = (sneaking = false, pitch = 0) =>
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch, ...(sneaking && { sneaking }) });
|
||||
move();
|
||||
|
||||
// a block with one state set, the way a player would have placed it
|
||||
const place = (x: number, y: number, z: number, id: string, state?: string, value = 0) => {
|
||||
const info = EverythingRegistry.get<BlockRegistry>("blocks", id)!;
|
||||
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 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") =>
|
||||
t.send(1, { type: "use_block", x, y, z, face, hit: [0.5, 0.5, 1] });
|
||||
const ticks = (n: number) => {
|
||||
for (let i = 0; i < n; i++) game.tick();
|
||||
};
|
||||
// the rpm a crank turns at
|
||||
const crank =
|
||||
(EverythingRegistry.get<BlockRegistry>("blocks", "create:hand_crank")!.components!["create:hand_crank"] as {
|
||||
speed: number;
|
||||
}).speed;
|
||||
return { ...t, move, place, speed, state, use, ticks, crank };
|
||||
}
|
||||
|
||||
// a crank at 0 100 0 facing west, its axle in a line of shafts along x from 1 to length
|
||||
async function crank_and_line(length = 4, config?: Record<string, unknown>) {
|
||||
const t = await setup(config);
|
||||
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
|
||||
for (let x = 1; x <= length; x++) t.place(x, 100, 0, "create:shaft", "axis", AXIS.x);
|
||||
return t;
|
||||
}
|
||||
|
||||
const line = (t: { speed: (x: number, y: number, z: number) => number }, from: number, to: number) =>
|
||||
Array.from({ length: to - from + 1 }, (_, i) => t.speed(from + i, 100, 0));
|
||||
|
||||
Deno.test("a hand crank turns the line of shafts on its axle while it's being clicked, then it stops", async () => {
|
||||
const t = await crank_and_line();
|
||||
// a shaft across the line, and one past a gap, aren't turned
|
||||
t.place(2, 100, 1, "create:shaft", "axis", AXIS.z);
|
||||
t.place(6, 100, 0, "create:shaft", "axis", AXIS.x);
|
||||
|
||||
// facing west, it turns counterclockwise seen from the west, which is clockwise around x
|
||||
t.use(0, 100, 0);
|
||||
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
assertEquals([t.speed(2, 100, 1), t.speed(6, 100, 0)], [0, 0]);
|
||||
|
||||
// holding use clicks every 4 ticks, which keeps it going
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t.ticks(4);
|
||||
t.use(0, 100, 0);
|
||||
}
|
||||
assertEquals(t.speed(4, 100, 0), -t.crank);
|
||||
t.ticks(40);
|
||||
assertEquals(line(t, 0, 4), [0, 0, 0, 0, 0]);
|
||||
// still, nothing ticks
|
||||
assertEquals(t.game.world.ticks(t.game.world.get_tile(0, 100, 0)!), false);
|
||||
});
|
||||
|
||||
Deno.test("sneaking turns a crank the other way", async () => {
|
||||
const t = await crank_and_line();
|
||||
t.move(true);
|
||||
t.use(0, 100, 0);
|
||||
assertEquals(line(t, 0, 4), [t.crank, t.crank, t.crank, t.crank, t.crank]);
|
||||
|
||||
// turning it the other way while it turns turns the whole line around
|
||||
t.move(false);
|
||||
t.use(0, 100, 0);
|
||||
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
});
|
||||
|
||||
Deno.test("a shaft placed on a turning line turns with it, and breaking one stops what's past it", async () => {
|
||||
const t = await crank_and_line();
|
||||
t.use(0, 100, 0);
|
||||
t.place(5, 100, 0, "create:shaft", "axis", AXIS.x);
|
||||
assertEquals(t.speed(5, 100, 0), -t.crank);
|
||||
|
||||
t.game.destroy_block(2, 100, 0);
|
||||
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, 0, 0, 0, 0]);
|
||||
|
||||
// put back, it joins them up again
|
||||
t.place(2, 100, 0, "create:shaft", "axis", AXIS.x);
|
||||
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
|
||||
// breaking the crank stops all of it
|
||||
t.game.destroy_block(0, 100, 0);
|
||||
assertEquals(line(t, 1, 5), [0, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
Deno.test("a crank turned against a line another one turns breaks, and drops", async () => {
|
||||
const t = await crank_and_line(4);
|
||||
// at the other end, facing east, where turning it turns the line the other way around x
|
||||
t.place(5, 100, 0, "create:hand_crank", "facing", FACING.east);
|
||||
t.use(0, 100, 0);
|
||||
t.use(5, 100, 0);
|
||||
assertEquals(t.game.world.get_block_id(5, 100, 0), AIR_ID);
|
||||
assert(t.game.item_entities().some((e) => e.item.type_id === "create:hand_crank"));
|
||||
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
});
|
||||
|
||||
Deno.test("two cranks turning a line the same way turn it together, and either keeps it going", async () => {
|
||||
const t = await crank_and_line(4);
|
||||
t.place(5, 100, 0, "create:hand_crank", "facing", FACING.east);
|
||||
t.use(0, 100, 0);
|
||||
// sneaking turns this one the same way around x as the first
|
||||
t.move(true);
|
||||
t.use(5, 100, 0);
|
||||
assertEquals(t.game.world.get_block_id(5, 100, 0), "create:hand_crank");
|
||||
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
|
||||
// the first one let go, the second keeps the line turning on its own
|
||||
for (let i = 0; i < 10; i++) {
|
||||
t.ticks(4);
|
||||
t.use(5, 100, 0);
|
||||
}
|
||||
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
|
||||
t.ticks(40);
|
||||
assertEquals(line(t, 0, 5), [0, 0, 0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
Deno.test("a crank that would turn things faster than create's max_speed breaks", async () => {
|
||||
const t = await crank_and_line(2, { max_speed: 16 });
|
||||
t.use(0, 100, 0);
|
||||
assertEquals(t.game.world.get_block_id(0, 100, 0), AIR_ID);
|
||||
assertEquals(line(t, 1, 2), [0, 0]);
|
||||
});
|
||||
|
||||
Deno.test("turning a crank makes the player hungry", async () => {
|
||||
const t = await crank_and_line();
|
||||
const player = t.game.mods.player(t.game.players()[0]);
|
||||
const before = player.saturation + player.food;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
t.use(0, 100, 0);
|
||||
t.ticks(4);
|
||||
}
|
||||
assert(player.saturation + player.food < before);
|
||||
});
|
||||
|
||||
Deno.test("speeds are saved, and a crank still stops after the world is loaded", async () => {
|
||||
const t = await crank_and_line();
|
||||
t.use(0, 100, 0);
|
||||
const loaded = await test_game("mods", t.game.save());
|
||||
loaded.join(1, "alice");
|
||||
const speed = (x: number) => loaded.game.world.get_tile(x, 100, 0)?.client_data?.speed as number ?? 0;
|
||||
assertEquals(speed(3), -t.crank);
|
||||
for (let i = 0; i < 40; i++) loaded.game.tick();
|
||||
assertEquals(speed(3), 0);
|
||||
});
|
||||
|
||||
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" });
|
||||
t.send(1, { type: "chat", text: "/give create:hand_crank 64" });
|
||||
t.send(1, { type: "select_slot", slot: 0 });
|
||||
|
||||
// on the floor, looking north and then down
|
||||
t.use(-2, 99, 0, "top");
|
||||
assertEquals(t.state(-2, 100, 0, "axis"), AXIS.z);
|
||||
t.move(false, -1.4);
|
||||
t.use(-3, 99, 0, "top");
|
||||
assertEquals(t.state(-3, 100, 0, "axis"), AXIS.y);
|
||||
|
||||
// beside the back of a crank facing west, along its axle
|
||||
t.move();
|
||||
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
|
||||
t.use(1, 99, 0, "top");
|
||||
assertEquals(t.state(1, 100, 0, "axis"), AXIS.x);
|
||||
|
||||
// a crank faces away from what it's placed on, or away from an axle beside it, so it turns it
|
||||
t.send(1, { type: "select_slot", slot: 1 });
|
||||
t.use(-1, 99, 1, "top");
|
||||
assertEquals(t.state(-1, 100, 1, "facing"), FACING.up);
|
||||
t.use(2, 99, 0, "top");
|
||||
assertEquals(t.state(2, 100, 0, "facing"), FACING.east);
|
||||
});
|
||||
|
||||
// create's client script with only what its visuals need, and a block for one to draw that records how its instances
|
||||
// turn, by model: "own" for the block's own model
|
||||
async function visual_for(id: string, states: Record<string, number>, data: Record<string, unknown>) {
|
||||
await test_game("mods");
|
||||
const visuals = new Map<string, (block: VisualBlock, instances: Instances) => Visual>();
|
||||
setup_client({
|
||||
blocks: {
|
||||
components: (id: string) =>
|
||||
structuredClone(EverythingRegistry.get<BlockRegistry>("blocks", id)!.components),
|
||||
},
|
||||
render: { register_visual: (id: string, create: never) => visuals.set(id, create) },
|
||||
} as unknown as ClientContext);
|
||||
const turns = new Map<string, [string, number, number]>();
|
||||
const rotating = (model?: ModelRef) => ({
|
||||
set_rotation: (axis: string, rpm: number, offset = 0) =>
|
||||
turns.set(model === undefined ? "own" : JSON.stringify(model), [axis, rpm, offset]),
|
||||
delete() {},
|
||||
});
|
||||
const block = { id, x: 0, y: 100, z: 0, states, get_client_data: (field: string) => data[field] as never };
|
||||
const visual = visuals.get(id)!(block, { rotating, transformed: () => ({}) } as unknown as Instances);
|
||||
return { visual, turns, data };
|
||||
}
|
||||
|
||||
Deno.test("a shaft is drawn turning around its axis at the speed its client data says", async () => {
|
||||
const { visual, turns, data } = await visual_for("create:shaft", { axis: AXIS.z }, { speed: 16 });
|
||||
// its own model, the way its states draw it
|
||||
assertEquals(turns.get("own")!.slice(0, 2), ["z", 16]);
|
||||
data.speed = -64;
|
||||
visual.update!();
|
||||
assertEquals(turns.get("own")!.slice(0, 2), ["z", -64]);
|
||||
});
|
||||
|
||||
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]);
|
||||
const handle = () => [...turns].find(([model]) => model.includes("handle"))![1];
|
||||
// degrees it turned by in a tick, after time ticks
|
||||
let time = 0;
|
||||
const step = () => {
|
||||
const before = handle()[2];
|
||||
visual.on_frame!(++time);
|
||||
return ((handle()[2] - before) % 360 + 540) % 360 - 180;
|
||||
};
|
||||
visual.on_frame!(time);
|
||||
const first = step();
|
||||
for (let i = 0; i < 40; i++) step();
|
||||
// it turns the same way as the shaft, around x, faster once it's caught up
|
||||
assertEquals(handle()[0], "x");
|
||||
assert(first < 0 && step() < first, `${first}`);
|
||||
|
||||
data.speed = undefined;
|
||||
visual.update!();
|
||||
const slowing = step();
|
||||
assert(slowing < 0, `${slowing}`);
|
||||
for (let i = 0; i < 100; i++) step();
|
||||
assert(Math.abs(step()) < 0.01);
|
||||
});
|
||||
@@ -294,6 +294,28 @@ Deno.test("a blockstate's variants become numbered states, each drawn with its m
|
||||
assertEquals(block.drops, "gears:shaft");
|
||||
});
|
||||
|
||||
Deno.test("a block table gives blocks what java sets in code, over the placeholders", () => {
|
||||
const files = {
|
||||
"blockstates/crank": { variants: { "": { model: "gears:block/crank" } } },
|
||||
"models/block/crank": GEAR,
|
||||
};
|
||||
const output = Deno.makeTempDirSync();
|
||||
const components = { "gears:turns": { speed: 32 } };
|
||||
const report = import_blocks(assets(files), {
|
||||
output,
|
||||
blocks: { "gears:crank": { components, mining: { toughness: 2 } } },
|
||||
});
|
||||
assertEquals(report.errors, []);
|
||||
const { block } = JSON.parse(Deno.readTextFileSync(`${output}/crank.json`));
|
||||
assertEquals(validate_block(block), []);
|
||||
assertEquals(block.components, components);
|
||||
assertEquals(block.mining, { toughness: 2 });
|
||||
|
||||
// a block the table names that wasn't made is an error, so a typo can't go unnoticed
|
||||
const typo = import_blocks(assets(files), { output, blocks: { "gears:cranck": { components } } });
|
||||
assertEquals(typo.errors.map(({ location }) => location), ["gears:cranck"]);
|
||||
});
|
||||
|
||||
Deno.test("uvlock carries over, so turned textures stay where they are on an unturned block", () => {
|
||||
const { block, report } = import_block({
|
||||
"blockstates/steps": {
|
||||
|
||||
@@ -77,6 +77,10 @@ function client_of(t: Game) {
|
||||
mod: { id: "bworld", version: "test" },
|
||||
side: "client",
|
||||
tags: tag_api(),
|
||||
blocks: {
|
||||
exists: (id) => info(id) !== undefined,
|
||||
components: (id) => structuredClone(info(id)!.components ?? {}),
|
||||
},
|
||||
world,
|
||||
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
|
||||
});
|
||||
@@ -84,7 +88,7 @@ function client_of(t: Game) {
|
||||
return {
|
||||
// what game_mode does when this client places held against face of x y z, at hit
|
||||
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
|
||||
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit, sneaking: false });
|
||||
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false });
|
||||
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
|
||||
rules.notify_neighbors(world.get_block, x, y, z);
|
||||
},
|
||||
|
||||
+5
-2
@@ -46,7 +46,9 @@ options:
|
||||
{ "textures": { "minecraft:block/": "bworld:" }, "models": {}, "ids": {}, "tags": {},
|
||||
"skip": ["crimson"] }
|
||||
minecraft's block and item textures, blocks, items and tags become bworld's of the same name,
|
||||
and forge's shared tags c's, unless it says otherwise`;
|
||||
and forge's shared tags c's, unless it says otherwise
|
||||
--blocks FILE json of fields blocks get by id, over the placeholders, for blockstate. what java sets in
|
||||
code, like components and mining: { "gears:shaft": { "components": {...} } }`;
|
||||
|
||||
function parse_args(args: string[]) {
|
||||
const positional: string[] = [];
|
||||
@@ -70,7 +72,8 @@ function parse_args(args: string[]) {
|
||||
tags: { ...DEFAULT_REMAPS.tags, ...remap.tags },
|
||||
...(remap.skip ? { skip: remap.skip } : {}),
|
||||
};
|
||||
} else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
|
||||
} else if (arg === "--blocks") options.blocks = JSON.parse(Deno.readTextFileSync(value()));
|
||||
else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
|
||||
else positional.push(arg);
|
||||
}
|
||||
return { positional, options };
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// java blockstates (assets/<namespace>/blockstates/*.json) to bworld's blocks/, so a mod's blocks can be placed and look
|
||||
// right: their states, and the model each state is drawn with, turned. how a block behaves isn't in any data file (java
|
||||
// mods set mining, sounds and what blocks do in code), so every block gets the same placeholders: a second to break with
|
||||
// anything, dropping itself
|
||||
// anything, dropping itself. --blocks gives some of them more, see ImportOptions.blocks
|
||||
import { dirname, join } from "@std/path";
|
||||
import { FORMAT_VERSION } from "$/common/mod_data.ts";
|
||||
import { is_empty, made_by, model_source, type ModelSource } from "./models.ts";
|
||||
@@ -95,11 +95,19 @@ export function import_blocks(input: string, options: ImportOptions = {}): Impor
|
||||
const result = convert_blockstate(location, json, read, remaps);
|
||||
if (result.kind === "error") report.errors.push({ location, problems: result.problems });
|
||||
else if (claim(result.id, location)) {
|
||||
Object.assign(result.json.block, options.blocks?.[result.id]);
|
||||
for (const warning of result.warnings) report.warnings.push({ location, warning });
|
||||
const text = format_json(result.json) + "\n";
|
||||
report.written.push({ location, id: result.id, file: join(options.output, `${where.path}.json`), text });
|
||||
}
|
||||
}
|
||||
// a typo in the table would otherwise quietly give a block nothing
|
||||
const written = new Set(report.written.map(({ id }) => id));
|
||||
for (const id of Object.keys(options.blocks ?? {})) {
|
||||
if (!written.has(id)) {
|
||||
report.errors.push({ location: id, problems: ["--blocks has it, but no block was made for it"] });
|
||||
}
|
||||
}
|
||||
write_report(report);
|
||||
return report;
|
||||
}
|
||||
|
||||
@@ -253,6 +253,9 @@ export interface ImportOptions {
|
||||
// more folders to look things up in, like parent models from another mod
|
||||
parents?: string[];
|
||||
remaps?: Remaps;
|
||||
// fields blocks get by id, over the placeholders, like their components or how long they take to mine. java sets
|
||||
// those in code, so a mod's import keeps them in a table, like mods/create/import/blocks.json
|
||||
blocks?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
// one file an import makes: text to write, or a file to copy
|
||||
|
||||
Reference in New Issue
Block a user