GLSL 片段着色器 是做什么的?
为程序化图形、纹理和视觉效果编写 GPU 加速的片段着色器。
何时使用
- 创建程序化纹理(木纹、大理石、云朵、地形)
- 使用距离场(SDF)绘制形状
- 生成图案、噪声、渐变
- 构建视觉效果和动画
- 为 Three.js、WebGL、Processing 编写自定义着色器
核心概念
片段着色器 同时在每个像素上执行。每个线程:
- 通过
gl_FragCoord接收像素位置 - 通过
gl_FragColor返回颜色(vec4:RGBA 0.0-1.0) - 不能与其他线程通信(无状态)
标准 Uniform 变量
uniform float u_time; // 已过去的秒数
uniform vec2 u_resolution; // 画布尺寸(宽度,高度)
uniform vec2 u_mouse; // 鼠标位置(像素)
标准化坐标:vec2 st = gl_FragCoord.xy / u_resolution;
常用函数
| 函数 | 用途 | 示例 |
|---|---|---|
mix(a,b,t) | 线性插值 | mix(red, blue, 0.5) |
step(edge,x) | 硬阈值 | step(0.5, st.x) |
smoothstep(e0,e1,x) | 平滑阈值 | smoothstep(0.2, 0.8, st.x) |
fract(x) | 小数部分 | fract(st * 3.0) 用于平铺 |
mod(x,y) | 取模 | mod(st.x, 0.25) |
clamp(x,min,max) | 限制值范围 | clamp(col, 0.0, 1.0) |
length(v) | 向量长度 | length(st - 0.5) |
distance(a,b) | 欧几里得距离 | distance(st, center) |
dot(a,b) | 点积 | dot(normal, lightDir) |
normalize(v) | 单位向量 | normalize(direction) |
atan(y,x) | 角度(弧度) | atan(st.y-0.5, st.x-0.5) |
sin/cos/pow/abs | 数学运算 | 硬件加速 |
快速模式
圆形:
float d = distance(st, vec2(0.5));
float circle = 1.0 - smoothstep(0.2, 0.21, d);
矩形:
vec2 bl = step(vec2(0.1), st);
vec2 tr = step(vec2(0.1), 1.0 - st);
float rect = bl.x * bl.y * tr.x * tr.y;
平铺:
st = fract(st * 4.0); // 4x4 网格
动画:
float wave = sin(st.x * 10.0 + u_time) * 0.5 + 0.5;
参考资料(渐进式查阅)
基础
references/glsl-fundamentals-data-types-vectors-precision-coordinates.mdreferences/glsl-shaping-functions-step-smoothstep-curves-interpolation.md
绘制
references/glsl-colors-rgb-hsb-gradients-mixing-color-spaces.mdreferences/glsl-shapes-sdf-circles-rectangles-polar-distance-fields.mdreferences/glsl-shapes-polygon-star-polar-sdf-combinations.md
程序化
references/glsl-patterns-tiling-fract-matrices-transformations.mdreferences/glsl-pattern-symmetry-truchet-domain-warping.mdreferences/glsl-noise-random-perlin-simplex-cellular-voronoi.mdreferences/glsl-cellular-voronoi-worley-noise-patterns.mdreferences/glsl-fbm-fractional-brownian-motion-turbulence-octaves.mdreferences/glsl-procedural-textures-clouds-marble-wood-terrain.md
API 参考
references/glsl-shader-builtin-functions-complete-api-reference.md
工具
- 在线编辑器: editor.thebookofshaders.com
- glslViewer: 运行 .frag 文件的命令行工具
- glslCanvas: 用于实时着色器的 HTML 嵌入
- ShaderToy: 使用 iTime、iResolution、iMouse 等 uniform 变量
外部资源
- The Book of Shaders:https://thebookofshaders.com
- LYGIA 库:https://lygia.xyz(可复用的着色器函数)
- ShaderToy:https://shadertoy.com
- Inigo Quilez 文章:https://iquilezles.org/articles/