程式判斷片斷是處於磚塊位置還是水泥位置,然後分別進行著色。
程式流程
使用內建函數說明:
vec2 floor (vec2 x): Returns a value equal to the nearest integer that
is less than or equal to x.
vec2 fract (vec2 x): Returns x – floor (x).
vec2 step (vec2 edge, vec2 x): Returns 0 if x <= edge; otherwise, it returns 1.0.
vec3 mix (vec3 x, vec3 y, vec3 a): Returns x * (1.0 – a) + y * a, i.e., the linear
blend of x and y using the floating-point value a.
The value for a is not restricted to the range [0,1].
得到當前片斷在整個磚塊圖案中的位置。(單位長度1 = 一個磚塊的尺寸)
position = MCposition / BrickSize;
每隔一行,位移半個磚塊寬度。產生交錯感。
if (fract(position.y * 0.5) > 0.5)
position.x += 0.5;
得到當前片斷在磚塊圖的一個圖元中的相對位置。
position = fract(position);
判斷當前片斷處於磚塊位置還是灰泥位置,處於磚塊位置時為1,處於灰泥位置時為0。
useBrick = step(position, BrickPct);
根據當前片斷的位置,得到當前片斷的顏色值。
color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);
在顏色中加入光照效果。
color *= LightIntensity;
將計算好的顏色賦給當前片斷。
gl_FragColor = vec4 (color, 1.0);
程式清單
uniform vec3 BrickColor, MortarColor;
uniform vec2 BrickSize;
uniform vec2 BrickPct;
varying vec2 MCposition;
varying float LightIntensity;
void main(void){
vec3 color;
vec2 position, useBrick;
position = MCposition / BrickSize;
if (fract(position.y * 0.5) > 0.5)
position.x += 0.5;
position = fract(position);
useBrick = step(position, BrickPct);
color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);
color *= LightIntensity;
gl_FragColor = vec4 (color, 1.0);
}