Communitygithub.com

liquid-glass

实现 Apple WWDC25 Liquid Glass(液态玻璃)材质、控件与全交互。当用户要求做苹果液态玻璃 / 玻璃拟态 UI、Liquid Glass 按钮·卡片·导航栏·Dock·菜单、透明折射玻璃,需要点击、展开、分离合并、拖拽、按压反馈,或需要实时光路分析、在 Web(WebGL/CSS)、C++/Qt6、SwiftUI 中复刻该材质时使用。覆盖透镜折射、Snell 位移、Fresnel 边缘、RGB 色散、厚度梯度、透镜唇、内发光、Regular/Clear 变体、自适应明暗、scroll edge 渐隐,以及多面板独立 draw call 的性能架构。附带 starter/glass-starter.html 最小可运行骨架(1 program、1 次 draw、已实跑验证),优先从它改起,不要从零手写 shader。

liquid-glass 是什么?

liquid-glass is a Claude Code agent skill that 实现 Apple WWDC25 Liquid Glass(液态玻璃)材质、控件与全交互。当用户要求做苹果液态玻璃 / 玻璃拟态 UI、Liquid Glass 按钮·卡片·导航栏·Dock·菜单、透明折射玻璃,需要点击、展开、分离合并、拖拽、按压反馈,或需要实时光路分析、在 Web(WebGL/CSS)、C++/Qt6、SwiftUI 中复刻该材质时使用。覆盖透镜折射、Snell 位移、Fresnel 边缘、RGB 色散、厚度梯度、透镜唇、内发光、Regular/Clear 变体、自适应明暗、scroll edge 渐隐,以及多面板独立 draw call 的性能架构。附带 starter/glass-starter.html 最小可运行骨架(1 program、1 次 draw、已实跑验证),优先从它改起,不要从零手写 shader。.

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Cyt-56/liquid-glass-webgl/tree/main/legacy

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Liquid Glass Implementation

0. Fastest Path (Follow This, Have a Usable Glass Panel in 10 Minutes)

Do not write a shader from scratch. The success rate of writing 400 lines of GLSL from zero is extremely low; "it doesn't look right" is almost always because of this step.

  1. Copy starter/glass-starter.html to the delivery directory.
  2. Only change the five numbers in CONFIG at the top of the file (refract / mag / rim / disp / tint). Refresh the page immediately after each change to see the effect.
  3. Replace the content drawn by drawBG() with the actual content that should be under the glass. This is the most critical step: 90% of the glass effect comes from what is underneath it.
  4. Adjust the width, height, and corner radius (PANEL) to determine the glass shape (r = h/2 gives a complete capsule).
  5. To add more glass panels, duplicate the rectangle and draw each with its own uRect in a loop (see Section 3 for architecture).

The starter has only ~90 lines of shader, 1 program, 1 draw call, and already includes: Snell refraction, thickness-weighted lateral displacement, Fresnel rim, edge milky white, top specular band, bottom bright arc, RGB dispersion, lens lip, and press feedback. It has been verified by running and taking screenshots in Chrome (including software-rendered SwiftShader).

To see it in action: open starter/glass-starter.html in a browser, drag your mouse over the glass, and watch the blue bar magnify and shift.

0.5 Three Hard Rules

  1. You must open and look at it before delivery. Writing code without opening it is the #1 reason for failure with this skill. If there is no GUI, use a headless screenshot:

    chrome --headless=new --enable-unsafe-swiftshader --virtual-time-budget=5000 ^
           --window-size=820,700 --screenshot=out.png "file:///<absolute_path>"
    

    Then actually look at the image to confirm the glass is visible. Without screenshot evidence, do not claim completion.

  2. Shader errors must be displayed on the page. console.error is invisible in a screenshot; you will only see a black screen and not know why. Immediately after compileShader:

    if (!gl.getShaderParameter(s, gl.COMPILE_STATUS))
      appendPre("Shader compilation failed:\n" + gl.getShaderInfoLog(s));   // appendPre = append a red <pre> to the body
    
  3. Start simple, then add complexity. First get one glass panel correct, then add a second. If you try refraction + interaction + multi-panel + animation all at once, you won't be able to isolate the bug when something goes wrong.

0.6 Doesn't Look Right? Check by Symptom

SymptomMost Likely CauseFix
Screen is completely black, only background visiblePanel wasn't drawn at allCheck that uRect is passed, uRad is not 0, and draw uses 4 vertices with TRIANGLE_STRIP
Mirror image / upside-down text inside the glassTexture Y-axis is flippedIf UNPACK_FLIP_Y is enabled, sample as 1.0 - uv.y; if not, use uv.y directly
No visible refraction, just blurDisplacement too smalloff = lat * tpx * refract, ensure tpx is several tens of pixels; temporarily set refract to 3 to see if anything changes
Hard rainbow band around the edgeDispersion applied across the entire edgeMultiply dispersion by eW*eW squared attenuation to separate channels only at the outermost edge
Glass looks like gray plasticUnderlying content is too monotonousEnsure high-contrast content (text, colored bars, grid) is underneath; otherwise any parameter adjustment looks like fog
Top specular follows mouse like a flashlightSpecular band is narrowed horizontallyKeep the entire edge's base brightness, use the pointer only for local enhancement (0.7 base + 0.3 boost)
Animation feels sluggish and softUsing first-order exponential easingSwitch to a second-order spring, damping 0.60.7, allow 58% overshoot (see Section 6.5)
Frame rate drops below 30Too many panels / full-screen draw per frameRasterize only each glass's own AABB; ≤ 10 panels on screen; reduce background upload frequency

For the flagship version (multi-panel, full interactivity, ray path analysis), continue reading; for a single glass panel, the starter is sufficient; read through Section 4.

1. Platform Decision

GoalAsset to UseDescription
Single glass panel / quick prototypingstarter/glass-starter.html90-line shader, 1 draw call, verified by running. Modify this one; do not start from scratch
Web / demo / interactive prototype (preferred)liquid-glass-studio.htmlSingle WebGL canvas + 9 glass panels + full interactivity + real-time ray path analysis. Real Snell refraction, dispersion, thickness gradient
Just need one glass panel, no fussliquid-glass-webgl.htmlLightweight single-panel, single-pass version; approximate displacement, no interaction layer
Cannot use WebGL / needs a fallbackliquid-glass-css.htmlbackdrop-filter + SVG displacement; approximate behavior but no per-pixel refraction
Desktop C++ / custom renderercpp/glass_math.h + cpp/qt6/Pure math library + Qt6 controls; port formulas into GLSL for production
iOS / macOS nativeswift/LiquidGlassDemo.swiftOfficial .glassEffect API; fallback to SimulatedGlass on older versions

Why WebGL is preferred: Refraction requires per-pixel sampling of the underlying content; CSS can only do whole-block displacement, and the edge "lens lip" is impossible to achieve.

2. Assets and Documentation

liquid-glass/
├── starter/
│   └── glass-starter.html        # Minimum runnable skeleton: 90-line shader, 1 program, 1 draw call, verified by running
├── liquid-glass-studio.html      # Flagship: full interaction + real-time raytrace (main deliverable of this skill)
├── liquid-glass-webgl.html       # Lightweight single-panel version
├── liquid-glass-css.html         # CSS/SVG fallback
├── cpp/
│   ├── glass_math.h              # Pure functions for SDF, squircle, Snell/Fresnel, BK7 dispersion, thickness/lip/arc rim
│   └── qt6/                      # CMake project
├── swift/LiquidGlassDemo.swift   # Official API + simulated fallback
└── references/
    ├── feature-matrix.md         # 22-item Session 219 feature matrix, coverage per target, design redlines
    ├── optics-model.md           # Optical physics model and parameter ranges (must read before writing shader)
    ├── interaction-playbook.md   # Click/expand/separate/drag state machine and acceptance checklist
    └── swiftui-api.md            # SwiftUI glass API signatures and notes

3. Rendering Architecture (Studio Version)

Two programs, 9 draw calls. Never stuff multiple glass panels into a single full-screen pass using a uniform array.

Pass 1  pBg   : full-screen quad, directly samples background texture
Pass 2  pGl   : same quad VBO, each panel translates/scales to its own AABB, one drawArrays call

The vertex shader maps the [-1,1] quad to the panel:

uniform vec2 uC, uH, uRes;          // center, half-width/height, canvas size (all in device pixels)
void main(){
  vec2 cN = (uC/uRes)*2.0 - 1.0;  cN.y = -cN.y;      // screen top-left origin → NDC
  vec2 hN = ((uH + vec2(6.0))/uRes)*2.0;             // expand 6px for antialiasing
  gl_Position = vec4(cN + vec2(aPos.x, -aPos.y)*hN, 0.0, 1.0);
}

The fragment shader uses gl_FragCoord to compute the screen position (not a varying, which would be local coordinates within the translated quad):

vec2 px = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y);
float d  = sdRoundBox(px - uC, uH, uRad);
float aa = smoothstep(-1.0, 1.4, d);
if(aa > 0.995) discard;                 // discard pixels outside the AABB contour
  gl_FragColor = vec4(gcol, 1.0 - aa);    // transition with alpha at the edge

Enable gl.enable(BLEND) + blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA) before the draw, and disable it afterward.

This way, each glass panel only rasterizes its own rectangle; the fill rate for 8 panels is roughly equivalent to one full-screen pass -- an order of magnitude faster than "full screen x 8 loops".

Scalar uniforms required for each glass panel per draw (fixed order, none may be omitted):

uniformMeaningSource
uC uHScreen center / half-width/height (device pixels, top-left origin)(g.x+g.w/2)*dpr etc.
uRadCorner radius (device pixels)min(g.radius, min(w,h)/2)*dpr
uVariant uThick uMagMulVariant / thick material / panel-level magnificationPanel properties
uHover uPress uGlow uActiveInteraction states 0~1Per-frame spring values
uPtrNormalized pointer coordinates within the panel, -1~1(cx-c)/(w/2)
uAmbUnderlying ambient color rgbgetImageData sample
GlobaluRes uTex uRefraction uRim uTint uDisp uN uMode uContrast uOpaque uMag uWireSet once per frame

4. Optical Model (Must Read This Section Before Writing Shaders)

Seven steps, order is fixed:

  1. Profile: Use sdRoundBox to get the signed distance d (negative inside). Normalize depth as x = clamp(-d/band, 0, 1), where 0 = edge and 1 = center; band = max(5, min(hx,hy)*0.30).
  2. Convex Height Field: H(x) = sqrt(1 - (1-x)²), H'(x) = v/sqrt(1-v²) (v = clamp(1-x, 0.02, 0.9995)). Use sqrt instead of pow -- pow is much slower on ANGLE.
  3. Angle of Incidence: sinI = min(H'/sqrt(1+H'²), 0.62), thI = asin(sinI), thT = asin(sinI/n), n = 1.5168 (BK7). The upper limit of 0.62 is a hard constraint: setting it to 0.93 will make edge displacement reach 200px, pushing the entire panel into a black block.
  4. Thickness: tpx = mdim*(0.05 + 0.28*H)*(1 + 0.40*thick)*vg, vg = 1 + 0.24*(1 - smoothstep(-0.85, 0.35, q.y)) (thicker at bottom, thinner at top). tpx is "pixel thickness", normal range is 0.1 ~ 0.4 * mdim. Values over 0.5 will definitely cause distortion.
  5. Displacement: lat = tan(thI-thT), off = -dir*lat*tpx*uRefraction*Tf, plus an edge-clamping term -dir*(1-smoothstep(0,0.28,x))*tpx*0.22. Finally off = clamp(off, -10, 10) -- this clamping is the only safeguard against the edge "forcibly pulling in" distant content.
  6. Focus / Lens Lip: focal = uMag * uMagMul * (0.50*cW - 0.40*eW), cW = smoothstep(0.10,0.90,x), eW = 1-smoothstep(0,0.62,x). Center focal > 0 → sample point moves toward center → magnification; edge focal < 0 → sample point moves outward → content is bent outward, creating Apple's lip. 1-focal must always be positive, otherwise a local 180-degree flip occurs, resulting in upside-down text. uMagMul is the panel-level magnification (see Section 6): small glasses have higher curvature and magnify more, while large sheets are nearly flat and magnify less. Without this coefficient, using the same uMag would cause a 214x300 text panel to be magnified into garbled characters, while a 158x126 lens would be too weak. The mapping of panel size to magMul: lens 1.30, plate 0.55, capsule 0.85, panel 0.60, dock 0.80, nav 0.90.
  7. Sampling and Composition: sp = c + rel*(1-focal) - off; sample three channels separated by ±uDisp*7*eW for dispersion; then apply in order: variant darken, uAmb ambient color spill (0.10), tint brightness compression 0.58*L + 0.133, dark field fill light +vec3(0.048,0.051,0.058), Fresnel rim + milky white + top specular + bottom bright arc ((1+0.75*press)), inner glow.

Texture Coordinates Must Have Y Flipped

The background canvas is uploaded with UNPACK_FLIP_Y_WEBGL = true, so texture v=0 corresponds to the bottom of the screen; while px has top-left origin. Therefore:

vec2 uv0 = vec2(sp.x/uRes.x, 1.0 - sp.y/uRes.y);   // Omitting this line = the glass will sample a mirrored image

This is not optional. The symptom is: upside-down text appearing inside the glass, with content coming from the opposite side of the screen.

5. Real-Time Ray Path Analysis

Two systems are provided; they do not replace each other:

A. Diagnostic View (params.wire = 1) -- Renders intermediate values from the shader directly, used to determine "is it actually refracting?":

ChannelMeaningInterpretation
Rlength(off)/mdim*22Red = deflection strength. Center should be nearly black, with a red ring at the edge
Gx (edge depth)Green ring hugging the contour, quickly going to zero inward
Bfocal*2Blue = magnification rate, bright at center, dark at edge

If all three appear simultaneously with clear separation, the optical model is working; if completely black, the uniform is usually not being passed in (see Section 7, Pitfall 1).

B. Cross-Section Ray Diagram (308x150 canvas at bottom-right) -- Draws 11 light rays passing through the convex glass (incident/internal/exit), annotating edge rays with θi / θt / Δx and thickness grade (thin/thick). Focus panel changes with pointer hover.

Both curves (the shader and the 2D diagram) must use the same formulas and the same sinI limit; otherwise the diagram says 68° while the shader computes 38°, misleading parameter tuning.

6. Parameter Recipes (Tune Against Reference Images)

Desired Effectrefractmagrimdisptintthick
Thick glass capsule (large, bright edge, clear bottom arc, dark inside)1.200.350.950.220.24✓
Lens on colored bars (bars magnified and displaced, bright spots on sides)1.500.601.000.180.10✓
Thick glass over small text (text magnified + edge distortion)1.250.420.800.300.16✓
Top nav bar (thin, restrained)0.900.200.600.150.10✗
Control panel (large, readable text)1.000.150.550.120.14✗
Default (preset 0)1.200.450.850.350.20—

Tuning order: First refract for displacement magnitude → then mag for lip strength → then rim for edge brightness → finally disp/tint for texture quality. Reversing this order will cause parameters to fight each other.

One-Click Preset Switching (Built into Studio Version)

The top of the control panel has four keys: "Thick Capsule / Lens / Text / Default". Clicking one does two things simultaneously: sets all five sliders to the corresponding table values, and triggers a flash inner glow on the focused panel (to draw the eye to "look at this one").

var PRESETS = {
  capsule: { refract:1.20, mag:0.35, rim:0.95, disp:0.22, tint:0.24, focus:"capsule" },
  lens:    { refract:1.50, mag:0.60, rim:1.00, disp:0.18, tint:0.10, focus:"lens" },
  text:    { refract:1.25, mag:0.42, rim:0.80, disp:0.30, tint:0.16, focus:"plate" },
  reset:   { refract:1.20, mag:0.45, rim:0.85, disp:0.35, tint:0.20, focus:null }
};

Programmatically changing params does not trigger the slider's input event, so you must manually call syncUI() to write back the slider positions and numeric labels; otherwise the sliders and actual parameters will diverge.

The flash decay is written in step(), and it must be merged into glow rather than overwriting it (otherwise the press-and-hold glow will be overridden by the flash):

if(g.flash > 0.002) g.flash *= 0.90; else g.flash = 0;
var gl = Math.max(g.active ? 1 : 0, g.flash*0.85);
g.glow += (gl - g.glow)*k;

6.5 Four Most Easily Missed Apple Details

These three items appear in Session 219 but are extremely easy to overlook when watching a demo; without them, "looking like glass" will immediately downgrade.

① Top Specular Follows the Pointer (Specular Moves, But Shouldn't Chase the Pointer)

A fixed bright line along the top edge is a "sticker"; but making the specular decay from the pointer outward turns it into a flashlight sweeping across the glass -- this is the most common mistake. The correct approach is: the entire top edge is always bright, the pointer only provides local enhancement.

float tx       = q.x - uPtr.x*0.30;                    // Pointer offset should be small (0.3, not 0.55)
float baseTop  = 1.0 - smoothstep(-0.92, -0.30, q.y);  // Base brightness of the entire edge
float boostTop = 1.0 - smoothstep(0.12, 1.00, abs(tx)); // Local boost at the pointer position
float topW     = baseTop * (0.70 + 0.30*boostTop);      // Minimum 0.70, maximum 1.0

Compare the wrong approach with its consequence:

ApproachResult
smoothstep(-0.30,-0.92,q.y) * (1-smoothstep(0.06,0.72,abs(tx)))Pointer moves, only a short segment is bright, rest goes dark → flashlight
baseTop * (0.70 + 0.30*boostTop)Edge is always connected in one line; slightly brighter at the pointer → realistic specular reflection

Also do not use reverse order smoothstep: smoothstep(1.0, -1.0, d) and smoothstep(-0.30, -0.92, x) with edge0 > edge1 are undefined behavior per the GLSL specification, and some implementations will produce wrong results. Always use 1.0 - smoothstep(small, large, x).

The specular from the pointer direction (spec computed via dot(dir, pdir)) should only contribute intensity when pressed, and should be absent during hover; otherwise a small bright spot will chase the edge as the mouse moves.

② Inner Glow Spreads to Neighboring Glass (Approx. 12%) When pressing A, the adjacent B also glows slightly, giving the impression that "light flows between glasses".

var maxGlow = 0;
G.forEach(g => { if(g.glow > maxGlow) maxGlow = g.glow; });
if(maxGlow > 0.02)
  G.forEach(g => { if(!g.active) g.glow = Math.max(g.glow, maxGlow*0.12); });

The coefficient should not exceed 0.15, otherwise the entire screen glows together, violating the "restrained highlight" redline.

③ Scroll Edge Fade Effect Content behind the glass that scrolls to the edge should "fade into the background", not be clipped with a hard line. Use an alpha mask, and only apply it when there is still content:

var st   = el.scrollTop;
var rest = el.scrollHeight - el.clientHeight - st;
var top  = st > 3 ? 28 : 0;              // If scrolled to top, don't mask; otherwise there's always a fake shadow
var bot  = rest > 3 ? 28 : 0;
el.style.webkitMaskImage =
  "linear-gradient(to bottom, rgba(0,0,0,0) 0px, #000 "+top+"px, " +
  "#000 calc(100% - "+bot+"px), rgba(0,0,0,0) 100%)";

Key point: mask reads the alpha channel; use rgba(0,0,0,0) rather than transparent (in some older implementations, transparent is transparent black; behavior is the same but the semantics are clearer). The scroll container itself must have pointer-events:auto, otherwise scrolling won't work; but be aware that this prevents the entire glass from receiving drag events, so glass that needs dragging should not have a full coverage scroll container.

④ Split / Merge: Need "Spring", Not "Slide"

First-order exponential easing x += (tx - x)*0.19 never overshoots, always settling with a soft stop. Replace with a second-order spring:

// Per frame dt = 1/60
g.vx += ((g.tx - g.x)*omX*omX - 2*z*omX*g.vx)*dt;
g.x  += g.vx*dt;
g.vw += ((g.tw - g.w)*omW*omW - 2*z*omW*g.vw)*dt;
g.w  += g.vw*dt;
if (g.w < 0){ g.w = 0; g.vw = 0; }   // If narrowing goes too far, width becomes negative, drawing will break

omX = 15, omW = 18.5, z = 0.66 → approx 6% overshoot, ~0.45s period. Width stiffness must be greater than displacement stiffness (18.5 > 15), so that it looks like "first deform, then return"; if they are the same, it becomes a whole block translation, returning to a rigid plank feel.

Two key points to make separation look like "two plates being pushed apart" rather than something else:

  • The right piece position is fixed (tx is always lay.x + lay.w - one piece width), only the width varies between 0 and 140 → visually it looks like "splitting from the middle", not "one shrinking and one growing, pulling apart horizontally"
  • At the instant of splitting / merging, give each piece a flash = 1 inner glow accent, so the action feels grounded

No matter how large you make the coefficient of first-order easing, you can never achieve a "spring" feel; it's a curve shape problem, not a speed problem.

7. Eight Must-Avoid Pitfalls (Tested on Real Hardware)

  1. Array uniforms are unreliable. uniform vec4 uGeo[12] -- getUniformLocation("uGeo[0]") returns non-null on ANGLE/D3D, uniform4fv does not error, but the data never reaches the shader. All panels read 0, and are skipped by if(hh.x < 1.5) continue, leaving only a dark background. Conclusion: never use uniform arrays to pass multi-panel geometry; use one draw call per panel instead.

  2. Loops with uniform branches can be optimized away entirely. Writing if(uOpaque > 0.5){...} inside a for loop on some drivers causes the entire loop body to be discarded. Inside a loop, always use branchless mix/step constructs. If using "one draw per panel", there is no loop at all.

  3. Declared but unused uniforms are optimized out, and getUniformLocation returns null, falsely reporting "missing uniform". Declarations and usage must come in pairs.

  4. gl.getUniform(prog, null) throws TypeError, skipping all subsequent code in the same frame (FPS, probes not updated), making the page appear to "freeze". Check for null after getting the location.

  5. Texture Y-axis (see Section 4): not flipping results in a mirrored image + upside-down text.

  6. Binding only click loses events. In automated environments or certain hosts, click may not be synthesized, and all interactions become mute. Use pointerdown + pointerup + displacement threshold for click detection; click should only be a supplement.

  7. half is a GLSL ES reserved word: writing vec2 half = uRect.zw*0.5; will cause the entire shader to fail to compile, and the log will only say syntax error, making it extremely hard to locate. Use hb for half-width/height. Similar reserved-word mines: filter, input, output, long, short, double, packed.

  8. Reverse-order smoothstep is undefined behavior: smoothstep(1.0, -1.0, d), smoothstep(-0.30, -0.92, y) with edge0 > edge1 may work on the browser you test on, but produce garbage values on another. Always rewrite as 1.0 - smoothstep(-1.0, 1.0, d).

8. Acceptance Checklist (Run After Every Change)

Rendering

  • All 8 glass panels are visible, positions match the layout table
  • Underlying content (text/blue bars/grid) is visible inside the glass, not just a solid color block
  • Content inside the glass is correctly oriented (no upside-down, no left-right mirror)
  • There is a bright rim around the edge, a specular highlight at the top, and a bright arc at the bottom
  • On a dark background, the interior of the glass is not pitch black (has a slight hazy gray)
  • Contour edges are cleanly anti-aliased, with no hard edges or white fringes

Interaction (see references/interaction-playbook.md for detailed version)

  • Click capsule → menu grows upward, bottom edge stays fixed; click again retracts
  • Drag capsule → follows, snaps back on release; is clamped at edges
  • Click Dock split button → two pieces open; click again closes
  • Press and hold any panel → slight shrink + inner glow; releases back to zero
  • Hover → specular shifts toward the pointer
  • Space / S / W keyboard equivalents work
  • Clicking the four keys "Thick Capsule / Lens / Text / Default": the five slider positions and values change synchronously, and the target panel flashes with an inner glow
  • Expand and split states are maintained after resize

Performance

  • FPS is stable, with no cyclical frame drops
  • Draw call count is re-evaluated after changing the number of panels

9. Performance Budget and Degradation

ItemBudgetWhat to Do If Exceeded
Glass panels on screen≤ 10Merge into one, or downgrade secondary panels to CSS fallback
Coverage area per drawOnly its own AABBDo not run glass pass full-screen
Background texture uploadEvery 5 frames (light spots are slow)Reduce to every 8 frames when static
Background pixel ratiomin(dpr, 1.5)If dropping frames, reduce to 1.0
Render scaleAdaptive 0.72 / 1.0Downgrade if < 42fps, upgrade if > 56fps
Underlying luminance sample getImageDataEvery 10 frames, only for panels with w*h > 24000This is the biggest synchronous overhead; it's better to sample less
Ray path cross-section diagramEvery 4 framesCan reduce to every 6 frames when static
Control panel heightmin(520, VH*0.62, VH-250)Leave 240px for the ray diagram at bottom-right; otherwise small windows will overlap

Degradation order: Reduce panel count → Lower render scale → Reduce background upload frequency → Disable dispersion → Fall back to full-page CSS version.

10. Design Redlines (Apple HIG)

  • Glass only on navigation layers: do not place glass over content layers.
  • No overlapping glass: overlapping two glass panels loses the refraction reference and looks like a dirty spot.
  • Do not mix variants: do not mix Regular and Clear on the same screen.
  • Use tint only for primary actions, and keep the area small; an entire colored panel is no longer glass.
  • Restrained highlights: the rim is "a ring", not "a full white edge". uRim > 1.2 will look fake.
  • Three accessibility toggles must be retained: Reduce Transparency, Increase Contrast, Reduce Motion. The first replaces the background content with an opaque base, the last sets the spring k to 1.
  • When text is placed on top of glass, the DOM content must have text-shadow; otherwise, white text on a bright glass surface is unreadable.

11. Migration to C++ / SwiftUI

  • C++: cpp/glass_math.h contains the same pure functions for H(x), H'(x), fres(), thickness gradient, lip, and arc rim. Port them directly into the fragment shader; the Qt6 example only demonstrates the interface; for production, do not use CPU per-pixel computation.
  • SwiftUI: Prefer .glassEffect(.regular, in: shape) for the system implementation; only draw SimulatedGlass yourself when a custom shape or custom refraction is needed, and document in comments the differences from the system effect (the system version has cross-process background sampling and realistic dynamic highlights).

相关技能