@es3d/es3d 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +86 -3
- package/docs/REFERENCE.md +581 -0
- package/docs/SPEC.md +417 -0
- package/package.json +50 -4
- package/scripts/es3d-cli.mjs +377 -0
- package/src/cache/geometry-store.js +392 -0
- package/src/cache/mesh-bundle.js +123 -0
- package/src/cache/sha256.js +73 -0
- package/src/format/ast.js +238 -0
- package/src/format/colors.js +93 -0
- package/src/format/compact-parser.js +171 -0
- package/src/format/compact-tokenizer.js +165 -0
- package/src/format/errors.js +247 -0
- package/src/format/json.js +55 -0
- package/src/format/limits.js +14 -0
- package/src/format/parse.js +92 -0
- package/src/format/schema.js +617 -0
- package/src/format/serializer.js +333 -0
- package/src/format/validator.js +330 -0
- package/src/format/value-error.js +12 -0
- package/src/format/value-format.js +314 -0
- package/src/format/values.js +459 -0
- package/src/format/xml-parser.js +136 -0
- package/src/format/xml-tokenizer.js +237 -0
- package/src/geometry/contour.js +86 -0
- package/src/geometry/extrude.js +175 -0
- package/src/geometry/gear.js +85 -0
- package/src/geometry/geometry-cache.js +159 -0
- package/src/geometry/lod-error.js +178 -0
- package/src/geometry/mesh.js +458 -0
- package/src/geometry/primitives.js +299 -0
- package/src/geometry/registry.js +645 -0
- package/src/geometry/revolve.js +136 -0
- package/src/geometry/sweep.js +441 -0
- package/src/index.js +47 -0
- package/src/io/compression.js +67 -0
- package/src/io/convert.js +236 -0
- package/src/io/download.js +13 -0
- package/src/io/external-scene.js +127 -0
- package/src/io/file-loader.js +28 -0
- package/src/io/gltf.js +630 -0
- package/src/io/mesh-import.js +104 -0
- package/src/io/obj.js +352 -0
- package/src/io/step-brep.js +439 -0
- package/src/io/step-exact.js +1149 -0
- package/src/io/step.js +1418 -0
- package/src/io/stl.js +193 -0
- package/src/io/svg-import.js +787 -0
- package/src/material/materials.js +154 -0
- package/src/math/mat4.js +475 -0
- package/src/math/random.js +30 -0
- package/src/math/trig.js +65 -0
- package/src/math/vec3.js +81 -0
- package/src/optimize/optimizer.js +579 -0
- package/src/path/path-flatten.js +322 -0
- package/src/path/path-parser.js +332 -0
- package/src/path/shapes.js +129 -0
- package/src/path/triangulate.js +517 -0
- package/src/pipeline.js +74 -0
- package/src/render/camera.js +168 -0
- package/src/render/frame-builder.js +362 -0
- package/src/render/geometry-pool.js +149 -0
- package/src/render/lighting.js +149 -0
- package/src/render/orbit-controls.js +237 -0
- package/src/render/renderer.js +249 -0
- package/src/render/scroll-timeline.js +104 -0
- package/src/render/shaders/glsl.js +285 -0
- package/src/render/shaders/wgsl.js +252 -0
- package/src/render/stage.js +352 -0
- package/src/render/texture-cache.js +40 -0
- package/src/render/textures.js +223 -0
- package/src/render/webgl2/webgl2-backend.js +532 -0
- package/src/render/webgpu/webgpu-backend.js +480 -0
- package/src/scene/animation.js +171 -0
- package/src/scene/camera-constraints.js +117 -0
- package/src/scene/flatten.js +754 -0
- package/src/scene/picking.js +161 -0
- package/src/scene/scene-graph.js +320 -0
- package/src/transform/transform.js +211 -0
- package/src/wasm/kernels-binary.js +3 -0
- package/src/wasm/kernels.js +385 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Serialization of the ES3D AST to text.
|
|
2
|
+
//
|
|
3
|
+
// serialize(doc, { syntax: 'xml' | 'compact' | 'json', pretty, aliases, precision, comments })
|
|
4
|
+
//
|
|
5
|
+
// pretty : indentation, one element per line, comments kept (default true)
|
|
6
|
+
// aliases : use the short attribute aliases (p, r, s, m, ...) (default !pretty)
|
|
7
|
+
// precision: quantize numbers to this many decimals (null = keep source values)
|
|
8
|
+
// normalize: re-format typed values canonically (implied by precision / !pretty)
|
|
9
|
+
//
|
|
10
|
+
// Without precision/normalize the original attribute strings are written
|
|
11
|
+
// unchanged, so load -> save is lossless.
|
|
12
|
+
|
|
13
|
+
import { elementSpec, attrSpec } from './schema.js';
|
|
14
|
+
import { formatNumber, formatNumberList, formatColor, formatTransformOps, formatPathData } from './value-format.js';
|
|
15
|
+
import { toJsonTree } from './json.js';
|
|
16
|
+
|
|
17
|
+
const PRESETS = {
|
|
18
|
+
pretty: { pretty: true, aliases: false, precision: null, normalize: false, comments: true },
|
|
19
|
+
minified: { pretty: false, aliases: true, precision: null, normalize: true, comments: false },
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function resolveOptions(opts = {}) {
|
|
23
|
+
const base = opts.pretty === false ? PRESETS.minified : PRESETS.pretty;
|
|
24
|
+
const o = { syntax: 'xml', indent: ' ', wrap: 100, ...base, ...opts };
|
|
25
|
+
if (o.precision !== null && o.precision !== undefined) o.normalize = true;
|
|
26
|
+
return o;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Canonical (or aliased) attribute name for output. */
|
|
30
|
+
function outName(elName, canonical, opts) {
|
|
31
|
+
if (!opts.aliases) return canonical;
|
|
32
|
+
const spec = attrSpec(elName, canonical);
|
|
33
|
+
return spec && spec.alias ? spec.alias : canonical;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function canonicalName(el, a) {
|
|
37
|
+
if (el.attrIndex) {
|
|
38
|
+
for (const [k, v] of Object.entries(el.attrIndex)) if (v === a) return k;
|
|
39
|
+
}
|
|
40
|
+
const spec = elementSpec(el.name);
|
|
41
|
+
if (!spec) return a.name;
|
|
42
|
+
if (spec.attrs[a.name]) return a.name;
|
|
43
|
+
for (const [k, s] of Object.entries(spec.attrs)) if (s.alias === a.name) return k;
|
|
44
|
+
return a.name;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const allEqual = (v) => v.every((x) => x === v[0]);
|
|
48
|
+
|
|
49
|
+
/** Format an attribute value, re-encoding typed values when normalizing. */
|
|
50
|
+
export function formatAttrValue(el, canonical, raw, opts) {
|
|
51
|
+
if (!opts.normalize) return raw;
|
|
52
|
+
const spec = attrSpec(el.name, canonical);
|
|
53
|
+
const v = el.values ? el.values[canonical] : undefined;
|
|
54
|
+
if (!spec || v === undefined) return raw.trim();
|
|
55
|
+
const p = opts.precision;
|
|
56
|
+
const c = !opts.pretty;
|
|
57
|
+
switch (spec.type) {
|
|
58
|
+
case 'number':
|
|
59
|
+
case 'angle':
|
|
60
|
+
return formatNumber(v, p, c);
|
|
61
|
+
case 'int':
|
|
62
|
+
return String(v);
|
|
63
|
+
case 'vec2':
|
|
64
|
+
case 'vec3':
|
|
65
|
+
case 'vec4':
|
|
66
|
+
case 'numbers':
|
|
67
|
+
case 'animValue':
|
|
68
|
+
return formatNumberList(v, { sep: ',', precision: p, compact: c });
|
|
69
|
+
case 'keyframes':
|
|
70
|
+
return v.map((k) => formatNumberList(k, { sep: ',', precision: p, compact: c })).join(c ? ';' : '; ');
|
|
71
|
+
case 'size2':
|
|
72
|
+
case 'size3':
|
|
73
|
+
case 'scale3':
|
|
74
|
+
return allEqual(v) ? formatNumber(v[0], p, c) : formatNumberList(v, { sep: ',', precision: p, compact: c });
|
|
75
|
+
case 'count2':
|
|
76
|
+
return v.join(',');
|
|
77
|
+
case 'points2':
|
|
78
|
+
return formatNumberList(v, { group: 2, precision: p, compact: c });
|
|
79
|
+
case 'points3':
|
|
80
|
+
return formatNumberList(v, { group: 3, precision: p, compact: c });
|
|
81
|
+
case 'floats':
|
|
82
|
+
return formatNumberList(v, { sep: ' ', precision: p, compact: c });
|
|
83
|
+
case 'indices':
|
|
84
|
+
return Array.from(v).join(' ');
|
|
85
|
+
case 'color': {
|
|
86
|
+
const hex = formatColor(v);
|
|
87
|
+
const r = raw.trim();
|
|
88
|
+
return r.length < hex.length ? r : hex;
|
|
89
|
+
}
|
|
90
|
+
case 'ref':
|
|
91
|
+
case 'id':
|
|
92
|
+
case 'enum':
|
|
93
|
+
case 'string':
|
|
94
|
+
return String(v);
|
|
95
|
+
case 'bool':
|
|
96
|
+
return v ? 'true' : 'false';
|
|
97
|
+
case 'transform':
|
|
98
|
+
return formatTransformOps(v.ops, p, c);
|
|
99
|
+
case 'path2d':
|
|
100
|
+
return formatPathData(v.segments, { precision: p, minify: c, dim: 2 });
|
|
101
|
+
case 'spine':
|
|
102
|
+
if (v.kind === 'path') return formatPathData(v.segments, { precision: p, minify: c, dim: 3 });
|
|
103
|
+
if (v.kind === 'points') return formatNumberList(v.points, { group: 3, precision: p, compact: c });
|
|
104
|
+
return `helix(${[v.radius, v.pitch, v.turns, ...(v.segmentsPerTurn ? [v.segmentsPerTurn] : [])].map((x) => formatNumber(x, p, c)).join(',')})`;
|
|
105
|
+
case 'range': {
|
|
106
|
+
const [a, b] = v;
|
|
107
|
+
return a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`;
|
|
108
|
+
}
|
|
109
|
+
case 'range3': {
|
|
110
|
+
const f = ([a, b]) => (a === b ? formatNumber(a, p, c) : `${formatNumber(a, p, c)}..${formatNumber(b, p, c)}`);
|
|
111
|
+
return v.ranges.map(f).join(',');
|
|
112
|
+
}
|
|
113
|
+
case 'idlist':
|
|
114
|
+
return v.join(',');
|
|
115
|
+
case 'duration':
|
|
116
|
+
return formatNumber(v, p, c) + 's';
|
|
117
|
+
case 'repeatCount':
|
|
118
|
+
return v === Infinity ? 'indefinite' : formatNumber(v, p, c);
|
|
119
|
+
default:
|
|
120
|
+
return raw.trim();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// markup syntax
|
|
126
|
+
|
|
127
|
+
function escAttr(s) {
|
|
128
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
|
129
|
+
}
|
|
130
|
+
function escText(s) {
|
|
131
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
132
|
+
}
|
|
133
|
+
function xmlComment(text) {
|
|
134
|
+
return `<!--${text.replace(/--/g, '- -').replace(/-$/, '- ')}-->`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function attrPairs(el, opts) {
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const a of el.attrs) {
|
|
140
|
+
const canonical = canonicalName(el, a);
|
|
141
|
+
out.push([outName(el.name, canonical, opts), formatAttrValue(el, canonical, a.value, opts), canonical]);
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function serializeXml(doc, opts) {
|
|
147
|
+
const lines = [];
|
|
148
|
+
const ind = (d) => opts.indent.repeat(d);
|
|
149
|
+
if (opts.pretty) {
|
|
150
|
+
if (opts.comments) for (const c of doc.leading) lines.push(xmlComment(c.text));
|
|
151
|
+
const emit = (el, depth) => {
|
|
152
|
+
const pairs = attrPairs(el, opts);
|
|
153
|
+
const attrsInline = pairs.map(([k, v]) => ` ${k}="${escAttr(v)}"`).join('');
|
|
154
|
+
const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
|
|
155
|
+
const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
|
|
156
|
+
let open = `${ind(depth)}<${el.name}${attrsInline}`;
|
|
157
|
+
if (open.length + 2 > opts.wrap && pairs.length > 1) {
|
|
158
|
+
open = `${ind(depth)}<${el.name}` + pairs.map(([k, v]) => `\n${ind(depth + 2)}${k}="${escAttr(v)}"`).join('');
|
|
159
|
+
}
|
|
160
|
+
if (!kids.length && !hasText) {
|
|
161
|
+
lines.push(open + '/>');
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (hasText && !kids.length) {
|
|
165
|
+
lines.push(`${open}>${escText(el.text.trim())}</${el.name}>`);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
lines.push(open + '>');
|
|
169
|
+
if (hasText) lines.push(ind(depth + 1) + escText(el.text.trim()));
|
|
170
|
+
for (const c of kids) {
|
|
171
|
+
if (c.type === 'comment') lines.push(ind(depth + 1) + xmlComment(c.text));
|
|
172
|
+
else emit(c, depth + 1);
|
|
173
|
+
}
|
|
174
|
+
lines.push(`${ind(depth)}</${el.name}>`);
|
|
175
|
+
};
|
|
176
|
+
emit(doc.root, 0);
|
|
177
|
+
if (opts.comments) for (const c of doc.trailing) lines.push(xmlComment(c.text));
|
|
178
|
+
return lines.join('\n') + '\n';
|
|
179
|
+
}
|
|
180
|
+
// minified
|
|
181
|
+
let out = '';
|
|
182
|
+
const emit = (el) => {
|
|
183
|
+
out += '<' + el.name;
|
|
184
|
+
for (const [k, v] of attrPairs(el, opts)) out += ` ${k}="${escAttr(v)}"`;
|
|
185
|
+
const kids = el.children.filter((c) => c.type === 'element' || opts.comments);
|
|
186
|
+
const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
|
|
187
|
+
if (!kids.length && !hasText) {
|
|
188
|
+
out += '/>';
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
out += '>';
|
|
192
|
+
if (hasText) out += escText(el.text.trim());
|
|
193
|
+
for (const c of kids) {
|
|
194
|
+
if (c.type === 'comment') out += xmlComment(c.text);
|
|
195
|
+
else emit(c);
|
|
196
|
+
}
|
|
197
|
+
out += `</${el.name}>`;
|
|
198
|
+
};
|
|
199
|
+
emit(doc.root);
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
// compact syntax
|
|
205
|
+
|
|
206
|
+
const NAME_RE = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;
|
|
207
|
+
|
|
208
|
+
function quoteCompact(v) {
|
|
209
|
+
if (v !== '' && !/[\s{};"\\]/.test(v)) return v;
|
|
210
|
+
return '"' + v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"';
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function compactComment(text, pretty) {
|
|
214
|
+
if (pretty && !text.includes('\n')) return '//' + (text.startsWith(' ') ? '' : ' ') + text.replace(/\s+$/, '');
|
|
215
|
+
return '/*' + text.replace(/\*\//g, '* /') + '*/';
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function compactHeader(el, opts) {
|
|
219
|
+
let s = el.name;
|
|
220
|
+
const rest = [];
|
|
221
|
+
for (const [k, v, canonical] of attrPairs(el, opts)) {
|
|
222
|
+
if (canonical === 'id' && NAME_RE.test(v)) s += '#' + v;
|
|
223
|
+
else if (canonical === 'ref' && NAME_RE.test(v)) rest.unshift('@' + v);
|
|
224
|
+
else rest.push(`${k}=${quoteCompact(v)}`);
|
|
225
|
+
}
|
|
226
|
+
const hasText = el.text !== null && el.text !== undefined && el.text.trim() !== '';
|
|
227
|
+
if (hasText) {
|
|
228
|
+
const t = el.text.trim();
|
|
229
|
+
rest.unshift('"' + t.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + '"');
|
|
230
|
+
}
|
|
231
|
+
return rest.length ? s + ' ' + rest.join(' ') : s;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function serializeCompact(doc, opts) {
|
|
235
|
+
if (opts.pretty) {
|
|
236
|
+
const lines = [];
|
|
237
|
+
const ind = (d) => opts.indent.repeat(d);
|
|
238
|
+
if (opts.comments) for (const c of doc.leading) lines.push(compactComment(c.text, true));
|
|
239
|
+
const emitChildren = (el, depth) => {
|
|
240
|
+
for (const c of el.children) {
|
|
241
|
+
if (c.type === 'comment') {
|
|
242
|
+
if (opts.comments) lines.push(ind(depth) + compactComment(c.text, true));
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
const kids = c.children.filter((k) => k.type === 'element' || opts.comments);
|
|
246
|
+
const head = ind(depth) + compactHeader(c, opts);
|
|
247
|
+
if (!kids.length) lines.push(head);
|
|
248
|
+
else {
|
|
249
|
+
lines.push(head + ' {');
|
|
250
|
+
emitChildren(c, depth + 1);
|
|
251
|
+
lines.push(ind(depth) + '}');
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
lines.push(compactHeader(doc.root, opts));
|
|
256
|
+
emitChildren(doc.root, 0);
|
|
257
|
+
if (opts.comments) for (const c of doc.trailing) lines.push(compactComment(c.text, true));
|
|
258
|
+
return lines.join('\n') + '\n';
|
|
259
|
+
}
|
|
260
|
+
const parts = [];
|
|
261
|
+
const emit = (el) => {
|
|
262
|
+
let s = compactHeader(el, opts);
|
|
263
|
+
const kids = el.children.filter((k) => k.type === 'element' || opts.comments);
|
|
264
|
+
if (kids.length) {
|
|
265
|
+
const inner = [];
|
|
266
|
+
for (const c of kids) inner.push(c.type === 'comment' ? compactComment(c.text, false) : emit(c));
|
|
267
|
+
s += '{' + joinStatements(inner) + '}';
|
|
268
|
+
}
|
|
269
|
+
return s;
|
|
270
|
+
};
|
|
271
|
+
parts.push(compactHeader(doc.root, opts));
|
|
272
|
+
for (const c of doc.root.children) {
|
|
273
|
+
if (c.type === 'comment') {
|
|
274
|
+
if (opts.comments) parts.push(compactComment(c.text, false));
|
|
275
|
+
} else parts.push(emit(c));
|
|
276
|
+
}
|
|
277
|
+
return joinStatements(parts);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Join compact statements; a separator is needed only between two plain headers. */
|
|
281
|
+
function joinStatements(items) {
|
|
282
|
+
let out = '';
|
|
283
|
+
for (let i = 0; i < items.length; i++) {
|
|
284
|
+
const s = items[i];
|
|
285
|
+
if (i > 0) {
|
|
286
|
+
const prev = items[i - 1];
|
|
287
|
+
if (!prev.endsWith('}') && !prev.endsWith('*/')) out += ';';
|
|
288
|
+
}
|
|
289
|
+
out += s;
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ---------------------------------------------------------------------------
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Serialize a document.
|
|
298
|
+
* @param {import('./ast.js').Document} doc
|
|
299
|
+
* @param {object} [options]
|
|
300
|
+
* @returns {string}
|
|
301
|
+
*/
|
|
302
|
+
export function serialize(doc, options = {}) {
|
|
303
|
+
const opts = resolveOptions(options);
|
|
304
|
+
if (!doc.root) throw new Error('Cannot serialize a document without a root element.');
|
|
305
|
+
if (opts.syntax === 'compact') return serializeCompact(doc, opts);
|
|
306
|
+
if (opts.syntax === 'json') {
|
|
307
|
+
const workDoc = opts.normalize ? normalizedCopy(doc, opts) : doc;
|
|
308
|
+
const tree = toJsonTree(workDoc, { comments: opts.comments });
|
|
309
|
+
return opts.pretty ? JSON.stringify(tree, null, 1) + '\n' : JSON.stringify(tree);
|
|
310
|
+
}
|
|
311
|
+
return serializeXml(doc, opts);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Copy of the AST where attribute values are already formatted per opts. */
|
|
315
|
+
function normalizedCopy(doc, opts) {
|
|
316
|
+
const clone = (el) => {
|
|
317
|
+
const pairs = attrPairs(el, opts);
|
|
318
|
+
return {
|
|
319
|
+
...el,
|
|
320
|
+
attrs: pairs.map(([k, v]) => ({ name: k, value: v })),
|
|
321
|
+
children: el.children.map((c) => (c.type === 'element' ? clone(c) : c)),
|
|
322
|
+
};
|
|
323
|
+
};
|
|
324
|
+
return { ...doc, root: clone(doc.root) };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export const SERIALIZE_PRESETS = {
|
|
328
|
+
'xml-pretty': { syntax: 'xml', pretty: true },
|
|
329
|
+
'xml-min': { syntax: 'xml', pretty: false },
|
|
330
|
+
'compact-pretty': { syntax: 'compact', pretty: true },
|
|
331
|
+
'compact-min': { syntax: 'compact', pretty: false },
|
|
332
|
+
'json-min': { syntax: 'json', pretty: false },
|
|
333
|
+
};
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// Schema validation and reference resolution.
|
|
2
|
+
//
|
|
3
|
+
// Converts raw attribute strings into typed values (element.values), checks
|
|
4
|
+
// element nesting, numeric ranges and cross-attribute rules, verifies every id
|
|
5
|
+
// reference and detects circular <use> chains. All problems are collected (not
|
|
6
|
+
// just the first) and reported with exact source positions and suggestions.
|
|
7
|
+
|
|
8
|
+
import { DiagnosticList, suggest } from './errors.js';
|
|
9
|
+
import { indexTree } from './ast.js';
|
|
10
|
+
import { ELEMENTS, ROOT_ELEMENTS, SHAPES, CONTAINERS, aliasesFor, elementSpec, ALL_ELEMENT_NAMES } from './schema.js';
|
|
11
|
+
import { parseTyped } from './values.js';
|
|
12
|
+
import { ValueError } from './value-error.js';
|
|
13
|
+
|
|
14
|
+
const USABLE = new Set([...SHAPES, ...CONTAINERS, 'use', 'light']);
|
|
15
|
+
|
|
16
|
+
function elementPath(el) {
|
|
17
|
+
const parts = [];
|
|
18
|
+
for (let e = el; e; e = e.parent) {
|
|
19
|
+
let label = e.name;
|
|
20
|
+
if (e.parent) {
|
|
21
|
+
let index = -1, same = 0;
|
|
22
|
+
for (const c of e.parent.children) {
|
|
23
|
+
if (c.type !== 'element' || c.name !== e.name) continue;
|
|
24
|
+
if (c === e) index = same;
|
|
25
|
+
same++;
|
|
26
|
+
}
|
|
27
|
+
if (same > 1) label += `[${index}]`;
|
|
28
|
+
}
|
|
29
|
+
const id = e.attr && e.attr('id');
|
|
30
|
+
if (id) label += `#${id}`;
|
|
31
|
+
parts.unshift(label);
|
|
32
|
+
}
|
|
33
|
+
return parts.join(' > ');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function describeNumber(spec) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
if (spec.exclusiveMin !== undefined) parts.push(`greater than ${spec.exclusiveMin}`);
|
|
39
|
+
else if (spec.min !== undefined) parts.push(`at least ${spec.min}`);
|
|
40
|
+
if (spec.max !== undefined) parts.push(`at most ${spec.max}`);
|
|
41
|
+
return parts.join(' and ');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function checkNumeric(spec, value) {
|
|
45
|
+
if (typeof value !== 'number') return null;
|
|
46
|
+
if (spec.exclusiveMin !== undefined && !(value > spec.exclusiveMin)) return describeNumber(spec);
|
|
47
|
+
if (spec.min !== undefined && value < spec.min) return describeNumber(spec);
|
|
48
|
+
if (spec.max !== undefined && value > spec.max) return describeNumber(spec);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validate a parsed document in place.
|
|
54
|
+
* Sets el.values / el.attrIndex, doc.ids and doc.diagnostics.
|
|
55
|
+
* @returns {import('./ast.js').Document}
|
|
56
|
+
*/
|
|
57
|
+
const REQUIRED = new WeakMap();
|
|
58
|
+
|
|
59
|
+
/** Names of an element's required attributes, in schema order (computed once per element type). */
|
|
60
|
+
function requiredAttrs(spec) {
|
|
61
|
+
let list = REQUIRED.get(spec);
|
|
62
|
+
if (!list) {
|
|
63
|
+
list = Object.entries(spec.attrs).filter(([, a]) => a.required).map(([name]) => name);
|
|
64
|
+
REQUIRED.set(spec, list);
|
|
65
|
+
}
|
|
66
|
+
return list;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function validate(doc) {
|
|
70
|
+
const diags = new DiagnosticList(doc.lineIndex);
|
|
71
|
+
indexTree(doc);
|
|
72
|
+
doc.ids = new Map();
|
|
73
|
+
const refs = []; // {el, attr, id, kind, list?}
|
|
74
|
+
|
|
75
|
+
const locEl = (el) => (el.nameStart >= 0 ? { offset: el.nameStart, length: el.nameEnd - el.nameStart } : { offset: -1, length: 0, path: elementPath(el) });
|
|
76
|
+
const locAttrName = (el, a) => (a && a.nameStart >= 0 ? { offset: a.nameStart, length: a.nameEnd - a.nameStart } : locEl(el));
|
|
77
|
+
const locAttrValue = (el, a, e) => {
|
|
78
|
+
if (!a || a.valueStart < 0) return locEl(el);
|
|
79
|
+
if (e && !a.decoded && e.offset !== undefined) {
|
|
80
|
+
const off = Math.min(a.valueStart + e.offset, a.valueEnd);
|
|
81
|
+
const len = Math.max(1, Math.min(e.length || 1, a.valueEnd - off));
|
|
82
|
+
return { offset: off, length: len };
|
|
83
|
+
}
|
|
84
|
+
return { offset: a.valueStart, length: Math.max(1, a.valueEnd - a.valueStart) };
|
|
85
|
+
};
|
|
86
|
+
const report = (severity, code, message, loc, extra = {}, el = null) => {
|
|
87
|
+
diags.add({ severity, code, message, offset: loc.offset, length: loc.length, path: loc.path || (loc.offset < 0 && el ? elementPath(el) : null), uid: el ? el.uid : 0, ...extra });
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const root = doc.root;
|
|
91
|
+
if (!ROOT_ELEMENTS.includes(root.name)) {
|
|
92
|
+
report('error', 'E_ROOT', `The root element must be <es3d> but found <${root.name}>.`, locEl(root), { suggestion: 'es3d' }, root);
|
|
93
|
+
doc.diagnostics = diags.sorted();
|
|
94
|
+
return doc;
|
|
95
|
+
}
|
|
96
|
+
if (root.name === 'v3d') {
|
|
97
|
+
report('warning', 'W_LEGACY_ROOT', 'The root element <v3d> is a legacy alias; write <es3d>.', locEl(root), {}, root);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
let sceneCount = 0;
|
|
101
|
+
let envCount = 0;
|
|
102
|
+
let controlsCount = 0;
|
|
103
|
+
|
|
104
|
+
const visit = (el, parentSpec, inDefs) => {
|
|
105
|
+
const spec = elementSpec(el.name);
|
|
106
|
+
if (!spec) {
|
|
107
|
+
if (el.name.startsWith('x-')) {
|
|
108
|
+
report('warning', 'W_EXTENSION', `Extension element <${el.name}> is not supported by this reader; it and its children are not rendered.`, locEl(el), {}, el);
|
|
109
|
+
} else {
|
|
110
|
+
report('error', 'E_UNKNOWN_ELEMENT', `Unknown element: ${el.name}`, locEl(el), { suggestion: suggest(el.name, ALL_ELEMENT_NAMES.concat(['es3d'])) }, el);
|
|
111
|
+
}
|
|
112
|
+
el.values = {};
|
|
113
|
+
el.attrIndex = {};
|
|
114
|
+
el.unknown = true;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
el.unknown = false;
|
|
118
|
+
if (el.name === 'scene' && ++sceneCount > 1) report('error', 'E_MULTIPLE_SCENES', 'Only one <scene> element is allowed.', locEl(el), {}, el);
|
|
119
|
+
if (el.name === 'environment' && ++envCount > 1) {
|
|
120
|
+
report('warning', 'W_MULTIPLE_ENVIRONMENTS', 'More than one <environment>: only the first one is used.', locEl(el), {}, el);
|
|
121
|
+
}
|
|
122
|
+
if (el.name === 'controls' && ++controlsCount > 1) {
|
|
123
|
+
report('warning', 'W_MULTIPLE_CONTROLS', 'More than one <controls>: only the first one is used.', locEl(el), {}, el);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// attributes
|
|
127
|
+
const aliases = aliasesFor(el.name);
|
|
128
|
+
const values = {};
|
|
129
|
+
const attrIndex = {};
|
|
130
|
+
for (const a of el.attrs) {
|
|
131
|
+
const canonical = aliases.get(a.name);
|
|
132
|
+
if (!canonical) {
|
|
133
|
+
if (a.name === 'xmlns' || a.name.startsWith('xmlns:')) continue;
|
|
134
|
+
const candidates = [...aliases.keys()];
|
|
135
|
+
const sug = suggest(a.name, candidates);
|
|
136
|
+
let hint = null;
|
|
137
|
+
if (!sug) {
|
|
138
|
+
const own = Object.keys(spec.attrs).filter((k) => !['id', 'name', 'transform', 'position', 'rotation', 'scale', 'visible', 'material', 'color'].includes(k));
|
|
139
|
+
if (own.length) hint = `<${el.name}> accepts: ${own.join(', ')} (plus id, name, transform, position, rotation, scale, material, color).`;
|
|
140
|
+
}
|
|
141
|
+
report('error', 'E_UNKNOWN_ATTRIBUTE', `Unknown attribute: ${a.name}`, locAttrName(el, a), { suggestion: sug, hint }, el);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (attrIndex[canonical]) {
|
|
145
|
+
report('error', 'E_DUPLICATE_ATTRIBUTE', `Attribute '${canonical}' is given twice (as '${attrIndex[canonical].name}' and '${a.name}').`, locAttrName(el, a), {}, el);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
attrIndex[canonical] = a;
|
|
149
|
+
const aspec = spec.attrs[canonical];
|
|
150
|
+
let value;
|
|
151
|
+
try {
|
|
152
|
+
value = a.typed !== undefined ? a.typed : parseTyped(aspec, a.value);
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (!(e instanceof ValueError)) throw e;
|
|
155
|
+
report('error', e.code || 'E_INVALID_VALUE', `Invalid value for '${a.name}': ${e.message}`, locAttrValue(el, a, e), { suggestion: e.suggestion, hint: e.hint }, el);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const bad = checkNumeric(aspec, value);
|
|
159
|
+
if (bad) {
|
|
160
|
+
report('error', 'E_RANGE', `'${a.name}' must be ${bad}; found ${value}.`, locAttrValue(el, a), {}, el);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
values[canonical] = value;
|
|
164
|
+
if (aspec.type === 'id' && canonical === 'id') {
|
|
165
|
+
const prev = doc.ids.get(value);
|
|
166
|
+
if (prev) {
|
|
167
|
+
let where = '';
|
|
168
|
+
if (prev.nameStart >= 0 && doc.lineIndex) {
|
|
169
|
+
const p = doc.lineIndex.position(prev.nameStart);
|
|
170
|
+
where = ` (first defined at line ${p.line})`;
|
|
171
|
+
}
|
|
172
|
+
report('error', 'E_DUPLICATE_ID', `Duplicate id '${value}'${where}.`, locAttrValue(el, a), {}, el);
|
|
173
|
+
} else {
|
|
174
|
+
doc.ids.set(value, el);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (aspec.type === 'ref') refs.push({ el, attr: a, canonical, id: value, kind: aspec.ref });
|
|
178
|
+
if (aspec.type === 'idlist' && aspec.ref) for (const id of value) refs.push({ el, attr: a, canonical, id, kind: aspec.ref });
|
|
179
|
+
}
|
|
180
|
+
el.values = values;
|
|
181
|
+
el.attrIndex = attrIndex;
|
|
182
|
+
|
|
183
|
+
for (const name of requiredAttrs(spec)) {
|
|
184
|
+
if (values[name] === undefined && !attrIndex[name]) {
|
|
185
|
+
report('error', 'E_MISSING_ATTRIBUTE', `<${el.name}> requires the attribute '${name}'.`, locEl(el), { hint: spec.attrs[name].desc }, el);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (spec.check) {
|
|
189
|
+
// attributes that are present but failed to parse count as given, so
|
|
190
|
+
// cross-attribute rules do not cascade into "missing attribute" errors
|
|
191
|
+
const given = (k) => values[k] !== undefined || !!attrIndex[k];
|
|
192
|
+
spec.check(values, (attrName, message, code = 'E_INVALID_VALUE') => {
|
|
193
|
+
const a = attrName ? attrIndex[attrName] : null;
|
|
194
|
+
report('error', code, message, a ? locAttrValue(el, a) : locEl(el), {}, el);
|
|
195
|
+
}, el, given);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// text content
|
|
199
|
+
if (el.text !== null && el.text.trim() !== '' && spec.children !== 'text') {
|
|
200
|
+
const loc = el.textStart >= 0 ? { offset: el.textStart, length: Math.max(1, Math.min(20, el.textEnd - el.textStart)) } : locEl(el);
|
|
201
|
+
report('error', 'E_TEXT_NOT_ALLOWED', `Text content is not allowed inside <${el.name}>.`, loc, {}, el);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (inDefs && el.parent && el.parent.name === 'defs' && values.id === undefined && !attrIndex.id) {
|
|
205
|
+
report('warning', 'W_DEF_WITHOUT_ID', `<${el.name}> inside <defs> has no id, so it can never be used.`, locEl(el), {}, el);
|
|
206
|
+
}
|
|
207
|
+
if (el.name === 'material' && values.id === undefined && !attrIndex.id) {
|
|
208
|
+
report('warning', 'W_MATERIAL_WITHOUT_ID', '<material> without an id can never be referenced.', locEl(el), {}, el);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// children
|
|
212
|
+
const allowed = spec.children;
|
|
213
|
+
for (const c of el.children) {
|
|
214
|
+
if (c.type !== 'element') continue;
|
|
215
|
+
if (allowed === 'text' || !Array.isArray(allowed) || !allowed.includes(c.name)) {
|
|
216
|
+
const childSpec = elementSpec(c.name);
|
|
217
|
+
if (childSpec || !c.name.startsWith('x-')) {
|
|
218
|
+
if (childSpec) {
|
|
219
|
+
let hint = null;
|
|
220
|
+
if (c.name === 'animate') hint = '<animate> can only be placed inside an element with a transform (shapes, group, use, repeat, scatter, lod, light, camera).';
|
|
221
|
+
else if (c.name === 'scene' || c.name === 'defs') hint = `<${c.name}> is only allowed directly inside <es3d>.`;
|
|
222
|
+
else if (c.name === 'controls') hint = '<controls> is only allowed directly inside <es3d> or <scene>.';
|
|
223
|
+
else if (spec.category === 'shape') hint = 'Shapes cannot contain other shapes; wrap them in a <group>.';
|
|
224
|
+
report('error', 'E_MISPLACED_ELEMENT', `<${c.name}> is not allowed inside <${el.name}>.`, locEl(c), { hint }, c);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
visit(c, spec, inDefs || el.name === 'defs');
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
visit(root, null, false);
|
|
232
|
+
|
|
233
|
+
// references ---------------------------------------------------------------
|
|
234
|
+
const kindLabel = { material: 'material', path: 'path', node: 'element' };
|
|
235
|
+
for (const r of refs) {
|
|
236
|
+
const target = doc.ids.get(r.id);
|
|
237
|
+
// computed only when reporting: element paths are expensive for large binary documents
|
|
238
|
+
const where = () => (r.attr.valueStart >= 0 ? { offset: r.attr.valueStart, length: Math.max(1, r.attr.valueEnd - r.attr.valueStart) } : locEl(r.el));
|
|
239
|
+
if (!target) {
|
|
240
|
+
const loc = where();
|
|
241
|
+
const candidates = [...doc.ids.entries()]
|
|
242
|
+
.filter(([, t]) => (r.kind === 'material' ? t.name === 'material' : r.kind === 'path' ? t.name === 'path' : USABLE.has(t.name)))
|
|
243
|
+
.map(([id]) => id);
|
|
244
|
+
diags.add({
|
|
245
|
+
phase: 'reference',
|
|
246
|
+
code: 'E_UNKNOWN_REFERENCE',
|
|
247
|
+
message: `Unknown ${kindLabel[r.kind]} '${r.id}' referenced by ${r.attr.name}.`,
|
|
248
|
+
offset: loc.offset,
|
|
249
|
+
length: loc.length,
|
|
250
|
+
path: loc.path || null,
|
|
251
|
+
suggestion: suggest(r.id, candidates),
|
|
252
|
+
uid: r.el.uid,
|
|
253
|
+
});
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
let ok = true;
|
|
257
|
+
if (r.kind === 'material') ok = target.name === 'material';
|
|
258
|
+
else if (r.kind === 'path') ok = target.name === 'path';
|
|
259
|
+
else if (r.kind === 'node') ok = USABLE.has(target.name);
|
|
260
|
+
if (!ok) {
|
|
261
|
+
const loc = where();
|
|
262
|
+
diags.add({
|
|
263
|
+
phase: 'reference',
|
|
264
|
+
code: 'E_REFERENCE_KIND',
|
|
265
|
+
message: `${r.attr.name}="${r.id}" refers to a <${target.name}>, but a ${r.kind === 'node' ? 'shape, group, use, repeat, scatter, lod or light' : `<${r.kind}>`} is required.`,
|
|
266
|
+
offset: loc.offset,
|
|
267
|
+
length: loc.length,
|
|
268
|
+
path: loc.path || null,
|
|
269
|
+
uid: r.el.uid,
|
|
270
|
+
});
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (r.canonical === 'ref') r.el.target = target;
|
|
274
|
+
if (r.kind === 'path') r.el.pathTarget = target;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// circular <use> chains ------------------------------------------------------
|
|
278
|
+
const usesInside = new Map();
|
|
279
|
+
const collectUses = (el) => {
|
|
280
|
+
if (usesInside.has(el)) return usesInside.get(el);
|
|
281
|
+
const list = [];
|
|
282
|
+
const stack = [el];
|
|
283
|
+
while (stack.length) {
|
|
284
|
+
const e = stack.pop();
|
|
285
|
+
if (e.name === 'use' && e.target) list.push(e);
|
|
286
|
+
for (const c of e.children) if (c.type === 'element') stack.push(c);
|
|
287
|
+
}
|
|
288
|
+
usesInside.set(el, list);
|
|
289
|
+
return list;
|
|
290
|
+
};
|
|
291
|
+
const state = new Map(); // target -> 1 visiting, 2 done
|
|
292
|
+
const reported = new Set();
|
|
293
|
+
const dfs = (target, chain) => {
|
|
294
|
+
state.set(target, 1);
|
|
295
|
+
for (const u of collectUses(target)) {
|
|
296
|
+
const t = u.target;
|
|
297
|
+
const st = state.get(t);
|
|
298
|
+
if (st === 1) {
|
|
299
|
+
if (!reported.has(u)) {
|
|
300
|
+
reported.add(u);
|
|
301
|
+
const ids = [...chain.map((x) => x.values.id || x.name), t.values.id || t.name];
|
|
302
|
+
const a = u.attrIndex.ref;
|
|
303
|
+
diags.add({
|
|
304
|
+
phase: 'reference',
|
|
305
|
+
code: 'E_CIRCULAR_REFERENCE',
|
|
306
|
+
message: `Circular reference: ${ids.join(' → ')}.`,
|
|
307
|
+
offset: a && a.valueStart >= 0 ? a.valueStart : u.nameStart,
|
|
308
|
+
length: a && a.valueStart >= 0 ? a.valueEnd - a.valueStart : u.nameEnd - u.nameStart,
|
|
309
|
+
path: u.nameStart < 0 ? elementPath(u) : null,
|
|
310
|
+
hint: 'An element cannot (directly or indirectly) contain a <use> of itself.',
|
|
311
|
+
uid: u.uid,
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
u.circular = true;
|
|
315
|
+
} else if (!st) {
|
|
316
|
+
dfs(t, [...chain, t]);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
state.set(target, 2);
|
|
320
|
+
};
|
|
321
|
+
for (const target of new Set([...doc.ids.values()])) {
|
|
322
|
+
if (!state.has(target)) dfs(target, [target]);
|
|
323
|
+
}
|
|
324
|
+
// uses outside any referenced subtree (e.g. in the scene) that point into a cycle are covered above.
|
|
325
|
+
|
|
326
|
+
doc.diagnostics = diags.sorted();
|
|
327
|
+
return doc;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export { elementPath, ELEMENTS };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Error raised by attribute value parsers; offsets are relative to the attribute value. */
|
|
2
|
+
export class ValueError extends Error {
|
|
3
|
+
constructor(message, offset = 0, length = 0, extra = {}) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = 'ValueError';
|
|
6
|
+
this.offset = offset;
|
|
7
|
+
this.length = length;
|
|
8
|
+
this.hint = extra.hint || null;
|
|
9
|
+
this.suggestion = extra.suggestion || null;
|
|
10
|
+
this.code = extra.code || null;
|
|
11
|
+
}
|
|
12
|
+
}
|