lk3d 0.1.0 → 0.2.1

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 (63) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +28 -7
  3. package/bin/lk3d.mjs +24 -13
  4. package/dist/lk3d-export.min.js +1 -1
  5. package/dist/lk3d.min.js +73 -35
  6. package/dist/lk3d.mjs +72 -34
  7. package/docs/api.md +132 -51
  8. package/docs/design.md +12 -7
  9. package/docs/handles-and-lines.md +27 -0
  10. package/docs/performance.md +42 -10
  11. package/docs/scene-format.md +31 -29
  12. package/index.d.ts +53 -2
  13. package/package.json +2 -3
  14. package/scene.d.ts +200 -1
  15. package/schema/scene.schema.json +329 -1
  16. package/skill/lk3d/SKILL.md +14 -1
  17. package/src/ao.js +58 -0
  18. package/src/controls.js +21 -2
  19. package/src/element.js +111 -0
  20. package/src/figure/api.js +18 -3
  21. package/src/figure/camera.js +57 -9
  22. package/src/figure/context.d.ts +37 -2
  23. package/src/figure/dimensions.js +140 -0
  24. package/src/figure/idle.js +57 -19
  25. package/src/figure/input.js +105 -7
  26. package/src/figure/labels.js +26 -8
  27. package/src/figure/loop.js +8 -2
  28. package/src/figure/pick.js +24 -8
  29. package/src/figure/steps.js +144 -0
  30. package/src/flow.js +33 -2
  31. package/src/index.js +16 -2
  32. package/src/locales/en.js +7 -0
  33. package/src/locales/vi.js +7 -0
  34. package/src/renderer-gl.js +88 -16
  35. package/src/shaders.js +63 -17
  36. package/src/stylesheet.js +14 -4
  37. package/src/validate.js +89 -0
  38. package/docs/flow.png +0 -0
  39. package/docs/generator.png +0 -0
  40. package/docs/pen-blueprint.png +0 -0
  41. package/docs/pen-dark.png +0 -0
  42. package/docs/pen-ortho.png +0 -0
  43. package/docs/shapes/blade.png +0 -0
  44. package/docs/shapes/blob.png +0 -0
  45. package/docs/shapes/box.png +0 -0
  46. package/docs/shapes/capsule.png +0 -0
  47. package/docs/shapes/cylinder.png +0 -0
  48. package/docs/shapes/dna.png +0 -0
  49. package/docs/shapes/ellipsoid.png +0 -0
  50. package/docs/shapes/extrude.png +0 -0
  51. package/docs/shapes/helix.png +0 -0
  52. package/docs/shapes/lathe.png +0 -0
  53. package/docs/shapes/loop.png +0 -0
  54. package/docs/shapes/molecule.png +0 -0
  55. package/docs/shapes/orbit.png +0 -0
  56. package/docs/shapes/ring.png +0 -0
  57. package/docs/shapes/scatter.png +0 -0
  58. package/docs/shapes/shell.png +0 -0
  59. package/docs/shapes/sphere.png +0 -0
  60. package/docs/shapes/terrain.png +0 -0
  61. package/docs/shapes/torus.png +0 -0
  62. package/docs/shapes/tree.png +0 -0
  63. package/docs/shapes/tube.png +0 -0
@@ -1,8 +1,9 @@
1
1
  // @ts-check
2
2
  // The camera: where it stands and looks (fitted to the stage), the views and their glides, zooming towards a point,
3
3
  // the cut's plane, boxes round parts, and the ray through a point of the stage. Owns viewProj_, eye_, frustum_,
4
- // baseDist_, explodeShift_, camera_, project_, cutPlane_, boxOf_, shownBox_, rayAt_, zoom_, view_ and cancelView_;
5
- // reads state_, spec_, built_, width_, height_ and animations_, and calls offsetOf_, pickHit_, markDirty_ and kick_.
4
+ // baseDist_, explodeShift_, camera_, project_, cutPlane_, cutPlane2_, cutRange_, boxOf_, frame_, shownBox_, rayAt_, zoom_, view_,
5
+ // viewAngles_ and cancelView_;
6
+ // reads state_, spec_, built_, width_, height_ and animations_, and calls offsetOf_, pickHit_, measure_, markDirty_ and kick_.
6
7
  import { D2R, M, sub, add, mulv, len, norm, cross, dot } from '../math.js';
7
8
  import { clock } from '../clock.js';
8
9
  import LK3D from '../namespace.js';
@@ -48,11 +49,9 @@ export function makeCamera(c) {
48
49
  );
49
50
  return out;
50
51
  }
51
- function fitNow() {
52
- const width = c.width_,
53
- height = c.height_,
54
- ortho = c.state_.projection === 'ortho',
55
- key = width / height + (ortho ? 'o' : 'p');
52
+ function fitNow(aspect = c.width_ / c.height_) {
53
+ const ortho = c.state_.projection === 'ortho',
54
+ key = aspect + (ortho ? 'o' : 'p');
56
55
  if (key === fitFor) return fit;
57
56
  fitFor = key;
58
57
  const cosPitch = Math.cos(home.pitch),
@@ -66,12 +65,29 @@ export function makeCamera(c) {
66
65
  need = Math.max(
67
66
  need,
68
67
  (ortho ? 0 : dot(fromTarget, back)) +
69
- Math.max(Math.abs(dot(fromTarget, up)), Math.abs(dot(fromTarget, right)) / (width / height)) / tanHalfFov,
68
+ Math.max(Math.abs(dot(fromTarget, up)), Math.abs(dot(fromTarget, right)) / aspect) / tanHalfFov,
70
69
  );
71
70
  }
72
71
  // (and, as before, on a stage squarer than the scene's own proportions (a phone), back far enough for its width)
73
- return (fit = Math.max(1, (c.spec_.w || 16) / (c.spec_.h || 10) / (width / height), need / home.dist));
72
+ return (fit = Math.max(1, (c.spec_.w || 16) / (c.spec_.h || 10) / aspect, need / home.dist));
74
73
  }
74
+ // where the camera looks and from how far (as the state holds them: before the fit to the stage, the step back and
75
+ // the shift when taken apart) to frame some parts as they are once taken apart by `explode`: the sphere round them
76
+ // inside the frame, however narrow it is
77
+ c.frame_ = (parts, explode = c.state_.explode) => {
78
+ if (c.width_ <= 1) c.measure_(); // (not laid out yet: a figure just mounted)
79
+ const now = c.state_.explode;
80
+ c.state_.explode = explode;
81
+ const box = c.boxOf_(parts);
82
+ c.state_.explode = now;
83
+ const aspect = c.width_ > 1 && c.height_ > 1 ? c.width_ / c.height_ : (c.spec_.w || 16) / (c.spec_.h || 10),
84
+ tanHalf = (Math.tan(((c.spec_.view?.fov ?? 35) * D2R) / 2) * Math.min(1, aspect)) / 1.08, // (with a margin)
85
+ distance = c.state_.projection === 'ortho' ? box.radius / tanHalf : box.radius / Math.sin(Math.atan(tanHalf));
86
+ return {
87
+ target: sub(box.center, mulv(c.spec_.view?.explodeShift || [0, 0, 0], explode)),
88
+ dist: distance / fitNow(aspect) / (1 + (c.spec_.view?.explodeZoom ?? 0.5) * explode),
89
+ };
90
+ };
75
91
  c.camera_ = () => {
76
92
  const width = c.width_,
77
93
  height = c.height_,
@@ -130,6 +146,14 @@ export function makeCamera(c) {
130
146
  }
131
147
  return [normal[0], normal[1], normal[2], -(swept < 1 ? from + (to - from) * swept : to)];
132
148
  };
149
+ // the second plane of a quarter cut (section.second): what lies beyond both planes is cut away; without one, a
150
+ // plane everything is beyond, so one plane cuts alone
151
+ c.cutPlane2_ = () => {
152
+ const second = c.state_.section.second;
153
+ if (!second) return [0, 0, 0, 1];
154
+ const normal = norm(second.normal || [1, 0, 0]);
155
+ return [normal[0], normal[1], normal[2], -(second.offset || 0)];
156
+ };
133
157
  // what is on screen now (for the shadow's reach) and the floor under the assembled model
134
158
  c.shownBox_ = () => c.boxOf_(c.built_.parts.filter((part) => part.drawAlpha >= 0.01));
135
159
  // the box round some parts where they are now (taken apart, moved)
@@ -145,6 +169,28 @@ export function makeCamera(c) {
145
169
  }
146
170
  return { center: mulv(add(min, max), 0.5), radius: len(sub(max, min)) / 2 || 1, min, max };
147
171
  };
172
+ // how far along the cut's normal the parts it cuts reach, as they are now: where the plane can go [from, to]
173
+ c.cutRange_ = (second = false) => {
174
+ const normal = norm(second ? (c.state_.section.second || {}).normal || [1, 0, 0] : c.state_.section.normal);
175
+ let from = Infinity,
176
+ to = -Infinity;
177
+ for (const part of c.built_.parts)
178
+ if (part.cut && !part.hidden) {
179
+ const offset = c.offsetOf_(part);
180
+ for (let corner = 0; corner < 8; corner++) {
181
+ const along = dot(
182
+ normal,
183
+ add(
184
+ offset,
185
+ [0, 1, 2].map((axis) => ((corner >> axis) & 1 ? part.max[axis] : part.min[axis])),
186
+ ),
187
+ );
188
+ from = Math.min(from, along);
189
+ to = Math.max(to, along);
190
+ }
191
+ }
192
+ return from <= to ? [from, to] : [-1, 1];
193
+ };
148
194
  // a point of the scene on the stage, in CSS pixels (null behind the eye), by the camera as last placed
149
195
  c.project_ = (point) => M.project(c.viewProj_, point, c.width_, c.height_);
150
196
  c.rayAt_ = (x, y) => {
@@ -235,6 +281,8 @@ export function makeCamera(c) {
235
281
  c.animations_.add(tween);
236
282
  c.kick_();
237
283
  };
284
+ // a named view's angles (degrees), else where the camera looks now
285
+ c.viewAngles_ = (name) => VIEWS[name] || [c.state_.yaw / D2R, c.state_.pitch / D2R];
238
286
  c.cancelView_ = () => {
239
287
  if (viewTween) c.animations_.delete(viewTween);
240
288
  viewTween = null;
@@ -21,6 +21,8 @@ export interface Renderer {
21
21
  upload?(batch: any): void;
22
22
  instances?(batch: any): void;
23
23
  release?(thing: any): void;
24
+ /** whether it places this flow's streaks itself, on the GPU (WebGL 2), so the frame loop need not */
25
+ placesFlow?(flow: any): boolean;
24
26
  edges?(batch: any): void;
25
27
  dispose(): void;
26
28
  }
@@ -42,8 +44,15 @@ export interface State {
42
44
  explode: number;
43
45
  spin: number;
44
46
  cut: boolean | number;
45
- section: { normal: Vec3 | number[]; offset: number };
47
+ /** the cut's plane, and a quarter cut's second (section.second) */
48
+ section: {
49
+ normal: Vec3 | number[];
50
+ offset: number;
51
+ second?: { normal?: Vec3 | number[]; offset?: number } | null | false;
52
+ };
46
53
  labels: any;
54
+ /** the dimensions shown, by id; null: the scene's own */
55
+ dimensions: string[] | null;
47
56
  xray: boolean;
48
57
  yaw: number;
49
58
  pitch: number;
@@ -95,6 +104,8 @@ export interface Ctx {
95
104
  treesMs: number | null;
96
105
  aoMs: number | null;
97
106
  refreshMs: number | null;
107
+ /** whether the crease shading was worked out in the page's worker (ao.js), not here */
108
+ aoWorker: boolean;
98
109
  };
99
110
  /** performance.now() when mount began (stats_ count from it) */
100
111
  mountedAt_: number;
@@ -188,12 +199,20 @@ export interface Ctx {
188
199
  project_(q: number[]): number[] | null;
189
200
  /** the cut's plane [nx, ny, nz, -offset] */
190
201
  cutPlane_(): number[];
202
+ /** a quarter cut's second plane, or [0, 0, 0, 1] (everything beyond it: the first plane cuts alone) */
203
+ cutPlane2_(): number[];
204
+ /** how far along the cut's normal the parts it cuts reach now: where the plane can go [from, to] */
205
+ cutRange_(second?: boolean): number[];
191
206
  /** the box round the parts drawn now */
192
207
  shownBox_(): { center: number[]; radius: number; min: number[]; max: number[] };
193
208
  boxOf_(ps: Part[]): { center: number[]; radius: number; min: number[]; max: number[] };
209
+ /** the target and distance (as the state holds them) that frame these parts, taken apart by explode */
210
+ frame_(ps: Part[], explode?: number): { target: number[]; dist: number };
194
211
  rayAt_(px: number, py: number): { origin: number[]; direction: number[] };
195
212
  zoom_(k: number, x?: number, y?: number): void;
196
213
  view_(name: any, o?: { ms?: number; [key: string]: any }): void;
214
+ /** a named view's [yaw, pitch] in degrees, else the camera's now */
215
+ viewAngles_(name: string): number[];
197
216
  cancelView_(): void;
198
217
 
199
218
  // ---- dom.js
@@ -212,6 +231,8 @@ export interface Ctx {
212
231
  /** the stage's size, CSS pixels */
213
232
  width_: number;
214
233
  height_: number;
234
+ /** measure (and shape) the stage now */
235
+ measure_(): void;
215
236
  dpr_: number;
216
237
  /** the share of full resolution drawn (lowered while frames come late) */
217
238
  resolution_: number;
@@ -241,7 +262,7 @@ export interface Ctx {
241
262
  px: number,
242
263
  py: number,
243
264
  see?: number,
244
- ): { id: string | null; t: number; origin: number[]; direction: number[] };
265
+ ): { id: string | null; t: number; origin: number[]; direction: number[]; onCut: boolean };
245
266
  pickAt_(px: number, py: number, see?: number): string | null;
246
267
 
247
268
  // ---- idle.js
@@ -257,6 +278,10 @@ export interface Ctx {
257
278
  setHandle_(grip: Grip, v: number, byReader: boolean): void;
258
279
  /** a hidden part's handle out of the Tab order and of what screen readers read */
259
280
  syncHandleInputs_(): void;
281
+ /** whether the reader may move the cut now (it is on, and the scene does not fix it) */
282
+ cutMovable_(): boolean;
283
+ /** the cut moved by the reader (held within the parts it cuts; onSection called) */
284
+ moveCut_(offset: number, second?: boolean): void;
260
285
 
261
286
  // ---- additions.js
262
287
  addParticles_(o: any): any;
@@ -266,6 +291,16 @@ export interface Ctx {
266
291
 
267
292
  // ---- api.js
268
293
  api_: any;
294
+
295
+ // ---- dimensions.js
296
+ /** the dimensions placed on the stage, after each picture */
297
+ placeDimensions_(): void;
298
+
299
+ // ---- steps.js
300
+ /** the step shown (from 0); -1 for a scene without steps */
301
+ stepAt_: number;
302
+ /** go to a step by its place (from 0) or id; ms: 0 sets it at once */
303
+ goToStep_(which: number | string, o?: { ms?: number }): void;
269
304
  }
270
305
 
271
306
  declare global {
@@ -0,0 +1,140 @@
1
+ // @ts-check
2
+ // Dimensions on the figure, as on a technical drawing (the scene's `dimensions`): a length between two points, with
3
+ // extension lines out to a dimension line, arrows and its value; an angle at a vertex, an arc with arrows and its value
4
+ // in degrees. A point may ride on a part ({part, at}), so a length to a moving part changes as it moves; the value is
5
+ // worked out from the points as shown (in the scene's unit), unless the scene gives its text. Drawn after each picture
6
+ // over the canvas, an SVG path and an HTML value each, changed only where they moved; listed for screen readers with
7
+ // their values. Which show: the scene's own (not hidden), or the ones a step or the page names (state_.dimensions).
8
+ // Owns placeDimensions_; reads spec_, built_, state_, words_, host_, leaderSvg_ and tagLayer_, and calls part_ and project_.
9
+ import { M, sub, add, mulv, len, norm, dot } from '../math.js';
10
+
11
+ /** @param {import('./context').Ctx} c */
12
+ export function makeDimensions(c) {
13
+ const dimensions = (c.spec_.dimensions || []).filter((dimension) => dimension && typeof dimension === 'object');
14
+ c.placeDimensions_ = () => {};
15
+ if (!dimensions.length) return;
16
+ const forReaders = document.createElement('ul');
17
+ forReaders.className = 'lk3d-sr';
18
+ forReaders.setAttribute('aria-label', c.words_.dimensions);
19
+ c.host_.append(forReaders);
20
+ const drawn = dimensions.map((dimension) => {
21
+ const path = /** @type {SVGPathElement} */ (document.createElementNS('http://www.w3.org/2000/svg', 'path')),
22
+ value = document.createElement('div'),
23
+ item = document.createElement('li');
24
+ path.setAttribute('class', 'lk3d-dim');
25
+ value.className = 'lk3d-dimtext';
26
+ value.setAttribute('aria-hidden', 'true');
27
+ c.leaderSvg_.append(path);
28
+ c.tagLayer_.append(value);
29
+ forReaders.append(item);
30
+ return { dimension, path, value, item, d: '', at: '', text: '', shown: true };
31
+ });
32
+
33
+ // a point as shown: [x, y, z], or one a part carries, through the part's matrix; null where that part is out of sight
34
+ /** @param {any} point */
35
+ const placed = (point) => {
36
+ if (Array.isArray(point)) return point;
37
+ const part = point && c.part_(point.part);
38
+ return part && !part.hidden ? M.pt(part.matrix, point.at) : null;
39
+ };
40
+ // a value in words: three significant figures (or the scene's digits), the locale's decimal mark, the unit
41
+ /** @param {number} number @param {number | undefined} digits */
42
+ const METRES = { mm: 0.001, cm: 0.01, dm: 0.1, m: 1, km: 1000 };
43
+ const say = (number, digits) =>
44
+ (digits == null ? String(+number.toPrecision(3)) : number.toFixed(digits)).replace('.', c.words_.decimal);
45
+ // an arrowhead at the stage point tip, pointing along direction (from the inside of the line to the tip)
46
+ /** @param {number[]} tip @param {number[]} along */
47
+ const arrow = (tip, along) => {
48
+ const length = Math.hypot(along[0], along[1]) || 1,
49
+ [x, y] = [along[0] / length, along[1] / length],
50
+ side = (sign) => [tip[0] - 7 * (x * 0.91 - sign * y * 0.42), tip[1] - 7 * (y * 0.91 + sign * x * 0.42)];
51
+ const [a, b] = [side(1), side(-1)];
52
+ return `M${a[0].toFixed(1)} ${a[1].toFixed(1)}L${tip[0].toFixed(1)} ${tip[1].toFixed(1)}L${b[0].toFixed(1)} ${b[1].toFixed(1)}`;
53
+ };
54
+ /** @param {number[][]} points */
55
+ const line = (points) => 'M' + points.map((point) => `${point[0].toFixed(1)} ${point[1].toFixed(1)}`).join('L');
56
+
57
+ c.placeDimensions_ = () => {
58
+ const wanted = c.state_.dimensions;
59
+ for (const each of drawn) {
60
+ const dimension = each.dimension,
61
+ named = wanted ? dimension.id != null && wanted.includes(dimension.id) : !dimension.hidden;
62
+ let d = '',
63
+ /** @type {number[] | null} */
64
+ at = null,
65
+ text = '';
66
+ if (named && dimension.angle) {
67
+ const [a, vertex, b] = dimension.angle.map(placed);
68
+ if (a && vertex && b) {
69
+ const u = sub(a, vertex),
70
+ w = sub(b, vertex),
71
+ theta = Math.acos(Math.max(-1, Math.min(1, dot(norm(u), norm(w))))),
72
+ radius = dimension.radius ?? Math.min(len(u), len(w)) / 3,
73
+ // (points along the arc, from one arm to the other: a slerp, or a half turn round a side when straight)
74
+ arc = Array.from({ length: 17 }, (_, k) => {
75
+ const t = k / 16,
76
+ s = Math.sin(theta) || 1e-6;
77
+ return add(
78
+ vertex,
79
+ mulv(add(mulv(norm(u), Math.sin((1 - t) * theta) / s), mulv(norm(w), Math.sin(t * theta) / s)), radius),
80
+ );
81
+ }).map((point) => c.project_(point));
82
+ if (theta > 1e-3 && theta < Math.PI - 1e-3 && arc.every(Boolean)) {
83
+ const onStage = /** @type {number[][]} */ (arc);
84
+ d =
85
+ line(onStage) +
86
+ arrow(onStage[0], sub(onStage[0], onStage[1])) +
87
+ arrow(onStage[16], sub(onStage[16], onStage[15]));
88
+ const ends = [c.project_(vertex), c.project_(a), c.project_(b)];
89
+ if (dimension.arms && ends.every(Boolean)) {
90
+ const [v, p, q] = /** @type {number[][]} */ (ends);
91
+ d += line([p, v, q]);
92
+ }
93
+ const middle = add(vertex, mulv(norm(add(norm(u), norm(w))), radius * 1.35));
94
+ at = c.project_(middle);
95
+ text = dimension.text ?? say((theta * 180) / Math.PI, dimension.digits ?? (theta < 0.17 ? 1 : 0)) + '°';
96
+ }
97
+ }
98
+ } else if (named) {
99
+ const from = placed(dimension.from),
100
+ to = placed(dimension.to);
101
+ if (from && to) {
102
+ const offset = dimension.offset || [0, 0, 0],
103
+ [a, b, a2, b2] = [from, to, add(from, offset), add(to, offset)].map((point) => c.project_(point));
104
+ if (a && b && a2 && b2) {
105
+ if (len(offset) > 0)
106
+ for (const [object, onLine] of [
107
+ [a, a2],
108
+ [b, b2],
109
+ ]) {
110
+ // (an extension line: a small gap at the object, past the dimension line a little)
111
+ const along = sub(onLine, object),
112
+ pixels = Math.hypot(along[0], along[1]) || 1,
113
+ step = mulv(along, 1 / pixels);
114
+ d += line([add(object, mulv(step, 3)), add(onLine, mulv(step, 5))]);
115
+ }
116
+ d += line([a2, b2]) + arrow(a2, sub(a2, b2)) + arrow(b2, sub(b2, a2));
117
+ at = mulv(add(a2, b2), 0.5);
118
+ const unit = dimension.unit || c.spec_.unit,
119
+ // (in the scene's unit, or converted to the dimension's own)
120
+ factor = dimension.unit && c.spec_.unit ? METRES[c.spec_.unit] / METRES[dimension.unit] : 1;
121
+ text = dimension.text ?? say(len(sub(to, from)) * factor, dimension.digits) + (unit ? ' ' + unit : '');
122
+ }
123
+ }
124
+ }
125
+ const show = !!(d && at);
126
+ if (show !== each.shown) {
127
+ each.path.style.display = each.value.style.display = show ? '' : 'none';
128
+ each.shown = show;
129
+ }
130
+ if (!show || !at) continue;
131
+ if (d !== each.d) each.path.setAttribute('d', (each.d = d));
132
+ const place = `translate(${at[0].toFixed(1)}px, ${at[1].toFixed(1)}px) translate(-50%, -50%)`;
133
+ if (place !== each.at) each.value.style.transform = each.at = place;
134
+ if (text !== each.text) {
135
+ each.value.textContent = each.text = text;
136
+ each.item.textContent = (dimension.name ? dimension.name + ': ' : '') + text;
137
+ }
138
+ }
139
+ };
140
+ }
@@ -1,11 +1,12 @@
1
1
  // @ts-check
2
2
  // The work done in idle slices after the first picture, a few milliseconds at a time: the trees for picking, the crease
3
3
  // shading (ambient occlusion) and the pen look's edges; and whether the figure is complete (checkReady_: its `ready`).
4
- // Owns aoComplete_, showEdges_, findEdges_ and checkReady_; reads built_, spec_, opts_, stats_, mountedAt_, renderer_,
4
+ // Owns aoComplete_, showEdges_, findEdges_ and checkReady_ (the crease shading in the page's worker: ao.js); reads built_, spec_, opts_, stats_, mountedAt_, renderer_,
5
5
  // look_, destroyed_, resolveReady_ and api_, and calls bvhOf_ and kick_.
6
6
  import { sub, len } from '../math.js';
7
7
  import { edgesOf } from '../geometry.js';
8
8
  import { aoJob } from '../bvh.js';
9
+ import { shadeAway } from '../ao.js';
9
10
 
10
11
  /** @param {import('./context').Ctx} c */
11
12
  export function makeIdle(c) {
@@ -47,30 +48,44 @@ export function makeIdle(c) {
47
48
  setTimeout(build, 30);
48
49
  }
49
50
 
50
- // ---- ambient occlusion: creases and the insides of hollow parts darkened, by rays against the trees, then drawn
51
+ // ---- ambient occlusion: creases and the insides of hollow parts darkened, by rays against each shape's tree, then
52
+ // drawn. Each shape is sent to the page's worker (ao.js) as it comes up, and drawn when its shading comes back; where
53
+ // there is no worker (or it stops), shaded here in idle slices, a few milliseconds at a time
51
54
  if (c.renderer_.kind !== '2d' && c.opts_.ao !== false) {
52
55
  const queue = batches.slice(),
53
- aoByMesh = new Map();
56
+ aoByMesh = new Map(),
57
+ away = new Map(); // a mesh in the worker → the batches waiting for its shading
54
58
  /** @type {{ batch: any, job: ReturnType<typeof aoJob> } | null} */
55
- let current = null; // (the batch being shaded, and its job)
59
+ let current = null, // (the batch being shaded here, and its job)
60
+ working = false;
61
+ const shaded = (batch, out) => {
62
+ batch.ao = out;
63
+ aoByMesh.set(batch.mesh, out);
64
+ c.renderer_.setAO(batch);
65
+ };
66
+ const finish = () => {
67
+ if (aoDone || queue.length || current || away.size) return;
68
+ c.aoComplete_ = aoDone = true;
69
+ c.stats_.aoMs = performance.now() - c.mountedAt_;
70
+ c.kick_();
71
+ c.checkReady_();
72
+ };
56
73
  const work = () => {
74
+ working = false;
57
75
  if (c.destroyed_) return;
58
76
  const end = performance.now() + 6;
59
77
  while (performance.now() < end) {
60
78
  if (!current) {
61
79
  const batch = queue.shift();
62
- if (batch && aoByMesh.has(batch.mesh)) {
80
+ if (!batch) return finish();
81
+ if (aoByMesh.has(batch.mesh)) {
63
82
  // (a mesh shared by parts alike: its crease shading is the same, made once)
64
- batch.ao = aoByMesh.get(batch.mesh);
65
- c.renderer_.setAO(batch);
83
+ shaded(batch, aoByMesh.get(batch.mesh));
66
84
  continue;
67
85
  }
68
- if (!batch) {
69
- c.aoComplete_ = aoDone = true;
70
- c.stats_.aoMs = performance.now() - c.mountedAt_;
71
- c.kick_();
72
- c.checkReady_();
73
- return;
86
+ if (away.has(batch.mesh)) {
87
+ away.get(batch.mesh).push(batch);
88
+ continue;
74
89
  }
75
90
  if (batch.mesh.count > 40000) continue; // a very detailed shape: its own folds already read; spare the phone the rays
76
91
  const mesh = batch.mesh;
@@ -82,19 +97,42 @@ export function makeIdle(c) {
82
97
  hi[axis] = Math.max(hi[axis], mesh.positions[3 * vertex + axis]);
83
98
  }
84
99
  // (rays as long as a quarter of the shape, within limits: creases darken, not the whole of a big part)
85
- const reach = Math.max(0.02, Math.min(len(sub(hi, lo)) * 0.25, c.built_.radius * 0.12));
100
+ const reach = Math.max(0.02, Math.min(len(sub(hi, lo)) * 0.25, c.built_.radius * 0.12)),
101
+ inWorker = shadeAway(mesh, reach);
102
+ if (inWorker) {
103
+ away.set(mesh, [batch]);
104
+ inWorker.then(
105
+ (out) => {
106
+ if (c.destroyed_) return;
107
+ c.stats_.aoWorker = true;
108
+ for (const each of away.get(mesh)) shaded(each, out);
109
+ away.delete(mesh);
110
+ c.kick_();
111
+ finish();
112
+ },
113
+ () => {
114
+ // (the worker stopped: its batches shaded here)
115
+ queue.push(...away.get(mesh));
116
+ away.delete(mesh);
117
+ start();
118
+ },
119
+ );
120
+ continue;
121
+ }
86
122
  current = { batch, job: aoJob(mesh, c.bvhOf_(batch), reach) };
87
123
  }
88
124
  if (current.job.step(Math.max(1, end - performance.now()))) {
89
- current.batch.ao = current.job.out;
90
- aoByMesh.set(current.batch.mesh, current.job.out);
91
- c.renderer_.setAO(current.batch);
125
+ shaded(current.batch, current.job.out);
92
126
  current = null;
93
127
  }
94
128
  }
95
- setTimeout(work, 16);
129
+ start(16);
130
+ };
131
+ const start = (ms = 0) => {
132
+ if (!working) setTimeout(work, ms);
133
+ working = true;
96
134
  };
97
- setTimeout(work, 60);
135
+ start(60);
98
136
  }
99
137
 
100
138
  // ---- edges: drawn in the pen look (and in any look with the scene's edges: true; never with edges: false), found in
@@ -1,10 +1,12 @@
1
1
  // @ts-check
2
2
  // The reader's hands on a figure: the pointer (orbit, pan, pinch, hover, pick, grabbing a handle and dragging it),
3
3
  // the wheel (only once the figure is taken hold of), the keys (turn, zoom, go through the parts), and each handle as
4
- // a range input (its value set by the reader or the page: setHandle_). Owns setHandle_ and syncHandleInputs_; reads
5
- // host_, canvas_, state_, opts_, words_, stage_, hint_, namedParts_, handles_, animations_ and height_, and calls
6
- // pickAt_, rayAt_, project_, baseMatrix_, zoom_, cancelView_, showInfo_, part_, markDirty_ and kick_.
7
- import { M, sub, add, mulv, len } from '../math.js';
4
+ // a range input (its value set by the reader or the page: setHandle_), and the cut moved by the reader (its face
5
+ // dragged, or the built-in slider: moveCut_). Owns setHandle_, syncHandleInputs_, cutMovable_ and moveCut_; reads
6
+ // host_, canvas_, spec_, state_, opts_, words_, stage_, hint_, namedParts_, handles_, animations_, controls_ and
7
+ // height_, and calls pickAt_, pickHit_, rayAt_, project_, cutPlane_, cutRange_, baseMatrix_, zoom_, cancelView_,
8
+ // showInfo_, part_, markDirty_ and kick_.
9
+ import { M, sub, add, mulv, len, dot, cross, norm } from '../math.js';
8
10
  import * as HD from '../handles.js';
9
11
  import { plainText } from './dom.js';
10
12
  import LK3D from '../namespace.js';
@@ -116,6 +118,66 @@ export function makeInput(c) {
116
118
  }
117
119
  c.setHandle_(grip, value, true);
118
120
  }
121
+ // ---- the cut moved by the reader: its face taken hold of and dragged along the plane's normal (unless the scene
122
+ // fixes it: section.fixed). A drag reads depth by the normal's direction on the stage, or by up and down where the
123
+ // cut face is seen nearly face on (the normal pointing at the eye has no direction on the stage)
124
+ c.cutMovable_ = () =>
125
+ !!c.state_.cut && c.spec_.section !== false && !c.spec_.section?.fixed && c.renderer_.kind !== '2d';
126
+ // (second: the quarter cut's other plane, section.second, moved instead)
127
+ c.moveCut_ = (offset, second = false) => {
128
+ const section = c.state_.section,
129
+ [from, to] = c.cutRange_(second),
130
+ held = Math.max(from, Math.min(to, offset));
131
+ if (held === (second ? (section.second || {}).offset : section.offset)) return;
132
+ c.state_.section = second
133
+ ? { ...section, second: { ...section.second, offset: held } }
134
+ : { ...section, offset: held };
135
+ if (c.controls_.style) c.controls_.style(); // (the slider follows)
136
+ c.kick_();
137
+ if (c.opts_.onSection) c.opts_.onSection(c.api_.section);
138
+ };
139
+ /** @type {{ id: number, x: number, y: number, from: number, along: number[], moved: number, part: string, second: boolean } | null} */
140
+ let cutting = null;
141
+ /** @param {number} x @param {number} y */
142
+ function cutAt(x, y) {
143
+ if (!c.cutMovable_()) return null;
144
+ const hit = c.pickHit_(x, y);
145
+ if (!hit.onCut || !hit.id) return null;
146
+ // (the face taken hold of: the first plane's, or in a quarter cut the second's, where the ray's crossing of the
147
+ // first lies outside the cut-away wedge)
148
+ const crossing = (/** @type {number[]} */ plane) => {
149
+ const facing = dot(plane.slice(0, 3), hit.direction);
150
+ return Math.abs(facing) < 1e-9
151
+ ? null
152
+ : add(hit.origin, mulv(hit.direction, -(dot(plane.slice(0, 3), hit.origin) + plane[3]) / facing));
153
+ };
154
+ const first = c.cutPlane_(),
155
+ other = c.cutPlane2_();
156
+ let plane = first,
157
+ point = crossing(first);
158
+ const second = !point || dot(other.slice(0, 3), point) + other[3] < 0;
159
+ if (second) point = crossing((plane = other));
160
+ if (!point) return null;
161
+ const normal = plane.slice(0, 3),
162
+ across = norm(cross(normal, Math.abs(normal[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0])),
163
+ here = c.project_(point),
164
+ deeper = c.project_(add(point, normal)),
165
+ aside = c.project_(add(point, across));
166
+ if (!here || !deeper || !aside) return null;
167
+ const perUnit = Math.hypot(aside[0] - here[0], aside[1] - here[1]); // (pixels a scene unit, across the cut)
168
+ let along = [deeper[0] - here[0], deeper[1] - here[1]];
169
+ if (Math.hypot(along[0], along[1]) < 0.3 * perUnit) along = [0, -perUnit];
170
+ const section = c.state_.section;
171
+ return {
172
+ x,
173
+ y,
174
+ from: second ? (section.second || {}).offset || 0 : section.offset,
175
+ along,
176
+ moved: 0,
177
+ part: hit.id,
178
+ second,
179
+ };
180
+ }
119
181
  const capture = (pointerId) => {
120
182
  try {
121
183
  c.canvas_.setPointerCapture(pointerId);
@@ -131,7 +193,18 @@ export function makeInput(c) {
131
193
  }
132
194
  if (!pointers.size) {
133
195
  const [x, y] = local(event),
134
- grip = handleAt(x, y);
196
+ grip = handleAt(x, y),
197
+ cut = grip ? null : cutAt(x, y);
198
+ if (cut) {
199
+ // the reader takes hold of the cut face: the plane moves, the view does not
200
+ cutting = { ...cut, id: event.pointerId };
201
+ capture(event.pointerId);
202
+ c.canvas_.style.cursor = 'grabbing';
203
+ c.hint_.classList.add('gone');
204
+ setActive(true);
205
+ event.preventDefault();
206
+ return;
207
+ }
135
208
  if (grip) {
136
209
  // the reader takes hold of a handle: it moves, the view does not
137
210
  grab = {
@@ -160,6 +233,18 @@ export function makeInput(c) {
160
233
  c.hint_.classList.add('gone');
161
234
  });
162
235
  c.canvas_.addEventListener('pointermove', (event) => {
236
+ if (cutting && event.pointerId === cutting.id) {
237
+ const [x, y] = local(event),
238
+ dx = x - cutting.x,
239
+ dy = y - cutting.y,
240
+ along = cutting.along;
241
+ cutting.moved = Math.max(cutting.moved, Math.abs(dx) + Math.abs(dy));
242
+ c.moveCut_(
243
+ cutting.from + (dx * along[0] + dy * along[1]) / (along[0] * along[0] + along[1] * along[1]),
244
+ cutting.second,
245
+ );
246
+ return;
247
+ }
163
248
  if (grab && event.pointerId === grab.id) {
164
249
  const [x, y] = local(event);
165
250
  grab.moved += Math.abs(event.movementX || 0) + Math.abs(event.movementY || 0);
@@ -201,8 +286,10 @@ export function makeInput(c) {
201
286
  // (hovering: what is under the pointer, at most every 40 ms)
202
287
  lastHover = performance.now();
203
288
  const [x, y] = local(event),
204
- id = c.pickAt_(x, y);
205
- const onHandle = id ? !!c.part_(id)?.handleOf : !!handleAt(x, y);
289
+ hit = c.pickHit_(x, y),
290
+ id = hit.id;
291
+ // (a handle, or a cut face the reader may move: grabbed, not chosen)
292
+ const onHandle = (id ? !!c.part_(id)?.handleOf : !!handleAt(x, y)) || (hit.onCut && c.cutMovable_());
206
293
  if (id !== c.state_.hover || onHandle !== wasOnHandle) {
207
294
  c.state_.hover = id;
208
295
  wasOnHandle = onHandle;
@@ -213,6 +300,17 @@ export function makeInput(c) {
213
300
  }
214
301
  });
215
302
  const end = (event) => {
303
+ if (cutting && event.pointerId === cutting.id) {
304
+ // let go of the cut; a tap without moving chooses the part, as elsewhere
305
+ if (cutting.moved < 4 && event.type === 'pointerup') {
306
+ c.state_.selected = cutting.part === c.state_.selected ? null : cutting.part;
307
+ c.showInfo_('pick');
308
+ }
309
+ cutting = null;
310
+ c.canvas_.style.cursor = 'grab';
311
+ c.kick_();
312
+ return;
313
+ }
216
314
  if (grab && event.pointerId === grab.id) {
217
315
  // let go of a handle; a tap without moving selects the part, as elsewhere
218
316
  if (grab.moved < 4 && event.type === 'pointerup') {