@es3d/es3d 1.0.0 → 1.0.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 (79) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +86 -86
  3. package/docs/SPEC.md +417 -417
  4. package/package.json +1 -1
  5. package/scripts/es3d-cli.mjs +377 -377
  6. package/src/cache/geometry-store.js +392 -392
  7. package/src/cache/mesh-bundle.js +123 -123
  8. package/src/cache/sha256.js +73 -73
  9. package/src/format/ast.js +238 -238
  10. package/src/format/colors.js +93 -93
  11. package/src/format/compact-parser.js +171 -171
  12. package/src/format/compact-tokenizer.js +165 -165
  13. package/src/format/errors.js +247 -247
  14. package/src/format/json.js +55 -55
  15. package/src/format/limits.js +14 -14
  16. package/src/format/parse.js +92 -92
  17. package/src/format/schema.js +617 -617
  18. package/src/format/serializer.js +333 -333
  19. package/src/format/validator.js +330 -330
  20. package/src/format/value-error.js +12 -12
  21. package/src/format/value-format.js +314 -314
  22. package/src/format/values.js +459 -459
  23. package/src/format/xml-parser.js +136 -136
  24. package/src/format/xml-tokenizer.js +237 -237
  25. package/src/geometry/contour.js +86 -86
  26. package/src/geometry/extrude.js +175 -175
  27. package/src/geometry/gear.js +85 -85
  28. package/src/geometry/geometry-cache.js +159 -159
  29. package/src/geometry/lod-error.js +178 -178
  30. package/src/geometry/mesh.js +458 -458
  31. package/src/geometry/primitives.js +299 -299
  32. package/src/geometry/registry.js +645 -645
  33. package/src/geometry/revolve.js +136 -136
  34. package/src/geometry/sweep.js +441 -441
  35. package/src/index.js +47 -47
  36. package/src/io/compression.js +67 -67
  37. package/src/io/convert.js +236 -236
  38. package/src/io/download.js +13 -13
  39. package/src/io/external-scene.js +127 -127
  40. package/src/io/file-loader.js +28 -28
  41. package/src/io/gltf.js +630 -630
  42. package/src/io/mesh-import.js +104 -104
  43. package/src/io/obj.js +352 -352
  44. package/src/io/step-brep.js +439 -439
  45. package/src/io/step-exact.js +1149 -1149
  46. package/src/io/step.js +1418 -1418
  47. package/src/io/stl.js +193 -193
  48. package/src/io/svg-import.js +787 -787
  49. package/src/material/materials.js +154 -154
  50. package/src/math/mat4.js +475 -475
  51. package/src/math/random.js +30 -30
  52. package/src/math/trig.js +65 -65
  53. package/src/math/vec3.js +81 -81
  54. package/src/optimize/optimizer.js +579 -579
  55. package/src/path/path-flatten.js +322 -322
  56. package/src/path/path-parser.js +332 -332
  57. package/src/path/shapes.js +129 -129
  58. package/src/path/triangulate.js +517 -517
  59. package/src/pipeline.js +74 -74
  60. package/src/render/camera.js +168 -168
  61. package/src/render/frame-builder.js +362 -362
  62. package/src/render/geometry-pool.js +149 -149
  63. package/src/render/lighting.js +149 -149
  64. package/src/render/orbit-controls.js +237 -237
  65. package/src/render/renderer.js +258 -249
  66. package/src/render/scroll-timeline.js +104 -104
  67. package/src/render/shaders/glsl.js +285 -285
  68. package/src/render/shaders/wgsl.js +252 -252
  69. package/src/render/stage.js +364 -352
  70. package/src/render/texture-cache.js +40 -40
  71. package/src/render/textures.js +223 -223
  72. package/src/render/webgl2/webgl2-backend.js +586 -532
  73. package/src/render/webgpu/webgpu-backend.js +482 -480
  74. package/src/scene/flatten.js +754 -754
  75. package/src/scene/picking.js +161 -161
  76. package/src/scene/scene-graph.js +320 -320
  77. package/src/transform/transform.js +211 -211
  78. package/src/wasm/kernels-binary.js +3 -3
  79. package/src/wasm/kernels.js +385 -385
package/src/io/convert.js CHANGED
@@ -1,236 +1,236 @@
1
- // File conversion to and from ES3D, shared by the website's converter and
2
- // the command-line tool. Works in browsers and in Node.
3
- //
4
- // const r = await importFiles([{ name: 'logo.svg', bytes }]); // → ES3D markup in r.text
5
- // const out = exportFormat(r.text, 'glb', { baseName: 'logo' }); // → { files: [{ name, data, mime }] }
6
-
7
- import { isGzip, gunzip } from './compression.js';
8
- import { parse } from '../format/parse.js';
9
- import { serialize } from '../format/serializer.js';
10
- import { isGLB, glbToScene, gltfToScene, exportGLB } from './gltf.js';
11
- import { objToScene, exportOBJ } from './obj.js';
12
- import { isBinarySTL, isAsciiSTL, stlToScene, exportSTL } from './stl.js';
13
- import { isSTEP, stepToScene, exportSTEP } from './step.js';
14
- import { stepToExact } from './step-exact.js';
15
- import { svgToES3D } from './svg-import.js';
16
- import { sceneToMeshDocument } from './mesh-import.js';
17
- import { compile } from '../pipeline.js';
18
- import { exportableInstances } from './external-scene.js';
19
-
20
- /** OBJ and STL repeat every copy's triangles; beyond this the file gets too large for a browser tab. */
21
- const OBJ_TRIANGLE_LIMIT = 4e6;
22
-
23
- export const INPUT_KINDS = {
24
- es3d: 'ES3D text',
25
- svg: 'SVG drawing',
26
- obj: 'Wavefront OBJ',
27
- stl: 'STL',
28
- gltf: 'glTF (JSON)',
29
- glb: 'glTF binary (GLB)',
30
- step: 'STEP',
31
- };
32
-
33
- export const OUTPUT_FORMATS = {
34
- es3d: { label: 'ES3D markup (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
35
- 'es3d-min': { label: 'ES3D markup, minified (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
36
- 'es3d-compact': { label: 'ES3D compact syntax (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
37
- glb: { label: 'glTF binary (.glb)', ext: '.glb', mime: 'model/gltf-binary' },
38
- obj: { label: 'Wavefront OBJ + MTL (.obj)', ext: '.obj', mime: 'model/obj', text: true },
39
- stl: { label: 'STL for 3D printing (.stl)', ext: '.stl', mime: 'model/stl' },
40
- step: { label: 'STEP, tessellated (.step)', ext: '.step', mime: 'model/step', text: true },
41
- };
42
-
43
- /** Files that only accompany a main file (OBJ materials, glTF buffers and textures). */
44
- const COMPANION = /\.(mtl|bin|png|jpe?g|webp|gif|ktx2|dds|tga|bmp)$/i;
45
-
46
- const decode = (bytes) => new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
47
-
48
- /**
49
- * The kind of a file, from its content first and its extension second.
50
- * @returns {keyof INPUT_KINDS | null}
51
- */
52
- export function detectKind(name, bytes) {
53
- if (isGLB(bytes)) return 'glb';
54
- const ext = ((/\.([a-z0-9]+)$/i.exec(name) || [])[1] || '').toLowerCase();
55
- const head = decode(bytes.subarray(0, 4096));
56
- if (isSTEP(head)) return 'step';
57
- if (isBinarySTL(bytes) && !['es3d', 'svg', 'obj', 'gltf'].includes(ext)) return 'stl';
58
- const es3dText = /^\s*(<\?xml[^>]*\?>\s*)?(<!--[\s\S]*?-->\s*)*<es3d[\s>/]/.test(head) || /^\s*((\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*es3d\b/.test(head);
59
- if (ext === 'es3d' || es3dText) return 'es3d';
60
- if (ext === 'svg' || /<svg[\s>/]/.test(head)) return 'svg';
61
- if (ext === 'stl' || isAsciiSTL(bytes)) return 'stl';
62
- if (ext === 'gltf' || /^\s*\{[\s\S]*"asset"\s*:/.test(head)) return 'gltf';
63
- if (ext === 'obj' || /^\s*(#[^\n]*\n\s*)*(mtllib|o|g|v|vt|vn|f|usemtl|s)\s/.test(head)) return 'obj';
64
- if (ext === 'step' || ext === 'stp' || ext === 'p21') return 'step';
65
- return null;
66
- }
67
-
68
- /** Options of the importers, with their defaults. */
69
- export const IMPORT_DEFAULTS = {
70
- svg: { size: 10, depth: 0.04, bevel: 0, strokes: true, base: false },
71
- mesh: { precision: 'auto', normals: 'auto', uvs: true, smooth: 30 },
72
- stl: { up: 'z' },
73
- };
74
-
75
- /**
76
- * Convert input files into an ES3D document.
77
- * @param {{name: string, bytes: Uint8Array}[]} files the main file plus companions (.mtl, .bin)
78
- * @param {{svg?: object, mesh?: object, stl?: object}} [opts] see IMPORT_DEFAULTS
79
- * @returns {Promise<{kind: string, name: string, title: string, text: string, warnings: string[], notes: string[]}>}
80
- */
81
- export async function importFiles(files, opts = {}) {
82
- if (!files.length) throw new Error('No file was given.');
83
- const list = [];
84
- for (const f of files) {
85
- let bytes = f.bytes instanceof Uint8Array ? f.bytes : new Uint8Array(f.bytes);
86
- let name = f.name || 'untitled';
87
- if (isGzip(bytes)) {
88
- bytes = await gunzip(bytes);
89
- name = name.replace(/\.svgz$/i, '.svg').replace(/\.gz$/i, '');
90
- }
91
- list.push({ name, bytes });
92
- }
93
- const main = list.find((f) => !COMPANION.test(f.name)) || list[0];
94
- const companions = list.filter((f) => f !== main);
95
- const kind = detectKind(main.name, main.bytes);
96
- if (!kind) throw new Error(`${main.name}: unknown file type. The converter reads SVG, OBJ, STL, STEP (.step, .stp) and glTF (.gltf, .glb) and ES3D (.es3d) files.`);
97
- const title = main.name.replace(/\.[^.]+$/, '') || 'untitled';
98
- const svgOpts = { ...IMPORT_DEFAULTS.svg, ...(opts.svg || {}) };
99
- const meshOpts = { ...IMPORT_DEFAULTS.mesh, ...(opts.mesh || {}) };
100
- const stlOpts = { ...IMPORT_DEFAULTS.stl, ...(opts.stl || {}) };
101
- const warnings = [];
102
- const notes = [];
103
- const meshDocument = (s, sourceHasNormals) => {
104
- const normals = meshOpts.normals === 'auto' ? sourceHasNormals : !!meshOpts.normals;
105
- const digits = meshOpts.precision === 'exact' ? null : meshOpts.precision;
106
- if (!normals) notes.push(`Normals are not stored; viewers compute them with a ${meshOpts.smooth}° crease angle.`);
107
- return sceneToMeshDocument(s.scene, s.meshOf, title, { digits, normals, uvs: meshOpts.uvs ? 'auto' : false, smooth: meshOpts.smooth });
108
- };
109
- let text;
110
- switch (kind) {
111
- case 'es3d':
112
- text = decode(main.bytes);
113
- break;
114
- case 'svg': {
115
- const r = svgToES3D(decode(main.bytes), { name: main.name, ...svgOpts });
116
- text = r.text;
117
- warnings.push(...r.warnings);
118
- notes.push(`${r.stats.fills} filled shape${r.stats.fills === 1 ? '' : 's'} extruded, ${r.stats.strokes} stroke${r.stats.strokes === 1 ? '' : 's'} turned into tubes, ${r.stats.materials} material${r.stats.materials === 1 ? '' : 's'}.`);
119
- break;
120
- }
121
- case 'obj': {
122
- const objText = decode(main.bytes);
123
- const lib = (/^mtllib\s+(.+?)\s*$/m.exec(objText) || [])[1];
124
- const mtlFile = companions.find((f) => /\.mtl$/i.test(f.name) && (!lib || f.name.toLowerCase() === lib.split(/[\\/]/).pop().toLowerCase())) || companions.find((f) => /\.mtl$/i.test(f.name));
125
- if (lib && !mtlFile) warnings.push(`The material library ${lib} was not given; default colors are used. Select the .obj and .mtl files together to keep the materials.`);
126
- if (companions.some((f) => /\.(png|jpe?g|webp|gif|tga|bmp)$/i.test(f.name)) || /^\s*map_/m.test(mtlFile ? decode(mtlFile.bytes) : '')) warnings.push('Textures are not converted; the materials keep their base colors.');
127
- const s = objToScene(objText, mtlFile ? decode(mtlFile.bytes) : '');
128
- const hasNormals = /^vn\s/m.test(objText);
129
- text = meshDocument(s, hasNormals);
130
- break;
131
- }
132
- case 'stl': {
133
- const s = stlToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
134
- if (s.info.degenerate) warnings.push(`${s.info.degenerate} degenerate triangle${s.info.degenerate === 1 ? '' : 's'} (with two identical corners) ${s.info.degenerate === 1 ? 'was' : 'were'} dropped.`);
135
- notes.push(`${s.info.format === 'binary' ? 'Binary' : 'ASCII'} STL with ${s.info.triangles.toLocaleString('en-US')} triangles, welded to ${s.info.vertices.toLocaleString('en-US')} vertices${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.`);
136
- text = meshDocument(s, false);
137
- break;
138
- }
139
- case 'step': {
140
- // a B-rep (what CAD tools export) becomes ES3D shapes; tessellated STEP stays a mesh
141
- const exact = stepToExact(main.bytes, { up: stlOpts.up, name: title });
142
- if (exact) {
143
- notes.push(exact.note);
144
- text = exact.text;
145
- break;
146
- }
147
- const s = stepToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
148
- if (s.info.curved) warnings.push(`${s.info.curved} curved face${s.info.curved === 1 ? '' : 's'} skipped. ES3D tessellates planar faces, circles and cylinders; re-export other curved solids as tessellated STEP or STL to keep them.`);
149
- const unit = s.info.unit ? ` Coordinates are in ${s.info.unit} and were not rescaled.` : ' The file does not name a length unit; coordinates were used as written.';
150
- notes.push(`STEP with ${s.info.triangles.toLocaleString('en-US')} triangles in ${s.info.meshes} mesh${s.info.meshes === 1 ? '' : 'es'}${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.${unit}`);
151
- text = meshDocument(s, false);
152
- break;
153
- }
154
- case 'gltf':
155
- case 'glb': {
156
- const resources = Object.fromEntries(companions.map((f) => [f.name, f.bytes]));
157
- const s = kind === 'glb' ? glbToScene(main.bytes) : gltfToScene(decode(main.bytes), resources);
158
- if (s.skipped.textures) warnings.push(`Textures are not converted (${s.skipped.textures} textured material${s.skipped.textures === 1 ? '' : 's'}); the materials keep their base colors.`);
159
- if (s.skipped.points) warnings.push(`${s.skipped.points} point cloud primitive${s.skipped.points === 1 ? ' was' : 's were'} skipped.`);
160
- const lines = s.scene.geometries.filter((g) => g.kind === 'lines').length;
161
- if (lines) warnings.push(`${lines} line primitive${lines === 1 ? ' was' : 's were'} skipped (ES3D meshes hold triangles).`);
162
- if ((s.json.skins || []).length || (s.json.animations || []).length) warnings.push('Skins and animations are not converted; the model is shown in its rest pose.');
163
- if (s.json.extensionsRequired && s.json.extensionsRequired.length) warnings.push(`The file requires extensions that are not supported: ${s.json.extensionsRequired.join(', ')}.`);
164
- const hasNormals = (s.json.meshes || []).some((m) => m.primitives.some((p) => p.attributes && p.attributes.NORMAL !== undefined));
165
- text = meshDocument(s, hasNormals);
166
- break;
167
- }
168
- }
169
- return { kind, name: main.name, title, text, warnings, notes };
170
- }
171
-
172
- /** Parse and validate ES3D text; throws with the first diagnostics on errors. */
173
- function validDocument(source) {
174
- const doc = parse(source);
175
- if (!doc.ok) throw new Error(describeErrors(doc.diagnostics, doc.lineIndex));
176
- return doc;
177
- }
178
-
179
- function describeErrors(diagnostics, lineIndex) {
180
- const errors = diagnostics.filter((d) => d.severity === 'error');
181
- const shown = errors.slice(0, 3).map((d) => d.format(lineIndex)).join('\n\n');
182
- return `The ES3D document has ${errors.length} error${errors.length === 1 ? '' : 's'}:\n\n${shown}${errors.length > 3 ? `\n\n… and ${errors.length - 3} more` : ''}`;
183
- }
184
-
185
- /**
186
- * Write an ES3D document in another format.
187
- * @param {string|Uint8Array} source ES3D text
188
- * @param {keyof OUTPUT_FORMATS} format
189
- * @param {{baseName?: string, lod?: number, compiled?: object, instancing?: boolean}} [opts]
190
- * compiled: an existing compile() result for the same source (saves compiling twice)
191
- * @returns {{files: {name: string, data: Uint8Array|string, mime: string}[], triangles?: number}}
192
- */
193
- export function exportFormat(source, format, { baseName = 'scene', lod = 0, compiled = null, instancing = true } = {}) {
194
- const spec = OUTPUT_FORMATS[format];
195
- if (!spec) throw new Error(`Unknown output format ${format}.`);
196
- const name = baseName + spec.ext;
197
- const one = (data) => ({ files: [{ name, data, mime: spec.mime }] });
198
- switch (format) {
199
- case 'es3d':
200
- return one(serialize(validDocument(source), { syntax: 'xml', pretty: true, comments: true }));
201
- case 'es3d-min':
202
- return one(serialize(validDocument(source), { syntax: 'xml', pretty: false }));
203
- case 'es3d-compact':
204
- return one(serialize(validDocument(source), { syntax: 'compact', pretty: true, comments: true }));
205
- default: {
206
- const r = compiled || compile(source);
207
- if (!r.ok) throw new Error(describeErrors(r.diagnostics, r.doc && r.doc.lineIndex));
208
- const meshOf = (e, l) => r.cache.mesh(e, Math.min(l, e.lods - 1));
209
- if (format === 'glb') return one(exportGLB(r.scene, meshOf, { lod, instancing }));
210
- if (format === 'obj') {
211
- let triangles = 0;
212
- for (const i of exportableInstances(r.scene)) {
213
- const m = meshOf(r.scene.geometries[r.scene.geom[i]], lod);
214
- if (m.kind === 'triangles') triangles += m.primitiveCount;
215
- }
216
- if (triangles > OBJ_TRIANGLE_LIMIT) throw new Error(`At this level of detail the scene has ${triangles.toLocaleString('en-US')} triangles, too many for an OBJ file (limit ${OBJ_TRIANGLE_LIMIT.toLocaleString('en-US')}). Choose a coarser detail, or glTF, which stores repeated shapes once.`);
217
- }
218
- if (format === 'stl') {
219
- const s = exportSTL(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
220
- return { ...one(s.data), triangles: s.triangles };
221
- }
222
- if (format === 'step') {
223
- const s = exportSTEP(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
224
- return { ...one(s.data), triangles: s.triangles };
225
- }
226
- const o = exportOBJ(r.scene, meshOf, { lod, name: baseName });
227
- return {
228
- files: [
229
- { name, data: o.obj, mime: spec.mime },
230
- { name: `${baseName}.mtl`, data: o.mtl, mime: 'text/plain' },
231
- ],
232
- triangles: o.triangles,
233
- };
234
- }
235
- }
236
- }
1
+ // File conversion to and from ES3D, shared by the website's converter and
2
+ // the command-line tool. Works in browsers and in Node.
3
+ //
4
+ // const r = await importFiles([{ name: 'logo.svg', bytes }]); // → ES3D markup in r.text
5
+ // const out = exportFormat(r.text, 'glb', { baseName: 'logo' }); // → { files: [{ name, data, mime }] }
6
+
7
+ import { isGzip, gunzip } from './compression.js';
8
+ import { parse } from '../format/parse.js';
9
+ import { serialize } from '../format/serializer.js';
10
+ import { isGLB, glbToScene, gltfToScene, exportGLB } from './gltf.js';
11
+ import { objToScene, exportOBJ } from './obj.js';
12
+ import { isBinarySTL, isAsciiSTL, stlToScene, exportSTL } from './stl.js';
13
+ import { isSTEP, stepToScene, exportSTEP } from './step.js';
14
+ import { stepToExact } from './step-exact.js';
15
+ import { svgToES3D } from './svg-import.js';
16
+ import { sceneToMeshDocument } from './mesh-import.js';
17
+ import { compile } from '../pipeline.js';
18
+ import { exportableInstances } from './external-scene.js';
19
+
20
+ /** OBJ and STL repeat every copy's triangles; beyond this the file gets too large for a browser tab. */
21
+ const OBJ_TRIANGLE_LIMIT = 4e6;
22
+
23
+ export const INPUT_KINDS = {
24
+ es3d: 'ES3D text',
25
+ svg: 'SVG drawing',
26
+ obj: 'Wavefront OBJ',
27
+ stl: 'STL',
28
+ gltf: 'glTF (JSON)',
29
+ glb: 'glTF binary (GLB)',
30
+ step: 'STEP',
31
+ };
32
+
33
+ export const OUTPUT_FORMATS = {
34
+ es3d: { label: 'ES3D markup (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
35
+ 'es3d-min': { label: 'ES3D markup, minified (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
36
+ 'es3d-compact': { label: 'ES3D compact syntax (.es3d)', ext: '.es3d', mime: 'model/vnd.es3d', text: true },
37
+ glb: { label: 'glTF binary (.glb)', ext: '.glb', mime: 'model/gltf-binary' },
38
+ obj: { label: 'Wavefront OBJ + MTL (.obj)', ext: '.obj', mime: 'model/obj', text: true },
39
+ stl: { label: 'STL for 3D printing (.stl)', ext: '.stl', mime: 'model/stl' },
40
+ step: { label: 'STEP, tessellated (.step)', ext: '.step', mime: 'model/step', text: true },
41
+ };
42
+
43
+ /** Files that only accompany a main file (OBJ materials, glTF buffers and textures). */
44
+ const COMPANION = /\.(mtl|bin|png|jpe?g|webp|gif|ktx2|dds|tga|bmp)$/i;
45
+
46
+ const decode = (bytes) => new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
47
+
48
+ /**
49
+ * The kind of a file, from its content first and its extension second.
50
+ * @returns {keyof INPUT_KINDS | null}
51
+ */
52
+ export function detectKind(name, bytes) {
53
+ if (isGLB(bytes)) return 'glb';
54
+ const ext = ((/\.([a-z0-9]+)$/i.exec(name) || [])[1] || '').toLowerCase();
55
+ const head = decode(bytes.subarray(0, 4096));
56
+ if (isSTEP(head)) return 'step';
57
+ if (isBinarySTL(bytes) && !['es3d', 'svg', 'obj', 'gltf'].includes(ext)) return 'stl';
58
+ const es3dText = /^\s*(<\?xml[^>]*\?>\s*)?(<!--[\s\S]*?-->\s*)*<es3d[\s>/]/.test(head) || /^\s*((\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*es3d\b/.test(head);
59
+ if (ext === 'es3d' || es3dText) return 'es3d';
60
+ if (ext === 'svg' || /<svg[\s>/]/.test(head)) return 'svg';
61
+ if (ext === 'stl' || isAsciiSTL(bytes)) return 'stl';
62
+ if (ext === 'gltf' || /^\s*\{[\s\S]*"asset"\s*:/.test(head)) return 'gltf';
63
+ if (ext === 'obj' || /^\s*(#[^\n]*\n\s*)*(mtllib|o|g|v|vt|vn|f|usemtl|s)\s/.test(head)) return 'obj';
64
+ if (ext === 'step' || ext === 'stp' || ext === 'p21') return 'step';
65
+ return null;
66
+ }
67
+
68
+ /** Options of the importers, with their defaults. */
69
+ export const IMPORT_DEFAULTS = {
70
+ svg: { size: 10, depth: 0.04, bevel: 0, strokes: true, base: false },
71
+ mesh: { precision: 'auto', normals: 'auto', uvs: true, smooth: 30 },
72
+ stl: { up: 'z' },
73
+ };
74
+
75
+ /**
76
+ * Convert input files into an ES3D document.
77
+ * @param {{name: string, bytes: Uint8Array}[]} files the main file plus companions (.mtl, .bin)
78
+ * @param {{svg?: object, mesh?: object, stl?: object}} [opts] see IMPORT_DEFAULTS
79
+ * @returns {Promise<{kind: string, name: string, title: string, text: string, warnings: string[], notes: string[]}>}
80
+ */
81
+ export async function importFiles(files, opts = {}) {
82
+ if (!files.length) throw new Error('No file was given.');
83
+ const list = [];
84
+ for (const f of files) {
85
+ let bytes = f.bytes instanceof Uint8Array ? f.bytes : new Uint8Array(f.bytes);
86
+ let name = f.name || 'untitled';
87
+ if (isGzip(bytes)) {
88
+ bytes = await gunzip(bytes);
89
+ name = name.replace(/\.svgz$/i, '.svg').replace(/\.gz$/i, '');
90
+ }
91
+ list.push({ name, bytes });
92
+ }
93
+ const main = list.find((f) => !COMPANION.test(f.name)) || list[0];
94
+ const companions = list.filter((f) => f !== main);
95
+ const kind = detectKind(main.name, main.bytes);
96
+ if (!kind) throw new Error(`${main.name}: unknown file type. The converter reads SVG, OBJ, STL, STEP (.step, .stp) and glTF (.gltf, .glb) and ES3D (.es3d) files.`);
97
+ const title = main.name.replace(/\.[^.]+$/, '') || 'untitled';
98
+ const svgOpts = { ...IMPORT_DEFAULTS.svg, ...(opts.svg || {}) };
99
+ const meshOpts = { ...IMPORT_DEFAULTS.mesh, ...(opts.mesh || {}) };
100
+ const stlOpts = { ...IMPORT_DEFAULTS.stl, ...(opts.stl || {}) };
101
+ const warnings = [];
102
+ const notes = [];
103
+ const meshDocument = (s, sourceHasNormals) => {
104
+ const normals = meshOpts.normals === 'auto' ? sourceHasNormals : !!meshOpts.normals;
105
+ const digits = meshOpts.precision === 'exact' ? null : meshOpts.precision;
106
+ if (!normals) notes.push(`Normals are not stored; viewers compute them with a ${meshOpts.smooth}° crease angle.`);
107
+ return sceneToMeshDocument(s.scene, s.meshOf, title, { digits, normals, uvs: meshOpts.uvs ? 'auto' : false, smooth: meshOpts.smooth });
108
+ };
109
+ let text;
110
+ switch (kind) {
111
+ case 'es3d':
112
+ text = decode(main.bytes);
113
+ break;
114
+ case 'svg': {
115
+ const r = svgToES3D(decode(main.bytes), { name: main.name, ...svgOpts });
116
+ text = r.text;
117
+ warnings.push(...r.warnings);
118
+ notes.push(`${r.stats.fills} filled shape${r.stats.fills === 1 ? '' : 's'} extruded, ${r.stats.strokes} stroke${r.stats.strokes === 1 ? '' : 's'} turned into tubes, ${r.stats.materials} material${r.stats.materials === 1 ? '' : 's'}.`);
119
+ break;
120
+ }
121
+ case 'obj': {
122
+ const objText = decode(main.bytes);
123
+ const lib = (/^mtllib\s+(.+?)\s*$/m.exec(objText) || [])[1];
124
+ const mtlFile = companions.find((f) => /\.mtl$/i.test(f.name) && (!lib || f.name.toLowerCase() === lib.split(/[\\/]/).pop().toLowerCase())) || companions.find((f) => /\.mtl$/i.test(f.name));
125
+ if (lib && !mtlFile) warnings.push(`The material library ${lib} was not given; default colors are used. Select the .obj and .mtl files together to keep the materials.`);
126
+ if (companions.some((f) => /\.(png|jpe?g|webp|gif|tga|bmp)$/i.test(f.name)) || /^\s*map_/m.test(mtlFile ? decode(mtlFile.bytes) : '')) warnings.push('Textures are not converted; the materials keep their base colors.');
127
+ const s = objToScene(objText, mtlFile ? decode(mtlFile.bytes) : '');
128
+ const hasNormals = /^vn\s/m.test(objText);
129
+ text = meshDocument(s, hasNormals);
130
+ break;
131
+ }
132
+ case 'stl': {
133
+ const s = stlToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
134
+ if (s.info.degenerate) warnings.push(`${s.info.degenerate} degenerate triangle${s.info.degenerate === 1 ? '' : 's'} (with two identical corners) ${s.info.degenerate === 1 ? 'was' : 'were'} dropped.`);
135
+ notes.push(`${s.info.format === 'binary' ? 'Binary' : 'ASCII'} STL with ${s.info.triangles.toLocaleString('en-US')} triangles, welded to ${s.info.vertices.toLocaleString('en-US')} vertices${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.`);
136
+ text = meshDocument(s, false);
137
+ break;
138
+ }
139
+ case 'step': {
140
+ // a B-rep (what CAD tools export) becomes ES3D shapes; tessellated STEP stays a mesh
141
+ const exact = stepToExact(main.bytes, { up: stlOpts.up, name: title });
142
+ if (exact) {
143
+ notes.push(exact.note);
144
+ text = exact.text;
145
+ break;
146
+ }
147
+ const s = stepToScene(main.bytes, { up: stlOpts.up, smooth: meshOpts.smooth });
148
+ if (s.info.curved) warnings.push(`${s.info.curved} curved face${s.info.curved === 1 ? '' : 's'} skipped. ES3D tessellates planar faces, circles and cylinders; re-export other curved solids as tessellated STEP or STL to keep them.`);
149
+ const unit = s.info.unit ? ` Coordinates are in ${s.info.unit} and were not rescaled.` : ' The file does not name a length unit; coordinates were used as written.';
150
+ notes.push(`STEP with ${s.info.triangles.toLocaleString('en-US')} triangles in ${s.info.meshes} mesh${s.info.meshes === 1 ? '' : 'es'}${stlOpts.up === 'z' ? '; turned from Z-up to Y-up' : ''}.${unit}`);
151
+ text = meshDocument(s, false);
152
+ break;
153
+ }
154
+ case 'gltf':
155
+ case 'glb': {
156
+ const resources = Object.fromEntries(companions.map((f) => [f.name, f.bytes]));
157
+ const s = kind === 'glb' ? glbToScene(main.bytes) : gltfToScene(decode(main.bytes), resources);
158
+ if (s.skipped.textures) warnings.push(`Textures are not converted (${s.skipped.textures} textured material${s.skipped.textures === 1 ? '' : 's'}); the materials keep their base colors.`);
159
+ if (s.skipped.points) warnings.push(`${s.skipped.points} point cloud primitive${s.skipped.points === 1 ? ' was' : 's were'} skipped.`);
160
+ const lines = s.scene.geometries.filter((g) => g.kind === 'lines').length;
161
+ if (lines) warnings.push(`${lines} line primitive${lines === 1 ? ' was' : 's were'} skipped (ES3D meshes hold triangles).`);
162
+ if ((s.json.skins || []).length || (s.json.animations || []).length) warnings.push('Skins and animations are not converted; the model is shown in its rest pose.');
163
+ if (s.json.extensionsRequired && s.json.extensionsRequired.length) warnings.push(`The file requires extensions that are not supported: ${s.json.extensionsRequired.join(', ')}.`);
164
+ const hasNormals = (s.json.meshes || []).some((m) => m.primitives.some((p) => p.attributes && p.attributes.NORMAL !== undefined));
165
+ text = meshDocument(s, hasNormals);
166
+ break;
167
+ }
168
+ }
169
+ return { kind, name: main.name, title, text, warnings, notes };
170
+ }
171
+
172
+ /** Parse and validate ES3D text; throws with the first diagnostics on errors. */
173
+ function validDocument(source) {
174
+ const doc = parse(source);
175
+ if (!doc.ok) throw new Error(describeErrors(doc.diagnostics, doc.lineIndex));
176
+ return doc;
177
+ }
178
+
179
+ function describeErrors(diagnostics, lineIndex) {
180
+ const errors = diagnostics.filter((d) => d.severity === 'error');
181
+ const shown = errors.slice(0, 3).map((d) => d.format(lineIndex)).join('\n\n');
182
+ return `The ES3D document has ${errors.length} error${errors.length === 1 ? '' : 's'}:\n\n${shown}${errors.length > 3 ? `\n\n… and ${errors.length - 3} more` : ''}`;
183
+ }
184
+
185
+ /**
186
+ * Write an ES3D document in another format.
187
+ * @param {string|Uint8Array} source ES3D text
188
+ * @param {keyof OUTPUT_FORMATS} format
189
+ * @param {{baseName?: string, lod?: number, compiled?: object, instancing?: boolean}} [opts]
190
+ * compiled: an existing compile() result for the same source (saves compiling twice)
191
+ * @returns {{files: {name: string, data: Uint8Array|string, mime: string}[], triangles?: number}}
192
+ */
193
+ export function exportFormat(source, format, { baseName = 'scene', lod = 0, compiled = null, instancing = true } = {}) {
194
+ const spec = OUTPUT_FORMATS[format];
195
+ if (!spec) throw new Error(`Unknown output format ${format}.`);
196
+ const name = baseName + spec.ext;
197
+ const one = (data) => ({ files: [{ name, data, mime: spec.mime }] });
198
+ switch (format) {
199
+ case 'es3d':
200
+ return one(serialize(validDocument(source), { syntax: 'xml', pretty: true, comments: true }));
201
+ case 'es3d-min':
202
+ return one(serialize(validDocument(source), { syntax: 'xml', pretty: false }));
203
+ case 'es3d-compact':
204
+ return one(serialize(validDocument(source), { syntax: 'compact', pretty: true, comments: true }));
205
+ default: {
206
+ const r = compiled || compile(source);
207
+ if (!r.ok) throw new Error(describeErrors(r.diagnostics, r.doc && r.doc.lineIndex));
208
+ const meshOf = (e, l) => r.cache.mesh(e, Math.min(l, e.lods - 1));
209
+ if (format === 'glb') return one(exportGLB(r.scene, meshOf, { lod, instancing }));
210
+ if (format === 'obj') {
211
+ let triangles = 0;
212
+ for (const i of exportableInstances(r.scene)) {
213
+ const m = meshOf(r.scene.geometries[r.scene.geom[i]], lod);
214
+ if (m.kind === 'triangles') triangles += m.primitiveCount;
215
+ }
216
+ if (triangles > OBJ_TRIANGLE_LIMIT) throw new Error(`At this level of detail the scene has ${triangles.toLocaleString('en-US')} triangles, too many for an OBJ file (limit ${OBJ_TRIANGLE_LIMIT.toLocaleString('en-US')}). Choose a coarser detail, or glTF, which stores repeated shapes once.`);
217
+ }
218
+ if (format === 'stl') {
219
+ const s = exportSTL(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
220
+ return { ...one(s.data), triangles: s.triangles };
221
+ }
222
+ if (format === 'step') {
223
+ const s = exportSTEP(r.scene, meshOf, { lod, name: baseName, maxTriangles: OBJ_TRIANGLE_LIMIT });
224
+ return { ...one(s.data), triangles: s.triangles };
225
+ }
226
+ const o = exportOBJ(r.scene, meshOf, { lod, name: baseName });
227
+ return {
228
+ files: [
229
+ { name, data: o.obj, mime: spec.mime },
230
+ { name: `${baseName}.mtl`, data: o.mtl, mime: 'text/plain' },
231
+ ],
232
+ triangles: o.triangles,
233
+ };
234
+ }
235
+ }
236
+ }
@@ -1,13 +1,13 @@
1
- // Browser download helper.
2
-
3
- export function download(name, data, mime = 'application/octet-stream') {
4
- const blob = data instanceof Blob ? data : new Blob([data], { type: mime });
5
- const url = URL.createObjectURL(blob);
6
- const a = document.createElement('a');
7
- a.href = url;
8
- a.download = name;
9
- document.body.appendChild(a);
10
- a.click();
11
- a.remove();
12
- setTimeout(() => URL.revokeObjectURL(url), 2000);
13
- }
1
+ // Browser download helper.
2
+
3
+ export function download(name, data, mime = 'application/octet-stream') {
4
+ const blob = data instanceof Blob ? data : new Blob([data], { type: mime });
5
+ const url = URL.createObjectURL(blob);
6
+ const a = document.createElement('a');
7
+ a.href = url;
8
+ a.download = name;
9
+ document.body.appendChild(a);
10
+ a.click();
11
+ a.remove();
12
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
13
+ }