From 26b59a189949f3cca1039001409811eec2df86f2 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 25 Oct 2026 15:02:31 -0300 Subject: [PATCH] Fluid containers --- client/fluid_rules.ts | 13 +++++ client/gui/mod_graphics.ts | 3 +- client/gui/tooltip.ts | 14 ++++-- client/mods.ts | 5 +- client/rendering/item_renderer.ts | 56 ++++++++++++++++++---- client/rendering/render_utils.ts | 49 ++++++++++++------- common/block_models.ts | 5 +- common/everything_registry.ts | 20 ++++++++ common/inventory.ts | 53 ++++++++++++++++----- common/mod_api/server.ts | 10 +++- common/mod_check.ts | 6 +++ common/mod_data.ts | 27 ++++++++++- common/worldgen/biome_colors.ts | 5 ++ docs/modding/entities/players.md | 5 ++ docs/modding/items/index.md | 63 +++++++++++++++++------- docs/modding/resources/fluids.md | 43 +++++++++++++++++ server/game/entity/item_entity.ts | 4 +- server/game/game_server.ts | 3 +- server/game/mod_runtime.ts | 18 +++++-- tests/fluid_container_test.ts | 79 +++++++++++++++++++++++++++++++ tests/fluid_registry_test.ts | 3 +- tests/importer_test.ts | 12 ++++- tests/stack_data_test.ts | 55 +++++++++++++++++++++ tools/importer/items.ts | 17 ++++--- 24 files changed, 486 insertions(+), 82 deletions(-) create mode 100644 client/fluid_rules.ts create mode 100644 tests/fluid_container_test.ts create mode 100644 tests/stack_data_test.ts diff --git a/client/fluid_rules.ts b/client/fluid_rules.ts new file mode 100644 index 0000000..a2f6aa9 --- /dev/null +++ b/client/fluid_rules.ts @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the fluids' rules from the mods' shared scripts on this client, the same as the server's (see common/fluids.ts), for +// drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods +// and makes it again for each server's +import { FluidRules } from "$/common/fluids.ts"; + +export let fluid_rules = new FluidRules(() => undefined); + +export function set_fluid_rules(rules: FluidRules) { + fluid_rules = rules; +} diff --git a/client/gui/mod_graphics.ts b/client/gui/mod_graphics.ts index 456fbc2..42daa32 100644 --- a/client/gui/mod_graphics.ts +++ b/client/gui/mod_graphics.ts @@ -161,8 +161,7 @@ export class ModGraphics implements Graphics { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); const stack = new ItemStack(id, count); // the count only shows when it's more than one - if (count === 1) stack.max_amount = 1; - draw_item(stack, this.#x(x), this.#y(y)); + draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1); } clip(x: number, y: number, w: number, h: number, draw: () => void) { diff --git a/client/gui/tooltip.ts b/client/gui/tooltip.ts index 6ef0355..cc06f08 100644 --- a/client/gui/tooltip.ts +++ b/client/gui/tooltip.ts @@ -1,10 +1,12 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the box next to the mouse saying what an item is, like minecraft's: its name, what it's worth, then its lore +// the box next to the mouse saying what an item is, like minecraft's: its name, the fluid in it, what it's worth, then +// its lore import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; -import type { ItemStack } from "$/common/inventory.ts"; +import { contained_fluid, type ItemStack } from "$/common/inventory.ts"; import { display_name } from "$/common/utils.ts"; +import { fluid_rules } from "$/client/fluid_rules.ts"; import { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "$/client/renderer/mod.ts"; import { AssetManager } from "$/client/assets.ts"; import { get_sprite_region } from "$/client/sprites.ts"; @@ -16,6 +18,7 @@ type Color = [number, number, number, number]; const NAME_COLOR: Color = [1, 1, 1, 1]; const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1]; const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1]; +const FLUID_COLOR: Color = [0.55, 0.75, 0.95, 1]; const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1]; // from the edge of the tooltip sprite to the text const PADDING = 4 * GUI_SCALE; @@ -34,10 +37,15 @@ export interface TooltipLine { icon?: string; } -// its name, the item's lore from its json, then what the server's scripts said about this stack +// its name, the fluid a full container holds, the item's lore from its json, then what the server's scripts said about +// this stack export function item_tooltip(item: ItemStack): TooltipLine[] { const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }]; const info = EverythingRegistry.get("items", item.type_id); + const fluid = contained_fluid(item.type_id, item.data); + if (fluid) { + lines.push({ text: `${fluid_rules.name(fluid)}, ${info!.fluid_container!.capacity} mB`, color: FLUID_COLOR }); + } if (info?.food) { lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR }); } diff --git a/client/mods.ts b/client/mods.ts index b8bad89..c0a8d57 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -11,6 +11,7 @@ import { type Bmod, read_bmod } from "$/common/bmod.ts"; import { get_state_value, set_state_value, shared_items_api } from "$/common/utils.ts"; import { BlockRules } from "$/common/block_rules.ts"; import { FluidRules } from "$/common/fluids.ts"; +import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts"; import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "$/common/block_shapes.ts"; import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts"; import { tag_api } from "$/common/tags.ts"; @@ -91,8 +92,6 @@ const rules_world: SharedWorld = { // what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts export let block_rules = new BlockRules(run_mod, rules_world.get_block); -// the fluids' rules from shared scripts, the same as the server's, see common/fluids.ts -export let fluid_rules = new FluidRules(run_mod); // whether shared scripts are being set up, the only time they can register rules let rules_setup = false; // whether client scripts are being set up, the only time they can register visuals, since chunk workers are told @@ -166,7 +165,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { // every mod's shared rules first, so client scripts can count on any mod's being there block_rules = new BlockRules(run_mod, rules_world.get_block); - fluid_rules = new FluidRules(run_mod); + set_fluid_rules(new FluidRules(run_mod)); rules_setup = true; for (const [i, bmod] of bmods.entries()) { const code = bmod.scripts.shared; diff --git a/client/rendering/item_renderer.ts b/client/rendering/item_renderer.ts index 96ca07b..8b5cf07 100644 --- a/client/rendering/item_renderer.ts +++ b/client/rendering/item_renderer.ts @@ -3,11 +3,11 @@ import { mat4, vec3 } from "gl-matrix"; import type { SpriteRegion } from "$/common/constants.ts"; -import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; +import { BlockRegistry, EverythingRegistry, type ItemLayer, ItemRegistry } from "$/common/everything_registry.ts"; import { AssetManager } from "$/client/assets.ts"; import { get_sprite_region } from "$/client/sprites.ts"; import type { ItemEntity } from "$/client/entity/item_entity.ts"; -import { type ItemData, ItemStack } from "$/common/inventory.ts"; +import { contained_fluid, type ItemData, ItemStack } from "$/common/inventory.ts"; import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts"; import { bake_model, @@ -23,12 +23,14 @@ import { type ModelDisplay, type ModelJson, } from "$/common/block_models.ts"; -import { item_model } from "./item_model.ts"; +import { item_model, type ItemQuad } from "./item_model.ts"; import { get_state_value, item_texture } from "$/common/utils.ts"; import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts"; import type { ClientLevel } from "$/client/level/client_level.ts"; import { entity_tint } from "./entity_light.ts"; import type { Vec3 } from "./player_renderer.ts"; +import { fluid_rules } from "$/client/fluid_rules.ts"; +import { color_rgb, tint_without_biome, type TintColor } from "$/common/worldgen/biome_colors.ts"; // how big items on the ground are drawn, minecraft's ground transform const BLOCK_SCALE = 0.25; @@ -50,6 +52,9 @@ const CORNER_UVS = [[0, 1], [1, 1], [1, 0], [0, 0]] as const; // where the extra copies of a bigger stack sit, as fractions of the model's size const COPY_OFFSETS = [[0, 0, 0], [0.35, 0.2, -0.25], [-0.3, 0.4, 0.2], [0.15, 0.6, 0.35], [-0.2, 0.8, -0.3]]; +// how far each of a flat item's layers sits out from the one under it, so it's drawn over it +const LAYER_GAP = 0.001; + // minecraft draws more copies of the model the bigger the stack is function copies(amount: number) { if (amount > 48) return 5; @@ -320,19 +325,54 @@ export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransf return; } + // its sprite, then its layers over it: only their fronts and backs, the first two quads, each a little further out const texture_id = item_texture(item); + push_sprite(atlas, texture_id, item_model(texture_id), [tr, tg, tb], 0, transform); + item_layers(item).forEach(({ texture, color: [r, g, b] }, i) => { + const color: Vec3 = [r * tr, g * tg, b * tb]; + push_sprite(atlas, texture, item_model(texture).slice(0, 2), color, (i + 1) * LAYER_GAP, transform); + }); +} + +// a flat item's sprite made 3d (see item_model.ts), its front and back gap further out than the item's +function push_sprite( + atlas: Texture, + texture_id: string, + quads: ItemQuad[], + [r, g, b]: Vec3, + gap: number, + transform: ItemTransform, +) { const region = get_sprite_region(texture_id); - const u = (pixels: number) => (region.x + pixels) / atlas.width; - const v = (pixels: number) => (region.y + pixels) / atlas.height; - for (const quad of item_model(texture_id)) { + for (const quad of quads) { for (const i of [0, 1, 2, 0, 2, 3]) { - const [px, py, pz] = transform(...quad.corners[i]); + const [cx, cy, cz] = quad.corners[i]; + const [px, py, pz] = transform(cx, cy, cz + Math.sign(cz) * gap); const [pu, pv] = quad.uvs[i]; - push_vertex(px, py, pz, u(pu), v(pv), quad.shade * tr, quad.shade * tg, quad.shade * tb, 1); + const u = (region.x + pu) / atlas.width; + const v = (region.y + pv) / atlas.height; + push_vertex(px, py, pz, u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1); } } } +// the layers drawn over a flat item's texture (see ItemLayer), each in its tint's color, without the ones whose tint +// has no color for this stack +export function item_layers(item: ItemStack): { texture: string; color: Vec3 }[] { + const layers = EverythingRegistry.get("items", item.type_id)?.layers ?? []; + return layers.flatMap(({ texture, tint }) => { + const color = layer_color(item, tint); + return color ? [{ texture, color }] : []; + }); +} + +function layer_color(item: ItemStack, tint: ItemLayer["tint"]): Vec3 | undefined { + if (tint === undefined) return [1, 1, 1]; + if (tint !== "fluid") return color_rgb(tint_without_biome(tint)); + const fluid = contained_fluid(item.type_id, item.data); + return fluid && color_rgb(tint_without_biome(fluid_rules.color(fluid) as TintColor)); +} + // where a model's uv in pixels (0-16) is in the atlas. the atlas's border around each sprite (see ATLAS_BORDER) keeps // lookups that round past its edge on its own pixels export function sprite_u(atlas: Texture, region: SpriteRegion, pixels: number) { diff --git a/client/rendering/render_utils.ts b/client/rendering/render_utils.ts index ff37da9..83630e9 100644 --- a/client/rendering/render_utils.ts +++ b/client/rendering/render_utils.ts @@ -15,7 +15,15 @@ import { ITEM_FACE_SHADE, item_tint, } from "$/common/block_models.ts"; -import { display_matrix, item_block, item_model_of, type ItemModel, sprite_u, sprite_v } from "./item_renderer.ts"; +import { + display_matrix, + item_block, + item_layers, + item_model_of, + type ItemModel, + sprite_u, + sprite_v, +} from "./item_renderer.ts"; import { draw_rect, draw_text, @@ -77,7 +85,8 @@ export function draw_nine_slice( } } -export function draw_item(item: ItemStack, x: number, y: number) { +// show_count is for drawing an item where its count means nothing, like one shown on a screen +export function draw_item(item: ItemStack, x: number, y: number, show_count = item.max_amount !== 1) { const item_info = EverythingRegistry.get("items", item.type_id); if (!item_info) { @@ -95,7 +104,7 @@ export function draw_item(item: ItemStack, x: number, y: number) { draw_item_item(item, item_info, x, y); } - if (item.max_amount !== 1) { + if (show_count) { draw_text( String(item.amount), x + SLOT_SIZE + 2 - 11 * 2, @@ -128,19 +137,27 @@ export function draw_item(item: ItemStack, x: number, y: number) { // ey its not a bad name function draw_item_item(item: ItemStack, item_info: ItemRegistry, x: number, y: number) { - const texture_id = item_texture(item, item_info); - const sprite_region = get_sprite_region(texture_id); - draw_texture_region( - AssetManager.instance.get("bworld:textures"), - sprite_region.x, - sprite_region.y, - sprite_region.width, - sprite_region.height, - x + 3, - y + 3, - SLOT_SIZE - 6, - SLOT_SIZE - 6, - ); + const draw = (texture_id: string, [r, g, b] = [1, 1, 1]) => { + const sprite_region = get_sprite_region(texture_id); + draw_texture_region( + AssetManager.instance.get("bworld:textures"), + sprite_region.x, + sprite_region.y, + sprite_region.width, + sprite_region.height, + x + 3, + y + 3, + SLOT_SIZE - 6, + SLOT_SIZE - 6, + false, + false, + r, + g, + b, + ); + }; + draw(item_texture(item, item_info)); + for (const layer of item_layers(item)) draw(layer.texture, layer.color); } // from a model's points to a slot, as screen x and y and depth toward the viewer. with a gui transform, the transform diff --git a/common/block_models.ts b/common/block_models.ts index a385c48..962b8a0 100644 --- a/common/block_models.ts +++ b/common/block_models.ts @@ -5,7 +5,7 @@ // a block picks one with "model" and fills in its texture variables with "textures". baking turns a model // into quads in block space (0 to 1) that the chunk mesher and the item renderers draw import { type BlockRegistry, type BlockTextures, fluid_textures } from "./everything_registry.ts"; -import { tint_without_biome } from "./worldgen/biome_colors.ts"; +import { color_rgb, tint_without_biome } from "./worldgen/biome_colors.ts"; import { get_state_value } from "./utils.ts"; import { type DisplayContext, MODEL_FACES, type ModelFace } from "./mod_data.ts"; @@ -382,8 +382,7 @@ export function cube_face_tint(block: BlockRegistry, face: "top" | "bottom" | "f // the color to draw a part of a block's item in that got its texture through these variables, see cube_face_tint export function item_tint(block: BlockRegistry, variables: string[]): number[] { if (!is_tinted(block, variables)) return [1, 1, 1]; - const color = tint_without_biome(block.tint!.color); - return [color >> 16, (color >> 8) & 0xff, color & 0xff].map((c) => c / 255); + return color_rgb(tint_without_biome(block.tint!.color)); } // how much darker each side of an item's model is drawn, like the mesher's: top, bottom, south, north, west, east diff --git a/common/everything_registry.ts b/common/everything_registry.ts index 34262de..319d985 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -247,6 +247,23 @@ export interface FoodProperties { returns?: string; } +// an item that holds one fluid, full or empty, like a bucket. a full one's stack data is { fluid: FluidVariant }, see +// docs/modding/resources/fluids.md. what it looks like full is a layer tinted "fluid" +export interface FluidContainerProperties { + // how much a full one holds, in mB + capacity: number; + // how many full ones fit in a slot, the item's max_stack when not set + full_max_stack?: number; +} + +// a texture drawn over a flat item's own, like the fluid in a bucket, drawn in its tint's color: a block tint's color +// outside any biome, or "fluid" for the fluid a fluid container holds. a layer whose tint has no color for a stack, like +// "fluid" on an empty container, isn't drawn +export interface ItemLayer { + texture: string; + tint?: TintColor | "fluid"; +} + export interface ItemRegistry { texture_id: string | ((item: ItemStack) => string); // shown in place of texture_id while the stack's data has that key set, like a cast fishing rod. the first wins @@ -267,6 +284,9 @@ export interface ItemRegistry { // whether players holding it aim at fluids, like buckets and fishing rods. others look through them, so they can // break and place blocks under water targets_fluids?: boolean; + fluid_container?: FluidContainerProperties; + // drawn over its texture in order, see ItemLayer + layers?: ItemLayer[]; components?: Record; on_create?(item: ItemStack): void; diff --git a/common/inventory.ts b/common/inventory.ts index 2770140..dc461aa 100644 --- a/common/inventory.ts +++ b/common/inventory.ts @@ -2,6 +2,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; +import type { FluidVariant } from "./mod_api/shared.ts"; +import { is_object } from "./schema.ts"; +import { same_data } from "./utils.ts"; // how item stacks are saved and sent over the network export interface ItemData { @@ -12,25 +15,53 @@ export interface ItemData { lore?: string; } +// whether two stacks are of one thing and can be one stack, like minecraft's isSameItemSameComponents: the same item, +// and the same data whatever order its keys are in +export function same_stack(a: ItemStack, b: ItemStack): boolean { + return a.type_id === b.type_id && same_data(a.data, b.data); +} + +// how many fit in one slot: the item's max_stack, 1 for tools and 64 for everything else when it has none, and a full +// fluid container's full_max_stack +export function max_stack(id: string, data?: unknown): number { + const item = EverythingRegistry.get("items", id); + const max = item?.max_stack ?? (item?.tool ? 1 : 64); + return contained_fluid(id, data) ? item!.fluid_container!.full_max_stack ?? max : max; +} + +// the fluid a fluid container's stack holds, undefined for an empty one or an item that isn't a container. one of a +// fluid no mod defines anymore is empty +export function contained_fluid(id: string, data?: unknown): FluidVariant | undefined { + if (!EverythingRegistry.get("items", id)?.fluid_container || !is_object(data)) return undefined; + const fluid = data.fluid; + if (!is_object(fluid) || typeof fluid.id !== "string" || !EverythingRegistry.get("fluids", fluid.id)) { + return undefined; + } + return fluid as unknown as FluidVariant; +} + export class ItemStack { type_id: string; amount: number; - max_amount: number; data?: T; // on clients, the lore the server's scripts gave it when it was last synced lore?: string; - constructor(type_id: string | string, amount: number = 1, max_amount?: number) { + constructor(type_id: string | string, amount: number = 1) { const item_info = EverythingRegistry.get("items", type_id); this.type_id = type_id; this.amount = amount; - this.max_amount = max_amount ?? item_info?.max_stack ?? (item_info?.tool ? 1 : 64); this.data = undefined; if (item_info?.on_create) { item_info.on_create(this); } } + // from its data each time, since scripts change that, like filling a bucket + get max_amount(): number { + return max_stack(this.type_id, this.data); + } + // what's left of a tool's durability, its max minus the damage kept in its data. undefined for non tools durability(): number | undefined { const tool = EverythingRegistry.get("items", this.type_id)?.tool; @@ -50,7 +81,7 @@ export class ItemStack { } clone(): ItemStack { - const item = new ItemStack(this.type_id, this.amount, this.max_amount); + const item = new ItemStack(this.type_id, this.amount); item.data = structuredClone(this.data); item.lore = this.lore; return item; @@ -143,7 +174,7 @@ export class Container { add_item(item_stack: ItemStack): number { for (const slot of this.#slots.filter((slot) => slot.has_item())) { const slot_item = slot.get_item()!; - if (slot_item.type_id === item_stack.type_id) { + if (same_stack(slot_item, item_stack)) { const missing = slot_item.max_amount - slot_item.amount; const adding = Math.min(missing, item_stack.amount); slot_item.amount += adding; @@ -240,7 +271,7 @@ function left_click(container: Container, index: number, cursor: Cursor, limit: // if you are holding something and slot type equals holding type // try to add to stack - if (slot_item && slot.type_id === holding.type_id) { + if (slot_item && same_stack(slot_item, holding)) { const space_left = Math.min(slot.max_amount!, limit) - slot_item.amount; const amount_to_add = Math.max(0, Math.min(space_left, holding.amount)); @@ -275,7 +306,7 @@ function right_click(container: Container, index: number, cursor: Cursor, limit: if (holding) { // and slot type equals holding type // add 1 to matching stack - if (slot_item && slot.type_id === holding.type_id) { + if (slot_item && same_stack(slot_item, holding)) { if (slot_item.amount < Math.min(slot_item.max_amount, limit)) { slot_item.amount += 1; holding.amount -= 1; @@ -333,7 +364,7 @@ export function move_into(item: ItemStack, slots: SlotRef[], accepts: (slot: Slo for (const slot of slots) { const there = slot.container.get_item(slot.index); if (item.amount <= 0) return; - if (there && there !== item && there.type_id === item.type_id && accepts(slot)) { + if (there && there !== item && same_stack(there, item) && accepts(slot)) { const moving = Math.max(0, Math.min(slot_cap(slot, there) - there.amount, item.amount)); there.amount += moving; item.amount -= moving; @@ -357,7 +388,7 @@ export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: Slot const there = slot.container.get_item(slot.index); if (!accepts(slot)) continue; if (!there) room += slot_cap(slot, item); - else if (there.type_id === item.type_id) room += Math.max(0, slot_cap(slot, there) - there.amount); + else if (same_stack(there, item)) room += Math.max(0, slot_cap(slot, there) - there.amount); } return room; } @@ -365,7 +396,7 @@ export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: Slot // whether take_output would take it export function can_take_output(item: ItemStack, cursor: Cursor): boolean { const holding = cursor.item; - return !holding || (holding.type_id === item.type_id && holding.max_amount - holding.amount >= item.amount); + return !holding || (same_stack(holding, item) && holding.max_amount - holding.amount >= item.amount); } // output slots (furnace result, crafting result) can only be taken from, all at once @@ -376,7 +407,7 @@ export function take_output(item: ItemStack, cursor: Cursor): boolean { cursor.item = item.clone(); return true; } - if (holding.type_id === item.type_id && holding.max_amount - holding.amount >= item.amount) { + if (same_stack(holding, item) && holding.max_amount - holding.amount >= item.amount) { holding.amount += item.amount; return true; } diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index fd5f747..3947d0a 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -421,6 +421,9 @@ export interface Player { readonly held_item: ItemStack | undefined; // what doesn't fit in the inventory drops at their feet give_item(id: Id, count?: number, data?: unknown): void; + // one of the held item becomes result, like an empty bucket filling: straight into the hand when it was the last + // one, into the inventory (or at their feet) when there are more + exchange_held(result: ItemStack): void; send_message(text: string, options?: MessageOptions): void; // items drawn on them, under a key so each mod keeps its own list, like "bworld:curios". replaces what that key // had, [] clears it. only items whose json has worn show. not saved: set it again when they join @@ -525,8 +528,11 @@ export interface ItemApi { exists(id: Id): boolean; // every item, in load order ids(): Id[]; - // how many fit in one slot - max_stack(id: Id): number; + // how many fit in one slot, with this data: a full fluid container's can be fewer + max_stack(id: Id, data?: unknown): number; + // how much a fluid container holds when full, in mB, or undefined for an item that isn't one. see + // docs/modding/resources/fluids.md + fluid_capacity(id: Id): number | undefined; // the tool type it is, like "pickaxe" or "shovel", from the item's "tool" tool(id: Id): string | undefined; // what one of it sells for, from the item's "base_sell_value", or undefined if it can't be sold diff --git a/common/mod_check.ts b/common/mod_check.ts index 48cd9ac..53f62d7 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -323,6 +323,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable(is_tint_color, 'must be "grass", "foliage", "water" or a color like "#80a755"'); + // a texture id, or texture variables mapped to ids const textures = z.union([id, z.record(z.string(), id)], "must be a texture id or { variable: texture id }"); const stack = z.object({ id, count: z.int().min(1) }); @@ -168,7 +174,7 @@ const block_fields = z.object({ render_layer: z.enum(RENDER_LAYERS).optional(), cull_same: z.boolean().optional(), tint: z.object({ - color: z.custom(is_tint_color, 'must be "grass", "foliage", "water" or a color like "#80a755"'), + color: tint_color, // texture variables, like ["top"] textures: z.array(z.string()).optional(), }).optional(), @@ -368,6 +374,8 @@ export interface ItemJson { worn?: WornProperties; // see ItemRegistry.targets_fluids targets_fluids?: boolean; + fluid_container?: FluidContainerProperties; + layers?: ItemLayer[]; name?: string; lore?: string; components?: Record; @@ -401,6 +409,17 @@ const item_schema: z.ZodType = z.object({ slim_texture: id.optional(), }, "must be { model, texture }, an entity model and a texture").optional(), targets_fluids: z.boolean().optional(), + fluid_container: z.strictObject({ + capacity: z.int().min(1), + full_max_stack: z.int().min(1).optional(), + }).optional(), + layers: z.array(z.strictObject({ + texture: id, + tint: z.custom( + (value) => value === "fluid" || is_tint_color(value), + 'must be "fluid", "grass", "foliage", "water" or a color like "#80a755"', + ).optional(), + })).optional(), name: text.optional(), lore: text.optional(), components: json_object.optional(), @@ -463,7 +482,7 @@ const fluid_schema = z.object({ id, // what players see, from the id when not set like an item's name: text.optional(), - // for whatever shows it, like a container's tinted overlay + // for whatever shows it, like a layer tinted "fluid" on a full container color, }); @@ -746,6 +765,8 @@ export function item_to_json(id: string, item: ItemRegistry): ItemJson { if (item.food !== undefined) json.food = item.food; if (item.worn !== undefined) json.worn = item.worn; if (item.targets_fluids !== undefined) json.targets_fluids = item.targets_fluids; + if (item.fluid_container !== undefined) json.fluid_container = item.fluid_container; + if (item.layers !== undefined) json.layers = item.layers; if (item.name !== undefined) json.name = item.name; if (item.lore !== undefined) json.lore = item.lore; if (item.components) json.components = item.components; @@ -774,6 +795,8 @@ function item_fields(json: ItemJson): Partial { if (json.food !== undefined) item.food = json.food; if (json.worn !== undefined) item.worn = json.worn; if (json.targets_fluids !== undefined) item.targets_fluids = json.targets_fluids; + if (json.fluid_container !== undefined) item.fluid_container = json.fluid_container; + if (json.layers !== undefined) item.layers = json.layers; if (json.name !== undefined) item.name = json.name; if (json.lore !== undefined) item.lore = json.lore; if (json.components) item.components = json.components; diff --git a/common/worldgen/biome_colors.ts b/common/worldgen/biome_colors.ts index dbd12df..c9c4ec9 100644 --- a/common/worldgen/biome_colors.ts +++ b/common/worldgen/biome_colors.ts @@ -30,6 +30,11 @@ export function is_tint_color(value: unknown): value is TintColor { (typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value)); } +// a color like 0x80a755 as red, green and blue from 0 to 1, for drawing +export function color_rgb(color: number): [number, number, number] { + return [(color >> 16) / 255, ((color >> 8) & 0xff) / 255, (color & 0xff) / 255]; +} + // the color outside any biome, for items: the default grass, foliage or water color, or the fixed one export function tint_without_biome(color: TintColor) { if (color === "grass") return DEFAULT_GRASS_COLOR; diff --git a/docs/modding/entities/players.md b/docs/modding/entities/players.md index 5987ff6..9013bcd 100644 --- a/docs/modding/entities/players.md +++ b/docs/modding/entities/players.md @@ -29,6 +29,7 @@ interface Player { readonly held_item: ItemStack | undefined; give_item(id: string, count?: number, data?: unknown): void; // what doesn't fit drops at their feet + exchange_held(result: ItemStack): void; // one of the held item becomes result, see below send_message(text: string, options?: { overlay?: boolean }): void; // in chat, or above the hotbar with overlay set_worn(key: string, items: ItemStack[]): void; // what's drawn on them, see Worn Items teleport(x: number, y: number, z: number): void; @@ -63,6 +64,10 @@ interface Player { `inventory` is a live [container](../inventories/containers.md), and `held_item` a live stack: changing them changes what the player has. +`exchange_held(result)` is for an item that turns into another when used, like an empty bucket filling: one of the held +stack goes, and `result` goes straight into their hand when that was the last one, or into their inventory (at their +feet when it's full) when there are more. + `eye_position` and `look_direction` are for aiming. With [`ctx.world.raycast`](../blocks/index.md#raycasts) they find what a player is looking at, like Minecraft's `getPlayerPOVHitResult`: diff --git a/docs/modding/items/index.md b/docs/modding/items/index.md index 7aa5eee..e8f1161 100644 --- a/docs/modding/items/index.md +++ b/docs/modding/items/index.md @@ -19,6 +19,9 @@ interface ItemStack { `data` is how one stack differs from another of the same item, like the water left in a watering can or the damage on a tool. It's saved, and synced to clients as part of the container the stack is in, so client code can read it. +Two stacks of one item only merge into one when their `data` is the same, whatever order its keys are in, in an +inventory or on the ground. No data is the same as `{}`. + Stacks handed to server scripts are live: setting `count` or `data` on one changes the real stack, and a stack counted down to 0 is gone. @@ -39,22 +42,24 @@ down to 0 is gone. ## Properties -| Field | Default | Meaning | -| ----------------- | ------------------- | ------------------------------------------------------------------------------------- | -| `id` | required | The item's id. | -| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). | -| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. | -| `lore` | none | Tooltip text under the name. `\n` starts a new line. | -| `max_stack` | `64`, `1` for tools | How many fit in one slot. | -| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. | -| `places` | none | A block it places when used on a block, like seeds. | -| `tool` | none | Makes it a [tool](tools.md). | -| `food` | none | Makes it [edible](food.md). | -| `data_textures` | none | Other textures, picked by the stack's `data`, see below. | -| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture. | -| `worn` | none | How it looks worn on a player, see [below](#worn-models). | -| `targets_fluids` | `false` | Players holding it aim at fluids, like buckets and fishing rods. Others aim through. | -| `components` | none | [Item components](#item-components) and their parameters. | +| Field | Default | Meaning | +| ----------------- | ------------------- | -------------------------------------------------------------------------------------- | +| `id` | required | The item's id. | +| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). | +| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. | +| `lore` | none | Tooltip text under the name. `\n` starts a new line. | +| `max_stack` | `64`, `1` for tools | How many fit in one slot. | +| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. | +| `places` | none | A block it places when used on a block, like seeds. | +| `tool` | none | Makes it a [tool](tools.md). | +| `food` | none | Makes it [edible](food.md). | +| `data_textures` | none | Other textures, picked by the stack's `data`, see below. | +| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture. | +| `worn` | none | How it looks worn on a player, see [below](#worn-models). | +| `targets_fluids` | `false` | Players holding it aim at fluids, like buckets and fishing rods. Others aim through. | +| `fluid_container` | none | Makes it hold a fluid, like a bucket, see [Fluids](../resources/fluids.md#containers). | +| `layers` | none | Textures drawn over its own, each in a color, see [below](#layers). | +| `components` | none | [Item components](#item-components) and their parameters. | ### Textures From Data @@ -67,6 +72,29 @@ is out: A stack whose `data.cast` is truthy uses `bworld:fishing_rod_cast`. When several keys are, the first listed wins. +### Layers + +`layers` are textures drawn over the item's own, in order, like the fluid in a bucket or the trim on armor. Each can be +drawn in a color, with `tint`: + +```json +"layers": [ + { "texture": "copper_tools:jar_fluid", "tint": "fluid" }, + { "texture": "copper_tools:jar_label", "tint": "#c42d39" } +] +``` + +| `tint` | The layer's drawn in | +| --------------------------------- | ---------------------------------------------------------------------------------------------------- | +| none | Its own colors. | +| a color, like `"#c42d39"` | That color. | +| `"grass"`, `"foliage"`, `"water"` | That color outside any biome, like a block's [tint](../blocks/index.md#tinting) in its item. | +| `"fluid"` | The color of the fluid a [fluid container](../resources/fluids.md#containers) holds. Not when empty. | + +A tint multiplies the texture's colors, so a tinted layer is painted in light grays. A layer whose tint has no color for +a stack, like `"fluid"` on an empty container, isn't drawn. Layers are drawn on the front and back of a flat item, so +they should stay inside the item's own shape, and an item drawn with a `model` can't have them. + ### Worn Models `worn` says how an item looks on a player who wears it, like Bedrock's attachables. A server script says what a player @@ -218,8 +246,11 @@ const { item, given } = ctx.world.use_item_on({ id: "bworld:cobblestone", count: ctx.items.exists("bworld:carrot"); // true ctx.items.ids(); // every item, in load order ctx.items.max_stack("bworld:wood_pickaxe"); // 1 +ctx.items.max_stack(id, data); // the same for a stack with this data, fewer for a full fluid container +ctx.items.fluid_capacity("bworld:bucket"); // how much a fluid container holds full, or undefined ctx.items.tool("bworld:wood_pickaxe"); // "pickaxe", or undefined for items that aren't tools ctx.items.sell_value("bworld:copper_coin"); // 1, or undefined for items without a base_sell_value player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet +player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this ``` diff --git a/docs/modding/resources/fluids.md b/docs/modding/resources/fluids.md index b6e1d4f..4d49d7d 100644 --- a/docs/modding/resources/fluids.md +++ b/docs/modding/resources/fluids.md @@ -88,3 +88,46 @@ ctx.fluids.name(birch); // "Birch Log Syrup" ctx.fluids.color(birch); // "#d9a441" ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is different ``` + +## Containers + +An item with `fluid_container` holds one fluid, full or empty, like a bucket or a bottle: + +```json +{ + "format_version": 1, + "item": { + "id": "copper_tools:jar", + "texture": "copper_tools:jar", + "max_stack": 16, + "fluid_container": { "capacity": 250, "full_max_stack": 4 }, + "layers": [{ "texture": "copper_tools:jar_fluid", "tint": "fluid" }] + } +} +``` + +| Field | Required | What it does | +| ---------------- | -------- | ---------------------------------------------------------------------- | +| `capacity` | yes | How much a full one holds, in mB. A bucket is 1000. | +| `full_max_stack` | no | How many full ones fit in a slot. The item's `max_stack` when not set. | + +A full one's stack data is `{ "fluid": }`, like +`{ "fluid": { "id": "copper_tools:syrup", "data": { ... } } }`, and one without a `fluid` is empty. It's only ever full +or empty, so there's no amount: a full one holds `capacity`. Stacks only merge when their data is the same, so jars of +maple and birch syrup don't stack, and an empty jar doesn't stack with a full one. + +What's in it is drawn with a [layer](../items/index.md#layers) tinted `"fluid"`, which is drawn in the fluid's +[color](#rules) while it's full and not at all while it's empty. Its texture is the size of the item's, opaque only +where the fluid shows, and light gray, since the color multiplies it: white comes out as the fluid's own color. Its +tooltip says what's in it and how much, like "Birch Log Syrup, 250 mB". + +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: + +```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" } } }); +} +``` diff --git a/server/game/entity/item_entity.ts b/server/game/entity/item_entity.ts index 382700d..d62733d 100644 --- a/server/game/entity/item_entity.ts +++ b/server/game/entity/item_entity.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -import { type ItemData, ItemStack } from "$/common/inventory.ts"; +import { type ItemData, ItemStack, same_stack } from "$/common/inventory.ts"; import type { EntityInfo } from "$/common/protocol.ts"; import { TICK_DELTA } from "$/common/constants.ts"; import { physics } from "$/common/physics.ts"; @@ -126,7 +126,7 @@ export class ItemEntity extends Entity { can_merge_with(other: ItemEntity) { return other !== this && !other.removed && other.item.type_id === this.item.type_id && this.item.amount < this.item.max_amount && other.item.amount < other.item.max_amount && - (other.item.data === this.item.data || JSON.stringify(other.item.data) === JSON.stringify(this.item.data)); + same_stack(other.item, this.item); } // the smaller stack goes into the bigger one, like minecraft's ItemEntity.tryToMerge diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 0d6c9fb..1b2d433 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -502,8 +502,9 @@ export class GameServer { let left = count; while (left > 0) { const stack = new ItemStack(id); - stack.amount = Math.min(left, stack.max_amount); + // first, a full fluid container stacks to fewer if (data !== undefined) stack.data = structuredClone(data); + stack.amount = Math.min(left, stack.max_amount); left -= stack.amount; this.give_stack(player, stack); } diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 07c8256..fe22036 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -4,7 +4,7 @@ // runs mods' server scripts: builds each one's ServerContext and keeps what they register. // see docs/modding/. parts not built yet throw when used, saying so import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "$/common/everything_registry.ts"; -import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts"; +import { Container as EngineContainer, ItemStack as EngineItemStack, max_stack } from "$/common/inventory.ts"; import { block_states, fluid_block, @@ -903,10 +903,14 @@ export class ModRuntime { items: { exists: (id) => EverythingRegistry.get("items", id) !== undefined, ids: () => EverythingRegistry.entries("items").map(([id]) => id), - max_stack: (id) => { + max_stack: (id, data) => { + if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); + return max_stack(id, data); + }, + fluid_capacity: (id) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`unknown item ${id}`); - return item.max_stack ?? (item.tool ? 1 : 64); + return item.fluid_container?.capacity; }, tool: (id) => { const item = EverythingRegistry.get("items", id); @@ -1401,6 +1405,14 @@ function player_api(game: GameServer, player: ServerPlayer): Player { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); game.give(player, id, count, data); }, + exchange_held(result) { + const held = player.held_item; + if (!held) throw new Error("exchange_held needs something in the hand"); + const stack = new_stack(result); + held.amount -= 1; + if (held.amount <= 0) player.inventory.set_item(player.selected_slot, stack); + else game.give_stack(player, stack); + }, send_message(text, options) { game.send_chat(player, String(text), options?.overlay === true); }, diff --git a/tests/fluid_container_test.ts b/tests/fluid_container_test.ts new file mode 100644 index 0000000..8612af7 --- /dev/null +++ b/tests/fluid_container_test.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// items that hold one fluid, full or empty: how many stack, what they look like, and turning the held one into another +import { assertEquals } from "@std/assert"; +import { item_tooltip } from "$/client/gui/tooltip.ts"; +import { item_layers } from "$/client/rendering/item_renderer.ts"; +import { ItemStack } from "$/common/inventory.ts"; +import { copy_dir, test_game } from "./helpers.ts"; + +const JAR = "testjars:jar"; +const FULL = { fluid: { id: "testjars:syrup", data: { tree: "maple" } } }; + +// mods/bworld, and testjars: syrup, and a jar of 250 mB that stacks to 16 empty and 4 full, drawn with the syrup in it +// and a red label +async function setup() { + const dir = Deno.makeTempDirSync({ prefix: "bworld_jars_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + const write = (path: string, json: unknown) => { + Deno.mkdirSync(`${dir}/testjars/${path.split("/").slice(0, -1).join("/")}`, { recursive: true }); + Deno.writeTextFileSync(`${dir}/testjars/${path}`, JSON.stringify(json)); + }; + write("manifest.json", { format_version: 1, id: "testjars", name: "Test Jars", version: "1.0.0" }); + write("fluids/syrup.json", { format_version: 1, fluid: { id: "testjars:syrup", color: "#a0522d" } }); + write("items/jar.json", { + format_version: 1, + item: { + id: JAR, + texture: "engine:missing", + max_stack: 16, + fluid_container: { capacity: 250, full_max_stack: 4 }, + layers: [{ texture: "engine:break_0", tint: "fluid" }, { texture: "engine:break_1", tint: "#ff0000" }], + }, + }); + const t = await test_game(dir); + Deno.removeSync(dir, { recursive: true }); + t.join(1, "alice"); + const player = t.game.players()[0]; + return { ...t, player, api: t.game.mods.player(player) }; +} + +const slots = (t: Awaited>) => + t.player.inventory.to_data().flatMap((item, slot) => item ? [[slot, item.count, item.data !== undefined]] : []); + +Deno.test("a full fluid container stacks to its full_max_stack, and an empty one to the item's max_stack", async () => { + const t = await setup(); + t.api.give_item(JAR, 20); + t.api.give_item(JAR, 6, FULL); + assertEquals(slots(t), [[0, 16, false], [1, 4, false], [2, 4, true], [3, 2, true]]); + // the fluid's name, from its id since it has none, and how much there is + const tooltip = (slot: number) => item_tooltip(t.player.inventory.get_item(slot)!).map((line) => line.text); + assertEquals(tooltip(2).slice(0, 2), ["Jar", "Syrup, 250 mB"]); + assertEquals(tooltip(0), ["Jar"]); +}); + +Deno.test("a layer tinted fluid is drawn in the fluid's color while there's one, and others always", async () => { + await setup(); + const jar = (data?: unknown) => { + const stack = new ItemStack(JAR); + stack.data = data; + return item_layers(stack); + }; + const red = { texture: "engine:break_1", color: [1, 0, 0] }; + assertEquals(jar(), [red]); + assertEquals(jar(FULL), [{ texture: "engine:break_0", color: [0xa0 / 255, 0x52 / 255, 0x2d / 255] }, red]); +}); + +Deno.test("exchange_held puts the result in the hand from a stack of one, and in the inventory from more", async () => { + const t = await setup(); + t.api.give_item(JAR, 3); + t.api.exchange_held({ id: JAR, count: 1, data: FULL }); + assertEquals(slots(t), [[0, 2, false], [1, 1, true]]); + + t.player.inventory.set_item(0, undefined); + t.api.give_item(JAR, 1); + t.api.exchange_held({ id: JAR, count: 1, data: FULL }); + // the filled one in the hand, the one filled before still beside it + assertEquals(slots(t), [[0, 1, true], [1, 1, true]]); +}); diff --git a/tests/fluid_registry_test.ts b/tests/fluid_registry_test.ts index 3902523..58e39e0 100644 --- a/tests/fluid_registry_test.ts +++ b/tests/fluid_registry_test.ts @@ -8,7 +8,8 @@ import type { ModListing } from "$/common/mod_loader.ts"; import type { FluidApi } from "$/common/mod_api/shared.ts"; import { read_bmod } from "$/common/bmod.ts"; import { register_mod_data } from "$/common/mod_loader.ts"; -import { fluid_rules, load_client_mods } from "$/client/mods.ts"; +import { load_client_mods } from "$/client/mods.ts"; +import { fluid_rules } from "$/client/fluid_rules.ts"; import { load_and_check } from "$/tools/check_mods.ts"; import { pack_mod } from "$/tools/pack_mod.ts"; import { copy_dir, test_game } from "./helpers.ts"; diff --git a/tests/importer_test.ts b/tests/importer_test.ts index 2e08744..c64d9fa 100644 --- a/tests/importer_test.ts +++ b/tests/importer_test.ts @@ -372,7 +372,7 @@ Deno.test("cubes stay solid, and models that can't be drawn are placeholders", ( assertStringIncludes(report.warnings[0].warning, "placeholder"); }); -Deno.test("items that aren't a block's get their sprite as their texture, or their model when java draws them in 3D", () => { +Deno.test("items that aren't a block's get their sprite as their texture and layers, or their model when java draws them in 3D", () => { const output = Deno.makeTempDirSync(); const report = import_items( assets({ @@ -380,6 +380,10 @@ Deno.test("items that aren't a block's get their sprite as their texture, or the "models/block/gear": GEAR, "models/item/gear": { parent: "gears:block/gear" }, "models/item/sheet": { parent: "item/generated", textures: { layer0: "gears:item/sheet" } }, + "models/item/trimmed_sheet": { + parent: "item/generated", + textures: { layer0: "gears:item/sheet", layer1: "gears:item/trim" }, + }, "models/item/wrench": { parent: "gears:item/wrench/item" }, "models/item/wrench/item": { textures: { handle: "gears:item/wrench" }, elements: GEAR.elements }, }), @@ -387,10 +391,14 @@ Deno.test("items that aren't a block's get their sprite as their texture, or the ); assertEquals(report.errors, []); // the gear's item comes with its block, and the wrench's model parts aren't items - assertEquals(report.written.map(({ id }) => id).sort(), ["gears:sheet", "gears:wrench"]); + assertEquals(report.written.map(({ id }) => id).sort(), ["gears:sheet", "gears:trimmed_sheet", "gears:wrench"]); const sheet = JSON.parse(Deno.readTextFileSync(`${output}/sheet.json`)).item; assertEquals(sheet, { id: "gears:sheet", texture: "gears:item_sheet" }); assertEquals(validate_item(sheet), []); + // java's other layers are drawn over the first + const trimmed = JSON.parse(Deno.readTextFileSync(`${output}/trimmed_sheet.json`)).item; + assertEquals(trimmed.layers, [{ texture: "gears:item_trim" }]); + assertEquals(validate_item(trimmed), []); // the model kind writes its model, and its texture is its model's const wrench = JSON.parse(Deno.readTextFileSync(`${output}/wrench.json`)).item; assertEquals(wrench, { id: "gears:wrench", texture: "gears:item_wrench", model: "gears:item_wrench" }); diff --git a/tests/stack_data_test.ts b/tests/stack_data_test.ts new file mode 100644 index 0000000..5e53a51 --- /dev/null +++ b/tests/stack_data_test.ts @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// stacks of one item only merge when their data is the same, whatever order its keys are in +import { assertEquals } from "@std/assert"; +import { click_slot, Container, type Cursor, ItemStack, LEFT_CLICK } from "$/common/inventory.ts"; +import { test_game } from "./helpers.ts"; + +const coal = (count: number, data?: unknown) => { + const stack = new ItemStack("bworld:coal", count); + stack.data = data; + return stack; +}; + +Deno.test("stacks with different data don't merge in an inventory, and ones whose data only differs in key order do", async () => { + await test_game("mods"); + const container = new Container(2); + container.add_item(coal(3, { mine: "north", grade: 1 })); + container.add_item(coal(2, { mine: "south" })); + assertEquals(container.to_data().map((item) => item?.count), [3, 2]); + assertEquals(container.add_item(coal(4, { mine: "east" })), 4, "there's no slot left for a third kind"); + container.add_item(coal(1, { grade: 1, mine: "north" })); + assertEquals(container.get_item(0)?.amount, 4); + + // clicking a stack onto one with other data swaps them instead + const cursor: Cursor = { item: coal(5, { mine: "east" }) }; + click_slot(container, 1, cursor, LEFT_CLICK); + assertEquals([container.get_item(1)?.amount, cursor.item?.amount], [5, 2]); + cursor.item = coal(5, { mine: "east" }); + click_slot(container, 1, cursor, LEFT_CLICK); + assertEquals([container.get_item(1)?.amount, cursor.item], [10, undefined]); + + // no data is the same as {} + const plain = new Container(1); + plain.add_item(coal(1)); + plain.add_item(coal(1, {})); + assertEquals(plain.get_item(0)?.amount, 2); +}); + +Deno.test("stacks with different data don't merge on the ground, and ones whose data only differs in key order do", async () => { + const { game, join } = await test_game("mods"); + // items only move near a player + join(1, "alice"); + for (let x = -2; x <= 2; x++) { + for (let z = -2; z <= 2; z++) game.set_block(x, 99, z, "bworld:stone"); + } + game.spawn_item(0.5, 100, 0.5, coal(1, { mine: "north", grade: 1 })); + game.spawn_item(0.5, 100, 0.5, coal(1, { mine: "south" })); + game.spawn_item(0.5, 100, 0.5, coal(1, { grade: 1, mine: "north" })); + for (let i = 0; i < 4; i++) game.tick(); + const counts = game.item_entities().map(( + entity, + ) => [(entity.item.data as { mine: string }).mine, entity.item.amount]); + assertEquals(counts.sort(), [["north", 2], ["south", 1]]); +}); diff --git a/tools/importer/items.ts b/tools/importer/items.ts index 9eb0ccd..d07a20a 100644 --- a/tools/importer/items.ts +++ b/tools/importer/items.ts @@ -3,8 +3,8 @@ // java item models (assets//models/item/*.json) to bworld's items/, for the items that aren't a block's: a // block's item comes with the block (see blocks.ts). java says an item is a flat sprite with item/generated and its -// layer0 texture, which is what a bworld item is. one java draws in 3D (a wrench) is drawn with its model, which the -// model kind writes, and gets its model's particle texture as its texture +// layer0 texture, which is what a bworld item is, and its layer1 and on are its layers. one java draws in 3D (a wrench) +// is drawn with its model, which the model kind writes, and gets its model's particle texture as its texture import { join } from "@std/path"; import { FORMAT_VERSION } from "$/common/mod_data.ts"; import { made_by, model_source } from "./models.ts"; @@ -61,10 +61,12 @@ export function import_items(input: string, options: ImportOptions = {}): Import }; let texture: string | undefined; let model: string | undefined; + const layers: { texture: string }[] = []; if (made_by(location, read)?.startsWith("an item sprite")) { texture = resolve(textures.layer0); - if (textures.layer1 !== undefined) { - report.warnings.push({ location, warning: "only the first layer of sprites with several was kept" }); + for (let i = 1; textures[`layer${i}`] !== undefined; i++) { + const layer = resolve(textures[`layer${i}`]); + if (layer !== undefined) layers.push({ texture: to_id(layer, remaps.textures) }); } } else { texture = resolve(textures.particle) ?? Object.values(textures).map(resolve).find((t) => t !== undefined); @@ -81,12 +83,13 @@ export function import_items(input: string, options: ImportOptions = {}): Import continue; } const texture_id = to_id(texture, remaps.textures); - if (!is_valid_id(id) || !is_valid_id(texture_id)) { - report.errors.push({ location, problems: [`its id ${id} or texture ${texture_id} isn't a valid id`] }); + if (!is_valid_id(id) || ![texture_id, ...layers.map((layer) => layer.texture)].every(is_valid_id)) { + report.errors.push({ location, problems: [`its id ${id} or one of its textures isn't a valid id`] }); continue; } if (!claim(id, location)) continue; - const json = { format_version: FORMAT_VERSION, item: { id, texture: texture_id, ...(model ? { model } : {}) } }; + const item = { id, texture: texture_id, ...(model ? { model } : {}), ...(layers.length ? { layers } : {}) }; + const json = { format_version: FORMAT_VERSION, item }; report.written.push({ location, id,