diff --git a/common/physics.ts b/common/physics.ts index 732b520..bd6d220 100644 --- a/common/physics.ts +++ b/common/physics.ts @@ -212,7 +212,8 @@ export function box_is_free( return !overlaps_solid(min, max, is_blocked); } -function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) { +// whether the box between min and max (x, y, z) touches anything solid +export function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) { for (let x = lowest(0, min[0]); x <= Math.floor(max[0] - EPSILON); x++) { for (let y = lowest(1, min[1]); y <= Math.floor(max[1] - EPSILON); y++) { for (let z = lowest(2, min[2]); z <= Math.floor(max[2] - EPSILON); z++) { diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts index 622bc8f..5d13194 100644 --- a/server/game/entity/entity.ts +++ b/server/game/entity/entity.ts @@ -72,6 +72,10 @@ export interface EntityLevel { // the bottom of the world, see WorldShape readonly min_y: number; has_collision(x: number, y: number, z: number): boolean; + // whether the chunk is kept, see World.has_chunk. reading blocks in one that isn't builds it, which takes a while + has_chunk(chunk_x: number, chunk_z: number): boolean; + // whether mobs' paths go through the block, see MOBS_PATH_THROUGH in pathfinding.ts + passes_through(x: number, y: number, z: number): boolean; // what it bumps into at a block, see common/physics.ts collision_shape(x: number, y: number, z: number): boolean | Shape; // water, and other blocks you're in instead of on diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts index fd9c95f..e3fc254 100644 --- a/server/game/entity/entity_manager.ts +++ b/server/game/entity/entity_manager.ts @@ -8,6 +8,7 @@ import { CHUNK_SIZE } from "@/common/constants.ts"; import { is_within_view } from "@/common/chunk_streaming.ts"; import { fluid_block, fluid_in_cell } from "@/common/utils.ts"; import { biome_season } from "@/common/worldgen/biomes.ts"; +import { Tags } from "@/common/tags.ts"; import type { ItemStack } from "@/common/inventory.ts"; import type { EntityEvent, EntityInfo, ServerMessage } from "@/common/protocol.ts"; import type { ServerPlayer } from "../player.ts"; @@ -15,6 +16,7 @@ import type { ServerWorld } from "../world.ts"; import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts"; import { load_entity } from "./entity_types.ts"; import { ItemEntity } from "./item_entity.ts"; +import { MOBS_PATH_THROUGH } from "./pathfinding.ts"; import type { LivingEntity } from "./living_entity.ts"; // everything the entities need from the game server @@ -105,6 +107,15 @@ export class EntityManager implements EntityLevel { return this.#host.world.has_collision(x, y, z); } + has_chunk(chunk_x: number, chunk_z: number) { + return this.#host.world.has_chunk(chunk_x, chunk_z); + } + + passes_through(x: number, y: number, z: number) { + const block = this.#host.world.get_block_info(x, y, z); + return block !== undefined && Tags.has("blocks", MOBS_PATH_THROUGH, block.id); + } + collision_shape(x: number, y: number, z: number) { return this.#host.world.collision_shape(x, y, z); } diff --git a/server/game/entity/pathfinding.ts b/server/game/entity/pathfinding.ts new file mode 100644 index 0000000..358e1f9 --- /dev/null +++ b/server/game/entity/pathfinding.ts @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// how mobs find their way, like minecraft's PathFinder with its WalkNodeEvaluator: an A* search over the blocks a +// mob's feet can be in. whether it fits in each one comes from its box against the blocks' collision shapes, so +// partial blocks need nothing of their own: it steps up onto a slab, and gets past a thin open door at the side of a +// doorway. see PATHFINDING.md +import type { Shape } from "@/common/block_shapes.ts"; +import { CHUNK_SIZE } from "@/common/constants.ts"; +import { overlaps_solid } from "@/common/physics.ts"; + +export interface Point { + x: number; + y: number; + z: number; +} + +// blocks the search goes through as if they weren't there, like doors: a mob that runs into a closed one waits at it +// for its behavior to open it, see PathNavigation +export const MOBS_PATH_THROUGH = "cubi:mobs_path_through"; + +// what the search reads, the entity manager is one +export interface PathLevel { + collision_shape(x: number, y: number, z: number): boolean | Shape; + is_fluid(x: number, y: number, z: number): boolean; + has_chunk(chunk_x: number, chunk_z: number): boolean; + // whether the block is tagged MOBS_PATH_THROUGH + passes_through(x: number, y: number, z: number): boolean; +} + +// the mob: its feet's middle, its box, and how far up and down it goes from one block to the next. max_rise is 1 for +// a mob that jumps, or its step height for one that doesn't. max_fall is in blocks, 0 never drops, so it keeps out of +// pits, like minecraft's getMaxFallDistance +export interface PathBody extends Point { + width: number; + height: number; + max_rise: number; + max_fall: number; +} + +export interface PathOptions { + // how many blocks it goes on from before settling for the closest it got, like minecraft's maxVisitedNodes + max_nodes: number; + // how far from where it starts it can go + range: number; +} + +export interface Path { + // where to go, one after another, not counting where it starts: the middle of its feet in each block + points: Point[]; + // whether it gets to the target's block, or only as close as it could + reached: boolean; +} + +// what going through water costs on top of the way, like minecraft's PathType.WATER malus +const WATER_COST = 8; +// how far under its feet something holds it up +const SUPPORT = 0.1; +const EPSILON = 1e-4; + +const SIDES = [[1, 0], [-1, 0], [0, 1], [0, -1]] as const; +const DIAGONALS = [[1, 1], [1, -1], [-1, 1], [-1, -1]] as const; + +interface Node { + // the block its feet are in + x: number; + y: number; + z: number; + point: Point; + // the cost of the way here, and the distance left + g: number; + h: number; + parent: Node | undefined; + closed: boolean; +} + +// where it stands in a block and whether that's in water, or why it can't: "blocked" when its box doesn't fit there, +// "air" when it fits but nothing holds it up +type Probe = { point: Point; water: boolean } | "blocked" | "air"; + +// a way from the body to the target's block, or to as close as it can get when it can't. undefined when it can't get +// any closer than it is +export function find_path(level: PathLevel, body: PathBody, target: Point, options: PathOptions): Path | undefined { + // the blocks it reads, once each. chunks that aren't kept are solid, so the search never builds one, and blocks it + // passes through are empty + const shapes = new Map(); + const shape = (x: number, y: number, z: number) => { + const key = `${x},${y},${z}`; + let found = shapes.get(key); + if (found === undefined) { + const kept = level.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)); + found = !kept ? true : level.passes_through(x, y, z) ? false : level.collision_shape(x, y, z); + shapes.set(key, found); + } + return found; + }; + const free = (min: number[], max: number[]) => !overlaps_solid(min, max, shape); + + const half = body.width / 2; + const height = body.height; + const fits = (p: Point) => free([p.x - half, p.y, p.z - half], [p.x + half, p.y + height, p.z + half]); + const held_up = (p: Point) => !free([p.x - half, p.y - SUPPORT, p.z - half], [p.x + half, p.y, p.z + half]); + + const probes = new Map(); + const probe = (x: number, y: number, z: number): Probe => { + const key = `${x},${y},${z}`; + let found = probes.get(key); + if (found === undefined) { + found = probe_block(x, y, z); + probes.set(key, found); + } + return found; + }; + const probe_block = (x: number, y: number, z: number): Probe => { + const own = shape(x, y, z); + const top = own === true ? 1 : own === false ? 0 : Math.max(0, ...own.map((box) => box[4])); + // on top of something low in the block, like a slab, otherwise on its floor, beside whatever's there + const point = { x: x + 0.5, y: top < 1 ? y + top : y, z: z + 0.5 }; + if (!fits(point)) return "blocked"; + const water = level.is_fluid(x, y, z); + return water || held_up(point) ? { point, water } : "air"; + }; + + // whether it can go straight from one spot to the next: up first when it climbs, then across at the higher of the + // two, then down when it drops. a diagonal step sweeps across both blocks beside it, so it can't cut a corner + const can_move = (from: Point, to: Point) => { + if (to.y - from.y > body.max_rise + EPSILON) return false; + const top = Math.max(from.y, to.y); + // the box swept from a to b, from y up to its head at the top of the move + const sweep = (a: Point, b: Point, y: number) => + free( + [Math.min(a.x, b.x) - half, y, Math.min(a.z, b.z) - half], + [Math.max(a.x, b.x) + half, top + height, Math.max(a.z, b.z) + half], + ); + return sweep(from, from, from.y) && sweep(from, to, top) && sweep(to, to, to.y); + }; + + // the blocks it can get to from a node, and where it'd stand in them + const neighbors = (node: Node) => { + const found: { x: number; y: number; z: number; point: Point; water: boolean }[] = []; + const add = (x: number, y: number, z: number) => { + const result = probe(x, y, z); + if (typeof result === "object") found.push({ x, y, z, ...result }); + return result; + }; + for (const [dx, dz] of SIDES) { + const x = node.x + dx; + const z = node.z + dz; + const same = add(x, node.y, z); + if (same === "blocked") { + add(x, node.y + 1, z); + } else if (same === "air") { + for (let drop = 1; drop <= body.max_fall; drop++) { + if (add(x, node.y - drop, z) !== "air") break; + } + } + } + for (const [dx, dz] of DIAGONALS) add(node.x + dx, node.y, node.z + dz); + return found; + }; + + const start: Node = { + x: Math.floor(body.x), + y: Math.floor(body.y + EPSILON), + z: Math.floor(body.z), + point: { x: body.x, y: body.y, z: body.z }, + g: 0, + h: distance(body, target), + parent: undefined, + closed: false, + }; + const goal = { x: Math.floor(target.x), y: Math.floor(target.y + EPSILON), z: Math.floor(target.z) }; + const nodes = new Map([[`${start.x},${start.y},${start.z}`, start]]); + const open = new Heap(); + open.push(start.h, start); + let best = start; + let visited = 0; + + while (open.size > 0) { + const node = open.pop()!; + if (node.closed) continue; + node.closed = true; + if (node.x === goal.x && node.y === goal.y && node.z === goal.z) return path_to(node, true); + if (node.h < best.h) best = node; + if (++visited >= options.max_nodes) break; + + for (const next of neighbors(node)) { + if (distance(next.point, start.point) > options.range) continue; + const key = `${next.x},${next.y},${next.z}`; + const known = nodes.get(key); + if (known?.closed) continue; + const g = node.g + distance(node.point, next.point) + (next.water ? WATER_COST : 0); + if (known && known.g <= g) continue; + if (!can_move(node.point, next.point)) continue; + const child = known ?? { + x: next.x, + y: next.y, + z: next.z, + point: next.point, + g, + h: distance(next.point, target), + parent: node, + closed: false, + }; + child.g = g; + child.parent = node; + nodes.set(key, child); + open.push(g + child.h, child); + } + } + return best === start ? undefined : path_to(best, false); +} + +function path_to(node: Node, reached: boolean): Path { + const points: Point[] = []; + for (let at: Node | undefined = node; at?.parent; at = at.parent) points.push(at.point); + return { points: points.reverse(), reached }; +} + +function distance(a: Point, b: Point) { + return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); +} + +// the open nodes, cheapest first. a node whose cost went down is pushed again, and its old place is skipped once +// it's closed +class Heap { + #items: [number, Node][] = []; + + get size() { + return this.#items.length; + } + + push(cost: number, node: Node) { + const items = this.#items; + items.push([cost, node]); + let i = items.length - 1; + while (i > 0) { + const parent = (i - 1) >> 1; + if (items[parent][0] <= items[i][0]) break; + [items[parent], items[i]] = [items[i], items[parent]]; + i = parent; + } + } + + pop(): Node | undefined { + const items = this.#items; + const first = items[0]; + const last = items.pop(); + if (items.length > 0 && last) { + items[0] = last; + let i = 0; + while (true) { + const left = i * 2 + 1; + const right = left + 1; + let smallest = i; + if (left < items.length && items[left][0] < items[smallest][0]) smallest = left; + if (right < items.length && items[right][0] < items[smallest][0]) smallest = right; + if (smallest === i) break; + [items[smallest], items[i]] = [items[i], items[smallest]]; + i = smallest; + } + } + return first?.[1]; + } +} diff --git a/tests/pathfinding_test.ts b/tests/pathfinding_test.ts new file mode 100644 index 0000000..03d3ae0 --- /dev/null +++ b/tests/pathfinding_test.ts @@ -0,0 +1,177 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the search mobs find their way with, see server/game/entity/pathfinding.ts, on small made up worlds +import { assert, assertEquals } from "@std/assert"; +import type { Shape } from "@/common/block_shapes.ts"; +import { find_path, type PathBody, type PathOptions, type Point } from "@/server/game/entity/pathfinding.ts"; + +// a world that's empty except for what's put in it +function world() { + const blocks = new Map(); + const water = new Set(); + const through = new Set(); + const key = (x: number, y: number, z: number) => `${x},${y},${z}`; + const w = { + kept: (_chunk_x: number, _chunk_z: number) => true, + set(x: number, y: number, z: number, shape: boolean | Shape = true) { + blocks.set(key(x, y, z), shape); + return w; + }, + fill(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, shape: boolean | Shape = true) { + for (let x = x0; x <= x1; x++) { + for (let y = y0; y <= y1; y++) { + for (let z = z0; z <= z1; z++) w.set(x, y, z, shape); + } + } + return w; + }, + // tagged for mobs to path through + through(x: number, y: number, z: number) { + through.add(key(x, y, z)); + return w; + }, + water(x: number, y: number, z: number) { + water.add(key(x, y, z)); + blocks.delete(key(x, y, z)); + return w; + }, + collision_shape: (x: number, y: number, z: number) => blocks.get(key(x, y, z)) ?? false, + is_fluid: (x: number, y: number, z: number) => water.has(key(x, y, z)), + has_chunk: (chunk_x: number, chunk_z: number) => w.kept(chunk_x, chunk_z), + passes_through: (x: number, y: number, z: number) => through.has(key(x, y, z)), + }; + return w; +} + +// a floor from -8 to 8 at y 0, so feet stand at y 1 +const floor = () => world().fill(-8, 0, -8, 8, 0, 8); + +const OPTIONS: PathOptions = { max_nodes: 2000, range: 32 }; + +// a mob that jumps 1 block and drops up to 3 +function walker(x: number, z: number, width = 0.6, height = 1.8): PathBody { + return { x: x + 0.5, y: 1, z: z + 0.5, width, height, max_rise: 1, max_fall: 3 }; +} + +// one that doesn't jump, only steps up, and doesn't drop at all +const careful = (x: number, z: number): PathBody => ({ ...walker(x, z, 0.8, 1.9), max_rise: 0.6, max_fall: 0 }); + +const target = (x: number, y: number, z: number): Point => ({ x: x + 0.5, y, z: z + 0.5 }); + +const blocks_on = (points: Point[]) => points.map((p) => `${Math.floor(p.x)},${Math.floor(p.y)},${Math.floor(p.z)}`); + +Deno.test("a mob on open ground goes straight to the target", () => { + const path = find_path(floor(), walker(0, 0), target(5, 1, 0), OPTIONS)!; + assert(path.reached); + assertEquals(blocks_on(path.points), ["1,1,0", "2,1,0", "3,1,0", "4,1,0", "5,1,0"]); +}); + +Deno.test("a mob goes through a doorway in a wall, and around a corner", () => { + // a wall along x = 2 with a gap at z = 4, two blocks high so it can't be jumped + const w = floor().fill(2, 1, -8, 2, 2, 8).fill(2, 1, 4, 2, 2, 4, false); + const path = find_path(w, walker(0, 0), target(5, 1, 0), OPTIONS)!; + assert(path.reached); + assert(blocks_on(path.points).includes("2,1,4")); +}); + +Deno.test("a mob that can't get there goes as close as it can, and nowhere when it's shut in", () => { + const walled = floor().fill(2, 1, -8, 2, 2, 8); + const partial = find_path(walled, walker(0, 0), target(5, 1, 0), OPTIONS)!; + assert(!partial.reached); + assertEquals(blocks_on(partial.points).at(-1), "1,1,0"); + + const shut_in = floor().fill(-1, 1, -1, 1, 2, 1).fill(0, 1, 0, 0, 2, 0, false); + assertEquals(find_path(shut_in, walker(0, 0), target(5, 1, 0), OPTIONS), undefined); +}); + +Deno.test("a mob jumps up one block but not two, and drops three but not four", () => { + const step = floor().set(2, 1, 0).fill(3, 1, -8, 8, 1, 8); + assert(find_path(step, walker(0, 0), target(5, 2, 0), OPTIONS)!.reached); + const wall = floor().fill(2, 1, -8, 8, 2, 8); + assert(!find_path(wall, walker(0, 0), target(5, 3, 0), OPTIONS)?.reached); + + // standing on a ledge at y 3 (feet at 4), the ground beyond it 3 or 4 blocks down + const ledge = (drop: number) => world().fill(-8, 3, -8, 1, 3, 8).fill(2, 3 - drop, -8, 8, 3 - drop, 8); + const from_ledge = { ...walker(0, 0), y: 4 }; + assert(find_path(ledge(3), from_ledge, target(5, 1, 0), OPTIONS)!.reached); + assert(!find_path(ledge(4), from_ledge, target(5, 0, 0), OPTIONS)?.reached); +}); + +Deno.test("a mob steps onto a slab", () => { + const slab: Shape = [[0, 0, 0, 1, 0.5, 1]]; + const w = floor().set(2, 1, 0, slab); + const path = find_path(w, walker(0, 0), target(2, 1.5, 0), OPTIONS)!; + assert(path.reached); + assertEquals(path.points.at(-1)!.y, 1.5); +}); + +Deno.test("a mob gets past a thin open door, but not a closed one or a doorway too low for it", () => { + // a wall 3 high along z = 2 with a doorway 2 high at x = 0, the door 1/16 thick + const doorway = (door: Shape) => floor().fill(-8, 1, 2, 8, 3, 2).set(0, 1, 2, door).set(0, 2, 2, door); + const open: Shape = [[0, 0, 0, 0.0625, 1, 1]]; + const closed: Shape = [[0, 0, 0, 1, 1, 0.0625]]; + const coilhead = walker(0, 0, 0.8, 1.9); + assert(find_path(doorway(open), coilhead, target(0, 1, 5), OPTIONS)!.reached); + assert(!find_path(doorway(closed), coilhead, target(0, 1, 5), OPTIONS)?.reached); + assert(!find_path(doorway([]), walker(0, 0, 0.8, 2.5), target(0, 1, 5), OPTIONS)?.reached); +}); + +Deno.test("a mob that doesn't jump steps onto a slab but not a block", () => { + const slab: Shape = [[0, 0, 0, 1, 0.5, 1]]; + assert(find_path(floor().set(2, 1, 0, slab), careful(0, 0), target(2, 1.5, 0), OPTIONS)!.reached); + const step = floor().set(2, 1, 0).fill(3, 1, -8, 8, 1, 8); + assert(!find_path(step, careful(0, 0), target(5, 2, 0), OPTIONS)?.reached); +}); + +Deno.test("a mob that doesn't drop goes around a pit, and stops at one it can't get around", () => { + // a pit 3 deep at 2, 0, right in the way + const pit = floor().fill(2, -2, 0, 2, 0, 0, false).set(2, -3, 0); + const around = find_path(pit, careful(0, 0), target(4, 1, 0), OPTIONS)!; + assert(around.reached); + assert(!blocks_on(around.points).some((block) => block.startsWith("2,") && block.endsWith(",0"))); + + const trench = floor().fill(2, -2, -8, 2, 0, 8, false).fill(2, -3, -8, 2, -3, 8); + const stopped = find_path(trench, careful(0, 0), target(4, 1, 0), OPTIONS)!; + assert(!stopped.reached); + assertEquals(blocks_on(stopped.points).at(-1), "1,1,0"); +}); + +Deno.test("a mob's path goes through blocks tagged for it, like a closed door", () => { + const closed: Shape = [[0, 0, 0, 1, 1, 0.0625]]; + const door = () => floor().fill(-8, 1, 2, 8, 3, 2).set(0, 1, 2, closed).set(0, 2, 2, closed); + assert(!find_path(door(), careful(0, 0), target(0, 1, 5), OPTIONS)?.reached); + const tagged = door().through(0, 1, 2).through(0, 2, 2); + const path = find_path(tagged, careful(0, 0), target(0, 1, 5), OPTIONS)!; + assert(path.reached); + assert(blocks_on(path.points).includes("0,1,2")); +}); + +Deno.test("a mob doesn't cut between two blocks that meet at a corner", () => { + // the only way to 1, 1 is the gap between the corners of 1, 0 and 0, 1 + const w = world().fill(-1, 0, -1, 1, 0, 1).fill(1, 1, 0, 1, 2, 0).fill(0, 1, 1, 0, 2, 1); + const path = find_path(w, walker(0, 0), target(1, 1, 1), OPTIONS); + assert(!path?.reached); +}); + +Deno.test("a mob swims across water in its way", () => { + // a strip of water across the way + const pool = floor().fill(2, 0, -8, 2, 0, 8, false); + for (let z = -8; z <= 8; z++) pool.water(2, 0, z).water(2, 1, z); + pool.set(2, -1, 0); + assert(find_path(pool, walker(0, 0), target(4, 1, 0), OPTIONS)!.reached); +}); + +Deno.test("chunks that aren't kept count as solid", () => { + const w = world().fill(-8, 0, -8, 24, 0, 8); + w.kept = (chunk_x) => chunk_x < 1; + const path = find_path(w, walker(0, 0), target(20, 1, 0), OPTIONS)!; + assert(!path.reached); + assert(path.points.every((p) => p.x < 16)); +}); + +Deno.test("a mob only looks so far", () => { + const path = find_path(floor(), walker(0, 0), target(8, 1, 0), { max_nodes: 2000, range: 4 })!; + assert(!path.reached); + assert(path.points.every((p) => Math.hypot(p.x - 0.5, p.z - 0.5) <= 4)); +});