Repository navigation
Expand file tree
/
Copy pathvision.js
More file actions
532 lines (498 loc) · 24.5 KB
/
Copy pathvision.js
File metadata and controls
532 lines (498 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/* vision.js — line-of-sight raycaster, light coverage, and darkness compositing.
* Casts visibility polygons from player tokens against sight segments (cached by castVersion),
* unions light sources into the light layer, paints explored memory, and composites LoS + darkness
* over the view. Pure compute + raster. The light mutator (addLight), the radius control, the
* obstacle readers, and the GM debug overlay (drawCastDebug, which reads the selection let) stay in
* app.js. castVersion is owned here (only invalidateCast bumps it) and exported read-only.
*/
import {
canvas, castCache, castFrameKeys, ctx, cur, darkCanvas, darkCtx, exploredMasks,
fogBuf, isPlayer, lightCache, lightCanvas, lightCtx, lightFrameKeys, losCanvas, losCtx,
state, tintCanvas, tintCtx,
} from "./state.js";
import {
pxPerCellNative, screenToNative,
} from "./geometry.js";
import {
activeTurnTokenId,
} from "./initiative.js";
let castVersion = 0; // bumps when sight obstacles or the active floor change, invalidating the cast cache
const LIGHT_BRIGHT_FRACTION = 0.5; // inner radius (fraction of outer) held at full brightness before falloff
const LIGHT_DEFAULT_COLOR = "#ffd9a0"; // warm torch — used for lights/torches authored before 5e (no color field)
const LIGHT_TINT_CORE_ALPHA = 0.55; // additive tint strength at the bright core; fades to 0 at the rim
// Parse a #rgb or #rrggbb hex into an rgba() string at the given alpha. Falls back to the warm
// default for anything unparseable, so an old or malformed light still glows rather than vanishing.
function hexToRgba(hex, a) {
let h = String(hex || LIGHT_DEFAULT_COLOR).replace("#", "");
if (h.length === 3) h = h.split("").map((c) => c + c).join("");
if (h.length !== 6 || /[^0-9a-fA-F]/.test(h)) h = LIGHT_DEFAULT_COLOR.replace("#", "");
const n = parseInt(h, 16);
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${a})`;
}
// Call whenever sight obstacles or the active floor change, so the next cast rebuilds.
function invalidateCast() {
castVersion++;
castCache.clear();
lightCache.clear();
}
// Native-space segments that block sight on the current floor: every consecutive pair of
// an obstacle polyline (open, like the renderer) where blocksSight isn't false (windows
// pass through), plus the four map-edge segments so rays that hit nothing terminate at the
// boundary and the visibility polygon stays bounded.
function sightSegments() {
const segs = [];
state.obstacles.forEach((ob) => {
if (ob.blocksSight === false) return; // windows let sight through
if (ob.kind === "door" && ob.open) return; // open doors let sight through
const pts = (ob.points || []).map((p) => ({ x: p[0], y: p[1] }));
for (let i = 0; i < pts.length - 1; i++) segs.push({ a: pts[i], b: pts[i + 1] });
});
const w = state.imageWidth || 0;
const h = state.imageHeight || 0;
segs.push({ a: { x: 0, y: 0 }, b: { x: w, y: 0 } });
segs.push({ a: { x: w, y: 0 }, b: { x: w, y: h } });
segs.push({ a: { x: w, y: h }, b: { x: 0, y: h } });
segs.push({ a: { x: 0, y: h }, b: { x: 0, y: 0 } });
return segs;
}
// Nearest hit of a ray (origin + t*dir, t>=0) against a segment. Returns { t, x, y } or null.
// Solves origin + t*dir = a + u*(b-a) for t>=0 and u in [0,1].
function rayHit(origin, dir, seg) {
const sdx = seg.b.x - seg.a.x;
const sdy = seg.b.y - seg.a.y;
const denom = dir.x * sdy - dir.y * sdx;
if (Math.abs(denom) < 1e-9) return null; // parallel
const t = ((seg.a.x - origin.x) * sdy - (seg.a.y - origin.y) * sdx) / denom;
const u = ((seg.a.x - origin.x) * dir.y - (seg.a.y - origin.y) * dir.x) / denom;
if (t < 1e-6 || u < -1e-9 || u > 1 + 1e-9) return null;
return { t, x: origin.x + dir.x * t, y: origin.y + dir.y * t };
}
// Compute the visibility polygon from `origin` (native) against `segments`. Casts three rays
// at each segment endpoint (its angle and +/- a tiny epsilon) so the polygon peeks just past
// corners to the wall behind, then sorts the nearest hits by angle into a closed fan.
function castVisibility(origin, segments) {
const EPS = 1e-4;
const angles = [];
segments.forEach((s) => {
[s.a, s.b].forEach((p) => {
const base = Math.atan2(p.y - origin.y, p.x - origin.x);
angles.push(base - EPS, base, base + EPS);
});
});
const hits = [];
angles.forEach((ang) => {
const dir = { x: Math.cos(ang), y: Math.sin(ang) };
let best = null;
for (const seg of segments) {
const h = rayHit(origin, dir, seg);
if (h && (!best || h.t < best.t)) best = h;
}
if (best) hits.push({ x: best.x, y: best.y, ang: Math.atan2(best.y - origin.y, best.x - origin.x) });
});
hits.sort((p, q) => p.ang - q.ang);
return hits;
}
// Cached accessor: returns the visibility polygon for `origin`, recomputing only when the
// origin (rounded to 1px) or the sight geometry (castVersion) has changed since last time.
// Registers the key as used this frame so render() can prune the cache to live origins.
function getVisibilityPolygon(origin) {
const key = castVersion + "|" + Math.round(origin.x) + "|" + Math.round(origin.y);
castFrameKeys.add(key);
const cached = castCache.get(key);
if (cached) return cached;
const polygon = castVisibility(origin, sightSegments());
castCache.set(key, polygon);
return polygon;
}
// LoS (5b): one visibility polygon per player-type token — the players' shared field of view.
// The tokens whose sight is unioned into the player's visible area, chosen by state.los.source. This
// is the single seam the per-token-vision feature grows from: "party" (default) is every player
// token — the original behaviour — and later sources ("active" combatant, "selected" token for a GM
// preview) add cases here. An unknown or missing source falls back to party, so the default and any
// older save with no source field behave exactly as before.
function visionOriginTokens() {
const players = state.tokens.filter((t) => t.type === "player");
switch (state.los?.source) {
case "active": {
// Vision follows the turn order: while it's a PLAYER character's turn, the table sees only
// what that character sees. Any other moment — a monster's turn, no combatants, initiative
// off, or the active combatant standing on a floor other than the table's — falls through to
// the party union below, so players never see through a monster's eyes and never lose all
// sight. (players.find resolves all of those at once: a non-player or off-floor id simply
// isn't in the player set, so tok is undefined and we return the party.)
const id = activeTurnTokenId();
const tok = id && players.find((t) => t.id === id);
return tok ? [tok] : players;
}
case "party":
default:
return players;
}
}
function playerVisionPolygons() {
const polys = [];
visionOriginTokens().forEach((t) => {
const poly = getVisibilityPolygon({ x: t.x, y: t.y });
if (poly.length >= 3) polys.push(poly);
});
return polys;
}
// A visibility polygon as a Path2D in fog-buffer resolution (native px * fogBuf.resScale), matching
// roomPathFog so the LoS mask lines up with the fog layers it composites alongside.
function losPath(points) {
const path = new Path2D();
if (!points.length) return path;
path.moveTo(points[0].x * fogBuf.resScale, points[0].y * fogBuf.resScale);
for (let i = 1; i < points.length; i++) path.lineTo(points[i].x * fogBuf.resScale, points[i].y * fogBuf.resScale);
path.closePath();
return path;
}
// Native segments that block LIGHT (blocksLight; windows pass light), plus the map edges.
function lightSegments() {
const segs = [];
state.obstacles.forEach((ob) => {
if (ob.blocksLight === false) return;
if (ob.kind === "door" && ob.open) return; // open doors let light through
const pts = (ob.points || []).map((p) => ({ x: p[0], y: p[1] }));
for (let i = 0; i < pts.length - 1; i++) segs.push({ a: pts[i], b: pts[i + 1] });
});
const w = state.imageWidth || 0;
const h = state.imageHeight || 0;
segs.push({ a: { x: 0, y: 0 }, b: { x: w, y: 0 } });
segs.push({ a: { x: w, y: 0 }, b: { x: w, y: h } });
segs.push({ a: { x: w, y: h }, b: { x: 0, y: h } });
segs.push({ a: { x: 0, y: h }, b: { x: 0, y: 0 } });
return segs;
}
// Cached wall-occluded visibility polygon cast from a light; lights are static so this is reused
// until geometry or the light set changes (lightCache is cleared by invalidateCast).
// Every light source on the floor as { pos (native), radius (native px) }: placed lights
// (5d-1, native px) and token-carried torches (5d-2, at the token's position).
// Axis-aligned native-space bounds of what's currently on screen — the four canvas corners mapped
// back through the view (rotation handled; the AABB is a safe over-estimate). Used to cull lights
// whose glow can't reach the view.
function visibleNativeBounds() {
const rect = canvas.getBoundingClientRect();
const pts = [
screenToNative({ x: 0, y: 0 }),
screenToNative({ x: rect.width, y: 0 }),
screenToNative({ x: 0, y: rect.height }),
screenToNative({ x: rect.width, y: rect.height }),
];
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const p of pts) {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
}
return { minX, minY, maxX, maxY };
}
// Every light source whose reach can touch the current view: placed lights (5d-1, native px) and
// token-carried torches (5d-2, at the token's position). Off-screen lights are culled — a torch
// three caverns away neither casts nor paints, which is what keeps a light-dense module (87 lights
// in Caves of Chaos) cheap when zoomed to the party. A light counts as in-view when its [pos ±
// radius] box overlaps the viewport box, so glow spilling in from a just-off-screen source survives.
function lightSources() {
const ppc = pxPerCellNative();
const b = visibleNativeBounds();
const reaches = (x, y, r) => x + r >= b.minX && x - r <= b.maxX && y + r >= b.minY && y - r <= b.maxY;
const sources = [];
state.lights.forEach((l) => {
const r = l.radius || 0;
if (reaches(l.x, l.y, r)) sources.push({ pos: { x: l.x, y: l.y }, radius: r, color: l.color || LIGHT_DEFAULT_COLOR });
});
state.tokens.forEach((t) => {
if ((t.light || 0) <= 0) return;
const r = t.light * ppc;
if (reaches(t.x, t.y, r)) sources.push({ pos: { x: t.x, y: t.y }, radius: r, color: t.lightColor || LIGHT_DEFAULT_COLOR });
});
return sources;
}
// ── light radius culling (uniform spatial grid) ──────────────────────────────
// castVisibility is O(6·N²) in the segment count N. A light only illuminates out to
// its radius, so casting against the whole floor (≈8,600 segments on Caves of Chaos)
// is wasted: the radial gradient clips visible reach to R regardless. We bucket the
// light-blocking segments into a uniform grid once per castVersion, then each light
// casts only against segments whose AABB overlaps its [pos ± R] box, plus a synthetic
// box at extent R so rays always close. The drop is EXACT, not approximate: a segment
// whose AABB lies fully outside the R-square is > R away (outside the axis-aligned
// square ⟹ Euclidean distance > R), so it can never be hit within R — the lit pixels
// are identical, only the invisible polygon tail beyond R changes.
const LIGHT_GRID_CELL_CELLS = 4; // bucket size in map cells (× pxPerCellNative → native px)
let _lightGrid = null; // { cell, cols, rows, minX, minY, buckets:Map<int,segIndex[]>, segs }
let _lightGridVersion = -1; // the castVersion the grid was built for
// (Re)build the bucket grid for the current castVersion. One O(N) pass that every
// light cast this frame reuses; the version gate clears it when geometry changes.
function lightGrid() {
if (_lightGrid && _lightGridVersion === castVersion) return _lightGrid;
const segs = lightSegments();
const cell = Math.max(1, LIGHT_GRID_CELL_CELLS * pxPerCellNative());
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
for (const s of segs) {
if (s.a.x < minX) minX = s.a.x; if (s.b.x < minX) minX = s.b.x;
if (s.a.y < minY) minY = s.a.y; if (s.b.y < minY) minY = s.b.y;
if (s.a.x > maxX) maxX = s.a.x; if (s.b.x > maxX) maxX = s.b.x;
if (s.a.y > maxY) maxY = s.a.y; if (s.b.y > maxY) maxY = s.b.y;
}
if (!segs.length) { minX = minY = maxX = maxY = 0; }
const cols = Math.max(1, Math.ceil((maxX - minX) / cell) + 1);
const rows = Math.max(1, Math.ceil((maxY - minY) / cell) + 1);
const buckets = new Map();
segs.forEach((s, i) => {
const cx0 = Math.floor((Math.min(s.a.x, s.b.x) - minX) / cell);
const cy0 = Math.floor((Math.min(s.a.y, s.b.y) - minY) / cell);
const cx1 = Math.floor((Math.max(s.a.x, s.b.x) - minX) / cell);
const cy1 = Math.floor((Math.max(s.a.y, s.b.y) - minY) / cell);
for (let cy = cy0; cy <= cy1; cy++) {
for (let cx = cx0; cx <= cx1; cx++) {
const k = cy * cols + cx;
let arr = buckets.get(k);
if (!arr) { arr = []; buckets.set(k, arr); }
arr.push(i);
}
}
});
_lightGrid = { cell, cols, rows, minX, minY, buckets, segs };
_lightGridVersion = castVersion;
return _lightGrid;
}
// Segments whose AABB overlaps the light's [pos ± R] box. AABB-overlap (NOT
// endpoint-inside) so a wall straddling the box edge is kept — dropping it would leak
// light. A few far-AABB segments may survive the grid query; the explicit overlap
// test trims those, and any that remain are harmless (conservative, never under-keeps).
function segmentsNearLight(pos, radius) {
const g = lightGrid();
const bMinX = pos.x - radius, bMinY = pos.y - radius;
const bMaxX = pos.x + radius, bMaxY = pos.y + radius;
const cx0 = Math.max(0, Math.floor((bMinX - g.minX) / g.cell));
const cy0 = Math.max(0, Math.floor((bMinY - g.minY) / g.cell));
const cx1 = Math.min(g.cols - 1, Math.floor((bMaxX - g.minX) / g.cell));
const cy1 = Math.min(g.rows - 1, Math.floor((bMaxY - g.minY) / g.cell));
const seen = new Set();
const out = [];
for (let cy = cy0; cy <= cy1; cy++) {
for (let cx = cx0; cx <= cx1; cx++) {
const arr = g.buckets.get(cy * g.cols + cx);
if (!arr) continue;
for (const i of arr) {
if (seen.has(i)) continue;
seen.add(i);
const s = g.segs[i];
if (Math.max(s.a.x, s.b.x) < bMinX || Math.min(s.a.x, s.b.x) > bMaxX) continue;
if (Math.max(s.a.y, s.b.y) < bMinY || Math.min(s.a.y, s.b.y) > bMaxY) continue;
out.push(s);
}
}
}
return out;
}
// Four segments forming the light's radius box — ray terminators so a ray that escapes
// every nearby wall still closes locally instead of shooting to the map edge. Extent R:
// the box sits at the radius, where the gradient alpha is already 0, so it paints nothing
// visible. Wound as a closed loop a→b→c→d→a.
function lightBoxSegments(pos, r) {
const p0 = { x: pos.x - r, y: pos.y - r }, p1 = { x: pos.x + r, y: pos.y - r };
const p2 = { x: pos.x + r, y: pos.y + r }, p3 = { x: pos.x - r, y: pos.y + r };
return [{ a: p0, b: p1 }, { a: p1, b: p2 }, { a: p2, b: p3 }, { a: p3, b: p0 }];
}
// Cached wall-occluded visibility polygon cast from a light. With radius culling the
// cast now depends on R (it bounds the segment set and the terminator box), so the cache
// key carries R — the version|lx|ly|radius shape state.js already anticipates. Lights are
// static, so an entry is reused until geometry changes (invalidateCast clears lightCache).
function getLightPolygon(pos, radius) {
const r = Math.max(0, radius || 0);
const key = castVersion + "|" + Math.round(pos.x) + "|" + Math.round(pos.y) + "|" + Math.round(r);
lightFrameKeys.add(key);
let poly = lightCache.get(key);
if (!poly) {
const segs = segmentsNearLight(pos, r).concat(lightBoxSegments(pos, r));
const t0 = window.VWAG_PERF ? performance.now() : 0; // dev hook: VWAG_PERF=true in console
poly = castVisibility(pos, segs);
lightCache.set(key, poly);
if (window.VWAG_PERF) {
const p = (window.__perf = window.__perf || { casts: 0, totalSegs: 0, totalMs: 0, floorSegs: 0, _last: 0 });
p.casts++;
p.totalSegs += segs.length; // segments this cast saw (culled set + 4 box)
p.totalMs += performance.now() - t0;
p.floorSegs = _lightGrid ? _lightGrid.segs.length : 0; // full floor N, for the ratio
const now = performance.now();
if (now - p._last > 400) { // throttle: at most ~2 lines/sec
p._last = now;
const avgSegs = (p.totalSegs / p.casts).toFixed(0);
const avgMs = (p.totalMs / p.casts).toFixed(3);
const speedup = p.floorSegs ? Math.round((p.floorSegs * p.floorSegs) / ((p.totalSegs / p.casts) ** 2)) : 0;
console.log(`[perf] ${p.casts} casts · ${avgSegs} segs/cast vs ${p.floorSegs} floor · ${avgMs}ms/cast · ~${speedup}x per-light speedup`);
}
}
}
return poly;
}
// Union every light's coverage into lightCanvas (fog-buffer resolution): the wall-occluded polygon
// painted with a radial gradient — white (full reveal) out to the bright core, fading to transparent
// at the rim. The gradient bounds the reach (no separate circle clip needed) and the alpha falloff
// flows through compositeLoS's destination-out, giving a bright center and a soft dim halo (5d-3).
function buildLightCoverage() {
lightCtx.setTransform(1, 0, 0, 1, 0, 0);
lightCtx.clearRect(0, 0, lightCanvas.width, lightCanvas.height);
lightSources().forEach(({ pos, radius }) => {
const poly = getLightPolygon(pos, radius);
if (poly.length < 3 || radius <= 0) return;
const cx = pos.x * fogBuf.resScale;
const cy = pos.y * fogBuf.resScale;
const rOuter = radius * fogBuf.resScale;
const grad = lightCtx.createRadialGradient(cx, cy, rOuter * LIGHT_BRIGHT_FRACTION, cx, cy, rOuter);
grad.addColorStop(0, "rgba(255,255,255,1)");
grad.addColorStop(1, "rgba(255,255,255,0)");
lightCtx.save();
lightCtx.fillStyle = grad;
lightCtx.fill(losPath(poly));
lightCtx.restore();
});
}
// 5e: paint every light's wall-occluded reach into tintCanvas in its own color, the alpha falling
// from LIGHT_TINT_CORE_ALPHA at the bright core to 0 at the rim — the colored counterpart to
// buildLightCoverage. tintCanvas is sized with the other fog buffers (resizeFogLayer), so it always
// matches lightCanvas. Takes the already-computed source list to avoid recomputing positions.
function buildLightTint(sources) {
tintCtx.setTransform(1, 0, 0, 1, 0, 0);
tintCtx.clearRect(0, 0, tintCanvas.width, tintCanvas.height);
sources.forEach(({ pos, radius, color }) => {
const poly = getLightPolygon(pos, radius);
if (poly.length < 3 || radius <= 0) return;
const cx = pos.x * fogBuf.resScale;
const cy = pos.y * fogBuf.resScale;
const rOuter = radius * fogBuf.resScale;
const grad = tintCtx.createRadialGradient(cx, cy, rOuter * LIGHT_BRIGHT_FRACTION, cx, cy, rOuter);
grad.addColorStop(0, hexToRgba(color, LIGHT_TINT_CORE_ALPHA));
grad.addColorStop(1, hexToRgba(color, 0));
tintCtx.save();
tintCtx.fillStyle = grad;
tintCtx.fill(losPath(poly));
tintCtx.restore();
});
}
// 5e: composite the colored-light glow over the map additively (`lighter`), on BOTH the GM and the
// player view, drawn under the tokens so minis stay readable. Always-on: a brazier glows whether or
// not darkness is enabled. On the player view the later LoS/darkness overlay clips the glow to what
// the party can currently see, so unseen rooms don't light up. Native-space draw, mirroring
// compositeLoS's scale from fog-buffer resolution to the full image.
function compositeLightTint() {
const sources = lightSources();
if (!sources.length) return;
buildLightTint(sources);
ctx.save();
ctx.globalCompositeOperation = "lighter";
ctx.imageSmoothingEnabled = true;
ctx.drawImage(tintCanvas, 0, 0, tintCanvas.width, tintCanvas.height, 0, 0, state.imageWidth, state.imageHeight);
ctx.restore();
}
function hitLight(native) {
const ppc = pxPerCellNative();
let best = null;
let bestDist = Math.max(12, ppc / 2);
state.lights.forEach((light) => {
const p = { x: light.x, y: light.y };
const d = Math.hypot(native.x - p.x, native.y - p.y);
if (d < bestDist) { bestDist = d; best = light; }
});
return best;
}
// GM-only markers: a glow dot plus a dashed radius ring so the GM can see each light's reach.
function drawLights() {
if (isPlayer || (!state.lights.length && !state.tokens.some((t) => (t.light || 0) > 0))) return;
const ppc = pxPerCellNative();
ctx.save();
// Token-carried torches (5d-2): faint reach ring around the token, no center marker.
state.tokens.forEach((t) => {
if ((t.light || 0) <= 0) return;
ctx.beginPath();
ctx.arc(t.x, t.y, t.light * ppc, 0, Math.PI * 2);
ctx.strokeStyle = hexToRgba(t.lightColor, 0.35);
ctx.lineWidth = 1.5 / (cur.k * cur.ms);
ctx.setLineDash([5 / (cur.k * cur.ms), 6 / (cur.k * cur.ms)]);
ctx.stroke();
ctx.setLineDash([]);
});
state.lights.forEach((light) => {
const p = { x: light.x, y: light.y };
const rNative = light.radius || 0;
ctx.beginPath();
ctx.arc(p.x, p.y, rNative, 0, Math.PI * 2);
ctx.strokeStyle = hexToRgba(light.color, 0.45);
ctx.lineWidth = 1.5 / (cur.k * cur.ms);
ctx.setLineDash([6 / (cur.k * cur.ms), 5 / (cur.k * cur.ms)]);
ctx.stroke();
ctx.setLineDash([]);
ctx.beginPath();
ctx.arc(p.x, p.y, 6 / (cur.k * cur.ms), 0, Math.PI * 2);
ctx.fillStyle = hexToRgba(light.color, 0.95);
ctx.fill();
ctx.strokeStyle = "rgba(70,45,0,0.85)";
ctx.lineWidth = 1 / (cur.k * cur.ms);
ctx.stroke();
});
ctx.restore();
}
// The current floor's explored canvas, lazily created at the fog-buffer resolution. Runtime-only:
// it lives in memory keyed by floor and is gone on reload (persisting it to the save file is a
// later chunk). If the fog buffer resized, the old memory is rescaled into the new dimensions.
function getExploredCanvas() {
const id = state.currentFloorId;
let c = exploredMasks.get(id);
if (!c || c.width !== losCanvas.width || c.height !== losCanvas.height) {
const nc = document.createElement("canvas");
nc.width = losCanvas.width;
nc.height = losCanvas.height;
if (c && c.width && c.height) nc.getContext("2d").drawImage(c, 0, 0, c.width, c.height, 0, 0, nc.width, nc.height);
c = nc;
exploredMasks.set(id, c);
}
return c;
}
// Player-view only: the three-state fog of war. Builds the current visibility mask, folds it into
// the floor's explored memory, then paints a darkness overlay — unexplored stays black, explored
// is dimmed to state.los.brightness, and currently-visible is fully clear. Fails open with no eyes.
// The hand-painted fog (compositeFog) still draws over this, so the GM can re-hide anything.
function compositeLoS() {
const polys = playerVisionPolygons();
if (!polys.length) return; // fail-open: no player tokens, show everything
// Current visibility, opaque where seen.
losCtx.setTransform(1, 0, 0, 1, 0, 0);
losCtx.clearRect(0, 0, losCanvas.width, losCanvas.height);
losCtx.fillStyle = "#ffffff";
polys.forEach((poly) => losCtx.fill(losPath(poly)));
// 5d: under darkness, you only see where line-of-sight AND light overlap.
if (state.los.darkness) {
buildLightCoverage();
losCtx.save();
losCtx.globalCompositeOperation = "destination-in";
losCtx.drawImage(lightCanvas, 0, 0);
losCtx.restore();
}
// Fold this frame's visibility into the floor's running memory.
const explored = getExploredCanvas();
const ectx = explored.getContext("2d");
ectx.globalCompositeOperation = "source-over";
ectx.drawImage(losCanvas, 0, 0);
// Darkness overlay: black everywhere, lift explored to a dim level, lift visible fully clear.
darkCtx.setTransform(1, 0, 0, 1, 0, 0);
darkCtx.clearRect(0, 0, darkCanvas.width, darkCanvas.height);
darkCtx.fillStyle = "#080909";
darkCtx.fillRect(0, 0, darkCanvas.width, darkCanvas.height);
darkCtx.save();
darkCtx.globalCompositeOperation = "destination-out";
darkCtx.globalAlpha = Math.max(0, Math.min(1, state.los.brightness ?? 0.5)); // explored -> dim
darkCtx.drawImage(explored, 0, 0);
darkCtx.globalAlpha = 1; // visible -> clear
darkCtx.drawImage(losCanvas, 0, 0);
darkCtx.restore();
ctx.save();
ctx.imageSmoothingEnabled = true;
ctx.drawImage(darkCanvas, 0, 0, darkCanvas.width, darkCanvas.height, 0, 0, state.imageWidth, state.imageHeight);
ctx.restore();
}
export {
invalidateCast, rayHit, castVisibility, getVisibilityPolygon, playerVisionPolygons, losPath, lightSegments, lightSources, compositeLightTint,
getLightPolygon, buildLightCoverage, hitLight, drawLights, compositeLoS, getExploredCanvas, sightSegments, castVersion,
};