@johnmorrisdotca/wakusei-planets 0.59.0 → 0.61.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 (43) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/NOTICE.md +9 -0
  3. package/README.md +31 -3
  4. package/dist/bodies/earth.js +22 -1
  5. package/dist/data/places-moon.d.ts +12 -9
  6. package/dist/data/places-moon.js +3 -3
  7. package/dist/element.d.ts +1 -1
  8. package/dist/flat/bodies.d.ts +122 -0
  9. package/dist/flat/bodies.js +115 -0
  10. package/dist/flat/define.d.ts +3 -0
  11. package/dist/flat/define.js +6 -0
  12. package/dist/flat/element.d.ts +145 -0
  13. package/dist/flat/element.js +1614 -0
  14. package/dist/flat/geometry.d.ts +127 -0
  15. package/dist/flat/geometry.js +121 -0
  16. package/dist/flat/index.d.ts +5 -0
  17. package/dist/flat/index.js +6 -0
  18. package/dist/flat/scene.d.ts +152 -0
  19. package/dist/flat/scene.js +195 -0
  20. package/dist/flat/system-define.d.ts +3 -0
  21. package/dist/flat/system-define.js +6 -0
  22. package/dist/flat/system-element.d.ts +133 -0
  23. package/dist/flat/system-element.js +1435 -0
  24. package/dist/flat/system-words.d.ts +28 -0
  25. package/dist/flat/system-words.js +102 -0
  26. package/dist/flat/system.d.ts +440 -0
  27. package/dist/flat/system.js +521 -0
  28. package/dist/flat/words.d.ts +55 -0
  29. package/dist/flat/words.js +133 -0
  30. package/dist/space/travel.js +36 -5
  31. package/dist/surface/drive.d.ts +5 -2
  32. package/dist/surface/drive.js +13 -15
  33. package/dist/surface/element.d.ts +38 -1
  34. package/dist/surface/element.js +144 -14
  35. package/dist/surface/index.d.ts +1 -0
  36. package/dist/surface/index.js +1 -0
  37. package/dist/surface/model.d.ts +54 -0
  38. package/dist/surface/model.js +147 -0
  39. package/dist/surface/rig.d.ts +125 -0
  40. package/dist/surface/rig.js +107 -0
  41. package/dist/surface/scene.d.ts +3 -0
  42. package/dist/surface/scene.js +22 -1
  43. package/package.json +38 -2
@@ -66,7 +66,7 @@ const num = (value, fallback) => {
66
66
  * ```
67
67
  */
68
68
  export class WakuseiSurface extends HTMLElement {
69
- static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects", "drive", "drive-camera", "drive-drag", "watch", "watch-from", "watch-camera"];
69
+ static observedAttributes = ["quality", "shadows", "detail", "exposure", "site", "time", "heading", "pitch", "fov", "tiles", "lang", "body", "standby", "scale", "stick", "objects", "drive", "drive-camera", "drive-drag", "drive-model", "watch", "watch-from", "watch-camera"];
70
70
  #root;
71
71
  #stage;
72
72
  #noteEl;
@@ -114,6 +114,10 @@ export class WakuseiSurface extends HTMLElement {
114
114
  #chosen;
115
115
  /** The rover being driven (`drive="on"`), the view of it, the driver's own turn of the view, the path left, the dust thrown, and the places it cannot go. */
116
116
  #vehicle;
117
+ /** The rover model asked for with `drive-model`, once it has loaded, and the address it was asked for at. */
118
+ #model;
119
+ #modelUrl = "";
120
+ #modelAbort;
117
121
  #driveCamera = "chase";
118
122
  #camOffset = { azimuth: 0, pitch: 0 };
119
123
  #driveEyeUp = 0;
@@ -236,6 +240,7 @@ export class WakuseiSurface extends HTMLElement {
236
240
  clearTimeout(this.#landingTimer);
237
241
  this.#gate?.cancel();
238
242
  clearTimeout(this.#walkTimer);
243
+ this.#dropModel();
239
244
  for (const [type, fn] of [["pointerdown", this.#onPointerDown], ["pointermove", this.#onPointerMove], ["pointerup", this.#onPointerUp], ["pointercancel", this.#onPointerUp], ["wheel", this.#onWheel], ["keydown", this.#onKeyDown], ["keyup", this.#onKeyUp], ["blur", this.#onBlur]])
240
245
  this.removeEventListener(type, fn);
241
246
  this.#view?.dispose();
@@ -255,6 +260,10 @@ export class WakuseiSurface extends HTMLElement {
255
260
  this.#syncLanding(name !== "watch");
256
261
  return;
257
262
  }
263
+ if (name === "drive-model") {
264
+ this.#syncModel();
265
+ return;
266
+ }
258
267
  if (name === "drive-camera") {
259
268
  this.driveCamera = this.getAttribute("drive-camera") === "seat" ? "seat" : "chase";
260
269
  return;
@@ -499,7 +508,7 @@ export class WakuseiSurface extends HTMLElement {
499
508
  this.#measured += 1;
500
509
  if (this.#drawScale < 1)
501
510
  this.#scaled += 1;
502
- scene.apply({ eye: { east: this.#at.east, north: this.#at.north, up: this.#eyeUp() }, look: this.#look, sky: this.#sky, shadows: this.getAttribute("shadows") !== "off", detail: this.getAttribute("detail") !== "off", exposure: num(this.getAttribute("exposure"), 1.6), quality: this.#quality(), scale: this.#drawScale, objects: this.#objects.length > 0, ...(this.#vehicle === undefined ? {} : { vehicle: this.#vehicle, trail: this.#trail, dust: this.#dust.position }), ...(this.#landing === undefined ? {} : { lander: this.#landerState(), dust: this.#dust.position }), measure: measure || this.getAttribute("measure") !== null });
511
+ scene.apply({ eye: { east: this.#at.east, north: this.#at.north, up: this.#eyeUp() }, look: this.#look, sky: this.#sky, shadows: this.getAttribute("shadows") !== "off", detail: this.getAttribute("detail") !== "off", exposure: num(this.getAttribute("exposure"), 1.6), quality: this.#quality(), scale: this.#drawScale, objects: this.#objects.length > 0, ...(this.#vehicle === undefined ? {} : { vehicle: this.#vehicle, ...(this.#model === undefined ? {} : { model: this.#model }), trail: this.#trail, dust: this.#dust.position }), ...(this.#landing === undefined ? {} : { lander: this.#landerState(), dust: this.#dust.position }), measure: measure || this.getAttribute("measure") !== null });
503
512
  this.#view.invalidate();
504
513
  this.#draws += 1;
505
514
  this.#placeLabels();
@@ -545,6 +554,7 @@ export class WakuseiSurface extends HTMLElement {
545
554
  const v = this.#vehicle;
546
555
  this.#vehicle = undefined;
547
556
  this.#trail = [];
557
+ this.#dropModel();
548
558
  this.#at = { east: v.east, north: v.north };
549
559
  this.#changed();
550
560
  return;
@@ -562,15 +572,78 @@ export class WakuseiSurface extends HTMLElement {
562
572
  for (const el of this.#labelEls.values())
563
573
  el.hidden = true;
564
574
  this.choose(undefined);
575
+ this.#syncModel();
565
576
  this.#syncDriveCamera();
566
577
  this.#changed();
567
578
  }
579
+ /** The vehicle's measures: a loaded model's, or the lunar rover's. */
580
+ #rig() {
581
+ return this.#model?.rig ?? ROVER;
582
+ }
583
+ /**
584
+ * The rover model being drawn in place of the shapes, with the node names it has and the angles its wheels and pivots were last set to; `undefined` while none is asked for (`drive-model`), while it loads or when it could not be loaded.
585
+ *
586
+ * @example
587
+ * ```ts no-run
588
+ * const surface = document.querySelector("wakusei-surface") as HTMLElement & { driveModel?: { url: string; nodes: readonly string[] } };
589
+ * surface.addEventListener("wakusei-model", () => console.log(surface.driveModel?.nodes.join(" ")));
590
+ * surface.setAttribute("drive-model", "/models/perseverance.glb");
591
+ * ```
592
+ */
593
+ get driveModel() {
594
+ const m = this.#model;
595
+ return m === undefined ? undefined : { url: this.#modelUrl, nodes: m.nodes, angles: { ...m.angles }, rig: m.rig, renders: m.renders };
596
+ }
597
+ #dropModel() {
598
+ this.#modelAbort?.abort();
599
+ this.#modelAbort = undefined;
600
+ this.#model?.dispose();
601
+ this.#model = undefined;
602
+ this.#modelUrl = "";
603
+ }
604
+ /**
605
+ * Load the model `drive-model` names, once the rover is being driven: its file is fetched and its loader imported only then. Until it is in (or if it cannot be loaded) the shapes are drawn; `wakusei-model` is sent when it is
606
+ * drawn, with `detail.url` and `detail.nodes`, and `wakusei-model-error` with `detail.url` and `detail.reason` when it cannot be.
607
+ */
608
+ #syncModel() {
609
+ const url = this.getAttribute("drive-model") ?? "";
610
+ if (this.#vehicle === undefined || url === "") {
611
+ this.#dropModel();
612
+ if (this.#vehicle !== undefined)
613
+ this.#changed();
614
+ return;
615
+ }
616
+ if (url === this.#modelUrl)
617
+ return;
618
+ this.#dropModel();
619
+ this.#modelUrl = url;
620
+ const abort = new AbortController();
621
+ this.#modelAbort = abort;
622
+ void import("./model.js")
623
+ .then((m) => m.loadVehicleModel(url, { signal: abort.signal }))
624
+ .then((model) => {
625
+ if (abort.signal.aborted) {
626
+ model.dispose();
627
+ return;
628
+ }
629
+ this.#model = model;
630
+ this.#syncDriveCamera();
631
+ this.#changed();
632
+ this.dispatchEvent(new CustomEvent("wakusei-model", { detail: { url, nodes: model.nodes }, bubbles: true, composed: true }));
633
+ })
634
+ .catch((error) => {
635
+ if (abort.signal.aborted)
636
+ return;
637
+ this.#modelUrl = "";
638
+ this.dispatchEvent(new CustomEvent("wakusei-model-error", { detail: { url, reason: error instanceof Error ? error.message : String(error) }, bubbles: true, composed: true }));
639
+ });
640
+ }
568
641
  /** The eyes where the view of the rover puts them. */
569
642
  #syncDriveCamera() {
570
643
  const v = this.#vehicle;
571
644
  if (v === undefined)
572
645
  return;
573
- const view = driveView(v, this.#driveCamera, this.#camOffset, (e, n) => this.#groundAt(e, n), this.driveDrag);
646
+ const view = driveView(v, this.#driveCamera, this.#camOffset, (e, n) => this.#groundAt(e, n), this.driveDrag, this.#rig());
574
647
  this.#at = { east: view.eye.east, north: view.eye.north };
575
648
  this.#driveEyeUp = view.eye.up;
576
649
  this.#look = clampLook({ azimuth: view.azimuth, pitch: view.pitch, fov: this.#look.fov });
@@ -599,17 +672,18 @@ export class WakuseiSurface extends HTMLElement {
599
672
  const ground = (e, n) => this.#groundAt(e, n);
600
673
  const blockers = this.#obstacles();
601
674
  const blocked = (e, n) => blockers.some((b) => (e - b.x) ** 2 + (n - b.y) ** 2 < b.r * b.r);
675
+ const rig = this.#rig();
602
676
  const steps = Math.max(1, Math.ceil(seconds * 60));
603
677
  const dt = seconds / steps;
604
678
  for (let i = 0; i < steps; i += 1) {
605
- v = driveStep(v, input, dt, ground, blocked);
679
+ v = driveStep(v, input, dt, ground, blocked, rig);
606
680
  // each wheel on the ground throws grains up and back: the faster, the more
607
681
  if (!v.airborne && Math.abs(v.speed) > 0.6) {
608
682
  const h = (v.heading * Math.PI) / 180;
609
683
  const [fx, fz] = [Math.sin(h), Math.cos(h)];
610
684
  const grains = Math.abs(v.speed) * dt * 26;
611
685
  const [rx, rz] = [Math.cos(h), -Math.sin(h)];
612
- for (const [wx, , wz] of ROVER.wheels) {
686
+ for (const [wx, , wz] of rig.wheels) {
613
687
  const w = toWorld(v, [wx, 0, wz]);
614
688
  for (let k = 0; k < grains + Math.random() * 0.999; k += 1) {
615
689
  // thrown up and back from the tyre in a fan: the faster the rover, the wider and farther
@@ -659,7 +733,26 @@ export class WakuseiSurface extends HTMLElement {
659
733
  return true;
660
734
  }
661
735
  // --- watching the landing (`watch="landing"`): Apollo 17's powered descent from the lunar module's window or from the ground ---------------------------------------------------------------------
662
- /** The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched. */
736
+ /**
737
+ * The descent being watched: its clock in seconds from ignition, whether it runs, the camera and what the lunar module is doing at that moment; `undefined` when it is not watched.
738
+ *
739
+ * Two events say what happens to it, both bubbling and composed. `wakusei-landing-state` is sent when it starts or stops running (`playLanding()`, `pauseLanding()`, and the clock reaching the touchdown),
740
+ * when `landingRate` changes and when `watch-camera` changes; its `detail` is `{ t, playing, rate, camera, ended }` (`t` in seconds from ignition, `ended` true at the touchdown), so a page can keep the pause
741
+ * state without reading `landing` every second. `wakusei-landing-ended` is sent once each time the clock arrives at the touchdown (T+12:05, 725 s), by running or by a seek; its `detail` is
742
+ * `{ t: 725, rate, camera }`, and it is sent again only after the clock has left the touchdown and come back.
743
+ *
744
+ * @example
745
+ * ```ts no-run
746
+ * import type { WakuseiSurface } from "@johnmorrisdotca/wakusei-planets/surface/element";
747
+ *
748
+ * const view = document.querySelector("wakusei-surface") as WakuseiSurface;
749
+ * view.addEventListener("wakusei-landing-state", (event) => {
750
+ * const { playing, rate, camera } = (event as CustomEvent).detail;
751
+ * location.hash = `${playing ? "play" : "pause"}-${rate}-${camera}`;
752
+ * });
753
+ * view.addEventListener("wakusei-landing-ended", () => console.log("the lunar module is down"));
754
+ * ```
755
+ */
663
756
  get landing() {
664
757
  const l = this.#landing;
665
758
  if (l === undefined)
@@ -689,8 +782,14 @@ export class WakuseiSurface extends HTMLElement {
689
782
  return this.#landing?.rate ?? 1;
690
783
  }
691
784
  set landingRate(value) {
692
- if (this.#landing !== undefined)
693
- this.#landing.rate = Math.min(16, Math.max(0.25, value));
785
+ const l = this.#landing;
786
+ if (l === undefined)
787
+ return;
788
+ const rate = Math.min(16, Math.max(0.25, value));
789
+ if (rate === l.rate)
790
+ return;
791
+ l.rate = rate;
792
+ this.#landingAnnounce();
694
793
  }
695
794
  /** Run the descent from where the clock is (from the start again if it had ended). */
696
795
  playLanding() {
@@ -699,17 +798,31 @@ export class WakuseiSurface extends HTMLElement {
699
798
  return;
700
799
  if (l.t >= LANDING.duration)
701
800
  this.landingTime = l.camera === "ground" ? 540 : LANDING.viewStart;
801
+ const was = l.playing;
702
802
  l.playing = true;
703
803
  this.#landingAt = performance.now();
804
+ if (!was)
805
+ this.#landingAnnounce();
704
806
  this.#landingTick();
705
807
  }
706
808
  /** Hold the descent where it is. */
707
809
  pauseLanding() {
708
- if (this.#landing === undefined)
810
+ const l = this.#landing;
811
+ if (l === undefined)
709
812
  return;
710
- this.#landing.playing = false;
813
+ const was = l.playing;
814
+ l.playing = false;
711
815
  clearTimeout(this.#landingTimer);
712
816
  this.#landingFrame(0, true);
817
+ if (was)
818
+ this.#landingAnnounce();
819
+ }
820
+ /** Tell a page the descent's state changed: `wakusei-landing-state` with the clock, whether it runs, the rate, the camera and whether it has ended. */
821
+ #landingAnnounce() {
822
+ const l = this.#landing;
823
+ if (l === undefined)
824
+ return;
825
+ this.dispatchEvent(new CustomEvent("wakusei-landing-state", { detail: { t: l.t, playing: l.playing, rate: l.rate, camera: l.camera, ended: l.t >= LANDING.duration }, bubbles: true, composed: true }));
713
826
  }
714
827
  /** The touchdown point: where the lunar module stands at Apollo 17 (the published place), or the site point where it has none. */
715
828
  #touchdown() {
@@ -746,13 +859,16 @@ export class WakuseiSurface extends HTMLElement {
746
859
  return;
747
860
  if (this.#landing.camera !== camera)
748
861
  this.#look = clampLook({ ...this.#look, fov: camera === "ground" ? 27 : 74 });
862
+ const changed = this.#landing.camera !== camera;
749
863
  this.#landing.camera = camera;
750
864
  this.#landing.from = from;
751
865
  this.#camOffset = { azimuth: 0, pitch: 0 };
752
866
  this.#landingFrame(0, true);
867
+ if (changed)
868
+ this.#landingAnnounce();
753
869
  return;
754
870
  }
755
- this.#landing = { t: camera === "ground" ? 540 : LANDING.viewStart, playing: true, rate: 1, camera, from, passed: 0, second: -1 };
871
+ this.#landing = { t: camera === "ground" ? 540 : LANDING.viewStart, playing: true, rate: 1, camera, from, passed: 0, second: -1, ended: false };
756
872
  this.#landing.passed = calloutsBy(this.#landing.t).length;
757
873
  this.#dust = new DustField(20000, 17);
758
874
  this.#camOffset = { azimuth: 0, pitch: 0 };
@@ -772,6 +888,13 @@ export class WakuseiSurface extends HTMLElement {
772
888
  const l = this.#landing;
773
889
  if (l === undefined)
774
890
  return;
891
+ // arriving at the touchdown, by running or by a seek, stops the clock
892
+ const atEnd = l.t >= LANDING.duration;
893
+ const stopped = atEnd && l.playing;
894
+ if (stopped) {
895
+ l.playing = false;
896
+ clearTimeout(this.#landingTimer);
897
+ }
775
898
  const pose = landingAt(l.t);
776
899
  const td = this.#touchdown();
777
900
  const ground = (e, n) => this.#groundAt(e, n);
@@ -859,6 +982,15 @@ export class WakuseiSurface extends HTMLElement {
859
982
  l.second = second;
860
983
  this.dispatchEvent(new CustomEvent("wakusei-landing-clock", { detail: { t: l.t, clock, altitude: pose.altitude, speed: pose.speed, descent: pose.descent, playing: l.playing, callout: newest === undefined ? undefined : { id: newest.id, t: newest.t, en: newest.en, ja: newest.ja, reported: newest.reported } }, bubbles: true, composed: true }));
861
984
  }
985
+ if (stopped)
986
+ this.#landingAnnounce();
987
+ // the descent ends once each time the clock arrives at the touchdown; a seek back or a play from the start makes it ready to end again
988
+ if (atEnd && !l.ended) {
989
+ l.ended = true;
990
+ this.dispatchEvent(new CustomEvent("wakusei-landing-ended", { detail: { t: l.t, rate: l.rate, camera: l.camera }, bubbles: true, composed: true }));
991
+ }
992
+ else if (!atEnd)
993
+ l.ended = false;
862
994
  this.#changed(l.playing);
863
995
  }
864
996
  /** While the descent runs: the clock moves by the real time between frames (times the rate), at most thirty times a second; at the touchdown, or paused, nothing is drawn. */
@@ -872,10 +1004,8 @@ export class WakuseiSurface extends HTMLElement {
872
1004
  this.#landingAt = now;
873
1005
  const seconds = Math.min(dt * l.rate, LANDING.duration - l.t);
874
1006
  l.t += seconds;
875
- if (l.t >= LANDING.duration - 1e-6) {
1007
+ if (l.t >= LANDING.duration - 1e-6)
876
1008
  l.t = LANDING.duration;
877
- l.playing = false;
878
- }
879
1009
  this.#landingFrame(seconds, false);
880
1010
  if (l.playing)
881
1011
  this.#landingTimer = setTimeout(this.#landingTick, 33);
@@ -7,6 +7,7 @@ export type { SurfaceState } from "./element.ts";
7
7
  export { ascentParts, landerParts, roverParts } from "./shapes.ts";
8
8
  export { calloutsBy, CALLOUTS, clockText, LANDING, landingAt, type Callout, type LandingPose } from "./landing.ts";
9
9
  export { DustField } from "./dust.ts";
10
+ export { MODEL_NODES, fromModelFrame, modelPose, modelShadowParts, rigOf, type ModelNodes, type Rig } from "./rig.ts";
10
11
  export { driveParts, driveStep, driveView, startDrive, ROVER, type DriveDrag, type DriveInput, type DriveState, type DriveView } from "./drive.ts";
11
12
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT, type Part, type SiteObject } from "./objects.ts";
12
13
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace, type Crater, type Rock } from "./detail.ts";
@@ -7,6 +7,7 @@ export { loadPlan, loadTerrain } from "./load.js";
7
7
  export { ascentParts, landerParts, roverParts } from "./shapes.js";
8
8
  export { calloutsBy, CALLOUTS, clockText, LANDING, landingAt } from "./landing.js";
9
9
  export { DustField } from "./dust.js";
10
+ export { MODEL_NODES, fromModelFrame, modelPose, modelShadowParts, rigOf } from "./rig.js";
10
11
  export { driveParts, driveStep, driveView, startDrive, ROVER } from "./drive.js";
11
12
  export { keepAway, objectParts, objectsOf, partShadows, traverseOf, KEEP_OUT } from "./objects.js";
12
13
  export { craterIn, craterProfile, madeGround, setKeepOut, rimBoost, rocksAround, standingPlace } from "./detail.js";
@@ -0,0 +1,54 @@
1
+ import { type DriveState } from "./drive.ts";
2
+ import { type Rig } from "./rig.ts";
3
+ /**
4
+ * A rover model that has been loaded: its rig for the drive step and the calls the scene makes. Made by `loadVehicleModel`.
5
+ *
6
+ * @example
7
+ * ```ts no-run
8
+ * import { loadVehicleModel, type VehicleModel } from "@johnmorrisdotca/wakusei-planets/surface/model";
9
+ *
10
+ * const model: VehicleModel = await loadVehicleModel("/models/perseverance.glb");
11
+ * console.log(model.rig.wheelbase, model.nodes.length);
12
+ * model.dispose();
13
+ * ```
14
+ */
15
+ export interface VehicleModel {
16
+ /** What a drive step and the seat view take from the model. */
17
+ readonly rig: Rig;
18
+ /** The names of the nodes the model has that this package uses (`wheel-fl`, `steer-fr`, `eye`, ...). */
19
+ readonly nodes: readonly string[];
20
+ /** The model's height over the ground, metres. */
21
+ readonly height: number;
22
+ /** Put the model where the drive state is, with the wheels rolled and steered, lit from `sun` (a direction in the scene's frame, east, up, minus north) at `strength` (0 to 1). */
23
+ place(state: DriveState, sun: readonly [number, number, number], strength: number): void;
24
+ /** Draw it with the page's renderer over what is drawn, with the ground's view-projection matrix. */
25
+ render(gl: {
26
+ render(scene: unknown, camera: unknown): void;
27
+ autoClear: boolean;
28
+ }, viewProjection: Float32Array): void;
29
+ /** The roll and steer angles each named node has been set to by the last `place`, for a test. */
30
+ readonly angles: Readonly<Record<string, number>>;
31
+ /** How many times it has been drawn, for a test. */
32
+ readonly renders: number;
33
+ /** Let go of the geometry, the materials and the textures. */
34
+ dispose(): void;
35
+ }
36
+ /**
37
+ * Load a rover model from a GLB and read its rig. The nodes it must give are in `MODEL_NODES`: `wheel-xx` (rolled about X), `steer-xx` (turned about Y) and `eye` or `seat-commander`; a model with no corner wheel is refused.
38
+ * The loader and the meshopt decoder are three.js's own add-ons, imported when this is first called. Each call makes its own copy (the loaded file is read again from the browser's cache), which `dispose()` frees.
39
+ *
40
+ * @param url - Where the GLB is served from.
41
+ * @param options - `signal` to cancel the request.
42
+ * @returns The model, or a rejection when the file cannot be read or has no corner wheel.
43
+ *
44
+ * @example
45
+ * ```ts no-run
46
+ * import { loadVehicleModel } from "@johnmorrisdotca/wakusei-planets/surface/model";
47
+ *
48
+ * const model = await loadVehicleModel("https://johnmorrisdotca.github.io/wakusei-planets/models/perseverance.glb");
49
+ * console.log(model.rig.track.toFixed(2), "m between the wheels");
50
+ * ```
51
+ */
52
+ export declare function loadVehicleModel(url: string, options?: {
53
+ signal?: AbortSignal;
54
+ }): Promise<VehicleModel>;
@@ -0,0 +1,147 @@
1
+ import { toWorld } from "./drive.js";
2
+ import { MODEL_NODES, fromModelFrame, modelPose, rigOf } from "./rig.js";
3
+ /**
4
+ * Load a rover model from a GLB and read its rig. The nodes it must give are in `MODEL_NODES`: `wheel-xx` (rolled about X), `steer-xx` (turned about Y) and `eye` or `seat-commander`; a model with no corner wheel is refused.
5
+ * The loader and the meshopt decoder are three.js's own add-ons, imported when this is first called. Each call makes its own copy (the loaded file is read again from the browser's cache), which `dispose()` frees.
6
+ *
7
+ * @param url - Where the GLB is served from.
8
+ * @param options - `signal` to cancel the request.
9
+ * @returns The model, or a rejection when the file cannot be read or has no corner wheel.
10
+ *
11
+ * @example
12
+ * ```ts no-run
13
+ * import { loadVehicleModel } from "@johnmorrisdotca/wakusei-planets/surface/model";
14
+ *
15
+ * const model = await loadVehicleModel("https://johnmorrisdotca.github.io/wakusei-planets/models/perseverance.glb");
16
+ * console.log(model.rig.track.toFixed(2), "m between the wheels");
17
+ * ```
18
+ */
19
+ export async function loadVehicleModel(url, options = {}) {
20
+ const [three, { GLTFLoader }, { MeshoptDecoder }] = await Promise.all([import("three"), import("three/addons/loaders/GLTFLoader.js"), import("three/addons/libs/meshopt_decoder.module.js")]);
21
+ options.signal?.throwIfAborted();
22
+ const loader = new GLTFLoader();
23
+ loader.setMeshoptDecoder(MeshoptDecoder);
24
+ const gltf = await loader.loadAsync(url);
25
+ options.signal?.throwIfAborted();
26
+ return makeModel(three, gltf.scene);
27
+ }
28
+ function makeModel(T, root) {
29
+ root.matrixAutoUpdate = false;
30
+ root.updateMatrixWorld(true);
31
+ const found = new Map();
32
+ root.traverse((node) => {
33
+ if (node.name !== "" && !found.has(node.name))
34
+ found.set(node.name, node);
35
+ });
36
+ const names = [...MODEL_NODES.wheels, ...MODEL_NODES.steers, ...MODEL_NODES.eyes].filter((name) => found.has(name));
37
+ const at = {};
38
+ const here = new T.Vector3();
39
+ for (const name of names) {
40
+ found.get(name).getWorldPosition(here);
41
+ at[name] = fromModelFrame([here.x, here.y, here.z]);
42
+ }
43
+ const box = new T.Box3().setFromObject(root);
44
+ const size = box.getSize(new T.Vector3());
45
+ // a wheel's radius: half the height of the biggest wheel node
46
+ let wheelRadius = 0;
47
+ const wheelBox = new T.Box3();
48
+ for (const name of MODEL_NODES.wheels) {
49
+ const node = found.get(name);
50
+ if (node === undefined)
51
+ continue;
52
+ wheelBox.setFromObject(node);
53
+ wheelRadius = Math.max(wheelRadius, (wheelBox.max.y - wheelBox.min.y) / 2);
54
+ }
55
+ const nodes = { at, wheelRadius, length: size.z };
56
+ const rig = rigOf(nodes);
57
+ if (rig === undefined) {
58
+ disposeAll(root);
59
+ throw new Error("the model has no wheel-fl, wheel-fr, wheel-rl and wheel-rr nodes");
60
+ }
61
+ // the nodes that move, with the turn they were loaded with
62
+ const moving = new Map();
63
+ for (const name of [...MODEL_NODES.wheels, ...MODEL_NODES.steers]) {
64
+ const node = found.get(name);
65
+ if (node !== undefined)
66
+ moving.set(name, { node, base: node.quaternion.clone() });
67
+ }
68
+ root.traverse((node) => {
69
+ node.frustumCulled = false;
70
+ });
71
+ const scene = new T.Scene();
72
+ const sunLight = new T.DirectionalLight(0xffffff, 3);
73
+ const fill = new T.AmbientLight(0xffffff, 0.35);
74
+ scene.add(root, sunLight, fill, sunLight.target);
75
+ const camera = new T.Camera();
76
+ camera.matrixAutoUpdate = false;
77
+ const angles = {};
78
+ let renders = 0;
79
+ const [ax, ay] = [new T.Vector3(1, 0, 0), new T.Vector3(0, 1, 0)];
80
+ const turn = new T.Quaternion();
81
+ return {
82
+ rig,
83
+ nodes: names,
84
+ height: size.y,
85
+ angles,
86
+ get renders() {
87
+ return renders;
88
+ },
89
+ place(state, sun, strength) {
90
+ const pose = modelPose(state);
91
+ // a positive roll is forward (the top moving toward +Z, a turn about +X); the model's +X is the left, so a steer to the right is a turn about +Y the other way
92
+ for (const [name, entry] of moving) {
93
+ const roll = pose.roll[name];
94
+ const steer = pose.steer[name];
95
+ if (roll !== undefined) {
96
+ angles[name] = roll;
97
+ entry.node.quaternion.copy(entry.base).multiply(turn.setFromAxisAngle(ax, roll));
98
+ }
99
+ else if (steer !== undefined) {
100
+ angles[name] = -steer;
101
+ entry.node.quaternion.copy(entry.base).multiply(turn.setFromAxisAngle(ay, -steer));
102
+ }
103
+ entry.node.matrixWorldNeedsUpdate = true;
104
+ entry.node.updateMatrix();
105
+ }
106
+ // the model's frame in the scene's (x east, y up, z minus north): the drive frame's axes, with left and right swapped for the model's
107
+ const o = toWorld(state, [0, 0, 0]);
108
+ const axis = (v) => {
109
+ const p = toWorld(state, v);
110
+ return [p[0] - o[0], p[1] - o[1], -(p[2] - o[2])];
111
+ };
112
+ const [cx, cy, cz] = [axis([-1, 0, 0]), axis([0, 1, 0]), axis([0, 0, 1])];
113
+ root.matrix.set(cx[0], cy[0], cz[0], o[0], cx[1], cy[1], cz[1], o[1], cx[2], cy[2], cz[2], -o[2], 0, 0, 0, 1);
114
+ root.updateMatrixWorld(true);
115
+ sunLight.position.set(sun[0] * 100, sun[1] * 100, sun[2] * 100).add(here.set(o[0], o[1], -o[2]));
116
+ sunLight.target.position.set(o[0], o[1], -o[2]);
117
+ sunLight.target.updateMatrixWorld();
118
+ sunLight.intensity = 3 * strength;
119
+ },
120
+ render(gl, viewProjection) {
121
+ camera.projectionMatrix.fromArray(viewProjection);
122
+ camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
123
+ renders += 1;
124
+ const was = gl.autoClear;
125
+ gl.autoClear = false;
126
+ gl.render(scene, camera);
127
+ gl.autoClear = was;
128
+ },
129
+ dispose() {
130
+ disposeAll(root);
131
+ },
132
+ };
133
+ }
134
+ function disposeAll(root) {
135
+ root.traverse((node) => {
136
+ const mesh = node;
137
+ if (mesh.geometry === undefined)
138
+ return;
139
+ mesh.geometry.dispose();
140
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
141
+ for (const value of Object.values(material))
142
+ if (value !== null && typeof value === "object" && "isTexture" in value)
143
+ value.dispose();
144
+ material.dispose();
145
+ }
146
+ });
147
+ }
@@ -0,0 +1,125 @@
1
+ import { type DriveState } from "./drive.ts";
2
+ import { type Part, type V3 } from "./shapes.ts";
3
+ /**
4
+ * The nodes a rover model may name: `wheel-fl`, `wheel-fr`, `wheel-ml`, `wheel-mr`, `wheel-rl` and `wheel-rr` roll about X (their origin is the wheel's centre), `steer-fl`, `steer-fr`, `steer-rl` and `steer-rr`
5
+ * turn about Y (a pivot holding the wheel and its leg), and the eye is `eye`, or `seat-commander` (the left seat) when the model has no `eye`. The model's metres have +Y up and its front on +Z.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { MODEL_NODES } from "@johnmorrisdotca/wakusei-planets/surface";
10
+ *
11
+ * console.log(MODEL_NODES.wheels.join(" "), MODEL_NODES.eyes.join(" or "));
12
+ * ```
13
+ */
14
+ export declare const MODEL_NODES: {
15
+ readonly wheels: readonly ["wheel-fl", "wheel-fr", "wheel-ml", "wheel-mr", "wheel-rl", "wheel-rr"];
16
+ readonly steers: readonly ["steer-fl", "steer-fr", "steer-rl", "steer-rr"];
17
+ readonly eyes: readonly ["eye", "seat-commander"];
18
+ };
19
+ /**
20
+ * The measures a drive step takes from a vehicle: where its four corner wheels touch the ground, how big they are and where the eyes are. `ROVER` is the lunar rover's; a model gives its own (`rigOf`).
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { ROVER, type Rig } from "@johnmorrisdotca/wakusei-planets/surface";
25
+ *
26
+ * const rig: Rig = ROVER;
27
+ * console.log(rig.wheels.length, rig.wheelRadius);
28
+ * ```
29
+ */
30
+ export interface Rig {
31
+ length: number;
32
+ wheelbase: number;
33
+ track: number;
34
+ wheelRadius: number;
35
+ /** The four corner wheels' centres in the vehicle's frame (x right, y up, z forward): front left, front right, rear left, rear right. */
36
+ wheels: readonly V3[];
37
+ /** The eyes of the view from the vehicle. */
38
+ seat: V3;
39
+ }
40
+ /**
41
+ * What the loader finds in a model: where each named node's origin is (in the drive frame, metres), the radius of the wheels and the length of the model along Z.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import type { ModelNodes } from "@johnmorrisdotca/wakusei-planets/surface";
46
+ *
47
+ * const nodes: ModelNodes = { at: { eye: [0, 1.9, 0] }, wheelRadius: 0.3, length: 2.4 };
48
+ * console.log(Object.keys(nodes.at).length, nodes.length);
49
+ * ```
50
+ */
51
+ export interface ModelNodes {
52
+ /** The world position of each named node that exists. */
53
+ at: Readonly<Record<string, V3>>;
54
+ /** The radius of the wheels, metres, from the biggest wheel's size (`0` when it could not be told). */
55
+ wheelRadius: number;
56
+ /** The model's length along Z, metres. */
57
+ length: number;
58
+ }
59
+ /**
60
+ * The rig of a model: its four corner wheels where its `wheel-fl`, `wheel-fr`, `wheel-rl` and `wheel-rr` nodes are, its wheelbase and track from them, its eyes where `eye` (or `seat-commander`) is. What a model does
61
+ * not say is the lunar rover's value; a model with no corner wheel at all is `undefined` (it cannot be driven by its wheels).
62
+ *
63
+ * @param nodes - What was found in the model.
64
+ * @returns The rig, or `undefined` when a corner wheel is missing.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * import { rigOf } from "@johnmorrisdotca/wakusei-planets/surface";
69
+ *
70
+ * const rig = rigOf({ at: { "wheel-fl": [-1, 0.25, 1], "wheel-fr": [1, 0.25, 1], "wheel-rl": [-1, 0.25, -1], "wheel-rr": [1, 0.25, -1], eye: [0, 2, 0] }, wheelRadius: 0.25, length: 3 });
71
+ * console.log(rig?.wheelbase, rig?.track, rig?.seat);
72
+ * ```
73
+ */
74
+ export declare function rigOf(nodes: ModelNodes): Rig | undefined;
75
+ /**
76
+ * How far each named node of a rover model is turned for a drive state: the wheels' roll about X (the four corner wheels as `spin` has them, each middle wheel the mean of the two beside it) and the steering pivots'
77
+ * turn about Y (the front ones with the steer, the rear ones the other way, as the lunar rover's four wheels steer).
78
+ *
79
+ * @param state - The vehicle.
80
+ * @returns Radians for each node name: `roll` for the `wheel-xx` nodes about X, `steer` for the `steer-xx` nodes about Y.
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * import { modelPose, startDrive } from "@johnmorrisdotca/wakusei-planets/surface";
85
+ *
86
+ * const rover = { ...startDrive(0, 0, 0, 0), steer: 0.2, spin: [1, 1, 3, 3] };
87
+ * const pose = modelPose(rover);
88
+ * console.log(pose.roll["wheel-ml"], pose.steer["steer-fl"], pose.steer["steer-rr"]);
89
+ * ```
90
+ */
91
+ export declare function modelPose(state: Pick<DriveState, "spin" | "steer">): {
92
+ roll: Record<string, number>;
93
+ steer: Record<string, number>;
94
+ };
95
+ /**
96
+ * Where a model's glTF frame (+Y up, front +Z, the left on +X) puts a point of the model in the drive frame (x right, y up, z forward): the left and right swapped.
97
+ *
98
+ * @param p - A point in the model's metres.
99
+ * @returns The point in the drive frame.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * import { fromModelFrame } from "@johnmorrisdotca/wakusei-planets/surface";
104
+ *
105
+ * console.log(fromModelFrame([0.5, 1.2, 2]));
106
+ * ```
107
+ */
108
+ export declare const fromModelFrame: (p: readonly [number, number, number]) => V3;
109
+ /**
110
+ * The shadow of a model: one box the size of its body, placed as the drive state puts the vehicle (a shadow is the hull of a part's corners, so a box is its footprint).
111
+ *
112
+ * @param state - The vehicle.
113
+ * @param rig - The model's rig.
114
+ * @param height - The model's height over the ground, metres.
115
+ * @returns One part, to hand to `partShadows`.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * import { modelShadowParts, partShadows, startDrive, ROVER } from "@johnmorrisdotca/wakusei-planets/surface";
120
+ *
121
+ * const parts = modelShadowParts(startDrive(0, 0, 0, 0), ROVER, 1.5);
122
+ * console.log(partShadows(parts, 0, 90, 20).length / 9, "triangles of shadow");
123
+ * ```
124
+ */
125
+ export declare function modelShadowParts(state: Pick<DriveState, "east" | "north" | "heading" | "pitch" | "roll" | "y">, rig: Rig, height: number): Part[];