フラグメントシェーダーを使って円を描く
フラグメントシェーダーを使って円を描いてみます。
三平方の定理で円を描く
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); vec4 c = vec4(1.0); if(pow(st.x,2.0) + pow(st.y,2.0) <= 0.5){ c = vec4(0.0); } gl_FragColor = c; }
lengthを使って円を描く
距離が1.0以内0.1以上の場合は切り上げられて1.0となる為、円が描画される。
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float c = 1.0 - ceil(0.5 - length(st)); gl_FragColor = vec4(c); }
distanceを使って円を描く
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float c = 1.0 - ceil(0.5 - distance(vec2(0.0),st)); gl_FragColor = vec4(c); }
smoothstepを使って円を描く
smoothstepを使って閾値にxとyの内積を使う。 エッジがきれいになる。
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float c = smoothstep(0.5,0.51, dot(st,st)); gl_FragColor = vec4(vec3(c),1.0); }
ちなみに内積の箇所をlengthで置き換えた場合もそんなに変わりは無かった。
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float c = smoothstep(0.5,0.51, length(st)); gl_FragColor = vec4(vec3(c),1.0); }
fractを使って円形の模様を描く
ビルドイン関数のfract
を使って連続した模様をえがいてみます。 fract(a)はa-floor(a)
らしく、簡単に言うと引数の小数部分を返却する関数のようです。
普通にlengthの値をfractに渡すとこんな感じになります。
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float d = length( st ); d = fract(d); gl_FragColor = vec4(vec3(d),1.0); }
lengthの値を増やすことで模様を作る事が出来ます。
void main( void ) { vec2 st = (gl_FragCoord.xy * 2.0 - resolution) / min(resolution.x, resolution.y); float d = length( st ); d = fract(d*5.0); gl_FragColor = vec4(vec3(d),1.0); }
動きをつけるとこんな感じです。
http://glslsandbox.com/e#43464.0
参考
↓大変参考になりました。 GLSL Sandboxで図形描画