// 移植自KdotJPG的OpenSimplex2 GLSL实现
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x*34.0)+1.0)*x); }
float openSimplexNoise(vec2 pos) {
const vec2 C = vec2(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439); // 0.5*(sqrt(3.0)-1.0)
vec2 i = floor(pos + dot(pos, C.yy));
vec2 x0 = pos - i + dot(i, C.xx);
vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
vec2 x1 = x0.xy + C.xx - i1;
vec2 x2 = x0.xy + C.xx * 2.0 - 1.0;
i = mod289(i);
vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0))
+ i.x + vec3(0.0, i1.x, 1.0));
vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x1, x1), dot(x2, x2)), 0.0);
m = m * m;
m = m * m;
vec3 x = 2.0 * fract(p * 0.0243902439) - 1.0; // [-1,1]
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * vec2(x1.x, x2.x) + h.yz * vec2(x1.y, x2.y);
return 130.0 * dot(m, g);
}
// 生成基于种子的随机偏移
vec2 seedOffset(int seed) {
return vec2(
fract(float(seed) * 0.12345) * 100.0,
fract(float(seed) * 0.67890) * 100.0
);
}
// 分形噪声函数
float fractalNoise(vec2 pos, int octaves, float persistence, float period, int seed) {
vec2 coord = pos / period + seedOffset(seed);
float total = 0.0;
float amplitude = 1.0;
float frequency = 1.0;
float maxAmplitude = 0.0;
for(int i = 0; i < octaves; i++) {
total += openSimplexNoise(coord * frequency) * amplitude;
maxAmplitude += amplitude;
amplitude *= persistence;
frequency *= 2.0;
}
return total / maxAmplitude; // 归一化到[-1,1]
}
/* 使用示例
void main() {
vec2 st = gl_FragCoord.xy / resolution.xy;
float noise = fractalNoise(st * 10.0, 4, 0.8, 20.0, 12345);
gl_FragColor = vec4(noise * 0.5 + 0.5); // 可视化
}
*/
glsl
float fractalNoise(vec2 pos, int octaves, float persistence, float period, int seed) {
// ...
float total = 0.0;
// ...
// 在边界处应用渐变(假设边界在[0,1]范围内)
float edgeFade = smoothstep(0.0, 0.1, pos.x) * smoothstep(0.0, 0.1, pos.y) *
smoothstep(1.0, 0.9, pos.x) * smoothstep(1.0, 0.9, pos.y);
return (total / maxAmplitude) * edgeFade; // 应用渐变
}
glsl
float seamlessFractalNoise(vec2 pos, int octaves, float persistence, float period, int seed) {
pos *= 0.01; // 坐标缩放,利用噪声函数的周期性
pos += seedOffset(seed); // 应用种子偏移
float total = 0.0, maxAmplitude = 0.0, amplitude = 1.0, frequency = 1.0;
for (int i = 0; i < octaves; i++) {
total += openSimplexNoise(pos * frequency) * amplitude;
maxAmplitude += amplitude;
amplitude *= persistence;
frequency *= 2.0;
}
// 应用边界渐变(示例)
float edgeFade = smoothstep(0.0, 0.1, pos.x) * smoothstep(0.0, 0.1, pos.y) *
smoothstep(1.0, 0.9, pos.x) * smoothstep(1.0, 0.9, pos.y);
return (total / maxAmplitude) * edgeFade;
}