@vielzeug/atlas 26.11.24 → 26.11.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,7 +34,7 @@ index.queryRect(camera.visibleRect); // viewport culling, returns ids
34
34
  - Narrow-phase geometry: `pointInPolygon`, `distanceToPolyline`, `pointNearPolygon`
35
35
  - Frames: `frameMatrix()` placement, `boundsOfFrame()` world AABBs, and `resizeRect()` edge/corner resizing with min and aspect locks
36
36
  - Snapping: `snapRect()` with candidate, grid, and equal-gap (`spacing`) targets and kind-tagged guide descriptors, plus pure `alignRects()`/`distributeRects()`
37
- - `@vielzeug/atlas/grid` subpath: square-tile coordinate math, viewport tile ranges, 8-octant shadowcasting `computeFov()`, and three-state `createFog()`
37
+ - `@vielzeug/atlas/grid` subpath: square-tile and axial-hex coordinate math, viewport culling, 8-octant shadowcasting `computeFov()` and hex-line `computeHexFov()`, three-state `createFog()`, `squareTopology()`/`hexTopology`, and `findPath()`/`reachable()` search
38
38
  - Typed errors; the camera follows the Vielzeug disposal contract
39
39
  - Zero runtime dependencies, no DOM requirement
40
40
 
@@ -0,0 +1,2 @@
1
+ const e=require("../errors.cjs");var t=Math.sqrt(3),n=[{q:1,r:0},{q:1,r:-1},{q:0,r:-1},{q:-1,r:0},{q:-1,r:1},{q:0,r:1}];function assertLayout(t){if(!(t.size>0))throw new e.AtlasConfigError(`hex layout.size must be positive, got ${t.size}`);if(t.orientation!==`flat`&&t.orientation!==`pointy`)throw new e.AtlasConfigError(`hex layout.orientation must be "flat" or "pointy", got ${String(t.orientation)}`)}function assertHex(t){if(!Number.isInteger(t.q)||!Number.isInteger(t.r))throw new e.AtlasConfigError(`hex coordinates must be integers, got (${t.q}, ${t.r})`)}function hexToWorld(e,n){return assertLayout(n),assertHex(e),n.orientation===`pointy`?{x:n.size*t*(e.q+e.r/2),y:n.size*1.5*e.r}:{x:n.size*1.5*e.q,y:n.size*t*(e.r+e.q/2)}}function worldToHex(e,n){return assertLayout(n),cubeRound(n.orientation===`pointy`?t/3*e.x/n.size-e.y/(3*n.size):2/3*e.x/n.size,n.orientation===`pointy`?2/3*e.y/n.size:-e.x/(3*n.size)+t/3*e.y/n.size)}function cubeRound(e,t){let n=-e-t,r=Math.round(e),i=Math.round(t),a=Math.round(n),o=Math.abs(r-e),s=Math.abs(i-t),c=Math.abs(a-n);return o>s&&o>c?r=-i-a:s>c&&(i=-r-a),{q:r,r:i}}function hexCorners(e,t){assertLayout(t);let n=hexToWorld(e,t),r=t.orientation===`pointy`?30:0;return Array.from({length:6},(e,i)=>{let a=(r+60*i)*Math.PI/180;return{x:n.x+t.size*Math.cos(a),y:n.y+t.size*Math.sin(a)}})}function hexKey(e){return`${String(e.q)}:${String(e.r)}`}function hexDistance(e,t){let n=e.q-t.q,r=e.r-t.r;return(Math.abs(n)+Math.abs(r)+Math.abs(n+r))/2}function hexNeighbors(e){return n.map(t=>({q:e.q+t.q,r:e.r+t.r}))}function hexRange(t,n){if(!Number.isInteger(n)||n<0)throw new e.AtlasConfigError(`hex radius must be a non-negative integer, got ${n}`);let r=[];for(let e=-n;e<=n;e+=1){let i=Math.max(-n,-e-n),a=Math.min(n,-e+n);for(let n=i;n<=a;n+=1)r.push({q:t.q+e,r:t.r+n})}return r}function hexLine(e,t){let n=hexDistance(e,t);if(n===0)return[{q:e.q,r:e.r}];let r=e.q<t.q||e.q===t.q&&e.r<=t.r,i=r?e:t,a=r?t:e,o=a.q-i.q,s=a.r-i.r,c=1e-7,l=i.q+c*Math.sign(o),u=i.r+c*Math.sign(s),d=a.q-c*Math.sign(o),f=a.r-c*Math.sign(s),p=[];for(let e=0;e<=n;e+=1){let t=e/n;p.push(cubeRound(l+(d-l)*t,u+(f-u)*t))}return r?p:p.reverse()}function visibleHexes(e,t){assertLayout(t);let n=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x,y:e.y+e.height},{x:e.x+e.width,y:e.y+e.height}],r=1/0,i=-1/0,a=1/0,o=-1/0;for(let e of n){let n=worldToHex(e,t);n.q<r&&(r=n.q),n.q>i&&(i=n.q),n.r<a&&(a=n.r),n.r>o&&(o=n.r)}let s=[];for(let e=r-1;e<=i+1;e+=1)for(let t=a-1;t<=o+1;t+=1)s.push({q:e,r:t});return s}function computeHexFov(t,n,r={}){if(!Number.isInteger(n)||n<0)throw new e.AtlasConfigError(`hex FOV radius must be a non-negative integer, got ${n}`);let i=r.blocks??(()=>!1),a=new Set([hexKey(t)]);for(let e of hexRange(t,n)){if(hexDistance(t,e)===0)continue;let n=hexLine(t,e),r=!0;for(let e=1;e<n.length-1;e+=1){let t=n[e];if(t&&i(t)){r=!1;break}}r&&a.add(hexKey(e))}return a}var r={distance:hexDistance,key:hexKey,line:hexLine,neighbors:hexNeighbors};exports.HEX_DIRECTIONS=n,exports.computeHexFov=computeHexFov,exports.hexCorners=hexCorners,exports.hexDistance=hexDistance,exports.hexKey=hexKey,exports.hexLine=hexLine,exports.hexNeighbors=hexNeighbors,exports.hexRange=hexRange,exports.hexToWorld=hexToWorld,exports.hexTopology=r,exports.visibleHexes=visibleHexes,exports.worldToHex=worldToHex;
2
+ //# sourceMappingURL=hex.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hex.cjs","names":["AtlasConfigError","require_errors","SQRT3","HEX_DIRECTIONS","layout","coord","point","s","q","r","rq","rr","rs","dq","dr","ds","center","start","angle","a","b","d","radius","out","rMin","rMax","forward","from","to","eps","q0","r0","q1","r1","i","corners","view","minQ","maxQ","minR","maxR","corner","hex","blocks","options","lit","origin","path","clear","step","hexTopology"],"sources":["../../src/grid/hex.ts"],"sourcesContent":["/**\n * Hex-grid math on axial coordinates. A hex is `{ q, r }`; the third cube axis\n * is derived (`s = -q - r`), so distance and rounding stay exact without\n * storing it. Layouts are pointy- or flat-topped with a world-unit radius\n * (`size` = centre to corner), and the conversion pair is an exact inverse:\n * `worldToHex(hexToWorld(h, l), l)` returns `h` for every hex.\n */\nimport { AtlasConfigError } from '../errors.js';\nimport type { Point, Rect } from '../shapes.js';\nimport type { GridTopology } from './topology.js';\n\n/** A hex addressed by axial coordinates (`s` is always `-q - r`). */\nexport type HexCoord = Readonly<{ q: number; r: number }>;\n\n/** How hexes map to world space: `size` is the centre-to-corner radius. */\nexport type HexLayout = Readonly<{\n orientation: 'flat' | 'pointy';\n size: number;\n}>;\n\nconst SQRT3 = Math.sqrt(3);\n\n/** The six axial neighbour directions, in clockwise order from east. */\nexport const HEX_DIRECTIONS: readonly HexCoord[] = [\n { q: 1, r: 0 },\n { q: 1, r: -1 },\n { q: 0, r: -1 },\n { q: -1, r: 0 },\n { q: -1, r: 1 },\n { q: 0, r: 1 },\n];\n\nfunction assertLayout(layout: HexLayout): void {\n if (!(layout.size > 0)) {\n throw new AtlasConfigError(`hex layout.size must be positive, got ${layout.size}`);\n }\n if (layout.orientation !== 'flat' && layout.orientation !== 'pointy') {\n throw new AtlasConfigError(`hex layout.orientation must be \"flat\" or \"pointy\", got ${String(layout.orientation)}`);\n }\n}\n\nfunction assertHex(coord: HexCoord): void {\n if (!Number.isInteger(coord.q) || !Number.isInteger(coord.r)) {\n throw new AtlasConfigError(`hex coordinates must be integers, got (${coord.q}, ${coord.r})`);\n }\n}\n\n/** The world centre of a hex. */\nexport function hexToWorld(coord: HexCoord, layout: HexLayout): Point {\n assertLayout(layout);\n assertHex(coord);\n if (layout.orientation === 'pointy') {\n return { x: layout.size * SQRT3 * (coord.q + coord.r / 2), y: layout.size * 1.5 * coord.r };\n }\n return { x: layout.size * 1.5 * coord.q, y: layout.size * SQRT3 * (coord.r + coord.q / 2) };\n}\n\n/** The hex whose centre is nearest to a world point. */\nexport function worldToHex(point: Point, layout: HexLayout): HexCoord {\n assertLayout(layout);\n const fq =\n layout.orientation === 'pointy'\n ? ((SQRT3 / 3) * point.x) / layout.size - point.y / (3 * layout.size)\n : ((2 / 3) * point.x) / layout.size;\n const fr =\n layout.orientation === 'pointy'\n ? ((2 / 3) * point.y) / layout.size\n : -point.x / (3 * layout.size) + ((SQRT3 / 3) * point.y) / layout.size;\n return cubeRound(fq, fr);\n}\n\n/** Rounds fractional axial coordinates to the nearest hex (cube rounding). */\nfunction cubeRound(q: number, r: number): HexCoord {\n const s = -q - r;\n let rq = Math.round(q);\n let rr = Math.round(r);\n const rs = Math.round(s);\n // The axis with the smallest rounding error is derived from the other two.\n const dq = Math.abs(rq - q);\n const dr = Math.abs(rr - r);\n const ds = Math.abs(rs - s);\n if (dq > dr && dq > ds) rq = -rr - rs;\n else if (dr > ds) rr = -rq - rs;\n return { q: rq, r: rr };\n}\n\n/** The six corner points of a hex, in clockwise order from the first corner. */\nexport function hexCorners(coord: HexCoord, layout: HexLayout): readonly Point[] {\n assertLayout(layout);\n const center = hexToWorld(coord, layout);\n const start = layout.orientation === 'pointy' ? 30 : 0;\n return Array.from({ length: 6 }, (_, i) => {\n const angle = ((start + 60 * i) * Math.PI) / 180;\n return { x: center.x + layout.size * Math.cos(angle), y: center.y + layout.size * Math.sin(angle) };\n });\n}\n\n/** A stable string key for a hex, e.g. `\"3:-1\"`. */\nexport function hexKey(coord: HexCoord): string {\n return `${String(coord.q)}:${String(coord.r)}`;\n}\n\n/** The number of hex steps between two hexes. */\nexport function hexDistance(a: HexCoord, b: HexCoord): number {\n const dq = a.q - b.q;\n const dr = a.r - b.r;\n return (Math.abs(dq) + Math.abs(dr) + Math.abs(dq + dr)) / 2;\n}\n\n/** The six hexes adjacent to a hex. */\nexport function hexNeighbors(coord: HexCoord): readonly HexCoord[] {\n return HEX_DIRECTIONS.map((d) => ({ q: coord.q + d.q, r: coord.r + d.r }));\n}\n\n/** Every hex within `radius` steps of a centre, centre included (`1 + 3n(n+1)`). */\nexport function hexRange(center: HexCoord, radius: number): readonly HexCoord[] {\n if (!Number.isInteger(radius) || radius < 0) {\n throw new AtlasConfigError(`hex radius must be a non-negative integer, got ${radius}`);\n }\n const out: HexCoord[] = [];\n for (let dq = -radius; dq <= radius; dq += 1) {\n const rMin = Math.max(-radius, -dq - radius);\n const rMax = Math.min(radius, -dq + radius);\n for (let r = rMin; r <= rMax; r += 1) out.push({ q: center.q + dq, r: center.r + r });\n }\n return out;\n}\n\n/**\n * The hexes a straight walk from `a` to `b` crosses, both ends included. The\n * interpolation is nudged a hair off exact hex edges so a line that grazes a\n * shared corner resolves to the same cells in both directions.\n */\nexport function hexLine(a: HexCoord, b: HexCoord): readonly HexCoord[] {\n const n = hexDistance(a, b);\n if (n === 0) return [{ q: a.q, r: a.r }];\n // Walk from one canonical endpoint so reversing the pair gives the same\n // cells in reverse order; float drift at a corner can otherwise round the\n // two directions onto different hexes.\n const forward = a.q < b.q || (a.q === b.q && a.r <= b.r);\n const from = forward ? a : b;\n const to = forward ? b : a;\n const dq = to.q - from.q;\n const dr = to.r - from.r;\n // 1e-7 hexes per step: far below any float drift, far above a real grazing.\n const eps = 1e-7;\n const q0 = from.q + eps * Math.sign(dq);\n const r0 = from.r + eps * Math.sign(dr);\n const q1 = to.q - eps * Math.sign(dq);\n const r1 = to.r - eps * Math.sign(dr);\n const out: HexCoord[] = [];\n for (let i = 0; i <= n; i += 1) {\n const t = i / n;\n out.push(cubeRound(q0 + (q1 - q0) * t, r0 + (r1 - r0) * t));\n }\n return forward ? out : out.reverse();\n}\n\n/**\n * The hexes overlapping a world rect, in axial column-major order. The rect's\n * corners map to axial space, and the bounds carry one hex of slack so no\n * partially visible hex is dropped.\n */\nexport function visibleHexes(view: Rect, layout: HexLayout): readonly HexCoord[] {\n assertLayout(layout);\n const corners: Point[] = [\n { x: view.x, y: view.y },\n { x: view.x + view.width, y: view.y },\n { x: view.x, y: view.y + view.height },\n { x: view.x + view.width, y: view.y + view.height },\n ];\n let minQ = Infinity;\n let maxQ = -Infinity;\n let minR = Infinity;\n let maxR = -Infinity;\n for (const corner of corners) {\n const hex = worldToHex(corner, layout);\n if (hex.q < minQ) minQ = hex.q;\n if (hex.q > maxQ) maxQ = hex.q;\n if (hex.r < minR) minR = hex.r;\n if (hex.r > maxR) maxR = hex.r;\n }\n const out: HexCoord[] = [];\n for (let q = minQ - 1; q <= maxQ + 1; q += 1) {\n for (let r = minR - 1; r <= maxR + 1; r += 1) out.push({ q, r });\n }\n return out;\n}\n\n/**\n * Hexes within `radius` of the origin that a straight line reaches without\n * crossing a blocker. A blocking hex is itself visible when the path to it is\n * clear: you can look at a wall you face.\n */\nexport function computeHexFov(\n origin: HexCoord,\n radius: number,\n options: Readonly<{ blocks?: (coord: HexCoord) => boolean }> = {},\n): Set<string> {\n if (!Number.isInteger(radius) || radius < 0) {\n throw new AtlasConfigError(`hex FOV radius must be a non-negative integer, got ${radius}`);\n }\n const blocks = options.blocks ?? (() => false);\n const lit = new Set<string>([hexKey(origin)]);\n for (const hex of hexRange(origin, radius)) {\n if (hexDistance(origin, hex) === 0) continue;\n const path = hexLine(origin, hex);\n let clear = true;\n for (let i = 1; i < path.length - 1; i += 1) {\n const step = path[i];\n if (step && blocks(step)) {\n clear = false;\n break;\n }\n }\n if (clear) lit.add(hexKey(hex));\n }\n return lit;\n}\n\n/** The {@link GridTopology} for hex grids: six neighbours, hex distance, hex lines. */\nexport const hexTopology: GridTopology<HexCoord> = {\n distance: hexDistance,\n key: hexKey,\n line: hexLine,\n neighbors: hexNeighbors,\n};\n"],"mappings":"A,iCAoBA,IAAME,EAAQ,KAAK,KAAK,CAAC,EAGZC,EAAsC,CACjD,CAAE,EAAG,EAAG,EAAG,CAAE,EACb,CAAE,EAAG,EAAG,EAAG,EAAG,EACd,CAAE,EAAG,EAAG,EAAG,EAAG,EACd,CAAE,EAAG,GAAI,EAAG,CAAE,EACd,CAAE,EAAG,GAAI,EAAG,CAAE,EACd,CAAE,EAAG,EAAG,EAAG,CAAE,CACf,EAEA,SAAS,aAAa,EAAyB,CAC7C,GAAI,EAAEC,EAAO,KAAO,GAClB,MAAM,IAAIJ,EAAAA,iBAAiB,yCAAyCI,EAAO,MAAM,EAEnF,GAAIA,EAAO,cAAgB,QAAUA,EAAO,cAAgB,SAC1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F,EAAKb,GAClB,GAAIe,GAAQN,EAAOM,CAAI,EAAG,CACxB,EAAQ,GACR,KACF,CACF,CACID,GAAOH,EAAI,IAAI,OAAOH,CAAG,CAAC,CAChC,CACA,OAAOG,CACT,CAGA,IAAaK,EAAsC,CACjD,SAAU,YACV,IAAK,OACL,KAAM,QACN,UAAW,YACb,E"}
@@ -0,0 +1,51 @@
1
+ import type { Point, Rect } from '../shapes.js';
2
+ import type { GridTopology } from './topology.js';
3
+ /** A hex addressed by axial coordinates (`s` is always `-q - r`). */
4
+ export type HexCoord = Readonly<{
5
+ q: number;
6
+ r: number;
7
+ }>;
8
+ /** How hexes map to world space: `size` is the centre-to-corner radius. */
9
+ export type HexLayout = Readonly<{
10
+ orientation: 'flat' | 'pointy';
11
+ size: number;
12
+ }>;
13
+ /** The six axial neighbour directions, in clockwise order from east. */
14
+ export declare const HEX_DIRECTIONS: readonly HexCoord[];
15
+ /** The world centre of a hex. */
16
+ export declare function hexToWorld(coord: HexCoord, layout: HexLayout): Point;
17
+ /** The hex whose centre is nearest to a world point. */
18
+ export declare function worldToHex(point: Point, layout: HexLayout): HexCoord;
19
+ /** The six corner points of a hex, in clockwise order from the first corner. */
20
+ export declare function hexCorners(coord: HexCoord, layout: HexLayout): readonly Point[];
21
+ /** A stable string key for a hex, e.g. `"3:-1"`. */
22
+ export declare function hexKey(coord: HexCoord): string;
23
+ /** The number of hex steps between two hexes. */
24
+ export declare function hexDistance(a: HexCoord, b: HexCoord): number;
25
+ /** The six hexes adjacent to a hex. */
26
+ export declare function hexNeighbors(coord: HexCoord): readonly HexCoord[];
27
+ /** Every hex within `radius` steps of a centre, centre included (`1 + 3n(n+1)`). */
28
+ export declare function hexRange(center: HexCoord, radius: number): readonly HexCoord[];
29
+ /**
30
+ * The hexes a straight walk from `a` to `b` crosses, both ends included. The
31
+ * interpolation is nudged a hair off exact hex edges so a line that grazes a
32
+ * shared corner resolves to the same cells in both directions.
33
+ */
34
+ export declare function hexLine(a: HexCoord, b: HexCoord): readonly HexCoord[];
35
+ /**
36
+ * The hexes overlapping a world rect, in axial column-major order. The rect's
37
+ * corners map to axial space, and the bounds carry one hex of slack so no
38
+ * partially visible hex is dropped.
39
+ */
40
+ export declare function visibleHexes(view: Rect, layout: HexLayout): readonly HexCoord[];
41
+ /**
42
+ * Hexes within `radius` of the origin that a straight line reaches without
43
+ * crossing a blocker. A blocking hex is itself visible when the path to it is
44
+ * clear: you can look at a wall you face.
45
+ */
46
+ export declare function computeHexFov(origin: HexCoord, radius: number, options?: Readonly<{
47
+ blocks?: (coord: HexCoord) => boolean;
48
+ }>): Set<string>;
49
+ /** The {@link GridTopology} for hex grids: six neighbours, hex distance, hex lines. */
50
+ export declare const hexTopology: GridTopology<HexCoord>;
51
+ //# sourceMappingURL=hex.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hex.d.ts","sourceRoot":"","sources":["../../src/grid/hex.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,qEAAqE;AACrE,MAAM,MAAM,QAAQ,GAAG,QAAQ,CAAC;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAE1D,2EAA2E;AAC3E,MAAM,MAAM,SAAS,GAAG,QAAQ,CAAC;IAC/B,WAAW,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC/B,IAAI,EAAE,MAAM,CAAC;CACd,CAAC,CAAC;AAIH,wEAAwE;AACxE,eAAO,MAAM,cAAc,EAAE,SAAS,QAAQ,EAO7C,CAAC;AAiBF,iCAAiC;AACjC,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,GAAG,KAAK,CAOpE;AAED,wDAAwD;AACxD,wBAAgB,UAAU,CAAC,KAAK,EAAE,KAAK,EAAE,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 q: 1,
10
+ r: -1
11
+ },
12
+ {
13
+ q: 0,
14
+ r: -1
15
+ },
16
+ {
17
+ q: -1,
18
+ r: 0
19
+ },
20
+ {
21
+ q: -1,
22
+ r: 1
23
+ },
24
+ {
25
+ q: 0,
26
+ r: 1
27
+ }
28
+ ];
29
+ function assertLayout(t) {
30
+ if (!(t.size > 0)) throw new e(`hex layout.size must be positive, got ${t.size}`);
31
+ if (t.orientation !== "flat" && t.orientation !== "pointy") throw new e(`hex layout.orientation must be "flat" or "pointy", got ${String(t.orientation)}`);
32
+ }
33
+ function assertHex(t) {
34
+ if (!Number.isInteger(t.q) || !Number.isInteger(t.r)) throw new e(`hex coordinates must be integers, got (${t.q}, ${t.r})`);
35
+ }
36
+ function hexToWorld(e, n) {
37
+ return assertLayout(n), assertHex(e), n.orientation === "pointy" ? {
38
+ x: n.size * t * (e.q + e.r / 2),
39
+ y: n.size * 1.5 * e.r
40
+ } : {
41
+ x: n.size * 1.5 * e.q,
42
+ y: n.size * t * (e.r + e.q / 2)
43
+ };
44
+ }
45
+ function worldToHex(e, n) {
46
+ return assertLayout(n), cubeRound(n.orientation === "pointy" ? t / 3 * e.x / n.size - e.y / (3 * n.size) : 2 / 3 * e.x / n.size, n.orientation === "pointy" ? 2 / 3 * e.y / n.size : -e.x / (3 * n.size) + t / 3 * e.y / n.size);
47
+ }
48
+ function cubeRound(e, t) {
49
+ let n = -e - t, r = Math.round(e), i = Math.round(t), a = Math.round(n), o = Math.abs(r - e), s = Math.abs(i - t), c = Math.abs(a - n);
50
+ return o > s && o > c ? r = -i - a : s > c && (i = -r - a), {
51
+ q: r,
52
+ r: i
53
+ };
54
+ }
55
+ function hexCorners(e, t) {
56
+ assertLayout(t);
57
+ let n = hexToWorld(e, t), r = t.orientation === "pointy" ? 30 : 0;
58
+ return Array.from({ length: 6 }, (e, i) => {
59
+ let a = (r + 60 * i) * Math.PI / 180;
60
+ return {
61
+ x: n.x + t.size * Math.cos(a),
62
+ y: n.y + t.size * Math.sin(a)
63
+ };
64
+ });
65
+ }
66
+ function hexKey(e) {
67
+ return `${String(e.q)}:${String(e.r)}`;
68
+ }
69
+ function hexDistance(e, t) {
70
+ let n = e.q - t.q, r = e.r - t.r;
71
+ return (Math.abs(n) + Math.abs(r) + Math.abs(n + r)) / 2;
72
+ }
73
+ function hexNeighbors(e) {
74
+ return n.map((t) => ({
75
+ q: e.q + t.q,
76
+ r: e.r + t.r
77
+ }));
78
+ }
79
+ function hexRange(t, n) {
80
+ if (!Number.isInteger(n) || n < 0) throw new e(`hex radius must be a non-negative integer, got ${n}`);
81
+ let r = [];
82
+ for (let e = -n; e <= n; e += 1) {
83
+ let i = Math.max(-n, -e - n), a = Math.min(n, -e + n);
84
+ for (let n = i; n <= a; n += 1) r.push({
85
+ q: t.q + e,
86
+ r: t.r + n
87
+ });
88
+ }
89
+ return r;
90
+ }
91
+ function hexLine(e, t) {
92
+ let n = hexDistance(e, t);
93
+ if (n === 0) return [{
94
+ q: e.q,
95
+ r: e.r
96
+ }];
97
+ let r = e.q < t.q || e.q === t.q && e.r <= t.r, i = r ? e : t, a = r ? t : e, o = a.q - i.q, s = a.r - i.r, c = 1e-7, l = i.q + c * Math.sign(o), u = i.r + c * Math.sign(s), d = a.q - c * Math.sign(o), f = a.r - c * Math.sign(s), p = [];
98
+ for (let e = 0; e <= n; e += 1) {
99
+ let t = e / n;
100
+ p.push(cubeRound(l + (d - l) * t, u + (f - u) * t));
101
+ }
102
+ return r ? p : p.reverse();
103
+ }
104
+ function visibleHexes(e, t) {
105
+ assertLayout(t);
106
+ let n = [
107
+ {
108
+ x: e.x,
109
+ y: e.y
110
+ },
111
+ {
112
+ x: e.x + e.width,
113
+ y: e.y
114
+ },
115
+ {
116
+ x: e.x,
117
+ y: e.y + e.height
118
+ },
119
+ {
120
+ x: e.x + e.width,
121
+ y: e.y + e.height
122
+ }
123
+ ], r = Infinity, i = -Infinity, a = Infinity, o = -Infinity;
124
+ for (let e of n) {
125
+ let n = worldToHex(e, t);
126
+ n.q < r && (r = n.q), n.q > i && (i = n.q), n.r < a && (a = n.r), n.r > o && (o = n.r);
127
+ }
128
+ let s = [];
129
+ for (let e = r - 1; e <= i + 1; e += 1) for (let t = a - 1; t <= o + 1; t += 1) s.push({
130
+ q: e,
131
+ r: t
132
+ });
133
+ return s;
134
+ }
135
+ function computeHexFov(t, n, r = {}) {
136
+ if (!Number.isInteger(n) || n < 0) throw new e(`hex FOV radius must be a non-negative integer, got ${n}`);
137
+ let i = r.blocks ?? (() => !1), a = /* @__PURE__ */ new Set([hexKey(t)]);
138
+ for (let e of hexRange(t, n)) {
139
+ if (hexDistance(t, e) === 0) continue;
140
+ let n = hexLine(t, e), r = !0;
141
+ for (let e = 1; e < n.length - 1; e += 1) {
142
+ let t = n[e];
143
+ if (t && i(t)) {
144
+ r = !1;
145
+ break;
146
+ }
147
+ }
148
+ r && a.add(hexKey(e));
149
+ }
150
+ return a;
151
+ }
152
+ var r = {
153
+ distance: hexDistance,
154
+ key: hexKey,
155
+ line: hexLine,
156
+ neighbors: hexNeighbors
157
+ };
158
+ export { n as HEX_DIRECTIONS, computeHexFov, hexCorners, hexDistance, hexKey, hexLine, hexNeighbors, hexRange, hexToWorld, r as hexTopology, visibleHexes, worldToHex };
159
+
160
+ //# sourceMappingURL=hex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hex.js","names":["SQRT3","HEX_DIRECTIONS","layout","AtlasConfigError","coord","point","s","q","r","rq","rr","rs","dq","dr","ds","center","start","angle","a","b","d","radius","out","rMin","rMax","forward","from","to","eps","q0","r0","q1","r1","i","corners","view","minQ","maxQ","minR","maxR","corner","hex","blocks","options","lit","origin","path","clear","step","hexTopology"],"sources":["../../src/grid/hex.ts"],"sourcesContent":["/**\n * Hex-grid math on axial coordinates. A hex is `{ q, r }`; the third cube axis\n * is derived (`s = -q - r`), so distance and rounding stay exact without\n * storing it. Layouts are pointy- or flat-topped with a world-unit radius\n * (`size` = centre to corner), and the conversion pair is an exact inverse:\n * `worldToHex(hexToWorld(h, l), l)` returns `h` for every hex.\n */\nimport { AtlasConfigError } from '../errors.js';\nimport type { Point, Rect } from '../shapes.js';\nimport type { GridTopology } from './topology.js';\n\n/** A hex addressed by axial coordinates (`s` is always `-q - r`). */\nexport type HexCoord = Readonly<{ q: number; r: number }>;\n\n/** How hexes map to world space: `size` is the centre-to-corner radius. */\nexport type HexLayout = Readonly<{\n orientation: 'flat' | 'pointy';\n size: number;\n}>;\n\nconst SQRT3 = Math.sqrt(3);\n\n/** The six axial neighbour directions, in clockwise order from east. */\nexport const HEX_DIRECTIONS: readonly HexCoord[] = [\n { q: 1, r: 0 },\n { q: 1, r: -1 },\n { q: 0, r: -1 },\n { q: -1, r: 0 },\n { q: -1, r: 1 },\n { q: 0, r: 1 },\n];\n\nfunction assertLayout(layout: HexLayout): void {\n if (!(layout.size > 0)) {\n throw new AtlasConfigError(`hex layout.size must be positive, got ${layout.size}`);\n }\n if (layout.orientation !== 'flat' && layout.orientation !== 'pointy') {\n throw new AtlasConfigError(`hex layout.orientation must be \"flat\" or \"pointy\", got ${String(layout.orientation)}`);\n }\n}\n\nfunction assertHex(coord: HexCoord): void {\n if (!Number.isInteger(coord.q) || !Number.isInteger(coord.r)) {\n throw new AtlasConfigError(`hex coordinates must be integers, got (${coord.q}, ${coord.r})`);\n }\n}\n\n/** The world centre of a hex. */\nexport function hexToWorld(coord: HexCoord, layout: HexLayout): Point {\n assertLayout(layout);\n assertHex(coord);\n if (layout.orientation === 'pointy') {\n return { x: layout.size * SQRT3 * (coord.q + coord.r / 2), y: layout.size * 1.5 * coord.r };\n }\n return { x: layout.size * 1.5 * coord.q, y: layout.size * SQRT3 * (coord.r + coord.q / 2) };\n}\n\n/** The hex whose centre is nearest to a world point. */\nexport function worldToHex(point: Point, layout: HexLayout): HexCoord {\n assertLayout(layout);\n const fq =\n layout.orientation === 'pointy'\n ? ((SQRT3 / 3) * point.x) / layout.size - point.y / (3 * layout.size)\n : ((2 / 3) * point.x) / layout.size;\n const fr =\n layout.orientation === 'pointy'\n ? ((2 / 3) * point.y) / layout.size\n : -point.x / (3 * layout.size) + ((SQRT3 / 3) * point.y) / layout.size;\n return cubeRound(fq, fr);\n}\n\n/** Rounds fractional axial coordinates to the nearest hex (cube rounding). */\nfunction cubeRound(q: number, r: number): HexCoord {\n const s = -q - r;\n let rq = Math.round(q);\n let rr = Math.round(r);\n const rs = Math.round(s);\n // The axis with the smallest rounding error is derived from the other two.\n const dq = Math.abs(rq - q);\n const dr = Math.abs(rr - r);\n const ds = Math.abs(rs - s);\n if (dq > dr && dq > ds) rq = -rr - rs;\n else if (dr > ds) rr = -rq - rs;\n return { q: rq, r: rr };\n}\n\n/** The six corner points of a hex, in clockwise order from the first corner. */\nexport function hexCorners(coord: HexCoord, layout: HexLayout): readonly Point[] {\n assertLayout(layout);\n const center = hexToWorld(coord, layout);\n const start = layout.orientation === 'pointy' ? 30 : 0;\n return Array.from({ length: 6 }, (_, i) => {\n const angle = ((start + 60 * i) * Math.PI) / 180;\n return { x: center.x + layout.size * Math.cos(angle), y: center.y + layout.size * Math.sin(angle) };\n });\n}\n\n/** A stable string key for a hex, e.g. `\"3:-1\"`. */\nexport function hexKey(coord: HexCoord): string {\n return `${String(coord.q)}:${String(coord.r)}`;\n}\n\n/** The number of hex steps between two hexes. */\nexport function hexDistance(a: HexCoord, b: HexCoord): number {\n const dq = a.q - b.q;\n const dr = a.r - b.r;\n return (Math.abs(dq) + Math.abs(dr) + Math.abs(dq + dr)) / 2;\n}\n\n/** The six hexes adjacent to a hex. */\nexport function hexNeighbors(coord: HexCoord): readonly HexCoord[] {\n return HEX_DIRECTIONS.map((d) => ({ q: coord.q + d.q, r: coord.r + d.r }));\n}\n\n/** Every hex within `radius` steps of a centre, centre included (`1 + 3n(n+1)`). */\nexport function hexRange(center: HexCoord, radius: number): readonly HexCoord[] {\n if (!Number.isInteger(radius) || radius < 0) {\n throw new AtlasConfigError(`hex radius must be a non-negative integer, got ${radius}`);\n }\n const out: HexCoord[] = [];\n for (let dq = -radius; dq <= radius; dq += 1) {\n const rMin = Math.max(-radius, -dq - radius);\n const rMax = Math.min(radius, -dq + radius);\n for (let r = rMin; r <= rMax; r += 1) out.push({ q: center.q + dq, r: center.r + r });\n }\n return out;\n}\n\n/**\n * The hexes a straight walk from `a` to `b` crosses, both ends included. The\n * interpolation is nudged a hair off exact hex edges so a line that grazes a\n * shared corner resolves to the same cells in both directions.\n */\nexport function hexLine(a: HexCoord, b: HexCoord): readonly HexCoord[] {\n const n = hexDistance(a, b);\n if (n === 0) return [{ q: a.q, r: a.r }];\n // Walk from one canonical endpoint so reversing the pair gives the same\n // cells in reverse order; float drift at a corner can otherwise round the\n // two directions onto different hexes.\n const forward = a.q < b.q || (a.q === b.q && a.r <= b.r);\n const from = forward ? a : b;\n const to = forward ? b : a;\n const dq = to.q - from.q;\n const dr = to.r - from.r;\n // 1e-7 hexes per step: far below any float drift, far above a real grazing.\n const eps = 1e-7;\n const q0 = from.q + eps * Math.sign(dq);\n const r0 = from.r + eps * Math.sign(dr);\n const q1 = to.q - eps * Math.sign(dq);\n const r1 = to.r - eps * Math.sign(dr);\n const out: HexCoord[] = [];\n for (let i = 0; i <= n; i += 1) {\n const t = i / n;\n out.push(cubeRound(q0 + (q1 - q0) * t, r0 + (r1 - r0) * t));\n }\n return forward ? out : out.reverse();\n}\n\n/**\n * The hexes overlapping a world rect, in axial column-major order. The rect's\n * corners map to axial space, and the bounds carry one hex of slack so no\n * partially visible hex is dropped.\n */\nexport function visibleHexes(view: Rect, layout: HexLayout): readonly HexCoord[] {\n assertLayout(layout);\n const corners: Point[] = [\n { x: view.x, y: view.y },\n { x: view.x + view.width, y: view.y },\n { x: view.x, y: view.y + view.height },\n { x: view.x + view.width, y: view.y + view.height },\n ];\n let minQ = Infinity;\n let maxQ = -Infinity;\n let minR = Infinity;\n let maxR = -Infinity;\n for (const corner of corners) {\n const hex = worldToHex(corner, layout);\n if (hex.q < minQ) minQ = hex.q;\n if (hex.q > maxQ) maxQ = hex.q;\n if (hex.r < minR) minR = hex.r;\n if (hex.r > maxR) maxR = hex.r;\n }\n const out: HexCoord[] = [];\n for (let q = minQ - 1; q <= maxQ + 1; q += 1) {\n for (let r = minR - 1; r <= maxR + 1; r += 1) out.push({ q, r });\n }\n return out;\n}\n\n/**\n * Hexes within `radius` of the origin that a straight line reaches without\n * crossing a blocker. A blocking hex is itself visible when the path to it is\n * clear: you can look at a wall you face.\n */\nexport function computeHexFov(\n origin: HexCoord,\n radius: number,\n options: Readonly<{ blocks?: (coord: HexCoord) => boolean }> = {},\n): Set<string> {\n if (!Number.isInteger(radius) || radius < 0) {\n throw new AtlasConfigError(`hex FOV radius must be a non-negative integer, got ${radius}`);\n }\n const blocks = options.blocks ?? (() => false);\n const lit = new Set<string>([hexKey(origin)]);\n for (const hex of hexRange(origin, radius)) {\n if (hexDistance(origin, hex) === 0) continue;\n const path = hexLine(origin, hex);\n let clear = true;\n for (let i = 1; i < path.length - 1; i += 1) {\n const step = path[i];\n if (step && blocks(step)) {\n clear = false;\n break;\n }\n }\n if (clear) lit.add(hexKey(hex));\n }\n return lit;\n}\n\n/** The {@link GridTopology} for hex grids: six neighbours, hex distance, hex lines. */\nexport const hexTopology: GridTopology<HexCoord> = {\n distance: hexDistance,\n key: hexKey,\n line: hexLine,\n neighbors: hexNeighbors,\n};\n"],"mappings":";;AAoBA,IAAMA,IAAQ,KAAK,KAAK,CAAC,GAGZC,IAAsC;CACjD;EAAE,GAAG;EAAG,GAAG;CAAE;CACb;EAAE,GAAG;EAAG,GAAG;CAAG;CACd;EAAE,GAAG;EAAG,GAAG;CAAG;CACd;EAAE,GAAG;EAAI,GAAG;CAAE;CACd;EAAE,GAAG;EAAI,GAAG;CAAE;CACd;EAAE,GAAG;EAAG,GAAG;CAAE;AACf;AAEA,SAAS,aAAa,GAAyB;CAC7C,IAAI,EAAEC,EAAO,OAAO,IAClB,MAAM,IAAIC,EAAiB,yCAAyCD,EAAO,MAAM;CAEnF,IAAI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GAC3C,IAAME,IAAOF,EAAKb;GAClB,IAAIe,KAAQN,EAAOM,CAAI,GAAG;IACxB,IAAQ;IACR;GACF;EACF;EACA,AAAID,KAAOH,EAAI,IAAI,OAAOH,CAAG,CAAC;CAChC;CACA,OAAOG;AACT;AAGA,IAAaK,IAAsC;CACjD,UAAU;CACV,KAAK;CACL,MAAM;CACN,WAAW;AACb"}
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../errors.cjs"),t=require("./fov.cjs"),n=require("./tile.cjs");exports.AtlasConfigError=e.AtlasConfigError,exports.AtlasError=e.AtlasError,exports.computeFov=t.computeFov,exports.createFog=t.createFog,exports.iterateTileRange=n.iterateTileRange,exports.tileCenter=n.tileCenter,exports.tileKey=n.tileKey,exports.tileToRect=n.tileToRect,exports.visibleTileRange=n.visibleTileRange,exports.worldToTile=n.worldToTile;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../errors.cjs"),t=require("./fov.cjs"),n=require("./hex.cjs"),r=require("./path.cjs"),i=require("./tile.cjs"),a=require("./topology.cjs");exports.AtlasConfigError=e.AtlasConfigError,exports.AtlasError=e.AtlasError,exports.HEX_DIRECTIONS=n.HEX_DIRECTIONS,exports.computeFov=t.computeFov,exports.computeHexFov=n.computeHexFov,exports.createFog=t.createFog,exports.findPath=r.findPath,exports.hexCorners=n.hexCorners,exports.hexDistance=n.hexDistance,exports.hexKey=n.hexKey,exports.hexLine=n.hexLine,exports.hexNeighbors=n.hexNeighbors,exports.hexRange=n.hexRange,exports.hexToWorld=n.hexToWorld,exports.hexTopology=n.hexTopology,exports.iterateTileRange=i.iterateTileRange,exports.reachable=r.reachable,exports.squareTopology=a.squareTopology,exports.tileCenter=i.tileCenter,exports.tileKey=i.tileKey,exports.tileToRect=i.tileToRect,exports.visibleHexes=n.visibleHexes,exports.visibleTileRange=i.visibleTileRange,exports.worldToHex=n.worldToHex,exports.worldToTile=i.worldToTile;
@@ -1,9 +1,13 @@
1
1
  /**
2
- * Public surface of the `@vielzeug/atlas/grid` subpath: square-tile grids,
3
- * field-of-view, and fog-of-war. Kept independent of the atlas root surface
4
- * (only structural shape types and the error classes are shared).
2
+ * Public surface of the `@vielzeug/atlas/grid` subpath: square-tile and hex
3
+ * grids, grid topologies, pathfinding, field-of-view, and fog-of-war. Kept
4
+ * independent of the atlas root surface (only structural shape types and the
5
+ * error classes are shared).
5
6
  */
6
7
  export { AtlasConfigError, AtlasError } from '../errors.js';
7
8
  export { type BlockPredicate, computeFov, createFog, type Fog, type FogSnapshot, type FogState, type FovOptions, } from './fov.js';
9
+ export { computeHexFov, HEX_DIRECTIONS, type HexCoord, type HexLayout, hexCorners, hexDistance, hexKey, hexLine, hexNeighbors, hexRange, hexTopology, hexToWorld, visibleHexes, worldToHex, } from './hex.js';
10
+ export { findPath, type ReachEntry, reachable, type SearchOptions, } from './path.js';
8
11
  export { type GridConfig, iterateTileRange, type TileCoord, type TileRange, tileCenter, tileKey, tileToRect, visibleTileRange, worldToTile, } from './tile.js';
12
+ export { type GridTopology, squareTopology, } from './topology.js';
9
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/grid/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,KAAK,cAAc,EACnB,UAAU,EACV,SAAS,EACT,KAAK,GAAG,EACR,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,UAAU,GAChB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,KAAK,UAAU,EACf,gBAAgB,EAChB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,UAAU,EACV,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/grid/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EACL,KAAK,cAAc,EACnB,UAAU,EACV,SAAS,EACT,KAAK,GAAG,EACR,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,UAAU,GAChB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,aAAa,EACb,cAAc,EACd,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,UAAU,EACV,WAAW,EACX,MAAM,EACN,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,WAAW,EACX,UAAU,EACV,YAAY,EACZ,UAAU,GACX,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,QAAQ,EACR,KAAK,UAAU,EACf,SAAS,EACT,KAAK,aAAa,GACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,UAAU,EACf,gBAAgB,EAChB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,UAAU,EACV,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,KAAK,YAAY,EACjB,cAAc,GACf,MAAM,eAAe,CAAC"}
@@ -1,4 +1,7 @@
1
1
  import { AtlasConfigError as e, AtlasError as t } from "../errors.js";
2
2
  import { computeFov as n, createFog as r } from "./fov.js";
3
- import { iterateTileRange as i, tileCenter as a, tileKey as o, tileToRect as s, visibleTileRange as c, worldToTile as l } from "./tile.js";
4
- export { e as AtlasConfigError, t as AtlasError, n as computeFov, r as createFog, i as iterateTileRange, a as tileCenter, o as tileKey, s as tileToRect, c as visibleTileRange, l as worldToTile };
3
+ import { HEX_DIRECTIONS as i, computeHexFov as a, hexCorners as o, hexDistance as s, hexKey as c, hexLine as l, hexNeighbors as u, hexRange as d, hexToWorld as f, hexTopology as p, visibleHexes as m, worldToHex as h } from "./hex.js";
4
+ import { findPath as g, reachable as _ } from "./path.js";
5
+ import { iterateTileRange as v, tileCenter as y, tileKey as b, tileToRect as x, visibleTileRange as S, worldToTile as C } from "./tile.js";
6
+ import { squareTopology as w } from "./topology.js";
7
+ export { e as AtlasConfigError, t as AtlasError, i as HEX_DIRECTIONS, n as computeFov, a as computeHexFov, r as createFog, g as findPath, o as hexCorners, s as hexDistance, c as hexKey, l as hexLine, u as hexNeighbors, d as hexRange, f as hexToWorld, p as hexTopology, v as iterateTileRange, _ as reachable, w as squareTopology, y as tileCenter, b as tileKey, x as tileToRect, m as visibleHexes, S as visibleTileRange, h as worldToHex, C as worldToTile };
@@ -0,0 +1,2 @@
1
+ const e=require("../errors.cjs");function createHeap(){let e=[],key=e=>e.f,swap=(t,n)=>{let r=e[t],i=e[n];r!==void 0&&i!==void 0&&(e[t]=i,e[n]=r)};return{pop(){let t=e[0],n=e.pop();if(t!==void 0&&n!==void 0){if(e.length>0){e[0]=n;let t=0;for(;;){let n=2*t+1,r=2*t+2,i=t;for(let t of[n,r]){let n=e[t],r=e[i];n!==void 0&&r!==void 0&&key(n)<key(r)&&(i=t)}if(i===t)break;swap(t,i),t=i}}return t}},push(t){e.push(t);let n=e.length-1;for(;n>0;){let t=n-1>>1,r=e[n],i=e[t];if(r===void 0||i===void 0||key(r)>=key(i))break;swap(n,t),n=t}},get size(){return e.length}}}function assertCost(t,n){if(!(t>0)||!Number.isFinite(t))throw new e.AtlasConfigError(`cell cost must be a positive finite number, got ${t} at ${String(n)}`);return t}function findPath(t,n,r){let{topology:i,passable:a}=r;if(r.maxCost!==void 0&&!(r.maxCost>=0))throw new e.AtlasConfigError(`maxCost must be non-negative, got ${String(r.maxCost)}`);let o=r.cost??(()=>1);if(!a(t)||!a(n))return null;let s=i.key(t),c=i.key(n);if(s===c)return[t];let l=r.maxCost??1/0,u=new Map([[s,0]]),d=new Map,f=createHeap();for(f.push({cell:t,cost:0,f:i.distance(t,n)});f.size>0;){let e=f.pop();if(e===void 0)break;let t=i.key(e.cell),r=u.get(t);if(!(r===void 0||r<e.cost)){if(t===c){let t=[e.cell],n=e.cell;for(;;){let e=d.get(i.key(n));if(e===void 0||(t.push(e),n=e,i.key(n)===s))break}return t.reverse()}for(let t of i.neighbors(e.cell)){if(!a(t))continue;let r=assertCost(o(t),t),s=e.cost+r;if(s>l)continue;let c=i.key(t),p=u.get(c);p!==void 0&&p<=s||(u.set(c,s),d.set(c,e.cell),f.push({cell:t,cost:s,f:s+i.distance(t,n)}))}}}return null}function reachable(t,n,r){if(!(n>=0)||!Number.isFinite(n))throw new e.AtlasConfigError(`movement budget must be a finite non-negative number, got ${n}`);let{topology:i,passable:a}=r,o=r.cost??(()=>1),s=new Map([[i.key(t),{cost:0,prev:null}]]);if(!a(t))return s;let c=createHeap();for(c.push({cell:t,cost:0,f:0});c.size>0;){let e=c.pop();if(e===void 0)break;let t=s.get(i.key(e.cell));if(!(t===void 0||t.cost<e.cost))for(let t of i.neighbors(e.cell)){if(!a(t))continue;let r=assertCost(o(t),t),l=e.cost+r;if(l>n)continue;let u=i.key(t),d=s.get(u);d!==void 0&&d.cost<=l||(s.set(u,{cost:l,prev:e.cell}),c.push({cell:t,cost:l,f:l}))}}return s}exports.findPath=findPath,exports.reachable=reachable;
2
+ //# sourceMappingURL=path.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.cjs","names":["AtlasConfigError","require_errors","items","item","tmp","i","at","j","top","last","left","right","smallest","child","a","b","parent","head","cost","coord","options","costOf","passable","start","goal","startKey","topology","goalKey","budget","best","cameFrom","open","current","currentKey","known","path","cell","prev","next","step","g","nextKey","previous","out","entry"],"sources":["../../src/grid/path.ts"],"sourcesContent":["/**\n * Grid search generic over a {@link GridTopology}: A* between two cells and a\n * Dijkstra flood for everything reachable within a movement budget. Costs are\n * per-entry (the start cell is never charged), so a caller can model difficult\n * terrain without the search knowing what terrain is.\n */\nimport { AtlasConfigError } from '../errors.js';\nimport type { GridTopology } from './topology.js';\n\n/** Shared options: which cells may be entered and what entering them costs. */\nexport interface SearchOptions<C> {\n /** Cost of entering a cell (default 1). Must be positive and finite. */\n cost?: (coord: C) => number;\n /**\n * Returns true when a cell may be entered. The start cell is queried too.\n * The search space must be finite: `passable` has to reject the cells beyond\n * the world's edge, or a search for an unreachable goal expands forever.\n */\n passable: (coord: C) => boolean;\n /** The grid's adjacency, distance, and keying. */\n topology: GridTopology<C>;\n}\n\n/** One reached cell in a {@link reachable} flood: its cost and predecessor. */\nexport interface ReachEntry<C> {\n cost: number;\n prev: C | null;\n}\n\ninterface QueueItem<C> {\n cell: C;\n cost: number;\n f: number;\n}\n\n/** Binary min-heap on `f`. */\nfunction createHeap<C>(): {\n pop(): QueueItem<C> | undefined;\n push(item: QueueItem<C>): void;\n readonly size: number;\n} {\n const items: QueueItem<C>[] = [];\n const key = (item: QueueItem<C>): number => item.f;\n const swap = (i: number, j: number): void => {\n const tmp = items[i];\n const at = items[j];\n if (tmp === undefined || at === undefined) return;\n items[i] = at;\n items[j] = tmp;\n };\n return {\n pop() {\n const top = items[0];\n const last = items.pop();\n if (top === undefined || last === undefined) return undefined;\n if (items.length > 0) {\n items[0] = last;\n let i = 0;\n for (;;) {\n const left = 2 * i + 1;\n const right = 2 * i + 2;\n let smallest = i;\n for (const child of [left, right]) {\n const a = items[child];\n const b = items[smallest];\n if (a !== undefined && b !== undefined && key(a) < key(b)) smallest = child;\n }\n if (smallest === i) break;\n swap(i, smallest);\n i = smallest;\n }\n }\n return top;\n },\n push(item) {\n items.push(item);\n let i = items.length - 1;\n while (i > 0) {\n const parent = (i - 1) >> 1;\n const child = items[i];\n const head = items[parent];\n if (child === undefined || head === undefined || key(child) >= key(head)) break;\n swap(i, parent);\n i = parent;\n }\n },\n get size() {\n return items.length;\n },\n };\n}\n\nfunction assertCost(cost: number, coord: unknown): number {\n if (!(cost > 0) || !Number.isFinite(cost)) {\n throw new AtlasConfigError(`cell cost must be a positive finite number, got ${cost} at ${String(coord)}`);\n }\n return cost;\n}\n\n/**\n * Cheapest route from `start` to `goal`, or null when none exists within\n * `maxCost`. Both endpoints must be passable; the start's cost is never\n * charged. The topology distance is the heuristic, so results are optimal\n * whenever every step costs at least 1.\n */\nexport function findPath<C>(start: C, goal: C, options: SearchOptions<C> & Readonly<{ maxCost?: number }>): C[] | null {\n const { topology, passable } = options;\n if (options.maxCost !== undefined && !(options.maxCost >= 0)) {\n throw new AtlasConfigError(`maxCost must be non-negative, got ${String(options.maxCost)}`);\n }\n const costOf = options.cost ?? (() => 1);\n if (!passable(start) || !passable(goal)) return null;\n const startKey = topology.key(start);\n const goalKey = topology.key(goal);\n if (startKey === goalKey) return [start];\n const budget = options.maxCost ?? Number.POSITIVE_INFINITY;\n\n const best = new Map<string, number>([[startKey, 0]]);\n const cameFrom = new Map<string, C>();\n const open = createHeap<C>();\n open.push({ cell: start, cost: 0, f: topology.distance(start, goal) });\n\n while (open.size > 0) {\n const current = open.pop();\n if (current === undefined) break;\n const currentKey = topology.key(current.cell);\n const known = best.get(currentKey);\n // A stale queue entry (a cheaper path arrived after it was queued) is skipped.\n if (known === undefined || known < current.cost) continue;\n if (currentKey === goalKey) {\n const path: C[] = [current.cell];\n let cell = current.cell;\n for (;;) {\n const prev = cameFrom.get(topology.key(cell));\n if (prev === undefined) break;\n path.push(prev);\n cell = prev;\n if (topology.key(cell) === startKey) break;\n }\n return path.reverse();\n }\n for (const next of topology.neighbors(current.cell)) {\n if (!passable(next)) continue;\n const step = assertCost(costOf(next), next);\n const g = current.cost + step;\n if (g > budget) continue;\n const nextKey = topology.key(next);\n const previous = best.get(nextKey);\n if (previous !== undefined && previous <= g) continue;\n best.set(nextKey, g);\n cameFrom.set(nextKey, current.cell);\n open.push({ cell: next, cost: g, f: g + topology.distance(next, goal) });\n }\n }\n return null;\n}\n\n/**\n * Every cell reachable from `start` within `budget`, keyed by cell, each with\n * its cheapest cost and predecessor. Rebuild a route by walking `prev` back\n * from any entry. The start is included with cost 0 and `prev: null`; an\n * impassable start reaches nothing but itself.\n */\nexport function reachable<C>(start: C, budget: number, options: SearchOptions<C>): Map<string, ReachEntry<C>> {\n if (!(budget >= 0) || !Number.isFinite(budget)) {\n throw new AtlasConfigError(`movement budget must be a finite non-negative number, got ${budget}`);\n }\n const { topology, passable } = options;\n const costOf = options.cost ?? (() => 1);\n const out = new Map<string, ReachEntry<C>>([[topology.key(start), { cost: 0, prev: null }]]);\n if (!passable(start)) return out;\n const open = createHeap<C>();\n open.push({ cell: start, cost: 0, f: 0 });\n while (open.size > 0) {\n const current = open.pop();\n if (current === undefined) break;\n const entry = out.get(topology.key(current.cell));\n if (entry === undefined || entry.cost < current.cost) continue;\n for (const next of topology.neighbors(current.cell)) {\n if (!passable(next)) continue;\n const step = assertCost(costOf(next), next);\n const cost = current.cost + step;\n if (cost > budget) continue;\n const nextKey = topology.key(next);\n const known = out.get(nextKey);\n if (known !== undefined && known.cost <= cost) continue;\n out.set(nextKey, { cost, prev: current.cell });\n open.push({ cell: next, cost, f: cost });\n }\n }\n return out;\n}\n"],"mappings":"A,iCAoCA,SAAS,YAIP,CACA,IAAME,EAAwB,CAAC,EACzB,IAAO,GAA+BC,EAAK,EAC3C,MAAQ,EAAW,IAAoB,CAC3C,IAAMC,EAAMF,EAAMG,GACZC,EAAKJ,EAAMK,GACbH,IAAQ,IAAA,IAAaE,IAAO,IAAA,KAChC,EAAMD,GAAKC,EACX,EAAMC,GAAKH,EACb,EACA,MAAO,CACL,KAAM,CACJ,IAAMI,EAAMN,EAAM,GACZO,EAAOP,EAAM,IAAI,EACvB,GAAIM,IAAQ,IAAA,IAAaC,IAAS,IAAA,GAClC,IAAIP,EAAM,OAAS,EAAG,CACpB,EAAM,GAAKO,EACX,IAAIJ,EAAI,EACR,OAAS,CACP,IAAMK,EAAO,EAAIL,EAAI,EACfM,EAAQ,EAAIN,EAAI,EAClBO,EAAWP,EACf,IAAK,IAAMQ,IAAS,CAACH,EAAMC,CAAK,EAAG,CACjC,IAAMG,EAAIZ,EAAMW,GACVE,EAAIb,EAAMU,GACZE,IAAM,IAAA,IAAaC,IAAM,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,GAAI,EAAEI,GAAU,IAAM,CAAC,OAAO,SAASA,CAAM,EAC3C,MAAM,IAAI5B,EAAAA,iBAAiB,6DAA6D4B,GAAQ,EAElG,GAAM,CAAE,WAAU,YAAaR,EACzBC,EAASD,EAAQ,WAAe,GAChCuB,EAAM,IAAI,IAA2B,CAAC,CAACjB,EAAS,IAAIH,CAAK,EAAG,CAAE,KAAM,EAAG,KAAM,IAAK,CAAC,CAAC,CAAC,EAC3F,GAAI,CAACD,EAASC,CAAK,EAAG,OAAOoB,EAC7B,IAAMZ,EAAO,WAAc,EAE3B,IADAA,EAAK,KAAK,CAAE,KAAMR,EAAO,KAAM,EAAG,EAAG,CAAE,CAAC,EACjCQ,EAAK,KAAO,GAAG,CACpB,IAAMC,EAAUD,EAAK,IAAI,EACzB,GAAIC,IAAY,IAAA,GAAW,MAC3B,IAAMY,EAAQD,EAAI,IAAIjB,EAAS,IAAIM,EAAQ,IAAI,CAAC,EAChD,GAAI,MAAU,IAAA,IAAaY,EAAM,KAAOZ,EAAQ,MAChD,IAAK,IAAMM,KAAQZ,EAAS,UAAUM,EAAQ,IAAI,EAAG,CACnD,GAAI,CAACV,EAASgB,CAAI,EAAG,SACrB,IAAMC,EAAO,WAAWlB,EAAOiB,CAAI,EAAGA,CAAI,EACpCpB,EAAOc,EAAQ,KAAOO,EAC5B,GAAIrB,EAAOU,EAAQ,SACnB,IAAMa,EAAUf,EAAS,IAAIY,CAAI,EAC3BJ,EAAQS,EAAI,IAAIF,CAAO,EACzBP,IAAU,IAAA,IAAaA,EAAM,MAAQhB,IACzCyB,EAAI,IAAIF,EAAS,CAAE,OAAM,KAAMT,EAAQ,IAAK,CAAC,EAC7CD,EAAK,KAAK,CAAE,KAAMO,EAAM,OAAM,EAAGpB,CAAK,CAAC,EACzC,CACF,CACA,OAAOyB,CACT,C"}
@@ -0,0 +1,36 @@
1
+ import type { GridTopology } from './topology.js';
2
+ /** Shared options: which cells may be entered and what entering them costs. */
3
+ export interface SearchOptions<C> {
4
+ /** Cost of entering a cell (default 1). Must be positive and finite. */
5
+ cost?: (coord: C) => number;
6
+ /**
7
+ * Returns true when a cell may be entered. The start cell is queried too.
8
+ * The search space must be finite: `passable` has to reject the cells beyond
9
+ * the world's edge, or a search for an unreachable goal expands forever.
10
+ */
11
+ passable: (coord: C) => boolean;
12
+ /** The grid's adjacency, distance, and keying. */
13
+ topology: GridTopology<C>;
14
+ }
15
+ /** One reached cell in a {@link reachable} flood: its cost and predecessor. */
16
+ export interface ReachEntry<C> {
17
+ cost: number;
18
+ prev: C | null;
19
+ }
20
+ /**
21
+ * Cheapest route from `start` to `goal`, or null when none exists within
22
+ * `maxCost`. Both endpoints must be passable; the start's cost is never
23
+ * charged. The topology distance is the heuristic, so results are optimal
24
+ * whenever every step costs at least 1.
25
+ */
26
+ export declare function findPath<C>(start: C, goal: C, options: SearchOptions<C> & Readonly<{
27
+ maxCost?: number;
28
+ }>): C[] | null;
29
+ /**
30
+ * Every cell reachable from `start` within `budget`, keyed by cell, each with
31
+ * its cheapest cost and predecessor. Rebuild a route by walking `prev` back
32
+ * from any entry. The start is included with cost 0 and `prev: null`; an
33
+ * impassable start reaches nothing but itself.
34
+ */
35
+ export declare function reachable<C>(start: C, budget: number, options: SearchOptions<C>): Map<string, ReachEntry<C>>;
36
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../../src/grid/path.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAElD,+EAA+E;AAC/E,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,wEAAwE;IACxE,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,CAAC;IAChC,kDAAkD;IAClD,QAAQ,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC;CAC3B;AAED,+EAA+E;AAC/E,MAAM,WAAW,UAAU,CAAC,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC;CAChB;AAwED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC;IAAE,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,CAkDrH;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CA4B5G"}
@@ -0,0 +1,121 @@
1
+ import { AtlasConfigError as e } from "../errors.js";
2
+ // src/grid/path.ts
3
+ function createHeap() {
4
+ let e = [], key = (e) => e.f, swap = (t, n) => {
5
+ let r = e[t], i = e[n];
6
+ r !== void 0 && i !== void 0 && (e[t] = i, e[n] = r);
7
+ };
8
+ return {
9
+ pop() {
10
+ let t = e[0], n = e.pop();
11
+ if (t !== void 0 && n !== void 0) {
12
+ if (e.length > 0) {
13
+ e[0] = n;
14
+ let t = 0;
15
+ for (;;) {
16
+ let n = 2 * t + 1, r = 2 * t + 2, i = t;
17
+ for (let t of [n, r]) {
18
+ let n = e[t], r = e[i];
19
+ n !== void 0 && r !== void 0 && key(n) < key(r) && (i = t);
20
+ }
21
+ if (i === t) break;
22
+ swap(t, i), t = i;
23
+ }
24
+ }
25
+ return t;
26
+ }
27
+ },
28
+ push(t) {
29
+ e.push(t);
30
+ let n = e.length - 1;
31
+ for (; n > 0;) {
32
+ let t = n - 1 >> 1, r = e[n], i = e[t];
33
+ if (r === void 0 || i === void 0 || key(r) >= key(i)) break;
34
+ swap(n, t), n = t;
35
+ }
36
+ },
37
+ get size() {
38
+ return e.length;
39
+ }
40
+ };
41
+ }
42
+ function assertCost(t, n) {
43
+ if (!(t > 0) || !Number.isFinite(t)) throw new e(`cell cost must be a positive finite number, got ${t} at ${String(n)}`);
44
+ return t;
45
+ }
46
+ function findPath(t, n, r) {
47
+ let { topology: i, passable: a } = r;
48
+ if (r.maxCost !== void 0 && !(r.maxCost >= 0)) throw new e(`maxCost must be non-negative, got ${String(r.maxCost)}`);
49
+ let o = r.cost ?? (() => 1);
50
+ if (!a(t) || !a(n)) return null;
51
+ let s = i.key(t), c = i.key(n);
52
+ if (s === c) return [t];
53
+ let l = r.maxCost ?? Infinity, u = /* @__PURE__ */ new Map([[s, 0]]), d = /* @__PURE__ */ new Map(), f = createHeap();
54
+ for (f.push({
55
+ cell: t,
56
+ cost: 0,
57
+ f: i.distance(t, n)
58
+ }); f.size > 0;) {
59
+ let e = f.pop();
60
+ if (e === void 0) break;
61
+ let t = i.key(e.cell), r = u.get(t);
62
+ if (!(r === void 0 || r < e.cost)) {
63
+ if (t === c) {
64
+ let t = [e.cell], n = e.cell;
65
+ for (;;) {
66
+ let e = d.get(i.key(n));
67
+ if (e === void 0 || (t.push(e), n = e, i.key(n) === s)) break;
68
+ }
69
+ return t.reverse();
70
+ }
71
+ for (let t of i.neighbors(e.cell)) {
72
+ if (!a(t)) continue;
73
+ let r = assertCost(o(t), t), s = e.cost + r;
74
+ if (s > l) continue;
75
+ let c = i.key(t), p = u.get(c);
76
+ p !== void 0 && p <= s || (u.set(c, s), d.set(c, e.cell), f.push({
77
+ cell: t,
78
+ cost: s,
79
+ f: s + i.distance(t, n)
80
+ }));
81
+ }
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+ function reachable(t, n, r) {
87
+ if (!(n >= 0) || !Number.isFinite(n)) throw new e(`movement budget must be a finite non-negative number, got ${n}`);
88
+ let { topology: i, passable: a } = r, o = r.cost ?? (() => 1), s = /* @__PURE__ */ new Map([[i.key(t), {
89
+ cost: 0,
90
+ prev: null
91
+ }]]);
92
+ if (!a(t)) return s;
93
+ let c = createHeap();
94
+ for (c.push({
95
+ cell: t,
96
+ cost: 0,
97
+ f: 0
98
+ }); c.size > 0;) {
99
+ let e = c.pop();
100
+ if (e === void 0) break;
101
+ let t = s.get(i.key(e.cell));
102
+ if (!(t === void 0 || t.cost < e.cost)) for (let t of i.neighbors(e.cell)) {
103
+ if (!a(t)) continue;
104
+ let r = assertCost(o(t), t), l = e.cost + r;
105
+ if (l > n) continue;
106
+ let u = i.key(t), d = s.get(u);
107
+ d !== void 0 && d.cost <= l || (s.set(u, {
108
+ cost: l,
109
+ prev: e.cell
110
+ }), c.push({
111
+ cell: t,
112
+ cost: l,
113
+ f: l
114
+ }));
115
+ }
116
+ }
117
+ return s;
118
+ }
119
+ export { findPath, reachable };
120
+
121
+ //# sourceMappingURL=path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.js","names":["items","item","tmp","i","at","j","top","last","left","right","smallest","child","a","b","parent","head","cost","AtlasConfigError","coord","options","costOf","passable","start","goal","startKey","topology","goalKey","budget","best","cameFrom","open","current","currentKey","known","path","cell","prev","next","step","g","nextKey","previous","out","entry"],"sources":["../../src/grid/path.ts"],"sourcesContent":["/**\n * Grid search generic over a {@link GridTopology}: A* between two cells and a\n * Dijkstra flood for everything reachable within a movement budget. Costs are\n * per-entry (the start cell is never charged), so a caller can model difficult\n * terrain without the search knowing what terrain is.\n */\nimport { AtlasConfigError } from '../errors.js';\nimport type { GridTopology } from './topology.js';\n\n/** Shared options: which cells may be entered and what entering them costs. */\nexport interface SearchOptions<C> {\n /** Cost of entering a cell (default 1). Must be positive and finite. */\n cost?: (coord: C) => number;\n /**\n * Returns true when a cell may be entered. The start cell is queried too.\n * The search space must be finite: `passable` has to reject the cells beyond\n * the world's edge, or a search for an unreachable goal expands forever.\n */\n passable: (coord: C) => boolean;\n /** The grid's adjacency, distance, and keying. */\n topology: GridTopology<C>;\n}\n\n/** One reached cell in a {@link reachable} flood: its cost and predecessor. */\nexport interface ReachEntry<C> {\n cost: number;\n prev: C | null;\n}\n\ninterface QueueItem<C> {\n cell: C;\n cost: number;\n f: number;\n}\n\n/** Binary min-heap on `f`. */\nfunction createHeap<C>(): {\n pop(): QueueItem<C> | undefined;\n push(item: QueueItem<C>): void;\n readonly size: number;\n} {\n const items: QueueItem<C>[] = [];\n const key = (item: QueueItem<C>): number => item.f;\n const swap = (i: number, j: number): void => {\n const tmp = items[i];\n const at = items[j];\n if (tmp === undefined || at === undefined) return;\n items[i] = at;\n items[j] = tmp;\n };\n return {\n pop() {\n const top = items[0];\n const last = items.pop();\n if (top === undefined || last === undefined) return undefined;\n if (items.length > 0) {\n items[0] = last;\n let i = 0;\n for (;;) {\n const left = 2 * i + 1;\n const right = 2 * i + 2;\n let smallest = i;\n for (const child of [left, right]) {\n const a = items[child];\n const b = items[smallest];\n if (a !== undefined && b !== undefined && key(a) < key(b)) smallest = child;\n }\n if (smallest === i) break;\n swap(i, smallest);\n i = smallest;\n }\n }\n return top;\n },\n push(item) {\n items.push(item);\n let i = items.length - 1;\n while (i > 0) {\n const parent = (i - 1) >> 1;\n const child = items[i];\n const head = items[parent];\n if (child === undefined || head === undefined || key(child) >= key(head)) break;\n swap(i, parent);\n i = parent;\n }\n },\n get size() {\n return items.length;\n },\n };\n}\n\nfunction assertCost(cost: number, coord: unknown): number {\n if (!(cost > 0) || !Number.isFinite(cost)) {\n throw new AtlasConfigError(`cell cost must be a positive finite number, got ${cost} at ${String(coord)}`);\n }\n return cost;\n}\n\n/**\n * Cheapest route from `start` to `goal`, or null when none exists within\n * `maxCost`. Both endpoints must be passable; the start's cost is never\n * charged. The topology distance is the heuristic, so results are optimal\n * whenever every step costs at least 1.\n */\nexport function findPath<C>(start: C, goal: C, options: SearchOptions<C> & Readonly<{ maxCost?: number }>): C[] | null {\n const { topology, passable } = options;\n if (options.maxCost !== undefined && !(options.maxCost >= 0)) {\n throw new AtlasConfigError(`maxCost must be non-negative, got ${String(options.maxCost)}`);\n }\n const costOf = options.cost ?? (() => 1);\n if (!passable(start) || !passable(goal)) return null;\n const startKey = topology.key(start);\n const goalKey = topology.key(goal);\n if (startKey === goalKey) return [start];\n const budget = options.maxCost ?? Number.POSITIVE_INFINITY;\n\n const best = new Map<string, number>([[startKey, 0]]);\n const cameFrom = new Map<string, C>();\n const open = createHeap<C>();\n open.push({ cell: start, cost: 0, f: topology.distance(start, goal) });\n\n while (open.size > 0) {\n const current = open.pop();\n if (current === undefined) break;\n const currentKey = topology.key(current.cell);\n const known = best.get(currentKey);\n // A stale queue entry (a cheaper path arrived after it was queued) is skipped.\n if (known === undefined || known < current.cost) continue;\n if (currentKey === goalKey) {\n const path: C[] = [current.cell];\n let cell = current.cell;\n for (;;) {\n const prev = cameFrom.get(topology.key(cell));\n if (prev === undefined) break;\n path.push(prev);\n cell = prev;\n if (topology.key(cell) === startKey) break;\n }\n return path.reverse();\n }\n for (const next of topology.neighbors(current.cell)) {\n if (!passable(next)) continue;\n const step = assertCost(costOf(next), next);\n const g = current.cost + step;\n if (g > budget) continue;\n const nextKey = topology.key(next);\n const previous = best.get(nextKey);\n if (previous !== undefined && previous <= g) continue;\n best.set(nextKey, g);\n cameFrom.set(nextKey, current.cell);\n open.push({ cell: next, cost: g, f: g + topology.distance(next, goal) });\n }\n }\n return null;\n}\n\n/**\n * Every cell reachable from `start` within `budget`, keyed by cell, each with\n * its cheapest cost and predecessor. Rebuild a route by walking `prev` back\n * from any entry. The start is included with cost 0 and `prev: null`; an\n * impassable start reaches nothing but itself.\n */\nexport function reachable<C>(start: C, budget: number, options: SearchOptions<C>): Map<string, ReachEntry<C>> {\n if (!(budget >= 0) || !Number.isFinite(budget)) {\n throw new AtlasConfigError(`movement budget must be a finite non-negative number, got ${budget}`);\n }\n const { topology, passable } = options;\n const costOf = options.cost ?? (() => 1);\n const out = new Map<string, ReachEntry<C>>([[topology.key(start), { cost: 0, prev: null }]]);\n if (!passable(start)) return out;\n const open = createHeap<C>();\n open.push({ cell: start, cost: 0, f: 0 });\n while (open.size > 0) {\n const current = open.pop();\n if (current === undefined) break;\n const entry = out.get(topology.key(current.cell));\n if (entry === undefined || entry.cost < current.cost) continue;\n for (const next of topology.neighbors(current.cell)) {\n if (!passable(next)) continue;\n const step = assertCost(costOf(next), next);\n const cost = current.cost + step;\n if (cost > budget) continue;\n const nextKey = topology.key(next);\n const known = out.get(nextKey);\n if (known !== undefined && known.cost <= cost) continue;\n out.set(nextKey, { cost, prev: current.cell });\n open.push({ cell: next, cost, f: cost });\n }\n }\n return out;\n}\n"],"mappings":";;AAoCA,SAAS,aAIP;CACA,IAAMA,IAAwB,CAAC,GACzB,OAAO,MAA+BC,EAAK,GAC3C,QAAQ,GAAW,MAAoB;EAC3C,IAAMC,IAAMF,EAAMG,IACZC,IAAKJ,EAAMK;EACjB,AAAIH,MAAQ,KAAA,KAAaE,MAAO,KAAA,MAChC,EAAMD,KAAKC,GACX,EAAMC,KAAKH;CACb;CACA,OAAO;EACL,MAAM;GACJ,IAAMI,IAAMN,EAAM,IACZO,IAAOP,EAAM,IAAI;GACvB,IAAIM,MAAQ,KAAA,KAAaC,MAAS,KAAA,GAClC;QAAIP,EAAM,SAAS,GAAG;KACpB,EAAM,KAAKO;KACX,IAAIJ,IAAI;KACR,SAAS;MACP,IAAMK,IAAO,IAAIL,IAAI,GACfM,IAAQ,IAAIN,IAAI,GAClBO,IAAWP;MACf,KAAK,IAAMQ,KAAS,CAACH,GAAMC,CAAK,GAAG;OACjC,IAAMG,IAAIZ,EAAMW,IACVE,IAAIb,EAAMU;OAChB,AAAIE,MAAM,KAAA,KAAaC,MAAM,KAAA,KAAa,IAAID,CAAC,IAAI,IAAIC,CAAC,MAAG,IAAWF;MACxE;MACA,IAAID,MAAaP,GAAG;MAEpB,AADA,KAAKA,GAAGO,CAAQ,GAChB,IAAIA;KACN;IACF;IACA,OAAOJ;GADP;EAEF;EACA,KA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IAAI,IAA2B,CAAC,CAACjB,EAAS,IAAIH,CAAK,GAAG;EAAE,MAAM;EAAG,MAAM;CAAK,CAAC,CAAC,CAAC;CAC3F,IAAI,CAACD,EAASC,CAAK,GAAG,OAAOoB;CAC7B,IAAMZ,IAAO,WAAc;CAE3B,KADAA,EAAK,KAAK;EAAE,MAAMR;EAAO,MAAM;EAAG,GAAG;CAAE,CAAC,GACjCQ,EAAK,OAAO,IAAG;EACpB,IAAMC,IAAUD,EAAK,IAAI;EACzB,IAAIC,MAAY,KAAA,GAAW;EAC3B,IAAMY,IAAQD,EAAI,IAAIjB,EAAS,IAAIM,EAAQ,IAAI,CAAC;EAChD,IAAI,QAAU,KAAA,KAAaY,EAAM,OAAOZ,EAAQ,OAChD,KAAK,IAAMM,KAAQZ,EAAS,UAAUM,EAAQ,IAAI,GAAG;GACnD,IAAI,CAACV,EAASgB,CAAI,GAAG;GACrB,IAAMC,IAAO,WAAWlB,EAAOiB,CAAI,GAAGA,CAAI,GACpCrB,IAAOe,EAAQ,OAAOO;GAC5B,IAAItB,IAAOW,GAAQ;GACnB,IAAMa,IAAUf,EAAS,IAAIY,CAAI,GAC3BJ,IAAQS,EAAI,IAAIF,CAAO;GAC7B,AAAIP,MAAU,KAAA,KAAaA,EAAM,QAAQjB,MACzC0B,EAAI,IAAIF,GAAS;IAAE;IAAM,MAAMT,EAAQ;GAAK,CAAC,GAC7CD,EAAK,KAAK;IAAE,MAAMO;IAAM;IAAM,GAAGrB;GAAK,CAAC;EACzC;CACF;CACA,OAAO0B;AACT"}
@@ -0,0 +1,2 @@
1
+ const e=require("./tile.cjs");var t=[{col:1,row:0},{col:-1,row:0},{col:0,row:1},{col:0,row:-1}],n=[{col:1,row:1},{col:1,row:-1},{col:-1,row:1},{col:-1,row:-1}];function squareTopology(r={}){let i=r.diagonal??!1,a=i?[...t,...n]:t;return{distance(e,t){let n=Math.abs(e.col-t.col),r=Math.abs(e.row-t.row);return i?Math.max(n,r):n+r},key:e.tileKey,line(e,t){return supercoverLine(e,t)},neighbors(e){return a.map(t=>({col:e.col+t.col,row:e.row+t.row}))}}}function supercoverLine(e,t){if(e.col===t.col&&e.row===t.row)return[e];let n=e.col<t.col||e.col===t.col&&e.row<=t.row,r=walkSupercover(n?e:t,n?t:e);return n?r:r.reverse()}function walkSupercover(e,t){let n=e.col+.5,r=e.row+.5,i=t.col+.5,a=t.row+.5,o=Math.abs(a-r)>Math.abs(i-n),s=[],c=new Set,add=(e,t)=>{let n=`${String(e)}:${String(t)}`;c.has(n)||(c.add(n),s.push({col:e,row:t}))},yAt=e=>r+(a-r)*(e-n)/(i-n),xAt=e=>n+(i-n)*(e-r)/(a-r),span=(e,t)=>{let n=Math.floor(Math.min(e,t));return[Number.isInteger(Math.min(e,t))?n-1:n,Math.floor(Math.max(e,t))]};if(o)for(let n=Math.min(e.row,t.row);n<=Math.max(e.row,t.row);n+=1){let e=Math.max(n,Math.min(r,a)),t=Math.min(n+1,Math.max(r,a));if(e>t)continue;let[i,o]=span(xAt(e),xAt(t));for(let e=i;e<=o;e+=1)add(e,n)}else for(let r=e.col;r<=t.col;r+=1){let e=Math.max(r,Math.min(n,i)),t=Math.min(r+1,Math.max(n,i));if(e>t)continue;let[a,o]=span(yAt(e),yAt(t));for(let e=a;e<=o;e+=1)add(r,e)}return s}exports.squareTopology=squareTopology;
2
+ //# sourceMappingURL=topology.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topology.cjs","names":["tileKey","require_tile","ORTHOGONAL","DIAGONALS","diagonal","options","steps","dc","a","b","dr","coord","d","forward","cells","xa","ya","xb","yb","steep","out","seen","key","col","row","x","y","first","lo","hi","yLo","yHi","colLo","colHi","xLo","xHi","rowLo","rowHi"],"sources":["../../src/grid/topology.ts"],"sourcesContent":["/**\n * Grid topology: the facts a search needs about a discrete grid, so the same\n * pathfinding runs on square tiles and hexes. A topology is a plain object of\n * pure functions; the hex implementation lives in `hex.ts`.\n */\nimport { type TileCoord, tileKey } from './tile.js';\n\n/** What a search needs to know about a grid of cells of type `C`. */\nexport interface GridTopology<C> {\n /** Distance in steps between two cells; admissible as an A* heuristic. */\n distance(a: C, b: C): number;\n /** A stable string key for a cell, usable as a Map/Set key. */\n key(coord: C): string;\n /** The cells a straight walk from `a` to `b` crosses, both ends included. */\n line(a: C, b: C): readonly C[];\n /** The cells adjacent to a cell. */\n neighbors(coord: C): readonly C[];\n}\n\nconst ORTHOGONAL: readonly TileCoord[] = [\n { col: 1, row: 0 },\n { col: -1, row: 0 },\n { col: 0, row: 1 },\n { col: 0, row: -1 },\n];\n\nconst DIAGONALS: readonly TileCoord[] = [\n { col: 1, row: 1 },\n { col: 1, row: -1 },\n { col: -1, row: 1 },\n { col: -1, row: -1 },\n];\n\n/**\n * The {@link GridTopology} for square tiles. `diagonal: true` gives 8-way\n * adjacency and Chebyshev distance; the default is 4-way with Manhattan\n * distance. `line` is a supercover line: every tile whose square the segment\n * touches, so a sight line never skips a corner tile.\n */\nexport function squareTopology(options: Readonly<{ diagonal?: boolean }> = {}): GridTopology<TileCoord> {\n const diagonal = options.diagonal ?? false;\n const steps = diagonal ? [...ORTHOGONAL, ...DIAGONALS] : ORTHOGONAL;\n return {\n distance(a, b) {\n const dc = Math.abs(a.col - b.col);\n const dr = Math.abs(a.row - b.row);\n return diagonal ? Math.max(dc, dr) : dc + dr;\n },\n key: tileKey,\n line(a, b) {\n return supercoverLine(a, b);\n },\n neighbors(coord) {\n return steps.map((d) => ({ col: coord.col + d.col, row: coord.row + d.row }));\n },\n };\n}\n\n/**\n * Supercover line between tile centres: for each column (or row, when the\n * segment is steeper) the segment spans, every row whose closed square the\n * segment touches joins the line. Corner touches count on both sides, and the\n * walk always runs from the lexicographically smaller endpoint, so reversing\n * the endpoints yields the same cells in reverse order.\n */\nfunction supercoverLine(a: TileCoord, b: TileCoord): readonly TileCoord[] {\n if (a.col === b.col && a.row === b.row) return [a];\n const forward = a.col < b.col || (a.col === b.col && a.row <= b.row);\n const from = forward ? a : b;\n const to = forward ? b : a;\n const cells = walkSupercover(from, to);\n return forward ? cells : cells.reverse();\n}\n\nfunction walkSupercover(a: TileCoord, b: TileCoord): TileCoord[] {\n const xa = a.col + 0.5;\n const ya = a.row + 0.5;\n const xb = b.col + 0.5;\n const yb = b.row + 0.5;\n const steep = Math.abs(yb - ya) > Math.abs(xb - xa);\n const out: TileCoord[] = [];\n const seen = new Set<string>();\n const add = (col: number, row: number): void => {\n const key = `${String(col)}:${String(row)}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ col, row });\n };\n const yAt = (x: number): number => ya + ((yb - ya) * (x - xa)) / (xb - xa);\n const xAt = (y: number): number => xa + ((xb - xa) * (y - ya)) / (yb - ya);\n\n // A span that lands exactly on a cell boundary touches the cell on each\n // side of it, so the lower bound steps down one cell in that case.\n const span = (lo: number, hi: number): readonly [number, number] => {\n const first = Math.floor(Math.min(lo, hi));\n return [Number.isInteger(Math.min(lo, hi)) ? first - 1 : first, Math.floor(Math.max(lo, hi))];\n };\n\n if (!steep) {\n for (let col = a.col; col <= b.col; col += 1) {\n const xLo = Math.max(col, Math.min(xa, xb));\n const xHi = Math.min(col + 1, Math.max(xa, xb));\n if (xLo > xHi) continue;\n const [rowLo, rowHi] = span(yAt(xLo), yAt(xHi));\n for (let row = rowLo; row <= rowHi; row += 1) add(col, row);\n }\n } else {\n for (let row = Math.min(a.row, b.row); row <= Math.max(a.row, b.row); row += 1) {\n const yLo = Math.max(row, Math.min(ya, yb));\n const yHi = Math.min(row + 1, Math.max(ya, yb));\n if (yLo > yHi) continue;\n const [colLo, colHi] = span(xAt(yLo), xAt(yHi));\n for (let col = colLo; col <= colHi; col += 1) add(col, row);\n }\n }\n return out;\n}\n"],"mappings":"A,8BAmBA,IAAME,EAAmC,CACvC,CAAE,IAAK,EAAG,IAAK,CAAE,EACjB,CAAE,IAAK,GAAI,IAAK,CAAE,EAClB,CAAE,IAAK,EAAG,IAAK,CAAE,EACjB,CAAE,IAAK,EAAG,IAAK,EAAG,CACpB,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IR,EAAIE,CAAE,CAAC,EACpCkB,EAAM,KAAK,IAAIZ,EAAM,EAAG,KAAK,IAAIR,EAAIE,CAAE,CAAC,EAC9C,GAAIiB,EAAMC,EAAK,SACf,GAAM,CAACC,EAAOC,GAAS,KAAK,IAAIH,CAAG,EAAG,IAAIC,CAAG,CAAC,EAC9C,IAAK,IAAIX,EAAMY,EAAOZ,GAAOa,EAAO,GAAO,EAAG,IAAId,EAAKC,CAAG,CAC5D,CAUF,OAAOJ,CACT,C"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Grid topology: the facts a search needs about a discrete grid, so the same
3
+ * pathfinding runs on square tiles and hexes. A topology is a plain object of
4
+ * pure functions; the hex implementation lives in `hex.ts`.
5
+ */
6
+ import { type TileCoord } from './tile.js';
7
+ /** What a search needs to know about a grid of cells of type `C`. */
8
+ export interface GridTopology<C> {
9
+ /** Distance in steps between two cells; admissible as an A* heuristic. */
10
+ distance(a: C, b: C): number;
11
+ /** A stable string key for a cell, usable as a Map/Set key. */
12
+ key(coord: C): string;
13
+ /** The cells a straight walk from `a` to `b` crosses, both ends included. */
14
+ line(a: C, b: C): readonly C[];
15
+ /** The cells adjacent to a cell. */
16
+ neighbors(coord: C): readonly C[];
17
+ }
18
+ /**
19
+ * The {@link GridTopology} for square tiles. `diagonal: true` gives 8-way
20
+ * adjacency and Chebyshev distance; the default is 4-way with Manhattan
21
+ * distance. `line` is a supercover line: every tile whose square the segment
22
+ * touches, so a sight line never skips a corner tile.
23
+ */
24
+ export declare function squareTopology(options?: Readonly<{
25
+ diagonal?: boolean;
26
+ }>): GridTopology<TileCoord>;
27
+ //# sourceMappingURL=topology.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topology.d.ts","sourceRoot":"","sources":["../../src/grid/topology.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,KAAK,SAAS,EAAW,MAAM,WAAW,CAAC;AAEpD,qEAAqE;AACrE,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,0EAA0E;IAC1E,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;IACtB,6EAA6E;IAC7E,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,EAAE,CAAC;IAC/B,oCAAoC;IACpC,SAAS,CAAC,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,EAAE,CAAC;CACnC;AAgBD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,QAAQ,CAAC;IAAE,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAAM,GAAG,YAAY,CAAC,SAAS,CAAC,CAiBtG"}
@@ -0,0 +1,89 @@
1
+ import { tileKey as e } from "./tile.js";
2
+ // src/grid/topology.ts
3
+ var t = [
4
+ {
5
+ col: 1,
6
+ row: 0
7
+ },
8
+ {
9
+ col: -1,
10
+ row: 0
11
+ },
12
+ {
13
+ col: 0,
14
+ row: 1
15
+ },
16
+ {
17
+ col: 0,
18
+ row: -1
19
+ }
20
+ ], n = [
21
+ {
22
+ col: 1,
23
+ row: 1
24
+ },
25
+ {
26
+ col: 1,
27
+ row: -1
28
+ },
29
+ {
30
+ col: -1,
31
+ row: 1
32
+ },
33
+ {
34
+ col: -1,
35
+ row: -1
36
+ }
37
+ ];
38
+ function squareTopology(r = {}) {
39
+ let i = r.diagonal ?? !1, a = i ? [...t, ...n] : t;
40
+ return {
41
+ distance(e, t) {
42
+ let n = Math.abs(e.col - t.col), r = Math.abs(e.row - t.row);
43
+ return i ? Math.max(n, r) : n + r;
44
+ },
45
+ key: e,
46
+ line(e, t) {
47
+ return supercoverLine(e, t);
48
+ },
49
+ neighbors(e) {
50
+ return a.map((t) => ({
51
+ col: e.col + t.col,
52
+ row: e.row + t.row
53
+ }));
54
+ }
55
+ };
56
+ }
57
+ function supercoverLine(e, t) {
58
+ if (e.col === t.col && e.row === t.row) return [e];
59
+ let n = e.col < t.col || e.col === t.col && e.row <= t.row, r = walkSupercover(n ? e : t, n ? t : e);
60
+ return n ? r : r.reverse();
61
+ }
62
+ function walkSupercover(e, t) {
63
+ let n = e.col + .5, r = e.row + .5, i = t.col + .5, a = t.row + .5, o = Math.abs(a - r) > Math.abs(i - n), s = [], c = /* @__PURE__ */ new Set(), add = (e, t) => {
64
+ let n = `${String(e)}:${String(t)}`;
65
+ c.has(n) || (c.add(n), s.push({
66
+ col: e,
67
+ row: t
68
+ }));
69
+ }, yAt = (e) => r + (a - r) * (e - n) / (i - n), xAt = (e) => n + (i - n) * (e - r) / (a - r), span = (e, t) => {
70
+ let n = Math.floor(Math.min(e, t));
71
+ return [Number.isInteger(Math.min(e, t)) ? n - 1 : n, Math.floor(Math.max(e, t))];
72
+ };
73
+ if (o) for (let n = Math.min(e.row, t.row); n <= Math.max(e.row, t.row); n += 1) {
74
+ let e = Math.max(n, Math.min(r, a)), t = Math.min(n + 1, Math.max(r, a));
75
+ if (e > t) continue;
76
+ let [i, o] = span(xAt(e), xAt(t));
77
+ for (let e = i; e <= o; e += 1) add(e, n);
78
+ }
79
+ else for (let r = e.col; r <= t.col; r += 1) {
80
+ let e = Math.max(r, Math.min(n, i)), t = Math.min(r + 1, Math.max(n, i));
81
+ if (e > t) continue;
82
+ let [a, o] = span(yAt(e), yAt(t));
83
+ for (let e = a; e <= o; e += 1) add(r, e);
84
+ }
85
+ return s;
86
+ }
87
+ export { squareTopology };
88
+
89
+ //# sourceMappingURL=topology.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"topology.js","names":["ORTHOGONAL","DIAGONALS","diagonal","options","steps","dc","a","b","dr","tileKey","coord","d","forward","cells","xa","ya","xb","yb","steep","out","seen","key","col","row","x","y","first","lo","hi","yLo","yHi","colLo","colHi","xLo","xHi","rowLo","rowHi"],"sources":["../../src/grid/topology.ts"],"sourcesContent":["/**\n * Grid topology: the facts a search needs about a discrete grid, so the same\n * pathfinding runs on square tiles and hexes. A topology is a plain object of\n * pure functions; the hex implementation lives in `hex.ts`.\n */\nimport { type TileCoord, tileKey } from './tile.js';\n\n/** What a search needs to know about a grid of cells of type `C`. */\nexport interface GridTopology<C> {\n /** Distance in steps between two cells; admissible as an A* heuristic. */\n distance(a: C, b: C): number;\n /** A stable string key for a cell, usable as a Map/Set key. */\n key(coord: C): string;\n /** The cells a straight walk from `a` to `b` crosses, both ends included. */\n line(a: C, b: C): readonly C[];\n /** The cells adjacent to a cell. */\n neighbors(coord: C): readonly C[];\n}\n\nconst ORTHOGONAL: readonly TileCoord[] = [\n { col: 1, row: 0 },\n { col: -1, row: 0 },\n { col: 0, row: 1 },\n { col: 0, row: -1 },\n];\n\nconst DIAGONALS: readonly TileCoord[] = [\n { col: 1, row: 1 },\n { col: 1, row: -1 },\n { col: -1, row: 1 },\n { col: -1, row: -1 },\n];\n\n/**\n * The {@link GridTopology} for square tiles. `diagonal: true` gives 8-way\n * adjacency and Chebyshev distance; the default is 4-way with Manhattan\n * distance. `line` is a supercover line: every tile whose square the segment\n * touches, so a sight line never skips a corner tile.\n */\nexport function squareTopology(options: Readonly<{ diagonal?: boolean }> = {}): GridTopology<TileCoord> {\n const diagonal = options.diagonal ?? false;\n const steps = diagonal ? [...ORTHOGONAL, ...DIAGONALS] : ORTHOGONAL;\n return {\n distance(a, b) {\n const dc = Math.abs(a.col - b.col);\n const dr = Math.abs(a.row - b.row);\n return diagonal ? Math.max(dc, dr) : dc + dr;\n },\n key: tileKey,\n line(a, b) {\n return supercoverLine(a, b);\n },\n neighbors(coord) {\n return steps.map((d) => ({ col: coord.col + d.col, row: coord.row + d.row }));\n },\n };\n}\n\n/**\n * Supercover line between tile centres: for each column (or row, when the\n * segment is steeper) the segment spans, every row whose closed square the\n * segment touches joins the line. Corner touches count on both sides, and the\n * walk always runs from the lexicographically smaller endpoint, so reversing\n * the endpoints yields the same cells in reverse order.\n */\nfunction supercoverLine(a: TileCoord, b: TileCoord): readonly TileCoord[] {\n if (a.col === b.col && a.row === b.row) return [a];\n const forward = a.col < b.col || (a.col === b.col && a.row <= b.row);\n const from = forward ? a : b;\n const to = forward ? b : a;\n const cells = walkSupercover(from, to);\n return forward ? cells : cells.reverse();\n}\n\nfunction walkSupercover(a: TileCoord, b: TileCoord): TileCoord[] {\n const xa = a.col + 0.5;\n const ya = a.row + 0.5;\n const xb = b.col + 0.5;\n const yb = b.row + 0.5;\n const steep = Math.abs(yb - ya) > Math.abs(xb - xa);\n const out: TileCoord[] = [];\n const seen = new Set<string>();\n const add = (col: number, row: number): void => {\n const key = `${String(col)}:${String(row)}`;\n if (seen.has(key)) return;\n seen.add(key);\n out.push({ col, row });\n };\n const yAt = (x: number): number => ya + ((yb - ya) * (x - xa)) / (xb - xa);\n const xAt = (y: number): number => xa + ((xb - xa) * (y - ya)) / (yb - ya);\n\n // A span that lands exactly on a cell boundary touches the cell on each\n // side of it, so the lower bound steps down one cell in that case.\n const span = (lo: number, hi: number): readonly [number, number] => {\n const first = Math.floor(Math.min(lo, hi));\n return [Number.isInteger(Math.min(lo, hi)) ? first - 1 : first, Math.floor(Math.max(lo, hi))];\n };\n\n if (!steep) {\n for (let col = a.col; col <= b.col; col += 1) {\n const xLo = Math.max(col, Math.min(xa, xb));\n const xHi = Math.min(col + 1, Math.max(xa, xb));\n if (xLo > xHi) continue;\n const [rowLo, rowHi] = span(yAt(xLo), yAt(xHi));\n for (let row = rowLo; row <= rowHi; row += 1) add(col, row);\n }\n } else {\n for (let row = Math.min(a.row, b.row); row <= Math.max(a.row, b.row); row += 1) {\n const yLo = Math.max(row, Math.min(ya, yb));\n const yHi = Math.min(row + 1, Math.max(ya, yb));\n if (yLo > yHi) continue;\n const [colLo, colHi] = span(xAt(yLo), xAt(yHi));\n for (let col = colLo; col <= colHi; col += 1) add(col, row);\n }\n }\n return out;\n}\n"],"mappings":";;AAmBA,IAAMA,IAAmC;CACvC;EAA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IV,GAAKC,CAAG;CAC5D;MAdA,KAAK,IAAID,IAAMhB,EAAE,KAAKgB,KAAOf,EAAE,KAAK,KAAO,GAAG;EAC5C,IAAM0B,IAAM,KAAK,IAAIX,GAAK,KAAK,IAAIR,GAAIE,CAAE,CAAC,GACpCkB,IAAM,KAAK,IAAIZ,IAAM,GAAG,KAAK,IAAIR,GAAIE,CAAE,CAAC;EAC9C,IAAIiB,IAAMC,GAAK;EACf,IAAM,CAACC,GAAOC,KAAS,KAAK,IAAIH,CAAG,GAAG,IAAIC,CAAG,CAAC;EAC9C,KAAK,IAAIX,IAAMY,GAAOZ,KAAOa,GAAO,KAAO,GAAG,IAAId,GAAKC,CAAG;CAC5D;CAUF,OAAOJ;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vielzeug/atlas",
3
- "version": "26.11.24",
3
+ "version": "26.11.26",
4
4
  "description": "Spatial math, camera, and indexing primitives for 2D canvases",
5
5
  "repository": {
6
6
  "type": "git",