Frosted Glass
A pane of frosted glass as a SwiftUI layer effect. Each point of the pane shows the average of sixteen samples of the view around it, on a spiral; each tiny facet of the rough surface moves and turns its spiral its own way, which is the grain; the pane has an edge, a rim and a shadow, and frost that lies thick in places and thin in others. The color of the glass isn't in the shader: SwiftUI passes it as an argument.
· SwiftUI Effects · SwiftUI Effect shader
Teaches A layer effect that scatters what is behind it, tinted by a color SwiftUI passes
Builds on Flowing Color Field (hash21, value noise), Heat Haze
Watch
The idea
A SwiftUI layer effect is a Metal function marked [[ stitchable ]] that SwiftUI runs once for every point of a view. It is handed the view itself as layer, and returns the color that point should show. layer.sample(position) is the view unchanged. Heat Haze read the view from one other place for each point, which bent it. This effect reads it from sixteen places and averages them, which is what frosted glass does to light.
Clear glass lets each ray through on its own line, so you see what is behind it. Frosted glass has a rough surface, etched or sandblasted, and every bump sends the light arriving from behind in a slightly different direction. Stand in front of it and each point of the pane shows you light from a whole patch of what is behind, mixed together. A wider patch is a deeper frost.
The subject is the card Ray Kiln previews SwiftUI effects on, 320 by 200 points, and everything is measured in points from the view's top left, as SwiftUI measures them. It is built in five steps, each a whole effect you can run in the playground or in an app. The last thing it needs is a color for the glass, and that color is the first one in Ray Kiln that comes from outside the shader.
Stage 1 · Sixteen samples
through is the whole trick. It takes sixteen samples of the layer around a point and returns their average. The samples sit on a spiral: each is turned 2.39996 radians on from the last, the golden angle, about 137.5 degrees, and sits at radius * sqrt((i + 0.5) / 16) from the middle. The golden angle never lines two samples up along one direction, and the square root spaces them so each covers the same area of the disc, so sixteen samples cover it evenly without a grid.
Here the whole view is behind the glass, and the radius opens and closes every five seconds, from nothing to blur points, so you can see what it does. Two things show. With only sixteen samples a sharp edge, like the letters, becomes sixteen faint copies of itself rather than a smooth smear. And the card's own edge softens: a sample past the view reads the clear layer around it. The header line // @maxSampleOffset 24 24 is how far past a point the effect may read, in points; SwiftUI needs the same number, and every stage keeps it.
stage-1-blur.metal
// Stage 1 · Sixteen samples
// Rough glass sends the light from each point behind it many ways at once,
// so a point of the pane shows the average of the view around it. Sixteen
// samples on a spiral are enough for a soft blur.
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param volume 0.7 0.0 1.0 How loud the glass sings
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float blur) {
// The blur opens and closes every five seconds, to show what it does.
float radius = blur * (0.5 - 0.5 * cos(time * 1.2566));
return through(layer, position, radius, 0.0);
}
float2 sound(float t, constant Params& p) {
// One glass rubbed at its rim: a pure tone that wavers a little, with
// a faint second tone two octaves up. It swells as the blur opens.
float ph = 6.2832 * 146.83 * t + 0.6 * sin(t * 4.3);
float note = sin(ph) + 0.18 * sin(4.21 * ph);
float open = 0.5 - 0.5 * cos(t * 1.2566);
float2 v = note * (0.25 + 0.75 * open) * (0.5 + p.blur / 32.0);
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.42 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}Stage 2 · A pane with an edge
Now the glass is a pane. paneEdge is the distance from a point to the edge of a rounded rectangle, negative inside it: 56% of the view wide, 80% of it high, with corners of 14 points. Its middle slides side to side by a fifth of the view's width, paneSlide, once in about eighteen seconds at slide 1, so the words pass under it and out again. The effect asks SwiftUI for the view's size to place it.
Outside the pane, the view is shown as it is, a little darker near the pane: 1 - 0.35 * exp(-d / 5), a shadow that is gone a few points out. Inside, it is the stage 1 blur at its full radius. A bright line 1.6 points inside the edge is the rim, where a real pane's cut edge catches the light.
stage-2-pane.metal34 new lines since stage 1
// Stage 2 · A pane with an edge
// The glass is a pane now: a rounded rectangle that slides across the view.
// Inside it the view is blurred; outside it is as it was, in the pane's
// shadow, and a bright rim marks the edge.
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param slide 1.0 0.0 3.0 How fast the pane slides across the view
// @param volume 0.7 0.0 1.0 How loud the glass sings
// How far the pane's middle is from the view's, as a share of its width:
// it slides side to side, once in about eighteen seconds.
float paneSlide(float t, float slide) {
return 0.2 * sin(t * 0.35 * slide);
}
// The distance to the edge of the pane, in points: a rounded rectangle
// 56% of the view wide and 80% of it high. Negative inside.
float paneEdge(float2 position, float2 size, float t, float slide) {
float2 middle = size * float2(0.5 + paneSlide(t, slide), 0.5);
float2 q = abs(position - middle) - size * float2(0.28, 0.4) + 14.0;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 14.0;
}
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float2 size,
float blur, float slide) {
half4 clear = layer.sample(position);
float d = paneEdge(position, size, time, slide);
if (d > 0.0) {
// Outside the pane: the view as it is, in the pane's soft shadow.
clear.rgb *= half(1.0 - 0.35 * exp(-d / 5.0));
return clear;
}
half4 c = through(layer, position, blur, 0.0);
// The rim: a bright line just inside the edge.
float rim = smoothstep(2.4, 0.0, abs(d + 1.6));
c.rgb += half(0.3 * rim) * c.a;
return c;
}
float2 sound(float t, constant Params& p) {
// Four glasses rubbed at their rims, a chord on D: each a pure tone
// that wavers a little, with a faint second tone two octaves up.
float2 v = 0.0;
for (int n = 0; n < 4; n++) {
float hz = n == 0 ? 146.83 : n == 1 ? 220.0 : n == 2 ? 369.99 : 440.0;
// Each swells and fades at its own slow pace.
float pace = 0.31 + 0.07 * float(n);
float swell = 0.5 + 0.5 * sin(t * pace + float(n) * 1.9);
swell = smoothstep(0.25, 0.8, swell);
// More blur dulls the high glasses, as it dulls the picture.
float dull = 1.0 / (1.0 + float(n) * p.blur * 0.06);
float ph = 6.2832 * hz * t + 0.6 * sin(t * (4.3 + float(n)));
float note = sin(ph) + 0.18 * sin(4.21 * ph);
float side = float(n) * 0.5 - 0.75;
v += note * swell * dull * float2(0.5 - 0.4 * side, 0.5 + 0.4 * side);
}
// The pane's slide leans the chord the way the pane has gone.
float pan = clamp(paneSlide(t, p.slide) * 2.5, -0.6, 0.6);
v *= float2(1.0 - pan, 1.0 + pan);
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.5 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}7 lines from stage 1 that are gone
float time, float blur) {
⋯
float radius = blur * (0.5 - 0.5 * cos(time * 1.2566));
return through(layer, position, radius, 0.0);
⋯
float ph = 6.2832 * 146.83 * t + 0.6 * sin(t * 4.3);
⋯
float open = 0.5 - 0.5 * cos(t * 1.2566);
float2 v = note * (0.25 + 0.75 * open) * (0.5 + p.blur / 32.0);
⋯
float2 o = tanh(v * 0.42 * 1.4) / 1.4;Stage 3 · Facets
A blur is what polished glass does when it is out of focus. Frosted glass looks different up close: it has a grain. The surface is tiny facets, each leaning its own way, and each shows the view from a place of its own.
floor(position / grain) names the facet a point is on; grain is its size in points. hash21 turns that name into a random number, with integer arithmetic so that SwiftUI's picture and Ray Kiln's agree on every GPU. Two of them are made for each facet. One is the direction the facet leans, and the middle of its spiral moves that way by up to half the blur's radius, times rough. The other turns the spiral. Since every facet's sixteen samples now land in different places, the sixteen copies of stage 1 are gone: they have been traded for noise, which is what frost looks like. Set rough to 0 and the facets stop leaning; each still turns its own spiral, so the copies stay away and a finer, more even grain is left.
The furthest a sample can land is 16 points of blur plus 8 of lean, the 24 that // @maxSampleOffset promises.
stage-3-facets.metal25 new lines since stage 2
// Stage 3 · Facets
// A blur is polished glass out of focus. Frosted glass is rough: its
// surface is tiny facets, each leaning its own way, so each shows the view
// from a place of its own. That is the grain.
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param grain 0.8 0.4 6.0 The size of a facet of the rough surface, in points
// @param rough 0.6 0.0 1.0 How much each facet throws the light its own way
// @param slide 1.0 0.0 3.0 How fast the pane slides across the view
// @param volume 0.7 0.0 1.0 How loud the glass sings
// A whole-number point in, a random 0 to 1 out, the same on every GPU.
float hash21(float2 p) {
int2 i = int2(floor(p));
uint h = uint(i.x) * 1597334677u ^ uint(i.y) * 3812015801u;
h ^= h >> 16;
h *= 2246822519u;
h ^= h >> 13;
return float(h & 0xFFFFFFu) / 16777216.0;
}
// How far the pane's middle is from the view's, as a share of its width:
// it slides side to side, once in about eighteen seconds.
float paneSlide(float t, float slide) {
return 0.2 * sin(t * 0.35 * slide);
}
// The distance to the edge of the pane, in points: a rounded rectangle
// 56% of the view wide and 80% of it high. Negative inside.
float paneEdge(float2 position, float2 size, float t, float slide) {
float2 middle = size * float2(0.5 + paneSlide(t, slide), 0.5);
float2 q = abs(position - middle) - size * float2(0.28, 0.4) + 14.0;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 14.0;
}
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float2 size,
float blur, float grain, float rough,
float slide) {
half4 clear = layer.sample(position);
float d = paneEdge(position, size, time, slide);
if (d > 0.0) {
// Outside the pane: the view as it is, in the pane's soft shadow.
clear.rgb *= half(1.0 - 0.35 * exp(-d / 5.0));
return clear;
}
// The facet of the surface this point is on, and two random numbers
// for it: which way it leans, and how its spiral is turned.
float2 facet = floor(position / grain);
float h1 = hash21(facet), h2 = hash21(facet + 57.0);
float lean = 6.2832 * h1;
float2 off = float2(cos(lean), sin(lean)) * h2 * 0.5 * blur * rough;
half4 c = through(layer, position + off, blur, 6.2832 * h2);
// The rim: a bright line just inside the edge.
float rim = smoothstep(2.4, 0.0, abs(d + 1.6));
c.rgb += half(0.3 * rim) * c.a;
return c;
}
float2 sound(float t, constant Params& p) {
// Four glasses rubbed at their rims, a chord on D: each a pure tone
// that wavers a little, with a faint second tone two octaves up.
float2 v = 0.0;
for (int n = 0; n < 4; n++) {
float hz = n == 0 ? 146.83 : n == 1 ? 220.0 : n == 2 ? 369.99 : 440.0;
// Each swells and fades at its own slow pace.
float pace = 0.31 + 0.07 * float(n);
float swell = 0.5 + 0.5 * sin(t * pace + float(n) * 1.9);
swell = smoothstep(0.25, 0.8, swell);
// More blur dulls the high glasses, as it dulls the picture.
float dull = 1.0 / (1.0 + float(n) * p.blur * 0.06);
// Four copies of each, detuned as the facets spread the light:
// more `rough`, a wider, rougher tone.
float note = 0.0;
for (int k = 0; k < 4; k++) {
float seed = float(n) * 7.0;
float off = hash21(float2(float(k), seed)) - 0.5;
float f = hz * (1.0 + 0.024 * off * p.rough);
float ph = 6.2832 * hash21(float2(seed, float(k) + 9.0));
ph += 6.2832 * f * t + 0.6 * sin(t * (4.3 + float(k)));
note += 0.25 * (sin(ph) + 0.18 * sin(4.21 * ph));
}
float side = float(n) * 0.5 - 0.75;
v += note * swell * dull * float2(0.5 - 0.4 * side, 0.5 + 0.4 * side);
}
// The pane's slide leans the chord the way the pane has gone.
float pan = clamp(paneSlide(t, p.slide) * 2.5, -0.6, 0.6);
v *= float2(1.0 - pan, 1.0 + pan);
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.9 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}5 lines from stage 2 that are gone
float blur, float slide) {
⋯
half4 c = through(layer, position, blur, 0.0);
⋯
float ph = 6.2832 * hz * t + 0.6 * sin(t * (4.3 + float(n)));
float note = sin(ph) + 0.18 * sin(4.21 * ph);
⋯
float2 o = tanh(v * 0.5 * 1.4) / 1.4;Stage 4 · The color of the glass
Glass has a color. It could be written into the shader as three numbers, but then an app could never change it. So it is an argument: half4 tint, after SwiftUI's own two. In Swift it is passed as .color(...), and it arrives premultiplied, as every color in a SwiftUI effect does: its red, green and blue already multiplied by its alpha, so a half-transparent color arrives with all three halved.
The line // @color tint 0.74 0.9 1 The color of the glass says which color Ray Kiln passes, a pale blue, and it is the default in the Swift code under the source on this page.
Colored glass does two things to light. What passes through it is multiplied by its color, c.rgb * tint.rgb, so this pale blue takes a quarter of the red out of the card's orange. And frost scatters some of the room's light back at you in the glass's own color, tint.rgb * 0.22, times the view's alpha so that a transparent view stays transparent. tinting blends from the plain scattered view to that. The rim takes the glass's color too.
stage-4-tint.metal5 new lines since stage 3
// Stage 4 · The color of the glass
// Glass has a color, and this one is not written in the shader: it is an
// argument, a half4 that SwiftUI passes with .color(...). The // @color line
// says which color Ray Kiln passes, and is a color well beside the picture.
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param grain 0.8 0.4 6.0 The size of a facet of the rough surface, in points
// @param rough 0.6 0.0 1.0 How much each facet throws the light its own way
// @param tinting 0.5 0.0 1.0 How much of the color of the glass shows
// @param slide 1.0 0.0 3.0 How fast the pane slides across the view
// @param volume 0.7 0.0 1.0 How loud the glass sings
// @color tint 0.74 0.9 1 The color of the glass
// A whole-number point in, a random 0 to 1 out, the same on every GPU.
float hash21(float2 p) {
int2 i = int2(floor(p));
uint h = uint(i.x) * 1597334677u ^ uint(i.y) * 3812015801u;
h ^= h >> 16;
h *= 2246822519u;
h ^= h >> 13;
return float(h & 0xFFFFFFu) / 16777216.0;
}
// How far the pane's middle is from the view's, as a share of its width:
// it slides side to side, once in about eighteen seconds.
float paneSlide(float t, float slide) {
return 0.2 * sin(t * 0.35 * slide);
}
// The distance to the edge of the pane, in points: a rounded rectangle
// 56% of the view wide and 80% of it high. Negative inside.
float paneEdge(float2 position, float2 size, float t, float slide) {
float2 middle = size * float2(0.5 + paneSlide(t, slide), 0.5);
float2 q = abs(position - middle) - size * float2(0.28, 0.4) + 14.0;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 14.0;
}
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float2 size, half4 tint,
float blur, float grain, float rough,
float tinting, float slide) {
half4 clear = layer.sample(position);
float d = paneEdge(position, size, time, slide);
if (d > 0.0) {
// Outside the pane: the view as it is, in the pane's soft shadow.
clear.rgb *= half(1.0 - 0.35 * exp(-d / 5.0));
return clear;
}
// The facet of the surface this point is on, and two random numbers
// for it: which way it leans, and how its spiral is turned.
float2 facet = floor(position / grain);
float h1 = hash21(facet), h2 = hash21(facet + 57.0);
float lean = 6.2832 * h1;
float2 off = float2(cos(lean), sin(lean)) * h2 * 0.5 * blur * rough;
half4 c = through(layer, position + off, blur, 6.2832 * h2);
// The color of the glass, as SwiftUI passes it: premultiplied. Light
// going through is multiplied by it, and the frost adds some of its own.
half3 glass = c.rgb * tint.rgb + tint.rgb * 0.22h * c.a;
c.rgb = mix(c.rgb, glass, half(tinting));
// The rim: a bright line just inside the edge.
float rim = smoothstep(2.4, 0.0, abs(d + 1.6));
c.rgb += tint.rgb * half(0.3 * rim) * c.a;
return c;
}
float2 sound(float t, constant Params& p) {
// Four glasses rubbed at their rims, a chord on D: each a pure tone
// that wavers a little, with a faint second tone two octaves up.
float2 v = 0.0;
for (int n = 0; n < 4; n++) {
float hz = n == 0 ? 146.83 : n == 1 ? 220.0 : n == 2 ? 369.99 : 440.0;
// Each swells and fades at its own slow pace.
float pace = 0.31 + 0.07 * float(n);
float swell = 0.5 + 0.5 * sin(t * pace + float(n) * 1.9);
swell = smoothstep(0.25, 0.8, swell);
// More blur dulls the high glasses, as it dulls the picture.
float dull = 1.0 / (1.0 + float(n) * p.blur * 0.06);
// Four copies of each, detuned as the facets spread the light:
// more `rough`, a wider, rougher tone.
float note = 0.0;
for (int k = 0; k < 4; k++) {
float seed = float(n) * 7.0;
float off = hash21(float2(float(k), seed)) - 0.5;
float f = hz * (1.0 + 0.024 * off * p.rough);
float ph = 6.2832 * hash21(float2(seed, float(k) + 9.0));
ph += 6.2832 * f * t + 0.6 * sin(t * (4.3 + float(k)));
note += 0.25 * (sin(ph) + 0.18 * sin(4.21 * ph));
}
float side = float(n) * 0.5 - 0.75;
v += note * swell * dull * float2(0.5 - 0.4 * side, 0.5 + 0.4 * side);
}
// The pane's slide leans the chord the way the pane has gone.
float pan = clamp(paneSlide(t, p.slide) * 2.5, -0.6, 0.6);
v *= float2(1.0 - pan, 1.0 + pan);
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.9 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}3 lines from stage 3 that are gone
float time, float2 size,
⋯
float slide) {
⋯
c.rgb += half(0.3 * rim) * c.a;Stage 5 · Frosted Glass
Frost is never even. frostAt is the thickness of the frost at a point, from two sizes of value noise, patches about 50 points across that drift slowly up the pane. Where the noise is low the frost thins to 1 - frost, and the thickness scales both the blur's radius and the tinting, so through a thin patch the words are nearly readable and nearly their own color.
And a facet now and then lines up just right and throws the light behind it straight at you. Each facet's first random number sets when: sin(time * 1.7 + ...) comes close to 1 for a moment every 3.7 seconds, and the facet adds up to 70% of the light it already shows, more where the frost is thick. Over the white letters that is a sparkle; over the dark corner of the card almost nothing, since a glint can only return light that is there.
shade(), from the finished shader
frosted-glass.metal, the whole file33 new lines since stage 4
// Ray Kiln · Frosted Glass
//
// @episode Frosted Glass
// @length 60
// @variation 30
// @variations 1,2,3,4,8,9,10,11
// @sweeps blur, grain, tinting
// @still 21.0
// @teaches A layer effect that scatters what is behind it, tinted by a color SwiftUI passes
// @category SwiftUI Effect
// @tags swiftui, layer effect, blur, frosted glass, premultiplied alpha, golden angle, signed distance fields, procedural sound
// @final Frosted glass | The frost lies thick in some places and thin in others, and drifts; where it is thin the view shows through almost clear, and here and there a facet catches the light.
//
// A pane of frosted glass is a SwiftUI layer effect: a function SwiftUI runs
// once for every point of a view, which reads the view itself through
// `layer.sample`. Rough glass sends the light from each point behind it many
// ways at once, so a point of the pane shows the average of the view around
// it: sixteen samples on a spiral. Each facet of the surface leans its own
// way, which is the grain; the pane has an edge, a rim and a shadow; and the
// glass has a color, which SwiftUI passes in as an argument.
//
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param grain 0.8 0.4 6.0 The size of a facet of the rough surface, in points
// @param rough 0.6 0.0 1.0 How much each facet throws the light its own way
// @param tinting 0.5 0.0 1.0 How much of the color of the glass shows
// @param frost 0.7 0.0 1.0 How uneven the frost is, thick in places and thin
// @param slide 1.0 0.0 3.0 How fast the pane slides across the view
// @param volume 0.7 0.0 1.0 How loud the glass sings
// @color tint 0.74 0.9 1 The color of the glass
// A whole-number point in, a random 0 to 1 out, the same on every GPU.
float hash21(float2 p) {
int2 i = int2(floor(p));
uint h = uint(i.x) * 1597334677u ^ uint(i.y) * 3812015801u;
h ^= h >> 16;
h *= 2246822519u;
h ^= h >> 13;
return float(h & 0xFFFFFFu) / 16777216.0;
}
// Value noise: random values at grid corners, blended smoothly.
float vnoise(float2 p) {
float2 i = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
float a = hash21(i), b = hash21(i + float2(1, 0));
float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
// How far the pane's middle is from the view's, as a share of its width:
// it slides side to side, once in about eighteen seconds.
float paneSlide(float t, float slide) {
return 0.2 * sin(t * 0.35 * slide);
}
// The distance to the edge of the pane, in points: a rounded rectangle
// 56% of the view wide and 80% of it high. Negative inside.
float paneEdge(float2 position, float2 size, float t, float slide) {
float2 middle = size * float2(0.5 + paneSlide(t, slide), 0.5);
float2 q = abs(position - middle) - size * float2(0.28, 0.4) + 14.0;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 14.0;
}
// How thick the frost is at a point, 0 to 1: patches about 50 points
// across that drift up the pane. `frost` is how thin the thin places get.
float frostAt(float2 position, float t, float frost) {
float2 p = position / 50.0 + float2(0.0, t * 0.05);
float n = vnoise(p) * 0.65 + vnoise(p * 2.3 + 9.0) * 0.35;
return 1.0 - frost * smoothstep(0.62, 0.34, n);
}
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float2 size, half4 tint,
float blur, float grain, float rough,
float tinting, float frost, float slide) {
half4 clear = layer.sample(position);
float d = paneEdge(position, size, time, slide);
if (d > 0.0) {
// Outside the pane: the view as it is, in the pane's soft shadow.
clear.rgb *= half(1.0 - 0.35 * exp(-d / 5.0));
return clear;
}
// The frost here: thin frost spreads the light less far.
float thick = frostAt(position, time, frost);
float radius = blur * thick;
// The facet of the surface this point is on, and two random numbers
// for it: which way it leans, and how its spiral is turned.
float2 facet = floor(position / grain);
float h1 = hash21(facet), h2 = hash21(facet + 57.0);
float lean = 6.2832 * h1;
float2 off = float2(cos(lean), sin(lean)) * h2 * 0.5 * radius * rough;
half4 c = through(layer, position + off, radius, 6.2832 * h2);
// The color of the glass, as SwiftUI passes it: premultiplied. Light
// going through is multiplied by it, and the frost adds some of its own.
half3 glass = c.rgb * tint.rgb + tint.rgb * 0.22h * c.a;
c.rgb = mix(c.rgb, glass, half(tinting * thick));
// A facet now and then catches the light behind it and throws it
// straight at the eye: a glint, brighter where the frost is thick.
float glint = smoothstep(0.97, 1.0, sin(time * 1.7 + 6.2832 * h1));
c.rgb += c.rgb * half(glint * 0.7 * thick * rough);
// The rim: a bright line just inside the edge.
float rim = smoothstep(2.4, 0.0, abs(d + 1.6));
c.rgb += tint.rgb * half(0.3 * rim) * c.a;
return c;
}
float2 sound(float t, constant Params& p) {
// Four glasses rubbed at their rims, a chord on D: each a pure tone
// that wavers a little, with a faint second tone two octaves up.
float2 v = 0.0;
for (int n = 0; n < 4; n++) {
float hz = n == 0 ? 146.83 : n == 1 ? 220.0 : n == 2 ? 369.99 : 440.0;
// Each swells and fades on its own slow noise, the frost's own.
float swell = vnoise(float2(t * 0.22 + float(n) * 13.0, float(n)));
swell = smoothstep(0.25, 0.8, swell);
// More blur dulls the high glasses, as it dulls the picture.
float dull = 1.0 / (1.0 + float(n) * p.blur * 0.06);
// Four copies of each, detuned as the facets spread the light:
// more `rough`, a wider, rougher tone.
float note = 0.0;
for (int k = 0; k < 4; k++) {
float seed = float(n) * 7.0;
float off = hash21(float2(float(k), seed)) - 0.5;
float f = hz * (1.0 + 0.024 * off * p.rough);
float ph = 6.2832 * hash21(float2(seed, float(k) + 9.0));
ph += 6.2832 * f * t + 0.6 * sin(t * (4.3 + float(k)));
note += 0.25 * (sin(ph) + 0.18 * sin(4.21 * ph));
}
float side = float(n) * 0.5 - 0.75;
v += note * swell * dull * float2(0.5 - 0.4 * side, 0.5 + 0.4 * side);
}
// The pane's slide leans the chord the way the pane has gone.
float pan = clamp(paneSlide(t, p.slide) * 2.5, -0.6, 0.6);
v *= float2(1.0 - pan, 1.0 + pan);
// Frost ticking: on each of eight ticks a second, a chance of a small
// high ping that dies in a few hundredths of a second.
float beat = floor(t * 8.0);
for (int k = 0; k < 3; k++) {
float n = beat - float(k);
if (hash21(float2(n, 3.0)) > 0.16 * (0.3 + p.frost)) continue;
float since = t - (n + hash21(float2(n, 5.0))) / 8.0;
if (since < 0.0) continue;
float hz = 2400.0 + 3600.0 * hash21(float2(n, 7.0));
float ping = sin(6.2832 * hz * since) * exp(-since * 55.0);
ping *= smoothstep(0.0, 0.002, since);
float side = hash21(float2(n, 11.0)) - 0.5;
v += ping * float2(0.5 - side, 0.5 + side) * 0.4;
}
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.9 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}6 lines from stage 4 that are gone
float tinting, float slide) {
⋯
float2 off = float2(cos(lean), sin(lean)) * h2 * 0.5 * blur * rough;
half4 c = through(layer, position + off, blur, 6.2832 * h2);
⋯
c.rgb = mix(c.rgb, glass, half(tinting));
⋯
float pace = 0.31 + 0.07 * float(n);
float swell = 0.5 + 0.5 * sin(t * pace + float(n) * 1.9);The sound
Four wine glasses rubbed at their rims, tuned to a chord on D: 146.83, 220, 369.99 and 440 Hz. Each is a pure tone whose phase wavers a little, with a faint second tone 4.21 times higher, a little over two octaves up. Each swells and fades on its own slow value noise, the vnoise the frost is made of.
The picture's sliders play it. Every glass is four copies of itself, detuned by random amounts from hash21, up to 1.2% either way at rough 1, as the facets spread the light: rougher glass, a wider and rougher tone. blur dulls the higher glasses, as it dulls the picture. The chord leans left and right with the pane, read from the same paneSlide. Over it the frost ticks: on each of eight ticks a second there is a chance, 16% at the default frost, of a small ping between 2400 and 6000 Hz that dies in a few hundredths of a second.
None of this is SwiftUI's: the file it takes leaves sound out. At the defaults the peak is about −6.4 dBFS and the average (RMS) about −20.3 dBFS over the minute; with rough, frost and volume at their highest, slide at 3 and blur at 0, −3.2 dBFS and −14.5 dBFS.
New in Ray Kiln
Color arguments for SwiftUI effects. Until now an effect's arguments were numbers: sliders, the clock, the view's size. A half4 argument with a line // @color name r g b is now a color (a fourth number is its alpha, and words after the numbers describe it). Ray Kiln passes it as SwiftUI's .color does, premultiplied, and that was checked against SwiftUI's own picture: a half-transparent Color(red: 1, green: 0.69, blue: 0.38) arrives as half4(0.5, 0.345, 0.19, 0.5) in both.
In the playground the effect's panel has a color well for each color; so does the Mac app's inspector, with its next release. Picking a color rewrites the // @color line and the code runs again with it, so a draft or a Share link keeps the color with the code. In the Swift package that Download for Xcode makes (Ray Kiln Pro) the color is a Color argument, .frostedGlass(tint: .mint), whose default is the line. The SwiftUI effects page has the rest, and the duotone template now takes its two colors the same way.
This episode's tint is the first: open stage 4 or the finished effect in the playground and change the well.
Try this
- In the playground, change the
tintwell to an amber, such as1 0.75 0.3: the pane warms, and the purple side of the card goes red-brown under it. - Give the color an alpha, a fourth number:
// @color tint 0.74 0.9 1 0.4 The color of the glass. The glass darkens, because a see-through color arrives with its red, green and blue already scaled down. - Set
roughto 0: the facets stop leaning and the glints stop, and a fine, even grain is left, since each facet still turns its own spiral. Then change6.2832 * h2to0.0in the call tothrough: with every spiral the same, the sixteen copies of each letter come back. - Set
grainto 6: glass bricks, each showing its own piece of the view. - Set
frostto 0 and then 1: an even pane, then one with clear patches drifting up it. - Set
tintingto 0: clear frosted glass, the card's own colors scattered. - In
through, change16to4in all three places: a much rougher frost for a quarter of the work. Then try 48. - In
paneEdge, change both14.0to80.0: the corners round until the pane's short sides are half circles.
Parameters
Pick a parameter and drag the slider. Each frame is the same moment of the shader, with only that one setting changed.
| Parameter | Default | Range | What it does |
|---|---|---|---|
blur | 10.0 | 0.0 to 16.0 | How far the glass spreads the light, in points |
grain | 0.8 | 0.4 to 6.0 | The size of a facet of the rough surface, in points |
rough | 0.6 | 0.0 to 1.0 | How much each facet throws the light its own way |
tinting | 0.5 | 0.0 to 1.0 | How much of the color of the glass shows |
frost | 0.7 | 0.0 to 1.0 | How uneven the frost is, thick in places and thin |
slide | 1.0 | 0.0 to 3.0 | How fast the pane slides across the view |
volume | 0.7 | 0.0 to 1.0 | How loud the glass sings |
More from this shader
The same shader 8 more ways: each from a different moment, with different settings, one after another. Each chapter below says which settings moved most, then lists them all.
Wallpapers
A still from the shader, rendered at full size for a desktop screen. Free to use as your wallpaper.
A clip to post
Fifteen seconds of the shader with its sound, sized for posting: square, for feeds. Free to post, ideally with a link to this page.
Made from this episode
The full source
This is the whole episode: the effect, the parameters and the sound.
frosted-glass.metal
// Ray Kiln · Frosted Glass
//
// @episode Frosted Glass
// @length 60
// @variation 30
// @variations 1,2,3,4,8,9,10,11
// @sweeps blur, grain, tinting
// @still 21.0
// @teaches A layer effect that scatters what is behind it, tinted by a color SwiftUI passes
// @category SwiftUI Effect
// @tags swiftui, layer effect, blur, frosted glass, premultiplied alpha, golden angle, signed distance fields, procedural sound
// @final Frosted glass | The frost lies thick in some places and thin in others, and drifts; where it is thin the view shows through almost clear, and here and there a facet catches the light.
//
// A pane of frosted glass is a SwiftUI layer effect: a function SwiftUI runs
// once for every point of a view, which reads the view itself through
// `layer.sample`. Rough glass sends the light from each point behind it many
// ways at once, so a point of the pane shows the average of the view around
// it: sixteen samples on a spiral. Each facet of the surface leans its own
// way, which is the grain; the pane has an edge, a rim and a shadow; and the
// glass has a color, which SwiftUI passes in as an argument.
//
// @subject card
// @backdrop dark
// @maxSampleOffset 24 24
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h>
using namespace metal;
// @param blur 10.0 0.0 16.0 How far the glass spreads the light, in points
// @param grain 0.8 0.4 6.0 The size of a facet of the rough surface, in points
// @param rough 0.6 0.0 1.0 How much each facet throws the light its own way
// @param tinting 0.5 0.0 1.0 How much of the color of the glass shows
// @param frost 0.7 0.0 1.0 How uneven the frost is, thick in places and thin
// @param slide 1.0 0.0 3.0 How fast the pane slides across the view
// @param volume 0.7 0.0 1.0 How loud the glass sings
// @color tint 0.74 0.9 1 The color of the glass
// A whole-number point in, a random 0 to 1 out, the same on every GPU.
float hash21(float2 p) {
int2 i = int2(floor(p));
uint h = uint(i.x) * 1597334677u ^ uint(i.y) * 3812015801u;
h ^= h >> 16;
h *= 2246822519u;
h ^= h >> 13;
return float(h & 0xFFFFFFu) / 16777216.0;
}
// Value noise: random values at grid corners, blended smoothly.
float vnoise(float2 p) {
float2 i = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
float a = hash21(i), b = hash21(i + float2(1, 0));
float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}
// How far the pane's middle is from the view's, as a share of its width:
// it slides side to side, once in about eighteen seconds.
float paneSlide(float t, float slide) {
return 0.2 * sin(t * 0.35 * slide);
}
// The distance to the edge of the pane, in points: a rounded rectangle
// 56% of the view wide and 80% of it high. Negative inside.
float paneEdge(float2 position, float2 size, float t, float slide) {
float2 middle = size * float2(0.5 + paneSlide(t, slide), 0.5);
float2 q = abs(position - middle) - size * float2(0.28, 0.4) + 14.0;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 14.0;
}
// How thick the frost is at a point, 0 to 1: patches about 50 points
// across that drift up the pane. `frost` is how thin the thin places get.
float frostAt(float2 position, float t, float frost) {
float2 p = position / 50.0 + float2(0.0, t * 0.05);
float n = vnoise(p) * 0.65 + vnoise(p * 2.3 + 9.0) * 0.35;
return 1.0 - frost * smoothstep(0.62, 0.34, n);
}
// The view through rough glass at one point: sixteen samples on a spiral
// around `at`, each the golden angle on from the last and a little further
// out, as far as `radius` points. `turn` turns the whole spiral.
half4 through(SwiftUI::Layer layer, float2 at, float radius, float turn) {
half4 sum = half4(0.0h);
for (int i = 0; i < 16; i++) {
float r = radius * sqrt((float(i) + 0.5) / 16.0);
float a = float(i) * 2.39996 + turn;
sum += layer.sample(at + r * float2(cos(a), sin(a)));
}
return sum / 16.0h;
}
[[ stitchable ]] half4 frostedGlass(float2 position, SwiftUI::Layer layer,
float time, float2 size, half4 tint,
float blur, float grain, float rough,
float tinting, float frost, float slide) {
half4 clear = layer.sample(position);
float d = paneEdge(position, size, time, slide);
if (d > 0.0) {
// Outside the pane: the view as it is, in the pane's soft shadow.
clear.rgb *= half(1.0 - 0.35 * exp(-d / 5.0));
return clear;
}
// The frost here: thin frost spreads the light less far.
float thick = frostAt(position, time, frost);
float radius = blur * thick;
// The facet of the surface this point is on, and two random numbers
// for it: which way it leans, and how its spiral is turned.
float2 facet = floor(position / grain);
float h1 = hash21(facet), h2 = hash21(facet + 57.0);
float lean = 6.2832 * h1;
float2 off = float2(cos(lean), sin(lean)) * h2 * 0.5 * radius * rough;
half4 c = through(layer, position + off, radius, 6.2832 * h2);
// The color of the glass, as SwiftUI passes it: premultiplied. Light
// going through is multiplied by it, and the frost adds some of its own.
half3 glass = c.rgb * tint.rgb + tint.rgb * 0.22h * c.a;
c.rgb = mix(c.rgb, glass, half(tinting * thick));
// A facet now and then catches the light behind it and throws it
// straight at the eye: a glint, brighter where the frost is thick.
float glint = smoothstep(0.97, 1.0, sin(time * 1.7 + 6.2832 * h1));
c.rgb += c.rgb * half(glint * 0.7 * thick * rough);
// The rim: a bright line just inside the edge.
float rim = smoothstep(2.4, 0.0, abs(d + 1.6));
c.rgb += tint.rgb * half(0.3 * rim) * c.a;
return c;
}
float2 sound(float t, constant Params& p) {
// Four glasses rubbed at their rims, a chord on D: each a pure tone
// that wavers a little, with a faint second tone two octaves up.
float2 v = 0.0;
for (int n = 0; n < 4; n++) {
float hz = n == 0 ? 146.83 : n == 1 ? 220.0 : n == 2 ? 369.99 : 440.0;
// Each swells and fades on its own slow noise, the frost's own.
float swell = vnoise(float2(t * 0.22 + float(n) * 13.0, float(n)));
swell = smoothstep(0.25, 0.8, swell);
// More blur dulls the high glasses, as it dulls the picture.
float dull = 1.0 / (1.0 + float(n) * p.blur * 0.06);
// Four copies of each, detuned as the facets spread the light:
// more `rough`, a wider, rougher tone.
float note = 0.0;
for (int k = 0; k < 4; k++) {
float seed = float(n) * 7.0;
float off = hash21(float2(float(k), seed)) - 0.5;
float f = hz * (1.0 + 0.024 * off * p.rough);
float ph = 6.2832 * hash21(float2(seed, float(k) + 9.0));
ph += 6.2832 * f * t + 0.6 * sin(t * (4.3 + float(k)));
note += 0.25 * (sin(ph) + 0.18 * sin(4.21 * ph));
}
float side = float(n) * 0.5 - 0.75;
v += note * swell * dull * float2(0.5 - 0.4 * side, 0.5 + 0.4 * side);
}
// The pane's slide leans the chord the way the pane has gone.
float pan = clamp(paneSlide(t, p.slide) * 2.5, -0.6, 0.6);
v *= float2(1.0 - pan, 1.0 + pan);
// Frost ticking: on each of eight ticks a second, a chance of a small
// high ping that dies in a few hundredths of a second.
float beat = floor(t * 8.0);
for (int k = 0; k < 3; k++) {
float n = beat - float(k);
if (hash21(float2(n, 3.0)) > 0.16 * (0.3 + p.frost)) continue;
float since = t - (n + hash21(float2(n, 5.0))) / 8.0;
if (since < 0.0) continue;
float hz = 2400.0 + 3600.0 * hash21(float2(n, 7.0));
float ping = sin(6.2832 * hz * since) * exp(-since * 55.0);
ping *= smoothstep(0.0, 0.002, since);
float side = hash21(float2(n, 11.0)) - 0.5;
v += ping * float2(0.5 - side, 0.5 + side) * 0.4;
}
// tanh rounds off the loudest moments instead of letting them clip.
float2 o = tanh(v * 0.9 * 1.4) / 1.4;
// Fade in over the first half second and out over the last, so the
// sound starts from silence and ends in it.
float fade = smoothstep(0.0, 0.5, t) * smoothstep(60.0, 59.0, t);
return o * p.volume * fade;
}Running it in your own project
This shader is a SwiftUI effect: a [[ stitchable ]] function SwiftUI runs on a view’s pixels. The standalone download above is the file as SwiftUI takes it. Add it to your app’s target, and Xcode compiles it into the app’s Metal library, where ShaderLibrary.frostedGlass finds it. Its sound is Ray Kiln’s alone: SwiftUI has no use for it, so the standalone file leaves it out.
Then apply it to any view with .layerEffect. Flatten the view first with .compositingGroup(), so the effect sees one picture rather than each layer of the view on its own. The numbers below are the sliders’ defaults, and each .color is the shader’s // @color line, which SwiftUI passes premultiplied by its opacity; start is when the view appeared, a Date you keep, and size the view’s size, from a GeometryReader or .visualEffect.
Using it, in SwiftUI
TimelineView(.animation) { context in
let time = context.date.timeIntervalSince(start)
yourView
.compositingGroup()
.layerEffect(
ShaderLibrary.frostedGlass(.float(time), .float2(size), .color(Color(red: 0.74, green: 0.9, blue: 1)), .float(10.0), .float(0.8), .float(0.6), .float(0.5), .float(0.7), .float(1.0)),
maxSampleOffset: CGSize(width: 24, height: 24)
)
}Positions are in points from the view’s top left, as SwiftUI measures them, and maxSampleOffset is how far past its edges the effect may reach. The SwiftUI effects page has more of them, and the playground runs any on SwiftUI’s own pictures.
More in SwiftUI Effects
Press ? for keyboard shortcuts.
