From ec2b53c02afc105d1991bf4974b5f0293d5125f3 Mon Sep 17 00:00:00 2001 From: Paula Date: Thu, 8 Oct 2026 00:54:45 -0300 Subject: [PATCH] Loot tables --- MODS.md | 1 + common/bmod.ts | 6 +- common/everything_registry.ts | 2 + common/loot.ts | 453 ++++++++++++++++++ common/mod_api/server.ts | 42 ++ common/mod_check.ts | 22 +- common/mod_data.ts | 17 + common/mod_loader.ts | 6 + common/utils.ts | 7 + docs/modding/blocks/crops.md | 90 +++- docs/modding/blocks/index.md | 7 +- docs/modding/entities/index.md | 1 + docs/modding/gettingstarted/modfiles.md | 3 +- docs/modding/resources/loot_tables.md | 184 +++++++ mods/bworld/blocks/carrots.json | 8 +- mods/bworld/blocks/potatoes.json | 8 +- mods/bworld/blocks/wheat.json | 8 +- mods/bworld/items/fishing_rod.json | 15 +- mods/bworld/loot_tables/blocks/carrots.json | 39 ++ mods/bworld/loot_tables/blocks/potatoes.json | 39 ++ mods/bworld/loot_tables/blocks/wheat.json | 61 +++ mods/bworld/loot_tables/gameplay/fishing.json | 19 + mods/bworld/scripts/server.ts | 59 +-- mods/farmersdelight/blocks/cabbages.json | 8 +- mods/farmersdelight/blocks/onions.json | 8 +- mods/farmersdelight/blocks/rice.json | 7 +- mods/farmersdelight/blocks/rice_panicles.json | 6 +- mods/farmersdelight/blocks/tomatoes.json | 16 +- .../loot_tables/blocks/cabbages.json | 61 +++ .../loot_tables/blocks/onions.json | 39 ++ .../loot_tables/blocks/rice.json | 14 + .../loot_tables/blocks/rice_panicles.json | 22 + .../loot_tables/blocks/tomatoes.json | 29 ++ .../loot_tables/harvest/tomatoes.json | 18 + server/game/entity/entity.ts | 2 + server/game/entity/entity_manager.ts | 6 + server/game/entity/living_entity.ts | 7 +- server/game/game_server.ts | 47 +- server/game/loot.ts | 100 ++++ server/game/mod_runtime.ts | 57 ++- server/load_bmods.ts | 1 + tests/helpers.ts | 1 + tests/loot_test.ts | 319 ++++++++++++ tools/check_mods.ts | 17 + tools/pack_mod.ts | 1 + 45 files changed, 1733 insertions(+), 150 deletions(-) create mode 100644 common/loot.ts create mode 100644 docs/modding/resources/loot_tables.md create mode 100644 mods/bworld/loot_tables/blocks/carrots.json create mode 100644 mods/bworld/loot_tables/blocks/potatoes.json create mode 100644 mods/bworld/loot_tables/blocks/wheat.json create mode 100644 mods/bworld/loot_tables/gameplay/fishing.json create mode 100644 mods/farmersdelight/loot_tables/blocks/cabbages.json create mode 100644 mods/farmersdelight/loot_tables/blocks/onions.json create mode 100644 mods/farmersdelight/loot_tables/blocks/rice.json create mode 100644 mods/farmersdelight/loot_tables/blocks/rice_panicles.json create mode 100644 mods/farmersdelight/loot_tables/blocks/tomatoes.json create mode 100644 mods/farmersdelight/loot_tables/harvest/tomatoes.json create mode 100644 server/game/loot.ts create mode 100644 tests/loot_test.ts diff --git a/MODS.md b/MODS.md index 9b20021..4f08165 100644 --- a/MODS.md +++ b/MODS.md @@ -61,6 +61,7 @@ deno task build && deno task server # packs the mods and starts a se - [Block Models](docs/modding/resources/models.md) - [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing and your own recipe types - [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to +- [Loot Tables](docs/modding/resources/loot_tables.md): what blocks, mobs, fishing and chests give **Everything else** diff --git a/common/bmod.ts b/common/bmod.ts index 7fdc600..5568874 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -28,6 +28,7 @@ import { validate_tag, } from "./mod_data.ts"; import type { ModData } from "./mod_loader.ts"; +import { type LootTableJson, validate_loot_table } from "./loot.ts"; import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts"; import { ENGINE_GLOBAL } from "./hooks.ts"; @@ -63,7 +64,7 @@ export class BmodError extends Error { // the zip's layout: // manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip -// data.json every block, model, item, recipe, ore, entity, entity model, effect and tag +// data.json every block, model, item, recipe, ore, entity, entity model, effect, tag and loot table // scripts/.js // textures/.png the texture : // textures/.json its animation, if it has one @@ -161,10 +162,11 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { ) as EntityModelJson[], effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[], tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[], + loot_tables: checked(raw_data.loot_tables, "loot_tables", validate_loot_table, problems) as LootTableJson[], }; // a mod only registers ids in its own namespace const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models]; - for (const { id } of [...registered, ...data.effects]) { + for (const { id } of [...registered, ...data.effects, ...data.loot_tables!]) { if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`); } diff --git a/common/everything_registry.ts b/common/everything_registry.ts index c1d3877..0f39bd7 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -132,6 +132,8 @@ export interface BlockRegistry { // the lowest tool tier it drops for when requires_tool, like minecraft's incorrect_for_*_tool tags. 0 when not set tool_tier?: number; drop_table?: string; + // what it drops when broken, see common/loot.ts. drop_table is one of an item instead + loot_table?: string; states?: BlockStateDefinition[]; // a different model or textures for some states, by conditions like "age=7". the first match wins diff --git a/common/loot.ts b/common/loot.ts new file mode 100644 index 0000000..b575c47 --- /dev/null +++ b/common/loot.ts @@ -0,0 +1,453 @@ +// 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 scripts), which are ids in their namespace. +// see docs/modding/resources/loot_tables.md +import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts"; +import { list_matches, Tags } from "./tags.ts"; +import { TAG_ID_PATTERN } from "./mod_data.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/.json in a mod is : + 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 }; + // 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 = (params: LootCondition, context: C) => boolean; +// a mod's function: the item changed, or undefined to take it away +export type LootFunctionFn = (item: LootItem, params: LootFunction, context: C) => LootItem | undefined; + +export interface LootEnvironment { + conditions?: ReadonlyMap>; + functions?: ReadonlyMap>; + // 0 to 1, Math.random when not given + random?: () => number; +} + +export const LOOT_CONDITIONS = [ + "random_chance", + "match_tool", + "block_state", + "killed_by_player", + "inverted", + "any_of", + "all_of", +] as const; +export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const; +const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"]; +// 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( + id: string, + context: C, + env: LootEnvironment = {}, +): LootItem[] { + return roll_table(id, context, { random: Math.random, ...env }, 0); +} + +type Env = LootEnvironment & { random: () => number }; + +function roll_table(id: string, context: C, env: Env, depth: number): LootItem[] { + const table = EverythingRegistry.get("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(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(entry: LootEntry, context: C, env: Env, 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(conditions: LootCondition[] | undefined, context: C, env: Env): boolean { + return (conditions ?? []).every((condition) => holds(condition, context, env)); +} + +function holds(condition: LootCondition, context: C, env: Env): 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("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).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( + item: LootItem | undefined, + functions: LootFunction[] | undefined, + context: C, + env: Env, +): LootItem | undefined { + for (const fn of functions ?? []) { + if (!item) return undefined; + item = apply(item, fn, context, env); + } + return item; +} + +function apply( + item: LootItem, + fn: LootFunction, + context: C, + env: Env, +): 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 + +type Problems = string[]; + +export function validate_loot_table(json: unknown): Problems { + if (!is_object(json)) return ["loot_table must be an object"]; + const problems: Problems = []; + if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) { + problems.push("its file name must be a-z, 0-9 and _, in folders"); + } + problems.push(...validate_conditions(json.conditions, "conditions")); + problems.push(...validate_functions(json.functions, "functions")); + if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"]; + json.pools.forEach((pool, i) => { + const where = `pools[${i}]`; + if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`); + if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`)); + problems.push(...validate_conditions(pool.conditions, `${where}.conditions`)); + problems.push(...validate_functions(pool.functions, `${where}.functions`)); + if (!Array.isArray(pool.entries) || pool.entries.length === 0) { + return problems.push(`${where}.entries must be a list of entries`); + } + pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`))); + }); + return problems; +} + +function validate_entry(entry: unknown, where: string): Problems { + if (!is_object(entry)) return [`${where} must be { type, item, weight }`]; + const problems: Problems = []; + const type = entry.type ?? "item"; + if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) { + problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`); + } + const field = { item: "item", tag: "tag", loot_table: "table" }[type as string]; + if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`); + if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) { + problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`); + } + if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`)); + if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) { + problems.push(`${where}.weight must be a number, 0 or more`); + } + problems.push(...validate_conditions(entry.conditions, `${where}.conditions`)); + problems.push(...validate_functions(entry.functions, `${where}.functions`)); + return problems; +} + +export function validate_number(value: unknown, where: string): Problems { + const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0; + if (whole(value)) return []; + if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) { + return []; + } + if ( + is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1 + ) return []; + return [`${where} must be a whole number, { min, max } or { n, p }`]; +} + +function validate_conditions(list: unknown, where: string): Problems { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list`]; + return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`)); +} + +function validate_condition(condition: unknown, where: string): Problems { + if (!is_object(condition) || typeof condition.condition !== "string") { + return [`${where} must be { "condition": ... }`]; + } + const name = condition.condition; + switch (name) { + case "random_chance": { + const chance = condition.chance; + return typeof chance === "number" && chance >= 0 && chance <= 1 + ? [] + : [`${where}.chance must be from 0 to 1`]; + } + case "match_tool": { + const problems: Problems = []; + const items = condition.items; + if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) { + problems.push(`${where}.items must be a list of item ids and #tags`); + } + if (condition.tool !== undefined && typeof condition.tool !== "string") { + problems.push(`${where}.tool must be a tool type, like "axe"`); + } + if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) { + problems.push(`${where}.min_tier must be a whole number`); + } + return problems; + } + case "block_state": { + const states = condition.states; + const ok = is_object(states) && Object.values(states).every((match) => + Number.isInteger(match) || + (is_object(match) && (match.min === undefined || Number.isInteger(match.min)) && + (match.max === undefined || Number.isInteger(match.max))) + ); + return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`]; + } + case "killed_by_player": + return []; + case "inverted": + return validate_condition(condition.term, `${where}.term`); + case "any_of": + case "all_of": + return Array.isArray(condition.terms) + ? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`)) + : [`${where}.terms must be a list of conditions`]; + } + return name.includes(":") ? [] : [ + `${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`, + ]; +} + +function validate_functions(list: unknown, where: string): Problems { + if (list === undefined) return []; + if (!Array.isArray(list)) return [`${where} must be a list`]; + return list.flatMap((fn, i) => { + const at = `${where}[${i}]`; + if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`]; + const problems = validate_conditions(fn.conditions, `${at}.conditions`); + switch (fn.function) { + case "set_count": + problems.push(...validate_number(fn.count, `${at}.count`)); + if (fn.add !== undefined && typeof fn.add !== "boolean") { + problems.push(`${at}.add must be true or false`); + } + break; + case "limit_count": + for (const key of ["min", "max"]) { + if (fn[key] !== undefined && !Number.isInteger(fn[key])) { + problems.push(`${at}.${key} must be a whole number`); + } + } + break; + case "set_data": + if (fn.data === undefined) problems.push(`${at}.data is needed`); + break; + default: + if (!fn.function.includes(":")) { + problems.push( + `${at}: ${fn.function} isn't a loot function. the engine's are ${ + LOOT_FUNCTIONS.join(", ") + }, a mod's has its id`, + ); + } + } + return problems; + }); +} + +// 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; +} + +function is_object(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index d8ec43c..6660b84 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -19,6 +19,7 @@ export interface ServerContext { blocks: BlockApi; recipes: RecipeApi; tags: TagApi; + loot: LootApi; menus: MenuRegistry; ui: ServerUi; net: ServerNet; @@ -388,6 +389,47 @@ export interface RecipeApi { list(type: Id): any[]; } +// loot tables, see docs/modding/resources/loot_tables.md + +// what's happening when a table is rolled. its built in conditions read block, tool and killed_by_player, mods' +// conditions and functions get all of it +export interface LootContext { + // where it happens, like the broken block or the fishing hook + position?: Position; + // the block being broken. its states are read from the world when not given + block?: { id: Id; x: number; y: number; z: number; states?: Record }; + // what it's done with, like the tool breaking the block or the fishing rod + tool?: ItemStack; + // who did it: broke the block, fished, killed the mob + player?: Player; + // the mob that died + entity?: EntityRef; + // a player killed it, for the "killed_by_player" condition + killed_by_player?: boolean; +} + +// a condition's or function's json, with its "condition" or "function" id and whatever params it has +// deno-lint-ignore no-explicit-any +export type LootParams = Record; + +export interface LootApi { + exists(id: Id): boolean; + // what rolling the table gives, stacks split to fit a slot. throws for a table that doesn't exist + roll(id: Id, context?: LootContext): ItemStack[]; + // rolls the table into the container's empty slots, at random like minecraft's chests. returns what didn't fit + fill(container: Container, id: Id, context?: LootContext): ItemStack[]; + // a condition tables can use by its id, in the mod's namespace. only during setup + register_condition(id: Id, condition: (params: LootParams, context: LootContext) => boolean): void; + // a function tables can use by its id: the item changed, or undefined to take it away. only during setup + register_function( + id: Id, + fn: (item: ItemStack, params: LootParams, context: LootContext) => ItemStack | undefined, + ): void; + // changes what a table gives every time it's rolled, or every table's with "*", like neoforge's global loot + // modifiers. return the new items, or change the list. only during setup + modify(table: Id | "*", fn: (items: ItemStack[], context: LootContext, table: Id) => ItemStack[] | void): void; +} + // forms, not built yet: menus whose screens the engine provides, see docs/modding_plan.md export interface ActionForm { diff --git a/common/mod_check.ts b/common/mod_check.ts index b72273e..b2f0d68 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -18,6 +18,7 @@ import { PLAYER_PARTS } from "./everything_registry.ts"; import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts"; import { resolve_tags } from "./tags.ts"; import type { TextureJson } from "./texture_animation.ts"; +import { loot_references, type LootTableJson } from "./loot.ts"; import { BIOMES } from "./worldgen/overworld.ts"; export interface ModReport { @@ -41,6 +42,7 @@ export interface LoadedMod { entity_models: { file: string; json: EntityModelJson }[]; effects: { file: string; json: EffectJson }[]; tags: { file: string; json: TagJson }[]; + loot_tables: { file: string; json: LootTableJson }[]; textures: string[]; // absolute paths by texture id texture_files: Map; @@ -87,6 +89,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable(); const tag_owners = new Map>(); const liquids = new Set(); + const loot_tables = new Set(); const add = (map: Map, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]); const textures = new Set(engine_textures); @@ -109,6 +112,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable { + const uses = ( + file: string, + id: string, + what: "block" | "item" | "texture" | "model" | "entity model" | "loot table", + ) => { check_namespace(file, id); if (id.startsWith("#") && (what === "block" || what === "item")) { if (!tag_owners.get(what === "block" ? "blocks" : "items")?.has(id.slice(1))) { @@ -150,6 +158,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable 1) { diff --git a/common/mod_data.ts b/common/mod_data.ts index 00fad77..9fa6930 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -79,6 +79,8 @@ export interface BlockJson { item_display?: { surface: number }; // makes it a liquid, see LiquidProperties. range is 7 when not set liquid?: Partial; + // what it drops when broken, see common/loot.ts. drops is the shorthand for one of an item + loot_table?: string; // the liquid it can hold, see BlockRegistry.waterloggable waterloggable?: string; // only placed into a source of it, see BlockRegistry.waterlogged_only @@ -152,6 +154,8 @@ export interface EntityJson { // protection from physical and from arcane damage, not used yet physical_shielding?: number; arcane_shielding?: number; + // what it drops when it dies, see common/loot.ts + loot_table?: string; } // a status effect, like neoforge's MobEffect. what it does over time comes from components scripts register, see @@ -301,6 +305,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso if (block.tool_tier) json.mining.tier = block.tool_tier; } if (block.drop_table !== undefined) json.drops = block.drop_table; + if (block.loot_table !== undefined) json.loot_table = block.loot_table; if (!has_item) json.item = false; if (block.interactive) json.interactive = true; if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable; @@ -351,6 +356,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it if (json.mining.tier) block.tool_tier = json.mining.tier; } if (json.drops !== undefined) block.drop_table = json.drops; + if (json.loot_table !== undefined) block.loot_table = json.loot_table; if (json.interactive) block.interactive = true; if (json.replaceable ?? json.liquid) block.replaceable = true; if (json.place_on) block.place_on = json.place_on; @@ -661,6 +667,12 @@ export function validate_block(json: unknown): Problems { } } if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops")); + if (json.loot_table !== undefined) { + if (!(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table))) { + problems.push('loot_table must be a loot table id, like "my_mod:blocks/thing"'); + } + if (json.drops !== undefined) problems.push("drops and loot_table can't both be set, drops is one item"); + } if (json.item_display !== undefined) { const surface = is_object(json.item_display) ? json.item_display.surface : undefined; if (typeof surface !== "number" || surface < 0 || surface > 16) { @@ -1005,6 +1017,11 @@ export function validate_entity(json: unknown): Problems { if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) { problems.push('behavior must be "animal", "monster" or "scripted"'); } + if ( + json.loot_table !== undefined && !(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table)) + ) { + problems.push('loot_table must be a loot table id, like "my_mod:entities/thing"'); + } for (const key of ["width", "height"]) { if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { problems.push(`${key} must be a number of blocks above 0, at most 16`); diff --git a/common/mod_loader.ts b/common/mod_loader.ts index 06334f0..e24f2d9 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -21,6 +21,7 @@ import { TagRegistry, } from "./mod_data.ts"; import { resolve_tags, Tags } from "./tags.ts"; +import type { LootTableJson } from "./loot.ts"; import { register_block_item } from "./utils.ts"; import type { ModelJson } from "./block_models.ts"; @@ -40,6 +41,8 @@ export interface ModData { effects: EffectJson[]; // tag files, see common/tags.ts tags: TagJson[]; + // see common/loot.ts. missing from mods packed before there were loot tables + loot_tables?: LootTableJson[]; } // a mod as the server lists it to clients, in load order: the .bmod players download, without its server script @@ -117,6 +120,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe for (const json of data.effects) { EverythingRegistry.register("effects", json.id, json); } + for (const json of data.loot_tables ?? []) { + EverythingRegistry.register("loot_tables", json.id, json); + } } catch (e) { throw new ModLoadError(id, (e as Error).message); } diff --git a/common/utils.ts b/common/utils.ts index cf167c4..5b91cf3 100644 --- a/common/utils.ts +++ b/common/utils.ts @@ -86,6 +86,13 @@ export function get_state_value(value: number, block_info: BlockRegistry, name: return (state_bits & s.mask) >>> s.shift; } +// every state of a block value by name, like { age: 7 } +export function block_states(value: number, block_info: BlockRegistry): Record { + return Object.fromEntries( + (block_info.states ?? []).map((s) => [s.name, get_state_value(value, block_info, s.name)!]), + ); +} + export function set_state_value(value: number, block_info: BlockRegistry, name: string, new_value: number) { if (!block_info.states) { return undefined; diff --git a/docs/modding/blocks/crops.md b/docs/modding/blocks/crops.md index 0e0aae1..95c0cd6 100644 --- a/docs/modding/blocks/crops.md +++ b/docs/modding/blocks/crops.md @@ -25,6 +25,7 @@ the day before grows a day, then all farmland dries out. The crop shows the stag "render_layer": "cutout", "collision": false, "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/cabbages", "item": false, "place_on": ["bworld:hoed_dirt"], "states": [{ "name": "age", "bits": 3, "default": 0 }], @@ -32,12 +33,7 @@ the day before grows a day, then all farmland dries out. The crop shows the stag "bworld:crop": { "days": 12, "stages": 8, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "farmersdelight:cabbage_seeds", - "mature": "farmersdelight:cabbage", - "bonus": "farmersdelight:cabbage_seeds" - } + "fertilizer": "bworld:bone_meal" } } } @@ -59,18 +55,56 @@ the day before grows a day, then all farmland dries out. The crop shows the stag `place_on` keeps it on farmland, and it pops off when the farmland is dug up. +## Drops + +What a crop drops is its block's [loot table](../resources/loot_tables.md), with a `block_state` condition on `age` for +grown or not. `loot_tables/blocks/cabbages.json` gives a seed while it grows, and once it's grown at age 7 the cabbage +and 1 to 4 seeds, like Minecraft's wheat: + +```json +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:cabbage", + "conditions": [{ "condition": "block_state", "states": { "age": 7 } }] + }, + { + "item": "farmersdelight:cabbage_seeds", + "conditions": [ + { "condition": "inverted", "term": { "condition": "block_state", "states": { "age": 7 } } } + ] + } + ] + }, + { + "conditions": [{ "condition": "block_state", "states": { "age": 7 } }], + "entries": [ + { + "item": "farmersdelight:cabbage_seeds", + "functions": [{ "function": "set_count", "count": { "n": 3, "p": 0.5714 }, "add": true }] + } + ] + } + ] + } +} +``` + ## Parameters -| Param | Meaning | -| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `days` | Watered mornings from planting to fully grown. | -| `stages` | How many ages it shows, 0 to `stages - 1`, spread evenly over `days`. The `age` state must fit them. | -| `drops` | What it drops when broken: `young` before it's grown, `mature` once it is, and `bonus`, 1 to 4 of an item when grown (Minecraft's 1 plus 3 tries at 57%, like wheat's seeds). `young` and `mature` can be one id or a list. | -| `fertilizer` | An item that grows it a day right away when used on it, like bone meal. | -| `water` | `"farmland"` (the default) needs watered farmland under it. `"always"` grows every morning. | -| `regrow_days`, `harvest` | Right clicking it once grown picks it, dropping `harvest.item` (`count` is `[min, max]`), and it grows back after `regrow_days`. | -| `upper` | `{ block, stages, supporting_age }`: its last stages grow a second block on top, see below. | -| `leaves` | What the spot becomes when it's broken, like the water rice was planted in. | +| Param | Meaning | +| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `days` | Watered mornings from planting to fully grown. | +| `stages` | How many ages it shows, 0 to `stages - 1`, spread evenly over `days`. The `age` state must fit them. | +| `fertilizer` | An item that grows it a day right away when used on it, like bone meal. | +| `water` | `"farmland"` (the default) needs watered farmland under it. `"always"` grows every morning. | +| `regrow_days`, `harvest` | Right clicking it once grown picks it, dropping what the [loot table](../resources/loot_tables.md) `harvest` gives, and it grows back after `regrow_days`. | +| `upper` | `{ block, stages, supporting_age }`: its last stages grow a second block on top, see below. | +| `leaves` | What the spot becomes when it's broken, like the water rice was planted in. | ## Harvesting By Hand @@ -81,10 +115,17 @@ Tomatoes are picked instead of broken: "days": 11, "stages": 8, "regrow_days": 4, - "harvest": { "item": "farmersdelight:tomato", "count": [1, 2] }, - "drops": { - "young": "farmersdelight:tomato_seeds", - "mature": ["farmersdelight:tomato", "farmersdelight:tomato_seeds"] + "harvest": "farmersdelight:harvest/tomatoes" +} +``` + +with `loot_tables/harvest/tomatoes.json` giving 1 or 2 tomatoes: + +```json +{ + "format_version": 1, + "loot_table": { + "pools": [{ "entries": [{ "item": "farmersdelight:tomato", "count": { "min": 1, "max": 2 } }] }] } } ``` @@ -103,17 +144,18 @@ block goes through its own `stages`: "stages": 4, "water": "always", "upper": { "block": "farmersdelight:rice_panicles", "stages": 4, "supporting_age": 4 }, - "leaves": "bworld:water", - "drops": { "young": "farmersdelight:rice", "mature": "farmersdelight:rice" } + "leaves": "bworld:water" } } ``` -The top block uses `bworld:crop_top` with its own `stages` and `drops`. Breaking either half harvests the whole plant: +The top block uses `bworld:crop_top` with its own `stages`, and its own loot table. Breaking either half harvests the +whole plant: ```json +"loot_table": "farmersdelight:blocks/rice_panicles", "components": { - "bworld:crop_top": { "stages": 4, "drops": { "mature": "farmersdelight:rice_panicle" } } + "bworld:crop_top": { "stages": 4 } } ``` diff --git a/docs/modding/blocks/index.md b/docs/modding/blocks/index.md index 50d3e36..a635fa1 100644 --- a/docs/modding/blocks/index.md +++ b/docs/modding/blocks/index.md @@ -60,7 +60,8 @@ there will be holes in the world behind them. | `mining.tool` | none | The [tool type](../items/tools.md) that breaks it faster, like `pickaxe`, `axe` or `shovel`. | | `mining.requires_tool` | `false` | Only drops when broken with `mining.tool`. | | `mining.tier` | `0` | With `requires_tool`, the lowest tool tier it drops for. Iron ore is `1`, so a wood pickaxe gets nothing. | -| `drops` | nothing | The item id it drops when broken. | +| `drops` | nothing | The item id it drops when broken, one of it. | +| `loot_table` | none | A [loot table](../resources/loot_tables.md) it drops from when broken instead, with its states and the tool. Not with `drops`. | | `item` | `true` | Also register an item that places it, with the same id. To give that item more, see [Block Items](../items/index.md#block-items). | | `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. | | `replaceable` | `false` | Placing a block into it replaces it, like water. Liquids default to `true`. | @@ -79,8 +80,8 @@ It can't hold functions. Breaking takes `mining.toughness` seconds by hand. A tool whose type matches `mining.tool` breaks it `tool.speed` times faster. The client times breaking itself, and the server checks the result. -When it breaks, the block's components' `on_break` runs and it drops `drops`, unless it has `requires_tool` and the -player's tool is the wrong type or a tier below `mining.tier`. +When it breaks, the block's components' `on_break` runs and it drops `drops` or what its `loot_table` gives, unless it +has `requires_tool` and the player's tool is the wrong type or a tier below `mining.tier`. ## Placement diff --git a/docs/modding/entities/index.md b/docs/modding/entities/index.md index d4dbb26..8f96256 100644 --- a/docs/modding/entities/index.md +++ b/docs/modding/entities/index.md @@ -34,6 +34,7 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi | `attack_damage` | `2` | What a monster's hits do, in half hearts. | | `physical_shielding` | `0` | Protection from physical damage. Not used yet. | | `arcane_shielding` | `0` | Protection from arcane damage. Not used yet. | +| `loot_table` | none | A [loot table](../resources/loot_tables.md) it drops from when it dies. | `/summon ` spawns one where you stand. diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md index a48c24e..f73dabf 100644 --- a/docs/modding/gettingstarted/modfiles.md +++ b/docs/modding/gettingstarted/modfiles.md @@ -19,6 +19,7 @@ mods/ effects/*.json # status effects, see entities/effects.md recipes/*.json tags///*.json # tags, see resources/tags.md + loot_tables/**/*.json # loot tables, see resources/loot_tables.md worldgen/ores.json worldgen/spawns.json # monsters that spawn on their own, see entities/index.md textures/*.png @@ -114,7 +115,7 @@ deno task build # packs every mod in mods/ into server_mo ``` copper_tools.bmod manifest.json # with scripts and credits pointing into the zip - data.json # every block, model, item, entity, recipe and ore + data.json # every block, model, item, entity, recipe, ore, tag and loot table scripts/server.js # each script bundled into one module scripts/client.js scripts/worldgen.js diff --git a/docs/modding/resources/loot_tables.md b/docs/modding/resources/loot_tables.md new file mode 100644 index 0000000..300cceb --- /dev/null +++ b/docs/modding/resources/loot_tables.md @@ -0,0 +1,184 @@ +# Loot Tables + +A loot table says what something gives, as data: a block when it's broken, a mob when it dies, a fishing rod when it +reels something in, a crop when it's picked, and a container a script fills, like a chest in a ruin. They work like +Minecraft's, and mods can add their own conditions and functions from a server script. + +## Files and Ids + +Every `.json` in a mod's `loot_tables/` folder is a table, and its id is its path, like Minecraft's: + +| File | Loot table id | +| ----------------------------------- | ------------------------------ | +| `loot_tables/blocks/wheat.json` | `bworld:blocks/wheat` | +| `loot_tables/gameplay/fishing.json` | `bworld:gameplay/fishing` | +| `loot_tables/entities/rotling.json` | `undergarden:entities/rotling` | + +The folders are only for keeping things tidy. By habit, `blocks/` is for blocks, `entities/` for mobs, `gameplay/` for +things like fishing and `chests/` for containers. + +## A Table + +`loot_tables/blocks/wheat.json`, the base game's wheat: its seeds when it's young, and once it's grown its wheat and 1 +to 4 seeds: + +```json +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { "item": "bworld:wheat", "conditions": [{ "condition": "block_state", "states": { "age": 7 } }] }, + { + "item": "bworld:wheat_seeds", + "conditions": [ + { "condition": "inverted", "term": { "condition": "block_state", "states": { "age": 7 } } } + ] + } + ] + }, + { + "conditions": [{ "condition": "block_state", "states": { "age": 7 } }], + "entries": [ + { + "item": "bworld:wheat_seeds", + "functions": [{ "function": "set_count", "count": { "n": 3, "p": 0.5714 }, "add": true }] + } + ] + } + ] + } +} +``` + +A table has **pools**. Each pool is rolled `rolls` times, and each roll picks one of its **entries** whose conditions +hold, by `weight`. What every pool gives together is what the table gives. + +| Where | Field | Default | Meaning | +| ----- | ------------ | ------- | --------------------------------------------------------------------------- | +| table | `pools` | | The pools. | +| table | `conditions` | none | Unless they all hold, the table gives nothing. | +| table | `functions` | none | Change every item the table gives. | +| pool | `rolls` | `1` | How many times it picks an entry, a [number](#numbers). | +| pool | `entries` | | What it picks from. | +| pool | `conditions` | none | Unless they all hold, the pool isn't rolled. | +| pool | `functions` | none | Change every item the pool gives. | +| entry | `type` | `item` | See [entries](#entries). | +| entry | `weight` | `1` | How likely it's picked against the other entries that can be. `0` is never. | +| entry | `conditions` | none | Unless they all hold, it can't be picked. | +| entry | `functions` | none | Change the items it gives. | + +## Entries + +| `type` | Field | Gives | +| ------------ | ------- | --------------------------------------------------------------------------------------- | +| `item` | `item` | That item. `count`, a [number](#numbers), is how many, `1` when not set. | +| `tag` | `tag` | One item of an item [tag](tags.md) at random, like `"#bworld:logs"`. Takes `count` too. | +| `loot_table` | `table` | What rolling another table gives, like a shared list of treasure. | +| `empty` | | Nothing. With a `weight`, it's the chance a roll gives nothing. | + +Fishing's table picks cod 60 times out of 85 and salmon 25: + +```json +"pools": [{ "entries": [{ "item": "bworld:cod", "weight": 60 }, { "item": "bworld:salmon", "weight": 25 }] }] +``` + +## Numbers + +Counts and rolls are whole numbers, picked one of three ways: + +| Written | Means | +| ------------------------- | ----------------------------------------------------------------------------- | +| `3` | Always 3. | +| `{ "min": 1, "max": 3 }` | 1, 2 or 3, each as likely. | +| `{ "n": 3, "p": 0.5714 }` | How many of 3 tries at a 57.14% chance work, 0 to 3. Minecraft's bonus seeds. | + +## Conditions + +| `condition` | Fields | Holds when | +| ------------------ | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `random_chance` | `chance` | A random number is below `chance`, from 0 to 1. | +| `match_tool` | `items`, `tool`, `min_tier` | It's done with an item in `items` (ids and #tags), of [tool](../items/tools.md) type `tool`, of at least `min_tier`. Each is optional. | +| `block_state` | `states`, `block` | The block's states match, each a number or `{ "min", "max" }`, like `{ "age": { "min": 3 } }`. `block` checks its id too. | +| `killed_by_player` | | A player killed the mob. | +| `inverted` | `term` | `term` doesn't hold. | +| `any_of` | `terms` | One of `terms` holds. | +| `all_of` | `terms` | They all hold. | + +A condition with an id, like `my_mod:full_moon`, is a mod's own, see [below](#from-a-script). + +## Functions + +Functions run in order, first an entry's, then its pool's, then the table's. Any function can have `conditions`, and +does nothing unless they hold. + +| `function` | Fields | Does | +| ------------- | -------------- | ---------------------------------------------------------------------- | +| `set_count` | `count`, `add` | Sets the count to a [number](#numbers), or adds it with `"add": true`. | +| `limit_count` | `min`, `max` | Keeps the count between them. | +| `set_data` | `data` | Sets the item's data, any JSON, like what a map leads to. | + +## Where Tables Are Used + +| What | How | +| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| [Blocks](../blocks/index.md) | `"loot_table"` in the block's json, rolled when it breaks, with its states and the tool. `"drops"` is the shorthand for one of an item. | +| [Mobs](../entities/index.md) | `"loot_table"` in the entity's json, rolled when it dies. `killed_by_player` holds when a player killed it. | +| [Crops](../blocks/crops.md) | Their block's `loot_table`, with `block_state` on `age` for grown or not. `harvest` is a table for picking. | +| Fishing | The fishing rod's `loot_table`, `bworld:gameplay/fishing`. | +| Scripts | `ctx.loot.roll` and `ctx.loot.fill`, for anything else, like chests in structures. | + +`check-mods` checks that every item, tag and table a table names exists, and that the tables blocks and mobs name do. + +## From a Script + +Server scripts roll tables, fill containers, and add conditions, functions and changes of their own: + +```ts +import type { ServerContext } from "bworld/server"; + +export function setup(ctx: ServerContext) { + // "condition": "my_mod:night" in any table + ctx.loot.register_condition("my_mod:night", (_params, context) => ctx.world.time % 24000 > 13000); + + // "function": "my_mod:named", "name": "..." gives the item a name in its data + ctx.loot.register_function("my_mod:named", (item, params) => ({ ...item, data: { name: params.name } })); + + // every fish a player catches comes with a coin, like neoforge's global loot modifiers + ctx.loot.modify("bworld:gameplay/fishing", (items) => { + items.push({ id: "bworld:copper_coin", count: 1 }); + }); +} +``` + +| `ctx.loot` | Does | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `exists(id)` | Whether the table exists. | +| `roll(id, context?)` | What it gives, in stacks that fit a slot. Throws for a table that doesn't exist. | +| `fill(container, id, context?)` | Rolls it into the container's empty slots at random, like Minecraft's chests. Returns what didn't fit. | +| `register_condition(id, fn)` | A condition: `fn(params, context)` says whether it holds. Setup only. | +| `register_function(id, fn)` | A function: `fn(item, params, context)` gives the changed item, or `undefined` to take it away. Setup only. | +| `modify(table, fn)` | Changes what a table gives each time, or every table's with `"*"`. `fn(items, context, table)` changes the list or returns a new one. Setup only. | + +`params` is the condition's or function's json. Ids are in the mod's namespace, and a table that uses one nobody +registered stops the server from starting, like a missing [component](../blocks/components.md). What a mod's code throws +is logged under the mod, and the roll carries on as if that condition didn't hold or that function did nothing. + +The **context** says what's happening. Every part is optional: + +| Field | What | +| ------------------ | ----------------------------------------------------------------------------------------------------- | +| `position` | Where it happens. | +| `block` | `{ id, x, y, z, states }`, the block being broken. Its states are read from the world when not given. | +| `tool` | What it's done with, like the pickaxe or the fishing rod. | +| `player` | Who did it. | +| `entity` | The mob that died. | +| `killed_by_player` | A player killed it. | + +The engine gives blocks and mobs all they have. A script rolling a table gives what its conditions need: + +```ts +const loot = ctx.loot.roll("my_mod:chests/ruin", { position: { x, y, z } }); +const left = ctx.loot.fill(chest, "my_mod:chests/ruin"); +``` diff --git a/mods/bworld/blocks/carrots.json b/mods/bworld/blocks/carrots.json index 6e67658..cfe9372 100644 --- a/mods/bworld/blocks/carrots.json +++ b/mods/bworld/blocks/carrots.json @@ -33,6 +33,7 @@ "mining": { "toughness": 0 }, + "loot_table": "bworld:blocks/carrots", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -48,12 +49,7 @@ "bworld:crop": { "days": 3, "stages": 4, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "bworld:carrot", - "mature": "bworld:carrot", - "bonus": "bworld:carrot" - } + "fertilizer": "bworld:bone_meal" } } } diff --git a/mods/bworld/blocks/potatoes.json b/mods/bworld/blocks/potatoes.json index 510079b..0b6d11c 100644 --- a/mods/bworld/blocks/potatoes.json +++ b/mods/bworld/blocks/potatoes.json @@ -33,6 +33,7 @@ "mining": { "toughness": 0 }, + "loot_table": "bworld:blocks/potatoes", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -48,12 +49,7 @@ "bworld:crop": { "days": 6, "stages": 4, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "bworld:potato", - "mature": "bworld:potato", - "bonus": "bworld:potato" - } + "fertilizer": "bworld:bone_meal" } } } diff --git a/mods/bworld/blocks/wheat.json b/mods/bworld/blocks/wheat.json index 124f523..2547d3f 100644 --- a/mods/bworld/blocks/wheat.json +++ b/mods/bworld/blocks/wheat.json @@ -53,6 +53,7 @@ "mining": { "toughness": 0 }, + "loot_table": "bworld:blocks/wheat", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -68,12 +69,7 @@ "bworld:crop": { "days": 7, "stages": 8, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "bworld:wheat_seeds", - "mature": "bworld:wheat", - "bonus": "bworld:wheat_seeds" - } + "fertilizer": "bworld:bone_meal" } } } diff --git a/mods/bworld/items/fishing_rod.json b/mods/bworld/items/fishing_rod.json index aea03ad..e4d549b 100644 --- a/mods/bworld/items/fishing_rod.json +++ b/mods/bworld/items/fishing_rod.json @@ -10,12 +10,15 @@ "lore": "Right click to cast into water, and again when something bites.", "components": { "bworld:fishing_rod": { - "wait": [100, 600], - "bite": [20, 40], - "loot": [ - { "item": "bworld:cod", "weight": 60 }, - { "item": "bworld:salmon", "weight": 25 } - ] + "wait": [ + 100, + 600 + ], + "bite": [ + 20, + 40 + ], + "loot_table": "bworld:gameplay/fishing" } } } diff --git a/mods/bworld/loot_tables/blocks/carrots.json b/mods/bworld/loot_tables/blocks/carrots.json new file mode 100644 index 0000000..04ad1f3 --- /dev/null +++ b/mods/bworld/loot_tables/blocks/carrots.json @@ -0,0 +1,39 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "bworld:carrot" + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 3 + } + } + ], + "entries": [ + { + "item": "bworld:carrot", + "functions": [ + { + "function": "set_count", + "count": { + "n": 3, + "p": 0.5714 + }, + "add": true + } + ] + } + ] + } + ] + } +} diff --git a/mods/bworld/loot_tables/blocks/potatoes.json b/mods/bworld/loot_tables/blocks/potatoes.json new file mode 100644 index 0000000..81566aa --- /dev/null +++ b/mods/bworld/loot_tables/blocks/potatoes.json @@ -0,0 +1,39 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "bworld:potato" + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 3 + } + } + ], + "entries": [ + { + "item": "bworld:potato", + "functions": [ + { + "function": "set_count", + "count": { + "n": 3, + "p": 0.5714 + }, + "add": true + } + ] + } + ] + } + ] + } +} diff --git a/mods/bworld/loot_tables/blocks/wheat.json b/mods/bworld/loot_tables/blocks/wheat.json new file mode 100644 index 0000000..fefdd53 --- /dev/null +++ b/mods/bworld/loot_tables/blocks/wheat.json @@ -0,0 +1,61 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "bworld:wheat", + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 7 + } + } + ] + }, + { + "item": "bworld:wheat_seeds", + "conditions": [ + { + "condition": "inverted", + "term": { + "condition": "block_state", + "states": { + "age": 7 + } + } + } + ] + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 7 + } + } + ], + "entries": [ + { + "item": "bworld:wheat_seeds", + "functions": [ + { + "function": "set_count", + "count": { + "n": 3, + "p": 0.5714 + }, + "add": true + } + ] + } + ] + } + ] + } +} diff --git a/mods/bworld/loot_tables/gameplay/fishing.json b/mods/bworld/loot_tables/gameplay/fishing.json new file mode 100644 index 0000000..3f9d9c5 --- /dev/null +++ b/mods/bworld/loot_tables/gameplay/fishing.json @@ -0,0 +1,19 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "bworld:cod", + "weight": 60 + }, + { + "item": "bworld:salmon", + "weight": 25 + } + ] + } + ] + } +} diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index 1bca76a..77b98ce 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -352,18 +352,6 @@ interface WateringCanData { } // items as they appear in crop params: one id, or several -type Items = string | string[]; - -// what a crop drops when broken, like the loot tables of minecraft's and farmer's delight's crops -interface CropDrops { - // before it's fully grown, like wheat's seeds - young?: Items; - // fully grown, like wheat's wheat - mature?: Items; - // fully grown, 1 to 4 of this, like the seeds from wheat (minecraft's loot tables: 1 plus 3 tries at 57%) - bonus?: string; -} - // a crop, like minecraft's CropBlock: its "age" state is its stage, and it grows one day every morning its farmland was // watered the day before. see docs/modding/blocks/crops.md interface CropParams { @@ -371,10 +359,10 @@ interface CropParams { days: number; // how many stages it shows, ages 0 to stages - 1. its "age" state must fit them stages: number; - drops?: CropDrops; - // grows back after it's harvested by right clicking, like tomatoes + // grows back after it's harvested by right clicking, like tomatoes, giving what this loot table does. what it + // drops when broken is the block's own loot table regrow_days?: number; - harvest?: { item: string; count: [number, number] }; + harvest?: string; // grows it a day right away, like bone meal fertilizer?: string; // "farmland" (the default) needs watered farmland under it, "always" grows every morning, like rice in water @@ -388,7 +376,6 @@ interface CropParams { // the top of a two block crop. it grows with the crop under it, and breaking it breaks the whole plant interface CropTopParams { stages: number; - drops?: CropDrops; } function register_farming(ctx: ServerContext) { @@ -439,17 +426,6 @@ function register_farming(ctx: ServerContext) { }, }); - const list = (items: Items | undefined) => items === undefined ? [] : typeof items === "string" ? [items] : items; - - const drop = (x: number, y: number, z: number, drops: CropDrops | undefined, mature: boolean) => { - for (const id of list(mature ? drops?.mature : drops?.young)) ctx.world.drop_item(x, y, z, { id, count: 1 }); - if (mature && drops?.bonus) { - let count = 1; - for (let i = 0; i < 3; i++) if (Math.random() < 0.5714) count++; - ctx.world.drop_item(x, y, z, { id: drops.bonus, count }); - } - }; - // the stage for how many days it has grown: evenly spread, fully grown on the last day const stage_for = (params: CropParams, days: number) => { const stages = params.stages + (params.upper?.stages ?? 0); @@ -486,8 +462,6 @@ function register_farming(ctx: ServerContext) { ctx.world.set_state(block.x, block.y + 1, block.z, "age", stage - params.stages); }; - const is_grown = (block: BlockRef, params: CropParams) => days_of(block, params) >= params.days; - ctx.components.register_block("bworld:crop", { // block data so on_new_day runs for it. placed at a later stage (by a script), it has grown that long on_create(block, params) { @@ -517,16 +491,14 @@ function register_farming(ctx: ServerContext) { } // regrowing crops are picked by hand and grow back, like farmer's delight's tomatoes if (params.regrow_days && params.harvest && days >= params.days) { - const [min, max] = params.harvest.count; - const count = min + Math.floor(Math.random() * (max - min + 1)); - ctx.world.drop_item(block.x, block.y, block.z, { id: params.harvest.item, count }); + const loot = ctx.loot.roll(params.harvest, { block, player, tool: held }); + for (const item of loot) ctx.world.drop_item(block.x, block.y, block.z, item); set_days(block, params, Math.max(0, params.days - params.regrow_days)); return true; } return false; }, on_break(block, params) { - drop(block.x, block.y, block.z, params.drops, is_grown(block, params)); if (params.leaves) { const { x, y, z } = block; const leaves = params.leaves; @@ -539,9 +511,7 @@ function register_farming(ctx: ServerContext) { }); ctx.components.register_block("bworld:crop_top", { - on_break(block, params) { - const age = ctx.world.get_state(block.x, block.y, block.z, "age") ?? 0; - drop(block.x, block.y, block.z, params.drops, age >= params.stages - 1); + on_break(block) { // the plant under it goes too, once this is gone const { x, y, z } = block; const lower = ctx.world.get_block(x, y - 1, z); @@ -658,7 +628,8 @@ interface FishingRodParams { wait: [number, number]; // ticks it stays on the hook before it gets away bite: [number, number]; - loot: { item: string; weight: number }[]; + // what's caught, a loot table + loot_table: string; } interface Cast { @@ -684,16 +655,6 @@ function register_fishing(ctx: ServerContext) { const between = ([min, max]: [number, number]) => min + Math.floor(Math.random() * (max - min + 1)); - const pick = (loot: FishingRodParams["loot"]) => { - const total = loot.reduce((sum, entry) => sum + entry.weight, 0); - let roll = Math.random() * total; - for (const entry of loot) { - roll -= entry.weight; - if (roll < 0) return entry.item; - } - return loot.at(-1)?.item; - }; - const fishable = new Map(); const is_fishable = (id: string) => { let result = fishable.get(id); @@ -745,8 +706,8 @@ function register_fishing(ctx: ServerContext) { const cast = casts.get(player.id); if (cast) { if (cast.escape_at !== undefined) { - const item = pick(params.loot); - if (item) player.give_item(item); + const loot = ctx.loot.roll(params.loot_table, { position: cast.position, player, tool: rod }); + for (const item of loot) player.give_item(item.id, item.count, item.data); } stop(player, player.id); return; diff --git a/mods/farmersdelight/blocks/cabbages.json b/mods/farmersdelight/blocks/cabbages.json index befbb36..57e8b56 100644 --- a/mods/farmersdelight/blocks/cabbages.json +++ b/mods/farmersdelight/blocks/cabbages.json @@ -53,6 +53,7 @@ "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/cabbages", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -68,12 +69,7 @@ "bworld:crop": { "days": 12, "stages": 8, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "farmersdelight:cabbage_seeds", - "mature": "farmersdelight:cabbage", - "bonus": "farmersdelight:cabbage_seeds" - } + "fertilizer": "bworld:bone_meal" } } } diff --git a/mods/farmersdelight/blocks/onions.json b/mods/farmersdelight/blocks/onions.json index e750e32..3404821 100644 --- a/mods/farmersdelight/blocks/onions.json +++ b/mods/farmersdelight/blocks/onions.json @@ -33,6 +33,7 @@ "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/onions", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -48,12 +49,7 @@ "bworld:crop": { "days": 4, "stages": 4, - "fertilizer": "bworld:bone_meal", - "drops": { - "young": "farmersdelight:onion", - "mature": "farmersdelight:onion", - "bonus": "farmersdelight:onion" - } + "fertilizer": "bworld:bone_meal" } } } diff --git a/mods/farmersdelight/blocks/rice.json b/mods/farmersdelight/blocks/rice.json index 5b4aec9..b7ade91 100644 --- a/mods/farmersdelight/blocks/rice.json +++ b/mods/farmersdelight/blocks/rice.json @@ -40,6 +40,7 @@ "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/rice", "item": false, "place_on": [ "bworld:dirt", @@ -67,11 +68,7 @@ "stages": 4, "supporting_age": 4 }, - "leaves": "bworld:water", - "drops": { - "young": "farmersdelight:rice", - "mature": "farmersdelight:rice" - } + "leaves": "bworld:water" } } } diff --git a/mods/farmersdelight/blocks/rice_panicles.json b/mods/farmersdelight/blocks/rice_panicles.json index 108506d..72bf7eb 100644 --- a/mods/farmersdelight/blocks/rice_panicles.json +++ b/mods/farmersdelight/blocks/rice_panicles.json @@ -33,6 +33,7 @@ "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/rice_panicles", "item": false, "place_on": [ "farmersdelight:rice" @@ -46,10 +47,7 @@ ], "components": { "bworld:crop_top": { - "stages": 4, - "drops": { - "mature": "farmersdelight:rice_panicle" - } + "stages": 4 } } } diff --git a/mods/farmersdelight/blocks/tomatoes.json b/mods/farmersdelight/blocks/tomatoes.json index 1eba9b2..bf0f5a0 100644 --- a/mods/farmersdelight/blocks/tomatoes.json +++ b/mods/farmersdelight/blocks/tomatoes.json @@ -53,6 +53,7 @@ "mining": { "toughness": 0 }, + "loot_table": "farmersdelight:blocks/tomatoes", "item": false, "place_on": [ "bworld:hoed_dirt" @@ -70,20 +71,7 @@ "stages": 8, "fertilizer": "bworld:bone_meal", "regrow_days": 4, - "harvest": { - "item": "farmersdelight:tomato", - "count": [ - 1, - 2 - ] - }, - "drops": { - "young": "farmersdelight:tomato_seeds", - "mature": [ - "farmersdelight:tomato", - "farmersdelight:tomato_seeds" - ] - } + "harvest": "farmersdelight:harvest/tomatoes" } } } diff --git a/mods/farmersdelight/loot_tables/blocks/cabbages.json b/mods/farmersdelight/loot_tables/blocks/cabbages.json new file mode 100644 index 0000000..df0e681 --- /dev/null +++ b/mods/farmersdelight/loot_tables/blocks/cabbages.json @@ -0,0 +1,61 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:cabbage", + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 7 + } + } + ] + }, + { + "item": "farmersdelight:cabbage_seeds", + "conditions": [ + { + "condition": "inverted", + "term": { + "condition": "block_state", + "states": { + "age": 7 + } + } + } + ] + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 7 + } + } + ], + "entries": [ + { + "item": "farmersdelight:cabbage_seeds", + "functions": [ + { + "function": "set_count", + "count": { + "n": 3, + "p": 0.5714 + }, + "add": true + } + ] + } + ] + } + ] + } +} diff --git a/mods/farmersdelight/loot_tables/blocks/onions.json b/mods/farmersdelight/loot_tables/blocks/onions.json new file mode 100644 index 0000000..31e48d5 --- /dev/null +++ b/mods/farmersdelight/loot_tables/blocks/onions.json @@ -0,0 +1,39 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:onion" + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 3 + } + } + ], + "entries": [ + { + "item": "farmersdelight:onion", + "functions": [ + { + "function": "set_count", + "count": { + "n": 3, + "p": 0.5714 + }, + "add": true + } + ] + } + ] + } + ] + } +} diff --git a/mods/farmersdelight/loot_tables/blocks/rice.json b/mods/farmersdelight/loot_tables/blocks/rice.json new file mode 100644 index 0000000..59098f4 --- /dev/null +++ b/mods/farmersdelight/loot_tables/blocks/rice.json @@ -0,0 +1,14 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:rice" + } + ] + } + ] + } +} diff --git a/mods/farmersdelight/loot_tables/blocks/rice_panicles.json b/mods/farmersdelight/loot_tables/blocks/rice_panicles.json new file mode 100644 index 0000000..de819e6 --- /dev/null +++ b/mods/farmersdelight/loot_tables/blocks/rice_panicles.json @@ -0,0 +1,22 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 3 + } + } + ], + "entries": [ + { + "item": "farmersdelight:rice_panicle" + } + ] + } + ] + } +} diff --git a/mods/farmersdelight/loot_tables/blocks/tomatoes.json b/mods/farmersdelight/loot_tables/blocks/tomatoes.json new file mode 100644 index 0000000..6a83403 --- /dev/null +++ b/mods/farmersdelight/loot_tables/blocks/tomatoes.json @@ -0,0 +1,29 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:tomato_seeds" + } + ] + }, + { + "conditions": [ + { + "condition": "block_state", + "states": { + "age": 7 + } + } + ], + "entries": [ + { + "item": "farmersdelight:tomato" + } + ] + } + ] + } +} diff --git a/mods/farmersdelight/loot_tables/harvest/tomatoes.json b/mods/farmersdelight/loot_tables/harvest/tomatoes.json new file mode 100644 index 0000000..5e94587 --- /dev/null +++ b/mods/farmersdelight/loot_tables/harvest/tomatoes.json @@ -0,0 +1,18 @@ +{ + "format_version": 1, + "loot_table": { + "pools": [ + { + "entries": [ + { + "item": "farmersdelight:tomato", + "count": { + "min": 1, + "max": 2 + } + } + ] + } + ] + } +} diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts index c33e560..6261297 100644 --- a/server/game/entity/entity.ts +++ b/server/game/entity/entity.ts @@ -84,6 +84,8 @@ export interface EntityLevel { entity_event(entity: Entity, event: EntityEvent): void; // it died, after dropping its things on_death(entity: Entity, source: DamageSource): void; + // what it drops when it dies, from its type's loot table + entity_loot(entity: Entity, source: DamageSource): ItemStack[]; } // an entity as level.json keeps it, see Entity.save. each kind adds its own fields diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts index de07ef7..666d602 100644 --- a/server/game/entity/entity_manager.ts +++ b/server/game/entity/entity_manager.ts @@ -20,6 +20,8 @@ export interface EntityHost { send(player: ServerPlayer, message: ServerMessage): void; hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean; on_entity_death?(entity: Entity, source: DamageSource): void; + // what it drops when it dies, from its loot table + entity_loot?(entity: Entity, source: DamageSource): ItemStack[]; } // what a client was last told about an entity, so only changes get sent @@ -154,6 +156,10 @@ export class EntityManager implements EntityLevel { this.#host.on_entity_death?.(entity, source); } + entity_loot(entity: Entity, source: DamageSource): ItemStack[] { + return this.#host.entity_loot?.(entity, source) ?? []; + } + // ticking // every entity active says should move, with their passengers. entities removed along the way are forgotten diff --git a/server/game/entity/living_entity.ts b/server/game/entity/living_entity.ts index 65a0335..8ee69b0 100644 --- a/server/game/entity/living_entity.ts +++ b/server/game/entity/living_entity.ts @@ -374,8 +374,11 @@ export abstract class LivingEntity extends Entity { this.level.on_death(this, source); } - // what it drops when it dies, each kind decides. spawn_at_location drops something where it is - drop_loot(_source: DamageSource) {} + // what it drops when it dies: its type's loot table, see EntityJson.loot_table. spawn_at_location drops + // something where it is + drop_loot(source: DamageSource) { + for (const stack of this.level.entity_loot(this, source)) this.spawn_at_location(stack); + } // mobs drop their equipment, see Mob drop_equipment(_source: DamageSource) {} diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 1c67109..64439ba 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -24,6 +24,7 @@ import type { WorldgenSetup } from "$/common/generation.ts"; import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts"; import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts"; import { + block_states, box_overlaps_block, can_place, can_stand_on, @@ -36,7 +37,9 @@ import { } from "$/common/utils.ts"; import { collision_shape_at, type Shape } from "$/common/block_shapes.ts"; import { EXHAUSTION } from "./vitals.ts"; -import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts"; +import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts"; +import type { LootContext } from "$/common/mod_api/server.ts"; +import type { EntityJson } from "$/common/mod_data.ts"; import { argument, choice, @@ -228,6 +231,18 @@ export class GameServer { on_entity_death: (entity, source) => { if (entity instanceof ServerPlayer) this.#kill(entity, source); }, + entity_loot: (entity, source) => { + const table = EverythingRegistry.get("entities", entity.type)?.loot_table; + if (!table) return []; + const killer = source.attacker instanceof ServerPlayer ? source.attacker : undefined; + return this.roll_loot(table, { + position: { x: entity.x, y: entity.y, z: entity.z }, + entity: entity_ref(entity), + killed_by_player: source.by_player === true, + player: killer && this.mods.player(killer), + tool: killer && this.mods.player(killer).held_item, + }); + }, }); this.mods.storage = upgrade_mod_storage(saved?.mod_storage ?? {}); if (saved) { @@ -610,6 +625,17 @@ export class GameServer { } } + // what a loot table gives, ready to drop. a table that can't be rolled is logged and gives nothing, so a broken + // table never stops a block breaking or a mob dying + roll_loot(table: string, context: LootContext): ItemStack[] { + try { + return this.mods.loot.roll(table, context).map(new_stack); + } catch (e) { + console.error(`Couldn't roll loot table ${table}:`, e); + return []; + } + } + // breaks a block the way breaking it by hand does: its components' on_break, then what it drops. without the // right tool of a high enough tier (or without a player) blocks that need one drop nothing destroy_block(x: number, y: number, z: number, player?: ServerPlayer) { @@ -620,14 +646,23 @@ export class GameServer { const held = EverythingRegistry.get("items", player?.held_item?.type_id ?? ""); const tool = held?.tool; const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0); - const drops = info.drop_table && (!info.requires_tool || right_tool); - // a waterlogged block leaves its liquid behind, a source + const drops = !info.requires_tool || right_tool; const value = this.world.get_block_value(x, y, z); + // rolled while it's still there, for its states + const loot = drops && info.loot_table + ? this.roll_loot(info.loot_table, { + position: { x: x + 0.5, y: y + 0.5, z: z + 0.5 }, + block: { id: info.id, x, y, z, states: block_states(value, info) }, + player: player && this.mods.player(player), + tool: player && this.mods.player(player).held_item, + }) + : drops && info.drop_table + ? [new ItemStack(info.drop_table)] + : []; + // a waterlogged block leaves its liquid behind, a source const liquid = is_waterlogged(value, info) ? liquid_block(value, info) : undefined; this.set_block(x, y, z, liquid?.id ?? AIR_ID, player); - if (drops) { - this.pop_item(x, y, z, new ItemStack(info.drop_table!)); - } + for (const stack of loot) this.pop_item(x, y, z, stack); } get_or_create_tile(x: number, y: number, z: number): Tile { diff --git a/server/game/loot.ts b/server/game/loot.ts new file mode 100644 index 0000000..ff5efba --- /dev/null +++ b/server/game/loot.ts @@ -0,0 +1,100 @@ +// the server's loot tables: rolling them (see common/loot.ts) with the conditions, functions and modifiers mods +// register through ctx.loot. what a mod's code throws is logged under it and the roll carries on without it +import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; +import { + loot_references, + type LootCondition, + type LootConditionFn, + type LootFunction, + type LootFunctionFn, + type LootItem, + type LootTableJson, + roll_loot, +} from "$/common/loot.ts"; +import type { ItemStack, LootContext, LootParams } from "$/common/mod_api/server.ts"; +import { ModLoadError } from "$/common/mod_loader.ts"; +import { run_guarded } from "./mod_runtime.ts"; + +type Modifier = (items: ItemStack[], context: LootContext, table: string) => ItemStack[] | void; + +export class LootTables { + #conditions = new Map>(); + #functions = new Map>(); + #modifiers: { mod: string; table: string; fn: Modifier }[] = []; + + register_condition(mod: string, id: string, fn: (params: LootParams, context: LootContext) => boolean) { + this.#own(mod, id, "loot condition", this.#conditions); + this.#conditions.set( + id, + (params: LootCondition, context) => + run_guarded(mod, `loot condition ${id}`, () => fn(params, context)) === true, + ); + } + + register_function( + mod: string, + id: string, + fn: (item: ItemStack, params: LootParams, context: LootContext) => ItemStack | undefined, + ) { + this.#own(mod, id, "loot function", this.#functions); + this.#functions.set(id, (item: LootItem, params: LootFunction, context) => { + // one that throws leaves the item as it was + let ok = false; + const result = run_guarded(mod, `loot function ${id}`, () => { + const changed = fn({ ...item }, params, context); + ok = true; + return changed; + }); + return ok ? result : item; + }); + } + + modify(mod: string, table: string, fn: Modifier) { + this.#modifiers.push({ mod, table, fn }); + } + + #own(mod: string, id: string, what: string, map: Map) { + if (!id.startsWith(`${mod}:`)) throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`); + if (map.has(id)) throw new ModLoadError(mod, `${what} ${id} is registered twice`); + } + + exists(id: string): boolean { + return EverythingRegistry.get("loot_tables", id) !== undefined; + } + + // what the table gives with the mods' modifiers, in stacks that fit a slot. throws for a table that doesn't exist + roll(id: string, context: LootContext = {}): ItemStack[] { + let items: ItemStack[] = roll_loot(id, context, { conditions: this.#conditions, functions: this.#functions }); + for (const { mod, table, fn } of this.#modifiers) { + if (table !== "*" && table !== id) continue; + const list = items.map((item) => ({ ...item })); + const result = run_guarded(mod, `a loot modifier for ${table}`, () => fn(list, context, id) ?? list); + if (result) items = result.filter((item) => item && typeof item.id === "string" && item.count > 0); + } + return items.flatMap(split_stack); + } + + // after every setup ran: every mod condition and function a table uses must be registered, like components + check() { + for (const [id, table] of EverythingRegistry.entries("loot_tables")) { + for (const custom of loot_references(table).custom) { + if (!this.#conditions.has(custom) && !this.#functions.has(custom)) { + throw new ModLoadError( + id.split(":")[0], + `loot table ${id} uses ${custom}, which nothing registered`, + ); + } + } + } + } +} + +// more than a slot holds is several stacks, like minecraft's +function split_stack(item: ItemStack): ItemStack[] { + const max = EverythingRegistry.get("items", item.id)?.max_stack ?? 64; + const stacks: ItemStack[] = []; + for (let left = item.count; left > 0; left -= max) { + stacks.push({ ...item, count: Math.min(left, max), data: structuredClone(item.data) }); + } + return stacks; +} diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 96110fa..0cdd694 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -2,7 +2,8 @@ // see docs/modding/. parts not built yet throw when used, saying so import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "$/common/everything_registry.ts"; import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts"; -import { get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts"; +import { block_states, get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts"; +import { LootTables } from "./loot.ts"; import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts"; import { AIR, ID_MASK } from "$/common/constants.ts"; import { BlockRules } from "$/common/block_rules.ts"; @@ -22,6 +23,7 @@ import type { ItemComponent, ItemStack, LivingRef, + LootContext, MenuBuilder, MenuHandle, MenuType, @@ -163,6 +165,8 @@ export class ModRuntime { #next_timer = 1; #setting_up = true; #players = new WeakMap(); + // loot tables with what mods registered for them, see ctx.loot + readonly loot = new LootTables(); // mod channels, see ctx.net: who listens on each channel #net_handlers = new Map void }[]>(); // mod messages each player sent this second, to drop floods @@ -344,6 +348,8 @@ export class ModRuntime { } } + this.loot.check(); + for (const [id, block] of EverythingRegistry.entries<{ components?: Record }>("blocks")) { for (const component of Object.keys(block.components ?? {})) { if (!this.block_components.has(component) && !this.rules.has(component)) { @@ -506,6 +512,19 @@ export class ModRuntime { }; } + // a script's loot context with its block's states read from the world, when it didn't give them + #loot_context(context: LootContext = {}): LootContext { + const block = context.block; + if (!block || block.states) return context; + const world = this.game.world; + const info = world.get_block_info(block.x, block.y, block.z); + if (info?.id !== block.id) return context; + return { + ...context, + block: { ...block, states: block_states(world.get_block_value(block.x, block.y, block.z), info) }, + }; + } + #context(mod: string, version: string): ServerContext { const setup_only = (what: string) => { if (!this.#setting_up) { @@ -759,6 +778,38 @@ export class ModRuntime { list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []), }, tags: tag_api(), + loot: { + exists: (id) => this.loot.exists(id), + roll: (id, context) => this.loot.roll(id, this.#loot_context(context)), + fill: (container, id, context) => { + const items = this.loot.roll(id, this.#loot_context(context)); + // empty slots in a random order, one item each, like minecraft's chests + const empty = [...Array(container.size).keys()].filter((slot) => !container.get(slot)); + for (let i = empty.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [empty[i], empty[j]] = [empty[j], empty[i]]; + } + const left: ItemStack[] = []; + for (const item of items) { + const slot = empty.pop(); + if (slot === undefined) left.push(item); + else container.set(slot, item); + } + return left; + }, + register_condition: (id, condition) => { + setup_only("loot conditions"); + this.loot.register_condition(mod, id, condition); + }, + register_function: (id, fn) => { + setup_only("loot functions"); + this.loot.register_function(mod, id, fn); + }, + modify: (table, fn) => { + setup_only("loot modifiers"); + this.loot.modify(mod, table, fn); + }, + }, containers: { create: (size) => { if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_SIZE) { @@ -1014,7 +1065,7 @@ export function item_api(stack: EngineItemStack): ItemStack { }; } -function new_stack(item: ItemStack): EngineItemStack { +export function new_stack(item: ItemStack): EngineItemStack { if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`); const stack = new EngineItemStack(item.id, item.count); if (item.data !== undefined) stack.data = structuredClone(item.data); @@ -1254,7 +1305,7 @@ function living_ref(entity: LivingEntity): LivingRef { }; } -function entity_ref(entity: Entity): EntityRef { +export function entity_ref(entity: Entity): EntityRef { return { id: entity.id, type: entity.type, diff --git a/server/load_bmods.ts b/server/load_bmods.ts index ede1432..b9a0504 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -106,6 +106,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod { entity_models: entries(bmod.data.entity_models), effects: entries(bmod.data.effects), tags: entries(bmod.data.tags), + loot_tables: entries(bmod.data.loot_tables ?? []), textures: [...bmod.textures.keys()], texture_files: new Map(), texture_json: new Map(bmod.texture_json), diff --git a/tests/helpers.ts b/tests/helpers.ts index b3a5bd9..8dd54ba 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -38,6 +38,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] { entity_models: mod.entity_models.map((m) => m.json), effects: mod.effects.map((e) => e.json), tags: mod.tags.map((t) => t.json), + loot_tables: mod.loot_tables.map((t) => t.json), }, server_url: url(scripts.server), worldgen_url: url(scripts.worldgen), diff --git a/tests/loot_test.ts b/tests/loot_test.ts new file mode 100644 index 0000000..e32a6ec --- /dev/null +++ b/tests/loot_test.ts @@ -0,0 +1,319 @@ +// loot tables: rolling them, checking them, and the game using them for blocks, mobs and scripts +import { assert, assertEquals, assertThrows } from "@std/assert"; +import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; +import { + type BaseLootContext, + type LootEnvironment, + type LootTableJson, + number, + roll_loot, + validate_loot_table, +} from "$/common/loot.ts"; +import { Tags } from "$/common/tags.ts"; +import { load_and_check } from "$/tools/check_mods.ts"; +import { create_entity } from "$/server/game/entity/entity_types.ts"; +import type { LivingEntity } from "$/server/game/entity/living_entity.ts"; +import { copy_dir, test_game } from "./helpers.ts"; + +// the tables, registered fresh, with a tool and a tag to match +function tables(...list: LootTableJson[]) { + EverythingRegistry.clear(); + for (const table of list) EverythingRegistry.register("loot_tables", table.id, table); + EverythingRegistry.register("items", "t:pick", { + texture_id: "t:pick", + tool: { type: "pickaxe", tier: 2, speed: 1, durability: 1 }, + }); + Tags.load(new Map([["items", new Map([["t:gems", ["t:ruby", "t:opal"]]])]])); +} + +// random numbers from a list, round and round +const randoms = (...values: number[]): LootEnvironment => { + let i = 0; + return { random: () => values[i++ % values.length] }; +}; + +const roll = (id: string, context: BaseLootContext = {}, env = randoms(0)) => roll_loot(id, context, env); + +Deno.test("a pool picks entries by weight, as many times as it rolls", () => { + tables({ + id: "t:fish", + pools: [{ rolls: 2, entries: [{ item: "t:cod", weight: 3 }, { item: "t:salmon", weight: 1 }] }], + }); + // 0.5 of 4 is in cod's 3, 0.9 of 4 in salmon's 1 + assertEquals(roll("t:fish", {}, randoms(0.5, 0.9)), [{ id: "t:cod", count: 1 }, { id: "t:salmon", count: 1 }]); +}); + +Deno.test("counts come from a number, a range or tries at a chance", () => { + const env = { random: () => 0.5 }; + assertEquals(number(3, env), 3); + assertEquals(number({ min: 1, max: 4 }, env), 3); + assertEquals(number({ n: 3, p: 0.6 }, env), 3); + assertEquals(number({ n: 3, p: 0.4 }, env), 0); + tables({ + id: "t:seeds", + pools: [{ + entries: [{ + item: "t:seed", + count: 1, + functions: [{ function: "set_count", count: { n: 3, p: 0.6 }, add: true }, { + function: "limit_count", + max: 3, + }], + }], + }], + }); + assertEquals(roll("t:seeds", {}, randoms(0.5)), [{ id: "t:seed", count: 3 }]); +}); + +Deno.test("conditions on tables, pools and entries: tools, block states, chance, who killed it", () => { + tables({ + id: "t:ore", + pools: [ + { + conditions: [{ condition: "match_tool", tool: "pickaxe", min_tier: 2 }], + entries: [{ item: "t:ruby" }], + }, + { + entries: [ + { item: "t:ripe", conditions: [{ condition: "block_state", states: { age: { min: 3 } } }] }, + { + item: "t:unripe", + conditions: [{ + condition: "inverted", + term: { condition: "block_state", states: { age: { min: 3 } } }, + }], + }, + ], + }, + { + conditions: [{ + condition: "any_of", + terms: [{ condition: "killed_by_player" }, { condition: "random_chance", chance: 0.25 }], + }], + entries: [{ item: "t:bonus" }], + }, + ], + }); + const ids = (context: BaseLootContext, random = 0.5) => + roll("t:ore", context, randoms(random)).map((item) => item.id); + assertEquals(ids({ tool: { id: "t:pick" }, block: { id: "t:ore", states: { age: 3 } } }), ["t:ruby", "t:ripe"]); + assertEquals(ids({ block: { id: "t:ore", states: { age: 1 } } }), ["t:unripe"]); + assertEquals(ids({ killed_by_player: true }), ["t:unripe", "t:bonus"]); + assertEquals(ids({}, 0.1), ["t:unripe", "t:bonus"]); +}); + +Deno.test("entries can be a tag's item, another table, or nothing, and set data", () => { + tables( + { + id: "t:chest", + pools: [{ + rolls: 3, + entries: [ + { type: "tag", tag: "#t:gems" }, + { type: "loot_table", table: "t:inner" }, + { type: "empty" }, + ], + }], + }, + { + id: "t:inner", + pools: [{ entries: [{ item: "t:map", functions: [{ function: "set_data", data: { to: "treasure" } }] }] }], + }, + { id: "t:loop", pools: [{ entries: [{ type: "loot_table", table: "t:loop" }] }] }, + ); + // each roll: 0.1 is the tag (then 0 its first item), 0.5 the table (then 0 its only entry), 0.9 nothing + assertEquals(roll("t:chest", {}, randoms(0.1, 0, 0.5, 0, 0.9)), [ + { id: "t:ruby", count: 1 }, + { id: "t:map", count: 1, data: { to: "treasure" } }, + ]); + assertThrows(() => roll("t:loop"), Error, "in itself"); + assertThrows(() => roll("t:nope"), Error, "doesn't exist"); +}); + +Deno.test("mods' conditions and functions are looked up by id", () => { + tables({ + id: "t:magic", + pools: [{ + conditions: [{ condition: "m:night" }], + entries: [{ item: "t:star", functions: [{ function: "m:double" }] }], + }], + }); + const env = (night: boolean): LootEnvironment => ({ + random: () => 0, + conditions: new Map([["m:night", () => night]]), + functions: new Map([["m:double", (item) => ({ ...item, count: item.count * 2 })]]), + }); + assertEquals(roll_loot("t:magic", {}, env(true)), [{ id: "t:star", count: 2 }]); + assertEquals(roll_loot("t:magic", {}, env(false)), []); + assertThrows(() => roll("t:magic"), Error, "m:night isn't registered"); +}); + +Deno.test("a table's json says what's wrong with it", () => { + const table = { id: "t:x", pools: [{ entries: [{ item: "t:a" }] }] }; + assertEquals(validate_loot_table(table), []); + const problems = (json: unknown) => validate_loot_table(json).join("\n"); + assert(problems({ ...table, pools: [{ entries: [] }] }).includes("entries must be a list")); + assert(problems({ ...table, pools: [{ rolls: -1, entries: [{ item: "t:a" }] }] }).includes("rolls")); + assert(problems({ ...table, pools: [{ entries: [{ type: "tag", tag: "t:gems" }] }] }).includes("#tag")); + assert(problems({ ...table, pools: [{ entries: [{ type: "loot_table" }] }] }).includes("table is needed")); + assert(problems({ ...table, conditions: [{ condition: "full_moon" }] }).includes("isn't a loot condition")); + assert(problems({ ...table, functions: [{ function: "enchant" }] }).includes("isn't a loot function")); + assert(problems({ ...table, conditions: [{ condition: "random_chance", chance: 2 }] }).includes("0 to 1")); + // a mod's own are only checked once its script registers them + assertEquals(validate_loot_table({ ...table, conditions: [{ condition: "m:full_moon" }] }), []); +}); + +// a mod with loot tables for a block, a mob and a chest, and a script with its own condition, function and modifier +function loot_mod(dir: string) { + const mod = `${dir}/testloot`; + const write = (path: string, json: unknown) => { + Deno.mkdirSync(`${mod}/${path.split("/").slice(0, -1).join("/")}`, { recursive: true }); + Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json)); + }; + write("manifest.json", { + format_version: 1, + id: "testloot", + name: "Test Loot", + version: "1.0.0", + dependencies: [{ id: "bworld", version: "*" }], + scripts: { server: "scripts/server.ts" }, + }); + for (const id of ["gem", "charm"]) { + write(`items/${id}.json`, { format_version: 1, item: { id: `testloot:${id}`, texture: `testloot:${id}` } }); + } + write("blocks/ore.json", { + format_version: 1, + block: { + id: "testloot:ore", + textures: "bworld:stone", + mining: { toughness: 0 }, + loot_table: "testloot:blocks/ore", + }, + }); + write("entities/golem.json", { + format_version: 1, + entity: { + id: "testloot:golem", + texture: "bworld:stone", + width: 1, + height: 2, + max_health: 10, + loot_table: "testloot:entities/golem", + }, + }); + const table = (path: string, loot_table: unknown) => + write(`loot_tables/${path}.json`, { format_version: 1, loot_table }); + // 2 gems for a pickaxe, doubled by the mod's function + table("blocks/ore", { + pools: [{ + conditions: [{ condition: "match_tool", tool: "pickaxe" }], + entries: [{ item: "testloot:gem", count: 2, functions: [{ function: "testloot:double" }] }], + }], + }); + // a gem when a player killed it, a charm when it died up high + table("entities/golem", { + pools: [ + { conditions: [{ condition: "killed_by_player" }], entries: [{ item: "testloot:gem" }] }, + { conditions: [{ condition: "testloot:high" }], entries: [{ item: "testloot:charm" }] }, + ], + }); + table("chests/treasure", { pools: [{ rolls: 3, entries: [{ item: "testloot:gem" }] }] }); + Deno.mkdirSync(`${mod}/scripts`); + Deno.writeTextFileSync( + `${mod}/scripts/server.ts`, + `import type { ServerContext } from "bworld/server"; +export function setup(ctx: ServerContext) { + ctx.loot.register_condition("testloot:high", (_params, context) => (context.position?.y ?? 0) > 120); + ctx.loot.register_function("testloot:double", (item) => ({ ...item, count: item.count * 2 })); + ctx.loot.modify("testloot:chests/treasure", (items) => { items.push({ id: "testloot:charm", count: 1 }); }); + ctx.events.after.chat_send.subscribe(({ message }) => { + if (message !== "treasure") return; + const container = ctx.containers.create(2); + const left = ctx.loot.fill(container, "testloot:chests/treasure"); + const slots = [0, 1].map((slot) => container.get(slot)?.id ?? null).sort(); + ctx.storage.set("filled", { slots, left: left.map((item) => item.id) }); + }); +} +`, + ); +} + +async function setup() { + const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + loot_mod(dir); + const t = await test_game(dir); + t.join(1, "alice"); + t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 }); + return { ...t, dir }; +} + +Deno.test("check-mods catches loot tables that point at nothing", () => { + const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_check_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + loot_mod(dir); + const ok = load_and_check(dir).find((mod) => mod.id === "testloot")!; + assertEquals(ok.report.errors, []); + assertEquals(ok.loot_tables.map((t) => t.json.id).sort(), [ + "testloot:blocks/ore", + "testloot:chests/treasure", + "testloot:entities/golem", + ]); + + Deno.writeTextFileSync( + `${dir}/testloot/loot_tables/broken.json`, + JSON.stringify({ + format_version: 1, + loot_table: { + pools: [{ entries: [{ item: "testloot:nothing" }, { type: "loot_table", table: "testloot:nowhere" }] }], + }, + }), + ); + const errors = load_and_check(dir).find((mod) => mod.id === "testloot")!.report.errors; + assert(errors.some((e) => e.includes("item testloot:nothing doesn't exist")), errors.join("\n")); + assert(errors.some((e) => e.includes("loot table testloot:nowhere doesn't exist")), errors.join("\n")); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("a broken block drops from its loot table, with the tool it was broken with", async () => { + const t = await setup(); + const dropped = () => t.game.item_entities().map((e) => e.item.to_data()); + t.game.set_block(1, 100, 0, "testloot:ore"); + t.send(1, { type: "break_block", x: 1, y: 100, z: 0 }); + // broken by hand, it gives nothing + assertEquals(t.game.world.get_block_id(1, 100, 0), "bworld:air"); + assertEquals(dropped(), []); + + t.send(1, { type: "chat", text: "/give bworld:iron_pickaxe" }); + t.game.set_block(1, 100, 0, "testloot:ore"); + t.send(1, { type: "break_block", x: 1, y: 100, z: 0 }); + assertEquals(dropped(), [{ id: "testloot:gem", count: 4 }]); + Deno.removeSync(t.dir, { recursive: true }); +}); + +Deno.test("a mob drops its loot table when it dies, more when a player killed it", async () => { + const t = await setup(); + const player = t.game.players()[0]; + const kill = (y: number, by_player: boolean) => { + for (const item of t.game.item_entities()) item.remove(); + const golem = create_entity(t.game.entities, "testloot:golem") as LivingEntity; + golem.set_position(0.5, y, 3.5); + t.game.entities.add_entity(golem); + golem.hurt(100, { type: "physical", cause: "test", attacker: by_player ? player : undefined, by_player }); + return t.game.item_entities().map((e) => e.item.type_id).sort(); + }; + assertEquals(kill(100, false), []); + assertEquals(kill(100, true), ["testloot:gem"]); + assertEquals(kill(130, true), ["testloot:charm", "testloot:gem"]); + Deno.removeSync(t.dir, { recursive: true }); +}); + +Deno.test("scripts fill containers from a table their modifier changes, and keep what doesn't fit", async () => { + const t = await setup(); + t.send(1, { type: "chat", text: "treasure" }); + // 3 gems and the modifier's charm, into 2 slots + const filled = t.game.mods.storage.testloot.filled as { slots: string[]; left: string[] }; + assertEquals(filled.slots.length, 2); + assertEquals([...filled.slots, ...filled.left].sort(), ["testloot:charm", ...Array(3).fill("testloot:gem")]); + Deno.removeSync(t.dir, { recursive: true }); +}); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index e20551d..a7a9709 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -20,6 +20,7 @@ import { import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts"; import { png_size, texture_size_problem } from "$/common/bmod.ts"; import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts"; +import { type LootTableJson, validate_loot_table } from "$/common/loot.ts"; import { dirname } from "@std/path"; export { load_order, type LoadedMod, type ModReport }; @@ -80,6 +81,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod { entity_models: [], effects: [], tags: [], + loot_tables: [], textures: [], texture_files: new Map(), texture_json: new Map(), @@ -178,6 +180,21 @@ function load_mod(mods_dir: string, id: string): LoadedMod { if (problems.length === 0) mod.tags.push({ file: path, json: json as TagJson }); } + // loot_tables/.json is the loot table :, like minecraft's + for (const file of walk(`${dir}/loot_tables`, ".json")) { + const path = `loot_tables/${file}`; + const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); + if (wrapper === undefined) continue; + if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !is_object(wrapper.loot_table)) { + error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "loot_table": { "pools": [ ... ] } }`); + continue; + } + const json = { ...wrapper.loot_table, id: `${id}:${file.replace(/\.json$/, "")}` }; + const problems = validate_loot_table(json); + for (const problem of problems) error(`${path}: ${problem}`); + if (problems.length === 0) mod.loot_tables.push({ file: path, json: json as LootTableJson }); + } + if (exists(`${dir}/worldgen/ores.json`)) { const ores = read_json(`${dir}/worldgen/ores.json`, (m) => error(`worldgen/ores.json: ${m}`)); if (!is_object(ores) || ores.format_version !== FORMAT_VERSION || !Array.isArray(ores.ores)) { diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index ca298d4..62dea94 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -42,6 +42,7 @@ export async function pack_mod(mod: LoadedMod): Promise> entity_models: mod.entity_models.map((m) => m.json), effects: mod.effects.map((e) => e.json), tags: mod.tags.map((t) => t.json), + loot_tables: mod.loot_tables.map((t) => t.json), }, scripts, textures,