@margoengine/loaders 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/NOTICE +4 -0
- package/README.md +1665 -2
- package/dist/3dm.d.ts +161 -0
- package/dist/3dm.js +289 -0
- package/dist/3ds.d.ts +124 -0
- package/dist/3ds.js +392 -0
- package/dist/acclaim.d.ts +90 -0
- package/dist/acclaim.js +312 -0
- package/dist/amf.d.ts +45 -0
- package/dist/amf.js +256 -0
- package/dist/babylon.d.ts +197 -0
- package/dist/babylon.js +701 -0
- package/dist/common.d.ts +7 -0
- package/dist/common.js +6 -0
- package/dist/crease.d.ts +7 -0
- package/dist/crease.js +67 -0
- package/dist/dae-animation.d.ts +66 -0
- package/dist/dae-animation.js +266 -0
- package/dist/dae-common.d.ts +95 -0
- package/dist/dae-common.js +226 -0
- package/dist/dae-controllers.d.ts +57 -0
- package/dist/dae-controllers.js +164 -0
- package/dist/dae-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -0
- package/dist/dae-pose.d.ts +131 -0
- package/dist/dae-pose.js +381 -0
- package/dist/dae-scene.d.ts +203 -0
- package/dist/dae-scene.js +279 -0
- package/dist/dae.d.ts +166 -0
- package/dist/dae.js +644 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- package/dist/dxf-hatch.d.ts +8 -0
- package/dist/dxf-hatch.js +346 -0
- package/dist/dxf-leaders.d.ts +59 -0
- package/dist/dxf-leaders.js +258 -0
- package/dist/dxf.d.ts +122 -0
- package/dist/dxf.js +985 -0
- package/dist/engine.d.ts +41 -0
- package/dist/engine.js +120 -0
- package/dist/font-opentype.d.ts +14 -0
- package/dist/font-opentype.js +33 -0
- package/dist/font-woff.d.ts +23 -0
- package/dist/font-woff.js +293 -0
- package/dist/font.d.ts +41 -0
- package/dist/font.js +26 -0
- package/dist/gcode.d.ts +92 -0
- package/dist/gcode.js +369 -0
- package/dist/geo-model.d.ts +84 -0
- package/dist/geo-model.js +220 -0
- package/dist/geo-mvt.d.ts +15 -0
- package/dist/geo-mvt.js +302 -0
- package/dist/geo-shp.d.ts +15 -0
- package/dist/geo-shp.js +234 -0
- package/dist/geo-xml.d.ts +6 -0
- package/dist/geo-xml.js +165 -0
- package/dist/geo.d.ts +8 -0
- package/dist/geo.js +59 -0
- package/dist/geometry.d.ts +60 -0
- package/dist/geometry.js +273 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +28 -0
- package/dist/kmz.d.ts +78 -0
- package/dist/kmz.js +173 -0
- package/dist/las.d.ts +92 -0
- package/dist/las.js +110 -0
- package/dist/ldraw.d.ts +118 -0
- package/dist/ldraw.js +474 -0
- package/dist/load.d.ts +72 -0
- package/dist/load.js +205 -0
- package/dist/lottie.d.ts +154 -0
- package/dist/lottie.js +893 -0
- package/dist/lwo.d.ts +81 -0
- package/dist/lwo.js +454 -0
- package/dist/lzf.d.ts +13 -0
- package/dist/lzf.js +56 -0
- package/dist/materialx.d.ts +120 -0
- package/dist/materialx.js +563 -0
- package/dist/md2.d.ts +52 -0
- package/dist/md2.js +112 -0
- package/dist/mmcif.d.ts +14 -0
- package/dist/mmcif.js +246 -0
- package/dist/mmd.d.ts +244 -0
- package/dist/mmd.js +958 -0
- package/dist/mocap.d.ts +71 -0
- package/dist/mocap.js +178 -0
- package/dist/molecule-common.d.ts +4 -0
- package/dist/molecule-common.js +54 -0
- package/dist/mtl.d.ts +125 -0
- package/dist/mtl.js +550 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +70 -0
- package/dist/nrrd.js +785 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +145 -0
- package/dist/obj.js +462 -0
- package/dist/off.d.ts +10 -0
- package/dist/off.js +155 -0
- package/dist/outline-font.d.ts +87 -0
- package/dist/outline-font.js +110 -0
- package/dist/outline.d.ts +20 -0
- package/dist/outline.js +215 -0
- package/dist/pcd.d.ts +34 -0
- package/dist/pcd.js +258 -0
- package/dist/pdb.d.ts +67 -0
- package/dist/pdb.js +126 -0
- package/dist/ply.d.ts +35 -0
- package/dist/ply.js +392 -0
- package/dist/polygon.d.ts +9 -0
- package/dist/polygon.js +49 -0
- package/dist/prwm.d.ts +24 -0
- package/dist/prwm.js +114 -0
- package/dist/render.d.ts +32 -0
- package/dist/render.js +181 -0
- package/dist/sfnt-cff.d.ts +37 -0
- package/dist/sfnt-cff.js +749 -0
- package/dist/sfnt-layout.d.ts +24 -0
- package/dist/sfnt-layout.js +266 -0
- package/dist/sfnt-reader.d.ts +28 -0
- package/dist/sfnt-reader.js +87 -0
- package/dist/sfnt-variation.d.ts +40 -0
- package/dist/sfnt-variation.js +318 -0
- package/dist/shared/asset-url.js +82 -0
- package/dist/shared/crc32.d.ts +2 -0
- package/dist/shared/crc32.js +47 -0
- package/dist/shared/errors.js +36 -0
- package/dist/shared/inflate.js +284 -0
- package/dist/shared/normals.js +26 -0
- package/dist/shared/scene-scope.js +56 -0
- package/dist/shared/trailing-data.js +45 -0
- package/dist/stl.d.ts +64 -0
- package/dist/stl.js +309 -0
- package/dist/svg.d.ts +90 -0
- package/dist/svg.js +1007 -0
- package/dist/tds.d.ts +2 -0
- package/dist/tds.js +2 -0
- package/dist/textures.d.ts +42 -0
- package/dist/textures.js +53 -0
- package/dist/threemf-beam-reader.d.ts +19 -0
- package/dist/threemf-beam-reader.js +165 -0
- package/dist/threemf-beams.d.ts +52 -0
- package/dist/threemf-beams.js +268 -0
- package/dist/threemf-boolean-read.d.ts +10 -0
- package/dist/threemf-boolean-read.js +113 -0
- package/dist/threemf-boolean.d.ts +59 -0
- package/dist/threemf-boolean.js +20 -0
- package/dist/threemf-csg.d.ts +14 -0
- package/dist/threemf-csg.js +193 -0
- package/dist/threemf-displacement-read.d.ts +8 -0
- package/dist/threemf-displacement-read.js +213 -0
- package/dist/threemf-displacement.d.ts +71 -0
- package/dist/threemf-displacement.js +18 -0
- package/dist/threemf-evaluate.d.ts +36 -0
- package/dist/threemf-evaluate.js +86 -0
- package/dist/threemf-functions.d.ts +33 -0
- package/dist/threemf-functions.js +359 -0
- package/dist/threemf-lattice-mesh.d.ts +9 -0
- package/dist/threemf-lattice-mesh.js +115 -0
- package/dist/threemf-lattice.d.ts +139 -0
- package/dist/threemf-lattice.js +379 -0
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +162 -0
- package/dist/threemf-materials.js +497 -0
- package/dist/threemf-mesh.d.ts +75 -0
- package/dist/threemf-mesh.js +422 -0
- package/dist/threemf-secure.d.ts +50 -0
- package/dist/threemf-secure.js +153 -0
- package/dist/threemf-tessellate.d.ts +37 -0
- package/dist/threemf-tessellate.js +277 -0
- package/dist/threemf-volume-colour.d.ts +25 -0
- package/dist/threemf-volume-colour.js +233 -0
- package/dist/threemf-volume-sample.d.ts +8 -0
- package/dist/threemf-volume-sample.js +65 -0
- package/dist/threemf-volumetric-read.d.ts +15 -0
- package/dist/threemf-volumetric-read.js +539 -0
- package/dist/threemf-volumetric.d.ts +177 -0
- package/dist/threemf-volumetric.js +28 -0
- package/dist/threemf.d.ts +170 -0
- package/dist/threemf.js +609 -0
- package/dist/tilt.d.ts +62 -0
- package/dist/tilt.js +186 -0
- package/dist/tmx.d.ts +151 -0
- package/dist/tmx.js +394 -0
- package/dist/ttf.d.ts +78 -0
- package/dist/ttf.js +568 -0
- package/dist/types.d.ts +108 -0
- package/dist/types.js +35 -0
- package/dist/usd.d.ts +2 -0
- package/dist/usd.js +2 -0
- package/dist/usd.worker.d.ts +1 -0
- package/dist/usdz.d.ts +50 -0
- package/dist/usdz.js +646 -0
- package/dist/util.d.ts +75 -0
- package/dist/util.js +241 -0
- package/dist/vdb.d.ts +111 -0
- package/dist/vdb.js +663 -0
- package/dist/vrml.d.ts +53 -0
- package/dist/vrml.js +532 -0
- package/dist/vtk-cells.d.ts +29 -0
- package/dist/vtk-cells.js +211 -0
- package/dist/vtk-legacy.d.ts +57 -0
- package/dist/vtk-legacy.js +439 -0
- package/dist/vtk-reader.d.ts +19 -0
- package/dist/vtk-reader.js +134 -0
- package/dist/vtk-xml.d.ts +96 -0
- package/dist/vtk-xml.js +578 -0
- package/dist/vtk.d.ts +13 -0
- package/dist/vtk.js +234 -0
- package/dist/woff-glyf.d.ts +17 -0
- package/dist/woff-glyf.js +215 -0
- package/dist/worker.d.ts +10 -0
- package/dist/worker.js +93 -0
- package/dist/workers/usd.js +3 -0
- package/dist/xfile.d.ts +99 -0
- package/dist/xfile.js +706 -0
- package/dist/xml.d.ts +107 -0
- package/dist/xml.js +843 -0
- package/dist/xyz.d.ts +16 -0
- package/dist/xyz.js +110 -0
- package/dist/zip.d.ts +38 -0
- package/dist/zip.js +150 -0
- package/package.json +289 -4
package/README.md
CHANGED
|
@@ -1,3 +1,1666 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/loaders
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
PLY, STL, 3MF, PCD, OFF, XYZ, OBJ/MTL, COLLADA, Tiled TMX, VTK, NRRD, LDraw, Rhino 3DM, 3DS, LWO, AMF, MD2, PDB, KMZ, NURBS, LAS, OpenVDB, MaterialX, Lottie, static USDA/USDZ, SVG and TrueType font loaders for Margo Engine.
|
|
4
|
+
|
|
5
|
+
`@margoengine/loaders/vtk-xml` also exposes `openVTKXMLDataset` for lazy numeric arrays and intact volume
|
|
6
|
+
topology in `.vtu`, `.vti`, `.vts` and `.vtp`. It shares every decoder with `parseVTKXML`; it does not construct
|
|
7
|
+
or triangulate geometry. Metadata and arrays stay separated by piece. Array `read(signal?)` returns owned
|
|
8
|
+
float64 values. `maxBytes` defaults to 256 MiB per decoded array. A `readAppended(offset, length, signal)`
|
|
9
|
+
callback supplies raw binary bytes relative to the appended underscore, enabling range loading from an
|
|
10
|
+
immutable file. Inline/base64 payloads must be in the supplied bytes. `signal` cancels all lazy reads.
|
|
11
|
+
A piece of a `.vtr` RectilinearGrid gives `coordinates`, its three axis arrays in x, y, z order, whether or not the file names them.
|
|
12
|
+
Unknown byte orders and integers beyond exact JavaScript number precision reject instead of silently corrupting data.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { openVTKXMLDataset } from '@margoengine/loaders/vtk-xml';
|
|
16
|
+
|
|
17
|
+
const bytes = new TextEncoder().encode(`<VTKFile type="ImageData"><ImageData WholeExtent="0 1 0 0 0 0">
|
|
18
|
+
<Piece Extent="0 1 0 0 0 0"><PointData><DataArray type="Float32" Name="wind">2 3</DataArray>
|
|
19
|
+
</PointData></Piece></ImageData></VTKFile>`);
|
|
20
|
+
const dataset = openVTKXMLDataset(bytes);
|
|
21
|
+
console.log(await dataset.pieces[0].pointData.wind.read());
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Import `margoengine/loaders` from the `margoengine` package, or `@margoengine/loaders` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
25
|
+
|
|
26
|
+
PLY, STL, 3MF, DXF, PCD, OFF, XYZ, OBJ/MTL, COLLADA, Tiled TMX, legacy VTK and static USDA/USDZ loaders for Margo Engine, each tree-shakable on its own, plus three optional entries: TrueType fonts and extruded 3D text (`@margoengine/loaders/font`), SVG (`@margoengine/loaders/svg`) and OBJ meshes with their MTL materials and textures (`@margoengine/loaders/mtl`).
|
|
27
|
+
|
|
28
|
+
Packages that read their own formats import the shared parts without the other parsers: `@margoengine/loaders/common`
|
|
29
|
+
(`LoaderError`, `fetchBytes`, `fetchResource`, `isPrivateHost`, `readZipDirectory`, `readZipEntry`, `crc32`, `computeVertexNormals`, `faceNormal` and
|
|
30
|
+
the shared types) and `@margoengine/loaders/usd` (`parseUSDA`, `parseUSDZ`, `readUSDA`). Both are also on the root.
|
|
31
|
+
|
|
32
|
+
Build from source with `npm run build` in `packages/loaders`.
|
|
33
|
+
|
|
34
|
+
Real big-endian PLY evidence includes the complete VTK horse: 48,485 vertices and 96,966 triangles. Every position, RGB component and index matches independently recorded python-plyfile 1.1.3 output exactly. The file has white vertex colors and a skipped confidence property; this does not prove varying-color, normal or UV accuracy. From a built clone, fetch the required original file and its licences with `node scripts/reference-rendering/fetch-skip-assets.mjs`, then run `node --test packages/loaders/tests/ply-outside.test.js`. Missing, changed and LFS-only inputs fail. The source, licences and oracle hashes are recorded in `tests/fixtures/horse-oracle.json`, the required external manifest and `THIRD-PARTY-NOTICES.md`.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import {Engine} from 'margoengine/core';
|
|
38
|
+
import {load, parse3MF, parsePLY, createMeshes, toGeometry} from 'margoengine/loaders';
|
|
39
|
+
import {createMesh} from 'margoengine/materials';
|
|
40
|
+
import {box} from 'margoengine/core';
|
|
41
|
+
const signal = AbortSignal.timeout(30_000);
|
|
42
|
+
const canvas = document.querySelector('canvas')!;
|
|
43
|
+
|
|
44
|
+
const engine = await Engine.create(canvas);
|
|
45
|
+
const mesh = engine.createMesh().setGeometry(box());
|
|
46
|
+
|
|
47
|
+
// Fetch with a size limit and an AbortSignal, then parse. Limits go to the parser too.
|
|
48
|
+
const model = await load('/parts/bracket.3mf', parse3MF, {signal, maxBytes: 64 << 20, maxTriangles: 2_000_000});
|
|
49
|
+
const {meshes, dispose} = createMeshes(engine, model); // one mesh + PbrMaterial per object color
|
|
50
|
+
|
|
51
|
+
// Or parse bytes you already have and build a core Geometry yourself.
|
|
52
|
+
const file = await fetch('/scans/part.ply');
|
|
53
|
+
const scan = parsePLY(await file.arrayBuffer());
|
|
54
|
+
mesh.setGeometry(toGeometry(scan, {normals: 'smooth'}));
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Every parser returns the same `LoadedGeometry`:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
{kind: 'mesh' | 'points', positions: Float32Array, normals?, colors? /* sRGB 0..1 */, uvs?, indices?: Uint32Array,
|
|
61
|
+
groups?: {start, count, name?, objectId?, color?: [r, g, b, a]}[], attributes?: Record<string, Float32Array>}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
| Function | Reads |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `parsePLY` (also alone from `/ply`) | ASCII, binary little and big endian; x y z, nx ny nz, red green blue (uchar, ushort or float), s/t, u/v, texture_u/texture_v; polygon faces fan-triangulated; `edge` elements (`vertex1`, `vertex2`) as `lineIndices`; files without faces become point clouds; unknown elements and properties skipped |
|
|
67
|
+
| `parseSTL` | See [STL](#stl) |
|
|
68
|
+
| `parse3MF` (async) | Own ZIP reader (stored and deflate through `DecompressionStream('deflate-raw')`, CRC-32 checked); objects, meshes, components, build items, 3x4 transforms; `basematerials` and materials-extension `colorgroup` colors; production extension (parts named by path, UUIDs, alternative representations); unit conversion to meters |
|
|
69
|
+
| `parseDXF` | ASCII and binary DXF, every version: `$INSUNITS` to meters, LAYER colours and off/frozen layers, ACI and true colours (BYLAYER, BYBLOCK), blocks through INSERT (scale, rotation, rows and columns, nested) and DIMENSION; faces from 3DFACE, SOLID, TRACE, polyface and polygon-mesh POLYLINEs and MESH; line segments from LINE, LWPOLYLINE and 2D/3D POLYLINE (bulge arcs), ARC, CIRCLE, ELLIPSE and SPLINE (NURBS), and MLINE (each element along the vertices' miters, with its breaks; the style's caps, fill and element colours are not read), in each entity's object coordinate system; [LEADER and MULTILEADER](#dxf-leaders) with their arrows, text and block content; POINT, TEXT and MTEXT (formatting and `%%` control codes resolved); [block attributes](#dxf-block-attributes) in `texts`; 3DSOLID, BODY and REGION ACIS data decoded to SAT text. `HATCH` with [`readDXFHatch`](#dxf-hatches). Returns `{mesh, lines, points, texts, layers, solids, unit, version, skipped}`; draw `lines` with `@margoengine/lines` (`mode: 'segments'`) and the mesh double-sided (DXF faces have no winding) |
|
|
70
|
+
| `parsePCD` | `DATA ascii`, `binary`, `binary_compressed` (own LZF decompressor); x y z, normal_x/y/z, packed `rgb`/`rgba`, `intensity`, any other field skipped |
|
|
71
|
+
| `parseOFF` (also alone from `/off`) | `OFF` with `ST`, `C`, `N` prefixes (texture coordinates, colors 0..1 or 0..255, normals), ASCII or big-endian binary; a face's colour or colormap index is kept in its group |
|
|
72
|
+
| `parseXYZ` | xyz, xyz+rgb, xyz+normal, xyz+normal+rgb, xyz+intensity, PTS (xyz+intensity+rgb), chemistry XYZ |
|
|
73
|
+
| `parseVTK` | `# vtk DataFile Version` 1.0 to 5.1, ASCII or BINARY `DATASET POLYDATA`: POINTS, POLYGONS (convex ones fanned, concave ones ear-clipped), TRIANGLE_STRIPS, 5.x OFFSETS/CONNECTIVITY, point NORMALS, COLOR_SCALARS, TEXTURE_COORDINATES (v = 1 - t, as VTK puts t = 0 at the image's bottom), SCALARS |
|
|
74
|
+
| `parseOBJ` (async), `parseMTL` | See [OBJ and MTL](#obj-and-mtl) |
|
|
75
|
+
| `parseDAE`, `flattenDAE` | See [COLLADA](#collada) |
|
|
76
|
+
| `parseDAEKinematics`, `poseDAEJoints` (`/dae-kinematics`) | See [Collada kinematics](#collada-kinematics) |
|
|
77
|
+
| `parseTMX` (async), `tmxLayerQuads` | See [Tiled TMX](#tiled-tmx) |
|
|
78
|
+
| `parseTTF`, `textGeometry` (`/font`) | See [Fonts and 3D text](#fonts-and-3d-text) |
|
|
79
|
+
| `parseSVG` (`/svg`) | See [SVG](#svg) |
|
|
80
|
+
| `parseBVH` (`/mocap`) | See [Motion capture](#motion-capture-bvh) |
|
|
81
|
+
| `parseASF`, `parseAMC` (`/mocap`) | See [Acclaim and CMU motion capture](#acclaim-and-cmu-motion-capture-asf-and-amc) |
|
|
82
|
+
| `parseVRML`, `parseX3D` (`/vrml`) | See [VRML and X3D](#vrml-and-x3d) |
|
|
83
|
+
| `parsePRWM` (`/prwm`) | See [PRWM](#prwm) |
|
|
84
|
+
| `parseTilt` (`/tilt`, async) | See [Tilt Brush](#tilt-brush) |
|
|
85
|
+
| `parseBabylon`, `flattenBabylon` (`/babylon`) | See [Babylon scenes](#babylon-scenes) |
|
|
86
|
+
| `parseX` (`/xfile`) | See [DirectX .x files](#directx-x-files) |
|
|
87
|
+
| `parsePMD`, `parsePMX`, `parseMMD`, `parseVMD`, `sampleVMDBone` (`/mmd`) | See [MikuMikuDance](#mikumikudance-models-and-motions) |
|
|
88
|
+
| `parseGCode`, `toolpathBeads` (`/gcode`) | See [G-code](#g-code) |
|
|
89
|
+
| `parseVDB` (`/vdb`, async) | See [VDB volumes](#vdb-volumes) |
|
|
90
|
+
| `parseMaterialX` (`/materialx`) | See [MaterialX](#materialx) |
|
|
91
|
+
| `parseLottie` (`/lottie`) | See [Lottie](#lottie) |
|
|
92
|
+
| `parseNRRD` (`/nrrd`, async) | See [NRRD volumes](#nrrd-volumes) |
|
|
93
|
+
| `parseLDraw` (`/ldraw`, async) | See [LDraw](#ldraw) |
|
|
94
|
+
| `parse3MFMaterials` (`/threemf-materials`, async) | See [3MF textures and colour groups](#3mf-textures-and-colour-groups) |
|
|
95
|
+
| `create3MFMesh` (`/threemf-mesh`, async) | Draws that result, layer stacks included; see [Drawing it](#drawing-it-create3mfmesh) |
|
|
96
|
+
| `parseVTKXML` (`/vtk-xml`, async) | See [VTK XML](#vtk-xml) |
|
|
97
|
+
| `parseVTKLegacy` (`/vtk-legacy`) | See [Legacy VTK datasets](#legacy-vtk-datasets-vtk-legacy) |
|
|
98
|
+
| `parseGeoJSON`, `parseShapefile`, `parseGPX`, `parseKML`, `parseMVT` (`/geo`) | See [Maps, tracks and vector tiles](#maps-tracks-and-vector-tiles-geo) |
|
|
99
|
+
| `parseMMCIF` (`/mmcif`) | See [mmCIF structures](#mmcif-structures-mmcif) |
|
|
100
|
+
| `parse3MFLattice` (`/threemf-lattice`, async) | See [3MF lattices and slices as data](#3mf-lattices-and-slices-as-data-threemf-lattice) |
|
|
101
|
+
| `parse3DM` (`/3dm`) | See [Rhino 3DM](#rhino-3dm) |
|
|
102
|
+
| `parse3DS` (`/3ds`), `parseTDS` (`/tds`) | See [3DS, LWO, AMF, MD2, PDB and KMZ](#3ds-lwo-amf-md2-pdb-and-kmz) |
|
|
103
|
+
| `parseLWO` (`/lwo`), `parseAMF` (`/amf`, async), `parseMD2` (`/md2`) | See [3DS, LWO, AMF, MD2, PDB and KMZ](#3ds-lwo-amf-md2-pdb-and-kmz) |
|
|
104
|
+
| `parsePDB` (`/pdb`), `parseKMZ` (`/kmz`, async) | See [3DS, LWO, AMF, MD2, PDB and KMZ](#3ds-lwo-amf-md2-pdb-and-kmz) |
|
|
105
|
+
| `loadTextures` (`/textures`, async) | See [3DS, LWO, AMF, MD2, PDB and KMZ](#3ds-lwo-amf-md2-pdb-and-kmz) |
|
|
106
|
+
| `evaluateNurbsCurve`, `tessellateNurbsCurve`, `evaluateNurbsSurface`, `tessellateNurbsSurface` (`/nurbs`) | See [NURBS curves and surfaces](#nurbs-curves-and-surfaces) |
|
|
107
|
+
| `parseLAS` (`/las`, async) | See [LAS and LAZ](#las-and-laz) |
|
|
108
|
+
| `loadOBJ`, `createMTLMaterials`, `createOBJMesh` (`/mtl`) | See [Textured OBJ meshes](#textured-obj-meshes) |
|
|
109
|
+
|
|
110
|
+
Helpers: `toGeometry` (core `Geometry`, flat or smooth normals when missing, per group), `toGeometries` (the same, split into parts of at most 11,184,810 vertices, core's limit, or `maxPartVertices`, with seam-free normals), `splitTriangles`, `pointsToGeometry` (octahedron markers for clouds), `createMeshes` (engine meshes with `PbrMaterial` colors), `load` / `fetchBytes`, `detectFormat` / `parseAny`, `computeVertexNormals`, `decompressLZF`, `readZipDirectory` / `readZipEntry` / `crc32`, `parsePLYHeader`, `parsePCDHeader`.
|
|
111
|
+
|
|
112
|
+
## How it works
|
|
113
|
+
|
|
114
|
+
- **One module per format.** The build is a plain TypeScript emit with `"sideEffects": false`, so importing `parsePLY` pulls in only the PLY reader and its helpers, not the 3MF, ZIP or XML code. In the main entry only `toGeometry`, `pointsToGeometry` and `createMeshes` import core; `/font` and `/svg` import `@margoengine/geometry` (a dependency), and `/mtl` and `/threemf-mesh` import `@margoengine/materials` (an optional peer: install it to use those entries).
|
|
115
|
+
- **Defensive parsing.** Headers are length-capped, every count is checked against `maxVertices` (default 8,000,000) and `maxTriangles` (default 16,000,000) before allocation, binary reads are bounds-checked before the loop, face and cell indices are validated, and ZIP entries are checked against their declared size while inflating (zip-bomb safe) and against CRC-32 afterwards. Every failure is a `LoaderError` with `format` and a `code` of `header`, `truncated`, `limit`, `range`, `syntax`, `unsupported`, `zip`, `aborted`, `fetch` or `url`. Its message reads `<format>: <what went wrong>; see https://margoengine.com/errors#loader-<code>`: the link is added in one place, the constructor, and each code has an entry on the errors page with its usual causes and what to do (see [Errors](#errors)).
|
|
116
|
+
- **3MF builds are baked.** Component and build item transforms are multiplied into the positions (Margo Engine meshes take position, rotation and scale only, not arbitrary 3x4 matrices). Mirroring transforms flip the winding back. Triangles are grouped by build item, object and color so `createMeshes` gives each its own material. When a `colorgroup` gives one triangle different corner colors, those objects are split per corner and `colors` is filled.
|
|
117
|
+
- **Colors.** Vertex colors are sRGB in [0,1]. `createMeshes` converts group colors to linear for `PbrMaterial`; since core has no vertex colors, meshes with only vertex colors get their average (`vertexColors: 'ignore'` turns that off). The optional [`/render` entry](#optional-vertex-color-and-opacity-rendering) preserves vertex RGB and opacity through the existing PBR renderer.
|
|
118
|
+
- **SSR safe.** Nothing touches `window`, `document`, `navigator` or `Worker` at import or parse time. `parse3MF` needs `DecompressionStream`, present in browsers and Node 22.
|
|
119
|
+
|
|
120
|
+
## Errors
|
|
121
|
+
|
|
122
|
+
Every failure is a `LoaderError`. Branch on `error.code` and `error.format`, not on the message text, and show `error.message` to the person: it ends with a link to the help entry for the code.
|
|
123
|
+
|
|
124
|
+
A `signal` that is already aborted makes every `/geo` reader (`parseGeoJSON`, `parseShapefile`, `parseGPX`, `parseKML`, `parseMVT`) throw code `aborted` before any input is converted or decoded.
|
|
125
|
+
|
|
126
|
+
| `code` | Help entry |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `header` | [loader-header](https://margoengine.com/errors#loader-header) |
|
|
129
|
+
| `truncated` | [loader-truncated](https://margoengine.com/errors#loader-truncated) |
|
|
130
|
+
| `limit` | [loader-limit](https://margoengine.com/errors#loader-limit) |
|
|
131
|
+
| `range` | [loader-range](https://margoengine.com/errors#loader-range) |
|
|
132
|
+
| `syntax` | [loader-syntax](https://margoengine.com/errors#loader-syntax) |
|
|
133
|
+
| `unsupported` | [loader-unsupported](https://margoengine.com/errors#loader-unsupported) |
|
|
134
|
+
| `zip` | [loader-zip](https://margoengine.com/errors#loader-zip) |
|
|
135
|
+
| `aborted` | [loader-aborted](https://margoengine.com/errors#loader-aborted) |
|
|
136
|
+
| `fetch` | [loader-fetch](https://margoengine.com/errors#loader-fetch) |
|
|
137
|
+
| `url` | [loader-url](https://margoengine.com/errors#loader-url) |
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import {parseSTL, LoaderError} from 'margoengine/loaders';
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
parseSTL(new Uint8Array(10));
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (error instanceof LoaderError) console.log(error.format, error.code, error.message);
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Options
|
|
150
|
+
|
|
151
|
+
| Option | Applies to | Default |
|
|
152
|
+
| --- | --- | --- |
|
|
153
|
+
| `maxVertices` | all parsers | 8,000,000 |
|
|
154
|
+
| `maxTriangles` | all parsers | 16,000,000 |
|
|
155
|
+
| `units` | `parse3MF` | `'meters'`; `'file'` keeps the model unit |
|
|
156
|
+
| `maxEntries`, `maxEntryBytes`, `maxRatio` | `parse3MF` | 65,535 entries (10,000 for the other ZIP formats), 512 MiB per part, a deflated part over 1 MiB may expand at most 200x (zip bombs reach 1,032x); a build expands to at most 100,000 object instances |
|
|
157
|
+
| `maxDepth` | `parse3MF` | 32 nested components |
|
|
158
|
+
| `maxModelParts` | `parse3MF` | 65,535 model parts (production extension), the root included: every part a ZIP without ZIP64 can hold, so a 10,000-part export reads back; `maxBytes`, `maxTriangles` and `maxEntryBytes` still bound the work |
|
|
159
|
+
| `modelResolution` | `parse3MF` | `'fullres'`; the first production alternative of this resolution (`'fullres'`, `'lowres'`, `'obfuscated'`) stands in for its object, which is read when there is none |
|
|
160
|
+
| `signal` | `parse3MF`, `load` | none |
|
|
161
|
+
| `keepInvalid` | `parsePCD` | `false` (NaN holes of organized clouds dropped) |
|
|
162
|
+
| `layout` | `parseXYZ` | `'auto'` (by column count; 6 columns are rgb unless a value is negative) |
|
|
163
|
+
| `maxBytes`, `fetch`, `init` | `load`, `fetchBytes`, `fetchResource` | 256 MiB, `globalThis.fetch`, none |
|
|
164
|
+
| `protocols`, `publicOnly`, `allowHost`, `maxRedirects`, `accept` | `load`, `fetchBytes`, `fetchResource` | any scheme, false, none, 20 once a guard is set (else the fetch follows), any type |
|
|
165
|
+
| `normals` | `toGeometry`, `createMeshes`, `createPBRMeshes` | `'auto'` (file normals; without them `toGeometry` smooths everything and the mesh creators smooth within `creaseAngle`); `'smooth'`, `'flat'` |
|
|
166
|
+
| `creaseAngle` | `createMeshes`, `createPBRMeshes` | 40 degrees: sharper edges of a mesh without normals stay sharp, each side with its own copy of the vertex; 0 is flat, 180 smooths everything |
|
|
167
|
+
| `group` | `toGeometry` | whole mesh |
|
|
168
|
+
| `merge`, `color`, `roughness`, `metalness`, `doubleSided`, `parent`, `vertexColors` | `createMeshes` | per group, `#b8bcc4`, 0.6, 0, true, none, `'average'` |
|
|
169
|
+
| `size`, `maxPoints` | `pointsToGeometry`, `createMeshes` on clouds | 0.4% of the bounds diagonal, 166,666 |
|
|
170
|
+
|
|
171
|
+
## Limits
|
|
172
|
+
|
|
173
|
+
- Core `Geometry` holds positions and normals only, at most 11,184,810 vertices (`CORE_MAX_VERTICES`): UVs and vertex colors are kept in `LoadedGeometry` but not rendered. `toGeometries` and `createMeshes` split a larger mesh into consecutive triangle ranges of at most that many vertices (or `maxPartVertices`) and 67,108,864 indices each; smooth normals are computed over the whole mesh first, so the parts meet without seams, and a vertex on a cut is stored in both parts. Point clouds render as octahedron markers (subsampled past `maxPoints`) because core has no point primitive.
|
|
174
|
+
- PLY face colors and other per-face scalar properties become per-face groups (`group.color`, `group.properties`). OFF reads ASCII and big-endian binary files and keeps each face's color or colormap index in its group. `parseVTK` reads legacy POLYDATA surfaces only; `parseVTKLegacy` (`/vtk-legacy`) reads every legacy dataset type with VERTICES and LINES cells and cell data, and `parseVTKXML` (`/vtk-xml`) the XML files. PCD ignores fields other than position, normal, rgb/rgba and intensity.
|
|
175
|
+
- 3MF: `parse3MF` reads the core format and base materials; textures, composite materials and multi-properties come from `parse3MFMaterials` (`/threemf-materials`), beam lattices and slices from `parse3MFLattice` (`/threemf-lattice`), volumetric and implicit data from `parse3MFVolumetric` (`/threemf-volumetric`) and displacement maps from `parse3MFDisplacement` (`/threemf-displacement`). `parse3MF` reads a displacement mesh as its base triangles, in groups marked `displaced`, and refuses a level set object or a boolean shape (`unsupported`), as neither has triangles of its own; `parse3MFBoolean` (`/threemf-boolean`) reads boolean shapes. ZIP64 and encrypted packages are refused; two property resources of one id are a `syntax` error; meshes of type `other` are skipped, however the build reaches them, and the type of an object of components is ignored (core specification). A group of another type than `model` says so in `objectType`, and `partNumber` and `itemPartNumber` carry the `partnumber` of its mesh object and build item. The production extension is read under whatever prefix a file declares: `buildUUID` on the result, `itemUUID`, `componentUUID`, `uuid` and `alternativeUUID` on each group, and `modelPath` for a mesh from a part other than the root. As the extension asks, only the root part may name another part, and another part's build is ignored.
|
|
176
|
+
- glTF lives in gltf and gltf/pbr.
|
|
177
|
+
|
|
178
|
+
## STL
|
|
179
|
+
|
|
180
|
+
`parseSTL` reads binary and ASCII STL into plain typed arrays and does nothing else: no GPU objects, no parts, no smoothing, and no welding unless you ask. A 204,800-triangle binary file becomes 614,400 vertices, as the file stores them.
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import {parseSTL, toGeometries} from 'margoengine/loaders';
|
|
184
|
+
const signal = AbortSignal.timeout(30_000);
|
|
185
|
+
|
|
186
|
+
const bytes = await (await fetch('/parts/bracket.stl', {signal})).arrayBuffer();
|
|
187
|
+
const mesh = parseSTL(bytes, {signal}); // weld: true shares corners that have equal positions
|
|
188
|
+
console.log(mesh.positions.length / 9, 'triangles', mesh.colors ? 'with colors' : 'without colors');
|
|
189
|
+
const parts = toGeometries(mesh, {normals: 'flat'}); // core Geometries of at most 11,184,810 vertices each
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
| Result | Content |
|
|
193
|
+
| --- | --- |
|
|
194
|
+
| `positions` | three vertices per triangle in file order (`weld: true`: one vertex per distinct position) |
|
|
195
|
+
| `normals` | the file's facet normal on each corner; a zero or non-finite stored normal (many writers leave zero) is replaced by the flat normal computed from the corners. With `weld: true`: smooth area-weighted normals |
|
|
196
|
+
| `colors` | binary files using a colour extension, sRGB 0 to 1. VisCAM / SolidView: attribute bit 15 set marks a facet colour (red bits 10-14, green 5-9, blue 0-4), 0.8 gray for facets without one. Materialise Magics, read when the 80-byte header holds `COLOR=`: bit 15 clear marks a facet colour (red bits 0-4, green 5-9, blue 10-14), and a set bit takes the part colour (the `,MATERIAL=` diffuse when given, else `COLOR=`). Absent otherwise and for ASCII |
|
|
197
|
+
| `materialise` | for a Materialise file, the header's colours as RGBA 0 to 1: `color` (`COLOR=`), and `diffuse`, `specular`, `ambient` (`,MATERIAL=`) |
|
|
198
|
+
| `indices` | `0, 1, 2, ...`, or the weld's indices |
|
|
199
|
+
|
|
200
|
+
Options (defaults): `weld: false`, `colorVariant: 'auto'` (`'viscam'` or `'materialise'` force one reading of the attribute bits; use `'materialise'` for a Magics file whose header has no `COLOR=`), `maxTriangles: 16,000,000`, `maxVertices: 8,000,000` (checked before allocating, so a short file cannot claim millions; the output has three vertices per triangle before welding, so the default `maxVertices` admits 2,666,666 triangles: pass `maxVertices: 3 * triangles` for more), `signal` (aborts with a `LoaderError` of code `'aborted'`, checked every 16,384 triangles). A binary file is recognised by its length (`84 + 50 * triangles`), so binary files whose header starts with `solid` still work; otherwise text starting with `solid` is read as ASCII, several solids in one file are concatenated, and keywords are case-insensitive. Errors are `LoaderError`s: `'truncated'` (data shorter than the header says; pass the whole file), `'syntax'`, `'limit'` (raise `maxTriangles` or `maxVertices`), `'header'`, `'aborted'`, and `'range'` for a bad option. Per-facet colors in ASCII files are not read (no ASCII colour convention is shared between writers).
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import {parseSTL} from 'margoengine/loaders';
|
|
204
|
+
|
|
205
|
+
// A Materialise Magics header: "COLOR=" then red, green, blue and alpha bytes; facet attribute 0x8000 = part colour.
|
|
206
|
+
const bytes = new Uint8Array(84 + 50);
|
|
207
|
+
bytes.set(new TextEncoder().encode('COLOR='), 0);
|
|
208
|
+
bytes.set([255, 128, 0, 255], 6);
|
|
209
|
+
const view = new DataView(bytes.buffer);
|
|
210
|
+
view.setUint32(80, 1, true);
|
|
211
|
+
[0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => view.setFloat32(96 + i * 4, v, true));
|
|
212
|
+
view.setUint16(132, 0x8000, true);
|
|
213
|
+
const part = parseSTL(bytes);
|
|
214
|
+
console.log(part.materialise?.color, part.colors?.slice(0, 3)); // [1, 0.502, 0, 1], the part colour on each corner
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
The repository's speed matrix (`docs/whitepaper`) measures this loader.
|
|
218
|
+
|
|
219
|
+
## Real files
|
|
220
|
+
|
|
221
|
+
`tests/real-files/manifest.json` names 123 public files from the tools people use: Blender, 3ds Max, AutoCAD, Rhino, CATIA, PrusaSlicer, Tiled, LightWave and more, each with its URL, licence, author, size and SHA-256. The files are not in this repository.
|
|
222
|
+
|
|
223
|
+
```sh
|
|
224
|
+
npm run test:real-files -w @margoengine/loaders -- --download
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
The script fetches nothing unless it is given `--download`: without it, an absent or changed file fails the run, which
|
|
228
|
+
names every one. With it, each file is downloaded by URL into `test-results/real-files`. The script refuses one whose hash differs, opens it and compares it with something independent: the counts in its own header, a second reader written in the script, or a published fact. It exits 1 on a failure and 2 when a file could not be run, such as a site refusing the download.
|
|
229
|
+
|
|
230
|
+
The MPD proof resolves all 13 embedded submodels and the external library/sticker parts with no missing files or warnings.
|
|
231
|
+
The PDAL PTS and Open Babel chemistry XYZ checks compare every coordinate, intensity and colour against the source text.
|
|
232
|
+
The real Slic3r ZIP AMF and the plain AMF control compare every placed vertex and triangle against an independent XML
|
|
233
|
+
oracle, including constellation translation/rotation. To run those rows on PowerShell:
|
|
234
|
+
|
|
235
|
+
```powershell
|
|
236
|
+
$env:REAL_FILES_ONLY='pts-pdal,xyz-openbabel,mpd-robotic-arm,amf-zipped-slic3r,amf-rook'
|
|
237
|
+
npm run test:real-files -w @margoengine/loaders -- --download
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
| Variable | Default | What it does |
|
|
241
|
+
| --- | --- | --- |
|
|
242
|
+
| `REAL_FILES_DIR` | `test-results/real-files` | Where files are kept between runs. |
|
|
243
|
+
| `REAL_FILES_ONLY` | every row | Comma-separated formats or row ids. |
|
|
244
|
+
| `REAL_FILES_RUNTIMES` | unset | A folder whose `node_modules` holds `rhino3dm` and `laz-perf`. Without it the 3DM rows read NOT RUN, and LAZ rows skip the comparison with laz-perf. `npm run test:real-files:runtimes -w @margoengine/loaders` fetches both into `test-results/real-files-runtimes`, at pinned versions with install scripts off. It is an opt-in test tool: neither runtime is a dependency or ships. |
|
|
245
|
+
| `REAL_FILES_RENDER` | unset | `1` draws every geometry through the real engine on the GPU and fails a blank picture. |
|
|
246
|
+
| `REAL_FILES_TRACE` | unset | Prints the stack of a failure. |
|
|
247
|
+
|
|
248
|
+
Neither runtime is a dependency of this package. Install them in a folder of your own.
|
|
249
|
+
|
|
250
|
+
## Tests
|
|
251
|
+
|
|
252
|
+
All fixture comparisons are required. Missing files fail with the exact tracked path and a `git restore`
|
|
253
|
+
command, and Git LFS pointers fail before parsing. From the repository root, `npm run fixtures --workspace
|
|
254
|
+
@margoengine/loaders` refreshes the pinned PCL/PyVista data, with HTTP, size and SHA-256 failures reported
|
|
255
|
+
as errors. The OFF comparisons use John Burkardt's
|
|
256
|
+
LGPL Geomview box and MC-letter meshes, downloaded by the same hash-checking fetcher.
|
|
257
|
+
`node packages/loaders/scripts/make-fixtures.js` regenerates the Margo-authored shapes. Build sibling packages with `npm run build:packages` before the
|
|
258
|
+
COLLADA-to-animation integration test.
|
|
259
|
+
|
|
260
|
+
`npm test` in `packages/loaders` runs Node tests for: OBJ/MTL fixtures covering every statement, map option and error line (and a Crocotile-style file whose triangle corners are checked against values read by hand from the text), COLLADA Y-up and Z-up fixtures (polylist quads, textured phong, TRS stacks, symbol-bound materials, trifans, tristrips, holes, errors; world-space corners checked against the document's transforms worked out by hand), TMX/TSX fixtures (csv, base64 plain, zlib and gzip written with `node:zlib`, legacy tiles, flips and their UVs, external and merged tilesets, infinite chunks, group offsets, errors), every PLY encoding and attribute naming generated in the test, PLY point clouds, OFF and XYZ variants, LZF round trips against an independent compressor, PCD ascii, binary and binary_compressed fixtures, VTK ASCII, big-endian BINARY and 5.1 polydata, ZIP archives with stored and deflate entries (written with `node:zlib`), 3MF components, mirrored transforms, colors, units and production parts, error cases for every format (bad headers, truncation, out-of-range indices, limits, zip bombs, CRC failures, cycles, aborts), `fetchBytes` limits against a local HTTP server, an SSR import check with throwing browser globals, Margo-made PLY, 3MF, PCD and XYZ fixtures (`node scripts/make-fixtures.js` rewrites them; the tests compare against the generator's own arrays and independent reads), and real files from PCL, the LGPL Geomview data collection and PyVista (`npm run fixtures` re-downloads them; see `tests/fixtures/SOURCES.txt`) compared with independent reads. `tests/font.test.js` assembles TrueType fonts in the test from the specification's table layouts (cmap 4 and 12, composites with scale and point matching, kern pairs, collections, both winding conventions); `tests/svg.test.js` covers every path command, arcs, shapes, transforms, fill rules, styles and stroke areas; `tests/mtl.test.js` checks the MTL to material mapping, texture URLs, OBJ groups and `loadOBJ`'s fetches with a stand-in fetch. `npm run test:browser` (a real-GPU script, not in CI) loads `face_colors.3mf` in Chromium, creates engine meshes, checks five face colors in the rendered pixels, a GPU pick, `maxBytes`, disposal, and zero WebGPU validation errors.
|
|
261
|
+
|
|
262
|
+
Apache-2.0 licensed.
|
|
263
|
+
|
|
264
|
+
## USD and USDZ
|
|
265
|
+
|
|
266
|
+
`parseUSDA(textOrBytes, options)` reads static polygon meshes with hierarchy, every UsdGeomXformOp (transform, translate, scale, rotateX/Y/Z, the six rotateABC orders and orient, with `:suffix` names such as pivots and `!invert!` entries), reset stacks, visibility and `purpose = "guide"` (both hide the subtree), Y/Z up, units, winding and display/PreviewSurface colors; a `material:binding` on an ancestor applies to the meshes under it, the nearest binding winning. Constant colors become `groups[].color` (sRGB). Constant or per-vertex RGB and opacity primvars, indexed or not, and read directly or through `UsdPrimvarReader_float3`/`UsdPrimvarReader_float` nodes, become sRGB `colors` and linear `attributes.opacity`. Other shader graphs and interpolations are refused. `createMeshes` averages vertex RGB and ignores vertex alpha; `createPBRMeshes` from `/render` keeps both. `parseUSDZ(bytes, options)` validates stored ZIP entries, 64-byte alignment and root-layer CRC before parsing USDA. Both return `LoadedGeometry`. `readUSDA(text, {maxDepth, signal, assets, skipOver})` exposes the underlying layer reader (the `def` prim tree with attributes, connections, relationships and property metadata such as `interpolation`); `@margoengine/usdz` builds on it. It skips dictionaries, reads single, double and triple-quoted strings with the C escapes OpenUSD reads (`\xHH`, `\ooo` and runs of them as UTF-8, `\n` and the other single letters; since 2026-11-19, KB-USDA-S1), refuses `relocates` by name, accepts list-op prefixes (`prepend apiSchemas`) in metadata, and parses numeric arrays on a fast path capped at 16 million values. `parseAny` detects USDA text and USDZ root filenames; ordinary ZIPs retain 3MF detection.
|
|
267
|
+
|
|
268
|
+
`@margoengine/loaders/worker` exports `parseUSDZInWorker(bytes, options)` and `parseUSDAInWorker(textOrBytes, options)`: the same `LoadedGeometry` (byte for byte, `tests/worker.test.js`) parsed in a worker (`dist/workers/usd.js`, about 6.6 kB min+gzip, [entry-sizes.json](../../examples/package-benchmarks/results/entry-sizes.json)) with its arrays transferred back; errors stay `LoaderError`s. A whole ArrayBuffer input moves to the worker (detached). Without `Worker` they parse on the calling thread.
|
|
269
|
+
|
|
270
|
+
Triangles and convex planar polygons are supported; meshes must author `subdivisionScheme = "none"`. A prim may reference a prim of the same layer (`references = </Path>`, what `exportUSDZ` writes for a shared geometry), and what it authors wins; class prims are not drawn. Binary USDC (the common production USDZ encoding), any other composition, animation, subdivision, hole faces, textures, uniform/face-varying color interpolation and concave polygons are rejected explicitly. Use OpenUSD `usdcat` to convert a binary root, or load it with `@margoengine/usdz`, which reads USDC natively; flatten/tessellate unsupported features before loading. File normals and UVs are not retained; normals are recomputed. `units` defaults to `'meters'`; `'file'` keeps authored scale. `maxDepth` defaults to 32 (maximum 64), `maxEntryBytes` to 64 MiB, and vertex/triangle/ZIP limits apply.
|
|
271
|
+
|
|
272
|
+
Root `npm run modern:test:interop` checks round trips, units, transforms, visibility, winding, topology/composition errors, CRC, alignment, USDC rejection and budgets. Full IFC geometry parsing is provided separately by `@margoengine/ifc` with web-ifc.
|
|
273
|
+
|
|
274
|
+
## Optional vertex color and opacity rendering
|
|
275
|
+
|
|
276
|
+
Install `@margoengine/gltf/pbr` alongside loaders to use this entry. The decode/root entry does not import it.
|
|
277
|
+
|
|
278
|
+
```ts
|
|
279
|
+
import {parsePLY} from 'margoengine/loaders';
|
|
280
|
+
import {createPBRMeshes} from 'margoengine/loaders/render';
|
|
281
|
+
import {Engine} from 'margoengine/core';
|
|
282
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
283
|
+
const bytes = new Uint8Array(await (await fetch('/scans/part.ply')).arrayBuffer());
|
|
284
|
+
|
|
285
|
+
const source = parsePLY(bytes);
|
|
286
|
+
const model = createPBRMeshes(engine, source, {
|
|
287
|
+
baseColorFactor: [1, 1, 1, 1], // linear material multiplier; default white
|
|
288
|
+
maxBytes: 256 << 20, // packed geometry budget; default 256 MiB
|
|
289
|
+
});
|
|
290
|
+
model.root.setScale([-1, 1, 1]);
|
|
291
|
+
// Existing PBRModel ownership includes automatic device restoration.
|
|
292
|
+
model.dispose();
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
`createPBRMeshes` returns a `PBRModel` (dispose it when done) that renders per-vertex sRGB colors and linear
|
|
296
|
+
`attributes.opacity` through `@margoengine/gltf/pbr`. Group RGBA fills in only a missing channel; `baseColorFactor`
|
|
297
|
+
multiplies the result, and any alpha below one draws blended. With vertex colors, neighboring groups that differ only in their group color are drawn as one part, so a colored scan with thousands of color groups stays within the 4,096 parts. `parent`, `normals`, `roughness`, `metalness` and
|
|
298
|
+
`doubleSided` work as in `createMeshes`; `unlit` uses the unlit material. It accepts triangle meshes of any size within `maxBytes`
|
|
299
|
+
and at most 4096 parts (a part past 262,144 vertices, gltf/pbr's default `maxPartVertices`, becomes several primitives of one mesh, split as
|
|
300
|
+
`toGeometries` splits, so gltf/pbr draws each as made), and refuses point clouds, malformed attributes, overlapping groups and data over
|
|
301
|
+
`maxBytes` before allocating GPU resources. `npm run test:render:browser` checks the colors on the GPU.
|
|
302
|
+
|
|
303
|
+
## Fetching untrusted links
|
|
304
|
+
|
|
305
|
+
A link a user pasted or a page found can point anywhere, this computer and the local network included. `fetchResource`
|
|
306
|
+
(and `fetchBytes` and `load`, which take the same options) guards it: `protocols` allows schemes, `publicOnly` refuses
|
|
307
|
+
loopback, private, shared and link-local hosts (RFC 1918, 3927, 4193, 4291, 6598, 6761) and links with a user name or
|
|
308
|
+
password, and `allowHost` is your own test. With any guard set, redirects are followed by hand (at most
|
|
309
|
+
`maxRedirects`, default 20) and every hop is checked again; `accept` refuses other media types before the body is
|
|
310
|
+
read. The result carries the final URL and the `Content-Type`, so a page's charset and its real address are known. A
|
|
311
|
+
refusal is a `LoaderError` with code `'url'`, `'limit'` or `'unsupported'`; an error your own `fetch` throws is the
|
|
312
|
+
`cause` of the `'fetch'` error. When the server answers with an error status, the `'fetch'` error carries it as
|
|
313
|
+
`status` (403, 404, 429, 503...), and `retryAfter`, the seconds its `Retry-After` header asks you to wait (RFC 9110
|
|
314
|
+
10.2.3, sent as seconds or as a date), when it sent one; a network failure has neither, so branch on the fields, not on
|
|
315
|
+
the message. `publicOnly` reads the host as written: a public name whose DNS answer is private is
|
|
316
|
+
not caught (resolve and pin the address in your own `fetch` for that). In a browser a guarded redirect is refused,
|
|
317
|
+
since the browser hides it from the page.
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import {fetchResource} from 'margoengine/loaders';
|
|
321
|
+
// A stand-in server: the link redirects once, then answers HTML.
|
|
322
|
+
const fetch = async (url: RequestInfo | URL) =>
|
|
323
|
+
String(url) === 'https://example.com/a'
|
|
324
|
+
? new Response(null, {status: 302, headers: {location: '/b'}})
|
|
325
|
+
: new Response('<p>Hello</p>', {headers: {'content-type': 'text/html; charset=utf-8'}});
|
|
326
|
+
const page = await fetchResource('https://example.com/a', {
|
|
327
|
+
fetch,
|
|
328
|
+
protocols: ['https:'],
|
|
329
|
+
publicOnly: true,
|
|
330
|
+
accept: ['text/html', 'text/plain'],
|
|
331
|
+
maxBytes: 2 * 1024 * 1024,
|
|
332
|
+
signal: AbortSignal.timeout(15_000),
|
|
333
|
+
});
|
|
334
|
+
console.log(page.url, page.type, page.redirects); // https://example.com/b text/html; charset=utf-8 1
|
|
335
|
+
const blocked = await fetchResource('https://192.168.1.1/admin', {fetch, publicOnly: true}).catch((e) => e.code);
|
|
336
|
+
console.log(blocked); // 'url'
|
|
337
|
+
// A busy server: the error carries the status and how long to wait.
|
|
338
|
+
const busy = async () => new Response('slow down', {status: 429, headers: {'retry-after': '120'}});
|
|
339
|
+
const refused = await fetchResource('https://example.com/data', {fetch: busy}).catch((e) => e);
|
|
340
|
+
console.log(refused.code, refused.status, refused.retryAfter); // 'fetch' 429 120
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
## Files that refer to other files
|
|
344
|
+
|
|
345
|
+
Parsers stay pure and return plain data. Files a model refers to come through a resolver you pass, `(path) => Promise<Uint8Array | string>`, called with paths relative to the folder of the file being parsed (`../` and `./` already resolved). Images are never read by the loaders: every result lists its texture paths in `images`, in the same form, ready for the same resolver (or `new URL(path, base)` in a browser).
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
// Electron (main or preload): read next to the model.
|
|
349
|
+
import fs from 'node:fs';
|
|
350
|
+
import {dirname, join} from 'node:path';
|
|
351
|
+
const file = '/models/ship.glb';
|
|
352
|
+
const resolveFromDisk = (path: string) => fs.promises.readFile(join(dirname(file), path));
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
// Browser: fetch next to the model.
|
|
357
|
+
import {resolveFromURL} from 'margoengine/loaders/ldraw';
|
|
358
|
+
const modelUrl = new URL('/models/ship.glb', location.href);
|
|
359
|
+
const resolve = async (path: string) => new Uint8Array(await (await fetch(new URL(path, modelUrl))).arrayBuffer());
|
|
360
|
+
// The built-in URL resolver has the same relative-path convention.
|
|
361
|
+
const builtInResolve = resolveFromURL(new URL('.', modelUrl).href);
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
## OBJ and MTL
|
|
365
|
+
|
|
366
|
+
`await parseOBJ(textOrBytes, {resolve, signal, maxVertices, maxTriangles})` reads `v` (with `w`, or `r g b` vertex colors after xyz, 0..1 or 0..255), `vt`, `vn`, faces of any size with `v`, `v/vt`, `v//vn`, `v/vt/vn` and negative indices, `o`, `g`, `s`, `usemtl` and `mtllib` (several files, or one name with spaces), `\` continuations, comments and CRLF. `p` points and `l` polylines come back as `pointIndices` (one vertex each) and `lineIndices` (two per segment): with faces, corners welded like face corners; without faces, the `v` list itself. Other statements (`vp`, curves) are kept in `extras`; malformed lines throw a `LoaderError` naming the line.
|
|
367
|
+
|
|
368
|
+
- Every distinct `v/vt/vn` corner becomes one vertex, so UV and normal seams survive (a corner without `vt` or `vn` reads zeros when others have them); `positionIndices` maps each vertex back to its `v` line for re-welding.
|
|
369
|
+
- `uvs` use Margo's convention: v = 1 - vt v (OBJ has v = 0 at the bottom of the image).
|
|
370
|
+
- Faces are fan-triangulated: face f with n = `faceSizes[f]` corners c0..cn-1 gives triangles (c0, ck, ck+1), in file order, so quads and n-gons can be rebuilt from `indices` and `faceSizes`. `smoothingGroups` holds each face's `s` value (0 = off).
|
|
371
|
+
- `groups` split at every change of `o`, `g` or `usemtl` and carry `object`, `groupNames` and `material`. With `resolve`, every MTL library is read once (`materials`, first definition of a name wins) and each group gets its material's `Kd` and `d` as `color`, so `createMeshes` colors it. A library the resolver cannot read, or a `usemtl` naming nothing, is a `warnings` entry, not an error.
|
|
372
|
+
|
|
373
|
+
`parseMTL(textOrBytes, {path})` returns `{name, Ka, Kd, Ks, Ke, Ns, d, Tr, illum, maps, extras}[]`. `maps` holds `map_Kd`, `map_Ka`, `map_Ks`, `map_Ke`, `map_Ns`, `map_d`, `bump` (also written `map_Bump`), `disp`, `decal`, `refl` (a cube reflection's faces also as `refl_cube_top` and so on) and any other `map_*` as `{file, path, options}`, where `options` uses the spec's names (`o`, `s`, `t` as three numbers, `clamp`, `blendu`, `blendv`, `cc` as booleans, `bm`, `boost`, `texres`, `mm`, `imfchan`, `type`). Statements it does not interpret, and maps with unknown options, stay in `extras`.
|
|
374
|
+
|
|
375
|
+
### Textured OBJ meshes
|
|
376
|
+
|
|
377
|
+
Pass `fetch: manager.fetch` from `@margoengine/cache/manager`'s `LoadingManager` to `load`, `fetchBytes` or `loadOBJ` for shared progress, errors, abort and a URL modifier across loaders (loadOBJ's `mtllib` files and textures included).
|
|
378
|
+
|
|
379
|
+
`createMeshes` gives core `PbrMaterial` colours only. For textures, `@margoengine/loaders/mtl` builds `@margoengine/materials` meshes (an optional peer dependency: install it to use this entry). One call fetches the .obj, its `mtllib` files next to it and every texture relative to its .mtl file, and draws each `usemtl` group with its material:
|
|
380
|
+
|
|
381
|
+
A textured quad from `packages/loaders/tests/fixtures/mtl-gpu` (an OBJ, its MTL and a 2 x 2 `map_Kd` image) is drawn on a real GPU, natively and on the WebGL2 layer, and each quadrant is checked for its texel's colour (`npm run test:gpu:mtl -w @margoengine/loaders`).
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
import {loadOBJ} from 'margoengine/loaders/mtl';
|
|
385
|
+
import {Engine} from 'margoengine/core';
|
|
386
|
+
const signal = AbortSignal.timeout(30_000);
|
|
387
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
388
|
+
|
|
389
|
+
const {mesh, warnings, dispose} = await loadOBJ(engine, '/models/crate.obj', {signal});
|
|
390
|
+
// mesh is a materials mesh (a gltf/pbr model): move it with mesh.root, add it to shadows, clustered, ...
|
|
391
|
+
dispose(); // destroys the mesh, its materials and its textures
|
|
392
|
+
// A scene that removes the mesh (removePlugin, scene or engine disposal) releases its materials and textures too.
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
Or step by step, with your own bytes and texture loader:
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
import {parseMTL, parseOBJ} from 'margoengine/loaders';
|
|
399
|
+
import {createMTLMaterials, createOBJMesh} from 'margoengine/loaders/mtl';
|
|
400
|
+
import {Engine} from 'margoengine/core';
|
|
401
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
402
|
+
const objUrl = new URL('/models/crate.obj', location.href).href;
|
|
403
|
+
const bytes = new Uint8Array(await (await fetch(objUrl)).arrayBuffer());
|
|
404
|
+
const resolve = async (path: string) => new Uint8Array(await (await fetch(new URL(path, objUrl))).arrayBuffer());
|
|
405
|
+
const obj = await parseOBJ(bytes, {resolve});
|
|
406
|
+
const set = await createMTLMaterials(obj.materials, {baseUrl: objUrl, bump: 'normal'});
|
|
407
|
+
const mesh = createOBJMesh(engine, obj, set); // one mesh, one material slot per usemtl material
|
|
408
|
+
// parseMTL output resolves against the .mtl URL instead: createMTLMaterials(parseMTL(text), {baseUrl: mtlUrl}).
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
- Each `newmtl` becomes a metallic-roughness `Material`: `Kd` colour (sRGB to linear), `d` or `1 - Tr` opacity (transparent below 1 or with `map_d`), `Ke` emission (values over 1 go to `emissiveIntensity`), roughness from `Ns` as `(2 / (Ns + 2))^(1/4)` (Ns 10 gives 0.64, 100 gives 0.37, 1000 gives 0.21; 1 with `illum 1` or a black `Ks`), and the PBR extension's `Pr` and `Pm` when present. `Ks` (sRGB to linear) is the specular reflectance at normal incidence, held as KHR_materials_specular's `specularColor` (`Ks` / 0.04), so `Ks 0.5 0.5 0.5` reflects as a Phong shader does and a dimmer `Ks` below sRGB 0.22 reflects less than a plain glTF dielectric; `illum 1` and a black `Ks` set `specularIntensity` 0. A material with `Pr` or `Pm` is a PBR one and leaves `Ks` out. `illum 0` is unlit.
|
|
412
|
+
- Maps: `map_Kd` (colour), `map_Ke` (emission), `bump`/`map_Bump` (bump map scaled by `-bm`, or a normal map with `bump: 'normal'`, as many exporters write them), `norm` (normal map), `map_d` (opacity), `map_Ks` (specular colour map, times `Ks`), `disp` (vertices move along their normals by the map's red channel; `-mm base gain` sets `displacementBias` and `displacementScale`, default 0 and 1 mesh unit) and `refl` (the material's `envMap`: one latitude-longitude image for `-type sphere`, the default, or all six `-type cube_*` faces, square and one size, `cube_front` facing -Z; an `envMap` also takes the place of the scene's ambient light on that material). `-o` and `-s` (not on `refl`) become the slot's UV transform, `-clamp on` clamped wrapping. Each file loads once per colour space.
|
|
413
|
+
- `Ka`, `Ni`, `Tf`, `map_Ka`, `map_Ns`, `decal` and other statements have no Margo equivalent (ambient light shades the base colour, so there is no ambient colour to set); they and any texture that fails to load are listed in `warnings` instead of throwing.
|
|
414
|
+
- An OBJ and its MTL files are untrusted input. `loadOBJ` reads `mtllib` files and textures only from the OBJ's own directory (same origin, no `../` past it) or a prefix in `allowedURLs` (default none): a library elsewhere throws a `LoaderError` with code `'url'` naming `allowedURLs`, a texture elsewhere is a warning and is not requested. `init` (headers, credentials) is sent only to the OBJ's origin, never to an allowed library on another origin (a custom `fetch` sees every request, so it decides for itself). The libraries share one budget: at most `maxMaterialLibraries` files (default 16) holding `maxMaterialBytes` together (default 64 MiB); more throws a `LoaderError` with code `'limit'`. `parseOBJ` applies the same budget to its `resolve`, and `createMTLMaterials` the same directory rule to map paths against `baseUrl` (with its own `allowedURLs`).
|
|
415
|
+
- The mesh gets the OBJ's UVs back with v up (for `flipY` textures), vertex colours in linear, and smooth normals shared across UV seams when the file has none. Groups without a known material use `fallback` (default a white `Material`). `prepareOBJMesh` returns the geometry and material array without creating the mesh. At most 1,000,000 vertices (a materials mesh limit). Front faces only unless `doubleSided: true`. Textures load with materials' `loadTexture` (http(s), blob: and data: URLs) unless you pass `loadTexture`.
|
|
416
|
+
|
|
417
|
+
## Fonts and 3D text
|
|
418
|
+
|
|
419
|
+
`@margoengine/loaders/font` reads OpenType fonts (TrueType `.ttf`, CFF and CFF2 `.otf`, `.ttc` collections and variable fonts) into an `OutlineFont` and extrudes text with `@margoengine/geometry`. It is Margo's one font outline parser: `@margoengine/text` builds its extruded, vector and outline-field text on it. TrueType fonts read with this entry alone; the CFF, CFF2 and variation readers are a separate entry, `@margoengine/loaders/font-opentype`, so an app that ships only `.ttf` files does not download them (9.1 KB gzip against 16.0 KB with the readers).
|
|
420
|
+
|
|
421
|
+
```ts
|
|
422
|
+
import {parseTTF, textGeometry} from 'margoengine/loaders/font';
|
|
423
|
+
import {openType, parseOpenType} from 'margoengine/loaders/font-opentype';
|
|
424
|
+
import {createMesh, Material} from 'margoengine/materials';
|
|
425
|
+
import {Engine} from 'margoengine/core';
|
|
426
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
427
|
+
|
|
428
|
+
const font = parseTTF(await (await fetch('/fonts/Inter.ttf')).arrayBuffer());
|
|
429
|
+
const geometry = textGeometry('Margo\nEngine', {font, size: 1, depth: 0.2, bevelEnabled: true, bevelThickness: 0.02, bevelSize: 0.01});
|
|
430
|
+
createMesh(engine, geometry, [new Material({color: '#ffffff'}), new Material({color: '#3355ff'})]); // caps, sides
|
|
431
|
+
|
|
432
|
+
const shapes = font.generateShapes('Logo', 10, {letterSpacing: 0.05, align: 'center'}); // geometry Shapes with holes
|
|
433
|
+
|
|
434
|
+
// A variable font at one instance: axis values in the font's own units, unset axes at their defaults.
|
|
435
|
+
// It needs the OpenType readers: pass {openType}, or call parseOpenType, which does the same.
|
|
436
|
+
const bytes = await (await fetch('/fonts/InterVariable.ttf')).arrayBuffer();
|
|
437
|
+
const weight = parseTTF(bytes).variationAxes.find((axis) => axis.tag === 'wght'); // {tag, min, default, max}
|
|
438
|
+
const bold = weight ? parseTTF(bytes, {variations: {wght: Math.min(700, weight.max)}, openType}) : parseTTF(bytes);
|
|
439
|
+
const cff = parseOpenType(await (await fetch('/fonts/SourceSans3-Regular.otf')).arrayBuffer()); // CFF outlines
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
WOFF and WOFF2 web fonts decode with `@margoengine/loaders/font-woff`, which uses the Brotli decoder of
|
|
443
|
+
`@margoengine/decoders` (an optional peer: install it for this entry):
|
|
444
|
+
|
|
445
|
+
```ts
|
|
446
|
+
import {decodeWOFF, parseWOFF} from 'margoengine/loaders/font-woff';
|
|
447
|
+
|
|
448
|
+
const woff2 = await (await fetch('/fonts/SourceSans3.woff2')).arrayBuffer();
|
|
449
|
+
const web = parseWOFF(woff2, {variations: {wght: 700}}); // an OutlineFont, like parseTTF's
|
|
450
|
+
console.log(web.generateShapes('Web', 10).length > 0, web.kerning('T', 'o') < 0); // true true
|
|
451
|
+
const sfnt = decodeWOFF(woff2, {maxBytes: 16 * 1024 * 1024}); // the .ttf or .otf bytes, for any other reader
|
|
452
|
+
console.log(sfnt.length > woff2.byteLength); // true
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
- `decodeWOFF(bytes, {maxBytes})` follows W3C WOFF 1.0 (zlib table data) and WOFF2 (one Brotli stream, the `glyf`, `loca` and `hmtx` transforms and font collections, which come out as `.ttc` bytes), recomputes table checksums and is synchronous. `maxBytes` (default 256 MiB) bounds the decompressed tables and the rebuilt font; a damaged file throws a `LoaderError` with format `WOFF`. WOFF metadata and private blocks are dropped. `parseWOFF(bytes, options)` is `parseOpenType(decodeWOFF(bytes), options)`.
|
|
456
|
+
|
|
457
|
+
- `parseTTF(bytes, {fontIndex, variations})` follows the OpenType specification: `head`, `hhea`, `maxp`, `hmtx`, `loca` (short and long), `glyf` simple and composite glyphs (offsets, scale, x/y scale, 2x2 transforms, point matching, ROUND_XY_TO_GRID, nesting), CFF outlines, name-keyed or CID-keyed with FDArray and FDSelect (Type 2 charstrings with local and global subroutines, hint masks, flex and, in name-keyed fonts, `endchar` accented characters; Adobe TN #5176 and #5177) and CFF2 outlines (Font DICT selection, `blend` and `vsindex`), `cmap` formats 4 and 12 (Unicode, and symbol fonts at U+F000), pair kerning from GPOS (the `kern` feature of the character's script: lookup type 2, formats 1 and 2, through extension lookups, the first glyph's XAdvance, with its variation deltas on a variable instance) or, when GPOS has no `kern` feature, `kern` format 0 pairs (Microsoft and Apple headers), and the family and style names. `fontIndex` picks one font of a `.ttc` collection. Glyphs decode on first use: TrueType glyphs as quadratic commands, CFF glyphs as cubic ones, all in font units.
|
|
458
|
+
- Variable fonts: `variations` (default `{}`) maps axis tags to values in the font's `fvar` user units, clamped to each axis; an unknown tag throws a `LoaderError` with code `range`. Normalization follows the specification (16.16, `avar` segment maps, then F2DOT14); `gvar` moves points (untouched points interpolated) and composite offsets, `HVAR` or the `gvar` phantom points move advances, and CFF2 charstrings blend through the ItemVariationStore. `font.variationAxes` lists the axes (empty for a static font).
|
|
459
|
+
- `openType` (default none) carries the CFF, CFF2 and variation readers from `@margoengine/loaders/font-opentype`; `parseOpenType(bytes, options)` and `parseOpenTypeSource(bytes, options)` there are `parseTTF` and `parseTTFSource` with them passed. Without them, TrueType fonts and the default instance of a variable TrueType font read in full (`variationAxes` included, since every delta is 0 there), and a CFF font or a `variations` instance throws a `LoaderError` with code `unsupported` that names the entry.
|
|
460
|
+
- `parseTTFSource(bytes, options)` returns the parser's `OutlineFontSource` without building an `OutlineFont`: glyphs by index, the instance's `variationCoordinates`, and `table(tag)` for raw tables such as `GPOS` and `GSUB`. Use it to drive your own layout or shaper.
|
|
461
|
+
- Budgets: composites nest at most 16 levels and visit at most 4,096 components and 1,000,000 points per glyph; a Type 2 charstring runs at most 100,000 operations, 10 subroutine levels and 96 stem hints. Past one the glyph throws a `LoaderError` with code `limit`.
|
|
462
|
+
- `font.generateShapes(text, size, {letterSpacing, lineHeight, align, kerning})` lays out text with one em = `size`: baseline at y = 0, `\n` for new lines, kerning on by default, `letterSpacing` in ems. Holes come from nesting and the winding rule, not from one fixed contour direction, so fonts written either way round work. Missing characters draw the font's `.notdef` glyph.
|
|
463
|
+
- `textGeometry(text, {font, size, depth, curveSegments, bevelEnabled, bevelThickness, bevelSize, bevelOffset, bevelSegments, steps})` defaults to size 100, depth 50 and no bevel, and returns `GeometryData` with groups 0 (caps) and 1 (sides).
|
|
464
|
+
- Limits: synthetic CFF fonts throw a `LoaderError` with code `unsupported`, and so do WOFF and WOFF2 bytes given to `parseTTF` (use `parseWOFF`); kerning is pair adjustment only, applied to the first glyph's XAdvance (no GPOS placement, contextual kerning or lookup flags), and a GPOS or GSUB table may list at most 16,384 subtables in the lookups used; no hinting, ligatures, right-to-left or complex-script shaping (`@margoengine/text` draws screen text).
|
|
465
|
+
|
|
466
|
+
## SVG
|
|
467
|
+
|
|
468
|
+
`@margoengine/loaders/svg` turns SVG drawings into geometry `Shape`s and stroke triangles:
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
import {parseSVG} from 'margoengine/loaders/svg';
|
|
472
|
+
import {extrudeGeometry} from 'margoengine/geometry';
|
|
473
|
+
import {SRGBToLinear} from 'margoengine/math/color';
|
|
474
|
+
import {Engine} from 'margoengine/core';
|
|
475
|
+
import {createMesh, Material} from 'margoengine/materials';
|
|
476
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
477
|
+
|
|
478
|
+
const {paths, viewBox, warnings} = parseSVG(await (await fetch('/logo.svg')).text());
|
|
479
|
+
for (const path of paths) {
|
|
480
|
+
if (path.fill) {
|
|
481
|
+
const geometry = extrudeGeometry(path.toShapes({flipY: true}), {depth: 2, bevelEnabled: false});
|
|
482
|
+
createMesh(engine, geometry, new Material({color: path.fill.map(SRGBToLinear), opacity: path.fillOpacity}));
|
|
483
|
+
}
|
|
484
|
+
if (path.stroke)
|
|
485
|
+
createMesh(engine, path.toStrokeGeometry({flipY: true}), new Material({color: path.stroke.map(SRGBToLinear)}));
|
|
486
|
+
}
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
- Elements: `path` (M L H V C S Q T A Z, absolute and relative, packed numbers and arc flags), `rect` (rounded), `circle`, `ellipse`, `line`, `polyline`, `polygon`, inside `g`, `a`, nested `svg` viewports (`viewBox`, `preserveAspectRatio`) and `use` of `defs` content or `symbol`s. `transform` lists with `matrix`, `translate`, `scale`, `rotate` (with a centre), `skewX` and `skewY` compose through every level.
|
|
490
|
+
- Each path has `commands` (M L Q C Z in root user units, arcs as cubic Béziers), `fill` and `stroke` (sRGB 0..1 or null), `fillOpacity` and `strokeOpacity` (including the colour's alpha and group `opacity`), `fillRule`, `strokeWidth`, `strokeLineJoin`, `strokeLineCap` and `strokeMiterLimit`. Styles come from attributes, `style` and `<style>` rules with type, class and id selectors, inherited as SVG does, with `currentColor`, named colours, `#rgb[a]`, `#rrggbb[aa]`, `rgb()` and `hsl()`.
|
|
491
|
+
- `toShapes({flipY})` applies the path's fill rule (`nonzero` or `evenodd`) to find holes. `toStrokeGeometry({flipY, width, divisions})` returns the stroke as flat triangles on z = 0 facing +z, with miter (and miter limit), round or bevel joins and butt, round or square caps, built in the element's units and then transformed. Its triangles may overlap, so a transparent stroke darkens where they do.
|
|
492
|
+
- Coordinates stay in root user units with y down, as in the file (the root `viewBox` is reported, not applied): `flipY` makes the drawing upright in a y-up scene.
|
|
493
|
+
- Not drawn, each listed in `warnings`: `text`, `image`, clip paths, masks, markers, patterns, filters and dashes; gradients fill with the average of their stop colours. CSS beyond simple selectors, and `@` rules, are skipped.
|
|
494
|
+
|
|
495
|
+
## COLLADA
|
|
496
|
+
|
|
497
|
+
`parseDAE(textOrBytes, {maxVertices, maxTriangles})` reads COLLADA 1.4.1 and 1.5 (`.dae`) and returns `{upAxis, meter, geometries, materials, images, nodes, cameras, lights, warnings}`, already converted to Y-up meters (`Z_UP` and `X_UP` rotate per the spec's axis table, `unit meter` scales geometry and translations).
|
|
498
|
+
|
|
499
|
+
- `geometries`: each `<mesh>` as a `LoadedGeometry` plus `id`, `name`, `faceSizes` and `positionIndices`, from `<triangles>`, `<polylist>` (`vcount` kept as `faceSizes`), `<polygons>`, `<trifans>` and `<tristrips>` with VERTEX/POSITION, NORMAL, TEXCOORD (lowest `set`, v flipped to 1 - t) and COLOR inputs at any offset, in the primitive or in `<vertices>`. One group per primitive with its material `symbol`. Corners are welded per primitive, so seams survive. `<lines>` and `<linestrips>` come back as `lines: {positions, colors?, positionIndices, indices, groups}`, vertices of their own (so the triangle arrays stay as they were) and two indices per segment, one group per line primitive with its `symbol`; `flattenDAE` and `createMeshes` draw triangles only.
|
|
500
|
+
- `materials`: `profile_COMMON` `constant`, `lambert`, `phong` and `blinn` with `emission`, `ambient`, `diffuse`, `specular`, `reflective` and `transparent` as `{color}` or `{texture: {path, texcoord}}` (through 1.4.1 sampler2D, surface and image, 1.5 `instance_image`, or a bare image id), `opaque`, `shininess`, `reflectivity`, `transparency`, `indexOfRefraction`.
|
|
501
|
+
- `images`: the texture paths materials use, relative to the .dae folder (`file:///C:/a%20b.png` becomes `C:/a b.png`), for your resolver.
|
|
502
|
+
- `nodes`: the instanced visual scene as `{id, name, matrix, instances, children}`, `matrix` being the node's matrix/translate/rotate/scale/lookat/skew stack (column-major, Y-up meters); `instances` are `{geometry, materials}` with `bind_material` symbols mapped to material indices; `instance_node` is expanded (at most 64 deep and 100,000 nodes).
|
|
503
|
+
- Not imported, each reported in `warnings`: polygon holes (the outer polygon is kept), embedded image data, non-mesh geometry, cameras and lights without `technique_common` optics or light (profile-specific techniques), and the controllers, joints and animation channels described below when they do not resolve. A degenerate `lookat` (eye on the interest point, or up along the view) keeps only its eye; a degenerate `skew` is skipped; both are warned.
|
|
504
|
+
|
|
505
|
+
`flattenDAE(dae, pose?)` bakes the hierarchy into one `LoadedGeometry` (mirrored nodes keep outward winding) with a group per node instance and primitive, named after the node and colored with the bound material's diffuse color, so `createMeshes(engine, flattenDAE(dae))` shows the scene. Skinned and morphed instances are deformed: at rest without a pose, animated with `flattenDAE(dae, poseDAE(dae, seconds))`.
|
|
506
|
+
|
|
507
|
+
### Collada cameras, lights, lookat and skew
|
|
508
|
+
|
|
509
|
+
- `lookat` (eye, interest, up) is the matrix that puts a frame at the eye looking down its -Z at the interest point: columns side = forward x up, true up = side x forward, -forward and the eye. `skew` (degrees, rotation axis, translation axis) is the RenderMan skew the spec adopts: points slide parallel to the translation axis so that the rotation axis turns by the angle toward it (x' = x + tan(angle) y for `45 0 1 0 1 0 0`). Both are stack elements like the others, so channels animate them by sid, whole (`node/look`, 9 values) or one value (`node/look(0)` is the eye's x).
|
|
510
|
+
- `cameras`: every `<instance_camera>` in scene order (one per `instance_node` copy) as `{id, name, node, type, perspective | orthographic, matrix}`. `perspective` keeps what the file gives (`xfov`, `yfov`, `aspectRatio`, full angles in degrees) and `orthographic` `xmag`/`ymag` (read as half-width and half-height, like glTF's); `znear`, `zfar` and magnifications are in meters. `matrix` is the camera's frame at rest in Y-up meters, looking down its -Z with +Y up (the node's world matrix times the up-axis rotation, so a `Z_UP` camera still looks where it did); `daeFrame(dae, node, pose)` gives it at a pose.
|
|
511
|
+
- `daeCameraView(dae, index, {pose, aspect})` returns what core's camera takes, `{position, target, up, fov, near, far, aspect, project}`: `yfov` is the vertical fov; `xfov` with `aspect_ratio` gives yfov = 2 atan(tan(xfov / 2) / aspect); `xfov` and `yfov` keep yfov and fix the aspect at tan(xfov / 2) / tan(yfov / 2); `xfov` alone needs `{aspect}` (the viewport's). All three warn and drop `aspect_ratio`. Orthographic views set `project` (half-height `ymag`, or `xmag / aspect_ratio`, or `xmag` over the viewport's aspect; WebGPU reversed depth) and perspective views clear it, so `Object.assign(engine.camera, view)` switches either way. `target` is one meter ahead.
|
|
512
|
+
- `lights`: every `<instance_light>` as `{id, name, node, type, color, position, direction, matrix}` (`ambient`, `directional`, `point`, `spot`; `direction` is the frame's -Z, the way the light travels) with `constantAttenuation`, `linearAttenuation` and `quadraticAttenuation` for point and spot (defaults 1, 0, 0, converted so distance is in meters) and `falloffAngle` (the full cone, default 180) and `falloffExponent` (default 0) for spot.
|
|
513
|
+
- `daeEngineLights(dae, {pose, intensity})` converts them: each color splits into a unit color and its brightest channel as the intensity (times `intensity`). The first directional light is `sun`, for core's `engine.scene.lighting` (`toward` the light); others are `directional`, for `@margoengine/clustered/directional`; ambient lights sum into `ambient` for core's `scene.lighting.ambient` and `radiance[3]`. Point and spot lights become `local` entries for `Clustered.setLights` (`position`, `range`, `color`, `intensity`, `decay`, and `direction`, `outerAngle`, `innerAngle` for spots). Approximations: `1 / (c + l d + q d^2)` keeps only its strongest set term (q: `decay` 2 and intensity / q; else l: `decay` 1; else c: `decay` 0 and unlimited `range`), matching far away and brighter close to the light; `range` ends where the light falls to 1/256; `outerAngle` is half the falloff angle (at most a hemisphere) and the `cos^e` falloff becomes a smooth edge starting where cos^e is 1/2 (`innerAngle`), a hard edge for e = 0.
|
|
514
|
+
|
|
515
|
+
```ts
|
|
516
|
+
import {parseDAE, daeCameraView, daeEngineLights} from 'margoengine/loaders';
|
|
517
|
+
import {Clustered} from 'margoengine/clustered';
|
|
518
|
+
import {Engine} from 'margoengine/core';
|
|
519
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
520
|
+
const text = await (await fetch('/text.txt')).text();
|
|
521
|
+
const dae = parseDAE(text);
|
|
522
|
+
if (dae.cameras.length) Object.assign(engine.camera, daeCameraView(dae, 0, {aspect: 16 / 9}));
|
|
523
|
+
const {sun, ambient, local} = daeEngineLights(dae);
|
|
524
|
+
if (sun) {
|
|
525
|
+
engine.scene.lighting.direction.set([...sun.toward, sun.intensity]);
|
|
526
|
+
engine.scene.lighting.radiance.set(sun.color);
|
|
527
|
+
}
|
|
528
|
+
if (ambient) {
|
|
529
|
+
engine.scene.lighting.ambient.set(ambient.color);
|
|
530
|
+
engine.scene.lighting.radiance[3] = ambient.intensity;
|
|
531
|
+
}
|
|
532
|
+
Clustered.attach(engine).setLights(local);
|
|
533
|
+
```
|
|
534
|
+
|
|
535
|
+
### Collada skins, morphs and animation
|
|
536
|
+
|
|
537
|
+
The result also has `skins`, `morphs`, `animations` and `clips`, all in the same Y-up meters as the geometry: node transforms, `bind_shape_matrix`, inverse bind matrices and animated values go through one conversion, so a `Z_UP` centimeter rig poses exactly like its Y-up meter twin.
|
|
538
|
+
|
|
539
|
+
- `skins`: each `<controller><skin>` as `{id, name, geometry, morph, bindShapeMatrix, joints, inverseBindMatrices, vertexJoints, vertexWeights}`. `joints` come from `Name_array` (sids) or `IDREF_array` (node ids); `vertex_weights` (`vcount`/`v`) keep the strongest four influences per `<vertices>` position, renormalised to sum 1, joint -1 being the bind shape. A skin may wrap a morph.
|
|
540
|
+
- `morphs`: each `<controller><morph>` as `{id, name, method, base, targets, weights}`; `NORMALIZED` blends (1 - sum w) base + sum w target, `RELATIVE` base + sum w target, position by position. `morphDAE(dae, morph, weights?)` returns the blended mesh (normals included), in the base mesh's vertex order.
|
|
541
|
+
- `<instance_controller>` adds an instance with `skin` and/or `morph`; `joints` lists the joint nodes, found by sid under its `<skeleton>` roots (else by id or name, else anywhere in the scene). A joint that names no node is reported and the instance stays unskinned.
|
|
542
|
+
- `animations`: every `<animation>`, nested ones included (each names its `parent`), with `channels` `{target, node, transform, morph, index, sampler}`. Targets address a node transform by sid, whole (`node/transform` matrix, `node/location` translate) or one value (`.X`, `.Y`, `.Z`, `.ANGLE`, `(i)`, and `(row)(column)` in a matrix), or a morph weight (`morph/weights(i)` or `weightsSource(i)`). Samplers keep `LINEAR`, `STEP`, `BEZIER` (2D `(time, value)` tangents, or value-only ones at a third of the segment) and `HERMITE` (value tangents) keys; `sampleDAESampler(sampler, seconds)` evaluates one, other interpolations sample as `LINEAR` with a warning. `clips` are `<animation_clip>`s `{id, name, start, end, animations}`.
|
|
543
|
+
- `poseDAE(dae, seconds, {clip})` gives every node's `local` and `world` matrix and every morph's `weights` at a time (a clip's time 0 is its `start`).
|
|
544
|
+
|
|
545
|
+
To play a rig on the GPU, `bindDAESkin(dae, instance?)` gives the animation package's `Skeleton` and `Skin` their inputs: the joint nodes and their ancestors as bones (named by `daeNodeNames`, split into translation, rotation and scale), inverse bind matrices, and four joints and weights per vertex of `geometry`, the mesh in its bind shape. Bones live in scene space, so keep the mesh at the scene root. `daeKeyframeClip(dae, {clip, fps})` turns the channels into `createKeyframeClip` input: COLLADA channels move single transform elements, so each animated node is sampled at its key times and every `1 / fps` second (default 30) and split into translation, rotation and scale tracks (nodes that only STEP keep their keys, `discrete`); animated morphs become `weights` tracks.
|
|
546
|
+
|
|
547
|
+
```ts
|
|
548
|
+
import {parseDAE, bindDAESkin, daeKeyframeClip, morphDAE, poseDAE} from 'margoengine/loaders';
|
|
549
|
+
import {Skeleton, Skin, createKeyframeClip, applyKeyframeClip, segmentTime} from 'margoengine/animation';
|
|
550
|
+
import {Material, createMesh} from 'margoengine/materials';
|
|
551
|
+
import {Engine} from 'margoengine/core';
|
|
552
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
553
|
+
const text = await (await fetch('/text.txt')).text();
|
|
554
|
+
const dae = parseDAE(text);
|
|
555
|
+
const binding = bindDAESkin(dae); // the first skinned instance
|
|
556
|
+
const skeleton = new Skeleton(binding.bones, binding.inverseBindMatrices);
|
|
557
|
+
const body = createMesh(engine, binding.geometry, new Material({color: '#c08060'}));
|
|
558
|
+
Skin.attach(body, skeleton, binding.joints, binding.weights);
|
|
559
|
+
const clip = createKeyframeClip(daeKeyframeClip(dae, {fps: 60}));
|
|
560
|
+
// A morphed (unskinned) instance: blend on the CPU and replace the geometry.
|
|
561
|
+
const face = dae.morphs.length ? createMesh(engine, morphDAE(dae, 0), new Material({color: '#e0b090'})) : undefined;
|
|
562
|
+
let elapsed = 0;
|
|
563
|
+
function frame(delta: number): void {
|
|
564
|
+
elapsed += delta;
|
|
565
|
+
const time = segmentTime(elapsed, clip.duration, {loop: true});
|
|
566
|
+
applyKeyframeClip(clip, skeleton, time); // the GPU skin follows next frame
|
|
567
|
+
face?.setGeometry(morphDAE(dae, 0, poseDAE(dae, time).weights[0]));
|
|
568
|
+
}
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
`Skin` takes no morph targets, so a morph is blended on the CPU (`morphDAE`), and a skin over a morph re-binds with `bindDAESkin(dae, instance, {weights})` and `setGeometry`. Without the animation package, `flattenDAE(dae, poseDAE(dae, seconds))` bakes any frame on the CPU.
|
|
572
|
+
|
|
573
|
+
### Collada kinematics
|
|
574
|
+
|
|
575
|
+
`parseDAEKinematics` of `@margoengine/loaders/dae-kinematics` is `parseDAE` plus the COLLADA 1.5 kinematics libraries (`library_joints`, `library_kinematics_models`, `library_articulated_systems`, `library_kinematics_scenes` and `instance_kinematics_scene`), as robot and machine exporters write them. `poseDAEJoints` moves the model by joint value.
|
|
576
|
+
|
|
577
|
+
```ts
|
|
578
|
+
import {createMeshes, flattenDAE} from 'margoengine/loaders';
|
|
579
|
+
import {parseDAEKinematics, poseDAEJoints} from 'margoengine/loaders/dae-kinematics';
|
|
580
|
+
import {Engine} from 'margoengine/core';
|
|
581
|
+
|
|
582
|
+
// A one-joint arm: the plate under node "arm" turns about the vertical axis.
|
|
583
|
+
const text = `<COLLADA version="1.5.0">
|
|
584
|
+
<library_geometries><geometry id="plate"><mesh>
|
|
585
|
+
<source id="p"><float_array id="pa" count="12">0 0 -0.2 1 0 -0.2 1 0 0.2 0 0 0.2</float_array>
|
|
586
|
+
<technique_common><accessor source="#pa" count="4" stride="3"/></technique_common></source>
|
|
587
|
+
<vertices id="v"><input semantic="POSITION" source="#p"/></vertices>
|
|
588
|
+
<polylist count="1"><input semantic="VERTEX" source="#v" offset="0"/><vcount>4</vcount><p>0 3 2 1</p></polylist>
|
|
589
|
+
</mesh></geometry></library_geometries>
|
|
590
|
+
<library_visual_scenes><visual_scene id="vs"><node id="arm">
|
|
591
|
+
<rotate sid="turn">0 1 0 0</rotate><instance_geometry url="#plate"/>
|
|
592
|
+
</node></visual_scene></library_visual_scenes>
|
|
593
|
+
<library_joints><joint id="shoulder" sid="shoulder"><revolute sid="axis0">
|
|
594
|
+
<axis>0 1 0</axis><limits><min>-120</min><max>120</max></limits>
|
|
595
|
+
</revolute></joint></library_joints>
|
|
596
|
+
<library_kinematics_models><kinematics_model id="model"><technique_common>
|
|
597
|
+
<instance_joint url="#shoulder" sid="shoulder"/><link sid="base"/>
|
|
598
|
+
</technique_common></kinematics_model></library_kinematics_models>
|
|
599
|
+
<library_kinematics_scenes><kinematics_scene id="ks">
|
|
600
|
+
<instance_kinematics_model url="#model" sid="robot"/>
|
|
601
|
+
</kinematics_scene></library_kinematics_scenes>
|
|
602
|
+
<scene><instance_visual_scene url="#vs"/><instance_kinematics_scene url="#ks">
|
|
603
|
+
<bind_joint_axis target="arm/turn"><axis><SIDREF>ks/robot/shoulder/axis0</SIDREF></axis>
|
|
604
|
+
<value><float>0</float></value></bind_joint_axis>
|
|
605
|
+
</instance_kinematics_scene></scene></COLLADA>`;
|
|
606
|
+
|
|
607
|
+
const dae = parseDAEKinematics(text);
|
|
608
|
+
console.log(dae.joints.map((j) => [j.name, j.type, j.min, j.max])); // [['shoulder', 'revolute', -120, 120]]
|
|
609
|
+
const pose = poseDAEJoints(dae, {shoulder: 45}); // degrees; meters for a prismatic joint
|
|
610
|
+
console.log(pose.world.get(dae.nodes[0])); // the arm's matrix, for meshes of your own
|
|
611
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
612
|
+
createMeshes(engine, flattenDAE(dae, pose));
|
|
613
|
+
engine.start();
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
- `joints`: one entry per revolute or prismatic axis, in document order: `name` (the joint's SID, with the axis SID or the whole `path` added only when two would share it), `joint`, `type`, `axis` (unit, Y-up, in the driven node's frame), `min` and `max`, `value` (where the file binds it), `active`, `locked`, `index`, the motion bounds `speed`, `acceleration`, `deceleration` and `jerk`, and `targets` (the nodes and transforms `bind_joint_axis` ties to it). Revolute values are degrees and prismatic ones meters (`unit meter` applied).
|
|
617
|
+
- Parameters (`newparam`, `setparam`, `param`, `SIDREF`) resolve through the instance tree, so two instances of one robot keep their own joints. `axis_info` limits replace a joint's own.
|
|
618
|
+
- `poseDAEJoints(dae, values, {clamp})` returns a `DAEPose` like `poseDAE`'s. A bound `<rotate>` becomes a rotation about the joint's axis by the value, and a bound `<translate>` the axis times the value; axes you leave out stand at their `value`. Values are held inside the limits unless `clamp: false`. An unknown name, a value that is not finite or a change to a locked axis throws a `RangeError`. The pose holds joints only: it does not play the file's animations.
|
|
619
|
+
- Not evaluated: `formula` (coupled or mimic joints, reported in `warnings`: pose those axes yourself), closed-loop attachments, tool frames (`frame_tip`, `frame_tcp`) and kinematics held in another file. Inverse kinematics is not part of the format.
|
|
620
|
+
|
|
621
|
+
## DXF block attributes
|
|
622
|
+
|
|
623
|
+
`parseDXF` returns the visible attributes of block references (room numbers, tags, title block fields) in `texts`,
|
|
624
|
+
each with its `tag`.
|
|
625
|
+
|
|
626
|
+
```ts
|
|
627
|
+
import { parseDXF } from '@margoengine/loaders';
|
|
628
|
+
|
|
629
|
+
// A block reference with one attribute.
|
|
630
|
+
const groups = [
|
|
631
|
+
0, 'SECTION', 2, 'BLOCKS', 0, 'BLOCK', 2, 'Door', 10, 0, 20, 0, 0, 'ENDBLK', 0, 'ENDSEC',
|
|
632
|
+
0, 'SECTION', 2, 'ENTITIES', 0, 'INSERT', 66, 1, 2, 'Door', 10, 4, 20, 2,
|
|
633
|
+
0, 'ATTRIB', 10, 4.2, 20, 2.1, 40, 0.25, 1, 'D12 %%c900', 2, 'NUMBER', 70, 0, 0, 'SEQEND', 0, 'ENDSEC', 0, 'EOF',
|
|
634
|
+
];
|
|
635
|
+
const drawing = parseDXF(new TextEncoder().encode(groups.join('\n')));
|
|
636
|
+
for (const { tag, text, position } of drawing.texts) console.log(tag, text, position); // NUMBER D12 ∅900 [4.2, 2.1, 0]
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
- An `ATTRIB` stands where the file puts it and takes the `INSERT`'s layer (when it is on layer 0) and colour (BYBLOCK).
|
|
640
|
+
An `INSERT` with rows and columns repeats its attributes with each copy.
|
|
641
|
+
- Constant attribute definitions of a block are drawn with the block; an attribute definition outside a block shows its
|
|
642
|
+
tag. Invisible attributes and empty values are left out.
|
|
643
|
+
- A multiline attribute reads the MTEXT after its group code 101.
|
|
644
|
+
- `TEXT`, `MTEXT` and attributes resolve the `%%d`, `%%p`, `%%c`, `%%%` and `%%nnn` control codes and drop the
|
|
645
|
+
`%%u`, `%%o` and `%%k` toggles.
|
|
646
|
+
|
|
647
|
+
## DXF leaders
|
|
648
|
+
|
|
649
|
+
`parseDXF` draws `LEADER` and `MULTILEADER` with no option. Leader lines go to `lines` as segments (splines sampled
|
|
650
|
+
`splineSegments` times a span), closed filled arrowheads to `mesh`, and a `MULTILEADER`'s text to `texts`. Its block
|
|
651
|
+
content, attribute values included, and custom arrowhead blocks are drawn from the drawing's `BLOCKS`.
|
|
652
|
+
|
|
653
|
+
- The arrow size is the entity's own (`MULTILEADER`), or `DIMASZ` x `DIMSCALE` from the leader's style overrides,
|
|
654
|
+
then its `DIMSTYLE`, then the header (`LEADER`). As in AutoCAD, a first segment shorter than twice that size has no
|
|
655
|
+
arrow.
|
|
656
|
+
- A `LEADER` that carries text above its line (`DIMTAD`) runs on under the text.
|
|
657
|
+
- Breaks are cut out of straight leader lines and doglegs. A leader type of "none" draws only the content.
|
|
658
|
+
- Not drawn: tolerance content (counted in `skipped`), the text frame and background, leader colours, linetypes and
|
|
659
|
+
weights set apart from the entity's, and MTEXT column layout.
|
|
660
|
+
|
|
661
|
+
```ts
|
|
662
|
+
import { parseDXF } from '@margoengine/loaders';
|
|
663
|
+
|
|
664
|
+
// A leader from (0, 0) over (4, 3) to (10, 3), with arrows of size 1.
|
|
665
|
+
const groups = [
|
|
666
|
+
0, 'SECTION', 2, 'HEADER', 9, '$DIMASZ', 40, 1, 0, 'ENDSEC', 0, 'SECTION', 2, 'ENTITIES',
|
|
667
|
+
0, 'LEADER', 71, 1, 72, 0, 73, 3, 76, 3, 10, 0, 20, 0, 10, 4, 20, 3, 10, 10, 20, 3,
|
|
668
|
+
0, 'ENDSEC', 0, 'EOF',
|
|
669
|
+
];
|
|
670
|
+
const file = new TextEncoder().encode(groups.join('\n'));
|
|
671
|
+
const drawing = parseDXF(file);
|
|
672
|
+
console.log(drawing.lines.positions.length / 6); // 2 segments
|
|
673
|
+
console.log(drawing.mesh.positions.length / 9); // 1 triangle, the arrow
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
## DXF hatches
|
|
677
|
+
|
|
678
|
+
`readDXFHatch` of `@margoengine/loaders/dxf-hatch` draws the `HATCH` entities of a drawing. Pass it to `parseDXF` as
|
|
679
|
+
`hatch`; without it they are counted in `skipped.HATCH` and their code is not in your bundle.
|
|
680
|
+
|
|
681
|
+
```ts
|
|
682
|
+
import { parseDXF } from '@margoengine/loaders';
|
|
683
|
+
import { readDXFHatch } from '@margoengine/loaders/dxf-hatch';
|
|
684
|
+
|
|
685
|
+
// A 4 x 3 area hatched with horizontal lines 0.5 apart.
|
|
686
|
+
const groups = [
|
|
687
|
+
0, 'SECTION', 2, 'ENTITIES', 0, 'HATCH', 62, 3, 70, 0, 91, 1,
|
|
688
|
+
92, 3, 72, 0, 73, 1, 93, 4, 10, 0, 20, 0, 10, 4, 20, 0, 10, 4, 20, 3, 10, 0, 20, 3, 97, 0,
|
|
689
|
+
75, 0, 76, 1, 78, 1, 53, 0, 43, 0, 44, 0.25, 45, 0, 46, 0.5, 79, 0, 0, 'ENDSEC', 0, 'EOF',
|
|
690
|
+
];
|
|
691
|
+
const file = new TextEncoder().encode(groups.join('\n'));
|
|
692
|
+
const drawing = parseDXF(file, { hatch: readDXFHatch });
|
|
693
|
+
console.log(drawing.lines.positions.length / 6); // 6 segments; solid hatches go to drawing.mesh
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
- **Solid hatches** are triangles in `mesh`, grouped by layer and colour like every face. A gradient hatch is filled
|
|
697
|
+
with its first gradient colour.
|
|
698
|
+
- **Pattern hatches** are segments in `lines`: every pattern definition line of the file, with its dashes. A dot is a
|
|
699
|
+
segment of no length, which round caps draw (`cap: 'round'`, the default of `@margoengine/lines`).
|
|
700
|
+
- **Boundaries** may be polylines (with bulges) or edge paths of lines, circular arcs, elliptic arcs and splines.
|
|
701
|
+
`arcSegments` and `splineSegments` set their sampling.
|
|
702
|
+
- **Islands** follow the file's hatch style: normal (every other ring), outer (the outermost area only) or ignore.
|
|
703
|
+
- **Limits.** Segments and dots count against `maxSegments`, triangles against `maxTriangles` and `maxVertices`; a
|
|
704
|
+
pattern too fine for them is a `limit` error. At most 10,000 boundary paths per hatch. A fill lies in the same plane
|
|
705
|
+
as the drawing's lines, so draw lines after the mesh or give them a depth bias. `MPOLYGON` entities are skipped.
|
|
706
|
+
|
|
707
|
+
## Motion capture (BVH)
|
|
708
|
+
|
|
709
|
+
`parseBVH(textOrBytes, {scale, name, maxJoints, maxKeys})` from `./mocap` reads Biovision HIERARCHY and MOTION into bones and a clip the animation package plays. BVH has no unit: `scale: 0.01` turns centimetres to metres (default 1). Euler channels apply in the order the file lists them, and a position channel moves the joint from its OFFSET. `End Site` offsets sit on the bone as `endSite`. The defaults are 4,096 joints and 4,000,000 keys.
|
|
710
|
+
|
|
711
|
+
```ts
|
|
712
|
+
import { Skeleton, applyKeyframeClip, createKeyframeClip } from '@margoengine/animation';
|
|
713
|
+
import { parseBVH } from '@margoengine/loaders/mocap';
|
|
714
|
+
|
|
715
|
+
const file = `HIERARCHY
|
|
716
|
+
ROOT Hips { OFFSET 0 90 0 CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation }
|
|
717
|
+
MOTION
|
|
718
|
+
Frames: 2
|
|
719
|
+
Frame Time: 0.5
|
|
720
|
+
0 0 0 0 0 0
|
|
721
|
+
0 0 10 0 45 0
|
|
722
|
+
`;
|
|
723
|
+
const { bones, clip } = parseBVH(file, { scale: 0.01 });
|
|
724
|
+
const skeleton = new Skeleton(bones);
|
|
725
|
+
applyKeyframeClip(createKeyframeClip(clip), skeleton, 0.25);
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
## Acclaim and CMU motion capture (ASF and AMC)
|
|
729
|
+
|
|
730
|
+
`parseASF(textOrBytes, {scale, maxJoints})` from `./mocap` reads an Acclaim skeleton (ASF 1.10, the format of the Carnegie Mellon University motion capture database) and `parseAMC(textOrBytes, skeleton, {frameTime, name, maxKeys})` reads a motion for it. The bones come out in `parseBVH`'s shape: one joint at each bone's start, parents first, resting unrotated with offsets in the skeleton's world frame, and the bone's far end as `endSite`. Each AMC frame turns a bone by its Euler angles in the bone's own `axis` frame, the axes applied in the order its `dof` line lists them. `scale` multiplies lengths (default 1; CMU files are in units of 0.45 inch, so `scale: 0.0254 / 0.45` gives metres). AMC files store no frame rate: `frameTime` defaults to 1/120 s, the rate of most CMU trials. The defaults are 4,096 joints and 4,000,000 keys. Bad files throw a `LoaderError` with a `code` (`header`, `syntax`, `truncated`, `range` or `limit`). `@margoengine/rigging` `prepareRetarget` names the joints with its `cmu` preset, so a CMU clip drives a Mixamo, VRM or Godot rig.
|
|
731
|
+
|
|
732
|
+
```ts
|
|
733
|
+
import { Skeleton, applyKeyframeClip, createKeyframeClip } from '@margoengine/animation';
|
|
734
|
+
import { parseAMC, parseASF } from '@margoengine/loaders/mocap';
|
|
735
|
+
|
|
736
|
+
const skeleton = parseASF(`:version 1.10
|
|
737
|
+
:name tiny
|
|
738
|
+
:units
|
|
739
|
+
length 1
|
|
740
|
+
angle deg
|
|
741
|
+
:root
|
|
742
|
+
order TX TY TZ RX RY RZ
|
|
743
|
+
axis XYZ
|
|
744
|
+
position 0 1 0
|
|
745
|
+
orientation 0 0 0
|
|
746
|
+
:bonedata
|
|
747
|
+
begin
|
|
748
|
+
id 1
|
|
749
|
+
name spine
|
|
750
|
+
direction 0 1 0
|
|
751
|
+
length 0.5
|
|
752
|
+
axis 0 0 0 XYZ
|
|
753
|
+
dof rx ry rz
|
|
754
|
+
end
|
|
755
|
+
:hierarchy
|
|
756
|
+
begin
|
|
757
|
+
root spine
|
|
758
|
+
end
|
|
759
|
+
`);
|
|
760
|
+
const { bones, clip, frames } = parseAMC(
|
|
761
|
+
`:FULLY-SPECIFIED
|
|
762
|
+
:DEGREES
|
|
763
|
+
1
|
|
764
|
+
root 0 0 0 0 0 0
|
|
765
|
+
spine 0 0 0
|
|
766
|
+
2
|
|
767
|
+
root 0 0 0.1 0 0 0
|
|
768
|
+
spine 10 0 0
|
|
769
|
+
`,
|
|
770
|
+
skeleton,
|
|
771
|
+
{ frameTime: 1 / 120, name: 'lean' },
|
|
772
|
+
);
|
|
773
|
+
const pose = new Skeleton(bones);
|
|
774
|
+
applyKeyframeClip(createKeyframeClip(clip), pose, 1 / 240);
|
|
775
|
+
console.log(frames, bones.map((b) => b.name)); // 2 [ 'root', 'spine' ]
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
## VRML and X3D
|
|
779
|
+
|
|
780
|
+
`parseVRML(textOrBytes, options)` reads VRML97 (`#VRML V2.0 utf8`) and `parseX3D(textOrBytes, options)` reads X3D XML, both from `./vrml`, into one `LoadedGeometry` with a group per Shape, so `toGeometry` takes the result. Transform (with `center` and `scaleOrientation`), Group, Anchor, Collision and Billboard nest and bake into world space. A Switch draws the child its `whichChoice` names (none for the default -1), and an LOD draws its first, most detailed level, since a file read has no viewer distance. Shape, Appearance, Material, IndexedFaceSet with normals, colours and texture coordinates per vertex or per face, `ccw`, `convex` and DEF/USE are read: faces are fanned, and a face set marked `convex FALSE` is ear-clipped so concave faces come out right. A Material without `diffuseColor` colours its vertices 0.8 grey, the VRML97 default; a Shape with no Material is unlit white. `v` turns to Margo's convention, with 0 at the image's top. Anything else, such as Box, Inline, PROTO instances and textures, is left out and named in `warnings`. `maxNodes` (default 1,000,000) counts each USE again, so a file of nested USEs stops early.
|
|
781
|
+
|
|
782
|
+
```ts
|
|
783
|
+
import { parseVRML } from '@margoengine/loaders/vrml';
|
|
784
|
+
|
|
785
|
+
const scene = parseVRML(`#VRML V2.0 utf8
|
|
786
|
+
Transform { translation 0 1 0 children
|
|
787
|
+
Shape {
|
|
788
|
+
appearance Appearance { material Material { diffuseColor 1 0.5 0 } }
|
|
789
|
+
geometry IndexedFaceSet { coord Coordinate { point [0 0 0, 1 0 0, 0 1 0] } coordIndex [0 1 2 -1] }
|
|
790
|
+
}
|
|
791
|
+
}`);
|
|
792
|
+
console.log(scene.groups?.[0].color, scene.warnings);
|
|
793
|
+
```
|
|
794
|
+
|
|
795
|
+
## PRWM
|
|
796
|
+
|
|
797
|
+
`parsePRWM(bytes, {maxVertices, maxTriangles})` from `./prwm` reads Packed Raw WebGL Model version 1 (specification: github.com/kchapelier/PRWM, `specifications/prwm.md`), little or big endian, indexed (16 or 32 bit) or not. Attributes named `position`, `normal`, `uv` (`uv0`, `texcoord`) and `color` fill `positions`, `normals`, `uvs` and `colors` (normalized integers become floats; `color` keeps RGB); any other attribute lands flattened in `attributes[name]`. `layout` lists each attribute's name, component count, `normalized` and `integer` flags. A non-indexed file gets the triangle list 0, 1, 2, ... (`nonIndexed: true`). Reserved encodings, version 0, a missing position attribute, out-of-range indices and truncation throw a `LoaderError` with a `code`. PRWM has no magic bytes, so `detectFormat` does not guess it; call it by name.
|
|
798
|
+
|
|
799
|
+
```ts
|
|
800
|
+
import { parsePRWM } from '@margoengine/loaders/prwm';
|
|
801
|
+
|
|
802
|
+
// One triangle, one float position attribute, little endian, non-indexed: version 1, 1 attribute, 3 values, 0 indices.
|
|
803
|
+
const header = [1, 0x01, 3, 0, 0, 0, 0, 0];
|
|
804
|
+
const name = [...'position'].map((c) => c.charCodeAt(0)).concat(0, 0x21, 0, 0); // flag: float, 3 components, encoding 1
|
|
805
|
+
const data = new Uint8Array(header.length + name.length + 36);
|
|
806
|
+
data.set([...header, ...name]);
|
|
807
|
+
new Float32Array(data.buffer, header.length + name.length, 9).set([0, 0, 0, 1, 0, 0, 0, 1, 0]);
|
|
808
|
+
const model = parsePRWM(data);
|
|
809
|
+
console.log(model.positions.length, [...model.indices!]); // 9 [0, 1, 2]
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
## Babylon scenes
|
|
813
|
+
|
|
814
|
+
`parseBabylon(input, {rightHanded, maxBytes, maxNodes, maxTextureBytes, maxVertices, maxTriangles})` from `./babylon` reads a Babylon.js `.babylon` scene (JSON; the format is described at doc.babylonjs.com, "Babylon file format"). `input` is the bytes, the JSON text or the parsed object. It returns `{meshes, transformNodes, materials, multiMaterials, cameras, lights, skeletons, clearColor, ambientColor, activeCameraId, producer, warnings}`:
|
|
815
|
+
|
|
816
|
+
- **Meshes** keep the file's vertices (`positions`, `normals`, `uvs`, `uvs2` as `attributes.uv1`, `colors` as rgb) or the shared `geometries.vertexData` they name through `geometryId`; each submesh is a group with `properties.materialIndex`; `instances` become meshes with `instanceOf` that share the geometry object. Placement is `translation`, `rotation` (a quaternion; an Euler `rotation` is read as Babylon's YXZ order) and `scale`, relative to `parentId`. Four (or eight, with `matricesIndicesExtra`) bone influences per vertex arrive as `joints` and `weights`.
|
|
817
|
+
- **Materials** are `standard` (diffuse, specular, specular power, emissive, alpha, `backFaceCulling`) or `pbr` (`PBRMaterial` and `PBRMetallicRoughnessMaterial`: base colour, metallic, roughness). Colours come out linear: Babylon's Standard colours are sRGB and are converted, PBR colours already are linear. Texture slots keep their name, offset, scale, wrap and `invertY`; an embedded `base64String` is decoded into `data`.
|
|
818
|
+
- **Cameras** give `position`, `target`, `fov` and the clip range, from `target`, from `alpha`/`beta`/`radius` (ArcRotate) or from the rotation (Free); `mode` 1 gives `orthographic`. **Lights** are `point`, `directional`, `spot` (full cone `angle`) or `hemispheric`. **Skeletons** list bones with column-major local bind matrices. Node animations of position, rotation and scaling arrive as keys (`animations`).
|
|
819
|
+
- Babylon is left-handed. `rightHanded` (default true) negates Z in positions, normals, placements, camera and light vectors and swaps each triangle's winding, so the scene lands in the engine's space; false keeps the file's numbers.
|
|
820
|
+
- Skipped with a note in `warnings`: delay-loaded `.babylonbinarymeshdata` meshes, pivot matrices, and light types past the four. Particle systems, sprites, sounds, LODs and post processes are not read. A non-JSON, wrongly shaped, out-of-range or cyclic file, an index past the vertices, a submesh past the indices, more than `maxNodes` nodes, a texture past `maxTextureBytes`, or counts past the vertex and triangle limits throws a `LoaderError` with a `code`.
|
|
821
|
+
|
|
822
|
+
`flattenBabylon(scene, {onlyVisible})` bakes every visible mesh's world transform (through its parents) into one `LoadedGeometry`, one group per mesh.
|
|
823
|
+
|
|
824
|
+
```ts
|
|
825
|
+
import { parseBabylon, flattenBabylon } from '@margoengine/loaders/babylon';
|
|
826
|
+
|
|
827
|
+
const scene = parseBabylon({
|
|
828
|
+
cameras: [{ id: 'cam', type: 'FreeCamera', position: [0, 1, -5], target: [0, 1, 0], fov: 0.9 }],
|
|
829
|
+
materials: [{ id: 'red', diffuse: [1, 0, 0] }],
|
|
830
|
+
meshes: [
|
|
831
|
+
{
|
|
832
|
+
id: 'tri',
|
|
833
|
+
position: [1, 2, 3],
|
|
834
|
+
materialId: 'red',
|
|
835
|
+
positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
|
|
836
|
+
indices: [0, 1, 2],
|
|
837
|
+
},
|
|
838
|
+
],
|
|
839
|
+
});
|
|
840
|
+
console.log(scene.cameras[0].position, scene.meshes[0].translation); // [0, 1, 5] [1, 2, -3]
|
|
841
|
+
console.log(flattenBabylon(scene).positions.length / 3); // 3
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
## DirectX .x files
|
|
845
|
+
|
|
846
|
+
`parseX(input, {rightHanded, maxVertices, maxTriangles, maxDepth, maxNodes})` from `./xfile` reads DirectX `.x` files, text (`txt `) or binary (`bin `), with 32 or 64-bit floats (format reference: Microsoft, "DirectX File Format"). `input` is the bytes or the text. Compressed files (`tzip`, `bzip`, MSZip) throw `'unsupported'`. It returns `{format, frames, meshes, materials, animationSets, ticksPerSecond, warnings}`:
|
|
847
|
+
|
|
848
|
+
- **Frames** keep the hierarchy: `name`, `parent` (-1 for a root; parents come first), `matrix` (the FrameTransformMatrix relative to the parent, 16 values column-major), `world` (that times every parent's) and `meshes` (indices into `meshes`). A mesh outside any frame gets a root frame of its own.
|
|
849
|
+
- **Meshes** are triangles: polygons are fanned, and because a `.x` file indexes normals apart from positions, a vertex is split wherever two faces give it different normals. `geometry` holds `positions`, `normals`, `uvs` (MeshTextureCoords), `colors` (MeshVertexColors, rgb) and one group per material (`properties.materialIndex`, triangles sorted by it); `attributes.sourceVertex` gives each output vertex's index in the file. `materials` are the mesh's MeshMaterialList (colour, specular power, specular, emissive, `texture`).
|
|
850
|
+
- **Skin**: each SkinWeights block becomes a bone (`name`, `frame`, `inverseBind`). `joints` and `weights` give four influences per vertex, strongest first (`joints1` and `weights1` hold five to eight; more are dropped and the rest renormalised).
|
|
851
|
+
- **Animation**: each AnimationSet lists animations by frame name with `rotation` (quaternion x, y, z, w; the file stores w, x, y, z), `scale`, `position` and `matrix` tracks, key times in seconds (ticks over AnimTicksPerSecond, default 4800).
|
|
852
|
+
- The format is left-handed with row vectors. `rightHanded` (default true) negates Z in positions, normals, matrices, quaternions and key positions and swaps each triangle's winding; false keeps the file's numbers.
|
|
853
|
+
- A count that claims more data than the file holds, an index past its list, a face with fewer than 3 corners, nesting past `maxDepth`, more than `maxNodes` frames, or counts past the vertex and triangle limits throws a `LoaderError` with a `code`, before anything is allocated from the count.
|
|
854
|
+
|
|
855
|
+
```ts
|
|
856
|
+
import { parseX } from '@margoengine/loaders/xfile';
|
|
857
|
+
|
|
858
|
+
const x = parseX(`xof 0302txt 0032
|
|
859
|
+
Frame Root {
|
|
860
|
+
FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,5,1;; }
|
|
861
|
+
Mesh Tri { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3;0,1,2;; }
|
|
862
|
+
}`);
|
|
863
|
+
console.log(x.frames[0].matrix.slice(12, 15), x.meshes[0].geometry.indices?.length); // [0, 0, -5] 3
|
|
864
|
+
```
|
|
865
|
+
|
|
866
|
+
## MikuMikuDance models and motions
|
|
867
|
+
|
|
868
|
+
`parsePMD`, `parsePMX` and `parseMMD` (either, by signature) read MikuMikuDance models; `parseVMD` reads motion and camera clips. All from `./mmd`. Formats: the PMD 1.0 layout, the PMX 2.0 and 2.1 specification and the VMD layout. MMD is left-handed and measures in units of about 8 cm: `scale` (default 0.08) turns units into metres and `rightHanded` (default true) mirrors Z (positions, normals, Euler angles and quaternions) and swaps the winding; `maxVertices` and `maxTriangles` apply.
|
|
869
|
+
|
|
870
|
+
`parsePMX(bytes, options)` returns `{format, version, name, comment, geometry, joints, weights, sdef, materials, textures, bones, morphs, rigidBodies, joints_, warnings}`:
|
|
871
|
+
|
|
872
|
+
- `geometry` is the mesh with one group per material (`properties.materialIndex`); `attributes` holds `uv1` to `uv4` (four values each, the extra UV sets) and `edgeScale`. `joints` and `weights` give four bone influences a vertex (BDEF1, BDEF2, BDEF4, QDEF; SDEF counts as BDEF2 and its C, R0 and R1 vectors are in `sdef`).
|
|
873
|
+
- `materials` carry diffuse, specular, ambient, edge colour and size, double-sided and edge flags, texture, sphere map and mode, and toon; `triangles` counts each group.
|
|
874
|
+
- `bones` have parent, deform layer, flags, tail, inherit (grant) bone and rate, after-physics flag and IK (target, iterations, limit angle, links with optional angle limits). `morphs` are group, vertex, bone, UV, extra UV, material, flip and impulse morphs with their offsets.
|
|
875
|
+
- `rigidBodies` and `joints_` are parsed as data only: shape, size, position, rotation, mass, damping, restitution, friction, group and mask, mode, and the joints' limits and springs. Nothing here simulates them.
|
|
876
|
+
- Soft bodies of PMX 2.1 are not read (a note in `warnings`). Index sizes of 1, 2 and 4 bytes, UTF-16 and UTF-8 text, and the extra UV sets are honoured.
|
|
877
|
+
|
|
878
|
+
`parsePMD(bytes, options)` reads the older format into the same shape: two-bone weights, per-material face ranges, bones with IK chains, morphs, the English name block, and rigid bodies and joints. Shift-JIS names are decoded with `TextDecoder('shift_jis')`.
|
|
879
|
+
|
|
880
|
+
`parseVMD(bytes, {scale, rightHanded, maxKeys})` returns `{modelName, fps: 30, bones, morphs, camera, lights, shadows, ik, duration}`. Bone and morph keys are grouped by name and sorted by frame (`bones[i]`: `frames`, `positions`, `rotations` as x, y, z, w, and 64 bytes of `interpolation` a key; `morphs[i]`: `frames`, `weights`). `camera` holds `frames`, `distance`, `position` (the point looked at), Euler `rotation`, `fov` in radians, a `perspective` flag and 24 bytes of `interpolation` a key. `sampleVMDBone(track, frame)` samples a bone at a (fractional) frame, easing each axis and the rotation with the later key's Bezier curves; `vmdBezier` is the curve alone. An old file that ends after the bone keys parses with the later sections empty.
|
|
881
|
+
|
|
882
|
+
Hostile files throw a `LoaderError` with a `code`: a count that claims more records than the bytes can hold is refused before anything is allocated, as are bad index sizes, texts, bone, texture, morph and vertex indices past their lists, and counts past the limits.
|
|
883
|
+
|
|
884
|
+
```ts
|
|
885
|
+
import { parseVMD, sampleVMDBone } from '@margoengine/loaders/mmd';
|
|
886
|
+
|
|
887
|
+
// A 'Vocaloid Motion Data 0002' file with one bone key at frame 0 and one at frame 10.
|
|
888
|
+
const bytes = new Uint8Array(30 + 20 + 4 + 2 * 111 + 16);
|
|
889
|
+
bytes.set(new TextEncoder().encode('Vocaloid Motion Data 0002'));
|
|
890
|
+
bytes.set(new TextEncoder().encode('model'), 30);
|
|
891
|
+
const view = new DataView(bytes.buffer);
|
|
892
|
+
view.setUint32(50, 2, true);
|
|
893
|
+
for (const [i, [frame, x]] of [[0, 0], [10, 10]].entries()) {
|
|
894
|
+
const at = 54 + i * 111;
|
|
895
|
+
bytes.set(new TextEncoder().encode('arm'), at);
|
|
896
|
+
view.setUint32(at + 15, frame, true);
|
|
897
|
+
view.setFloat32(at + 19, x, true);
|
|
898
|
+
view.setFloat32(at + 43, 1, true); // quaternion w
|
|
899
|
+
bytes.set([20, 20, 20, 20, 20, 20, 20, 20, 107, 107, 107, 107, 107, 107, 107, 107], at + 47); // curve x1, y1, x2, y2
|
|
900
|
+
}
|
|
901
|
+
const motion = parseVMD(bytes, { scale: 1 });
|
|
902
|
+
console.log(motion.bones[0].name, sampleVMDBone(motion.bones[0], 5)!.position[0].toFixed(2)); // arm 5.00
|
|
903
|
+
```
|
|
904
|
+
|
|
905
|
+
## Tilt Brush
|
|
906
|
+
|
|
907
|
+
`parseTilt(bytes, {scale, rightHanded, widthScale, minControlPoints, signal, maxVertices, ...zip limits})` from `./tilt` reads a Tilt Brush or Open Brush `.tilt` sketch (a zip behind a 16-byte `tilT` header, holding `data.sketch` and `metadata.json`; format notes at docs.openbrush.app/developer-notes/open-brush-file-format) and returns `{geometry, strokes, brushes, metadata, version}`. Every stroke becomes a flat ribbon through its control points: width `size * pressure * widthScale` along the controller's local X axis, one vertex colour (the stroke's RGB) and one group per stroke (`color`, `name` = the brush GUID from `metadata.json`'s `BrushIndex`, `properties.brushIndex`). Draw it double-sided. `scale` is metres per sketch unit (default 0.1: sketches are in decimetres); `rightHanded` (default true) mirrors Tilt Brush's left-handed space into the engine's and keeps the winding. `strokes` keeps every stroke as stored (colour, size, control points with orientation, pressure and timestamp). Stroke and control point extension fields are skipped by their size; only pressure and timestamp are read. Brush looks (glow, fire, ink) are not reproduced: ribbons carry the colour only. `parseTiltSketch(bytes)` reads an already-unzipped `data.sketch`.
|
|
908
|
+
|
|
909
|
+
```ts
|
|
910
|
+
import { parseTilt } from '@margoengine/loaders/tilt';
|
|
911
|
+
|
|
912
|
+
const bytes = new Uint8Array(await (await fetch('/sketches/ribbon.tilt')).arrayBuffer());
|
|
913
|
+
const { geometry, strokes, brushes } = await parseTilt(bytes, { signal: AbortSignal.timeout(10_000) });
|
|
914
|
+
console.log(geometry.positions.length / 6, strokes.length, brushes.length); // control points, strokes, brushes
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
## G-code
|
|
918
|
+
|
|
919
|
+
`parseGCode(textOrBytes, {maxVertices, arcP})` from `./gcode` reads RepRap toolpaths: G0 and G1 with X, Y, Z, E; G2 and G3 arcs; G17, G18, G19; G90.1, G91.1; G90, G91, M82, M83; G92; G20, G21; G28. Layers come by rising Z, each with `extrusion` (moves that push material) and `travel` (moves that lead into it), two points per segment. Coordinates stay the machine's: millimetres, Z up.
|
|
920
|
+
|
|
921
|
+
Arcs follow the RepRap and LinuxCNC references. The centre is given by I, J and K, its offset from the start (I J in the XY plane of G17, the default; K I in ZX for G18; J K in YZ for G19), or by R, where a positive radius takes the arc under 180 degrees and a negative one the arc over it. G2 turns clockwise and G3 counter-clockwise, seen from the positive end of the plane's normal axis. G90.1 makes I, J and K the centre itself, in the program's coordinates whatever G90 or G91 says, and then both of the plane's two centre words must be given (LinuxCNC); G91.1, the default, makes them an offset again. An arc that ends where it starts is a full circle and the normal axis moves evenly along the arc, a helix. P on an arc counts as `arcP` says: `'turns'` (the default, LinuxCNC) reads P as the number of turns, P1 the programmed arc alone; `'circles'` (Marlin with `ARC_P_CIRCLES`, whose page calls P "complete circles") draws P full circles on top of the arc, so Marlin's P1 is LinuxCNC's P2. Each arc is drawn as chords no more than 0.002 mm from it, with its E spread evenly, so the layers and the filament total count it like any move. An end more than LinuxCNC's tolerance off the circle (0.5 mm, or both 0.005 mm and 0.1% of the radius) is a `range` error, as is an R shorter than half the chord.
|
|
922
|
+
|
|
923
|
+
```ts
|
|
924
|
+
import { parseGCode } from '@margoengine/loaders/gcode';
|
|
925
|
+
|
|
926
|
+
const { layers, filament, min, max } = parseGCode('G1 Z0.2\nG1 X10 E1\nG3 X0 Y10 I-10 E2\nG2 X0 Y0 R5 E3\n');
|
|
927
|
+
const first = { mode: 'segments', positions: layers[0].extrusion };
|
|
928
|
+
console.log(first.positions.length, filament, min, max);
|
|
929
|
+
|
|
930
|
+
// G90.1: I and J name the centre itself. arcP 'circles' reads a Marlin file's P as extra full circles.
|
|
931
|
+
const marlin = parseGCode('G1 Z0.2\nG1 X10 E1\nG90.1\nG3 X10 Y0 I0 J0 P1 E5\n', { arcP: 'circles' });
|
|
932
|
+
console.log(marlin.layers[0].extrusion.length, marlin.filament);
|
|
933
|
+
```
|
|
934
|
+
|
|
935
|
+
`toolpathBeads(segments, {width, height, round})` turns a layer's `extrusion` or `travel` into solid beads, as a slicer preview draws them: each segment becomes a closed prism of the stadium section extruded filament takes (a rectangle with half-round sides, Comminal et al. 2018), `width` across (default 0.45) and `height` tall (default 0.2) with its top on the nozzle path. It returns `{positions, normals, indices}` in the file's frame, Z up, ready for a core `Geometry`.
|
|
936
|
+
|
|
937
|
+
```ts
|
|
938
|
+
import { parseGCode, toolpathBeads } from '@margoengine/loaders/gcode';
|
|
939
|
+
|
|
940
|
+
const { layers } = parseGCode('G1 Z0.28\nG1 X20 E1\nG1 Y20 E2\n');
|
|
941
|
+
const bead = toolpathBeads(layers[0].extrusion, { width: 0.45, height: 0.28 });
|
|
942
|
+
console.log(bead.positions.length / 3, bead.indices.length / 3);
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
## NRRD volumes
|
|
946
|
+
|
|
947
|
+
`parseNRRD` from `@margoengine/loaders/nrrd` reads the NRRD files CT and MRI tools write, `.nrrd` and detached `.nhdr`, into the arrays `fig.volume()` of `@margoengine/sciviz` takes. It reads raw, ascii, hex and gzip data in either byte order, `line skip`, `byte skip` (with -1 for the end of a raw file), and one data file, a printf pattern such as `slice%03d.raw` or a `LIST`, each with its optional `subdim` (by default one slice along the slowest axis per file, and the file count must match). Samples stay in the file's own type; 64-bit integers become `Float64Array`, exact up to 2^53.
|
|
948
|
+
|
|
949
|
+
```ts
|
|
950
|
+
import { parseNRRD } from '@margoengine/loaders/nrrd';
|
|
951
|
+
|
|
952
|
+
const header = 'NRRD0004\ntype: short\ndimension: 3\nsizes: 2 2 1\nspace: LPS\n' +
|
|
953
|
+
'space directions: (0.5,0,0) (0,0.5,0) (0,0,2)\nspace origin: (10,0,0)\nencoding: ascii\n\n';
|
|
954
|
+
const scan = await parseNRRD(new TextEncoder().encode(`${header}0 100 200 300\n`));
|
|
955
|
+
console.log(scan.dims, scan.spacing, scan.bounds, scan.matrix);
|
|
956
|
+
// With a figure: fig.volume(scan.data, { dims: scan.dims, bounds: scan.bounds });
|
|
957
|
+
|
|
958
|
+
// A .nhdr header reads its data through resolve, by the path the header names.
|
|
959
|
+
const detached = 'NRRD0004\ntype: uchar\ndimension: 1\nsizes: 2\nencoding: raw\ndata file: body.raw\n';
|
|
960
|
+
const { data } = await parseNRRD(new TextEncoder().encode(detached), {
|
|
961
|
+
resolve: async (path) => new Uint8Array([path.length, 1]),
|
|
962
|
+
});
|
|
963
|
+
console.log(data);
|
|
964
|
+
```
|
|
965
|
+
|
|
966
|
+
- `dims` holds the spatial axes, the first fastest. A leading non-spatial axis (an RGB `kinds` entry, or `none` in `space directions`) is `components`; axes after the spatial ones, such as time, are `frames`. A sample sits at `(((t * nz + z) * ny + y) * nx + x) * components + c`.
|
|
967
|
+
- `bounds` is the box in true proportions from 0. `matrix` takes a voxel index to the file's `space`, with its origin, rotation and flips: use it to line a scan up with other data.
|
|
968
|
+
- `resolve` gets the path as the header writes it, tidied of `.` and `..`. It is your code: keep it inside the folder you trust.
|
|
969
|
+
- The header is checked against the format: the magic is `NRRD0001` to `NRRD0005` alone on its line, a field newer than the magic (key/value pairs before 0002, `kinds` before 0003, `space` fields and several data files before 0004) is a `header` error, as is an unknown `space` or a kind on an axis of the wrong size (`RGB-color` needs 3). ASCII floats follow the format's rule: any word with `nan` is NaN, then `-inf` and `inf`.
|
|
970
|
+
- `maxSamples` (default 536,870,912) stops a huge declared size before anything is allocated. Data past what the header needs is ignored, as the format says: gzip and bzip2 decoding stop once the samples are out, so a small file never inflates to more than it needs. `bzip2` data needs `@margoengine/decoders`. A `block` file comes out as `type: 'block'`, its blocks as stored in a `Uint8Array` of `blockSize` (the `block size` field) bytes each: no byte order applies, ascii encoding is a `header` error, and the blocks may take at most 8 bytes per sample of `maxSamples`.
|
|
971
|
+
|
|
972
|
+
## LDraw
|
|
973
|
+
|
|
974
|
+
`parseLDraw` from `@margoengine/loaders/ldraw` reads LDraw brick models, `.ldr`, `.dat` and multi-part `.mpd`, into one mesh with a group per colour, plus the model's edge lines. Parts load through `resolve` from an LDraw library folder you host, and a part nobody can find is listed in `missing` while the rest of the model still loads.
|
|
975
|
+
|
|
976
|
+
```ts
|
|
977
|
+
import { parseLDraw } from '@margoengine/loaders/ldraw';
|
|
978
|
+
|
|
979
|
+
const parts: Record<string, string> = { 'parts/plate.dat': '0 BFC CERTIFY CCW\n4 16 0 0 0 20 0 0 20 0 20 0 0 20\n2 24 0 0 0 20 0 0\n' };
|
|
980
|
+
const model = await parseLDraw('1 4 0 0 0 1 0 0 0 1 0 0 0 1 plate.dat\n', {
|
|
981
|
+
resolve: async (path) => {
|
|
982
|
+
if (path in parts) return parts[path];
|
|
983
|
+
throw new Error(`no ${path}`);
|
|
984
|
+
},
|
|
985
|
+
});
|
|
986
|
+
console.log(model.groups[0].name, model.lines.length, model.missing);
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
A normal `.ldr` is mostly references, so without a library it draws almost nothing and lists its parts in `missing`. Download the "Complete" library from [ldraw.org](https://www.ldraw.org), unzip it where your site serves files, and pass `resolveFromURL`, which takes `fetch` and `signal`. The library is not part of this package.
|
|
990
|
+
|
|
991
|
+
```ts
|
|
992
|
+
import { parseLDraw, resolveFromURL } from '@margoengine/loaders/ldraw';
|
|
993
|
+
|
|
994
|
+
const text = '1 4 0 0 0 1 0 0 0 1 0 0 0 1 3024.dat\n';
|
|
995
|
+
const model = await parseLDraw(text, { resolve: resolveFromURL('/ldraw/') });
|
|
996
|
+
console.log(model.missing);
|
|
997
|
+
```
|
|
998
|
+
|
|
999
|
+
- **Colours.** 16 takes the colour of the reference above it and 24 that colour's edge. `0x2RRGGBB` is a direct colour. `0 !COLOUR` lines and `LDConfig.ldr` fill the palette, read through `resolve` or passed as `config`; without one, the 16 classic colours apply and an unknown code draws light grey with a warning.
|
|
1000
|
+
- **Parts.** Each reference tries `searchPaths` in order, in lower case with forward slashes. An MPD pack's own files win over the library, and each file is read once.
|
|
1001
|
+
- **Winding.** A file with `0 BFC CERTIFY` keeps its winding through mirrors, `CW` and `INVERTNEXT`. Polygons of an uncertified file, or inside `NOCLIP`, are written on both sides, so they draw correctly with back faces culled. Each file's own certification decides, so a certified part inside a plain `.ldr` model still culls.
|
|
1002
|
+
- **Repeated parts.** `instanced: true` keeps each placed `.dat` part in each colour as one geometry with a matrix per placement, in `model.instances`, so a wall of a thousand alike bricks stores one brick and draws in one call. The main mesh and lines then hold only what is not a placed part, and mirrored placements, which stay expanded because a renderer's winding does not follow a mirrored matrix. See the example below.
|
|
1003
|
+
- **Units.** By default 1 LDraw unit is 0.4 mm and the model turns Y up. `units: 'file'` keeps LDraw units with -Y up.
|
|
1004
|
+
- **Lines.** `lines` and `lineColors` go to `@margoengine/lines` in `segments` mode. `conditionalLines` holds four points each: the two ends, then the two control points that decide whether to draw it. `edges: false` drops them all.
|
|
1005
|
+
- **Limits.** `maxDepth` (64), `maxInstances` (4,000,000) and the shared vertex and triangle limits stop a file of doubling references. Texture maps (`!TEXMAP`) are skipped with a warning.
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
Drawing repeated parts with `@margoengine/materials`, one instanced mesh a part:
|
|
1009
|
+
|
|
1010
|
+
```ts
|
|
1011
|
+
import { createStage } from '@margoengine/stage';
|
|
1012
|
+
import { computeVertexNormals } from '@margoengine/loaders/common';
|
|
1013
|
+
import { parseLDraw } from '@margoengine/loaders/ldraw';
|
|
1014
|
+
import { createInstancedMesh, Material } from '@margoengine/materials';
|
|
1015
|
+
|
|
1016
|
+
const stage = await createStage('#viewport', { backend: 'webgpu' });
|
|
1017
|
+
const brick = '3 16 0 0 0 20 0 0 0 0 20\n3 16 20 0 0 20 0 20 0 0 20\n';
|
|
1018
|
+
const row = Array.from({ length: 100 }, (_, i) => `1 4 ${i * 20} 0 0 1 0 0 0 1 0 0 0 1 brick.dat`).join('\n');
|
|
1019
|
+
const model = await parseLDraw(row, {
|
|
1020
|
+
instanced: true,
|
|
1021
|
+
resolve: async (path) => (path === 'parts/brick.dat' ? brick : Promise.reject(new Error('not here'))),
|
|
1022
|
+
});
|
|
1023
|
+
for (const { positions, indices, groups, matrices } of model.instances) {
|
|
1024
|
+
const materials = groups.map(({ color }) => new Material({ color: color as [number, number, number, number] })),
|
|
1025
|
+
geometry = {
|
|
1026
|
+
positions,
|
|
1027
|
+
normals: computeVertexNormals(positions, indices),
|
|
1028
|
+
indices,
|
|
1029
|
+
groups: groups.map(({ start, count }, materialIndex) => ({ start, count, materialIndex })),
|
|
1030
|
+
},
|
|
1031
|
+
mesh = createInstancedMesh(stage.engine, geometry, materials, matrices.length / 16);
|
|
1032
|
+
for (let i = 0; i < matrices.length / 16; i++) mesh.instances.setMatrixAt(i, matrices.subarray(i * 16, i * 16 + 16));
|
|
1033
|
+
}
|
|
1034
|
+
```
|
|
1035
|
+
|
|
1036
|
+
## 3MF volumes and displacement
|
|
1037
|
+
|
|
1038
|
+
`parse3MFVolumetric` returns the meshes as `parse3MF` does, with `images` (PNG sheets), `functions` (image samplers and node graphs), `volumes` and the built `objects` that have volume data or a level set, each with its placements and a level set's bounding mesh. References, graph order and types are checked. A built level set is evaluated and meshed, and its surface joins the result's triangles in the object's frame: inside is where the function is below zero within the domain mesh (or its box with `meshbboxonly`), and an undefined value takes `fallbackvalue`. Functions are image stacks (filters and tile styles of the extension) and graphs of native nodes, called functions, gradients, normalized distances and mesh distances included. The surface comes from the Marching Cubes of `@margoengine/procedural` on a grid of `levelSetResolution` cells along the domain's longest side (default 64, at most 512, spacing rounded down to a power of two); a file's `minfeaturesize` asks for two cells to a feature, and `levelSet.unresolved` says the grid could not give them. Edges where the domain cuts the surface are rounded within one cell. `meshLevelSets: false` reads the resources only. Meshing needs the optional `@margoengine/procedural`, `@margoengine/bvh` and `@margoengine/decoders` peers, loaded only for a package with a level set. The `beamlattice` node gives the signed distance to a mesh object's beams and balls, clipped by the lattice's clipping mesh (see `threeMFBeamDistance` below). The colour of a shape's volume data is sampled onto its surface: triangles are split until no side is longer than the spacing (`colorResolution` samples along the longest side, default 32, at most 512; a colour's `minfeaturesize` asks for two samples to a feature, and `colorUnresolved` says they could not be given), the function is read at each corner, its linear channels are clipped to 0..1 and written as sRGB vertex colours, and a triangle with a surface property of its own keeps it. A volume with a composite and no colour is painted the same way in its mixture: the base materials' display colours in the sampled ratios, mixed in linear light as a composite material is shown, and in equal parts where the contributions add to under 1e-5. A boolean's result keeps its operands' colour or mixture where the shape moves them. `sampleColors: false` leaves the triangles as the file has them. A built object with volume data also has `sample(positions)`, which reads it at any points of the object, inside it or on its surface, in the object's own coordinates: `colors` (sRGB), `composite` (the mixing ratios of the base materials, each contribution clipped to 0..1 and divided by their sum, zeros where the sum is under 1e-5) and `properties` (each with its name, namespace, `required`, `size` and `values`). A composite needs one mapping for each base material, and volume data on a displacement mesh is refused, as the extension allows it on mesh and level set shapes only. A boolean's operands are not built themselves, so `parse3MFEvaluated` gives each operand with volume data its own `sample` (`shapes[i].base.sample`, `shapes[i].operands[j].sample`), in that object's coordinates. The Marching Cubes method and its citations are in the procedural package.
|
|
1039
|
+
|
|
1040
|
+
`parse3MFDisplacement` returns the displaced surface as its triangles, with `maps`, `displacementGroups` (coordinates, factors and unit vectors) and `meshes` (base triangles, each corner's coordinate and the placements) beside it. Each base edge is split until a segment spans at most one texel of its map (`samplesPerTexel`, default 1) and its interpolated vectors turn at most 15 degrees, never into more than `maxSegments` pieces (default 256, rounded down to a power of two). Points move by `(texture * height + offset) * f` along the normalized mix of the corner vectors, with the extension's filters and tile styles. Both sides of an edge split alike, so no crack opens; sides that move apart are joined directly when they use the same vectors and through the base edge when not. Colours follow the base triangles. `tessellate: false` gives the base triangles, as `parse3MF` does. Reading the map needs the optional `@margoengine/decoders` peer. Self-intersections of a displaced surface are not resolved. The subdivision follows the per-edge factors of Fisher, Fatahalian, Boulos, Akeley, Mark and Hanrahan, [DiagSplit: parallel, crack-free, adaptive tessellation for micropolygon rendering](https://graphics.stanford.edu/~mdfisher/Data/DiagSplit.pdf) (2009), as the edge-split patterns of Boubekeur and Schlick, [Generic adaptive mesh refinement](https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch05.html) (GPU Gems 3, 2007).
|
|
1041
|
+
|
|
1042
|
+
```ts
|
|
1043
|
+
import { export3MF } from 'margoengine/exporters/threemf';
|
|
1044
|
+
import { parse3MFVolumetric } from 'margoengine/loaders/threemf-volumetric';
|
|
1045
|
+
|
|
1046
|
+
const geometry = {
|
|
1047
|
+
positions: new Float32Array([0, 0, 0, 0.04, 0, 0, 0, 0.04, 0, 0, 0, 0.04]),
|
|
1048
|
+
indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2],
|
|
1049
|
+
};
|
|
1050
|
+
const height = {
|
|
1051
|
+
nodes: [{ id: 'axes', op: 'decomposevector', in: { A: 'inputs.pos' } }],
|
|
1052
|
+
outputs: { z: 'axes.z' },
|
|
1053
|
+
};
|
|
1054
|
+
const file = await export3MF(
|
|
1055
|
+
{ nodes: [{ name: 'Block', geometry }] },
|
|
1056
|
+
{ objectInfo: () => ({ levelSet: { function: height } }) },
|
|
1057
|
+
);
|
|
1058
|
+
const { functions, objects } = await parse3MFVolumetric(file);
|
|
1059
|
+
console.log(functions.length, objects[0].levelSet?.channel, objects[0].levelSet?.cellSize);
|
|
1060
|
+
// A finer surface.
|
|
1061
|
+
const fine = await parse3MFVolumetric(file, { levelSetResolution: 128 });
|
|
1062
|
+
console.log((fine.indices?.length ?? 0) / 3);
|
|
1063
|
+
```
|
|
1064
|
+
|
|
1065
|
+
```ts
|
|
1066
|
+
import { export3MF, type ThreeMFImplicitFunction } from 'margoengine/exporters/threemf';
|
|
1067
|
+
import { parse3MFVolumetric } from 'margoengine/loaders/threemf-volumetric';
|
|
1068
|
+
|
|
1069
|
+
const geometry = {
|
|
1070
|
+
positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1]),
|
|
1071
|
+
indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2],
|
|
1072
|
+
};
|
|
1073
|
+
// Two materials that trade places along x.
|
|
1074
|
+
const mix: ThreeMFImplicitFunction = {
|
|
1075
|
+
nodes: [
|
|
1076
|
+
{ id: 'axes', op: 'decomposevector', in: { A: 'inputs.pos' } },
|
|
1077
|
+
{ id: 'one', op: 'constant', value: 1 },
|
|
1078
|
+
{ id: 'rest', op: 'subtraction', in: { A: 'one.value', B: 'axes.x' } },
|
|
1079
|
+
],
|
|
1080
|
+
outputs: { x: 'axes.x', rest: 'rest.result' },
|
|
1081
|
+
};
|
|
1082
|
+
const file = await export3MF(
|
|
1083
|
+
{ nodes: [{ name: 'Block', geometry }] },
|
|
1084
|
+
{
|
|
1085
|
+
unit: 'millimeter',
|
|
1086
|
+
upAxis: 'z',
|
|
1087
|
+
objectInfo: () => ({
|
|
1088
|
+
volume: {
|
|
1089
|
+
composite: [
|
|
1090
|
+
{ name: 'PLA', color: '#ff0000', function: mix, channel: 'x' },
|
|
1091
|
+
{ name: 'TPU', color: '#0000ff', function: mix, channel: 'rest' },
|
|
1092
|
+
],
|
|
1093
|
+
},
|
|
1094
|
+
}),
|
|
1095
|
+
},
|
|
1096
|
+
);
|
|
1097
|
+
const { objects } = await parse3MFVolumetric(file, { units: 'file' });
|
|
1098
|
+
const samples = await objects[0].sample!([0.25, 0.1, 0.1, 0.75, 0.1, 0.1]);
|
|
1099
|
+
console.log(samples.composite?.ratios, samples.properties.length);
|
|
1100
|
+
```
|
|
1101
|
+
|
|
1102
|
+
```ts
|
|
1103
|
+
import { export3MF } from 'margoengine/exporters/threemf';
|
|
1104
|
+
import { parse3MFDisplacement } from 'margoengine/loaders/threemf-displacement';
|
|
1105
|
+
|
|
1106
|
+
const image = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAAAAABX3VL4AAAADklEQVR4nGNg+M/wnwEABgAB/4/x/JoAAAAASUVORK5CYII='), (c) => c.charCodeAt(0));
|
|
1107
|
+
const geometry = {
|
|
1108
|
+
positions: new Float32Array([0, 0, 0, 0.04, 0, 0, 0, 0.04, 0, 0, 0, 0.04]),
|
|
1109
|
+
uvs: new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]),
|
|
1110
|
+
indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2],
|
|
1111
|
+
};
|
|
1112
|
+
const file = await export3MF({ nodes: [{ geometry }] }, { objectInfo: () => ({ displacement: { image, height: 0.001 } }) });
|
|
1113
|
+
const { displacementGroups, meshes } = await parse3MFDisplacement(file);
|
|
1114
|
+
console.log(displacementGroups[0].height, meshes[0].triangleGroups.length);
|
|
1115
|
+
// A coarser surface for a preview.
|
|
1116
|
+
const preview = await parse3MFDisplacement(file, { samplesPerTexel: 0.5, maxSegments: 32 });
|
|
1117
|
+
console.log((preview.indices?.length ?? 0) / 3);
|
|
1118
|
+
```
|
|
1119
|
+
|
|
1120
|
+
## 3MF boolean shapes
|
|
1121
|
+
|
|
1122
|
+
`parse3MFBoolean` returns each shape with its `operation`, its `base` and `operands` (each with a transform and, for a mesh, its triangles) and the places the build puts it, and refuses what the extension rules out. Each shape is also evaluated, and its surface joins the result's triangles where the build places it: the exact n-ary boolean of `@margoengine/mesh-edit` applies the operands in order on the base, transforms first, and each face keeps the colour of the surface it came from (none when that surface has no property). Inputs must be closed, outward solids; triangles with no area are removed first. This entry does not evaluate a base that is a displacement mesh or a level set, and refuses a package that builds a level set (`unsupported`): `parse3MFEvaluated` below does both. `evaluate: false` reads the shapes only. Evaluating needs the optional `@margoengine/mesh-edit` peer, loaded only for a package with a shape.
|
|
1123
|
+
|
|
1124
|
+
```ts
|
|
1125
|
+
import { export3MF } from 'margoengine/exporters/threemf';
|
|
1126
|
+
import { parse3MFBoolean } from 'margoengine/loaders/threemf-boolean';
|
|
1127
|
+
|
|
1128
|
+
const positions = new Float32Array([0, 0, 0, 0.04, 0, 0, 0, 0.04, 0, 0, 0, 0.04]);
|
|
1129
|
+
const geometry = { positions, indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2] };
|
|
1130
|
+
const file = await export3MF(
|
|
1131
|
+
{ nodes: [{ name: 'Part', geometry }] },
|
|
1132
|
+
{ objectInfo: () => ({ boolean: { operation: 'difference', operands: [{ geometry }] } }) },
|
|
1133
|
+
);
|
|
1134
|
+
const { shapes } = await parse3MFBoolean(file);
|
|
1135
|
+
console.log(shapes[0].operation, shapes[0].operands.length);
|
|
1136
|
+
// The shapes alone, without evaluating them.
|
|
1137
|
+
const structure = await parse3MFBoolean(file, { evaluate: false });
|
|
1138
|
+
console.log(structure.indices?.length);
|
|
1139
|
+
```
|
|
1140
|
+
|
|
1141
|
+
## 3MF packages that mix extensions
|
|
1142
|
+
|
|
1143
|
+
`parse3MFEvaluated` (`/threemf-evaluate`) evaluates every shape of a package in one call: displacement meshes are tessellated, level sets meshed, beam lattices and balls made into triangles and cut by their clipping mesh, boolean shapes evaluated on any of these as their base, and volume colours sampled onto the surfaces that result. It returns what `parse3MFDisplacement`, `parse3MFVolumetric` and `parse3MFBoolean` return, plus `lattices`, and takes their options except the ones that switch evaluation off, with `beamSegments` (sides of a beam around its axis, default 16). A lattice's shells overlap its mesh and each other, which the 3MF positive fill rule reads as one solid; a clipped lattice and a boolean's result are single surfaces. In a boolean's result a face keeps its source's surface property. A face with none takes volume colour as the extension's overlapping order says: the base's for a difference, the last object's for an intersection, and in a union each surface its own. Clipping and booleans need the optional `@margoengine/mesh-edit` peer, level sets also `@margoengine/procedural`, `@margoengine/bvh` and `@margoengine/decoders`.
|
|
1144
|
+
|
|
1145
|
+
```ts
|
|
1146
|
+
import { export3MF } from 'margoengine/exporters/threemf';
|
|
1147
|
+
import { parse3MFEvaluated } from 'margoengine/loaders/threemf-evaluate';
|
|
1148
|
+
|
|
1149
|
+
const positions = new Float32Array([0, 0, 0, 0.04, 0, 0, 0, 0.04, 0, 0, 0, 0.04]);
|
|
1150
|
+
const geometry = { positions, indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2] };
|
|
1151
|
+
const file = await export3MF(
|
|
1152
|
+
{ nodes: [{ name: 'Truss', geometry }] },
|
|
1153
|
+
{
|
|
1154
|
+
objectInfo: () => ({
|
|
1155
|
+
lattice: { positions: [0, 0, 0.05, 0.05, 0, 0.05], beams: [{ v1: 0, v2: 1 }], radius: 0.002 },
|
|
1156
|
+
}),
|
|
1157
|
+
},
|
|
1158
|
+
);
|
|
1159
|
+
const { indices, lattices } = await parse3MFEvaluated(file);
|
|
1160
|
+
console.log((indices?.length ?? 0) / 3, lattices[0].lattice.beams.length);
|
|
1161
|
+
// Rounder beams.
|
|
1162
|
+
const round = await parse3MFEvaluated(file, { beamSegments: 48 });
|
|
1163
|
+
console.log((round.indices?.length ?? 0) / 3);
|
|
1164
|
+
```
|
|
1165
|
+
|
|
1166
|
+
## 3MF beam lattices as triangles
|
|
1167
|
+
|
|
1168
|
+
`mesh3MFBeamLattice` (`/threemf-beams`) makes the surface of a lattice, as `parse3MFLattice` returns it, over its mesh's vertices: one closed shell for each active beam (a conical frustum between its radii, closed by a flat `butt`, a `sphere` or the `hemisphere` outside the end) and for each ball, with `parts` naming the triangles of each and `along` placing every vertex on its beam's axis. `threeMFBeamDistance` returns the signed distance to the same solids: exact outside and in sign everywhere; inside overlapping beams it is the depth in the beam the point lies deepest in. Neither applies a clipping mesh. The distance walks a median-split tree of boxes (Wald, Boulos and Shirley, [Ray tracing deformable scenes using dynamic bounding volume hierarchies](https://www.sci.utah.edu/~wald/Publications/2007/BVH/download/togbvh.pdf), ACM Transactions on Graphics 26(1), 2007).
|
|
1169
|
+
|
|
1170
|
+
```ts
|
|
1171
|
+
import { mesh3MFBeamLattice, threeMFBeamDistance } from 'margoengine/loaders/threemf-beams';
|
|
1172
|
+
|
|
1173
|
+
const vertices = [0, 0, 0, 10, 0, 0];
|
|
1174
|
+
const lattice = { beams: [{ v1: 0, v2: 1, r1: 2, r2: 1, cap1: 'sphere' as const, cap2: 'butt' as const }] };
|
|
1175
|
+
const { positions, indices } = mesh3MFBeamLattice(vertices, lattice, { segments: 32 });
|
|
1176
|
+
console.log(positions.length / 3, indices.length / 3);
|
|
1177
|
+
const distance = threeMFBeamDistance(vertices, lattice);
|
|
1178
|
+
console.log(distance(5, 4, 0), distance(5, 0, 0));
|
|
1179
|
+
```
|
|
1180
|
+
|
|
1181
|
+
## 3MF encrypted parts
|
|
1182
|
+
|
|
1183
|
+
`parse3MFKeystore` returns a package's secure content key store (consumers, key groups, wrapped keys, and each encrypted part with its parameters and bytes), or `undefined` without one. It decrypts nothing; `parse3MF` refuses a part that is encrypted.
|
|
1184
|
+
|
|
1185
|
+
```ts
|
|
1186
|
+
import { export3MF } from 'margoengine/exporters/threemf';
|
|
1187
|
+
import { parse3MFKeystore } from 'margoengine/loaders/threemf-secure';
|
|
1188
|
+
|
|
1189
|
+
const geometry = {
|
|
1190
|
+
positions: new Float32Array([0, 0, 0, 0.04, 0, 0, 0, 0.04, 0, 0, 0, 0.04]),
|
|
1191
|
+
indices: [0, 2, 1, 0, 1, 3, 1, 2, 3, 0, 3, 2],
|
|
1192
|
+
};
|
|
1193
|
+
const file = await export3MF(
|
|
1194
|
+
{ nodes: [{ name: 'Part', geometry }] },
|
|
1195
|
+
{
|
|
1196
|
+
production: { separateParts: true },
|
|
1197
|
+
// Stand-in bytes: encrypt `data` here.
|
|
1198
|
+
secureContent: { groups: [{}], encrypt: ({ data }) => ({ group: 0, data }) },
|
|
1199
|
+
},
|
|
1200
|
+
);
|
|
1201
|
+
const store = await parse3MFKeystore(file);
|
|
1202
|
+
console.log(store?.groups[0].resources.map((r) => r.path));
|
|
1203
|
+
```
|
|
1204
|
+
|
|
1205
|
+
## 3MF textures and colour groups
|
|
1206
|
+
|
|
1207
|
+
`parse3MFMaterials` from `@margoengine/loaders/threemf-materials` reads a 3MF package like `parse3MF` and adds the materials extension: `texture2d` images, `texture2dgroup` coordinates, `compositematerials`, `multiproperties` and the display properties (metallic, specular and translucent). The plain `parse3MF` stays as small as it was.
|
|
1208
|
+
|
|
1209
|
+
```ts
|
|
1210
|
+
import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
|
|
1211
|
+
|
|
1212
|
+
const bytes = await (await fetch('/prints/lithophane.3mf')).arrayBuffer();
|
|
1213
|
+
const { groups, textures, uvs } = await parse3MFMaterials(bytes);
|
|
1214
|
+
const image = await createImageBitmap(new Blob([textures[groups[0].texture ?? 0].data.slice()]));
|
|
1215
|
+
console.log(image.width, uvs?.length);
|
|
1216
|
+
```
|
|
1217
|
+
|
|
1218
|
+
- **Vertices.** Every triangle corner gets its own vertex, so `uvs` and `colors` can differ across a seam. `uvs` use v = 1 minus the file's v, and a mirrored build item keeps each coordinate on its corner.
|
|
1219
|
+
- **Groups.** A group's `texture` indexes `textures`; a triangle without one falls in a separate group. Each texture carries its image bytes, `contentType`, `tileStyleU`, `tileStyleV` and `filter`.
|
|
1220
|
+
- **Composites.** `compositematerials` mix their base colours by weight into one colour.
|
|
1221
|
+
- **Layers.** A group whose triangles use a `multiproperties` carries its whole stack in `layers`, bottom first: each layer's `kind` (`'color'` or `'texture'`), a texture layer's `texture`, its `blend` (`'mix'` or `'multiply'`, from `blendmethods`) and the name of its per-vertex values in `attributes` (`layerColor<k>`: sRGB red, green, blue and linear alpha; `layerUV<k>`: u and v). A pindex a row leaves out is 0. `multiproperties` that break the spec's rules (a second colour group, a material group not first or twice, a nested `multiproperties`) are `syntax` errors. For older readers `texture` still names the first texture layer and `colors` the colour layers mixed together.
|
|
1222
|
+
- **Metalness and roughness.** A group's `metallic` holds the display properties of its triangles (their first corner's, as the spec says): `name`, `metalness` and `roughness` from `pbmetallic` on base materials, colour groups and composites, or from `pbmetallictexturedisplayproperties` on a texture group, where the two numbers are factors and `metalnessTexture` and `roughnessTexture` index the maps in `textures` (red channel; roughness in red and metalness in green when both name one resource), with `baseColorFactor` when it is not white. A stack takes the lowest layer that has any, named by `metallic.layer`. Triangles that differ in it fall in separate groups.
|
|
1223
|
+
- **Specular colour and glossiness.** A group's `specular` holds `specularColor` (sRGB reflectance at normal incidence, default `#383838`) and `glossiness` from `pbspecular`, or from `pbspeculartexturedisplayproperties`, where they are factors over `specularTexture` (sRGB) and `glossinessTexture` (its alpha when it is the same resource, else its red), with `diffuseFactor` when it is not white. The diffuse colour is the group's own colour or texture.
|
|
1224
|
+
- **Translucency.** A group's `translucent` holds `attenuation` for red, green and blue per metre (Beer-Lambert), `refractiveIndex` (default 1, 1, 1) and `roughness`. `metresPerUnit` on the result gives the mesh's unit.
|
|
1225
|
+
- **One kind per group.** A group has at most one of `metallic`, `specular` and `translucent`; in a stack it is that of the lowest layer that has any, named by its `layer`.
|
|
1226
|
+
|
|
1227
|
+
```ts
|
|
1228
|
+
import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
|
|
1229
|
+
|
|
1230
|
+
const bytes = await (await fetch('/prints/gears.3mf')).arrayBuffer();
|
|
1231
|
+
for (const { name, metallic, specular, translucent } of (await parse3MFMaterials(bytes)).groups)
|
|
1232
|
+
console.log(name, metallic?.metalness, specular?.glossiness, translucent?.attenuation);
|
|
1233
|
+
```
|
|
1234
|
+
|
|
1235
|
+
### Drawing it: `create3MFMesh`
|
|
1236
|
+
|
|
1237
|
+
`create3MFMesh` from `@margoengine/loaders/threemf-mesh` draws that result as one `@margoengine/materials` mesh (an optional peer) with a material for each look (groups that differ in vertex colour alone share one): vertex colours, the texture as the colour map, and a layer stack through `layered()`. Each material takes its group's `metallic` metalness and roughness, maps included (repacked into one glTF-layout map from the texels the optional `@margoengine/decoders` peer reads exactly). A `specular` group is drawn with an index of refraction of 0 (`KHR_materials_ior`) and that specular colour, with roughness 1 - glossiness. A `translucent` group is transmissive: its thickness is the object's mean chord, 4 V / S (Cauchy's formula; Santalo, *Integral Geometry and Geometric Probability*, 1976), its attenuation is converted from per metre, and green's refractive index and the red to blue spread give the index and dispersion. Add `@margoengine/materials/transmission` to refract the scene behind it; without it the background shows through tinted. The layers blend as the 3MF Materials and Properties Extension 1.2.1 (chapter 5) specifies, in linear light: mix is `new.rgb * new.a + below.rgb * (1 - new.a)`, multiply `new.rgb * below.rgb`, and the bottom layer is opaque.
|
|
1238
|
+
|
|
1239
|
+
```ts
|
|
1240
|
+
import { Engine } from '@margoengine/core';
|
|
1241
|
+
import { parse3MFMaterials } from '@margoengine/loaders/threemf-materials';
|
|
1242
|
+
import { create3MFMesh } from '@margoengine/loaders/threemf-mesh';
|
|
1243
|
+
|
|
1244
|
+
const engine = await Engine.create(document.querySelector('canvas')!);
|
|
1245
|
+
const bytes = await (await fetch('/prints/multiprop-opaque.3mf')).arrayBuffer();
|
|
1246
|
+
const model = await create3MFMesh(engine, await parse3MFMaterials(bytes), { roughness: 0.5 });
|
|
1247
|
+
console.log(model.materials.length, model.textures.size);
|
|
1248
|
+
model.dispose(); // or `using model = ...`
|
|
1249
|
+
```
|
|
1250
|
+
|
|
1251
|
+
| Option | Default | Meaning |
|
|
1252
|
+
| --- | --- | --- |
|
|
1253
|
+
| `normals` | `'smooth'` | `'smooth'` shares a normal where corners meet at one position on faces within `creaseAngle`; `'flat'` gives each triangle its face normal |
|
|
1254
|
+
| `creaseAngle` | 40 | Degrees, 0 to 180: edges sharper than this stay sharp under `'smooth'` |
|
|
1255
|
+
| `roughness`, `metalness` | the file's, else 0.6, 0 | Every material's surface numbers; a number given here replaces the file's value and its map (a `specular` group's roughness is 1 - glossiness) |
|
|
1256
|
+
| `doubleSided` | true | Draw both faces |
|
|
1257
|
+
| `unlit` | false | Draw the colours without light (`shading: 'basic'`), so no specular or translucent look |
|
|
1258
|
+
| `renderOrder` | 0 | Draw order of the mesh |
|
|
1259
|
+
| `signal` | none | Stops the image decoding (`LoaderError` code `aborted`) |
|
|
1260
|
+
|
|
1261
|
+
The colour layers below the first texture layer blend per corner into the vertex colour; every layer from the first texture up is a material layer, a texture mixing by its alpha (the bottom one covers) and a colour layer by its colour's alpha. Limits: a stack's texture layers share UV0 and UV1, so a stack with more than two different coordinate sets, or a colour above a texture layer that changes across the group, is an `unsupported` error; a mix layer does not raise opacity a multiply layer lowered; tile style `none` draws as `clamp`; a translucent object's thickness is one number, its mean chord, and is 0 for an open mesh; in a stack under a translucent layer the layers above should tint the light that passes, but a picture layer does not yet ([known bugs](../../docs/known-bugs.md), KB-MAT-TINTMAP1).
|
|
1262
|
+
|
|
1263
|
+
## VTK XML
|
|
1264
|
+
|
|
1265
|
+
`parseVTKXML` from `@margoengine/loaders/vtk-xml` reads the XML files ParaView and most simulation tools write: `.vtp` PolyData and `.vtu` unstructured grids.
|
|
1266
|
+
|
|
1267
|
+
```ts
|
|
1268
|
+
import { parseVTKXML } from '@margoengine/loaders/vtk-xml';
|
|
1269
|
+
|
|
1270
|
+
const file = `<VTKFile type="PolyData"><PolyData><Piece NumberOfPoints="3" NumberOfPolys="1">
|
|
1271
|
+
<Points><DataArray type="Float32" NumberOfComponents="3" format="ascii">0 0 0 1 0 0 0 1 0</DataArray></Points>
|
|
1272
|
+
<Polys><DataArray type="Int32" Name="connectivity" format="ascii">0 1 2</DataArray>
|
|
1273
|
+
<DataArray type="Int32" Name="offsets" format="ascii">3</DataArray></Polys>
|
|
1274
|
+
</Piece></PolyData></VTKFile>`;
|
|
1275
|
+
const { positions, indices } = await parseVTKXML(new TextEncoder().encode(file));
|
|
1276
|
+
console.log(positions.length, indices);
|
|
1277
|
+
```
|
|
1278
|
+
|
|
1279
|
+
- **Encodings.** ascii, binary and appended arrays, raw or base64, either byte order, 32 or 64-bit headers, and zlib or LZ4 blocks. Several pieces in a file are merged.
|
|
1280
|
+
- **Cells.** Polygons and strips become triangles over the file's points (a convex polygon fanned, a concave one ear-clipped on its own plane), and polylines become `lines`. Volume cells are reduced to the faces only one cell owns, their outer surface; `surface: 'all'` keeps every face. Higher-order cells (quadratic, biquadratic and triquadratic types 21 to 37, Lagrange 68 to 74 and Bezier 75 to 81) draw from their corner points, which VTK lists first, with a warning. `triangleCells` names the cell each triangle came from, numbered as VTK does (PolyData: verts, lines, polys, then strips, whatever order the file writes them in), so a cell field can colour them.
|
|
1281
|
+
- **Data.** Every array is in `pointData` or `cellData` by name. `Normals`, `TCoords` and a 3 or 4 component `UInt8` `Scalars` array also fill `normals`, `uvs` and `colors`.
|
|
1282
|
+
- **Not read.** Other dataset types, such as image and structured grids, are `unsupported` errors. The legacy text format is `parseVTK`. LZMA blocks (`vtkLZMADataCompressor`) need `@margoengine/decoders`.
|
|
1283
|
+
|
|
1284
|
+
## Legacy VTK datasets (`/vtk-legacy`)
|
|
1285
|
+
|
|
1286
|
+
`parseVTKLegacy` from `@margoengine/loaders/vtk-legacy` reads all five legacy dataset types (`STRUCTURED_POINTS`, `STRUCTURED_GRID`, `RECTILINEAR_GRID`, `POLYDATA` and `UNSTRUCTURED_GRID`), ASCII or big-endian `BINARY`, in the pre-5.0 cell layout and the 5.x `OFFSETS`/`CONNECTIVITY` one. `parseVTK` in the main entry stays the small POLYDATA surface reader.
|
|
1287
|
+
|
|
1288
|
+
```ts
|
|
1289
|
+
import { parseVTKLegacy } from '@margoengine/loaders/vtk-legacy';
|
|
1290
|
+
|
|
1291
|
+
const file = `# vtk DataFile Version 3.0
|
|
1292
|
+
one tetrahedron and a line
|
|
1293
|
+
ASCII
|
|
1294
|
+
DATASET UNSTRUCTURED_GRID
|
|
1295
|
+
POINTS 5 double
|
|
1296
|
+
0 0 0 1 0 0 0 1 0 0 0 1 2 2 2
|
|
1297
|
+
CELLS 2 8
|
|
1298
|
+
4 0 1 2 3
|
|
1299
|
+
2 3 4
|
|
1300
|
+
CELL_TYPES 2
|
|
1301
|
+
10
|
|
1302
|
+
3
|
|
1303
|
+
POINT_DATA 5
|
|
1304
|
+
SCALARS temperature double 1
|
|
1305
|
+
LOOKUP_TABLE default
|
|
1306
|
+
20 21 22 23 24
|
|
1307
|
+
CELL_DATA 2
|
|
1308
|
+
SCALARS material int 1
|
|
1309
|
+
LOOKUP_TABLE default
|
|
1310
|
+
7 9
|
|
1311
|
+
`;
|
|
1312
|
+
const grid = parseVTKLegacy(new TextEncoder().encode(file));
|
|
1313
|
+
console.log(grid.type, grid.cellCount, grid.cellTypes); // UNSTRUCTURED_GRID 2 [10, 3]
|
|
1314
|
+
console.log(grid.indices!.length / 3, grid.triangleCells, grid.lines); // 4 [0, 0, 0, 0] [3, 4]
|
|
1315
|
+
console.log(grid.pointData.temperature.values, grid.cellData.material.values); // [20 ... 24] [7, 9]
|
|
1316
|
+
```
|
|
1317
|
+
|
|
1318
|
+
- **Topology stays whole.** `offsets` (with a leading zero), `connectivity` and `cellTypes` hold every source cell, volume cells included, as the file has them; `cellCount` counts them. Structured types also give `dimensions` (x fastest), and `STRUCTURED_POINTS` its `origin` and `spacing`.
|
|
1319
|
+
- **What draws.** `indices` holds the surface triangles of polygon, strip and volume cells, `triangleCells` the source cell of each; `lines` holds two point indices per line segment (`LINE`, `POLY_LINE` and cell edges with no face), `lineCells` theirs; `vertices` and `vertexCells` the `VERTEX` and `POLY_VERTEX` points. Higher-order and unknown cells keep their topology and draw their corner shape, each such difference named once in `warnings`.
|
|
1320
|
+
- **Surface policy.** `surface: 'outer'` (the default) keeps only volume faces no other cell shares, so a grid draws as its skin; `'all'` keeps internal faces too. Faces wind outward from the cell, in the XML reader too. The wedge (type 13) uses VTK's standard corner order: corners 0 1 2 make one triangle and 3 4 5 the other, so its outward faces are 0 2 1 and 3 4 5.
|
|
1321
|
+
- **Data.** `pointData`, `cellData` (in source cell order) and the global `fieldData` hold every numeric array by its file name in a prototype-free object, each `{components, values}` with `values` a `Float64Array` (no rounding to float32). `SCALARS`, `VECTORS`, `NORMALS`, `TENSORS`, `TEXTURE_COORDINATES`, `COLOR_SCALARS` and `FIELD` arrays all arrive there.
|
|
1322
|
+
- **Limits.** `maxCells` (default `maxTriangles`, 16,000,000) bounds the source cells beside the usual `maxVertices` and `maxTriangles`; `signal` is checked while reading and while building topology.
|
|
1323
|
+
|
|
1324
|
+
## Maps, tracks and vector tiles (`/geo`)
|
|
1325
|
+
|
|
1326
|
+
`@margoengine/loaders/geo` reads GIS vector data into one shape: `parseGeoJSON`, `parseShapefile`, `parseGPX`, `parseKML` and `parseMVT`. Points, lines and polygons can be mixed in one file; polygons with holes are triangulated for drawing, and every primitive remembers its feature.
|
|
1327
|
+
|
|
1328
|
+
```ts
|
|
1329
|
+
import { parseGeoJSON, parseGPX } from '@margoengine/loaders/geo';
|
|
1330
|
+
|
|
1331
|
+
const map = parseGeoJSON({
|
|
1332
|
+
type: 'FeatureCollection',
|
|
1333
|
+
features: [
|
|
1334
|
+
{ type: 'Feature', id: 'park', properties: { name: 'Park' }, geometry: { type: 'Polygon', coordinates: [
|
|
1335
|
+
[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]], // outer ring
|
|
1336
|
+
[[4, 4], [6, 4], [6, 6], [4, 6], [4, 4]], // a pond
|
|
1337
|
+
] } },
|
|
1338
|
+
{ type: 'Feature', properties: { name: 'Path' }, geometry: { type: 'LineString', coordinates: [[0, -1, 2], [10, -1, 3]] } },
|
|
1339
|
+
{ type: 'Feature', properties: { name: 'Well' }, geometry: { type: 'Point', coordinates: [5, 12] } },
|
|
1340
|
+
],
|
|
1341
|
+
});
|
|
1342
|
+
console.log(map.crs, map.features.length, map.mesh.indices!.length / 3); // OGC:CRS84 3 8
|
|
1343
|
+
console.log(map.polygons[0].rings.length, map.lineFeatures.at(-1), map.pointFeatures); // 2 1 [2]
|
|
1344
|
+
|
|
1345
|
+
const ride = parseGPX(`<gpx version="1.1" creator="me" xmlns="http://www.topografix.com/GPX/1/1"><trk><name>Ride</name>
|
|
1346
|
+
<trkseg><trkpt lat="1" lon="2"><ele>10</ele></trkpt><trkpt lat="1.1" lon="2.1"><ele>12</ele></trkpt></trkseg></trk></gpx>`);
|
|
1347
|
+
console.log(ride.features[0].properties?.name, ride.positions); // Ride [2, 1, 10, 2.1, 1.1, 12]
|
|
1348
|
+
```
|
|
1349
|
+
|
|
1350
|
+
- **The result.** `features` holds each source feature as GeoJSON (`id`, `properties`, `geometry`, and for MVT its `layer` and `extent`). `positions` keeps the source coordinates as `Float64Array` xyz (x = longitude or easting, z defaults to 0), with no projection applied; `crs` names their system (`OGC:CRS84` for GeoJSON, GPX and KML, the `.prj` text for a Shapefile). `points`/`pointFeatures`, `lines`/`lineFeatures` (polygon boundaries included) and `polygons` (`rings` of indices, outer ring first, holes after, without the repeated closing point) address them. `mesh` is a float32 `LoadedGeometry` of the polygon triangles for `toGeometry` and `createMeshes`, `triangleFeatures` giving each triangle's feature and one group per feature carrying its `id` and `name`. Rings are grouped into polygons by containment, whatever their winding or part order.
|
|
1351
|
+
- **Shapefile.** `parseShapefile(shp, {dbf, prj, encoding, includeDeleted})` reads point, multipoint, polyline, polygon and multipatch records with their Z and M values; the optional `.dbf` gives `properties` in record order (`encoding` defaults to `windows-1252`; pass the `.cpg` label), and records dBASE marks deleted are left out unless `includeDeleted`.
|
|
1352
|
+
- **GPX and KML.** GPX 1.0 and 1.1 waypoints, routes and tracks (each segment its own line) and KML placemarks keep their names, descriptions and `Data`/`SimpleData` values in `properties`; GPX elevations become z and point times are kept in `properties.times`.
|
|
1353
|
+
- **Vector tiles.** `parseMVT(bytes, {tile, layers})` reads Mapbox Vector Tile 1 and 2 protobufs, layers, tags, ids, multipart lines and holes included. Without `tile` the coordinates stay in tile units (y down); with `{x, y, z}` they become WGS84 longitude and latitude.
|
|
1354
|
+
- **Limits.** `maxFeatures` (100,000), `maxBytes` (256 MiB) and `maxDepth` (geometry collections nested 64 deep) bound a file, beside `maxVertices` and `maxTriangles`; `signal` is checked between features and primitives.
|
|
1355
|
+
|
|
1356
|
+
## mmCIF structures (`/mmcif`)
|
|
1357
|
+
|
|
1358
|
+
`parseMMCIF` from `@margoengine/loaders/mmcif` reads PDBx/mmCIF coordinate files, the format the Protein Data Bank now serves, into the same `PDBMolecule` that `parsePDB` returns: a point cloud with element colours, covalent radii, atom labels and bonds.
|
|
1359
|
+
|
|
1360
|
+
```ts
|
|
1361
|
+
import { parseMMCIF } from '@margoengine/loaders/mmcif';
|
|
1362
|
+
|
|
1363
|
+
const cif = `data_demo
|
|
1364
|
+
loop_
|
|
1365
|
+
_atom_site.group_PDB
|
|
1366
|
+
_atom_site.id
|
|
1367
|
+
_atom_site.type_symbol
|
|
1368
|
+
_atom_site.label_atom_id
|
|
1369
|
+
_atom_site.label_alt_id
|
|
1370
|
+
_atom_site.label_comp_id
|
|
1371
|
+
_atom_site.label_asym_id
|
|
1372
|
+
_atom_site.auth_seq_id
|
|
1373
|
+
_atom_site.pdbx_PDB_ins_code
|
|
1374
|
+
_atom_site.Cartn_x
|
|
1375
|
+
_atom_site.Cartn_y
|
|
1376
|
+
_atom_site.Cartn_z
|
|
1377
|
+
_atom_site.pdbx_PDB_model_num
|
|
1378
|
+
ATOM 1 N N . GLY A 52 A 0.000 0.000 0.000 1
|
|
1379
|
+
ATOM 2 C CA A GLY A 52 A 1.450 0.000 0.000 1
|
|
1380
|
+
ATOM 3 C CA B GLY A 52 A 1.460 0.100 0.000 1
|
|
1381
|
+
ATOM 4 N N . GLY A 1 . 9.000 0.000 0.000 2
|
|
1382
|
+
`;
|
|
1383
|
+
const molecule = parseMMCIF(cif);
|
|
1384
|
+
console.log(molecule.atoms.map((a) => `${a.name} ${a.residueId}${a.insertionCode} ${a.alternateLocation}`)); // ['N 52A ', 'CA 52A A']
|
|
1385
|
+
console.log(molecule.bonds, molecule.warnings); // [0, 1] ['only the first MODEL is read']
|
|
1386
|
+
```
|
|
1387
|
+
|
|
1388
|
+
- **What is read.** The CIF 1.1 syntax (quoted values, semicolon text fields, loops), the first data block or the one `block` names (without `data_`, any case), and `_atom_site` with author and label identifiers: `residueId` is the author residue id (text, so non-numeric ids survive), `id` a non-numeric atom id.
|
|
1389
|
+
- **Models and conformers.** Only the first model loads (noted once in `warnings`), and an atom with alternate locations keeps its first (`alternateLocation` names it). `insertionCode` holds the PDB insertion code, so residues 52 and 52A stay apart; `parsePDB` fills the same two fields.
|
|
1390
|
+
- **Bonds.** `_struct_conn` covalent and disulfide records become bonds when both partners are in the selected model and conformer; records that need a symmetry operation (crystal expansion) are skipped with a warning. Distance bonds from covalent radii follow, as in `parsePDB`, unless `guessBonds: false`. Building a crystal or biological assembly is a separate step.
|
|
1391
|
+
|
|
1392
|
+
## 3MF lattices and slices as data (`/threemf-lattice`)
|
|
1393
|
+
|
|
1394
|
+
`parse3MFLattice` from `@margoengine/loaders/threemf-lattice` returns what `parse3MFMaterials` returns (the textured, coloured triangle mesh) plus the beam lattice and slice extensions as they are written, so a slicer or a simulation can use the exact beams and layers instead of the triangles. `mesh3MFBeamLattice` (`/threemf-beams`, above) turns a lattice into triangles.
|
|
1395
|
+
|
|
1396
|
+
```ts
|
|
1397
|
+
import { parse3MFLattice } from '@margoengine/loaders/threemf-lattice';
|
|
1398
|
+
|
|
1399
|
+
const bytes = await (await fetch('/prints/lattice-slices.3mf')).arrayBuffer();
|
|
1400
|
+
const result = await parse3MFLattice(bytes, { maxBeams: 2_000_000 });
|
|
1401
|
+
for (const { object, transform, unitScale } of result.instances) {
|
|
1402
|
+
const lattice = object.lattice;
|
|
1403
|
+
if (lattice) console.log(object.id, lattice.beams.length, lattice.activeBeams.length, lattice.effectiveBalls.length, unitScale); // 9 2 1 2 0.001
|
|
1404
|
+
}
|
|
1405
|
+
for (const { stack } of result.sliceInstances) console.log(stack.id, stack.layers.length); // 10 2
|
|
1406
|
+
```
|
|
1407
|
+
|
|
1408
|
+
- **Native objects and their uses.** `objects` holds each source object once, in source units and source doubles (`vertices`, `triangles`, its `lattice` or `slices` reference); `instances` holds each occurrence in the build with its exact row-vector 4 x 3 `transform` (object, component and build transforms multiplied) and the `unitScale` to metres applied after it. A beam radius stays valid under a non-uniform scale because the transform is kept, not baked. The triangle mesh, by contrast, is the baked preview `parse3MF` makes.
|
|
1409
|
+
- **Beam lattices.** Each `lattice` keeps its defaults (`radius`, `minLength`, `cap`), `beams` (vertex pair, both radii, both caps, property), `balls`, named `sets` of beam and ball references, `ballMode` and `ballRadius`, and the clipping and representation mesh references (`clippingMode`, `clippingMesh`, `representationMesh`), which are reported, not applied. `activeBeams` lists the beams at least `minLength` long (the others keep their place, so set indices stay valid); `effectiveBalls` the balls `ballMode` asks for, implicit ones at beam ends in `all` mode included.
|
|
1410
|
+
- **Slices.** `sliceStacks` holds each slice stack with its `bottom`, its own `slices` (each a `top`, xy `vertices` and closed `polygons` of segments that may carry properties, void layers included) and its `references` to stacks in other parts, which are resolved: `layers` is the whole stack, rising monotonically. `sliceInstances` gives each build use of a stack; a stack on a component wins over stacks on what it contains.
|
|
1411
|
+
- **Properties.** `propertyResources` keeps the material resources as written: colour groups with resolved `colors`, composite materials with their `materialId`, `materialIndices` and `weights`, and multiproperties with `propertyIds`, `rows` and `blendMethods`.
|
|
1412
|
+
- **Limits.** `maxBeams` (1,000,000 beams and as many explicit balls) and `maxSlices` (100,000 layers and slice references) beside the 3MF options; `signal` cancels.
|
|
1413
|
+
|
|
1414
|
+
## Rhino 3DM
|
|
1415
|
+
|
|
1416
|
+
`parse3DM` from `@margoengine/loaders/3dm` reads the meshes, untrimmed surfaces, layers and attributes of a Rhino `.3dm` file through a rhino3dm runtime you install, host and load, the same pattern as `parseIFC`. Its Wasm file is never part of this package.
|
|
1417
|
+
|
|
1418
|
+
```ts
|
|
1419
|
+
import { parse3DM, type RhinoRuntime } from '@margoengine/loaders/3dm';
|
|
1420
|
+
|
|
1421
|
+
// `rhino` is `await rhino3dm()`, from the rhino3dm package you install and host.
|
|
1422
|
+
export async function loadChair(rhino: RhinoRuntime) {
|
|
1423
|
+
const bytes = await (await fetch('/models/chair.3dm')).arrayBuffer();
|
|
1424
|
+
const { groups, layers } = parse3DM(rhino, bytes);
|
|
1425
|
+
console.log(groups[0].name, layers[groups[0].layer ?? 0].name);
|
|
1426
|
+
}
|
|
1427
|
+
```
|
|
1428
|
+
|
|
1429
|
+
- **Geometry.** Each object is a group of one merged mesh: a mesh as it is, and any other surface object through the render mesh saved in the file. With no render mesh, a NURBS surface and a solid that is one plain surface are tessellated by `@margoengine/loaders/nurbs` and counted in `surfaces`; `segmentsU` and `segmentsV` set the quads per knot span, default 4 times the degree. Other solids saved without a render mesh are counted in `skipped`, because any face may be trimmed and the runtime gives no trim curves. Nothing draws past a trim. Save the file from Rhino with render meshes kept to see them.
|
|
1430
|
+
- **Attributes.** A group has the object's `name`, `id`, `layer`, `material` and `userStrings`, and its colour, from the object or else its layer. `layers` lists each layer's name, full path, colour and visibility.
|
|
1431
|
+
- **Units.** Metres by the file's unit system; `units: 'file'` keeps the file's own numbers. A file with no known unit keeps them too, and `metersPerUnit` is left unset.
|
|
1432
|
+
- **Hidden.** Hidden objects and objects on hidden layers stay out unless `hidden: true`.
|
|
1433
|
+
- **Memory.** Every handle the runtime gives out is freed before `parse3DM` returns, failures included.
|
|
1434
|
+
- **Tested.** Against a stand-in with rhino3dm's shape in `npm test`, and against the real rhino3dm 8.35 on McNeel's sample files in `npm run test:real-files`, surfaces saved with no render mesh included: each matches the runtime's own `pointAt` to within 1e-9.
|
|
1435
|
+
|
|
1436
|
+
## 3DS, LWO, AMF, MD2, PDB and KMZ
|
|
1437
|
+
|
|
1438
|
+
Older and specialist formats, one small entry each, so an app pays only for the one it imports.
|
|
1439
|
+
|
|
1440
|
+
```ts
|
|
1441
|
+
import { parse3DS } from '@margoengine/loaders/3ds';
|
|
1442
|
+
import { parseLWO } from '@margoengine/loaders/lwo';
|
|
1443
|
+
import { parseAMF } from '@margoengine/loaders/amf';
|
|
1444
|
+
import { parseMD2 } from '@margoengine/loaders/md2';
|
|
1445
|
+
import { parsePDB } from '@margoengine/loaders/pdb';
|
|
1446
|
+
import { parseKMZ } from '@margoengine/loaders/kmz';
|
|
1447
|
+
|
|
1448
|
+
const bytes = async (url: string) => (await fetch(url)).arrayBuffer();
|
|
1449
|
+
console.log(parse3DS(await bytes('/models/teapot.3ds')).materials[0]?.texture);
|
|
1450
|
+
console.log(parseLWO(await bytes('/models/ship.lwo')).groups[0].name);
|
|
1451
|
+
console.log((await parseAMF(await bytes('/prints/bracket.amf'))).unit);
|
|
1452
|
+
console.log(parseMD2(await bytes('/models/knight.md2')).clips);
|
|
1453
|
+
console.log(parsePDB(await (await fetch('/molecules/1crn.pdb')).text()).bonds.length);
|
|
1454
|
+
console.log((await parseKMZ(await bytes('/maps/tower.kmz'))).models[0]?.location);
|
|
1455
|
+
```
|
|
1456
|
+
|
|
1457
|
+
Textures and skins are named by the file, and `loadTextures` from `/textures` reads them through a resolver, the same kind `parseLDraw` takes. Old tools wrote paths from their own PC, so each path is asked for as written, then with forward slashes, in lower case, and by its base name. A file nobody has is listed in `missing`, so one lost skin does not lose the model.
|
|
1458
|
+
|
|
1459
|
+
```ts
|
|
1460
|
+
import { resolveFromURL } from '@margoengine/loaders/ldraw';
|
|
1461
|
+
import { parseMD2 } from '@margoengine/loaders/md2';
|
|
1462
|
+
import { loadTextures } from '@margoengine/loaders/textures';
|
|
1463
|
+
import { parsePCX } from '@margoengine/decoders/pcx';
|
|
1464
|
+
|
|
1465
|
+
const model = parseMD2(await (await fetch('/models/tank.md2')).arrayBuffer());
|
|
1466
|
+
const { textures, missing } = await loadTextures(model.skins, resolveFromURL('/models/'));
|
|
1467
|
+
for (const bytes of textures.values()) console.log(parsePCX(bytes).width);
|
|
1468
|
+
console.log(missing.map(({ path }) => path));
|
|
1469
|
+
```
|
|
1470
|
+
|
|
1471
|
+
`parse3DS(...).materials[i].texture`, `parseLWO(...).images` and `parseMD2(...).skins` all feed it. Decode what comes back with `createImageBitmap` for PNG, JPEG and BMP, `parseTGA` from `@margoengine/decoders/tga` and `parsePCX` from `@margoengine/decoders/pcx`.
|
|
1472
|
+
|
|
1473
|
+
- **3DS.** `parse3DS` reads every triangle mesh with UVs, one group per object and material, and each material's colour, transparency and diffuse map name. Vertices are saved in world space. `cameras` and `lights` hold position, target, lens, colour, multiplier and spot cones, `ambient` the ambient colour, and `keyframes` the keyframer's nodes with hierarchy, pivots and tracks. They come back as the file holds them: rotation keys are axis and angle, each relative to the key before, and nothing plays them for you. `parseTDS` from `/tds` is the same reader: a `.tds` file is the same 3D Studio format under another extension, so this is one format with two names.
|
|
1474
|
+
- **LWO.** `parseLWO` reads LWO2 and the older LWOB: every layer's points and face polygons, `SURF` colours and image maps in `surfaces`, still images in `images`, every `TXUV` map in `uvMaps` and every `WGHT` map in `weightMaps` with their `VMAD` values, which split a vertex along a seam in all maps at once. `uvs` is each layer's first map. `bones` holds the skelegons with names, parents and weight maps, in the coordinates of `positions`. There is one group per layer and surface, and z changes sign to make the left-handed file right-handed. Patch and subdivision polygons come in as their control cage with a warning. Curves, and clips that are not still images, are skipped with a warning.
|
|
1475
|
+
- **AMF.** `parseAMF` reads plain or zipped files: objects, volumes, material, object, volume, vertex and triangle colours, and constellations, nested ones included. Colours rank as ISO/ASTM 52915 orders them, triangle first, then vertex, volume, object and material; a coloured triangle gets three corners of its own, and a vertex without a colour of its own shows its volume's colour. Positions are in metres unless `units: 'file'`. Curved edges and colour formulas are skipped with a warning.
|
|
1476
|
+
- **MD2.** `parseMD2` gives the first frame as a mesh with every frame beside it in one layout, so frames blend as morph targets. Frames named `run1`, `run2` form the clip `run`. Normals are computed from each frame's triangles. `skins` names the skin files, for `loadTextures` and `parsePCX`.
|
|
1477
|
+
- **PDB.** `parsePDB` returns atoms as a point cloud with element colours, radii and labels, plus `bonds` as index pairs from CONECT rows and from distance, which `guessBonds: false` turns off. Only the first MODEL loads, and an atom with alternate locations keeps its first.
|
|
1478
|
+
- **KMZ.** `parseKMZ` reads the KML document's `<Model>` elements and their COLLADA files, one mesh each, and an archive with no document gives every `.dae` it holds. `location`, `orientation`, `scale` and `altitudeMode` are returned. Pass `origin`, a place or `'first'`, and each located model also gets a column-major `matrix` that puts its geometry in a Y-up scene in metres, x east and z south at the origin, with the orientation, the scale and the Earth's curve between the two places. Without `origin` nothing is applied, for an app with a map projection of its own. Altitudes are taken as metres above the WGS84 ellipsoid, and `clampToGround`, the KML default, sits at height 0: no terrain or geoid is known here. Placemark points, lines and polygons are not read. `read(path)` returns any other file in the archive.
|
|
1479
|
+
|
|
1480
|
+
## NURBS curves and surfaces
|
|
1481
|
+
|
|
1482
|
+
`@margoengine/loaders/nurbs` evaluates and tessellates NURBS curves and surfaces held as plain data, the numbers a CAD file hands you. It checks them, fills in the end knots Rhino leaves out, and hands the maths to `@margoengine/geometry/nurbs`, the one evaluator, which `parseDXF` uses for SPLINE too. Rational weights make circles and spheres exact.
|
|
1483
|
+
|
|
1484
|
+
```ts
|
|
1485
|
+
import { evaluateNurbsCurve, tessellateNurbsCurve, tessellateNurbsSurface } from '@margoengine/loaders/nurbs';
|
|
1486
|
+
|
|
1487
|
+
const arc = { degree: 2, knots: [0, 0, 0, 1, 1, 1], points: [1, 0, 0, 1, 1, 0, 0, 1, 0], weights: [1, Math.SQRT1_2, 1] };
|
|
1488
|
+
console.log(evaluateNurbsCurve(arc, 0.5), tessellateNurbsCurve(arc, { tolerance: 0.001 }).length / 3);
|
|
1489
|
+
|
|
1490
|
+
const patch = { degreeU: 1, degreeV: 1, knotsU: [0, 0, 1, 1], knotsV: [0, 0, 1, 1], countU: 2, countV: 2,
|
|
1491
|
+
points: [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0] };
|
|
1492
|
+
console.log(tessellateNurbsSurface(patch, { segmentsU: 2, segmentsV: 2 }).indices?.length);
|
|
1493
|
+
```
|
|
1494
|
+
|
|
1495
|
+
- **Knots.** A knot vector may leave out its two end knots, as Rhino files do. Unclamped curves evaluate on their own domain.
|
|
1496
|
+
- **Curves.** `tessellateNurbsCurve` splits each knot span until the curve is within `tolerance` of its chords, so straight runs stay cheap. The result is xyz per point, for `mode: 'strip'` of `@margoengine/lines`. `maxPoints` caps it.
|
|
1497
|
+
- **Surfaces.** `tessellateNurbsSurface` makes a triangle grid with exact normals, with grid lines on every distinct knot and `segmentsU` and `segmentsV` quads per span. `evaluateNurbsSurface` gives a point and unit normal, and the normal is zero at a pole.
|
|
1498
|
+
- **Whole surfaces.** Trim curves are not applied, and there is no solid modelling: no topology and no boolean operations.
|
|
1499
|
+
|
|
1500
|
+
## LAS and LAZ
|
|
1501
|
+
|
|
1502
|
+
`parseLAS` from `@margoengine/loaders/las` reads ASPRS LAS and LAZ point clouds, versions 1.0 to 1.5 and point formats 0 to 10 (LAS 1.5 removed formats 0 to 5, so a 1.5 file using one is refused). It is a thin layer over `@margoengine/points/las`, the one LAS reader of the engine, and gives the same data in the shape of this package.
|
|
1503
|
+
|
|
1504
|
+
```ts
|
|
1505
|
+
import { parseLAS } from '@margoengine/loaders/las';
|
|
1506
|
+
|
|
1507
|
+
const bytes = await (await fetch('/surveys/quarry.laz')).arrayBuffer();
|
|
1508
|
+
const { positions, classification, origin } = await parseLAS(bytes, { step: 4 });
|
|
1509
|
+
console.log(positions.length / 3, classification[0], origin);
|
|
1510
|
+
```
|
|
1511
|
+
|
|
1512
|
+
- **Positions.** They come back relative to `origin`, because survey coordinates are too large for 32-bit floats. Add it back for world coordinates. `origin` is the header's minimum corner, or the first point when the header's box misses the points, a fault of some writers.
|
|
1513
|
+
- **Attributes.** `intensity`, `classification`, `returnNumber`, `returnCount`, `gpsTime` where the format has it, and `colors` in [0,1], from 16 bits or from 8 for files that fill only the low byte. `header` and `records` give the header and its variable records. `extra` holds extra bytes by name, `crs` the projection, and `points` everything else the file stores: flags, scan angle, user data, source id, channel, NIR and wave packets.
|
|
1514
|
+
- **Thinning.** `step: 4` keeps every fourth point, and `maxVertices` counts points after thinning.
|
|
1515
|
+
- **LAZ.** A `.laz` opens as it is. The decoder of `@margoengine/points/laz` loads when the first compressed file arrives, so a plain `.las` never pays for it. `decompress` replaces it with a decoder of your own, which gets the file and its header and returns the plain point records. LAZ item version 1, the coding of LASzip 1.0, is an `unsupported` error, as no published text describes it: [limits](../../docs/limits.md).
|
|
1516
|
+
- **Waves.** Formats 4, 5, 9 and 10 carry wave packets in `points.wavePackets`. `lasWaveform(cloud.points, index, source)` from `@margoengine/points/las` reads one point's samples, from the file or from the `.wdp` beside it, and `lasWaveDescriptors(cloud.records)` the descriptors.
|
|
1517
|
+
|
|
1518
|
+
## VDB volumes
|
|
1519
|
+
|
|
1520
|
+
`parseVDB` from `@margoengine/loaders/vdb` reads OpenVDB `.vdb` files, the sparse volumes that simulation tools write for smoke, clouds and fire. It reads file versions 222 and later, which is OpenVDB 2.0 onward.
|
|
1521
|
+
|
|
1522
|
+
```ts
|
|
1523
|
+
import { parseVDB } from '@margoengine/loaders/vdb';
|
|
1524
|
+
|
|
1525
|
+
const bytes = await (await fetch('/sims/smoke.vdb')).arrayBuffer();
|
|
1526
|
+
const { grids, skipped } = await parseVDB(bytes, { grids: ['density'] });
|
|
1527
|
+
const density = grids[0]!;
|
|
1528
|
+
console.log(density.gridClass, density.activeVoxels, density.box, skipped.length);
|
|
1529
|
+
console.log(density.at(10, 20, 30), density.isActive(10, 20, 30));
|
|
1530
|
+
const { data, dims, bounds } = density.dense();
|
|
1531
|
+
console.log(data.length, dims, bounds); // fig.volume(data, { dims, bounds }) in @margoengine/sciviz
|
|
1532
|
+
```
|
|
1533
|
+
|
|
1534
|
+
- **Sparse.** Each grid keeps `leaves` (blocks of voxels, with an active mask) and `tiles` (cubes of one value) as the file stores them. `at` and `isActive` look up one voxel, and a voxel with nothing stored holds `background`.
|
|
1535
|
+
- **Dense.** `dense()` fills an array over the active box, or over `{ box }`, x fastest. `bounds` is in world units around the voxel centres. A rotated grid gets the box around its corners, so use `matrix` when the rotation matters. `maxValues` caps the array, 536,870,912 by default.
|
|
1536
|
+
- **Types.** `float`, `double`, `int32`, `int64`, `vec3s`, `vec3d` and `vec3i`. Grids stored as 16-bit halves widen to `float` or `double`, with `half` set. A vector grid has `components` 3, with the three values side by side.
|
|
1537
|
+
- **Empty half-value blocks.** A half-precision node with no stored values consumes no size prefix, so the next node stays aligned. A pinned OpenVDB level-set sphere (CC-BY-4.0) regresses this against its stored voxel count and bounds; `npm run fixtures --workspace @margoengine/loaders` restores it.
|
|
1538
|
+
- **Compression.** Uncompressed, zlib and Blosc with LZ4, the OpenVDB default, in every value layout. Blosc with another codec or with bit shuffle is refused with code `unsupported`.
|
|
1539
|
+
- **Transforms.** `matrix` is the index-to-world matrix of an affine, scale, translation or unitary map, column-major. A frustum map has no matrix, so that grid goes to `skipped`.
|
|
1540
|
+
- **Left out.** A grid this reader does not decode goes to `skipped` with the reason, and the others still read: `bool`, mask and point grids. NanoVDB files (`.nvdb`) are refused, because their header is not an OpenVDB one.
|
|
1541
|
+
|
|
1542
|
+
## MaterialX
|
|
1543
|
+
|
|
1544
|
+
`parseMaterialX` from `@margoengine/loaders/materialx` reads `.mtlx` documents, version 1.38 and later, and `toGraph` turns a material into the graph that `nodeMaterial()` of `@margoengine/materials` takes.
|
|
1545
|
+
|
|
1546
|
+
`materialXDocument(parts)` builds a document from nodes and materials that came from elsewhere, which is how `margoengine/usdz/materialx` hands a USD network to `toGraph`.
|
|
1547
|
+
|
|
1548
|
+
```ts
|
|
1549
|
+
import { parseMaterialX } from '@margoengine/loaders/materialx';
|
|
1550
|
+
import { nodeMaterial } from '@margoengine/materials';
|
|
1551
|
+
|
|
1552
|
+
const text = '<materialx version="1.39"><standard_surface name="S" type="surfaceshader">' +
|
|
1553
|
+
'<input name="base_color" type="color3" value="0.9, 0.6, 0.2"/><input name="metalness" type="float" value="1"/>' +
|
|
1554
|
+
'</standard_surface><surfacematerial name="Brass" type="material">' +
|
|
1555
|
+
'<input name="surfaceshader" type="surfaceshader" nodename="S"/></surfacematerial></materialx>';
|
|
1556
|
+
const parsed = parseMaterialX(text);
|
|
1557
|
+
const { graph, skipped } = await parsed.toGraph('Brass');
|
|
1558
|
+
console.log(parsed.materials[0]?.shader?.category, skipped);
|
|
1559
|
+
const extension = nodeMaterial(graph); // primitive.extension = extension
|
|
1560
|
+
console.log(Object.keys(extension).length);
|
|
1561
|
+
```
|
|
1562
|
+
|
|
1563
|
+
- **Shaders.** `standard_surface`, `open_pbr_surface`, `gltf_pbr` and `UsdPreviewSurface`: base colour and its weight, metal, roughness, normal, coat and transmission. An unset input takes the default of that shader's published definition; a `standard_surface` with `version="1.0.0"` takes that definition's. Converting another shader is refused with code `unsupported`, though the document still reads.
|
|
1564
|
+
- **Nodes.** `image`, `tiledimage`, `gltf_image`, `constant`, `add`, `multiply`, `subtract`, `mix`, `dot`, `convert` and `normalmap`, inside and outside node graphs, with interface inputs.
|
|
1565
|
+
- **Images.** Pass `texture`, which gets `{ file, type, colorspace, addressU, addressV, filter }` once per image and returns `{ view, sampler }`. Upload `srgb_texture` images as sRGB. A `float` image reads the file's first channel, as MaterialX does, so it mixes, weighs and feeds roughness or metal as one value; a colour image feeding a lobe is read as the node material reads it (roughness green, metal blue), and a packed one needs `metalRough` by hand.
|
|
1566
|
+
- **`skipped`.** Node materials are a closed set, so whatever has no form there is listed with its reason and the input keeps its default: emission, opacity, noise and other procedural nodes. `uvtiling` and `uvoffset` are listed too, and the image still applies untiled.
|
|
1567
|
+
- **Colour.** Constants in `srgb_texture` convert to linear. Another colour space reads as linear and is named in `skipped`.
|
|
1568
|
+
- **Checked against MaterialX.** Eight test documents convert to graphs that match MaterialX 1.39.5's own texture bakes of them within one 8-bit sRGB step, on the CPU and drawn on the GPU, and the 26 example materials of MaterialX v1.39.5 convert with only named skips (`tests/materialx-reference.test.js`). The light and BSDF are Margo's; the picture is not compared with MaterialXView.
|
|
1569
|
+
- **Left out.** `xi:include` targets are listed in `includes` and not followed, custom `nodedef` graphs are not expanded, and the `<material>` form of 1.37 and before is refused. `look` assignments are read into `assignments`, for you to apply.
|
|
1570
|
+
|
|
1571
|
+
## Lottie
|
|
1572
|
+
|
|
1573
|
+
`parseLottie` from `@margoengine/loaders/lottie` reads Lottie JSON animations. `draw` paints a frame onto a 2D canvas for use as a texture, and `frame` gives the same frame as vector shapes.
|
|
1574
|
+
|
|
1575
|
+
```ts
|
|
1576
|
+
import { parseLottie } from '@margoengine/loaders/lottie';
|
|
1577
|
+
|
|
1578
|
+
const animation = parseLottie(await (await fetch('/motion/logo.json')).text());
|
|
1579
|
+
console.log(animation.width, animation.duration, animation.unsupported);
|
|
1580
|
+
|
|
1581
|
+
const canvas = new OffscreenCanvas(animation.width, animation.height);
|
|
1582
|
+
const context = canvas.getContext('2d')!;
|
|
1583
|
+
animation.draw(context, animation.frameRate * 0.5); // the frame half a second in; upload the canvas as a texture
|
|
1584
|
+
|
|
1585
|
+
for (const item of animation.frame(12.5)) // fractions blend between keyframes
|
|
1586
|
+
if (item.kind === 'path') console.log(item.fill, item.opacity, item.toShapes({ flipY: true }).length);
|
|
1587
|
+
```
|
|
1588
|
+
|
|
1589
|
+
- **Layers.** Shape, solid, image, null and precomposition layers, with parents, in and out frames, time stretch and time remapping. A precomposition clips what it holds to its `w` by `h` rectangle: each item lists those rectangles in `clip`, and `draw` applies them with the canvas's `clip()`. A layer's own keyframes run in the time of its composition, as Bodymovin writes them; `st` and `sr` move what a precomposition plays. Hand `draw` your loaded images as `{ images: { id: bitmap } }`, by the ids in `animation.images`.
|
|
1590
|
+
- **Shapes.** Rectangles, ellipses, polygons, stars, bezier paths and groups, with solid and gradient fills and strokes, dashes and trim paths, parallel or one by one. A trim reaches every shape before it in scope, also inside groups, and a stroke's width follows the transforms over the stroke.
|
|
1591
|
+
- **Keyframes.** Bezier easing, per axis where the file gives it, hold keys, spatial curves on positions (the ease is a share of the arc length), and paths that blend between keys. Colours from 0 to 255 in files older than Bodymovin 4.1.9 are read as such.
|
|
1592
|
+
- **Clear the canvas yourself.** `draw` paints over what is there, so call `clearRect` between frames.
|
|
1593
|
+
- **`unsupported`.** Masks, track mattes, text layers, effects, blend modes, 3D layers, repeaters, merge paths, rounded corners and star roundness are not drawn. Each one the file uses is named in this list, so check it when a file looks wrong. Expressions are ignored and are not listed.
|
|
1594
|
+
- **Proof.** Eight real exports match lottie-web 5.12.2 within 1 of 255 grey levels on a 16 by 16 grid (`REAL_FILES_ONLY=lottie npm run test:real-files -- --download`). Files that lean on masks, mattes or expressions differ: see `docs/limits.md`.
|
|
1595
|
+
|
|
1596
|
+
## XML
|
|
1597
|
+
|
|
1598
|
+
`margoengine/loaders/xml` is the small reader the XML formats here share, for any other format built on XML. It follows XML 1.0 Fifth Edition (W3C, 2008) as a non-validating reader (section 5.1): it skips comments and processing instructions, keeps CDATA as text, turns CR LF and CR into LF, normalizes attribute values (tabs and line ends become spaces, entity text included), refuses a character reference to a character XML does not allow, and checks that tags nest. `readXMLTree` gives the elements, with namespace prefixes removed. `readXML` streams them to a handler. `decodeXML` turns bytes into text by their byte order mark, then by the `encoding` of the XML declaration (ISO-8859-1, windows-1252 and the other labels `TextDecoder` knows), else as UTF-8.
|
|
1599
|
+
|
|
1600
|
+
The DOCTYPE's internal subset is read in full: general entities (Adobe Illustrator SVG writes `&ns_svg;` this way), parameter entities between declarations, and attribute declarations, whose defaults fill in missing attributes and whose tokenized types (ID, NMTOKENS, enumerations) collapse spaces. An entity holding markup is read as content and must hold whole elements. At most `maxExpansion` characters (default 1 Mi) come from entity references, which stops nested expansion bombs.
|
|
1601
|
+
|
|
1602
|
+
External entities are never fetched while reading. `resolveDTD(xml, {resolve, signal, base})` is the opt-in: it asks `resolve` for the external DTD subset, the external parameter entities it uses and the external entities the document references, until nothing more is needed, and returns their texts; pass them to `readXML` or `readXMLTree` as `external`. The external subset may use parameter entities inside declarations and INCLUDE and IGNORE sections. Without it, an entity the unread part could declare throws code `unsupported`, and entity and attribute declarations after an unread parameter entity are skipped, as section 5.1 asks (all of them are read when the document says `standalone="yes"`). `resolveDTD` reads at most `maxFiles` (64) entities and `maxCharacters` (16 Mi) in all; a failed read throws code `fetch` with the error as its `cause`.
|
|
1603
|
+
|
|
1604
|
+
```ts
|
|
1605
|
+
import { readXMLTree, resolveDTD } from 'margoengine/loaders/xml';
|
|
1606
|
+
|
|
1607
|
+
const root = readXMLTree('<scene name="yard"><item name="crate"/></scene>', 'Scene file');
|
|
1608
|
+
const scene = root.children[0];
|
|
1609
|
+
console.log(scene.name, scene.attributes.name, scene.children.length); // scene yard 1
|
|
1610
|
+
|
|
1611
|
+
// The DTD: a parameter entity, an entity holding markup and an attribute default.
|
|
1612
|
+
const doc = `<!DOCTYPE parts SYSTEM "parts.dtd" [
|
|
1613
|
+
<!ENTITY % common "<!ENTITY nut '<item kind="nut"/>'>">
|
|
1614
|
+
%common;
|
|
1615
|
+
]><parts>&nut;&bolt;</parts>`;
|
|
1616
|
+
const files = new Map([['parts.dtd', '<!ENTITY bolt "<item/>"><!ATTLIST item kind CDATA "bolt" unit CDATA "mm">']]);
|
|
1617
|
+
// In a browser: resolve: (id, {signal}) => fetch(new URL(id, location.href), {signal}).then((r) => r.text())
|
|
1618
|
+
const external = await resolveDTD(doc, { resolve: (id) => files.get(id) ?? '', signal: AbortSignal.timeout(10_000) });
|
|
1619
|
+
const items = readXMLTree(doc, 'Parts', { external }).children[0].children;
|
|
1620
|
+
console.log(items.map((item) => item.attributes.kind + ' ' + item.attributes.unit)); // ['nut mm', 'bolt mm']
|
|
1621
|
+
```
|
|
1622
|
+
|
|
1623
|
+
Every parser that reads XML takes the same `external` option (`XMLExternalOptions`): `parseDAE`, `parseKMZ`, `parseX3D`, `parse3MF` and `parse3MFLattice` (the model parts), `parseAMF`, `parseKML`, `parseGPX`, `parseTMX` (its map and its TSX tilesets), `parseSVG`, `parseMaterialX`, `parseVTKXML` and `openVTKXMLDataset`. Call `resolveDTD` first and pass its result, so a file with an external DTD loads without dropping to `readXMLTree`. Without `external` an entity only the external DTD declares throws code `unsupported`.
|
|
1624
|
+
|
|
1625
|
+
```ts
|
|
1626
|
+
import { parseDAE } from 'margoengine/loaders';
|
|
1627
|
+
import { resolveDTD } from 'margoengine/loaders/xml';
|
|
1628
|
+
|
|
1629
|
+
const doc = `<!DOCTYPE COLLADA SYSTEM "names.dtd">
|
|
1630
|
+
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
|
|
1631
|
+
<asset><up_axis>Y_UP</up_axis></asset>
|
|
1632
|
+
<library_visual_scenes><visual_scene id="S"><node id="n" name="∂"/></visual_scene></library_visual_scenes>
|
|
1633
|
+
<scene><instance_visual_scene url="#S"/></scene>
|
|
1634
|
+
</COLLADA>`;
|
|
1635
|
+
const files = new Map([['names.dtd', '<!ENTITY part "Wheel">']]);
|
|
1636
|
+
const external = await resolveDTD(doc, { resolve: (id) => files.get(id) ?? '' });
|
|
1637
|
+
console.log(parseDAE(doc, { external }).nodes[0].name); // Wheel
|
|
1638
|
+
```
|
|
1639
|
+
|
|
1640
|
+
## Tiled TMX
|
|
1641
|
+
|
|
1642
|
+
`await parseTMX(textOrBytes, {resolve, signal})` reads orthogonal Tiled maps (other orientations throw `unsupported`) and returns `{orientation, renderorder, width, height, tilewidth, tileheight, infinite, tilesets, tilesetRefs, layers, properties, warnings}`.
|
|
1643
|
+
|
|
1644
|
+
- Tilesets: embedded or external TSX (read through `resolve`, each file once), with `tilewidth`, `tileheight`, `spacing`, `margin`, `columns`, `tilecount`, `tileoffset: {x, y}` (pixels, y down, default 0, 0) and `image: {path, width, height}`, the path relative to the TMX folder. Tilesets with the same image, grid and tile offset are merged, so `tilesets` has no duplicates; `tilesetRefs` keeps every `firstgid` and the tileset it maps to.
|
|
1645
|
+
- Tile layers: csv, base64 (plain, zlib or gzip through `DecompressionStream`, size-capped; zstd throws `unsupported`) and legacy `<tile gid>` data, infinite-map `<chunk>`s merged into one grid whose top-left cell is `x`, `y`. `gids` hold the global tile ids with the flip bits cleared (the hexagonal-rotation bit too), `flips` the bits as 1 horizontal, 2 vertical, 4 diagonal.
|
|
1646
|
+
- Object layers: `{name, type, x, y, width, height, rotation, visible, gid, flips, properties}` per object, in pixels. Custom properties come typed (`int`, `float`, `bool`).
|
|
1647
|
+
- Group layers are flattened: offsets add up, opacity multiplies, visibility combines. Image layers and image-collection tilesets are reported in `warnings`.
|
|
1648
|
+
|
|
1649
|
+
`tmxLayerQuads(map, layer, {tileSize})` turns one tile layer into a `LoadedGeometry` of quads on the XZ plane facing +Y (column along +X, row along +Z, `tileSize` world units per cell, default 1, layer and tileset offsets included), four vertices per tile with UVs from the atlas rectangle (spacing and margin honored, flips applied in Tiled's order, v = 0 at the top of the image), `faceSizes` all 4, one group per tileset and `cells` mapping each quad back to its layer cell. One object per layer, as Crocotile imports TMX:
|
|
1650
|
+
|
|
1651
|
+
```ts
|
|
1652
|
+
import {parseTMX, tmxLayerQuads} from 'margoengine/loaders';
|
|
1653
|
+
const bytes = new Uint8Array(await (await fetch('/map.tmx')).arrayBuffer());
|
|
1654
|
+
|
|
1655
|
+
const resolve = async (path: string) => new Uint8Array(await (await fetch(path)).arrayBuffer());
|
|
1656
|
+
const map = await parseTMX(bytes, {resolve});
|
|
1657
|
+
for (const layer of map.layers) {
|
|
1658
|
+
if (layer.type !== 'tile' || !layer.visible) continue;
|
|
1659
|
+
const quads = tmxLayerQuads(map, layer, {tileSize: 1});
|
|
1660
|
+
for (const group of quads.groups) console.log(layer.name, map.tilesets[group.tileset].image?.path, group.count / 6);
|
|
1661
|
+
}
|
|
1662
|
+
```
|
|
1663
|
+
|
|
1664
|
+
### Loading into a second scene
|
|
1665
|
+
|
|
1666
|
+
`loadOBJ` remembers the scene that is active when you call it, before its first await, and makes the mesh there, though the OBJ and its libraries download later. Start it inside a second scene's plugin `setup` (or any code running while that scene is set up) and what it makes belongs to that scene; start it anywhere else and it belongs to the default scene. An abort leaves nothing in either scene.
|