@chanmeng666/archlang-3d 0.1.2 → 0.3.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.
package/dist/browser.js CHANGED
@@ -1,40 +1,57 @@
1
1
  import {
2
+ PRESET_LABELS,
2
3
  PREVIEW_LABEL,
4
+ VIEW_CONTROLS_LABEL,
5
+ VIEW_HINT,
3
6
  replayPayload,
4
- viewBoxOf
5
- } from "./chunk-54YVSAVZ.js";
7
+ viewBoxOf,
8
+ viewToolbar
9
+ } from "./chunk-WBA4LABI.js";
6
10
  import {
11
+ ELEVATION_RANGE,
7
12
  END_AZIMUTH,
8
13
  END_FOV,
14
+ KIND_PALETTE,
15
+ PALETTE,
9
16
  START_FOV,
17
+ WALL_CAP_SRGB,
10
18
  boxOfNodes,
11
19
  cameraPosition,
12
20
  cameraStops,
21
+ distanceLimits,
13
22
  drawingFrame,
23
+ finishColour,
14
24
  frameCamera,
25
+ pivotAbove,
26
+ presetCamera,
27
+ slotColour,
15
28
  stateAt,
16
- stripAt
17
- } from "./chunk-CTFMM64C.js";
29
+ stripAt,
30
+ takenLens,
31
+ targetBounds
32
+ } from "./chunk-VPYTRKMK.js";
18
33
 
19
34
  // src/replay/mount.ts
20
35
  import {
21
- AmbientLight,
22
36
  BufferAttribute,
23
37
  BufferGeometry,
24
38
  Color,
25
39
  DirectionalLight,
26
40
  EdgesGeometry,
27
41
  Group,
42
+ HemisphereLight,
28
43
  LineBasicMaterial,
29
44
  LineSegments,
30
45
  Mesh,
31
46
  MeshLambertMaterial,
47
+ NeutralToneMapping,
32
48
  OrthographicCamera,
33
49
  PerspectiveCamera,
34
50
  Scene,
35
51
  Vector3,
36
52
  WebGLRenderer
37
53
  } from "three";
54
+ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
38
55
 
39
56
  // src/replay/strip-dom.ts
40
57
  function paintStrip(el, items) {
@@ -54,26 +71,19 @@ function paintStrip(el, items) {
54
71
  }
55
72
 
56
73
  // src/replay/mount.ts
74
+ var KEY_TURN_DEG = 5;
75
+ var KEY_DOLLY = 0.9;
57
76
  var THEMES = {
58
77
  light: {
59
78
  background: "#f7f5f0",
60
- edge: "#5b5650",
61
- colors: {
62
- slab: "#cfc8bc",
63
- floor: "#ece5d8",
64
- column: "#bdb5a8",
65
- wall: "#f4f1eb",
66
- roof: "#9c958a",
67
- door: "#b48a5c",
68
- "window:frame": "#e9e6e0",
69
- "window:glass": "#a9c7d8",
70
- "wall:demolish": "#c8553d",
71
- furniture: "#d9d1c3"
72
- }
79
+ edge: "#8f877c",
80
+ cap: WALL_CAP_SRGB,
81
+ colors: Object.fromEntries(Object.entries(KIND_PALETTE).map(([k, v]) => [k, v.srgb]))
73
82
  },
74
83
  dark: {
75
84
  background: "#0f2235",
76
85
  edge: "#cfe3f5",
86
+ cap: "#cfe3f5",
77
87
  colors: {
78
88
  slab: "#20384f",
79
89
  floor: "#1b3248",
@@ -88,9 +98,21 @@ var THEMES = {
88
98
  }
89
99
  }
90
100
  };
101
+ var LIGHT = {
102
+ sky: 16317439,
103
+ ground: 14275271,
104
+ hemi: 2.4,
105
+ keyColour: 16775922,
106
+ key: 2.7,
107
+ keyFrom: [-1, 1.25, 0.3],
108
+ fillColour: 15002869,
109
+ fill: 0.5,
110
+ fillFrom: [0.7, 0.5, -0.6]
111
+ };
91
112
  var FOOTPRINT_MM = 12;
92
- function mountReplay(out, p, strip) {
113
+ function mountReplay(out, p, strip, opts = {}) {
93
114
  const theme = THEMES[p.theme];
115
+ const furniture = theme.colors.furniture;
94
116
  const W = p.width;
95
117
  const H = p.height;
96
118
  const gl = document.createElement("canvas");
@@ -102,12 +124,16 @@ function mountReplay(out, p, strip) {
102
124
  const renderer = new WebGLRenderer({ canvas: gl, antialias: false, preserveDrawingBuffer: true });
103
125
  renderer.setPixelRatio(1);
104
126
  renderer.setSize(W, H, false);
127
+ renderer.toneMapping = NeutralToneMapping;
105
128
  const scene = new Scene();
106
129
  scene.background = new Color(theme.background);
107
- scene.add(new AmbientLight(16777215, 1.6));
108
- const sun = new DirectionalLight(16777215, 1.4);
109
- sun.position.set(-0.6, 1.4, 0.9);
110
- scene.add(sun);
130
+ scene.add(new HemisphereLight(LIGHT.sky, LIGHT.ground, LIGHT.hemi));
131
+ const key = new DirectionalLight(LIGHT.keyColour, LIGHT.key);
132
+ key.position.set(...LIGHT.keyFrom);
133
+ scene.add(key);
134
+ const fill = new DirectionalLight(LIGHT.fillColour, LIGHT.fill);
135
+ fill.position.set(...LIGHT.fillFrom);
136
+ scene.add(fill);
111
137
  const nodes = /* @__PURE__ */ new Map();
112
138
  const owned = [];
113
139
  for (const n of p.nodes) {
@@ -126,34 +152,66 @@ function mountReplay(out, p, strip) {
126
152
  pos[i + 1] = y - base;
127
153
  pos[i + 2] = z;
128
154
  }
129
- const geo = new BufferGeometry();
130
- geo.setAttribute("position", new BufferAttribute(pos, 3));
131
- geo.setIndex(n.indices);
132
- geo.computeVertexNormals();
133
- const key = n.part ? `${n.kind}:${n.part}` : n.kind;
134
- const glass = key === "window:glass";
135
- const ghost = key === "wall:demolish";
136
- const mat = new MeshLambertMaterial({
137
- color: new Color(theme.colors[key] ?? theme.colors.furniture),
138
- transparent: glass || ghost,
139
- opacity: glass ? 0.45 : ghost ? 0.3 : 1,
140
- depthWrite: !ghost,
141
- flatShading: true,
142
- // The floor finish sits a few millimetres under every footprint: pushed back in depth, so a
143
- // flat footprint never fights it in perspective.
144
- polygonOffset: n.kind === "floor" || n.kind === "slab",
145
- polygonOffsetFactor: 1,
146
- polygonOffsetUnits: 4
147
- });
148
- owned.push(geo, mat);
155
+ const key2 = n.part ? `${n.kind}:${n.part}` : n.kind;
149
156
  const g = new Group();
150
157
  g.position.y = base + (n.lift ?? 0);
151
- g.add(new Mesh(geo, mat));
152
- if (n.kind !== "slab" && !glass) {
153
- const edges = new EdgesGeometry(geo, 30);
154
- const line = new LineBasicMaterial({ color: new Color(theme.edge) });
155
- owned.push(edges, line);
156
- g.add(new LineSegments(edges, line));
158
+ const add = (attr2, indices, colour, glass, opacity, normals, edged = true) => {
159
+ const geo = new BufferGeometry();
160
+ geo.setAttribute("position", attr2);
161
+ geo.setIndex(indices);
162
+ if (normals) geo.computeVertexNormals();
163
+ const ghost = key2 === "wall:demolish";
164
+ const flatLaid = n.kind === "floor" || n.kind === "slab";
165
+ const mat = new MeshLambertMaterial({
166
+ color: new Color(colour),
167
+ transparent: glass || ghost,
168
+ opacity: glass ? opacity : ghost ? 0.3 : 1,
169
+ depthWrite: !ghost,
170
+ flatShading: true,
171
+ // Every face is pushed back a little, so the outline drawn on it wins the depth test
172
+ // cleanly instead of stippling into a dashed line. The floor finish sits a few millimetres
173
+ // under every footprint: pushed back further, so a flat footprint never fights it in
174
+ // perspective.
175
+ polygonOffset: true,
176
+ polygonOffsetFactor: 1,
177
+ polygonOffsetUnits: flatLaid ? 4 : 1
178
+ });
179
+ owned.push(geo, mat);
180
+ g.add(new Mesh(geo, mat));
181
+ if (n.kind !== "slab" && !glass && edged) {
182
+ const edges = new EdgesGeometry(geo, 30);
183
+ const line = new LineBasicMaterial({ color: new Color(theme.edge) });
184
+ owned.push(edges, line);
185
+ g.add(new LineSegments(edges, line));
186
+ }
187
+ };
188
+ const attr = new BufferAttribute(pos, 3);
189
+ if (n.groups) {
190
+ let at = 0;
191
+ for (const { slot, count } of n.groups) {
192
+ const run = n.indices.slice(at, at + count);
193
+ at += count;
194
+ if (slot === "body") add(attr, run, theme.colors[key2] ?? furniture, false, 1, false);
195
+ else {
196
+ const { alpha } = PALETTE[slot];
197
+ add(attr, run, slotColour(slot, p.theme, furniture), alpha < 1, alpha, false);
198
+ }
199
+ }
200
+ } else if (n.finish) {
201
+ add(attr, n.indices, finishColour(n.finish, p.theme, THEMES.dark.colors.floor), false, 1, true);
202
+ } else if (key2 === "wall") {
203
+ const atTop = (v) => n.positions[v * 3 + 1] / 1e3 === topY;
204
+ const cap = [];
205
+ const body = [];
206
+ for (let i = 0; i < n.indices.length; i += 3) {
207
+ const tri = n.indices.slice(i, i + 3);
208
+ (tri.every(atTop) ? cap : body).push(...tri);
209
+ }
210
+ add(attr, body, theme.colors.wall ?? furniture, false, 1, true);
211
+ if (cap.length) add(attr, cap, theme.cap, false, 1, true, false);
212
+ } else {
213
+ const glass = key2 === "window:glass";
214
+ add(attr, n.indices, theme.colors[key2] ?? furniture, glass, glass ? KIND_PALETTE["window:glass"].alpha : 1, true);
157
215
  }
158
216
  g.visible = false;
159
217
  scene.add(g);
@@ -188,35 +246,76 @@ function mountReplay(out, p, strip) {
188
246
  });
189
247
  img.src = `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(p.svg)))}`;
190
248
  let disposed = false;
191
- function seek(t) {
192
- if (disposed) return;
249
+ const frameView = { cx, cz, oh, elevation: p.elevation };
250
+ const storeyOf = new Map(p.events.map((e) => [e.key, e.storey ?? 0]));
251
+ const storeys = Math.max(1, ...p.events.filter((e) => !e.hidden).map((e) => (e.storey ?? 0) + 1));
252
+ let shown = storeys;
253
+ let holder = "replay";
254
+ let tNow = 0;
255
+ const halfDiagonal = size.length() / 2;
256
+ const reachFrom = (target) => Math.max(radius, mid.distanceTo(target) + halfDiagonal);
257
+ function place(f, r) {
258
+ const { fov, dist, elevation, azimuth } = f;
259
+ const target = new Vector3(...f.target);
260
+ const el = rad(elevation);
261
+ persp.fov = fov;
262
+ persp.near = Math.max(10, dist - r);
263
+ persp.far = dist + r;
264
+ persp.updateProjectionMatrix();
265
+ persp.up.set(0, 0, -1);
266
+ if (el < rad(89.99)) persp.up.set(0, 1, 0);
267
+ persp.position.set(...cameraPosition([target.x, target.y, target.z], dist, { elevation, azimuth }));
268
+ persp.lookAt(target);
269
+ }
270
+ const viewScene = { events: p.events, fits, frame: frameView, box: boxOfNodes(p.nodes), aspect };
271
+ const presets = /* @__PURE__ */ new Map();
272
+ const presetOf = (name) => {
273
+ const known = presets.get(name);
274
+ if (known) return known;
275
+ const f = presetCamera(name, viewScene);
276
+ presets.set(name, f);
277
+ return f;
278
+ };
279
+ let controls;
280
+ let halt = () => {
281
+ };
282
+ let unhook = () => {
283
+ };
284
+ let primeAgain = () => {
285
+ };
286
+ const listeners = /* @__PURE__ */ new Set();
287
+ const notify = () => {
288
+ for (const fn of listeners) fn();
289
+ };
290
+ function draw(t) {
291
+ tNow = t;
193
292
  if (strip && p.facts) paintStrip(strip, stripAt(p.facts, p.events, Math.min(1, Math.max(0, t))));
194
293
  const s = stateAt(p.events, t);
195
- for (const [key, { g, flat }] of nodes) {
196
- const st = s.nodes.get(key);
197
- g.visible = st?.visible === true;
294
+ for (const [key2, { g, flat }] of nodes) {
295
+ const st = s.nodes.get(key2);
296
+ g.visible = st?.visible === true && (storeyOf.get(key2) ?? 0) < shown;
198
297
  g.scale.y = Math.max(flat, st?.rise ?? 0);
199
298
  }
200
299
  let cam = ortho;
201
- if (s.tilt > 0 || s.dolly > 0) {
202
- const f = frameCamera(s, fits, { cx, cz, oh, elevation: p.elevation });
203
- const { fov, dist, elevation, azimuth } = f;
204
- const target = new Vector3(...f.target);
205
- const el = rad(elevation);
206
- persp.fov = fov;
207
- persp.near = Math.max(10, dist - radius);
208
- persp.far = dist + radius;
300
+ if (holder === "free" && controls) {
301
+ const dist = persp.position.distanceTo(controls.target);
302
+ const r = reachFrom(controls.target);
303
+ persp.near = Math.max(10, dist - r);
304
+ persp.far = dist + r;
209
305
  persp.updateProjectionMatrix();
210
- persp.up.set(0, 0, -1);
211
- if (el < rad(89.99)) persp.up.set(0, 1, 0);
212
- persp.position.set(...cameraPosition([target.x, target.y, target.z], dist, { elevation, azimuth }));
213
- persp.lookAt(target);
306
+ cam = persp;
307
+ } else if (holder !== "replay" && holder !== "free") {
308
+ const f = presetOf(holder);
309
+ place(f, reachFrom(new Vector3(...f.target)));
310
+ cam = persp;
311
+ } else if (s.tilt > 0 || s.dolly > 0) {
312
+ place(frameCamera(s, fits, frameView), radius);
214
313
  cam = persp;
215
314
  }
216
315
  renderer.render(scene, cam);
217
316
  ctx.globalAlpha = 1;
218
317
  ctx.drawImage(gl, 0, 0);
219
- if (s.svg > 0 && img.complete && img.naturalWidth > 0) {
318
+ if (holder === "replay" && s.svg > 0 && img.complete && img.naturalWidth > 0) {
220
319
  const k = Math.min(W / vw, H / vh);
221
320
  const dw = vw * k;
222
321
  const dh = vh * k;
@@ -225,25 +324,205 @@ function mountReplay(out, p, strip) {
225
324
  ctx.globalAlpha = 1;
226
325
  }
227
326
  }
327
+ function seek(t) {
328
+ if (disposed) return;
329
+ if (holder !== "replay") {
330
+ halt();
331
+ holder = "replay";
332
+ notify();
333
+ }
334
+ draw(t);
335
+ primeAgain();
336
+ }
228
337
  async function frameHash() {
229
338
  const data = ctx.getImageData(0, 0, W, H).data;
230
339
  const digest = await crypto.subtle.digest("SHA-256", data);
231
340
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
232
341
  }
342
+ const view = opts.interactive ? interact() : void 0;
343
+ function interact() {
344
+ const c = new OrbitControls(persp, out);
345
+ controls = c;
346
+ c.enableDamping = false;
347
+ c.screenSpacePanning = false;
348
+ c.minPolarAngle = rad(90 - ELEVATION_RANGE.max);
349
+ c.maxPolarAngle = rad(90 - ELEVATION_RANGE.min);
350
+ const bounds = targetBounds(box);
351
+ c.cursor.set(...bounds.centre);
352
+ const tabIndex0 = out.getAttribute("tabindex");
353
+ out.tabIndex = 0;
354
+ let loop = 0;
355
+ let dragging = false;
356
+ let quiet = false;
357
+ const reduced = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
358
+ const settle = () => {
359
+ loop = 0;
360
+ if (disposed || holder !== "free") return;
361
+ if (c.update() || dragging) loop = requestAnimationFrame(settle);
362
+ };
363
+ const kick = () => {
364
+ if (c.enableDamping && !loop) loop = requestAnimationFrame(settle);
365
+ };
366
+ halt = () => {
367
+ if (loop) cancelAnimationFrame(loop);
368
+ loop = 0;
369
+ dragging = false;
370
+ if (!c.enableDamping) return;
371
+ quiet = true;
372
+ c.enableDamping = false;
373
+ c.update();
374
+ quiet = false;
375
+ };
376
+ const aim = (position, target, fov) => {
377
+ persp.fov = fov;
378
+ persp.up.set(0, 1, 0);
379
+ persp.position.set(...position);
380
+ c.target.set(...pivotAbove(position, target, viewScene.box.lo[1]));
381
+ persp.lookAt(c.target);
382
+ const dist = persp.position.distanceTo(c.target);
383
+ const lim = distanceLimits(fits, fov);
384
+ c.minDistance = Math.min(lim.min, dist);
385
+ c.maxDistance = Math.max(lim.max, dist);
386
+ c.maxTargetRadius = Math.max(bounds.radius, c.target.distanceTo(c.cursor));
387
+ c.enableDamping = !reduced();
388
+ };
389
+ const prime = () => {
390
+ if (holder === "free") return;
391
+ const f = holder === "replay" ? takenLens(frameCamera(stateAt(p.events, tNow), fits, frameView)) : presetOf(holder);
392
+ aim(cameraPosition(f.target, f.dist, f), f.target, f.fov);
393
+ };
394
+ const own = () => {
395
+ if (holder === "free") return;
396
+ holder = "free";
397
+ opts.onTake?.();
398
+ notify();
399
+ kick();
400
+ };
401
+ let armed = false;
402
+ primeAgain = () => {
403
+ if (armed) prime();
404
+ };
405
+ c.addEventListener("start", () => {
406
+ prime();
407
+ armed = true;
408
+ dragging = true;
409
+ });
410
+ c.addEventListener("end", () => {
411
+ armed = false;
412
+ dragging = false;
413
+ });
414
+ c.addEventListener("change", () => {
415
+ if (quiet || disposed) return;
416
+ armed = false;
417
+ own();
418
+ draw(tNow);
419
+ });
420
+ const turn = rad(KEY_TURN_DEG);
421
+ const keys = /* @__PURE__ */ new Map([
422
+ ["ArrowLeft", () => c.rotateLeft(turn)],
423
+ ["ArrowRight", () => c.rotateLeft(-turn)],
424
+ ["ArrowUp", () => c.rotateUp(turn)],
425
+ ["ArrowDown", () => c.rotateUp(-turn)],
426
+ ["+", () => c.dollyIn(KEY_DOLLY)],
427
+ ["=", () => c.dollyIn(KEY_DOLLY)],
428
+ ["-", () => c.dollyOut(KEY_DOLLY)],
429
+ ["_", () => c.dollyOut(KEY_DOLLY)]
430
+ ]);
431
+ const onKey = (e) => {
432
+ const act = keys.get(e.key);
433
+ if (!act || disposed || e.ctrlKey || e.metaKey || e.altKey) return;
434
+ e.preventDefault();
435
+ prime();
436
+ act();
437
+ kick();
438
+ };
439
+ out.addEventListener("keydown", onKey);
440
+ unhook = () => {
441
+ out.removeEventListener("keydown", onKey);
442
+ c.dispose();
443
+ if (tabIndex0 === null) out.removeAttribute("tabindex");
444
+ else out.setAttribute("tabindex", tabIndex0);
445
+ listeners.clear();
446
+ };
447
+ const clampStoreys = (k) => Math.min(storeys, Math.max(1, Math.round(k)));
448
+ const shownState = () => shown === storeys ? "all" : shown;
449
+ return {
450
+ at: (t) => {
451
+ if (!disposed) draw(t);
452
+ },
453
+ // A preset takes the view as a drag does: the host pauses, or its next frame would hand the
454
+ // camera straight back to the replay.
455
+ preset: (name) => {
456
+ if (disposed) return;
457
+ halt();
458
+ holder = name;
459
+ opts.onTake?.();
460
+ notify();
461
+ draw(tNow);
462
+ },
463
+ reset: () => {
464
+ if (disposed) return;
465
+ halt();
466
+ holder = "replay";
467
+ shown = storeys;
468
+ notify();
469
+ draw(tNow);
470
+ },
471
+ storeys,
472
+ showStoreys: (k) => {
473
+ if (disposed) return;
474
+ shown = clampStoreys(k);
475
+ notify();
476
+ draw(tNow);
477
+ },
478
+ onChange: (fn) => {
479
+ listeners.add(fn);
480
+ return () => listeners.delete(fn);
481
+ },
482
+ get shown() {
483
+ return shown;
484
+ },
485
+ get camera() {
486
+ return holder;
487
+ },
488
+ state: () => holder === "free" ? {
489
+ camera: "free",
490
+ position: persp.position.toArray(),
491
+ target: c.target.toArray(),
492
+ fov: persp.fov,
493
+ storeys: shownState()
494
+ } : { camera: holder, storeys: shownState() },
495
+ restore: (s) => {
496
+ if (disposed) return;
497
+ halt();
498
+ shown = s.storeys === "all" ? storeys : clampStoreys(s.storeys);
499
+ if (s.camera === "free") aim(s.position, s.target, s.fov);
500
+ holder = s.camera;
501
+ if (holder !== "replay") opts.onTake?.();
502
+ notify();
503
+ }
504
+ };
505
+ }
233
506
  function dispose() {
234
507
  if (disposed) return;
508
+ halt();
235
509
  disposed = true;
510
+ unhook();
236
511
  for (const o of owned) o.dispose();
237
512
  renderer.dispose();
238
513
  renderer.forceContextLoss();
239
514
  }
240
- return { seek, frameHash, ready, dispose };
515
+ return { seek, frameHash, ready, dispose, ...view ? { view } : {} };
241
516
  }
242
517
  export {
518
+ PRESET_LABELS,
243
519
  PREVIEW_LABEL,
520
+ VIEW_CONTROLS_LABEL,
521
+ VIEW_HINT,
244
522
  mountReplay,
245
523
  paintStrip,
246
524
  replayPayload,
247
525
  stripAt,
248
- viewBoxOf
526
+ viewBoxOf,
527
+ viewToolbar
249
528
  };