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
package/CHANGELOG.md CHANGED
@@ -3,6 +3,65 @@
3
3
  lk3d follows [semantic versioning](https://semver.org): before 1.0, a minor version (0.x.0) may change the scene
4
4
  format or the API, and says how to move.
5
5
 
6
+ ## 0.2.1 (11 November 2026)
7
+
8
+ - **Quarter cuts**: a second plane, `section.second` (`{normal, offset}`), and only what lies beyond both planes is cut
9
+ away, as in a technical cutaway; both faces are filled and hatched, the reader drags either, and `fig.section` reports
10
+ both. A step or the page drops it with `second: false` / `null`.
11
+ - **The playground** (`playground/`, published at https://xoai.github.io/lk3d/playground/): a scene's JSON beside the
12
+ figure, drawn as it is typed and checked as `lk3d check` does (the format and the geometry, in a worker), each problem
13
+ shown at its place in the text; the examples to start from; a look and a theme; Share makes a link with the scene in
14
+ it, and the scene goes out as .json or .glb. `npm run playground` serves it from a checkout.
15
+ - **Dimensions** (`dimensions` in the scene): lengths between points and angles at vertices, drawn as on a technical
16
+ drawing (extension lines, arrows, the value), their values worked out from the figure as shown, in the scene's unit or
17
+ the dimension's own (`unit`); a point may ride on a part (`{part, at}`), so a length to it follows the part as the
18
+ reader moves it. Steps (`dimensions: [ids]`) and the page (`fig.set({ dimensions })`) choose which show; screen
19
+ readers find them listed. The lens bench example measures the object's distance and the focal length. New word:
20
+ `dimensions`.
21
+ - **Examples**: a tour of a human cell (`examples/cell-tour.html`, its scene made by `examples/cell-tour.mjs`), made as
22
+ detailed as an illustrated film: proteins in the membrane, nuclear pores, loose chromatin, smooth ER, mitochondria
23
+ with folded cristae, a Golgi stack with swollen rims and budding vesicles, centrioles of nine triplets, and the
24
+ cytoskeleton's three fibres; eleven guided steps, messenger RNA leaving through the pores, a close-up of the
25
+ membrane. The lens bench measures the object's distance and the focal length.
26
+ - A label whose point the cut has taken points at its part's cut face instead; it hides only when the cut has taken
27
+ the whole part. (0.2.0 hid the label of any part whose label point was cut away, though the rest of it still showed:
28
+ the generator's south magnet when cut open, say.)
29
+
30
+ ## 0.2.0 (11 November 2026)
31
+
32
+ - **Guided steps** (`steps` in the scene): the figure explained in order, each step its words (`title`, `text`) and a
33
+ state of the figure: `view` or `focus`, `explode`, `cut` and `section`, `xray`, `labels`, `hide`, `select`, the
34
+ motions' values (`motion`) and which `play`. A panel under the figure shows the step's words, said aloud, with Back
35
+ and Next; a page goes through them with `fig.step(index or id)` (`currentStep`, `steps`), starts at one with
36
+ `opts.step`, hears the reader's moves with `opts.onStep`, or leaves the panel out (`steps: false`). What a step leaves
37
+ out goes back to the figure's start, so a step is the same picture however the reader came to it. The validator
38
+ checks what steps name; `lk3d render` draws each step (`--poses steps`). New words in every locale: `steps`, `back`,
39
+ `next`, `stepOf`.
40
+ - **Crease shading in a Web Worker**: the ambient occlusion is worked out off the page's main thread, in a worker made
41
+ of lk3d's own script (nothing more to ship), and finishes 2 to 4 times sooner (the molecules: 2.2 s to 0.6 at full
42
+ speed). Where no worker can be made it is shaded on the page as before; `fig.stats().aoWorker` says which.
43
+ - The size budget is 67 KB gzipped (65 before), for this release's additions.
44
+ - **Flow streaks are placed on the GPU** (WebGL 2): each flow's paths go to the GPU once, as a texture, and the vertex
45
+ shader places every streak from the time travelled, so a frame sends one number a flow instead of its streaks'
46
+ geometry. lk3d's own work for 8 000 moving streaks fell from 2.0 ms a frame to under 0.1 (13.7 to 0.1 with the CPU
47
+ slowed six times, as on a low-end phone). WebGL 1 and the 2D fallback place them on the CPU, as before.
48
+ - **`<lk3d-figure>`**: a figure as an HTML element, for a page that writes no script (Markdown, a content system): the
49
+ scene from `src` or a JSON script inside, options as attributes (`look`, `theme`, `labels`, `step` change it live;
50
+ `locale`, `controls`, `steps`, `info`, `transparent` mount it again), a line for the part's name and note under it,
51
+ and the reader's moves as events (`lk3d-pick`, `lk3d-handle`, `lk3d-step`, `lk3d-section`, `lk3d-error`);
52
+ `element.figure` and `element.ready` for a script.
53
+ - **The reader moves the cut**: with the model cut open, dragging the cut face moves the plane along its normal (up
54
+ and down where it is seen face on), held within the parts it cuts, and a slider beside **Cut open** does the same
55
+ by keys and screen readers. `section.fixed: true` keeps it where the scene puts it; `opts.onSection` hears the
56
+ reader's moves; `fig.section` reads where it is. Labels whose place the cut has passed are no longer shown. New
57
+ words: `cutAt`, `cutAtLabel`.
58
+ - A pressed button reads on a dark page: its words take `--lk3d-highlight-ink` (dark by default, for the light
59
+ highlight), not the page's ink, which a dark page sets light.
60
+ - Printed, a figure keeps its picture (and a step's words) without the buttons and the hint.
61
+ - The npm package leaves out the documentation's pictures (388 KB packed, from 1.1 MB); they are on GitHub.
62
+ - `fig.focus()` frames the parts whole: from far enough for the camera's field of view and the stage's shape, and as
63
+ they are taken apart (it stood too close for a tall or wide group, cutting it off).
64
+
6
65
  ## 0.1.0 (8 November 2026)
7
66
 
8
67
  The first release as its own package, after it grew as the 3D engine of lessonkit.
package/README.md CHANGED
@@ -10,7 +10,7 @@ The scene is plain data (JSON), so it can be written, reviewed and checked like
10
10
 
11
11
  ```html
12
12
  <div id="fig"></div>
13
- <script src="https://unpkg.com/lk3d@0.1.0/dist/lk3d.min.js"></script>
13
+ <script src="https://unpkg.com/lk3d@0.2.1/dist/lk3d.min.js"></script>
14
14
  <script>
15
15
  LK3D.mount(document.getElementById('fig'), {
16
16
  title: 'A bolt and a nut',
@@ -40,12 +40,16 @@ The scene is plain data (JSON), so it can be written, reviewed and checked like
40
40
  ## What it does
41
41
 
42
42
  - **Explore**: turn and zoom (mouse, touch, pen, keyboard) and pan (Shift-drag or right-drag); preset views; take the
43
- model apart (each part along its own path); cut it open, with the cut faces filled and hatched; see through casings;
43
+ model apart (each part along its own path); cut it open, with the cut faces filled and hatched (a half, or a quarter with two planes), and move the cut through it (drag its face); see through casings;
44
44
  labels with leader lines that do not overlap; a note for each part.
45
45
  - **Move parts by hand**: handles that turn (a focus ring, a rotor), slide (a piston, an object on a bench) or follow a
46
46
  path (a planet on its orbit), each also a range input for the keyboard and screen readers. Rays, field lines and
47
47
  forces as lines; streaks of air or blood flowing along paths, coloured cool to hot, as many and as fast as a page
48
48
  value says ([flow](docs/handles-and-lines.md#flow)); particles along paths; solid balls a simulation places.
49
+ - **Guided steps**: the figure explained in order, each step a few words and a state of the figure (where the camera
50
+ looks, taken apart, cut open, which labels, a part chosen, a motion playing), gone through with Back and Next under
51
+ the figure, said aloud as the reader comes to each, or driven by the page as its own text scrolls
52
+ ([steps](docs/api.md#guided-steps)).
49
53
  - **Mechanisms that move as they are joined**: a crank turns and its piston, rod and cam follow exactly, from joints
50
54
  rather than keys for each part ([joints](docs/handles-and-lines.md#joints-parts-posed-by-how-they-are-joined)).
51
55
  - **Out to glTF**: the figure as a .glb for Blender, a game engine or a viewer, posed as shown (`fig.exportGLB()`,
@@ -63,6 +67,8 @@ The scene is plain data (JSON), so it can be written, reviewed and checked like
63
67
  shadows, surface detail, glass that bends light) and a hand-drawn ink look, with an orthographic camera for a
64
68
  technical illustration; light, dark, blueprint and sepia themes, or the reader's own setting
65
69
  ([looks](docs/looks-and-materials.md)).
70
+ - **Dimensions**: lengths and angles drawn as on a technical drawing, their values worked out from the figure as shown,
71
+ so a length to a part changes as the reader moves it ([dimensions](docs/handles-and-lines.md#dimensions)).
66
72
  - **Honest scale**: a scale bar that keeps its true length as the view zooms, or a note saying what is not to scale.
67
73
  - **Accessible**: the figure has a text description and lists its parts for screen readers; the keyboard turns it,
68
74
  zooms and goes through its parts (each said aloud with its note); every control works by keyboard, handles are read out, motion
@@ -78,7 +84,7 @@ The scene is plain data (JSON), so it can be written, reviewed and checked like
78
84
 
79
85
  | | Minified | Gzipped |
80
86
  | --------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
81
- | lk3d | 148 KB | 59.3 KB |
87
+ | lk3d | 171 KB | 66.6 KB |
82
88
  | three.js r187, the smallest page | 522 KB | 131 KB |
83
89
  | three.js r187 with what lk3d does (PBR and glass, shadows, environment, controls, picking, glTF, labels, bloom, shape generators) | 708 KB | 181 KB |
84
90
 
@@ -96,10 +102,16 @@ lk3d explains objects. For games, character animation (skins, morph targets), VR
96
102
  scenes, use [three.js](https://threejs.org) or [Babylon.js](https://www.babylonjs.com); to show a single glTF model
97
103
  with hotspots and AR, use [model-viewer](https://modelviewer.dev).
98
104
 
105
+ ## Try it
106
+
107
+ The [playground](https://xoai.github.io/lk3d/playground/): write a scene as JSON and see it drawn as you type,
108
+ checked as `lk3d check` does (each problem shown where it is in the text), starting from an example; share it as a
109
+ link, or take it away as a .json or .glb file. From a checkout: `npm run playground`, then open `/playground/`.
110
+
99
111
  ## Use it
100
112
 
101
113
  A page loads one script, the global `LK3D`, as above: from a CDN with its version pinned
102
- (`https://unpkg.com/lk3d@0.1.0/dist/lk3d.min.js`, or `https://cdn.jsdelivr.net/npm/lk3d@0.1.0/dist/lk3d.min.js`), or a
114
+ (`https://unpkg.com/lk3d@0.2.1/dist/lk3d.min.js`, or `https://cdn.jsdelivr.net/npm/lk3d@0.2.1/dist/lk3d.min.js`), or a
103
115
  copy of `dist/lk3d.min.js` next to the page. A project with a bundler installs it and imports it:
104
116
 
105
117
  ```sh
@@ -113,6 +125,15 @@ const fig = LK3D.mount(el, scene, { info: document.querySelector('#info'), onHan
113
125
  fig.set({ explode: 1 });
114
126
  ```
115
127
 
128
+ A page that writes no script of its own (Markdown, a content system) uses the element `<lk3d-figure>`, which the
129
+ same script defines: the scene from `src`, or from a JSON script inside it, and the options as attributes; the reader's
130
+ moves come as events ([the element](docs/api.md#the-element-lk3d-figure)).
131
+
132
+ ```html
133
+ <script src="https://unpkg.com/lk3d@0.2.1/dist/lk3d.min.js"></script>
134
+ <lk3d-figure src="generator.json" look="pen" locale="vi"></lk3d-figure>
135
+ ```
136
+
116
137
  To build it yourself, or to work on it: `git clone https://github.com/xoai/lk3d.git`, then `npm install && npm run build`
117
138
  (`dist/lk3d.min.js`).
118
139
 
@@ -120,8 +141,8 @@ To build it yourself, or to work on it: `git clone https://github.com/xoai/lk3d.
120
141
  - [Scene format](docs/scene-format.md) · [Shapes](docs/shapes.md) · [Handles and lines](docs/handles-and-lines.md) ·
121
142
  [Looks and materials](docs/looks-and-materials.md) · [Models](docs/models.md) · [How it works](docs/design.md) ·
122
143
  [Performance](docs/performance.md).
123
- - [Examples](examples/): a generator, a lens bench, a cell, molecules, the Solar System, rock layers, a gauge, a fossil
124
- skull, the three looks, a circuit, air through a fan. `npm run examples` serves them.
144
+ - [Examples](examples/): a generator, a lens bench, a cell (and a guided tour of one), molecules, the Solar System, rock layers, a gauge, a fossil
145
+ skull, the three looks, a circuit, air through a fan, and a figure on a page that writes no script. `npm run examples` serves them.
125
146
  - Reading a figure: drag to turn it, Shift-drag or right-drag to pan, pinch to zoom; the wheel zooms only with Ctrl
126
147
  held or once the figure has been clicked, and a finger moved up or down scrolls the page until the figure has been
127
148
  touched, so it never takes over the page's scrolling. On the keyboard, the arrow keys turn it, `+` and `-` zoom,
@@ -139,7 +160,7 @@ To build it yourself, or to work on it: `git clone https://github.com/xoai/lk3d.
139
160
  npm install
140
161
  npm test # geometry, models, handles, the validator, the geometry check, the skill, the locales
141
162
  npm run typecheck # the TypeScript types
142
- npm run size # fails if the bundle is over its budget (65 KB gzipped, BUDGET_KB in build.mjs)
163
+ npm run size # fails if the bundle is over its budget (67 KB gzipped, BUDGET_KB in build.mjs)
143
164
  npm run test:visual # reference scenes compared with stored pictures (Chromium and Firefox on macOS; all three on Linux, in CI)
144
165
  npm run lint # ESLint and Prettier
145
166
  npm run docs # the scene-format reference and the shape pictures, made again
package/bin/lk3d.mjs CHANGED
@@ -3,10 +3,10 @@
3
3
  // a scene, runs after each step).
4
4
  // lk3d check scene.json [--json]
5
5
  // the format (lk3d/validate) and the geometry (lk3d/lint), with the scene's size: exit code 1 on any problem
6
- // lk3d render scene.json [--looks pen,ink,studio] [--poses rest,apart,cut] [--theme NAME] [--ortho] [--width 640]
7
- // [--out DIR]
8
- // PNG pictures, one per look and pose, drawn by the real engine in a headless browser (Playwright); without
9
- // Playwright it says so: the scene is then not checked by eye
6
+ // lk3d render scene.json [--looks pen,ink,studio] [--poses rest,apart,cut,steps] [--theme NAME] [--ortho]
7
+ // [--width 640] [--out DIR]
8
+ // PNG pictures, one per look and pose (steps: one per guided step, when the scene has them), drawn by the real
9
+ // engine in a headless browser (Playwright); without Playwright it says so: the scene is then not checked by eye
10
10
  // lk3d export scene.json [out.glb] [--animate] [--motion id=value,…]
11
11
  // the scene as glTF 2.0 binary (Blender, game engines, viewers): parts as named nodes with their materials, posed
12
12
  // at the motions' starts (or --motion), each motion an animation with --animate
@@ -39,10 +39,10 @@ const fail = (message, code = 2) => {
39
39
  process.exitCode = code;
40
40
  };
41
41
  const LOOKS = ['pen', 'studio', 'ink'],
42
- POSES = ['rest', 'apart', 'cut'];
42
+ POSES = ['rest', 'apart', 'cut', 'steps'];
43
43
  const USAGE = `usage: lk3d check scene.json [--json]
44
44
  lk3d export scene.json [out.glb] [--animate] [--motion id=value,…]
45
- lk3d render scene.json [--looks pen,ink,studio] [--poses rest,apart,cut] [--theme NAME] [--ortho] [--width 640] [--out DIR]`;
45
+ lk3d render scene.json [--looks pen,ink,studio] [--poses rest,apart,cut,steps] [--theme NAME] [--ortho] [--width 640] [--out DIR]`;
46
46
 
47
47
  function load(scenePath) {
48
48
  const scene = JSON.parse(fs.readFileSync(scenePath, 'utf8'));
@@ -116,11 +116,14 @@ const PAGE = `<!doctype html><meta charset="utf-8"><title>lk3d render</title>
116
116
  const query = new URLSearchParams(location.search), scene = await (await fetch('/scene.json')).json(), errors = [];
117
117
  window.addEventListener('error', (e) => errors.push(String(e.message)));
118
118
  if (query.get('ortho')) scene.view = { ...scene.view, projection: 'ortho' };
119
+ const pose = query.get('pose');
119
120
  const fig = LK3D.mount(document.getElementById('g'), scene, { controls: false, adaptive: false, locale: 'en',
120
- style: query.get('look'), theme: query.get('theme') || undefined, labels: query.get('pose') === 'apart' ? 'auto' : 'none' });
121
+ style: query.get('look'), theme: query.get('theme') || undefined,
122
+ labels: pose === 'apart' ? 'auto' : pose === 'step' ? undefined : 'none',
123
+ step: pose === 'step' ? Number(query.get('step')) : -1 }); // (at rest, apart and cut: before the first step)
121
124
  await Promise.race([fig.ready, new Promise((resolve) => setTimeout(resolve, 30000))]);
122
- if (query.get('pose') === 'apart') fig.set({ explode: 1 });
123
- if (query.get('pose') === 'cut') fig.set({ cut: true });
125
+ if (pose === 'apart') fig.set({ explode: 1 });
126
+ if (pose === 'cut') fig.set({ cut: true });
124
127
  for (let k = 0; k < 3; k++) await new Promise((resolve) => requestAnimationFrame(resolve));
125
128
  window.__ready = { errors, renderer: fig.renderer };
126
129
  </script>`;
@@ -168,12 +171,14 @@ async function render(scenePath) {
168
171
  }
169
172
  const width = Number(flag('width', 640)),
170
173
  looks = String(flag('looks', 'pen,ink')).split(','),
171
- poses = String(flag('poses', 'rest,apart,cut')).split(','),
174
+ stepCount = Array.isArray(data.steps) ? data.steps.length : 0,
175
+ poses = String(flag('poses', stepCount ? 'rest,apart,cut,steps' : 'rest,apart,cut')).split(','),
172
176
  unknown = [...looks.filter((look) => !LOOKS.includes(look)), ...poses.filter((pose) => !POSES.includes(pose))];
173
177
  if (!(width >= 64 && width <= 4096))
174
178
  return fail(`--width is a number of pixels from 64 to 4096, not ${flag('width')}`);
175
179
  if (unknown.length)
176
180
  return fail(`no look or pose ${unknown.join(', ')} (looks: ${LOOKS.join(', ')}; poses: ${POSES.join(', ')})`);
181
+ if (poses.includes('steps') && !stepCount) return fail('--poses steps: the scene has no steps');
177
182
  const scene = JSON.stringify(data),
178
183
  engine = await engineScript(),
179
184
  page = PAGE.replace('WIDTH', String(width));
@@ -213,10 +218,16 @@ async function render(scenePath) {
213
218
  try {
214
219
  const tab = await browser.newPage({ deviceScaleFactor: 2 });
215
220
  for (const look of looks)
216
- for (const pose of poses) {
217
- await tab.goto(`${base}?look=${look}&pose=${pose}${theme ? '&theme=' + theme : ''}${ortho ? '&ortho=1' : ''}`);
221
+ for (const [pose, query, picture] of poses.flatMap((pose) =>
222
+ pose === 'steps'
223
+ ? Array.from({ length: stepCount }, (_, index) => ['step', `&step=${index}`, `step${index + 1}`])
224
+ : [[pose, '', pose]],
225
+ )) {
226
+ await tab.goto(
227
+ `${base}?look=${look}&pose=${pose}${query}${theme ? '&theme=' + theme : ''}${ortho ? '&ortho=1' : ''}`,
228
+ );
218
229
  const result = await (await tab.waitForFunction(() => window.__ready, null, { timeout: 60000 })).jsonValue();
219
- const png = path.join(out, `${name}-${look}-${pose}.png`);
230
+ const png = path.join(out, `${name}-${look}-${picture}.png`);
220
231
  await tab.locator('.lk3d-stage').screenshot({ path: png });
221
232
  console.log(png + (result.errors.length ? ' errors: ' + result.errors.join('; ') : ''));
222
233
  errorCount += result.errors.length;
@@ -1,2 +1,2 @@
1
- /*! lk3d 0.1.0 | MIT License | Copyright (c) 2026 xoai */
1
+ /*! lk3d 0.2.1 | MIT License | Copyright (c) 2026 xoai */
2
2
  "use strict";(()=>{var _={mm:.001,cm:.01,dm:.1,m:1,km:1e3},q=i=>i<=.04045?i/12.92:((i+.055)/1.055)**2.4;function B(i){let s=n=>Math.hypot(i[4*n],i[4*n+1],i[4*n+2]);if([0,1,2].some(n=>Math.abs(s(n)-1)>1e-4))return null;let[g,y,p,,x,d,h,,A,m,L]=i,b=g+d+L,M;if(b>0){let n=Math.sqrt(b+1)*2;M=[(h-m)/n,(A-p)/n,(y-x)/n,n/4]}else if(g>d&&g>L){let n=Math.sqrt(1+g-d-L)*2;M=[n/4,(y+x)/n,(A+p)/n,(h-m)/n]}else if(d>L){let n=Math.sqrt(1+d-g-L)*2;M=[(y+x)/n,n/4,(h+m)/n,(A-p)/n]}else{let n=Math.sqrt(1+L-g-d)*2;M=[(A+p)/n,(h+m)/n,n/4,(y-x)/n]}let F=Math.hypot(...M);return{translation:[i[12],i[13],i[14]],rotation:M.map(n=>n/F)}}function N(i,s={}){let g=[],y=[],p=[],x=[],d=[],h=[],A=[],m=0,L=(t,e)=>{for(;m%4;)g.push(new Uint8Array(1)),m++;let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return g.push(o),y.push({buffer:0,byteOffset:m,byteLength:o.byteLength,...e&&{target:e}}),m+=o.byteLength,y.length-1},b=(t,e,o={})=>{let l={SCALAR:1,VEC3:3,VEC4:4}[e],a=t instanceof Float32Array?5126:t instanceof Uint32Array?5125:5123;return p.push({bufferView:L(t,o.target),componentType:a,count:t.length/l,type:e,...o.minMax}),p.length-1},M=(t,e)=>{let o=Array(e).fill(1/0),l=Array(e).fill(-1/0);for(let a=0;a<t.length;a++)o[a%e]=Math.min(o[a%e],t[a]),l[a%e]=Math.max(l[a%e],t[a]);return{min:o,max:l}},F=(t,e)=>{let o=B(e);o?(o.translation.some(l=>Math.abs(l)>1e-7)&&(t.translation=o.translation),Math.abs(o.rotation[3])<1-1e-7&&(t.rotation=o.rotation)):t.matrix=Array.from(e)},n=new Map;for(let t of i.parts){if(t.hidden||!t.batches.length)continue;let e=s.flatten(t);if(!e.count)continue;let o=new Float32Array(e.positions),l=new Float32Array(e.normals),a=e.count>65535?new Uint32Array(e.indices):new Uint16Array(e.indices),k=t.studioColor.map(q),V={POSITION:b(o,"VEC3",{target:34962,minMax:M(o,3)}),NORMAL:b(l,"VEC3",{target:34962})};if(e.colors){let O=new Float32Array(e.count*4);for(let r=0;r<e.count;r++){let u=e.colors[4*r+3]/255;for(let f=0;f<3;f++)O[4*r+f]=k[f]+(q(e.colors[4*r+f]/255)-k[f])*u;O[4*r+3]=1}V.COLOR_0=b(O,"VEC4",{target:34962})}d.push({name:t.name||t.id,pbrMetallicRoughness:{baseColorFactor:[...e.colors?[1,1,1]:k,t.alpha],metallicFactor:t.metalRoughness[0],roughnessFactor:t.metalRoughness[1]},...t.alpha<1&&{alphaMode:"BLEND"},doubleSided:!0}),x.push({name:t.name||t.id,primitives:[{attributes:V,indices:b(a,"SCALAR",{target:34963}),material:d.length-1}]});let c={name:t.name||t.id,mesh:x.length-1,extras:{lk3d:{id:t.id,...t.note&&{note:t.note}}}};s.matrix&&F(c,s.matrix(t)),h.push(c),n.set(t,h.length-1)}for(let t of s.animations||[]){let e=new Float32Array(t.times),o=[],l=[],a=null;for(let[k,V]of n){let c=t.times.map((r,u)=>B(t.matrix(k,u)));if(c.some(r=>!r))continue;let O=r=>c.some(u=>u[r].some((f,R)=>Math.abs(f-c[0][r][R])>1e-6));for(let r=1;r<c.length;r++)c[r].rotation.reduce((u,f,R)=>u+f*c[r-1].rotation[R],0)<0&&(c[r].rotation=c[r].rotation.map(u=>-u));for(let[r,u]of[["translation","VEC3"],["rotation","VEC4"]])O(r)&&(a==null&&(a=b(e,"SCALAR",{minMax:{min:[e[0]],max:[e[e.length-1]]}})),l.push({input:a,output:b(new Float32Array(c.flatMap(f=>f[r])),u),interpolation:"LINEAR"}),o.push({sampler:l.length-1,target:{node:V,path:r}}))}o.length&&A.push({name:t.name,channels:o,samplers:l})}let j=_[s.unit]??1;h.push({name:s.title||"lk3d",children:h.map((t,e)=>e),...j!==1&&{scale:[j,j,j]}});let I={asset:{version:"2.0",generator:"lk3d",...(s.author||s.license)&&{copyright:[s.author&&"\xA9 "+s.author,s.license].filter(Boolean).join(", ")}},scene:0,scenes:[{name:s.title||"lk3d",nodes:[h.length-1]}],nodes:h,meshes:x,materials:d,accessors:p,bufferViews:y,buffers:[{byteLength:m+(4-m%4)%4}],...A.length&&{animations:A}},E=new TextEncoder().encode(JSON.stringify(I)),C=E.length+(4-E.length%4)%4,S=I.buffers[0].byteLength,U=new Uint8Array(20+C+8+S),w=new DataView(U.buffer);w.setUint32(0,1179937895,!0),w.setUint32(4,2,!0),w.setUint32(8,U.length,!0),w.setUint32(12,C,!0),w.setUint32(16,1313821514,!0),U.set(E,20),U.fill(32,20+E.length,20+C),w.setUint32(20+C,S,!0),w.setUint32(24+C,5130562,!0);let T=28+C;for(let t of g)U.set(t,T),T+=t.length;return U}if(!globalThis.LK3D)throw new Error("lk3d-export: load dist/lk3d.min.js first");globalThis.LK3D.toGLB=N;})();