1

我正在尝试在 GLSL 中编写类似于木材的噪声模式。这是我当前的代码:

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;

float random (in vec2 st) {
    return fract(sin(dot(st.xy,
                     vec2(12.9898,78.233))) * 43758.545312);
}

float noise(vec2 st) {
    vec2 i = floor(st);
    vec2 f = fract(st);
    vec2 u = f*f*(3.0-2.0*f);
    return mix( mix( random(i + vec2(0.0,0.0) ),
                 random(i + vec2(1.0,0.0) ), u.x),
            mix( random(i + vec2(0.0,1.0) ),
                 random(i + vec2(1.0,1.0) ), u.x), u.y);
}

mat2 rotate2d(float angle)
{
    return mat2(cos(angle), -sin(angle),
            sin(angle), cos(angle));
}

float lines(in vec2 pos, float b){
    float scale = 10.0;
    pos *= scale;
    return smoothstep(0.0, 0.5+b * 0.5, abs((sin(pos.x*3.1415)+b*2.0))*0.5);
}

vec3 c1 = vec3(0.134,0.109,0.705);
vec3 c2 = vec3(0.000,0.411,0.665);

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy;
    vec2 pos = st.yx*vec2(11.0, 3.0);


    vec3 color = vec3(1.0);

    float pattern = pos.x;
    color = mix(c1, c2, pattern);

    // Add noise
    pos = rotate2d(noise(pos)) * pos;

    // Draw lines
    pattern = lines(pos, 0.7);

    gl_FragColor = vec4(pattern, color);
} 

在当前状态下,它使我的图案看起来呈红粉色,底部出现了一些奇怪的渐变。我想让粉红色区域变成棕色,而我的图案保持黑色。有人可以展示如何调整我的颜色变量来做到这一点吗?

4

1 回答 1

1

颜色通道是红色、绿色、蓝色。因此,红色是第一个组件:

vec3 c1 = vec3(0.705,0.109,0.134);
vec3 c2 = vec3(0.665,0.411,0.000);

您需要在pattern设置后混合颜色:

void main() {
    // [...]

    // Draw lines
    pattern = lines(pos, 0.7);
    color = mix(c1, c2, pattern);

    gl_FragColor = vec4(color, 1.0);
} 

查看使用深棕色和浅棕色时的结果:

vec3 c1 = vec3(50.0, 40.0, 30.0) / 255.0;
vec3 c2 = vec3(200.0, 150.0, 100.0) / 255.0;

#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;

float random (in vec2 st) {
    return fract(sin(dot(st.xy, vec2(12.9898,78.233))) * 43758.545312);
}

float noise(vec2 st) {
    vec2 i = floor(st);
    vec2 f = fract(st);
    vec2 u = f*f*(3.0-2.0*f);
    return mix( mix( random(i + vec2(0.0,0.0) ),
                 random(i + vec2(1.0,0.0) ), u.x),
            mix( random(i + vec2(0.0,1.0) ),
                 random(i + vec2(1.0,1.0) ), u.x), u.y);
}

mat2 rotate2d(float angle)
{
    return mat2(cos(angle), -sin(angle), sin(angle), cos(angle));
}

float lines(in vec2 pos, float b){
    float scale = 10.0;
    pos *= scale;
    return smoothstep(0.0, 0.5+b * 0.5, abs((sin(pos.x*3.1415)+b*2.0))*0.5);
}

vec3 c1 = vec3(50.0, 40.0, 30.0) / 255.0;
vec3 c2 = vec3(200.0, 150.0, 100.0) / 255.0;

void main() {
    vec2 st = gl_FragCoord.xy/u_resolution.xy;
    vec2 pos = st.yx*vec2(11.0, 3.0);

    // Add noise
    pos = rotate2d(noise(pos)) * pos;

    // Draw lines
    float pattern = lines(pos, 0.7);
    vec3 color = mix(c1, c2, pattern);

    gl_FragColor = vec4(color, 1.0);
} 
于 2020-10-08T20:05:22.473 回答