diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 6c8a7f1..88a5209 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -249,7 +249,7 @@ export interface BuiltinGoals { nearest_attackable_player(): BuiltinGoal; } -// a mob, the way its behavior's goals see it. refs are made fresh, so compare them by id +// a mob, the way its behavior's goals see it. each mob has one, so a target can be compared with === export interface MobRef extends LivingRef { readonly type: Id; readonly position: Readonly; diff --git a/server/game/entity/mod_entity.ts b/server/game/entity/mod_entity.ts index 89ed35e..ddcca1d 100644 --- a/server/game/entity/mod_entity.ts +++ b/server/game/entity/mod_entity.ts @@ -21,13 +21,18 @@ import { import { Mob, type MobCategory } from "./mob.ts"; // the entity's class. the attributes are read while LivingEntity is being built, before any field of a subclass is -// set, so each kind gets its own class that has its json already -export function mod_entity_factory(json: EntityJson): EntityFactory { +// set, so each kind gets its own class that has its json already. behaviors are mods' (see ctx.entities), looked up +// when a mob first thinks, after every script has registered its own +export function mod_entity_factory( + json: EntityJson, + behaviors: ReadonlyMap void>, +): EntityFactory { if (json.behavior === "scripted") { return (level) => new ScriptedEntity(level, json); } const monster = json.behavior === "monster"; + const behavior = json.behavior?.includes(":") ? json.behavior : undefined; const category = entity_category(json); class ModEntity extends Mob { @@ -52,6 +57,10 @@ export function mod_entity_factory(json: EntityJson): EntityFactory { } override register_goals() { + if (behavior) { + behaviors.get(behavior)!(this); + return; + } if (monster) { // like undergarden's rotspawn and minecraft's zombies this.goals.add_goal(0, new FloatGoal(this)); diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index dae1c3f..0131d8b 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -38,8 +38,11 @@ export async function start_game( expose_engine({ common: common_engine(), server: server_engine() }); const recipes = register_mod_data(mods.map((mod) => ({ id: mod.listing.id, data: mod.data }))); + const runtime = new ModRuntime(); for (const mod of mods) { - for (const json of mod.data.entities) register_entity_type(json.id, mod_entity_factory(json)); + for (const json of mod.data.entities) { + register_entity_type(json.id, mod_entity_factory(json, runtime.entity_behaviors)); + } } const dimension = default_dimension(mods); @@ -59,7 +62,6 @@ export async function start_game( const problem = cell_height_problem(shape, [terrain.cell_height, caves.cell_height]); if (problem) throw new Error(`dimension ${dimension.id} can't be generated by ${generator}: ${problem}`); - const runtime = new ModRuntime(); // before the world loads, its mobs can have effects set_effect_types(runtime.effect_types()); const game = new GameServer(host, save, default_seed, { diff --git a/server/game/mob_behaviors.ts b/server/game/mob_behaviors.ts new file mode 100644 index 0000000..6dabe56 --- /dev/null +++ b/server/game/mob_behaviors.ts @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// mods' mob behaviors, see EntityApi in common/mod_api/server.ts: the goals scripts write, run by the same goal +// selectors as the engine's own, and the engine's goals made for scripts to add +import type { BuiltinGoal, BuiltinGoals, GoalFlag, MobGoals, ScriptGoal } from "@/common/mod_api/server.ts"; +import { + FloatGoal, + Goal, + type GoalSelector, + HurtByTargetGoal, + LookAtPlayerGoal, + MeleeAttackGoal, + NearestAttackablePlayerGoal, + PanicGoal, + RandomLookAroundGoal, + RandomStrollGoal, +} from "./entity/goals.ts"; +import type { Mob } from "./entity/mob.ts"; +import { run_guarded } from "./mod_runtime.ts"; + +const GOAL_FLAGS: readonly GoalFlag[] = ["move", "look", "jump", "target"]; + +// a script's goal, with each call guarded. one that throws is dropped: it never runs again, so it doesn't log every +// tick, and the mob's other goals go on +class ScriptedGoal extends Goal { + #broken = false; + + constructor(readonly mod: string, readonly behavior: string, readonly goal: ScriptGoal) { + super(); + this.flags = [...(goal.flags ?? [])]; + } + + #call(what: string, fn: () => T, fallback: T): T { + if (this.#broken) return fallback; + let done = false; + const result = run_guarded(this.mod, `${this.behavior} goal ${what}`, () => { + const result = fn(); + done = true; + return result; + }); + if (!done) this.#broken = true; + return done ? result as T : fallback; + } + + can_use() { + return this.#call("can_use", () => Boolean(this.goal.can_use()), false); + } + + override can_continue_to_use() { + const goal = this.goal; + return this.#call( + "can_continue_to_use", + () => Boolean(goal.can_continue_to_use ? goal.can_continue_to_use() : goal.can_use()), + false, + ); + } + + override is_interruptable() { + if (!this.goal.is_interruptable) return true; + return this.#call("is_interruptable", () => Boolean(this.goal.is_interruptable!()), true); + } + + override start() { + if (this.goal.start) this.#call("start", () => this.goal.start!(), undefined); + } + + override stop() { + if (this.goal.stop) this.#call("stop", () => this.goal.stop!(), undefined); + } + + override tick() { + if (this.goal.tick) this.#call("tick", () => this.goal.tick!(), undefined); + } +} + +// what makes each BuiltinGoal for a mob. one BuiltinGoal can be added to many mobs, each gets its own +const builders = new WeakMap Goal>(); + +function builtin(kind: string, build: (mob: Mob) => Goal): BuiltinGoal { + const goal = Object.freeze({ kind }); + builders.set(goal, build); + return goal; +} + +// undefined leaves the goal's own default +function option(options: Record | undefined, name: string): number | undefined { + const value = options?.[name]; + if (value === undefined) return undefined; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw new Error(`a goal's ${name} must be a number, 0 or more`); + } + return value; +} + +export const BUILTIN_GOALS = Object.freeze({ + float: () => builtin("float", (mob) => new FloatGoal(mob)), + random_stroll(options) { + const [speed, interval, range] = ["speed", "interval", "range"].map((name) => option(options, name)); + return builtin("random_stroll", (mob) => new RandomStrollGoal(mob, speed, interval, range)); + }, + panic(options) { + const speed = option(options, "speed"); + return builtin("panic", (mob) => new PanicGoal(mob, speed)); + }, + look_at_player(options) { + const [range, probability] = ["range", "probability"].map((name) => option(options, name)); + return builtin("look_at_player", (mob) => new LookAtPlayerGoal(mob, range, probability)); + }, + random_look_around: () => builtin("random_look_around", (mob) => new RandomLookAroundGoal(mob)), + melee_attack(options) { + const [speed, interval] = ["speed", "interval"].map((name) => option(options, name)); + return builtin("melee_attack", (mob) => new MeleeAttackGoal(mob, speed, interval)); + }, + hurt_by_target: () => builtin("hurt_by_target", (mob) => new HurtByTargetGoal(mob)), + nearest_attackable_player: () => + builtin("nearest_attackable_player", (mob) => new NearestAttackablePlayerGoal(mob)), +}); + +// what a behavior adds the mob's goals to +export function mob_goals(mod: string, behavior: string, mob: Mob): MobGoals { + const adder = (selector: GoalSelector) => (priority: number, goal: ScriptGoal | BuiltinGoal) => { + if (typeof priority !== "number" || !Number.isFinite(priority)) { + throw new Error("a goal's priority must be a number"); + } + selector.add_goal(priority, engine_goal(mod, behavior, mob, goal)); + }; + return { add: adder(mob.goals), add_target: adder(mob.target_goals) }; +} + +function engine_goal(mod: string, behavior: string, mob: Mob, goal: ScriptGoal | BuiltinGoal): Goal { + const build = builders.get(goal as BuiltinGoal); + if (build) return build(mob); + const script_goal = goal as ScriptGoal; + if (typeof script_goal?.can_use !== "function") { + throw new Error("a goal needs a can_use function, or has to come from ctx.entities.goals"); + } + const flags = script_goal.flags ?? []; + if (!Array.isArray(flags) || flags.some((flag) => !GOAL_FLAGS.includes(flag))) { + throw new Error(`a goal's flags must be some of ${GOAL_FLAGS.map((flag) => `"${flag}"`).join(", ")}`); + } + return new ScriptedGoal(mod, behavior, script_goal); +} diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index fa10179..270c833 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -46,6 +46,7 @@ import type { MenuBuilder, MenuHandle, MenuType, + MobRef, Player, PlayerMenuBuilder, Position, @@ -86,7 +87,9 @@ import type { ServerPlayer } from "./player.ts"; import { Menu, type MenuFluidSlot, type MenuSlot } from "./menu.ts"; import { damage_source, type DamageSource, type Entity } from "./entity/entity.ts"; import type { LivingEntity } from "./entity/living_entity.ts"; -import type { EffectJson } from "@/common/mod_data.ts"; +import type { EffectJson, EntityJson } from "@/common/mod_data.ts"; +import { Mob } from "./entity/mob.ts"; +import { BUILTIN_GOALS, mob_goals } from "./mob_behaviors.ts"; import { create_entity } from "./entity/entity_types.ts"; import { BLOCK_DROP_PICKUP_DELAY, ItemEntity } from "./entity/item_entity.ts"; import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts"; @@ -178,6 +181,8 @@ export class ModRuntime { fluid_rules = new FluidRules(run_guarded); item_components = new Map(); effect_components = new Map(); + // mods' mob behaviors by id, each adding its goals to a mob, see mod_entity.ts + entity_behaviors = new Map void>(); // every command, the engine's and mods', see common/commands.ts commands = new CommandDispatcher(); // who registered each command name: "cubi" or a mod's id @@ -247,6 +252,9 @@ export class ModRuntime { // the other way, for apis that take a player #server_players = new WeakMap(); + // mob refs, one for each mob so scripts can compare them, and the other way + #mob_refs = new WeakMap(); + #mobs = new WeakMap(); // menu types by id, every mod's #menu_types = new Set(); // what each mod adds to the player's own menu, in load order @@ -390,6 +398,16 @@ export class ModRuntime { this.loot.check(); + for (const [id, entity] of EverythingRegistry.entries("entities")) { + const behavior = entity.behavior; + if (behavior?.includes(":") && !this.entity_behaviors.has(behavior)) { + throw new ModLoadError( + id.split(":")[0], + `entity ${id} has behavior ${behavior}, which nothing registered`, + ); + } + } + for (const [id, block] of EverythingRegistry.entries<{ components?: Record }>("blocks")) { for (const component of Object.keys(block.components ?? {})) { if (!this.block_components.has(component) && !this.rules.has(component)) { @@ -651,6 +669,84 @@ export class ModRuntime { return api; } + mob(mob: Mob): MobRef { + let ref = this.#mob_refs.get(mob); + if (!ref) { + ref = this.#mob_ref(mob); + this.#mob_refs.set(mob, ref); + this.#mobs.set(ref, mob); + } + return ref; + } + + // a player or a mob the way scripts see them, undefined once they're dead or gone + #living_ref(entity: LivingEntity | undefined): Player | MobRef | undefined { + if (!entity?.alive) return undefined; + return entity instanceof Mob ? this.mob(entity) : this.player(entity as ServerPlayer); + } + + // the other way, for apis that take a player or a mob + #living_entity(ref: Player | MobRef, what: string): LivingEntity { + const entity = this.#server_players.get(ref as Player) ?? this.#mobs.get(ref as MobRef); + if (!entity) throw new Error(`${what} must be a player or a mob`); + return entity; + } + + #mob_ref(mob: Mob): MobRef { + const runtime = this; + const extra: Omit = { + type: mob.type, + get position() { + return { x: mob.x, y: mob.y, z: mob.z }; + }, + get eye_position() { + return { x: mob.x, y: mob.y + mob.eye_height, z: mob.z }; + }, + get look_direction() { + return look_direction(mob.head_yaw, mob.pitch); + }, + get velocity() { + return { x: mob.vx, y: mob.vy, z: mob.vz }; + }, + get on_ground() { + return mob.on_ground; + }, + get in_water() { + return mob.in_water; + }, + get target() { + return runtime.#living_ref(mob.target); + }, + set target(target) { + mob.target = target === undefined ? undefined : runtime.#living_entity(target, "a target"); + }, + get last_attacker() { + return runtime.#living_ref(mob.last_attacker); + }, + random: () => mob.random(), + move_to(x, y, z, speed = 1) { + if (![x, y, z, speed].every(Number.isFinite)) throw new Error("move_to takes a position and a speed"); + mob.move_control.move_to(x, y, z, speed); + }, + stop() { + mob.move_control.stop(); + }, + look_at(x, y, z) { + if (![x, y, z].every(Number.isFinite)) throw new Error("look_at takes a position"); + mob.look_control.look_at(x, y, z); + }, + jump() { + mob.jump_control.jump(); + }, + attack(target) { + const entity = runtime.#living_entity(target, "what a mob attacks"); + mob.level.entity_event(mob, "swing"); + mob.do_hurt_target(entity); + }, + }; + return Object.defineProperties(living_ref(mob), Object.getOwnPropertyDescriptors(extra)) as MobRef; + } + block_ref(x: number, y: number, z: number, id: string): BlockRef { const game = this.game; return { @@ -718,6 +814,20 @@ export class ModRuntime { this.effect_components.set(id, { mod, component: component as EffectComponent }); }, }, + entities: { + register_behavior: (id, behavior) => { + register.new_id("entity behavior", id, this.entity_behaviors.has(id)); + if (typeof behavior !== "function") register.fail(`entity behavior ${id} must be a function`); + this.entity_behaviors.set(id, (mob) => { + run_guarded( + mod, + `entity behavior ${id}`, + () => behavior(this.mob(mob), mob_goals(mod, id, mob)), + ); + }); + }, + goals: BUILTIN_GOALS, + }, commands: { register: (name_or_node: string | CommandNode, command?: Command) => { register.running("command"); @@ -1486,12 +1596,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player { }, // the same way the client aims, see ClientLevel.pick get look_direction() { - const cos_pitch = Math.cos(player.pitch); - return { - x: -Math.sin(player.yaw) * cos_pitch, - y: Math.sin(player.pitch), - z: -Math.cos(player.yaw) * cos_pitch, - }; + return look_direction(player.yaw, player.pitch); }, get biome() { return game.world.biome_at(Math.floor(player.x), Math.floor(player.y), Math.floor(player.z)); @@ -1624,6 +1729,12 @@ function effect_of(entity: LivingEntity, id: string) { return effect && { amplifier: effect.amplifier, duration: effect.duration }; } +// which way yaw and pitch face, a vector 1 long +function look_direction(yaw: number, pitch: number): Position { + const cos_pitch = Math.cos(pitch); + return { x: -Math.sin(yaw) * cos_pitch, y: Math.sin(pitch), z: -Math.cos(yaw) * cos_pitch }; +} + export function living_ref(entity: LivingEntity): LivingRef { return { id: entity.id,