Files
bworld/common/loot.ts
T
2026-11-14 12:18:41 -03:00

402 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table
// has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
// conditions and functions (ctx.loot in server phases), which are ids in their namespace.
// see docs/modding/resources/loot_tables.md
import * as z from "zod";
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
import { list_matches, Tags } from "./tags.ts";
import {
by_kind,
find_problems,
id,
id_or_tag,
json_object,
loot_table_id,
type Problems,
TAG_ID_PATTERN,
} from "./schema.ts";
// a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's
// constant, uniform and binomial number providers
export type NumberProvider = number | { min: number; max: number } | { n: number; p: number };
export interface LootCondition {
condition: string;
[param: string]: unknown;
}
export interface LootFunction {
function: string;
[param: string]: unknown;
}
export interface LootEntry {
// "item" when not given
type?: "item" | "tag" | "loot_table" | "empty";
// for "item"
item?: string;
// for "item", the count it gives, 1 when not given. the same as a set_count function first
count?: NumberProvider;
// for "tag": one item of the tag at random, like "#bworld:logs"
tag?: string;
// for "loot_table": what rolling that table gives
table?: string;
// how likely it is picked against the pool's other entries, 1 when not given
weight?: number;
conditions?: LootCondition[];
functions?: LootFunction[];
}
export interface LootPool {
// how many times one of its entries is picked, 1 when not given
rolls?: NumberProvider;
conditions?: LootCondition[];
entries: LootEntry[];
functions?: LootFunction[];
}
export interface LootTableJson {
// from its file: loot_tables/<path>.json in a mod is <mod>:<path>
id: string;
pools: LootPool[];
conditions?: LootCondition[];
functions?: LootFunction[];
}
// an item a table gives
export interface LootItem {
id: string;
count: number;
data?: unknown;
}
// what the built in conditions read from what's happening. more is there for mods' conditions and functions, like
// the player, see LootContext in mod_api/server.ts
export interface BaseLootContext {
// the block being broken, with its states
block?: { id: string; states?: Record<string, number> };
// what it's done with, like the tool breaking the block or the fishing rod
tool?: { id: string };
// a player killed the entity it's for
killed_by_player?: boolean;
}
// a mod's condition: whether it holds, from its params (the condition's json) and what's happening
export type LootConditionFn<C> = (params: LootCondition, context: C) => boolean;
// a mod's function: the item changed, or undefined to take it away
export type LootFunctionFn<C> = (item: LootItem, params: LootFunction, context: C) => LootItem | undefined;
export interface LootEnvironment<C extends BaseLootContext> {
conditions?: ReadonlyMap<string, LootConditionFn<C>>;
functions?: ReadonlyMap<string, LootFunctionFn<C>>;
// 0 to 1, Math.random when not given
random?: () => number;
}
// tables in tables in tables: past this it's taken as a loop and gives nothing more
const MAX_DEPTH = 16;
export class LootError extends Error {
constructor(message: string) {
super(message);
this.name = "LootError";
}
}
// rolls a registered table: every item it gives, in the order its pools gave them
export function roll_loot<C extends BaseLootContext>(
id: string,
context: C,
env: LootEnvironment<C> = {},
): LootItem[] {
return roll_table(id, context, { random: Math.random, ...env }, 0);
}
type Env<C extends BaseLootContext> = LootEnvironment<C> & { random: () => number };
function roll_table<C extends BaseLootContext>(id: string, context: C, env: Env<C>, depth: number): LootItem[] {
const table = EverythingRegistry.get<LootTableJson>("loot_tables", id);
if (!table) throw new LootError(`loot table ${id} doesn't exist`);
if (depth > MAX_DEPTH) throw new LootError(`loot table ${id} is in itself, through its loot_table entries`);
if (!all(table.conditions, context, env)) return [];
const items: LootItem[] = [];
for (const pool of table.pools) {
if (!all(pool.conditions, context, env)) continue;
const rolls = number(pool.rolls ?? 1, env);
for (let i = 0; i < rolls; i++) {
const entry = pick(pool.entries.filter((e) => all(e.conditions, context, env)), env);
if (!entry) continue;
for (const item of entry_items(entry, context, env, depth)) {
const done = apply_all(apply_all(item, entry.functions, context, env), pool.functions, context, env);
if (done) items.push(done);
}
}
}
return items.flatMap((item) => apply_all(item, table.functions, context, env) ?? []).filter((item) =>
item.count > 0
);
}
// one of them by weight, undefined for none
function pick<T extends { weight?: number }>(entries: T[], env: { random: () => number }): T | undefined {
const total = entries.reduce((sum, entry) => sum + (entry.weight ?? 1), 0);
if (total <= 0) return undefined;
let left = env.random() * total;
for (const entry of entries) {
left -= entry.weight ?? 1;
if (left < 0) return entry;
}
return entries.at(-1);
}
function entry_items<C extends BaseLootContext>(entry: LootEntry, context: C, env: Env<C>, depth: number): LootItem[] {
switch (entry.type ?? "item") {
case "item":
return [{ id: entry.item!, count: number(entry.count ?? 1, env) }];
case "tag": {
const items = Tags.get("items", entry.tag!);
const id = items[Math.floor(env.random() * items.length)];
return id === undefined ? [] : [{ id, count: number(entry.count ?? 1, env) }];
}
case "loot_table":
return roll_table(entry.table!, context, env, depth + 1);
default:
return [];
}
}
export function number(provider: NumberProvider, env: { random: () => number }): number {
if (typeof provider === "number") return provider;
if ("min" in provider) return provider.min + Math.floor(env.random() * (provider.max - provider.min + 1));
let count = 0;
for (let i = 0; i < provider.n; i++) if (env.random() < provider.p) count++;
return count;
}
function all<C extends BaseLootContext>(conditions: LootCondition[] | undefined, context: C, env: Env<C>): boolean {
return (conditions ?? []).every((condition) => holds(condition, context, env));
}
function holds<C extends BaseLootContext>(condition: LootCondition, context: C, env: Env<C>): boolean {
switch (condition.condition) {
case "random_chance":
return env.random() < (condition.chance as number);
case "match_tool": {
const id = context.tool?.id;
if (!id) return false;
const items = condition.items as string[] | undefined;
if (items && !list_matches("items", items, id)) return false;
const tool = EverythingRegistry.get<ItemRegistry>("items", id)?.tool;
if (condition.tool !== undefined && tool?.type !== condition.tool) return false;
if (condition.min_tier !== undefined && (tool?.tier ?? -1) < (condition.min_tier as number)) return false;
return true;
}
case "block_state": {
const block = context.block;
if (!block) return false;
if (condition.block !== undefined && block.id !== condition.block) return false;
return Object.entries(condition.states as Record<string, StateMatch>).every(([name, match]) => {
const value = block.states?.[name];
if (value === undefined) return false;
if (typeof match === "number") return value === match;
return value >= (match.min ?? -Infinity) && value <= (match.max ?? Infinity);
});
}
case "killed_by_player":
return context.killed_by_player === true;
case "inverted":
return !holds(condition.term as LootCondition, context, env);
case "any_of":
return (condition.terms as LootCondition[]).some((term) => holds(term, context, env));
case "all_of":
return (condition.terms as LootCondition[]).every((term) => holds(term, context, env));
}
const custom = env.conditions?.get(condition.condition);
if (!custom) throw new LootError(`loot condition ${condition.condition} isn't registered`);
return custom(condition, context);
}
type StateMatch = number | { min?: number; max?: number };
function apply_all<C extends BaseLootContext>(
item: LootItem | undefined,
functions: LootFunction[] | undefined,
context: C,
env: Env<C>,
): LootItem | undefined {
for (const fn of functions ?? []) {
if (!item) return undefined;
item = apply(item, fn, context, env);
}
return item;
}
function apply<C extends BaseLootContext>(
item: LootItem,
fn: LootFunction,
context: C,
env: Env<C>,
): LootItem | undefined {
if (!all(fn.conditions as LootCondition[] | undefined, context, env)) return item;
switch (fn.function) {
case "set_count": {
const count = number(fn.count as NumberProvider, env);
return { ...item, count: fn.add ? item.count + count : count };
}
case "limit_count": {
const min = (fn.min as number | undefined) ?? 0;
const max = (fn.max as number | undefined) ?? Infinity;
return { ...item, count: Math.min(Math.max(item.count, min), max) };
}
case "set_data":
return { ...item, data: structuredClone(fn.data) };
}
const custom = env.functions?.get(fn.function);
if (!custom) throw new LootError(`loot function ${fn.function} isn't registered`);
return custom(item, fn, context);
}
// checking a table's json
const whole = z.int().min(0);
const number_provider: z.ZodType<NumberProvider> = z.union([
whole,
z.object({ min: whole, max: whole }).refine(({ min, max }) => min <= max, {
path: ["max"],
message: "can't be below min",
}),
z.object({ n: whole, p: z.number().min(0).max(1) }),
], "must be a whole number, { min, max } or { n, p }");
const conditions = z.array(z.lazy(() => loot_condition));
// the engine's conditions, by name
const CONDITIONS = new Map<string, z.ZodType>([
["random_chance", z.object({ chance: z.number().min(0).max(1) })],
[
"match_tool",
z.object({ items: z.array(id_or_tag).optional(), tool: z.string().optional(), min_tier: z.int().optional() }),
],
[
"block_state",
z.object({
block: id.optional(),
states: z.record(
z.string(),
z.union(
[z.int(), z.object({ min: z.int().optional(), max: z.int().optional() })],
'must be a number or { min, max }, like { "age": 7 }',
),
),
}),
],
["killed_by_player", z.object({})],
["inverted", z.object({ term: z.lazy(() => loot_condition) })],
["any_of", z.object({ terms: conditions })],
["all_of", z.object({ terms: conditions })],
]);
// any other condition is a mod's own, by its id. the server checks a script registered it when it starts
const loot_condition: z.ZodType<LootCondition> = by_kind(
"condition",
(name) => CONDITIONS.get(name) ?? (name.includes(":") ? json_object : undefined),
`must be one of ${[...CONDITIONS.keys()].join(", ")}, or a mod's own condition's id`,
);
// every function can have conditions
const loot_function_base = z.object({ conditions: conditions.optional() });
// the engine's functions, by name
const FUNCTIONS = new Map<string, z.ZodType>([
["set_count", loot_function_base.extend({ count: number_provider, add: z.boolean().optional() })],
["limit_count", loot_function_base.extend({ min: z.int().optional(), max: z.int().optional() })],
["set_data", loot_function_base.extend({ data: z.unknown() })],
]);
// any other function is a mod's own, like conditions
const loot_function: z.ZodType<LootFunction> = by_kind(
"function",
(name) => FUNCTIONS.get(name) ?? (name.includes(":") ? loot_function_base : undefined),
`must be one of ${[...FUNCTIONS.keys()].join(", ")}, or a mod's own function's id`,
);
const functions = z.array(loot_function);
// every entry can have these
const loot_entry_base = z.object({
weight: z.number().min(0).optional(),
conditions: conditions.optional(),
functions: functions.optional(),
});
const loot_entry: z.ZodType<LootEntry> = z.discriminatedUnion("type", [
loot_entry_base.extend({ type: z.literal("item").optional(), item: id, count: number_provider.optional() }),
loot_entry_base.extend({
type: z.literal("tag"),
tag: z.string('must be a #tag, like "#bworld:logs"').refine((tag) =>
tag.startsWith("#") && TAG_ID_PATTERN.test(tag.slice(1))
),
count: number_provider.optional(),
}),
loot_entry_base.extend({ type: z.literal("loot_table"), table: loot_table_id }),
loot_entry_base.extend({ type: z.literal("empty") }),
]);
const loot_table_schema: z.ZodType<LootTableJson> = z.object({
id: z.string("its file name must be a-z, 0-9 and _, in folders").regex(TAG_ID_PATTERN),
pools: z.array(z.object({
rolls: number_provider.optional(),
conditions: conditions.optional(),
entries: z.array(loot_entry).min(1),
functions: functions.optional(),
})),
conditions: conditions.optional(),
functions: functions.optional(),
});
export function validate_loot_table(json: unknown): Problems {
return find_problems(loot_table_schema, json);
}
// what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions
export function loot_references(table: LootTableJson) {
const refs = { items: [] as string[], tags: [] as string[], tables: [] as string[], custom: [] as string[] };
const conditions = (list: LootCondition[] | undefined) => {
for (const condition of list ?? []) {
if (condition.condition.includes(":")) refs.custom.push(condition.condition);
if (condition.condition === "match_tool") {
for (const id of (condition.items as string[] | undefined) ?? []) {
(id.startsWith("#") ? refs.tags : refs.items).push(id);
}
}
if (condition.term) conditions([condition.term as LootCondition]);
if (condition.terms) conditions(condition.terms as LootCondition[]);
}
};
const functions = (list: LootFunction[] | undefined) => {
for (const fn of list ?? []) {
if (fn.function.includes(":")) refs.custom.push(fn.function);
conditions(fn.conditions as LootCondition[] | undefined);
}
};
conditions(table.conditions);
functions(table.functions);
for (const pool of table.pools) {
conditions(pool.conditions);
functions(pool.functions);
for (const entry of pool.entries) {
conditions(entry.conditions);
functions(entry.functions);
if ((entry.type ?? "item") === "item") refs.items.push(entry.item!);
if (entry.type === "tag") refs.tags.push(entry.tag!);
if (entry.type === "loot_table") refs.tables.push(entry.table!);
}
}
return refs;
}