BlueGit

timfa questward

Penalize combat path backsteps at 2x tile cost.

Track the previous standing tile and prefer routes that do not immediately reverse while chasing, including ranged approach Dijkstra costs.

timfa Tim Falken · pushed by timfa

Authored 2026-09-06 · 2 months ago

Hash
7b7eb78461d1c6115c9ff673a869f2b8afe24f94
Parent
796508a1
6 files changed +252 −14
server/src/combat/service.js +22 −3
@@ -65,6 +65,7 @@ import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlay
65 65 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
66 66 import { tileToChunk } from "../world/coordinates.js";
67 67 import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
68 import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
68 69 import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
69 70 import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
70 71 import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
@@ -1320,6 +1321,20 @@ function shouldSeekCoverApproach (world, handle)
1320 1321 return !mobHasRangedRetaliation(world, handle);
1321 1322 }
1322 1323
1324 /** Double cost for stepping back onto the tile just left while chasing. */
1325 function combatApproachStepCost (position, baseCost = null)
1326 {
1327 const prevX = position?.prevTileX;
1328 const prevY = position?.prevTileY;
1329 return (x, y) => withCombatBackstepCost(
1330 baseCost ? baseCost(x, y) : 1,
1331 x,
1332 y,
1333 prevX,
1334 prevY
1335 );
1336 }
1337
1323 1338 function coverStepCost (world, threatPos, goalX, goalY, x, y)
1324 1339 {
1325 1340 // Final adjacent step is always in LOS — don't punish the last lunge.
@@ -1401,7 +1416,10 @@ function findCoverMeleeApproachPath (world, entityId, handle, position, targetPo
1401 1416 bounds.maxY,
1402 1417 {
1403 1418 preferVertical,
1404 stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1419 stepCost: combatApproachStepCost(
1420 position,
1421 (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1422 )
1405 1423 }
1406 1424 );
1407 1425 if (!tiles.length)
@@ -1604,7 +1622,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
1604 1622 bounds.minY,
1605 1623 bounds.maxX,
1606 1624 bounds.maxY,
1607 { preferVertical }
1625 { preferVertical, stepCost: combatApproachStepCost(position) }
1608 1626 );
1609 1627 if (!tiles.length)
1610 1628 {
@@ -1677,7 +1695,8 @@ export function queueStandInRangeApproach (
1677 1695 bounds.minX,
1678 1696 bounds.minY,
1679 1697 bounds.maxX,
1680 bounds.maxY
1698 bounds.maxY,
1699 { stepCost: combatApproachStepCost(position) }
1681 1700 );
1682 1701 if (!tiles.length)
1683 1702 {
@@ -65,6 +65,7 @@ import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlay
65import { chunkBoundsAround, findPath } from "../navigation/astar.js";
65import { chunkBoundsAround, findPath } from "../navigation/astar.js";
66import { tileToChunk } from "../world/coordinates.js";
66import { tileToChunk } from "../world/coordinates.js";
67import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
67import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
68import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
68import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
69import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
69import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
70import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
70import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
71import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
@@ -1320,6 +1321,20 @@ function shouldSeekCoverApproach (world, handle)
1320 return !mobHasRangedRetaliation(world, handle);
1321 return !mobHasRangedRetaliation(world, handle);
1321}
1322}
1322
1323
1324/** Double cost for stepping back onto the tile just left while chasing. */
1325function combatApproachStepCost (position, baseCost = null)
1326{
1327 const prevX = position?.prevTileX;
1328 const prevY = position?.prevTileY;
1329 return (x, y) => withCombatBackstepCost(
1330 baseCost ? baseCost(x, y) : 1,
1331 x,
1332 y,
1333 prevX,
1334 prevY
1335 );
1336}
1337
1323function coverStepCost (world, threatPos, goalX, goalY, x, y)
1338function coverStepCost (world, threatPos, goalX, goalY, x, y)
1324{
1339{
1325 // Final adjacent step is always in LOS — don't punish the last lunge.
1340 // Final adjacent step is always in LOS — don't punish the last lunge.
@@ -1401,7 +1416,10 @@ function findCoverMeleeApproachPath (world, entityId, handle, position, targetPo
1401 bounds.maxY,
1416 bounds.maxY,
1402 {
1417 {
1403 preferVertical,
1418 preferVertical,
1404 stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1419 stepCost: combatApproachStepCost(
1420 position,
1421 (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1422 )
1405 }
1423 }
1406 );
1424 );
1407 if (!tiles.length)
1425 if (!tiles.length)
@@ -1604,7 +1622,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
1604 bounds.minY,
1622 bounds.minY,
1605 bounds.maxX,
1623 bounds.maxX,
1606 bounds.maxY,
1624 bounds.maxY,
1607 { preferVertical }
1625 { preferVertical, stepCost: combatApproachStepCost(position) }
1608 );
1626 );
1609 if (!tiles.length)
1627 if (!tiles.length)
1610 {
1628 {
@@ -1677,7 +1695,8 @@ export function queueStandInRangeApproach (
1677 bounds.minX,
1695 bounds.minX,
1678 bounds.minY,
1696 bounds.minY,
1679 bounds.maxX,
1697 bounds.maxX,
1680 bounds.maxY
1698 bounds.maxY,
1699 { stepCost: combatApproachStepCost(position) }
1681 );
1700 );
1682 if (!tiles.length)
1701 if (!tiles.length)
1683 {
1702 {
server/src/simulation/workerWorld.js +28 −8
@@ -95,6 +95,7 @@ import {
95 95 PATH_GROUND_STEP_COST,
96 96 SOFT_OCCUPIED_DWELL_MS
97 97 } from "../../../shared/navigation/pathGround.js";
98 import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
98 99 import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
99 100 import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
100 101 import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
@@ -1600,6 +1601,8 @@ export class WorkerWorld
1600 1601 const flying = this.#isFlying(handle);
1601 1602 if (!flying)
1602 1603 { this.#vacate(entityId, fromTileX, fromTileY); }
1604 position.prevTileX = fromTileX;
1605 position.prevTileY = fromTileY;
1603 1606 position.tileX = next.x;
1604 1607 position.tileY = next.y;
1605 1608 tiles.shift();
@@ -1672,7 +1675,8 @@ export class WorkerWorld
1672 1675 this.pathfindOptions({
1673 1676 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1674 1677 preferPaths: !inCombat,
1675 entityId
1678 entityId,
1679 penalizeCombatBackstep: inCombat
1676 1680 })
1677 1681 );
1678 1682 path.stuckSince = now;
@@ -2260,20 +2264,36 @@ export class WorkerWorld
2260 2264 }
2261 2265
2262 2266 /**
2263 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]
2267 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]
2264 2268 */
2265 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})
2269 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})
2266 2270 {
2267 2271 const options = { preferVertical: !!preferVertical };
2268 2272 const now = Date.now();
2269 2273 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2270 options.stepCost = (x, y) => stepCostForGround(
2271 this.groundTypeAt(x, y, dimensionId),
2274 let prevTileX = null;
2275 let prevTileY = null;
2276 if (penalizeCombatBackstep && entityId != null)
2277 {
2278 const handle = this.ecs.handleOf(entityId);
2279 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2280 if (position?.prevTileX != null && position?.prevTileY != null)
2272 2281 {
2273 preferPaths: !!preferPaths,
2274 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2282 prevTileX = position.prevTileX | 0;
2283 prevTileY = position.prevTileY | 0;
2275 2284 }
2276 );
2285 }
2286 options.stepCost = (x, y) =>
2287 {
2288 const base = stepCostForGround(
2289 this.groundTypeAt(x, y, dimensionId),
2290 {
2291 preferPaths: !!preferPaths,
2292 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2293 }
2294 );
2295 return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);
2296 };
2277 2297 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2278 2298 return options;
2279 2299 }
@@ -95,6 +95,7 @@ import {
95 PATH_GROUND_STEP_COST,
95 PATH_GROUND_STEP_COST,
96 SOFT_OCCUPIED_DWELL_MS
96 SOFT_OCCUPIED_DWELL_MS
97} from "../../../shared/navigation/pathGround.js";
97} from "../../../shared/navigation/pathGround.js";
98import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
98import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
99import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
99import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
100import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
100import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
101import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
@@ -1600,6 +1601,8 @@ export class WorkerWorld
1600 const flying = this.#isFlying(handle);
1601 const flying = this.#isFlying(handle);
1601 if (!flying)
1602 if (!flying)
1602 { this.#vacate(entityId, fromTileX, fromTileY); }
1603 { this.#vacate(entityId, fromTileX, fromTileY); }
1604 position.prevTileX = fromTileX;
1605 position.prevTileY = fromTileY;
1603 position.tileX = next.x;
1606 position.tileX = next.x;
1604 position.tileY = next.y;
1607 position.tileY = next.y;
1605 tiles.shift();
1608 tiles.shift();
@@ -1672,7 +1675,8 @@ export class WorkerWorld
1672 this.pathfindOptions({
1675 this.pathfindOptions({
1673 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1676 preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1674 preferPaths: !inCombat,
1677 preferPaths: !inCombat,
1675 entityId
1678 entityId,
1679 penalizeCombatBackstep: inCombat
1676 })
1680 })
1677 );
1681 );
1678 path.stuckSince = now;
1682 path.stuckSince = now;
@@ -2260,20 +2264,36 @@ export class WorkerWorld
2260 }
2264 }
2261
2265
2262 /**
2266 /**
2263 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]
2267 * @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]
2264 */
2268 */
2265 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})
2269 pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})
2266 {
2270 {
2267 const options = { preferVertical: !!preferVertical };
2271 const options = { preferVertical: !!preferVertical };
2268 const now = Date.now();
2272 const now = Date.now();
2269 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2273 const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2270 options.stepCost = (x, y) => stepCostForGround(
2274 let prevTileX = null;
2271 this.groundTypeAt(x, y, dimensionId),
2275 let prevTileY = null;
2276 if (penalizeCombatBackstep && entityId != null)
2277 {
2278 const handle = this.ecs.handleOf(entityId);
2279 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2280 if (position?.prevTileX != null && position?.prevTileY != null)
2272 {
2281 {
2273 preferPaths: !!preferPaths,
2282 prevTileX = position.prevTileX | 0;
2274 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2283 prevTileY = position.prevTileY | 0;
2275 }
2284 }
2276 );
2285 }
2286 options.stepCost = (x, y) =>
2287 {
2288 const base = stepCostForGround(
2289 this.groundTypeAt(x, y, dimensionId),
2290 {
2291 preferPaths: !!preferPaths,
2292 softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2293 }
2294 );
2295 return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);
2296 };
2277 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2297 options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2278 return options;
2298 return options;
2279 }
2299 }
server/tests/astar.test.js +26 −0
@@ -2,6 +2,7 @@ import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { findPath, orderedCardinals } from "../src/navigation/astar.js";
4 4 import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";
5 import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
5 6 import { GroundType } from "../../shared/definitions/tiles.js";
6 7
7 8 test("A* walks around an impassable tile", () =>
@@ -202,3 +203,28 @@ test("A* still crosses soft-occupied when the detour is much longer", () =>
202 203 );
203 204 assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
204 205 });
206
207 test("A* combat backstep cost prefers not re-entering the previous tile", () =>
208 {
209 // Open field start (0,0) goal (1,1). Paths: (1,0)-(1,1) or (0,1)-(1,1).
210 // Prev tile (1,0) → first path costs 2+1=3, second costs 1+1=2 → prefer (0,1).
211 const prevX = 1;
212 const prevY = 0;
213 const path = findPath(
214 0,
215 0,
216 1,
217 1,
218 () => true,
219 -2,
220 -2,
221 4,
222 4,
223 {
224 stepCost: (x, y) => withCombatBackstepCost(1, x, y, prevX, prevY)
225 }
226 );
227 assert.ok(path.length > 0);
228 assert.deepEqual(path[0], { x: 0, y: 1 }, JSON.stringify(path));
229 assert.ok(!path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
230 });
@@ -2,6 +2,7 @@ import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { findPath, orderedCardinals } from "../src/navigation/astar.js";
3import { findPath, orderedCardinals } from "../src/navigation/astar.js";
4import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";
4import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";
5import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
5import { GroundType } from "../../shared/definitions/tiles.js";
6import { GroundType } from "../../shared/definitions/tiles.js";
6
7
7test("A* walks around an impassable tile", () =>
8test("A* walks around an impassable tile", () =>
@@ -202,3 +203,28 @@ test("A* still crosses soft-occupied when the detour is much longer", () =>
202 );
203 );
203 assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
204 assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
204});
205});
206
207test("A* combat backstep cost prefers not re-entering the previous tile", () =>
208{
209 // Open field start (0,0) goal (1,1). Paths: (1,0)-(1,1) or (0,1)-(1,1).
210 // Prev tile (1,0) → first path costs 2+1=3, second costs 1+1=2 → prefer (0,1).
211 const prevX = 1;
212 const prevY = 0;
213 const path = findPath(
214 0,
215 0,
216 1,
217 1,
218 () => true,
219 -2,
220 -2,
221 4,
222 4,
223 {
224 stepCost: (x, y) => withCombatBackstepCost(1, x, y, prevX, prevY)
225 }
226 );
227 assert.ok(path.length > 0);
228 assert.deepEqual(path[0], { x: 0, y: 1 }, JSON.stringify(path));
229 assert.ok(!path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
230});
server/tests/bfs-approach.test.js +18 −0
@@ -1,6 +1,7 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
4 import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
4 5
5 6 test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6 7 {
@@ -38,3 +39,20 @@ test("BFS returns empty when already at a goal", () =>
38 39 );
39 40 assert.deepEqual(path, []);
40 41 });
42
43 test("weighted nearest-goal search avoids an expensive backstep tile", () =>
44 {
45 // Start (0,0); goals are (1,0) and (0,1). Prev is (1,0) so prefer (0,1).
46 const path = findPathToNearestGoal(
47 0,
48 0,
49 (x, y) => (x === 1 && y === 0) || (x === 0 && y === 1),
50 () => true,
51 -2,
52 -2,
53 4,
54 4,
55 { stepCost: (x, y) => withCombatBackstepCost(1, x, y, 1, 0) }
56 );
57 assert.deepEqual(path, [{ x: 0, y: 1 }]);
58 });
@@ -1,6 +1,7 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
3import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
4import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
4
5
5test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6{
7{
@@ -38,3 +39,20 @@ test("BFS returns empty when already at a goal", () =>
38 );
39 );
39 assert.deepEqual(path, []);
40 assert.deepEqual(path, []);
40});
41});
42
43test("weighted nearest-goal search avoids an expensive backstep tile", () =>
44{
45 // Start (0,0); goals are (1,0) and (0,1). Prev is (1,0) so prefer (0,1).
46 const path = findPathToNearestGoal(
47 0,
48 0,
49 (x, y) => (x === 1 && y === 0) || (x === 0 && y === 1),
50 () => true,
51 -2,
52 -2,
53 4,
54 4,
55 { stepCost: (x, y) => withCombatBackstepCost(1, x, y, 1, 0) }
56 );
57 assert.deepEqual(path, [{ x: 0, y: 1 }]);
58});
shared/navigation/bfs.js +132 −3
@@ -1,6 +1,6 @@
1 1 /**
2 * 4-connected BFS from the start tile to the nearest walkable goal.
3 * First goal reached is shortest path length (no top-left Chebyshev bias).
2 * 4-connected path to the nearest walkable goal.
3 * Uniform costs use BFS; optional stepCost uses Dijkstra (same API).
4 4 */
5 5
6 6 const CARDINALS = Object.freeze([
@@ -19,9 +19,10 @@ const CARDINALS = Object.freeze([
19 19 * @param {number} minY
20 20 * @param {number} maxX
21 21 * @param {number} maxY
22 * @param {{ stepCost?: (x: number, y: number) => number }} [options]
22 23 * @returns {{ x: number, y: number }[]} path tiles after start (empty if already at goal or unreachable)
23 24 */
24 export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY)
25 export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY, options = {})
25 26 {
26 27 if (!isWalkable(startX, startY))
27 28 { return []; }
@@ -33,6 +34,24 @@ export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX,
33 34 if (width <= 0 || height <= 0)
34 35 { return []; }
35 36
37 const stepCost = typeof options.stepCost === "function" ? options.stepCost : null;
38 if (stepCost)
39 {
40 return findPathToNearestGoalWeighted(
41 startX,
42 startY,
43 isGoal,
44 isWalkable,
45 minX,
46 minY,
47 maxX,
48 maxY,
49 width,
50 height,
51 stepCost
52 );
53 }
54
36 55 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
37 56 const index = (x, y) => (y - minY) * width + (x - minX);
38 57
@@ -67,6 +86,116 @@ export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX,
67 86 return [];
68 87 }
69 88
89 /**
90 * Dijkstra to nearest goal when tile step costs are non-uniform.
91 * @param {(x: number, y: number) => number} stepCost
92 */
93 function findPathToNearestGoalWeighted (
94 startX,
95 startY,
96 isGoal,
97 isWalkable,
98 minX,
99 minY,
100 maxX,
101 maxY,
102 width,
103 height,
104 stepCost
105 )
106 {
107 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
108 const index = (x, y) => (y - minY) * width + (x - minX);
109
110 const cameFrom = new Int32Array(width * height).fill(-1);
111 const gScore = new Float64Array(width * height).fill(Infinity);
112 const closed = new Uint8Array(width * height);
113 const startIndex = index(startX, startY);
114 gScore[startIndex] = 0;
115
116 /** @type {{ x: number, y: number, g: number }[]} */
117 const heap = [{ x: startX, y: startY, g: 0 }];
118
119 const siftUp = (i) =>
120 {
121 while (i > 0)
122 {
123 const p = (i - 1) >> 1;
124 if (heap[p].g <= heap[i].g)
125 { break; }
126 const tmp = heap[p];
127 heap[p] = heap[i];
128 heap[i] = tmp;
129 i = p;
130 }
131 };
132 const siftDown = (i) =>
133 {
134 for (;;)
135 {
136 const left = i * 2 + 1;
137 const right = left + 1;
138 let best = i;
139 if (left < heap.length && heap[left].g < heap[best].g)
140 { best = left; }
141 if (right < heap.length && heap[right].g < heap[best].g)
142 { best = right; }
143 if (best === i)
144 { break; }
145 const tmp = heap[i];
146 heap[i] = heap[best];
147 heap[best] = tmp;
148 i = best;
149 }
150 };
151 const pop = () =>
152 {
153 const root = heap[0];
154 const last = heap.pop();
155 if (heap.length > 0 && last)
156 {
157 heap[0] = last;
158 siftDown(0);
159 }
160 return root;
161 };
162
163 while (heap.length > 0)
164 {
165 const current = pop();
166 if (!inBounds(current.x, current.y))
167 { continue; }
168 const currentIndex = index(current.x, current.y);
169 if (closed[currentIndex])
170 { continue; }
171 closed[currentIndex] = 1;
172
173 if (isGoal(current.x, current.y) && !(current.x === startX && current.y === startY))
174 { return reconstruct(cameFrom, current.x, current.y, minX, minY, width); }
175
176 for (const dir of CARDINALS)
177 {
178 const nx = current.x + dir.x;
179 const ny = current.y + dir.y;
180 if (!inBounds(nx, ny) || !isWalkable(nx, ny))
181 { continue; }
182 const neighborIndex = index(nx, ny);
183 if (closed[neighborIndex])
184 { continue; }
185 const cost = Math.max(0.001, Number(stepCost(nx, ny)) || 1);
186 const tentative = gScore[currentIndex] + cost;
187 if (tentative >= gScore[neighborIndex])
188 { continue; }
189 cameFrom[neighborIndex] = currentIndex;
190 gScore[neighborIndex] = tentative;
191 heap.push({ x: nx, y: ny, g: tentative });
192 siftUp(heap.length - 1);
193 }
194 }
195
196 return [];
197 }
198
70 199 function reconstruct (cameFrom, x, y, minX, minY, width)
71 200 {
72 201 const path = [];
@@ -1,6 +1,6 @@
1/**
1/**
2 * 4-connected BFS from the start tile to the nearest walkable goal.
2 * 4-connected path to the nearest walkable goal.
3 * First goal reached is shortest path length (no top-left Chebyshev bias).
3 * Uniform costs use BFS; optional stepCost uses Dijkstra (same API).
4 */
4 */
5
5
6const CARDINALS = Object.freeze([
6const CARDINALS = Object.freeze([
@@ -19,9 +19,10 @@ const CARDINALS = Object.freeze([
19 * @param {number} minY
19 * @param {number} minY
20 * @param {number} maxX
20 * @param {number} maxX
21 * @param {number} maxY
21 * @param {number} maxY
22 * @param {{ stepCost?: (x: number, y: number) => number }} [options]
22 * @returns {{ x: number, y: number }[]} path tiles after start (empty if already at goal or unreachable)
23 * @returns {{ x: number, y: number }[]} path tiles after start (empty if already at goal or unreachable)
23 */
24 */
24export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY)
25export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX, minY, maxX, maxY, options = {})
25{
26{
26 if (!isWalkable(startX, startY))
27 if (!isWalkable(startX, startY))
27 { return []; }
28 { return []; }
@@ -33,6 +34,24 @@ export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX,
33 if (width <= 0 || height <= 0)
34 if (width <= 0 || height <= 0)
34 { return []; }
35 { return []; }
35
36
37 const stepCost = typeof options.stepCost === "function" ? options.stepCost : null;
38 if (stepCost)
39 {
40 return findPathToNearestGoalWeighted(
41 startX,
42 startY,
43 isGoal,
44 isWalkable,
45 minX,
46 minY,
47 maxX,
48 maxY,
49 width,
50 height,
51 stepCost
52 );
53 }
54
36 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
55 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
37 const index = (x, y) => (y - minY) * width + (x - minX);
56 const index = (x, y) => (y - minY) * width + (x - minX);
38
57
@@ -67,6 +86,116 @@ export function findPathToNearestGoal (startX, startY, isGoal, isWalkable, minX,
67 return [];
86 return [];
68}
87}
69
88
89/**
90 * Dijkstra to nearest goal when tile step costs are non-uniform.
91 * @param {(x: number, y: number) => number} stepCost
92 */
93function findPathToNearestGoalWeighted (
94 startX,
95 startY,
96 isGoal,
97 isWalkable,
98 minX,
99 minY,
100 maxX,
101 maxY,
102 width,
103 height,
104 stepCost
105)
106{
107 const inBounds = (x, y) => x >= minX && y >= minY && x <= maxX && y <= maxY;
108 const index = (x, y) => (y - minY) * width + (x - minX);
109
110 const cameFrom = new Int32Array(width * height).fill(-1);
111 const gScore = new Float64Array(width * height).fill(Infinity);
112 const closed = new Uint8Array(width * height);
113 const startIndex = index(startX, startY);
114 gScore[startIndex] = 0;
115
116 /** @type {{ x: number, y: number, g: number }[]} */
117 const heap = [{ x: startX, y: startY, g: 0 }];
118
119 const siftUp = (i) =>
120 {
121 while (i > 0)
122 {
123 const p = (i - 1) >> 1;
124 if (heap[p].g <= heap[i].g)
125 { break; }
126 const tmp = heap[p];
127 heap[p] = heap[i];
128 heap[i] = tmp;
129 i = p;
130 }
131 };
132 const siftDown = (i) =>
133 {
134 for (;;)
135 {
136 const left = i * 2 + 1;
137 const right = left + 1;
138 let best = i;
139 if (left < heap.length && heap[left].g < heap[best].g)
140 { best = left; }
141 if (right < heap.length && heap[right].g < heap[best].g)
142 { best = right; }
143 if (best === i)
144 { break; }
145 const tmp = heap[i];
146 heap[i] = heap[best];
147 heap[best] = tmp;
148 i = best;
149 }
150 };
151 const pop = () =>
152 {
153 const root = heap[0];
154 const last = heap.pop();
155 if (heap.length > 0 && last)
156 {
157 heap[0] = last;
158 siftDown(0);
159 }
160 return root;
161 };
162
163 while (heap.length > 0)
164 {
165 const current = pop();
166 if (!inBounds(current.x, current.y))
167 { continue; }
168 const currentIndex = index(current.x, current.y);
169 if (closed[currentIndex])
170 { continue; }
171 closed[currentIndex] = 1;
172
173 if (isGoal(current.x, current.y) && !(current.x === startX && current.y === startY))
174 { return reconstruct(cameFrom, current.x, current.y, minX, minY, width); }
175
176 for (const dir of CARDINALS)
177 {
178 const nx = current.x + dir.x;
179 const ny = current.y + dir.y;
180 if (!inBounds(nx, ny) || !isWalkable(nx, ny))
181 { continue; }
182 const neighborIndex = index(nx, ny);
183 if (closed[neighborIndex])
184 { continue; }
185 const cost = Math.max(0.001, Number(stepCost(nx, ny)) || 1);
186 const tentative = gScore[currentIndex] + cost;
187 if (tentative >= gScore[neighborIndex])
188 { continue; }
189 cameFrom[neighborIndex] = currentIndex;
190 gScore[neighborIndex] = tentative;
191 heap.push({ x: nx, y: ny, g: tentative });
192 siftUp(heap.length - 1);
193 }
194 }
195
196 return [];
197}
198
70function reconstruct (cameFrom, x, y, minX, minY, width)
199function reconstruct (cameFrom, x, y, minX, minY, width)
71{
200{
72 const path = [];
201 const path = [];
shared/navigation/combatPathCost.js added +26 −0
@@ -0,0 +1,26 @@
1 /**
2 * Extra A* / Dijkstra cost when combat-pathing back onto the tile just left.
3 * Discourages oscillating between two tiles while chasing.
4 */
5 export const COMBAT_BACKSTEP_COST_MULT = 2;
6
7 /**
8 * @param {number} baseCost
9 * @param {number} x
10 * @param {number} y
11 * @param {number | null | undefined} prevTileX
12 * @param {number | null | undefined} prevTileY
13 */
14 export function withCombatBackstepCost (baseCost, x, y, prevTileX, prevTileY)
15 {
16 const cost = Number(baseCost);
17 const safe = Number.isFinite(cost) && cost > 0 ? cost : 1;
18 if (
19 prevTileX != null
20 && prevTileY != null
21 && x === (prevTileX | 0)
22 && y === (prevTileY | 0)
23 )
24 { return safe * COMBAT_BACKSTEP_COST_MULT; }
25 return safe;
26 }
@@ -0,0 +1,26 @@
1/**
2 * Extra A* / Dijkstra cost when combat-pathing back onto the tile just left.
3 * Discourages oscillating between two tiles while chasing.
4 */
5export const COMBAT_BACKSTEP_COST_MULT = 2;
6
7/**
8 * @param {number} baseCost
9 * @param {number} x
10 * @param {number} y
11 * @param {number | null | undefined} prevTileX
12 * @param {number | null | undefined} prevTileY
13 */
14export function withCombatBackstepCost (baseCost, x, y, prevTileX, prevTileY)
15{
16 const cost = Number(baseCost);
17 const safe = Number.isFinite(cost) && cost > 0 ? cost : 1;
18 if (
19 prevTileX != null
20 && prevTileY != null
21 && x === (prevTileX | 0)
22 && y === (prevTileY | 0)
23 )
24 { return safe * COMBAT_BACKSTEP_COST_MULT; }
25 return safe;
26}