depthview-mcp 0.2.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -3
- package/dist/cli.js +1008 -1333
- package/dist/probe.js +782 -0
- package/package.json +5 -7
- package/skill/SKILL.md +558 -57
- package/skill/references/award-sites.md +175 -0
- package/skill/references/extension-ui.md +190 -0
- package/skill/references/modeling.md +198 -0
- package/skill/references/particles.md +137 -0
- package/skill/references/performance.md +114 -0
- package/skill/references/r3f.md +151 -0
- package/skill/references/rendering.md +150 -0
- package/skill/references/shaders.md +200 -0
- package/skill/references/site-build.md +288 -0
- package/skill/references/threejs.md +387 -0
- package/skill/references/visual-qa.md +152 -0
- package/skill/references/volumetrics.md +165 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# three.js, as it is now (checked against r187)
|
|
2
|
+
|
|
3
|
+
What changed in three.js while most tutorials stood still, and the set-up that is right today.
|
|
4
|
+
Taken from the three.js manual and the API documentation of r187. **For anything not here, or
|
|
5
|
+
on another version, ask `three_docs`**: it reads the documentation out of the three.js package
|
|
6
|
+
the project has installed, so the answer is for that version. A name it cannot find does not
|
|
7
|
+
exist in this version: do not write it.
|
|
8
|
+
|
|
9
|
+
## Names that are gone or going (do not write these)
|
|
10
|
+
|
|
11
|
+
| Old | Now | Since |
|
|
12
|
+
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ----- |
|
|
13
|
+
| `THREE.Clock` | `THREE.Timer`: `timer.update(now)` once per frame, then `getDelta()` / `getElapsed()` | r183 |
|
|
14
|
+
| `PCFSoftShadowMap` | `PCFShadowMap` (the default; soft through `light.shadow.radius`). The old name warns and falls back | r186 |
|
|
15
|
+
| `RGBELoader` | `HDRLoader` (`three/addons/loaders/HDRLoader.js`) | r180 |
|
|
16
|
+
| `iridescenceThicknessRange` | `iridescenceThicknessMinimum`, `iridescenceThicknessMaximum` | r187 |
|
|
17
|
+
| `renderer.outputEncoding`, `sRGBEncoding` | `renderer.outputColorSpace = SRGBColorSpace` (the default), `texture.colorSpace` | r152 |
|
|
18
|
+
| `physicallyCorrectLights`, `useLegacyLights` | Nothing: light units are always physical | r155+ |
|
|
19
|
+
| `encodings_fragment` (shader chunk) | `colorspace_fragment` | r154 |
|
|
20
|
+
| `BufferGeometryUtils.mergeBufferGeometries` | `mergeGeometries` | r151 |
|
|
21
|
+
| `PostProcessing` (WebGPU) | `RenderPipeline` | r18x |
|
|
22
|
+
| `examples/jsm/...` in an import | `three/addons/...` | |
|
|
23
|
+
| A `<script>` tag for three.min.js, `THREE.OrbitControls` on the global | ES modules: `import * as THREE from 'three'`, add-ons from `three/addons/` | |
|
|
24
|
+
| WebGL 1 | Not supported | r163 |
|
|
25
|
+
|
|
26
|
+
## The renderer, set up right
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
import * as THREE from 'three';
|
|
30
|
+
|
|
31
|
+
const renderer = new THREE.WebGLRenderer({
|
|
32
|
+
canvas,
|
|
33
|
+
antialias: true, // false when an EffectComposer draws the scene: give its target `samples`
|
|
34
|
+
powerPreference: 'high-performance',
|
|
35
|
+
});
|
|
36
|
+
renderer.toneMapping = THREE.AgXToneMapping; // default is NoToneMapping: highlights clip
|
|
37
|
+
renderer.toneMappingExposure = 1;
|
|
38
|
+
renderer.shadowMap.enabled = true; // type defaults to PCFShadowMap
|
|
39
|
+
// outputColorSpace is SRGBColorSpace already. ColorManagement is on already.
|
|
40
|
+
|
|
41
|
+
renderer.setAnimationLoop(frame); // not requestAnimationFrame: the docs advise this one
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Constructor defaults worth knowing: `antialias: false`, `alpha: false`,
|
|
45
|
+
`premultipliedAlpha: true`, `stencil: false`, `depth: true`, `preserveDrawingBuffer: false`,
|
|
46
|
+
`powerPreference: 'default'`, `logarithmicDepthBuffer: false`, `reversedDepthBuffer: false`
|
|
47
|
+
(needs `EXT_clip_control`; the logarithmic buffer is ignored when it is on),
|
|
48
|
+
`outputBufferType: UnsignedByteType` (`HalfFloatType` for HDR output).
|
|
49
|
+
|
|
50
|
+
Tone mapping constants: `NoToneMapping` (default), `LinearToneMapping`, `ReinhardToneMapping`,
|
|
51
|
+
`CineonToneMapping`, `ACESFilmicToneMapping`, `AgXToneMapping`, `NeutralToneMapping`,
|
|
52
|
+
`CustomToneMapping`. ACES bends hues (an orange turns red): for a product whose colour matters
|
|
53
|
+
use `NeutralToneMapping`; for a natural film roll-off `AgXToneMapping`.
|
|
54
|
+
|
|
55
|
+
Shadow map types: `BasicShadowMap`, `PCFShadowMap` (default), `VSMShadowMap` (every receiver
|
|
56
|
+
also casts).
|
|
57
|
+
|
|
58
|
+
### Size and pixel ratio
|
|
59
|
+
|
|
60
|
+
The manual's pattern: CSS decides the size of the canvas, the code makes the drawing buffer
|
|
61
|
+
match it, and only when it changed.
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
function resize() {
|
|
65
|
+
const dpr = Math.min(window.devicePixelRatio, 2); // above 2 the eye gains nothing
|
|
66
|
+
const w = canvas.clientWidth;
|
|
67
|
+
const h = canvas.clientHeight;
|
|
68
|
+
renderer.setPixelRatio(dpr);
|
|
69
|
+
renderer.setSize(w, h, false); // false: leave the CSS size to the stylesheet
|
|
70
|
+
composer?.setPixelRatio(dpr);
|
|
71
|
+
composer?.setSize(w, h);
|
|
72
|
+
camera.aspect = w / h;
|
|
73
|
+
camera.updateProjectionMatrix();
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- The manual prefers multiplying the size yourself (`setSize(w * dpr, h * dpr, false)`) over
|
|
78
|
+
`setPixelRatio`, because then `canvas.width` is exactly what you asked for (it matters for
|
|
79
|
+
`gl_FragCoord`, reading pixels, 2D copies). Either way: **every render target and every
|
|
80
|
+
composer must be sized in the same pixels as the canvas.**
|
|
81
|
+
- Fractional OS scaling makes `devicePixelRatio` lie upwards. Cap the pixel count too:
|
|
82
|
+
if `w * h * dpr²` is over about 3840 × 2160, scale both sides by
|
|
83
|
+
`Math.sqrt(max / count)`.
|
|
84
|
+
- A canvas is `display: inline` by default and leaves a gap under it: `display: block`.
|
|
85
|
+
- The visible height at a distance is `2 * Math.tan(fov / 2) * distance` (fov in radians).
|
|
86
|
+
To keep objects the same size when the window height changes, change `fov`, not the position.
|
|
87
|
+
|
|
88
|
+
## Colour (the manual's rules)
|
|
89
|
+
|
|
90
|
+
- Working space is Linear-sRGB; output is sRGB. `ColorManagement.enabled` is `true` by default.
|
|
91
|
+
- Hex and CSS colours given to `Color` are converted from sRGB for you
|
|
92
|
+
(`new Color('#808080').r` is `0.214`). Setting `.r .g .b` directly is linear, never converted.
|
|
93
|
+
- Colour textures (`map`, `emissiveMap`, `sheenColorMap`, `specularColorMap`): PNG and JPEG
|
|
94
|
+
need `texture.colorSpace = THREE.SRGBColorSpace`. `GLTFLoader` sets it; `TextureLoader` does
|
|
95
|
+
not.
|
|
96
|
+
- Everything else (`normalMap`, `roughnessMap`, `metalnessMap`, `aoMap`, `bumpMap`,
|
|
97
|
+
`alphaMap`, `displacementMap`): leave `NoColorSpace` (the default).
|
|
98
|
+
- HDR and EXR files are `LinearSRGBColorSpace` and may hold values above 1.
|
|
99
|
+
- A `ShaderMaterial` does its own output conversion: end `main()` with
|
|
100
|
+
`#include <tonemapping_fragment>` and `#include <colorspace_fragment>`.
|
|
101
|
+
- With post-processing the conversion needs `OutputPass`, once, at the end.
|
|
102
|
+
- A whole scene too dark: the conversion to sRGB is missing. Too pale: it happened twice.
|
|
103
|
+
More light does not fix either.
|
|
104
|
+
|
|
105
|
+
## Lights (units and cost)
|
|
106
|
+
|
|
107
|
+
| Light | Constructor defaults | Notes |
|
|
108
|
+
| ------------------ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
109
|
+
| `AmbientLight` | `(0xffffff, 1)` | No direction: it only lifts the darks. Not lighting |
|
|
110
|
+
| `HemisphereLight` | `(sky, ground, 1)` | Sky colour from above, ground from below. A fill, with another light |
|
|
111
|
+
| `DirectionalLight` | `(0xffffff, 1)` | Parallel rays from `position` towards `target`. Rotation does nothing. Add `light.target` to the scene when you move it |
|
|
112
|
+
| `PointLight` | `(0xffffff, 1, distance 0, decay 2)` | Intensity in **candela**. Leave `decay` at 2. Tens to hundreds for a room-size scene, not 1 |
|
|
113
|
+
| `SpotLight` | `(0xffffff, 1, distance 0, angle π/3, penumbra 0, decay 2)` | Candela. `angle` at most π/2. `penumbra` 0 is a hard disc, 1 fades from the centre |
|
|
114
|
+
| `RectAreaLight` | `(0xffffff, 1, width 10, height 10)` | Standard and Physical materials only, **no shadows**. Call `RectAreaLightUniformsLib.init()` (`three/addons/lights/RectAreaLightUniformsLib.js`) or it looks wrong. Aimed by rotation, no target |
|
|
115
|
+
|
|
116
|
+
Every light is paid for on every lit pixel. Three or four, plus an environment.
|
|
117
|
+
|
|
118
|
+
## Shadows (from the manual)
|
|
119
|
+
|
|
120
|
+
- A shadow map is the scene drawn again from the light: one extra pass per shadow light,
|
|
121
|
+
**six for a point light**. One shadow-casting light is the usual budget.
|
|
122
|
+
- `DirectionalLight` shadow camera defaults: an orthographic box `-5..5` wide and high,
|
|
123
|
+
`near 0.5`, `far 500`. `shadow.mapSize` defaults to 512 × 512 (powers of two; the limit is
|
|
124
|
+
`renderer.capabilities.maxTextureSize`). The map is stretched over the box: **make the box
|
|
125
|
+
as small as the casters allow**, then raise the map size, not the other way round.
|
|
126
|
+
After changing the box: `light.shadow.camera.updateProjectionMatrix()`.
|
|
127
|
+
- `SpotLight`: the shadow camera's field of view follows `angle`; set only `near`, `far`,
|
|
128
|
+
`mapSize`.
|
|
129
|
+
- `LightShadow`: `bias 0`, `normalBias 0`, `radius 1` (blur; not with `BasicShadowMap`),
|
|
130
|
+
`blurSamples 8` (VSM), `intensity 1` (0 to 1: how dark the shadow is), `autoUpdate true`.
|
|
131
|
+
- See the box: `scene.add(new THREE.CameraHelper(light.shadow.camera))`.
|
|
132
|
+
- A **fake shadow** is often better and nearly free: a plane just above the ground with a soft
|
|
133
|
+
dark texture, `transparent: true`, `depthWrite: false`, fading as the object lifts.
|
|
134
|
+
- Forgetting `renderer.shadowMap.enabled = true` is the classic lost afternoon.
|
|
135
|
+
|
|
136
|
+
## Materials
|
|
137
|
+
|
|
138
|
+
Cost, cheapest first: Basic, Lambert, Phong, Standard, Physical. Use the cheapest that gives
|
|
139
|
+
the look, and Physical only where one of its extras is wanted.
|
|
140
|
+
|
|
141
|
+
`MeshStandardMaterial` defaults: `roughness 1`, `metalness 0`, `envMapIntensity 1`,
|
|
142
|
+
`normalScale (1, 1)`, `aoMapIntensity 1`, `displacementScale 1`, `flatShading false`.
|
|
143
|
+
"For best results always specify an environment map."
|
|
144
|
+
|
|
145
|
+
`MeshPhysicalMaterial` adds (all off by default, each one costs when on):
|
|
146
|
+
|
|
147
|
+
| Property | Default | What it is |
|
|
148
|
+
| ----------------------------------------- | ----------- | ------------------------------------------------------------- |
|
|
149
|
+
| `clearcoat`, `clearcoatRoughness` | 0, 0 | A lacquer layer: car paint, wet surfaces, carbon |
|
|
150
|
+
| `transmission` | 0 | Real see-through with refraction. Keep `opacity` at 1 with it |
|
|
151
|
+
| `thickness` | 0 | 0 is a thin wall (no bending). Scene units |
|
|
152
|
+
| `ior` | 1.5 | 1.0 to 2.333 |
|
|
153
|
+
| `attenuationColor`, `attenuationDistance` | white, ∞ | Tint that deepens with thickness |
|
|
154
|
+
| `dispersion` | 0 | Rainbow split at edges. Transmissive objects only |
|
|
155
|
+
| `sheen`, `sheenRoughness`, `sheenColor` | 0, 1, black | Cloth |
|
|
156
|
+
| `iridescence`, `iridescenceIOR` | 0, 1.3 | Soap film, oil |
|
|
157
|
+
| `anisotropy`, `anisotropyRotation` | 0, 0 | Brushed metal. **Needs tangents** (see below) |
|
|
158
|
+
| `specularIntensity`, `specularColor` | 1, white | Reflection strength of non-metals |
|
|
159
|
+
| `reflectivity` | 0.5 | No effect at `metalness: 1` |
|
|
160
|
+
|
|
161
|
+
- `renderer.transmissionResolutionScale` (default 1): lower it when transmission is too slow.
|
|
162
|
+
- Transmissive objects are drawn after the opaque ones, reading a copy of what is behind
|
|
163
|
+
them. **They do not see each other, nor transparent objects.** A liquid inside a glass
|
|
164
|
+
bottle is therefore an opaque (or alpha-tested) body, not a second transmissive one.
|
|
165
|
+
- `anisotropy` without a `tangent` attribute derives tangents from the UVs; where the UVs
|
|
166
|
+
collapse (the centre of a lathe or disc, a pole) the result is not a number, and bloom
|
|
167
|
+
spreads that pixel into a white blob. `geometry.computeTangents()` or no anisotropy.
|
|
168
|
+
- `roughnessMap` and `metalnessMap` **multiply** `roughness` and `metalness`. With a map,
|
|
169
|
+
set the property to 1, or the surface comes out shinier than the map says.
|
|
170
|
+
- `aoMap` reads the red channel and needs a second UV set.
|
|
171
|
+
|
|
172
|
+
What cannot change after a material was first drawn without `material.needsUpdate = true`
|
|
173
|
+
(a recompile, a hitch): adding or removing a texture, `flatShading`, `fog`, `vertexColors`,
|
|
174
|
+
`transparent`, `alphaTest`, `side`, the number of lights. Swap a texture for another freely.
|
|
175
|
+
To avoid the hitch keep a 1 × 1 white texture, a zero-intensity light, zero-density fog in
|
|
176
|
+
place from the start.
|
|
177
|
+
|
|
178
|
+
## Textures
|
|
179
|
+
|
|
180
|
+
- GPU memory is `width × height × 4 × 1.33` bytes whatever the file weighs: a 3024 × 3761
|
|
181
|
+
JPEG of 157 kB takes 60 MB. Small in pixels, not only in bytes.
|
|
182
|
+
- `minFilter` default `LinearMipmapLinearFilter` is the smooth one; `NearestFilter` and
|
|
183
|
+
`LinearFilter` skip the mipmaps and shimmer in the distance.
|
|
184
|
+
- `wrapS`, `wrapT` default to `ClampToEdgeWrapping`. `repeat` only shows with
|
|
185
|
+
`RepeatWrapping`. Changing a wrap mode after first use needs `texture.needsUpdate = true`.
|
|
186
|
+
- `rotation` turns around `center` (default `0, 0`, the corner): set `center` to `0.5, 0.5`.
|
|
187
|
+
- A `CanvasTexture` is the way to make text, gradients, noise and labels in code. Set
|
|
188
|
+
`needsUpdate = true` after drawing into its canvas again.
|
|
189
|
+
- Wait for several files with one `LoadingManager` (`onProgress(url, loaded, total)`,
|
|
190
|
+
`onLoad`): that is the real progress number for a loading screen.
|
|
191
|
+
|
|
192
|
+
## Camera
|
|
193
|
+
|
|
194
|
+
- `near` and `far` share the depth buffer's precision, most of it close to `near`. `near` as
|
|
195
|
+
far out and `far` as close in as the scene allows; a tiny `near` is what z-fighting is.
|
|
196
|
+
- `logarithmicDepthBuffer` fixes it at a cost in speed; a last resort.
|
|
197
|
+
- After `fov`, `aspect`, `near`, `far` or `zoom`: `camera.updateProjectionMatrix()`.
|
|
198
|
+
- `camera.setViewOffset(fullW, fullH, x, y, w, h)` slides the picture inside the frame
|
|
199
|
+
without changing the perspective: the way to put the subject on one side of the screen.
|
|
200
|
+
`clearViewOffset()` undoes it.
|
|
201
|
+
|
|
202
|
+
## Fog and backgrounds
|
|
203
|
+
|
|
204
|
+
- `Fog(color, near, far)` is linear and lets you choose where it starts; `FogExp2(color,
|
|
205
|
+
density)` is closer to air. **Fog only colours what is drawn**: set the background to the
|
|
206
|
+
same colour or the fog ends in a visible edge.
|
|
207
|
+
- `material.fog = false` keeps one object clear (a sky, a backdrop).
|
|
208
|
+
- `scene.background`: a `Color`, a texture, a cube map, or an equirectangular picture
|
|
209
|
+
(`texture.mapping = THREE.EquirectangularReflectionMapping`). `backgroundBlurriness` (0 to
|
|
210
|
+
1), `backgroundIntensity`, `backgroundRotation`.
|
|
211
|
+
- `scene.environment` lights every physical material that has no `envMap` of its own.
|
|
212
|
+
`environmentIntensity`, `environmentRotation` (radians).
|
|
213
|
+
- A background that post-processing must affect has to be drawn by three.js; a CSS
|
|
214
|
+
background behind a canvas with `alpha: true` is not.
|
|
215
|
+
|
|
216
|
+
## Environment maps without a file
|
|
217
|
+
|
|
218
|
+
```js
|
|
219
|
+
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
|
|
220
|
+
const pmrem = new THREE.PMREMGenerator(renderer);
|
|
221
|
+
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
|
|
222
|
+
pmrem.dispose(); // the texture it returned stays yours
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
`fromScene(scene, sigma = 0, near = 0.1, far = 100, { size = 256, position })`: any scene of
|
|
226
|
+
bright panels becomes a studio. `fromEquirectangular(texture)` for an HDR picture
|
|
227
|
+
(`HDRLoader`). The result belongs to the caller; `dispose()` it when replaced.
|
|
228
|
+
|
|
229
|
+
## Geometry (what is built in)
|
|
230
|
+
|
|
231
|
+
Solids: `BoxGeometry`, `SphereGeometry`, `CylinderGeometry`, `ConeGeometry`,
|
|
232
|
+
`CapsuleGeometry(radius 1, height 1, capSegments 4, radialSegments 8, heightSegments 1)`,
|
|
233
|
+
`TorusGeometry`, `TorusKnotGeometry(radius 1, tube 0.4, tubularSegments 64, radialSegments 8,
|
|
234
|
+
p 2, q 3)`, `IcosahedronGeometry(radius 1, detail 0)`, `OctahedronGeometry`,
|
|
235
|
+
`DodecahedronGeometry`, `TetrahedronGeometry`, `PolyhedronGeometry`.
|
|
236
|
+
|
|
237
|
+
Made from a drawing:
|
|
238
|
+
|
|
239
|
+
- `LatheGeometry(points, segments = 12, phiStart = 0, phiLength = 2π)`: a `Vector2` profile
|
|
240
|
+
(x is the radius, greater than 0; y the height) turned round the y axis. Bottles, glasses,
|
|
241
|
+
vases, knobs, columns, rings.
|
|
242
|
+
- `ExtrudeGeometry(shapes, { depth 1, steps 1, bevelEnabled true, bevelThickness 0.2,
|
|
243
|
+
bevelSize bevelThickness − 0.1, bevelOffset 0, bevelSegments 3, curveSegments 12,
|
|
244
|
+
extrudePath })`: a 2D outline given depth, with a real bevel. Extrudes along +z. No bevel
|
|
245
|
+
along an `extrudePath`. It is the base of `TextGeometry`.
|
|
246
|
+
- `TubeGeometry(path, tubularSegments 64, radius 1, radialSegments 8, closed false)`: a
|
|
247
|
+
circle carried along a curve. Cables, pipes, ribbons, handles.
|
|
248
|
+
- `ShapeGeometry`: a flat outline, triangulated.
|
|
249
|
+
- Add-ons: `RoundedBoxGeometry(width 1, height 1, depth 1, segments 2, radius 0.1)`,
|
|
250
|
+
`TextGeometry` (needs a `FontLoader` typeface JSON; its own defaults are huge: `size 100`,
|
|
251
|
+
`depth 50`), `ParametricGeometry`, `ConvexGeometry`, `DecalGeometry(mesh, position,
|
|
252
|
+
orientation, size)`, `TeapotGeometry`, `LoftGeometry`.
|
|
253
|
+
|
|
254
|
+
Lines only: `EdgesGeometry(geometry, thresholdAngle)`, `WireframeGeometry`.
|
|
255
|
+
|
|
256
|
+
Segments are the trade: a 24 × 10 sphere and a 50 × 50 one look the same once smooth-shaded;
|
|
257
|
+
a silhouette close to the camera needs 64 and up, a plane needs 1 unless it is deformed.
|
|
258
|
+
|
|
259
|
+
### Your own geometry
|
|
260
|
+
|
|
261
|
+
- A vertex is position **and** normal **and** uv together. Where any one differs (a hard
|
|
262
|
+
edge, a texture seam) the position is there twice. That is why a cube has 24 vertices.
|
|
263
|
+
- `computeVertexNormals()` smooths over shared vertices only: at a seam (the closing edge of
|
|
264
|
+
a cylinder or lathe) it leaves a visible line. Fix: `BufferGeometryUtils.mergeVertices`
|
|
265
|
+
first (after `deleteAttribute('uv')` if the UVs are not needed), or write the normals.
|
|
266
|
+
- `BufferGeometryUtils` (`three/addons/utils/BufferGeometryUtils.js`):
|
|
267
|
+
`mergeGeometries(geometries, useGroups = false)` (null when attributes do not match),
|
|
268
|
+
`mergeVertices(geometry, tolerance = 1e-4)`, `toCreasedNormals(geometry, creaseAngle =
|
|
269
|
+
π/3)` (smooth below the angle, hard above: bevel-free hard edges that still shade well).
|
|
270
|
+
- Buffers cannot grow. Allocate for the largest case and use `setDrawRange`, or make a new
|
|
271
|
+
geometry and `dispose()` the old one.
|
|
272
|
+
- After changing an attribute: `attribute.needsUpdate = true`, and
|
|
273
|
+
`computeBoundingSphere()` / `computeBoundingBox()` or culling uses the old shape.
|
|
274
|
+
- An attribute that changes every frame: `attribute.setUsage(THREE.DynamicDrawUsage)`.
|
|
275
|
+
|
|
276
|
+
## Many objects
|
|
277
|
+
|
|
278
|
+
- Every `Mesh` is a draw call. Hundreds of the same shape: `InstancedMesh(geometry,
|
|
279
|
+
material, count)`, `setMatrixAt(i, matrix)`, `setColorAt(i, color)`, then
|
|
280
|
+
`instanceMatrix.needsUpdate = true` (and `instanceColor.needsUpdate`), then
|
|
281
|
+
`computeBoundingSphere()` or the whole set is culled as if it sat at the origin.
|
|
282
|
+
- Different shapes, one material: `BatchedMesh(maxInstanceCount, maxVertexCount,
|
|
283
|
+
maxIndexCount, material)`, `addGeometry()` returns an id, `addInstance(id)` another.
|
|
284
|
+
- Static and never moving apart: `mergeGeometries` into one mesh, colours as a `color`
|
|
285
|
+
attribute with `vertexColors: true`.
|
|
286
|
+
- Moving between whole arrangements: morph targets (`geometry.morphAttributes.position`,
|
|
287
|
+
`mesh.morphTargetInfluences`).
|
|
288
|
+
- Points on a surface (scatter, particles that form a shape): `MeshSurfaceSampler`
|
|
289
|
+
(`three/addons/math/MeshSurfaceSampler.js`): `new MeshSurfaceSampler(mesh).build()`, then
|
|
290
|
+
`sample(position, normal)`.
|
|
291
|
+
|
|
292
|
+
## Curves and motion maths
|
|
293
|
+
|
|
294
|
+
- `CatmullRomCurve3(points, closed = false, curveType = 'centripetal', tension = 0.5)`.
|
|
295
|
+
`getPoint(t)` follows the curve's own parameter: points bunch up between close keys.
|
|
296
|
+
`getPointAt(u)` is even along the length. A camera path keyed by scroll wants `getPoint`
|
|
297
|
+
with `t` taken from the key spacing; a train on a track wants `getPointAt`.
|
|
298
|
+
- `MathUtils.damp(x, y, lambda, dt)`: the frame-rate independent ease towards a target.
|
|
299
|
+
`lambda` 3 to 6 for a camera. Also `lerp`, `clamp`, `mapLinear`, `smoothstep(x, min, max)`,
|
|
300
|
+
`smootherstep`, `degToRad`.
|
|
301
|
+
- `Timer`: `timer.connect(document)` stops time while the tab is hidden, so nothing jumps
|
|
302
|
+
when the visitor comes back. `timer.update(timestamp)` once per frame.
|
|
303
|
+
|
|
304
|
+
## Transparency (the manual's summary: "perfect transparency is hard")
|
|
305
|
+
|
|
306
|
+
- Objects are sorted back to front, triangles are not. A see-through object drawn
|
|
307
|
+
double-sided loses back faces at some angles: draw it twice, `BackSide` first then
|
|
308
|
+
`FrontSide`.
|
|
309
|
+
- `depthWrite: false` for glows, shadows planes, particles: nothing behind them is cut.
|
|
310
|
+
- Cut-outs (leaves, lettering, grilles): `alphaTest: 0.5`, opaque, no sorting at all. With
|
|
311
|
+
MSAA add `alphaToCoverage: true` for smooth edges.
|
|
312
|
+
- `renderOrder` forces an order when sorting by distance picks the wrong one.
|
|
313
|
+
|
|
314
|
+
## Post-processing (WebGLRenderer)
|
|
315
|
+
|
|
316
|
+
```js
|
|
317
|
+
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
|
|
318
|
+
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
|
|
319
|
+
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
|
|
320
|
+
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
|
|
321
|
+
|
|
322
|
+
const target = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, samples: 4 });
|
|
323
|
+
const composer = new EffectComposer(renderer, target);
|
|
324
|
+
composer.addPass(new RenderPass(scene, camera));
|
|
325
|
+
composer.addPass(new UnrealBloomPass(new THREE.Vector2(1, 1), 0.15, 0.5, 1.1)); // strength, radius, threshold
|
|
326
|
+
composer.addPass(new OutputPass()); // tone mapping + sRGB, once, here
|
|
327
|
+
// passes that need sRGB input (FXAAPass, a grain or vignette ShaderPass) go after OutputPass
|
|
328
|
+
composer.render(dt);
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
- The composer swaps two targets; the last enabled pass draws to the screen. Without
|
|
332
|
+
`OutputPass` the picture is linear and untone-mapped: dark and harsh.
|
|
333
|
+
- `SMAAPass` works on linear colour: before `OutputPass`. `FXAAPass` on sRGB: after.
|
|
334
|
+
- `UnrealBloomPass` needs tone mapping set on the renderer. Threshold at or above 1 so only
|
|
335
|
+
light brighter than white glows.
|
|
336
|
+
- Passes that exist: `GTAOPass(scene, camera, width, height)` (ambient occlusion),
|
|
337
|
+
`BokehPass` (depth of field: `focus`, `aperture 0.025`, `maxblur 1`), `SSRPass`,
|
|
338
|
+
`TAARenderPass`, `SSAARenderPass`, `OutlinePass`, `FilmPass`, `LUTPass`, `HalftonePass`,
|
|
339
|
+
`RenderPixelatedPass`, `AfterimagePass`, `RenderTransitionPass`, `GlitchPass`, `ShaderPass`
|
|
340
|
+
(your own: `tDiffuse` is the picture so far).
|
|
341
|
+
- `composer.setSize` and `setPixelRatio` on every resize.
|
|
342
|
+
|
|
343
|
+
## WebGPU and TSL (what the manual says)
|
|
344
|
+
|
|
345
|
+
- `import * as THREE from 'three/webgpu'`, shader nodes from `'three/tsl'`.
|
|
346
|
+
`new THREE.WebGPURenderer({ antialias: true })`, falls back to WebGL 2 by itself
|
|
347
|
+
(`forceWebGL: true` to test that). It starts asynchronously: use `setAnimationLoop`, or
|
|
348
|
+
`await renderer.init()` before the first use.
|
|
349
|
+
- **Not supported there:** `ShaderMaterial`, `RawShaderMaterial`, `onBeforeCompile`,
|
|
350
|
+
`EffectComposer` and its passes. They become node materials, TSL and `RenderPipeline`
|
|
351
|
+
(`pass(scene, camera)`, effect nodes from `three/addons/tsl/display/`, `renderOutput()` to
|
|
352
|
+
place tone mapping yourself).
|
|
353
|
+
- The manual calls it experimental still, and `WebGLRenderer` "the recommended choice for
|
|
354
|
+
pure WebGL 2 applications", maintained but without large new features. Depthview reads
|
|
355
|
+
`WebGLRenderer` scenes. Choose WebGPU for compute (millions of particles, fluids) and say
|
|
356
|
+
what it costs.
|
|
357
|
+
|
|
358
|
+
## Freeing memory
|
|
359
|
+
|
|
360
|
+
three.js cannot free GPU memory by itself. `dispose()` what is no longer shown: geometries,
|
|
361
|
+
materials, textures (a material does not dispose its textures), render targets, PMREM
|
|
362
|
+
results, composers and passes, controls. Removing a mesh from the scene frees nothing.
|
|
363
|
+
`renderer.info.memory` counts what is still held. Disposing something still in use is not an
|
|
364
|
+
error: it is rebuilt on the next frame, with a hitch.
|
|
365
|
+
|
|
366
|
+
## Loading models
|
|
367
|
+
|
|
368
|
+
glTF (`.glb`) through `GLTFLoader` is the format: `setDRACOLoader`, `setKTX2Loader` (call
|
|
369
|
+
`ktx2.detectSupport(renderer)` first), `setMeshoptDecoder`. When a model looks wrong: check
|
|
370
|
+
the console and pass an `onError`; open the file in another viewer; scale by 1000 either way
|
|
371
|
+
(units); add a light; look for failed texture requests. A scene from an artist often arrives
|
|
372
|
+
with scaled or rotated parent nodes: print the graph before animating anything in it.
|
|
373
|
+
|
|
374
|
+
## The page around the canvas (from the manual's tips)
|
|
375
|
+
|
|
376
|
+
- three.js as the background of a page: the canvas `position: fixed; inset: 0`, behind the
|
|
377
|
+
content (`z-index`), and `pointer-events: none` if the content must take the clicks.
|
|
378
|
+
- A transparent canvas: `alpha: true`. The canvas expects premultiplied alpha by default.
|
|
379
|
+
- Many 3D views on one page: **one** canvas and renderer, one scene per view, drawn with
|
|
380
|
+
`setScissor` / `setViewport` where each placeholder element is. Browsers allow about 8
|
|
381
|
+
WebGL contexts and nothing is shared between them.
|
|
382
|
+
- HTML that follows a 3D point: `v.project(camera)`, then
|
|
383
|
+
`x = (v.x * 0.5 + 0.5) * width`, `y = (v.y * -0.5 + 0.5) * height`, set with a `transform`;
|
|
384
|
+
hide it when `v.z` is outside -1 to 1. Or `CSS2DRenderer`.
|
|
385
|
+
- Text in the scene: HTML over it (sharpest, selectable), a `CanvasTexture`, `TextGeometry`
|
|
386
|
+
for solid letters, or `troika-three-text` for SDF text from any font file.
|
|
387
|
+
- Nothing animating? Draw on demand (on input, on load, on resize) instead of every frame.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# Visual QA: finding and fixing what looks wrong
|
|
2
|
+
|
|
3
|
+
Run `audit_visuals` first (add `scroll: [0, 25, 50, 75, 100]` to cover the whole page). It
|
|
4
|
+
reads the set-up and measures a real frame. Then confirm with `take_screenshot view:"site"`
|
|
5
|
+
and fix in the source. This file explains every issue it reports, and the ones only eyes find.
|
|
6
|
+
|
|
7
|
+
## How to test a 3D page, in order
|
|
8
|
+
|
|
9
|
+
1. `get_errors`: failed shaders and exceptions explain half of all "it looks wrong".
|
|
10
|
+
2. `audit_visuals { scroll: [0, 25, 50, 75, 100] }`.
|
|
11
|
+
3. For each issue with `tryLive`: run it, then `take_screenshot view:"site" compare:true`.
|
|
12
|
+
A fix that does not change the picture was not the cause.
|
|
13
|
+
4. Sizes: `set_viewport { width: 500, height: 900, pixelRatio: 3 }` (a phone), then a wide
|
|
14
|
+
one (2560 × 1300). Audit and screenshot each. `set_viewport { reset: true }` after.
|
|
15
|
+
5. Time: `set_time pause`, `step`, screenshot: catches one-frame glitches and lets you compare
|
|
16
|
+
identical frames. Always `resume`.
|
|
17
|
+
6. `get_performance` at the heaviest scroll position, at pixel ratio 2.
|
|
18
|
+
7. Look at the screenshots yourself, zoomed in on edges, gradients and where objects meet.
|
|
19
|
+
The audit cannot judge composition, colour taste or timing.
|
|
20
|
+
|
|
21
|
+
## Resolution: pixelated, soft, blurry
|
|
22
|
+
|
|
23
|
+
| Issue id | What you see | Cause | Fix |
|
|
24
|
+
| ------------------ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
25
|
+
| `canvas-upscaled` | Whole scene soft; text and thin edges show pixels, HTML is sharp | Drawing buffer smaller than the canvas's box × device pixel ratio: `setPixelRatio` never called, `setSize` before layout, CSS-only resize | `renderer.setPixelRatio(Math.min(devicePixelRatio, 2))`; `setSize` from the element on every resize (ResizeObserver). R3F: `dpr={[1, 2]}` |
|
|
26
|
+
| `target-upscaled` | Same, but the canvas itself is full size | The scene is drawn into a smaller render target and enlarged by the post chain: composer sized in CSS pixels | `composer.setPixelRatio(renderer.getPixelRatio()); composer.setSize(w, h)` on resize; custom targets from `renderer.getDrawingBufferSize()` |
|
|
27
|
+
| `pixel-blocks` | Visible square blocks | A low-res target sampled with `NearestFilter`, or a pixelation effect | `LinearFilter` and a full-size target, unless it is the style |
|
|
28
|
+
| `soft-picture` | Edges 2+ pixels wide everywhere | An undersized pass somewhere, or a blur (DOF, bloom radius) | `get_performance` → `passesOfOneFrame`: find the small target |
|
|
29
|
+
| `canvas-stretched` | Circles are ovals | CSS size and render size have different shapes | `setSize(el.clientWidth, el.clientHeight)` and camera aspect together |
|
|
30
|
+
| `camera-aspect` | Scene squashed after a resize | `camera.aspect` not updated | `camera.aspect = w / h; camera.updateProjectionMatrix()` |
|
|
31
|
+
| `css-pixelated` | Hard blocks when the canvas is scaled | `image-rendering: pixelated` on the canvas | Remove it |
|
|
32
|
+
| `pixel-ratio-high` | Fine, but slow | Pixel ratio 3 on a phone | Cap at 2 |
|
|
33
|
+
|
|
34
|
+
Pixelation that appears only **during** scroll or animation: an adaptive-resolution system
|
|
35
|
+
dropping the pixel ratio (drei `<AdaptiveDpr>`, `PerformanceMonitor`) under load. Check
|
|
36
|
+
`get_performance` there; fix the load, or raise the floor.
|
|
37
|
+
|
|
38
|
+
Pixelation only on **one object**: its texture (below), or it is drawn into its own small
|
|
39
|
+
render target (reflections, portals, `RenderTexture`): raise that target's size.
|
|
40
|
+
|
|
41
|
+
## Edges: jaggies, shimmer, crawling
|
|
42
|
+
|
|
43
|
+
- `jagged-edges` with anti-aliasing off: `antialias: true` on the renderer.
|
|
44
|
+
- `jagged-edges` with it on: the scene goes through a composer, where the canvas's MSAA does
|
|
45
|
+
nothing. `multisampling: 4` on the composer (or `samples` on its render target), or SMAA.
|
|
46
|
+
- Jaggies only on cut-out textures (leaves, hair): `alphaTest` edges are not anti-aliased.
|
|
47
|
+
`alphaToCoverage: true` with MSAA.
|
|
48
|
+
- Sparkling highlights on metal when the camera moves: specular aliasing from a normal map
|
|
49
|
+
with no mipmaps, or roughness near 0. Raise roughness, enable mipmaps.
|
|
50
|
+
- Thin lines flicker (wires, grid): sub-pixel geometry. Fatten with `Line2` (screen-space
|
|
51
|
+
width), fade by distance, or supersample.
|
|
52
|
+
- Moiré on fine patterns (grilles, fabric): no mipmaps or no anisotropy; or a pattern finer
|
|
53
|
+
than a pixel: fade the pattern out with distance in the shader.
|
|
54
|
+
|
|
55
|
+
## Textures
|
|
56
|
+
|
|
57
|
+
| Issue id | What you see | Fix |
|
|
58
|
+
| ----------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
|
|
59
|
+
| `texture-magnified` | One surface blurry while its silhouette is sharp | Larger source image for that camera distance; detail texture tiled on top; do not let the camera get that close |
|
|
60
|
+
| `texture-nearest` | Blocky texels | `magFilter = LinearFilter` |
|
|
61
|
+
| `texture-no-mipmaps` | Sparkle and moiré when small or far | `generateMipmaps = true`, `minFilter = LinearMipmapLinearFilter`; KTX2 with mips |
|
|
62
|
+
| `texture-anisotropy` | Floor turns to blur a few metres away | `texture.anisotropy = 8` |
|
|
63
|
+
| `texture-colour-linear` | Washed-out, pale colours | `colorSpace = SRGBColorSpace` on colour maps |
|
|
64
|
+
| `texture-data-srgb` | Lighting looks off: too rough/shiny, normals tilted | `colorSpace = NoColorSpace` on normal/roughness/metal/AO maps |
|
|
65
|
+
|
|
66
|
+
Also: seams along UV borders (mip bleeding: add padding in the atlas, or lower `anisotropy`
|
|
67
|
+
on atlases); a texture upside down (`flipY`: glTF textures are `false`, TextureLoader `true`);
|
|
68
|
+
black texture (not loaded, or a non-power-of-two with repeat on WebGL 1; cross-origin without
|
|
69
|
+
CORS); a video texture frozen (autoplay blocked: muted + playsInline).
|
|
70
|
+
|
|
71
|
+
## Depth: flicker, stripes, things showing through
|
|
72
|
+
|
|
73
|
+
- `coplanar`: two surfaces in the same plane fight in stripes that move with the camera.
|
|
74
|
+
Offset one (1/1000 of the camera distance), or `polygonOffset: true, polygonOffsetFactor: -1`
|
|
75
|
+
on the decal.
|
|
76
|
+
- `depth-range`: `near` too small. Precision is spent near the camera: `near: 0.01, far: 10000`
|
|
77
|
+
leaves almost none in the distance. Raise `near` first (0.1 for a room-scale scene, more for
|
|
78
|
+
a landscape). Symptoms: distant surfaces flicker, shadows and decals shimmer far away.
|
|
79
|
+
- Objects vanish at the screen edge or when close: frustum culling with a wrong bounding
|
|
80
|
+
sphere (vertices moved in the shader, skinned meshes, instances): `frustumCulled = false` or
|
|
81
|
+
set the bounding sphere by hand. Or the camera's `near` plane cuts them.
|
|
82
|
+
- Things visible through other things: `depthTest: false`, `depthWrite: false` on an opaque
|
|
83
|
+
material, or a `renderOrder` hack that outlived its reason.
|
|
84
|
+
|
|
85
|
+
## Transparency
|
|
86
|
+
|
|
87
|
+
- `transparent-depth-write`: parts of a see-through object, or objects behind it, pop in and
|
|
88
|
+
out. `depthWrite: false`; sort layers with `renderOrder`.
|
|
89
|
+
- Objects sort wrong as the camera moves: three sorts transparent objects by their centre,
|
|
90
|
+
not per pixel. Split interpenetrating transparent meshes, or use `alphaHash` /
|
|
91
|
+
alpha-to-coverage (order-independent, slightly noisy).
|
|
92
|
+
- Inside of a glass object missing: `side: DoubleSide` renders both in one pass in the wrong
|
|
93
|
+
order: two meshes (BackSide first, FrontSide second) or `forceSinglePass: false` (default
|
|
94
|
+
for DoubleSide since r149).
|
|
95
|
+
- Dark halo around a cut-out PNG: the transparent pixels are black and get filtered in.
|
|
96
|
+
`premultiplyAlpha`, or bleed the colour into the transparent area, or `alphaTest: 0.5`.
|
|
97
|
+
- Additive glow invisible: the background is white. Additive cannot darken.
|
|
98
|
+
|
|
99
|
+
## Colour and light
|
|
100
|
+
|
|
101
|
+
- `output-colour-space`: dark and contrasty. `outputColorSpace = SRGBColorSpace`.
|
|
102
|
+
- Washed-out, low contrast, grey blacks: tone mapping or sRGB applied twice (renderer and
|
|
103
|
+
composer), or a colour texture left linear.
|
|
104
|
+
- `clipped-highlights`: flat white areas. Tone mapping, lower exposure or light.
|
|
105
|
+
- `banding`: steps in dark gradients, fog, vignettes. Dither: `material.dithering = true`,
|
|
106
|
+
a noise/dither pass last, HalfFloat intermediate targets.
|
|
107
|
+
- Black object: no light reaches it and there is no environment (metals are black without
|
|
108
|
+
one), normals missing or inverted, or a shader error (`get_errors`).
|
|
109
|
+
- Object much brighter or darker than its neighbours: a ShaderMaterial without the
|
|
110
|
+
tone-mapping and colour-space includes, or `toneMapped: false`.
|
|
111
|
+
- Colours differ from the design: tone mapping shifts hues. `NeutralToneMapping`, or
|
|
112
|
+
`toneMapped: false` on brand-colour surfaces.
|
|
113
|
+
|
|
114
|
+
## Shadows (`get_lighting` has the details)
|
|
115
|
+
|
|
116
|
+
| What you see | Cause | Fix |
|
|
117
|
+
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- |
|
|
118
|
+
| Blurry, blocky shadow | Shadow camera far larger than the scene | Fit `shadow.camera` to the casters; larger `mapSize` |
|
|
119
|
+
| Shadow cut off in a straight line | Shadow camera too small | Enlarge it to cover the receivers |
|
|
120
|
+
| Stripes on lit surfaces (acne) | Bias too small | `normalBias: 0.02–0.05`, then a small negative `bias` |
|
|
121
|
+
| Shadow detached from the object | Bias too large | Lower it |
|
|
122
|
+
| Shadow swims when the light or camera moves | Texels not snapped | Static light; or cascade shadows (CSM) |
|
|
123
|
+
| No shadow at all | `renderer.shadowMap.enabled`, `light.castShadow`, `mesh.castShadow`, `receiveShadow`: one is off; or the material is Basic | Turn all four on; use a lit material |
|
|
124
|
+
| Light leaking through walls | VSM bleeding, or single-sided thin walls | PCF; give walls thickness; `shadowSide` |
|
|
125
|
+
|
|
126
|
+
## Geometry and transforms
|
|
127
|
+
|
|
128
|
+
- `nan-transform`: an object vanished or flickers. Find the division by zero.
|
|
129
|
+
- Faceted where it should be smooth: no vertex normals, or `flatShading`. `computeVertexNormals()`;
|
|
130
|
+
export smooth normals.
|
|
131
|
+
- Dark, inside-out faces: flipped normals or negative scale. Fix in the model;
|
|
132
|
+
`side: DoubleSide` only as a plaster.
|
|
133
|
+
- Round shapes with visible corners: too few segments (`get_realism` reports it).
|
|
134
|
+
- A seam on a smooth model: split normals at the UV seam; merge vertices with tolerance
|
|
135
|
+
(`BufferGeometryUtils.mergeVertices`) before computing normals.
|
|
136
|
+
|
|
137
|
+
## Motion
|
|
138
|
+
|
|
139
|
+
- Stutter every second or so: garbage collection (allocations in the loop) or a timer.
|
|
140
|
+
- Jitter while scrolling: camera bound directly to scroll events (which fire irregularly) or
|
|
141
|
+
two smoothers fighting (CSS smooth scroll + Lenis). Damp one value in the frame loop.
|
|
142
|
+
- Speed differs between a 60 Hz and a 120 Hz screen: motion per frame instead of per second.
|
|
143
|
+
Multiply by `delta`.
|
|
144
|
+
- A hitch the first time an object appears: shader compile or texture upload: precompile.
|
|
145
|
+
- A jump after switching tabs: a huge `delta`. Clamp it (`Math.min(delta, 1 / 30)`).
|
|
146
|
+
- `get_animated_values` shows what the site drives per frame and on scroll.
|
|
147
|
+
|
|
148
|
+
## Things that are not bugs
|
|
149
|
+
|
|
150
|
+
A soft picture under intentional depth of field; blocks in a pixel-art style; pure white on a
|
|
151
|
+
white page background; banding inside a compressed video texture. Say what was measured and
|
|
152
|
+
ask, rather than "fixing" a decision.
|