drone-path 0.8.1 → 0.10.0

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +18 -25
  3. package/THIRD-PARTY-NOTICES.md +14 -7
  4. package/app/ipc.mjs +178 -0
  5. package/app/main.mjs +10 -150
  6. package/app/preload.cjs +3 -0
  7. package/dist/appassets.js +2 -11
  8. package/dist/apppaths.js +2 -10
  9. package/dist/appsession.js +59 -59
  10. package/dist/appstate.js +22 -38
  11. package/dist/assets.js +0 -7
  12. package/dist/buildinfo.js +71 -0
  13. package/dist/cammeta.js +127 -89
  14. package/dist/changeset-gate.js +0 -7
  15. package/dist/cli.js +3 -36
  16. package/dist/config.js +216 -167
  17. package/dist/configfile.js +0 -8
  18. package/dist/decimate.js +2 -12
  19. package/dist/exportjob.js +3 -19
  20. package/dist/ff.js +2 -27
  21. package/dist/fftools.js +0 -10
  22. package/dist/frametime.js +32 -0
  23. package/dist/geo.js +3 -13
  24. package/dist/inputs.js +0 -4
  25. package/dist/manual/anchors.js +1 -7
  26. package/dist/manual/build.js +0 -6
  27. package/dist/manual/cliref.js +0 -6
  28. package/dist/manual/links.js +0 -17
  29. package/dist/manual/markdown.js +2 -10
  30. package/dist/manual/model.js +0 -3
  31. package/dist/manual/module.js +0 -3
  32. package/dist/manual/nav.js +0 -2
  33. package/dist/manual/reference.js +1 -4
  34. package/dist/page.js +3 -26
  35. package/dist/paths.js +0 -12
  36. package/dist/plan.js +1 -18
  37. package/dist/png.js +1 -21
  38. package/dist/proto.js +4 -4
  39. package/dist/range.js +0 -8
  40. package/dist/render.js +38 -165
  41. package/dist/renderer/dom.js +0 -6
  42. package/dist/renderer/framemath.js +0 -4
  43. package/dist/renderer/scene.js +10 -34
  44. package/dist/renderer/theme.js +58 -10
  45. package/dist/renderer/tilesources.js +0 -10
  46. package/dist/renderer/trail.js +1 -12
  47. package/dist/restyle.js +1 -9
  48. package/dist/run.js +79 -143
  49. package/dist/serve.js +0 -13
  50. package/dist/srt.js +30 -8
  51. package/dist/summary.js +0 -3
  52. package/dist/telemetry-json-schema.js +23 -0
  53. package/dist/telemetry-json.js +113 -0
  54. package/dist/telemetry-math.js +11 -46
  55. package/dist/telemetry.js +58 -11
  56. package/dist/tilecache.js +0 -5
  57. package/dist/tiles.js +31 -117
  58. package/package.json +15 -13
  59. package/dist/renderer/leaflet.js +0 -5
  60. package/dist/tracing.js +0 -208
package/dist/proto.js CHANGED
@@ -1,5 +1,3 @@
1
- // Just enough of the format for the DJI DVTM messages: varint, fixed64,
2
- // fixed32 and length-delimited fields, one nesting level at a time.
3
1
  const MAX_VARINT_BYTES = 10;
4
2
  function readVarint(buf, pos, end) {
5
3
  let value = 0n;
@@ -14,7 +12,6 @@ function readVarint(buf, pos, end) {
14
12
  }
15
13
  return null;
16
14
  }
17
- /** Interpret a 64-bit varint as a signed integer. */
18
15
  function signedVarint(value) {
19
16
  return Number(BigInt.asIntN(64, value));
20
17
  }
@@ -80,7 +77,6 @@ function pushField(fields, fieldNumber, field) {
80
77
  else
81
78
  fields.set(fieldNumber, [field]);
82
79
  }
83
- /** Sub-messages are length-delimited fields; only the first occurrence is decoded. */
84
80
  export function subMessage(buf, fields, fieldNumber) {
85
81
  const field = fields.get(fieldNumber)?.[0];
86
82
  if (!field?.bytesSpan)
@@ -100,3 +96,7 @@ export function firstDouble(fields, fieldNumber) {
100
96
  const value = fields.get(fieldNumber)?.[0]?.doubleValue;
101
97
  return value ?? null;
102
98
  }
99
+ export function firstString(buf, fields, fieldNumber) {
100
+ const span = fields.get(fieldNumber)?.[0]?.bytesSpan;
101
+ return span ? buf.toString('utf8', span[0], span[1]) : null;
102
+ }
package/dist/range.js CHANGED
@@ -1,7 +1,3 @@
1
- // HTTP byte-range parsing and response planning (RFC 7233) shared by the
2
- // headless render server and the app's custom-scheme handler.
3
- // Malformed range headers are ignored (full response); only syntactically
4
- // valid but unsatisfiable ranges earn a 416.
5
1
  export function parseRange(header, size) {
6
2
  if (header === undefined)
7
3
  return null;
@@ -32,9 +28,6 @@ export function parseRange(header, size) {
32
28
  return 'unsatisfiable';
33
29
  return { start, end: Math.min(end, size - 1) };
34
30
  }
35
- // Everything both transports compute by hand for one Range request: status,
36
- // the response headers, and the byte span (or 416 body) to send. Only the
37
- // transport write is left to the caller.
38
31
  export function rangePlan(header, size, mime) {
39
32
  const range = parseRange(header, size);
40
33
  if (range === 'unsatisfiable') {
@@ -47,7 +40,6 @@ export function rangePlan(header, size, mime) {
47
40
  const headers = {
48
41
  'Content-Type': mime,
49
42
  'Accept-Ranges': 'bytes',
50
- // A URL-keyed cache must never replay stale bytes from this live local file.
51
43
  'Cache-Control': 'no-store',
52
44
  'Content-Length': String(range === null ? size : range.end - range.start + 1),
53
45
  };
package/dist/render.js CHANGED
@@ -1,20 +1,13 @@
1
- // Frames are captured by N parallel pages and streamed to ffmpeg's stdin in
2
- // exact frame order (no scratch frame files on disk). The headless browser is
3
- // the system Chrome/Edge via playwright-core - no browser download.
4
1
  import http from 'node:http';
5
2
  import { spawn } from 'node:child_process';
6
3
  import { once } from 'node:events';
7
4
  import { MIME } from './assets.js';
8
5
  import { errorMessage } from './errors.js';
9
6
  import { RENDERER_DIR, serveAsset } from './serve.js';
10
- import { NOOP_TRACER, stage } from './tracing.js';
11
7
  const PAGE_LOAD_TIMEOUT_MS = 60000;
12
8
  const SCREENSHOT_TIMEOUT_MS = 60000;
13
9
  function startServer({ html, style, tileCache, }) {
14
10
  const server = http.createServer((req, res) => {
15
- // A malformed request URL (e.g. "GET /%") must not crash the render:
16
- // decodeURIComponent throws URIError, which would surface as an
17
- // uncaughtException inside this handler.
18
11
  let url;
19
12
  try {
20
13
  url = decodeURIComponent((req.url ?? '/').split('?')[0]);
@@ -47,8 +40,6 @@ async function launchBrowser(log, browserPath) {
47
40
  const attempts = [];
48
41
  if (browserPath)
49
42
  attempts.push({ executablePath: browserPath });
50
- // System Chrome/Edge first (nothing to download), then the Playwright
51
- // browser registry (usable after `npx playwright install chromium`).
52
43
  attempts.push({ channel: 'chrome' }, { channel: 'msedge' }, {});
53
44
  const attemptErrors = [];
54
45
  for (const opt of attempts) {
@@ -61,23 +52,17 @@ async function launchBrowser(log, browserPath) {
61
52
  attemptErrors.push(e);
62
53
  }
63
54
  }
64
- // Every attempt's failure survives in the cause chain; the message keeps
65
- // the final attempt's detail and the remediation steps.
66
55
  throw new Error(`could not launch a Chromium browser (tried explicit path, channel=chrome, channel=msedge, playwright registry): ${errorMessage(attemptErrors[attemptErrors.length - 1])}. ` +
67
56
  'Install Google Chrome or Microsoft Edge, run "npx playwright install chromium", ' +
68
57
  'or pass --browser <path>.', { cause: new AggregateError(attemptErrors, 'all browser launch attempts failed') });
69
58
  }
70
- // The quality level as an encoder CRF per codec (lower is better): x265's
71
- // CRF scale sits about five points above x264's for the same perceived
72
- // quality. h264 "high" is the CRF 18 that shipped before quality became
73
- // configurable.
59
+ // x265's CRF scale sits ~5 points above x264's for the same perceived quality.
74
60
  const CRF = {
75
61
  h264: { 'near-lossless': 16, high: 18, medium: 21, low: 26 },
76
62
  h265: { 'near-lossless': 20, high: 22, medium: 25, low: 30 },
77
63
  };
78
64
  function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
79
- // h265 gets the hvc1 sample tag: the ffmpeg-default hev1 tag is refused by
80
- // QuickTime and some NLEs.
65
+ // h265 gets hvc1: the ffmpeg-default hev1 tag is refused by QuickTime and some NLEs.
81
66
  const codecArgs = encode.codec === 'h265' ? ['-c:v', 'libx265', '-tag:v', 'hvc1'] : ['-c:v', 'libx264'];
82
67
  const ffmpegProcess = spawn(ffmpeg, [
83
68
  '-hide_banner', '-loglevel', 'error', '-y',
@@ -92,9 +77,7 @@ function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
92
77
  ffmpegProcess.stderr?.on('data', (d) => {
93
78
  stderr += d.toString();
94
79
  });
95
- // ffmpeg's stdin must never surface an unhandled 'error' (EPIPE when the
96
- // encoder exits early), and a worker parked on 'drain' must wake up when it
97
- // dies instead of waiting forever. `closed` also resolves for late waits.
80
+ // ffmpeg's stdin must never surface an unhandled 'error' (EPIPE on early exit); a drain-waiter must wake when the encoder dies.
98
81
  const closed = new Promise((resolve) => {
99
82
  ffmpegProcess.once('close', (code) => resolve(code));
100
83
  });
@@ -156,23 +139,14 @@ function screenshotOptions(capture) {
156
139
  timeout: SCREENSHOT_TIMEOUT_MS,
157
140
  };
158
141
  }
159
- // One frame: evaluate, screenshot, record and stream it into ffmpeg in
160
- // order.
161
142
  async function captureFrame(run, loop, page, idx) {
162
- // __setFrame resolves after the canvas painted (canvas drawing is
163
- // deferred to requestAnimationFrame); awaiting it keeps every
164
- // screenshot on the current frame.
165
143
  const evalStart = Date.now();
166
144
  await page.evaluate((frame) => globalThis.__setFrame(frame), run.frameStart + idx);
167
145
  run.timing.evalMs += Date.now() - evalStart;
168
146
  const captureStart = Date.now();
169
147
  const buf = await page.screenshot(screenshotOptions(run.capture));
170
- const captureMs = Date.now() - captureStart;
171
- run.timing.captureMs += captureMs;
172
- // The local count (not the shared one read after an await) keeps every
173
- // boundary event exactly-once under worker races.
148
+ run.timing.captureMs += Date.now() - captureStart;
174
149
  const done = ++loop.capturesDone;
175
- run.batches.recordFrame(done, captureMs);
176
150
  const emitStart = Date.now();
177
151
  await run.stream.submit(idx, buf);
178
152
  run.timing.emitMs += Date.now() - emitStart;
@@ -181,7 +155,6 @@ async function captureFrame(run, loop, page, idx) {
181
155
  run.onCapture?.({ done, total: run.frames });
182
156
  }
183
157
  }
184
- // One worker's page and frame loop.
185
158
  async function workerLoop(run, loop, workerId) {
186
159
  const page = await run.active.newPage({
187
160
  viewport: { width: run.width, height: run.height },
@@ -191,8 +164,6 @@ async function workerLoop(run, loop, workerId) {
191
164
  await page.goto(run.url, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT_MS });
192
165
  await page.waitForFunction('window.__READY === true', null, { timeout: PAGE_LOAD_TIMEOUT_MS });
193
166
  for (;;) {
194
- // A doomed render stops at the next frame: survivors have to settle
195
- // before the batch and capture spans are wound down.
196
167
  if (loop.failed)
197
168
  return;
198
169
  if (run.signal?.aborted)
@@ -208,9 +179,6 @@ async function workerLoop(run, loop, workerId) {
208
179
  }
209
180
  run.log(`worker ${workerId} done`);
210
181
  }
211
- // The frame loop: workers race for frame indices and stream every capture
212
- // into ffmpeg in exact order. allSettled, not all: the batch spans and the
213
- // captured-frame count must be final before the capture span is wound down.
214
182
  async function runWorkers(run, workerCount) {
215
183
  const loop = { cursor: 0, capturesDone: 0, failed: false };
216
184
  const settled = await Promise.allSettled(Array.from({ length: workerCount }, (_, i) => workerLoop(run, loop, i + 1).catch((e) => {
@@ -218,17 +186,13 @@ async function runWorkers(run, workerCount) {
218
186
  throw e;
219
187
  })));
220
188
  const rejected = settled.find((r) => r.status === 'rejected');
221
- run.batches.close(rejected?.reason);
222
- run.captureSpan.setAttribute('render.frames.captured', loop.capturesDone);
223
189
  if (rejected)
224
190
  throw rejected.reason;
225
191
  }
226
- async function finishEncode(encoder, stream, encodeSpan, log, outPath) {
192
+ async function finishEncode(encoder, stream, log, outPath) {
227
193
  await stream.flushReady();
228
194
  stream.end();
229
- // `closed` (not `once(ffmpeg, 'close')`): ffmpeg may already have exited.
230
195
  const code = await encoder.closed;
231
- encodeSpan.setAttribute('render.ffmpeg.exitCode', code ?? -1);
232
196
  if (code !== 0) {
233
197
  throw new Error(`ffmpeg exited with code ${code}: ${encoder.stderrText().trim()}`);
234
198
  }
@@ -238,97 +202,29 @@ function formatProfile(profile, workerCount) {
238
202
  return (`profile: eval=${(profile.evalMs / 1000).toFixed(1)}s capture=${(profile.captureMs / 1000).toFixed(1)}s ` +
239
203
  `encode-backpressure=${(profile.emitMs / 1000).toFixed(1)}s (summed over ${workerCount} workers)`);
240
204
  }
241
- // One `render.capture.batch` subspan per cadence of captured frames, carrying
242
- // the per-frame capture spread of that batch. Per-frame spans would bury the
243
- // trace in thousands of near-identical spans and overflow the exporter queue.
244
- export class FrameBatchRecorder {
245
- tracer;
246
- parent;
247
- frames;
248
- cadence;
249
- openSpan = null;
250
- durations = [];
251
- closed = false;
252
- constructor(tracer, parent, frames, cadence = 100) {
253
- this.tracer = tracer;
254
- this.parent = parent;
255
- this.frames = frames;
256
- this.cadence = cadence;
257
- }
258
- recordFrame(capturedSoFar, captureMs) {
259
- // close() is permanent: a straggling frame must not re-open a batch under
260
- // the already-ended capture span.
261
- if (this.closed)
262
- return;
263
- this.openSpan ??= this.tracer.startSpan('render.capture.batch', {
264
- parent: this.parent,
265
- });
266
- this.durations.push(captureMs);
267
- const boundary = capturedSoFar % this.cadence === 0 || capturedSoFar === this.frames;
268
- if (!boundary)
269
- return;
270
- const span = this.openSpan;
271
- const durations = this.durations;
272
- this.openSpan = null;
273
- this.durations = [];
274
- span.setAttribute('render.frames.captured', capturedSoFar);
275
- span.setAttribute('render.frame.minMs', Math.min(...durations));
276
- span.setAttribute('render.frame.avgMs', Math.round((durations.reduce((a, b) => a + b, 0) / durations.length) * 10) / 10);
277
- span.setAttribute('render.frame.maxMs', Math.max(...durations));
278
- span.end();
279
- }
280
- // A half-open batch at close time is normal (nothing in flight).
281
- close(error) {
282
- if (this.closed)
283
- return;
284
- this.closed = true;
285
- if (this.openSpan === null)
286
- return;
287
- if (error !== undefined)
288
- this.openSpan.fail(error);
289
- this.openSpan.end();
290
- this.openSpan = null;
291
- this.durations = [];
292
- }
293
- }
294
- // The encode span encloses the capture span on purpose: frames stream into
295
- // ffmpeg while they are still being captured, and the trace must show that
296
- // overlap.
297
205
  async function captureAndEncode(active, env) {
298
- const { ctx, tracer, renderSpan, url, timing, workerCount } = env;
206
+ const { ctx, url, timing, workerCount } = env;
299
207
  const { fpsStr, codec, quality, preset, outPath, signal, width, height, frames, frameStart, capture, log, onCapture, tools, } = ctx;
300
208
  const encoder = spawnEncoder(tools.ffmpeg, fpsStr, { codec, quality, preset }, outPath);
301
- // A cancel must reach the encoder directly: a worker parked on stdin
302
- // backpressure would otherwise never notice the abort.
303
209
  const killOnAbort = () => encoder.kill();
304
210
  signal?.addEventListener('abort', killOnAbort, { once: true });
305
211
  const stream = new OrderedFrameStream(encoder);
306
212
  try {
307
- await stage(tracer, 'render.encode', renderSpan, {
308
- 'render.codec': codec,
309
- 'render.quality': quality,
310
- 'render.preset': preset,
311
- }, async (encodeSpan) => {
312
- await stage(tracer, 'render.capture', renderSpan, {}, async (captureSpan) => {
313
- await runWorkers({
314
- active,
315
- url,
316
- width,
317
- height,
318
- frames,
319
- frameStart,
320
- capture,
321
- signal,
322
- log,
323
- onCapture,
324
- stream,
325
- batches: new FrameBatchRecorder(tracer, captureSpan, frames),
326
- timing,
327
- captureSpan,
328
- }, workerCount);
329
- });
330
- await finishEncode(encoder, stream, encodeSpan, log, outPath);
331
- });
213
+ await runWorkers({
214
+ active,
215
+ url,
216
+ width,
217
+ height,
218
+ frames,
219
+ frameStart,
220
+ capture,
221
+ signal,
222
+ log,
223
+ onCapture,
224
+ stream,
225
+ timing,
226
+ }, workerCount);
227
+ await finishEncode(encoder, stream, log, outPath);
332
228
  }
333
229
  catch (e) {
334
230
  encoder.kill();
@@ -338,31 +234,18 @@ async function captureAndEncode(active, env) {
338
234
  signal?.removeEventListener('abort', killOnAbort);
339
235
  }
340
236
  }
341
- // The profile stage: fold the summed stage timings into what the caller gets,
342
- // mirrored on the render span and in the log.
343
237
  function reportProfile(env) {
344
- const { ctx, timing, renderSpan, workerCount } = env;
238
+ const { ctx, timing, workerCount } = env;
345
239
  const profile = {
346
240
  evalMs: Math.round(timing.evalMs),
347
241
  captureMs: Math.round(timing.captureMs),
348
242
  emitMs: Math.round(timing.emitMs),
349
243
  };
350
- renderSpan.setAttributes({
351
- 'render.evalMs': profile.evalMs,
352
- 'render.captureMs': profile.captureMs,
353
- 'render.emitMs': profile.emitMs,
354
- });
355
244
  ctx.log(formatProfile(profile, workerCount));
356
245
  return { profile };
357
246
  }
358
- // Every output frame gets its own capture (held frames judder whenever the map
359
- // moves, so there is no frame-step option), streamed to ffmpeg in exact frame
360
- // order.
361
- // Traced as `render` over `render.capture` (+ batch subspans) and
362
- // `render.encode`; capture and encode overlap by design.
363
247
  export async function renderVideo(opts) {
364
- const { html, style, tileCache, width, height, frames, fpsStr, workers, outPath, log = () => { }, browserPath = null, tools, capture = 'jpeg', codec = 'h264', quality = 'high', preset = 'medium', frameStart = 0, signal, trace, onCapture, } = opts;
365
- const tracer = trace?.tracer ?? NOOP_TRACER;
248
+ const { html, style, tileCache, width, height, frames, fpsStr, workers, outPath, log = () => { }, browserPath = null, tools, capture = 'jpeg', codec = 'h264', quality = 'high', preset = 'medium', frameStart = 0, signal, onCapture, } = opts;
366
249
  const workerCount = Math.max(1, Math.min(workers, frames));
367
250
  const ctx = {
368
251
  width,
@@ -380,29 +263,19 @@ export async function renderVideo(opts) {
380
263
  onCapture,
381
264
  tools,
382
265
  };
383
- return stage(tracer, 'render', trace?.parent, {
384
- 'render.workers': workerCount,
385
- 'render.capture.mode': capture,
386
- 'render.codec': codec,
387
- 'render.quality': quality,
388
- 'render.preset': preset,
389
- }, async (renderSpan) => {
390
- if (signal?.aborted)
391
- throw new Error('render canceled');
392
- const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
393
- const { server, url } = await startServer({ html, style, tileCache });
394
- const env = { ctx, tracer, renderSpan, url, timing, workerCount };
395
- // The try spans startup as well: a browser-launch failure must still
396
- // close the server, whose listening socket would keep the process alive.
397
- let browser = null;
398
- try {
399
- browser = await launchBrowser(log, browserPath);
400
- await captureAndEncode(browser, env);
401
- }
402
- finally {
403
- await browser?.close().catch(() => { });
404
- server.close();
405
- }
406
- return reportProfile(env);
407
- });
266
+ if (signal?.aborted)
267
+ throw new Error('render canceled');
268
+ const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
269
+ const { server, url } = await startServer({ html, style, tileCache });
270
+ const env = { ctx, url, timing, workerCount };
271
+ let browser = null;
272
+ try {
273
+ browser = await launchBrowser(log, browserPath);
274
+ await captureAndEncode(browser, env);
275
+ }
276
+ finally {
277
+ await browser?.close().catch(() => { });
278
+ server.close();
279
+ }
280
+ return reportProfile(env);
408
281
  }
@@ -1,8 +1,3 @@
1
- // Renderer markup and styling, shared verbatim by the generated page and the
2
- // app's map islands so both look and measure identically. Element ids are the
3
- // renderer's DOM contract. The styles are scoped to one scene host each: the
4
- // app mounts two scenes at once (player island and export preview), so bare
5
- // selectors would let one scene's scale values restyle the other.
6
1
  export function sceneCss(src, theme, width, height, scale, scope) {
7
2
  const at = `.${scope}`;
8
3
  return `
@@ -123,7 +118,6 @@ export function droneMarkerMarkup(coreColor) {
123
118
  '" stroke="rgba(255,255,255,0.9)" stroke-width="0.9" stroke-linejoin="round"/></svg>' +
124
119
  '</div></div>');
125
120
  }
126
- /** Returns the element the renderer's DOM contract guarantees. */
127
121
  export function el(root, selector) {
128
122
  const found = root.querySelector(selector);
129
123
  if (!found)
@@ -1,5 +1,3 @@
1
- // Pure viewport and timeline math for the shared renderer. Kept free of DOM
2
- // and Leaflet so the frame-exact behaviors stay unit-testable.
3
1
  export function computeScale(width, height) {
4
2
  return Math.max(0.7, Math.min(2.2, Math.min(width, height) / 1024));
5
3
  }
@@ -7,7 +5,6 @@ export function smoothstep(t) {
7
5
  const clamped = Math.max(0, Math.min(1, t));
8
6
  return clamped * clamped * (3 - 2 * clamped);
9
7
  }
10
- // Intro/outro zoom-out: 0.5 = one zoom level further out, smoothstepped.
11
8
  export function introOutroScale(i, introN, outroN, totalN) {
12
9
  let kIn = 1;
13
10
  let kOut = 1;
@@ -22,7 +19,6 @@ export function introOutroScale(i, introN, outroN, totalN) {
22
19
  export function metersPerPixel(lat, zoom) {
23
20
  return (156543.033928 * Math.cos((lat * Math.PI) / 180)) / Math.pow(2, zoom);
24
21
  }
25
- // The map never zooms during a render, so the scale bar picks one step once.
26
22
  export function scaleBarMeters(mPerPx, maxPx) {
27
23
  const steps = [5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000];
28
24
  let best = steps[0];
@@ -1,16 +1,3 @@
1
- // The shared map renderer: it receives all telemetry inline (no fetch), paints
2
- // the map once, and exposes setFrame(i) for per-frame marker/trail updates.
3
- // Headless capture workers (via the generated page's window.__setFrame bridge)
4
- // and the app's React map island both drive this one implementation;
5
- // setFrame resolves after the canvas has painted so screenshots are
6
- // frame-exact. update(data) restyles in place for the app's settings panel,
7
- // rebuilding only the decorations the new settings actually invalidate.
8
- //
9
- // Views:
10
- // overview - static map fitted to the whole track (trail grows with time)
11
- // follow - drone marker stays in the frame center and the map slides under
12
- // it (all tiles are loaded once up-front; the per-frame move is a
13
- // pure CSS transform, so no tile loads happen mid-render)
14
1
  import { TILE_SOURCES } from './tilesources.js';
15
2
  import { droneMarkerMarkup, el, hudMarkup, mapMarkup, quietAttributionLinks, sceneCss } from './dom.js';
16
3
  import { computeScale, introOutroScale, metersPerPixel, scaleBarMeters } from './framemath.js';
@@ -24,9 +11,6 @@ function setChipText(chip, value, format) {
24
11
  return;
25
12
  chip.textContent = value === null || value === undefined ? '--' : format(value);
26
13
  }
27
- // Per-scene style scope: the app mounts two scenes at once (the player island
28
- // and the export preview), and one scene's scale values must never restyle the
29
- // other's elements.
30
14
  let scopeCount = 0;
31
15
  class SceneState {
32
16
  ready;
@@ -84,9 +68,7 @@ class SceneState {
84
68
  this.frameEl = el(host, '#map-frame');
85
69
  this.scalelineEl = el(host, '#scaleline');
86
70
  this.scaletextEl = el(host, '#scaletext');
87
- // Before the decorations below: Leaflet defers marker DOM creation until
88
- // the map has a view, so the arrow/wrap elements only exist after this
89
- // first call.
71
+ // Leaflet only creates marker DOM once the map has a view: layoutMap() must precede buildDecor() so the arrow/wrap elements exist.
90
72
  this.layoutMap();
91
73
  this.decor = this.buildDecor();
92
74
  this.rebuildHud();
@@ -110,12 +92,10 @@ class SceneState {
110
92
  return data.lat.map((la, i) => [la, data.lon[i]]);
111
93
  }
112
94
  applyChrome() {
113
- this.styleEl.textContent = sceneCss(TILE_SOURCES[this.data.style], themeFor(this.data.style), this.data.width, this.data.height, this.scale(), this.scopeClass);
95
+ this.styleEl.textContent = sceneCss(TILE_SOURCES[this.data.style], themeFor(this.data.style, this.data.trailColor), this.data.width, this.data.height, this.scale(), this.scopeClass);
114
96
  this.attrEl.innerHTML = this.data.attribution;
115
97
  quietAttributionLinks(this.attrEl);
116
98
  }
117
- // The map fills its frame at any size (headless: the export canvas; app:
118
- // the pane currently holding it), so every frame size change re-lays out.
119
99
  layoutMap() {
120
100
  const { data, map, mapEl, frameEl } = this;
121
101
  const vw = frameEl.clientWidth || data.width;
@@ -137,7 +117,6 @@ class SceneState {
137
117
  map.invalidateSize();
138
118
  map.setView(data.view === 'follow' ? this.bb.getCenter() : [data.center.lat, data.center.lon], data.zoom);
139
119
  const c0 = map.project(map.getCenter(), data.zoom);
140
- // Static scale bar (the map never zooms during a render).
141
120
  const latC = data.view === 'follow' ? this.bb.getCenter().lat : data.center.lat;
142
121
  const mPerPx = metersPerPixel(latC, data.zoom);
143
122
  const bestM = scaleBarMeters(mPerPx, 110 * this.scale());
@@ -172,11 +151,9 @@ class SceneState {
172
151
  layers.push(ghost);
173
152
  return layers;
174
153
  }
175
- // The live trail layers (empty until the controller fills them): glow,
176
- // casing and core, thickest first so the core stays on top.
154
+ // Creation order sets stacking: thickest first so the core stays on top.
177
155
  buildTrailLayers(theme) {
178
- // All geometry is pre-decimated (smoothFactor 0 skips Leaflet's own
179
- // simplification) and the canvas renderer keeps redraws rAF-batched.
156
+ // smoothFactor 0 keeps Leaflet from re-simplifying the pre-decimated path.
180
157
  const wCore = Math.max(3, 5.5 * this.scale());
181
158
  const trailGlow = this.L.polyline([], {
182
159
  color: theme.glow,
@@ -197,7 +174,7 @@ class SceneState {
197
174
  });
198
175
  trailCasing.addTo(this.map);
199
176
  const trail = this.L.polyline([], {
200
- color: theme.core,
177
+ color: theme.trailCore,
201
178
  weight: wCore,
202
179
  opacity: 1,
203
180
  lineCap: 'round',
@@ -230,7 +207,7 @@ class SceneState {
230
207
  return { startDot, drone };
231
208
  }
232
209
  buildDecor() {
233
- const theme = themeFor(this.data.style);
210
+ const theme = themeFor(this.data.style, this.data.trailColor);
234
211
  const s = this.scale();
235
212
  const ghostLatlngs = this.data.trailLat.map((la, i) => [la, this.data.trailLon[i]]);
236
213
  const ghostDash = Math.round(7 * s) + ' ' + Math.round(9 * s);
@@ -297,9 +274,7 @@ class SceneState {
297
274
  const k = introOutroScale(i, this.data.introN, this.data.outroN, this.data.lat.length);
298
275
  this.updateTransform(i, k);
299
276
  this.updateHud(i);
300
- // Canvas painting is deferred to requestAnimationFrame; the headless
301
- // capture awaits this barrier so screenshots never catch the previous
302
- // frame.
277
+ // Canvas painting is deferred to requestAnimationFrame
303
278
  return new Promise((resolve) => {
304
279
  requestAnimationFrame(() => {
305
280
  requestAnimationFrame(() => resolve());
@@ -318,14 +293,14 @@ class SceneState {
318
293
  this.bb = this.L.latLngBounds(this.latlngs);
319
294
  }
320
295
  const chromeChanged = next.style !== prev.style ||
296
+ next.trailColor !== prev.trailColor ||
321
297
  next.width !== prev.width ||
322
298
  next.height !== prev.height ||
323
299
  next.attribution !== prev.attribution;
324
300
  if (chromeChanged)
325
301
  this.applyChrome();
326
302
  if (next.style !== prev.style) {
327
- // The zoom constraints are per source (topo tiles are native to z17),
328
- // so a style switch swaps the layer instead of only its URL.
303
+ // Zoom constraints are per tile layer (topo is native to z17), so a style switch swaps the layer instead of only its URL.
329
304
  this.tiles.remove();
330
305
  this.tiles = this.makeTileLayer(next.tileUrl, next.style);
331
306
  this.tiles.addTo(this.map);
@@ -334,6 +309,7 @@ class SceneState {
334
309
  this.tiles.setUrl(next.tileUrl);
335
310
  }
336
311
  const decorInvalidated = next.style !== prev.style ||
312
+ next.trailColor !== prev.trailColor ||
337
313
  next.trailLat !== prev.trailLat ||
338
314
  next.lat !== prev.lat ||
339
315
  next.width !== prev.width ||
@@ -1,16 +1,53 @@
1
- // Per-style renderer colors. One mapping so the generated page and the app's
2
- // map island can never drift apart. The trail core is shared across styles so
3
- // every flight trail wears the one palette accent (#147).
4
- /** The flight-trail color: the palette accent, one color everywhere. */
5
1
  const TRAIL_COLOR = '#e87f54';
2
+ function parseHexColor(hex) {
3
+ const m = /^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(hex);
4
+ if (!m)
5
+ throw new Error(`invalid trail color: ${hex}`);
6
+ const [r, g, b, a] = [0, 2, 4, 6].map((i) => i < m[1].length ? Number.parseInt(m[1].slice(i, i + 2), 16) : 255);
7
+ return { r, g, b, a: a / 255 };
8
+ }
9
+ function rgba(c, alpha) {
10
+ return `rgba(${c.r},${c.g},${c.b},${Math.round(alpha * 10000) / 10000})`;
11
+ }
12
+ function luminance(c) {
13
+ const linear = (v) => {
14
+ const s = v / 255;
15
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
16
+ };
17
+ return 0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b);
18
+ }
19
+ function mix(base, tint, amount) {
20
+ const k = (x, y) => Math.round(x + (y - x) * amount);
21
+ return { r: k(base.r, tint.r), g: k(base.g, tint.g), b: k(base.b, tint.b), a: 1 };
22
+ }
23
+ const CASING_ANCHORS = {
24
+ satellite: {
25
+ anchor: { r: 10, g: 14, b: 20, a: 1 },
26
+ opposite: { r: 255, g: 255, b: 255, a: 1 },
27
+ alpha: 0.9,
28
+ },
29
+ topo: {
30
+ anchor: { r: 255, g: 255, b: 255, a: 1 },
31
+ opposite: { r: 10, g: 14, b: 20, a: 1 },
32
+ alpha: 1,
33
+ },
34
+ };
35
+ const CONTRAST_FLIP = 0.18;
36
+ const CORE_TINT = 0.2;
37
+ function deriveCasing(style, core) {
38
+ const { anchor, opposite, alpha } = CASING_ANCHORS[style];
39
+ const base = Math.abs(luminance(core) - luminance(anchor)) < CONTRAST_FLIP ? opposite : anchor;
40
+ return rgba(mix(base, core, CORE_TINT), alpha);
41
+ }
42
+ const GLOW_ALPHA = { satellite: 0.32, topo: 0.26 };
6
43
  function trailGlow(alpha) {
7
- const [r, g, b] = [1, 3, 5].map((i) => Number.parseInt(TRAIL_COLOR.slice(i, i + 2), 16));
8
- return `rgba(${r},${g},${b},${alpha})`;
44
+ return rgba(parseHexColor(TRAIL_COLOR), alpha);
9
45
  }
10
46
  const THEMES = {
11
47
  satellite: {
12
48
  core: TRAIL_COLOR,
13
- glow: trailGlow(0.32),
49
+ trailCore: TRAIL_COLOR,
50
+ glow: trailGlow(GLOW_ALPHA.satellite),
14
51
  casing: 'rgba(10,14,20,0.9)',
15
52
  ghost: '#ffffff',
16
53
  ghostOpacity: 0.85,
@@ -20,7 +57,8 @@ const THEMES = {
20
57
  },
21
58
  topo: {
22
59
  core: TRAIL_COLOR,
23
- glow: trailGlow(0.26),
60
+ trailCore: TRAIL_COLOR,
61
+ glow: trailGlow(GLOW_ALPHA.topo),
24
62
  casing: '#ffffff',
25
63
  ghost: '#6b6252',
26
64
  ghostOpacity: 0.7,
@@ -29,6 +67,16 @@ const THEMES = {
29
67
  vignette: 0.06,
30
68
  },
31
69
  };
32
- export function themeFor(style) {
33
- return THEMES[style];
70
+ export function themeFor(style, trailColor = null) {
71
+ const base = THEMES[style];
72
+ if (trailColor === null)
73
+ return base;
74
+ const core = parseHexColor(trailColor);
75
+ return {
76
+ ...base,
77
+ core: rgba(core, 1),
78
+ trailCore: trailColor,
79
+ glow: rgba(core, GLOW_ALPHA[style] * core.a),
80
+ casing: deriveCasing(style, core),
81
+ };
34
82
  }
@@ -1,12 +1,5 @@
1
- // The tile-source vocabulary: where tiles come from and how they look. Pure
2
- // data shared by the tile pipeline (Node) and the shared map renderer
3
- // (browser); cache layout lives in tilecache.ts, download logic in tiles.ts.
4
- // Lives inside renderer/ so the browser-served module graph stays within
5
- // that directory.
6
1
  export const TILE_SOURCES = {
7
2
  // Esri World Imagery (free for non-commercial use, attribution required).
8
- // Tiles are JPEG; the cache filename stays .png and browsers decode by
9
- // content, which is fine for Leaflet <img> tiles.
10
3
  satellite: {
11
4
  cacheKey: 'esri-imagery',
12
5
  url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
@@ -17,9 +10,6 @@ export const TILE_SOURCES = {
17
10
  tileFilter: 'saturate(1.06) contrast(1.03)',
18
11
  maxZoom: 19,
19
12
  },
20
- // OpenTopoMap: OSM topography with contour lines and shaded relief - rich
21
- // detail in alpine terrain. Tiles are native to z17; Leaflet auto-scales
22
- // them above that (maxNativeZoom), so the view zoom stays style-independent.
23
13
  topo: {
24
14
  cacheKey: 'opentopomap',
25
15
  url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',