diff --git a/MODS.md b/MODS.md index 72b8543..106651e 100644 --- a/MODS.md +++ b/MODS.md @@ -66,7 +66,8 @@ deno task build && deno task server # packs the mods and starts a se - [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types - [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to - [Loot Tables](docs/modding/resources/loot_tables.md): what blocks, mobs, fishing and chests give -- [Fluids](docs/modding/resources/fluids.md): fluids that can be held, apart from blocks that flow +- [Fluids](docs/modding/resources/fluids.md): fluids that can be held, apart from blocks that flow, and the fluid + handlers that tanks and containers are filled and drained through **Everything else** diff --git a/common/fluids.ts b/common/fluids.ts index 6209d2e..91808c2 100644 --- a/common/fluids.ts +++ b/common/fluids.ts @@ -51,7 +51,7 @@ export class FluidRules { exists: (id) => EverythingRegistry.get("fluids", id) !== undefined, name: (fluid) => this.name(fluid), color: (fluid) => this.color(fluid), - same: (a, b) => a.id === b.id && same_data(a.data, b.data), + same: same_fluid, }; } @@ -68,6 +68,11 @@ export class FluidRules { } } +// whether they're one fluid, see FluidApi.same +export function same_fluid(a: FluidVariant, b: FluidVariant): boolean { + return a.id === b.id && same_data(a.data, b.data); +} + function known_fluid(id: string): FluidJson { const json = EverythingRegistry.get("fluids", id); if (!json) throw new Error(`unknown fluid ${id}`); diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 7eef23b..8c61071 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -7,6 +7,7 @@ import type { LootTableJson } from "../loot.ts"; export type { FluidApi, + FluidStack, FluidVariant, Id, ItemStack, diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index b2e2c04..fefcc15 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -2,7 +2,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // what server scripts get, see docs/modding/ -import type { EventSignal, Face, FluidApi, Id, ItemStack, ModInfo, Position, Season, TagApi } from "./shared.ts"; +import type { + EventSignal, + Face, + FluidApi, + FluidStack, + FluidVariant, + Id, + ItemStack, + ModInfo, + Position, + Season, + TagApi, +} from "./shared.ts"; import type { ArgumentType, CommandNode } from "../commands.ts"; import type { LootTableJson } from "../loot.ts"; @@ -12,6 +24,7 @@ export type { EventSignal, Face, FluidApi, + FluidStack, FluidVariant, Id, ItemStack, @@ -37,8 +50,8 @@ export interface ServerContext { containers: ContainerApi; items: ItemApi; blocks: BlockApi; - // every fluid, named and colored by its rules, see docs/modding/resources/fluids.md - fluids: FluidApi; + // every fluid, named and colored by its rules, and fluid handlers, see docs/modding/resources/fluids.md + fluids: ServerFluidApi; recipes: RecipeApi; tags: TagApi; loot: LootApi; @@ -100,6 +113,10 @@ export interface BlockComponent

{ // 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; + // what pipes, buckets and other blocks put fluid in and take it out by, reached from face, or from no side in + // particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none + // there. see ServerFluidApi.block_handler + fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined; // placing and neighbor rules are in shared scripts, see BlockRules in bworld/shared } @@ -563,6 +580,67 @@ export interface BlockApi { solid(id: Id): boolean; } +// fluid handlers, like neoforge's IFluidHandler: tanks others can fill and drain without knowing how a block or an +// item keeps what's in them. see docs/modding/resources/fluids.md + +// whether fill and drain do it, or only say what they would, like neoforge's FluidAction +export type FluidAction = "execute" | "simulate"; + +export interface FluidHandler { + // how many tanks it has, like getTanks + tanks(): number; + // what's in a tank, undefined when it's empty, like getFluidInTank. not to be changed + fluid_in_tank(tank: number): FluidStack | undefined; + // how much a tank holds in mB, like getTankCapacity + tank_capacity(tank: number): number; + // whether a tank can hold the fluid at all, full or not, like isFluidValid + is_fluid_valid(tank: number, fluid: FluidVariant): boolean; + // puts in what of stack fits, returning how much that is, like fill + fill(stack: FluidStack, action: FluidAction): number; + // takes out up to stack's amount of its fluid, or up to a number of mB of whatever it gives first, returning what + // came out, undefined for nothing, like neoforge's two drains + drain(what: FluidStack | number, action: FluidAction): FluidStack | undefined; +} + +// a fluid container's, see ServerFluidApi.item_handler. like IFluidHandlerItem +export interface FluidHandlerItem extends FluidHandler { + // one of the container, as filling and draining left it, like getContainer + readonly container: ItemStack; +} + +// tanks kept by a script, see ServerFluidApi.tank_handler +export interface TankHandlerOptions { + // how many tanks, and how much each holds in mB + tanks: number; + capacity: number; + // what's in them, without empty ones, read every time the handler is used, so it's never out of date + get(): readonly FluidStack[]; + // what's in them after an executed fill or drain changed it, without empty ones, to be kept for get + set(tanks: FluidStack[]): void; +} + +// ctx.fluids in server scripts: FluidApi, and fluid handlers +export interface ServerFluidApi extends FluidApi { + // the handler of the block at x y z reached from face, from the first of its components with one, like + // level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there + block_handler(x: number, y: number, z: number, face?: Face): FluidHandler | undefined; + // the handler of one of a stack of fluid containers, undefined for an item that isn't one, like + // Capabilities.FluidHandler.ITEM. it holds a single fluid, full or empty, so it only fills with its whole capacity + // and drains all of it, like neoforge's FluidBucketWrapper. it changes container, not stack + item_handler(stack: ItemStack): FluidHandlerItem | undefined; + // a handler for tanks a script keeps, like neoforge's FluidTank: each holds one fluid, and there's never two of the + // same fluid. a fluid goes into the tank that has it, or else an empty one, and a number of mB drains from the + // first one + tank_handler(options: TankHandlerOptions): FluidHandler; + // pours up to max mB from one handler into the other, what the second takes of what the first gives, returning what + // moved, undefined for nothing, like FluidUtil.tryFluidTransfer + transfer(from: FluidHandler, to: FluidHandler, max: number): FluidStack | undefined; + // the fluid container the player holds filled from handler, or else emptied into it, the held one becoming what + // it's turned into, like FluidUtil.interactWithFluidHandler. returns whether any fluid moved, false when they don't + // hold a fluid container + interact(player: Player, handler: FluidHandler): boolean; +} + export interface RecipeApi { furnace_result(input: Id): { output: ItemStack; cook_time: number } | undefined; fuel_value(item: Id): number; // burn time in ticks, 0 if it isn't fuel diff --git a/common/mod_api/shared.ts b/common/mod_api/shared.ts index f8ba275..2404bc3 100644 --- a/common/mod_api/shared.ts +++ b/common/mod_api/shared.ts @@ -24,6 +24,12 @@ export interface FluidVariant { readonly data?: unknown; } +// an amount of a fluid in mB, like neoforge's FluidStack: what's in a tank, or what's poured from one into another +export interface FluidStack { + fluid: FluidVariant; + amount: number; +} + // ctx.fluids in server and client scripts: every fluid any mod defines, the same on the server and every client export interface FluidApi { // every fluid's id, in load order, like ctx.items.ids. each without data, which a fluid like juice has many of diff --git a/deno.lock b/deno.lock index d76a447..5f59a35 100644 --- a/deno.lock +++ b/deno.lock @@ -2,6 +2,7 @@ "version": "5", "specifiers": { "jsr:@gfx/canvas-wasm@~0.4.2": "0.4.2", + "jsr:@paulaboks/codecounter@*": "0.0.3", "jsr:@paulaboks/rng@^0.0.3": "0.0.3", "jsr:@std/assert@1": "1.0.14", "jsr:@std/cli@^1.0.27": "1.0.27", @@ -19,6 +20,7 @@ "jsr:@std/media-types@^1.1.0": "1.1.0", "jsr:@std/net@^1.0.6": "1.0.6", "jsr:@std/path@1": "1.1.6", + "jsr:@std/path@^1.1.2": "1.1.6", "jsr:@std/path@^1.1.4": "1.1.4", "jsr:@std/streams@^1.0.17": "1.1.2", "jsr:@zod/zod@^4.6.7": "4.6.7", @@ -33,6 +35,12 @@ "jsr:@std/encoding@1.0.5" ] }, + "@paulaboks/codecounter@0.0.3": { + "integrity": "90a094d7106d512bf4a4fca0ca2af68530e44e028d1cb3305f50a9d98a09d402", + "dependencies": [ + "jsr:@std/path@^1.1.2" + ] + }, "@paulaboks/rng@0.0.3": { "integrity": "8d2571f9f406dab2674178f4034825cc654c5a52aa7c2a176a25f8b713eee202" }, diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md index 2901579..03ae57f 100644 --- a/docs/modding/blocks/components.md +++ b/docs/modding/blocks/components.md @@ -59,20 +59,21 @@ component. ## Handlers -| Handler | Called when | Returns | -| --------------------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------- | -| `on_create(block, params)` | The block is placed or set, by a player or a script. | | -| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | | -| `on_click(block, params, player)` | A player starts hitting it. | | -| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something | -| `on_scroll(block, params, player, scroll)` | A player turns the mouse wheel looking at it. See [Scrolling](#scrolling). | | -| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | | -| `on_second(block, params, dt)` | Every second, near a player. | | -| `on_new_day(block, params, day)` | Every morning at 06:00. See [Ticking](#ticking) for where. | | -| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. See [Changes](#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). | | +| Handler | Called when | Returns | +| --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------- | +| `on_create(block, params)` | The block is placed or set, by a player or a script. | | +| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | | +| `on_click(block, params, player)` | A player starts hitting it. | | +| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something | +| `on_scroll(block, params, player, scroll)` | A player turns the mouse wheel looking at it. See [Scrolling](#scrolling). | | +| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | | +| `on_second(block, params, dt)` | Every second, near a player. | | +| `on_new_day(block, params, day)` | Every morning at 06:00. See [Ticking](#ticking) for where. | | +| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. See [Changes](#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). | | +| `fluid_handler(block, params, face?)` | Something reaches for its tanks from `face`. See [Fluid Handlers](../resources/fluids.md#fluid-handlers). | a `FluidHandler`, or `undefined` | `block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome` diff --git a/docs/modding/resources/fluids.md b/docs/modding/resources/fluids.md index 519cb73..b0efbec 100644 --- a/docs/modding/resources/fluids.md +++ b/docs/modding/resources/fluids.md @@ -40,7 +40,7 @@ animated, and any fluid can use it. Without one, the fluid is drawn with the mis A fluid with data is a `FluidVariant`, `{ id, data? }`, like Fabric's. The data is any JSON value, and tells fluids of one id apart: `copper_tools:syrup` can be maple syrup or birch syrup, `{ "id": "copper_tools:syrup", "data": { "tree": "bworld:birch_log" } }`. A variant has no amount. Whatever holds fluid -keeps the amount next to it, like a tank's `{ fluid, amount }`. +keeps the amount next to it, in a `FluidStack` `{ fluid, amount }` like NeoForge's, which is what a tank holds. Two variants are the same fluid when their ids are the same and so is their data, whatever order its keys are in. No data is the same as `{}`, so a fluid whose data was emptied is the plain fluid again. Maple and birch syrup never share @@ -146,13 +146,86 @@ how much it holds, rounded up to a whole number. A jar of maple syrup worth 40 a value when it has one. It can't be sold if neither has a value. Server scripts get this from `ctx.items.sell_value(id, data)`, which the base game's shipping bin sells by, and tooltips show it. -A server script fills one with [`player.exchange_held`](../entities/players.md#the-player-api), which turns one of the -held stack into the full one, and `ctx.items.fluid_capacity(id)` says how much it takes: +A server script fills and empties one through its [fluid handler](#fluid-handlers), and `ctx.items.fluid_capacity(id)` +says how much one holds. + +## Fluid Handlers + +A fluid handler is how fluid goes in and out of something without knowing how it keeps it, like NeoForge's +`IFluidHandler`: a machine's tanks, a fluid container, another mod's pipe. It's a list of tanks, each with a fluid and +an amount in mB, a [`FluidStack`](#fluids-with-data): ```ts -const held = player.held_item; -const capacity = held && ctx.items.fluid_capacity(held.id); -if (capacity !== undefined && !held!.data) { - player.exchange_held({ id: held!.id, count: 1, data: { fluid: { id: "copper_tools:syrup" } } }); +interface FluidHandler { + tanks(): number; + fluid_in_tank(tank: number): FluidStack | undefined; // undefined when it's empty + tank_capacity(tank: number): number; + is_fluid_valid(tank: number, fluid: FluidVariant): boolean; // whether it can ever hold it + fill(stack: FluidStack, action: FluidAction): number; // how much of stack went in + drain(what: FluidStack | number, action: FluidAction): FluidStack | undefined; // what came out } ``` + +`fill` and `drain` take an action, `"execute"` or `"simulate"`, like NeoForge's `FluidAction`. Simulating says what +would happen without changing anything, so a script can check before it moves fluid. `drain` takes a `FluidStack` for up +to that much of that fluid, or a number for up to that many mB of whatever the handler gives first. + +### Blocks + +A block has a fluid handler when one of its [components](../blocks/components.md#handlers) gives one, like registering +NeoForge's `Capabilities.FluidHandler.BLOCK`. `fluid_handler(block, params, face)` returns it, made new each time from +what the block keeps. `face` is the side it's reached from, `undefined` for no side in particular, so a block can give +different tanks to different sides, or none. Others get it with `ctx.fluids.block_handler`: + +```ts +ctx.components.register_block("copper_tools:barrel", { + fluid_handler(block, _params, face) { + if (face === "bottom") return undefined; + return ctx.fluids.tank_handler({ + tanks: 2, + capacity: 4000, + get: () => block.get_client_data("tanks") ?? [], + set: (tanks) => block.set_client_data("tanks", tanks), + }); + }, +}); + +// from somewhere else, like a pump below the barrel's side +const barrel = ctx.fluids.block_handler(x, y, z, "west"); +``` + +`ctx.fluids.tank_handler(options)` is the handler for tanks a script keeps, like NeoForge's `FluidTank`. A fluid goes +into the tank that has it, or else an empty one, so no two tanks hold the same fluid, and a number of mB drains from the +first. `get` gives what's in them, without empty ones, and `set` keeps what an executed `fill` or `drain` left. Here +it's the block's [client data](../blocks/tiledata.md#client-data), so its visual can draw it, but it can be its tile +data or anywhere else. + +A handler is a plain object, so a block that only gives fluid out, like the base game's juicer, can change one method: + +```ts +fluid_handler: (block) => ({ ...tanks(block), fill: () => 0 }), +``` + +### Items + +`ctx.fluids.item_handler(stack)` is the handler of one of a stack of [fluid containers](#containers), `undefined` for an +item that isn't one, like NeoForge's `Capabilities.FluidHandler.ITEM`. It has one tank, and like NeoForge's +`FluidBucketWrapper` it's full or empty: it only fills with its whole capacity at once, and only drains all of it. +Filling and draining change its `container`, one item as it is now, not the stack it came from. + +### Moving Fluid + +`ctx.fluids.transfer(from, to, max)` pours up to `max` mB from one handler into the other, what `to` takes of what +`from` gives, and returns what moved, `undefined` for nothing, like NeoForge's `FluidUtil.tryFluidTransfer`. + +`ctx.fluids.interact(player, handler)` is a player using the fluid container they hold on a handler, like +`FluidUtil.interactWithFluidHandler`: it fills the container from the handler, or else empties it into it, and the held +container becomes the full or empty one. It returns whether any fluid moved, and `false` when they don't hold a fluid +container. A block with tanks lets players fill and empty bottles and buckets on it from its `on_interact`: + +```ts +on_interact(block, _params, player) { + const tanks = ctx.fluids.block_handler(block.x, block.y, block.z); + return tanks !== undefined && ctx.fluids.interact(player, tanks); +}, +``` diff --git a/mods/bworld/scripts/client.ts b/mods/bworld/scripts/client.ts index 9774d01..61e6f69 100644 --- a/mods/bworld/scripts/client.ts +++ b/mods/bworld/scripts/client.ts @@ -8,6 +8,7 @@ import type { ClientContext, ClientMenu, Color, + FluidStack, Graphics, Instance, Instances, @@ -17,7 +18,7 @@ import type { VisualBlock, } from "bworld/client"; import { MINIGAMES } from "./minigames/mod.ts"; -import { JUICER_CAPACITY, JUICER_PRESSES, type JuicerTank } from "./shared.ts"; +import { JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts"; import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts"; const WIDTH = 176; @@ -65,7 +66,7 @@ function juicer_visual(block: VisualBlock, instances: Instances): Visual { target = press_target(); for (const instance of shown) instance.delete(); shown = []; - const tank = block.get_client_data("tank"); + const tank = block.get_client_data("tank"); if (tank) { const juice = instances.fluid(tank.fluid); const [low, high] = JUICER_INSIDE; diff --git a/mods/bworld/scripts/juicing.ts b/mods/bworld/scripts/juicing.ts index 0fc7cdd..0ee12b4 100644 --- a/mods/bworld/scripts/juicing.ts +++ b/mods/bworld/scripts/juicing.ts @@ -5,7 +5,7 @@ // bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared scripts. // whatever makes juice reads them, like the juicer. with create installed, each is also a create:compacting recipe, // so its press can make juice in a basin -import type { FluidVariant, SharedContext, TagApi } from "bworld/shared"; +import type { FluidStack, SharedContext, TagApi } from "bworld/shared"; import type { JuiceableParams } from "./shared.ts"; export const JUICING = "bworld:juicing"; @@ -14,7 +14,7 @@ export interface JuicingRecipe { // the items it presses input: string[]; // what one of them makes - juice: { fluid: FluidVariant; amount: number }; + juice: FluidStack; } // a recipe for every juiceable item, pressing one into the juice named after it, as much as its component says diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index 817aa69..802a6ca 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -2,13 +2,13 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // the base game's block and item behavior, written against the same api as any other mod -import type { BlockRef, Container, Player, Season, ServerContext } from "bworld/server"; +import type { BlockRef, Container, FluidHandler, FluidStack, Player, Season, ServerContext } from "bworld/server"; import { register_curios } from "./curios.ts"; import { register_effects } from "./effects.ts"; import { register_fishing } from "./fishing.ts"; import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts"; import { register_verdigris } from "./verdigris/server.ts"; -import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES, type JuicerTank } from "./shared.ts"; +import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts"; import { juicing_for, juicing_recipes } from "./juicing.ts"; export function setup(ctx: ServerContext) { @@ -851,14 +851,14 @@ function register_buckets(ctx: ServerContext) { // the juicer has no screen. right clicking it with something a juicing recipe takes puts that in, one kind at a time, // and pressing it (sneaking with an empty hand) JUICER_PRESSES times turns one of it into the recipe's juice, while -// that fits in the tank. right clicking it with an empty fluid container fills it from the tank. breaking it drops what's in it, and the -// juice is lost. clients see what's in it, its juice and how many times it's been pressed toward the next as its -// "stack", "tank" and "presses" client data, which its visual draws (see scripts/client.ts) +// that fits in the tank. its fluid handler only gives the juice out, so right clicking it with an empty fluid container +// fills that from the tank. breaking it drops what's in it, and the juice is lost. clients see what's in it, its juice +// and how many times it's been pressed toward the next as its "stack", "tank" and "presses" client data, which its +// visual draws (see scripts/client.ts) interface JuicerData { container?: string; // how many times it's been pressed toward the next juice presses?: number; - tank?: JuicerTank; } function register_juicer(ctx: ServerContext) { @@ -871,6 +871,18 @@ function register_juicer(ctx: ServerContext) { const data = item?.data !== undefined && { data: item.data }; block.set_client_data("stack", item && { id: item.id, count: item.count, ...data }); }; + const tank = (block: BlockRef) => + ctx.fluids.tank_handler({ + tanks: 1, + capacity: JUICER_CAPACITY, + get: () => { + const juice = block.get_client_data("tank"); + return juice ? [juice] : []; + }, + set: ([juice]) => block.set_client_data("tank", juice), + }); + // what others reach, which juice only comes out of + const handler = (block: BlockRef): FluidHandler => ({ ...tank(block), fill: () => 0 }); ctx.components.register_block("bworld:juicer", { on_interact(block, _params, player) { @@ -883,29 +895,16 @@ function register_juicer(ctx: ServerContext) { // true even when none fit, so the fruit isn't eaten instead return true; } - - const capacity = held && ctx.items.fluid_capacity(held.id); - if (held && capacity !== undefined) { - if ((held.data as { fluid?: unknown } | undefined)?.fluid !== undefined) return false; - const tank = data.tank; - if (!tank || tank.amount < capacity) return false; - const amount = tank.amount - capacity; - const left = amount > 0 ? { ...tank, amount } : undefined; - block.data = { ...data, tank: left } satisfies JuicerData; - block.set_client_data("tank", left); - player.exchange_held({ id: held.id, count: 1, data: { fluid: tank.fluid } }); - return true; + if (held && ctx.items.fluid_capacity(held.id) !== undefined) { + return ctx.fluids.interact(player, handler(block)); } if (held || !player.is_sneaking()) return false; const item = container.get(0); const recipe = item && juicing_for(recipes, item.id); if (!item || !recipe) return false; - const { fluid: juice, amount } = recipe.juice; - const tank = data.tank; - const fits = (tank ? tank.amount : 0) + amount <= JUICER_CAPACITY && - (!tank || ctx.fluids.same(tank.fluid, juice)); - if (!fits) return false; + const juice = tank(block); + if (juice.fill(recipe.juice, "simulate") < recipe.juice.amount) return false; const presses = (data.presses ?? 0) + 1; if (presses < JUICER_PRESSES) { block.data = { ...data, presses } satisfies JuicerData; @@ -914,15 +913,15 @@ function register_juicer(ctx: ServerContext) { } item.count -= 1; show(block, container); - const filled = { fluid: juice, amount: (tank?.amount ?? 0) + amount }; - block.data = { ...data, presses: 0, tank: filled } satisfies JuicerData; - block.set_client_data("tank", filled); + juice.fill(recipe.juice, "execute"); + block.data = { ...data, presses: 0 } satisfies JuicerData; block.set_client_data("presses", undefined); return true; }, on_break(block) { drop_contents(ctx, block); }, + fluid_handler: (block) => handler(block), }); } diff --git a/mods/bworld/scripts/shared.ts b/mods/bworld/scripts/shared.ts index ec3b643..b224fe5 100644 --- a/mods/bworld/scripts/shared.ts +++ b/mods/bworld/scripts/shared.ts @@ -5,7 +5,7 @@ // server and on every client, so players see a fence join or a trapdoor turn the moment they place it, and a trapdoor // or a door open the moment they click it. and the juice's rules, which name and color it by the item it's from, and // the recipes that make it -import type { FluidVariant, SharedBlock, SharedContext } from "bworld/shared"; +import type { SharedBlock, SharedContext } from "bworld/shared"; import { register_juicing } from "./juicing.ts"; import { register_verdigris_rules } from "./verdigris/shared.ts"; @@ -147,15 +147,11 @@ export interface JuiceableParams { color: string; } -// how much juice the juicer holds, in mB, and the juice in it: in its tile data, and in its "tank" client data for its -// visual to draw (see register_juicer in server.ts and juicer_visual in client.ts) +// how much juice the juicer holds, in mB. the juice in it is its "tank" client data, a FluidStack, which its visual +// draws (see register_juicer in server.ts and juicer_visual in client.ts) export const JUICER_CAPACITY = 1000; // how many presses make one of what's in it into juice. its visual lowers its press for each one toward the next export const JUICER_PRESSES = 4; -export interface JuicerTank { - fluid: FluidVariant; - amount: number; -} // what juice sells for, as a multiple of what the items pressed to make it sell for export const JUICE_VALUE = 1.2; diff --git a/mods/create/scripts/client.ts b/mods/create/scripts/client.ts index 4b36d08..1175884 100644 --- a/mods/create/scripts/client.ts +++ b/mods/create/scripts/client.ts @@ -15,7 +15,7 @@ import type { Visual, VisualBlock, } from "bworld/client"; -import type { Face } from "bworld/shared"; +import type { Face, FluidStack } from "bworld/shared"; import { actual_speed, type Axis, @@ -28,7 +28,7 @@ import { OPPOSITE, } from "./kinetics/connections.ts"; import { BASIN_TRAVEL, head_offset, type PressShown } from "./processing/press.ts"; -import { BASIN_TANK_CAPACITY, BASIN_TANKS, type BasinTank } from "./processing/basin.ts"; +import { BASIN_TANK_CAPACITY, BASIN_TANKS } from "./processing/basin.ts"; // a model reaching north turned to reach each way const facing_turns = (model: string): Record => ({ @@ -244,7 +244,7 @@ function basin_visual(block: VisualBlock, instances: Instances): Visual { for (const instance of shown) instance.delete(); shown = []; floating = []; - const tanks = block.get_client_data("tanks") ?? []; + const tanks = block.get_client_data("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; diff --git a/mods/create/scripts/processing/basin.ts b/mods/create/scripts/processing/basin.ts index b3ff1ce..4ff13df 100644 --- a/mods/create/scripts/processing/basin.ts +++ b/mods/create/scripts/processing/basin.ts @@ -5,17 +5,12 @@ // 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"; +import type { FluidStack, 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) { @@ -31,11 +26,11 @@ export function insert_item(items: readonly ItemStack[], stack: ItemStack, max: // 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[], + tanks: readonly FluidStack[], fluid: FluidVariant, amount: number, same: (a: FluidVariant, b: FluidVariant) => boolean, -): BasinTank[] | undefined { +): FluidStack[] | 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; @@ -44,15 +39,6 @@ export function fill( 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); @@ -72,7 +58,7 @@ function canonical(value: unknown): string { export interface BasinContents { items: readonly ItemStack[]; outputs: readonly ItemStack[]; - tanks: readonly BasinTank[]; + tanks: readonly FluidStack[]; } // what a basin recipe needs: one item for each ingredient, and what it makes @@ -80,7 +66,7 @@ export interface BasinRecipe { // each ingredient as every item that fits it ingredients: readonly (readonly string[])[]; results: readonly ItemStack[]; - fluid_results: readonly BasinTank[]; + fluid_results: readonly FluidStack[]; } // the basin once recipe has been made in it, or undefined when it can't be: an item for each ingredient comes out of @@ -104,7 +90,7 @@ export function apply_basin_recipe( if (into.inserted < result.count) return undefined; outputs = into.items; } - let tanks: readonly BasinTank[] = basin.tanks; + let tanks: readonly FluidStack[] = basin.tanks; for (const { fluid, amount } of recipe.fluid_results) { const filled = fill(tanks, fluid, amount, same); if (!filled) return undefined; diff --git a/mods/create/scripts/recipes/processing.ts b/mods/create/scripts/recipes/processing.ts index 9e3e6a7..2af6a88 100644 --- a/mods/create/scripts/recipes/processing.ts +++ b/mods/create/scripts/recipes/processing.ts @@ -4,7 +4,7 @@ // create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and // stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. read and checked when the server starts, so a broken one stops it there instead of // in a machine. no ctx, tests give what it needs -import type { FluidVariant, Id } from "bworld/shared"; +import type { FluidStack, Id } from "bworld/shared"; // how many ingredients, item results and fluid results a type takes at most, like getMaxInputCount, // getMaxOutputCount and getMaxFluidOutputCount @@ -31,7 +31,7 @@ export interface ProcessingRecipe { ingredients: Id[][]; results: ProcessingResult[]; // in mB - fluid_results: { fluid: FluidVariant; amount: number }[]; + fluid_results: FluidStack[]; } // what reading recipes needs from the game diff --git a/mods/create/scripts/server.ts b/mods/create/scripts/server.ts index 56273f6..5dd03dc 100644 --- a/mods/create/scripts/server.ts +++ b/mods/create/scripts/server.ts @@ -3,7 +3,7 @@ // create's blocks that do something: so far what turns (create:kinetic), the generators that turn it (the hand crank, // the creative motor and the water wheel), the mechanical press and the basin -import type { BlockRef, EntityRef, FluidVariant, Id, ItemStack, ServerContext } from "bworld/server"; +import type { BlockRef, EntityRef, FluidStack, Id, ItemStack, ServerContext } from "bworld/server"; import { actual_speed, along, @@ -30,10 +30,9 @@ import { import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts"; import { apply_basin_recipe, + BASIN_TANK_CAPACITY, + BASIN_TANKS, type BasinContents, - type BasinTank, - drain, - fill, insert_item, } from "./processing/basin.ts"; @@ -214,15 +213,20 @@ export function setup(ctx: ServerContext) { 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 +// holds items dropped into it and fluid poured in, like create's BasinBlock: an item that lands in it goes in, and an +// empty hand takes every item out. its tanks are its fluid handler, which a full fluid container used on it empties +// into and an empty one fills from. what's in it is its "items" and "tanks" client data, kept nowhere else, which its +// visual draws. breaking it drops the items, and the fluid is lost function register_basin(ctx: ServerContext) { const items_of = (block: BlockRef) => basin_contents(block).items; - const tanks_of = (block: BlockRef) => basin_contents(block).tanks; const set_items = (block: BlockRef, items: readonly ItemStack[]) => set_basin(block, { items }); - const set_tanks = (block: BlockRef, tanks: readonly BasinTank[]) => set_basin(block, { tanks }); + const tanks = (block: BlockRef) => + ctx.fluids.tank_handler({ + tanks: BASIN_TANKS, + capacity: BASIN_TANK_CAPACITY, + get: () => basin_contents(block).tanks, + set: (tanks) => set_basin(block, { tanks }), + }); ctx.components.register_block("create:basin", { on_entity_stand(block, _params, entity) { @@ -241,23 +245,9 @@ function register_basin(ctx: ServerContext) { set_basin(block, { items: [], outputs: [] }); 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 } }); - } - } + if (ctx.items.fluid_capacity(held.id) === undefined) return false; + ctx.fluids.interact(player, tanks(block)); // a fluid container is used up on the basin even when nothing fits, like create's return true; }, @@ -265,6 +255,7 @@ function register_basin(ctx: ServerContext) { const { items, outputs } = basin_contents(block); for (const item of [...items, ...outputs]) ctx.world.drop_item(block.x, block.y, block.z, item); }, + fluid_handler: (block) => tanks(block), }); } @@ -273,7 +264,7 @@ function basin_contents(block: BlockRef): BasinContents { return { items: block.get_client_data("items") ?? [], outputs: block.get_client_data("outputs") ?? [], - tanks: block.get_client_data("tanks") ?? [], + tanks: block.get_client_data("tanks") ?? [], }; } diff --git a/server/game/fluid_handlers.ts b/server/game/fluid_handlers.ts new file mode 100644 index 0000000..d404896 --- /dev/null +++ b/server/game/fluid_handlers.ts @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the fluid handlers the engine makes for server scripts, see ServerFluidApi in mod_api/server.ts: fluid containers', +// tanks scripts keep, and pouring from one handler into another +import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; +import { contained_fluid } from "$/common/inventory.ts"; +import type { + FluidHandler, + FluidHandlerItem, + FluidStack, + ItemStack, + Player, + TankHandlerOptions, +} from "$/common/mod_api/server.ts"; +import { same_fluid } from "$/common/fluids.ts"; + +// one of a stack of fluid containers, full of its whole capacity or empty, undefined for an item that isn't one +export function item_handler(stack: ItemStack): FluidHandlerItem | undefined { + const capacity = EverythingRegistry.get("items", stack.id)?.fluid_container?.capacity; + if (capacity === undefined) return undefined; + let fluid = contained_fluid(stack.id, stack.data); + return { + get container() { + return fluid ? { id: stack.id, count: 1, data: { fluid } } : { id: stack.id, count: 1 }; + }, + tanks: () => 1, + fluid_in_tank: () => fluid && { fluid, amount: capacity }, + tank_capacity: () => capacity, + is_fluid_valid: () => true, + fill(stack, action) { + if (fluid || stack.amount < capacity) return 0; + if (action === "execute") fluid = stack.fluid; + return capacity; + }, + drain(what, action) { + if (!fluid) return undefined; + const wanted = typeof what === "number" ? what : same_fluid(what.fluid, fluid) ? what.amount : 0; + if (wanted < capacity) return undefined; + const drained = { fluid, amount: capacity }; + if (action === "execute") fluid = undefined; + return drained; + }, + }; +} + +export function tank_handler(options: TankHandlerOptions): FluidHandler { + const { tanks, capacity, get, set } = options; + return { + tanks: () => tanks, + fluid_in_tank: (tank) => get()[tank], + tank_capacity: () => capacity, + is_fluid_valid: () => true, + fill(stack, action) { + if (!EverythingRegistry.get("fluids", stack.fluid.id)) throw new Error(`unknown fluid ${stack.fluid.id}`); + if (!(stack.amount > 0)) return 0; + const now = get(); + const index = now.findIndex((tank) => same_fluid(tank.fluid, stack.fluid)); + if (index === -1 && now.length >= tanks) return 0; + const had = index === -1 ? 0 : now[index].amount; + const filled = Math.min(stack.amount, capacity - had); + if (filled > 0 && action === "execute") { + const into = { fluid: stack.fluid, amount: had + filled }; + set(index === -1 ? [...now, into] : now.with(index, into)); + } + return Math.max(0, filled); + }, + drain(what, action) { + const now = get(); + const index = typeof what === "number" ? 0 : now.findIndex((tank) => same_fluid(tank.fluid, what.fluid)); + const tank = now[index]; + if (!tank) return undefined; + const drained = Math.min(typeof what === "number" ? what : what.amount, tank.amount); + if (!(drained > 0)) return undefined; + if (action === "execute") { + const left = tank.amount - drained; + set(left > 0 ? now.with(index, { ...tank, amount: left }) : now.toSpliced(index, 1)); + } + return { fluid: tank.fluid, amount: drained }; + }, + }; +} + +// what to gives of what from would, then that much taken from from and put into to +export function transfer(from: FluidHandler, to: FluidHandler, max: number): FluidStack | undefined { + const offered = from.drain(max, "simulate"); + if (!offered) return undefined; + const taken = to.fill(offered, "simulate"); + if (taken <= 0) return undefined; + const drained = from.drain({ fluid: offered.fluid, amount: taken }, "execute"); + if (!drained) return undefined; + return { fluid: drained.fluid, amount: to.fill(drained, "execute") }; +} + +export function interact(player: Player, handler: FluidHandler): boolean { + const held = player.held_item; + const item = held && item_handler(held); + if (!item) return false; + const moved = transfer(handler, item, Infinity) ?? transfer(item, handler, Infinity); + if (moved) player.exchange_held(item.container); + return moved !== undefined; +} diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 35fb0a9..fbf197e 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -25,6 +25,7 @@ import { physics } from "$/common/physics.ts"; import { clock } from "$/common/time.ts"; import { BlockRules } from "$/common/block_rules.ts"; import { FluidRules } from "$/common/fluids.ts"; +import { interact, item_handler, tank_handler, transfer } from "./fluid_handlers.ts"; import type { SharedContext } from "$/common/mod_api/shared.ts"; import { tag_api } from "$/common/tags.ts"; import { loading_mod } from "$/common/hooks.ts"; @@ -38,6 +39,8 @@ import type { EffectComponent, EntityRef, EventSignal, + Face, + FluidHandler, ItemComponent, ItemStack, LivingRef, @@ -532,6 +535,26 @@ export class ModRuntime { } #components_with = new Map>(); + // the fluid handler of the block at x y z reached from face, from the first of its components with one + block_fluid_handler(x: number, y: number, z: number, face: Face | undefined): FluidHandler | undefined { + if (face !== undefined && !faces.includes(face)) { + throw new Error(`a face is one of ${faces.join(", ")}, not ${face}`); + } + const id = this.game.world.get_block_id(x, y, z); + const components = this.components_with(id, "fluid_handler"); + if (components.length === 0) return undefined; + const block = this.block_ref(x, y, z, id); + for (const { mod, id: component_id, component, params } of components) { + const handler = run_guarded( + mod, + `${component_id} fluid_handler`, + () => component.fluid_handler!(block, params, face), + ); + if (handler) return handler; + } + return undefined; + } + // the block at x y z was told the one at from changed, and its rules have had their say: its components' // on_neighbor_change #neighbor_changed(x: number, y: number, z: number, from: Position) { @@ -974,7 +997,14 @@ export class ModRuntime { return is_solid(block); }, }, - fluids: this.fluid_rules.api(), + fluids: { + ...this.fluid_rules.api(), + block_handler: (x, y, z, face) => this.block_fluid_handler(x, y, z, face), + item_handler, + tank_handler, + transfer, + interact, + }, recipes: { furnace_result: (input) => { const recipe = game().recipes.furnace.get(input); diff --git a/tests/create/basin_test.ts b/tests/create/basin_test.ts index ab7ceae..6cd3190 100644 --- a/tests/create/basin_test.ts +++ b/tests/create/basin_test.ts @@ -5,14 +5,12 @@ // 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 type { FluidStack, ItemStack as Stack } from "bworld/shared"; import { apply_basin_recipe, BASIN_SLOTS, BASIN_TANK_CAPACITY, BASIN_TANKS, - type BasinTank, - drain, fill, insert_item, } from "$/mods/create/scripts/processing/basin.ts"; @@ -40,9 +38,9 @@ Deno.test("a basin keeps one stack of each kind of item, and only so many kinds" 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", () => { +Deno.test("a basin recipe's fluids each go in a tank of their own", () => { const half = BASIN_TANK_CAPACITY / 2; - let tanks: BasinTank[] = fill([], juice("apple"), half, same)!; + let tanks: FluidStack[] = 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 @@ -50,11 +48,6 @@ Deno.test("a basin keeps each fluid in a tank of its own, and drains the first", 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); }); Deno.test("a basin recipe takes an item for each ingredient, and puts what it makes where recipes don't take it", () => { @@ -91,7 +84,7 @@ async function 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 tanks = () => t.game.world.get_tile(0, 100, 0)?.client_data?.tanks as FluidStack[] | 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); diff --git a/tests/fluid_handler_test.ts b/tests/fluid_handler_test.ts new file mode 100644 index 0000000..b9582fe --- /dev/null +++ b/tests/fluid_handler_test.ts @@ -0,0 +1,204 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// fluid handlers: blocks' from their components, fluid containers', the tanks ctx.fluids.tank_handler keeps for a +// script, and pouring from one into another +import { assertEquals } from "@std/assert"; +import { item_handler, transfer } from "$/server/game/fluid_handlers.ts"; +import { copy_dir, stone_floor, test_game } from "./helpers.ts"; + +const SYRUP = { id: "testmod:syrup" }; +const MAPLE = { id: "testmod:syrup", data: { tree: "maple" } }; +const HONEY = { id: "testmod:honey" }; +const JAR = "testmod:jar"; + +const SERVER_SCRIPT = ` +import type { FluidStack, ServerContext } from "bworld/server"; +export function setup(ctx: ServerContext) { + // two tanks kept in its data, reached from every side but the bottom + ctx.components.register_block("testmod:tank", { + fluid_handler(block, _params, face) { + if (face === "bottom") return undefined; + return ctx.fluids.tank_handler({ + tanks: 2, + capacity: 1000, + get: () => block.data?.tanks ?? [], + set: (tanks: FluidStack[]) => { block.data = { tanks }; }, + }); + }, + on_interact(block, _params, player) { + const handler = ctx.fluids.block_handler(block.x, block.y, block.z, "top"); + return handler !== undefined && ctx.fluids.interact(player, handler); + }, + }); +} +`; + +async function setup() { + const dir = Deno.makeTempDirSync({ prefix: "bworld_fluid_handler_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + const mod = `${dir}/testmod`; + for (const folder of ["blocks", "items", "fluids", "scripts"]) { + Deno.mkdirSync(`${mod}/${folder}`, { recursive: true }); + } + const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json)); + write("manifest.json", { + format_version: 1, + id: "testmod", + name: "Test", + version: "1.0.0", + dependencies: [{ id: "bworld", version: "*" }], + scripts: { server: "scripts/server.ts" }, + }); + write("fluids/syrup.json", { format_version: 1, fluid: { id: SYRUP.id, color: "#a0522d" } }); + write("fluids/honey.json", { format_version: 1, fluid: { id: HONEY.id, color: "#e0a030" } }); + write("items/jar.json", { + format_version: 1, + item: { id: JAR, texture: "engine:missing", fluid_container: { capacity: 250 } }, + }); + write("blocks/tank.json", { + format_version: 1, + block: { + id: "testmod:tank", + textures: "bworld:stone", + mining: { toughness: 1 }, + components: { "testmod:tank": {} }, + }, + }); + Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT); + try { + const t = await test_game(dir); + stone_floor(t.game); + t.game.set_block(1, 100, 0, "testmod:tank"); + const tank = (face?: "top" | "bottom") => t.game.mods.block_fluid_handler(1, 100, 0, face); + const tanks = () => [0, 1].map((i) => tank()!.fluid_in_tank(i)); + return { ...t, tank, tanks }; + } finally { + Deno.removeSync(dir, { recursive: true }); + } +} + +Deno.test("a block's fluid handler comes from its components, for the side it's reached from", async () => { + const { game, tank } = await setup(); + assertEquals(tank()?.tanks(), 2); + assertEquals(tank("top")?.tanks(), 2); + assertEquals(tank("bottom"), undefined); + // blocks without one, and air + assertEquals(game.mods.block_fluid_handler(0, 99, 0, "top"), undefined); + assertEquals(game.mods.block_fluid_handler(0, 110, 0, undefined), undefined); +}); + +Deno.test("tank_handler fills the tank with the same fluid or else an empty one, and drains from the first", async () => { + const { tank, tanks } = await setup(); + assertEquals(tank()!.fill({ fluid: SYRUP, amount: 600 }, "execute"), 600); + // only what fits, and simulating changes nothing + assertEquals(tank()!.fill({ fluid: SYRUP, amount: 600 }, "simulate"), 400); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 600 }, undefined]); + // the same fluid with other data is another fluid, in the other tank + assertEquals(tank()!.fill({ fluid: MAPLE, amount: 300 }, "execute"), 300); + // and with both tanks taken there's no room for a third + assertEquals(tank()!.fill({ fluid: HONEY, amount: 100 }, "execute"), 0); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 600 }, { fluid: MAPLE, amount: 300 }]); + + // a number of mB comes from the first tank, a fluid from its own + assertEquals(tank()!.drain(100, "execute"), { fluid: SYRUP, amount: 100 }); + assertEquals(tank()!.drain({ fluid: MAPLE, amount: 1000 }, "simulate"), { fluid: MAPLE, amount: 300 }); + assertEquals(tank()!.drain({ fluid: HONEY, amount: 1000 }, "execute"), undefined); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 500 }, { fluid: MAPLE, amount: 300 }]); + // an emptied tank takes any fluid again + assertEquals(tank()!.drain({ fluid: MAPLE, amount: 1000 }, "execute"), { fluid: MAPLE, amount: 300 }); + assertEquals(tank()!.fill({ fluid: HONEY, amount: 100 }, "execute"), 100); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 500 }, { fluid: HONEY, amount: 100 }]); +}); + +Deno.test("a fluid container's handler fills and drains all it holds at once, changing its container", async () => { + await setup(); + assertEquals(item_handler({ id: "bworld:stone", count: 1 }), undefined); + // one of the stack + const jar = item_handler({ id: JAR, count: 5 })!; + assertEquals([jar.tanks(), jar.tank_capacity(0), jar.fluid_in_tank(0)], [1, 250, undefined]); + assertEquals(jar.container, { id: JAR, count: 1 }); + assertEquals(jar.drain(1000, "execute"), undefined); + // less than it holds doesn't fill it + assertEquals(jar.fill({ fluid: SYRUP, amount: 100 }, "execute"), 0); + assertEquals(jar.fill({ fluid: SYRUP, amount: 1000 }, "simulate"), 250); + assertEquals(jar.container, { id: JAR, count: 1 }); + assertEquals(jar.fill({ fluid: SYRUP, amount: 1000 }, "execute"), 250); + assertEquals(jar.container, { id: JAR, count: 1, data: { fluid: SYRUP } }); + assertEquals(jar.fill({ fluid: SYRUP, amount: 1000 }, "execute"), 0); + + // and it only empties all at once, of its own fluid + assertEquals(jar.drain(100, "execute"), undefined); + assertEquals(jar.drain({ fluid: HONEY, amount: 250 }, "execute"), undefined); + assertEquals(jar.drain(1000, "execute"), { fluid: SYRUP, amount: 250 }); + assertEquals(jar.container, { id: JAR, count: 1 }); + + // a full one from its data + assertEquals(item_handler({ id: JAR, count: 1, data: { fluid: MAPLE } })!.fluid_in_tank(0), { + fluid: MAPLE, + amount: 250, + }); +}); + +Deno.test("transfer pours what the second handler takes of what the first gives", async () => { + const { tank, tanks } = await setup(); + tank()!.fill({ fluid: SYRUP, amount: 600 }, "execute"); + const jar = item_handler({ id: JAR, count: 1 })!; + assertEquals(transfer(tank()!, jar, Infinity), { fluid: SYRUP, amount: 250 }); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 350 }, undefined]); + assertEquals(transfer(tank()!, jar, Infinity), undefined); + // a jar takes no less than it holds + assertEquals(transfer(tank()!, item_handler({ id: JAR, count: 1 })!, 200), undefined); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 350 }, undefined]); + assertEquals(transfer(jar, tank()!, Infinity), { fluid: SYRUP, amount: 250 }); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 600 }, undefined]); + assertEquals(jar.container, { id: JAR, count: 1 }); +}); + +Deno.test("using a fluid container on a block's handler fills it from there, or else empties it in", async () => { + const { game, join, send, tank, tanks } = await setup(); + join(1, "alice"); + send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + const player = game.players()[0]; + game.mods.player(player).give_item(JAR, 2); + const jars = () => player.inventory.to_data().filter((item) => item?.id === JAR); + const use = () => send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); + tank()!.fill({ fluid: SYRUP, amount: 300 }, "execute"); + + use(); + assertEquals(jars(), [{ id: JAR, count: 1 }, { id: JAR, count: 1, data: { fluid: SYRUP } }]); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 50 }, undefined]); + // 50 mB doesn't fill a jar + use(); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 50 }, undefined]); + + send(1, { type: "select_slot", slot: player.inventory.to_data().findIndex((item) => item?.data) }); + use(); + assertEquals(tanks(), [{ fluid: SYRUP, amount: 300 }, undefined]); + assertEquals(jars(), [{ id: JAR, count: 1 }, { id: JAR, count: 1 }]); +}); + +Deno.test("the juicer's fluid handler only gives juice out, and the basin's takes any two fluids", async () => { + // every mod in mods/, create among them + const { game } = await test_game("mods"); + stone_floor(game); + const juice = { id: "bworld:juice" }; + game.set_block(1, 100, 0, "bworld:juicer"); + const juicer = () => game.mods.block_fluid_handler(1, 100, 0, "top")!; + assertEquals(juicer().fill({ fluid: juice, amount: 100 }, "execute"), 0); + game.mods.block_ref(1, 100, 0, "bworld:juicer").set_client_data("tank", { fluid: juice, amount: 500 }); + assertEquals(juicer().drain(200, "execute"), { fluid: juice, amount: 200 }); + assertEquals(game.world.get_tile(1, 100, 0)?.client_data?.tank, { fluid: juice, amount: 300 }); + + game.set_block(2, 100, 0, "create:basin"); + const basin = () => game.mods.block_fluid_handler(2, 100, 0, "top")!; + assertEquals(transfer(juicer(), basin(), Infinity), { fluid: juice, amount: 300 }); + assertEquals( + basin().fill({ fluid: { id: "bworld:juice", data: { item: "bworld:apple" } }, amount: 100 }, "execute"), + 100, + ); + assertEquals(game.world.get_tile(2, 100, 0)?.client_data?.tanks, [ + { fluid: juice, amount: 300 }, + { fluid: { id: "bworld:juice", data: { item: "bworld:apple" } }, amount: 100 }, + ]); +});