This commit is contained in:
2026-10-28 22:26:42 -03:00
parent b8cccb86ff
commit 5d64b801a3
14 changed files with 480 additions and 12 deletions
+14 -2
View File
@@ -7,8 +7,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, cogwheels, gearboxes,
encased shafts and cogs, clutches, gearshifts and chain drives turned by a 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.
with stress and overstress), Create's pressing recipes, the mechanical press pressing items on the ground, and the basin
holding items and fluids. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts
about bworld from its source.
## Sources
@@ -603,6 +604,17 @@ rate as `press` client data whenever the rate changes, and the visual moves the
while it runs at a steady speed. Pressing on belts, depots and basins, its stress impact, sound and particles come with
those.
The basin (`scripts/processing/basin.ts`) holds what Create's input inventory and tanks do: up to 9 kinds of item, a
stack of each, and 2 tanks of 1000 mB, a fluid each. An item that lands in it goes in through the engine's
`on_entity_stand`, like `updateEntityAfterFallOn`, so it doesn't tick. A full fluid container used on it empties into
it, an empty one fills from its first tank, and an empty hand takes every item out, like `BasinBlock.useItemOn`. What's
in it is only its `items` and `tanks` client data, and its visual draws them like `BasinRenderer`: the fluids side by
side, filling faster at first, and the items in a ring over them, bobbing while there's fluid. Water and lava buckets
aren't fluid containers in bworld, so they don't fill it yet. Its output inventory and tanks, its facing toward an
output, and the item and fluid capabilities (S1, S2) come with mixing and the logistics that move things in and out. For
it the engine got `on_entity_stand`, and an item inside a block only floats out of it when it's inside what it bumps
into, like Minecraft's `noCollision`, so items can lie in a hollow.
### P4: Logistics
- R3's `scrolling` type.
+3
View File
@@ -97,6 +97,9 @@ export interface BlockComponent<P = any> {
on_state_change?(block: BlockRef, params: P, before: Readonly<Record<string, number>>): void;
// the tick ServerWorld.schedule_tick asked for came, like neoforge's tick from scheduleTick
on_scheduled_tick?(block: BlockRef, params: P): void;
// an entity is standing on it, every tick the entity moves, like minecraft's updateEntityAfterFallOn: an item
// dropped into a basin going in. items lying still move every tick too
on_entity_stand?(block: BlockRef, params: P, entity: EntityRef): void;
// placing and neighbor rules are in shared scripts, see BlockRules in bworld/shared
}
+18
View File
@@ -72,12 +72,30 @@ component.
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. See [Changes](#changes). | |
| `on_state_change(block, params, before)` | Its own states change without it being replaced, by `set_state` or a rule. See [Changes](#changes). | |
| `on_scheduled_tick(block, params)` | A tick it asked for comes. See [Scheduled Ticks](#scheduled-ticks). | |
| `on_entity_stand(block, params, entity)` | An entity standing on it moves, every tick it does. See [Entities on It](#entities-on-it). | |
`block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the
block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome`
and `season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)) and `set_ticking` turns its
[ticking](#ticking) off and on. `params` is what the block's JSON lists for this component, and `dt` is in seconds.
### Entities on It
`on_entity_stand` runs every tick an entity moves while it stands on the block, like Minecraft's
`updateEntityAfterFallOn`, with an [`EntityRef`](../entities/index.md) to it. Items lying still move every tick too, so
it runs for them while they lie there. The block is the one under the entity's feet, or the one its feet are in when
that one's floor is lower than a whole block, like a basin's. Create's basin takes in the items dropped into it this
way, without ticking or looking for them:
```ts
ctx.components.register_block("create:basin", {
on_entity_stand(block, _params, entity) {
const item = entity.get_item();
if (item) entity.set_item(insert(block, item));
},
});
```
### Changes
`on_neighbor_change` is the server's side of the [rule](#neighbors) with the same name, like NeoForge's
+12 -2
View File
@@ -12,11 +12,21 @@
"facing=3": { "model": "create:block_basin_block_directional", "y": 90 }
},
"states": [
{ "name": "facing", "bits": 3, "default": 0 }
{ "name": "facing", "bits": 3, "default": 4 }
],
"render_layer": "cutout",
"shape": [
[2, 0, 2, 14, 2, 14],
[0, 2, 0, 16, 16, 2],
[0, 2, 14, 16, 16, 16],
[0, 2, 2, 2, 16, 14],
[14, 2, 2, 16, 16, 14]
],
"mining": { "toughness": 1 },
"drops": "create:basin",
"item_model": "create:item_basin"
"item_model": "create:item_basin",
"components": {
"create:basin": {}
}
}
}
+94 -2
View File
@@ -3,8 +3,18 @@
// 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. they're still while their network is
// overstressed
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "bworld/client";
// overstressed. and what's in a basin
import { mat4 } from "gl-matrix";
import type {
ClientContext,
Instance,
Instances,
ItemStack,
ModelRef,
TransformedInstance,
Visual,
VisualBlock,
} from "bworld/client";
import type { Face } from "bworld/shared";
import {
actual_speed,
@@ -18,6 +28,7 @@ import {
OPPOSITE,
} from "./kinetics/connections.ts";
import { head_offset, type PressShown } from "./processing/press.ts";
import { BASIN_TANK_CAPACITY, BASIN_TANKS, type BasinTank } from "./processing/basin.ts";
// a model reaching north turned to reach each way
const facing_turns = (model: string): Record<Face, ModelRef> => ({
@@ -167,6 +178,8 @@ export function setup(ctx: ClientContext) {
};
});
ctx.render.register_visual("create:basin", basin_visual);
// 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) => {
@@ -214,3 +227,82 @@ 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;
}
// a basin's items are a copy more for every this many
const BASIN_ITEMS_A_COPY = 8;
// what's in a basin, by its "tanks" and "items" client data (see register_basin in server.ts), like BasinRenderer. its
// fluids fill the 12 pixels inside its walls side by side, as wide as their share of it, and as high as all of them
// make it, filling faster at first. its items lie in a ring over the fluid, tipped over and turned toward the middle,
// one in the middle when it's alone, and bob up and down while there's fluid
function basin_visual(block: VisualBlock, instances: Instances): Visual {
let shown: Instance[] = [];
// each copy of an item, placed in the basin but for how high it bobs, and where in its bobbing it is
let floating: { instance: TransformedInstance; placed: mat4; phase: number }[] = [];
const update = () => {
for (const instance of shown) instance.delete();
shown = [];
floating = [];
const tanks = block.get_client_data<BasinTank[]>("tanks") ?? [];
const total = tanks.reduce((sum, tank) => sum + tank.amount, 0);
const full = 1 - (1 - Math.min(1, total / (BASIN_TANKS * BASIN_TANK_CAPACITY))) ** 2;
const top = total > 0 ? 2 + 12 * full : 0;
let x = 2;
for (const tank of tanks) {
const width = 12 * tank.amount / total;
const fluid = instances.fluid(tank.fluid);
fluid.set_box([x, 2, 2], [x + width, top, 14]);
shown.push(fluid);
x += width;
}
const items = block.get_client_data<ItemStack[]>("items") ?? [];
const level = Math.min(0.6, Math.max(0.125, top / 16 - 0.3));
const radius = items.length === 1 ? 0 : 0.125;
const random = seeded(block.x * 961 + block.y * 31 + block.z);
items.forEach((stack, i) => {
const angle = 360 / items.length * (items.length - i) * Math.PI / 180;
for (let copy = 0; copy <= Math.floor(stack.count / BASIN_ITEMS_A_COPY); copy++) {
const placed = mat4.fromTranslation(mat4.create(), [
radius * Math.cos(angle),
level,
-radius * Math.sin(angle),
]);
mat4.rotateY(placed, placed, angle + 35 * Math.PI / 180);
mat4.rotateX(placed, placed, 65 * Math.PI / 180);
const jitter = () => (random() - 0.5) / 8;
mat4.translate(placed, placed, [jitter() - 0.5, jitter() - 0.5, jitter() - 0.5]);
const instance = instances.item(stack);
shown.push(instance);
floating.push({ instance, placed, phase: angle * 180 / Math.PI });
place(instance, placed, 0);
}
});
if (top === 0) floating = [];
};
update();
return {
update,
on_frame(time) {
for (const { instance, placed, phase } of floating) {
place(instance, placed, (Math.sin(time / 12 + phase) + 1.5) / 32);
}
},
};
}
// an item copy in a basin, bob higher than where it was placed
function place(instance: TransformedInstance, placed: mat4, bob: number) {
const matrix = mat4.fromTranslation(mat4.create(), [0.5, 0.2 + bob, 0.5]);
instance.set_transform(mat4.multiply(matrix, matrix, placed));
}
// the same numbers from 0 to 1 every time for the same seed, so a basin's items lie the same way however often they're
// drawn again
function seeded(seed: number) {
let state = seed >>> 0;
return () => {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
return state / 2 ** 32;
};
}
+68
View File
@@ -0,0 +1,68 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what a basin holds, like create's BasinBlockEntity's input inventory and tanks: up to BASIN_SLOTS kinds of item, a
// stack of each, and BASIN_TANKS tanks with a fluid each. a kind of item or fluid only ever goes where there's already
// some of it, so there's never two stacks or two tanks of one. no ctx, so the server keeps it and the client draws it
// from the same shapes
import type { FluidVariant, ItemStack } from "bworld/shared";
export const BASIN_SLOTS = 9;
export const BASIN_TANKS = 2;
export const BASIN_TANK_CAPACITY = 1000;
export interface BasinTank {
fluid: FluidVariant;
amount: number;
}
// how many of stack go into items, and what items is after: into the stack of the same item, or a new one while
// there's room for another kind, up to max a stack. like BasinInventory.insertItem
export function insert_item(items: readonly ItemStack[], stack: ItemStack, max: number) {
const index = items.findIndex((item) => same_item(item, stack));
if (index === -1 && items.length >= BASIN_SLOTS) return { items, inserted: 0 };
const had = index === -1 ? 0 : items[index].count;
const inserted = Math.max(0, Math.min(stack.count, max - had));
if (inserted === 0) return { items, inserted };
const into = { ...stack, count: had + inserted };
return { items: index === -1 ? [...items, into] : items.with(index, into), inserted };
}
// tanks with amount of fluid poured in, or undefined when it doesn't all fit: into the tank that has that fluid, or else
// an empty one, like SmartFluidTankBehaviour's tanks that each keep to one fluid
export function fill(
tanks: readonly BasinTank[],
fluid: FluidVariant,
amount: number,
same: (a: FluidVariant, b: FluidVariant) => boolean,
): BasinTank[] | undefined {
const index = tanks.findIndex((tank) => same(tank.fluid, fluid));
if (index === -1) {
return tanks.length < BASIN_TANKS && amount <= BASIN_TANK_CAPACITY ? [...tanks, { fluid, amount }] : undefined;
}
const total = tanks[index].amount + amount;
return total <= BASIN_TANK_CAPACITY ? tanks.with(index, { fluid, amount: total }) : undefined;
}
// amount of the first tank's fluid taken out, and the tanks left, or undefined when it has less than that. like
// filling an item from CombinedTankWrapper, which drains the first tank with any
export function drain(tanks: readonly BasinTank[], amount: number) {
const [first, ...rest] = tanks;
if (!first || first.amount < amount) return undefined;
const left = first.amount - amount;
return { fluid: first.fluid, tanks: left > 0 ? [{ ...first, amount: left }, ...rest] : rest };
}
// whether two stacks are of one item: the same id, and the same data whatever order its keys are in
export function same_item(a: ItemStack, b: ItemStack): boolean {
return a.id === b.id && canonical(a.data) === canonical(b.data);
}
function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
if (value && typeof value === "object") {
const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1);
return `{${entries.map(([key, v]) => `${JSON.stringify(key)}:${canonical(v)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "";
}
+58 -2
View File
@@ -2,8 +2,8 @@
// 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), and the mechanical press
import type { BlockRef, EntityRef, Id, ServerContext } from "bworld/server";
// the creative motor and the water wheel), the mechanical press and the basin
import type { BlockRef, EntityRef, FluidVariant, Id, ItemStack, ServerContext } from "bworld/server";
import {
actual_speed,
along,
@@ -27,6 +27,7 @@ import {
roll_results,
} from "./recipes/processing.ts";
import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts";
import { type BasinTank, drain, fill, insert_item } from "./processing/basin.ts";
interface Config {
max_speed: number;
@@ -194,6 +195,61 @@ export function setup(ctx: ServerContext) {
});
register_press(ctx, pressing);
register_basin(ctx);
}
// holds items dropped into it and fluid poured in, like create's BasinBlock: an item that lands in it goes in, a full
// fluid container used on it empties into it and an empty one fills from it, and an empty hand takes every item out.
// 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) => block.get_client_data<ItemStack[]>("items") ?? [];
const tanks_of = (block: BlockRef) => block.get_client_data<BasinTank[]>("tanks") ?? [];
const set_items = (block: BlockRef, items: readonly ItemStack[]) =>
block.set_client_data("items", items.length > 0 ? items : undefined);
const set_tanks = (block: BlockRef, tanks: BasinTank[]) =>
block.set_client_data("tanks", tanks.length > 0 ? tanks : undefined);
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) {
for (const item of items_of(block)) player.give_item(item.id, item.count, item.data);
set_items(block, []);
return true;
}
const capacity = ctx.items.fluid_capacity(held.id);
// anything else is used or placed as if the basin weren't there
if (capacity === undefined) return false;
const fluid = (held.data as { fluid?: FluidVariant } | undefined)?.fluid;
if (fluid) {
const tanks = fill(tanks_of(block), fluid, capacity, (a, b) => ctx.fluids.same(a, b));
if (tanks) {
set_tanks(block, tanks);
player.exchange_held({ id: held.id, count: 1 });
}
} else {
const drained = drain(tanks_of(block), capacity);
if (drained) {
set_tanks(block, drained.tanks);
player.exchange_held({ id: held.id, count: 1, data: { fluid: drained.fluid } });
}
}
// a fluid container is used up on the basin even when nothing fits, like create's
return true;
},
on_break(block) {
for (const item of items_of(block)) ctx.world.drop_item(block.x, block.y, block.z, item);
},
});
}
// presses items lying on the ground under it while it turns, like create's MechanicalPressBlockEntity pressing in the
+9
View File
@@ -24,6 +24,8 @@ export const MAX_AIR = 300;
const MAX_LOADED_SPEED = 10 * TICKS_PER_SECOND;
// like minecraft
export const MAX_TAGS = 1024;
// how far under its feet the block it stands on is looked for, so standing on top of a block finds that one
const STANDING_DEPTH = 1 / 1024;
// something that can hurt an entity: another entity, or a player
export interface Attacker {
@@ -94,6 +96,8 @@ export interface EntityLevel {
on_death(entity: Entity, source: DamageSource): void;
// what it drops when it dies, from its type's loot table
entity_loot(entity: Entity, source: DamageSource): ItemStack[];
// it's standing on the block at x y z after moving, for the block's components, see on_entity_stand
stands_on(entity: Entity, x: number, y: number, z: number): void;
}
// an entity as level.json keeps it, see Entity.save. each kind adds its own fields
@@ -293,6 +297,11 @@ export abstract class Entity {
);
this.on_ground = collisions.y === 1;
this.horizontal_collision = collisions.x !== 0 || collisions.z !== 0;
// the block its feet are on, which can be the one they're in when it's lower than a whole block, like a basin's
// floor
if (this.on_ground) {
this.level.stands_on(this, Math.floor(this.x), Math.floor(this.y - STANDING_DEPTH), Math.floor(this.z));
}
this.update_fall_distance(this.y - from_y);
return collisions;
}
+6
View File
@@ -26,6 +26,8 @@ export interface EntityHost {
on_entity_death?(entity: Entity, source: DamageSource): void;
// what it drops when it dies, from its loot table
entity_loot?(entity: Entity, source: DamageSource): ItemStack[];
// see EntityLevel.stands_on
stands_on?(entity: Entity, x: number, y: number, z: number): void;
}
// what a client was last told about an entity, so only changes get sent
@@ -172,6 +174,10 @@ export class EntityManager implements EntityLevel {
return this.#host.entity_loot?.(entity, source) ?? [];
}
stands_on(entity: Entity, x: number, y: number, z: number) {
this.#host.stands_on?.(entity, x, y, z);
}
// ticking
// every entity active says should move, with their passengers. entities removed along the way are forgotten
+3 -2
View File
@@ -80,9 +80,10 @@ export class ItemEntity extends Entity {
this.pickup_delay -= 1;
}
// covered by a block placed on it, float out the top instead of being stuck inside
// covered by a block placed on it, float out the top instead of being stuck inside. only inside what it bumps
// into, like minecraft's noCollision, so it can lie in a block with a hollow, like a basin
const level = this.level;
if (level.has_collision(Math.floor(this.x), Math.floor(this.y + this.height / 2), Math.floor(this.z))) {
if (!physics.box_is_free(this, 0, 0, 0, (x, y, z) => level.collision_shape(x, y, z))) {
this.vy = UNSTICK_SPEED;
}
+14
View File
@@ -246,6 +246,20 @@ export class GameServer {
on_entity_death: (entity, source) => {
if (entity instanceof ServerPlayer) this.#kill(entity, source);
},
stands_on: (entity, x, y, z) => {
const id = this.world.get_block_id(x, y, z);
const components = this.mods.components_with(id, "on_entity_stand");
if (components.length === 0) return;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
if (entity.removed) return;
run_guarded(
mod,
`${component_id} on_entity_stand`,
() => component.on_entity_stand!(block, params, entity_ref(entity)),
);
}
},
entity_loot: (entity, source) => {
const table = EverythingRegistry.get<EntityJson>("entities", entity.type)?.loot_table;
if (!table) return [];
+144
View File
@@ -0,0 +1,144 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's basin: items dropped into it go in, a kind to a stack, fluid containers empty into it and fill from it, and
// an empty hand takes the items out
import { assert, assertEquals } from "@std/assert";
import { ItemStack } from "$/common/inventory.ts";
import type { ItemStack as Stack } from "bworld/shared";
import {
BASIN_SLOTS,
BASIN_TANK_CAPACITY,
BASIN_TANKS,
type BasinTank,
drain,
fill,
insert_item,
} from "$/mods/create/scripts/processing/basin.ts";
import { setup, visual_for } from "./helpers.ts";
const juice = (item: string) => ({ id: "bworld:juice", data: { item } });
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
Deno.test("a basin keeps one stack of each kind of item, and only so many kinds", () => {
let { items } = insert_item([], { id: "a:iron", count: 40 }, 64);
({ items } = insert_item(items, { id: "a:gold", count: 1 }, 64));
const more = insert_item(items, { id: "a:iron", count: 40 }, 64);
assertEquals(more.inserted, 24);
assertEquals(more.items.map((item) => [item.id, item.count]), [["a:iron", 64], ["a:gold", 1]]);
// a full stack doesn't spill into another
assertEquals(insert_item(more.items, { id: "a:iron", count: 1 }, 64).inserted, 0);
// stacks with other data are other kinds, whatever order their data's keys are in
const marked = insert_item([], { id: "a:map", count: 1, data: { x: 1, y: 2 } }, 64).items;
assertEquals(insert_item(marked, { id: "a:map", count: 1, data: { y: 2, x: 1 } }, 64).items.length, 1);
assertEquals(insert_item(marked, { id: "a:map", count: 1, data: { x: 2, y: 2 } }, 64).items.length, 2);
const kinds = Array.from({ length: BASIN_SLOTS }, (_, i) => ({ id: `a:item_${i}`, count: 1 }));
let full: readonly Stack[] = [];
for (const stack of kinds) full = insert_item(full, stack, 64).items;
assertEquals(insert_item(full, { id: "a:another", count: 1 }, 64).inserted, 0);
});
Deno.test("a basin keeps each fluid in a tank of its own, and drains the first", () => {
const half = BASIN_TANK_CAPACITY / 2;
let tanks: BasinTank[] = fill([], juice("apple"), half, same)!;
tanks = fill(tanks, juice("apple"), half, same)!;
assertEquals(tanks, [{ fluid: juice("apple"), amount: BASIN_TANK_CAPACITY }]);
// it doesn't overflow into another tank
assertEquals(fill(tanks, juice("apple"), 1, same), undefined);
for (let i = 1; i < BASIN_TANKS; i++) tanks = fill(tanks, juice(`fruit_${i}`), half, same)!;
assertEquals(tanks.length, BASIN_TANKS);
assertEquals(fill(tanks, juice("another"), 1, same), undefined);
assertEquals(drain(tanks, BASIN_TANK_CAPACITY + 1), undefined);
const drained = drain(tanks, BASIN_TANK_CAPACITY)!;
assertEquals(drained.fluid, juice("apple"));
assertEquals(drained.tanks.length, BASIN_TANKS - 1);
});
// a basin at 0 100 0, and what's in it
async function basin() {
const t = await setup();
t.place(0, 100, 0, "create:basin");
const items = () =>
(t.game.world.get_tile(0, 100, 0)?.client_data?.items as { id: string; count: number }[] | undefined ?? [])
.map(({ id, count }) => [id, count]);
const tanks = () => t.game.world.get_tile(0, 100, 0)?.client_data?.tanks as BasinTank[] | undefined ?? [];
const player = t.game.mods.player(t.game.players()[0]);
const hold = (item: { id: string; count: number; data?: unknown } | undefined) => {
player.inventory.set(0, item);
t.send(1, { type: "select_slot", slot: 0 });
};
return { ...t, items, tanks, player, hold };
}
Deno.test("items dropped into a basin go in, and an empty hand takes them out", async () => {
const t = await basin();
t.game.spawn_item(0.5, 101.5, 0.5, new ItemStack("bworld:iron_ingot", 3));
t.game.spawn_item(0.5, 102.5, 0.5, new ItemStack("bworld:gold_ingot", 1));
t.ticks(40);
assertEquals(t.items(), [["bworld:iron_ingot", 3], ["bworld:gold_ingot", 1]]);
assertEquals(t.game.item_entities().length, 0);
t.hold(undefined);
t.use(0, 100, 0, "top");
assertEquals(t.items(), []);
const held = [0, 1, 2, 3, 4, 5, 6, 7, 8].map((slot) => t.player.inventory.get(slot)).filter((item) => item);
assertEquals(held.map((item) => [item!.id, item!.count]).sort(), [["bworld:gold_ingot", 1], [
"bworld:iron_ingot",
3,
]]);
});
Deno.test("a full fluid container empties into a basin, and an empty one fills from it", async () => {
const t = await basin();
t.hold({ id: "bworld:bucket", count: 1, data: { fluid: juice("bworld:apple") } });
t.use(0, 100, 0, "top");
assertEquals(t.tanks(), [{ fluid: juice("bworld:apple"), amount: 1000 }]);
assertEquals(t.player.held_item?.data, undefined);
// another bucket of it doesn't fit, so it stays full
t.hold({ id: "bworld:bucket", count: 1, data: { fluid: juice("bworld:apple") } });
t.use(0, 100, 0, "top");
assertEquals(t.tanks().length, 1);
assert(t.player.held_item?.data !== undefined);
t.hold({ id: "bworld:bucket", count: 1 });
t.use(0, 100, 0, "top");
assertEquals(t.tanks(), []);
assertEquals(t.player.held_item?.data, { fluid: juice("bworld:apple") });
});
Deno.test("a broken basin drops its items", async () => {
const t = await basin();
t.game.spawn_item(0.5, 101.5, 0.5, new ItemStack("bworld:iron_ingot", 3));
t.ticks(40);
t.game.destroy_block(0, 100, 0);
const dropped = t.game.item_entities().map((e) => [e.item.type_id, e.item.amount]).sort();
assertEquals(dropped, [["bworld:iron_ingot", 3], ["create:basin", 1]]);
});
Deno.test("a basin is drawn with its fluids side by side and a copy of each item for every few", async () => {
const { visual, items, fluids, data } = await visual_for("create:basin", { facing: 4 }, {
tanks: [{ fluid: juice("a"), amount: 500 }, { fluid: juice("b"), amount: 1500 }],
items: [{ id: "bworld:iron_ingot", count: 1 }, { id: "bworld:gold_ingot", count: 20 }],
});
// the second tank is three times as wide, and they reach as high as each other
const [first, second] = [...fluids].map(({ box }) => box!);
assertEquals(second[1][0] - second[0][0], 3 * (first[1][0] - first[0][0]));
assertEquals(first[1][1], second[1][1]);
assertEquals(first[1][0], second[0][0]);
// more copies of the bigger stack
const copies = (id: string) => [...items].filter((item) => item.id === id).length;
assert(copies("bworld:gold_ingot") > copies("bworld:iron_ingot"));
// bobbing on the fluid, the items move from frame to frame
const before = [...items].map((item) => item.transform);
visual.on_frame!(10);
assert([...items].some((item, i) => JSON.stringify(item.transform) !== JSON.stringify(before[i])));
data.tanks = undefined;
data.items = undefined;
visual.update!();
assertEquals([items.size, fluids.size], [0, 0]);
});
+21 -2
View File
@@ -50,7 +50,8 @@ export async function setup(config: Record<string, unknown> = {}) {
}
// create's client script with only what its visuals need, and a block for one to draw that records what its instances
// do, by model ("own" for the block's own model): how rotating ones turn, and where transformed ones are moved
// do, by model ("own" for the block's own model): how rotating ones turn, and where transformed ones are moved. and the
// items and fluid boxes it draws now, by item and fluid id
export async function visual_for(
id: string,
states: Record<string, number>,
@@ -69,6 +70,8 @@ export async function visual_for(
const key = (model?: ModelRef) => model === undefined ? "own" : JSON.stringify(model);
const turns = new Map<string, [string, number, number]>();
const transforms = new Map<string, number[]>();
const items = new Set<{ id: string; transform?: number[] }>();
const fluids = new Set<{ id: string; box?: [number[], number[]] }>();
const instances = {
rotating: (model?: ModelRef) => ({
set_rotation: (axis: string, rpm: number, offset = 0) => turns.set(key(model), [axis, rpm, offset]),
@@ -78,8 +81,24 @@ export async function visual_for(
set_transform: (matrix: ArrayLike<number>) => transforms.set(key(model), Array.from(matrix)),
delete() {},
}),
item: (stack: { id: string }) => {
const item: { id: string; transform?: number[] } = { id: stack.id };
items.add(item);
return {
set_transform: (matrix: ArrayLike<number>) => item.transform = Array.from(matrix),
delete: () => items.delete(item),
};
},
fluid: (fluid: { id: string }) => {
const box: { id: string; box?: [number[], number[]] } = { id: fluid.id };
fluids.add(box);
return {
set_box: (from: number[], to: number[]) => box.box = [from, to],
delete: () => fluids.delete(box),
};
},
} as unknown as Instances;
const block = { id, x, y, z, states, get_client_data: (field: string) => structuredClone(data[field]) as never };
const visual = visuals.get(id)!(block, instances);
return { visual, turns, transforms, data };
return { visual, turns, transforms, items, fluids, data };
}
+16
View File
@@ -148,3 +148,19 @@ Deno.test("items fall into water, float back up and bob at its surface", async (
assert(Math.min(...heights) > 102.4, `down to ${Math.min(...heights)}`);
assertEquals([item.x, item.z], [6.5, 0.5]);
});
Deno.test("an item inside a block floats out of it, but not out of a hollow in one", async () => {
const { game, join } = await test_game("mods");
// things only move near players
join(1, "alice");
build_floor(game);
game.set_block(0, 100, 0, "bworld:stone");
game.set_block(2, 100, 0, "bworld:juicer");
const buried = game.spawn_item(0.5, 100.3, 0.5, new ItemStack("bworld:dirt", 1));
// between its posts and under its press, above its floor
const kept = game.spawn_item(2.5, 100.2, 0.5, new ItemStack("bworld:dirt", 1));
for (let i = 0; i < 40; i++) game.tick();
assert(buried.y >= 101, `${buried.y}`);
assert(kept.on_ground);
assertEquals(kept.y, 100 + 2 / 16);
});