3D噪音纹理:3D Noise Texture - MartinRGB/GLES30_ProgrammingGuide_NDK GitHub Wiki

3D噪音纹理

3D纹理本质是2D纹理的堆叠。GLSL中的噪音函数生成的是伪随机连续噪音值,实现GLSL噪音函数需要大量的指令计算。

因此考虑使用3D纹理,预先计算噪音放置在3D纹理中,本案例采用的是 Ken Perlin 的基于网格的梯度噪音。

梯度噪声算法,以一个 3D坐标作为输入,返回浮点值,所以,我们需要把 xyz 映射到网格中对应的整数位置

一、生成噪音

1.定义GLSL中的内置函数公式

//定义了glsl中一些内建函数的公式
#define FLOOR(x)           ((int)(x) - ((x) < 0 && (x) != (int)(x)))
#define smoothstep(t)      ( t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f ) )
#define lerp(t, a, b)      ( a + t * (b - a) )
#ifdef _WIN32
   #define srandom srand
   #define random rand
#endif

2.梯度向量的生成

// permTable describes a random permutatin of 8-bit values from 0 to 255.
// 生成一份临时梯度向量表
static unsigned char permTable[256] =
{
   0xE1, 0x9B, 0xD2, 0x6C, 0xAF, 0xC7, 0xDD, 0x90, 0xCB, 0x74, 0x46, 0xD5, 0x45, 0x9E, 0x21, 0xFC,
   0x05, 0x52, 0xAD, 0x85, 0xDE, 0x8B, 0xAE, 0x1B, 0x09, 0x47, 0x5A, 0xF6, 0x4B, 0x82, 0x5B, 0xBF,
   0xA9, 0x8A, 0x02, 0x97, 0xC2, 0xEB, 0x51, 0x07, 0x19, 0x71, 0xE4, 0x9F, 0xCD, 0xFD, 0x86, 0x8E,
   0xF8, 0x41, 0xE0, 0xD9, 0x16, 0x79, 0xE5, 0x3F, 0x59, 0x67, 0x60, 0x68, 0x9C, 0x11, 0xC9, 0x81,
   0x24, 0x08, 0xA5, 0x6E, 0xED, 0x75, 0xE7, 0x38, 0x84, 0xD3, 0x98, 0x14, 0xB5, 0x6F, 0xEF, 0xDA,
   0xAA, 0xA3, 0x33, 0xAC, 0x9D, 0x2F, 0x50, 0xD4, 0xB0, 0xFA, 0x57, 0x31, 0x63, 0xF2, 0x88, 0xBD,
   0xA2, 0x73, 0x2C, 0x2B, 0x7C, 0x5E, 0x96, 0x10, 0x8D, 0xF7, 0x20, 0x0A, 0xC6, 0xDF, 0xFF, 0x48,
   0x35, 0x83, 0x54, 0x39, 0xDC, 0xC5, 0x3A, 0x32, 0xD0, 0x0B, 0xF1, 0x1C, 0x03, 0xC0, 0x3E, 0xCA,
   0x12, 0xD7, 0x99, 0x18, 0x4C, 0x29, 0x0F, 0xB3, 0x27, 0x2E, 0x37, 0x06, 0x80, 0xA7, 0x17, 0xBC,
   0x6A, 0x22, 0xBB, 0x8C, 0xA4, 0x49, 0x70, 0xB6, 0xF4, 0xC3, 0xE3, 0x0D, 0x23, 0x4D, 0xC4, 0xB9,
   0x1A, 0xC8, 0xE2, 0x77, 0x1F, 0x7B, 0xA8, 0x7D, 0xF9, 0x44, 0xB7, 0xE6, 0xB1, 0x87, 0xA0, 0xB4,
   0x0C, 0x01, 0xF3, 0x94, 0x66, 0xA6, 0x26, 0xEE, 0xFB, 0x25, 0xF0, 0x7E, 0x40, 0x4A, 0xA1, 0x28,
   0xB8, 0x95, 0xAB, 0xB2, 0x65, 0x42, 0x1D, 0x3B, 0x92, 0x3D, 0xFE, 0x6B, 0x2A, 0x56, 0x9A, 0x04,
   0xEC, 0xE8, 0x78, 0x15, 0xE9, 0xD1, 0x2D, 0x62, 0xC1, 0x72, 0x4E, 0x13, 0xCE, 0x0E, 0x76, 0x7F,
   0x30, 0x4F, 0x93, 0x55, 0x1E, 0xCF, 0xDB, 0x36, 0x58, 0xEA, 0xBE, 0x7A, 0x5F, 0x43, 0x8F, 0x6D,
   0x89, 0xD6, 0x91, 0x5D, 0x5C, 0x64, 0xF5, 0x00, 0xD8, 0xBA, 0x3C, 0x53, 0x69, 0x61, 0xCC, 0x34,
};

3.初始化噪音表

// 根据临时数据表,生成 3D 噪音表
void initNoiseTable()
{
   int            i;
   float          a;
   float          x, y, z, r, theta;
   float          gradients[256 * 3];
   unsigned int   *p, *psrc;

   srandom ( 0 );

   // build gradient table for 3D noise
   for ( i = 0; i < 256; i++ )
   {
      /*
      * calculate 1 - 2 * random number
      */
      a = ( random() % 32768 ) / 32768.0f;
      z = ( 1.0f - 2.0f * a );

      r = sqrtf ( 1.0f - z * z ); // r is radius of circle

      a = ( random() % 32768 ) / 32768.0f;
      theta = ( 2.0f * ( float ) M_PI * a );
      x = ( r * cosf ( a ) );
      y = ( r * sinf ( a ) );

      gradients[i * 3] = x;
      gradients[i * 3 + 1] = y;
      gradients[i * 3 + 2] = z;
   }

   // use the index in the permutation table to load the
   // gradient values from gradients to gradientTable
   p = ( unsigned int * ) gradientTable;
   psrc = ( unsigned int * ) gradients;

   for ( i = 0; i < 256; i++ )
   {
      int indx = permTable[i];
      p[i * 3] = psrc[indx * 3];
      p[i * 3 + 1] = psrc[indx * 3 + 1];
      p[i * 3 + 2] = psrc[indx * 3 + 2];
   }
}

4.根据给定的晶格点,生成梯度噪音值

//
// generate the value of gradient noise for a given lattice point
//
// (ix, iy, iz) specifies the 3D lattice position
// (fx, fy, fz) specifies the fractional part
// ix iy iz 代表 3D 晶格位置 fx fy fz 代表小数部分
static float glattice3D ( int ix, int iy, int iz, float fx, float fy, float fz )
{
   float *g;
   int   indx, y, z;

   z = permTable[iz & NOISE_TABLE_MASK];
   y = permTable[ ( iy + z ) & NOISE_TABLE_MASK];
   indx = ( ix + y ) & NOISE_TABLE_MASK;
   g = &gradientTable[indx * 3];

   return ( g[0] * fx + g[1] * fy + g[2] * fz );
}

5.构建 Noise3D 函数,传入 xyz 位置值,利用 glattice3D晶格化3D 中噪音值的 lerp()插值计算,返送一个标量噪音浮点值

//
// generate the 3D noise value
// f describes the input (x, y, z) position for which the noise value needs to be computed
// noise3D returns the scalar noise value
// 
float noise3D ( float *f )
{
   int   ix, iy, iz;
   float fx0, fx1, fy0, fy1, fz0, fz1;
   float wx, wy, wz;
   float vx0, vx1, vy0, vy1, vz0, vz1;

   ix = FLOOR ( f[0] );
   fx0 = f[0] - ix;
   fx1 = fx0 - 1;
   wx = smoothstep ( fx0 );

   iy = FLOOR ( f[1] );
   fy0 = f[1] - iy;
   fy1 = fy0 - 1;
   wy = smoothstep ( fy0 );

   iz = FLOOR ( f[2] );
   fz0 = f[2] - iz;
   fz1 = fz0 - 1;
   wz = smoothstep ( fz0 );

   vx0 = glattice3D ( ix, iy, iz, fx0, fy0, fz0 );
   vx1 = glattice3D ( ix + 1, iy, iz, fx1, fy0, fz0 );
   vy0 = lerp ( wx, vx0, vx1 );
   vx0 = glattice3D ( ix, iy + 1, iz, fx0, fy1, fz0 );
   vx1 = glattice3D ( ix + 1, iy + 1, iz, fx1, fy1, fz0 );
   vy1 = lerp ( wx, vx0, vx1 );
   vz0 = lerp ( wy, vy0, vy1 );

   vx0 = glattice3D ( ix, iy, iz + 1, fx0, fy0, fz1 );
   vx1 = glattice3D ( ix + 1, iy, iz + 1, fx1, fy0, fz1 );
   vy0 = lerp ( wx, vx0, vx1 );
   vx0 = glattice3D ( ix, iy + 1, iz + 1, fx0, fy1, fz1 );
   vx1 = glattice3D ( ix + 1, iy + 1, iz + 1, fx1, fy1, fz1 );
   vy1 = lerp ( wx, vx0, vx1 );
   vz1 = lerp ( wy, vy0, vy1 );

   return lerp ( wz, vz0, vz1 );;
}

二、使用噪音

1.创建3D噪音材质

void Create3DNoiseTexture ( ESContext *esContext )
{
   UserData *userData = ( UserData * ) esContext->userData;
   int textureSize = 64; // Size of the 3D nosie texture
   float frequency = 5.0f; // Frequency of the noise.
   GLfloat *texBuf = ( GLfloat * ) malloc ( sizeof ( GLfloat ) * textureSize * textureSize * textureSize );
   GLubyte *texBufUbyte = ( GLubyte * ) malloc ( sizeof ( GLubyte ) * textureSize * textureSize * textureSize );
   int x, y, z;
   int index = 0;
   float min = 1000;
   float max = -1000;
   float range;

   initNoiseTable();

   for ( z = 0; z < textureSize; z++ )
   {
      for ( y = 0; y < textureSize; y++ )
      {
         for ( x = 0; x < textureSize; x++ )
         {
            float noiseVal;
            float pos[3] = { ( float ) x / ( float ) textureSize, ( float ) y / ( float ) textureSize, ( float ) z  / ( float ) textureSize };
            pos[0] *= frequency;
            pos[1] *= frequency;
            pos[2] *= frequency;
            noiseVal = noise3D ( pos );

            if ( noiseVal < min )
            {
               min = noiseVal;
            }

            if ( noiseVal > max )
            {
               max = noiseVal;
            }

            texBuf[ index++ ] = noiseVal;
         }
      }
   }

   // Normalize to the [0, 1] range
   range = ( max - min );
   index = 0;

   for ( z = 0; z < textureSize; z++ )
   {
      for ( y = 0; y < textureSize; y++ )
      {
         for ( x = 0; x < textureSize; x++ )
         {
            float noiseVal = texBuf[index];
            noiseVal = ( noiseVal - min ) / range;
            texBufUbyte[index++] = ( GLubyte ) ( noiseVal * 255.0f );
         }
      }
   }

   glGenTextures ( 1, &userData->textureId );
   glBindTexture ( GL_TEXTURE_3D, userData->textureId );
   glTexImage3D ( GL_TEXTURE_3D, 0, GL_R8, textureSize, textureSize, textureSize, 0,
                  GL_RED, GL_UNSIGNED_BYTE, texBufUbyte );

   glTexParameteri ( GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
   glTexParameteri ( GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
   glTexParameteri ( GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT );
   glTexParameteri ( GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT );
   glTexParameteri ( GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT );

   glBindTexture ( GL_TEXTURE_3D, 0 );

   free ( texBuf );
   free ( texBufUbyte );
}

2.撰写着色器

非常类似于雾化的着色器,复习一下:

1.雾化需要两个输入 像素到眼睛的距离(u_eyePos) 以及 雾化颜色(u_fogColor)。除此之外,还要提供雾化覆盖的最小和最大范围

2.线性雾化因子公式 Factor = (MaxDist - EyeDist)/(MaxDist - MinDist),然后用 Factor 乘以雾化颜色,最后和总体颜色进行线性插值

这个案例中,主要是用 3DNoise 纹理扭曲雾化因子,着色器根据实际计算 3D纹理坐标,放入 noiseCoord,3D纹理的包装方法 GL_MIRRORED_REPEAT 保证了噪音体可以循环滚动。(s,t)为纹理坐标,r基于时间——因此纹理在时间内循环。

3D纹理是单通道 GL_R8 纹理,因此使用 RGB 任何一个通道就可以。然后利用计算好的 fogFactor 在 雾化颜色 和 基本颜色 之间插值

3D纹理性能开销比较小,能够体现较好的视觉效果,可以应用到尘埃、波浪效果中,因此非常重要

vert:

#version 300 es                             
uniform mat4 u_mvpMatrix;                   
uniform mat4 u_mvMatrix;                    
layout(location = 0) in vec4 a_position;    
layout(location = 1) in vec4 a_color;       
layout(location = 2) in vec2 a_texCoord;    
out vec4 v_color;                           
out vec2 v_texCoord;                        
out vec4 v_eyePos;                          
void main()                                 
{                                           
   // Transform vertex to view-space        
   v_eyePos = u_mvMatrix * a_position;      
   v_color = a_color;                       
   v_texCoord = a_texCoord;                 
   gl_Position = u_mvpMatrix * a_position;  
}           

frag:

#version 300 es                                   
precision mediump float;                          
uniform mediump sampler3D s_noiseTex;             
uniform float u_fogMaxDist;                       
uniform float u_fogMinDist;                       
uniform vec4  u_fogColor;                         
uniform float u_time;                             
in vec4 v_color;                                  
in vec2 v_texCoord;                               
in vec4 v_eyePos;                                 
layout(location = 0) out vec4 outColor;           
                                                  
float computeLinearFogFactor()                    
{                                                 
  float factor;                                   
  // Compute linear fog equation
  // 计算像素到眼睛的距离                  
  float dist = distance( v_eyePos,                
                 vec4( 0.0, 0.0, 0.0, 1.0 ) );
  // 求出雾化因子    
  factor = (u_fogMaxDist - dist) /                
           (u_fogMaxDist - u_fogMinDist );        
  // Clamp in the [0,1] range                     
  factor = clamp( factor, 0.0, 1.0 );             
  return factor;                                  
}                                                 
                                                  
void main( void )                                 
{                                                 
  float fogFactor = computeLinearFogFactor();
  // 设置3D纹理的 str 坐标,让纹理随着时间滚动     
  vec3 noiseCoord =                               
     vec3( v_texCoord.xy - u_time, u_time );
  // 使用3D纹理生成的噪音扭曲雾化因子      
  fogFactor -=                                    
     texture(s_noiseTex, noiseCoord).r * 0.25;    
  fogFactor = clamp(fogFactor, 0.0, 1.0);         
  vec4 baseColor = v_color;                       
  outColor = baseColor * fogFactor +              
            u_fogColor * (1.0 - fogFactor);       
}