3D engine that AI agents drive
Add a three.js mapping guide and an optional three-compat addon (#986)
Nguyen Xuan An8c31eeead046
diff --git a/changes/986-three-style-api.md b/changes/986-three-style-api.mdnew file mode 100644index 00000000..8f7de323--- /dev/null+++ b/changes/986-three-style-api.md@@ -0,0 +1 @@+- The optional `@codepawlhq/67js-three-compat` addon accepts the common three.js names and builds 67js parts from them, and "If you know three.js" maps each three.js idiom to the 67js call (#986)diff --git a/changes/986-three-style-api.size.md b/changes/986-three-style-api.size.mdnew file mode 100644index 00000000..7a177f4f--- /dev/null+++ b/changes/986-three-style-api.size.md@@ -0,0 +1 @@+- three-compat: a new optional addon of 28,962 bytes of source (8,110 bytes gzip) that no core bundle includes; the core bundles are unchanged.diff --git a/docs/learn/if-you-know-three-js.md b/docs/learn/if-you-know-three-js.mdnew file mode 100644index 00000000..b84ed59f--- /dev/null+++ b/docs/learn/if-you-know-three-js.md@@ -0,0 +1,123 @@+# If you know three.js++67js does not copy the three.js API, but every common three.js idea has a 67js call. This page maps one to the other. A test checks that each 67js name below exists, so the page cannot drift from the code.++The main difference: three.js keeps a tree of objects that you change. 67js keeps a flat list of parts, which are plain objects with a `name`, a `geometry`, a 16 number `matrix` and a `material`. You change the list and call `renderer.updateParts(parts)`, then draw with `renderer.render(frame)`. The camera and the lights are not objects in the scene. They are fields of the frame and of the `environment` option.++If you would rather write three.js-shaped code, the optional addon `packages/three-compat` accepts the common names and builds the 67js parts for you. It is at the end of this page.++## Scene, objects and meshes++| three.js | 67js |+| --- | --- |+| `new THREE.Scene()` | A `parts` array: `const parts = []`. |+| `new THREE.Group()` | A shared matrix. Multiply it into each child matrix, or use `createSceneGraph()`, which keeps named nodes with a parent and retained world matrices. |+| `new THREE.Mesh(geometry, material)` | A part `{ name, geometry, matrix, material }`. `name` must be unique. |+| `scene.add(mesh)` | `parts.push(part)`, then `new Renderer67(canvas, parts)`. |+| `mesh.position.set(x, y, z)` | The last four numbers of `part.matrix`: `matrix[12]`, `matrix[13]`, `matrix[14]`. |+| `mesh.rotation`, `mesh.scale` | The other numbers of `part.matrix`, which is column-major. |+| Change a mesh after the first frame | Change the part, then call `renderer.updateParts(parts)`. |++## Geometry++| three.js | 67js |+| --- | --- |+| `new THREE.BoxGeometry(w, h, d)` | `box()` is a cube of side 1 with rounded edges. Scale it in the matrix, and use `box(0)` for sharp edges. |+| `new THREE.SphereGeometry(radius, widthSegments, heightSegments)` | `sphere(segments, rings)` has radius 1. Scale it in the matrix. |+| `new THREE.CylinderGeometry(r, r, height, segments)` | `cylinder(segments)` has radius 1 and height 1. |+| `new THREE.TorusGeometry(radius, tube)` | `torus(tubeRadius)` has a ring radius of 1. `tubeRadius` is `tube / radius`. |+| `new THREE.PlaneGeometry(w, h)` | `box(0)` scaled flat. |+| `new THREE.ConeGeometry()` | `createModel()` from `67js/addons/model`. |+| `new THREE.BufferGeometry()` | An object with `positions`, `normals` and `indices`. See [Parts and geometry](#parts-and-geometry). |++## Materials++| three.js | 67js |+| --- | --- |+| `new THREE.MeshStandardMaterial({ color, metalness, roughness })` | `material: { color, metallic, roughness }`. `color` is three linear numbers from 0 to 1, not a hex number. |+| `emissive` and `emissiveIntensity` | `material.emission` and `material.emissiveColor`. |+| `map`, `normalMap` | `material.map` and `material.normalMap`, each `{ image, colorSpace }`. |+| `transparent` and `opacity` | `material.alphaMode` set to `'blend'`, and `material.opacity`. |+| `alphaTest` | `material.alphaMode` set to `'mask'`, and `material.alphaCutoff`. |+| `side: THREE.DoubleSide` | `material.doubleSided` set to `true`. |+| `new THREE.MeshPhysicalMaterial({ clearcoat, transmission, ior })` | The same `material` with `material.clearcoat`, `material.transmission` and `material.ior`. The fields are listed in `docs/material-maps.md` in the repository. |+| `ShaderMaterial` | None. 67js has no custom shaders. |++## Cameras++The camera is a frame passed to `renderer.render(frame)`.++| three.js | 67js |+| --- | --- |+| `new THREE.PerspectiveCamera(fov, aspect, near, far)` | `renderer.render({ eye, target, fov, near, far })`. `frame.fov` is the vertical angle in degrees. The aspect comes from the canvas. |+| `new THREE.OrthographicCamera(...)` | `frame.projection` set to `'orthographic'`, and `frame.orthographicHeight`. |+| `camera.position.set(x, y, z)` | `frame.eye`. |+| `camera.lookAt(x, y, z)` | `frame.target`. |+| `camera.up` | `frame.up`. |+| `renderer.setSize(w, h)` and a window resize handler | Size the canvas in CSS, then call `renderer.resize()`. |+| `camera.updateProjectionMatrix()` | Not needed. `renderer.render()` reads the frame every time. |++## Lights++The lights are fields of the `environment` option of `Renderer67`, or of `frame.environment` for one frame. The studio rig (a key light, two fills and ambient light) is on by default.++| three.js | 67js |+| --- | --- |+| `new THREE.AmbientLight(color, intensity)` | `environment.ambientIntensity`. |+| `new THREE.HemisphereLight()` | `environment.ambientIntensity`. |+| `new THREE.DirectionalLight(color, intensity)` | `environment.lightDirection`, `environment.keyIntensity` and `environment.keyColor`. It casts shadows. |+| `new THREE.PointLight(color, intensity, distance)` | An entry of `environment.pointLights`: `{ position, color, intensity, range }`. At most 16. |+| `new THREE.SpotLight(...)` | An entry of `environment.spotLights`: `{ position, direction, angle, penumbra, intensity }`. At most 8. |+| `new THREE.RectAreaLight(...)` | An entry of `environment.areaLights`: `{ position, direction, width, height, intensity }`. At most 7. |+| `light.castShadow = true` | `castShadow: true` on a point, spot or area light. The key light always casts. |+| `scene.background` | `environment.skyTop` and `environment.skyBottom`. |+| `scene.fog` | `environment.fogColor` and `environment.fogDensity`. |++Light units differ, so a copied intensity is not the same brightness. Tune by eye. The [lighting contract](/lighting.md) lists the fields.++## Loaders++| three.js | 67js |+| --- | --- |+| `new GLTFLoader().load(url, onLoad)` | `loadGltf(url)` from `67js/addons/gltf`. It returns an asset, and `asset.parts` are ordinary parts. |+| `gltf.scene` | `asset.parts`. |+| `gltf.animations` and `new THREE.AnimationMixer(scene)` | `createAnimationMixer(parts)`, or `createAnimationPlayer(clip, parts)`. |+| `DRACOLoader`, `KTX2Loader` | The `decoders` option of `loadGltf`. See [Import and export models](#import-and-export-models). |+| `new THREE.TextureLoader().load(url)` | Load an `Image` yourself and put it in `material.map`. |+| `RGBELoader` and `scene.environment` | `createEnvironmentMap()` and the `environment.map` option. |++## The render loop++| three.js | 67js |+| --- | --- |+| `renderer.setAnimationLoop(fn)` | Call `requestAnimationFrame` yourself, change the parts, call `renderer.updateParts(parts)` and `renderer.render(frame)`. |+| `renderer.render(scene, camera)` | `renderer.render(frame)`. |+| `new THREE.Clock()` and `clock.getDelta()` | `performance.now()`. For motion that must repeat exactly, pass absolute time to `sampleAnimationClip()`. |+| `renderer.setPixelRatio(ratio)` | The `pixelRatio` option of `Renderer67`. |+| `renderer.dispose()` | `renderer.dispose()`. |+| `new THREE.WebGLRenderer({ antialias: true })` | `new Renderer67(canvas, parts, { samples: 4 })`. |++## Controls and render targets++| three.js | 67js |+| --- | --- |+| `new OrbitControls(camera, canvas)` | Keep a yaw, a pitch and a distance, then compute `frame.eye` from them on `pointermove` and `wheel`. [Cameras and framing](#cameras-and-framing) has the code. `cameraView()` and `fitPerspectiveDistance()` frame a subject. |+| `new THREE.WebGLRenderTarget(w, h)` | None. `Renderer67` draws to its canvas. Read the picture with `canvas.toBlob()`. For a PNG job in an agent, use the `scene_render_submit` tool. |+| `EffectComposer` and passes | `frame.effects`, built with `resolveEffects()`. |+| `renderer.shadowMap.enabled` | Shadows are always on. A part leaves them with `castShadow: false`. |++## Names the addon refuses++`packages/three-compat` is an optional addon that accepts the common three.js names and builds 67js parts, materials, cameras and lights from them. It has no import of `three` and no dependency on the core: you pass it the 67js exports.++```js+import * as core from '67js';+import { loadGltf } from '67js/addons/gltf';+import { createThreeCompat } from '@codepawlhq/67js-three-compat';++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.++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/learn/introduction.md b/docs/learn/introduction.mdindex 77de17f6..5de951c7 100644--- a/docs/learn/introduction.md+++ b/docs/learn/introduction.md@@ -65,7 +65,7 @@ To move something, change the part and call `renderer.updateParts(parts)`. Then## What 67js is not-67js does not copy the three.js API. Code for three.js does not run in 67js without changes. 67js also has no mouse editor like Blender. You build scenes in code, or an AI agent builds them through the MCP server.+67js does not copy the three.js API. If you know three.js, [If you know three.js](#if-you-know-three-js) maps its common calls to 67js, and the optional `three-compat` addon builds 67js parts from the common three.js names. It supports a subset, so code that uses other three.js names needs changes. 67js also has no mouse editor like Blender. You build scenes in code, or an AI agent builds them through the MCP server.## How these docs are organizeddiff --git a/packages/three-compat/README.md b/packages/three-compat/README.mdnew file mode 100644index 00000000..a61d033d--- /dev/null+++ b/packages/three-compat/README.md@@ -0,0 +1,37 @@+# @codepawlhq/67js-three-compat++Optional addon that lets code written from memory in the three.js style build a 67js scene. It imports neither `three` nor `67js`: you pass the 67js exports to it, so the core gains no dependency and this package gains none. It is not part of the core `67js` archive.++```js+import * as core from '@codepawlhq/67js';+import { loadGltf } from '@codepawlhq/67js/addons/gltf';+import { createThreeCompat } from '@codepawlhq/67js-three-compat';++const THREE = createThreeCompat({ ...core, loadGltf });++const scene = new THREE.Scene();+const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+camera.position.set(3, 2, 4);+camera.lookAt(0, 0.5, 0);+const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x2f9e6b, roughness: 0.5 }));+cube.position.y = 0.5;+scene.add(cube, new THREE.DirectionalLight(0xffffff, 3), new THREE.AmbientLight(0xffffff, 0.4));++const renderer = new THREE.WebGLRenderer({ canvas: document.querySelector('#scene') });+renderer.setAnimationLoop(() => {+ cube.rotation.y += 0.01;+ renderer.render(scene, camera);+});+```++## What it accepts++`Scene`, `Group`, `Object3D`, `Mesh`, `BoxGeometry`, `PlaneGeometry`, `SphereGeometry`, `CylinderGeometry` (equal radii), `TorusGeometry`, `MeshStandardMaterial`, `MeshPhysicalMaterial`, `Texture`, `CanvasTexture`, `PerspectiveCamera`, `OrthographicCamera`, `AmbientLight`, `HemisphereLight`, `DirectionalLight`, `PointLight`, `SpotLight`, `RectAreaLight`, `GLTFLoader` (`load` and `loadAsync`), `OrbitControls`, `WebGLRenderer` (`render`, `setSize`, `setPixelRatio`, `setAnimationLoop`, `dispose`), `Clock`, `Color`, `Vector2`, `Vector3` and `Euler` (order XYZ).++Light intensities pass through unchanged: three.js and 67js use different units, so tune them by eye. A scene with at least one light switches the studio rig off, as in three.js; a scene with none keeps it. `AmbientLight` and `HemisphereLight` use their intensity only, not their colour.++## What it refuses++Any other capitalised name, such as `MeshBasicMaterial`, `ShaderMaterial`, `WebGLRenderTarget` or `Fog`, throws an error that names the three.js call and the 67js call to use instead. The full mapping is in [If you know three.js](../../docs/learn/if-you-know-three-js.md).++`createThreeCompat(core).collectScene(scene, camera)` returns `{ parts, environment, frame }` without a renderer, which is what the tests use.diff --git a/packages/three-compat/index.mjs b/packages/three-compat/index.mjsnew file mode 100644index 00000000..aa520ef0--- /dev/null+++ b/packages/three-compat/index.mjs@@ -0,0 +1,784 @@+// three.js-shaped names that build 67js parts, materials, cameras and lights.+// It imports neither three.js nor 67js: pass the 67js exports you have to createThreeCompat(core).+// import * as core from '@codepawlhq/67js';+// import { loadGltf } from '@codepawlhq/67js/addons/gltf';+// const THREE = createThreeCompat({ ...core, loadGltf });+// Names it does not support throw an error that names the 67js call to use instead.++const DEGREES_TO_RADIANS = Math.PI / 180;+const WHITE_HEX = 0xffffff;+const FRONT_SIDE = 0;+const BACK_SIDE = 1;+const DOUBLE_SIDE = 2;+const PLANE_THICKNESS = 0.002;++const GUIDE = 'docs/learn/if-you-know-three-js.md';++const UNSUPPORTED = {+ MeshBasicMaterial: 'Use MeshStandardMaterial with emissive and emissiveIntensity (67js: material { color, emission }).',+ MeshLambertMaterial: 'Use MeshStandardMaterial (67js: material { color, metallic: 0, roughness }).',+ MeshPhongMaterial: 'Use MeshStandardMaterial (67js: material { color, metallic, roughness }).',+ MeshNormalMaterial: 'Use MeshStandardMaterial (67js: material { color, metallic, roughness }).',+ ShaderMaterial: '67js has no custom shaders. Use the material fields of materials-and-color (67js: part.material).',+ RawShaderMaterial: '67js has no custom shaders. Use the material fields of materials-and-color (67js: part.material).',+ ConeGeometry: 'Model a cone with createModel() from 67js/addons/model, or use CylinderGeometry with equal radii.',+ CapsuleGeometry: 'Model it with createModel() from 67js/addons/model, or combine CylinderGeometry and SphereGeometry.',+ CircleGeometry: 'Use CylinderGeometry with a small height (67js: cylinder()).',+ IcosahedronGeometry: 'Use SphereGeometry (67js: sphere()).',+ BufferGeometry: 'A part takes a geometry object { positions, normals, indices } (67js: geometry in a part). Build one with box(), sphere(), cylinder(), torus() or createModel().',+ InstancedMesh: 'Give parts the same geometry object: the renderer batches them (67js: Renderer67 with batching: true).',+ SkinnedMesh: 'Load a rigged GLB with GLTFLoader, then drive it with createSkinPose() and updateSkinPose().',+ AnimationMixer: 'Use createAnimationMixer(parts) from 67js.',+ Points: '67js draws triangle parts only. Use small SphereGeometry parts, or the spume addon for particles.',+ Line: '67js draws triangle parts only. Use thin CylinderGeometry parts.',+ LineSegments: '67js draws triangle parts only. Use thin CylinderGeometry parts.',+ Sprite: '67js draws triangle parts only. Use PlaneGeometry with a map.',+ WebGLRenderTarget: 'Renderer67 draws to its canvas. Read it with canvas.toBlob(), or render a PNG with the scene_render_submit tool.',+ EffectComposer: 'Post effects are frame fields: frame.effects with EFFECT_PRESETS and resolveEffects().',+ Fog: 'Set environment { fogColor, fogDensity } on Renderer67.',+ FogExp2: 'Set environment { fogColor, fogDensity } on Renderer67.',+ TextureLoader: 'Load the image yourself and pass new Texture(image) as the map (67js: material.map = { image, colorSpace: "srgb" }).',+ CubeTextureLoader: 'Use createEnvironmentMap() from 67js for image based light.',+ RGBELoader: 'Use createEnvironmentMap() from 67js for image based light.',+ DRACOLoader: 'loadGltf() from 67js/addons/gltf takes decoders in its options.',+ FBXLoader: 'Convert the file to GLB and use loadGltf() from 67js/addons/gltf.',+ OBJLoader: 'Convert the file to GLB and use loadGltf() from 67js/addons/gltf.',+ TransformControls: '67js has no mouse editor. Change part.matrix and call updateParts().',+ DragControls: '67js has no mouse editor. Change part.matrix and call updateParts().',+ TrackballControls: 'Use OrbitControls from this addon, or move frame.eye yourself.',+ FlyControls: 'Use OrbitControls from this addon, or move frame.eye yourself.',+};++const UNSUPPORTED_OPTIONS = {+ MeshStandardMaterial: {+ aoMap: 'Use the occlusionMap field of a 67js material (materials-and-color).',+ envMap: 'Use createEnvironmentMap() and the Renderer67 environment.map option.',+ roughnessMap: 'Use the roughness field, or a glTF with a metallicRoughness map.',+ metalnessMap: 'Use the metalness field, or a glTF with a metallicRoughness map.',+ bumpMap: 'Use normalMap.',+ displacementMap: 'Model the relief in the geometry.',+ wireframe: '67js has no wireframe view.',+ flatShading: 'Use a box() or a geometry with split vertices.',+ vertexColors: 'Give each part its own color.',+ },+};++class CompatError extends Error {+ constructor(message) {+ super(`${message} See ${GUIDE}.`);+ this.name = 'ThreeCompatError';+ }+}++function unsupported(name, replacement) {+ return new CompatError(`THREE.${name} is not supported by 67js three-compat. ${replacement}`);+}++function srgbToLinear(channel) {+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;+}++function hexToLinear(hex) {+ return [(hex >> 16) & 255, (hex >> 8) & 255, hex & 255].map(value => srgbToLinear(value / 255));+}++class Color {+ constructor(first = WHITE_HEX, green, blue) {+ this.r = 1;+ this.g = 1;+ this.b = 1;+ this.set(first, green, blue);+ }++ set(first, green, blue) {+ if (typeof first === 'number' && green === undefined) {+ [this.r, this.g, this.b] = hexToLinear(first);+ } else if (typeof first === 'string') {+ const digits = first.replace('#', '');+ const expanded = digits.length === 3 ? [...digits].map(digit => digit + digit).join('') : digits;+ if (!/^[0-9a-fA-F]{6}$/.test(expanded)) {+ throw new CompatError(`Color "${first}" is not a hex string. Pass 0xRRGGBB, "#rrggbb", or linear red, green and blue numbers (67js: material.color = [r, g, b]).`);+ }+ [this.r, this.g, this.b] = hexToLinear(parseInt(expanded, 16));+ } else if (first instanceof Color) {+ [this.r, this.g, this.b] = [first.r, first.g, first.b];+ } else if (typeof first === 'number') {+ [this.r, this.g, this.b] = [first, green, blue];+ }+ return this;+ }++ setHex(hex) {+ return this.set(hex);+ }++ setRGB(red, green, blue) {+ [this.r, this.g, this.b] = [red, green, blue];+ return this;+ }++ copy(other) {+ return this.set(other);+ }++ clone() {+ return new Color(this);+ }++ toArray() {+ return [this.r, this.g, this.b];+ }+}++function asColor(value) {+ return value instanceof Color ? value : new Color(value);+}++class Vector3 {+ constructor(x = 0, y = 0, z = 0) {+ this.x = x;+ this.y = y;+ this.z = z;+ }++ set(x, y, z) {+ [this.x, this.y, this.z] = [x, y, z];+ return this;+ }++ setScalar(value) {+ return this.set(value, value, value);+ }++ copy(other) {+ return this.set(other.x, other.y, other.z);+ }++ clone() {+ return new Vector3(this.x, this.y, this.z);+ }++ toArray() {+ return [this.x, this.y, this.z];+ }+}++class Euler extends Vector3 {+ constructor(x = 0, y = 0, z = 0, order = 'XYZ') {+ super(x, y, z);+ if (order !== 'XYZ') throw new CompatError(`Euler order "${order}" is not supported. Use XYZ, or set part.matrix yourself.`);+ this.order = order;+ }+}++class Vector2 {+ constructor(x = 0, y = 0) {+ this.x = x;+ this.y = y;+ }++ set(x, y) {+ [this.x, this.y] = [x, y];+ return this;+ }+}++// Column-major 4x4 products, the layout of part.matrix.+function multiply(left, right) {+ const result = new Float32Array(16);+ for (let column = 0; column < 4; column++) {+ for (let row = 0; row < 4; row++) {+ let sum = 0;+ for (let step = 0; step < 4; step++) sum += left[step * 4 + row] * right[column * 4 + step];+ result[column * 4 + row] = sum;+ }+ }+ return result;+}++function composeMatrix(position, rotation, scale) {+ const [sinX, cosX] = [Math.sin(rotation.x), Math.cos(rotation.x)];+ const [sinY, cosY] = [Math.sin(rotation.y), Math.cos(rotation.y)];+ const [sinZ, cosZ] = [Math.sin(rotation.z), Math.cos(rotation.z)];+ // R = Rx * Ry * Rz, three.js order XYZ.+ const xAxis = [cosY * cosZ, cosX * sinZ + sinX * sinY * cosZ, sinX * sinZ - cosX * sinY * cosZ];+ const yAxis = [-cosY * sinZ, cosX * cosZ - sinX * sinY * sinZ, sinX * cosZ + cosX * sinY * sinZ];+ const zAxis = [sinY, -sinX * cosY, cosX * cosY];+ return new Float32Array([+ ...xAxis.map(value => value * scale.x), 0,+ ...yAxis.map(value => value * scale.y), 0,+ ...zAxis.map(value => value * scale.z), 0,+ position.x, position.y, position.z, 1,+ ]);+}++function transformPoint(matrix, x, y, z) {+ return [+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14],+ ];+}++function subtract(first, second) {+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+}++class Object3D {+ constructor() {+ this.name = '';+ this.visible = true;+ this.children = [];+ this.parent = null;+ this.position = new Vector3();+ this.rotation = new Euler();+ this.scale = new Vector3(1, 1, 1);+ this.up = new Vector3(0, 1, 0);+ this.lookAtPoint = null;+ }++ add(...objects) {+ for (const object of objects) {+ if (!(object instanceof Object3D)) throw new CompatError('add() takes objects made by this addon (Group, Mesh, lights, cameras).');+ object.parent?.remove(object);+ object.parent = this;+ this.children.push(object);+ }+ return this;+ }++ remove(...objects) {+ for (const object of objects) {+ const index = this.children.indexOf(object);+ if (index >= 0) {+ this.children.splice(index, 1);+ object.parent = null;+ }+ }+ return this;+ }++ lookAt(x, y, z) {+ this.lookAtPoint = x instanceof Vector3 ? x.toArray() : [x, y, z];+ return this;+ }++ localMatrix() {+ return composeMatrix(this.position, this.rotation, this.scale);+ }++ worldMatrix() {+ const local = this.localMatrix();+ return this.parent ? multiply(this.parent.worldMatrix(), local) : local;+ }++ worldPosition() {+ return transformPoint(this.worldMatrix(), 0, 0, 0);+ }+}++class Group extends Object3D {}++class Scene extends Object3D {+ constructor() {+ super();+ this.background = null;+ }+}++const geometrySymbol = Symbol('geometry');++export function createThreeCompat(core) {+ for (const name of ['Renderer67', 'box', 'sphere', 'cylinder', 'torus']) {+ if (typeof core?.[name] !== 'function') {+ throw new TypeError(`createThreeCompat needs the 67js export ${name}. Pass { ...core } from import * as core from '@codepawlhq/67js'.`);+ }+ }+ const shapeCache = new Map();++ function shared(key, build) {+ if (!shapeCache.has(key)) shapeCache.set(key, build());+ return shapeCache.get(key);+ }++ class BoxGeometry {+ constructor(width = 1, height = 1, depth = 1) {+ this[geometrySymbol] = { build: () => shared('box', () => core.box(0)), scale: [width, height, depth] };+ }+ }++ class PlaneGeometry {+ constructor(width = 1, height = 1) {+ this[geometrySymbol] = { build: () => shared('plane', () => core.box(0)), scale: [width, height, PLANE_THICKNESS] };+ }+ }++ class SphereGeometry {+ constructor(radius = 1, widthSegments = 32, heightSegments = 16) {+ this[geometrySymbol] = {+ build: () => shared(`sphere:${widthSegments}:${heightSegments}`, () => core.sphere(widthSegments, heightSegments)),+ scale: [radius, radius, radius],+ };+ }+ }++ class CylinderGeometry {+ constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32) {+ if (radiusTop !== radiusBottom) {+ throw unsupported('CylinderGeometry with different radii', 'Use equal radii, or model a cone with createModel() from 67js/addons/model.');+ }+ this[geometrySymbol] = {+ build: () => shared(`cylinder:${radialSegments}`, () => core.cylinder(radialSegments)),+ scale: [radiusTop, height, radiusTop],+ };+ }+ }++ class TorusGeometry {+ constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48) {+ const tubeRatio = tube / radius;+ this[geometrySymbol] = {+ build: () => shared(`torus:${tubeRatio}:${tubularSegments}:${radialSegments}`, () => core.torus(tubeRatio, tubularSegments, radialSegments)),+ scale: [radius, radius, radius],+ };+ }+ }++ class Texture {+ constructor(image, colorSpace = 'srgb') {+ this.image = image;+ this.colorSpace = colorSpace;+ }+ }++ class CanvasTexture extends Texture {}++ function textureDescriptor(texture, colorSpace) {+ if (!(texture instanceof Texture)) {+ throw new CompatError('A map must be a THREE.Texture or THREE.CanvasTexture made by this addon (67js: material.map = { image, colorSpace }).');+ }+ return { image: texture.image, colorSpace };+ }++ class MeshStandardMaterial {+ constructor(parameters = {}) {+ const rejected = UNSUPPORTED_OPTIONS[new.target.name === 'MeshPhysicalMaterial' ? 'MeshStandardMaterial' : new.target.name] ?? {};+ for (const option of Object.keys(parameters)) {+ if (rejected[option]) throw unsupported(`${new.target.name} option "${option}"`, rejected[option]);+ }+ this.color = asColor(parameters.color ?? WHITE_HEX);+ this.metalness = parameters.metalness ?? 0;+ this.roughness = parameters.roughness ?? 1;+ this.emissive = asColor(parameters.emissive ?? 0x000000);+ this.emissiveIntensity = parameters.emissiveIntensity ?? 1;+ this.map = parameters.map ?? null;+ this.normalMap = parameters.normalMap ?? null;+ this.normalScale = parameters.normalScale ?? new Vector2(1, 1);+ this.opacity = parameters.opacity ?? 1;+ this.transparent = parameters.transparent ?? false;+ this.alphaTest = parameters.alphaTest ?? 0;+ this.side = parameters.side ?? FRONT_SIDE;+ }++ toMaterial() {+ if (this.side === BACK_SIDE) throw unsupported('BackSide', 'Use DoubleSide (67js: material.doubleSided = true).');+ const isEmissive = this.emissive.r + this.emissive.g + this.emissive.b > 0;+ const material = {+ color: this.color.toArray(),+ metallic: this.metalness,+ roughness: this.roughness,+ };+ if (isEmissive) {+ material.emission = this.emissiveIntensity;+ material.emissiveColor = this.emissive.toArray();+ }+ if (this.map) material.map = textureDescriptor(this.map, 'srgb');+ if (this.normalMap) {+ material.normalMap = textureDescriptor(this.normalMap, 'linear');+ material.normalScale = this.normalScale.x;+ }+ if (this.alphaTest > 0) {+ material.alphaMode = 'mask';+ material.alphaCutoff = this.alphaTest;+ } else if (this.transparent) {+ material.alphaMode = 'blend';+ }+ if (this.opacity !== 1) material.opacity = this.opacity;+ if (this.side === DOUBLE_SIDE) material.doubleSided = true;+ return material;+ }+ }++ const PHYSICAL_FIELDS = ['clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'specularIntensity', 'iridescence', 'sheenRoughness', 'anisotropy'];+ const PHYSICAL_FIELD_NAMES = { specularIntensity: 'specular' };++ class MeshPhysicalMaterial extends MeshStandardMaterial {+ constructor(parameters = {}) {+ super(parameters);+ for (const field of PHYSICAL_FIELDS) this[field] = parameters[field];+ }++ toMaterial() {+ const material = super.toMaterial();+ for (const field of PHYSICAL_FIELDS) {+ if (this[field] !== undefined) material[PHYSICAL_FIELD_NAMES[field] ?? field] = this[field];+ }+ return material;+ }+ }++ class Mesh extends Object3D {+ constructor(geometry, material = new MeshStandardMaterial()) {+ super();+ if (!geometry?.[geometrySymbol]) {+ throw new CompatError('Mesh needs BoxGeometry, SphereGeometry, CylinderGeometry, TorusGeometry or PlaneGeometry (67js: box(), sphere(), cylinder(), torus()).');+ }+ if (!(material instanceof MeshStandardMaterial)) {+ throw new CompatError('Mesh needs MeshStandardMaterial or MeshPhysicalMaterial (67js: a material { color, metallic, roughness }).');+ }+ this.geometry = geometry;+ this.material = material;+ }+ }++ class PerspectiveCamera extends Object3D {+ constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {+ super();+ Object.assign(this, { fov, aspect, near, far, isPerspectiveCamera: true });+ }++ updateProjectionMatrix() {}+ }++ class OrthographicCamera extends Object3D {+ constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {+ super();+ Object.assign(this, { left, right, top, bottom, near, far, zoom: 1, isOrthographicCamera: true });+ }++ updateProjectionMatrix() {}+ }++ class Light extends Object3D {+ constructor(color = WHITE_HEX, intensity = 1) {+ super();+ this.color = asColor(color);+ this.intensity = intensity;+ this.target = new Object3D();+ }++ targetPoint() {+ return this.lookAtPoint ?? this.target.worldPosition();+ }+ }++ class AmbientLight extends Light {}+ class HemisphereLight extends Light {+ constructor(skyColor = WHITE_HEX, groundColor = 0x000000, intensity = 1) {+ super(skyColor, intensity);+ }+ }+ class DirectionalLight extends Light {}+ class PointLight extends Light {+ constructor(color, intensity, distance = 0) {+ super(color, intensity);+ this.distance = distance;+ }+ }+ class SpotLight extends Light {+ constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0) {+ super(color, intensity);+ Object.assign(this, { distance, angle, penumbra });+ }+ }+ class RectAreaLight extends Light {+ constructor(color, intensity, width = 10, height = 10) {+ super(color, intensity);+ Object.assign(this, { width, height });+ }+ }++ function traverse(object, visit) {+ if (!object.visible) return;+ visit(object);+ for (const child of object.children) traverse(child, visit);+ }++ function colorOrUndefined(color) {+ return color.r === 1 && color.g === 1 && color.b === 1 ? undefined : color.toArray();+ }++ function withoutUndefined(fields) {+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));+ }++ function environmentFor(lights, scene) {+ const environment = {};+ const background = scene.background instanceof Color ? scene.background.toArray() : null;+ if (background) {+ environment.skyTop = background;+ environment.skyBottom = background;+ }+ if (lights.length === 0) return environment;+ // A three.js scene is dark until it has lights, so the studio rig is switched off once the scene brings its own.+ Object.assign(environment, { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0, pointLights: [], spotLights: [], areaLights: [] });+ for (const light of lights) {+ const position = light.worldPosition();+ if (light instanceof AmbientLight || light instanceof HemisphereLight) {+ environment.ambientIntensity += light.intensity;+ } else if (light instanceof DirectionalLight) {+ const direction = subtract(position, light.targetPoint());+ Object.assign(environment, withoutUndefined({ keyIntensity: light.intensity, lightDirection: direction, keyColor: colorOrUndefined(light.color) }));+ } else if (light instanceof PointLight) {+ environment.pointLights.push(withoutUndefined({+ position, color: light.color.toArray(), intensity: light.intensity, range: light.distance > 0 ? light.distance : undefined,+ }));+ } else if (light instanceof SpotLight) {+ environment.spotLights.push(withoutUndefined({+ position,+ direction: subtract(light.targetPoint(), position),+ angle: light.angle,+ penumbra: light.penumbra,+ color: light.color.toArray(),+ intensity: light.intensity,+ range: light.distance > 0 ? light.distance : undefined,+ }));+ } else if (light instanceof RectAreaLight) {+ environment.areaLights.push({+ position, direction: subtract(light.targetPoint(), position), width: light.width, height: light.height,+ color: light.color.toArray(), intensity: light.intensity,+ });+ }+ }+ return environment;+ }++ function cameraFrame(camera) {+ if (!(camera instanceof PerspectiveCamera || camera instanceof OrthographicCamera)) {+ throw new CompatError('render() needs a PerspectiveCamera or OrthographicCamera from this addon (67js: renderer.render({ eye, target, fov })).');+ }+ const matrix = camera.worldMatrix();+ const eye = transformPoint(matrix, 0, 0, 0);+ const target = camera.lookAtPoint ?? transformPoint(matrix, 0, 0, -1);+ const frame = { eye, target, up: camera.up.toArray(), near: camera.near, far: camera.far };+ if (camera instanceof PerspectiveCamera) {+ frame.fov = camera.fov;+ } else {+ frame.projection = 'orthographic';+ frame.orthographicHeight = (camera.top - camera.bottom) / camera.zoom;+ }+ return frame;+ }++ /** Walk a scene and return what Renderer67 draws: the parts, the environment of its lights and a frame from the camera. */+ function collectScene(scene, camera) {+ if (!(scene instanceof Scene)) throw new CompatError('render() needs a THREE.Scene from this addon.');+ const parts = [];+ const lights = [];+ traverse(scene, object => {+ if (object instanceof Light) {+ lights.push(object);+ } else if (object instanceof Mesh) {+ const { build, scale } = object.geometry[geometrySymbol];+ const sizing = composeMatrix({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }, { x: scale[0], y: scale[1], z: scale[2] });+ parts.push({+ name: `${object.name || 'mesh'}-${parts.length}`,+ geometry: build(),+ matrix: multiply(object.worldMatrix(), sizing),+ material: object.material.toMaterial(),+ });+ } else if (object.loadedParts) {+ const world = object.worldMatrix();+ for (const loaded of object.loadedParts) {+ parts.push({ ...loaded, name: `${object.name || 'gltf'}-${loaded.name}`, matrix: multiply(world, loaded.matrix) });+ }+ }+ });+ return { parts, environment: environmentFor(lights, scene), frame: cameraFrame(camera) };+ }++ class WebGLRenderer {+ constructor(parameters = {}) {+ if (!parameters.canvas) throw new CompatError('WebGLRenderer needs { canvas } (67js: new Renderer67(canvas, parts)).');+ this.domElement = parameters.canvas;+ this.antialias = parameters.antialias ?? true;+ this.pixelRatio = 1.5;+ this.shadowMap = { enabled: true, type: undefined };+ this.clearColor = null;+ this.renderer67 = null;+ this.structure = null;+ this.geometries = new Map();+ this.loopHandle = null;+ }++ setSize(width, height) {+ this.domElement.style.width = `${width}px`;+ this.domElement.style.height = `${height}px`;+ this.renderer67?.resize();+ }++ setPixelRatio(ratio) {+ this.pixelRatio = ratio;+ }++ setClearColor(color) {+ this.clearColor = asColor(color);+ }++ render(scene, camera) {+ const { parts, environment, frame } = collectScene(scene, camera);+ if (!scene.background && this.clearColor) {+ environment.skyTop = this.clearColor.toArray();+ environment.skyBottom = this.clearColor.toArray();+ }+ const key = this.structureKey(parts);+ if (!this.renderer67 || key !== this.structure) {+ this.renderer67?.dispose();+ this.renderer67 = new core.Renderer67(this.domElement, parts, {+ ground: false, samples: this.antialias ? 4 : 1, pixelRatio: this.pixelRatio, environment,+ });+ this.structure = key;+ } else {+ this.renderer67.updateParts(parts);+ }+ this.renderer67.resize();+ this.renderer67.render({ ...frame, environment });+ }++ structureKey(parts) {+ for (const part of parts) {+ if (!this.geometries.has(part.geometry)) this.geometries.set(part.geometry, this.geometries.size);+ }+ return parts.map(part => [+ part.name, this.geometries.get(part.geometry), part.material.alphaMode ?? '', part.material.doubleSided ?? '',+ part.material.map ? 'map' : '', part.material.normalMap ? 'normal' : '',+ ].join('|')).join('\n');+ }++ setAnimationLoop(callback) {+ if (this.loopHandle !== null) globalThis.cancelAnimationFrame(this.loopHandle);+ this.loopHandle = null;+ if (!callback) return;+ const step = time => {+ callback(time);+ this.loopHandle = globalThis.requestAnimationFrame(step);+ };+ this.loopHandle = globalThis.requestAnimationFrame(step);+ }++ dispose() {+ this.setAnimationLoop(null);+ this.renderer67?.dispose();+ this.renderer67 = null;+ }+ }++ class Clock {+ constructor(autoStart = true) {+ this.startTime = autoStart ? performance.now() : null;+ this.previousTime = this.startTime;+ this.elapsedTime = 0;+ }++ getDelta() {+ const now = performance.now();+ this.startTime ??= now;+ this.previousTime ??= now;+ const delta = (now - this.previousTime) / 1000;+ this.previousTime = now;+ this.elapsedTime += delta;+ return delta;+ }++ getElapsedTime() {+ this.getDelta();+ return this.elapsedTime;+ }+ }++ class OrbitControls {+ constructor(camera, domElement) {+ this.object = camera;+ this.domElement = domElement;+ this.target = new Vector3();+ this.enableDamping = false;+ this.enabled = true;+ this.onChange = null;+ const offset = subtract(camera.worldPosition(), this.target.toArray());+ this.distance = Math.hypot(...offset);+ this.yaw = Math.atan2(offset[0], offset[2]);+ this.pitch = Math.asin(offset[1] / (this.distance || 1));+ domElement.style.touchAction = 'none';+ domElement.addEventListener('pointerdown', event => domElement.setPointerCapture?.(event.pointerId));+ domElement.addEventListener('pointermove', event => {+ if (!this.enabled || !domElement.hasPointerCapture?.(event.pointerId)) return;+ this.rotate(-event.movementX * 0.01, event.movementY * 0.01);+ });+ domElement.addEventListener('wheel', event => {+ event.preventDefault();+ this.distance = Math.min(1000, Math.max(0.01, this.distance * Math.exp(event.deltaY * 0.001)));+ this.update();+ }, { passive: false });+ }++ rotate(yawChange, pitchChange) {+ this.yaw += yawChange;+ this.pitch = Math.min(1.5, Math.max(-1.5, this.pitch + pitchChange));+ this.update();+ }++ update() {+ const flat = Math.cos(this.pitch) * this.distance;+ this.object.position.set(+ this.target.x + Math.sin(this.yaw) * flat,+ this.target.y + Math.sin(this.pitch) * this.distance,+ this.target.z + Math.cos(this.yaw) * flat,+ );+ this.object.lookAt(this.target.x, this.target.y, this.target.z);+ this.onChange?.();+ return true;+ }++ dispose() {}+ }++ class GLTFLoader {+ async loadAsync(url, onProgress) {+ if (typeof core.loadGltf !== 'function') {+ throw new CompatError('GLTFLoader needs loadGltf. Pass createThreeCompat({ ...core, loadGltf }) with loadGltf from 67js/addons/gltf.');+ }+ const asset = await core.loadGltf(url);+ onProgress?.({ loaded: 1, total: 1 });+ const scene = new Group();+ scene.loadedParts = asset.parts;+ return { scene, scenes: [scene], animations: asset.animations ?? [], asset };+ }++ load(url, onLoad, onProgress, onError) {+ this.loadAsync(url, onProgress).then(onLoad, onError ?? (error => { throw error; }));+ }+ }++ const exported = {+ Color, Vector2, Vector3, Euler, Object3D, Group, Scene, Mesh, Clock,+ BoxGeometry, PlaneGeometry, SphereGeometry, CylinderGeometry, TorusGeometry,+ Texture, CanvasTexture, MeshStandardMaterial, MeshPhysicalMaterial,+ PerspectiveCamera, OrthographicCamera,+ AmbientLight, HemisphereLight, DirectionalLight, PointLight, SpotLight, RectAreaLight,+ WebGLRenderer, OrbitControls, GLTFLoader,+ FrontSide: FRONT_SIDE, BackSide: BACK_SIDE, DoubleSide: DOUBLE_SIDE,+ collectScene,+ };++ return new Proxy(exported, {+ get(target, name) {+ if (typeof name === 'string' && !(name in target)) {+ if (UNSUPPORTED[name]) throw unsupported(name, UNSUPPORTED[name]);+ if (/^[A-Z]/.test(name)) throw unsupported(name, 'It is not part of the common subset. Build the 67js part, material, camera or light directly.');+ }+ return target[name];+ },+ });+}++export const unsupportedNames = Object.freeze(Object.keys(UNSUPPORTED));diff --git a/packages/three-compat/package.json b/packages/three-compat/package.jsonnew file mode 100644index 00000000..b04b8d8f--- /dev/null+++ b/packages/three-compat/package.json@@ -0,0 +1,18 @@+{+ "name": "@codepawlhq/67js-three-compat",+ "version": "0.1.0",+ "description": "Optional three.js-shaped names that build 67js parts, materials, cameras and lights. Imports neither three nor 67js. Not part of the core archive.",+ "type": "module",+ "main": "./index.mjs",+ "exports": {+ ".": "./index.mjs"+ },+ "files": [+ "index.mjs",+ "README.md"+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19"+ }+}diff --git a/public/llms.txt b/public/llms.txtindex 40660e73..28b57897 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -75,6 +75,10 @@ Scenes are plain data with stable IDs, so an agent can edit by ID and check eachCall `scene_capabilities` for field detail. This list is generated from the server's tool registry by `scripts/generate-llms.mjs`.+## If you know three.js++Models write three.js from memory. The section "If you know three.js" of the [complete guide](https://67js.codepawl.com/guide.md) maps each common three.js idiom to the 67js call. The optional addon `@codepawlhq/67js-three-compat` (folder `packages/three-compat`) accepts the common three.js shapes (`Scene`, `Mesh`, `MeshStandardMaterial`, `PerspectiveCamera`, the light classes, `GLTFLoader`, `setAnimationLoop`) and builds 67js parts from them. It throws an error that names the 67js call when you use a name it does not support.+## Docs- [Complete plain-text guide](https://67js.codepawl.com/guide.md): renderer, parts, materials, cameras, animation, export and troubleshooting.diff --git a/scripts/generate-llms.mjs b/scripts/generate-llms.mjsindex 9135ab8e..dcd75555 100644--- a/scripts/generate-llms.mjs+++ b/scripts/generate-llms.mjs@@ -99,6 +99,10 @@ ${toolLines}Call \`scene_capabilities\` for field detail. This list is generated from the server's tool registry by \`scripts/generate-llms.mjs\`.+## If you know three.js++Models write three.js from memory. The section "If you know three.js" of the [complete guide](${page('guide.md')}) maps each common three.js idiom to the 67js call. The optional addon \`@codepawlhq/67js-three-compat\` (folder \`packages/three-compat\`) accepts the common three.js shapes (\`Scene\`, \`Mesh\`, \`MeshStandardMaterial\`, \`PerspectiveCamera\`, the light classes, \`GLTFLoader\`, \`setAnimationLoop\`) and builds 67js parts from them. It throws an error that names the 67js call when you use a name it does not support.+## Docs- [Complete plain-text guide](${page('guide.md')}): renderer, parts, materials, cameras, animation, export and troubleshooting.diff --git a/src/documentation-topics.js b/src/documentation-topics.jsindex 4d219847..db1d479a 100644--- a/src/documentation-topics.js+++ b/src/documentation-topics.js@@ -1,7 +1,7 @@// The order of the documentation. The site navigation and the plain-text guide (`/guide.md`) both read it.// Ids are file names in docs/learn, or slugs of the `## ` headings in docs/guide.md.export const documentationGroups = [- { title: 'Start here', icon: 'start', ids: ['introduction', 'install', 'first-scene', 'faq'] },+ { title: 'Start here', icon: 'start', ids: ['introduction', 'install', 'first-scene', 'if-you-know-three-js', 'faq'] },{ title: 'Build a scene', icon: 'cube', ids: ['parts-and-geometry', 'materials-and-color', 'cameras-and-framing', 'effects-and-lighting', 'local-lights-and-volume-fog', 'hdr-environment-lighting', 'renderer-reference'] },{ title: 'Model and fit surfaces', icon: 'cube', ids: ['procedural-modeling', 'sculpt-brushes', 'contact-detection', 'shrinkwrap-and-surface-patches', 'retained-surface-attachments'] },{ title: 'Worlds', icon: 'world', ids: ['terrain-and-ground-textures', 'trees-and-grass', 'grass-fields', 'wheeled-vehicles', 'baked-liquid'] },diff --git a/tests/fixtures/three-compat/page.html b/tests/fixtures/three-compat/page.htmlnew file mode 100644index 00000000..b1f68e84--- /dev/null+++ b/tests/fixtures/three-compat/page.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+<style>html,body{margin:0;background:#000}canvas{width:256px;height:256px;display:block}</style>+</head>+<body>+<canvas id="scene"></canvas>+<script type="module" src="./page.js"></script>+</body>+</html>diff --git a/tests/fixtures/three-compat/page.js b/tests/fixtures/three-compat/page.jsnew file mode 100644index 00000000..858f085b--- /dev/null+++ b/tests/fixtures/three-compat/page.js@@ -0,0 +1,76 @@+// Draws each three.js-style snippet through the addon and reports the picture, so the test can tell a lit scene from a blank one.+import * as core from '../../../src/index.js';+import { loadGltf } from '../../../src/gltf.js';+import { createThreeCompat } from '../../../packages/three-compat/index.mjs';+import { snippets } from './snippets.mjs';++function checkerboard() {+ const picture = document.createElement('canvas');+ picture.width = 64;+ picture.height = 64;+ const context = picture.getContext('2d');+ for (let row = 0; row < 8; row++) {+ for (let column = 0; column < 8; column++) {+ context.fillStyle = (row + column) % 2 ? '#f4f4f4' : '#2255aa';+ context.fillRect(column * 8, row * 8, 8, 8);+ }+ }+ return picture;+}++function describePicture(canvas) {+ const copy = document.createElement('canvas');+ copy.width = canvas.width;+ copy.height = canvas.height;+ const context = copy.getContext('2d', { willReadFrequently: true });+ context.drawImage(canvas, 0, 0);+ const { data } = context.getImageData(0, 0, copy.width, copy.height);+ const colors = new Set();+ let hash = 0;+ for (let offset = 0; offset < data.length; offset += 4) {+ const packed = (data[offset] >> 3) << 10 | (data[offset + 1] >> 3) << 5 | data[offset + 2] >> 3;+ colors.add(packed);+ hash = (hash * 31 + packed) >>> 0;+ }+ return { distinctColors: colors.size, hash };+}++// Each snippet draws on its own canvas, so no snippet inherits the context of the one before.+function freshCanvas() {+ document.querySelector('#scene').remove();+ const canvas = document.createElement('canvas');+ canvas.id = 'scene';+ document.body.append(canvas);+ return canvas;+}++const nextFrame = () => new Promise(resolve => requestAnimationFrame(() => resolve()));++window.snippetNames = snippets.map(snippet => snippet.name);+window.drawSnippet = async name => {+ const snippet = snippets.find(entry => entry.name === name);+ const THREE = createThreeCompat({ ...core, loadGltf });+ const canvas = freshCanvas();+ const { scene, camera, animate } = await snippet.build(THREE, { canvas, checkerboard });+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });+ renderer.setSize(256, 256);+ let frames = 0;+ let picture = null;+ if (snippet.loop) {+ // The picture is read inside the frame that drew it, because the canvas does not keep its pixels afterwards.+ renderer.setAnimationLoop(() => {+ animate();+ renderer.render(scene, camera);+ frames += 1;+ if (frames === 3) picture = describePicture(canvas);+ });+ while (frames < 3) await nextFrame();+ renderer.setAnimationLoop(null);+ } else {+ renderer.render(scene, camera);+ frames = 1;+ picture = describePicture(canvas);+ }+ renderer.dispose();+ return { frames, ...picture };+};diff --git a/tests/fixtures/three-compat/snippets.mjs b/tests/fixtures/three-compat/snippets.mjsnew file mode 100644index 00000000..5964985b--- /dev/null+++ b/tests/fixtures/three-compat/snippets.mjs@@ -0,0 +1,199 @@+// Twelve scenes written the way a model writes three.js from memory. The Node tests build each one and check the parts,+// and the render test draws each one in Chrome. Each snippet gets THREE (the addon), a canvas and a helper that makes a+// small checkerboard picture, and returns what to draw.++const GLB_URL = new URL('../RobotExpressive.glb', import.meta.url).href;++function lookingAt(camera, x, y, z) {+ camera.lookAt(x, y, z);+ return camera;+}++function floor(THREE, color = 0x303844) {+ const plane = new THREE.Mesh(new THREE.PlaneGeometry(12, 12), new THREE.MeshStandardMaterial({ color, roughness: 0.9 }));+ plane.rotation.x = -Math.PI / 2;+ return plane;+}++export const snippets = [+ {+ name: 'lit box',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.5, 0);+ camera.position.set(3, 2.2, 4);+ const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x2f9e6b, roughness: 0.5 }));+ cube.position.y = 0.5;+ const sun = new THREE.DirectionalLight(0xffffff, 3);+ sun.position.set(4, 6, 3);+ scene.add(floor(THREE), cube, sun, new THREE.AmbientLight(0xffffff, 0.4));+ return { scene, camera };+ },+ },+ {+ name: 'metal sphere under a point light',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(50, 1, 0.1, 100), 0, 0.8, 0);+ camera.position.set(0, 1.5, 4);+ const ball = new THREE.Mesh(new THREE.SphereGeometry(0.8, 48, 24), new THREE.MeshStandardMaterial({ color: 0xffb86c, metalness: 1, roughness: 0.25 }));+ ball.position.y = 0.8;+ const lamp = new THREE.PointLight(0xfff0dd, 30, 12);+ lamp.position.set(1.5, 3, 2);+ scene.add(floor(THREE), ball, lamp, new THREE.AmbientLight(0xffffff, 0.3));+ return { scene, camera };+ },+ },+ {+ name: 'group of a cylinder and a torus',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.6, 0);+ camera.position.set(3, 2, 4);+ const group = new THREE.Group();+ const post = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 1.2, 32), new THREE.MeshStandardMaterial({ color: 0x8899aa, roughness: 0.4 }));+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.7, 0.12, 16, 64), new THREE.MeshStandardMaterial({ color: 0xcc3355, roughness: 0.3 }));+ post.position.y = 0.6;+ ring.position.y = 1.4;+ ring.rotation.x = Math.PI / 2;+ group.add(post, ring);+ group.rotation.y = 0.5;+ scene.add(floor(THREE), group, new THREE.HemisphereLight(0xffffff, 0x444444, 1.2), new THREE.DirectionalLight(0xffffff, 2.5));+ return { scene, camera };+ },+ },+ {+ name: 'textured mesh',+ build(THREE, { checkerboard }) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.8, 0);+ camera.position.set(2.5, 2, 3.5);+ const texture = new THREE.CanvasTexture(checkerboard());+ const ball = new THREE.Mesh(new THREE.SphereGeometry(0.9, 48, 24), new THREE.MeshStandardMaterial({ map: texture, roughness: 0.6 }));+ ball.position.y = 0.9;+ const sun = new THREE.DirectionalLight(0xffffff, 3);+ sun.position.set(3, 5, 4);+ scene.add(floor(THREE), ball, sun, new THREE.AmbientLight(0xffffff, 0.5));+ return { scene, camera };+ },+ },+ {+ name: 'loaded GLB',+ browserOnly: true,+ async build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(40, 1, 0.1, 200), 0, 1.5, 0);+ camera.position.set(6, 4, 9);+ const gltf = await new THREE.GLTFLoader().loadAsync(GLB_URL);+ scene.add(gltf.scene, new THREE.HemisphereLight(0xffffff, 0x555555, 1.5), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera };+ },+ },+ {+ name: 'orbiting camera',+ build(THREE, { canvas }) {+ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+ camera.position.set(0, 2, 5);+ const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x4488ff, roughness: 0.4 }));+ cube.position.y = 0.5;+ const controls = new THREE.OrbitControls(camera, canvas);+ controls.target.set(0, 0.5, 0);+ controls.rotate(0.8, 0.1);+ scene.add(floor(THREE), cube, new THREE.AmbientLight(0xffffff, 0.5), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera };+ },+ },+ {+ name: 'light rig with spot, point and area lights',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(50, 1, 0.1, 100), 0, 0.5, 0);+ camera.position.set(0, 2.5, 5);+ const statue = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1.5, 32), new THREE.MeshStandardMaterial({ color: 0xdddddd, roughness: 0.5 }));+ statue.position.y = 0.75;+ const spot = new THREE.SpotLight(0xffffff, 80, 15, Math.PI / 5, 0.4);+ spot.position.set(-3, 4, 3);+ spot.target.position.set(0, 0.7, 0);+ const warm = new THREE.PointLight(0xff8844, 20, 10);+ warm.position.set(2.5, 1.5, 1);+ const panel = new THREE.RectAreaLight(0x88aaff, 20, 3, 2);+ panel.position.set(0, 3, -2);+ panel.lookAt(0, 0.7, 0);+ scene.add(floor(THREE), statue, spot, warm, panel);+ return { scene, camera };+ },+ },+ {+ name: 'orthographic camera',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.OrthographicCamera(-3, 3, 3, -3, 0.1, 100), 0, 0.5, 0);+ camera.position.set(5, 5, 5);+ const cube = new THREE.Mesh(new THREE.BoxGeometry(1.5, 1, 1), new THREE.MeshStandardMaterial({ color: 0xe0a030, roughness: 0.5 }));+ cube.position.y = 0.5;+ scene.add(floor(THREE), cube, new THREE.AmbientLight(0xffffff, 0.5), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera };+ },+ },+ {+ name: 'physical material with a clear coat',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.7, 0);+ camera.position.set(2.5, 1.8, 3.5);+ const paint = new THREE.MeshPhysicalMaterial({ color: 0xaa1122, metalness: 0.6, roughness: 0.35, clearcoat: 1, clearcoatRoughness: 0.05 });+ const ball = new THREE.Mesh(new THREE.SphereGeometry(0.8, 48, 24), paint);+ ball.position.y = 0.8;+ scene.add(floor(THREE), ball, new THREE.AmbientLight(0xffffff, 0.4), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera };+ },+ },+ {+ name: 'transparent and emissive parts',+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.6, 0);+ camera.position.set(2.5, 2, 4);+ const glass = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2), new THREE.MeshStandardMaterial({ color: 0x66ccff, transparent: true, opacity: 0.4, roughness: 0.1 }));+ glass.position.y = 0.6;+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.25, 24, 12), new THREE.MeshStandardMaterial({ color: 0x000000, emissive: 0xffaa33, emissiveIntensity: 4 }));+ bulb.position.set(0, 0.6, 0);+ scene.add(floor(THREE), glass, bulb, new THREE.AmbientLight(0xffffff, 0.5), new THREE.DirectionalLight(0xffffff, 2.5));+ return { scene, camera };+ },+ },+ {+ name: 'animation loop',+ loop: true,+ build(THREE) {+ const scene = new THREE.Scene();+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 0.5, 0);+ camera.position.set(3, 2.2, 4);+ const cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x2f9e6b, roughness: 0.5 }));+ cube.position.y = 0.5;+ scene.add(floor(THREE), cube, new THREE.AmbientLight(0xffffff, 0.5), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera, animate: () => { cube.rotation.y += 0.3; } };+ },+ },+ {+ name: 'nested groups, scale and a background',+ build(THREE) {+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x203050);+ const camera = lookingAt(new THREE.PerspectiveCamera(45, 1, 0.1, 100), 0, 1, 0);+ camera.position.set(4, 3, 6);+ const outer = new THREE.Group();+ const inner = new THREE.Group();+ const box = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0xff6644, roughness: 0.5 }));+ inner.position.set(1, 0, 0);+ inner.scale.set(1.5, 1.5, 1.5);+ box.position.y = 0.5;+ inner.add(box);+ outer.add(inner);+ outer.rotation.y = 0.6;+ scene.add(floor(THREE), outer, new THREE.AmbientLight(0xffffff, 0.6), new THREE.DirectionalLight(0xffffff, 3));+ return { scene, camera };+ },+ },+];diff --git a/tests/three-compat.test.js b/tests/three-compat.test.jsnew file mode 100644index 00000000..093d1408--- /dev/null+++ b/tests/three-compat.test.js@@ -0,0 +1,225 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import { constants, setPriority } from 'node:os';+import * as core from '../src/index.js';+import { loadGltf } from '../src/gltf.js';+import { createThreeCompat, unsupportedNames } from '../packages/three-compat/index.mjs';+import { snippets } from './fixtures/three-compat/snippets.mjs';++const THREE = createThreeCompat({ ...core, loadGltf });+const fakeCanvas = { style: {}, addEventListener() {} };+const fakeServices = { canvas: fakeCanvas, checkerboard: () => ({ width: 64, height: 64 }) };++function litScene(light) {+ const scene = new THREE.Scene();+ scene.add(light);+ const camera = new THREE.PerspectiveCamera(60, 1, 0.5, 50);+ camera.position.set(0, 1, 5);+ return { scene, camera };+}++test('the addon does not import three or the core by name', async () => {+ const { readFile } = await import('node:fs/promises');+ const source = await readFile(new URL('../packages/three-compat/index.mjs', import.meta.url), 'utf8');+ assert.doesNotMatch(source, /^\s*import\s/m, 'the addon has no import statement');+ assert.throws(() => createThreeCompat({}), /needs the 67js export Renderer67/);+});++test('every snippet that needs no browser builds parts, an environment and a frame', async () => {+ const runnable = snippets.filter(snippet => !snippet.browserOnly);+ assert.ok(runnable.length >= 10);+ for (const snippet of runnable) {+ const { scene, camera } = await snippet.build(THREE, fakeServices);+ const { parts, environment, frame } = THREE.collectScene(scene, camera);+ assert.ok(parts.length >= 2, `${snippet.name} has parts`);+ assert.equal(new Set(parts.map(part => part.name)).size, parts.length, `${snippet.name} has unique part names`);+ for (const part of parts) {+ assert.equal(part.matrix.length, 16, `${snippet.name} ${part.name} has a 4 x 4 matrix`);+ assert.ok(part.matrix.every(Number.isFinite), `${snippet.name} ${part.name} matrix is finite`);+ assert.ok(part.geometry.positions.length > 0, `${snippet.name} ${part.name} has a geometry`);+ assert.ok(part.material.color.every(Number.isFinite));+ }+ assert.equal(frame.eye.length, 3);+ assert.equal(frame.target.length, 3);+ assert.ok(environment);+ }+});++test('a mesh matrix places and scales the unit geometry, in the order of three.js', () => {+ const scene = new THREE.Scene();+ const group = new THREE.Group();+ group.position.set(10, 0, 0);+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(2, 4, 6), new THREE.MeshStandardMaterial());+ mesh.position.set(1, 2, 3);+ group.add(mesh);+ scene.add(group);+ const { parts } = THREE.collectScene(scene, new THREE.PerspectiveCamera());+ const matrix = parts[0].matrix;+ assert.deepEqual([...matrix.slice(12, 15)], [11, 2, 3]);+ assert.deepEqual([matrix[0], matrix[5], matrix[10]], [2, 4, 6]);+});++test('Euler rotation XYZ turns a mesh like three.js does', () => {+ const scene = new THREE.Scene();+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial());+ mesh.rotation.z = Math.PI / 2;+ scene.add(mesh);+ const { parts } = THREE.collectScene(scene, new THREE.PerspectiveCamera());+ // A quarter turn about Z sends the X axis to Y.+ assert.ok(Math.abs(parts[0].matrix[1] - 1) < 1e-6);+ assert.ok(Math.abs(parts[0].matrix[4] + 1) < 1e-6);+});++test('MeshStandardMaterial and MeshPhysicalMaterial become 67js materials in linear colour', () => {+ const standard = new THREE.MeshStandardMaterial({ color: 0xff8000, metalness: 0.7, roughness: 0.2, emissive: 0x00ff00, emissiveIntensity: 2, side: THREE.DoubleSide }).toMaterial();+ assert.ok(Math.abs(standard.color[0] - 1) < 1e-6);+ assert.ok(Math.abs(standard.color[1] - 0.2158605) < 1e-5, 'sRGB 0x80 is linear 0.2159');+ assert.equal(standard.metallic, 0.7);+ assert.equal(standard.roughness, 0.2);+ assert.equal(standard.emission, 2);+ assert.deepEqual(standard.emissiveColor, [0, 1, 0]);+ assert.equal(standard.doubleSided, true);+ const physical = new THREE.MeshPhysicalMaterial({ clearcoat: 1, transmission: 0.5, ior: 1.4, specularIntensity: 0.8 }).toMaterial();+ assert.deepEqual([physical.clearcoat, physical.transmission, physical.ior, physical.specular], [1, 0.5, 1.4, 0.8]);+ const blended = new THREE.MeshStandardMaterial({ transparent: true, opacity: 0.3 }).toMaterial();+ assert.deepEqual([blended.alphaMode, blended.opacity], ['blend', 0.3]);+ const cutout = new THREE.MeshStandardMaterial({ alphaTest: 0.4 }).toMaterial();+ assert.deepEqual([cutout.alphaMode, cutout.alphaCutoff], ['mask', 0.4]);+});++test('lights fill the environment of the frame', () => {+ const directional = new THREE.DirectionalLight(0xffffff, 3);+ directional.position.set(2, 4, 6);+ const { scene, camera } = litScene(directional);+ scene.add(new THREE.AmbientLight(0xffffff, 0.5));+ const lit = THREE.collectScene(scene, camera).environment;+ assert.deepEqual(lit.lightDirection, [2, 4, 6]);+ assert.equal(lit.keyIntensity, 3);+ assert.equal(lit.ambientIntensity, 0.5);+ assert.equal(lit.fillIntensity, 0, 'a scene with its own lights switches the studio fill off');++ const point = new THREE.PointLight(0xffffff, 12, 9);+ point.position.set(1, 2, 3);+ const pointEnvironment = THREE.collectScene(litScene(point).scene, camera).environment;+ assert.deepEqual(pointEnvironment.pointLights, [{ position: [1, 2, 3], color: [1, 1, 1], intensity: 12, range: 9 }]);+ assert.equal(pointEnvironment.keyIntensity, 0);++ const spot = new THREE.SpotLight(0xffffff, 50, 0, 0.5, 0.3);+ spot.position.set(0, 5, 0);+ const spotLight = THREE.collectScene(litScene(spot).scene, camera).environment.spotLights[0];+ assert.deepEqual(spotLight.direction, [0, -5, 0]);+ assert.deepEqual([spotLight.angle, spotLight.penumbra, spotLight.range], [0.5, 0.3, undefined]);++ const panel = new THREE.RectAreaLight(0xffffff, 5, 3, 2);+ panel.position.set(0, 3, 0);+ panel.lookAt(0, 0, 0);+ const area = THREE.collectScene(litScene(panel).scene, camera).environment.areaLights[0];+ assert.deepEqual([area.width, area.height, ...area.direction], [3, 2, 0, -3, 0]);++ const dark = THREE.collectScene(new THREE.Scene(), camera).environment;+ assert.equal(dark.keyIntensity, undefined, 'a scene with no light keeps the studio rig');+});++test('cameras become frames', () => {+ const perspective = new THREE.PerspectiveCamera(35, 2, 0.2, 80);+ perspective.position.set(1, 2, 3);+ perspective.lookAt(0, 0, 0);+ const frame = THREE.collectScene(new THREE.Scene(), perspective).frame;+ assert.deepEqual([frame.eye, frame.target, frame.fov, frame.near, frame.far], [[1, 2, 3], [0, 0, 0], 35, 0.2, 80]);++ const orthographic = new THREE.OrthographicCamera(-4, 4, 3, -3, 0.1, 50);+ orthographic.position.set(0, 0, 5);+ const orthographicFrame = THREE.collectScene(new THREE.Scene(), orthographic).frame;+ assert.equal(orthographicFrame.projection, 'orthographic');+ assert.equal(orthographicFrame.orthographicHeight, 6);+ assert.deepEqual(orthographicFrame.target, [0, 0, 4], 'a camera without lookAt looks down its -Z axis');+});++test('OrbitControls moves the camera around its target', () => {+ const camera = new THREE.PerspectiveCamera();+ camera.position.set(0, 0, 4);+ const controls = new THREE.OrbitControls(camera, fakeCanvas);+ controls.target.set(0, 0, 0);+ controls.rotate(Math.PI / 2, 0);+ assert.ok(Math.abs(camera.position.x - 4) < 1e-6);+ assert.ok(Math.abs(camera.position.z) < 1e-6);+});++test('unsupported three.js names throw an error that names the 67js replacement', () => {+ const cases = [+ ['MeshBasicMaterial', /MeshStandardMaterial.*emission/],+ ['ShaderMaterial', /no custom shaders/],+ ['ConeGeometry', /createModel/],+ ['WebGLRenderTarget', /toBlob/],+ ['Fog', /fogDensity/],+ ['EffectComposer', /resolveEffects/],+ ['AnimationMixer', /createAnimationMixer/],+ ['TextureLoader', /material\.map/],+ ['SomethingElse', /not part of the common subset/],+ ];+ for (const [name, replacement] of cases) {+ assert.throws(() => THREE[name], error => error.message.includes(`THREE.${name}`) && replacement.test(error.message) && error.message.includes('if-you-know-three-js.md'), name);+ }+ assert.throws(() => new THREE.MeshStandardMaterial({ aoMap: {} }), /occlusionMap/);+ assert.throws(() => new THREE.CylinderGeometry(0, 1, 2), /createModel/);+ assert.throws(() => new THREE.MeshStandardMaterial({ side: THREE.BackSide }).toMaterial(), /doubleSided/);+ assert.throws(() => new THREE.Color('red'), /hex/);+ assert.throws(() => new THREE.Mesh({}, new THREE.MeshStandardMaterial()), /box\(\)/);+ assert.equal(THREE.then, undefined, 'lowercase names are plain properties');+});++test('every 67js call named by an error exists', () => {+ const known = new Set([...Object.keys(core), ...Object.getOwnPropertyNames(core.Renderer67.prototype), 'loadGltf', 'createModel', 'box', 'sphere', 'cylinder', 'torus', 'canvas.toBlob', 'Texture']);+ assert.ok(unsupportedNames.length >= 20);+ for (const name of unsupportedNames) {+ let message = '';+ try {+ THREE[name];+ } catch (error) {+ message = error.message;+ }+ assert.ok(message, `${name} throws`);+ for (const [, call] of message.matchAll(/([A-Za-z_.]+)\(/g)) {+ assert.ok(known.has(call) || known.has(call.split('.').at(-1)), `${name}: the error names ${call}, which is not a 67js export`);+ }+ }+});++// Draws every snippet in Chrome so each gets a real frame. It runs only when asked, because it needs a browser and a GPU:+// RENDER_TESTS=1 node --test tests/three-compat.test.js+// CHROME_PATH names the browser. THREE_COMPAT_ANGLE picks the graphics backend (default d3d11 on Windows, vulkan elsewhere).+const chromePath = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const renderEnabled = process.env.RENDER_TESTS === '1' && existsSync(chromePath);++test('each three.js-style snippet draws a frame through the addon', { skip: !renderEnabled, timeout: 300000 }, async () => {+ setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+ const { chromium } = await import('playwright');+ const { createServer } = await import('vite');+ const angle = process.env.THREE_COMPAT_ANGLE ?? (process.platform === 'win32' ? 'd3d11' : 'vulkan');+ const flags = ['--enable-webgl', '--ignore-gpu-blocklist', `--use-angle=${angle}`, '--enable-gpu', '--no-sandbox'];+ if (angle === 'vulkan') flags.push('--enable-features=Vulkan');+ const server = await createServer({ root: new URL('..', import.meta.url).pathname.replace(/^\/(\w:)/, '$1'), server: { host: '127.0.0.1', port: 0, fs: { strict: false } }, logLevel: 'silent' });+ await server.listen();+ const browser = await chromium.launch({ executablePath: chromePath, headless: true, args: flags });+ try {+ const page = await browser.newPage({ viewport: { width: 256, height: 256 } });+ const failures = [];+ page.on('pageerror', error => failures.push(error.message));+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/tests/fixtures/three-compat/page.html`, { timeout: 60000 });+ await page.waitForFunction(() => window.drawSnippet, null, { timeout: 60000 });+ const hashes = new Set();+ for (const snippet of snippets) {+ const result = await page.evaluate(name => window.drawSnippet(name), snippet.name);+ assert.ok(result.frames >= 1, `${snippet.name} drew a frame`);+ assert.ok(result.distinctColors >= 12, `${snippet.name} is not a blank frame (${result.distinctColors} colours)`);+ assert.ok(!hashes.has(result.hash), `${snippet.name} differs from every other snippet`);+ hashes.add(result.hash);+ }+ assert.deepEqual(failures, []);+ assert.ok(hashes.size >= 10);+ } finally {+ await browser.close();+ await server.close();+ }+});diff --git a/tests/three-js-guide.test.js b/tests/three-js-guide.test.jsnew file mode 100644index 00000000..6d8b0090--- /dev/null+++ b/tests/three-js-guide.test.js@@ -0,0 +1,88 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync, readFileSync } from 'node:fs';+import * as core from '../src/index.js';+import * as gltf from '../src/gltf.js';++// Checks docs/learn/if-you-know-three-js.md against the code: every 67js call and field the 67js column names must exist.+const read = path => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');+const guide = read('docs/learn/if-you-know-three-js.md');++const rows = guide.split('\n')+ .filter(line => line.startsWith('| ') && !line.startsWith('| ---') && !line.startsWith('| three.js'))+ .map(line => line.split(' | ').map(cell => cell.replace(/^\| |\ \|$/g, '')));++const calls = new Set([+ ...Object.keys(core),+ ...Object.keys(gltf),+ ...Object.getOwnPropertyNames(core.Renderer67.prototype),+ 'createModel',+ // Browser calls the table uses.+ 'toBlob', 'now', 'requestAnimationFrame', 'push',+]);++const fieldSources = {+ frame: ['docs/learn/cameras-and-framing.md', 'docs/learn/effects-and-lighting.md'],+ environment: ['docs/lighting.md', 'docs/learn/effects-and-lighting.md', 'docs/learn/local-lights-and-volume-fog.md', 'docs/learn/hdr-environment-lighting.md'],+ material: ['docs/learn/materials-and-color.md', 'docs/material-maps.md'],+ part: ['docs/learn/parts-and-geometry.md', 'docs/learn/local-lights-and-volume-fog.md'],+};++function backtickTokens(cell) {+ return [...cell.matchAll(/`([^`]+)`/g)].map(match => match[1]);+}++test('the guide has a row for each idiom in the issue', () => {+ const left = rows.map(row => row[0]).join('\n');+ for (const idiom of ['Scene', 'Group', 'Mesh', 'BoxGeometry', 'SphereGeometry', 'MeshStandardMaterial', 'MeshPhysicalMaterial', 'PerspectiveCamera',+ 'OrthographicCamera', 'AmbientLight', 'DirectionalLight', 'PointLight', 'SpotLight', 'RectAreaLight', 'GLTFLoader', 'setAnimationLoop', 'OrbitControls', 'WebGLRenderTarget']) {+ assert.ok(left.includes(idiom), `no row for ${idiom}`);+ }+ assert.ok(rows.length >= 45);+});++test('every call the 67js column names is a real export or method', () => {+ let checked = 0;+ for (const [idiom, replacement] of rows) {+ for (const token of backtickTokens(replacement)) {+ for (const [, name] of token.matchAll(/([A-Za-z0-9_]+)\(/g)) {+ assert.ok(calls.has(name), `"${idiom}" names ${name}(), which 67js does not export`);+ checked += 1;+ }+ }+ }+ assert.ok(checked >= 25, `only ${checked} calls were checked`);+});++test('every field the 67js column names appears in the docs of its object', () => {+ let checked = 0;+ for (const [idiom, replacement] of rows) {+ for (const token of backtickTokens(replacement)) {+ for (const [, owner, field] of token.matchAll(/\b(frame|environment|material|part)\.(\w+)/g)) {+ const text = fieldSources[owner].map(read).join('\n');+ assert.ok(new RegExp(`\\b${field}\\b`).test(text), `"${idiom}" names ${owner}.${field}, which the ${owner} docs never mention`);+ checked += 1;+ }+ }+ }+ assert.ok(checked >= 25, `only ${checked} fields were checked`);+});++test('every 67js name in the guide that is an export exists in src/index.js or an addon', () => {+ for (const [, name] of guide.matchAll(/\b(Renderer67)\b/g)) assert.ok(name in core);+ for (const [, path] of guide.matchAll(/`(67js\/addons\/[\w-]+)`/g)) {+ const exportName = `./addons/${path.split('/').at(-1)}`;+ const packageExports = JSON.parse(read('package.json')).exports;+ assert.ok(exportName in packageExports, `${path} is not an export of the package`);+ }+});++test('the guide is in the navigation, llms.txt points to it and the addon folder exists', () => {+ assert.match(read('src/documentation-topics.js'), /'if-you-know-three-js'/);+ const llms = read('public/llms.txt');+ assert.match(llms, /## If you know three\.js/);+ assert.match(llms, /67js-three-compat/);+ assert.ok(existsSync(new URL('../packages/three-compat/index.mjs', import.meta.url)));+ assert.match(read('docs/learn/introduction.md'), /\(#if-you-know-three-js\)/);+ assert.doesNotMatch(read('docs/learn/introduction.md'), /does not run in 67js without changes/);+});