(本文未经许可禁止转载)

           

关于Voronoi

Voronoi是大自然中非常常见的图案,比如梅花鹿的斑纹,裂开的岩浆灰分布,树皮,细胞。

自然中的Voronoi图

程序生成的Voronoi

暴力生成

Voronoi最直接的生成方式是在图片上撒点,以点为圆心做圆,进而挤压出Voronoi图案。

生成过程

算法复杂度

我们的最终目标是在GPU上运行这样的特效。仔细想想可知道其算法复杂度会与点的数目成正相关。

O(Width\cdot Height\cdot Number)

如果我们想生成一个含有1000个细胞的代码,那将等价于需要预渲染1000张图片——这并不高效。

优化

其实Voronoi特效一般不要求细胞做非常大的移动,我们可能只需要细胞在特定的位置上做做小晃动即可。

所以我们可以把点先按照网格的形式撒出来,再给它们加上小小的随机偏移。

然后当你算某一个像素的Voronoi特效的时候,只需要遍历其当前所在cell的周围8个cell的位置即可。

计算复杂度

O(Width\cdot Height\cdot 8)

Fragment实现

作者:Inigo Quilez

// The MIT License
// Copyright © 2013 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

vec2 hash( vec2 p ) { p=vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))); return fract(sin(p)*18.5453); }

// return distance, and cell id
vec2 voronoi( in vec2 x )
{
    vec2 n = floor( x );
    vec2 f = fract( x );

    vec3 m = vec3( 8.0 );
    for( int j=-1; j<=1; j++ )
    for( int i=-1; i<=1; i++ )
    {
        vec2  g = vec2( float(i), float(j) );
        vec2  o = hash( n + g );
      //vec2  r = g - f + o;
        vec2  r = g - f + (0.5+0.5*sin(iTime+6.2831*o));
        float d = dot( r, r );
        if( d<m.x )
            m = vec3( d, o );
    }

    return vec2( sqrt(m.x), m.y+m.z );
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 p = fragCoord.xy/max(iResolution.x,iResolution.y);

    // computer voronoi patterm
    vec2 c = voronoi( (14.0+6.0*sin(0.2*iTime))*p );

    // colorize
    vec3 col = 0.5 + 0.5*cos( c.y*6.2831 + vec3(0.0,1.0,2.0) ); 
    col *= clamp(1.0 - 0.4*c.x*c.x,0.0,1.0);
    col -= (1.0-smoothstep( 0.08, 0.09, c.x));

    fragColor = vec4( col, 1.0 );
}
       

(本文未经许可禁止转载)

   

发表评论