BlueGit

timfa questward

Files

questward / shared / render / natureNoise.js

natureNoise.js

natureNoise.js 1.4 KiB Download Raw
1/**
2 * World-space tile noise for subtle nature-ground tint (1 sample per tile).
3 * Uses chunk+local indices so adjacent chunks share a continuous field.
4 */
5
6function fade (t)
7{
8 return t * t * t * (t * (t * 6 - 15) + 10);
9}
10
11function lerp (a, b, t)
12{
13 return a + (b - a) * t;
14}
15
16function hash2 (ix, iy)
17{
18 const n = Math.sin(ix * 127.1 + iy * 311.7) * 43758.5453123;
19 return n - Math.floor(n);
20}
21
22/** Gradient-style value at integer lattice. */
23function gradDot (ix, iy, x, y)
24{
25 const angle = hash2(ix, iy) * Math.PI * 2;
26 return Math.cos(angle) * x + Math.sin(angle) * y;
27}
28
29/** Classic 2D Perlin in roughly [-1, 1]. */
30export function perlin2 (x, y)
31{
32 const x0 = Math.floor(x);
33 const y0 = Math.floor(y);
34 const fx = x - x0;
35 const fy = y - y0;
36 const u = fade(fx);
37 const v = fade(fy);
38 const n00 = gradDot(x0, y0, fx, fy);
39 const n10 = gradDot(x0 + 1, y0, fx - 1, fy);
40 const n01 = gradDot(x0, y0 + 1, fx, fy - 1);
41 const n11 = gradDot(x0 + 1, y0 + 1, fx - 1, fy - 1);
42 return lerp(lerp(n00, n10, u), lerp(n01, n11, u), v);
43}
44
45/** 0..1 FBM of Perlin (2 octaves — cheap for 16×16 fills). */
46export function natureNoise01 (worldTileX, worldTileY, scale = 0.08)
47{
48 const s = Math.max(0.001, Number(scale) || 0.08);
49 const x = worldTileX * s;
50 const y = worldTileY * s;
51 let sum = perlin2(x, y);
52 sum += 0.5 * perlin2(x * 2.0 + 19.1, y * 2.0 - 7.3);
53 return Math.min(1, Math.max(0, sum * 0.5 + 0.5));
54}