Capítulo 850 de 859

Chapter 850: Transparency (Manual)

Core Idea

Basic transparency (transparent: true + opacity) is easy, but correct-looking transparency is hard: three.js sorts whole objects back-to-front, not individual triangles, so overlapping or self-intersecting transparent geometry commonly shows visual artifacts with no single perfect fix.

Key Concepts

  • Basic transparency: set material.transparent = true and material.opacity (1 = opaque, 0 = fully transparent).
  • Missing backfaces: transparent objects still default to THREE.FrontSide, so a transparent cube appears to be missing its back faces unless side: THREE.DoubleSide is set.
  • Per-triangle sorting isn't done: three.js sorts whole objects (like separate Meshes) back-to-front for transparency, but not individual triangles within one geometry (too slow) — so within a single mesh, triangles farther from the camera can still fail to draw behind nearer ones, causing missing/wrong-looking backfaces even with DoubleSide.
  • Double-mesh workaround: for convex shapes, add the object twice — once with a BackSide-only material, once with FrontSide — relying on stable draw order between the two.
  • Splitting intersecting geometry: two literally intersecting planes/objects have no correct sort order at all; the practical fix is manually splitting the geometry (e.g. via texture offset/repeat tricks on separate non-intersecting planes) so there's no true intersection to sort.
  • alphaTest: pixels below the alpha threshold aren't drawn at all, sidestepping the depth-sorting problem entirely — works well for sharp-edged cutout textures (leaves, grass) but isn't a general transparency solution.

Code Examples

const material = new THREE.MeshPhongMaterial({
  map: texture,
  transparent: true,
  alphaTest: 0.5,
  side: THREE.DoubleSide,
});
  • What it demonstrates: combining alphaTest with transparent/DoubleSide so a cutout texture (e.g. a tree/leaf sprite) skips drawing fully-transparent pixels, avoiding depth-sort artifacts for sharp-edged alpha content.

Key Takeaways

  1. transparent: true + opacity is easy but incomplete — you'll also usually need side: THREE.DoubleSide to see backfaces at all.
  2. Three.js sorts whole objects for transparency, not individual triangles, so a single transparent mesh can still show sorting artifacts.
  3. Genuinely intersecting transparent geometry has no fully correct sort order — split it into non-intersecting pieces if you need it to look right.
  4. alphaTest avoids the sorting problem entirely for sharp cutout textures by not drawing below-threshold pixels at all, at the cost of hard (not soft) edges.

Connects To

  • PlaneGeometry: the geometry used to demonstrate the intersecting-planes transparency problem.