Loot tables
This commit is contained in:
@@ -84,6 +84,8 @@ export interface EntityLevel {
|
||||
entity_event(entity: Entity, event: EntityEvent): void;
|
||||
// it died, after dropping its things
|
||||
on_death(entity: Entity, source: DamageSource): void;
|
||||
// what it drops when it dies, from its type's loot table
|
||||
entity_loot(entity: Entity, source: DamageSource): ItemStack[];
|
||||
}
|
||||
|
||||
// an entity as level.json keeps it, see Entity.save. each kind adds its own fields
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface EntityHost {
|
||||
send(player: ServerPlayer, message: ServerMessage): void;
|
||||
hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean;
|
||||
on_entity_death?(entity: Entity, source: DamageSource): void;
|
||||
// what it drops when it dies, from its loot table
|
||||
entity_loot?(entity: Entity, source: DamageSource): ItemStack[];
|
||||
}
|
||||
|
||||
// what a client was last told about an entity, so only changes get sent
|
||||
@@ -154,6 +156,10 @@ export class EntityManager implements EntityLevel {
|
||||
this.#host.on_entity_death?.(entity, source);
|
||||
}
|
||||
|
||||
entity_loot(entity: Entity, source: DamageSource): ItemStack[] {
|
||||
return this.#host.entity_loot?.(entity, source) ?? [];
|
||||
}
|
||||
|
||||
// ticking
|
||||
|
||||
// every entity active says should move, with their passengers. entities removed along the way are forgotten
|
||||
|
||||
@@ -374,8 +374,11 @@ export abstract class LivingEntity extends Entity {
|
||||
this.level.on_death(this, source);
|
||||
}
|
||||
|
||||
// what it drops when it dies, each kind decides. spawn_at_location drops something where it is
|
||||
drop_loot(_source: DamageSource) {}
|
||||
// what it drops when it dies: its type's loot table, see EntityJson.loot_table. spawn_at_location drops
|
||||
// something where it is
|
||||
drop_loot(source: DamageSource) {
|
||||
for (const stack of this.level.entity_loot(this, source)) this.spawn_at_location(stack);
|
||||
}
|
||||
|
||||
// mobs drop their equipment, see Mob
|
||||
drop_equipment(_source: DamageSource) {}
|
||||
|
||||
@@ -24,6 +24,7 @@ import type { WorldgenSetup } from "$/common/generation.ts";
|
||||
import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts";
|
||||
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
|
||||
import {
|
||||
block_states,
|
||||
box_overlaps_block,
|
||||
can_place,
|
||||
can_stand_on,
|
||||
@@ -36,7 +37,9 @@ import {
|
||||
} from "$/common/utils.ts";
|
||||
import { collision_shape_at, type Shape } from "$/common/block_shapes.ts";
|
||||
import { EXHAUSTION } from "./vitals.ts";
|
||||
import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
|
||||
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
|
||||
import type { LootContext } from "$/common/mod_api/server.ts";
|
||||
import type { EntityJson } from "$/common/mod_data.ts";
|
||||
import {
|
||||
argument,
|
||||
choice,
|
||||
@@ -228,6 +231,18 @@ export class GameServer {
|
||||
on_entity_death: (entity, source) => {
|
||||
if (entity instanceof ServerPlayer) this.#kill(entity, source);
|
||||
},
|
||||
entity_loot: (entity, source) => {
|
||||
const table = EverythingRegistry.get<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 ?? {});
|
||||
if (saved) {
|
||||
@@ -610,6 +625,17 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
// what a loot table gives, ready to drop. a table that can't be rolled is logged and gives nothing, so a broken
|
||||
// table never stops a block breaking or a mob dying
|
||||
roll_loot(table: string, context: LootContext): ItemStack[] {
|
||||
try {
|
||||
return this.mods.loot.roll(table, context).map(new_stack);
|
||||
} catch (e) {
|
||||
console.error(`Couldn't roll loot table ${table}:`, e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// breaks a block the way breaking it by hand does: its components' on_break, then what it drops. without the
|
||||
// right tool of a high enough tier (or without a player) blocks that need one drop nothing
|
||||
destroy_block(x: number, y: number, z: number, player?: ServerPlayer) {
|
||||
@@ -620,14 +646,23 @@ export class GameServer {
|
||||
const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? "");
|
||||
const tool = held?.tool;
|
||||
const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0);
|
||||
const drops = info.drop_table && (!info.requires_tool || right_tool);
|
||||
// a waterlogged block leaves its liquid behind, a source
|
||||
const drops = !info.requires_tool || right_tool;
|
||||
const value = this.world.get_block_value(x, y, z);
|
||||
// rolled while it's still there, for its states
|
||||
const loot = drops && info.loot_table
|
||||
? this.roll_loot(info.loot_table, {
|
||||
position: { x: x + 0.5, y: y + 0.5, z: z + 0.5 },
|
||||
block: { id: info.id, x, y, z, states: block_states(value, info) },
|
||||
player: player && this.mods.player(player),
|
||||
tool: player && this.mods.player(player).held_item,
|
||||
})
|
||||
: drops && info.drop_table
|
||||
? [new ItemStack(info.drop_table)]
|
||||
: [];
|
||||
// a waterlogged block leaves its liquid behind, a source
|
||||
const liquid = is_waterlogged(value, info) ? liquid_block(value, info) : undefined;
|
||||
this.set_block(x, y, z, liquid?.id ?? AIR_ID, player);
|
||||
if (drops) {
|
||||
this.pop_item(x, y, z, new ItemStack(info.drop_table!));
|
||||
}
|
||||
for (const stack of loot) this.pop_item(x, y, z, stack);
|
||||
}
|
||||
|
||||
get_or_create_tile(x: number, y: number, z: number): Tile {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
// see docs/modding/. parts not built yet throw when used, saying so
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "$/common/everything_registry.ts";
|
||||
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
|
||||
import { get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts";
|
||||
import { block_states, get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts";
|
||||
import { LootTables } from "./loot.ts";
|
||||
import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
|
||||
import { AIR, ID_MASK } from "$/common/constants.ts";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
@@ -22,6 +23,7 @@ import type {
|
||||
ItemComponent,
|
||||
ItemStack,
|
||||
LivingRef,
|
||||
LootContext,
|
||||
MenuBuilder,
|
||||
MenuHandle,
|
||||
MenuType,
|
||||
@@ -163,6 +165,8 @@ export class ModRuntime {
|
||||
#next_timer = 1;
|
||||
#setting_up = true;
|
||||
#players = new WeakMap<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
|
||||
#net_handlers = new Map<string, { mod: string; handler: (player: Player, data: unknown) => void }[]>();
|
||||
// mod messages each player sent this second, to drop floods
|
||||
@@ -344,6 +348,8 @@ export class ModRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
this.loot.check();
|
||||
|
||||
for (const [id, block] of EverythingRegistry.entries<{ components?: Record<string, unknown> }>("blocks")) {
|
||||
for (const component of Object.keys(block.components ?? {})) {
|
||||
if (!this.block_components.has(component) && !this.rules.has(component)) {
|
||||
@@ -506,6 +512,19 @@ export class ModRuntime {
|
||||
};
|
||||
}
|
||||
|
||||
// a script's loot context with its block's states read from the world, when it didn't give them
|
||||
#loot_context(context: LootContext = {}): LootContext {
|
||||
const block = context.block;
|
||||
if (!block || block.states) return context;
|
||||
const world = this.game.world;
|
||||
const info = world.get_block_info(block.x, block.y, block.z);
|
||||
if (info?.id !== block.id) return context;
|
||||
return {
|
||||
...context,
|
||||
block: { ...block, states: block_states(world.get_block_value(block.x, block.y, block.z), info) },
|
||||
};
|
||||
}
|
||||
|
||||
#context(mod: string, version: string): ServerContext {
|
||||
const setup_only = (what: string) => {
|
||||
if (!this.#setting_up) {
|
||||
@@ -759,6 +778,38 @@ export class ModRuntime {
|
||||
list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []),
|
||||
},
|
||||
tags: tag_api(),
|
||||
loot: {
|
||||
exists: (id) => this.loot.exists(id),
|
||||
roll: (id, context) => this.loot.roll(id, this.#loot_context(context)),
|
||||
fill: (container, id, context) => {
|
||||
const items = this.loot.roll(id, this.#loot_context(context));
|
||||
// empty slots in a random order, one item each, like minecraft's chests
|
||||
const empty = [...Array(container.size).keys()].filter((slot) => !container.get(slot));
|
||||
for (let i = empty.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[empty[i], empty[j]] = [empty[j], empty[i]];
|
||||
}
|
||||
const left: ItemStack[] = [];
|
||||
for (const item of items) {
|
||||
const slot = empty.pop();
|
||||
if (slot === undefined) left.push(item);
|
||||
else container.set(slot, item);
|
||||
}
|
||||
return left;
|
||||
},
|
||||
register_condition: (id, condition) => {
|
||||
setup_only("loot conditions");
|
||||
this.loot.register_condition(mod, id, condition);
|
||||
},
|
||||
register_function: (id, fn) => {
|
||||
setup_only("loot functions");
|
||||
this.loot.register_function(mod, id, fn);
|
||||
},
|
||||
modify: (table, fn) => {
|
||||
setup_only("loot modifiers");
|
||||
this.loot.modify(mod, table, fn);
|
||||
},
|
||||
},
|
||||
containers: {
|
||||
create: (size) => {
|
||||
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_SIZE) {
|
||||
@@ -1014,7 +1065,7 @@ export function item_api(stack: EngineItemStack): ItemStack {
|
||||
};
|
||||
}
|
||||
|
||||
function new_stack(item: ItemStack): EngineItemStack {
|
||||
export function new_stack(item: ItemStack): EngineItemStack {
|
||||
if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`);
|
||||
const stack = new EngineItemStack(item.id, item.count);
|
||||
if (item.data !== undefined) stack.data = structuredClone(item.data);
|
||||
@@ -1254,7 +1305,7 @@ function living_ref(entity: LivingEntity): LivingRef {
|
||||
};
|
||||
}
|
||||
|
||||
function entity_ref(entity: Entity): EntityRef {
|
||||
export function entity_ref(entity: Entity): EntityRef {
|
||||
return {
|
||||
id: entity.id,
|
||||
type: entity.type,
|
||||
|
||||
@@ -106,6 +106,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
|
||||
entity_models: entries(bmod.data.entity_models),
|
||||
effects: entries(bmod.data.effects),
|
||||
tags: entries(bmod.data.tags),
|
||||
loot_tables: entries(bmod.data.loot_tables ?? []),
|
||||
textures: [...bmod.textures.keys()],
|
||||
texture_files: new Map(),
|
||||
texture_json: new Map(bmod.texture_json),
|
||||
|
||||
Reference in New Issue
Block a user