Threejs bridge

From Generous-Corp/pulp · View interactive version

Threejs bridge is an AI agent skill from the GitHub repository Generous-Corp/pulp. Build or iterate on Pulp's native Dawn-backed Three.js workflow using the real three.webgpu.js renderer, focused bridge tests, and native demo capture.

How to use this skill

Skill file

Three.js Bridge

Use this skill when a task involves Pulp's native Three.js bridge or the

examples/threejs-native-demo workflow.

Truthful Position

Pulp now supports a native Three.js lane built on:

Supported now:

Not supported by this skill:

Critical Build Requirements

  1. V8 engine required — Three.js needs typed arrays, promises, and full ES

module support. Use Pulp's pinned, sealed v8-builder provider; do not use a

Homebrew libnode for acceptance. Fetch the matched platform asset once and

enable the strict provider gate:

```bash

python3 tools/scripts/fetch_v8_for_release.py darwin-arm64

cmake -S . -B build -DPULP_JS_ENGINE=v8 \

-DPULP_VALIDATE_V8_PROVIDER_STRICT=ON \

-DPULP_ENABLE_GPU=ON -DPULP_BUILD_TESTS=ON

```

Verify the linked dylib and run the no-skip identity/capture gate before

trusting a local Three.js result:

```bash

otool -L build/examples/threejs-native-demo/pulp-threejs-native-demo | grep libv8

ctest --test-dir build -R '^v8_provider_identity_strict$' --output-on-failure

```

V8_DIR may select a baked sealed provider. The legacy V8_INCLUDE_DIR,

V8_LIB_DIR, and V8_LIBRARY_PATH overrides are for explicit local

experimentation only; results from Homebrew libnode are not acceptance

evidence because its external ICU/Abseil surface can collide with Skia.

  1. gpu_surface MUST be passed to WidgetBridge — The native GPU bridge only initializes when WidgetBridge receives a non-null GpuSurface pointer. Without it, Three.js gets no WebGPU device and the 3D canvas renders black. This is the attach_gpu_surface() call in the demo.
  1. Three.js defaults to the pinned FetchContent source —

PULP_ENABLE_THREEJS_RUNTIME follows the GPU default and sets

PULP_HAS_THREEJS after validating the complete runtime payload.

  1. Release and installed-SDK work must select the shipped runtime — GPU

SDKs publish the pinned resolver payload at share/pulp/threejs and expose

it through PULP_THREEJS_RUNTIME_DIR in PulpConfig.cmake. For an

installed-runtime proof, configure with

-DPULP_THREEJS_RUNTIME_DIR=$PULP_SDK_DIR/share/pulp/threejs; do not accept a

FetchContent cache or source-tree path as equivalent evidence. Configuration

fails when the WebGPU module, core modules, supported addons, license, or

package metadata is incomplete.

  1. Bind runtime demo fixtures at configure time — ccache may prefix-map

__FILE__ to a cache-owned diagnostic path. Files such as

demo.js.template must use a CMake-provided source-directory definition;

never derive runtime asset paths from __FILE__ or from the fetched

Three.js directory. The strict provider-identity cube gate must work from a

warm shared cache and an arbitrary build directory.

Failure Modes To Recognize

These three failures all present as "demo says status: 'ready' but the canvas is solid black/blank" — Three.js's renderer.init() uses new Promise(async (resolve, reject) => {…}) which silently swallows any throw inside the executor, so errors do NOT propagate as rejections. Whenever you see a black canvas, suspect one of these:

  1. createNativeAdapter / describeNativeAdapter missing from window.pulp.gpu (regression introduced by ad7175be7 in April 2026). web-compat-canvas.js's __ensurePulpGpuHelpers calls window.pulp.gpu.createNativeAdapter(); if undefined, the entire native bridge silently falls back to no-op mocks. Fix: keep the describeNativeAdapter / createNativeAdapter accessors in web-compat-document.js alongside the mock-adapter accessors, and keep the native-aware navigator.gpu.requestAdapter that prefers __describeNativeAdapterImpl over the mock.
  1. globalThis.requestAnimationFrame recursing on globalThis.window.requestAnimationFrame (RangeError: Maximum call stack size exceeded). In V8 the script-top var window = {…} becomes a property of globalThis, so a wrapper that lives on globalThis and calls globalThis.window.X resolves back to itself. Bind directly to the inner __requestFrame__ helper (or capture window.requestAnimationFrame once at install time and call that local).
  1. var depthStencil missing in the __createMockGPURenderPassEncoder closure in web-compat-gpu-buffered.js. encoder.draw / encoder.drawIndexed reference depthStencil to forward to createBufferedDrawPayload; if undeclared in the closure, the reference resolves as a free variable and throws ReferenceError as soon as the bridge is engaged. Add var depthStencil = descriptor.depthStencilAttachment || null; next to the other closure vars.
  1. Geometry arrives all-zero → the mesh collapses to a degenerate point. Three.js's WebGPUBackend uploads vertex/index buffers with createBuffer({mappedAtCreation:true}) → new T(buf.getMappedRange()).set(array) → buf.unmap(). The mock __createMockGPUBuffer in web-compat-document-gpu-mock.js previously returned _bytes.buffer.slice(...) from getMappedRange() (an independent COPY) with a no-op unmap(), so every mapped write was silently dropped — buffer._bytes stayed zero. The buffered-draw serializer ships buffer._bytes to native (web-compat-canvas-gpu.js), so the native draw received all-zero positions+indices and rasterized nothing while the render-pass clear still showed. Uniforms survived only because they use queue.writeBuffer, which writes _bytes directly. Fix: getMappedRange() hands back a standalone ArrayBuffer seeded from _bytes, records it, and unmap() copies each recorded range back into _bytes. Regression test: [webcompat][gpu][mock][issue-3217] round-trips a mappedAtCreation write through _bytes. Tell-tale: a render-pass clear color is visible but geometry is not, and a per-draw dump of the vertex/index buffer head bytes is all 00.
  1. JS-guessed bind-group layout silently mismatches Three's layout:"auto" pipeline → the vertex stage reads zeroed uniforms. The buffered path (__gpuQueueDrawBufferedImpl) used to build an EXPLICIT BindGroupLayout from visibility/types guessed in JS (web-compat-gpu-buffered.js inferVisibilityFromShaders regex-scans the WGSL), then create the pipeline with an explicit pipeline layout. Under the iOS-Sim skip_validation toggle, a layout mismatch does NOT raise an error — it just leaves bindings unfulfilled, so the vertex shader reads zero matrices and the cube degenerates even though every uniform byte uploaded correctly. Fix (mirrors the immediate __gpuQueueDrawImpl path): create the pipeline with layout = nullptr (auto), then build each bind group from pipeline.GetBindGroupLayout(group_index). This makes the layout come from the real shader interface. The same fix repaired Three's sRGB output-conversion/composite pass, which has the same bind-group shape (sampler + sampled texture_2d). Whenever you replay a serialized WebGPU pipeline, prefer auto layout + GetBindGroupLayout() over reconstructing the layout from a JS guess.

iOS AUv3 live-present gotchas

The iOS AUv3 GPU path (PulpMetalPluginView in core/view/platform/ios/plugin_view_host_ios.mm) is not on main — main routes iOS AUv3 to the CPU host — so it has no CI coverage. Hard-won facts:

Diagnosing tools:

Core Files

Main workflow files:

Bridge/runtime files often involved:

Truth/status docs to keep aligned:

Recommended Workflow

1. Keep the native path honest

Default to the real native stack:

If the task is about the original Phase 13 acceptance set, prefer extending the

existing native demo modes rather than inventing detached throwaway samples.

2. Build the narrowest targets first

cmake --build build --target pulp-threejs-native-demo pulp-test-threejs-bridge -j8

If the task is deeper in the bridge layer, also use the lower-level focused

proofs as needed:

./build/test/pulp-test-web-compat-prelude "[webcompat][canvas][gpu]"
./build/test/pulp-test-canvas-widget "[canvas_widget][gpu]"
./build/test/pulp-test-skia-surface "[render][skia][readback]"

3. Run the narrowest truthful test slice

Examples:

./build/test/pulp-test-threejs-bridge "[threejs][gpu][phase13]"
./build/test/pulp-test-threejs-bridge "[threejs][gpu][phase13][spectrum]"
./build/test/pulp-test-threejs-bridge "[threejs][gpu][phase13][particles]"
./build/test/pulp-test-threejs-bridge "[threejs][gpu][phase13][ribbon]"
./build/test/pulp-test-threejs-bridge "[threejs][gpu][phase13][reverb]"

For the full focused CTest slice, build the resource-test target first so

Catch2 does not leave a NOT_BUILT placeholder in the selected test set:

cmake --build build --target pulp-test-threejs-resources pulp-test-threejs-bridge pulp-threejs-native-demo -j8
ctest --test-dir build -R "threejs|Three.js|pulp_bundle_threejs_for_jsc_smoke" --output-on-failure

For release packaging work, also run the install-layout test from the configured

build and the release-content negative controls. The install-layout test creates

a separate find_package(Pulp) consumer and checks that the runtime resolves

inside the selected install prefix:

ctest --test-dir build -R '^pulp_install_layout$' --output-on-failure
python3 tools/scripts/test_release_artifact_contents.py

Do not rerun broad unrelated suites when a focused bridge/demo tag is enough.

4. Always capture the real native demo for visible changes

./build/examples/threejs-native-demo/pulp-threejs-native-demo --demo spectrum --capture /tmp/pulp-threejs-spectrum.png
./build/examples/threejs-native-demo/pulp-threejs-native-demo --demo particles --capture /tmp/pulp-threejs-particles.png
./build/examples/threejs-native-demo/pulp-threejs-native-demo --demo ribbon --capture /tmp/pulp-threejs-ribbon.png
./build/examples/threejs-native-demo/pulp-threejs-native-demo --demo reverb --capture /tmp/pulp-threejs-reverb.png

Use screenshots to confirm the result is visibly truthful, not just test-green.

Capture mode is also the CI/headless smoke path: --capture sets

WindowOptions::initially_hidden=true and exits before run_event_loop().

Keep future capture changes on that hidden path; do not add show() or

focus-stealing activation before the screenshot is written.

Engine/GPU identity: --print-engine-identity brings up a real V8

ScriptEngine + offscreen Dawn surface and prints a parseable

PULP_ENGINE_IDENTITY_BEGIN…END block (engine_type, runtime_version,

provider_kind, provider_path, pulp_has_v8, gpu_available, gpu_native_bridge,

gpu_backend, gpu_software). Use it to prove which V8 is linked (e.g. the

sealed v8-builder seal vs Homebrew libnode — see the engine skill's

sealed-provider (FindV8.cmake) section) and that the GPU is real hardware

(gpu_backend=Metal, gpu_software=0). The strict

v8_provider_identity_strict CTest (gated on

PULP_VALIDATE_V8_PROVIDER_STRICT) parses that block with no skip-pass and

then requires a non-empty --demo cube --capture PNG. It also compares the

printed runtime_version with PULP_V8_EXPECTED_RUNTIME_VERSION, which

PulpViewJsEngines.cmake parses from the manifest's V8 tag. After a V8 pin

bump, a build tree still linking the previous provider

fails this gate rather than passing, so reconfigure against the new provider

before reading a failure as a regression.

4a. A capture test that skips is not a capture test that passed

capture_test.cmake has two modes, and only one of them is evidence that the

capture works.

The default (tolerant) mode exists to guard against the demo hanging. If the

build has no V8, or the host has no native Dawn adapter, the binary prints an

explanatory line on stderr and exits 1, and the script reports

SKIP (tolerant mode): ... and stops without asserting the PNG. That is the

right behaviour for a lane that merely wants to know the demo terminates. Read a

green threejs_native_demo_*_no_hang result as "it did not hang", never as "it

rendered".

A CMake -P script that prints a marker and return()s exits 0, so CTest scores

it Passed unless the test carries SKIP_REGULAR_EXPRESSION — which is how a

skipped capture came to read as a successful one in the summary. Both tolerant

tests now set SKIP_REGULAR_EXPRESSION "SKIP \\(tolerant mode\\)", so

ctest prints ***Skipped and the two outcomes are distinguishable without

reading per-test stdout. Any new tolerant-return branch in capture_test.cmake

must print that same marker, or it silently becomes a pass again.

Configure with -DPULP_VALIDATE_CAPTURE_STRICT=ON on any lane where the capture

is genuinely expected to produce a PNG. That registers

threejs_native_demo_capture_strict and

threejs_native_demo_gltf_box_capture_strict, which pass REQUIRE_CAPTURE=ON

into the same script: both skip paths become FATAL_ERROR, so a missing V8 or a

missing native Dawn adapter fails instead of reporting success. They write their

own *-capture-strict.png files so a strict run cannot pass by finding a

tolerant run's leftover output, and they carry the capture-strict label. This

is the same opt-in shape as PULP_VALIDATE_V8_PROVIDER_STRICT, which

provider_identity_test.cmake uses for the same reason.

5. Prefer contract-driven bridge work

When something breaks, do not guess at generic browser APIs.

Instead:

That keeps the bridge aligned to real Three.js usage instead of drifting toward

an unfocused browser shim.

What To Check

For native Three.js work, verify:

For agent-readable correctness evidence, run:

pulp gpu probe --recipe threejs.multi-pass.v1 \
  --artifacts artifacts/gpu/threejs --json
pulp gpu probe --recipe threejs.multi-pass.v1 \
  --artifacts artifacts/gpu/threejs-mutated --negative-control --json

These commands require a build configured with V8 and the pinned Three.js

runtime. Other builds expose its metadata row as callable: false, while

omitting it from probe help, the callable registry, and the MCP probe enum.

Default standalone releases remain QuickJS-only; executing this recipe

there is follow-up work that must ship sealed V8 and preserve the nested runtime

through Rust self-upgrades.

The recipe loads the SDK's hash-verified pinned three.webgpu.js runtime

through V8 and the native Dawn bridge. It records background, intermediate,

and final RGBA readbacks plus an independent C++ color-region oracle. A valid

negative control keeps adapter acquisition, module initialization, rendering,

and readback successful while the final oracle fails with exit 1. Exit 2 means

V8, authentic hardware identity, or the pinned runtime was unavailable; it is

not acceptable proof of rendering correctness.

For the audio-reactive spectrum demo, VisualizationBridge::process() only

captures audio and meters on the realtime thread. The UI-side spectrum source

must call bridge.poll() before read_spectrum(); snapshot reads no longer run

FFT analysis implicitly. Keep that poll on the one UI owner so the demo cannot

accidentally introduce a second consumer of the bridge's SPSC capture stream.

When Updating Docs

Keep these in sync when the workflow meaningfully changes:

If the workflow grows stable enough for broader reuse, keep this skill aligned

with the actual shipped demo modes and focused validation commands.

Benchmark Mode

A4 DPR campaign producer

The A4 DPR matrix uses the dedicated, non-default

pulp-gpu-dpr-native-measurement target for the maintained

threejs-audio-reactive canary. Configure it with PULP_BENCHMARK=ON,

PULP_TRACING=ON, and V8, then pass the exact binary through

PULP_DPR_NATIVE_MEASUREMENT_BIN to

tools/scripts/gpu_dpr_pulp_native_adapter.py. The producer loads the pinned

three.webgpu.js and three.core.js bytes, verifies both digests, and renders

through the real native WebGPU canvas on the same WidgetBridge tree used for

the Pulp capture and input oracle.

Keep screenshot readbacks outside the steady timing loop. A readback can

finalize the Skia recording before SkiaSurface::end_frame() attaches its GPU

elapsed-time callback. gpu_render_time_ms() == 0 is the documented

no-sample sentinel, not a fast frame; the producer and evidence verifier must

both reject it. Only strictly positive, same-process GPU samples can make a

cell terminal.

Positive alone is not sufficient: the producer records an empirical timestamp

resolution and must distinguish five one-frame baseline trials from five trials

that sum eight frames of known work. Every metric declares

measured/derived/unavailable provenance. The frozen scenario supplies the

independent logical input point/target, fidelity uses two hashed same-content

captures plus numeric text/stroke observations, and adaptive mode records the

measured samples and actual scale transitions rather than echoing requested

metadata.

When PULP_BENCHMARK=ON, pulp-threejs-native-demo exposes a

headless benchmark that drives the JS→GPU upload path without a

visible window:

pulp-threejs-native-demo --benchmark-seconds=10 --widget=particles \
                         --particle-count=10000 --target-fps=60 \
                         --output=planning/bench/particles-N10000.json

The benchmark bypasses the full three.webgpu.js module loader and

calls __gpuQueueDrawBufferedImpl directly with a vertex-buffer

payload shaped like `THREE.BufferGeometry.setAttribute('position',

new THREE.BufferAttribute(new Float32Array(count * 3), 3))`. It

exercises the exact widget_bridge.cpp WriteBuffer path a real

Three.js particles scene would hit.

Gotchas:

depends on the native GPU bridge paths which are gated on

PULP_HAS_SKIA. If external/skia-build/ only contains include/

PULP_HAS_SKIA=FALSE and every native WebGPU call in

widget_bridge.cpp short-circuits on its `#ifndef PULP_HAS_SKIA

return false` guard. The benchmark harness detects this and fails

fast rather than emitting zero counters.

at status: 'starting' headless on some hosts** (module runs to

completion with empty error, but top-level state never transitions

to 'ready'). The benchmark works around this by using a minimal

JS harness; the in-window demo may still hit the hang when invoked

headlessly via --capture. If that happens, fix the loader, don't

paper over it in the harness.

that counter only fires on the __gpuComputeDispatchImpl

bufferDataBase64 lane, not the vertex-buffer lane. Don't

read a zero there as a bug.

Zero-Copy Decision Status

The zero-copy JS↔GPU decision was evaluated twice:

  1. The first pass measured ui-preview's oscilloscope + spectrogram —

wrong workload, C++-driven, never exercises the upload path.

  1. The follow-up benchmark measured Three.js particles — honest

workload, 0.036% → 0.26% of frame budget at 1K → 100K points.

Both landed NO-GO; the particle benchmark supersedes the earlier verdict. See

planning/zero-copy-decision-1-re-evaluation-2026-04-20.md. The

new PerfCounters fields (base64_decode_total_us,

gpu_buffer_upload_count, gpu_buffer_bytes_resident_peak) stay

merged for future workload-specific re-evaluations.

JSC iOS lane

Before invoking threejs.multi-pass.v1, inspect it with `pulp gpu recipes show

threejs.multi-pass.v1 --json`. The canonical row remains discoverable on

QuickJS, but callable:false is expected unless the matched native build has

both V8 and the pinned Three.js runtime. Do not treat catalog presence or an

installed runtime directory as callable capability; only the native registry

controls pulp gpu probe and its MCP enum.

Pulp ships Three.js inside an AUv3 .appex on iOS via JSC (system framework, no V8 build). The full bring-up is in planning/2026-05-29-ios-d3b-threejs-webgpu-program.md.

Path summary:

Perf delta vs V8 macOS:

Don't reach for V8 on iOS unless a measurable feature gap surfaces — the build is 3-5h, needs Chromium depot_tools + 50GB workspace, and JSC's jitless interpreter already clears the bar.

The presentable flag is the load-bearing signal that distinguishes a real swapchain-backed canvas from a silent offscreen texture. Both __gpuCanvasConfigureImpl and __gpuCanvasDescribeCurrentTextureImpl surface it. If a JSC-backed Three.js demo shows a black editor pane, grep the log for presentable=false before debugging anything else.

OrbitControls on the iOS JSC lane (touch orbit/pinch)

The macOS native demo imports OrbitControls from three/addons (ESM). The iOS lane runs the IIFE bundle, which does NOT include addons by default. To ship OrbitControls on iOS:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.