# 前言

1. uv坐标的矫正
2. 如何绘制网格（对uv坐标乘上一个数并且取小数部分作为新的uv坐标）

# 常用的内置函数

vec3 grid(vec2 uv) {
vec3 color = vec3(1.0);

vec2 cell = 1.0 - 2.0 * abs(fract(uv) - 0.5);
// color = vec3(cell, 0.0);
if(abs(uv.x) <= 2. * fwidth(uv.x)) {
color = vec3(0.0, 1.0, 0.0);
} else if(abs(uv.y) <= 2. * fwidth(uv.y)) {
color = vec3(1.0, 0.0, 0.0);
} else if(abs(cell.x) <= 2. * fwidth(uv.x) || abs(cell.y) < 2. * fwidth(uv.y)) {
color = vec3(0.6);
}
return color;
}

## step

step generates a step function by comparing x to edge. For element i of the return value, 0.0 is returned if x[i] < edge[i], and 1.0 is returned otherwise.

// if(abs(uv.x) <= 2. * fwidth(uv.x)) {
//     color = vec3(0.0, 1.0, 0.0);
// }
// ===>

color = step(abs(uv.x), 2.0 * fwidth(uv.x)) * vec3(0.0, 1.0, 0.0);

## mix

genType mix(genType x, genType y, genType a);

mix performs a linear interpolation between x and y using a to weight between them. The return value is computed as follows: x⋅(1−a)+y⋅a.

$Color = Src.color * (1 - Dst.a) + Dst.color * Dst.a$

color = mix(color, vec3(0.0, 1.0, 0.0), step(abs(uv.x), 2.0 * fwidth(uv.x)));


color = mix(color, vec3(0.6), step(abs(_uv.x), 2.0 * fwidth(uv.x)));
color = mix(color, vec3(0.6), step(abs(_uv.y), 2.0 * fwidth(uv.x)));
color = mix(color, vec3(0.0, 1.0, 0.0), step(abs(uv.x), 2.0 * fwidth(uv.x)));
color = mix(color, vec3(1.0, 0.0, 0.0), step(abs(uv.y), 2.0 * fwidth(uv.y)));

OK，现在我们就已经完成了if 分支的替换工作。但是使用 step函数它有一个小小的缺陷，我们可以通过一张图看出来。

## smoothstep

genType smoothstep(genType edge0, genType edge1, genType x)

smoothstep performs smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1. This is useful in cases where a threshold function with a smooth transition is desired. smoothstep is equivalent to:

    genType t;  /* Or genDType t; */
t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);

smoothstep returns 0.0 if x ≤ edge0 and 1.0 if x ≥ edge1.

color = mix(color, vec3(0.6), smoothstep(3.0 * fwidth(uv.x), 1.0 * fwidth(uv.x), abs(cell.x)));

color = mix(color, vec3(0.6), smoothstep(3.0 * fwidth(uv.x), 1.0 * fwidth(uv.x), abs(cell.y)));

    vec2 cell = 1.0 - 2.0 * abs(fract(uv) - 0.5);
color = mix(color, vec3(0.6), smoothstep(3.0 * fwidth(uv.x), 1.0 * fwidth(uv.x), abs(cell.x)));
color = mix(color, vec3(0.6), smoothstep(3.0 * fwidth(uv.x), 1.0 * fwidth(uv.x), abs(cell.y)));

# 总结

1. 为了解决掉if分支，我们使用了step 函数
2. 为了解决颜色融合的问题，我们使用了 mix 函数，
3. 为了解决线条锯齿的问题，我们使用了smoothstep 函数。