# The Book of Shaders 计算次数评估, 2800 * 1800分辨率,60fps,每秒计算311040000次. GPU并行计算, 芯片支持复杂函数(三角/矩阵). `GLSL`, openGL Shading Language. 类似于声明式编程. http://openglbook.com/chapter-0-preface-what-is-opengl.html ## 工具 ``` > brew install glslviewer > glslViewer hello.frag ``` ## 简介 ### hello ```glsl #ifdef GL_ES precision mediump float; #endif uniform float u_time; void main() { gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0); } ``` - 需要一个`main`函数,最后返回颜色值 - 最终像素颜色取决于全局变量`gl_FragColor` - 宏 - `GL_ES`,移动端/浏览器 - 数据类型 - `vec4` - (R,G,B,Alpha) - `vec3` - `vec2` - `float` - float精度, 精度高质量好, 精度低速度快(定量?) - `precision mediump float;` - `precision lowp float;` - `precision highp float;` - `int` - `bool` ```glsl vec4 red() { return vec4(vec3(1.0, 0.0, 1.0), 1.0); } void main() { gl_FragColor = red(); } ``` ### uniforms GPU的所有parallel thread输入必须统一, 并且只读. `uniform`: float, vec2, vec3, vec4, mat2, mat3, mat4, sampler2D, samplerCube. `uniform`值的命名应该加前缀`u_`. - `u_resolution` - 画布尺寸 - `u_mouse` - 鼠标位置 - `u_time` - 时间秒 ```glsl ... uniform float u_time; void main() { gl_FragColor = vec4(abs(sin(u_time)), 0., 0., 1.); } ``` - 降低变化速度 - `sin(u_time * 0.1)` - 提高变化速度 - `sin(u_time * 100)` - 变化三通道 - `gl_FragColor = vec4(abs(sin(u_time)), abs(cos(u_time)), abs(tan(u_time)), 1.);` 常用的函数 `sin()` `cos()` `tan()` `asin()` `acos()` `atan()` `pow()` `exp()` `log()` `sqrt()` `abs()` `sign()` `floor()` `ceil()` `fract()` `mod()` `min()` `max()` `clamp()` 全局变量`gl_FragCoord`, 存储了当前活动线程正在处理的像素或屏幕碎片的坐标. 它不是`uniform`值, 而是`varying`. #### 使用`u_mouse`的交互图像 ```glsl uniform vec2 u_resolution; uniform vec2 u_mouse; void main() { vec2 st = u_mouse / u_resolution; gl_FragColor = vec4(st.x, st.y, 0.0, 1.0); } ``` 颜色随着鼠标移动变化. ### running your shader skip ## 算法绘图