2016-04-14 114 views
0

我在使用OpenGL片段着色器試圖計算Perlin噪聲時遇到了一個問題。 結果是塊狀,根本不連續。 enter image description herePerlin噪聲塊網格

我試圖使用這種實現的: enter image description here

我想不通的問題,這裏是我的片段着色器代碼:

#version 330 core 
out vec3 color; 
in vec4 p; 
in vec2 uv; 

// random value for x gradiant coordinate 
float randx(vec2 co){ 
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); 
} 


// random value for y gradaint coordiante 
float randy(vec2 co){ 
    return fract(cos(dot(co.xy ,vec2(4.9898,78.233))) * 68758.5453); 
} 


// smooth interpolation funtion 
float smoothInter(float x){ 
    return 6*x*x*x*x*x -15*x*x*x*x + 10*x*x*x; 
} 


float grid_dim = 10.0f; 


void main() { 
    // Get coloumn and row of the bottom left 
    //point of the square in wich the point is in the grid 
    int col = int(uv.x * grid_dim); 
    int row = int(uv.y * grid_dim); 



// Get the 4 corner coordinate of the square, 
//divided by the grid_dim to have value between [0,1] 
vec2 bl = vec2(col, row)/10.0f; 
vec2 br = vec2(col+1, row)/10.0f; 
vec2 tl = vec2(col, row+1)/10.0f; 
vec2 tr = vec2(col+1, row+1)/10.0f; 

// Get vectors that goes from the corner to the point 
vec2 a = normalize(uv - bl); 
vec2 b = normalize(uv - br); 
vec2 c = normalize(uv - tl); 
vec2 d = normalize(uv - tr); 

// Compute the dot products 
float q = dot(vec2(randx(tl),randy(tl)), c); 
float r = dot(vec2(randx(tr),randy(tr)), d); 
float s = dot(vec2(randx(bl),randy(bl)), a); 
float t = dot(vec2(randx(br),randy(br)), b); 

// interpolate using mix and our smooth interpolation function 
float st = mix(s, t, smoothInter(uv.x)); 
float qr = mix(q, r, smoothInter(uv.x)); 
float noise = mix(st, qr, smoothInter(uv.y)); 

// Output the color 
color = vec3(noise, noise, noise); 

}

回答

1

在最後幾行中,您要調用xl和y座標的全局上的smoothInter(),當需要在loc上調用它時al座標。

float st = mix(s, t, smoothInter((uv.x - col) * grid_dim)); 
float qr = mix(q, r, smoothInter((uv.x - col) * grid_dim)); 
float noise = mix(st, qr, smoothInter((uv.y - row) * grid_dim)); 

這裏乘以grid_dim是因爲你的網格單元不是單位寬度。 smoothInter()應該取0到1之間的值,並且這個變換確保了。

我也必須刪除normalize()調用,而是將結果「歸一化」到[0,1]範圍內。這很棘手,我假設你是在網格頂點生成隨機梯度向量的方法。就目前而言,您的代碼似乎會輸出約-2500到+2500之間的值。一旦我把這個範圍縮小到正確範圍,我就會出現一些不合需要的規律性。我再次把這個歸咎於prng的選擇。