BlueGit

timfa questward

Files

questward / shared / world / neighborConnect.js

neighborConnect.js

neighborConnect.js 6.9 KiB Download Raw
1/**
2 * Generic neighbor-connect autotile masks (N/E/S/W).
3 * Stored as block/ground `state` for bakeable sprite variants.
4 *
5 * - Cardinal numeric (tables/fences/counters): `"0"`…`"15"` (or `pine-3` with material).
6 * - Named cardinal (stone walls): `"thick-stone-wall"`, `"thick-stone-wall-esw"`, …
7 */
8
9export const NeighborBit = Object.freeze({
10 n: 1,
11 e: 2,
12 s: 4,
13 w: 8
14});
15
16export const NEIGHBOR_CONNECT_MASK_COUNT = 16;
17
18export function neighborConnectMask ({ n = false, e = false, s = false, w = false } = {})
19{
20 return (n ? NeighborBit.n : 0)
21 | (e ? NeighborBit.e : 0)
22 | (s ? NeighborBit.s : 0)
23 | (w ? NeighborBit.w : 0);
24}
25
26export function neighborConnectStateName (mask)
27{
28 const m = Math.max(0, Math.min(15, mask | 0));
29 return String(m);
30}
31
32/**
33 * Cardinal connection suffix for named wall sprites.
34 * Opposite runs: `ns`, `we`. Three-ways clockwise from the side after the gap
35 * (`esw` = T open north, `wne` = T open south). Full: `nesw`. Alone: `""`.
36 */
37export function cardinalConnectionSuffix (mask)
38{
39 const m = (mask | 0) & 15;
40 if (m === 0)
41 { return ""; }
42 const n = (m & NeighborBit.n) !== 0;
43 const e = (m & NeighborBit.e) !== 0;
44 const s = (m & NeighborBit.s) !== 0;
45 const w = (m & NeighborBit.w) !== 0;
46 const count = (n ? 1 : 0) + (e ? 1 : 0) + (s ? 1 : 0) + (w ? 1 : 0);
47 if (count === 1)
48 {
49 if (n)
50 { return "n"; }
51 if (e)
52 { return "e"; }
53 if (s)
54 { return "s"; }
55 return "w";
56 }
57 if (count === 2)
58 {
59 if (n && s)
60 { return "ns"; }
61 if (e && w)
62 { return "we"; }
63 if (n && e)
64 { return "ne"; }
65 if (e && s)
66 { return "es"; }
67 if (s && w)
68 { return "sw"; }
69 return "wn";
70 }
71 if (count === 3)
72 {
73 const bits = [NeighborBit.n, NeighborBit.e, NeighborBit.s, NeighborBit.w];
74 const letters = ["n", "e", "s", "w"];
75 let miss = 0;
76 for (let i = 0; i < 4; i++)
77 {
78 if ((m & bits[i]) === 0)
79 { miss = i; }
80 }
81 return letters[(miss + 1) % 4] + letters[(miss + 2) % 4] + letters[(miss + 3) % 4];
82 }
83 return "nesw";
84}
85
86export function composeNamedNeighborConnectState (def, mask)
87{
88 const key = def?.key ?? "block";
89 const suffix = cardinalConnectionSuffix(mask);
90 return suffix ? `${key}-${suffix}` : key;
91}
92
93/** Parse named (`thick-stone-wall-esw`) or bare (`esw`) or legacy numeric states. */
94export function parseNamedNeighborConnectMask (state, def = null)
95{
96 const s = String(state ?? "").trim().toLowerCase();
97 if (!s)
98 { return 0; }
99 if (/^\d+$/.test(s))
100 { return Math.max(0, Math.min(15, Number(s) | 0)); }
101 const key = String(def?.key ?? "").toLowerCase();
102 if (key && s === key)
103 { return 0; }
104 let suffix = s;
105 if (key && s.startsWith(`${key}-`))
106 { suffix = s.slice(key.length + 1); }
107 let mask = 0;
108 for (const ch of suffix)
109 {
110 if (ch === "n")
111 { mask |= NeighborBit.n; }
112 else if (ch === "e")
113 { mask |= NeighborBit.e; }
114 else if (ch === "s")
115 { mask |= NeighborBit.s; }
116 else if (ch === "w")
117 { mask |= NeighborBit.w; }
118 }
119 return mask;
120}
121
122export function parseNeighborConnectMask (state)
123{
124 if (state == null || state === "")
125 { return 0; }
126 const n = Number(state);
127 if (!Number.isFinite(n))
128 { return 0; }
129 return Math.max(0, Math.min(15, n | 0));
130}
131
132export function hasNeighborBit (mask, bit)
133{
134 return ((mask | 0) & bit) !== 0;
135}
136
137/** Cardinal offsets in tile space (y increases south in this project). */
138export const NEIGHBOR_CARDINALS = Object.freeze([
139 Object.freeze({ bit: NeighborBit.n, dx: 0, dy: -1, key: "n" }),
140 Object.freeze({ bit: NeighborBit.e, dx: 1, dy: 0, key: "e" }),
141 Object.freeze({ bit: NeighborBit.s, dx: 0, dy: 1, key: "s" }),
142 Object.freeze({ bit: NeighborBit.w, dx: -1, dy: 0, key: "w" })
143]);
144
145/**
146 * @param {(dx: number, dy: number) => boolean} isConnectedNeighbor
147 */
148export function computeNeighborConnectMask (isConnectedNeighbor)
149{
150 let mask = 0;
151 for (const dir of NEIGHBOR_CARDINALS)
152 {
153 if (isConnectedNeighbor(dir.dx, dir.dy))
154 { mask |= dir.bit; }
155 }
156 return mask;
157}
158
159export function definitionUsesNeighborConnect (def)
160{
161 return !!def?.neighborConnect;
162}
163
164export function definitionUsesNamedNeighborConnect (def)
165{
166 return !!def?.neighborConnect && !!def?.neighborConnectNamed;
167}
168
169export function definitionUsesMaterialNeighborConnect (def)
170{
171 return !!def?.neighborConnect && !!def?.neighborConnectByMaterial;
172}
173
174function clampCardinalMask (value)
175{
176 const n = Number(value);
177 if (!Number.isFinite(n))
178 { return 0; }
179 return Math.max(0, Math.min(15, n | 0));
180}
181
182/**
183 * Tables (and similar) store `${material}-${mask}` e.g. `pine-3`.
184 * Plain masks (`"7"`) stay valid for counters.
185 */
186export function parseMaterialNeighborConnectState (state, def = null)
187{
188 const fallback = def?.defaultNeighborMaterial ?? "pine";
189 const s = String(state ?? "").trim();
190 const paired = /^([a-z][a-z0-9]*)-(\d+)$/i.exec(s);
191 if (paired)
192 {
193 return {
194 material: paired[1].toLowerCase(),
195 mask: clampCardinalMask(paired[2])
196 };
197 }
198 if (/^\d+$/.test(s))
199 {
200 return { material: fallback, mask: clampCardinalMask(s) };
201 }
202 if (/^[a-z][a-z0-9]*$/i.test(s))
203 {
204 return { material: s.toLowerCase(), mask: 0 };
205 }
206 return { material: fallback, mask: 0 };
207}
208
209export function composeNeighborConnectState (def, currentState, mask)
210{
211 const m = clampCardinalMask(mask);
212 if (definitionUsesMaterialNeighborConnect(def))
213 {
214 const { material } = parseMaterialNeighborConnectState(currentState, def);
215 return `${material}-${m}`;
216 }
217 if (definitionUsesNamedNeighborConnect(def))
218 { return composeNamedNeighborConnectState(def, m); }
219 return neighborConnectStateName(m);
220}
221
222/** True when two blocks should join for neighbor-connect (same type; same material if required). */
223export function neighborConnectBlocksMatch (self, neighbor, def)
224{
225 if (!self || !neighbor || (self.typeId | 0) !== (neighbor.typeId | 0))
226 { return false; }
227 if (!definitionUsesMaterialNeighborConnect(def))
228 { return true; }
229 const a = parseMaterialNeighborConnectState(self.state, def).material;
230 const b = parseMaterialNeighborConnectState(neighbor.state, def).material;
231 return a === b;
232}
233
234/** Resolve the visual mask from any neighbor-connect state string. */
235export function parseNeighborConnectMaskFromState (state, def = null)
236{
237 if (definitionUsesMaterialNeighborConnect(def))
238 { return parseMaterialNeighborConnectState(state, def).mask; }
239 if (definitionUsesNamedNeighborConnect(def))
240 { return parseNamedNeighborConnectMask(state, def); }
241 return parseNeighborConnectMask(state);
242}
243
244/**
245 * Map a world tile to chunk coords + local tile (handles negative world tiles).
246 */
247export function worldTileToChunkLocal (tileX, tileY, chunkSize = 16)
248{
249 const size = Math.max(1, chunkSize | 0 || 16);
250 const chunkX = Math.floor(tileX / size);
251 const chunkY = Math.floor(tileY / size);
252 return {
253 chunkX,
254 chunkY,
255 localX: tileX - chunkX * size,
256 localY: tileY - chunkY * size
257 };
258}
259
260/** Self + cardinal neighbors in world tile space (for connect mask refresh). */
261export function neighborConnectRefreshTiles (tileX, tileY)
262{
263 return [
264 [tileX, tileY],
265 [tileX, tileY - 1],
266 [tileX + 1, tileY],
267 [tileX, tileY + 1],
268 [tileX - 1, tileY]
269 ];
270}