@johnmorrisdotca/wakusei-planets 0.45.0 → 0.46.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.
@@ -0,0 +1,166 @@
1
+ // The rocks and their shadows as geometry: each rock a small faceted stone of one of three shapes, set on the ground, and a quad of shadow laid on the ground away from the Sun. Pure: the
2
+ // ground's height is a function handed in. All made, none measured.
3
+ import { pcg2d, unit24 } from "./detail.js";
4
+ const PHI = (1 + Math.sqrt(5)) / 2;
5
+ const ICOSAHEDRON = [
6
+ [-1, PHI, 0], [1, PHI, 0], [-1, -PHI, 0], [1, -PHI, 0],
7
+ [0, -1, PHI], [0, 1, PHI], [0, -1, -PHI], [0, 1, -PHI],
8
+ [PHI, 0, -1], [PHI, 0, 1], [-PHI, 0, -1], [-PHI, 0, 1],
9
+ ].map((v) => {
10
+ const l = Math.hypot(v[0], v[1], v[2]);
11
+ return [v[0] / l, v[1] / l, v[2] / l];
12
+ });
13
+ const FACES = [
14
+ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8],
15
+ [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1],
16
+ ];
17
+ /** The icosahedron cut once: each edge's middle pushed out to the sphere, so 42 corners and 80 faces, round enough that a rock seen close is not a die. */
18
+ const subdivided = (() => {
19
+ const vertices = [...ICOSAHEDRON];
20
+ const middle = new Map();
21
+ const mid = (a, b) => {
22
+ const key = a < b ? `${a}:${b}` : `${b}:${a}`;
23
+ let at = middle.get(key);
24
+ if (at === undefined) {
25
+ const p = vertices[a];
26
+ const q = vertices[b];
27
+ const m = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2];
28
+ const l = Math.hypot(m[0], m[1], m[2]);
29
+ at = vertices.push([m[0] / l, m[1] / l, m[2] / l]) - 1;
30
+ middle.set(key, at);
31
+ }
32
+ return at;
33
+ };
34
+ const faces = [];
35
+ for (const [a, b, c] of FACES) {
36
+ const ab = mid(a, b);
37
+ const bc = mid(b, c);
38
+ const ca = mid(c, a);
39
+ faces.push([a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]);
40
+ }
41
+ return { vertices, faces };
42
+ })();
43
+ /** Vertices a rock's mesh has: 80 faces of 3. */
44
+ export const ROCK_VERTICES = subdivided.faces.length * 3;
45
+ /** The three shapes: the cut icosahedron with each corner pulled in or out by a seeded share, in lumps (a corner takes the share of its neighbours too), so each shape is its own and none is a ball. */
46
+ export const SHAPES = [0, 1, 2].map((shape) => {
47
+ const raw = subdivided.vertices.map((_, i) => 0.78 + 0.42 * unit24(pcg2d(shape * 101 + 5, i * 13 + 9)[0]));
48
+ return subdivided.vertices.map((v, i) => {
49
+ // smoothed over the corner's own face neighbours, so the lumps are broad
50
+ let sum = raw[i];
51
+ let n = 1;
52
+ for (const f of subdivided.faces) {
53
+ if (f[0] === i || f[1] === i || f[2] === i) {
54
+ for (const j of f) {
55
+ if (j !== i) {
56
+ sum += raw[j];
57
+ n += 1;
58
+ }
59
+ }
60
+ }
61
+ }
62
+ const k = (raw[i] + sum / n) / 2;
63
+ return [v[0] * k, v[1] * k, v[2] * k];
64
+ });
65
+ });
66
+ /** How many segments a shadow is cut into along its length, so it follows the ground it lies on. */
67
+ const SEGMENTS = 4;
68
+ /**
69
+ * The mesh of a list of rocks standing on the ground, and a shadow for each.
70
+ *
71
+ * @param rocks - The rocks, from `rocksAround`.
72
+ * @param ground - The ground's height at a point (metres east and north of the site), the made craters on it and the Moon's curve taken off.
73
+ * @param sun - The Sun's azimuth (degrees clockwise from north) and altitude (degrees).
74
+ * @returns The arrays.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { rockMesh, rocksAround } from "@johnmorrisdotca/wakusei-planets/surface";
79
+ *
80
+ * const mesh = rockMesh(rocksAround(0, 0, 20, 0.0024), () => 0, { azimuth: 95, altitude: 13 });
81
+ * console.log(mesh.count, "rocks");
82
+ * ```
83
+ */
84
+ export function rockMesh(rocks, ground, sun) {
85
+ const n = rocks.length;
86
+ const per = ROCK_VERTICES;
87
+ const position = new Float32Array(n * per * 3);
88
+ const normal = new Float32Array(n * per * 3);
89
+ const tone = new Float32Array(n * per);
90
+ const shadowPosition = new Float32Array(n * (SEGMENTS + 1) * 2 * 3);
91
+ const shadowUv = new Float32Array(n * (SEGMENTS + 1) * 2 * 2);
92
+ const shadowIndex = new Uint32Array(n * SEGMENTS * 6);
93
+ const away = ((sun.azimuth + 180) * Math.PI) / 180;
94
+ const ax = Math.sin(away);
95
+ const ay = Math.cos(away);
96
+ const tan = Math.tan((Math.max(sun.altitude, 0.8) * Math.PI) / 180);
97
+ let p = 0;
98
+ let q = 0;
99
+ let sp = 0;
100
+ let su = 0;
101
+ let si = 0;
102
+ rocks.forEach((rock) => {
103
+ const base = SHAPES[rock.shape];
104
+ const half = rock.size / 2;
105
+ const sx = half;
106
+ const sz = half * (0.55 + 0.45 * ((rock.tone * 7) % 1));
107
+ const sy = half * rock.flat;
108
+ const c = Math.cos(rock.turn);
109
+ const s = Math.sin(rock.turn);
110
+ // half buried: the middle is only a quarter of its height over the ground
111
+ const lift = sy * 0.25;
112
+ const ground0 = ground(rock.x, rock.y);
113
+ const corner = base.map(([vx, vy, vz]) => {
114
+ const lx = vx * sx;
115
+ const lz = vz * sz;
116
+ const ly = vy * sy;
117
+ // the smooth normal of the ellipsoid it is cut from, turned with the rock: a stone with lumps, not a die
118
+ const ex = vx / sx;
119
+ const ey = vy / sy;
120
+ const ez = vz / sz;
121
+ const l = Math.hypot(ex, ey, ez) || 1;
122
+ const nx0 = ex / l;
123
+ const nz0 = ez / l;
124
+ return { pos: [rock.x + lx * c - lz * s, ground0 + lift + ly, rock.y + lx * s + lz * c], normal: [nx0 * c - nz0 * s, ey / l, nx0 * s + nz0 * c] };
125
+ });
126
+ for (const [a, b, d] of subdivided.faces) {
127
+ for (const k of [a, b, d]) {
128
+ const v = corner[k];
129
+ position[p++] = v.pos[0];
130
+ position[p++] = v.pos[1];
131
+ position[p++] = v.pos[2];
132
+ normal[q++] = v.normal[0];
133
+ normal[q++] = v.normal[1];
134
+ normal[q++] = v.normal[2];
135
+ tone[(p - 3) / 3] = rock.tone;
136
+ }
137
+ }
138
+ // its shadow: along the way the light goes, as long as the rock is high over tan(the Sun's altitude), as wide as the rock
139
+ const length = Math.min(14, (sy * 2 + lift) / tan);
140
+ const width = Math.max(sx, sz) * 0.85;
141
+ const firstVertex = sp / 3;
142
+ for (let k = 0; k <= SEGMENTS; k += 1) {
143
+ const u = k / SEGMENTS;
144
+ const w = width * (1 - 0.45 * u);
145
+ for (const side of [-1, 1]) {
146
+ const x = rock.x + ax * length * u - ay * w * side;
147
+ const y = rock.y + ay * length * u + ax * w * side;
148
+ shadowPosition[sp++] = x;
149
+ shadowPosition[sp++] = ground(x, y) + 0.03;
150
+ shadowPosition[sp++] = y;
151
+ shadowUv[su++] = u;
152
+ shadowUv[su++] = side;
153
+ }
154
+ }
155
+ for (let k = 0; k < SEGMENTS; k += 1) {
156
+ const a = firstVertex + k * 2;
157
+ shadowIndex[si++] = a;
158
+ shadowIndex[si++] = a + 1;
159
+ shadowIndex[si++] = a + 2;
160
+ shadowIndex[si++] = a + 1;
161
+ shadowIndex[si++] = a + 3;
162
+ shadowIndex[si++] = a + 2;
163
+ }
164
+ });
165
+ return { position, normal, tone, count: n, shadowPosition, shadowUv, shadowIndex };
166
+ }
@@ -0,0 +1,64 @@
1
+ import type { Item3D, Scene3D } from "@johnmorrisdotca/kazoku-ui/renderer";
2
+ import type { ThreeParts } from "../scene/body.ts";
3
+ import type { HeightLevel, TerrainManifest } from "./height.ts";
4
+ import type { MoonSky } from "./sky.ts";
5
+ import { type Look } from "./view.ts";
6
+ /** Everything that changes how the view looks. The element fills one in and hands it over; the scene holds no clock of its own. */
7
+ export interface SurfaceState {
8
+ /** The eyes: metres east and north of the site, and metres over the site's ground (the site's own height is the origin). */
9
+ eye: {
10
+ east: number;
11
+ north: number;
12
+ up: number;
13
+ };
14
+ look: Look;
15
+ sky: MoonSky;
16
+ /** Brightness: the sunlit ground of an albedo of 0.14 comes out as this share of white times the Sun's height factor (default 4.5). */
17
+ exposure?: number;
18
+ /** The ground's own brightness, 0 to 1 (default 0.14, a grey a little lighter than the Moon's mean). */
19
+ albedo?: number;
20
+ /** Whether the ground shadows itself (default true; false is a try-out, a lit slope with no shadow). */
21
+ shadows?: boolean;
22
+ /** Whether the made detail (craters, roughness) is there (default true). */
23
+ detail?: boolean;
24
+ /** How much the draw spends on shadows: `full` (the default), `medium` or `fast` (the near march shortened, the made craters left out of it): a draw while the view moves is `fast`. */
25
+ quality?: "full" | "medium" | "fast";
26
+ /** Time the next draw to the end of the graphics queue (it waits for the card, so it is for a few draws, not every one). */
27
+ measure?: boolean;
28
+ }
29
+ /** The scene the shared renderer draws, with the one call that moves it. */
30
+ export interface SurfaceScene extends Scene3D {
31
+ apply(state: SurfaceState): void;
32
+ /** Send what changed to the card: the names of the levels (`h5`), picture levels (`a5`) and horizon maps (`horizon:h5`) whose bytes have changed since. The rocks are made again on the next `apply`. */
33
+ refresh(ids: Iterable<string>): void;
34
+ /** The rocks made round the eyes now. */
35
+ readonly rocks: number;
36
+ /** How long the last measured draw took, in milliseconds, the card finished (asked for with `measure` in the state: a pixel is read back to wait for the card), or `undefined` before one. */
37
+ readonly drawMs: number | undefined;
38
+ /** The mesh's size, for a test or a status line. */
39
+ readonly mesh: {
40
+ rings: number;
41
+ rays: number;
42
+ triangles: number;
43
+ };
44
+ }
45
+ export interface SurfaceItemOptions {
46
+ /** The pyramid's levels, finest first, filled with their heights. */
47
+ levels: readonly HeightLevel[];
48
+ /** The ground picture's levels, where the site has them. */
49
+ pictures?: readonly HeightLevel[];
50
+ /** The baked horizons (see the manifest's `horizon`), where the site has them. */
51
+ horizons?: readonly {
52
+ id: string;
53
+ width: number;
54
+ height: number;
55
+ data: Uint8Array;
56
+ }[];
57
+ /** The ground's height at a point, metres east and north of the site, for the rocks to stand on: the measured heights, the made craters, the Moon's curve taken off. */
58
+ groundY?(east: number, north: number): number;
59
+ manifest: TerrainManifest;
60
+ /** A key that changes whenever the picture would: the renderer keeps one still for each key. */
61
+ key: string;
62
+ }
63
+ /** The Moon's standing view for one site as an item of the shared renderer. */
64
+ export declare function createSurfaceItem(options: SurfaceItemOptions): Item3D<ThreeParts>;
@@ -0,0 +1,323 @@
1
+ import { rocksAround } from "./detail.js";
2
+ import { DISC_FRAGMENT, DISC_VERTEX, GROUND_FRAGMENT, GROUND_VERTEX, ROCK_FRAGMENT, ROCK_VERTEX, SHADOW_FRAGMENT, SHADOW_VERTEX } from "./glsl.js";
3
+ import { rockMesh } from "./rocks.js";
4
+ import { cameraAxes, viewProjection } from "./view.js";
5
+ const RINGS = 480;
6
+ const RAYS = 600;
7
+ const R_MIN = 0.1;
8
+ const R_MAX = 300_000;
9
+ /** The distances out to which each level is read, finest first (the coarsest reads to the end): a level's own samples are about this far from being finer than a pixel. */
10
+ const BANDS = [4_000, 16_000, 60_000, Infinity];
11
+ /** The ground's mesh: rings spaced out geometrically (a share of the distance apart) and rays across the view; its positions are not positions but where to look in the polar grid. */
12
+ function groundGeometry(T) {
13
+ const positions = new Float32Array((RINGS + 1) * (RAYS + 1) * 3);
14
+ let at = 0;
15
+ for (let i = 0; i <= RINGS; i += 1) {
16
+ for (let j = 0; j <= RAYS; j += 1) {
17
+ positions[at++] = i / RINGS;
18
+ positions[at++] = (j / RAYS) * 2 - 1;
19
+ positions[at++] = 0;
20
+ }
21
+ }
22
+ const indices = new Uint32Array(RINGS * RAYS * 6);
23
+ let k = 0;
24
+ for (let i = 0; i < RINGS; i += 1) {
25
+ for (let j = 0; j < RAYS; j += 1) {
26
+ const a = i * (RAYS + 1) + j;
27
+ const b = a + 1;
28
+ const c = a + RAYS + 1;
29
+ const d = c + 1;
30
+ indices[k++] = a;
31
+ indices[k++] = b;
32
+ indices[k++] = c;
33
+ indices[k++] = b;
34
+ indices[k++] = d;
35
+ indices[k++] = c;
36
+ }
37
+ }
38
+ const geometry = new T.BufferGeometry();
39
+ geometry.setAttribute("position", new T.BufferAttribute(positions, 3));
40
+ geometry.setIndex(new T.BufferAttribute(indices, 1));
41
+ return { geometry, triangles: indices.length / 3 };
42
+ }
43
+ function squareGeometry(T) {
44
+ const geometry = new T.BufferGeometry();
45
+ geometry.setAttribute("position", new T.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), 3));
46
+ geometry.setIndex(new T.BufferAttribute(new Uint16Array([0, 1, 2, 0, 2, 3]), 1));
47
+ return geometry;
48
+ }
49
+ /** The Moon's standing view for one site as an item of the shared renderer. */
50
+ export function createSurfaceItem(options) {
51
+ return {
52
+ key: options.key,
53
+ build(context) {
54
+ const T = context.three;
55
+ const { manifest } = options;
56
+ const textures = options.levels.map((level) => context.assets.acquire(`surface:${manifest.site}:${level.id}`, () => {
57
+ const texture = new T.DataTexture(level.data, level.size, level.size, T.RGBAFormat);
58
+ texture.minFilter = 1003; // NearestFilter: the two bytes of a height must not be blended
59
+ texture.magFilter = 1003;
60
+ texture.wrapS = T.ClampToEdgeWrapping;
61
+ texture.wrapT = T.ClampToEdgeWrapping;
62
+ texture.generateMipmaps = false;
63
+ texture.flipY = false;
64
+ texture.needsUpdate = true;
65
+ return texture;
66
+ }, (texture) => texture.dispose()));
67
+ const pictures = (options.pictures ?? []).map((level) => context.assets.acquire(`surface:${manifest.site}:picture:${level.id}`, () => {
68
+ const texture = new T.DataTexture(level.data, level.size, level.size, T.RGBAFormat);
69
+ texture.minFilter = 1008; // LinearMipmapLinearFilter: a picture seen from far is averaged, not sparkling
70
+ texture.magFilter = T.LinearFilter;
71
+ texture.wrapS = T.ClampToEdgeWrapping;
72
+ texture.wrapT = T.ClampToEdgeWrapping;
73
+ texture.generateMipmaps = true;
74
+ texture.flipY = false;
75
+ texture.needsUpdate = true;
76
+ return texture;
77
+ }, (texture) => texture.dispose()));
78
+ const horizons = (options.horizons ?? []).map((h) => context.assets.acquire(`surface:${manifest.site}:horizon:${h.id}`, () => {
79
+ const texture = new T.DataTexture(h.data, h.width, h.height, T.RGBAFormat);
80
+ texture.minFilter = T.LinearFilter; // a smooth horizon between the cells; each colour is its own direction, so blending them is blending the same direction's neighbours
81
+ texture.magFilter = T.LinearFilter;
82
+ texture.wrapS = T.ClampToEdgeWrapping;
83
+ texture.wrapT = T.ClampToEdgeWrapping;
84
+ texture.generateMipmaps = false;
85
+ texture.flipY = false;
86
+ texture.needsUpdate = true;
87
+ return texture;
88
+ }, (texture) => texture.dispose()));
89
+ const hz = manifest.horizon;
90
+ const level = (i) => {
91
+ const l = options.levels[i];
92
+ return { value: [l.half, l.res, l.size, BANDS[i] ?? Infinity] };
93
+ };
94
+ const maxY = Math.max(...options.levels.map((l) => l.max ?? manifest.height.min + manifest.height.range)) - manifest.ground;
95
+ const uniforms = {
96
+ uVP: { value: new Float32Array(16) },
97
+ uEyeEN: { value: new T.Vector2(0, 0) },
98
+ uEye: { value: new T.Vector3(0, 1.7, 0) },
99
+ uYaw: { value: 0 },
100
+ uSpan: { value: 0.6 },
101
+ uRMin: { value: R_MIN },
102
+ uRMax: { value: R_MAX },
103
+ uSun: { value: new T.Vector3(0, 0.5, 0.8) },
104
+ uExposure: { value: 4.5 },
105
+ uAlbedo: { value: 0.14 },
106
+ uMaxY: { value: maxY },
107
+ uEarthshine: { value: 0.05 },
108
+ uShadows: { value: 1 },
109
+ uHmin: { value: manifest.height.min },
110
+ uHrange: { value: manifest.height.range },
111
+ uFarHeight: { value: new T.Vector2(options.levels[3]?.height?.min ?? manifest.height.min, options.levels[3]?.height?.range ?? manifest.height.range) },
112
+ uGround: { value: manifest.ground },
113
+ uRadius: { value: manifest.radius },
114
+ uH0: { value: textures[0] },
115
+ uH1: { value: textures[1] ?? textures[0] },
116
+ uH2: { value: textures[2] ?? textures[0] },
117
+ uH3: { value: textures[3] ?? textures[0] },
118
+ uA0: { value: pictures[0] ?? textures[0] },
119
+ uA1: { value: pictures[1] ?? textures[0] },
120
+ uA2: { value: pictures[2] ?? textures[0] },
121
+ uPicture: { value: pictures.length >= 3 ? 1 : 0 },
122
+ uZ0: { value: horizons[0] ?? textures[0] },
123
+ uZ1: { value: horizons[1] ?? textures[0] },
124
+ uZ2: { value: horizons[2] ?? textures[0] },
125
+ uHzOn: { value: horizons.length >= 3 && hz !== null && hz !== undefined ? 1 : 0 },
126
+ uHzSun: { value: new T.Vector3(0, 1, 0) },
127
+ uHzRange: { value: new T.Vector2(hz?.from ?? -10, hz?.to ?? 60) },
128
+ uSunDegrees: { value: 13 },
129
+ uNear: { value: new T.Vector3(56, 80, 36) },
130
+ uPixel: { value: 0.0024 },
131
+ uDetail: { value: 1 },
132
+ uL0: level(0),
133
+ uL1: level(1),
134
+ uL2: level(2),
135
+ uL3: level(3),
136
+ };
137
+ const { geometry, triangles } = groundGeometry(T);
138
+ const groundMaterial = new T.ShaderMaterial({ vertexShader: GROUND_VERTEX, fragmentShader: GROUND_FRAGMENT, uniforms });
139
+ const ground = new T.Mesh(geometry, groundMaterial);
140
+ ground.frustumCulled = false;
141
+ ground.renderOrder = 0;
142
+ const square = squareGeometry(T);
143
+ const disc = (kind, half) => {
144
+ const u = {
145
+ uVP: uniforms.uVP,
146
+ uEyeWorld: { value: new T.Vector3() },
147
+ uDirWorld: { value: new T.Vector3(0, 1, 0) },
148
+ uRightWorld: { value: new T.Vector3(1, 0, 0) },
149
+ uUpWorld: { value: new T.Vector3(0, 0, -1) },
150
+ uHalf: { value: half },
151
+ uKind: { value: kind },
152
+ uSunEnu: { value: new T.Vector3() },
153
+ uDirEnu: { value: new T.Vector3() },
154
+ uRightEnu: { value: new T.Vector3(1, 0, 0) },
155
+ uUpEnu: { value: new T.Vector3(0, 1, 0) },
156
+ uExposure: uniforms.uExposure,
157
+ };
158
+ const material = new T.ShaderMaterial({ vertexShader: DISC_VERTEX, fragmentShader: DISC_FRAGMENT, uniforms: u, depthTest: false, depthWrite: false });
159
+ const mesh = new T.Mesh(square, material);
160
+ mesh.frustumCulled = false;
161
+ mesh.renderOrder = -10 + kind;
162
+ return { mesh, material, uniforms: u };
163
+ };
164
+ const sun = disc(0, Math.tan((0.533 * Math.PI) / 360));
165
+ const earth = disc(1, Math.tan((1.9 * Math.PI) / 360));
166
+ const scene = new T.Scene();
167
+ scene.add(sun.mesh, earth.mesh, ground);
168
+ // the rocks and their shadows, made again when the eyes have walked a while or the Sun has moved
169
+ const rockMaterial = new T.ShaderMaterial({ vertexShader: ROCK_VERTEX, fragmentShader: ROCK_FRAGMENT, uniforms });
170
+ const shadowMaterial = new T.ShaderMaterial({ vertexShader: SHADOW_VERTEX, fragmentShader: SHADOW_FRAGMENT, uniforms: { uVP: uniforms.uVP }, transparent: true, depthWrite: false });
171
+ shadowMaterial.polygonOffset = true;
172
+ shadowMaterial.polygonOffsetFactor = -2;
173
+ shadowMaterial.polygonOffsetUnits = -2;
174
+ let rockGeometry;
175
+ let shadowGeometry;
176
+ let rockMeshObject;
177
+ let shadowMeshObject;
178
+ let rockKey = "";
179
+ let rockCount = 0;
180
+ const makeRocks = (state) => {
181
+ const ground = options.groundY;
182
+ if (ground === undefined || state.detail === false)
183
+ return;
184
+ const pixel = uniforms.uPixel.value;
185
+ const key = `${Math.round(state.eye.east / 8)}|${Math.round(state.eye.north / 8)}|${state.sky.sun.azimuth.toFixed(0)}|${state.sky.sun.altitude.toFixed(0)}|${pixel.toFixed(4)}`;
186
+ if (key === rockKey)
187
+ return;
188
+ rockKey = key;
189
+ const rocks = rocksAround(state.eye.east, state.eye.north, 55, pixel);
190
+ const mesh = rockMesh(rocks, ground, { azimuth: state.sky.sun.azimuth, altitude: state.sky.sun.altitude });
191
+ rockCount = mesh.count;
192
+ rockGeometry?.dispose();
193
+ shadowGeometry?.dispose();
194
+ rockGeometry = new T.BufferGeometry();
195
+ rockGeometry.setAttribute("position", new T.BufferAttribute(mesh.position, 3));
196
+ rockGeometry.setAttribute("normal", new T.BufferAttribute(mesh.normal, 3));
197
+ rockGeometry.setAttribute("tone", new T.BufferAttribute(mesh.tone, 1));
198
+ shadowGeometry = new T.BufferGeometry();
199
+ shadowGeometry.setAttribute("position", new T.BufferAttribute(mesh.shadowPosition, 3));
200
+ shadowGeometry.setAttribute("uv", new T.BufferAttribute(mesh.shadowUv, 2));
201
+ shadowGeometry.setIndex(new T.BufferAttribute(mesh.shadowIndex, 1));
202
+ if (rockMeshObject === undefined) {
203
+ rockMeshObject = new T.Mesh(rockGeometry, rockMaterial);
204
+ rockMeshObject.frustumCulled = false;
205
+ rockMeshObject.renderOrder = 1;
206
+ shadowMeshObject = new T.Mesh(shadowGeometry, shadowMaterial);
207
+ shadowMeshObject.frustumCulled = false;
208
+ shadowMeshObject.renderOrder = 2;
209
+ scene.add(rockMeshObject, shadowMeshObject);
210
+ }
211
+ else {
212
+ rockMeshObject.geometry = rockGeometry;
213
+ shadowMeshObject.geometry = shadowGeometry;
214
+ }
215
+ };
216
+ let measuring = false;
217
+ let drawMs;
218
+ let aspect = context.width / Math.max(1, context.height);
219
+ let pixelHeight = Math.max(1, context.height);
220
+ let last;
221
+ const place = (state) => {
222
+ last = state;
223
+ const { eye, look, sky } = state;
224
+ makeRocks(state);
225
+ measuring = state.measure === true;
226
+ const world = new T.Vector3(eye.east, eye.up, -eye.north);
227
+ const vp = viewProjection([world.x, world.y, world.z], look, aspect);
228
+ uniforms.uVP.value.set(vp);
229
+ uniforms.uEyeEN.value.set(eye.east, eye.north);
230
+ uniforms.uEye.value.set(eye.east, eye.up, eye.north);
231
+ uniforms.uYaw.value = (look.azimuth * Math.PI) / 180;
232
+ const halfV = Math.tan((look.fov * Math.PI) / 360);
233
+ const halfH = Math.atan(halfV * aspect);
234
+ const tilt = Math.abs(look.pitch) + look.fov / 2;
235
+ uniforms.uSpan.value = tilt > 78 ? Math.PI : Math.min(Math.PI, halfH / Math.cos((tilt * Math.PI) / 180) + 0.06);
236
+ uniforms.uSun.value.set(sky.sun.enu[0], sky.sun.enu[2], sky.sun.enu[1]);
237
+ uniforms.uExposure.value = state.exposure ?? 4.5;
238
+ uniforms.uAlbedo.value = state.albedo ?? 0.14;
239
+ uniforms.uShadows.value = state.shadows === false ? 0 : 1;
240
+ uniforms.uDetail.value = state.detail === false ? 0 : 1;
241
+ uniforms.uSunDegrees.value = sky.sun.altitude;
242
+ // the sector pair the Sun's azimuth lies between, in the baked horizon's eighteen directions
243
+ const sectors = hz?.sectors ?? 18;
244
+ const f = (((sky.sun.azimuth % 360) + 360) % 360) / (360 / sectors);
245
+ const a = Math.floor(f);
246
+ uniforms.uHzSun.value.set(a % sectors, (a + 1) % sectors, f - a);
247
+ const q = state.quality ?? "full";
248
+ const near = q === "full" ? [56, 80, 36] : q === "medium" ? [28, 40, 16] : [10, 14, 0];
249
+ uniforms.uNear.value.set(near[0], near[1], near[2]);
250
+ uniforms.uPixel.value = (2 * Math.tan((look.fov * Math.PI) / 360)) / pixelHeight;
251
+ const axes = cameraAxes(look);
252
+ const toEnu = (v) => [v[0], -v[2], v[1]];
253
+ const sunWorld = [sky.sun.enu[0], sky.sun.enu[2], -sky.sun.enu[1]];
254
+ const earthWorld = [sky.earth.enu[0], sky.earth.enu[2], -sky.earth.enu[1]];
255
+ for (const [d, dir] of [[sun, sunWorld], [earth, earthWorld]]) {
256
+ d.uniforms.uEyeWorld.value = world;
257
+ d.uniforms.uDirWorld.value.set(dir[0], dir[1], dir[2]);
258
+ d.uniforms.uRightWorld.value.set(axes.right[0], axes.right[1], axes.right[2]);
259
+ d.uniforms.uUpWorld.value.set(axes.up[0], axes.up[1], axes.up[2]);
260
+ const de = toEnu(dir);
261
+ d.uniforms.uDirEnu.value.set(de[0], de[1], de[2]);
262
+ const re = toEnu(axes.right);
263
+ d.uniforms.uRightEnu.value.set(re[0], re[1], re[2]);
264
+ const ue = toEnu(axes.up);
265
+ d.uniforms.uUpEnu.value.set(ue[0], ue[1], ue[2]);
266
+ d.uniforms.uSunEnu.value.set(sky.sun.enu[0], sky.sun.enu[1], sky.sun.enu[2]);
267
+ }
268
+ earth.uniforms.uHalf.value = Math.tan((sky.earthDiameter * Math.PI) / 360);
269
+ sun.uniforms.uHalf.value = Math.tan((sky.sunDiameter * Math.PI) / 360);
270
+ sun.mesh.visible = sky.sun.altitude > -1;
271
+ earth.mesh.visible = sky.earth.altitude > -1;
272
+ };
273
+ const camera = new T.OrthographicCamera(-1, 1, 1, -1, 0, 1);
274
+ return {
275
+ scene,
276
+ camera,
277
+ mesh: { rings: RINGS, rays: RAYS, triangles },
278
+ get rocks() {
279
+ return rockCount;
280
+ },
281
+ get drawMs() {
282
+ return drawMs;
283
+ },
284
+ render(gl) {
285
+ const t0 = performance.now();
286
+ gl.render(scene, camera);
287
+ if (measuring) {
288
+ const canvas = gl.domElement;
289
+ // reading one pixel back waits for the card to finish the draw (`finish` returns at once in a browser that draws in another process)
290
+ const g = (canvas.getContext("webgl2") ?? canvas.getContext("webgl"));
291
+ g?.readPixels(0, 0, 1, 1, g.RGBA, g.UNSIGNED_BYTE, new Uint8Array(4));
292
+ drawMs = performance.now() - t0;
293
+ }
294
+ },
295
+ apply: place,
296
+ refresh(ids) {
297
+ const wanted = new Set(ids);
298
+ options.levels.forEach((level, i) => wanted.has(level.id) && (textures[i].needsUpdate = true));
299
+ (options.pictures ?? []).forEach((level, i) => wanted.has(level.id) && (pictures[i].needsUpdate = true));
300
+ (options.horizons ?? []).forEach((h, i) => wanted.has(`horizon:${h.id}`) && (horizons[i].needsUpdate = true));
301
+ rockKey = "";
302
+ },
303
+ resize(width, height) {
304
+ aspect = width / Math.max(1, height);
305
+ pixelHeight = Math.max(1, height);
306
+ if (last !== undefined)
307
+ place(last);
308
+ },
309
+ dispose() {
310
+ geometry.dispose();
311
+ square.dispose();
312
+ groundMaterial.dispose();
313
+ rockGeometry?.dispose();
314
+ shadowGeometry?.dispose();
315
+ rockMaterial.dispose();
316
+ shadowMaterial.dispose();
317
+ sun.material.dispose();
318
+ earth.material.dispose();
319
+ },
320
+ };
321
+ },
322
+ };
323
+ }
@@ -0,0 +1,58 @@
1
+ import type { Look } from "./view.ts";
2
+ /**
3
+ * A site's record.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { siteById, type SurfaceSite } from "@johnmorrisdotca/wakusei-planets/surface";
8
+ *
9
+ * const site: SurfaceSite | undefined = siteById("apollo-17");
10
+ * console.log(site?.name.en, site?.lat, site?.lon);
11
+ * ```
12
+ */
13
+ export interface SurfaceSite {
14
+ /** The name in the `site` attribute. */
15
+ id: string;
16
+ /** The body it is on. */
17
+ body: "moon";
18
+ name: {
19
+ en: string;
20
+ ja: string;
21
+ };
22
+ /** Planetocentric degrees. */
23
+ lat: number;
24
+ lon: number;
25
+ /** The site's place in the Moon's list of places (`/places`), which the orbit view turns to when it lands here. */
26
+ place: string;
27
+ /** A moment with a low Sun and long shadows, milliseconds since 1970: the landing itself. */
28
+ time: number;
29
+ /** Where to look first: toward the biggest mountain near. */
30
+ look: Look;
31
+ }
32
+ /**
33
+ * The sites with heights. The Apollo 17 landing site stands in Taurus-Littrow, a valley a few kilometres wide between mountains 2 kilometres high; it is first looked at toward the South Massif,
34
+ * at the moment of the landing, with the Sun 13 degrees up and the Earth above the mountain.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { SURFACE_SITES } from "@johnmorrisdotca/wakusei-planets/surface";
39
+ *
40
+ * console.log(SURFACE_SITES.map((site) => site.id).join(", "));
41
+ * ```
42
+ */
43
+ export declare const SURFACE_SITES: readonly SurfaceSite[];
44
+ /**
45
+ * A site by name, or `undefined`.
46
+ *
47
+ * @param id - The site's name, as in the `site` attribute.
48
+ * @returns The site's record, or `undefined` when there is no such site.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * import { siteById } from "@johnmorrisdotca/wakusei-planets/surface";
53
+ *
54
+ * const site = siteById("apollo-17");
55
+ * console.log(site?.name.en, siteById("nowhere"));
56
+ * ```
57
+ */
58
+ export declare const siteById: (id: string) => SurfaceSite | undefined;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The sites with heights. The Apollo 17 landing site stands in Taurus-Littrow, a valley a few kilometres wide between mountains 2 kilometres high; it is first looked at toward the South Massif,
3
+ * at the moment of the landing, with the Sun 13 degrees up and the Earth above the mountain.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { SURFACE_SITES } from "@johnmorrisdotca/wakusei-planets/surface";
8
+ *
9
+ * console.log(SURFACE_SITES.map((site) => site.id).join(", "));
10
+ * ```
11
+ */
12
+ export const SURFACE_SITES = [
13
+ {
14
+ id: "apollo-17",
15
+ body: "moon",
16
+ name: { en: "Apollo 17, Taurus-Littrow", ja: "アポロ17号、タウルス・リットロー" },
17
+ lat: 20.1911,
18
+ lon: 30.7723,
19
+ place: "moon/apollo-17-lunar-module",
20
+ time: Date.UTC(1972, 11, 11, 19, 54),
21
+ look: { azimuth: 232, pitch: 13, fov: 74 },
22
+ },
23
+ ];
24
+ /**
25
+ * A site by name, or `undefined`.
26
+ *
27
+ * @param id - The site's name, as in the `site` attribute.
28
+ * @returns The site's record, or `undefined` when there is no such site.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { siteById } from "@johnmorrisdotca/wakusei-planets/surface";
33
+ *
34
+ * const site = siteById("apollo-17");
35
+ * console.log(site?.name.en, siteById("nowhere"));
36
+ * ```
37
+ */
38
+ export const siteById = (id) => SURFACE_SITES.find((site) => site.id === id);