像素精灵元素GLSL - 28- 五角星绘制(the devil)

873 阅读1分钟

绘制五角星

示例代码

本示例核心代码, 输入不同的边数,显示不同形状的星星

float starSDF(vec2 st, int V, float s) {
	st = st * 4.0 - 2.0;
	float a = atan(st.y, st.x) / TAU;
	float seg = a * float(V);
	a = ((floor(seg) + 0.5) / float(V) + mix(s, -s, step(0.5, fract(seg)))) * TAU;
	return abs(dot(vec2(cos(a), sin(a)), st));
}

完整代码

#ifdef GL_ES
precision mediump float;
#endif

uniform float u_time;
uniform vec2 u_resolution;
uniform vec2 u_mouse;
float TAU = 6.2831853071795864769252867665590;  // 2PI

/** 绘制线条
* @param {float } x 坐标点
* @param {float } s 划线的位置
* @param {float } w 现对与屏幕宽度的线宽
*/
float stroke(float x, float s, float w){
    float d = step(s, x + w * 0.5) - step(s, x - w * 0.5);
    return clamp(d, 0.0, 1.0);
}
/** 填充一个区域
* @param x 坐标点
* @param size 大小 
*/
float fill(float x, float size){
    return 1.0 - step(size,x);
}

/** 绘制星星状的图形
* @param st 坐标点
* @param  V 边数
* @param s 图形大小
*/
float starSDF(vec2 st, int V, float s){
   st = st * 4.0 - 2.0;
   float a = atan(st.y,st.x) / TAU;
   float seg = a * float(V);
   a = ((floor(seg)+0.5) / float(V) + mix(s, -s, step(0.5, fract(seg)))) * TAU;
   return abs(dot(vec2(cos(a), sin(a)),st));
}

/** 绘制一个圆
* @param st 坐标点
*/
float circleSDF(vec2 st){
    return length(st-0.5) * 2.0;
}

void main(){
    vec2 st = gl_FragCoord.xy / u_resolution;
    st.x *= u_resolution.x/u_resolution.y;
    st.y *= u_resolution.y/u_resolution.x;

    vec3 color = vec3(0.0); 

    color += stroke(circleSDF(st),0.8, 0.05);
    st.y = 1.0 - st.y;
    float s = starSDF(st.yx, 5, 0.1);
    color *=step(0.7, s);
    color += stroke(s, 0.4, 0.1);

    gl_FragColor = vec4(color, 1.0);
}
代码效果

《像素精灵元素GLSL》期待你的关注与点赞