Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Merge remote-tracking branch 'origin/main' into HEAD

Nguyen Xuan An2db17be3fedf
diff --cc CHANGELOG.md
index 208264ad,44ccbd3a..b12b7d71
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,8 -2,10 +2,12 @@@
## Unreleased
+- Add frustum culling, levels of detail and live adaptive resolution (part of issue #37). `Renderer67` tests each instance of a batch against the view frustum with the geometry's bounding sphere and draws only the visible ones (on by default, `culling: false` turns it off; skinned, morphed, swaying, fire, smoke, water, assembly and blended batches and the shadow passes are not culled). A part's `lods`, the array from `generateGeometryLods`, makes each instance pick a level by pixel error (`lodPixelError`, default 1). Selection is a pure function of the camera and the matrices, so a seek draws the same frame. `createGpuTimer` and `AdaptiveResolution` in `src/adaptive-quality.js` give live viewers GPU timing and a resolution scale with a minimum; an export can not build one, and `src/main.js` uses it only outside `export=1`. New `large-outdoor` scene in `bench/runtime` with ablations: 1.55 ms against 8.41 ms without culling and 6.0 ms for three.js on an RTX 3060, 517 ms against 4,428 ms and 944 ms on SwiftShader. Core grows 1,845 bytes gzip (budget 81,500). Recipes cannot declare `lods` yet. See `docs/culling-lod.md`.
+
+ - Add relations between parts (part of issue #44, no new tool): a mesh node takes `relations` (`attach`, `gap`, `flush`, `align`, `centered`, up to 8) against other mesh nodes, or against the faces of one carrying a mesh tag (`region`). They work on world bounds, are solved after geometry exists and again on every `scene_apply`, so one edit to a body keeps the parts that sit against it. Unknown IDs and tags, two relations on one axis and cycles (a part waiting on its own child included) are rejected with the next action; solving is deterministic and independent of node order. The code loads on demand (`relations`). The schema carries only a generic `relations` list (597 bytes over `scene_create` and `scene_apply` together); the kinds and fields are in `scene_capabilities` `relations`, and the engine validates them. Measured on Sonnet (3 runs each), relations did not cut tool calls or errors: the kettle resize took 3.3 calls against 3.0, and a 12-part desk with three inspected resizes took 8 against 8, with 13% fewer output tokens (3,833 against 4,403) and the same cost and pass rate. The suite gains `kettle-resize`, `desk-resize` and their plain twins, and `touches` and `centreAt` checks.
+ - Add render passes, depth of field and camera motion blur (issue #54, first slice). Render jobs of kind `image` or `stills` take `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) and write each as a raw, unantialiased PNG beside the lit image (`render-depth.png`, `frame-3-objectId.png`); depth is 16 bits over 100 m in red and green, object IDs are 24 bits with the part names in the job metrics. In code, `renderer.render({ pass })` draws a pass into its own non-multisampled target. `effects.depthOfField` (`blur`, `focusDistance`) and `effects.motionBlur` (`shutter`) are new recipe effects: fixed sample patterns and a per-pixel rotation from the pixel position, so a seek to a frame repeats the same pixels. They live in the new `67js/addons/camera-effects` entry; the preview installs it, and the core renderer only gains a stage hook and the pass branch (a compiled-out shader feature). Motion blur follows camera tracks only, sampled from time at `motion.start + elapsed - shutter`. Measured on SwiftShader through MCP (`npm run smoke:render-passes`): 8 stills with 5 passes each, then four seeks, all byte-identical to the same frame in the sequence. Temporal anti-aliasing, accumulation and the compositing graph of #54 are not part of this slice.
+
+ - Expose clip layers, bone masks and name retargeting through MCP, and morph clips in `createAssetPose` (issue #59, in part). An asset recipe's `motion.layers` (up to 8) plays the file's own clips at motion time with a bone `mask`, `weight`, `speed`, `offset`, `loop`, `additive` with `reference`, `bones` (clip track to another asset node) and `morph`, before tracks and IK, so a character walks and waves at once; everything is checked against the asset and bounded, and a seek equals playing. `morphClipFromGltfAnimation` and a layer's `morphs` put morph weights through `createAssetPose` (masks pick parts by their owning bone), `createAssetLayerEvaluator` serves hosts that stage the pose themselves, and `asset.stagePose` takes `morphWeights`. Add the `robot-walk-wave` task to the agent modeling suite and extend `npm run smoke:character`. Not done: foot tilt on slopes, full-body IK, and rest-pose retargeting from another asset through MCP. Raise `entry:skeleton-pose` to 19,000 and `entry:agent-asset` to 85,200 bytes gzip, and the tool schema budgets by 800 bytes (`scene_apply` to 47,800, `scene_create_asset` to 20,150, total to 190,700).
- Use one expression language for fields and drivers (issue #98). `src/expression.js` holds the limits, number literals, operator table, syntax and hostile-input checks; `src/mesh-fields.js` (per mesh element: attributes, noise, random, vectors) and `src/motion-expression.js` (per time: `time`, node reads) only add their own inputs, and each rejects the other's with a message that names the context. **This changes driver expressions** (neither language was released): an operator with one operand may be written bare, `{"neg": x}`, in drivers as in fields; `if` takes its second operand when the condition is not 0 (a driver used above 0); `sqrt` of a negative, `pow` overflow and `mod` by 0 give 0 instead of an error; `smoothstep` with equal edges is a step; `div` by 0 is still a non-finite error in a driver, because a hostile-input test pins it, and 0 in a field. Drivers gain `ceil`, `round`, `sign`, `lte`, `gte`, `eq`, `and`, `or`, `not` and booleans; fields gain `atan2` and `saturate`. The unknown-operator hint of fields lists operators in a new order. Error messages for a malformed driver changed in wording and are all TypeErrors. The MCP schema for drivers now points at the field language instead of listing operators (schemas 183,741 to 183,762 bytes), and the `scene_capabilities` budget rises from 3,050 to 3,100 bytes for two operator names.
- Add branches and labelled images to the agent tools (part of issue #67, no new tool). `scene_apply` with a `branch` name runs the operations on a scratch copy and stores the result in a snapshot store that holds one copy per distinct recipe (8 branches), leaving the scene, its revision and its checkpoints untouched. `scene_review` shots take a `branch` and render it in a private scene; `scene_restore` with `branch` keeps one. `labels: true` on `scene_look` and `scene_review` draws part names, material tags and mesh lint problems on the image and returns them as JSON with pixel positions. Branch names are bounded (`^[a-z][a-z0-9_-]{0,23}$`). The tool-schema budget rose by 800 bytes in total (150 for `scene_apply`). `npm run smoke:agent-branches` drives it through MCP on SwiftShader.
diff --cc bench/size/baseline.json
index 1de505ad,85a56cb9..b2561b0d
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@@ -14,9 -14,9 +14,9 @@@
},
"bundles": {
"entry:core": {
- "min": 279820,
- "gzip": 79852,
- "brotli": 68242
- "min": 277673,
- "gzip": 79031,
- "brotli": 67391
++ "min": 283098,
++ "gzip": 80905,
++ "brotli": 69041
},
"entry:model": {
"min": 40093,
@@@ -39,9 -39,9 +39,9 @@@
"brotli": 7331
},
"entry:gltf": {
- "min": 152150,
- "gzip": 46707,
- "brotli": 40067
+ "min": 154791,
+ "gzip": 47466,
- "brotli": 40606
++ "brotli": 40652
},
"entry:modeling": {
"min": 15517,
@@@ -129,49 -129,59 +129,59 @@@
"brotli": 762
},
"entry:agent-scene": {
- "min": 190657,
- "gzip": 57330,
- "brotli": 49632
+ "min": 195659,
- "gzip": 59292,
- "brotli": 51242
++ "gzip": 59291,
++ "brotli": 51288
},
"entry:agent-scene+lazy": {
- "min": 497784,
- "gzip": 164818,
- "brotli": 143871
+ "min": 513028,
- "gzip": 170623,
- "brotli": 148898
++ "gzip": 170622,
++ "brotli": 148944
},
"entry:agent-asset": {
- "min": 273341,
- "gzip": 83733,
- "brotli": 72953
+ "min": 286211,
- "gzip": 88215,
- "brotli": 76934
++ "gzip": 88211,
++ "brotli": 76977
},
"entry:agent-asset+lazy": {
- "min": 524940,
- "gzip": 172137,
- "brotli": 149809
+ "min": 545319,
- "gzip": 179573,
- "brotli": 156501
++ "gzip": 179569,
++ "brotli": 156544
},
"entry:hdri": {
"min": 8075,
"gzip": 3138,
"brotli": 2801
},
+ "entry:camera-effects": {
+ "min": 23985,
+ "gzip": 8396,
+ "brotli": 6688
+ },
+ "entry:render-passes": {
+ "min": 3412,
+ "gzip": 1608,
+ "brotli": 1425
+ },
"scene:lit-box": {
- "min": 211766,
- "gzip": 57906,
- "brotli": 49427
- "min": 209451,
- "gzip": 57034,
- "brotli": 48658
++ "min": 214877,
++ "gzip": 58928,
++ "brotli": 50227
},
"scene:gltf-box": {
- "min": 269645,
- "gzip": 76810,
- "brotli": 66055
- "min": 268357,
- "gzip": 76237,
- "brotli": 65528
++ "min": 273787,
++ "gzip": 78107,
++ "brotli": 67034
},
"scene:agent-scene": {
- "min": 299465,
- "gzip": 86309,
- "brotli": 74093
- "min": 300023,
- "gzip": 86690,
- "brotli": 74386
++ "min": 305458,
++ "gzip": 88650,
++ "brotli": 75931
},
"scene:agent-scene+lazy": {
- "min": 606592,
- "gzip": 193797,
- "brotli": 168354
- "min": 617392,
- "gzip": 198024,
- "brotli": 172011
++ "min": 622827,
++ "gzip": 199984,
++ "brotli": 173556
}
}
}
diff --cc bench/size/budgets.json
index 1e91f839,97ad3088..ddfcd88e
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@@ -5,7 -5,7 +5,7 @@@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 81500,
- "entry:core": 80700,
++ "entry:core": 82600,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
@@@ -28,14 -28,16 +28,16 @@@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 58500,
- "entry:agent-scene+lazy": 168200,
- "entry:agent-asset": 85500,
- "entry:agent-asset+lazy": 175600,
+ "entry:agent-scene": 60500,
+ "entry:agent-scene+lazy": 174100,
+ "entry:agent-asset": 90000,
+ "entry:agent-asset+lazy": 183200,
"entry:hdri": 3300,
- "scene:lit-box": 59100,
- "scene:gltf-box": 78500,
- "scene:agent-scene": 88100,
- "scene:agent-scene+lazy": 195700
+ "entry:camera-effects": 8600,
+ "entry:render-passes": 1700,
- "scene:lit-box": 58200,
- "scene:gltf-box": 77800,
- "scene:agent-scene": 88500,
- "scene:agent-scene+lazy": 202000
++ "scene:lit-box": 60200,
++ "scene:gltf-box": 79700,
++ "scene:agent-scene": 90500,
++ "scene:agent-scene+lazy": 204000
}
}
diff --cc docs/parity.md
index 6bc307ac,0dc81664..e01ff410
--- a/docs/parity.md
+++ b/docs/parity.md
@@@ -238,10 -238,10 +238,10 @@@ The goal also needs this work, and no p
| --- | --- | --- | --- |
| Parity evidence | partial | This ledger exists. The Blender comparisons do not. | #24, #25, #26 |
| Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is gone from the library; only the benchmark page imports it. | #27, #33, #34, #35, #36 |
-| Runtime speed | partial | `bench/runtime` compares 7 scenes, and three.js wins most of them. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38, #74 |
+| Runtime speed | partial | `bench/runtime` compares 8 scenes, and three.js wins most of the 7 older ones. Frustum culling per part and per instance group is on by default, `lods` from `generateGeometryLods` pick a level per instance by pixel error (`docs/culling-lod.md`), and `createGpuTimer` plus `createAdaptiveResolution` give live viewers GPU timing and a bounded resolution scale. On `large-outdoor` 67.js is 1.55 ms against 6.0 ms for three.js on an RTX 3060. Part of #37: recipes have no way to declare `lods` yet, shadow passes are not culled, and bakes run on the main thread. | #28, #37, #38, #74 |
| Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 |
| Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 |
- | Relations between parts | missing | The agent version of snapping. | #44 |
+ | Relations between parts | partial | The agent version of snapping: node `relations` (`attach`, `gap`, `flush`, `align`, `centered`) over world bounds or a tagged region, solved again on every edit, cycles rejected. Tests in [part-relations](../tests/part-relations.test.js); suite tasks `kettle-resize` and `desk-resize` with plain twins (no gain in calls measured on Sonnet). No snapping to edges or vertices, no relation on the part's own tagged region. | #44 |
| Imported mesh editing | missing | Imported assets accept poses and transforms. Their topology is fixed. | #48 |
| Rendering backend | missing | WebGL2 only. WebGPU is not evaluated. | #56 |
| Terrain and navigation | partial | Terrain with 4 splat layers and no holes. There is no navmesh. | #64 |
diff --cc src/renderer.js
index d2bc392b,2322ec8a..7ae59a68
--- a/src/renderer.js
+++ b/src/renderer.js
@@@ -206,57 -204,6 +207,28 @@@ function packInstance(data, index, part
data.set(part.material.emissiveColor ?? part.material.color, offset + 38);
}
++// The objectId mode of RENDER_PASS_MODES in render-passes.js.
++const OBJECT_ID_PASS_MODE = 5;
++
+function isCullable(parts) {
+ const first = parts[0];
+ if (first.skin || first.morph || DEFORMING_TAGS.has(first.material.tag)) return false;
+ if (renderPass(first.material) !== 'opaque' || materialAlphaState(first.material)[0] === 'blend') return false;
+ return parts.every(part => !part.assembly);
+}
+
+function validateLods(part, levels) {
+ if (!Array.isArray(levels) || levels.length < 2 || levels[0].geometry !== part.geometry) {
+ throw new TypeError(`lods must list level 0 (the own geometry of the part) and at least one coarser level: ${part.name}`);
+ }
+ levels.forEach((level, index) => {
+ if (!level.geometry?.positions || !level.geometry.indices) throw new TypeError(`Every lods entry needs a geometry: ${part.name}`);
+ if (!Number.isFinite(level.error) || level.error < 0 || (index > 0 && level.error < levels[index - 1].error)) {
+ throw new RangeError(`lods errors must be finite and not decrease from level to level: ${part.name}`);
+ }
+ });
+}
+
- // Starting a program without asking for its result lets the driver build several programs at once.
- function startProgram(context, vertexSource, fragmentSource) {
- const program = context.createProgram();
- context.getExtension('KHR_parallel_shader_compile');
- const shaders = [];
- for (const [kind, source] of [[context.VERTEX_SHADER, vertexSource], [context.FRAGMENT_SHADER, fragmentSource]]) {
- const shader = context.createShader(kind);
- context.shaderSource(shader, source);
- context.compileShader(shader);
- context.attachShader(program, shader);
- shaders.push(shader);
- }
- context.linkProgram(program);
- return { program, shaders };
- }
-
- function finishProgram(context, { program, shaders }) {
- const linked = context.getProgramParameter(program, context.LINK_STATUS);
- const failedShader = shaders.find(shader => !context.getShaderParameter(shader, context.COMPILE_STATUS));
- const message = failedShader ? context.getShaderInfoLog(failedShader) : context.getProgramInfoLog(program);
- shaders.forEach((shader) => context.deleteShader(shader));
- if (!linked) {
- context.deleteProgram(program);
- throw new Error(failedShader ? `Shader compilation failed: ${message}` : `Shader linking failed: ${message}`);
- }
- return program;
- }
-
- function compileProgram(context, vertexSource, fragmentSource) {
- return finishProgram(context, startProgram(context, vertexSource, fragmentSource));
- }
-
function groundPart() {
return {
name: 'Studio floor',
@@@ -1815,10 -1681,12 +1809,13 @@@ export class Renderer67
mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);
mat4.multiply(this.viewProjection, this.projection, this.view);
mat4.invert(this.inverseViewProjection, this.viewProjection);
+ extractFrustumPlanes(this.viewProjection, this.frustumPlanes);
- context.bindFramebuffer(context.FRAMEBUFFER, this.benchmark ? null : this.multisampleFramebuffer);
+ this.viewForward = [-this.view[2], -this.view[6], -this.view[10]];
+ context.bindFramebuffer(context.FRAMEBUFFER, passMode ? this.passSupport.framebuffer : this.benchmark ? null : this.multisampleFramebuffer);
context.viewport(0, 0, this.canvas.width, this.canvas.height);
- if (this.transparent) {
+ if (passMode) {
+ context.clearColor(...this.passSupport.background(frame.pass));
+ } else if (this.transparent) {
context.clearColor(0, 0, 0, 0);
} else {
context.clearColor(0.145, 0.162, 0.177, 1);
@@@ -1864,17 -1735,23 +1864,25 @@@
for (const batch of this.batches) {
if (this.benchmark) {
this.drawBatch(batch, true);
- } else if (batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend') {
- this.drawAlphaBatch(batch, true, true);
+ } else if (this.drawsInOpaqueLoop(batch)) {
+ context.uniform1f(this.uniforms.renderPassObjectBase, objectBase);
+ objectBase += batch.instanceCount;
- this.drawAlphaBatch(batch, true);
++ // Object IDs are the instance ordinal, which culling and level selection renumber, so that pass draws every instance.
++ this.drawAlphaBatch(batch, true, passMode !== OBJECT_ID_PASS_MODE);
}
}
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
context.bindVertexArray(null);
- if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);
- if (!this.benchmark) this.drawBlendBatches(frame);
- if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);
+ if (passMode) {
+ this.passSupport.copyToCanvas();
+ } else if (!this.benchmark) {
+ this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);
+ this.drawBlendBatches(frame);
+ this.resolveFrame(frame, effects, environment, volume);
+ }
+ this.renderingPass = false;
+ this.endGpuTiming();
this.cpuMilliseconds = performance.now() - start;
}