Compare commits

..
3 Commits
Author SHA1 Message Date
paula e5221ba681 Juice sell price 2026-10-26 19:32:46 -03:00
paula e729b92d20 Keg model 2026-10-25 22:09:19 -03:00
paula f46058f9b5 Some optimization 2026-10-25 21:31:32 -03:00
27 changed files with 378 additions and 72 deletions
+1
View File
@@ -93,6 +93,7 @@ export class DebugOverlay {
text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`); text(`chunks: ${level.chunks.size} loaded, ${meshed} meshed, ${level_renderer.visible_chunks} in view`);
text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`); text(` ${level.dirty_count} waiting to mesh, ${level.meshes_in_flight} meshing`);
text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`); text(` meshes: ${(bytes / 1024 / 1024).toFixed(1)} MB`);
text(`entities: ${level.entities.size} loaded, ${level_renderer.drawn_entities} in view`);
separator(); separator();
text("switches"); text("switches");
+4 -3
View File
@@ -4,7 +4,7 @@
// 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 // 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 // its lore
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { contained_fluid, type ItemStack } from "$/common/inventory.ts"; import { contained_fluid, type ItemStack, sell_value } from "$/common/inventory.ts";
import { display_name } from "$/common/utils.ts"; import { display_name } from "$/common/utils.ts";
import { fluid_rules } from "$/client/fluid_rules.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 { canvas, draw_text, draw_texture_region, measure_text, type Texture } from "$/client/renderer/mod.ts";
@@ -49,8 +49,9 @@ export function item_tooltip(item: ItemStack): TooltipLine[] {
if (info?.food) { if (info?.food) {
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR }); lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
} }
if (info?.base_sell_value !== undefined) { const value = sell_value(item.type_id, item.data, fluid_rules);
lines.push({ icon: VALUE_ICON, text: `${info.base_sell_value}`, color: VALUE_COLOR }); if (value !== undefined) {
lines.push({ icon: VALUE_ICON, text: `${value}`, color: VALUE_COLOR });
} }
const static_lore = info?.lore; const static_lore = info?.lore;
for (const lore of [static_lore, item.lore]) { for (const lore of [static_lore, item.lore]) {
+11 -7
View File
@@ -367,17 +367,21 @@ function push_sprite(
) { ) {
const region = get_sprite_region(texture_id); const region = get_sprite_region(texture_id);
for (const quad of quads) { for (const quad of quads) {
for (const i of [0, 1, 2, 0, 2, 3]) { // each corner transformed once, though corners 0 and 2 are in both triangles
const [cx, cy, cz] = quad.corners[i]; const points = quad.corners.map(([cx, cy, cz]) => transform(cx, cy, cz + Math.sign(cz) * gap));
const [px, py, pz] = transform(cx, cy, cz + Math.sign(cz) * gap); for (const i of QUAD_CORNERS) {
const [pu, pv] = quad.uvs[i]; const point = points[i];
const u = (region.x + pu) / atlas.width; const uv = quad.uvs[i];
const v = (region.y + pv) / atlas.height; const u = (region.x + uv[0]) / atlas.width;
vertex(px, py, pz, u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1); const v = (region.y + uv[1]) / atlas.height;
vertex(point[0], point[1], point[2], u, v, quad.shade * r, quad.shade * g, quad.shade * b, 1);
} }
} }
} }
// a quad's corners as two triangles
const QUAD_CORNERS = [0, 1, 2, 0, 2, 3];
// the layers drawn over a flat item's texture (see ItemLayer), each in its tint's color, without the ones whose tint // 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 // has no color for this stack
export function item_layers(item: ItemStack): { texture: string; color: Vec3 }[] { export function item_layers(item: ItemStack): { texture: string; color: Vec3 }[] {
+34 -4
View File
@@ -47,10 +47,17 @@ export class LevelRenderer {
// what to draw, switched off in the f3 performance window to see what each costs // what to draw, switched off in the f3 performance window to see what each costs
draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true }; draw = { solid: true, cutout: true, translucent: true, entities: true, visuals: true };
// entities drawn this frame, for the f3 performance window
#drawn_entities = 0;
get visible_chunks() { get visible_chunks() {
return this.#visible.length; return this.#visible.length;
} }
get drawn_entities() {
return this.#drawn_entities;
}
// solid and cutout terrain, drawn before entities // solid and cutout terrain, drawn before entities
render_opaque(level: ClientLevel, camera: Camera) { render_opaque(level: ClientLevel, camera: Camera) {
profiler.section("chunk upkeep", () => this.#find_visible(level, camera)); profiler.section("chunk upkeep", () => this.#find_visible(level, camera));
@@ -116,15 +123,18 @@ export class LevelRenderer {
return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE); return this.frustum.intersects_box(x, chunk.min_y, z, x + CHUNK_SIZE, chunk.max_y, z + CHUNK_SIZE);
} }
// every entity but the one the camera is in // every entity in view but the one the camera is in
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) { render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
this.#drawn_entities = 0;
if (!this.draw.entities) return; if (!this.draw.entities) return;
flush_batch(); flush_batch();
const default_skin = AssetManager.instance.get<Texture>("bworld:skin"); const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
// what they wear is drawn with the atlas, after every skin // what they wear is drawn with the atlas, after every skin
const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = []; const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = [];
for (const entity of level.entities.values()) { for (const entity of level.entities.values()) {
if (entity !== camera_entity && entity instanceof RemotePlayer) { if (
entity !== camera_entity && entity instanceof RemotePlayer && this.#entity_in_view(entity, partial_tick)
) {
const skin = entity.skin ?? default_skin; const skin = entity.skin ?? default_skin;
use_texture(skin.tex); use_texture(skin.tex);
const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined); const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined);
@@ -138,9 +148,9 @@ export class LevelRenderer {
set_current_texture(level.image.tex); set_current_texture(level.image.tex);
for (const { player, pose, tint } of posed) render_worn(player, pose, tint); for (const { player, pose, tint } of posed) render_worn(player, pose, tint);
for (const entity of level.entities.values()) { for (const entity of level.entities.values()) {
if (entity instanceof ItemEntity) { if (entity instanceof ItemEntity && this.#entity_in_view(entity, partial_tick)) {
render_item_entity(entity, partial_tick); render_item_entity(entity, partial_tick);
} else if (entity instanceof RemoteEntity) { } else if (entity instanceof RemoteEntity && this.#entity_in_view(entity, partial_tick)) {
render_mod_entity(entity, camera, partial_tick); render_mod_entity(entity, camera, partial_tick);
} }
} }
@@ -148,6 +158,23 @@ export class LevelRenderer {
flush_batch(); flush_batch();
} }
// whether an entity's box, grown by ENTITY_CULL_MARGIN, is in view. entities are drawn on the cpu every frame, so
// the ones out of view are skipped
#entity_in_view(entity: Entity, partial_tick: number) {
const { x, y, z } = entity.render_position(partial_tick);
const half = entity.width / 2 + ENTITY_CULL_MARGIN;
const in_view = this.frustum.intersects_box(
x - half,
y - ENTITY_CULL_MARGIN,
z - half,
x + half,
y + entity.height + ENTITY_CULL_MARGIN,
z + half,
);
if (in_view) this.#drawn_entities += 1;
return in_view;
}
// blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first // blocks drawn with code, see client/rendering/visuals.ts. the ones in chunks in view get their on_frame first
render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) { render_visuals(level: ClientLevel, camera: Camera, partial_tick: number) {
if (!this.draw.visuals) return; if (!this.draw.visuals) return;
@@ -224,6 +251,9 @@ export class LevelRenderer {
#baked = new Map<number, BakedQuad[]>(); #baked = new Map<number, BakedQuad[]>();
} }
// how far models can stick out of their entity's box, like a swinging arm or a dropped item bobbing
const ENTITY_CULL_MARGIN = 0.5;
// minecraft's outline is black at 40% // minecraft's outline is black at 40%
const OUTLINE_COLOR = [0, 0, 0, 0.4] as const; const OUTLINE_COLOR = [0, 0, 0, 0.4] as const;
// half the line's width for each block it is away from the camera, about a pixel on a 1080p screen // half the line's width for each block it is away from the camera, about a pixel on a 1080p screen
+15 -9
View File
@@ -63,6 +63,8 @@ const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: num
shade: 0.8, shade: 0.8,
}, },
]; ];
// a face's corners as two triangles
const QUAD_CORNERS = [0, 1, 2, 0, 2, 3];
// how a player is posed this frame, for drawing them and what they wear // how a player is posed this frame, for drawing them and what they wear
export function player_pose(player: Player, partial_tick: number): PlayerPose { export function player_pose(player: Player, partial_tick: number): PlayerPose {
@@ -116,20 +118,24 @@ export function push_box(
emit: VertexSink = push_vertex, emit: VertexSink = push_vertex,
) { ) {
const [w, h, d] = size; const [w, h, d] = size;
// the box's 8 corners, transformed once each rather than once per vertex. indexed by x * 4 + y * 2 + z, 0 for
// the low end and 1 for the high one
const points: Vec3[] = [];
for (let i = 0; i < 8; i++) {
points.push(transform(i & 4 ? high[0] : low[0], i & 2 ? high[1] : low[1], i & 1 ? high[2] : low[2]));
}
for (const face of FACES) { for (const face of FACES) {
const [rx, ry, rw, rh] = face.rect(w, h, d); const [rx, ry, rw, rh] = face.rect(w, h, d);
const [u0, v0] = to_uv(u + rx + UV_INSET, v + ry + UV_INSET); const [u0, v0] = to_uv(u + rx + UV_INSET, v + ry + UV_INSET);
const [u1, v1] = to_uv(u + rx + rw - UV_INSET, v + ry + rh - UV_INSET); const [u1, v1] = to_uv(u + rx + rw - UV_INSET, v + ry + rh - UV_INSET);
const [r, g, b] = tint.map((c) => c * face.shade); const r = tint[0] * face.shade;
const g = tint[1] * face.shade;
const b = tint[2] * face.shade;
for (const i of [0, 1, 2, 0, 2, 3]) { for (const i of QUAD_CORNERS) {
const [cx, cy, cz, cu, cv] = face.corners[i]; const corner = face.corners[i];
const [px, py, pz] = transform( const point = points[corner[0] * 4 + corner[1] * 2 + corner[2]];
cx ? high[0] : low[0], emit(point[0], point[1], point[2], corner[3] ? u1 : u0, corner[4] ? v1 : v0, r, g, b, 1);
cy ? high[1] : low[1],
cz ? high[2] : low[2],
);
emit(px, py, pz, cu ? u1 : u0, cv ? v1 : v0, r, g, b, 1);
} }
} }
} }
+31 -5
View File
@@ -97,7 +97,7 @@ export function draw_item(item: ItemStack, x: number, y: number, show_count = it
const model = item_model_of(item); const model = item_model_of(item);
const block_info = item_block(item); const block_info = item_block(item);
if (model) { if (model) {
draw_item_model(model, icon_matrix(x, y, model.display.gui)); draw_item_model(model, x, y);
} else if (block_info) { } else if (block_info) {
draw_item_block(block_info, x, y); draw_item_block(block_info, x, y);
} else { } else {
@@ -177,10 +177,36 @@ function icon_matrix(x: number, y: number, gui?: DisplayTransform): mat4 {
return mat4.fromValues(size, -size / 2, -1, 0, 0, -size, 1, 0, -size, -size / 2, -1, 0, cx, cy + size * 1.5, 0, 1); return mat4.fromValues(size, -size / 2, -1, 0, 0, -size, 1, 0, -size, -size / 2, -1, 0, cx, cy + size * 1.5, 0, 1);
} }
// each model's icon in a slot at 0, 0, as x y u v r g b per vertex. a slot's place only moves the icon (see
// icon_matrix), so it's worked out once per model and moved to each slot, rather than every slot every frame
const model_icons = new WeakMap<ItemModel, Float32Array>();
// an item's model in a slot: its faces that face the viewer, back to front // an item's model in a slot: its faces that face the viewer, back to front
function draw_item_model(model: ItemModel, matrix: mat4) { function draw_item_model(model: ItemModel, x: number, y: number) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures"); const atlas = AssetManager.instance.get<Texture>("bworld:textures");
use_texture(atlas.tex); use_texture(atlas.tex);
let icon = model_icons.get(model);
if (!icon) {
icon = model_icon(model, atlas);
model_icons.set(model, icon);
}
for (let i = 0; i < icon.length; i += 7) {
push_vertex(
x + icon[i],
y + icon[i + 1],
0,
icon[i + 2],
icon[i + 3],
icon[i + 4],
icon[i + 5],
icon[i + 6],
1,
);
}
}
function model_icon(model: ItemModel, atlas: Texture): Float32Array {
const matrix = icon_matrix(0, 0, model.display.gui);
// a mirroring matrix (like the y flip to the screen's y down) turns which way a face's corners go round // a mirroring matrix (like the y flip to the screen's y down) turns which way a face's corners go round
const flip = Math.sign(mat4.determinant(matrix)); const flip = Math.sign(mat4.determinant(matrix));
const visible = model.quads const visible = model.quads
@@ -197,24 +223,24 @@ function draw_item_model(model: ItemModel, matrix: mat4) {
.filter(({ facing }) => facing > 1e-6) .filter(({ facing }) => facing > 1e-6)
.sort((a, b) => a.depth - b.depth); .sort((a, b) => a.depth - b.depth);
const vertices: number[] = [];
for (const { quad, corners } of visible) { for (const { quad, corners } of visible) {
const region = get_sprite_region(quad.texture); const region = get_sprite_region(quad.texture);
const [r, g, b] = model.block ? item_tint(model.block, quad.variables) : [1, 1, 1]; const [r, g, b] = model.block ? item_tint(model.block, quad.variables) : [1, 1, 1];
const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1; const shade = quad.shade ? ITEM_FACE_SHADE[quad.face] : 1;
for (const i of [0, 1, 2, 0, 2, 3]) { for (const i of [0, 1, 2, 0, 2, 3]) {
push_vertex( vertices.push(
corners[i][0], corners[i][0],
corners[i][1], corners[i][1],
0,
sprite_u(atlas, region, quad.uvs[i * 2]), sprite_u(atlas, region, quad.uvs[i * 2]),
sprite_v(atlas, region, quad.uvs[i * 2 + 1]), sprite_v(atlas, region, quad.uvs[i * 2 + 1]),
shade * r, shade * r,
shade * g, shade * g,
shade * b, shade * b,
1,
); );
} }
} }
return new Float32Array(vertices);
} }
function draw_item_block(block_info: BlockRegistry, x: number, y: number) { function draw_item_block(block_info: BlockRegistry, x: number, y: number) {
+17 -8
View File
@@ -1,9 +1,9 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name and // fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name,
// color a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips and a // color and value a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips
// client's drawing agree // and a client's drawing agree
import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts"; import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts";
import { EverythingRegistry } from "./everything_registry.ts"; import { EverythingRegistry } from "./everything_registry.ts";
import type { FluidJson } from "./mod_data.ts"; import type { FluidJson } from "./mod_data.ts";
@@ -25,16 +25,25 @@ export class FluidRules {
name(fluid: FluidVariant): string { name(fluid: FluidVariant): string {
const json = known_fluid(fluid.id); const json = known_fluid(fluid.id);
const name = this.#ask(fluid, "name", "a name", (value) => typeof value === "string" && value.length > 0); const valid = (value: unknown): value is string => typeof value === "string" && value.length > 0;
const name = this.#ask(fluid, "name", "a name", valid);
return name ?? json.name ?? name_from_id(fluid.id); return name ?? json.name ?? name_from_id(fluid.id);
} }
color(fluid: FluidVariant): string { color(fluid: FluidVariant): string {
const json = known_fluid(fluid.id); const json = known_fluid(fluid.id);
const valid = (value: unknown) => color_schema.safeParse(value).success; const valid = (value: unknown): value is string => color_schema.safeParse(value).success;
return this.#ask(fluid, "color", 'a color like "#c42d39"', valid) ?? json.color; return this.#ask(fluid, "color", 'a color like "#c42d39"', valid) ?? json.color;
} }
// what 1000 mB sells for, undefined when it can't be sold
sell_value(fluid: FluidVariant): number | undefined {
const json = known_fluid(fluid.id);
const valid = (value: unknown): value is number =>
typeof value === "number" && Number.isFinite(value) && value >= 0;
return this.#ask(fluid, "sell_value", "a number of 0 or more", valid) ?? json.base_sell_value;
}
// ctx.fluids for server and client scripts // ctx.fluids for server and client scripts
api(): FluidApi { api(): FluidApi {
return { return {
@@ -46,14 +55,14 @@ export class FluidRules {
} }
// what the fluid's rule says, or undefined when it has none, says nothing, or says something that isn't one // what the fluid's rule says, or undefined when it has none, says nothing, or says something that isn't one
#ask(fluid: FluidVariant, rule: "name" | "color", wanted: string, valid: (value: unknown) => boolean) { #ask<T>(fluid: FluidVariant, rule: keyof Rules, wanted: string, valid: (value: unknown) => value is T) {
const entry = this.#rules.get(fluid.id); const entry = this.#rules.get(fluid.id);
const fn = entry?.rules[rule]; const fn: ((data: unknown) => unknown) | undefined = entry?.rules[rule];
if (!entry || !fn) return undefined; if (!entry || !fn) return undefined;
return this.run(entry.mod, `the ${rule} rule of ${fluid.id}`, () => { return this.run(entry.mod, `the ${rule} rule of ${fluid.id}`, () => {
const value = fn.call(entry.rules, fluid.data); const value = fn.call(entry.rules, fluid.data);
if (value !== undefined && !valid(value)) throw new Error(`gave ${JSON.stringify(value)}, not ${wanted}`); if (value !== undefined && !valid(value)) throw new Error(`gave ${JSON.stringify(value)}, not ${wanted}`);
return value; return value as T | undefined;
}); });
} }
} }
+13
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import type { FluidRules } from "./fluids.ts";
import type { FluidVariant } from "./mod_api/shared.ts"; import type { FluidVariant } from "./mod_api/shared.ts";
import { is_object } from "./schema.ts"; import { is_object } from "./schema.ts";
import { same_data } from "./utils.ts"; import { same_data } from "./utils.ts";
@@ -40,6 +41,18 @@ export function contained_fluid(id: string, data?: unknown): FluidVariant | unde
return fluid as unknown as FluidVariant; return fluid as unknown as FluidVariant;
} }
// what one of a stack sells for: its item's base_sell_value, and a full fluid container's fluid on top, rounded up.
// undefined when neither has a value, so it can't be sold
export function sell_value(id: string, data: unknown, fluids: FluidRules): number | undefined {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
const fluid = contained_fluid(id, data);
const per_bucket = fluid && fluids.sell_value(fluid);
if (per_bucket === undefined) return item?.base_sell_value;
const value = per_bucket * item!.fluid_container!.capacity / 1000;
// so float error doesn't round 18.000000000000004 up to 19
return (item!.base_sell_value ?? 0) + Math.ceil(value - 1e-9);
}
export class ItemStack<T = unknown | undefined> { export class ItemStack<T = unknown | undefined> {
type_id: string; type_id: string;
amount: number; amount: number;
+3 -2
View File
@@ -538,8 +538,9 @@ export interface ItemApi {
fluid_capacity(id: Id): number | undefined; fluid_capacity(id: Id): number | undefined;
// the tool type it is, like "pickaxe" or "shovel", from the item's "tool" // the tool type it is, like "pickaxe" or "shovel", from the item's "tool"
tool(id: Id): string | undefined; 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 // what one of it sells for with this data, or undefined if it can't be sold: the item's "base_sell_value", and a full
sell_value(id: Id): number | undefined; // fluid container's fluid on top, rounded up. see docs/modding/resources/fluids.md
sell_value(id: Id, data?: unknown): number | undefined;
// the components its json lists and their params, a copy. a mod can read params of its components this way // the components its json lists and their params, a copy. a mod can read params of its components this way
// without a stack, like the curios slots do for bworld:curio_modifiers // without a stack, like the curios slots do for bworld:curio_modifiers
components(id: Id): Record<Id, unknown>; components(id: Id): Record<Id, unknown>;
+4
View File
@@ -43,6 +43,8 @@ export interface FluidRules {
name?(data: unknown): string | undefined; name?(data: unknown): string | undefined;
// a color like "#c42d39" // a color like "#c42d39"
color?(data: unknown): string | undefined; color?(data: unknown): string | undefined;
// what 1000 mB of it is worth when sold, 0 or more and not always whole
sell_value?(data: unknown): number | undefined;
} }
// the registries tags are for, see docs/modding/resources/tags.md // the registries tags are for, see docs/modding/resources/tags.md
@@ -112,6 +114,8 @@ export interface SharedContext {
name(id: Id): string; name(id: Id): string;
// the components its json lists and their params, a copy // the components its json lists and their params, a copy
components(id: Id): Record<Id, unknown>; components(id: Id): Record<Id, unknown>;
// what one sells for, from its "base_sell_value", or undefined if it can't be sold
sell_value(id: Id): number | undefined;
}; };
readonly fluids: { readonly fluids: {
// the rules of one of the mod's fluids, which the server and every client name and color it by // the rules of one of the mod's fluids, which the server and every client name and color it by
+2
View File
@@ -486,6 +486,8 @@ const fluid_schema = z.object({
color, color,
// what a box of it is drawn with, tinted by its color, like neoforge's still texture. engine:missing when not set // what a box of it is drawn with, tinted by its color, like neoforge's still texture. engine:missing when not set
texture: z.string().optional(), texture: z.string().optional(),
// what 1000 mB of it is worth when sold in a fluid container, like an item's base_sell_value
base_sell_value: z.int().min(0).optional(),
}); });
export type FluidJson = z.infer<typeof fluid_schema>; export type FluidJson = z.infer<typeof fluid_schema>;
+1
View File
@@ -98,6 +98,7 @@ export function shared_items_api(mod: string): SharedContext["items"] {
exists: (id) => EverythingRegistry.get("items", id) !== undefined, exists: (id) => EverythingRegistry.get("items", id) !== undefined,
name: (id) => (known(id), display_name(id)), name: (id) => (known(id), display_name(id)),
components: (id) => structuredClone(known(id).components ?? {}), components: (id) => structuredClone(known(id).components ?? {}),
sell_value: (id) => known(id).base_sell_value,
}; };
} }
+1 -1
View File
@@ -299,7 +299,7 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
| Component | Params | What it does | | Component | Params | What it does |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. | | `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it with a `base_sell_value` for coins. | | `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it that has a sell value for coins. |
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. | | `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. | | `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
| `bworld:stonecutter` | none | Cuts one item into another with `bworld:stonecutting` recipes, picked from a list. | | `bworld:stonecutter` | none | Cuts one item into another with `bworld:stonecutting` recipes, picked from a list. |
+4
View File
@@ -45,6 +45,10 @@ Juices from different items are different fluids, so they never share a bottle o
(`bworld:glass_bottle`, 250 mB) and buckets (`bworld:bucket`, 1000 mB) hold it, and whatever makes juice reads the (`bworld:glass_bottle`, 250 mB) and buckets (`bworld:bucket`, 1000 mB) hold it, and whatever makes juice reads the
component. component.
Juice sells for 1.2 times the items it took to make, rounded up, so it's always worth juicing something. A bottle of
juice from an item worth 30 that makes 200 mB took 1.25 of them, and sells for 45. Juice from an item without a
`base_sell_value` can't be sold.
## Hunger and Health ## Hunger and Health
Hunger and health work like Minecraft's: Hunger and health work like Minecraft's:
+1
View File
@@ -250,6 +250,7 @@ ctx.items.max_stack(id, data); // the same for a stack with this data, fewer for
ctx.items.fluid_capacity("bworld:bucket"); // how much a fluid container holds full, or undefined 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.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 ctx.items.sell_value("bworld:copper_coin"); // 1, or undefined for items without a base_sell_value
ctx.items.sell_value(id, data); // the same for a stack with this data, with a full fluid container's fluid on top
player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet 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 player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this
+23 -9
View File
@@ -17,17 +17,19 @@ here has no block, so it can't be placed.
"id": "copper_tools:maple_syrup", "id": "copper_tools:maple_syrup",
"name": "Maple Syrup", "name": "Maple Syrup",
"color": "#a0522d", "color": "#a0522d",
"texture": "bworld:water_still" "texture": "bworld:water_still",
"base_sell_value": 40
} }
} }
``` ```
| Field | Required | What it does | | Field | Required | What it does |
| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- | | ----------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `id` | yes | The fluid's id, in the mod's [namespace](../concepts/registries.md#identifiers). | | `id` | yes | The fluid's id, in the mod's [namespace](../concepts/registries.md#identifiers). |
| `name` | no | What players see. `copper_tools:maple_syrup` is "Maple Syrup" when not set, like an item's. | | `name` | no | What players see. `copper_tools:maple_syrup` is "Maple Syrup" when not set, like an item's. |
| `color` | yes | Its color, like `"#a0522d"`, for whatever shows it. | | `color` | yes | Its color, like `"#a0522d"`, for whatever shows it. |
| `texture` | no | What a [box of it](../blocks/visuals.md#fluids) is drawn with, tinted by its color, like NeoForge's still texture. See below. | | `texture` | no | What a [box of it](../blocks/visuals.md#fluids) is drawn with, tinted by its color, like NeoForge's still texture. See below. |
| `base_sell_value` | no | What 1000 mB is worth sold in a [container](#containers), a whole number of 0 or more. None when not set. |
Like a fluid container's layer, the texture is multiplied by the fluid's color, so a light gray one comes out in the Like a fluid container's layer, the texture is multiplied by the fluid's color, so a light gray one comes out in the
fluid's own color, and its alpha is how much shows through. The base game's `bworld:water_still` is such a texture, fluid's own color, and its alpha is how much shows through. The base game's `bworld:water_still` is such a texture,
@@ -46,8 +48,8 @@ a tank.
## Rules ## Rules
A fluid's name and color can depend on its data. The mod's [shared script](../concepts/sides.md#shared-scripts) gives A fluid's name, color and value can depend on its data. The mod's [shared script](../concepts/sides.md#shared-scripts)
one of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`: gives one of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`:
```ts ```ts
import type { SharedContext } from "bworld/shared"; import type { SharedContext } from "bworld/shared";
@@ -66,22 +68,29 @@ export function setup(ctx: SharedContext) {
const { tree } = (data ?? {}) as SyrupData; const { tree } = (data ?? {}) as SyrupData;
return tree === "bworld:birch_log" ? "#d9a441" : undefined; return tree === "bworld:birch_log" ? "#d9a441" : undefined;
}, },
// worth twice the logs it takes to make, 4 to a bucket
sell_value(data) {
const { tree } = (data ?? {}) as SyrupData;
const value = tree && ctx.items.sell_value(tree);
return value ? value * 4 * 2 : undefined;
},
}); });
} }
``` ```
| Rule | Returns | | Rule | Returns |
| ------------- | -------------------------------------------------------- | | ------------------ | ------------------------------------------------------------------------------------------------------- |
| `name(data)` | What players see, or `undefined` for the JSON's name. | | `name(data)` | What players see, or `undefined` for the JSON's name. |
| `color(data)` | A color like `"#d9a441"`, or `undefined` for the JSON's. | | `color(data)` | A color like `"#d9a441"`, or `undefined` for the JSON's. |
| `sell_value(data)` | What 1000 mB is worth, 0 or more and not always whole, or `undefined` for the JSON's `base_sell_value`. |
`data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something `data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something
that isn't a name or a color, is logged and the JSON's is used. A fluid has one set of rules, from its own mod, and they that isn't a name, a color or a value, is logged and the JSON's is used. A fluid has one set of rules, from its own mod,
can only be registered during `setup`. and they can only be registered during `setup`.
The rules are in the shared script because both sides need them: the server for tooltips, and clients to draw the fluid. The rules are in the shared script because both sides need them: the server for tooltips, and clients to draw the fluid.
Shared scripts have `ctx.items.exists(id)`, `ctx.items.name(id)` and `ctx.items.components(id)` for rules that read an Shared scripts have `ctx.items.exists(id)`, `ctx.items.name(id)`, `ctx.items.components(id)` and
item, like syrup named after its tree. `ctx.items.sell_value(id)` for rules that read an item, like syrup named after its tree.
## Using Fluids ## Using Fluids
@@ -127,6 +136,11 @@ What's in it is drawn with a [layer](../items/index.md#layers) tinted `"fluid"`,
where the fluid shows, and light gray, since the color multiplies it: white comes out as the fluid's own color. Its 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". tooltip says what's in it and how much, like "Birch Log Syrup, 250 mB".
A full one sells for its own `base_sell_value` and what its fluid is worth on top: the fluid's value for 1000 mB times
how much it holds, rounded up to a whole number. A jar of maple syrup worth 40 a bucket sells for 10, and the jar's own
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 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: held stack into the full one, and `ctx.items.fluid_capacity(id)` says how much it takes:
+30
View File
@@ -0,0 +1,30 @@
{
"format_version": 1,
"block": {
"id": "bworld:keg",
"name": "Keg",
"model": "bworld:keg",
"textures": {},
"item_model": "bworld:keg",
"render_layer": "cutout",
"states": [
{
"name": "facing",
"bits": 2,
"default": 0
}
],
"variants": {
"facing=1": { "y": 90 },
"facing=2": { "y": 180 },
"facing=3": { "y": 270 }
},
"mining": {
"toughness": 2
},
"drops": "bworld:keg",
"interactive": true,
"components": {
}
}
}
+74
View File
@@ -0,0 +1,74 @@
{
"format_version": 1,
"model": {
"id": "bworld:keg",
"textures": {
"1": "bworld:keg_side",
"2": "bworld:keg_front",
"3": "bworld:keg_back",
"particle": "bworld:keg_side"
},
"elements": [
{
"from": [13, 0, 13],
"to": [16, 2, 16],
"faces": {
"north": { "texture": "#3", "uv": [0, 0, 3, 2] },
"east": { "texture": "#3", "uv": [0, 0, 3, 2] },
"south": { "texture": "#3", "uv": [0, 0, 3, 2] },
"west": { "texture": "#3", "uv": [0, 0, 3, 2] },
"top": { "texture": "#1", "uv": [0, 0, 3, 3] },
"bottom": { "texture": "#3", "uv": [0, 0, 3, 3] }
}
},
{
"from": [0, 0, 13],
"to": [3, 2, 16],
"faces": {
"north": { "texture": "#3", "uv": [0, 0, 3, 2] },
"east": { "texture": "#3", "uv": [0, 0, 3, 2] },
"south": { "texture": "#3", "uv": [0, 0, 3, 2] },
"west": { "texture": "#3", "uv": [0, 0, 3, 2] },
"top": { "texture": "#1", "uv": [0, 0, 3, 3] },
"bottom": { "texture": "#3", "uv": [0, 0, 3, 3] }
}
},
{
"from": [0, 0, 0],
"to": [3, 2, 3],
"faces": {
"north": { "texture": "#3", "uv": [0, 0, 3, 2] },
"east": { "texture": "#3", "uv": [0, 0, 3, 2] },
"south": { "texture": "#3", "uv": [0, 0, 3, 2] },
"west": { "texture": "#3", "uv": [0, 0, 3, 2] },
"top": { "texture": "#1", "uv": [0, 0, 3, 3] },
"bottom": { "texture": "#3", "uv": [0, 0, 3, 3] }
}
},
{
"from": [13, 0, 0],
"to": [16, 2, 3],
"faces": {
"north": { "texture": "#3", "uv": [0, 0, 3, 2] },
"east": { "texture": "#3", "uv": [0, 0, 3, 2] },
"south": { "texture": "#3", "uv": [0, 0, 3, 2] },
"west": { "texture": "#3", "uv": [0, 0, 3, 2] },
"top": { "texture": "#1", "uv": [0, 0, 3, 3] },
"bottom": { "texture": "#3", "uv": [0, 0, 3, 3] }
}
},
{
"from": [0, 2, 0],
"to": [16, 16, 16],
"faces": {
"north": { "texture": "#2", "uv": [0, 2, 16, 16] },
"east": { "texture": "#1", "uv": [0, 2, 16, 16] },
"south": { "texture": "#3", "uv": [0, 2, 16, 16] },
"west": { "texture": "#1", "uv": [0, 2, 16, 16] },
"top": { "texture": "#1", "uv": [0, 0, 16, 16], "rotation": 90 },
"bottom": { "texture": "#1", "uv": [0, 0, 16, 16], "rotation": 90 }
}
}
]
}
}
+3 -3
View File
@@ -132,8 +132,8 @@ function register_storage(ctx: ServerContext) {
return menu_type; return menu_type;
} }
// a shipping bin, like stardew valley's: a chest that every morning at 06:00 sells everything in it with a // a shipping bin, like stardew valley's: a chest that every morning at 06:00 sells everything in it with a sell
// base_sell_value, and pays for it in as few coins as it can // value, and pays for it in as few coins as it can
const COINS = [ const COINS = [
"bworld:cobalt_coin", "bworld:cobalt_coin",
@@ -165,7 +165,7 @@ function register_shipping_bin(ctx: ServerContext, storage_menu: ReturnType<type
let total = 0; let total = 0;
for (let slot = 0; slot < container.size; slot++) { for (let slot = 0; slot < container.size; slot++) {
const item = container.get(slot); const item = container.get(slot);
const value = item && ctx.items.sell_value(item.id); const value = item && ctx.items.sell_value(item.id, item.data);
if (value === undefined) continue; if (value === undefined) continue;
total += value * item!.count; total += value * item!.count;
container.set(slot, undefined); container.set(slot, undefined);
+14 -2
View File
@@ -154,13 +154,18 @@ export interface JuicerTank {
amount: number; 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;
// juice is one fluid for every fruit, like create's potion fluid: which fruit sits in its data, { item }. it's named // juice is one fluid for every fruit, like create's potion fluid: which fruit sits in its data, { item }. it's named
// after that item, "Strawberry Juice", in the color its bworld:juiceable says // after that item, "Strawberry Juice", in the color its bworld:juiceable says, and sells for JUICE_VALUE times the
// items it took
function register_juice(ctx: SharedContext) { function register_juice(ctx: SharedContext) {
const item_of = (data: unknown) => { const item_of = (data: unknown) => {
const item = (data as { item?: unknown } | undefined)?.item; const item = (data as { item?: unknown } | undefined)?.item;
return typeof item === "string" && ctx.items.exists(item) ? item : undefined; return typeof item === "string" && ctx.items.exists(item) ? item : undefined;
}; };
const juiceable = (item: string) => ctx.items.components(item)["bworld:juiceable"] as JuiceableParams | undefined;
ctx.fluids.register("bworld:juice", { ctx.fluids.register("bworld:juice", {
name(data) { name(data) {
const item = item_of(data); const item = item_of(data);
@@ -168,7 +173,14 @@ function register_juice(ctx: SharedContext) {
}, },
color(data) { color(data) {
const item = item_of(data); const item = item_of(data);
return item && (ctx.items.components(item)["bworld:juiceable"] as JuiceableParams | undefined)?.color; return item && juiceable(item)?.color;
},
sell_value(data) {
const item = item_of(data);
if (!item) return undefined;
const juice = juiceable(item)?.juice;
const value = ctx.items.sell_value(item);
return juice && value !== undefined ? JUICE_VALUE * value * 1000 / juice : undefined;
}, },
}); });
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 411 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 B

+9 -5
View File
@@ -4,7 +4,12 @@
// runs mods' server scripts: builds each one's ServerContext and keeps what they register. // 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 // see docs/modding/. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "$/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack, max_stack } from "$/common/inventory.ts"; import {
Container as EngineContainer,
ItemStack as EngineItemStack,
max_stack,
sell_value,
} from "$/common/inventory.ts";
import { import {
block_states, block_states,
fluid_block, fluid_block,
@@ -921,10 +926,9 @@ export class ModRuntime {
if (!item) throw new Error(`unknown item ${id}`); if (!item) throw new Error(`unknown item ${id}`);
return item.tool?.type; return item.tool?.type;
}, },
sell_value: (id) => { sell_value: (id, data) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id); if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`);
if (!item) throw new Error(`unknown item ${id}`); return sell_value(id, data, this.fluid_rules);
return item.base_sell_value;
}, },
components: (id) => { components: (id) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id); const item = EverythingRegistry.get<ItemRegistry>("items", id);
+27
View File
@@ -4,6 +4,7 @@
// the base game's block and item behavior: hoeing, chests, furnaces, crops and the watering can // the base game's block and item behavior: hoeing, chests, furnaces, crops and the watering can
import { assert, assertEquals } from "@std/assert"; import { assert, assertEquals } from "@std/assert";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { sell_value } from "$/common/inventory.ts";
import { CYCLE_TICKS } from "$/common/time.ts"; import { CYCLE_TICKS } from "$/common/time.ts";
import { display_name, get_state_value } from "$/common/utils.ts"; import { display_name, get_state_value } from "$/common/utils.ts";
import { container_items, menu_data, menu_items, opened_menu, stone_floor, test_game } from "./helpers.ts"; import { container_items, menu_data, menu_items, opened_menu, stone_floor, test_game } from "./helpers.ts";
@@ -131,6 +132,32 @@ Deno.test("a shipping bin sells what's in it every morning for as few coins as i
]); ]);
}); });
Deno.test("a shipping bin sells a stack for what its data makes it worth, like a bottle by its juice", async () => {
const t = await setup();
const [fruit] = EverythingRegistry.entries<ItemRegistry>("items")
.find(([, item]) => item.components?.["bworld:juiceable"] && item.base_sell_value !== undefined)!;
const full = { fluid: { id: "bworld:juice", data: { item: fruit } } };
t.send(1, { type: "chat", text: `/give bworld:glass_bottle 3 ${JSON.stringify(full)}` });
t.game.set_block(1, 100, 0, "bworld:shipping_bin");
const bottles = slot_of(t.take(1), "bworld:glass_bottle");
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
const opened = opened_menu(t.take(1));
move_to_menu(t, opened, bottles, 0);
t.send(1, { type: "close_menu", menu: opened.id });
t.take(1);
t.game.set_time((t.game.world.day + 1) * CYCLE_TICKS - 1);
t.game.tick();
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
const sold = menu_items(t.take(1)).slice(0, 27).filter((item: Msg) => item);
const coin_value = (id: string) => EverythingRegistry.get<ItemRegistry>("items", id)!.base_sell_value!;
const paid = sold.reduce((total: number, coin: Msg) => total + coin.count * coin_value(coin.id), 0);
const value = sell_value("bworld:glass_bottle", full, t.game.mods.fluid_rules)!;
assert(value > 0);
assertEquals(paid, 3 * value);
});
Deno.test("a furnace burns fuel to smelt, shows its progress, and only lets the result be taken", async () => { Deno.test("a furnace burns fuel to smelt, shows its progress, and only lets the result be taken", async () => {
const t = await setup([["bworld:iron_ore", 2], ["bworld:coal", 1]]); const t = await setup([["bworld:iron_ore", 2], ["bworld:coal", 1]]);
t.game.set_block(1, 100, 0, "bworld:furnace"); t.game.set_block(1, 100, 0, "bworld:furnace");
+25 -5
View File
@@ -1,18 +1,20 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // 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 // items that hold one fluid, full or empty: how many stack, what they look like, what they sell for, and turning the
// held one into another
import { assertEquals } from "@std/assert"; import { assertEquals } from "@std/assert";
import { item_tooltip } from "$/client/gui/tooltip.ts"; import { item_tooltip } from "$/client/gui/tooltip.ts";
import { item_layers } from "$/client/rendering/item_renderer.ts"; import { item_layers } from "$/client/rendering/item_renderer.ts";
import { ItemStack } from "$/common/inventory.ts"; import { ItemStack, sell_value } from "$/common/inventory.ts";
import { copy_dir, test_game } from "./helpers.ts"; import { copy_dir, test_game } from "./helpers.ts";
const JAR = "testjars:jar"; const JAR = "testjars:jar";
const FLASK = "testjars:flask";
const FULL = { fluid: { id: "testjars:syrup", data: { tree: "maple" } } }; 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 // mods/bworld, and testjars: syrup worth 10 a bucket, a jar of 250 mB that stacks to 16 empty and 4 full, drawn with
// and a red label // the syrup in it and a red label, and a flask of 1000 mB worth 2 on its own
async function setup() { async function setup() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_jars_" }); const dir = Deno.makeTempDirSync({ prefix: "bworld_jars_" });
copy_dir("mods/bworld", `${dir}/bworld`); copy_dir("mods/bworld", `${dir}/bworld`);
@@ -21,7 +23,10 @@ async function setup() {
Deno.writeTextFileSync(`${dir}/testjars/${path}`, JSON.stringify(json)); Deno.writeTextFileSync(`${dir}/testjars/${path}`, JSON.stringify(json));
}; };
write("manifest.json", { format_version: 1, id: "testjars", name: "Test Jars", version: "1.0.0" }); 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("fluids/syrup.json", {
format_version: 1,
fluid: { id: "testjars:syrup", color: "#a0522d", base_sell_value: 10 },
});
write("items/jar.json", { write("items/jar.json", {
format_version: 1, format_version: 1,
item: { item: {
@@ -32,6 +37,10 @@ async function setup() {
layers: [{ texture: "engine:break_0", tint: "fluid" }, { texture: "engine:break_1", tint: "#ff0000" }], layers: [{ texture: "engine:break_0", tint: "fluid" }, { texture: "engine:break_1", tint: "#ff0000" }],
}, },
}); });
write("items/flask.json", {
format_version: 1,
item: { id: FLASK, texture: "engine:missing", base_sell_value: 2, fluid_container: { capacity: 1000 } },
});
const t = await test_game(dir); const t = await test_game(dir);
Deno.removeSync(dir, { recursive: true }); Deno.removeSync(dir, { recursive: true });
t.join(1, "alice"); t.join(1, "alice");
@@ -65,6 +74,17 @@ Deno.test("a layer tinted fluid is drawn in the fluid's color while there's one,
assertEquals(jar(FULL), [{ texture: "engine:break_0", color: [0xa0 / 255, 0x52 / 255, 0x2d / 255] }, red]); assertEquals(jar(FULL), [{ texture: "engine:break_0", color: [0xa0 / 255, 0x52 / 255, 0x2d / 255] }, red]);
}); });
Deno.test("a full fluid container sells for its own value and its fluid's, rounded up", async () => {
const t = await setup();
const value = (id: string, data?: unknown) => sell_value(id, data, t.game.mods.fluid_rules);
// a jar of syrup is 2.5, and a flask of it is the flask's 2 and the syrup's 10
assertEquals([value(JAR), value(JAR, FULL)], [undefined, 3]);
assertEquals([value(FLASK), value(FLASK, FULL)], [2, 12]);
const jar = new ItemStack(JAR);
jar.data = FULL;
assertEquals(item_tooltip(jar).map((line) => line.text), ["Jar", "Syrup, 250 mB", "3"]);
});
Deno.test("exchange_held puts the result in the hand from a stack of one, and in the inventory from more", async () => { 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(); const t = await setup();
t.api.give_item(JAR, 3); t.api.give_item(JAR, 3);
+23 -1
View File
@@ -1,17 +1,19 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// juice: one fluid named and colored after the bworld:juiceable item in its data, and the juicer that makes it // juice: one fluid named, colored and valued after the bworld:juiceable item in its data, and the juicer that makes it
import { assert, assertEquals } from "@std/assert"; import { assert, assertEquals } from "@std/assert";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { FluidJson } from "$/common/mod_data.ts"; import type { FluidJson } from "$/common/mod_data.ts";
import type { ClientContext, Instances, Visual, VisualBlock } from "$/common/mod_api/client.ts"; import type { ClientContext, Instances, Visual, VisualBlock } from "$/common/mod_api/client.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "$/common/constants.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "$/common/constants.ts";
import { block_value, display_name } from "$/common/utils.ts"; import { block_value, display_name } from "$/common/utils.ts";
import { sell_value } from "$/common/inventory.ts";
import { block_visuals, Visuals } from "$/client/rendering/visuals.ts"; import { block_visuals, Visuals } from "$/client/rendering/visuals.ts";
import { AssetManager } from "$/client/assets.ts"; import { AssetManager } from "$/client/assets.ts";
import { fluid_rules, set_fluid_rules } from "$/client/fluid_rules.ts"; import { fluid_rules, set_fluid_rules } from "$/client/fluid_rules.ts";
import { setup as setup_client } from "$/mods/bworld/scripts/client.ts"; import { setup as setup_client } from "$/mods/bworld/scripts/client.ts";
import { JUICE_VALUE, type JuiceableParams } from "$/mods/bworld/scripts/shared.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts"; import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const CLOUDBERRY = "testberries:cloudberry"; const CLOUDBERRY = "testberries:cloudberry";
@@ -63,6 +65,26 @@ Deno.test("juice made from any item with bworld:juiceable is named after it, in
]); ]);
}); });
Deno.test("juice in any container sells for JUICE_VALUE times the items it took, rounded up", async () => {
const { game } = await setup();
const sellable = EverythingRegistry.entries<ItemRegistry>("items")
.filter(([, item]) => item.components?.["bworld:juiceable"] && item.base_sell_value !== undefined);
const containers = EverythingRegistry.entries<ItemRegistry>("items").filter(([, item]) => item.fluid_container);
assert(sellable.length > 0 && containers.length > 0);
for (const [id, item] of sellable) {
const { juice } = item.components!["bworld:juiceable"] as JuiceableParams;
for (const [container, info] of containers) {
const full = { fluid: { id: "bworld:juice", data: { item: id } } };
const value = sell_value(container, full, game.mods.fluid_rules)! - (info.base_sell_value ?? 0);
const exact = JUICE_VALUE * item.base_sell_value! * info.fluid_container!.capacity / juice;
assert(Number.isInteger(value) && value >= exact - 1e-9 && value < exact + 1, `${container} of ${id}`);
}
}
// juice from what can't be sold, the cloudberry, can't be sold either
assertEquals(game.mods.fluid_rules.sell_value({ id: "bworld:juice", data: { item: CLOUDBERRY } }), undefined);
});
Deno.test("the juicer takes juiceable items, juices one every 4 presses, and fills empty containers from it", async () => { Deno.test("the juicer takes juiceable items, juices one every 4 presses, and fills empty containers from it", async () => {
const t = await setup(); const t = await setup();
t.join(1, "alice"); t.join(1, "alice");