@es3d/es3d 0.0.0-stage → 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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +85 -2
  3. package/docs/REFERENCE.md +581 -0
  4. package/docs/SPEC.md +417 -0
  5. package/package.json +50 -4
  6. package/scripts/es3d-cli.mjs +377 -0
  7. package/src/cache/geometry-store.js +392 -0
  8. package/src/cache/mesh-bundle.js +123 -0
  9. package/src/cache/sha256.js +73 -0
  10. package/src/format/ast.js +238 -0
  11. package/src/format/colors.js +93 -0
  12. package/src/format/compact-parser.js +171 -0
  13. package/src/format/compact-tokenizer.js +165 -0
  14. package/src/format/errors.js +247 -0
  15. package/src/format/json.js +55 -0
  16. package/src/format/limits.js +14 -0
  17. package/src/format/parse.js +92 -0
  18. package/src/format/schema.js +617 -0
  19. package/src/format/serializer.js +333 -0
  20. package/src/format/validator.js +330 -0
  21. package/src/format/value-error.js +12 -0
  22. package/src/format/value-format.js +314 -0
  23. package/src/format/values.js +459 -0
  24. package/src/format/xml-parser.js +136 -0
  25. package/src/format/xml-tokenizer.js +237 -0
  26. package/src/geometry/contour.js +86 -0
  27. package/src/geometry/extrude.js +175 -0
  28. package/src/geometry/gear.js +85 -0
  29. package/src/geometry/geometry-cache.js +159 -0
  30. package/src/geometry/lod-error.js +178 -0
  31. package/src/geometry/mesh.js +458 -0
  32. package/src/geometry/primitives.js +299 -0
  33. package/src/geometry/registry.js +645 -0
  34. package/src/geometry/revolve.js +136 -0
  35. package/src/geometry/sweep.js +441 -0
  36. package/src/index.js +47 -0
  37. package/src/io/compression.js +67 -0
  38. package/src/io/convert.js +236 -0
  39. package/src/io/download.js +13 -0
  40. package/src/io/external-scene.js +127 -0
  41. package/src/io/file-loader.js +28 -0
  42. package/src/io/gltf.js +630 -0
  43. package/src/io/mesh-import.js +104 -0
  44. package/src/io/obj.js +352 -0
  45. package/src/io/step-brep.js +439 -0
  46. package/src/io/step-exact.js +1149 -0
  47. package/src/io/step.js +1418 -0
  48. package/src/io/stl.js +193 -0
  49. package/src/io/svg-import.js +787 -0
  50. package/src/material/materials.js +154 -0
  51. package/src/math/mat4.js +475 -0
  52. package/src/math/random.js +30 -0
  53. package/src/math/trig.js +65 -0
  54. package/src/math/vec3.js +81 -0
  55. package/src/optimize/optimizer.js +579 -0
  56. package/src/path/path-flatten.js +322 -0
  57. package/src/path/path-parser.js +332 -0
  58. package/src/path/shapes.js +129 -0
  59. package/src/path/triangulate.js +517 -0
  60. package/src/pipeline.js +74 -0
  61. package/src/render/camera.js +168 -0
  62. package/src/render/frame-builder.js +362 -0
  63. package/src/render/geometry-pool.js +149 -0
  64. package/src/render/lighting.js +149 -0
  65. package/src/render/orbit-controls.js +237 -0
  66. package/src/render/renderer.js +258 -0
  67. package/src/render/scroll-timeline.js +104 -0
  68. package/src/render/shaders/glsl.js +285 -0
  69. package/src/render/shaders/wgsl.js +252 -0
  70. package/src/render/stage.js +364 -0
  71. package/src/render/texture-cache.js +40 -0
  72. package/src/render/textures.js +223 -0
  73. package/src/render/webgl2/webgl2-backend.js +586 -0
  74. package/src/render/webgpu/webgpu-backend.js +482 -0
  75. package/src/scene/animation.js +171 -0
  76. package/src/scene/camera-constraints.js +117 -0
  77. package/src/scene/flatten.js +754 -0
  78. package/src/scene/picking.js +161 -0
  79. package/src/scene/scene-graph.js +320 -0
  80. package/src/transform/transform.js +211 -0
  81. package/src/wasm/kernels-binary.js +3 -0
  82. package/src/wasm/kernels.js +385 -0
@@ -0,0 +1,238 @@
1
+ // The ES3D abstract syntax tree.
2
+ //
3
+ // Every surface syntax (markup, compact, JSON, binary) produces the same tree of
4
+ // Element / Comment nodes. Attribute values stay as raw strings in the AST so a
5
+ // document can be round-tripped losslessly; typed values are attached by the
6
+ // validator in `element.values` (keyed by canonical attribute name).
7
+
8
+ export class Attr {
9
+ constructor(name, value, nameStart = -1, nameEnd = -1, valueStart = -1, valueEnd = -1, quote = '"') {
10
+ this.name = name;
11
+ this.value = value;
12
+ this.nameStart = nameStart;
13
+ this.nameEnd = nameEnd;
14
+ this.valueStart = valueStart;
15
+ this.valueEnd = valueEnd;
16
+ this.quote = quote;
17
+ /** true when the raw value contained entity references (offsets inside the value are approximate) */
18
+ this.decoded = false;
19
+ /** pre-parsed typed value supplied by a decoder (the validator then skips parsing the text) */
20
+ this.typed = undefined;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Attribute whose typed value is known and whose text is produced on demand
26
+ * (binary decoding of large arrays: formatting a mesh as text only to parse
27
+ * it again would dominate the load time). Assigning a new text value drops
28
+ * the typed value.
29
+ */
30
+ export class LazyAttr extends Attr {
31
+ constructor(name, typed, format) {
32
+ super(name, null);
33
+ this.typed = typed;
34
+ this.format = format;
35
+ }
36
+
37
+ get value() {
38
+ if (this._value === null) this._value = this.format();
39
+ return this._value;
40
+ }
41
+
42
+ set value(v) {
43
+ this._value = v;
44
+ if (v !== null) this.typed = undefined;
45
+ }
46
+ }
47
+
48
+ export class Comment {
49
+ constructor(text, start = -1, end = -1) {
50
+ this.type = 'comment';
51
+ this.text = text;
52
+ this.start = start;
53
+ this.end = end;
54
+ this.parent = null;
55
+ }
56
+ }
57
+
58
+ export class Element {
59
+ constructor(name, start = -1) {
60
+ this.type = 'element';
61
+ this.name = name;
62
+ /** @type {Attr[]} */
63
+ this.attrs = [];
64
+ /** @type {(Element|Comment)[]} */
65
+ this.children = [];
66
+ this.text = null;
67
+ this.textStart = -1;
68
+ this.textEnd = -1;
69
+ this.start = start;
70
+ this.end = start;
71
+ this.nameStart = start;
72
+ this.nameEnd = start;
73
+ this.openEnd = start;
74
+ this.closeStart = -1;
75
+ this.selfClosing = true;
76
+ this.uid = 0;
77
+ this.parent = null;
78
+ /** canonical name -> typed value (set by the validator) */
79
+ this.values = null;
80
+ /** canonical name -> Attr (set by the validator) */
81
+ this.attrIndex = null;
82
+ }
83
+
84
+ attr(name) {
85
+ for (let i = 0; i < this.attrs.length; i++) if (this.attrs[i].name === name) return this.attrs[i].value;
86
+ return undefined;
87
+ }
88
+
89
+ attrNode(name) {
90
+ for (let i = 0; i < this.attrs.length; i++) if (this.attrs[i].name === name) return this.attrs[i];
91
+ return null;
92
+ }
93
+
94
+ setAttr(name, value) {
95
+ const a = this.attrNode(name);
96
+ if (a) a.value = String(value);
97
+ else this.attrs.push(new Attr(name, String(value)));
98
+ return this;
99
+ }
100
+
101
+ removeAttr(name) {
102
+ const i = this.attrs.findIndex((a) => a.name === name);
103
+ if (i >= 0) this.attrs.splice(i, 1);
104
+ return this;
105
+ }
106
+
107
+ appendChild(node) {
108
+ node.parent = this;
109
+ this.children.push(node);
110
+ this.selfClosing = false;
111
+ return node;
112
+ }
113
+
114
+ get elementChildren() {
115
+ return this.children.filter((c) => c.type === 'element');
116
+ }
117
+
118
+ /** The canonical id of this element, if any. */
119
+ get id() {
120
+ return this.values && this.values.id !== undefined ? this.values.id : this.attr('id');
121
+ }
122
+ }
123
+
124
+ export class Document {
125
+ constructor({ root, syntax, source = null, leading = [], trailing = [] }) {
126
+ /** @type {Element} */
127
+ this.root = root;
128
+ /** 'xml' | 'compact' | 'json' | 'binary' */
129
+ this.syntax = syntax;
130
+ this.source = source;
131
+ /** comments before / after the root element */
132
+ this.leading = leading;
133
+ this.trailing = trailing;
134
+ this.lineIndex = null;
135
+ this.diagnostics = [];
136
+ /** id -> Element (set by the validator) */
137
+ this.ids = new Map();
138
+ /** uid -> Element */
139
+ this.byUid = new Map();
140
+ this.elementCount = 0;
141
+ }
142
+
143
+ get errors() {
144
+ return this.diagnostics.filter((d) => d.severity === 'error');
145
+ }
146
+
147
+ get warnings() {
148
+ return this.diagnostics.filter((d) => d.severity === 'warning');
149
+ }
150
+
151
+ get ok() {
152
+ return !this.diagnostics.some((d) => d.severity === 'error');
153
+ }
154
+ }
155
+
156
+ /** Depth-first pre-order traversal of elements. Return false from fn to skip children. */
157
+ export function walk(el, fn, parent = null, depth = 0) {
158
+ if (fn(el, parent, depth) === false) return;
159
+ const kids = el.children;
160
+ for (let i = 0; i < kids.length; i++) {
161
+ const c = kids[i];
162
+ if (c.type === 'element') walk(c, fn, el, depth + 1);
163
+ }
164
+ }
165
+
166
+ /** Assign sequential uids and parent links; returns the number of elements. */
167
+ export function indexTree(doc) {
168
+ let uid = 0;
169
+ doc.byUid.clear();
170
+ const visit = (el, parent) => {
171
+ el.uid = ++uid;
172
+ el.parent = parent;
173
+ doc.byUid.set(el.uid, el);
174
+ for (const c of el.children) {
175
+ if (c.type === 'element') visit(c, el);
176
+ else c.parent = el;
177
+ }
178
+ };
179
+ if (doc.root) visit(doc.root, null);
180
+ doc.elementCount = uid;
181
+ return uid;
182
+ }
183
+
184
+ /** Deep copy of an element subtree without source positions or typed values. */
185
+ export function cloneElement(el, keepPositions = false) {
186
+ const copy = new Element(el.name, keepPositions ? el.start : -1);
187
+ for (const a of el.attrs) {
188
+ copy.attrs.push(keepPositions ? Object.assign(new Attr(a.name, a.value), a) : new Attr(a.name, a.value));
189
+ }
190
+ copy.text = el.text;
191
+ copy.selfClosing = el.selfClosing;
192
+ for (const c of el.children) {
193
+ if (c.type === 'element') copy.appendChild(cloneElement(c, keepPositions));
194
+ else copy.appendChild(new Comment(c.text));
195
+ }
196
+ copy.selfClosing = el.children.length === 0;
197
+ return copy;
198
+ }
199
+
200
+ /** Convenience constructor: h('box', {size: '2'}, ...children) */
201
+ export function h(name, attrs = {}, ...children) {
202
+ const el = new Element(name);
203
+ for (const [k, v] of Object.entries(attrs)) {
204
+ if (v === undefined || v === null) continue;
205
+ el.attrs.push(new Attr(k, String(v)));
206
+ }
207
+ for (const c of children.flat()) {
208
+ if (c === null || c === undefined || c === false) continue;
209
+ if (typeof c === 'string') el.text = (el.text || '') + c;
210
+ else el.appendChild(c);
211
+ }
212
+ el.selfClosing = el.children.length === 0 && el.text === null;
213
+ return el;
214
+ }
215
+
216
+ /** Structural equality of two subtrees (names, attributes, text, element children). */
217
+ export function treesEqual(a, b, { ignoreComments = true, attrOrder = false } = {}) {
218
+ if (a.name !== b.name) return false;
219
+ if ((a.text || '').trim() !== (b.text || '').trim()) return false;
220
+ if (a.attrs.length !== b.attrs.length) return false;
221
+ if (attrOrder) {
222
+ for (let i = 0; i < a.attrs.length; i++) {
223
+ if (a.attrs[i].name !== b.attrs[i].name || a.attrs[i].value !== b.attrs[i].value) return false;
224
+ }
225
+ } else {
226
+ for (const at of a.attrs) if (b.attr(at.name) !== at.value) return false;
227
+ }
228
+ const ka = ignoreComments ? a.children.filter((c) => c.type === 'element') : a.children;
229
+ const kb = ignoreComments ? b.children.filter((c) => c.type === 'element') : b.children;
230
+ if (ka.length !== kb.length) return false;
231
+ for (let i = 0; i < ka.length; i++) {
232
+ if (ka[i].type !== kb[i].type) return false;
233
+ if (ka[i].type === 'comment') {
234
+ if (ka[i].text !== kb[i].text) return false;
235
+ } else if (!treesEqual(ka[i], kb[i], { ignoreComments, attrOrder })) return false;
236
+ }
237
+ return true;
238
+ }
@@ -0,0 +1,93 @@
1
+ // Color parsing. ES3D colors are sRGB like CSS/SVG: #rgb, #rgba, #rrggbb,
2
+ // #rrggbbaa, rgb(r,g,b), rgba(r,g,b,a) and the 148 CSS named colors.
3
+ // Values are returned as [r, g, b, a] in 0..1 (sRGB, not linearized).
4
+
5
+ const NAMED =
6
+ 'aliceblue:f0f8ff,antiquewhite:faebd7,aqua:00ffff,aquamarine:7fffd4,azure:f0ffff,beige:f5f5dc,bisque:ffe4c4,' +
7
+ 'black:000000,blanchedalmond:ffebcd,blue:0000ff,blueviolet:8a2be2,brown:a52a2a,burlywood:deb887,cadetblue:5f9ea0,' +
8
+ 'chartreuse:7fff00,chocolate:d2691e,coral:ff7f50,cornflowerblue:6495ed,cornsilk:fff8dc,crimson:dc143c,cyan:00ffff,' +
9
+ 'darkblue:00008b,darkcyan:008b8b,darkgoldenrod:b8860b,darkgray:a9a9a9,darkgreen:006400,darkgrey:a9a9a9,' +
10
+ 'darkkhaki:bdb76b,darkmagenta:8b008b,darkolivegreen:556b2f,darkorange:ff8c00,darkorchid:9932cc,darkred:8b0000,' +
11
+ 'darksalmon:e9967a,darkseagreen:8fbc8f,darkslateblue:483d8b,darkslategray:2f4f4f,darkslategrey:2f4f4f,' +
12
+ 'darkturquoise:00ced1,darkviolet:9400d3,deeppink:ff1493,deepskyblue:00bfff,dimgray:696969,dimgrey:696969,' +
13
+ 'dodgerblue:1e90ff,firebrick:b22222,floralwhite:fffaf0,forestgreen:228b22,fuchsia:ff00ff,gainsboro:dcdcdc,' +
14
+ 'ghostwhite:f8f8ff,gold:ffd700,goldenrod:daa520,gray:808080,green:008000,greenyellow:adff2f,grey:808080,' +
15
+ 'honeydew:f0fff0,hotpink:ff69b4,indianred:cd5c5c,indigo:4b0082,ivory:fffff0,khaki:f0e68c,lavender:e6e6fa,' +
16
+ 'lavenderblush:fff0f5,lawngreen:7cfc00,lemonchiffon:fffacd,lightblue:add8e6,lightcoral:f08080,lightcyan:e0ffff,' +
17
+ 'lightgoldenrodyellow:fafad2,lightgray:d3d3d3,lightgreen:90ee90,lightgrey:d3d3d3,lightpink:ffb6c1,' +
18
+ 'lightsalmon:ffa07a,lightseagreen:20b2aa,lightskyblue:87cefa,lightslategray:778899,lightslategrey:778899,' +
19
+ 'lightsteelblue:b0c4de,lightyellow:ffffe0,lime:00ff00,limegreen:32cd32,linen:faf0e6,magenta:ff00ff,maroon:800000,' +
20
+ 'mediumaquamarine:66cdaa,mediumblue:0000cd,mediumorchid:ba55d3,mediumpurple:9370db,mediumseagreen:3cb371,' +
21
+ 'mediumslateblue:7b68ee,mediumspringgreen:00fa9a,mediumturquoise:48d1cc,mediumvioletred:c71585,' +
22
+ 'midnightblue:191970,mintcream:f5fffa,mistyrose:ffe4e1,moccasin:ffe4b5,navajowhite:ffdead,navy:000080,' +
23
+ 'oldlace:fdf5e6,olive:808000,olivedrab:6b8e23,orange:ffa500,orangered:ff4500,orchid:da70d6,palegoldenrod:eee8aa,' +
24
+ 'palegreen:98fb98,paleturquoise:afeeee,palevioletred:db7093,papayawhip:ffefd5,peachpuff:ffdab9,peru:cd853f,' +
25
+ 'pink:ffc0cb,plum:dda0dd,powderblue:b0e0e6,purple:800080,rebeccapurple:663399,red:ff0000,rosybrown:bc8f8f,' +
26
+ 'royalblue:4169e1,saddlebrown:8b4513,salmon:fa8072,sandybrown:f4a460,seagreen:2e8b57,seashell:fff5ee,' +
27
+ 'sienna:a0522d,silver:c0c0c0,skyblue:87ceeb,slateblue:6a5acd,slategray:708090,slategrey:708090,snow:fffafa,' +
28
+ 'springgreen:00ff7f,steelblue:4682b4,tan:d2b48c,teal:008080,thistle:d8bfd8,tomato:ff6347,turquoise:40e0d0,' +
29
+ 'violet:ee82ee,wheat:f5deb3,white:ffffff,whitesmoke:f5f5f5,yellow:ffff00,yellowgreen:9acd32';
30
+
31
+ export const NAMED_COLORS = new Map(NAMED.split(',').map((kv) => kv.split(':')));
32
+
33
+ const HEX = /^#([0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
34
+
35
+ /** Parse a color; returns [r,g,b,a] (0..1 sRGB) or null when the syntax is invalid. */
36
+ export function parseColor(str) {
37
+ const s = str.trim();
38
+ if (s[0] === '#') {
39
+ if (!HEX.test(s)) return null;
40
+ let h = s.slice(1);
41
+ if (h.length <= 4) h = [...h].map((c) => c + c).join('');
42
+ const n = h.length === 6 ? h + 'ff' : h;
43
+ return [0, 2, 4, 6].map((i) => parseInt(n.slice(i, i + 2), 16) / 255);
44
+ }
45
+ const lower = s.toLowerCase();
46
+ if (lower === 'transparent') return [0, 0, 0, 0];
47
+ const named = NAMED_COLORS.get(lower);
48
+ if (named) return parseColor('#' + named);
49
+ const m = /^rgba?\(\s*([^)]*)\)$/i.exec(s);
50
+ if (m) {
51
+ const parts = m[1].split(/\s*,\s*|\s+/).filter(Boolean);
52
+ if (parts.length !== 3 && parts.length !== 4) return null;
53
+ const out = [];
54
+ for (let i = 0; i < parts.length; i++) {
55
+ const p = parts[i];
56
+ let v;
57
+ if (p.endsWith('%')) v = Number(p.slice(0, -1)) / 100;
58
+ else v = i < 3 ? Number(p) / 255 : Number(p);
59
+ if (!Number.isFinite(v) || v < 0 || v > 1) return null;
60
+ out.push(v);
61
+ }
62
+ if (out.length === 3) out.push(1);
63
+ return out;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ export function srgbToLinear(c) {
69
+ return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
70
+ }
71
+
72
+ export function linearToSrgb(c) {
73
+ return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
74
+ }
75
+
76
+ /** [r,g,b,a] sRGB -> [r,g,b,a] linear (alpha untouched). */
77
+ export function colorToLinear(c) {
78
+ return [srgbToLinear(c[0]), srgbToLinear(c[1]), srgbToLinear(c[2]), c[3]];
79
+ }
80
+
81
+ /** Canonical lowercase hex form (#rrggbb or #rrggbbaa). */
82
+ export function colorToHex(c) {
83
+ const h = (v) => Math.round(Math.max(0, Math.min(1, v)) * 255).toString(16).padStart(2, '0');
84
+ const base = '#' + h(c[0]) + h(c[1]) + h(c[2]);
85
+ return c[3] !== undefined && c[3] < 1 ? base + h(c[3]) : base;
86
+ }
87
+
88
+ /** Shortest hex form (#rgb when possible). */
89
+ export function colorToShortHex(c) {
90
+ const hex = colorToHex(c);
91
+ if (hex.length === 7 && hex[1] === hex[2] && hex[3] === hex[4] && hex[5] === hex[6]) return '#' + hex[1] + hex[3] + hex[5];
92
+ return hex;
93
+ }
@@ -0,0 +1,171 @@
1
+ // Parser for the ES3D compact syntax: tokens -> the same AST as the markup syntax.
2
+ //
3
+ // Grammar (newlines are whitespace):
4
+ // document := comment* root
5
+ // root := 'es3d' header ( '{' statement* '}' | statement* )
6
+ // statement := element | comment | ';'
7
+ // element := NAME header ( '{' statement* '}' )?
8
+ // header := ('#' ID)? ('@' REF)? STRING? (NAME '=' VALUE)*
9
+
10
+ import { Attr, Comment, Document, Element } from './ast.js';
11
+ import { Diagnostic, ES3DError, LineIndex } from './errors.js';
12
+ import { CTok, CompactTokenizer } from './compact-tokenizer.js';
13
+
14
+ const ROOT_NAMES = new Set(['es3d', 'v3d']);
15
+
16
+ export function parseCompact(text, lineIndex = new LineIndex(text)) {
17
+ const tz = new CompactTokenizer(text, lineIndex);
18
+ const buf = [];
19
+ const peek = (k = 0) => {
20
+ while (buf.length <= k) buf.push(tz.next());
21
+ return buf[k];
22
+ };
23
+ const take = () => (buf.length ? buf.shift() : tz.next());
24
+ const fail = (code, message, offset, length = 1, extra = {}) => {
25
+ const d = new Diagnostic({ code, message, offset, length, ...extra });
26
+ d.locate(lineIndex);
27
+ throw new ES3DError([d], lineIndex);
28
+ };
29
+ const where = (offset) => {
30
+ const p = lineIndex.position(offset);
31
+ return `line ${p.line}, column ${p.column}`;
32
+ };
33
+
34
+ function parseHeader(el) {
35
+ let last = el.nameEnd;
36
+ for (;;) {
37
+ const t = peek();
38
+ if (t.type === CTok.ID || t.type === CTok.REF) {
39
+ take();
40
+ const name = t.type === CTok.ID ? 'id' : 'ref';
41
+ if (el.attrNode(name)) fail('E_DUPLICATE_ATTRIBUTE', `Duplicate attribute '${name}' on ${el.name}.`, t.start, t.end - t.start);
42
+ el.attrs.push(new Attr(name, t.value, t.start, t.start + 1, t.start + 1, t.end, t.type === CTok.ID ? '#' : '@'));
43
+ last = t.end;
44
+ } else if (t.type === CTok.STRING) {
45
+ take();
46
+ if (el.text !== null) fail('E_SYNTAX', `${el.name} already has text content.`, t.start, t.end - t.start);
47
+ el.text = t.value;
48
+ el.textStart = t.start;
49
+ el.textEnd = t.end;
50
+ last = t.end;
51
+ } else if (t.type === CTok.NAME && peek(1).type === CTok.EQ) {
52
+ take();
53
+ take();
54
+ const v = take();
55
+ if (v.type !== CTok.VALUE) fail('E_MISSING_VALUE', `Expected a value for attribute '${t.value}'.`, v.start, 1);
56
+ for (const prev of el.attrs) {
57
+ if (prev.name === t.value) fail('E_DUPLICATE_ATTRIBUTE', `Duplicate attribute '${t.value}' on ${el.name}.`, t.start, t.end - t.start);
58
+ }
59
+ const a = new Attr(t.value, v.value, t.start, t.end, v.valueStart, v.valueEnd, v.quote);
60
+ a.decoded = !!v.escaped;
61
+ el.attrs.push(a);
62
+ last = v.end;
63
+ } else {
64
+ break;
65
+ }
66
+ }
67
+ el.openEnd = last;
68
+ }
69
+
70
+ function parseStatements(parent, closeTok) {
71
+ for (;;) {
72
+ const t = peek();
73
+ if (t.type === CTok.EOF) {
74
+ if (closeTok) {
75
+ fail('E_UNCLOSED_ELEMENT', `Unclosed block of '${parent.name}' (opened at ${where(closeTok.start)}): missing '}'.`, closeTok.start, 1);
76
+ }
77
+ return;
78
+ }
79
+ if (t.type === CTok.RBRACE) {
80
+ if (!closeTok) fail('E_UNEXPECTED_CLOSE', "Unexpected '}': no block is open.", t.start, 1);
81
+ take();
82
+ parent.closeStart = t.start;
83
+ parent.end = t.end;
84
+ return;
85
+ }
86
+ if (t.type === CTok.SEMI) {
87
+ take();
88
+ continue;
89
+ }
90
+ if (t.type === CTok.COMMENT) {
91
+ take();
92
+ parent.appendChild(new Comment(t.text, t.start, t.end));
93
+ continue;
94
+ }
95
+ if (t.type === CTok.NAME) {
96
+ if (peek(1).type === CTok.EQ) {
97
+ fail('E_SYNTAX', `Attribute '${t.value}' must follow an element name.`, t.start, t.end - t.start, {
98
+ hint: 'Attributes belong to the element written before them on the same statement.',
99
+ });
100
+ }
101
+ parent.appendChild(parseElement());
102
+ continue;
103
+ }
104
+ if (t.type === CTok.LBRACE) fail('E_SYNTAX', "Unexpected '{': a block must follow an element name.", t.start, 1);
105
+ if (t.type === CTok.STRING || t.type === CTok.ID || t.type === CTok.REF) {
106
+ fail('E_SYNTAX', 'Expected an element name.', t.start, t.end - t.start);
107
+ }
108
+ fail('E_SYNTAX', 'Unexpected token.', t.start, Math.max(1, t.end - t.start));
109
+ }
110
+ }
111
+
112
+ function parseElement() {
113
+ const t = take();
114
+ const el = new Element(t.value, t.start);
115
+ el.nameStart = t.start;
116
+ el.nameEnd = t.end;
117
+ parseHeader(el);
118
+ el.end = el.openEnd;
119
+ if (peek().type === CTok.LBRACE) {
120
+ const open = take();
121
+ el.selfClosing = false;
122
+ parseStatements(el, open);
123
+ } else {
124
+ el.selfClosing = true;
125
+ }
126
+ return el;
127
+ }
128
+
129
+ const leading = [];
130
+ while (peek().type === CTok.COMMENT || peek().type === CTok.SEMI) {
131
+ const c = take();
132
+ if (c.type === CTok.COMMENT) leading.push(new Comment(c.text, c.start, c.end));
133
+ }
134
+ const first = peek();
135
+ if (first.type === CTok.EOF) fail('E_EMPTY_DOCUMENT', "Empty document: expected 'es3d version=1'.", first.start, 0);
136
+ if (first.type !== CTok.NAME || !ROOT_NAMES.has(first.value)) {
137
+ fail('E_COMPACT_ROOT', "An ES3D compact document must start with the root element 'es3d'.", first.start, Math.max(1, first.end - first.start), {
138
+ hint: "Begin the file with: es3d version=1",
139
+ });
140
+ }
141
+ const rt = take();
142
+ const root = new Element(rt.value, rt.start);
143
+ root.nameStart = rt.start;
144
+ root.nameEnd = rt.end;
145
+ parseHeader(root);
146
+ root.end = root.openEnd;
147
+ const trailing = [];
148
+ if (peek().type === CTok.LBRACE) {
149
+ const open = take();
150
+ root.selfClosing = false;
151
+ parseStatements(root, open);
152
+ for (;;) {
153
+ const t = peek();
154
+ if (t.type === CTok.EOF) break;
155
+ if (t.type === CTok.COMMENT) {
156
+ take();
157
+ trailing.push(new Comment(t.text, t.start, t.end));
158
+ } else if (t.type === CTok.SEMI) take();
159
+ else fail('E_MULTIPLE_ROOTS', 'Content after the end of the root block.', t.start, Math.max(1, t.end - t.start));
160
+ }
161
+ } else {
162
+ // Header form: everything after the root header belongs to the root.
163
+ root.headerForm = true;
164
+ parseStatements(root, null);
165
+ root.selfClosing = root.children.length === 0;
166
+ root.end = text.length;
167
+ }
168
+ const doc = new Document({ root, syntax: 'compact', source: text, leading, trailing });
169
+ doc.lineIndex = lineIndex;
170
+ return doc;
171
+ }
@@ -0,0 +1,165 @@
1
+ // Tokenizer for the ES3D compact syntax ("ES3D-C").
2
+ //
3
+ // es3d version=1
4
+ // material#red c=#e53935
5
+ // box s=2 m=red
6
+ // group p=0,2,0 { sphere r=1 }
7
+ // use @tree p=10,0,5
8
+ //
9
+ // Newlines are insignificant: an element header ends where the next token is
10
+ // not an attribute (NAME '='), so the grammar is LL(2) and needs no schema.
11
+
12
+ import { Diagnostic, ES3DError } from './errors.js';
13
+
14
+ export const CTok = Object.freeze({
15
+ NAME: 'name',
16
+ ID: 'id', // #name
17
+ REF: 'ref', // @name
18
+ EQ: 'eq',
19
+ VALUE: 'value', // bare or quoted attribute value
20
+ STRING: 'string', // quoted text content in header position
21
+ LBRACE: 'lbrace',
22
+ RBRACE: 'rbrace',
23
+ SEMI: 'semi',
24
+ COMMENT: 'comment',
25
+ EOF: 'eof',
26
+ });
27
+
28
+ function isSpace(c) {
29
+ return c === 32 || c === 10 || c === 9 || c === 13;
30
+ }
31
+ function isNameStart(c) {
32
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95;
33
+ }
34
+ function isNameChar(c) {
35
+ return isNameStart(c) || (c >= 48 && c <= 57) || c === 45 || c === 46 || c === 58;
36
+ }
37
+ // characters that terminate a bare value
38
+ function isValueStop(c) {
39
+ return isSpace(c) || c === 123 || c === 125 || c === 59 || c === 34;
40
+ }
41
+
42
+ export class CompactTokenizer {
43
+ constructor(text, lineIndex = null) {
44
+ this.s = text;
45
+ this.n = text.length;
46
+ this.i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
47
+ this.lineIndex = lineIndex;
48
+ this.afterEq = false;
49
+ }
50
+
51
+ fail(code, message, offset, length = 1, extra = {}) {
52
+ const d = new Diagnostic({ code, message, offset, length, ...extra });
53
+ d.locate(this.lineIndex);
54
+ throw new ES3DError([d], this.lineIndex);
55
+ }
56
+
57
+ readQuoted(start) {
58
+ const s = this.s;
59
+ let i = start + 1;
60
+ let out = '';
61
+ let segStart = i;
62
+ for (;;) {
63
+ if (i >= this.n) this.fail('E_UNTERMINATED_STRING', 'Unterminated string: missing closing quote.', start, 1);
64
+ const c = s.charCodeAt(i);
65
+ if (c === 34) break;
66
+ if (c === 92) {
67
+ out += s.slice(segStart, i);
68
+ const e = s[i + 1];
69
+ if (e === '"' || e === '\\') out += e;
70
+ else if (e === 'n') out += '\n';
71
+ else if (e === 't') out += '\t';
72
+ else this.fail('E_BAD_ESCAPE', `Unknown escape sequence '\\${e ?? ''}'. Use \\" \\\\ \\n or \\t.`, i, 2);
73
+ i += 2;
74
+ segStart = i;
75
+ continue;
76
+ }
77
+ i++;
78
+ }
79
+ out += s.slice(segStart, i);
80
+ return { value: out, end: i + 1, escaped: segStart !== start + 1 };
81
+ }
82
+
83
+ next() {
84
+ const s = this.s;
85
+ let i = this.i;
86
+ while (i < this.n && isSpace(s.charCodeAt(i))) i++;
87
+ if (i >= this.n) {
88
+ this.i = i;
89
+ if (this.afterEq) this.fail('E_MISSING_VALUE', "Expected a value after '='.", i, 0);
90
+ return { type: CTok.EOF, start: i, end: i };
91
+ }
92
+ const c = s.charCodeAt(i);
93
+ const start = i;
94
+
95
+ if (this.afterEq) {
96
+ this.afterEq = false;
97
+ if (c === 34) {
98
+ const q = this.readQuoted(i);
99
+ this.i = q.end;
100
+ return { type: CTok.VALUE, value: q.value, start, end: q.end, valueStart: start + 1, valueEnd: q.end - 1, quote: '"', escaped: q.escaped };
101
+ }
102
+ if (c === 123 || c === 125 || c === 59) this.fail('E_MISSING_VALUE', "Expected a value after '='.", i, 1);
103
+ while (i < this.n && !isValueStop(s.charCodeAt(i))) i++;
104
+ this.i = i;
105
+ return { type: CTok.VALUE, value: s.slice(start, i), start, end: i, valueStart: start, valueEnd: i, quote: '' };
106
+ }
107
+
108
+ // comments
109
+ if (c === 47) {
110
+ const c2 = s.charCodeAt(i + 1);
111
+ if (c2 === 47) {
112
+ let end = s.indexOf('\n', i);
113
+ if (end < 0) end = this.n;
114
+ this.i = end;
115
+ return { type: CTok.COMMENT, text: s.slice(i + 2, end).replace(/\r$/, ''), start, end, line: true };
116
+ }
117
+ if (c2 === 42) {
118
+ const end = s.indexOf('*/', i + 2);
119
+ if (end < 0) this.fail('E_UNTERMINATED_COMMENT', "Unterminated comment: missing '*/'.", i, 2);
120
+ this.i = end + 2;
121
+ return { type: CTok.COMMENT, text: s.slice(i + 2, end), start, end: end + 2, line: false };
122
+ }
123
+ }
124
+ switch (c) {
125
+ case 123:
126
+ this.i = i + 1;
127
+ return { type: CTok.LBRACE, start, end: i + 1 };
128
+ case 125:
129
+ this.i = i + 1;
130
+ return { type: CTok.RBRACE, start, end: i + 1 };
131
+ case 59:
132
+ this.i = i + 1;
133
+ return { type: CTok.SEMI, start, end: i + 1 };
134
+ case 61:
135
+ this.i = i + 1;
136
+ this.afterEq = true;
137
+ return { type: CTok.EQ, start, end: i + 1 };
138
+ case 34: {
139
+ const q = this.readQuoted(i);
140
+ this.i = q.end;
141
+ return { type: CTok.STRING, value: q.value, start, end: q.end, valueStart: start + 1, valueEnd: q.end - 1 };
142
+ }
143
+ case 35: // #id
144
+ case 64: {
145
+ // @ref
146
+ let j = i + 1;
147
+ if (!isNameStart(s.charCodeAt(j))) {
148
+ this.fail('E_SYNTAX', c === 35 ? "Expected an id after '#'." : "Expected a reference id after '@'.", i, 1);
149
+ }
150
+ while (j < this.n && isNameChar(s.charCodeAt(j))) j++;
151
+ this.i = j;
152
+ return { type: c === 35 ? CTok.ID : CTok.REF, value: s.slice(i + 1, j), start, end: j };
153
+ }
154
+ default:
155
+ break;
156
+ }
157
+ if (isNameStart(c)) {
158
+ let j = i + 1;
159
+ while (j < this.n && isNameChar(s.charCodeAt(j))) j++;
160
+ this.i = j;
161
+ return { type: CTok.NAME, value: s.slice(i, j), start, end: j };
162
+ }
163
+ this.fail('E_SYNTAX', `Unexpected character '${s[i]}'.`, i, 1);
164
+ }
165
+ }