Loot tables

This commit is contained in:
2026-10-08 00:54:45 -03:00
parent 757ee74bc7
commit ec2b53c02a
45 changed files with 1733 additions and 150 deletions
+1
View File
@@ -61,6 +61,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Block Models](docs/modding/resources/models.md) - [Block Models](docs/modding/resources/models.md)
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing and your own recipe types - [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 - [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** **Everything else**
+4 -2
View File
@@ -28,6 +28,7 @@ import {
validate_tag, validate_tag,
} from "./mod_data.ts"; } from "./mod_data.ts";
import type { ModData } from "./mod_loader.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 { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts"; import { ENGINE_GLOBAL } from "./hooks.ts";
@@ -63,7 +64,7 @@ export class BmodError extends Error {
// the zip's layout: // the zip's layout:
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip // 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/<side>.js // scripts/<side>.js
// textures/<name>.png the texture <mod id>:<name> // textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one // textures/<name>.json its animation, if it has one
@@ -161,10 +162,11 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
) as EntityModelJson[], ) as EntityModelJson[],
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[], effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[], 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 // a mod only registers ids in its own namespace
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models]; 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`); if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
} }
+2
View File
@@ -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 // the lowest tool tier it drops for when requires_tool, like minecraft's incorrect_for_*_tool tags. 0 when not set
tool_tier?: number; tool_tier?: number;
drop_table?: string; 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[]; states?: BlockStateDefinition[];
// a different model or textures for some states, by conditions like "age=7". the first match wins // a different model or textures for some states, by conditions like "age=7". the first match wins
+453
View File
@@ -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/<path>.json in a mod is <mod>:<path>
id: string;
pools: LootPool[];
conditions?: LootCondition[];
functions?: LootFunction[];
}
// an item a table gives
export interface LootItem {
id: string;
count: number;
data?: unknown;
}
// what the built in conditions read from what's happening. more is there for mods' conditions and functions, like
// the player, see LootContext in mod_api/server.ts
export interface BaseLootContext {
// the block being broken, with its states
block?: { id: string; states?: Record<string, number> };
// what it's done with, like the tool breaking the block or the fishing rod
tool?: { id: string };
// a player killed the entity it's for
killed_by_player?: boolean;
}
// a mod's condition: whether it holds, from its params (the condition's json) and what's happening
export type LootConditionFn<C> = (params: LootCondition, context: C) => boolean;
// a mod's function: the item changed, or undefined to take it away
export type LootFunctionFn<C> = (item: LootItem, params: LootFunction, context: C) => LootItem | undefined;
export interface LootEnvironment<C extends BaseLootContext> {
conditions?: ReadonlyMap<string, LootConditionFn<C>>;
functions?: ReadonlyMap<string, LootFunctionFn<C>>;
// 0 to 1, Math.random when not given
random?: () => number;
}
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<C extends BaseLootContext>(
id: string,
context: C,
env: LootEnvironment<C> = {},
): LootItem[] {
return roll_table(id, context, { random: Math.random, ...env }, 0);
}
type Env<C extends BaseLootContext> = LootEnvironment<C> & { random: () => number };
function roll_table<C extends BaseLootContext>(id: string, context: C, env: Env<C>, depth: number): LootItem[] {
const table = EverythingRegistry.get<LootTableJson>("loot_tables", id);
if (!table) throw new LootError(`loot table ${id} doesn't exist`);
if (depth > MAX_DEPTH) throw new LootError(`loot table ${id} is in itself, through its loot_table entries`);
if (!all(table.conditions, context, env)) return [];
const items: LootItem[] = [];
for (const pool of table.pools) {
if (!all(pool.conditions, context, env)) continue;
const rolls = number(pool.rolls ?? 1, env);
for (let i = 0; i < rolls; i++) {
const entry = pick(pool.entries.filter((e) => all(e.conditions, context, env)), env);
if (!entry) continue;
for (const item of entry_items(entry, context, env, depth)) {
const done = apply_all(apply_all(item, entry.functions, context, env), pool.functions, context, env);
if (done) items.push(done);
}
}
}
return items.flatMap((item) => apply_all(item, table.functions, context, env) ?? []).filter((item) =>
item.count > 0
);
}
// one of them by weight, undefined for none
function pick<T extends { weight?: number }>(entries: T[], env: { random: () => number }): T | undefined {
const total = entries.reduce((sum, entry) => sum + (entry.weight ?? 1), 0);
if (total <= 0) return undefined;
let left = env.random() * total;
for (const entry of entries) {
left -= entry.weight ?? 1;
if (left < 0) return entry;
}
return entries.at(-1);
}
function entry_items<C extends BaseLootContext>(entry: LootEntry, context: C, env: Env<C>, depth: number): LootItem[] {
switch (entry.type ?? "item") {
case "item":
return [{ id: entry.item!, count: number(entry.count ?? 1, env) }];
case "tag": {
const items = Tags.get("items", entry.tag!);
const id = items[Math.floor(env.random() * items.length)];
return id === undefined ? [] : [{ id, count: number(entry.count ?? 1, env) }];
}
case "loot_table":
return roll_table(entry.table!, context, env, depth + 1);
default:
return [];
}
}
export function number(provider: NumberProvider, env: { random: () => number }): number {
if (typeof provider === "number") return provider;
if ("min" in provider) return provider.min + Math.floor(env.random() * (provider.max - provider.min + 1));
let count = 0;
for (let i = 0; i < provider.n; i++) if (env.random() < provider.p) count++;
return count;
}
function all<C extends BaseLootContext>(conditions: LootCondition[] | undefined, context: C, env: Env<C>): boolean {
return (conditions ?? []).every((condition) => holds(condition, context, env));
}
function holds<C extends BaseLootContext>(condition: LootCondition, context: C, env: Env<C>): boolean {
switch (condition.condition) {
case "random_chance":
return env.random() < (condition.chance as number);
case "match_tool": {
const id = context.tool?.id;
if (!id) return false;
const items = condition.items as string[] | undefined;
if (items && !list_matches("items", items, id)) return false;
const tool = EverythingRegistry.get<ItemRegistry>("items", id)?.tool;
if (condition.tool !== undefined && tool?.type !== condition.tool) return false;
if (condition.min_tier !== undefined && (tool?.tier ?? -1) < (condition.min_tier as number)) return false;
return true;
}
case "block_state": {
const block = context.block;
if (!block) return false;
if (condition.block !== undefined && block.id !== condition.block) return false;
return Object.entries(condition.states as Record<string, StateMatch>).every(([name, match]) => {
const value = block.states?.[name];
if (value === undefined) return false;
if (typeof match === "number") return value === match;
return value >= (match.min ?? -Infinity) && value <= (match.max ?? Infinity);
});
}
case "killed_by_player":
return context.killed_by_player === true;
case "inverted":
return !holds(condition.term as LootCondition, context, env);
case "any_of":
return (condition.terms as LootCondition[]).some((term) => holds(term, context, env));
case "all_of":
return (condition.terms as LootCondition[]).every((term) => holds(term, context, env));
}
const custom = env.conditions?.get(condition.condition);
if (!custom) throw new LootError(`loot condition ${condition.condition} isn't registered`);
return custom(condition, context);
}
type StateMatch = number | { min?: number; max?: number };
function apply_all<C extends BaseLootContext>(
item: LootItem | undefined,
functions: LootFunction[] | undefined,
context: C,
env: Env<C>,
): LootItem | undefined {
for (const fn of functions ?? []) {
if (!item) return undefined;
item = apply(item, fn, context, env);
}
return item;
}
function apply<C extends BaseLootContext>(
item: LootItem,
fn: LootFunction,
context: C,
env: Env<C>,
): LootItem | undefined {
if (!all(fn.conditions as LootCondition[] | undefined, context, env)) return item;
switch (fn.function) {
case "set_count": {
const count = number(fn.count as NumberProvider, env);
return { ...item, count: fn.add ? item.count + count : count };
}
case "limit_count": {
const min = (fn.min as number | undefined) ?? 0;
const max = (fn.max as number | undefined) ?? Infinity;
return { ...item, count: Math.min(Math.max(item.count, min), max) };
}
case "set_data":
return { ...item, data: structuredClone(fn.data) };
}
const custom = env.functions?.get(fn.function);
if (!custom) throw new LootError(`loot function ${fn.function} isn't registered`);
return custom(item, fn, context);
}
// checking a table's json
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<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+42
View File
@@ -19,6 +19,7 @@ export interface ServerContext {
blocks: BlockApi; blocks: BlockApi;
recipes: RecipeApi; recipes: RecipeApi;
tags: TagApi; tags: TagApi;
loot: LootApi;
menus: MenuRegistry; menus: MenuRegistry;
ui: ServerUi; ui: ServerUi;
net: ServerNet; net: ServerNet;
@@ -388,6 +389,47 @@ export interface RecipeApi {
list(type: Id): any[]; 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<string, number> };
// 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<string, any>;
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 // forms, not built yet: menus whose screens the engine provides, see docs/modding_plan.md
export interface ActionForm { export interface ActionForm {
+21 -1
View File
@@ -18,6 +18,7 @@ import { PLAYER_PARTS } from "./everything_registry.ts";
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts"; import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
import { resolve_tags } from "./tags.ts"; import { resolve_tags } from "./tags.ts";
import type { TextureJson } from "./texture_animation.ts"; import type { TextureJson } from "./texture_animation.ts";
import { loot_references, type LootTableJson } from "./loot.ts";
import { BIOMES } from "./worldgen/overworld.ts"; import { BIOMES } from "./worldgen/overworld.ts";
export interface ModReport { export interface ModReport {
@@ -41,6 +42,7 @@ export interface LoadedMod {
entity_models: { file: string; json: EntityModelJson }[]; entity_models: { file: string; json: EntityModelJson }[];
effects: { file: string; json: EffectJson }[]; effects: { file: string; json: EffectJson }[];
tags: { file: string; json: TagJson }[]; tags: { file: string; json: TagJson }[];
loot_tables: { file: string; json: LootTableJson }[];
textures: string[]; textures: string[];
// absolute paths by texture id // absolute paths by texture id
texture_files: Map<string, string>; texture_files: Map<string, string>;
@@ -87,6 +89,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const effect_owners = new Map<string, string[]>(); const effect_owners = new Map<string, string[]>();
const tag_owners = new Map<TagRegistry, Set<string>>(); const tag_owners = new Map<TagRegistry, Set<string>>();
const liquids = new Set<string>(); const liquids = new Set<string>();
const loot_tables = new Set<string>();
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]); const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
const textures = new Set<string>(engine_textures); const textures = new Set<string>(engine_textures);
@@ -109,6 +112,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
entity_model_jsons.set(json.id, json); entity_model_jsons.set(json.id, json);
} }
for (const { json } of mod.effects) add(effect_owners, json.id, mod.id); for (const { json } of mod.effects) add(effect_owners, json.id, mod.id);
for (const { json } of mod.loot_tables ?? []) loot_tables.add(json.id);
for (const { json } of mod.tags) { for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set()); if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
tag_owners.get(json.registry)!.add(json.id); tag_owners.get(json.registry)!.add(json.id);
@@ -138,7 +142,11 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}; };
// block and item ids can be #tags, like in recipes and place_on // block and item ids can be #tags, like in recipes and place_on
const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => { const uses = (
file: string,
id: string,
what: "block" | "item" | "texture" | "model" | "entity model" | "loot table",
) => {
check_namespace(file, id); check_namespace(file, id);
if (id.startsWith("#") && (what === "block" || what === "item")) { if (id.startsWith("#") && (what === "block" || what === "item")) {
if (!tag_owners.get(what === "block" ? "blocks" : "items")?.has(id.slice(1))) { 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<st
if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`); if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`);
} else if (what === "texture") { } else if (what === "texture") {
if (!textures.has(id)) warnings.push(`${file}: texture ${id} doesn't exist, it will show as missing`); if (!textures.has(id)) warnings.push(`${file}: texture ${id} doesn't exist, it will show as missing`);
} else if (what === "loot table") {
if (!loot_tables.has(id)) errors.push(`${file}: loot table ${id} doesn't exist`);
} else if (!(what === "block" ? block_owners : item_owners).has(id)) { } else if (!(what === "block" ? block_owners : item_owners).has(id)) {
errors.push(`${file}: ${what} ${id} doesn't exist`); errors.push(`${file}: ${what} ${id} doesn't exist`);
} }
@@ -167,6 +177,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
} }
} }
if (json.drops) uses(file, json.drops, "item"); if (json.drops) uses(file, json.drops, "item");
if (json.loot_table) uses(file, json.loot_table, "loot table");
if (json.waterloggable) { if (json.waterloggable) {
uses(file, json.waterloggable, "block"); uses(file, json.waterloggable, "block");
if (block_owners.has(json.waterloggable) && !liquids.has(json.waterloggable)) { if (block_owners.has(json.waterloggable) && !liquids.has(json.waterloggable)) {
@@ -251,6 +262,15 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
} }
if (json.model !== undefined) uses(file, json.model, "entity model"); if (json.model !== undefined) uses(file, json.model, "entity model");
uses(file, json.texture, "texture"); uses(file, json.texture, "texture");
if (json.loot_table) uses(file, json.loot_table, "loot table");
}
for (const { file, json } of mod.loot_tables ?? []) {
const refs = loot_references(json);
for (const id of refs.items) uses(file, id, "item");
for (const id of refs.tags) uses(file, id, "item");
for (const id of refs.tables) uses(file, id, "loot table");
// mods' conditions and functions are registered by scripts, the server checks them when it starts
for (const id of refs.custom) check_namespace(file, id);
} }
for (const { file, json } of mod.effects) { for (const { file, json } of mod.effects) {
if ((effect_owners.get(json.id)?.length ?? 0) > 1) { if ((effect_owners.get(json.id)?.length ?? 0) > 1) {
+17
View File
@@ -79,6 +79,8 @@ export interface BlockJson {
item_display?: { surface: number }; item_display?: { surface: number };
// makes it a liquid, see LiquidProperties. range is 7 when not set // makes it a liquid, see LiquidProperties. range is 7 when not set
liquid?: Partial<LiquidProperties>; liquid?: Partial<LiquidProperties>;
// 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 // the liquid it can hold, see BlockRegistry.waterloggable
waterloggable?: string; waterloggable?: string;
// only placed into a source of it, see BlockRegistry.waterlogged_only // 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 // protection from physical and from arcane damage, not used yet
physical_shielding?: number; physical_shielding?: number;
arcane_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 // 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.tool_tier) json.mining.tier = block.tool_tier;
} }
if (block.drop_table !== undefined) json.drops = block.drop_table; 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 (!has_item) json.item = false;
if (block.interactive) json.interactive = true; if (block.interactive) json.interactive = true;
if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable; 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.mining.tier) block.tool_tier = json.mining.tier;
} }
if (json.drops !== undefined) block.drop_table = json.drops; 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.interactive) block.interactive = true;
if (json.replaceable ?? json.liquid) block.replaceable = true; if (json.replaceable ?? json.liquid) block.replaceable = true;
if (json.place_on) block.place_on = json.place_on; 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.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) { if (json.item_display !== undefined) {
const surface = is_object(json.item_display) ? json.item_display.surface : undefined; const surface = is_object(json.item_display) ? json.item_display.surface : undefined;
if (typeof surface !== "number" || surface < 0 || surface > 16) { 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)) { if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) {
problems.push('behavior must be "animal", "monster" or "scripted"'); 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"]) { for (const key of ["width", "height"]) {
if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { 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`); problems.push(`${key} must be a number of blocks above 0, at most 16`);
+6
View File
@@ -21,6 +21,7 @@ import {
TagRegistry, TagRegistry,
} from "./mod_data.ts"; } from "./mod_data.ts";
import { resolve_tags, Tags } from "./tags.ts"; import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { register_block_item } from "./utils.ts"; import { register_block_item } from "./utils.ts";
import type { ModelJson } from "./block_models.ts"; import type { ModelJson } from "./block_models.ts";
@@ -40,6 +41,8 @@ export interface ModData {
effects: EffectJson[]; effects: EffectJson[];
// tag files, see common/tags.ts // tag files, see common/tags.ts
tags: TagJson[]; 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 // 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) { for (const json of data.effects) {
EverythingRegistry.register<EffectJson>("effects", json.id, json); EverythingRegistry.register<EffectJson>("effects", json.id, json);
} }
for (const json of data.loot_tables ?? []) {
EverythingRegistry.register<LootTableJson>("loot_tables", json.id, json);
}
} catch (e) { } catch (e) {
throw new ModLoadError(id, (e as Error).message); throw new ModLoadError(id, (e as Error).message);
} }
+7
View File
@@ -86,6 +86,13 @@ export function get_state_value(value: number, block_info: BlockRegistry, name:
return (state_bits & s.mask) >>> s.shift; 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<string, number> {
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) { export function set_state_value(value: number, block_info: BlockRegistry, name: string, new_value: number) {
if (!block_info.states) { if (!block_info.states) {
return undefined; return undefined;
+66 -24
View File
@@ -25,6 +25,7 @@ the day before grows a day, then all farmland dries out. The crop shows the stag
"render_layer": "cutout", "render_layer": "cutout",
"collision": false, "collision": false,
"mining": { "toughness": 0 }, "mining": { "toughness": 0 },
"loot_table": "farmersdelight:blocks/cabbages",
"item": false, "item": false,
"place_on": ["bworld:hoed_dirt"], "place_on": ["bworld:hoed_dirt"],
"states": [{ "name": "age", "bits": 3, "default": 0 }], "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": { "bworld:crop": {
"days": 12, "days": 12,
"stages": 8, "stages": 8,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "farmersdelight:cabbage_seeds",
"mature": "farmersdelight:cabbage",
"bonus": "farmersdelight:cabbage_seeds"
}
} }
} }
} }
@@ -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. `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 ## Parameters
| Param | Meaning | | Param | Meaning |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `days` | Watered mornings from planting to fully grown. | | `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. | | `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. |
| `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. |
| `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`. |
| `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. |
| `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. |
| `leaves` | What the spot becomes when it's broken, like the water rice was planted in. |
## Harvesting By Hand ## Harvesting By Hand
@@ -81,10 +115,17 @@ Tomatoes are picked instead of broken:
"days": 11, "days": 11,
"stages": 8, "stages": 8,
"regrow_days": 4, "regrow_days": 4,
"harvest": { "item": "farmersdelight:tomato", "count": [1, 2] }, "harvest": "farmersdelight:harvest/tomatoes"
"drops": { }
"young": "farmersdelight:tomato_seeds", ```
"mature": ["farmersdelight:tomato", "farmersdelight:tomato_seeds"]
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, "stages": 4,
"water": "always", "water": "always",
"upper": { "block": "farmersdelight:rice_panicles", "stages": 4, "supporting_age": 4 }, "upper": { "block": "farmersdelight:rice_panicles", "stages": 4, "supporting_age": 4 },
"leaves": "bworld:water", "leaves": "bworld:water"
"drops": { "young": "farmersdelight:rice", "mature": "farmersdelight:rice" }
} }
} }
``` ```
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 ```json
"loot_table": "farmersdelight:blocks/rice_panicles",
"components": { "components": {
"bworld:crop_top": { "stages": 4, "drops": { "mature": "farmersdelight:rice_panicle" } } "bworld:crop_top": { "stages": 4 }
} }
``` ```
+4 -3
View File
@@ -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.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.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. | | `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). | | `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. | | `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`. | | `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 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. 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 When it breaks, the block's components' `on_break` runs and it drops `drops` or what its `loot_table` gives, unless it
player's tool is the wrong type or a tier below `mining.tier`. has `requires_tool` and the player's tool is the wrong type or a tier below `mining.tier`.
## Placement ## Placement
+1
View File
@@ -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. | | `attack_damage` | `2` | What a monster's hits do, in half hearts. |
| `physical_shielding` | `0` | Protection from physical damage. Not used yet. | | `physical_shielding` | `0` | Protection from physical damage. Not used yet. |
| `arcane_shielding` | `0` | Protection from arcane 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 <entity>` spawns one where you stand. `/summon <entity>` spawns one where you stand.
+2 -1
View File
@@ -19,6 +19,7 @@ mods/
effects/*.json # status effects, see entities/effects.md effects/*.json # status effects, see entities/effects.md
recipes/*.json recipes/*.json
tags/<registry>/<namespace>/*.json # tags, see resources/tags.md tags/<registry>/<namespace>/*.json # tags, see resources/tags.md
loot_tables/**/*.json # loot tables, see resources/loot_tables.md
worldgen/ores.json worldgen/ores.json
worldgen/spawns.json # monsters that spawn on their own, see entities/index.md worldgen/spawns.json # monsters that spawn on their own, see entities/index.md
textures/*.png textures/*.png
@@ -114,7 +115,7 @@ deno task build # packs every mod in mods/ into server_mo
``` ```
copper_tools.bmod copper_tools.bmod
manifest.json # with scripts and credits pointing into the zip 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/server.js # each script bundled into one module
scripts/client.js scripts/client.js
scripts/worldgen.js scripts/worldgen.js
+184
View File
@@ -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");
```
+2 -6
View File
@@ -33,6 +33,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "bworld:blocks/carrots",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -48,12 +49,7 @@
"bworld:crop": { "bworld:crop": {
"days": 3, "days": 3,
"stages": 4, "stages": 4,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "bworld:carrot",
"mature": "bworld:carrot",
"bonus": "bworld:carrot"
}
} }
} }
} }
+2 -6
View File
@@ -33,6 +33,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "bworld:blocks/potatoes",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -48,12 +49,7 @@
"bworld:crop": { "bworld:crop": {
"days": 6, "days": 6,
"stages": 4, "stages": 4,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "bworld:potato",
"mature": "bworld:potato",
"bonus": "bworld:potato"
}
} }
} }
} }
+2 -6
View File
@@ -53,6 +53,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "bworld:blocks/wheat",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -68,12 +69,7 @@
"bworld:crop": { "bworld:crop": {
"days": 7, "days": 7,
"stages": 8, "stages": 8,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "bworld:wheat_seeds",
"mature": "bworld:wheat",
"bonus": "bworld:wheat_seeds"
}
} }
} }
} }
+9 -6
View File
@@ -10,12 +10,15 @@
"lore": "Right click to cast into water, and again when something bites.", "lore": "Right click to cast into water, and again when something bites.",
"components": { "components": {
"bworld:fishing_rod": { "bworld:fishing_rod": {
"wait": [100, 600], "wait": [
"bite": [20, 40], 100,
"loot": [ 600
{ "item": "bworld:cod", "weight": 60 }, ],
{ "item": "bworld:salmon", "weight": 25 } "bite": [
] 20,
40
],
"loot_table": "bworld:gameplay/fishing"
} }
} }
} }
@@ -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
}
]
}
]
}
]
}
}
@@ -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
}
]
}
]
}
]
}
}
+61
View File
@@ -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
}
]
}
]
}
]
}
}
@@ -0,0 +1,19 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"entries": [
{
"item": "bworld:cod",
"weight": 60
},
{
"item": "bworld:salmon",
"weight": 25
}
]
}
]
}
}
+10 -49
View File
@@ -352,18 +352,6 @@ interface WateringCanData {
} }
// items as they appear in crop params: one id, or several // 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 // 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 // watered the day before. see docs/modding/blocks/crops.md
interface CropParams { interface CropParams {
@@ -371,10 +359,10 @@ interface CropParams {
days: number; days: number;
// how many stages it shows, ages 0 to stages - 1. its "age" state must fit them // how many stages it shows, ages 0 to stages - 1. its "age" state must fit them
stages: number; stages: number;
drops?: CropDrops; // grows back after it's harvested by right clicking, like tomatoes, giving what this loot table does. what it
// grows back after it's harvested by right clicking, like tomatoes // drops when broken is the block's own loot table
regrow_days?: number; regrow_days?: number;
harvest?: { item: string; count: [number, number] }; harvest?: string;
// grows it a day right away, like bone meal // grows it a day right away, like bone meal
fertilizer?: string; fertilizer?: string;
// "farmland" (the default) needs watered farmland under it, "always" grows every morning, like rice in water // "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 // the top of a two block crop. it grows with the crop under it, and breaking it breaks the whole plant
interface CropTopParams { interface CropTopParams {
stages: number; stages: number;
drops?: CropDrops;
} }
function register_farming(ctx: ServerContext) { 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 // 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 stage_for = (params: CropParams, days: number) => {
const stages = params.stages + (params.upper?.stages ?? 0); 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); 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<CropParams>("bworld:crop", { ctx.components.register_block<CropParams>("bworld:crop", {
// block data so on_new_day runs for it. placed at a later stage (by a script), it has grown that long // 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) { 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 // regrowing crops are picked by hand and grow back, like farmer's delight's tomatoes
if (params.regrow_days && params.harvest && days >= params.days) { if (params.regrow_days && params.harvest && days >= params.days) {
const [min, max] = params.harvest.count; const loot = ctx.loot.roll(params.harvest, { block, player, tool: held });
const count = min + Math.floor(Math.random() * (max - min + 1)); for (const item of loot) ctx.world.drop_item(block.x, block.y, block.z, item);
ctx.world.drop_item(block.x, block.y, block.z, { id: params.harvest.item, count });
set_days(block, params, Math.max(0, params.days - params.regrow_days)); set_days(block, params, Math.max(0, params.days - params.regrow_days));
return true; return true;
} }
return false; return false;
}, },
on_break(block, params) { on_break(block, params) {
drop(block.x, block.y, block.z, params.drops, is_grown(block, params));
if (params.leaves) { if (params.leaves) {
const { x, y, z } = block; const { x, y, z } = block;
const leaves = params.leaves; const leaves = params.leaves;
@@ -539,9 +511,7 @@ function register_farming(ctx: ServerContext) {
}); });
ctx.components.register_block<CropTopParams>("bworld:crop_top", { ctx.components.register_block<CropTopParams>("bworld:crop_top", {
on_break(block, params) { on_break(block) {
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);
// the plant under it goes too, once this is gone // the plant under it goes too, once this is gone
const { x, y, z } = block; const { x, y, z } = block;
const lower = ctx.world.get_block(x, y - 1, z); const lower = ctx.world.get_block(x, y - 1, z);
@@ -658,7 +628,8 @@ interface FishingRodParams {
wait: [number, number]; wait: [number, number];
// ticks it stays on the hook before it gets away // ticks it stays on the hook before it gets away
bite: [number, number]; bite: [number, number];
loot: { item: string; weight: number }[]; // what's caught, a loot table
loot_table: string;
} }
interface Cast { 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 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<string, boolean>(); const fishable = new Map<string, boolean>();
const is_fishable = (id: string) => { const is_fishable = (id: string) => {
let result = fishable.get(id); let result = fishable.get(id);
@@ -745,8 +706,8 @@ function register_fishing(ctx: ServerContext) {
const cast = casts.get(player.id); const cast = casts.get(player.id);
if (cast) { if (cast) {
if (cast.escape_at !== undefined) { if (cast.escape_at !== undefined) {
const item = pick(params.loot); const loot = ctx.loot.roll(params.loot_table, { position: cast.position, player, tool: rod });
if (item) player.give_item(item); for (const item of loot) player.give_item(item.id, item.count, item.data);
} }
stop(player, player.id); stop(player, player.id);
return; return;
+2 -6
View File
@@ -53,6 +53,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "farmersdelight:blocks/cabbages",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -68,12 +69,7 @@
"bworld:crop": { "bworld:crop": {
"days": 12, "days": 12,
"stages": 8, "stages": 8,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "farmersdelight:cabbage_seeds",
"mature": "farmersdelight:cabbage",
"bonus": "farmersdelight:cabbage_seeds"
}
} }
} }
} }
+2 -6
View File
@@ -33,6 +33,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "farmersdelight:blocks/onions",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -48,12 +49,7 @@
"bworld:crop": { "bworld:crop": {
"days": 4, "days": 4,
"stages": 4, "stages": 4,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal"
"drops": {
"young": "farmersdelight:onion",
"mature": "farmersdelight:onion",
"bonus": "farmersdelight:onion"
}
} }
} }
} }
+2 -5
View File
@@ -40,6 +40,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "farmersdelight:blocks/rice",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:dirt", "bworld:dirt",
@@ -67,11 +68,7 @@
"stages": 4, "stages": 4,
"supporting_age": 4 "supporting_age": 4
}, },
"leaves": "bworld:water", "leaves": "bworld:water"
"drops": {
"young": "farmersdelight:rice",
"mature": "farmersdelight:rice"
}
} }
} }
} }
@@ -33,6 +33,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "farmersdelight:blocks/rice_panicles",
"item": false, "item": false,
"place_on": [ "place_on": [
"farmersdelight:rice" "farmersdelight:rice"
@@ -46,10 +47,7 @@
], ],
"components": { "components": {
"bworld:crop_top": { "bworld:crop_top": {
"stages": 4, "stages": 4
"drops": {
"mature": "farmersdelight:rice_panicle"
}
} }
} }
} }
+2 -14
View File
@@ -53,6 +53,7 @@
"mining": { "mining": {
"toughness": 0 "toughness": 0
}, },
"loot_table": "farmersdelight:blocks/tomatoes",
"item": false, "item": false,
"place_on": [ "place_on": [
"bworld:hoed_dirt" "bworld:hoed_dirt"
@@ -70,20 +71,7 @@
"stages": 8, "stages": 8,
"fertilizer": "bworld:bone_meal", "fertilizer": "bworld:bone_meal",
"regrow_days": 4, "regrow_days": 4,
"harvest": { "harvest": "farmersdelight:harvest/tomatoes"
"item": "farmersdelight:tomato",
"count": [
1,
2
]
},
"drops": {
"young": "farmersdelight:tomato_seeds",
"mature": [
"farmersdelight:tomato",
"farmersdelight:tomato_seeds"
]
}
} }
} }
} }
@@ -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
}
]
}
]
}
]
}
}
@@ -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
}
]
}
]
}
]
}
}
@@ -0,0 +1,14 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"entries": [
{
"item": "farmersdelight:rice"
}
]
}
]
}
}
@@ -0,0 +1,22 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"conditions": [
{
"condition": "block_state",
"states": {
"age": 3
}
}
],
"entries": [
{
"item": "farmersdelight:rice_panicle"
}
]
}
]
}
}
@@ -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"
}
]
}
]
}
}
@@ -0,0 +1,18 @@
{
"format_version": 1,
"loot_table": {
"pools": [
{
"entries": [
{
"item": "farmersdelight:tomato",
"count": {
"min": 1,
"max": 2
}
}
]
}
]
}
}
+2
View File
@@ -84,6 +84,8 @@ export interface EntityLevel {
entity_event(entity: Entity, event: EntityEvent): void; entity_event(entity: Entity, event: EntityEvent): void;
// it died, after dropping its things // it died, after dropping its things
on_death(entity: Entity, source: DamageSource): void; 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 // an entity as level.json keeps it, see Entity.save. each kind adds its own fields
+6
View File
@@ -20,6 +20,8 @@ export interface EntityHost {
send(player: ServerPlayer, message: ServerMessage): void; send(player: ServerPlayer, message: ServerMessage): void;
hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean; hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean;
on_entity_death?(entity: Entity, source: DamageSource): void; 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 // 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); this.#host.on_entity_death?.(entity, source);
} }
entity_loot(entity: Entity, source: DamageSource): ItemStack[] {
return this.#host.entity_loot?.(entity, source) ?? [];
}
// ticking // ticking
// every entity active says should move, with their passengers. entities removed along the way are forgotten // every entity active says should move, with their passengers. entities removed along the way are forgotten
+5 -2
View File
@@ -374,8 +374,11 @@ export abstract class LivingEntity extends Entity {
this.level.on_death(this, source); this.level.on_death(this, source);
} }
// what it drops when it dies, each kind decides. spawn_at_location drops something where it is // what it drops when it dies: its type's loot table, see EntityJson.loot_table. spawn_at_location drops
drop_loot(_source: DamageSource) {} // 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 // mobs drop their equipment, see Mob
drop_equipment(_source: DamageSource) {} drop_equipment(_source: DamageSource) {}
+41 -6
View File
@@ -24,6 +24,7 @@ import type { WorldgenSetup } from "$/common/generation.ts";
import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.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 { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
import { import {
block_states,
box_overlaps_block, box_overlaps_block,
can_place, can_place,
can_stand_on, can_stand_on,
@@ -36,7 +37,9 @@ import {
} from "$/common/utils.ts"; } from "$/common/utils.ts";
import { collision_shape_at, type Shape } from "$/common/block_shapes.ts"; import { collision_shape_at, type Shape } from "$/common/block_shapes.ts";
import { EXHAUSTION } from "./vitals.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 { import {
argument, argument,
choice, choice,
@@ -228,6 +231,18 @@ export class GameServer {
on_entity_death: (entity, source) => { on_entity_death: (entity, source) => {
if (entity instanceof ServerPlayer) this.#kill(entity, source); if (entity instanceof ServerPlayer) this.#kill(entity, source);
}, },
entity_loot: (entity, source) => {
const table = EverythingRegistry.get<EntityJson>("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 ?? {}); this.mods.storage = upgrade_mod_storage(saved?.mod_storage ?? {});
if (saved) { 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 // 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 // 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) { destroy_block(x: number, y: number, z: number, player?: ServerPlayer) {
@@ -620,14 +646,23 @@ export class GameServer {
const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? ""); const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? "");
const tool = held?.tool; const tool = held?.tool;
const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0); 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); const drops = !info.requires_tool || right_tool;
// a waterlogged block leaves its liquid behind, a source
const value = this.world.get_block_value(x, y, z); 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; const liquid = is_waterlogged(value, info) ? liquid_block(value, info) : undefined;
this.set_block(x, y, z, liquid?.id ?? AIR_ID, player); this.set_block(x, y, z, liquid?.id ?? AIR_ID, player);
if (drops) { for (const stack of loot) this.pop_item(x, y, z, stack);
this.pop_item(x, y, z, new ItemStack(info.drop_table!));
}
} }
get_or_create_tile(x: number, y: number, z: number): Tile { get_or_create_tile(x: number, y: number, z: number): Tile {
+100
View File
@@ -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<string, LootConditionFn<LootContext>>();
#functions = new Map<string, LootFunctionFn<LootContext>>();
#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<string, unknown>) {
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<LootTableJson>("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<LootTableJson>("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<ItemRegistry>("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;
}
+54 -3
View File
@@ -2,7 +2,8 @@
// see docs/modding/. parts not built yet throw when used, saying so // see docs/modding/. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "$/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.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 { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
import { AIR, ID_MASK } from "$/common/constants.ts"; import { AIR, ID_MASK } from "$/common/constants.ts";
import { BlockRules } from "$/common/block_rules.ts"; import { BlockRules } from "$/common/block_rules.ts";
@@ -22,6 +23,7 @@ import type {
ItemComponent, ItemComponent,
ItemStack, ItemStack,
LivingRef, LivingRef,
LootContext,
MenuBuilder, MenuBuilder,
MenuHandle, MenuHandle,
MenuType, MenuType,
@@ -163,6 +165,8 @@ export class ModRuntime {
#next_timer = 1; #next_timer = 1;
#setting_up = true; #setting_up = true;
#players = new WeakMap<ServerPlayer, Player>(); #players = new WeakMap<ServerPlayer, Player>();
// 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 // mod channels, see ctx.net: who listens on each channel
#net_handlers = new Map<string, { mod: string; handler: (player: Player, data: unknown) => void }[]>(); #net_handlers = new Map<string, { mod: string; handler: (player: Player, data: unknown) => void }[]>();
// mod messages each player sent this second, to drop floods // 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<string, unknown> }>("blocks")) { for (const [id, block] of EverythingRegistry.entries<{ components?: Record<string, unknown> }>("blocks")) {
for (const component of Object.keys(block.components ?? {})) { for (const component of Object.keys(block.components ?? {})) {
if (!this.block_components.has(component) && !this.rules.has(component)) { 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 { #context(mod: string, version: string): ServerContext {
const setup_only = (what: string) => { const setup_only = (what: string) => {
if (!this.#setting_up) { if (!this.#setting_up) {
@@ -759,6 +778,38 @@ export class ModRuntime {
list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []), list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []),
}, },
tags: tag_api(), 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: { containers: {
create: (size) => { create: (size) => {
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_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}`); if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`);
const stack = new EngineItemStack(item.id, item.count); const stack = new EngineItemStack(item.id, item.count);
if (item.data !== undefined) stack.data = structuredClone(item.data); 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 { return {
id: entity.id, id: entity.id,
type: entity.type, type: entity.type,
+1
View File
@@ -106,6 +106,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
entity_models: entries(bmod.data.entity_models), entity_models: entries(bmod.data.entity_models),
effects: entries(bmod.data.effects), effects: entries(bmod.data.effects),
tags: entries(bmod.data.tags), tags: entries(bmod.data.tags),
loot_tables: entries(bmod.data.loot_tables ?? []),
textures: [...bmod.textures.keys()], textures: [...bmod.textures.keys()],
texture_files: new Map(), texture_files: new Map(),
texture_json: new Map(bmod.texture_json), texture_json: new Map(bmod.texture_json),
+1
View File
@@ -38,6 +38,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
entity_models: mod.entity_models.map((m) => m.json), entity_models: mod.entity_models.map((m) => m.json),
effects: mod.effects.map((e) => e.json), effects: mod.effects.map((e) => e.json),
tags: mod.tags.map((t) => t.json), tags: mod.tags.map((t) => t.json),
loot_tables: mod.loot_tables.map((t) => t.json),
}, },
server_url: url(scripts.server), server_url: url(scripts.server),
worldgen_url: url(scripts.worldgen), worldgen_url: url(scripts.worldgen),
+319
View File
@@ -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<ItemRegistry>("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<BaseLootContext> => {
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<BaseLootContext> => ({
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 });
});
+17
View File
@@ -20,6 +20,7 @@ import {
import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts"; 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 { png_size, texture_size_problem } from "$/common/bmod.ts";
import { type TextureJson, validate_texture_json } from "$/common/texture_animation.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"; import { dirname } from "@std/path";
export { load_order, type LoadedMod, type ModReport }; export { load_order, type LoadedMod, type ModReport };
@@ -80,6 +81,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
entity_models: [], entity_models: [],
effects: [], effects: [],
tags: [], tags: [],
loot_tables: [],
textures: [], textures: [],
texture_files: new Map(), texture_files: new Map(),
texture_json: 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 }); if (problems.length === 0) mod.tags.push({ file: path, json: json as TagJson });
} }
// loot_tables/<path>.json is the loot table <mod id>:<path>, 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`)) { if (exists(`${dir}/worldgen/ores.json`)) {
const ores = read_json(`${dir}/worldgen/ores.json`, (m) => error(`worldgen/ores.json: ${m}`)); 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)) { if (!is_object(ores) || ores.format_version !== FORMAT_VERSION || !Array.isArray(ores.ores)) {
+1
View File
@@ -42,6 +42,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
entity_models: mod.entity_models.map((m) => m.json), entity_models: mod.entity_models.map((m) => m.json),
effects: mod.effects.map((e) => e.json), effects: mod.effects.map((e) => e.json),
tags: mod.tags.map((t) => t.json), tags: mod.tags.map((t) => t.json),
loot_tables: mod.loot_tables.map((t) => t.json),
}, },
scripts, scripts,
textures, textures,