266 lines
9.3 KiB
TypeScript
266 lines
9.3 KiB
TypeScript
// 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 goes through a block when its box fits
|
|
// beside what's in it. 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, solid or not. a mob pressed against a solid one on its way
|
|
// waits there, for its behavior to do something about it, see PathNavigation.blocked_by
|
|
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<string, boolean | Shape>();
|
|
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<string, Probe>();
|
|
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<string, Node>([[`${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];
|
|
}
|
|
}
|