基於模型的擴散效果(學習精神小夥
的代碼)
最終效果:
shadertoy:
// 應用: 基於模型的擴散效果
#define PI 3.1415926
float lerp (float x,float y,float t ) {
return ( 1.0 - t ) * x + t * y;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// 當前像素的位置
vec2 uv = (fragCoord.xy/iResolution.xy-0.5);
// 圓環擴散的速度
const float u_speed = .05;
// 擴散的最大半徑
const float u_radius = 0.5;
// 圓環的寬度
const float u_width = 0.08;
// 圓環內的顏色
const vec3 hightColor = vec3(1.,0.,0.);
// 圓環外的顏色
const vec3 baseColor = vec3(.3,.3,.3);
vec3 vColor;
float u_time = u_speed * iTime;
// rangeLen: 0~u_radius之間週期變化
float rangeLen = mod(u_time, u_radius);
// 當前像素點到中心(0,0)的距離
float distance = length(uv);
// 滿足在圓環內部的像素,高亮着色
if ( distance> rangeLen && distance < rangeLen + u_width) {
// 佔整個圓環寬度的百分比
float i = (distance-rangeLen) / u_width;
// 過渡更平滑一些,圓環兩邊模糊,中間清楚
float d = sin(i*PI);
// 線性差值
float r = lerp(baseColor.r, hightColor.r, d);
float g = lerp(baseColor.g, hightColor.g, d);
float b = lerp(baseColor.b, hightColor.b, d);
vColor = vec3(r, g, b);
} else {
// 圓環外部的點,正常顏色着色
vColor = baseColor;
}
fragColor = vec4(vColor,1.);
}
繪圖模型:
關鍵步驟解釋:
float d = sin(i*PI);
取sin:
效果:
實際應用
把距離換成是模型的相對距離在頂點着色器中傳過來就行.
頂點:
varying vec3 v_position;
void main() {
v_position = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
片元:
vec2 curr = vec2(v_position.x, v_position.z);
float distance = distanceTo(vec2(0.0, 0.0), curr);