3D engine that AI agents drive
Add a three.js bridge addon that imports object trees and exports parts (#989)
Nguyen Xuan An7b7e70c7451f
diff --git a/changes/989.md b/changes/989.mdnew file mode 100644index 00000000..e88f91ff--- /dev/null+++ b/changes/989.md@@ -0,0 +1,2 @@+- `@codepawlhq/67js-three-bridge` is a new optional addon: `fromThreeObject` imports a three.js object tree as 67js parts with a warning list, `toThreeObject` builds three.js meshes from parts, and `exportGlb` writes the GLB (#989)+ media: https://raw.githubusercontent.com/codepawl/67.js/989-three-bridge/docs/three-bridge-comparison.jpg A three.js scene on the left and the same scene after import into 67js on the rightdiff --git a/changes/989.size.md b/changes/989.size.mdnew file mode 100644index 00000000..fcca4f2d--- /dev/null+++ b/changes/989.size.md@@ -0,0 +1 @@+- three-bridge: a new optional addon of 24,900 bytes of source (7,140 bytes gzip, measured with `gzip -9`) that no core bundle includes; the core bundles are unchanged. The addon has no dependency and lists three.js and 67js as peer dependencies, so its install adds no packages.diff --git a/docs/guide.md b/docs/guide.mdindex c73d03db..e9afeeab 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -84,6 +84,8 @@ Core exports are available from `67js`:`67js/addons/canvas2d`: 2D recipes. `67js/addons/gltf`: optional asset decoding. These are separate imports to keep the core smaller.+The [three.js bridge](three-bridge.md) imports a three.js object tree as parts and exports parts back to three.js objects and GLB.+Other people's addons follow the [addon contract](addons.md): a peer dependency on 67js, the `67js-addon` keyword and a `67js` manifest.67js targets WebGL2. Version `0.4.0` includes the APIs below. Check the installed package version and release metadata before using them.diff --git a/docs/learn/if-you-know-three-js.md b/docs/learn/if-you-know-three-js.mdindex b84ed59f..0e7d99c7 100644--- a/docs/learn/if-you-know-three-js.md+++ b/docs/learn/if-you-know-three-js.md@@ -120,4 +120,6 @@ const THREE = createThreeCompat({ ...core, loadGltf });It accepts `Scene`, `Group`, `Mesh`, the box, plane, sphere, cylinder and torus geometries, `MeshStandardMaterial`, `MeshPhysicalMaterial`, both cameras, the light classes, `GLTFLoader`, `OrbitControls` and `WebGLRenderer` with `setAnimationLoop`. For any other three.js name it throws an error that names the 67js call to use. For example, `THREE.MeshBasicMaterial` tells you to use `MeshStandardMaterial` with `emissive`, which is `material.emission` in 67js.+To move a scene you already have, the [three.js bridge](../three-bridge.md) imports a three.js object tree as 67js parts and builds three.js meshes from parts.+The addon is a bridge for code that an agent writes from memory. For new code, write parts directly: it is shorter and has no extra layer.diff --git a/docs/three-bridge-comparison.jpg b/docs/three-bridge-comparison.jpgnew file mode 100644index 00000000..5518964bBinary files /dev/null and b/docs/three-bridge-comparison.jpg differdiff --git a/docs/three-bridge.md b/docs/three-bridge.mdnew file mode 100644index 00000000..ff3abb1a--- /dev/null+++ b/docs/three-bridge.md@@ -0,0 +1,75 @@+# three.js bridge++++Left: the three.js scene. Right: the same scene after `fromThreeObject` turned it into 67js parts. Geometry, colours, metalness, roughness and the checker texture carry over. Light and sky are not part of the tree: you set them on the 67js side, so they differ by design.++`@codepawlhq/67js-three-bridge` (folder `packages/three-bridge`) moves meshes between a live three.js object tree and 67js parts. Use it to try 67js on a scene you already have, or to hand 67js parts to code that expects three.js objects. For a GLB you do not need three.js at all: 67js writes it.++The addon is optional and not part of the core archive. It imports neither `three` nor 67js. `three` is a peer dependency of the addon only, and you pass the namespace in when you export.++## Import a three.js tree++```js+import * as THREE from 'three';+import { Renderer67 } from '@codepawlhq/67js';+import { fromThreeObject } from '@codepawlhq/67js-three-bridge';++const group = new THREE.Group();+group.add(new THREE.Mesh(new THREE.TorusKnotGeometry(0.7, 0.24), new THREE.MeshStandardMaterial({ color: 0xe0782a, metalness: 0.9, roughness: 0.3 })));++const { parts, warnings } = fromThreeObject(group);+if (warnings.length > 0) console.warn(warnings.join('\n'));+const renderer = new Renderer67(canvas, parts);+```++Each mesh becomes one part with its world matrix, so groups, parents and their transforms are applied. `InstancedMesh` becomes one part per instance, and meshes that share a `BufferGeometry` share one geometry object, which the renderer batches. A material array with `geometry.groups` becomes one part per group.++| three.js | 67js |+| --- | --- |+| `position`, `normal`, `uv`, `index` (or no index) | `positions`, `normals`, `uvs`, `indices`. Missing normals are computed and listed in `warnings`. |+| `color` attribute, when `material.vertexColors` is on | `colors` (three channels) |+| `color`, `metalness`, `roughness` | `color`, `metallic`, `roughness` (linear RGB) |+| `emissive`, `emissiveIntensity` | `emissiveColor`, `emission` |+| `map`, `normalMap`, `aoMap`, `emissiveMap` | `map`, `normalMap`, `occlusionMap`, `emissiveMap` |+| `roughnessMap` and `metalnessMap` when they are one texture | `metallicRoughnessMap` |+| `MeshPhysicalMaterial` `transmission`, `thickness`, `ior`, `clearcoat`, `clearcoatRoughness`, `specularIntensity` | `transmission`, `thickness`, `ior`, `clearcoat`, `clearcoatRoughness`, `specular` |+| `transparent`, `opacity`, `alphaTest`, `side: DoubleSide` | `alphaMode`, `opacity`, `alphaCutoff`, `doubleSided` |++### What goes in the warning list++Nothing is dropped silently. `warnings` names the object and the property for: morph targets, `drawRange`, `instanceColor`, `envMap`, `bumpMap`, `displacementMap`, `alphaMap`, `lightMap`, `wireframe`, `flatShading`, `BackSide`, texture repeat, offset and rotation, sheen, iridescence, anisotropy, separate roughness and metalness maps, and materials that are not `MeshStandardMaterial` (only colour, map and opacity are used). Invisible objects, points, lines, sprites, lights and cameras are skipped and listed. A `SkinnedMesh` with a skeleton is imported in its current pose.++Two inputs throw an error that names the object and what to change: a `ShaderMaterial` or `RawShaderMaterial` (67js runs no custom shaders) and a `SkinnedMesh` without `skeleton.bones`. Pass `skipUnsupported: true` to leave such an object out and get a warning instead.++### Limits++`maxParts` (default 10,000, at most 100,000) and `maxVertices` (default 4,000,000 per mesh, at most 20,000,000; the whole tree may hold four times that). A tree past a limit throws an error that says which option to raise. Unknown options throw.++## Export parts as three.js objects++```js+import * as THREE from 'three';+import { toThreeObject } from '@codepawlhq/67js-three-bridge';++const { object, warnings } = toThreeObject(parts, THREE, { name: 'scene' });+threeScene.add(object);+```++`object` is a `Group` of `Mesh` objects with `MeshStandardMaterial` (`MeshPhysicalMaterial` when a part uses transmission, clearcoat or ior). Parts that share a geometry or material share one `BufferGeometry` or material. Each mesh keeps its part matrix exactly, with `matrixAutoUpdate` off, so the world matrix equals the part's. To animate a mesh with `position` and `rotation`, decompose the matrix first: `mesh.matrix.decompose(mesh.position, mesh.quaternion, mesh.scale); mesh.matrixAutoUpdate = true;`. Skin and morph targets are not exported and are listed in `warnings`.++## Export a GLB++```js+import { exportGlb } from '@codepawlhq/67js';++const glb = exportGlb(fromThreeObject(group).parts);+```++The GLB loads with `GLTFLoader`, with node transforms matching the source within 1e-6. Textures need RGBA pixel data outside a browser.++## Checks++`tests/three-bridge.test.js` builds a group with a box, a sphere, a textured plane and a vertex coloured box, imports it, builds three.js objects from the parts and compares positions, normals, indices, world matrices and material fields (matrices within 1e-6, geometry arrays byte for byte). It also loads the `exportGlb` result with `GLTFLoader`.++The picture above comes from the same scene rendered by `THREE.WebGLRenderer` and by `Renderer67` on a software GPU at 640 by 360, so edges and timing differ from a real GPU.diff --git a/packages/three-bridge/README.md b/packages/three-bridge/README.mdnew file mode 100644index 00000000..07ed9c20--- /dev/null+++ b/packages/three-bridge/README.md@@ -0,0 +1,15 @@+# @codepawlhq/67js-three-bridge++Optional addon that imports a three.js object tree as 67js parts and builds three.js meshes from 67js parts. It imports neither `three` nor 67js. `three` is a peer dependency of this package only; the core gains none. Not part of the core `67js` archive.++```js+import * as THREE from 'three';+import { exportGlb } from '@codepawlhq/67js';+import { fromThreeObject, toThreeObject } from '@codepawlhq/67js-three-bridge';++const { parts, warnings } = fromThreeObject(group); // three.js Object3D -> 67js parts+const { object } = toThreeObject(parts, THREE); // 67js parts -> Group of Mesh+const glb = exportGlb(parts); // 67js parts -> GLB+```++Anything it cannot map is listed in `warnings`. A `ShaderMaterial` and a `SkinnedMesh` without bones throw an error that names the object. The guide with the mapping table, limits and options is [docs/three-bridge.md](../../docs/three-bridge.md).diff --git a/packages/three-bridge/index.mjs b/packages/three-bridge/index.mjsnew file mode 100644index 00000000..6884452f--- /dev/null+++ b/packages/three-bridge/index.mjs@@ -0,0 +1,464 @@+// Moves meshes between a three.js object tree and 67js parts.+// fromThreeObject(root) three.js Object3D tree -> { parts, warnings }+// toThreeObject(parts, THREE) 67js parts -> { object, warnings }, a Group of Mesh + MeshStandardMaterial+// It imports neither three.js nor 67js. It reads three.js objects by their shape (matrixWorld, geometry.attributes,+// material fields) and builds three.js objects from the THREE namespace you pass in. For a GLB, give the parts to+// exportGlb() from 67js.+// Anything it cannot map is listed in `warnings`; a custom shader or a skinned mesh without bones throws.++const DEFAULT_LIMITS = Object.freeze({ maxParts: 10000, maxVertices: 4000000 });+const HARD_LIMITS = Object.freeze({ maxParts: 100000, maxVertices: 20000000 });+const NORMAL_TOLERANCE = 1e-6;++// three.js wrap constants -> the GL constants a 67js texture descriptor uses.+const GL_WRAP = Object.freeze({ 1000: 10497, 1001: 33071, 1002: 33648 });+const THREE_WRAP_NAMES = Object.freeze({ 10497: 'RepeatWrapping', 33071: 'ClampToEdgeWrapping', 33648: 'MirroredRepeatWrapping' });+const DOUBLE_SIDE = 2;+const BACK_SIDE = 1;++// three.js physical field -> 67js material field, with the three.js default that means "not set".+const LAYER_FIELDS = Object.freeze([+ ['clearcoat', 'clearcoat', 0],+ ['clearcoatRoughness', 'clearcoatRoughness', 0],+ ['transmission', 'transmission', 0],+ ['thickness', 'thickness', 0],+ ['ior', 'ior', 1.5],+ ['specularIntensity', 'specular', 1],+]);++// Properties that three.js has and a 67js material cannot show, checked on every material.+const UNSUPPORTED_MATERIAL_PROPERTIES = Object.freeze({+ envMap: 'Pass the image based light to Renderer67 with createEnvironmentMap().',+ bumpMap: 'Convert it to a normal map.',+ displacementMap: 'Model the relief in the geometry.',+ alphaMap: 'Put the alpha in the alpha channel of the base colour map.',+ lightMap: 'Bake the light into the base colour map or use the 67js light bake.',+ wireframe: '67js has no wireframe view.',+ flatShading: 'Give the geometry split vertices.',+});++const SHADER_MATERIALS = ['isShaderMaterial', 'isRawShaderMaterial'];++class ThreeBridgeError extends Error {+ constructor(message) {+ super(message);+ this.name = 'ThreeBridgeError';+ }+}++function describe(object) {+ return `${object.type ?? 'Object3D'} "${object.name || '(unnamed)'}"`;+}++function resolveLimits(options) {+ const known = [...Object.keys(DEFAULT_LIMITS), 'skipUnsupported'];+ for (const key of Object.keys(options)) {+ if (!known.includes(key)) throw new ThreeBridgeError(`Unknown option "${key}". Pass ${known.join(', ')}.`);+ }+ const limits = { ...DEFAULT_LIMITS };+ for (const key of Object.keys(DEFAULT_LIMITS)) {+ if (options[key] === undefined) continue;+ if (!Number.isInteger(options[key]) || options[key] < 1 || options[key] > HARD_LIMITS[key]) {+ throw new ThreeBridgeError(`Option ${key} must be a whole number from 1 to ${HARD_LIMITS[key]}, not ${options[key]}.`);+ }+ limits[key] = options[key];+ }+ limits.skipUnsupported = options.skipUnsupported === true;+ return limits;+}++function multiply(left, right) {+ const product = new Array(16).fill(0);+ for (let column = 0; column < 4; column += 1) {+ for (let row = 0; row < 4; row += 1) {+ for (let k = 0; k < 4; k += 1) product[column * 4 + row] += left[k * 4 + row] * right[column * 4 + k];+ }+ }+ return product;+}++// ---------------------------------------------------------------- import++function readAttribute(attribute, itemSize, count, label) {+ if (attribute.itemSize < itemSize) {+ throw new ThreeBridgeError(`${label} has ${attribute.itemSize} values per vertex, ${itemSize} are needed. Pass an attribute with itemSize ${itemSize}.`);+ }+ const values = new Float32Array(count * itemSize);+ const getters = ['getX', 'getY', 'getZ'].slice(0, itemSize);+ for (let vertex = 0; vertex < count; vertex += 1) {+ getters.forEach((getter, component) => {+ values[vertex * itemSize + component] = attribute[getter](vertex);+ });+ }+ return values;+}++function smoothNormals(positions, indices) {+ const normals = new Float32Array(positions.length);+ for (let corner = 0; corner < indices.length; corner += 3) {+ const [a, b, c] = [indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3];+ const edgeOne = [0, 1, 2].map(axis => positions[b + axis] - positions[a + axis]);+ const edgeTwo = [0, 1, 2].map(axis => positions[c + axis] - positions[a + axis]);+ const face = [+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],+ ];+ for (const vertex of [a, b, c]) face.forEach((value, axis) => { normals[vertex + axis] += value; });+ }+ return normals;+}++function normalizeNormals(normals, fallbackAxis = 1) {+ let changed = false;+ for (let offset = 0; offset < normals.length; offset += 3) {+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]);+ if (Math.abs(length - 1) <= NORMAL_TOLERANCE) continue;+ changed = true;+ if (length === 0) {+ normals[offset + fallbackAxis] = 1;+ } else {+ for (let axis = 0; axis < 3; axis += 1) normals[offset + axis] /= length;+ }+ }+ return changed;+}++function readIndices(geometry, count, object, limits) {+ const source = geometry.index;+ const length = source ? source.count : count;+ if (length < 3 || length % 3 !== 0) {+ throw new ThreeBridgeError(`${describe(object)} geometry.${source ? 'index' : 'attributes.position'} holds ${length} entries, which is not whole triangles. Pass triangle geometry.`);+ }+ if (length > limits.maxVertices * 3) throw new ThreeBridgeError(`${describe(object)} geometry has ${length} indices, above the limit of ${limits.maxVertices * 3}. Raise maxVertices or simplify the mesh.`);+ const indices = new Uint32Array(length);+ for (let entry = 0; entry < length; entry += 1) indices[entry] = source ? source.getX(entry) : entry;+ return indices;+}++function importGeometry(object, useVertexColors, limits, state) {+ const { geometry } = object;+ const position = geometry?.attributes?.position;+ if (!position) throw new ThreeBridgeError(`${describe(object)} has no geometry.attributes.position. Pass a BufferGeometry with a position attribute.`);+ if (position.count > limits.maxVertices) throw new ThreeBridgeError(`${describe(object)} geometry has ${position.count} vertices, above the limit of ${limits.maxVertices}. Raise maxVertices or simplify the mesh.`);+ state.vertices += position.count;+ if (state.vertices > limits.maxVertices * 4) throw new ThreeBridgeError(`The tree holds more than ${limits.maxVertices * 4} vertices in total. Raise maxVertices or import fewer objects.`);+ const positions = readAttribute(position, 3, position.count, `${describe(object)} geometry.attributes.position`);+ const indices = readIndices(geometry, position.count, object, limits);+ for (const index of indices) {+ if (index >= position.count) throw new ThreeBridgeError(`${describe(object)} geometry.index points at vertex ${index} but there are ${position.count}. Fix the index.`);+ }+ let normals;+ if (geometry.attributes.normal) {+ normals = readAttribute(geometry.attributes.normal, 3, position.count, `${describe(object)} geometry.attributes.normal`);+ } else {+ normals = smoothNormals(positions, indices);+ state.warnings.push(`${describe(object)}: geometry has no normal attribute, smooth normals were computed.`);+ }+ if (normalizeNormals(normals)) state.warnings.push(`${describe(object)}: normals were not unit length and were normalized.`);+ const imported = { positions, normals, indices };+ if (geometry.attributes.uv) imported.uvs = readAttribute(geometry.attributes.uv, 2, position.count, `${describe(object)} geometry.attributes.uv`);+ if (useVertexColors && geometry.attributes.color) {+ const colors = geometry.attributes.color;+ imported.colors = readAttribute(colors, 3, position.count, `${describe(object)} geometry.attributes.color`);+ if (colors.itemSize === 4) state.warnings.push(`${describe(object)}: vertex colour alpha is ignored.`);+ }+ if (geometry.morphAttributes && Object.keys(geometry.morphAttributes).length > 0) {+ state.warnings.push(`${describe(object)}: morph targets are not imported.`);+ }+ if (geometry.drawRange && (geometry.drawRange.start !== 0 || Number.isFinite(geometry.drawRange.count))) {+ state.warnings.push(`${describe(object)}: geometry.drawRange is ignored, every triangle is imported.`);+ }+ return imported;+}++function importTexture(texture, colorSpace, label, state) {+ if (!texture.image) throw new ThreeBridgeError(`${label} has no image yet. Wait until the texture has loaded before importing.`);+ const moved = texture.repeat && (texture.repeat.x !== 1 || texture.repeat.y !== 1);+ const offset = texture.offset && (texture.offset.x !== 0 || texture.offset.y !== 0);+ if (moved || offset || texture.rotation) state.warnings.push(`${label}: texture repeat, offset and rotation are not applied.`);+ return {+ image: texture.image,+ colorSpace,+ flipY: texture.flipY === true,+ wrapS: GL_WRAP[texture.wrapS] ?? 10497,+ wrapT: GL_WRAP[texture.wrapT] ?? 10497,+ };+}++function importMaterial(material, owner, state) {+ const label = `${describe(owner)} material "${material.name || material.type}"`;+ if (SHADER_MATERIALS.some(flag => material[flag])) {+ throw new ThreeBridgeError(`${label} is a ${material.type}, which 67js cannot run. Replace it with MeshStandardMaterial, or pass skipUnsupported: true to leave the object out.`);+ }+ if (!material.isMeshStandardMaterial) {+ state.warnings.push(`${label}: ${material.type} has no roughness or metalness, so only its colour, map and opacity are used.`);+ }+ for (const [property, advice] of Object.entries(UNSUPPORTED_MATERIAL_PROPERTIES)) {+ if (material[property]) state.warnings.push(`${label}: ${property} is not imported. ${advice}`);+ }+ if (material.side === BACK_SIDE) state.warnings.push(`${label}: BackSide is imported as front side.`);+ const result = {+ color: [material.color?.r ?? 1, material.color?.g ?? 1, material.color?.b ?? 1],+ metallic: material.metalness ?? 0,+ roughness: material.roughness ?? 1,+ };+ const emissive = material.emissive;+ if (emissive && emissive.r + emissive.g + emissive.b > 0) {+ result.emission = material.emissiveIntensity ?? 1;+ result.emissiveColor = [emissive.r, emissive.g, emissive.b];+ }+ if (material.map) result.map = importTexture(material.map, 'srgb', `${label} map`, state);+ if (material.normalMap) {+ result.normalMap = importTexture(material.normalMap, 'linear', `${label} normalMap`, state);+ result.normalScale = material.normalScale?.x ?? 1;+ }+ if (material.aoMap) {+ result.occlusionMap = importTexture(material.aoMap, 'linear', `${label} aoMap`, state);+ result.occlusionStrength = material.aoMapIntensity ?? 1;+ }+ if (material.emissiveMap) result.emissiveMap = importTexture(material.emissiveMap, 'srgb', `${label} emissiveMap`, state);+ if (material.roughnessMap && material.roughnessMap === material.metalnessMap) {+ result.metallicRoughnessMap = importTexture(material.roughnessMap, 'linear', `${label} roughnessMap`, state);+ } else if (material.roughnessMap || material.metalnessMap) {+ state.warnings.push(`${label}: roughnessMap and metalnessMap are imported only when they are the same texture (glTF packs them in one image).`);+ }+ for (const [threeField, field, defaultValue] of LAYER_FIELDS) {+ if (material[threeField] !== undefined && material[threeField] !== defaultValue) result[field] = material[threeField];+ }+ if (material.sheen || material.iridescence || material.anisotropy) {+ state.warnings.push(`${label}: sheen, iridescence and anisotropy are not imported.`);+ }+ if (material.alphaTest > 0) {+ result.alphaMode = 'mask';+ result.alphaCutoff = material.alphaTest;+ } else if (material.transparent) {+ result.alphaMode = 'blend';+ }+ if (material.opacity !== undefined && material.opacity !== 1) result.opacity = material.opacity;+ if (material.side === DOUBLE_SIDE) result.doubleSided = true;+ return result;+}++function checkMesh(object, state) {+ if (object.isSkinnedMesh) {+ if (!object.skeleton?.bones?.length) {+ throw new ThreeBridgeError(`${describe(object)} is a SkinnedMesh without skeleton.bones. Bind a Skeleton first, or pass skipUnsupported: true to leave it out.`);+ }+ state.warnings.push(`${describe(object)}: skinning is not imported, the mesh is imported in its current pose.`);+ }+ if (object.isInstancedMesh && object.instanceColor) {+ state.warnings.push(`${describe(object)}: instanceColor is not imported.`);+ }+}++function uniqueName(object, fallback, state) {+ const base = object.name || fallback;+ let name = base;+ for (let copy = 1; state.names.has(name); copy += 1) name = `${base}-${copy}`;+ state.names.add(name);+ return name;+}++function importMesh(object, limits, state) {+ checkMesh(object, state);+ const materials = Array.isArray(object.material) ? object.material : [object.material];+ const groups = Array.isArray(object.material) ? object.geometry.groups : [{ start: 0, count: Infinity, materialIndex: 0 }];+ if (!groups?.length) {+ throw new ThreeBridgeError(`${describe(object)} has a material array but geometry.groups is empty. Add groups with geometry.addGroup(start, count, materialIndex), or pass one material.`);+ }+ const instances = object.isInstancedMesh ? object.count : 1;+ if (state.parts.length + instances * groups.length > limits.maxParts) {+ throw new ThreeBridgeError(`${describe(object)} would take the tree past ${limits.maxParts} parts (${instances} instances x ${groups.length} materials). Raise maxParts (up to ${HARD_LIMITS.maxParts}) or import fewer instances.`);+ }+ const cacheKey = materials.some(material => material.vertexColors);+ const cached = state.geometries.get(object.geometry) ?? new Map();+ if (!cached.has(cacheKey)) cached.set(cacheKey, importGeometry(object, cacheKey, limits, state));+ state.geometries.set(object.geometry, cached);+ const whole = cached.get(cacheKey);+ const matrices = object.isInstancedMesh+ ? Array.from({ length: object.count }, (_, instance) => multiply(object.matrixWorld.elements, Array.from(object.instanceMatrix.array.subarray(instance * 16, instance * 16 + 16))))+ : [Array.from(object.matrixWorld.elements)];+ const found = [];+ for (const group of groups) {+ const material = materials[group.materialIndex];+ if (!material) throw new ThreeBridgeError(`${describe(object)} geometry.groups uses materialIndex ${group.materialIndex} but the material array has ${materials.length}. Fix the group.`);+ if (!state.materials.has(material)) state.materials.set(material, importMaterial(material, object, state));+ const geometry = Number.isFinite(group.count)+ ? { ...whole, indices: whole.indices.slice(group.start, group.start + group.count) }+ : whole;+ found.push({ geometry, material: state.materials.get(material) });+ }+ for (const matrix of matrices) {+ for (const { geometry, material } of found) {+ if (state.parts.length >= limits.maxParts) {+ throw new ThreeBridgeError(`The tree holds more than ${limits.maxParts} parts. Raise maxParts (up to ${HARD_LIMITS.maxParts}) or import a smaller subtree.`);+ }+ state.parts.push({ name: uniqueName(object, object.isInstancedMesh ? 'instance' : 'mesh', state), geometry, matrix, material });+ }+ }+}++function visit(object, limits, state) {+ if (object.visible === false) {+ state.warnings.push(`${describe(object)}: invisible objects are skipped, with their children.`);+ return;+ }+ if (object.isMesh) {+ try {+ importMesh(object, limits, state);+ } catch (error) {+ if (!limits.skipUnsupported || !(error instanceof ThreeBridgeError)) throw error;+ state.warnings.push(`${error.message} (skipped)`);+ }+ } else if (object.isPoints || object.isLine || object.isSprite) {+ state.warnings.push(`${describe(object)}: 67js draws triangle meshes only, so this object is skipped.`);+ } else if (object.isLight || object.isCamera) {+ state.warnings.push(`${describe(object)}: lights and cameras are not parts. Set them as 67js environment and frame fields.`);+ }+ for (const child of object.children ?? []) visit(child, limits, state);+}++/**+ * Walks a three.js Object3D tree and returns `{ parts, warnings }`. Each part is a 67js part+ * `{ name, geometry, matrix, material }` with the world matrix of its mesh. Meshes that share a BufferGeometry share one+ * geometry object, so the renderer batches them. Options: `maxParts`, `maxVertices`, `skipUnsupported`.+ */+export function fromThreeObject(root, options = {}) {+ if (!root || typeof root !== 'object' || !Array.isArray(root.children)) {+ throw new ThreeBridgeError('fromThreeObject needs a three.js Object3D, such as a Group or a Scene. Pass the root of the tree you want to import.');+ }+ const limits = resolveLimits(options);+ root.updateWorldMatrix?.(true, true);+ const state = { parts: [], warnings: [], names: new Set(), geometries: new Map(), materials: new Map(), vertices: 0 };+ visit(root, limits, state);+ return { parts: state.parts, warnings: state.warnings };+}++// ---------------------------------------------------------------- export++function requireNamespace(THREE) {+ for (const name of ['Group', 'Mesh', 'BufferGeometry', 'BufferAttribute', 'MeshStandardMaterial']) {+ if (typeof THREE?.[name] !== 'function') {+ throw new ThreeBridgeError(`toThreeObject needs the three.js namespace as its second argument, with ${name}. Pass import * as THREE from 'three'.`);+ }+ }+}++function checkPart(part, index, limits) {+ const label = `parts[${index}]${part?.name ? ` "${part.name}"` : ''}`;+ const geometry = part?.geometry;+ if (!geometry?.positions || geometry.positions.length < 9 || geometry.positions.length % 3 !== 0) {+ throw new ThreeBridgeError(`${label} needs geometry.positions with XYZ triples for at least one triangle.`);+ }+ if (geometry.positions.length / 3 > limits.maxVertices) {+ throw new ThreeBridgeError(`${label} has ${geometry.positions.length / 3} vertices, above the limit of ${limits.maxVertices}. Raise maxVertices.`);+ }+ if (!geometry.indices || geometry.indices.length === 0 || geometry.indices.length % 3 !== 0) {+ throw new ThreeBridgeError(`${label} needs geometry.indices holding whole triangles (a Uint32Array).`);+ }+ if (part.matrix?.length !== 16 || Array.from(part.matrix).some(value => !Number.isFinite(value))) {+ throw new ThreeBridgeError(`${label} needs a matrix of 16 finite numbers (column-major).`);+ }+ if (!part.material || typeof part.material !== 'object') throw new ThreeBridgeError(`${label} needs a material object { color, metallic, roughness }.`);+ return label;+}++function buildGeometry(THREE, geometry) {+ const result = new THREE.BufferGeometry();+ result.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(geometry.positions), 3));+ if (geometry.normals) result.setAttribute('normal', new THREE.BufferAttribute(Float32Array.from(geometry.normals), 3));+ if (geometry.uvs) result.setAttribute('uv', new THREE.BufferAttribute(Float32Array.from(geometry.uvs), 2));+ if (geometry.colors) result.setAttribute('color', new THREE.BufferAttribute(Float32Array.from(geometry.colors), 3));+ result.setIndex(new THREE.BufferAttribute(Uint32Array.from(geometry.indices), 1));+ return result;+}++function buildTexture(THREE, descriptor, label, state) {+ if (!state.textures.has(descriptor)) {+ if (typeof THREE.Texture !== 'function') throw new ThreeBridgeError(`${label} has a texture but the THREE namespace has no Texture. Pass import * as THREE from 'three'.`);+ const texture = new THREE.Texture(descriptor.image);+ texture.colorSpace = descriptor.colorSpace === 'srgb' ? THREE.SRGBColorSpace : THREE.NoColorSpace;+ texture.flipY = descriptor.flipY === true;+ texture.wrapS = THREE[THREE_WRAP_NAMES[descriptor.wrapS]] ?? THREE.RepeatWrapping;+ texture.wrapT = THREE[THREE_WRAP_NAMES[descriptor.wrapT]] ?? THREE.RepeatWrapping;+ texture.needsUpdate = true;+ state.textures.set(descriptor, texture);+ }+ return state.textures.get(descriptor);+}++function buildMaterial(THREE, source, label, state) {+ const usesLayers = LAYER_FIELDS.some(([, field]) => source[field] !== undefined);+ const MaterialClass = usesLayers && typeof THREE.MeshPhysicalMaterial === 'function' ? THREE.MeshPhysicalMaterial : THREE.MeshStandardMaterial;+ if (usesLayers && MaterialClass === THREE.MeshStandardMaterial) state.warnings.push(`${label}: the THREE namespace has no MeshPhysicalMaterial, so clearcoat, transmission and ior are dropped.`);+ const material = new MaterialClass();+ material.color.setRGB(...source.color);+ material.metalness = source.metallic ?? 0;+ material.roughness = source.roughness ?? 1;+ if ((source.emission ?? 0) > 0) {+ material.emissive.setRGB(...(source.emissiveColor ?? source.color));+ material.emissiveIntensity = source.emission;+ }+ const maps = { map: 'map', normalMap: 'normalMap', occlusionMap: 'aoMap', emissiveMap: 'emissiveMap' };+ for (const [field, threeField] of Object.entries(maps)) {+ if (source[field]) material[threeField] = buildTexture(THREE, source[field], `${label} ${field}`, state);+ }+ if (source.metallicRoughnessMap) {+ material.roughnessMap = buildTexture(THREE, source.metallicRoughnessMap, `${label} metallicRoughnessMap`, state);+ material.metalnessMap = material.roughnessMap;+ }+ if (source.normalScale !== undefined) material.normalScale.set(source.normalScale, source.normalScale);+ if (source.occlusionStrength !== undefined) material.aoMapIntensity = source.occlusionStrength;+ if (MaterialClass !== THREE.MeshStandardMaterial) {+ for (const [threeField, field] of LAYER_FIELDS) {+ if (source[field] !== undefined) material[threeField] = source[field];+ }+ }+ if (source.alphaMode === 'mask') {+ material.alphaTest = source.alphaCutoff ?? 0.5;+ } else if (source.alphaMode === 'blend' || source.alphaMode === 'add') {+ material.transparent = true;+ if (source.alphaMode === 'add' && THREE.AdditiveBlending !== undefined) material.blending = THREE.AdditiveBlending;+ }+ if (source.opacity !== undefined) material.opacity = source.opacity;+ if (source.doubleSided) material.side = THREE.DoubleSide ?? DOUBLE_SIDE;+ return material;+}++/**+ * Builds a Group of Mesh objects from 67js parts and returns `{ object, warnings }`. THREE is the namespace of three.js+ * (`import * as THREE from 'three'`). Parts that share a geometry object share a BufferGeometry, and parts that share a+ * material object share a material. Each mesh takes its part matrix as is (`matrixAutoUpdate` is off), so the world+ * matrix matches the part exactly; copy `mesh.matrix` into position, quaternion and scale to animate it.+ * Options: `maxParts`, `maxVertices`, `name` of the group.+ */+export function toThreeObject(parts, THREE, options = {}) {+ requireNamespace(THREE);+ if (!Array.isArray(parts) || parts.length === 0) {+ throw new ThreeBridgeError('toThreeObject needs a nonempty array of 67js parts. Pass the parts of a scene, such as the parts of fromThreeObject().');+ }+ const { name = 'parts', ...limitOptions } = options;+ const limits = resolveLimits(limitOptions);+ if (parts.length > limits.maxParts) throw new ThreeBridgeError(`${parts.length} parts is above the limit of ${limits.maxParts}. Raise maxParts (up to ${HARD_LIMITS.maxParts}) or pass fewer parts.`);+ const state = { warnings: [], textures: new Map() };+ const geometries = new Map();+ const materials = new Map();+ const group = new THREE.Group();+ group.name = name;+ parts.forEach((part, index) => {+ const label = checkPart(part, index, limits);+ if (part.skin || part.morph) state.warnings.push(`${label}: skin and morph targets are not exported to three.js objects.`);+ if (!geometries.has(part.geometry)) geometries.set(part.geometry, buildGeometry(THREE, part.geometry));+ if (!materials.has(part.material)) materials.set(part.material, buildMaterial(THREE, part.material, label, state));+ const mesh = new THREE.Mesh(geometries.get(part.geometry), materials.get(part.material));+ mesh.name = part.name ?? `part-${index}`;+ mesh.matrixAutoUpdate = false;+ mesh.matrix.fromArray(Array.from(part.matrix));+ mesh.castShadow = part.castShadow !== false;+ mesh.receiveShadow = true;+ group.add(mesh);+ });+ group.updateMatrixWorld(true);+ return { object: group, warnings: state.warnings };+}diff --git a/packages/three-bridge/package.json b/packages/three-bridge/package.jsonnew file mode 100644index 00000000..335fef19--- /dev/null+++ b/packages/three-bridge/package.json@@ -0,0 +1,28 @@+{+ "name": "@codepawlhq/67js-three-bridge",+ "version": "0.1.0",+ "description": "Optional addon that imports a three.js object tree as 67js parts and builds three.js meshes from 67js parts. Imports neither three nor 67js. Not part of the core archive.",+ "type": "module",+ "main": "./index.mjs",+ "exports": {+ ".": "./index.mjs"+ },+ "files": [+ "index.mjs",+ "README.md"+ ],+ "keywords": [+ "67js-addon",+ "three",+ "threejs",+ "gltf"+ ],+ "license": "MIT",+ "peerDependencies": {+ "@codepawlhq/67js": ">=0.19.0 <1.0.0",+ "three": ">=0.160.0"+ },+ "engines": {+ "node": ">=20.19"+ }+}diff --git a/tests/three-bridge.test.js b/tests/three-bridge.test.jsnew file mode 100644index 00000000..dfba62ba--- /dev/null+++ b/tests/three-bridge.test.js@@ -0,0 +1,241 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { exportGlb } from '../src/export.js';+import { fromThreeObject, toThreeObject } from '../packages/three-bridge/index.mjs';++const TOLERANCE = 1e-6;++function checkerTexture() {+ const data = new Uint8Array(4 * 4 * 4).fill(200);+ const texture = new THREE.Texture({ data, width: 4, height: 4 });+ texture.colorSpace = THREE.SRGBColorSpace;+ texture.flipY = false;+ texture.wrapS = THREE.ClampToEdgeWrapping;+ return texture;+}++function buildSourceGroup() {+ const group = new THREE.Group();+ group.name = 'source';+ group.position.set(1, 2, 3);+ group.rotation.set(0.1, 0.2, 0.3);++ const box = new THREE.Mesh(new THREE.BoxGeometry(1, 2, 3), new THREE.MeshStandardMaterial({ color: 0x2f9e6b, roughness: 0.4, metalness: 0.6 }));+ box.name = 'box';+ box.position.set(-2, 0, 0);++ const sphere = new THREE.Mesh(new THREE.SphereGeometry(1, 12, 8), new THREE.MeshPhysicalMaterial({+ color: 0xffaa33, roughness: 0.2, transmission: 0.7, ior: 1.3, thickness: 0.5, clearcoat: 0.4,+ emissive: 0x112233, emissiveIntensity: 2, transparent: true, opacity: 0.8, side: THREE.DoubleSide,+ }));+ sphere.name = 'sphere';+ sphere.scale.set(1, 2, 0.5);+ sphere.position.set(2, 0, 1);++ const textured = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.MeshStandardMaterial({ map: checkerTexture(), normalMap: checkerTexture(), normalScale: new THREE.Vector2(0.5, 0.5) }));+ textured.name = 'textured';+ textured.rotation.x = -Math.PI / 2;++ const vertexColored = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ vertexColors: true }));+ vertexColored.geometry.setAttribute('color', new THREE.BufferAttribute(new Float32Array(24 * 3).fill(0.25), 3));+ vertexColored.name = 'colored';+ vertexColored.position.y = 3;++ group.add(box, sphere, textured, vertexColored);+ return group;+}++function maxDifference(left, right) {+ assert.equal(left.length, right.length);+ let largest = 0;+ for (let index = 0; index < left.length; index += 1) largest = Math.max(largest, Math.abs(left[index] - right[index]));+ return largest;+}++test('the addon has no import statement and keeps three.js as a peer dependency only', async () => {+ const source = await readFile(new URL('../packages/three-bridge/index.mjs', import.meta.url), 'utf8');+ assert.doesNotMatch(source, /^\s*import\s/m);+ const pack = JSON.parse(await readFile(new URL('../packages/three-bridge/package.json', import.meta.url), 'utf8'));+ assert.equal(pack.dependencies, undefined);+ assert.ok(pack.peerDependencies.three);+ assert.ok(pack.peerDependencies['@codepawlhq/67js']);+ const core = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));+ assert.equal(core.dependencies?.three, undefined, 'the core takes no three.js runtime dependency');+});++test('a group is imported with vertex counts, index counts and world matrices', () => {+ const group = buildSourceGroup();+ const { parts, warnings } = fromThreeObject(group);+ assert.deepEqual(parts.map(part => part.name), ['box', 'sphere', 'textured', 'colored']);+ const expectedGeometries = [group.children[0], group.children[1], group.children[2], group.children[3]].map(mesh => mesh.geometry);+ parts.forEach((part, index) => {+ const geometry = expectedGeometries[index];+ assert.equal(part.geometry.positions.length / 3, geometry.attributes.position.count, `${part.name} vertices`);+ assert.equal(part.geometry.indices.length, geometry.index.count, `${part.name} indices`);+ assert.ok(maxDifference(part.matrix, group.children[index].matrixWorld.elements) < TOLERANCE, `${part.name} matrix`);+ });+ assert.equal(parts[2].geometry.uvs.length, 4 * 2);+ assert.equal(parts[3].geometry.colors.length, 24 * 3);+ assert.equal(parts[0].geometry.colors, undefined, 'colours import only when material.vertexColors is on');+ assert.deepEqual(warnings, [], 'a supported tree gives no warnings');+});++test('material fields map to the 67js material', () => {+ const { parts } = fromThreeObject(buildSourceGroup());+ const [box, sphere, textured] = parts.map(part => part.material);+ assert.ok(maxDifference(box.color, new THREE.Color(0x2f9e6b).toArray()) < TOLERANCE);+ assert.equal(box.roughness, 0.4);+ assert.equal(box.metallic, 0.6);+ assert.equal(sphere.transmission, 0.7);+ assert.equal(sphere.ior, 1.3);+ assert.equal(sphere.thickness, 0.5);+ assert.equal(sphere.clearcoat, 0.4);+ assert.equal(sphere.emission, 2);+ assert.equal(sphere.alphaMode, 'blend');+ assert.equal(sphere.opacity, 0.8);+ assert.equal(sphere.doubleSided, true);+ assert.equal(textured.map.colorSpace, 'srgb');+ assert.equal(textured.map.wrapS, 33071);+ assert.equal(textured.normalMap.colorSpace, 'linear');+ assert.equal(textured.normalScale, 0.5);+ assert.equal(box.map, undefined);+});++test('import is deterministic', () => {+ assert.deepEqual(fromThreeObject(buildSourceGroup()), fromThreeObject(buildSourceGroup()));+});++test('a round trip keeps positions, normals, indices, matrices and material fields', () => {+ const group = buildSourceGroup();+ const { parts } = fromThreeObject(group);+ const { object, warnings } = toThreeObject(parts, THREE);+ assert.deepEqual(warnings, []);+ assert.equal(object.children.length, parts.length);+ object.children.forEach((mesh, index) => {+ const source = group.children[index];+ assert.equal(mesh.name, source.name);+ assert.equal(maxDifference(mesh.geometry.attributes.position.array, source.geometry.attributes.position.array), 0);+ assert.equal(maxDifference(mesh.geometry.attributes.normal.array, source.geometry.attributes.normal.array), 0);+ assert.deepEqual(Array.from(mesh.geometry.index.array), Array.from(source.geometry.index.array));+ assert.ok(maxDifference(mesh.matrixWorld.elements, source.matrixWorld.elements) < TOLERANCE, `${mesh.name} world matrix`);+ assert.ok(mesh.material.isMeshStandardMaterial);+ for (const field of ['roughness', 'metalness', 'opacity', 'transparent', 'side', 'emissiveIntensity']) {+ assert.equal(mesh.material[field], source.material[field], `${mesh.name} ${field}`);+ }+ assert.ok(maxDifference(mesh.material.color.toArray(), source.material.color.toArray()) < TOLERANCE);+ assert.ok(maxDifference(mesh.material.emissive.toArray(), source.material.emissive.toArray()) < TOLERANCE);+ });+ const sphere = object.children[1].material;+ assert.ok(sphere.isMeshPhysicalMaterial);+ assert.deepEqual([sphere.transmission, sphere.ior, sphere.thickness, sphere.clearcoat], [0.7, 1.3, 0.5, 0.4]);+ const textured = object.children[2].material;+ assert.equal(textured.map.image, group.children[2].material.map.image);+ assert.equal(textured.map.wrapS, THREE.ClampToEdgeWrapping);+ assert.equal(textured.map.colorSpace, THREE.SRGBColorSpace);+ assert.equal(textured.normalScale.x, 0.5);+ const again = fromThreeObject(object).parts;+ assert.deepEqual(again.map(part => Array.from(part.geometry.indices)), parts.map(part => Array.from(part.geometry.indices)));+ again.forEach((part, index) => assert.equal(maxDifference(part.geometry.positions, parts[index].geometry.positions), 0));+});++test('exportGlb of the bridged parts loads in GLTFLoader with matching transforms and counts', async () => {+ const group = buildSourceGroup();+ group.remove(group.children[2]);+ const { parts } = fromThreeObject(group);+ const gltf = await new GLTFLoader().parseAsync(exportGlb(parts), '');+ gltf.scene.updateMatrixWorld(true);+ const loaded = [];+ gltf.scene.traverse(node => { if (node.isMesh) loaded.push(node); });+ assert.equal(loaded.length, parts.length);+ loaded.forEach((mesh, index) => {+ const source = group.children[index];+ assert.equal(mesh.name, source.name);+ assert.equal(mesh.geometry.attributes.position.count, source.geometry.attributes.position.count);+ assert.equal(mesh.geometry.index.count, source.geometry.index.count);+ assert.ok(maxDifference(mesh.matrixWorld.elements, source.matrixWorld.elements) < TOLERANCE, `${mesh.name} node transform`);+ });+});++test('an InstancedMesh becomes one part per instance that all share one geometry', () => {+ const instanced = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial(), 3);+ instanced.name = 'crate';+ for (let index = 0; index < 3; index += 1) {+ instanced.setMatrixAt(index, new THREE.Matrix4().makeTranslation(index * 2, 0, 0));+ }+ instanced.position.y = 1;+ const { parts } = fromThreeObject(instanced);+ assert.deepEqual(parts.map(part => part.name), ['crate', 'crate-1', 'crate-2']);+ assert.equal(new Set(parts.map(part => part.geometry)).size, 1);+ assert.deepEqual(parts.map(part => part.matrix[12]), [0, 2, 4]);+ assert.equal(parts[0].matrix[13], 1);+});++test('a non-indexed mesh without normals gets indices and computed normals, with a warning', () => {+ const geometry = new THREE.BufferGeometry();+ geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), 3));+ const { parts, warnings } = fromThreeObject(new THREE.Mesh(geometry, new THREE.MeshStandardMaterial()));+ assert.deepEqual(Array.from(parts[0].geometry.indices), [0, 1, 2]);+ assert.deepEqual(Array.from(parts[0].geometry.normals.slice(0, 3)), [0, 0, 1]);+ assert.match(warnings.join('\n'), /no normal attribute/);+ assert.doesNotThrow(() => exportGlb(parts));+});++test('a material array is split by geometry group', () => {+ const geometry = new THREE.BoxGeometry(1, 1, 1);+ const materials = [new THREE.MeshStandardMaterial({ color: 0xff0000 }), new THREE.MeshStandardMaterial({ color: 0x0000ff })];+ geometry.clearGroups();+ geometry.addGroup(0, 18, 0);+ geometry.addGroup(18, 18, 1);+ const { parts } = fromThreeObject(new THREE.Mesh(geometry, materials));+ assert.equal(parts.length, 2);+ assert.deepEqual(parts.map(part => part.geometry.indices.length), [18, 18]);+ assert.notDeepEqual(parts[0].material.color, parts[1].material.color);+});++test('unsupported features are listed in warnings, never dropped silently', () => {+ const group = new THREE.Group();+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ envMap: new THREE.Texture(), wireframe: true, side: THREE.BackSide }));+ mesh.name = 'shiny';+ const basic = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial());+ const hidden = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());+ hidden.visible = false;+ const light = new THREE.PointLight();+ const points = new THREE.Points(new THREE.BufferGeometry(), new THREE.PointsMaterial());+ group.add(mesh, basic, hidden, light, points);+ const { parts, warnings } = fromThreeObject(group);+ assert.equal(parts.length, 2);+ const text = warnings.join('\n');+ for (const expected of ['envMap is not imported', 'wireframe is not imported', 'BackSide', 'MeshBasicMaterial has no roughness', 'invisible', 'PointLight', 'Points']) {+ assert.match(text, new RegExp(expected), expected);+ }+});++test('a shader material and a skinned mesh without bones throw errors that name the object and the fix', () => {+ const shader = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.ShaderMaterial());+ shader.name = 'glow';+ assert.throws(() => fromThreeObject(shader), /Mesh "glow" material "ShaderMaterial" is a ShaderMaterial.*MeshStandardMaterial/);+ const skinned = new THREE.SkinnedMesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial());+ skinned.name = 'hero';+ assert.throws(() => fromThreeObject(skinned), /SkinnedMesh "hero" is a SkinnedMesh without skeleton\.bones/);+ const skipped = fromThreeObject(new THREE.Group().add(shader, skinned), { skipUnsupported: true });+ assert.equal(skipped.parts.length, 0);+ assert.equal(skipped.warnings.length, 2);+});++test('limits are bounded and errors say what to pass', () => {+ const instanced = new THREE.InstancedMesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial(), 20);+ assert.throws(() => fromThreeObject(instanced, { maxParts: 10 }), /Raise maxParts/);+ assert.throws(() => fromThreeObject(new THREE.Mesh(new THREE.SphereGeometry(1, 16, 16)), { maxVertices: 50 }), /above the limit of 50/);+ assert.throws(() => fromThreeObject(instanced, { maxParts: 1e9 }), /whole number from 1 to 100000/);+ assert.throws(() => fromThreeObject(instanced, { maxPart: 5 }), /Unknown option "maxPart"/);+ assert.throws(() => fromThreeObject({}), /needs a three\.js Object3D/);+ assert.throws(() => toThreeObject([], THREE), /nonempty array of 67js parts/);+ assert.throws(() => toThreeObject([{ name: 'a' }], THREE), /parts\[0\] "a" needs geometry\.positions/);+ assert.throws(() => toThreeObject(fromThreeObject(buildSourceGroup()).parts, {}), /needs the three\.js namespace.*Group/);+ const { parts } = fromThreeObject(buildSourceGroup());+ assert.throws(() => toThreeObject(parts, THREE, { maxParts: 2 }), /4 parts is above the limit of 2/);+ assert.throws(() => toThreeObject([{ ...parts[0], matrix: [1] }], THREE), /matrix of 16 finite numbers/);+});