opengl - 2D Perlin 噪声看起来是四四方方的

标签 opengl glsl shader procedural-programming

我似乎在二维输入上得到了四四方方的柏林噪声地形。

我一直在关注这个https://www.shadertoy.com/view/4tGSzW ,它使用 WebGL 而不是 opengl。我用范围 0.0 到 1.0 的 float 组替换了从某些样本纹理中获取的渐变方法。

#version 330 core
out vec4 FragColor;


uniform float gradient[256];

float fade(float t)
{
    return t*t*t*(t*(t*6.0-15.0)+10.0);
}


vec2 grad(vec2 p){
    vec2 v = vec2(gradient[int(p.x)&255],gradient[int(p.y)&255]);
    return normalize(v.xy*2.0 - vec2(1.0));
}

float noise(vec2 p){
    vec2 p0 = floor(p);
    vec2 p1 = p0 + vec2(1.0,0.0);
    vec2 p2 = p0 + vec2(0.0,1.0);
    vec2 p3 = p0 + vec2(1.0,1.0);

    vec2 g0 = grad(p0);
    vec2 g1 = grad(p1);
    vec2 g2 = grad(p2);
    vec2 g3 = grad(p3);

    float t0 = p.x - p0.x;
    float fade_t0 = fade(t0);
    float t1 = p.y - p0.y;
    float fade_t1 = fade(t1);

    float p0p1 = (1.0-fade_t0)*dot(g0,(p-p0)) + fade_t0*dot(g1,(p-p1));
    float p2p3 = (1.0-fade_t0)*dot(g2,(p-p2)) + fade_t0*dot(g3,(p-p3));

    return ((1.0-fade_t1)*p0p1 + fade_t1*p2p3);
}


void main()
{
    float n = noise(vec2(gl_FragCoord.x,gl_FragCoord.y)/64.0)*1.0 +
              noise(vec2(gl_FragCoord.x,gl_FragCoord.y)/32.0) * 0.5 +
              noise(vec2(gl_FragCoord.x,gl_FragCoord.y)/16.0) * 0.25 +
              noise(vec2(gl_FragCoord.x,gl_FragCoord.y)/8.0) * 0.125;


    FragColor = vec4(vec3(n*0.5+0.5),1.0);

}

Boxy perlin noise Image being generated

最佳答案

shadertoy版本中的源纹理是二维的,由256*256随机像素和多个颜色 channel 组成。 此外,当在原始 grad 函数中查找纹理时,会根据纹理缩小过滤器(可能是 GL_LINEAR)对像素进行插值。

vec2 grad(vec2 p) {
  const float texture_width = 256.0;
  vec4 v = texture(iChannel0, vec2(p.x / texture_width, p.y / texture_width));
   return normalize(v.xy*2.0 - vec2(1.0));
}

您的统一数组只有 256 个不同的值,并且纹素之间的插值未在您的 grad 函数中模拟:

vec2 grad(vec2 p){
   vec2 v = vec2(gradient[int(p.x)&255],gradient[int(p.y)&255]);
   return normalize(v.xy*2.0 - vec2(1.0));
}

使用 Random noise functions将噪声函数的返回值解释为角度(噪声*2*PI)来计算grad()的返回值:

float rand(vec2 co){
    return fract(sin(dot(co.xy, vec2(12.9898,78.233))) * 43758.5453);
}

vec2 grad(vec2 p){
    float a = rand(p) * 2.0 * 3.1415926;
    return vec2(cos(a), sin(a)); 
}

或者使用uniform数组生成随机值

vec2 grad(vec2 p){

    ivec2 i00 = ivec2(int(p.x)&255, int(p.y)&255); 
    vec2  f   = floor(p); 

    float vx = mix(gradient[i00.x], gradient[i00.x+1], f.x);
    float vy = mix(gradient[i00.y], gradient[i00.y+1], f.y);

    float a = (vx + vy) * 3.141529;
    return vec2(cos(a), sin(a)); 
}

关于opengl - 2D Perlin 噪声看起来是四四方方的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558338/

相关文章:

glsl - 我需要帮助将此 2D 天空着色器转换为 3D

java - 在 java androidgles20 api 中将纹理单元上传到采样器时出现错误 1281(错误值)

javascript - ThreeJS AdditiveBlending、ShaderMaterial、DepthTest问题

opengl - 可以只在 opengl 中移动相机而不重绘场景吗?

c++ - glm::rotate() 调用无法编译?

three.js - 光照模型的计算在着色器程序中是如何工作的?

javascript - 三.ShaderMaterial不透明度不起作用

opengl - 除了抗锯齿之外,我可以使用多重采样缓冲区吗?

opengl - OpenGL 中两个纹理的幂

c++ - TrueType 字体缩放会导致文本模糊?