Compare commits

...
2 Commits
Author SHA1 Message Date
paula e1c2b13d1f Entity scripts api 2026-11-21 10:56:59 -03:00
paula 60a7cae86e Start working on entities 2026-11-21 10:53:33 -03:00
9 changed files with 244 additions and 12 deletions
+92
View File
@@ -46,6 +46,8 @@ export interface ServerContext {
readonly config: any;
components: ComponentRegistry; // only during setup
commands: CommandRegistry; // only during setup
// mob behaviors, see docs/modding/entities/index.md. register_behavior only during setup
entities: EntityApi;
events: { before: ServerBeforeEvents; after: ServerAfterEvents };
system: System;
world: ServerWorld;
@@ -186,6 +188,96 @@ export interface ComponentRegistry {
register_effect<P>(id: Id, component: EffectComponent<P>): void;
}
// mob behaviors, like neoforge's Mob.registerGoals: an entity whose json has "behavior": "my_mod:thing" gets its goals
// from the function registered under that id
export interface EntityApi {
// runs once for each mob with this behavior, before its first thought. what the mob has to remember goes in the
// function's closures, one set per mob. only during setup
register_behavior(id: Id, behavior: (mob: MobRef, goals: MobGoals) => void): void;
// the engine's own goals, to add next to a mod's
readonly goals: BuiltinGoals;
}
// the controls a goal needs while it runs. a goal only starts once every flag it has is free, or held by a less
// important goal that can be interrupted, which then stops. "target" is for goals that pick who the mob is after
export type GoalFlag = "move" | "look" | "jump" | "target";
// something a mob does, like minecraft's Goal. every tick, running goals that can't continue stop, then goals that
// can start do, most important first, then every running goal ticks
export interface ScriptGoal {
flags?: GoalFlag[];
// whether it wants to start
can_use(): boolean;
// whether it wants to keep going, can_use when not given
can_continue_to_use?(): boolean;
// whether a more important goal can take its flags, true when not given
is_interruptable?(): boolean;
start?(): void;
stop?(): void;
tick?(): void;
}
// what a behavior adds its goals to. a lower priority number is more important
export interface MobGoals {
// what it does
add(priority: number, goal: ScriptGoal | BuiltinGoal): void;
// who it goes after, like minecraft's targetSelector. these set mob.target
add_target(priority: number, goal: ScriptGoal | BuiltinGoal): void;
}
// one of the engine's goals, made by BuiltinGoals and built for the mob when it's added
export interface BuiltinGoal {
readonly kind: string;
}
// the goals animal and monster behaviors are made of. speeds multiply the mob's movement_speed
export interface BuiltinGoals {
// swims up in water so it doesn't drown
float(): BuiltinGoal;
// wanders to a random spot within range every interval ticks or so
random_stroll(options?: { speed?: number; interval?: number; range?: number }): BuiltinGoal;
// runs around after being hurt or while burning
panic(options?: { speed?: number }): BuiltinGoal;
// looks at a player within range for a couple of seconds, with probability each tick
look_at_player(options?: { range?: number; probability?: number }): BuiltinGoal;
random_look_around(): BuiltinGoal;
// walks to its target and hits it with its attack_damage, at most once every interval ticks
melee_attack(options?: { speed?: number; interval?: number }): BuiltinGoal;
// target goals: whoever hurt it last, and the nearest player within its follow range
hurt_by_target(): BuiltinGoal;
nearest_attackable_player(): BuiltinGoal;
}
// a mob, the way its behavior's goals see it. refs are made fresh, so compare them by id
export interface MobRef extends LivingRef {
readonly type: Id;
readonly position: Readonly<Position>;
// where it sees from and which way it looks, a vector 1 long, like Player's
readonly eye_position: Readonly<Position>;
readonly look_direction: Readonly<Position>;
// in blocks a second
readonly velocity: Readonly<Position>;
readonly on_ground: boolean;
readonly in_water: boolean;
// who it's after, set by target goals or by a script. undefined once they die or leave
target: Player | MobRef | undefined;
// who hurt it last
readonly last_attacker: Player | MobRef | undefined;
// a number from 0 to 1, from the mob's own random, which tests replace
random(): number;
// walks toward x y z until it's there or stop is called. speed multiplies its movement_speed
move_to(x: number, y: number, z: number, speed?: number): void;
stop(): void;
// turns its head, and its body after it, toward a point. it stops after a couple of ticks, so a goal that keeps
// looking at something calls this every tick
look_at(x: number, y: number, z: number): void;
// this tick: jumps if it's on the ground, swims up if it's in water
jump(): void;
// swings its arm and hits target with its attack_damage, wherever target is
attack(target: Player | MobRef): void;
}
// commands, brigadier's way like neoforge's: see common/commands.ts and docs/modding/misc/commands.md
// who ran a command
+7 -2
View File
@@ -7,6 +7,7 @@ import {
type BlockJson,
choice_list,
type EffectJson,
entity_category,
type EntityJson,
type EntityModelJson,
type FluidJson,
@@ -380,6 +381,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (json.model !== undefined) uses(file, json.model, "entity model");
uses(file, json.texture, "texture");
if (json.loot_table) uses(file, json.loot_table, "loot table");
// scripts register behaviors, the server checks them when it starts
if (json.behavior?.includes(":")) check_namespace(file, json.behavior);
}
for (const { file, json } of mod.loot_tables ?? []) {
const refs = loot_references(json);
@@ -527,8 +530,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
check_namespace(file, json.entity);
const entity = entity_jsons.get(json.entity);
if (!entity) errors.push(`${file}: entity ${json.entity} doesn't exist`);
else if (entity.behavior !== "monster") {
errors.push(`${file}: ${json.entity} isn't a monster, only monsters spawn on their own for now`);
else if (entity_category(entity) !== "monster") {
errors.push(
`${file}: ${json.entity} isn't in the monster category, only monsters spawn on their own for now`,
);
}
for (const biome of json.biomes ?? []) {
check_namespace(file, biome);
+14 -2
View File
@@ -430,8 +430,14 @@ const entity_schema = z.object({
texture: id,
// "animal" (the default) wanders around, panics when hurt and looks at players. "monster" goes after players it
// sees and whoever hurts it, and despawns far from players, like minecraft's zombies. "scripted" stays where
// scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook
behavior: z.enum(["animal", "monster", "scripted"]).optional(),
// scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook. any other id
// is a behavior a mod's script registers
behavior: z.custom<string>(
(value) => ["animal", "monster", "scripted"].includes(value as string) || id.safeParse(value).success,
'must be "animal", "monster", "scripted" or a behavior id like "my_mod:thing"',
).optional(),
// what natural spawning counts it as, see entity_category
category: z.enum(["monster", "creature"]).optional(),
// its collision box in blocks, width is for both x and z
width: z.number().positive().max(16),
height: z.number().positive().max(16),
@@ -449,6 +455,12 @@ const entity_schema = z.object({
export type EntityJson = z.infer<typeof entity_schema>;
// like minecraft's MobCategory: monsters can spawn on their own and go away when no player is near, creatures stay.
// monster behavior makes one a monster unless it says otherwise
export function entity_category(json: EntityJson): "monster" | "creature" {
return json.category ?? (json.behavior === "monster" ? "monster" : "creature");
}
// like minecraft's MobEffectCategory, "neutral" when not set
const effect_category = z.enum(["beneficial", "harmful", "neutral"]);
export type EffectCategory = z.infer<typeof effect_category>;
+6 -1
View File
@@ -28,6 +28,7 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi
| `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. |
| `model` | none | An [entity model](#entity-models). Without one it's drawn as its texture, facing the camera. |
| `behavior` | `"animal"` | `"animal"`, `"monster"` or `"scripted"`, see below. |
| `category` | see below | `"monster"` or `"creature"`, see [Natural Spawning](#natural-spawning). |
| `width`, `height` | required | Its collision box in blocks, up to 16. `width` is for both x and z. Its eyes are at 85% of the height. |
| `max_health` | `10` | In half hearts. |
| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. |
@@ -89,6 +90,10 @@ the world, so a script never finds one it doesn't know about after a restart. Th
## Natural Spawning
An entity's `category` is what natural spawning counts it as, like Minecraft's mob categories. Monsters can spawn on
their own and go away when no player is near, creatures stay. Without one, a `"monster"` is a monster and anything else
is a creature.
Monsters spawn on their own in the dark around players, the way Minecraft's do. A mod lists which ones, how often and in
which biomes in `worldgen/spawns.json`, like NeoForge's `add_spawns` biome modifier. The Undergarden's rotwalkers:
@@ -109,7 +114,7 @@ which biomes in `worldgen/spawns.json`, like NeoForge's `add_spawns` biome modif
| Field | Default | Meaning |
| ----------- | ----------- | --------------------------------------------------------------------------------------------------------------- |
| `entity` | required | A `"monster"` entity. Only monsters spawn on their own for now. |
| `entity` | required | An entity in the `"monster"` category. Only monsters spawn on their own for now. |
| `weight` | required | How often this one is picked over the others that can spawn in the same biome. |
| `min_count` | required | How many spawn together, at least. |
| `max_count` | required | And at most. |
@@ -0,0 +1,15 @@
{
"format_version": 1,
"entity": {
"id": "dangerous_business:coilhead",
"model": "dangerous_business:coilhead",
"texture": "dangerous_business:coilhead",
"behavior": "dangerous_business:coilhead",
"width": 0.8,
"height": 2.5,
"max_health": 40,
"movement_speed": 0.23,
"attack_damage": 5,
"physical_shielding": 3
}
}
@@ -0,0 +1,91 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.unknown",
"texture_width": 128,
"texture_height": 128,
"visible_bounds_width": 3,
"visible_bounds_height": 4.5,
"visible_bounds_offset": [0, 1.75, 0]
},
"bones": [
{
"name": "root",
"pivot": [0, 0, 0]
},
{
"name": "Torso",
"parent": "root",
"pivot": [0.5, 17, 0],
"cubes": [
{"origin": [-4.5, 17, -3.5], "size": [9, 14, 5], "uv": [0, 0]},
{"origin": [5.5, 20, -5.499], "size": [0, 1, 1], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [1, 1]},
{"origin": [10.5, 23, -5.499], "size": [0, 1, 1], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [1, 1]},
{"origin": [-1.5, 20.05952, -5.5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [-0.5, 26.05952, -5.5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [-0.5, 24.05952, 1.5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [-2.5, 19.05952, 1.5], "size": [0, 1, 2], "uv": [0, 0]}
]
},
{
"name": "RightArm",
"parent": "Torso",
"pivot": [-5, 28, -1.5],
"cubes": [
{"origin": [-8.5, 20, -3], "size": [4, 10, 4], "uv": [0, 34]},
{"origin": [-5.5, 28.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [-5.5, 28.05952, 1], "size": [0, 1, 2], "uv": [0, 0]}
]
},
{
"name": "LeftArm",
"parent": "Torso",
"pivot": [5, 28.66032, -0.66633],
"cubes": [
{"origin": [4.5, 22, -3], "size": [4, 8, 4], "uv": [40, 38]},
{"origin": [6.5, 27.05952, -4.5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [8.5, 27, -10.499], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
]
},
{
"name": "Neck",
"parent": "Torso",
"pivot": [-1.5, 31, 0],
"cubes": [
{"origin": [-2, 30.75, -3], "size": [4, 9, 4], "uv": [16, 38]}
]
},
{
"name": "Head",
"parent": "Neck",
"pivot": [0, 39.75, -1],
"cubes": [
{"origin": [-3.5, 39.75, -4.5], "size": [7, 8, 7], "uv": [0, 19]}
]
},
{
"name": "RightLeg",
"parent": "root",
"pivot": [-1, 16, -0.833],
"cubes": [
{"origin": [-4, 0, -3], "size": [4, 17, 4], "uv": [28, 21]},
{"origin": [-1.5, 10.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [8.5, 10, 4], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
]
},
{
"name": "LeftLeg",
"parent": "root",
"pivot": [0.167, 16, -0.833],
"cubes": [
{"origin": [0, 0, -3], "size": [4, 17, 4], "uv": [28, 0]},
{"origin": [2.5, 8.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
{"origin": [8.5, 12, -6], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
]
}
]
}
]
}
+2 -1
View File
@@ -7,8 +7,9 @@
import { ATTRIBUTES } from "./attributes.ts";
import type { LivingEntity } from "./living_entity.ts";
import type { Mob } from "./mob.ts";
import type { GoalFlag } from "@/common/mod_api/server.ts";
export type GoalFlag = "move" | "look" | "jump" | "target";
export type { GoalFlag };
export abstract class Goal {
flags: GoalFlag[] = [];
+5 -4
View File
@@ -4,7 +4,7 @@
// the kinds of entity mods define in entities/<name>.json (see EntityJson): animals that wander around, panic when hurt
// and look at players now and then, like minecraft's simpler animals, monsters that go after players, and scripted
// ones that stay where scripts put them
import type { EntityJson } from "@/common/mod_data.ts";
import { entity_category, type EntityJson } from "@/common/mod_data.ts";
import { ATTRIBUTES, type AttributeType } from "./attributes.ts";
import { Entity } from "./entity.ts";
import type { EntityFactory } from "./entity_types.ts";
@@ -28,6 +28,7 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
}
const monster = json.behavior === "monster";
const category = entity_category(json);
class ModEntity extends Mob {
readonly type = json.id;
@@ -36,7 +37,7 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
override eye_height = json.height * 0.85;
override get category(): MobCategory {
return monster ? "monster" : "creature";
return category;
}
override default_attributes(): [AttributeType, number?][] {
@@ -68,9 +69,9 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
this.goals.add_goal(7, new RandomLookAroundGoal(this));
}
// animals stay, like minecraft's farm animals. monsters go away when no player is near
// creatures stay, like minecraft's farm animals. monsters go away when no player is near
override remove_when_far_away() {
return monster;
return category === "monster";
}
}
return (level) => new ModEntity(level);
+12 -2
View File
@@ -3,7 +3,7 @@
// mobs mods define in entities/<name>.json, drawn with a bedrock model from models/<name>.geo.json
import { assert, assertAlmostEquals, assertEquals, assertNotEquals, assertStringIncludes } from "@std/assert";
import { entity_model_from_geo, type EntityBoneJson, validate_entity } from "@/common/mod_data.ts";
import { entity_category, entity_model_from_geo, type EntityBoneJson, validate_entity } from "@/common/mod_data.ts";
import type { Texture } from "@/client/renderer/mod.ts";
import { IDENTITY } from "@/client/rendering/model_math.ts";
import { push_model } from "@/client/rendering/model_renderer.ts";
@@ -82,8 +82,18 @@ Deno.test("an entity needs a texture and a size", () => {
Deno.test("an entity without a model is drawn as its texture, and a scripted one has no ai", () => {
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "scripted", width: 0.25, height: 0.25 }), []);
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "flying", width: 0.25, height: 0.25 }), [
'behavior must be "animal", "monster" or "scripted"',
'behavior must be "animal", "monster", "scripted" or a behavior id like "my_mod:thing"',
]);
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "a:flying", width: 0.25, height: 0.25 }), []);
});
Deno.test("an entity's category is monster for monsters unless it says otherwise", () => {
const entity = { id: "a:b", texture: "a:b", width: 1, height: 1 };
assertEquals(entity_category(entity), "creature");
assertEquals(entity_category({ ...entity, behavior: "monster" }), "monster");
assertEquals(entity_category({ ...entity, behavior: "a:flying", category: "monster" }), "monster");
assertEquals(entity_category({ ...entity, behavior: "monster", category: "creature" }), "creature");
assertEquals(validate_entity({ ...entity, category: "boss" }), ['category must be "monster" or "creature"']);
});
Deno.test("scripted entities stay put and aren't saved with the world", async () => {