Files
bworld/common/inventory.ts
T
2026-10-26 19:32:46 -03:00

429 lines
13 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import type { FluidRules } from "./fluids.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 {
id: string;
count: number;
data?: unknown;
// what server scripts say about it (get_lore), only sent to players, never saved
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<ItemRegistry>("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<ItemRegistry>("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;
}
// 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> {
type_id: string;
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) {
const item_info = EverythingRegistry.get<ItemRegistry>("items", type_id);
this.type_id = type_id;
this.amount = amount;
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<ItemRegistry>("items", this.type_id)?.tool;
if (!tool) return undefined;
const damage = (this.data as { damage?: number } | undefined)?.damage ?? 0;
return tool.durability - damage;
}
// takes durability off a tool, true when that used it up
damage(amount: number): boolean {
const left = this.durability();
if (left === undefined) return false;
const data = (this.data ?? {}) as { damage?: number };
data.damage = (data.damage ?? 0) + amount;
this.data = data as T;
return left - amount <= 0;
}
clone(): ItemStack {
const item = new ItemStack(this.type_id, this.amount);
item.data = structuredClone(this.data);
item.lore = this.lore;
return item;
}
to_data(): ItemData {
return this.data === undefined
? { id: this.type_id, count: this.amount }
: { id: this.type_id, count: this.amount, data: this.data };
}
// what players are sent: to_data with the lore from the item's get_lore, which only runs on the server
to_synced_data(): ItemData {
const data = this.to_data();
const lore = EverythingRegistry.get<ItemRegistry>("items", this.type_id)?.get_lore?.(this);
if (lore) {
data.lore = lore;
}
return data;
}
static from_data(data: ItemData): ItemStack {
const item = new ItemStack(data.id, data.count);
if (data.data !== undefined) {
item.data = data.data;
}
if (data.lore !== undefined) {
item.lore = data.lore;
}
return item;
}
}
export class ContainerSlot {
#item_stack: ItemStack | undefined;
has_item() {
return this.get_item() !== undefined;
}
set_item(item_stack: ItemStack | undefined) {
if ((item_stack?.amount ?? 0) <= 0) {
item_stack = undefined;
}
this.#item_stack = item_stack;
}
get_item() {
// scripts can count a stack down to nothing, it's gone then
if (this.#item_stack && this.#item_stack.amount <= 0) {
this.#item_stack = undefined;
}
return this.#item_stack;
}
get type_id() {
return this.get_item()?.type_id;
}
set amount(new_amount: number) {
if (this.#item_stack) {
this.#item_stack.amount = new_amount;
if (this.#item_stack.amount <= 0) {
this.#item_stack = undefined;
}
}
}
get amount(): number | undefined {
return this.get_item()?.amount;
}
get max_amount() {
return this.get_item()?.max_amount;
}
}
export class Container {
#slots: ContainerSlot[] = [];
readonly size: number;
constructor(size: number) {
this.size = size;
for (let i = 0; i < size; i += 1) {
this.#slots.push(new ContainerSlot());
}
}
// returns how many items didn't fit
add_item(item_stack: ItemStack): number {
for (const slot of this.#slots.filter((slot) => slot.has_item())) {
const slot_item = slot.get_item()!;
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;
item_stack.amount -= adding;
if (item_stack.amount === 0) {
return 0;
}
}
}
for (const slot of this.#slots) {
if (!slot.has_item()) {
slot.set_item(item_stack);
return 0;
}
}
// TODO: drop item on ground
return item_stack.amount;
}
get_item(slot: number): ItemStack | undefined {
return this.#slots[slot]?.get_item();
}
get_slot(slot: number): ContainerSlot {
return this.#slots[slot];
}
set_item(slot: number, item: ItemStack | undefined) {
this.#slots[slot].set_item(item);
}
to_data(): (ItemData | null)[] {
return this.#slots.map((slot) => slot.get_item()?.to_data() ?? null);
}
// what players are sent, with lore, see ItemStack.to_synced_data
to_synced_data(): (ItemData | null)[] {
return this.#slots.map((slot) => slot.get_item()?.to_synced_data() ?? null);
}
load(data: (ItemData | null)[]) {
for (let i = 0; i < this.size; i += 1) {
const item = data[i];
this.#slots[i].set_item(item ? ItemStack.from_data(item) : undefined);
}
}
clear() {
for (const slot of this.#slots) {
slot.set_item(undefined);
}
}
}
// the item a player is carrying around with the mouse in an inventory screen
export interface Cursor {
item: ItemStack | undefined;
}
export const LEFT_CLICK = 0;
export const RIGHT_CLICK = 2;
// what clicking a normal slot does, the server runs this for real and clients run it to predict. limit is the most
// the slot holds of anything, like minecraft's Slot.getMaxStackSize
export function click_slot(container: Container, index: number, cursor: Cursor, button: number, limit = Infinity) {
if (button === LEFT_CLICK) {
left_click(container, index, cursor, limit);
} else if (button === RIGHT_CLICK) {
right_click(container, index, cursor, limit);
}
if (cursor.item && cursor.item.amount <= 0) {
cursor.item = undefined;
}
}
function swap_with_cursor(container: Container, index: number, cursor: Cursor) {
const slot = container.get_slot(index);
const original = cursor.item;
cursor.item = slot.get_item();
slot.set_item(original);
}
function left_click(container: Container, index: number, cursor: Cursor, limit: number) {
const holding = cursor.item;
const slot = container.get_slot(index);
const slot_item = slot.get_item();
// if you aren't holding anything
// "swap" with nothing on your hand (pick it up)
if (!holding) {
swap_with_cursor(container, index, cursor);
return;
}
// if you are holding something and slot type equals holding type
// try to add to stack
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));
slot_item.amount += amount_to_add;
holding.amount -= amount_to_add;
return;
}
// more than the slot holds: an empty one takes as many as it can, a full one keeps what it has
if (holding.amount > limit) {
if (!slot_item) {
const placed = holding.clone();
placed.amount = limit;
slot.set_item(placed);
holding.amount -= limit;
}
return;
}
// if something on hand but not the same
// swap
swap_with_cursor(container, index, cursor);
}
function right_click(container: Container, index: number, cursor: Cursor, limit: number) {
const holding = cursor.item;
const slot = container.get_slot(index);
const slot_item = slot.get_item();
// if holding something
if (holding) {
// and slot type equals holding type
// add 1 to matching stack
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;
}
return;
}
// place 1 into empty slot
if (!slot_item) {
const new_item = holding.clone();
new_item.amount = 1;
slot.set_item(new_item);
holding.amount -= 1;
return;
}
// if something on hand but not the same
// swap, when all of it fits
if (holding.amount <= limit) swap_with_cursor(container, index, cursor);
return;
}
// if player is holding nothing and clicks nothing, nothing happens
if (!slot_item) {
return;
}
// pick up half of the stack
const original_amount = slot_item.amount;
const half = Math.floor(original_amount / 2);
const picked_up = slot_item.clone();
picked_up.amount = original_amount - half;
cursor.item = picked_up;
slot.amount = half;
}
// a slot of some container, menus' slots can come from several
export interface SlotRef {
container: Container;
index: number;
// the most it holds of anything, when that's less than a stack
max_count?: number;
}
// how many of item the slot holds
function slot_cap(slot: SlotRef, item: ItemStack): number {
return Math.min(item.max_amount, slot.max_count ?? Infinity);
}
// shift clicking, like minecraft's moveItemStackTo: tops up stacks of the same item in these slots, in order, then
// fills empty ones. what doesn't fit stays in the item
export function move_into(item: ItemStack, slots: SlotRef[], accepts: (slot: SlotRef) => boolean = () => true) {
for (const slot of slots) {
const there = slot.container.get_item(slot.index);
if (item.amount <= 0) return;
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;
}
}
for (const slot of slots) {
if (item.amount <= 0) return;
if (!slot.container.get_item(slot.index) && accepts(slot)) {
const moved = item.clone();
moved.amount = Math.min(item.amount, slot_cap(slot, item));
slot.container.set_item(slot.index, moved);
item.amount -= moved.amount;
}
}
}
// how many of the item move_into could put in these slots
export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: SlotRef) => boolean = () => true): number {
let room = 0;
for (const slot of slots) {
const there = slot.container.get_item(slot.index);
if (!accepts(slot)) continue;
if (!there) room += slot_cap(slot, item);
else if (same_stack(there, item)) room += Math.max(0, slot_cap(slot, there) - there.amount);
}
return room;
}
// whether take_output would take it
export function can_take_output(item: ItemStack, cursor: Cursor): boolean {
const holding = cursor.item;
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
// returns whether it was taken
export function take_output(item: ItemStack, cursor: Cursor): boolean {
const holding = cursor.item;
if (!holding) {
cursor.item = item.clone();
return true;
}
if (same_stack(holding, item) && holding.max_amount - holding.amount >= item.amount) {
holding.amount += item.amount;
return true;
}
return false;
}