Chapitre -107 · BruitNoise
Ruis

Boîte de PerlinPerlin toolbox
Perlin-gereedschapskist

Objectif de ce chapitreWhat you’ll learn
Wat je leert
  • Fonctions de hachage : hash de gradient, hash au sinusHash functions: gradient hash, sine hash
  • Interpolation C² avec la courbe quintiqueC² interpolation with the quintic fade curve
  • Bruit de gradient 2D / 3D, bruit de valeur RVB2D / 3D gradient noise, RGB value noise
  • fBm et domain warpingfBm and domain warping
  • Partager des fonctions MSL entre shaders avec inlineSharing MSL functions across shaders with inline
⏱ ~20 min

Pourquoi inlineWhy inline
Waarom inline

Le Makefile compile chaque .metal en un .air, puis les lie tous dans default.metallib.The Makefile compiles each .metal to its own .air, then links them all into default.metallib. Noise.metal est compilé seul, puis à nouveau dans chaque shader qui l'inclut.Noise.metal is compiled on its own, and again inside each shader that includes it. Une fonction ordinaire est alors définie dans deux .air :A plain function is then defined in two .air files:

/// MSL — Exemple — update:04/11/26
LLVM ERROR: multiple symbols ('_Z6hash22Dv2_f')!

inline autorise une définition identique par fichier ; l'éditeur de liens n'en garde qu'une.inline allows one identical definition per file; the linker keeps a single copy. Un shader qui inclut Noise.metal ne redéfinit pas les mêmes noms : ses copies locales sont à supprimer.A shader that includes Noise.metal must not define the same names again: delete its local copies.

/// MSL — Skybox.metal — update:04/11/26
#include "Noise.metal" // hash33, perlinNoise3D, perlinFBMColor3D, …

hash22 — hash de gradient 2D2D gradient hash
2D-gradienthash

\( \mathbb{R}^2 \to [-1, 1]^2 \). Hash sans sinus (Dave Hoskins) : uniquement fract, dot et des produits, aucune fonction transcendante — stable d'un GPU à l'autre.Hash without Sine (Dave Hoskins): only fract, dot and products, no transcendental function — stable across GPUs. Sert de gradient à perlinNoise2D à chaque coin de la grille.Used as the gradient of perlinNoise2D at each lattice corner.

/// MSL — Noise.metal — update:04/11/26
#include <metal_stdlib>
using namespace metal;

inline float2 hash22(float2 p)
{
  float3 p3 = fract(float3(p.xyx) * float3(0.1031, 0.1030, 0.0973));
  p3 += dot(p3, p3.yzx + 33.33);
  return fract((p3.xx + p3.yz) * p3.zy) * 2.0 - 1.0;
}

hash33 — hash 3D au sinus3D sine hash
3D-sinushash

\( \mathbb{R}^3 \to [-1, 1]^3 \). Trois produits scalaires projettentThree dot products project \( p \) sur trois directions fixes ;on three fixed directions; \( \operatorname{fract}(\sin(x) \cdot 43758.5453) \) garde les derniers chiffres, chaotiques, du sinus.keeps the low, chaotic digits of the sine.

La précision de sin baisse quandThe precision of sin drops as \( |x| \) grandit : pour de grandes valeurs, le motif dépend du sin du GPU.grows: for large inputs the pattern depends on the GPU's sin. Suffisant pour l'image, pas pour des données qui doivent être reproductibles.Fine for visuals, not for data that must be reproducible.

/// MSL — Noise.metal — update:04/11/26
inline float3 hash33(float3 p)
{
  p = float3(dot(p, float3(127.1, 311.7, 74.7)),
             dot(p, float3(269.5, 183.3, 246.1)),
             dot(p, float3(113.5, 271.9, 124.6)));
  return fract(sin(p) * 43758.5453123) * 2.0 - 1.0;
}

quintic — courbe de fondu C²C² fade curve
C²-overgangscurve

\[ f(t) = 6t^5 - 15t^4 + 10t^3 \]

\[ f'(t) = 30\,t^2 (t-1)^2 \qquad f''(t) = 60\,t\,(t-1)(2t-1) \]

\( f(0)=0 \), \( f(1)=1 \), etand \( f' \), \( f'' \) s'annulent en 0 et 1 : le bruit est C² d'une cellule à l'autre (Perlin, 2002).vanish at 0 and 1: the noise is C² across cell borders (Perlin, 2002). smoothstep, \( 3t^2 - 2t^3 \), n'est que C¹ : sa dérivée seconde saute aux bords, ce qui se voit en plis dans un éclairage calculé à partir du bruit.is only C¹: its second derivative jumps at the borders, visible as creases in lighting computed from the noise.

01 00.51 t = fract(p) quintic — C² smoothstep — C¹ linear — C⁰
/// MSL — Noise.metal — update:04/11/26
inline float quintic(float t)
{
  return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
}

quintic3

quintic par composante : les trois poids de l'interpolation trilinéaire.quintic per component: the three weights of trilinear interpolation.

/// MSL — Noise.metal — update:04/11/26
inline float3 quintic3(float3 t)
{
  return float3(quintic(t.x), quintic(t.y), quintic(t.z));
}

perlinNoise2D — bruit de gradientgradient noise
gradiëntruis

\( i = \lfloor p \rfloor \), \( f = p - i \). Chaque coinEach corner \( c \in \{0,1\}^2 \) porte un gradientholds a gradient \( g_c \) ; sa contribution est la hauteur du plan qui passe par ce coin :; its contribution is the height of the plane through that corner:

\[ v_c = g_c \cdot (f - c) \]

\[ n(p) = \operatorname{mix}\big(\operatorname{mix}(v_{00}, v_{10}, u_x),\ \operatorname{mix}(v_{01}, v_{11}, u_x),\ u_y\big) \qquad u = \operatorname{quintic}(f) \]

i + (0,0)i + (1,0) i + (0,1)i + (1,1) p g_c = hash22(i + c) f − c v_c = g_c · (f − c)

\( n = 0 \) sur chaque point de la grille.on every lattice point. Sortie centrée sur 0, environOutput centred on 0, roughly \( [-1, 1] \) : les gradients ne sont pas normalisés.: the gradients are not normalised.

/// MSL — Noise.metal — update:04/11/26
inline float perlinNoise2D(float2 p)
{
  float2 i = floor(p);
  float2 f = fract(p);

  // Gradients at the 4 corners
  float2 g00 = hash22(i + float2(0.0, 0.0));
  float2 g10 = hash22(i + float2(1.0, 0.0));
  float2 g01 = hash22(i + float2(0.0, 1.0));
  float2 g11 = hash22(i + float2(1.0, 1.0));

  // Offsets to the corners
  float v00 = dot(g00, f - float2(0.0, 0.0));
  float v10 = dot(g10, f - float2(1.0, 0.0));
  float v01 = dot(g01, f - float2(0.0, 1.0));
  float v11 = dot(g11, f - float2(1.0, 1.0));

  // Smooth interpolation
  float2 u = float2(quintic(f.x), quintic(f.y));

  float v0 = mix(v00, v10, u.x);
  float v1 = mix(v01, v11, u.x);

  return mix(v0, v1, u.y);
}

perlinNoise3D

Même construction sur un cube : 8 coins, 8 hash33, 7 mix.Same construction on a cube: 8 corners, 8 hash33, 7 mix. Coût par appel : 8 hashes, 24 sin.Cost per call: 8 hashes, 24 sin.

/// MSL — Noise.metal — update:04/11/26
inline float perlinNoise3D(float3 p)
{
  float3 i = floor(p); // integer corner
  float3 f = fract(p); // fraction inside the cell

  // 8 corners of the cube
  float3 g000 = hash33(i + float3(0,0,0));
  float3 g100 = hash33(i + float3(1,0,0));
  float3 g010 = hash33(i + float3(0,1,0));
  float3 g110 = hash33(i + float3(1,1,0));
  float3 g001 = hash33(i + float3(0,0,1));
  float3 g101 = hash33(i + float3(1,0,1));
  float3 g011 = hash33(i + float3(0,1,1));
  float3 g111 = hash33(i + float3(1,1,1));

  float v000 = dot(g000, f - float3(0,0,0));
  float v100 = dot(g100, f - float3(1,0,0));
  float v010 = dot(g010, f - float3(0,1,0));
  float v110 = dot(g110, f - float3(1,1,0));
  float v001 = dot(g001, f - float3(0,0,1));
  float v101 = dot(g101, f - float3(1,0,1));
  float v011 = dot(g011, f - float3(0,1,1));
  float v111 = dot(g111, f - float3(1,1,1));

  // Smooth trilinear interpolation
  float3 u = quintic3(f);

  float v00 = mix(v000, v100, u.x);
  float v10 = mix(v010, v110, u.x);
  float v01 = mix(v001, v101, u.x);
  float v11 = mix(v011, v111, u.x);

  float v0 = mix(v00, v10, u.y);
  float v1 = mix(v01, v11, u.y);

  return mix(v0, v1, u.z);
}

perlinFBM — mouvement brownien fractionnairefractional Brownian motion
fractionele Brownse beweging

\[ \operatorname{fbm}(p) = \frac{\sum_{k=0}^{D-1} r^k\, n(\lambda^k p)}{\sum_{k=0}^{D-1} r^k} \]

\( D \) = DETAIL octaves,octaves, \( r \) = ROUGHNESS (rapport d'amplitude),(amplitude ratio), \( \lambda \) = LACUNARITY (rapport de fréquence).(frequency ratio). Diviser parDividing by \( \sum r^k = 1.5 \) garde l'amplitude dekeeps the range of \( n \). Les noms sont ceux du nœud Noise Texture de Blender.The names match Blender's Noise Texture node.

Distorsion :Distortion: \( p \leftarrow p + 0.1\,\big(n(p + (d,0)),\ n(p + (0,d))\big) \), \( d \) = DISTORTION = 33.6. Les deux échantillons sont loin l'un de l'autre : les deux décalages sont indépendants.The two samples are far apart, so the two offsets are uncorrelated. SCALE < 0 inverse le motif.SCALE < 0 mirrors the pattern.

/// MSL — Noise.metal — update:04/11/26
// Fractional Brownian Motion default; scale: -0.2, detail: 2, roughness: 0.5, distortion: 33.6, lacunarity: 2
inline float perlinFBM(float2 uv)
{
  const float SCALE = -0.2;
  const int DETAIL = 2;
  const float ROUGHNESS = 0.5;
  const float DISTORTION = 33.6;
  const float LACUNARITY = 2.0;

  float2 p = uv * SCALE;

  // Initial distortion
  p += float2(perlinNoise2D(p + float2(DISTORTION, 0.0)),
              perlinNoise2D(p + float2(0.0, DISTORTION))) * 0.1;

  float value = 0.0;
  float amplitude = 1.0;
  float frequency = 1.0;
  float maxValue = 0.0;

  for (int i = 0; i < DETAIL; ++i)
  {
    value += perlinNoise2D(p * frequency) * amplitude;
    maxValue += amplitude;

    amplitude *= ROUGHNESS;
    frequency *= LACUNARITY;
  }
  return value / maxValue;
}

perlinFBM — gris : 0.5 + 0.5 · fbmgrey: 0.5 + 0.5 · fbm

perlinNoiseColor3D — coupe z = 0.37, rendu pastel de la skyboxslice z = 0.37, skybox pastel grade

Calcul en JavaScript, en double précision : le sin de hash33 donne un motif proche de celui du GPU, pas identique.Computed in JavaScript, in double precision: the sin of hash33 gives a pattern close to the GPU's, not identical. La courbe de fondu s'applique aux deux panneaux.The fade curve applies to both panels.

perlinNoiseColor3D — bruit de valeur RVBRGB value noise
RGB-waarderuis

Bruit de valeur, pas de gradient : chaque coin rend une valeurValue noise, not gradient noise: each corner returns a value \( c = \operatorname{hash33}(i + c) \), lue comme une couleur dansread as a colour in \( [-1, 1]^3 \).

Les poids sont linéaires,The weights are linear, \( u = f \) : la couleur est continue (C⁰), mais sa dérivée saute sur chaque face de cellule et trace des plis droits le long de la grille — une part du rendu de la skybox.: the colour is continuous (C⁰), but its derivative jumps on every cell face and draws straight creases along the lattice — part of the skybox look. \( u = \operatorname{quintic3}(f) \) les lisserait et changerait ce rendu : le commentaire « Smooth » du code ne correspond pas à \( u = f \).would smooth them and change that look: the code's “Smooth” comment does not match u = f.

/// MSL — Noise.metal — update:04/11/26
// PERLIN 3D COLOR - outputs RGB directly
inline float3 perlinNoiseColor3D(float3 p)
{
  float3 i = floor(p);
  float3 f = fract(p);

  // 8 corners with an RGB hash
  float3 c000 = hash33(i + float3(0,0,0));
  float3 c100 = hash33(i + float3(1,0,0));
  float3 c010 = hash33(i + float3(0,1,0));
  float3 c110 = hash33(i + float3(1,1,0));
  float3 c001 = hash33(i + float3(0,0,1));
  float3 c101 = hash33(i + float3(1,0,1));
  float3 c011 = hash33(i + float3(0,1,1));
  float3 c111 = hash33(i + float3(1,1,1));

  // Smooth RGB interpolation
  float3 u = f;

  float3 c00 = mix(c000, c100, u.x);
  float3 c10 = mix(c010, c110, u.x);
  float3 c01 = mix(c001, c101, u.x);
  float3 c11 = mix(c011, c111, u.x);

  float3 c0 = mix(c00, c10, u.y);
  float3 c1 = mix(c01, c11, u.y);

  return mix(c0, c1, u.z);
}

perlinFBMColor3D — la couleur de la skyboxthe skybox colour
de kleur van de skybox

\( p = -0.85\,\mathit{pos} \), puis domain warping, puis 2 octaves de perlinNoiseColor3D aux fréquences 15 et 30, normalisées par 1,5.then domain warping, then 2 octaves of perlinNoiseColor3D at frequencies 15 and 30, normalised by 1.5.

Avec DISTORTION = 0, les trois échantillons du warping lisent le même point :With DISTORTION = 0 the three warp samples read the same point: \( q = n(p)\,(1, 1, 1) \), un déplacement sur la diagonale seulement,a displacement along the diagonal only, \( p \leftarrow p + 20\,q \). Le compilateur fusionne les trois appels identiques en un seul.The compiler merges the three identical calls into one. Une DISTORTION non nulle déforme selon trois axes indépendants et change le rendu.A non-zero DISTORTION warps along three independent axes and changes the look.

Coût par pixel :Cost per pixel: 1 perlinNoise3D + 2 perlinNoiseColor3D = 24 hashes, 72 sin.24 hashes, 72 sin.

/// MSL — Noise.metal — update:04/11/26
// 3D FBM with COLOR output
inline float3 perlinFBMColor3D(float3 pos)
{
  const float SCALE = -0.85;
  const int DETAIL = 2;
  const float ROUGHNESS = 0.5;
  float DISTORTION = 0.0;
  const float LACUNARITY = 2.0;

  float3 p = pos * SCALE;

  // Domain warping (distortion)
  float3 q = float3(perlinNoise3D(p + float3(DISTORTION, 0.0, 0.0)),
                    perlinNoise3D(p + float3(0.0, DISTORTION, 0.0)),
                    perlinNoise3D(p + float3(0.0, 0.0, DISTORTION)));
  p += q / 0.05;

  // RGB FBM accumulation
  float3 value = float3(0.0);
  float amplitude = 1.0;
  float frequency = 15.0;
  float maxValue = 0.0;

  for (int i = 0; i < DETAIL; ++i)
  {
    // Each octave has its own RGB colours
    value += perlinNoiseColor3D(p * frequency) * amplitude;
    maxValue += amplitude;

    amplitude *= ROUGHNESS;
    frequency *= LACUNARITY;
  }

  return value / maxValue;
}