/ghibli-threejs:threejs-webgl-performance-profilingfrom ghibli-threejs
Profiles and optimizes heavy three.js WebGL scenes with multi-pass rendering. Measures GPU timing via gl.finish and readPixels, toggles passes on/off, reports triangles per mesh, warms up shader compiles, and applies optimizations like shared shadows, LOD, adaptive resolution, and GLB compression.
Ships in ghibli-threejs. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A method, not a list of tricks: measure honestly, find the biggest cost, cut it without
visible loss, re-measure in the same session. Stack: three.js WebGLRenderer +
EffectComposer (vanilla or R3F), often with water pre-passes and post-processing.
Profile each render pass of
{{entry file}}with synchronous timing (gl.finish()then a 1-pixelreadPixelsof the default framebuffer, warm-up render first, median of ~12 runs) and list triangles per mesh (× instance count, with cast-shadow flag). Toggle each pass (AO, bloom, water, shadows, pixel ratio) on/off in alternating cycles. Cut the biggest costs without visible loss, then report before and after at the same size in the same session.
gl.finish() followed by a readPixels of the default
framebuffer. A readPixels(RGBA, UNSIGNED_BYTE) on a HalfFloat target is
INVALID_OPERATION, which silently gives you CPU-submit time only.frame() calls + gl.finish(), not
requestAnimationFrame — direct calls work in a hidden tab and give compile cost exactly.references/profile-passes.mjs.requestAnimationFrame stalls: tweens freeze and FPS reads 0.
Don't mistake that for a bug. An MCP/automation tab must be visible or an rAF-based
evaluate hangs.Emulation.setCPUThrottlingRate (4× for a mid phone, 2.5× for a budget laptop),
Network.emulateNetworkConditions (9 Mbps / 150 ms for 4G), a phone viewport, and an init
script that spoofs UNMASKED_RENDERER_WEBGL, hardwareConcurrency and deviceMemory so
the tier logic runs as it would there. Record time to ready, bytes by kind, longtask
entries and the program count (renderer.info.programs.length). Keep the old build on a
second port and interleave runs; single runs swing by seconds on a loaded machine.Log the top offenders after load (?stats flag):
const costs = []
scene.traverse(o => { if (o.isMesh) costs.push({ name:o.name || o.material.name,
triangles:(o.geometry.index?.count || o.geometry.attributes.position.count)/3*(o.count || 1), shadow:o.castShadow }) })
console.log(JSON.stringify(costs.sort((a, b) => b.triangles - a.triangles).slice(0, 15)))
The first bottleneck here was a 5k-triangle blob × 2000 instances. Also watch
renderer.info.render.calls/triangles per frame.
renderer.shadowMap.autoUpdate = false; set
shadowMap.needsUpdate = true once per frame before the pre-passes, so refraction,
reflection and main passes share it.renderer.info.programs.length. renderer.clippingPlanes
on a planar reflection gives every material a second, clipped program (about half of ~540
here); clip with an oblique near plane on the mirror camera instead (see
threejs-webgl-realistic-water). One variant, no per-pixel cost.computeBoundingSphere() + a pad (~.35 m for wind
sway) so frustum culling works on instanced foliage. Add coarse distance culling (every
0.25 s, radii matched to where fog is ~94 %).sparseGeometry(g, groupSize, stride) keeps every
n-th card group) past ~33 m, back under ~27 m (hysteresis), checked every 0.2 s. Choose
fur shell counts by distance (24/14/6/3/0).PointLight later recompiles every lit material on that frame.
Prefer one real point light that follows the nearest source over N lights.onBeforeCompile source share a program. If you
inject something only one material needs (a leaf-clearing discard), add a key such as
houseClip:true to its customProgramCacheKey, or the other material gets it too. The
reverse also holds: per-slot tint uniforms on otherwise identical materials keep one program.low | medium | high once, before anything is built, from the
unmasked GPU string (read on a throwaway context and hand it straight back with
WEBGL_lose_context: phones cap live contexts), hardwareConcurrency, deviceMemory
and touch. What worked: software renderers, ≤ 2 cores or ≤ 2 GB → low; phones (coarse
pointer, short screen side < 600 px) → low; tablets → medium on an Apple GPU with ≥ 4 GB,
else low; Intel UHD / HD / Iris, Mali, Adreno, PowerVR → low; Ryzen APUs and integrated
Arc → medium (low at ≤ 4 cores or ≤ 4 GB); Apple, NVIDIA, Radeon RX / Pro, discrete Arc →
high; unknown → medium. ?quality= forces one; show tier, GPU and compile time under
?debug. Knobs per tier (high / medium / low): pixel budget 4.2M / 1.4M / 0.78M, DPR cap
2 / 1.25 / 1, adaptive floor .70 / .55 / .40, AO and SMAA off on low, shadow map
2048 / 2048 / 1024, grass ×1 / 1 / .55, flowers ×1 / 1 / .85, meadow in the reflection on
high only, water grid 330 / 330 / 240 segments. Thin only where it doesn't show: the
flower carpet reads thin below ~.85, grass at .55 doesn't.ratio = min(devicePixelRatio, tier DPR, √(budget / (w·h)))
× the adaptive scale, so a 4K monitor is bounded too. On the high tier (not touch) never go
below min(1, ratio): a strong desktop keeps one rendered pixel per CSS pixel.avg = avg·.9 + ms·.1; ignore samples while
loading and frames ≤ 0 or > 1500 ms). Above 28 ms drop the scale ×0.9 after 90 samples and
10 s since the last change; above 45 ms (under ~22 fps) react fast: ×0.8 after 20 samples
and 2.5 s — waiting 180 frames at 5 fps is a minute of freeze. Floor = the tier's. Raise
+.05 below 18 ms, 30 s after the last change; reset on visibilitychange.localStorage, in try/catch)
and apply it by reloading with ?quality= — the tier is read before anything is built.
HD = the high tier with an 8.3M-pixel budget (up to DPR 2), a 4096 shadow map and adaptive
scaling off; Smooth = low.position.<head>: import map first (on minified builds), a modulepreload
per module in the graph, and a tiny inline script that fetch()es every GLB and JSON (see
threejs-cinematic-loading-screen); the scene later parses the buffers with
GLTFLoader.parseAsync, and DRACOLoader.preload() fetches the decoder alongside. Model
fetches started at 0.17 s instead of 1.5 s on a phone profile.webglcontextlost call preventDefault() (three re-uploads on
restore; re-render anything rendered once, e.g. the PMREM environment) and offer a reload
button if it has not come back after ~2.5 s. Catch the renderer constructor and say
"WebGL 2 is off or missing" on the loading screen instead of a frozen 0 %.The one-second hitch on the first dive under water was compilation, not render cost.
Make the render loop a named frame(); during load render one frame from the underwater
view and one from above before the loading screen lifts. Measured with ?nowarm: first dive
163 ms cold → 10 ms warmed.
Warm-up frames alone compile on the main thread, one program after another (~2.5 s for ~270
programs on an M-series Mac, far longer on Direct3D and phones, loading screen frozen). With
KHR_parallel_shader_compile, compile before the warm-up instead:
renderer.compile(group, camera, scene) in ~6 slices with a setTimeout(0) between,
then poll program.isReady() on the new entries of renderer.info.programs every 30 ms,
driving the progress bar. Without the extension skip this; the warm-up compiles as before.compile() walks the target scene's lights on every call, so one call per object is
quadratic (0.6 s at 4× CPU). A slice is a fake group over a share of scene.children:
{ traverse: fn => part.forEach(o => o.traverse(fn)), traverseVisible: () => {} }. If it
hands the lights over again, every variant is compiled for twice the lights.setRenderTarget) before compile():
programs drawn into a target are linear and untoned, a different variant from the screen.frame() renders nothing behind the opaque loading
screen and only streams work in (terrain chunks). Result here: 270 programs in parallel
before the warm-up plus 59 in it, against 436 one by one; the longest freeze on an
Android-like profile went 2.3 → 1.0 s.Without the extension the main thread still blocks for seconds while shaders compile at load — automation calls time out in that window; wait ~15 s before probing.
Frame ~20 ms at 2.5K; GTAO ≈ 8 ms at half-res (8 samples, 8 denoise samples); shadow pass
≈ 3.5 ms. Later gl.finish() timing put the composer at 8–18 ms and every other pass under
5 ms. Grass: 10 tris × 100k ≈ 1.0M; 163 shrubs ≈ 150k; a 290-culm bamboo grove ≈ 270k (+2 %).
readPixels, no gl.finish).frame(T) with T below the page clock gives a negative dt: fades run backwards (clear
weather wound up to 40 % rain). Capture at a clock above performance.now().three.module.min.js imports ./three.core.js (unminified): remap that URL to
three.core.min.js in the import map, and put the import map before any modulepreload.Report a before/after table: per-pass ms (median), fps median, draw calls, triangles, GLB MB, first-interaction hitch ms. Screenshot the same views before and after to prove "no visible loss".
references/profile-passes.mjs — Playwright script: median frame time with passes toggled.references/gpu-timing.js — in-page synchronous per-pass timer.threejs-headless-visual-verification · threejs-postprocessing-anime-grade · threejs-open-world-streaming · threejs-procedural-vegetation · threejs-blender-glb-pipeline · threejs-webgl-realistic-water · threejs-cinematic-loading-screen
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
31 skills in this plugin
/threejs-blender-glb-pipelineBuilds a reference-image-driven asset pipeline from headless Blender to GLB for a three.js scene — an asset contract (units, axes, grounding, required mesh/material names, budgets, attachment numbers), one parallel subagent per asset group writing craft_<slug>.py generators, preview renders compared against the reference, measured-bounding-box placement in the web scene, Draco compression, and a scored asset quality pass. Use when the user has a reference picture and wants a 3D scene from it, asks to model props/trees/characters in Blender for three.js, export GLBs, fix glTF export issues (vertex-colour alpha, UV flip, axes, custom normals), compress models, or rate and improve every asset in a scene./threejs-boat-buoyancy-steeringFloats a boat (or any buoyant prop) on three.js water with Gerstner waves generated from one JS table that feeds both the GLSL vertex shader and a CPU waveHeight(), four-probe heave/pitch/roll damped springs, an arc-length drift lane that bends round rocks, click-to-steer W/A/S/D rowing with momentum and drag, an autopilot that pursues the lane back, and a chase camera that keeps the orbit. Use when the user wants a drifting or steerable boat, buoyancy, objects bobbing on waves, Gerstner waves on a river/lake, a boat autopilot, or a follow/chase camera behind a vehicle on water./threejs-camera-guided-tourBuilds a hands-free guided camera tour for a three.js scene — keyframes as data, a time-parametrised Catmull-Rom (Hermite) path with continuous velocity, one camera-owner flag, the tour driving time of day and a day→night blend, staged creatures crossing the frame, handwritten captions, portrait-phone lens widening, instant hand-back on drag/scroll/tap/Esc, and a seek() hook for screenshots and video capture. Use when adding a tour mode, cinematic flythrough, attract mode, camera path animation, keyframed camera, spline camera or showcase video capture to a WebGL scene./threejs-cinematic-loading-screenBuilds a cinematic loading gate for a three.js scene — a painted CSS dawn (layered gradients, drifting blurred mist bands, optional conic god rays, SVG feTurbulence grain, vignette), a 2D-canvas layer of falling petals and glowing motes, a handwritten title that animates in, a gold progress line with stage captions, then "tap anywhere to enter" whose tap is the browser gesture that unlocks audio; uses a still captured from the live scene as the backdrop that cross-fades into the real render, and warms up shaders before lifting so the first interaction never stalls. Use when adding a loading screen, splash screen, intro curtain, preloader, tap-to-start / audio unlock gate or shader pre-compilation to a WebGL scene./threejs-day-cycle-lightingAnimates the sun in a three.js scene from sunrise to sunset through a single applySun(az, el) writer — azimuth sweep, elevation arc, warm-to-gold light colour, horizon falloff, warming sky dome and fog, re-aimed god rays and every sun-driven shader uniform — plus a cinematic "sun follows the lens" mode that keeps the sun beside the camera heading for backlit shots with boosted god rays and forward scattering. Use when adding a day/night cycle, time-of-day slider, sunrise/sunset, moving sun, backlit tour shots, or when several systems fight over the sun direction in WebGL/R3F./threejs-dreamy-glass-hudTurns a three.js scene's DOM overlay into one coherent, dreamlike HUD — a single frosted-glass material shared by every pill, badge and popover whose colours are registered CSS properties so the whole HUD cross-fades from pearl to deep indigo as the scene turns to night; an inline-SVG icon dock whose lit toggles glow gold instead of shouting; a glass popover in place of a native select; first-visit hints "whispered" in handwriting that step aside the moment the visitor understands; a HUD that drifts away after half a minute of stillness; a mote of light under each tap; a staggered arrival after the loading gate; and letterbox bars during a camera tour. Use when the overlay UI looks like a dev panel on top of a beautiful scene, when asked for a dreamy, cinematic, premium or 梦幻 / 绝美 UI, glassmorphism, a day/night-aware HUD, onboarding hints, auto-hiding UI, tap feedback, or to restyle lil-gui to match.npx claudepluginhub nicksonthc/ghibli-threejs --plugin ghibli-threejs