Repository navigation
Expand file tree
/
Copy pathengine.ts
More file actions
1068 lines (1001 loc) · 61.5 KB
/
Copy pathengine.ts
File metadata and controls
1068 lines (1001 loc) · 61.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { PlannerConfig } from '../planner/config';
import type { Coordinate } from '../planner/geo';
import { worldPixel } from '../planner/layers/mercator';
import { instantAt } from '../planner/solar';
import { eyeAltitude, follow, groundOf, MIN_CLEARANCE, move, VFOV, viewProjection, type Footing, type Pose } from './frame/camera';
import { Controls, type Pointer } from './frame/controls';
import { CURVATURE, frameAt, type Frame } from './frame/frame';
import { UNITS } from './frame/space';
import { Gpu } from './gpu/device';
import { PassTimes } from './gpu/timing';
import { Ground, groundPipelines, type GroundStats } from './ground/ground';
import { moonAt, starFrame, sunAt, type Mat3 } from './light/celestial';
import { coronaSeed, coronaShare, drawnMoon, solarActivity, sunlightLeft } from './light/eclipse';
import { airColour, eclipsed, eyeLook, lightAt, moonlit, moonShare, weatherLight, WEATHERS, type EyeLook } from './light/light';
import { LOOK_BYTES, lookUniform } from './light/look';
import { Shadow } from './light/shadow';
import { DARK_SKY, nightSky } from './light/night';
import { Sky, SKY_CREDITS, skyPipeline } from './light/sky';
import { Resolve, resolvePipeline } from './resolve/resolve';
import { MAX_SCALE, Targets } from './resolve/targets';
import { jitter, STILL_FRAMES, Temporal, type Step } from './resolve/temporal';
import { EYE, Instances, SUN, type InstanceStats, type LastFrame } from './instances/instances';
import { ModelFiles } from './instances/model-files';
import { GroundSource } from './stream/ground';
import { eyeTiles, pageDecoder, type EyeTiles } from './stream/terrain';
import { Terrain, terrainPipelines, type Audit, type TerrainStats } from './terrain/terrain';
import { piecePipelines } from './plan/pieces';
import HOUSE_VERSION from 'virtual:house-version';
import PLAN_VERSION from 'virtual:plan-version';
import STAMP_VERSION from 'virtual:stamp-version';
import MODELS from 'virtual:models';
import { FINEST, NEAR_M } from './terrain/lod';
import { Houses, type HouseStats } from './structures/houses';
import { Forest } from './vegetation/forest';
import { TREE_REACH_M, TreeModels, type Reach } from './vegetation/tree-models';
import { Plants } from './vegetation/plants';
import { Rows } from './vegetation/rows';
import { Dressing } from './dressing/dressing';
import { KindPoints } from './structures/kind-points';
import { LightPools } from './structures/light-pools';
import { aboutEye, LIFT_M, nearestRoute, onImage, onScreen } from './route/pick';
import { Route, type RouteLine, type RoutePin } from './route/route';
import type { PlanStats } from './plan/plan';
import { sampleDistances, terrainHides } from './sight';
import { Pacer } from './pacer';
import { BUDGETS, type Budget, type Tier } from './budget';
import type { StillPoints } from './still';
import { DEBUG_VIEWS, TIME_ZONE, type View } from './view';
const PASSES = ['terrain', 'ground', 'stamp', 'houses', 'vegetation', 'casters', 'shadow', 'far-casters', 'far-shadow', 'mips', 'resolve', 'pieces', 'cliff'];
/** Metres to a view that is at another place. */
const NEW_PLACE = 1000;
/** A step of the footing this small no longer moves the view about the eye: `eyeReady` counts it as settled. */
const SETTLED_M = 0.02;
/** The longest that the other loads wait for the tiles under the eye: a tile that hangs must not hold the view back until its request times out. */
const EYE_WAIT_MS = 1000;
/** The clear colour of the crack test: any red pixel is a hole in the terrain. */
const RED = { r: 1, g: 0, b: 0, a: 1 };
/** `Frame` in terrain.wgsl. */
const FRAME_BYTES = 96;
const MAX_PIXEL_RATIO = 2;
const RAD = Math.PI / 180;
/** A walking eye steps up or down this far onto a floor; on a floor this far under the terrain it is in a tunnel. */
const STEP_M = 1, HEADROOM_M = 2;
/** A flying eye under the terrain is in a tunnel when a floor lies at most this far below it. */
const BORE_M = 6;
/** The regions in reach are read this much wider and again only when the eye moves farther or the ground pages change. */
const REACH_MARGIN_M = 250;
export interface Stats {
adapter: string;
/** Milliseconds per render pass, from timestamp queries. */
gpu: Record<string, number>;
/** The stamp jobs of the frame whose times `gpu` holds, by kind, and that frame's start in milliseconds. */
timed?: Record<string, number>;
cpu: number;
/** Bytes per GPU pool. */
pools: Map<string, number>;
requests: number;
bytes: number;
failed: number;
/** Terrain nodes drawn. */
drawn: number;
/** The render scale: render pixels per output pixel along each axis. */
scale: number;
/** Terrain pages on the GPU. */
resident: number;
recoveries: number;
terrain: TerrainStats;
ground: GroundStats;
houses: HouseStats;
instances: InstanceStats;
/** The ground plan, only with `ground=plan`. */
plan?: PlanStats;
}
/**
* The pipelines of the first frames: the terrain and its compute, the ground pages, the sky and the resolve, and with the
* records (`plan`) the meshes, which draw the view about the eye. The other passes compile theirs at their attach, once
* the view about the eye is drawn: a compile holds the GPU process, which the first frames' stamps and corners need.
*/
const first = (plan: boolean): ((gpu: Gpu) => Promise<unknown>)[] => [terrainPipelines(plan), groundPipelines, skyPipeline, resolvePipeline, ...(plan ? [piecePipelines] : [])];
/**
* The longest from the attach that the other passes wait for the view about the eye: a view whose eye has no ground
* draws none. Their compile, which takes about a second on a desktop, would stall the view about the eye.
*/
const REST_WAIT_MS = 5000;
/** The options of `TrailView.start`. */
interface StartOptions extends Pointer { plan?: boolean; finest?: number; tier?: Tier; size?: [number, number] }
/** Where the eye stands: a height, and whether it lies in a tunnel. */
interface Feet { z: number; tunnel: boolean; floor: boolean }
/** Where the selection looks from: `above` is the eye's height above the ground, or the pose's height over an unknown ground. */
interface Place { east: number; north: number; above: number }
/** The eye in the frame, at height z above sea level. */
interface Eye extends Place { z: number }
/** The engine: a frame loop that draws a view on demand, and recovers from a lost device until `destroy()`. */
export class TrailView {
/** Called with the view after it changes. */
onView?: (view: View) => void;
recoveries = 0;
/** Picks the display frames that draw: `pacer.rate` is the frame rate. */
readonly pacer: Pacer;
private readonly context: GPUCanvasContext;
private readonly frame: Frame;
private readonly terrain: Terrain;
private readonly groundLook: Ground;
private readonly houses: Houses;
private readonly instances = new Instances();
private readonly models: ModelFiles;
private readonly trees: TreeModels;
/** The last regions in reach, where they were read from and at which change of the ground pages. */
private reached?: Reach & { east: number; north: number; changes: number };
private readonly forest: Forest;
private readonly plants: Plants;
private readonly rows: Rows;
private readonly kindPoints: KindPoints;
private readonly lightPools = new LightPools();
private readonly dressing: Dressing;
private readonly route = new Route();
private readonly sky = new Sky();
private readonly shadow = new Shadow();
private readonly resolve = new Resolve();
private readonly temporal = new Temporal();
private readonly controls?: Controls;
private destroyed = false;
private pose: Pose;
private extras: Pick<View, 'date' | 'time' | 'weather' | 'debug' | 'plan'>;
private gpuState!: { gpu: Gpu; uniform: GPUBuffer; look: GPUBuffer; times: PassTimes; targets: Targets };
/** The ground under the eye, on the plane of the last probe; a new view forgets it. */
private footing?: Footing;
/** Where the eye stood in the last frame: the height, and whether it was in a tunnel. */
private feet?: Feet;
private ready = false;
/** No frame draws before `start` lets it: a frame asks for every tile, and the tiles under the eye come first. */
private starting = true;
/** The attach of the other passes, which starts once a frame draws the view about the eye (`eyeDrawn`); it rejects when one fails. */
private rest: Promise<unknown> = Promise.resolve();
private eyeDrawn?: () => void;
/** Whether every pass is attached; `completed` until a frame draws them all. */
private complete = false;
private completed = false;
private pending = false;
private moved = false;
private last = 0;
private cpu = 0;
private drawn = 0;
/** Whether the last frame could draw: the eye has ground and the ground look is ready. */
private drawing = false;
/** What the last frame drew: the camera and the extras, to tell a move and a change. */
private camera: number[] = [];
/** The camera of the last frame that could draw, without its jitter: `routeAt` projects with it. */
private sight?: Pick<Grabbed, 'viewProj' | 'eye'>;
/** The pick points on the screen, as `routeAt` last projected them, and what it projected them from. */
private picked?: { sight: Pick<Grabbed, 'viewProj' | 'eye'>; picks: readonly (Float64Array | undefined)[]; width: number; height: number; screen: (Float32Array | undefined)[] };
private drawnExtras = '';
private rendered: (() => void)[] = [];
/** The last frame that drew, for occlusion culling: its depth, pixels and view projection, and its eye. */
private lastFrame?: Omit<LastFrame, 'moved'> & { eye: number[] };
/** Whether the last frame that placed the instances moved or changed: the next one places them again, culled by a depth of the same view. */
private unrest = true;
/** A capture that waits for the last jittered frame of the view. */
private grab?: { resolve: (grabbed: Grabbed) => void; reject: (error: Error) => void };
/**
* The brightness of the sky at the eye on a moonless night, in magnitudes per square arcsecond, as
* a sky quality meter reads it: about 22 far from lights, 18 in a town. It sets the faintest
* stars and the Milky Way's share (light/night.ts). Nothing sets it from data yet.
*/
private skyMagnitude = DARK_SKY;
private constructor(private readonly canvas: HTMLCanvasElement, config: PlannerConfig, view: View, ground: GroundSource | undefined, tiles: EyeTiles, private readonly stop: AbortController, private readonly scale: number, readonly groundPlan: boolean, finest: number, budget: Budget, pointer: Pointer, private readonly output?: [number, number]) {
// `destroy()` aborts it: it ends the tile requests, the workers and the listeners.
const { signal } = stop;
this.context = canvas.getContext('webgpu')!;
this.pacer = new Pacer(budget.frameRate);
this.frame = frameAt(view.lon, view.lat);
this.pose = this.poseOf(view);
this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug, plan: view.plan };
const { features } = tiles;
// The release ID, and the tile URLs for a config without one.
const release = JSON.stringify([config.id, config.manifest, config.terrain, config.layers]);
this.terrain = new Terrain(this.frame, { fetch: tiles.terrain, decode: pageDecoder(signal) }, features, config.bounds, () => this.request(), signal, budget, groundPlan, finest, tiles.stamps, { release, version: STAMP_VERSION, plan: PLAN_VERSION });
this.groundLook = new Ground(ground, budget, () => this.request());
this.houses = new Houses(this.frame, features, this.groundLook.rules, () => this.request(), signal, budget, { release, version: HOUSE_VERSION });
this.models = new ModelFiles(MODELS, () => this.request(), signal);
this.trees = new TreeModels(this.instances, () => this.treesNear(), this.models, budget.loads.models);
this.forest = new Forest(config, this.groundLook.rules, this.trees, this.instances, () => this.request(), signal, budget);
this.plants = new Plants(this.groundLook.rules, this.trees, this.instances, this.models);
this.rows = new Rows(config, this.groundLook.rules, this.trees, this.plants, this.instances, MODELS);
this.kindPoints = new KindPoints(this.instances, this.models);
this.dressing = new Dressing(this.groundLook.rules, this.instances, this.models);
// A still has a size of its own and no input: the controls listen for keys on the whole window.
if (output) return;
this.controls = new Controls(canvas, {
pose: () => this.pose,
moved: pose => { this.pose = pose; this.moved = true; this.request(); },
ground: () => this.ground(),
}, signal, pointer);
const resize = new ResizeObserver(() => this.request());
resize.observe(canvas);
signal.addEventListener('abort', () => resize.disconnect());
}
/**
* Compiles the pipelines of the first frames on a device, without a view and without pools: on a cold
* shader cache that takes seconds. Call it as soon as a view is likely, such as when a drag toward one
* starts; `start` on the same device takes what it compiled, also while it still compiles.
*/
static prepare(gpu: Gpu, plan = false): Promise<void> {
return Promise.all(first(plan).map(make => gpu.once(make))).then(() => {});
}
/**
* Starts the terrain and feature tiles under the eye, reads the ruleset and opens the ground layers,
* attaches what the first frame draws, then starts the other tile loads once the tiles under the eye
* are in, or after EYE_WAIT_MS: on a slow link the other loads would share it with them. The other
* passes draw once they attach after the view about the eye. `scale` is the render scale; `plan` builds the
* ground plan beside the old ground (`ground=plan`); `finest` caps the terrain's finest level (`finest=`), and `tier`
* chooses the budget: the pools, the loads and the frame rate (`tier=`). `size` is the output of a still in pixels,
* in place of the element's size on the screen. `onclick` and `onhover` get a click and a move with no button on the canvas, in CSS pixels (`Pointer`).
* All but the attach run while `gpu` comes: the frames before it ask for the view's records and stamps.
*/
static async start(canvas: HTMLCanvasElement, gpu: Gpu | Promise<Gpu>, config: PlannerConfig, view: View, scale: number, { plan = false, finest = FINEST, tier = 'desktop', size, onclick, onhover }: StartOptions = {}): Promise<TrailView> {
const budget = BUDGETS[tier], stop = new AbortController(), tiles = eyeTiles(config, [view.lon, view.lat], budget.caps, stop.signal);
const ground = await GroundSource.open(config, budget.caps, stop.signal).catch(error => void console.warn(`TrailView draws no ground: ${error instanceof Error ? error.message : error}`));
const engine = new TrailView(canvas, config, view, ground ?? undefined, tiles, stop, scale, plan, finest, budget, { onclick, onhover }, size);
engine.request();
// No caller holds an engine whose start fails, so it ends itself: its workers and listeners run already.
await Promise.resolve(gpu).then(device => engine.attach(device)).catch(error => {
engine.destroy();
throw error;
});
await Promise.race([tiles.arrived, new Promise(resolve => setTimeout(resolve, EYE_WAIT_MS))]);
engine.starting = false;
engine.request();
return engine;
}
get gpu(): Gpu {
return this.gpuState.gpu;
}
get view(): View {
const [lon, lat] = this.frame.lonLat(this.pose.east, this.pose.north);
const heading = ((this.pose.heading - this.convergence(this.pose.east, this.pose.north)) % 360 + 360) % 360;
return { lat, lon, heading, pitch: this.pose.pitch, mode: this.pose.mode, height: this.pose.height, ...this.extras };
}
set view(view: View) {
const pose = this.poseOf(view);
// A view at another place forgets the ground; a scripted flight step keeps it for the probe to follow.
if (Math.hypot(pose.east - this.pose.east, pose.north - this.pose.north) > NEW_PLACE) {
this.footing = undefined;
this.feet = undefined;
this.terrain.forget();
this.temporal.reset();
this.lastFrame = undefined;
}
this.pose = pose;
this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug, plan: view.plan };
this.moved = true;
this.request();
}
get skyBrightness(): number {
return this.skyMagnitude;
}
set skyBrightness(magnitude: number) {
this.skyMagnitude = magnitude;
this.request();
}
stats(): Stats {
const { gpu, times } = this.gpuState, { pages } = this.terrain, terrain = this.terrain.stats, ground = this.groundLook.stats, forest = this.forest.requests;
return {
adapter: gpu.adapter, gpu: { ...times.ms }, timed: times.tag, cpu: this.cpu, pools: new Map(gpu.pools),
requests: pages.requests + ground.requests + forest.requests, bytes: pages.bytes + ground.bytes + forest.bytes, failed: pages.failed + ground.failed + forest.failed + this.terrain.failed,
drawn: this.drawn, scale: this.scaleNow, resident: terrain.resident.stored + terrain.resident.synth, recoveries: this.recoveries, terrain, ground, houses: this.houses.stats, instances: this.instances.stats,
...(this.terrain.plan ? { plan: this.terrain.plan.stats } : {}),
};
}
/** The credits of the ground layers and the sky. */
get attribution(): string[] {
return [...this.groundLook.attribution, SKY_CREDITS];
}
/**
* Draws the routes on the surface in place of the ones before, numbered from 1 in their order. A route of fewer
* than two points draws none. No route of the new list is bold.
*/
showRoutes(routes: readonly RouteLine[]): void {
this.route.set(routes, this.frame);
this.request();
}
/** Draws the route of this number bold and on top of the others; null draws none bold. */
boldRoute(route: number | null): void {
this.route.setBold(route);
this.request();
}
/**
* The number of the route under (x, y), CSS pixels of the canvas, or null for none: `nearestRoute` of
* the pick points of each route, projected with the camera of the last frame. It does not ask the
* terrain whether it hides a point, so a route behind a ridge answers when no nearer route is there.
*/
routeAt(x: number, y: number): number | null {
const { sight, route: { picks, bold } } = this, { clientWidth: width, clientHeight: height } = this.canvas;
if (!sight) return null;
let picked = this.picked;
if (!picked || picked.sight !== sight || picked.picks !== picks || picked.width !== width || picked.height !== height) {
picked = this.picked = { sight, picks, width, height, screen: picks.map(points => points && onScreen(sight.viewProj, sight.eye, width, height, points)) };
}
return nearestRoute(picked.screen, x, y, bold);
}
/** Stands a pin with a sphere in `colour` at `at`, apart from the others so that it moves cheaply; null takes it away. */
showMarker(at: Coordinate | null, colour = '#ffffff'): void {
this.route.setMarker(at ? { coordinate: at, colour } : undefined);
this.request();
}
/** Stands the pins on the ground in place of the ones before. */
showPins(pins: readonly RoutePin[]): void {
this.route.setPins(pins);
this.request();
}
/** drawnHeight at points from the probe and from an instance shader, and the share of the sun there, with the state of the last frame. */
check(points: [number, number][]): Promise<{ probe: number[]; instance: number[]; sun: number[] }> {
return this.terrain.check(points, this.groundLook.group!);
}
/**
* The finished image of the view as RGBA and, for a line of [lon, lat] points, the place of each
* point in it: call it after `waitForIdle()`. It draws the jittered frames of the view again and
* copies the canvas of the last one. A point stands where the route's ribbon would: LIFT_M above the
* drawn surface. It is visible unless the drawn terrain hides it (`terrainHides`), which it probes at
* `sampleDistances` on the way from the eye to the point.
*/
async capture(line?: readonly [number, number][]): Promise<{ colour: ImageData; points?: StillPoints }> {
if (this.destroyed) throw new Error('The engine has ended.');
const grabbed = await new Promise<Grabbed>((resolve, reject) => {
this.grab = { resolve, reject };
this.temporal.reset();
this.request();
});
const { colour, row, output: [width, height], eye } = grabbed;
// The points of the line, then the samples on the way from the eye to each point, in one probe.
const along = line?.map(point => {
const [east, north] = this.frame.local(...point);
return sampleDistances(Math.hypot(east - eye[0], north - eye[1]));
});
const probes = line && along && new Float64Array(2 * (line.length + along.reduce((sum, list) => sum + list.length, 0)));
if (line && along && probes) for (let i = 0, at = 2 * line.length; i < line.length; i++) {
probes.set(worldPixel(line[i], UNITS), 2 * i);
const [east, north] = this.frame.local(...line[i]), across = Math.hypot(east - eye[0], north - eye[1]);
for (const d of along[i]) {
probes.set(worldPixel(this.frame.lonLat(eye[0] + d / across * (east - eye[0]), eye[1] + d / across * (north - eye[1])), UNITS), at);
at += 2;
}
}
const [heights] = await Promise.all([probes && this.terrain.probeAt(probes), colour.mapAsync(GPUMapMode.READ)]);
// The canvas holds the device's format, often BGRA, in rows padded to 256 bytes.
const bytes = new Uint8Array(colour.getMappedRange()), rgba = new Uint8ClampedArray(4 * width * height), bgra = this.gpu.format === 'bgra8unorm';
for (let y = 0; y < height; y++) for (let x = 0, from = y * row, to = 4 * y * width; x < width; x++, from += 4, to += 4) {
rgba[to] = bytes[from + (bgra ? 2 : 0)];
rgba[to + 1] = bytes[from + 1];
rgba[to + 2] = bytes[from + (bgra ? 0 : 2)];
rgba[to + 3] = 255;
}
const points = line && along && heights && placed(line, along, heights, this.frame, grabbed);
colour.destroy();
return { colour: new ImageData(rgba, width, height), points };
}
/** The invariant audit of the drawn terrain, with the state of the last frame: call it after `waitForIdle()`. */
audit(): Promise<Audit> {
return this.terrain.audit();
}
/** The determinism check's hashes of the drawn terrain (Terrain.hashes), with the state of the last frame: call it after `waitForIdle()`. */
hashes(): Promise<Record<string, string>> {
return this.terrain.hashes();
}
/**
* Ends the engine: no frame draws, no tile loads, no worker runs, and the buffers and textures that
* it made are destroyed. The device stays for the next engine. The waits for a frame resolve.
*/
destroy(): void {
if (this.destroyed) return;
this.destroyed = true;
this.ready = false;
this.stop.abort();
for (const resolve of this.rendered.splice(0)) resolve();
this.grab?.reject(new Error('The engine has ended.'));
this.context.unconfigure();
// A start that fails in its first attach may have no GPU state yet.
this.gpuState?.times.destroy();
this.gpuState?.gpu.release();
}
/** Resolves after the next frame is drawn, or at once after `destroy()`. */
nextFrame(): Promise<void> {
this.request();
return this.afterFrame();
}
/** Resolves after the next frame that draws; a destroyed engine draws none. */
private afterFrame(): Promise<void> {
return this.destroyed ? Promise.resolve() : new Promise(resolve => this.rendered.push(resolve));
}
/**
* Resolves after a frame in which no tile loads, every wanted page and shadow map is drawn, the eye
* stands on the probed ground and the still view has all its jittered frames, once the GPU has
* finished it. Rejects when a pass fails to attach, as `nearReady` does.
*/
async waitForIdle(): Promise<void> {
await this.rest;
await this.nextFrame();
// A tile or a probe that arrives draws the next frame.
while (!this.destroyed && (!this.idle() || this.terrain.meshesLoading)) await this.afterFrame();
if (!this.destroyed) await this.gpu.device.queue.onSubmittedWorkDone();
}
private idle(): boolean {
return !this.loading && !this.shadow.pending && this.settled() && !this.converging;
}
/** Whether the late passes still attach, or a tile, a model or a page is on its way. */
private get loading(): boolean {
return !this.complete || !this.terrain.idle || !this.groundLook.idle || !this.houses.idle || !this.trees.idle || !this.forest.idle || !this.plants.idle || !this.models.idle || !this.instances.idle
|| !this.sky.idle;
}
/**
* Resolves after the first drawn frame in which the near field (NEAR_M about the eye) is final: the
* eye stands on the probe of the finest heights under it, the terrain within NEAR_M draws at its
* wanted levels with its stamps, the ground pages, houses, trees and plants there are in, and the
* near shadow map holds them. It waits neither for the far field nor for the jittered frames. A view
* that never gets there, such as one whose tiles fail, resolves when it is idle.
*/
async nearReady(): Promise<void> {
await this.rest;
await this.nextFrame();
while (!this.destroyed && !this.near() && !this.idle()) await this.afterFrame();
}
/**
* Resolves after the first drawn frame in which the view about the eye (EYE_M) is final: the eye
* stands on its final ground, and the terrain and the ground look within EYE_M draw at their wanted
* levels with their stamps. It waits for no houses, plants, shadows, water, structures or far field.
* A view that never gets there resolves when it is idle, or when a late pass fails to attach.
*/
async eyeReady(): Promise<void> {
// A failed late pass keeps the view from ever being idle: the wait then ends with it.
let failed = false;
this.rest.catch(() => { failed = true; });
await this.nextFrame();
while (!this.destroyed && !failed && !this.eyeFinal() && !this.idle()) await this.afterFrame();
}
private eyeFinal(): boolean {
return this.drawing && this.terrain.eye && this.footed() && this.groundLook.eyeIdle;
}
/**
* Whether the step of the footing no longer moves the camera. The last centimetres of a walking eye's
* step down fade for half a second; nobody sees them. A flying eye above its clearance does not stand on
* the footing, so its step moves nothing.
*/
private footed(): boolean {
const step = Math.abs(this.footing?.step ?? 0), ground = this.ground(), z = eyeAltitude(this.pose, ground);
if (this.pose.mode === 'fly' && ground !== undefined && z !== undefined && z - ground - MIN_CLEARANCE > step) return true;
return this.settled(SETTLED_M);
}
private near(): boolean {
return this.drawing && this.complete && this.terrain.near && this.settled() && this.groundLook.nearIdle && this.houses.nearIdle && this.trees.nearIdle && this.forest.idle
&& this.plants.nearIdle && this.kindPoints.idle && this.dressing.idle && this.instances.idle && this.shadow.nearDrawn;
}
/**
* Resolves when the first frame can draw. The other passes attach once the view about the eye is drawn, or
* after REST_WAIT_MS: their compiles would share the compiler and the CPU with that view. The engine's
* buffers and textures are made in a scope of the device, which `destroy()` releases.
*/
private async attach(base: Gpu): Promise<void> {
const gpu = base.scope();
// The passes' attaches report a failed compile.
TrailView.prepare(gpu, this.groundPlan).catch(() => {});
this.complete = false;
// A still copies the canvas.
this.context.configure({ device: gpu.device, format: gpu.format, alphaMode: 'opaque', usage: GPUTextureUsage.RENDER_ATTACHMENT | (this.output ? GPUTextureUsage.COPY_SRC : 0) });
const uniform = gpu.buffer('uniforms', FRAME_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
const look = gpu.buffer('uniforms', LOOK_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
const targets = new Targets(gpu, !!this.output);
this.gpuState = { gpu, uniform, look, times: new PassTimes(gpu, PASSES, { resolve: 'terrain' }), targets };
this.temporal.reset();
// The maps at once: the ground's group binds them.
const shadow = this.shadow.attach(gpu), frames = [uniform, this.shadow.frame];
await this.terrain.attach(gpu, uniform);
const surface = this.terrain.surface!, features = this.terrain.features!;
await Promise.all([this.groundLook.attach(gpu, look, surface, this.shadow.entries()), this.sky.attach(gpu), this.resolve.attach(gpu)]);
const drawn = new Promise<void>(resolve => {
this.eyeDrawn = resolve;
setTimeout(resolve, REST_WAIT_MS);
});
// A device lost before the first frame leaves the other passes to the next attach.
this.rest = drawn.then(async () => {
if (this.destroyed || this.gpuState.gpu !== gpu) return;
// The night sky's files load on their own: the passes and the shadows never wait for them.
void this.sky.attachNight(gpu).then(() => {
if (this.destroyed) gpu.release();
else this.request();
});
// A destroy during these attaches released the scope before they made their buffers, also when one fails.
try {
await Promise.all([shadow, this.terrain.attachParts(frames), this.houses.attach(gpu, frames, surface, features), this.instances.attach(gpu, frames, { surface, features }), this.lightPools.attach(gpu, uniform), this.route.attach(gpu, uniform), this.terrain.plan?.draw.attach(gpu, uniform)]);
} finally {
if (this.destroyed) gpu.release();
}
if (this.destroyed || this.gpuState.gpu !== gpu) return;
this.complete = this.completed = true;
this.request();
});
this.rest.catch(error => console.error('TrailView: a pass failed to attach:', error));
// A lost device is created again and gets every pool again, without a reload of the page.
gpu.device.lost.then(async info => {
if (this.destroyed || info.reason === 'destroyed') return;
console.warn(`The WebGPU device was lost (${info.reason}): ${info.message}`);
this.ready = false;
const next = await Gpu.request();
if (this.destroyed) return;
if (!next) return console.error('WebGPU has no adapter after a lost device.');
try {
await this.attach(next);
} finally {
if (this.destroyed) this.gpuState.gpu.release();
}
if (this.destroyed) return;
// The other passes attach before the next frame: until they do, they hold the lost device's resources.
this.eyeDrawn?.();
this.recoveries++;
this.request();
});
this.ready = !this.destroyed;
}
/**
* Asks for a frame. Every arrival (a terrain or ground page, stamps, houses, canopy, models, plants)
* wakes the engine only here and goes to the GPU only in a frame: after `destroy()` none does.
*/
private request(): void {
if (this.pending || this.destroyed) return;
this.pending = true;
requestAnimationFrame(now => this.render(now));
}
/** The height that the eye stands on. */
private ground(): number | undefined {
return this.stand()?.z;
}
/**
* Where the eye stands: on the ground under it from the GPU probe, or where no level knows it, the
* last known ground. A walking eye stands on the floor of a deck or a tunnel within a step of its
* feet instead. Off a tunnel's floor, past its edge or between its segments, it keeps its feet: the
* hill over it is no place to land. A flying eye under the terrain stands on a tunnel's floor below it.
*/
private stand(): Feet | undefined {
const terrain = this.footing && groundOf(this.footing, this.pose.east, this.pose.north);
if (terrain === undefined) return terrain;
const at = this.frame.lonLat(this.pose.east, this.pose.north), feet = this.feet?.z ?? terrain;
const floor = this.pose.mode === 'fly'
? this.pose.height < terrain ? this.terrain.floorAt(at, this.pose.height - BORE_M, this.pose.height) : undefined
: this.terrain.floorAt(at, feet - STEP_M, feet + STEP_M) ?? (this.feet?.tunnel ? feet : undefined);
const z = floor ?? terrain;
return { z, tunnel: z < terrain - HEADROOM_M, floor: floor !== undefined };
}
/** Whether a still view that can draw needs more jittered frames. */
private get converging(): boolean {
return this.drawing && this.temporal.converging;
}
/** The render scale of the view: the debug views draw every output pixel. */
private get scaleNow(): number {
return this.extras.debug === 'off' ? this.scale : 1;
}
/** Whether the eye stands on the last probe, with at most `within` metres of a step still fading. */
private settled(within = 0): boolean {
const probe = this.terrain.ground;
return !probe || Number.isNaN(probe.height) || (probe.frame === this.footing?.probe.frame && Math.abs(this.footing.step) <= within);
}
/** The eye; a walking eye waits for a known ground. */
private eye(): Eye | undefined {
const ground = this.ground(), z = eyeAltitude(this.pose, ground);
if (z === undefined) return undefined;
return { east: this.pose.east, north: this.pose.north, z, above: ground === undefined ? this.pose.height : z - ground };
}
/** Where the tiles are selected from; over an unknown ground, the pose's height stands for the height above it. */
private place(): Place {
return this.eye() ?? { east: this.pose.east, north: this.pose.north, above: this.pose.height };
}
/** The tree models of the regions about the eye, each by its weight in their packs. */
private treesNear(): Map<string, number> {
const [lon, lat] = this.frame.lonLat(this.pose.east, this.pose.north), near = new Map<string, number>();
for (const [region, share] of this.groundLook.regionsAt(lon, lat)) {
for (const { model, weight } of this.groundLook.rules.regions[region]?.trees ?? []) near.set(model, (near.get(model) ?? 0) + share * weight);
}
return near;
}
/**
* The regions where trees and plants can stand about the eye, and those of the near field, each read REACH_MARGIN_M
* wider: the last answer holds until the pages change or the eye moves past that margin.
*/
private reach(): Reach {
const { east, north } = this.pose, last = this.reached, changes = this.groundLook.changes;
if (last && last.changes === changes && Math.abs(east - last.east) <= REACH_MARGIN_M && Math.abs(north - last.north) <= REACH_MARGIN_M) return last;
const [lon, lat] = this.frame.lonLat(east, north), wider = (metres: number) => this.groundLook.regionsNear(lon, lat, metres + REACH_MARGIN_M);
this.reached = { east, north, changes, reach: wider(TREE_REACH_M), near: wider(NEAR_M) };
return this.reached;
}
/** Degrees clockwise from the frame's north to true north at a point. */
private convergence(east: number, north: number): number {
const [lon, lat] = this.frame.lonLat(east, north), [e, n] = this.frame.local(lon, lat + 1e-4);
return Math.atan2(e - east, n - north) / RAD;
}
private poseOf(view: View): Pose {
const [east, north] = this.frame.local(view.lon, view.lat);
return { east, north, heading: view.heading + this.convergence(east, north), pitch: view.pitch, mode: view.mode, height: view.height };
}
private render(now: number): void {
this.pending = false;
if (!this.ready) {
if (!this.destroyed) this.ask();
return;
}
if (this.starting) return;
if (!this.pacer.due(now)) return this.request();
const start = performance.now();
const steer = this.controls?.steer(), dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0;
if (steer) this.pose = move(this.pose, steer, dt, this.ground());
const probe = this.terrain.ground;
if (probe && !Number.isNaN(probe.height)) {
const [east, north] = this.frame.local(...probe.lonLat);
this.footing = follow(this.footing, { ...probe, east, north }, this.pose.east, this.pose.north, dt);
}
this.feet = this.stand();
const settled = this.settled();
this.last = steer || !settled ? now : 0;
const eye = this.eye(), place = this.place();
const { gpu, uniform, times, targets } = this.gpuState;
const resized = this.fit();
if (resized) {
this.temporal.reset();
this.lastFrame = undefined;
}
const debug = this.extras.debug !== 'off', scale = this.scaleNow, [width, height] = targets.viewport(scale), aspect = targets.width / targets.height;
// Metres per output pixel at 1 m from the eye.
const pixel = 2 * Math.tan(VFOV * RAD / 2) / targets.height;
const viewProj = viewProjection(this.pose.heading, this.pose.pitch, aspect);
const lonLat = this.frame.lonLat(place.east, place.north);
// The shipping render scale selects the nodes, also for a debug view: it shows the LOD that ships.
if (this.terrain.plan) this.terrain.plan.debug = this.extras.plan === 'faces';
this.terrain.update({ lonLat, above: place.above, z: eye?.z, viewProj, pixels: targets.viewport(this.scale)[1], ahead: ahead(this.pose) }, this.groundLook.reads);
this.models.update();
this.kindPoints.update(this.terrain.kindPoints);
this.lightPools.set(this.kindPoints.lights);
const { drawn, wanted, arrived, origins } = this.terrain.selected;
this.groundLook.update(drawn, wanted, arrived, origins, this.extras.date, lonLat, this.forest.regionPages(lonLat));
this.houses.update(lonLat, eye && { viewProj, eye: [eye.east, eye.north, eye.z] });
const reach = this.reach();
this.trees.update(this.extras.date, reach);
this.forest.update(lonLat);
this.plants.update(lonLat, this.extras.date, place.above, reach);
this.rows.update(lonLat);
this.dressing.update(lonLat);
const group = this.groundLook.group;
this.drawing = !!(eye && group);
// A frame that cannot draw asks for no next frame: a capture would wait forever.
if (this.grab && !this.drawing) {
this.grab.reject(new Error(eye ? 'The still draws nothing: the ground layers are not ready.' : 'The still draws nothing: no terrain is known under the eye.'));
this.grab = undefined;
}
let step: Step | undefined, offset: [number, number] = [0, 0], ndc: [number, number] = [0, 0], moved = true, changed = false, cascade = -1, hold = false;
let lights: Lights | undefined, grabbed: Grabbed | undefined;
if (eye && group) {
const camera = [...viewProj, eye.east, eye.north, eye.z, eye.above, scale], extras = JSON.stringify([this.extras, this.skyMagnitude]);
moved = camera.some((value, i) => value !== this.camera[i]);
const newExtras = extras !== this.drawnExtras;
changed = this.completed || this.terrain.newContent || this.groundLook.newContent || this.houses.newContent || this.trees.newContent || this.forest.newContent || this.models.newContent || this.instances.newContent || this.sky.newContent || this.lightPools.newContent || this.route.newContent || newExtras;
// While a view at rest loads, its frames run the updates and the compute but draw LOAD_RATE frames a second. Input and a resize draw
// at once; a frame that would draw nothing does not hold, so it asks for no more frames.
hold = !this.output && !this.grab && (changed || this.temporal.converging) && this.pacer.holds(now, !moved && !newExtras && !resized, this.loading || this.terrain.meshesLoading);
// The frame that draws after held ones takes in their change: the restart, and the instances placed twice.
if (!hold) changed ||= this.temporal.held;
this.camera = camera;
if (moved) this.sight = { viewProj, eye: [eye.east, eye.north, eye.z] };
this.drawnExtras = extras;
this.completed = false;
lights = this.lights();
const light = lights.key, casters = this.houses.newContent || this.trees.newContent || this.forest.newContent || this.models.newContent;
const casting = { casters, reshaped: this.terrain.reshaped };
// A held frame keeps its changes for the next frame that draws: `due()` marks the map that it returns as drawn.
if (this.complete && hold) this.shadow.hold(casting);
else if (this.complete) cascade = this.shadow.due([eye.east, eye.north, eye.z - eye.above], eye.above, light, casting, moved);
this.shadow.write(gpu, [eye.east, eye.north, eye.z], light);
// A new map changes the frame as new content does.
if (hold) this.temporal.hold(changed);
else step = this.temporal.next(moved, changed || cascade >= 0, debug ? 1 : STILL_FRAMES);
if (step && !debug) offset = jitter(step.sample);
// The jitter in clip space: render pixels are y down.
ndc = [2 * offset[0] / width, -2 * offset[1] / height];
gpu.device.queue.writeBuffer(uniform, 0, this.uniforms(eye, jittered(viewProj, ndc), pixel, light));
const near = this.regionLook(eye);
gpu.device.queue.writeBuffer(this.gpuState.look, 0, this.look(eye, near, lights, aspect, ndc, scale, step?.sample ?? 0));
const { cover } = near.weather, night = lightAt(lights.sunAltitude).night;
this.sky.write(gpu, {
stars: lights.stars, moon: lights.drawnMoon, moonRadius: lights.moonRadius, moonAir: lights.moonAir, moonLight: lights.share > 0,
night: nightSky({ sun: lights.sunAltitude, moon: lights.moonAltitude, phase: lights.phase, sky: this.skyMagnitude, cover, left: lights.left }),
moonDisk: (1 - cover) * (0.35 + 0.65 * night), pixel: [2 / width, 2 / height],
eclipse: [(1 - cover) * coronaShare(lights.left), 1 - lights.left, lights.activity, lights.seed],
});
} else this.temporal.reset();
const encoder = gpu.device.createCommandEncoder();
const probed = this.terrain.encode(encoder, pass => times.writes(pass));
// On a floor the eye stands on a structure, not on the probe: a tunnel's floor lies under the terrain.
if (this.drawing && !this.feet?.floor) this.terrain.clampEye(encoder);
this.groundLook.encode(encoder, () => times.writes('ground'));
const counted = this.houses.encode(encoder, this.groundLook.computeGroup, moved, changed, () => times.writes('houses'));
const last = eye && this.lastFrame
? { ...this.lastFrame, moved: [eye.east - this.lastFrame.eye[0], eye.north - this.lastFrame.eye[1], eye.z - this.lastFrame.eye[2]] as [number, number, number] } : undefined;
// The instances keep their lists while the camera and the content rest, once a frame culled them by a depth of the same view.
const pixels = targets.viewport(this.scale)[1], placing = !!(eye && group && step) && (moved || changed || this.unrest || this.instances.due(pixels));
if (placing) this.unrest = moved || changed || !last;
const placed = this.vegetation(encoder, placing ? pixels : 0, last, () => times.writes('vegetation'));
const cast = cascade >= 0 && step && eye && group && lights ? this.cast(encoder, group, eye, cascade, lights.key) : () => {};
if (!eye || !group) {
// Until the eye has ground nothing draws: the horizon of the weather fills the canvas.
encoder.beginRenderPass({
colorAttachments: [{
view: this.context.getCurrentTexture().createView(), loadOp: 'clear', storeOp: 'store',
clearValue: this.extras.debug === 'cracks' ? RED : horizon(WEATHERS[this.extras.weather].horizon),
}],
}).end();
} else if (step) {
// The frame at the render scale in the top left of the targets; a still view that has all its frames draws none.
const pass = encoder.beginRenderPass({
colorAttachments: [{ view: targets.scene!.createView(), loadOp: 'clear', storeOp: 'store', clearValue: this.extras.debug === 'cracks' ? RED : [0, 0, 0, 1] }],
depthStencilAttachment: { view: targets.depth!.createView(), depthClearValue: 0, depthLoadOp: 'clear', depthStoreOp: 'store' },
timestampWrites: times.writes('terrain'),
});
pass.setViewport(0, 0, width, height, 0, 1);
// Before the terrain: the ground that the trees hide fails the depth test. The owned view draws the meshes and the terrain only.
const owned = this.extras.debug === 'owned';
if (!owned) this.instances.draw(pass, group);
this.terrain.draw(pass, group, owned);
if (!owned) this.houses.draw(pass, group);
if (this.extras.debug !== 'cracks' && !owned) this.sky.draw(pass, group);
// After the sky, which draws where nothing did: the route and its pins write no depth.
if (!owned && this.terrain.surface && this.terrain.features) this.route.draw(pass, this.terrain.surface, this.terrain.features);
pass.end();
if (this.terrain.surface && this.terrain.features) this.lightPools.encode(encoder, targets.scene!, targets.depth!, [width, height], this.terrain.surface, group, this.terrain.features);
const canvas = this.context.getCurrentTexture().createView();
this.resolve.encode(encoder, targets, canvas, group,
{ viewProj, eye: [eye.east, eye.north, eye.z], render: [width, height], jitter: offset }, { weight: step.weight, clip: step.clip, copy: debug }, times.writes('resolve'));
if (this.extras.plan === 'faces' && this.terrain.plan && this.terrain.surface && this.terrain.features) {
this.terrain.plan.draw.encode(encoder, canvas, targets.depth!, [width / targets.width, height / targets.height], this.terrain.surface, this.terrain.features);
}
targets.swap();
this.lastFrame = { depth: targets.depth!, pixels: [width, height], viewProj: jittered(viewProj, ndc), eye: [eye.east, eye.north, eye.z] };
if (this.grab && !this.converging) grabbed = this.copy(encoder, { viewProj, eye: [eye.east, eye.north, eye.z], pixel });
}
const read = times.resolve(encoder, { ...this.terrain.stats.jobs, frame: start });
gpu.device.queue.submit([encoder.finish()]);
if (grabbed) {
this.grab!.resolve(grabbed);
this.grab = undefined;
}
if (step && this.eyeFinal()) this.eyeDrawn?.();
read();
probed();
counted();
placed();
cast();
this.cpu = performance.now() - start;
this.drawn = eye ? this.terrain.drawn : 0;
// The model files from the network go to the device cache once the view is idle, so a load never waits for the writes.
if (this.models.unsaved && this.idle()) this.models.save();
// Frames go on while the eye moves or settles on the ground, while the terrain or the ground has
// work that no load waits for, and until a still view has all its jittered frames, which a held frame's change restarts.
if (steer || !settled || this.terrain.working || this.groundLook.working || this.houses.working || this.shadow.pending || this.converging) this.request();
if (steer || this.moved) this.onView?.(this.view);
this.moved = false;
// The waits are for a frame that draws: a held frame shows none of what it took in.
if (!hold) for (const resolve of this.rendered.splice(0)) resolve();
}
/**
* Encodes the producers of instances and the sort of what they stage, for a render `pixels` high (0:
* none draws), with the last frame's depth hiding what it hid.
*/
private vegetation(encoder: GPUCommandEncoder, pixels: number, last: LastFrame | undefined, timing: () => GPUComputePassTimestampWrites | undefined): () => void {
const ground = this.groundLook.group;
if (!pixels || !ground) return () => {};
this.instances.begin(EYE, pixels);
this.instances.occlude(encoder, last);
this.instances.bake(encoder);
const pass = encoder.beginComputePass({ label: 'vegetation', timestampWrites: timing() });
this.instances.run(pass, ground, EYE);
// The anchored meshes' heights share the pass: a pass of their own costs more than their work.
this.terrain.encodeAnchors(pass);
pass.end();
return this.instances.read(encoder);
}
/**
* Draws a cascade's shadow map: the producers and the houses cull for the sun's view, then the
* casters draw. Call the returned function after the submit.
*/
private cast(encoder: GPUCommandEncoder, group: GPUBindGroup, eye: Eye, cascade: number, light: number[]): () => void {
const { gpu, times } = this.gpuState, computeGroup = this.groundLook.computeGroup, label = PASSES[PASSES.indexOf('casters') + 2 * cascade];
const at: [number, number, number] = [eye.east, eye.north, eye.z], viewProj = this.shadow.matrix(cascade, at);
// The sun's view culls nothing by its size on screen.
gpu.device.queue.writeBuffer(this.shadow.frame, 0, this.uniforms(eye, viewProj, 1e-6, light));
this.instances.begin(SUN, 0, this.shadow.run(cascade));
const pass = encoder.beginComputePass({ label, timestampWrites: times.writes(label) });
this.instances.run(pass, group, SUN);
if (computeGroup) this.houses.encodeCasters(pass, computeGroup, { viewProj, eye: at });
pass.end();
const shadowLabel = PASSES[PASSES.indexOf('casters') + 2 * cascade + 1];
const casters = this.shadow.pass(encoder, cascade, times.writes(shadowLabel));
this.instances.cast(casters);
this.houses.cast(casters);
this.terrain.cast(casters);
casters.end();
this.shadow.encodeMips(encoder, cascade, times.writes('mips'));
return this.houses.readCasters(encoder);
}
/**
* A frame before the device draws: it selects the view's nodes only for the records and the meshes' stamps, so that
* their workers start before the pipelines are compiled.
*/
private ask(): void {
const place = this.place(), [width, height] = this.size();
this.terrain.update({ lonLat: this.frame.lonLat(place.east, place.north), above: place.above, viewProj: viewProjection(this.pose.heading, this.pose.pitch, width / height), pixels: Math.max(1, Math.round(height * this.scale)), ahead: ahead(this.pose) });
}
/** The canvas's size in pixels: the size of `start`, or the element's size on the screen. */
private size(): [number, number] {
if (this.output) return this.output;
const ratio = Math.min(devicePixelRatio, MAX_PIXEL_RATIO);
return [Math.max(1, Math.round(this.canvas.clientWidth * ratio)), Math.max(1, Math.round(this.canvas.clientHeight * ratio))];
}
/** Encodes the copy of the canvas, in rows of a multiple of 256 bytes. */
private copy(encoder: GPUCommandEncoder, camera: Omit<Grabbed, 'colour' | 'row' | 'output'>): Grabbed {
const canvas = this.context.getCurrentTexture(), row = Math.ceil(4 * canvas.width / 256) * 256;
const colour = this.gpu.device.createBuffer({ size: row * canvas.height, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
encoder.copyTextureToBuffer({ texture: canvas }, { buffer: colour, bytesPerRow: row }, [canvas.width, canvas.height]);
return { ...camera, colour, row, output: [canvas.width, canvas.height] };
}
/** Fits the canvas and the targets to `size()`; true when the targets are new. */
private fit(): boolean {
const [width, height] = this.size();
if (!this.gpuState.targets.fit(width, height, Math.max(this.scaleNow, MAX_SCALE))) return false;
this.canvas.width = width;
this.canvas.height = height;
return true;
}
/** Frame of terrain.wgsl; `pixel` is the metres per pixel at 1 m from the eye, `light` the key light of `lights()`. */
private uniforms(eye: Eye, viewProj: Float32Array, pixel: number, light: number[]): ArrayBuffer {
const data = new ArrayBuffer(FRAME_BYTES), floats = new Float32Array(data);
floats.set(viewProj, 0);
floats.set(light.slice(0, 4), 16);
floats.set([eye.z, CURVATURE], 20);
new Uint32Array(data)[22] = DEBUG_VIEWS.indexOf(this.extras.debug);
floats[23] = pixel;
return data;
}
/** The look of the regions about the eye under the view's weather. */
private regionLook(eye: Eye): EyeLook {
const [lon, lat] = this.frame.lonLat(eye.east, eye.north);
return eyeLook(this.groundLook.rules.regions, this.groundLook.regionsAt(lon, lat), this.extras.weather);
}
/**
* The look of shade.wgsl: the light keys at the sun's altitude under the weather, with the moon's
* light at night, and the haze, light and grade of the regions about the eye.
*/
private look(eye: Eye, near: EyeLook, lights: Lights, aspect: number, jitter: [number, number], scale: number, sample: number): ArrayBuffer {
const [x, y, z, , bearing] = lights.key, light = lightAt(lights.sunAltitude);
const h = this.pose.heading * RAD, p = this.pose.pitch * RAD, ty = Math.tan(VFOV * RAD / 2), tx = ty * aspect;
const forward = [Math.sin(h) * Math.cos(p), Math.cos(h) * Math.cos(p), Math.sin(p)], right = [Math.cos(h), -Math.sin(h), 0];
const up = [right[1] * forward[2] - right[2] * forward[1], right[2] * forward[0] - right[0] * forward[2], right[0] * forward[1] - right[1] * forward[0]];
return lookUniform({
sun: [x, y, z, bearing], skySun: lights.sun, light: weatherLight(lights.share > 0 ? moonlit(light, lights.share, lights.moonAir) : eclipsed(light, lights.left), near.weather),
eye: near, altitude: eye.z, place: [eye.east, eye.north],
camera: { right: right.map(v => v * tx), up: up.map(v => v * ty), forward },
codes: this.groundLook.codes,
debug: DEBUG_VIEWS.indexOf(this.extras.debug), sample,
jitter, scale, detail: this.instances.detail,
});
}
/**
* The sun and the moon at the view's place, date and time, in the frame. `key` is the light that
* shades and shadows: the direction to it, its light, and its bearing in turns from true north. The
* moon takes the sun's place once the sun's light is gone.
*/
private lights(): Lights {
const { east, north } = this.pose, place = this.frame.lonLat(east, north);
const [hours, minutes, seconds = 0] = this.extras.time.split(':').map(Number), minute = 60 * hours + minutes;
let instant: number;
try {
instant = instantAt(this.extras.date, minute, TIME_ZONE);
} catch {
// The clock skips this time when it changes to summer time.
instant = instantAt(this.extras.date, minute + 60, TIME_ZONE);
}
instant += 1000 * seconds;
// East, north and up to the frame, whose north turns from true north by the convergence.
const c = this.convergence(east, north) * RAD, cos = Math.cos(c), sin = Math.sin(c);
const toFrame = ([e, n, u]: number[]) => [e * cos + n * sin, n * cos - e * sin, u];
const toSun = sunAt(place, instant), toMoon = moonAt(place, instant), sun = toFrame(toSun.toward), moon = toFrame(toMoon.toward);
const altitude = Math.asin(toSun.toward[2]), sunAltitude = altitude / RAD, moonAltitude = Math.asin(toMoon.toward[2]) / RAD;
const phase = Math.acos(Math.min(1, Math.max(-1, -(sun[0] * moon[0] + sun[1] * moon[1] + sun[2] * moon[2])))) / RAD;
const share = moonShare(sunAltitude, moonAltitude, phase), weather = WEATHERS[this.extras.weather].sun;
const turns = (b: number) => ((b / (2 * Math.PI)) % 1 + 1) % 1;
const key = share > 0
? [...moon, weather * share, turns(Math.atan2(toMoon.toward[0], toMoon.toward[1]))]
: [...sun, weather * Math.min(1, Math.max(0, (altitude + 0.05) / 0.15)), turns(Math.atan2(toSun.toward[0], toSun.toward[1]))];
// An eclipse fades as the sun sets: below the horizon the sky's light is the twilight's.
const left = share > 0 ? 1 : 1 - (1 - sunlightLeft(toSun, toMoon)) * Math.min(1, Math.max(0, (sunAltitude + 4) / 4));
const drawn = drawnMoon(toSun, toMoon);
const m = starFrame(place, instant);
const stars = [0, 1, 2].map(j => cos * m[j] + sin * m[3 + j]).concat([0, 1, 2].map(j => cos * m[3 + j] - sin * m[j]), m.slice(6)) as Mat3;
return {
key, sun, sunAltitude, moon, moonAltitude, moonAir: airColour(moonAltitude), phase, share, stars,
drawnMoon: toFrame(drawn.toward), moonRadius: drawn.radius, left, activity: solarActivity(instant), seed: coronaSeed(instant),
};
}
}
/** The sun and the moon of `lights()`: directions in the frame, altitudes and the phase angle in degrees. */
interface Lights {
key: number[];
sun: number[];
sunAltitude: number;
moon: number[];
moonAltitude: number;
/** The air's colour at the moon's altitude (`airColour`). */
moonAir: [number, number, number];
phase: number;
/** The moon's share of its full light, 0 while the sun is the light. */
share: number;
/** J2000 equatorial directions to the frame, rows first. */
stars: Mat3;
/** The moon as the sky draws it (light/eclipse.ts): toward it in the frame, and its half width in radians. */