Randomness and Noise

Why shaders need noise

Look at concrete, wood grain, clouds or the back of your hand. None of them is perfectly smooth, and none of them repeats like the tiles you built in Chapter 5. Every material has small, irregular variations, and those variations are a big part of why a surface reads as real instead of computer generated.

To fake that irregularity we need something that looks random. On a GPU, though, "random" has to come from a deterministic function: the same input always produces the same output. This chapter shows why, then builds up from a single random number per cell to the smooth, layered noise used for clouds, marble and wood.

Why a shader can't call random()

On the CPU you call Float.random(in: 0...1) and get a new number every time. That works because the random number generator keeps hidden state: each call reads the state, updates it, and returns a value derived from it.

A shader can't work that way. Remember the model from Chapter 1: your function runs once for every pixel, as thousands of independent invocations in parallel, and nothing is kept between frames. Metal has no built-in random() function, and a hand-made generator with shared state would cause three problems:

  1. Thousands of pixels would be reading and updating the same state at once. Which pixel gets which number would depend on the order the GPU happens to schedule them, and that order changes from frame to frame.
  2. Because the order changes, every pixel would get a different number on every frame. A texture that should stay still would flicker like a broken TV.
  3. Neighboring pixels couldn't agree on anything. Smooth noise, which you'll build below, needs every pixel inside a grid cell to see the same random values at that cell's corners.

The fix is to make the random number a function of something the pixel already knows: its position. A hash function takes a coordinate and scrambles it into a number between 0 and 1. Pixels in the same spot always get the same value, so the image is stable. Pixels in different spots get values that look unrelated. And because any pixel can compute the hash for any coordinate, neighbors can agree on shared values without talking to each other.

If you want the pattern to change over time, you change the input (for example by adding time to the coordinate). The function itself stays deterministic.

The sin-based hash

You already met this function in Chapter 5, where you used it to give each grid cell its own value:

float random(float2 st) {
    return fract(sin(dot(st, float2(12.9898, 78.233))) * 43758.5453);
}

Here it is broken into steps:

// Step 1: dot product creates a single value from 2D input
float dotProduct = dot(st, float2(12.9898, 78.233));
// For st = (1,1): 12.9898 + 78.233 = 91.2228

// Step 2: sin() creates oscillation (-1 to 1)
float sineValue = sin(dotProduct);
// sin(91.2228) = some value between -1 and 1

// Step 3: Multiply by a large number
float amplified = sineValue * 43758.5453;
// Amplifies tiny differences in sine values

// Step 4: fract() keeps only decimal part (0-1)
float result = fract(amplified);
// Ensures output is always 0-1 range

The interesting part is step 3. sin on its own is smooth, so nearby inputs give nearby outputs. Multiplying by about 44,000 stretches the sine wave so that a change of 0.001 in the sine value becomes a change of about 44 in the product. fract then throws away the whole-number part and keeps only the digits after the decimal point, and those digits look unrelated from one input to the next.

Here's what it produces for a few cells, computed in 32-bit float:

st        dot        sin        × 43758.5453   fract
(0, 0)     0.0        0.0            0.0        0.0
(1, 0)    12.9898     0.4109     17979.94       0.94
(2, 0)    25.9796     0.7492     32784.09       0.09
(1, 1)    91.2228    -0.1164     -5091.31       0.69

Cells (1, 0) and (2, 0) are neighbors, yet one comes out almost white and the other almost black. Notice two details. fract of a negative number is still between 0 and 1, because Metal's fract(x) is x - floor(x): -5091.31 minus -5092 gives 0.69. And cell (0, 0) always gives exactly 0, because sin(0) = 0. In the shader below, the top-left cell is always black.

The constants 12.9898, 78.233 and 43758.5453 have no special meaning. Other values work too, as long as the two dot weights are different (so that (1, 2) and (2, 1) don't collide) and the multiplier is large. The pattern is: combine the coordinates into one number, pass it through a nonlinear function, magnify the result, keep the fractional part.

Precision: keep the hash in float

This hash works by keeping the low-order digits of a big number, and those are exactly the digits a floating-point type loses first. That makes it sensitive to the type you use and to the size of the input.

Never compute it in half. That type has an 11-bit mantissa. The multiplier 43758.5453 can't even be stored as a half: it rounds to 43744. Between 32768 and 65504 (the largest half), representable half values are 32 apart, so most products land on a whole number and fract returns 0. Your "random" texture comes out mostly black.

In float, the output is coarser than it looks. A product around 40,000 sits in the range where 32-bit floats are spaced 1/256 apart, so the hash only produces about 256 distinct levels there. That's fine for a grayscale value, but it's not high-quality randomness. You can see the effect in the table: the values come out on neat fractions.

The size of the input matters too. If you feed raw positions in points into the hash, say (500, 800), the dot product is about 69,000 and floats at that size are spaced 1/128 apart. sin of such a large argument needs heavy range reduction. Metal compiles with fast math by default, which trades accuracy for speed in functions like sin, so different GPUs can disagree in exactly the digits this hash depends on. The same shader can then produce a different pattern on a different device. Feeding the hash small integer cell IDs, as every shader in this chapter does, avoids most of this.

If you need a hash that gives the same bits on every GPU, use integer arithmetic instead. This one is the PCG hash from Jarzynski and Olano's paper "Hash Functions for GPU Rendering" (2020):

uint pcgHash(uint v) {
    uint state = v * 747796405u + 2891336453u;
    uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;
    return (word >> 22u) ^ word;
}

// Drop-in replacement for random(): integer cell coordinates in, 0..1 out
float randomInt(float2 st) {
    uint2 cell = uint2(int2(floor(st)));
    uint h = pcgHash(cell.x + pcgHash(cell.y));
    return float(h >> 8) / 16777216.0;  // top 24 bits, exactly representable in float
}

The rest of the chapter sticks with the sin hash because it's short and it's what you'll see in most shader examples online.

Your first noise shader: one random value per cell

Random Noise

Digital static - a grid of random grayscale values demonstrating basic hash-based randomness

[[ stitchable ]] half4 randomNoise(float2 position, half4 color, float2 size) {
  // Convert to UV coordinates (normalized 0-1 range, explained in Chapter 2)
  float2 uv = position / size;

  // Scale up to see individual random values
  float2 scaledUV = uv * 10.0;

  // Get the integer part (which cell we're in)
  float2 cellID = floor(scaledUV);

  // Generate random value for this cell
  float randomValue = fract(sin(dot(cellID, float2(12.9898, 78.233))) * 43758.5453);

  return half4(randomValue, randomValue, randomValue, 1.0);
}
SwiftUI Metal Shader

uv * 10.0 divides the view into a 10 × 10 grid, and floor turns every position inside a cell into that cell's integer ID. A pixel at uv = (0.37, 0.82) gets cellID = (3, 8), as does every other pixel in that cell, so the whole cell gets one gray value. The size of the view comes from the size argument you pass from SwiftUI (.float2(proxy.size)); colorEffect doesn't provide it on its own.

The result is a grid of unrelated gray squares. Each value is random, but there's no relationship between neighbors, so it looks like static rather than like a material. The next step is to blend between the values.

Value noise: blending random values

Ken Perlin developed his noise function in the early 1980s, after working on the film Tron, and received an Academy Award for Technical Achievement for it in 1997. The key idea was to keep random values on a grid and fill the space between them with a smooth blend. The simplest version of that idea, which blends random values, is called value noise. (Perlin's own version blends random gradients; you'll build that next.)

Picture one cell of the grid. The hash gives a random value at each of its four corners. In SwiftUI, y grows downward, so the corner at offset (0, 1) is below the one at (0, 0):

 i + (0,0)            i + (1,0)
     a ●────────────────● b        f = position inside the cell,
       │                │              0..1 on each axis
       │      ✕ f       │
       │                │
     c ●────────────────● d
 i + (0,1)            i + (1,1)

For a pixel inside the cell, you blend a toward b horizontally, blend c toward d horizontally, then blend those two results vertically. That's bilinear interpolation. Every pixel in the cell computes the same four corner values on its own, which is why the hash has to be deterministic.

Smooth Noise (Value Noise)

Smooth interpolation between random values creates organic, cloud-like patterns - the foundation of natural textures

// Generate smooth noise by interpolating between random values
float valueNoise(float2 st) {
  // Grid coordinates
  float2 i = floor(st);  // Integer (cell) position
  float2 f = fract(st);  // Fractional position within cell

  // Four corners of current cell (y grows downward in SwiftUI)
  float a = random(i);                        // Top-left
  float b = random(i + float2(1.0, 0.0));    // Top-right
  float c = random(i + float2(0.0, 1.0));    // Bottom-left
  float d = random(i + float2(1.0, 1.0));    // Bottom-right

  // Smoothstep curve 3f^2 - 2f^3 (better than linear!)
  float2 u = f * f * (3.0 - 2.0 * f);

  // Bilinear interpolation
  float top = mix(a, b, u.x);      // Interpolate top edge
  float bottom = mix(c, d, u.x);   // Interpolate bottom edge
  return mix(top, bottom, u.y);    // Interpolate between edges
}

[[ stitchable ]] half4 smoothNoise(float2 position, half4 color, float2 size) {
  float2 uv = position / size;

  // Scale for visible noise pattern
  float noiseScale = 8.0;
  float noise = valueNoise(uv * noiseScale);

  return half4(noise, noise, noise, 1.0);
}
SwiftUI Metal Shader

Tracing one pixel

Say a pixel lands at st = (3.25, 5.5) after scaling. Then i = (3, 5) and f = (0.25, 0.5): a quarter of the way across the cell and halfway down.

  1. Corner values from the hash (rounded): a = random(3, 5) = 0.835, b = random(4, 5) = 0.916, c = random(3, 6) = 0.064, d = random(4, 6) = 0.500. Your GPU's sin may differ in the last digits, so your exact numbers can differ slightly.
  2. Smoothed weights: u.x = 0.25² × (3 - 0.5) = 0.156 and u.y = 0.5² × (3 - 1) = 0.5.
  3. Top edge: mix(0.835, 0.916, 0.156) = 0.848.
  4. Bottom edge: mix(0.064, 0.500, 0.156) = 0.133.
  5. Final: mix(0.848, 0.133, 0.5) = 0.490, a mid gray.

A pixel right at the top-left corner (f = (0, 0)) gets exactly a. As it moves across the cell, its value slides smoothly toward the other corners, and when it crosses into the next cell it continues from the same corner values the neighboring cell uses. There are no jumps.

What the interpolation curve does

mix(a, b, t) is linear in t. If you passed f straight in as t, the value would change at a constant rate inside each cell, then change at a different rate in the next cell. The slope jumps at every cell edge, and your eye picks those jumps up as a visible grid of creases.

The line u = f * f * (3.0 - 2.0 * f) reshapes f before it's used. It's the same 3t² - 2t³ curve as smoothstep(0.0, 1.0, f) from Chapter 4. Its slope is zero at 0 and at 1, so the value eases out of one corner and eases into the next, and the slope is zero on both sides of every cell edge. The creases disappear.

Smoothstep still has a weakness: its curvature (second derivative) isn't zero at the ends. It's 6 at f = 0 and -6 at f = 1, so the curvature flips sign abruptly at cell edges. You can't see that in a plain grayscale image, but it shows up when noise is used as a height map for lighting, where the shading depends on slope and curvature. Perlin's 2002 "improved noise" fixed this with a fifth-degree (quintic) curve, 6t⁵ - 15t⁴ + 10t³, which has zero slope and zero curvature at both ends (Chapter 7 calls it smootherstep):

// Quintic fade: drop-in replacement for the smoothstep line
float2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);

Here are the three curves side by side:

f       linear   smoothstep   quintic
0.25    0.25     0.156        0.104
0.5     0.5      0.5          0.5
0.75    0.75     0.844        0.896

The quintic curve spends longer near each corner's value and moves faster through the middle of the cell.

Why value noise looks blocky

Look at the value noise preview for a while and you'll start to see the grid. Every peak and every valley sits exactly on a grid corner, because the corners are where the random values live; everything in between is a blend. With eight cells across, you get bright and dark blobs arranged in rows and columns. Our eyes are very good at spotting that kind of alignment.

Gradient noise moves the features off the grid, as the next section shows.

Gradient noise (Perlin noise)

Instead of a random value at each corner, gradient noise stores a random direction: a unit vector, called a gradient. Each corner then contributes a tilted plane that passes through zero at the corner and slopes upward in the gradient's direction. dot(g, offset) is the height of that plane at the pixel, where offset is the vector from the corner to the pixel. The four heights are blended with the same smoothed u as before:

// Generate random gradient vector for a grid point
float2 randomGradient(float2 p) {
    // Random angle
    float angle = random(p) * 6.28318530718;  // 2π
    return float2(cos(angle), sin(angle));
}

float gradientNoise(float2 st) {
    float2 i = floor(st);
    float2 f = fract(st);
    
    // Calculate gradients at four corners
    float2 g00 = randomGradient(i);
    float2 g10 = randomGradient(i + float2(1.0, 0.0));
    float2 g01 = randomGradient(i + float2(0.0, 1.0));
    float2 g11 = randomGradient(i + float2(1.0, 1.0));
    
    // Calculate dot products
    float n00 = dot(g00, f);
    float n10 = dot(g10, f - float2(1.0, 0.0));
    float n01 = dot(g01, f - float2(0.0, 1.0));
    float n11 = dot(g11, f - float2(1.0, 1.0));
    
    // Smooth interpolation
    float2 u = f * f * (3.0 - 2.0 * f);
    
    // Interpolate
    float nx0 = mix(n00, n10, u.x);
    float nx1 = mix(n01, n11, u.x);
    return mix(nx0, nx1, u.y) * 0.5 + 0.5;  // Map roughly -0.7..0.7 to 0.15..0.85
}

At a grid corner, the offset to that corner is (0, 0), so its plane contributes 0, and the other corners' weights are 0 there. That means gradient noise is exactly 0 (0.5 after the remap) at every grid point. The hills and valleys form between grid points, and they lean in random directions set by the gradients. The grid is still there, but it's much harder to see, which is why gradient noise looks more natural than value noise at the same scale.

The raw output of 2D gradient noise with unit gradients stays within about -0.7 to 0.7, so after * 0.5 + 0.5 it covers roughly 0.15 to 0.85, not the full 0 to 1. If you need the full range, stretch it with smoothstep or a multiply and saturate.

To try it, the Xcode project has a stitchable gradientNoise(position, color, size) that calls this function with uv * 8.0 (Example 4 in Chapter 6).

Simplex noise

In 2001 Perlin published simplex noise. In 2D, it splits space into triangles instead of squares, so each pixel blends 3 corners instead of 4. Each corner's contribution fades out with distance on its own (the 0.5 - dot(x, x) falloff), so there's no bilinear interpolation step at all. The triangular grid also has fewer axis-aligned artifacts than a square grid. The savings grow with dimension: a 3D square-grid noise blends 8 corners, 3D simplex blends 4.

// 2D Simplex noise - more efficient than classic Perlin
float simplexNoise(float2 st) {
    const float F2 = 0.366025404;  // (sqrt(3) - 1) / 2
    const float G2 = 0.211324865;  // (3 - sqrt(3)) / 6
    
    // Skew the input space to determine simplex cell
    float s = (st.x + st.y) * F2;
    float2 i = floor(st + s);
    float t = (i.x + i.y) * G2;
    float2 i0 = i - t;  // Unskew cell origin back to (x,y) space
    float2 x0 = st - i0;  // The x,y distances from cell origin
    
    // Determine which simplex we're in
    float2 i1 = (x0.x > x0.y) ? float2(1.0, 0.0) : float2(0.0, 1.0);
    
    // Calculate corner offsets
    float2 x1 = x0 - i1 + G2;
    float2 x2 = x0 - 1.0 + 2.0 * G2;
    
    // Calculate contributions from three corners.
    // Hash the integer (skewed) corner coordinates so neighboring cells
    // agree on the gradient at a shared corner.
    float n0 = max(0.0, 0.5 - dot(x0, x0));
    n0 = n0 * n0 * n0 * n0 * dot(randomGradient(i), x0);
    
    float n1 = max(0.0, 0.5 - dot(x1, x1));
    n1 = n1 * n1 * n1 * n1 * dot(randomGradient(i + i1), x1);
    
    float n2 = max(0.0, 0.5 - dot(x2, x2));
    n2 = n2 * n2 * n2 * n2 * dot(randomGradient(i + 1.0), x2);
    
    // Scale output to [0, 1]
    return 70.0 * (n0 + n1 + n2) * 0.5 + 0.5;
}

The skew step is the only unfamiliar part. Multiplying by F2 stretches the triangle grid into a square grid, so floor can find the cell, and G2 maps the cell's corner back. Comparing x0.x and x0.y tells you which of the two triangles in that square the pixel is in. The gradients must be looked up with the integer corner IDs (i, i + i1, i + 1.0). If you hash the unskewed positions instead, two neighboring cells compute different gradients for the same corner and you get visible seams along the cell edges.

Fractal noise: stacking octaves

A single layer of noise has features of one size. Nature has many sizes at once: a mountain range has an overall shape, then ridges, then boulders, then gravel. You get the same effect by adding several layers of noise, each with smaller features and less strength than the one before. Each layer is called an octave (borrowed from music, where going up an octave doubles the frequency). The sum is called fractal noise, or fBm (fractional Brownian motion).

Two numbers control how the octaves relate:

  • Lacunarity is how much the frequency grows per octave. With lacunarity 2, each octave packs twice as many cells into the same space, so its features are half the size.
  • Gain (sometimes called persistence) is how much the amplitude shrinks per octave. With gain 0.5, each octave contributes half as much as the previous one.

Fractal Noise (Multi-Octave)

Layering multiple scales of noise creates complex, natural-looking textures with detail at every zoom level - animated for realism

[[ stitchable ]] half4 fractalNoise(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  float value = 0.0;      // Accumulated noise value
  float amplitude = 1.0;   // Strength of each octave
  float frequency = 1.0;   // Scale of each octave

  // Add 6 octaves of noise
  for(int i = 0; i < 6; i++) {
      // Add noise at current frequency and amplitude
      value += amplitude * valueNoise(uv * frequency * 4.0 + time * 0.1);

      // Each octave is twice as detailed but half as strong
      frequency *= 2.0;   // Double the frequency (smaller details)
      amplitude *= 0.5;   // Halve the amplitude (less influence)
  }

  // Normalize (sum of amplitudes: 1 + 0.5 + 0.25 + ... ≈ 2)
  value /= 2.0;

  return half4(value, value, value, 1.0);
}
SwiftUI Metal Shader

This shader uses lacunarity 2 and gain 0.5, with a base scale of 4 cells across the view. Here's what each pass through the loop adds:

octave   cells across view   amplitude   running max of value
0          4                 1.0         1.0
1          8                 0.5         1.5
2         16                 0.25        1.75
3         32                 0.125       1.875
4         64                 0.0625      1.9375
5        128                 0.03125     1.96875

The first octave sets the large shapes; the last one adds fine grain at 1/32 of the strength. Since valueNoise returns 0 to 1, the sum can reach 1.96875, which is why the shader divides by 2 at the end. If you change the octave count or the gain, divide by the new sum of amplitudes instead, or the result will be too dark or blow past 1.

Changing the two parameters changes the character of the texture:

  • Raising the gain toward 0.7 keeps the small octaves strong, giving a rough, gritty surface. Lowering it toward 0.3 gives soft, rolling shapes.
  • A lacunarity of exactly 2.0 means every grid line of one octave lands on a grid line of the next, and these aligned lines can reinforce each other. The marble example below uses 2.1 to break that alignment.

There's also a ceiling on useful octaves. Octave 5 here has 128 cells across the view. On a view 300 points wide on a 3x display (900 pixels), that's about 7 pixels per cell. Two more octaves would put 512 cells across 900 pixels, smaller than 2 pixels each. Detail smaller than a pixel can't be displayed; it only adds shimmer when the noise moves, and it still costs the same to compute.

The time * 0.1 offset slides every octave across the noise field. Because the noise is continuous, a small change in input gives a small change in output, and the texture drifts smoothly. (The Xcode version of this shader uses a speed of 0.6, so it moves faster than the web preview.)

Practical applications

Each of these examples uses value noise and fBm from above, then reshapes the output into a material.

Marble texture

Marble Texture

Realistic marble with flowing veins created by warping sine waves with noise - demonstrates practical material generation

[[ stitchable ]] half4 marbleTexture(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  // Create flowing marble veins
  float noise = 0.0;
  float frequency = 4.0;
  float amplitude = 1.0;

  // Multiple octaves for detail
  for(int i = 0; i < 4; i++) {
      noise += amplitude * valueNoise(uv * frequency + time * 0.02);
      frequency *= 2.1;  // Slightly non-doubling for more organic look
      amplitude *= 0.5;
  }

  // Create vein pattern with sine
  float marble = sin(uv.x * 10.0 + noise * 10.0) * 0.5 + 0.5;

  // Color: white marble with gray veins
  half3 white = half3(0.95, 0.95, 0.9);
  half3 gray = half3(0.4, 0.4, 0.45);
  half3 marbleColor = mix(gray, white, marble);

  return half4(marbleColor.r, marbleColor.g, marbleColor.b, 1.0);
}
SwiftUI Metal Shader

Without noise, sin(uv.x * 10.0) would draw straight vertical stripes. Adding noise * 10.0 inside the sin shifts each stripe left or right by a different amount at every height, so the stripes bend into veins. Because the noise sum ranges from 0 to about 1.9, the phase shift is up to about 19 radians, roughly three full stripe widths. Lower the 10.0 on noise and the veins straighten; raise it and they tangle.

Animated clouds

Cloudy Skies

Realistic animated clouds using multiple layers of noise moving at different speeds over a sky gradient

[[ stitchable ]] half4 cloudySkies(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  // Two layers of clouds moving at different speeds
  float clouds1 = 0.0;
  float clouds2 = 0.0;

  // Layer 1: Large, slow clouds
  float2 offset1 = float2(time * 0.01, time * 0.005);
  for(int i = 0; i < 3; i++) {
      float freq = pow(2.0, float(i));
      clouds1 += valueNoise((uv + offset1) * freq * 2.0) / freq;
  }

  // Layer 2: Smaller, faster clouds
  float2 offset2 = float2(time * 0.02, -time * 0.01);
  for(int i = 0; i < 4; i++) {
      float freq = pow(2.0, float(i));
      clouds2 += valueNoise((uv + offset2) * freq * 4.0) / freq;
  }

  // Combine layers
  float cloudDensity = clouds1 * 0.7 + clouds2 * 0.3;
  cloudDensity = smoothstep(0.4, 0.7, cloudDensity);

  // Sky gradient
  float3 skyTop = float3(0.3, 0.5, 0.9);
  float3 skyBottom = float3(0.7, 0.8, 1.0);
  float3 skyColor = mix(skyBottom, skyTop, uv.y);

  // Cloud color
  float3 cloudColor = float3(1.0, 1.0, 1.0);

  // Mix sky and clouds
  float3 finalColor = mix(skyColor, cloudColor, cloudDensity);

  return half4(finalColor.r, finalColor.g, finalColor.b, 1.0);
}
SwiftUI Metal Shader

Two fBm layers drift in different directions at different speeds, which gives a sense of depth. Dividing by freq is the same as a gain of 0.5. The important line is smoothstep(0.4, 0.7, cloudDensity): density below 0.4 becomes clear sky, above 0.7 becomes solid cloud, and only the band in between is soft. Without it, the whole sky would be a gray haze. Move the two thresholds apart for wispier clouds, closer together for harder edges.

One thing to check: uv.y is 0 at the top of the view in SwiftUI, so mix(skyBottom, skyTop, uv.y) puts the light skyBottom color at the top. Swap the two colors (or use 1.0 - uv.y) if you want the deeper blue overhead.

The Xcode project's cloudySkies (Example 7) is a more advanced version with four extra parameters: complexity (the octave count), evolution (nudges lacunarity and gain), turbulence (warps the coordinates with noise before sampling) and contrast (a pow on the result). It also normalizes by the running sum of amplitudes, as described in the fBm section.

Wood grain

Wood Grain

Natural wood texture with growth rings and grain detail created by warping sine patterns with noise

[[ stitchable ]] half4 woodGrain(
  float2 position,
  half4 color,
  float2 size
) {
  float2 uv = position / size;

  // Rotate for wood grain direction
  float angle = 0.1;  // Slight angle
  float2 rotatedUV = float2(
      uv.x * cos(angle) - uv.y * sin(angle),
      uv.x * sin(angle) + uv.y * cos(angle)
  );

  // Base wood ring pattern
  float rings = sin((rotatedUV.x + valueNoise(rotatedUV * 3.0) * 0.1) * 30.0);

  // Add fine detail
  float detail = valueNoise(rotatedUV * 50.0) * 0.1;
  float grain = rings + detail;

  // Wood colors
  half3 lightWood = half3(0.7, 0.5, 0.3);
  half3 darkWood = half3(0.4, 0.25, 0.1);

  half3 woodColor = mix(darkWood, lightWood, grain * 0.5 + 0.5);

  return half4(woodColor.r, woodColor.g, woodColor.b, 1.0);
}
SwiftUI Metal Shader

Wood uses the same trick as marble with two scales of noise doing different jobs. Low-frequency noise (rotatedUV * 3.0) bends the stripes gently, the way growth rings wander. High-frequency noise (rotatedUV * 50.0) is added after the sin, so it doesn't move the rings at all; it only adds fine streaks on top. The small 0.1 radian rotation keeps the rings from running perfectly parallel to the view's edges.

Performance

Relative cost of each technique

Cost is roughly proportional to how many times the hash runs per pixel:

  1. Hash-based random: 1 hash call.
  2. Value noise: 4 hash calls plus 3 mixes.
  3. Gradient noise: 4 hash calls, each followed by a cos and sin to build the gradient, plus 4 dot products.
  4. Simplex noise: 3 corner contributions, each with a hash, cos and sin, so a little cheaper than gradient noise in 2D.
  5. Fractal noise: the cost of one noise call times the number of octaves. Six octaves of value noise is 24 hash calls per pixel.

Where the cost really comes from

// Both lines cost the same: one valueNoise call per pixel, every frame.
// A shader keeps nothing between frames, so there's no way to
// "calculate once" inside it.
float scrolling = valueNoise(uv * 10.0 + time);
float pulsing   = sin(time + valueNoise(uv * 10.0) * 2.0);

// What does change the cost is how many noise calls you make.
for(int i = 0; i < 10; i++) {  // 10 octaves = 40 hash calls per pixel

for(int i = 0; i < 4; i++) {   // 4 octaves = 16 hash calls, often enough

The first pair shows a common misconception. Moving time outside the noise call changes how the texture animates (scrolling versus pulsing in place), but the shader still recomputes the noise for every pixel on every frame. If a noise texture never changes, the way to avoid recomputing it is to not run a shader for it at all: render it once into an image and display that.

What you control inside the shader is the number of noise calls. Use as few octaves as the view size can show (see the pixel calculation in the fBm section), and if a view isn't animating, don't drive it with a timeline.

Common pitfalls

Pitfall 1: Banding in gradients

// WRONG: Visible stepping in smooth gradients
float noise = floor(valueNoise(uv * 10.0) * 10.0) / 10.0;  // Quantized

// CORRECT: Smooth gradients
float noise = valueNoise(uv * 10.0);

floor(x * 10.0) / 10.0 snaps the noise to 10 levels, so you get flat contour bands instead of a smooth surface. Sometimes that's the look you want (a topographic map or a posterized style), but if you didn't intend it, look for rounding like this in your math.

Pitfall 2: Noise outside the 0 to 1 range

// WRONG: Noise values can exceed 0-1 range
float noise = valueNoise(uv) * 2.0;  // Can be > 1!

// CORRECT: Keep in valid range or clamp
float noise = saturate(valueNoise(uv) * 2.0);

Scaling noise up to boost contrast pushes part of it above 1, and everything above 1 clips to flat white. The same thing happens with fBm if you forget to divide by the sum of amplitudes. saturate clamps to 0 to 1, which at least makes the clipping predictable. For contrast that keeps detail, use smoothstep(low, high, noise) instead.

Pitfall 3: Letting the octave count run unchecked

// RISKY: no upper bound. A slider set to 20 means 80 hash calls per pixel.
for(int octave = 0; octave < userOctaves; octave++) {

// BETTER: let the user choose, but cap it at what the view can show
int octaves = min(userOctaves, 6);
for(int octave = 0; octave < octaves; octave++) {

Cost grows linearly with the octave count: each octave adds one more noise call. A loop count that comes from a shader argument is fine, because every pixel runs the same number of iterations (the Xcode cloudySkies does exactly this with its complexity parameter). The risk is letting that number grow without a cap, since past the pixel limit the extra octaves cost time and add nothing visible.

Challenges

Challenge 1: Static texture generator

Static Texture Generator Example

Create a staticTexture shader that generates TV static with a controllable grain size. Treat grainSize as the number of cells across the view: floor(uv * grainSize) gives each cell its ID, and the hash gives it a gray value. Higher values mean more, smaller grains.

The solution in the Xcode project goes a step further. It also takes elapsed time (from a TimelineView) so the grains re-randomize every frame, and it blends the static at 20% over a photo with mix(color, staticColor, 0.2). To animate yours, add a .float(time) argument before grainSize and feed time into the hash input.

SwiftUI Template:

struct StaticTextureView: View {
    @State private var grainSize: Float = 100.0
    
    var body: some View {
        VStack {
            Rectangle() // Or replace with image
                .visualEffect { content, proxy in
                    content.colorEffect(ShaderLibrary.staticTexture(
                        .float2(proxy.size),
                        .float(grainSize)
                    ))
                }
                .frame(height: 300)
            
            HStack {
                Text("Grain Size")
                Slider(value: $grainSize, in: 10...200)
            }
            .padding()
        }
    }
}

Challenge 2: Animated water caustics

Animated Water Caustics Example

Create an animated waterCaustics shader using several layers of value noise. Caustics are the bright, wobbly lines of light you see on the bottom of a swimming pool. A good approach: sample three noise layers at different scales, each moving in a different direction, take a weighted sum, then raise it to a high power (pow(x, 4.0)). The power pushes most values toward 0 and keeps only the brightest overlaps, which turns soft blobs into thin bright highlights. Mix the result between a water blue and white.

SwiftUI Template:

struct WaterCausticsView: View {
    @State private var timeValue: Float = 0.0
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        Rectangle()
            .fill(Color.blue.opacity(0.3))
            .visualEffect { content, proxy in
                content.colorEffect(ShaderLibrary.waterCaustics(
                    .float2(proxy.size),
                    .float(timeValue)
                ))
            }
            .frame(height: 400)
            .onReceive(timer) { _ in
                timeValue += 1/60.0
            }
    }
}

Challenge 3: Procedural fire

Procedural Fire Example

Create a fireEffect shader using noise and a color ramp. Use a few octaves of noise that scroll with time so the flames rise, multiply by a shape mask that is strongest in the middle column, then map the resulting intensity through black, red, orange, yellow and white.

The Xcode solution adds an amplitude parameter (with its own slider) that sets the starting amplitude of the noise octaves. If you add it, append .float(amplitude) after .float(intensity) in the template.

SwiftUI Template:

struct ProceduralFireView: View {
    @State private var timeValue: Float = 0.0
    @State private var intensity: Float = 1.0
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.black)
                .visualEffect { content, proxy in
                    content.colorEffect(ShaderLibrary.fireEffect(
                        .float2(proxy.size),
                        .float(timeValue),
                        .float(intensity)
                    ))
                }
                .frame(height: 300)
            
            HStack {
                Text("Intensity")
                Slider(value: $intensity, in: 0.5...2.0)
            }
            .padding()
        }
        .onReceive(timer) { _ in
            timeValue += 1/60.0
        }
    }
}

Challenge 4: Touch particle system (advanced)

Touch Particle System Example

Create a touchParticles shader that spawns particles at the touch location, each with its own random properties. Think of it as a magic drawing board.

The shader can't store particles between frames, so each particle has to be recomputed from scratch every frame. Give each particle an index, derive its spawn time from that index and the current time, and use the hash with the particle's index as input to pick its direction, speed and size. Its position is then a formula of its age: start point plus velocity times age, plus gravity. The touch position arrives normalized to 0 to 1, so compare it with uv, not with position.

Requirements:

  • Particles spawn at the touch position with random velocities.
  • Each particle has its own size, color variation and lifetime.
  • Particles fade out smoothly over time.
  • Use noise to add organic wobble to their movement.
  • The result should look like sparkles or fairy dust following your finger.

SwiftUI Template:

struct TouchParticleView: View {
    @State private var touchPosition = CGPoint(x: 0.5, y: 0.5)
    @State private var isTouching = false
    @State private var timeValue: Float = 0.0
    @State private var particleIntensity: Float = 1.0
    @State private var colorScheme: Float = 0.0
    
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Text("Touch Particle System")
                .font(.title2)
                .padding()
            
            Text("Draw with your finger to create particles")
                .font(.caption)
                .foregroundColor(.secondary)
            
            GeometryReader { geometry in
                Rectangle()
                    .fill(Color.black)
                    .visualEffect { content, proxy in
                        content.colorEffect(ShaderLibrary.touchParticles(
                            .float2(proxy.size),
                            .float(timeValue),
                            .float2(Float(touchPosition.x), Float(touchPosition.y)),
                            .float(isTouching ? 1.0 : 0.0),
                            .float(particleIntensity),
                            .float(colorScheme)
                        ))
                    }
                    .gesture(
                        DragGesture(minimumDistance: 0)
                            .onChanged { value in
                                isTouching = true
                                touchPosition = CGPoint(
                                    x: value.location.x / geometry.size.width,
                                    y: value.location.y / geometry.size.height
                                )
                            }
                            .onEnded { _ in
                                isTouching = false
                            }
                    )
            }
            .frame(height: 400)
            .border(Color.gray, width: 1)
            
            VStack(spacing: 15) {
                HStack {
                    Text("Intensity")
                    Slider(value: $particleIntensity, in: 0.5...2.0)
                }
                
                Picker("Color Scheme", selection: Binding(
                    get: { Int(colorScheme) },
                    set: { colorScheme = Float($0) }
                )) {
                    Text("Fire").tag(0)
                    Text("Magic").tag(1)
                    Text("Ice").tag(2)
                }
                .pickerStyle(SegmentedPickerStyle())
            }
            .padding()
        }
        .onReceive(timer) { _ in
            timeValue += 1/60.0
        }
    }
}

Want the Challenges Solutions?

Get the full Xcode project with solutions to all challenges, bonus examples, and clean, runnable code.

Get the Full Project →

Validation Questions

  1. Why can't shaders use traditional random() functions?

    • Answer: A CPU random generator keeps hidden state that each call updates. In a shader, thousands of pixel invocations run in parallel with no memory between frames, so shared state would hand out numbers in whatever order the GPU schedules the pixels. The pattern would change every frame (flicker), and neighboring pixels couldn't agree on shared values. A hash of the position gives each location the same value every time, and any pixel can compute the value for any location.
  2. What makes the hash function fract(sin(dot(st, float2(12.9898,78.233))) * 43758.5453) work?

    • Answer: The dot product combines the 2D coordinate into one number, with different weights so (1, 2) and (2, 1) don't collide. sin makes the mapping nonlinear. Multiplying by a large number turns small differences in the sine value into large differences, and fract keeps only the fractional digits, which vary unpredictably from input to input. The constants have no special meaning; they just give a reasonable distribution.
  3. Why is it a bad idea to compute this hash in half, and what else affects its quality?

    • Answer: half can't represent 43758.5453 (it becomes 43744), and above 32768 consecutive half values are 32 apart, so fract of the product is almost always 0. Even in float the result only has about 256 distinct levels at that magnitude. Large inputs (raw positions in points instead of small cell IDs) make it worse, and fast-math sin can differ between GPUs in exactly the digits the hash keeps. Keep it in float with small inputs, or use an integer hash.
  4. What's the difference between value noise and gradient noise, and why does value noise look blockier?

    • Answer: Value noise stores a random value at each grid corner and blends between them, so every peak and valley sits on a grid point and the features line up in rows and columns. Gradient noise stores a random direction at each corner; each corner contributes a sloped plane that is zero at the corner. The result is 0 (mid gray after remapping) at every grid point, and its hills and valleys form between grid points, which hides the grid.
  5. What does the f * f * (3.0 - 2.0 * f) line do, and why might you replace it with a quintic curve?

    • Answer: It's smoothstep. It reshapes the position inside the cell so the slope is zero at both edges, which removes the creases you'd get with linear interpolation. Its curvature is still nonzero at the edges, which shows up when noise drives lighting or normals. The quintic 6f⁵ - 15f⁴ + 10f³ has zero slope and zero curvature at both edges.
  6. Why do we use multiple octaves of noise, and what do lacunarity and gain control?

    • Answer: Natural textures have detail at several scales at once. Each octave adds noise at a higher frequency and lower amplitude. Lacunarity is the frequency multiplier per octave (2 means features half the size each time); gain is the amplitude multiplier (0.5 means half the strength each time). With 6 octaves at gain 0.5, the amplitudes sum to 1.96875, so you divide by that to keep the result in 0 to 1.
  7. How do you ensure noise-based animations don't flicker?

    • Answer: Move smoothly through noise space, for example noise(uv + time * speed), instead of feeding time into the hash as a seed. Smooth noise is continuous, so a small change in input gives a small change in output. Hashing time directly re-randomizes every cell on every frame, which is only what you want for effects like TV static.
  8. What advantages does simplex noise have over classic Perlin noise?

    • Answer: It uses a triangular grid, so a 2D sample blends 3 corners instead of 4 (in 3D, 4 instead of 8), and each corner's contribution fades out on its own without an interpolation step. It also shows fewer axis-aligned artifacts. In 2D the speed difference is modest; the savings grow with the number of dimensions.

Further Exploration

  • Worley (cellular) noise: each pixel's value is its distance to the nearest of a set of random points, giving cell and stone patterns. It builds on the Voronoi technique from Chapter 5.
  • Blue noise: random points spread evenly, without the clumps white noise produces. Often used for dithering.
  • Curl noise: a noise-derived vector field with no sources or sinks, used to move particles in fluid-like swirls.
  • Domain warping: using one noise to offset the coordinates of another, as the Xcode cloudySkies does with its turbulence parameter.

Next Chapter Preview: So far your shapes and masks have had hard edges, and you've seen smoothstep turn thresholds into soft transitions. Chapter 7 is about edges: why hard edges look jagged on screen (aliasing), how to make anti-aliased shapes with smoothstep and a width of about one pixel, and how to build smooth masks, reveals and gradients.