@bendyline/molen-client 0.0.1 → 0.0.3

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,308 @@
1
+ import * as THREE from "three";
2
+ //#region src/markers/marker-image.ts
3
+ function defaultCanvas(width, height) {
4
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
5
+ const canvas = document.createElement("canvas");
6
+ canvas.width = width;
7
+ canvas.height = height;
8
+ return canvas;
9
+ }
10
+ function roundedRect(context, x, y, w, h, r) {
11
+ const radius = Math.min(r, w / 2, h / 2);
12
+ context.beginPath();
13
+ context.moveTo(x + radius, y);
14
+ context.arcTo(x + w, y, x + w, y + h, radius);
15
+ context.arcTo(x + w, y + h, x, y + h, radius);
16
+ context.arcTo(x, y + h, x, y, radius);
17
+ context.arcTo(x, y, x + w, y, radius);
18
+ context.closePath();
19
+ }
20
+ /**
21
+ * Draw `image` (cover-cropped to a square) inside a bordered, rounded frame with an optional tail,
22
+ * returning a canvas ready for `MarkerSpec.image`. Its bottom-center is the pin point.
23
+ */
24
+ function composeMarkerImage(image, style = {}) {
25
+ const size = style.size ?? 52;
26
+ const border = style.borderWidth ?? 3;
27
+ const radius = style.radius ?? 8;
28
+ const tail = style.tail ?? 9;
29
+ const shadow = style.shadow ?? 6;
30
+ const ratio = style.pixelRatio ?? 2;
31
+ const frame = size + border * 2;
32
+ const pad = shadow;
33
+ const width = Math.ceil((frame + pad * 2) * ratio);
34
+ const height = Math.ceil((pad + frame + tail) * ratio);
35
+ const canvas = (style.createCanvas ?? defaultCanvas)(width, height);
36
+ const context = canvas.getContext("2d");
37
+ if (context === null) throw new Error("2D canvas context unavailable for marker images");
38
+ context.scale(ratio, ratio);
39
+ const left = pad;
40
+ const top = pad;
41
+ context.save();
42
+ if (shadow > 0) {
43
+ context.shadowColor = style.shadowColor ?? "rgba(0, 0, 0, 0.35)";
44
+ context.shadowBlur = shadow;
45
+ context.shadowOffsetY = shadow / 3;
46
+ }
47
+ context.fillStyle = style.borderColor ?? "#ffffff";
48
+ roundedRect(context, left, top, frame, frame, radius + border);
49
+ context.fill();
50
+ if (tail > 0) {
51
+ context.beginPath();
52
+ context.moveTo(left + frame / 2 - tail, top + frame - 1);
53
+ context.lineTo(left + frame / 2, top + frame + tail);
54
+ context.lineTo(left + frame / 2 + tail, top + frame - 1);
55
+ context.closePath();
56
+ context.fill();
57
+ }
58
+ context.restore();
59
+ const sourceWidth = image.width;
60
+ const sourceHeight = image.height;
61
+ const side = Math.min(sourceWidth, sourceHeight);
62
+ context.save();
63
+ roundedRect(context, left + border, top + border, size, size, radius);
64
+ context.clip();
65
+ if (side > 0) context.drawImage(image, (sourceWidth - side) / 2, (sourceHeight - side) / 2, side, side, left + border, top + border, size, size);
66
+ context.restore();
67
+ return canvas;
68
+ }
69
+ //#endregion
70
+ //#region src/markers/marker-layer.ts
71
+ const scratch = new THREE.Vector3();
72
+ const viewSpace = new THREE.Vector3();
73
+ /**
74
+ * Project an absolute world position (the coordinates you give markers and cameras) to CSS
75
+ * pixels, accounting for the renderer's floating-origin rebase.
76
+ */
77
+ function projectWorldToScreen(host, position) {
78
+ const [width, height] = host.getViewportSize();
79
+ host.worldRoot.updateWorldMatrix(true, false);
80
+ host.camera.updateMatrixWorld();
81
+ const world = host.worldRoot.localToWorld(scratch.set(position[0], position[1], position[2]));
82
+ viewSpace.copy(world).applyMatrix4(host.camera.matrixWorldInverse);
83
+ const distance = viewSpace.length();
84
+ const inFront = viewSpace.z < 0;
85
+ world.project(host.camera);
86
+ const x = (world.x + 1) / 2 * width;
87
+ const y = (1 - world.y) / 2 * height;
88
+ return {
89
+ x,
90
+ y,
91
+ distance,
92
+ visible: inFront && x >= 0 && x <= width && y >= 0 && y <= height
93
+ };
94
+ }
95
+ function imageAspect(image) {
96
+ if (typeof image === "string") return void 0;
97
+ const sized = image;
98
+ if (sized.width !== void 0 && sized.height !== void 0 && sized.height > 0) return sized.width / sized.height;
99
+ }
100
+ /** A group of screen-sized world markers; add markers with `set`, advance with `update`. */
101
+ var MarkerLayer = class {
102
+ host;
103
+ options;
104
+ object = new THREE.Group();
105
+ entries = /* @__PURE__ */ new Map();
106
+ textures = /* @__PURE__ */ new Map();
107
+ loader = new THREE.TextureLoader();
108
+ visible = true;
109
+ disposed = false;
110
+ constructor(host, options = {}) {
111
+ this.host = host;
112
+ this.options = options;
113
+ this.object.name = "molen:markers";
114
+ }
115
+ /** Replace the marker set. Markers are matched by id, so unchanged images are not reloaded. */
116
+ set(markers) {
117
+ if (this.disposed) return;
118
+ const seen = /* @__PURE__ */ new Set();
119
+ for (const spec of markers) {
120
+ seen.add(spec.id);
121
+ const existing = this.entries.get(spec.id);
122
+ if (existing !== void 0) {
123
+ if (existing.imageKey !== spec.image) {
124
+ this.release(existing.imageKey);
125
+ existing.texture = this.acquire(spec.image, existing);
126
+ existing.imageKey = spec.image;
127
+ existing.material.map = existing.texture;
128
+ existing.material.needsUpdate = true;
129
+ existing.aspect = imageAspect(spec.image) ?? existing.aspect;
130
+ }
131
+ if (existing.spec.x !== spec.x || existing.spec.z !== spec.z) existing.groundY = void 0;
132
+ existing.spec = { ...spec };
133
+ continue;
134
+ }
135
+ const entry = this.create(spec);
136
+ this.entries.set(spec.id, entry);
137
+ this.object.add(entry.sprite);
138
+ }
139
+ for (const [id, entry] of this.entries) if (!seen.has(id)) this.remove(id, entry);
140
+ }
141
+ /** Marker ids currently in the layer. */
142
+ ids() {
143
+ return [...this.entries.keys()];
144
+ }
145
+ /**
146
+ * Per frame: snap to ground, fade, budget, and size markers for the current camera. Pass the
147
+ * camera's absolute world position (the one given to `setCamera`).
148
+ */
149
+ update(cameraPosition) {
150
+ if (this.disposed) return;
151
+ const [, viewportHeight] = this.host.getViewportSize();
152
+ const perPixel = this.worldPerPixel(viewportHeight);
153
+ const hideUntilGrounded = this.options.hideUntilGrounded ?? true;
154
+ const candidates = [];
155
+ for (const entry of this.entries.values()) {
156
+ const { spec } = entry;
157
+ let y = spec.y;
158
+ if (y === void 0) {
159
+ const ground = this.options.groundHeight?.(spec.x, spec.z);
160
+ if (ground !== void 0) entry.groundY = ground;
161
+ y = entry.groundY === void 0 ? hideUntilGrounded ? void 0 : spec.elevation ?? 0 : entry.groundY + (spec.elevation ?? 0);
162
+ }
163
+ entry.sprite.visible = false;
164
+ if (y === void 0 || !this.visible) continue;
165
+ entry.sprite.position.set(spec.x, y, spec.z);
166
+ entry.distance = Math.hypot(spec.x - cameraPosition[0], y - cameraPosition[1], spec.z - cameraPosition[2]);
167
+ candidates.push(entry);
168
+ }
169
+ candidates.sort((a, b) => (b.spec.priority ?? 0) - (a.spec.priority ?? 0) || a.distance - b.distance || a.spec.id.localeCompare(b.spec.id));
170
+ const budget = this.options.maxVisible ?? 256;
171
+ const fade = this.options.fade;
172
+ for (const [index, entry] of candidates.entries()) {
173
+ if (index >= budget) break;
174
+ const opacity = fade === void 0 ? 1 : Math.max(0, Math.min(1, (fade.far - entry.distance) / (fade.far - fade.near)));
175
+ if (opacity <= 0) continue;
176
+ const size = entry.spec.size ?? 56;
177
+ entry.material.opacity = opacity;
178
+ entry.sprite.scale.set(size * entry.aspect * perPixel, size * perPixel, 1);
179
+ entry.sprite.center.set(.5, (entry.spec.anchor ?? "bottom") === "bottom" ? 0 : .5);
180
+ entry.sprite.visible = true;
181
+ }
182
+ }
183
+ /** The front-most drawn marker under a CSS-pixel point, if any. */
184
+ pick(x, y) {
185
+ let best;
186
+ for (const [id, entry] of this.entries) {
187
+ if (!entry.sprite.visible) continue;
188
+ const p = entry.sprite.position;
189
+ const screen = projectWorldToScreen(this.host, [
190
+ p.x,
191
+ p.y,
192
+ p.z
193
+ ]);
194
+ if (screen.distance <= 0) continue;
195
+ const height = entry.spec.size ?? 56;
196
+ const width = height * entry.aspect;
197
+ const top = (entry.spec.anchor ?? "bottom") === "bottom" ? screen.y - height : screen.y - height / 2;
198
+ if (x < screen.x - width / 2 || x > screen.x + width / 2 || y < top || y > top + height) continue;
199
+ if (best === void 0 || screen.distance < best.distance) best = {
200
+ id,
201
+ distance: screen.distance
202
+ };
203
+ }
204
+ return best?.id;
205
+ }
206
+ /** Where a marker's anchor point appears on screen (for DOM callouts), if it exists. */
207
+ screenPosition(id) {
208
+ const entry = this.entries.get(id);
209
+ if (entry === void 0) return void 0;
210
+ const p = entry.sprite.position;
211
+ const screen = projectWorldToScreen(this.host, [
212
+ p.x,
213
+ p.y,
214
+ p.z
215
+ ]);
216
+ return {
217
+ ...screen,
218
+ visible: screen.visible && entry.sprite.visible
219
+ };
220
+ }
221
+ setVisible(visible) {
222
+ this.visible = visible;
223
+ if (!visible) for (const entry of this.entries.values()) entry.sprite.visible = false;
224
+ }
225
+ dispose() {
226
+ if (this.disposed) return;
227
+ this.disposed = true;
228
+ for (const [id, entry] of this.entries) this.remove(id, entry);
229
+ this.object.removeFromParent();
230
+ }
231
+ worldPerPixel(viewportHeight) {
232
+ const camera = this.host.camera;
233
+ if (camera instanceof THREE.PerspectiveCamera) return 2 * Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2) / viewportHeight;
234
+ if (camera instanceof THREE.OrthographicCamera) return (camera.top - camera.bottom) / camera.zoom / viewportHeight;
235
+ return 1 / viewportHeight;
236
+ }
237
+ create(spec) {
238
+ const material = new THREE.SpriteMaterial({
239
+ transparent: true,
240
+ depthWrite: false,
241
+ depthTest: this.options.occlude ?? true,
242
+ sizeAttenuation: false
243
+ });
244
+ const entry = {
245
+ spec: { ...spec },
246
+ sprite: new THREE.Sprite(material),
247
+ material,
248
+ texture: void 0,
249
+ imageKey: spec.image,
250
+ aspect: imageAspect(spec.image) ?? 1,
251
+ groundY: void 0,
252
+ distance: 0
253
+ };
254
+ entry.texture = this.acquire(spec.image, entry);
255
+ material.map = entry.texture;
256
+ entry.sprite.name = `marker:${spec.id}`;
257
+ entry.sprite.userData.markerId = spec.id;
258
+ entry.sprite.visible = false;
259
+ if (this.options.renderOrder !== void 0) entry.sprite.renderOrder = this.options.renderOrder;
260
+ return entry;
261
+ }
262
+ remove(id, entry) {
263
+ entry.sprite.removeFromParent();
264
+ entry.material.dispose();
265
+ this.release(entry.imageKey);
266
+ this.entries.delete(id);
267
+ }
268
+ acquire(image, entry) {
269
+ const cached = this.textures.get(image);
270
+ if (cached !== void 0) {
271
+ cached.users++;
272
+ return cached.texture;
273
+ }
274
+ let texture;
275
+ if (typeof image === "string") texture = this.loader.load(image, (loaded) => {
276
+ const aspect = imageAspect(loaded.image);
277
+ if (aspect === void 0) return;
278
+ for (const other of this.entries.values()) if (other.imageKey === image) other.aspect = aspect;
279
+ entry.aspect = aspect;
280
+ });
281
+ else {
282
+ texture = new THREE.Texture(image);
283
+ texture.needsUpdate = true;
284
+ }
285
+ texture.colorSpace = THREE.SRGBColorSpace;
286
+ this.textures.set(image, {
287
+ texture,
288
+ users: 1
289
+ });
290
+ return texture;
291
+ }
292
+ release(image) {
293
+ const cached = this.textures.get(image);
294
+ if (cached === void 0) return;
295
+ cached.users--;
296
+ if (cached.users > 0) return;
297
+ cached.texture.dispose();
298
+ this.textures.delete(image);
299
+ }
300
+ };
301
+ /** Create a marker layer and attach it under the host's world root. */
302
+ function createMarkerLayer(host, options = {}) {
303
+ const layer = new MarkerLayer(host, options);
304
+ host.worldRoot.add(layer.object);
305
+ return layer;
306
+ }
307
+ //#endregion
308
+ export { MarkerLayer, composeMarkerImage, createMarkerLayer, projectWorldToScreen };