diff --git a/Makefile b/Makefile index 69e46ec..2818ada 100644 --- a/Makefile +++ b/Makefile @@ -32,12 +32,12 @@ $(B)/cJSON.o: cJSON/cJSON.c cJSON/cJSON.h | $(B) $(B)/stb.o: src/stb.c third_party/stb/stb_image_write.h | $(B) $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ -VSMV_OBJ = vsmv cs pb json maps save img dump lcg noise shape worldgen fastnoise rivers settings verify cJSON stb +VSMV_OBJ = vsmv cs pb json maps save img dump lcg noise shape worldgen fastnoise rivers terra settings verify cJSON stb $(B)/vsmv: $(VSMV_OBJ:%=$(B)/%.o) $(CC) $^ -o $@ -lsqlite3 -VIEWER_OBJ = viewer tiles settings worldgen fastnoise rivers shape noise lcg maps save pb json cs nk cJSON stb +VIEWER_OBJ = viewer tiles settings worldgen fastnoise rivers terra shape noise lcg maps save pb json cs nk cJSON stb $(B)/vs-map-viewer: $(VIEWER_OBJ:%=$(B)/%.o) $(CC) $^ -o $@ $(SDL_LIBS) -lsqlite3 diff --git a/Plan.org b/Plan.org index cf918fd..1b5e4a4 100644 --- a/Plan.org +++ b/Plan.org @@ -408,22 +408,43 @@ Viewer: - *Hover info.* River distance and bank depth. - *World panel.* A rivers config path; empty means the mod's defaults. -** 5. Terrain height -- Port =NewGenTerra='s per-column path: - - landform weights (lerped, radius 3) with the river landform; - - valley blend; - - warp distortion (seed+9876/+9878); - - oceanicity and upheaval distY; - - =NoiseSign= with the bounds early-out; - - carving. -- Port the dry-climate raise from =GenBlockLayers=, with the Rivers patch - factor applied, so we can compare against stored heights. The Rivers - transpiler is IL pattern matching, so whether it applies in 1.22.7 - will show up in the diff. -- =vsmv verify-height= compares against =WorldGenTerrainHeightMap= for - all 11,414 stored map chunks. It reports the match percentage and - writes a diff PNG. -- Viewer: hillshaded terrain with water. +** 5. Terrain height (done) +=src/terra.sex= ports Rivers' NewGenTerra per column. That covers: +- the landform weights (LerpedWeightedIndex2DMap); +- per-Y thresholds; +- fair-warp distortion, oceanicity and upheaval; +- NewNormalizedSimplexFractalNoise with its stateful =NoiseSign=; +- the valley blend toward Rivers' river landform; +- riverbed carving. + +It returns the top solid block, which is the height the strata are +laid from. A chunk's bulk-solid layers reduce to a per-column rule. +With a river column in the chunk, Rivers disables those layers, which +lets carving reach y = 1. + +Against the 11,687,936 stored columns: +- *Exact:* 11,481,361 (98.2%). +- *Stored higher, under water:* 141,978. GenBlockLayers raises dry + seabeds after the strata. +- *Stored lower, on land:* 77,222. GenCaves lowers the height where a + cave opens the surface. +- *Unexplained:* 2,810, or 0.02%, likely the two passes combined. + +Neither later pass matters for the rock overlay. The raise only stacks +more of the top rock, and caves don't change which stratum a block +belongs to. + +The fix that took it from 87% to 98%: GenTerra turns its threshold into +a noise value with =NormalizedSimplexNoise.NoiseValueCurveInverse=, +the inverse of the *tanh* curve. The column bounds use the new noise's +own =v / sqrt(1 + v^2)= curve. Vanilla does the same. + +Viewer: +- *Terrain height layer.* Water depth below sea level, elevation and + hillshade above. +- *Sampling.* Every 1 to 32 blocks depending on zoom; a column costs + about 11 us. +- *Hover info.* Shows the height. ** 6. Rock strata + overlay - Port =GenRockStrataNew.genBlockColumn=: diff --git a/Sex-field-notes.org b/Sex-field-notes.org index 845148e..1afe466 100644 --- a/Sex-field-notes.org +++ b/Sex-field-notes.org @@ -9,6 +9,16 @@ the whole token as a symbol and the leading =-= is mangled like any other. =(- INFINITY)= works. Negative literals like =-1= are fine, so it's only symbolic constants, but the mangled name reads like a typo. +* A cast of a bitwise expression loses its parentheses +=(cast (c-bit-or xn 1) float)= emits =(float)xn | 1=, which C reads as +=((float)xn) | 1=: a compile error here, but with an integer target +type it would silently cast only =xn=. Arithmetic operands are +parenthesized; bitwise ones aren't. With the two entries below, that +makes three places where operator precedence leaks into the output. +In this project they have cost more time than every other entry put +together, mostly through =(if ...)= in arithmetic, which keeps coming +back because it reads so naturally. + * A cast as the object of =.= loses its parentheses =(. (cast pa (* const wanted)) distance)= emits =(const wanted *)pa->distance=, which C reads as a cast of diff --git a/src/noise.sex b/src/noise.sex index 2a48b80..f3e5389 100644 --- a/src/noise.sex +++ b/src/noise.sex @@ -15,6 +15,7 @@ (define SQUISH-3D 0.3333333333333333) (define NORM-2D 0.02127659574468085) (define NORM-3D 0.009708737864077669) +(define NORM-2D-WARP 0.020435461373899677) (pub define MAX-VALUE-3D 0.9871465422297019) (define VALUE-MULTIPLIER 1.2) (pub define MAX-OCTAVES 16) @@ -333,3 +334,128 @@ (var v double (* (.eval-2d (& [(. self octaves) i]) (* x f) (* y f)) [(. self amplitudes) i])) (+= value (if (> v 0.0) (fmax 0.0 (- v [thresholds i])) (fmin 0.0 (+ v [thresholds i]))))) (return value))) + +;;; Generated from vsapi SimplexOctave.cs warpUpgradeVectors2D; do not edit. +(var warp-vectors [double 384] + #(0.9238795325112866 0.3826834323650898 4.97524354451166 2.060813352245919 -4.975243544511659 -2.060813352245919 + 0.7071067811865476 0.7071067811865476 3.807886552931954 3.807886552931954 3.8078865529319543 -3.8078865529319543 + 1.0 0.0 4.975243544511659 2.0608133522459187 4.975243544511659 -2.0608133522459187 + 0.3826834323650897 0.9238795325112867 0.0 5.385164807134505 5.385164807134505 0.0 + 1.0 0.0 4.975243544511659 2.0608133522459187 -4.975243544511659 2.0608133522459187 + 0.9238795325112867 -0.3826834323650897 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.9238795325112866 0.3826834323650898 4.975243544511659 2.060813352245919 4.97524354451166 2.060813352245919 + 0.7071067811865476 0.7071067811865476 3.8078865529319543 -3.8078865529319543 3.807886552931954 3.807886552931954 + 0.7071067811865476 0.7071067811865476 3.807886552931954 3.807886552931954 -3.8078865529319543 3.8078865529319543 + 0.3826834323650898 0.9238795325112866 2.060813352245919 4.97524354451166 2.060813352245919 4.975243544511659 + -0.3826834323650897 0.9238795325112867 -5.385164807134505 0.0 0.0 5.385164807134505 + 0.0 1.0 -2.0608133522459187 4.975243544511659 2.0608133522459187 4.975243544511659 + 0.9238795325112867 0.3826834323650897 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.0 1 2.0608133522459187 -4.975243544511659 2.0608133522459187 4.975243544511659 + 0.7071067811865476 0.7071067811865476 -3.8078865529319543 3.8078865529319543 3.807886552931954 3.807886552931954 + 0.3826834323650898 0.9238795325112866 -2.060813352245919 -4.975243544511659 2.060813352245919 4.97524354451166 + -1.0 0.0 4.975243544511659 -2.0608133522459187 4.975243544511659 2.0608133522459187 + -0.3826834323650897 0.9238795325112867 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + -0.9238795325112866 0.3826834323650898 4.975243544511659 -2.060813352245919 -4.97524354451166 2.060813352245919 + -0.7071067811865476 0.7071067811865476 3.8078865529319543 3.8078865529319543 -3.807886552931954 3.807886552931954 + -0.9238795325112866 0.3826834323650898 4.97524354451166 -2.060813352245919 4.975243544511659 -2.060813352245919 + -0.7071067811865476 0.7071067811865476 3.807886552931954 -3.807886552931954 -3.8078865529319543 -3.8078865529319543 + -1.0 0.0 4.975243544511659 -2.0608133522459187 -4.975243544511659 -2.0608133522459187 + -0.9238795325112867 -0.3826834323650897 5.385164807134505 0.0 0.0 -5.385164807134505 + 0.3826834323650897 0.9238795325112867 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.0 1.0 2.0608133522459187 4.975243544511659 -2.0608133522459187 4.975243544511659 + -0.7071067811865476 0.7071067811865476 -3.8078865529319543 -3.8078865529319543 -3.807886552931954 3.807886552931954 + -0.3826834323650898 0.9238795325112866 -2.060813352245919 4.975243544511659 -2.060813352245919 4.97524354451166 + -0.7071067811865476 0.7071067811865476 3.807886552931954 -3.807886552931954 3.8078865529319543 3.8078865529319543 + -0.3826834323650898 0.9238795325112866 2.060813352245919 -4.97524354451166 -2.060813352245919 4.975243544511659 + -0.9238795325112867 0.3826834323650897 0.0 -5.385164807134505 -5.385164807134505 0.0 + 0.0 1.0 -2.0608133522459187 -4.975243544511659 -2.0608133522459187 4.975243544511659 + 1.0 0.0 4.975243544511659 -2.0608133522459187 -4.975243544511659 -2.0608133522459187 + 0.9238795325112867 0.3826834323650897 5.385164807134505 0.0 0.0 -5.385164807134505 + 0.9238795325112866 -0.3826834323650898 4.97524354451166 -2.060813352245919 4.975243544511659 -2.060813352245919 + 0.7071067811865476 -0.7071067811865476 3.807886552931954 -3.807886552931954 -3.8078865529319543 -3.8078865529319543 + 0.9238795325112866 -0.3826834323650898 4.975243544511659 -2.060813352245919 -4.97524354451166 2.060813352245919 + 0.7071067811865476 -0.7071067811865476 3.8078865529319543 3.8078865529319543 -3.807886552931954 3.807886552931954 + 1.0 0.0 4.975243544511659 -2.0608133522459187 4.975243544511659 2.0608133522459187 + 0.3826834323650897 -0.9238795325112867 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.9238795325112867 -0.3826834323650897 0.0 -5.385164807134505 -5.385164807134505 0.0 + 0.0 -1.0 -2.0608133522459187 -4.975243544511659 -2.0608133522459187 4.975243544511659 + 0.7071067811865476 -0.7071067811865476 3.807886552931954 -3.807886552931954 3.8078865529319543 3.8078865529319543 + 0.3826834323650898 -0.9238795325112866 2.060813352245919 -4.97524354451166 -2.060813352245919 4.975243544511659 + 0.7071067811865476 -0.7071067811865476 -3.8078865529319543 -3.8078865529319543 -3.807886552931954 3.807886552931954 + 0.3826834323650898 -0.9238795325112866 -2.060813352245919 4.975243544511659 -2.060813352245919 4.97524354451166 + -0.3826834323650897 -0.9238795325112867 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.0 -1.0 2.0608133522459187 4.975243544511659 -2.0608133522459187 4.975243544511659 + -0.9238795325112866 -0.3826834323650898 4.975243544511659 2.060813352245919 4.97524354451166 2.060813352245919 + -0.7071067811865476 -0.7071067811865476 3.8078865529319543 -3.8078865529319543 3.807886552931954 3.807886552931954 + -1.0 0.0 4.975243544511659 2.0608133522459187 -4.975243544511659 2.0608133522459187 + -0.9238795325112867 0.3826834323650897 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + -1.0 0.0 4.975243544511659 2.0608133522459187 4.975243544511659 -2.0608133522459187 + -0.3826834323650897 -0.9238795325112867 0.0 5.385164807134505 5.385164807134505 0.0 + -0.9238795325112866 -0.3826834323650898 4.97524354451166 2.060813352245919 -4.975243544511659 -2.060813352245919 + -0.7071067811865476 -0.7071067811865476 3.807886552931954 3.807886552931954 3.8078865529319543 -3.8078865529319543 + -0.7071067811865476 -0.7071067811865476 -3.8078865529319543 3.8078865529319543 3.807886552931954 3.807886552931954 + -0.3826834323650898 -0.9238795325112866 -2.060813352245919 -4.975243544511659 2.060813352245919 4.97524354451166 + -0.9238795325112867 -0.3826834323650897 3.807886552931954 3.807886552931954 -3.807886552931954 3.807886552931954 + 0.0 -1.0 2.0608133522459187 -4.975243544511659 2.0608133522459187 4.975243544511659 + 0.3826834323650897 -0.9238795325112867 -5.385164807134505 0.0 0.0 5.385164807134505 + 0.0 -1.0 -2.0608133522459187 4.975243544511659 2.0608133522459187 4.975243544511659 + -0.7071067811865476 -0.7071067811865476 3.807886552931954 3.807886552931954 -3.8078865529319543 3.8078865529319543 + -0.3826834323650898 -0.9238795325112866 2.060813352245919 4.97524354451166 2.060813352245919 4.975243544511659)) + +;;; SimplexNoiseOctave.EvaluateFairWarpVector: a 2D warp from a pair of +;;; octaves, rotated so its directions are fairer than two independent +;;; noises'. +(fn fair-warp-octave ((ox (* const simplex-octave)) (oz (* const simplex-octave)) + (x double) (y double) (out-x (* double)) (out-y (* double))) void + (var stretch double (* (+ x y) STRETCH-2D)) + (var xs double (+ x stretch)) + (var ys double (+ y stretch)) + (var xsb int (cast (floor xs) int)) + (var ysb int (cast (floor ys) int)) + (-= xs xsb) + (-= ys ysb) + (var squish double (* (+ xsb ysb) SQUISH-2D)) + (var dx0 double (- x (+ xsb squish))) + (var dy0 double (- y (+ ysb squish))) + (var in-sum double (+ xs ys)) + (var hash u32 (c-bit-or (cast (+ (- xs ys) 1) u32) + (<< (cast in-sum u32) 1) + (<< (cast (+ in-sum ys) u32) 2) + (<< (cast (+ in-sum xs) u32) 4))) + (var dist-x double 0) + (var dist-y double 0) + (for (var c int [lookup-2d hash]) (>= c 0) (= c (. [pool c] next)) + (var dx double (+ dx0 (. [pool c] dx))) + (var dy double (+ dy0 (. [pool c] dy))) + (var attn double (- 2.0 (* dx dx) (* dy dy))) + (if (> attn 0.0) + (do + (var px int (+ xsb (. [pool c] xsb))) + (var py int (+ ysb (. [pool c] ysb))) + (var i int [(. ox perm-2d) (& (+ [(. ox perm) (& px 255)] py) 255)]) + (var j int [(. oz perm-2d) (& (+ [(. oz perm) (& px 255)] py) 255)]) + (var k int (* (+ (* i 8) j) 3)) + (var rx double [warp-vectors k]) + (var ry double [warp-vectors (+ k 1)]) + (var a double (+ (* [warp-vectors (+ k 2)] dx) (* [warp-vectors (+ k 3)] dy))) + (var b double (+ (* [warp-vectors (+ k 4)] dx) (* [warp-vectors (+ k 5)] dy))) + (*= attn attn) + (*= attn attn) + (+= dist-x (* attn (+ (* a rx) (* b ry)))) + (+= dist-y (* attn (- (* a ry) (* b rx))))))) + (= (* out-x) (* dist-x NORM-2D-WARP)) + (= (* out-y) (* dist-y NORM-2D-WARP))) + +;;; SimplexNoise.NoiseFairWarpVector over the octaves of two noises +;;; made alike. +(pub fn fair-warp ((nx (* const simplex-sum)) (nz (* const simplex-sum)) (x double) (y double) + (out-x (* double)) (out-y (* double))) void + (= (* out-x) 0) + (= (* out-y) 0) + (for (var i int 0) (< i (. nx count)) (++ i) + (var f double [(. nx frequencies) i]) + (var hx double) + (var hy double) + (fair-warp-octave (& [(. nx octaves) i]) (& [(. nz octaves) i]) (* x f) (* y f) (& hx) (& hy)) + (+= (* out-x) (* hx [(. nx amplitudes) i])) + (+= (* out-y) (* hy [(. nx amplitudes) i])))) diff --git a/src/terra.sex b/src/terra.sex new file mode 100644 index 0000000..4c2db71 --- /dev/null +++ b/src/terra.sex @@ -0,0 +1,786 @@ +;;; Terrain height, as Rivers' NewGenTerra computes it: vanilla GenTerra +;;; plus the river valley blend and the riverbed carving. Only the +;;; column's height is kept, the highest solid block, which is what +;;; worldgen stores as WorldGenTerrainHeightMap and what the rock +;;; strata are laid from. +;;; +;;; Per column: landform weights lerped from the region's landform +;;; map, a Y threshold profile from them, distortion and upheaval, and +;;; a 3D noise against the threshold at every Y until the column is +;;; certainly air above. + +(include stdio.h stdlib.h string.h math.h) +(import maps) +(import lcg) +(import noise) +(import shape) +(import json) +(import worldgen) +(import fastnoise) +(import rivers) + +;;; NewSimplexNoiseLayer -------------------------------------------- + +(define PRIME-X 5910200641878280303) +(define PRIME-Y 6452764530575939509) +(define PRIME-Z 6614699811220273867) +(define HASH-MULTIPLIER 6026932503003350773) +(define SEED-FLIP -5968755714895566377) +(define NORMALIZER-3D 0.2781926117527186) +(define MAX-Y-SLOPE 5.0) + +;;; Generated from vsapi NewSimplexNoiseLayer.cs grad3; do not edit. +(var grad3 [float 192] + #(2.22474487139 2.22474487139 -1.0 0.0 + 2.22474487139 2.22474487139 1.0 0.0 + 3.0862664687972017 1.1721513422464978 0.0 0.0 + 1.1721513422464978 3.0862664687972017 0.0 0.0 + -2.22474487139 2.22474487139 -1.0 0.0 + -2.22474487139 2.22474487139 1.0 0.0 + -1.1721513422464978 3.0862664687972017 0.0 0.0 + -3.0862664687972017 1.1721513422464978 0.0 0.0 + -1.0 -2.22474487139 -2.22474487139 0.0 + 1.0 -2.22474487139 -2.22474487139 0.0 + 0.0 -3.0862664687972017 -1.1721513422464978 0.0 + 0.0 -1.1721513422464978 -3.0862664687972017 0.0 + -1.0 -2.22474487139 2.22474487139 0.0 + 1.0 -2.22474487139 2.22474487139 0.0 + 0.0 -1.1721513422464978 3.0862664687972017 0.0 + 0.0 -3.0862664687972017 1.1721513422464978 0.0 + -2.22474487139 -2.22474487139 -1.0 0.0 + -2.22474487139 -2.22474487139 1.0 0.0 + -3.0862664687972017 -1.1721513422464978 0.0 0.0 + -1.1721513422464978 -3.0862664687972017 0.0 0.0 + -2.22474487139 -1.0 -2.22474487139 0.0 + -2.22474487139 1.0 -2.22474487139 0.0 + -1.1721513422464978 0.0 -3.0862664687972017 0.0 + -3.0862664687972017 0.0 -1.1721513422464978 0.0 + -2.22474487139 -1.0 2.22474487139 0.0 + -2.22474487139 1.0 2.22474487139 0.0 + -3.0862664687972017 0.0 1.1721513422464978 0.0 + -1.1721513422464978 0.0 3.0862664687972017 0.0 + -1.0 2.22474487139 -2.22474487139 0.0 + 1.0 2.22474487139 -2.22474487139 0.0 + 0.0 1.1721513422464978 -3.0862664687972017 0.0 + 0.0 3.0862664687972017 -1.1721513422464978 0.0 + -1.0 2.22474487139 2.22474487139 0.0 + 1.0 2.22474487139 2.22474487139 0.0 + 0.0 3.0862664687972017 1.1721513422464978 0.0 + 0.0 1.1721513422464978 3.0862664687972017 0.0 + 2.22474487139 -2.22474487139 -1.0 0.0 + 2.22474487139 -2.22474487139 1.0 0.0 + 1.1721513422464978 -3.0862664687972017 0.0 0.0 + 3.0862664687972017 -1.1721513422464978 0.0 0.0 + 2.22474487139 -1.0 -2.22474487139 0.0 + 2.22474487139 1.0 -2.22474487139 0.0 + 3.0862664687972017 0.0 -1.1721513422464978 0.0 + 1.1721513422464978 0.0 -3.0862664687972017 0.0 + 2.22474487139 -1.0 2.22474487139 0.0 + 2.22474487139 1.0 2.22474487139 0.0 + 1.1721513422464978 0.0 3.0862664687972017 0.0 + 3.0862664687972017 0.0 1.1721513422464978 0.0)) + +(var gradients [float 1024]) + +(fn init-gradients () void + (for (var i int 0) (< i 1024) (++ i) + (= [gradients i] (cast (/ (cast [grad3 (% i 192)] double) NORMALIZER-3D) float)))) + +(fn grad ((hash u64) (dx float) (dy float) (dz float)) float + (*= hash (cast HASH-MULTIPLIER u64)) + (^= hash (cast (>> (cast hash i64) 58) u64)) + (var gi int (& (cast hash int) 1020)) + (return (+ (+ (* [gradients gi] dx) (* [gradients (c-bit-or gi 1)] dy)) + (* [gradients (c-bit-or gi 2)] dz)))) + +(fn hash4 ((seed u64) (x u64) (y u64) (z u64)) u64 + (return (^ seed x y z))) + +(fn mask ((m int)) u64 + (return (cast (cast m i64) u64))) + +(fn noise3-base ((seed i64) (xr double) (yr double) (zr double)) float + (var xrb int (cast (floor xr) int)) + (var yrb int (cast (floor yr) int)) + (var zrb int (cast (floor zr) int)) + (var xi float (cast (- xr xrb) float)) + (var yi float (cast (- yr yrb) float)) + (var zi float (cast (- zr zrb) float)) + (var px u64 (cast PRIME-X u64)) + (var py u64 (cast PRIME-Y u64)) + (var pz u64 (cast PRIME-Z u64)) + (var xrbp u64 (* (mask xrb) px)) + (var yrbp u64 (* (mask yrb) py)) + (var zrbp u64 (* (mask zrb) pz)) + (var s1 u64 (cast seed u64)) + (var s2 u64 (^ s1 (cast SEED-FLIP u64))) + (var xn int (cast (- (cast -0.5 float) xi) int)) + (var yn int (cast (- (cast -0.5 float) yi) int)) + (var zn int (cast (- (cast -0.5 float) zi) int)) + (var x0 float (+ xi xn)) + (var y0 float (+ yi yn)) + (var z0 float (+ zi zn)) + (var a0 float (- (cast 0.75 float) (* x0 x0) (* y0 y0) (* z0 z0))) + (var value float (* (* (* a0 a0) (* a0 a0)) + (grad (hash4 s1 (+ xrbp (& (mask xn) px)) (+ yrbp (& (mask yn) py)) + (+ zrbp (& (mask zn) pz))) + x0 y0 z0))) + (var x1 float (- xi (cast 0.5 float))) + (var y1 float (- yi (cast 0.5 float))) + (var z1 float (- zi (cast 0.5 float))) + (var a1 float (- (cast 0.75 float) (* x1 x1) (* y1 y1) (* z1 z1))) + (+= value (* (* (* a1 a1) (* a1 a1)) + (grad (hash4 s2 (+ xrbp px) (+ yrbp py) (+ zrbp pz)) x1 y1 z1))) +;; The masks are 0 or -1; shifts of them become multiplications, as a + ;; negative left shift is undefined in C. + (var xf0 float (* (cast (* (c-bit-or xn 1) 2) float) x1)) + (var yf0 float (* (cast (* (c-bit-or yn 1) 2) float) y1)) + (var zf0 float (* (cast (* (c-bit-or zn 1) 2) float) z1)) + (var one float 1) + (var xf1 float (- (* (cast (- -2 (* xn 4)) float) x1) one)) + (var yf1 float (- (* (cast (- -2 (* yn 4)) float) y1) one)) + (var zf1 float (- (* (cast (- -2 (* zn 4)) float) z1) one)) + (var xsi int (c-bit-or xn 1)) + (var ysi int (c-bit-or yn 1)) + (var zsi int (c-bit-or zn 1)) + (var xs float xsi) + (var ys float ysi) + (var zs float zsi) + + (var skip5 bool false) + (var a2 float (+ xf0 a0)) + (if (> a2 0) + (+= value (* (* (* a2 a2) (* a2 a2)) + (grad (hash4 s1 (+ xrbp (& (~ (mask xn)) px)) (+ yrbp (& (mask yn) py)) + (+ zrbp (& (mask zn) pz))) + (- x0 xs) y0 z0))) + (do + (var a3 float (+ (+ yf0 zf0) a0)) + (if (> a3 0) + (+= value (* (* (* a3 a3) (* a3 a3)) + (grad (hash4 s1 (+ xrbp (& (mask xn) px)) (+ yrbp (& (~ (mask yn)) py)) + (+ zrbp (& (~ (mask zn)) pz))) + x0 (- y0 ys) (- z0 zs))))) + (var a4 float (+ xf1 a1)) + (if (> a4 0) + (do + (+= value (* (* (* a4 a4) (* a4 a4)) + (grad (hash4 s2 (+ xrbp (& (mask xn) (* px 2))) (+ yrbp py) (+ zrbp pz)) + (+ xs x1) y1 z1))) + (= skip5 true))))) + + (var skip9 bool false) + (var a6 float (+ yf0 a0)) + (if (> a6 0) + (+= value (* (* (* a6 a6) (* a6 a6)) + (grad (hash4 s1 (+ xrbp (& (mask xn) px)) (+ yrbp (& (~ (mask yn)) py)) + (+ zrbp (& (mask zn) pz))) + x0 (- y0 ys) z0))) + (do + (var a7 float (+ (+ xf0 zf0) a0)) + (if (> a7 0) + (+= value (* (* (* a7 a7) (* a7 a7)) + (grad (hash4 s1 (+ xrbp (& (~ (mask xn)) px)) (+ yrbp (& (mask yn) py)) + (+ zrbp (& (~ (mask zn)) pz))) + (- x0 xs) y0 (- z0 zs))))) + (var a8 float (+ yf1 a1)) + (if (> a8 0) + (do + (+= value (* (* (* a8 a8) (* a8 a8)) + (grad (hash4 s2 (+ xrbp px) (+ yrbp (& (mask yn) (<< py 1))) (+ zrbp pz)) + x1 (+ ys y1) z1))) + (= skip9 true))))) + + (var skip-d bool false) + (var aa float (+ zf0 a0)) + (if (> aa 0) + (+= value (* (* (* aa aa) (* aa aa)) + (grad (hash4 s1 (+ xrbp (& (mask xn) px)) (+ yrbp (& (mask yn) py)) + (+ zrbp (& (~ (mask zn)) pz))) + x0 y0 (- z0 zs)))) + (do + (var ab float (+ (+ xf0 yf0) a0)) + (if (> ab 0) + (+= value (* (* (* ab ab) (* ab ab)) + (grad (hash4 s1 (+ xrbp (& (~ (mask xn)) px)) (+ yrbp (& (~ (mask yn)) py)) + (+ zrbp (& (mask zn) pz))) + (- x0 xs) (- y0 ys) z0)))) + (var ac float (+ zf1 a1)) + (if (> ac 0) + (do + (+= value (* (* (* ac ac) (* ac ac)) + (grad (hash4 s2 (+ xrbp px) (+ yrbp py) (+ zrbp (& (mask zn) (<< pz 1)))) + x1 y1 (+ zs z1)))) + (= skip-d true))))) + + (if (! skip5) + (do + (var a5 float (+ (+ yf1 zf1) a1)) + (if (> a5 0) + (+= value (* (* (* a5 a5) (* a5 a5)) + (grad (hash4 s2 (+ xrbp px) (+ yrbp (& (mask yn) (<< py 1))) + (+ zrbp (& (mask zn) (<< pz 1)))) + x1 (+ ys y1) (+ zs z1))))))) + (if (! skip9) + (do + (var a9 float (+ (+ xf1 zf1) a1)) + (if (> a9 0) + (+= value (* (* (* a9 a9) (* a9 a9)) + (grad (hash4 s2 (+ xrbp (& (mask xn) (* px 2))) (+ yrbp py) + (+ zrbp (& (mask zn) (<< pz 1)))) + (+ xs x1) y1 (+ zs z1))))))) + (if (! skip-d) + (do + (var ad float (+ (+ xf1 yf1) a1)) + (if (> ad 0) + (+= value (* (* (* ad ad) (* ad ad)) + (grad (hash4 s2 (+ xrbp (& (mask xn) (<< px 1))) + (+ yrbp (& (mask yn) (<< py 1))) (+ zrbp pz)) + (+ xs x1) (+ ys y1) z1)))))) + (return value)) + +(fn evaluate-improved-xz ((seed i64) (x double) (y double) (z double)) float + (var root3over3 double 0.577350269189626) + (var xz double (+ x z)) + (var s2 double (* xz -0.211324865405187)) + (var yy double (* y root3over3)) + (var xr double (+ (+ x s2) yy)) + (var zr double (+ (+ z s2) yy)) + (var yr double (+ (* xz (- root3over3)) yy)) + (return (noise3-base seed xr yr zr))) + +;;; .NET's Math.Max and Math.Min: NaN if either side is. C's fmax and +;;; fmin return the other side instead, and NoiseSign's first pass +;;; relies on the NaN. +(fn net-max ((a double) (b double)) double + (if (|| (!= a a) (!= b b)) (return NAN)) + (return (if (> a b) a b))) + +(fn net-min ((a double) (b double)) double + (if (|| (!= a a) (!= b b)) (return NAN)) + (return (if (< a b) a b))) + +(fn smooth-max ((a double) (b double) (k double)) double + (var falloff double (/ (net-max (- k (fabs (- a b))) 0.0) k)) + (return (+ (net-max a b) (* (* (* falloff falloff) k) 0.25)))) + +(fn smooth-min ((a double) (b double) (k double)) double + (var falloff double (/ (net-max (- k (fabs (- a b))) 0.0) k)) + (return (- (net-min a b) (* (* (* falloff falloff) k) 0.25)))) + +(fn thresholding ((value double) (threshold double) (k double)) double + (return (+ (smooth-max 0 (- value threshold) k) (smooth-min 0 (+ value threshold) k)))) + +(fn value-curve ((v double)) double + (return (+ (* (/ v (sqrt (+ 1 (* v v)))) 0.5) 0.5))) + +;;; NormalizedSimplexNoise.NoiseValueCurveInverse: the inverse of the +;;; *tanh* curve. GenTerra turns its threshold into a noise value with +;;; this one, though the column bounds use the new noise's own curve. +(fn tanh-curve-inverse ((v double)) double + (if (<= v 0.0) (return (- INFINITY))) + (if (>= v 1.0) (return INFINITY)) + (return (* 0.5 (log (/ v (- 1.0 v)))))) + +(define MAX-TERRAIN-OCTAVES 16) + +;;; NewNormalizedSimplexFractalNoise.ColumnNoise: one column's octaves, +;;; strongest first, each with the bound on what the rest can add. +(record octave-entry + ((seed i64) (x double) (frequency-y double) (z double) (amplitude double) (threshold double) + (smoothing double) (stop-bound double) (past-value double) (past-y double))) + +(record column-noise ((entries [octave-entry 16]) (count int) (bound-min double) (bound-max double))) + +(pub record terrain-noise + ((count int) (frequencies [double 16]) (seeds [i64 16]))) + +(fn value-multiplier () double (return (* 1.2 MAX-VALUE-3D))) +(fn threshold-rescale () double (return (/ 1.0 MAX-VALUE-3D))) + +(fn column-noise/make ((n (* const terrain-noise)) (relative-y double) (amps (* const double)) + (thresholds (* const double)) (x double) (z double) (c (* column-noise))) void + (var vm double (value-multiplier)) + (var max-values [double 16]) + (var order [int 16]) + (var used int 0) + (var bound double 0) + (for (var i int (- (. n count) 1)) (>= i 0) (-- i) + (= [max-values i] (* (fmax 0 (- (fabs [amps i]) [thresholds i])) vm)) + (+= bound [max-values i]) + (if (== [max-values i] 0) + (continue)) + (= [order used] i) + (for (var j int (- used 1)) (>= j 0) (-- j) + (if (> [max-values [order (+ j 1)]] [max-values [order j]]) + (do + (var t int [order j]) + (= [order j] [order (+ j 1)]) + (= [order (+ j 1)] t)))) + (++ used)) + (= (. c bound-min) (value-curve (- bound))) + (= (. c bound-max) (value-curve bound)) + (= (. c count) used) + (var vm-tr double (* vm (threshold-rescale))) + (var sum double 0) + (for (var j int (- used 1)) (>= j 0) (-- j) + (var i int [order j]) + (+= sum [max-values i]) + (var f double [(. n frequencies) i]) + (var e (* octave-entry) (& [(. c entries) j])) + (= (. e seed) [(. n seeds) i]) + (= (. e x) (* x f)) + (= (. e z) (* z f)) + (= (. e frequency-y) (* f relative-y)) + (= (. e amplitude) (* [amps i] vm)) + (= (. e threshold) (* [thresholds i] vm-tr)) + (= (. e smoothing) (* (* [amps i] f) 3.5)) + (= (. e stop-bound) sum) + (= (. e past-value) 0) + (= (. e past-y) NAN))) + +;;; ColumnNoise.NoiseSign: the sign of noise plus thresholder at Y, +;;; leaving out octaves once the rest cannot change it. The first pass +;;; bounds each octave from its value at the last Y sampled, which can +;;; settle the sign without evaluating anything. +(fn column-noise/sign ((c (* column-noise)) (y double) (thresholder double)) double + (var value double thresholder) + (var lo double thresholder) + (var hi double thresholder) + (for (var j int 0) (< j (. c count)) (++ j) + (if (&& (! (<= hi 0)) (! (>= lo 0))) + (break)) + (var e (* octave-entry) (& [(. c entries) j])) + (if (>= lo (. e stop-bound)) (return lo)) + (if (<= hi (- (. e stop-bound))) (return hi)) + (var eval-y double (* y (. e frequency-y))) + (var dy double (fabs (- (. e past-y) eval-y))) + (+= lo (thresholding (* (net-max -1 (- (. e past-value) (* dy MAX-Y-SLOPE))) (. e amplitude)) + (. e threshold) (. e smoothing))) + (+= hi (thresholding (* (net-min 1 (+ (. e past-value) (* dy MAX-Y-SLOPE))) (. e amplitude)) + (. e threshold) (. e smoothing)))) + (for (var j int 0) (< j (. c count)) (++ j) + (var e (* octave-entry) (& [(. c entries) j])) + (if (|| (>= value (. e stop-bound)) (<= value (- (. e stop-bound)))) + (break)) + (var eval-y double (* y (. e frequency-y))) + (var v double (evaluate-improved-xz (. e seed) (. e x) eval-y (. e z))) + (= (. e past-value) v) + (= (. e past-y) eval-y) + (+= value (thresholding (* v (. e amplitude)) (. e threshold) (. e smoothing)))) + (return value)) + +;;; LerpedWeightedIndex2DMap over a region's landform map: each pixel's +;;; landforms box-blurred over a radius of 3, as (index, weight) lists. +(define LANDFORM-BLUR 3) + +(pub record landform-weights + ((size int) (pad int) (counts (* u8)) (indices (* u8)) (weights (* float)))) + +(fn landform-weights/make ((m (* const int-map))) landform-weights + (var w landform-weights) + (var n int (. m size)) + (= (. w size) n) + (= (. w pad) (. m pad-tl)) + (= (. w counts) (calloc (* n n) 1)) + (= (. w indices) (malloc (* n n 49))) + (= (. w weights) (malloc (* n n 49 (sizeof float)))) + (for (var x int 0) (< x n) (++ x) + (for (var z int 0) (< z n) (++ z) + (var min-x int (if (< (- x LANDFORM-BLUR) 0) 0 (- x LANDFORM-BLUR))) + (var min-z int (if (< (- z LANDFORM-BLUR) 0) 0 (- z LANDFORM-BLUR))) + (var max-x int (if (> (+ x LANDFORM-BLUR) (- n 1)) (- n 1) (+ x LANDFORM-BLUR))) + (var max-z int (if (> (+ z LANDFORM-BLUR) (- n 1)) (- n 1) (+ z LANDFORM-BLUR))) + (var frac float (/ (cast 1 float) (cast (* (+ (- max-x min-x) 1) (+ (- max-z min-z) 1)) float))) + (var cell int (+ (* z n) x)) + (var base int (* cell 49)) + (var count int 0) + (for (var bx int min-x) (<= bx max-x) (++ bx) + (for (var bz int min-z) (<= bz max-z) (++ bz) + (var index int [(. m data) (+ (* bz n) bx)]) + (var k int 0) + (while (&& (< k count) (!= [(. w indices) (+ base k)] index)) + (++ k)) + (if (== k count) + (do + (= [(. w indices) (+ base k)] (cast index u8)) + (= [(. w weights) (+ base k)] frac) + (++ count)) + (= [(. w weights) (+ base k)] (+ frac [(. w weights) (+ base k)]))))) + (= [(. w counts) cell] (cast count u8)))) + (return w)) + +(fn landform-weights/release ((w (* landform-weights))) void + (free (. w counts)) + (free (. w indices)) + (free (. w weights))) + +(fn half-bilerp ((w (* const landform-weights)) (left int) (right int) (lerp float) + (out (* float)) (overall float)) void + (for (var k int 0) (< k [(. w counts) left]) (++ k) + (var i int [(. w indices) (+ (* left 49) k)]) + (+= [out i] (* (* (- (cast 1 float) lerp) [(. w weights) (+ (* left 49) k)]) overall))) + (for (var k int 0) (< k [(. w counts) right]) (++ k) + (var i int [(. w indices) (+ (* right 49) k)]) + (+= [out i] (* (* lerp [(. w weights) (+ (* right 49) k)]) overall)))) + +;;; WeightsAt: the landform weights at landform-map position (x, z) +;;; (inner pixels), into OUT of LENGTH entries. +(fn landform-weights/at ((w (* const landform-weights)) (x float) (z float) (out (* float)) + (length int)) void + (for (var i int 0) (< i length) (++ i) + (= [out i] 0)) + (var pad int (. w pad)) + (var half float 0.5) + (var xl int (+ (cast (floor (cast (- x half) double)) int) pad)) + (var zl int (+ (cast (floor (cast (- z half) double)) int) pad)) + (var fx float (- x (+ (cast (- xl pad) float) half))) + (var fz float (- z (+ (cast (- zl pad) float) half))) + (var n int (. w size)) + (half-bilerp w (+ (* zl n) xl) (+ (* zl n) xl 1) fx out (- (cast 1 float) fz)) + (half-bilerp w (+ (* (+ zl 1) n) xl) (+ (* (+ zl 1) n) xl 1) fx out fz)) + +;;; The terrain generator ------------------------------------------------ + +(pub record terra + ((g (* worldgen)) (config river-config) (sampler river-sampler) + (size-y int) (sea-level int) (octaves int) (noise-scale float) + (noise terrain-noise) (distort-x (* simplex-sum)) (distort-z (* simplex-sum)) + (geo-upheaval (* simplex-noise)) (valley fast-noise) (river landform) (river-index int) + (landform-count int) (y-thresholds [* float 129]) + ;; the region last asked for + (rx int) (rz int) (has-region bool) (landform-map int-map) (ocean-map int-map) + (upheaval-map int-map) (weights landform-weights) + ;; the river plates last asked for + (plates [* river-plate 4]) (plate-used [u64 4]) (plate-clock u64) (segments (* int)) + (segment-cap int))) + +(var gradients-ready bool false) + +(fn scaled ((v double) (scale float)) double + (return (/ v scale))) + +;;; Rivers' river landform: almost flat, a few blocks above sea level, +;;; with the sixth octave only. +(fn river-landform ((size-y int) (octaves int)) landform + (var l landform) + (memset (& l) 0 (sizeof l)) + (snprintf (. l code) 64 "riverlandform") + (= (. l octave-count) 9) + (= [(. l octaves) 5] 1) + (= (. l octave-threshold-count) 9) + (var modifier float (/ (cast 256 float) (cast size-y float))) + (var sea float (cast 0.4313725490196078 float)) + (var block float (* (/ sea (cast 110 float)) modifier)) + (= (. l y-key-count) 4) + (= [(. l y-keys) 0] sea) + (= [(. l y-keys) 1] (+ sea (* block (cast 4 float)))) + (= [(. l y-keys) 2] (+ sea (* block (cast 9 float)))) + (= [(. l y-keys) 3] (+ sea (* block (cast 15 float)))) + (= (. l y-key-threshold-count) 4) + (= [(. l y-key-thresholds) 0] 1) + (= [(. l y-key-thresholds) 1] (cast 0.5 float)) + (= [(. l y-key-thresholds) 2] (cast 0.25 float)) + (= [(. l y-key-thresholds) 3] 0) + (landform/init-terrain (& l) octaves size-y) + (return l)) + +(pub fn terra/make ((g (* worldgen)) (config river-config)) (* terra) + (if (! gradients-ready) + (do (init-gradients) (= gradients-ready true))) + (var t (* terra) (calloc 1 (sizeof terra))) + (var s (* world-settings) (& (. g settings))) + (= (. t g) g) + (= (. t config) config) + (= (. t size-y) (. s size-y)) + (= (. t sampler) (river-sampler/make (& config) (. s size-y))) + (= (. t sea-level) (cast (* 0.4313725490196078 (. s size-y)) int)) + (= (. t octaves) (terrain-octave-count (. s size-y))) + (var scale float (/ (cast (. s size-y) float) (cast 256 float))) + (if (< scale (cast 1 float)) (= scale 1)) + (= (. t noise-scale) scale) + (var seed i64 (. s seed)) + + (var base double (/ (* 0.0005 0.6123724356957945) scale)) + (= (. t noise count) (. t octaves)) + (for (var i int 0) (< i (. t octaves)) (++ i) + (= [(. t noise frequencies) i] (* (pow 2 i) base)) + (= [(. t noise seeds) i] (cast (+ (* (cast seed u64) 65599) (cast i u64)) i64))) + + (var damps [double 4] #(55 40 30 10)) + (var dfreqs [double 4]) + (= [dfreqs 0] (scaled (/ 1 5.0) scale)) + (= [dfreqs 1] (scaled (/ 1 2.50) scale)) + (= [dfreqs 2] (scaled (/ 1 1.250) scale)) + (= [dfreqs 3] (scaled (/ 1 0.65) scale)) + (= (. t distort-x) (simplex-sum/make damps dfreqs 4 (+ (. s seed) 9876 0))) + (= (. t distort-z) (simplex-sum/make damps dfreqs 4 (+ (. s seed) 9876 2))) + + (var gamps [double 6] #(55 40 30 15 7 4)) + (var gfreqs [double 6]) + (= [gfreqs 0] (scaled (/ 1.0 5.5) scale)) + (= [gfreqs 1] (scaled (/ 1.1 2.75) scale)) + (= [gfreqs 2] (scaled (/ 1.2 1.375) scale)) + (= [gfreqs 3] (scaled (/ 1.2 0.715) scale)) + (= [gfreqs 4] (scaled (/ 1.2 0.45) scale)) + (= [gfreqs 5] (scaled (/ 1.2 0.25) scale)) + (= (. t geo-upheaval) (simplex-noise/make gamps gfreqs 6 (+ (. s seed) 9876 1))) + + (= (. t valley) (fast-noise/make 0 (cast 0.0008 float) 2 (cast 0.5 float) 2)) + (= (. t river) (river-landform (. s size-y) (. t octaves))) + (= (. t landform-count) (. g landform-table count)) + (= (. t river-index) (. t landform-count)) + (for (var i int 0) (< i (. t landform-count)) (++ i) + (= [(. t y-thresholds) i] (. [(. g landform-table all) i] y-thresholds))) + (= [(. t y-thresholds) (. t river-index)] (. t river y-thresholds)) + (return t)) + +(fn release-region ((t (* terra))) void + (if (! (. t has-region)) + (return)) + (free (. t landform-map data)) + (free (. t ocean-map data)) + (free (. t upheaval-map data)) + (landform-weights/release (& (. t weights))) + (= (. t has-region) false)) + +(pub fn terra/free ((t (* terra))) void + (release-region t) + (for (var i int 0) (< i 4) (++ i) + (if [(. t plates) i] (river-plate/free [(. t plates) i]))) + (free (. t segments)) + (free (. t river y-thresholds)) + (free (. t distort-x)) + (free (. t distort-z)) + (free (. t geo-upheaval)) + (free t)) + +(fn use-region ((t (* terra)) (rx int) (rz int)) void + (if (&& (. t has-region) (== (. t rx) rx) (== (. t rz) rz)) + (return)) + (release-region t) + (worldgen/map (. t g) MAP-LANDFORM 0 rx rz (& (. t landform-map))) + (worldgen/map (. t g) MAP-OCEAN 0 rx rz (& (. t ocean-map))) + (worldgen/map (. t g) MAP-UPHEAVAL 0 rx rz (& (. t upheaval-map))) + (= (. t weights) (landform-weights/make (& (. t landform-map)))) + (= (. t rx) rx) + (= (. t rz) rz) + (= (. t has-region) true)) + +(fn use-plate ((t (* terra)) (px int) (pz int)) (* river-plate) + (++ (. t plate-clock)) + (var oldest int 0) + (for (var i int 0) (< i 4) (++ i) + (var p (* river-plate) [(. t plates) i]) + (if (&& p (== (. p px) px) (== (. p pz) pz)) + (do (= [(. t plate-used) i] (. t plate-clock)) (return p))) + (if (< [(. t plate-used) i] [(. t plate-used) oldest]) + (= oldest i))) + (if [(. t plates) oldest] + (river-plate/free [(. t plates) oldest])) + (var p (* river-plate) (river-plate/make (. t config) (& (. t g oceans)) (. t size-y) px pz)) + (= [(. t plates) oldest] p) + (= [(. t plate-used) oldest] (. t plate-clock)) + (if (> (+ (. p segment-count) 1) (. t segment-cap)) + (do + (= (. t segment-cap) (+ (. p segment-count) 1)) + (= (. t segments) (realloc (. t segments) (* (. t segment-cap) (sizeof int)))))) + (return p)) + +;;; IntMapExt.GetValues: a region map's four pixels around chunk +;;; (cx, cz), as UL UR BL BR. +(fn chunk-corners ((m (* const int-map)) (cx int) (cz int) (out (* int))) void + (var lx int (% cx 16)) + (var lz int (% cz 16)) + (var inner int (- (. m size) (. m pad-tl) (. m pad-br))) + (var factor float (/ (cast inner float) (cast 16 float))) + (var x0 int (cast (* lx factor) int)) + (var z0 int (cast (* lz factor) int)) + (var x1 int (cast (+ (* lx factor) factor) int)) + (var z1 int (cast (+ (* lz factor) factor) int)) + (var p int (. m pad-tl)) + (= [out 0] [(. m data) (+ (* (+ z0 p) (. m size)) x0 p)]) + (= [out 1] [(. m data) (+ (* (+ z0 p) (. m size)) x1 p)]) + (= [out 2] [(. m data) (+ (* (+ z1 p) (. m size)) x0 p)]) + (= [out 3] [(. m data) (+ (* (+ z1 p) (. m size)) x1 p)])) + +;;; IntMapData.LerpForChunk. +(fn lerp-for-chunk ((c (* const int)) (lx int) (lz int)) float + (var delta float (/ (cast 1 float) (cast 32 float))) + (var x float (* (cast lx float) delta)) + (var z float (* (cast lz float) delta)) + (var top float (+ (cast [c 0] float) (* (- (cast [c 1] float) (cast [c 0] float)) x))) + (var bot float (+ (cast [c 2] float) (* (- (cast [c 3] float) (cast [c 2] float)) x))) + (return (+ top (* (- bot top) z)))) + +(fn interpolated-octaves ((t (* const terra)) (weights (* const float)) (amps (* double)) + (thresholds (* double))) void + (for (var o int 0) (< o (. t octaves)) (++ o) + (var a double 0) + (var th double 0) + (for (var i int 0) (< i (. t landform-count)) (++ i) + (var w float [weights i]) + (if (== w 0) + (continue)) + (var l (* const landform) (& [(. (. t g) landform-table all) i])) + (+= a (* [(. l octaves) o] w)) + (+= th (* [(. l octave-thresholds) o] w))) + (= [amps o] a) + (= [thresholds o] th))) + +(fn bilerp ((a double) (b double) (c double) (d double) (x double) (z double)) double + (var top double (+ a (* (- b a) x))) + (var bot double (+ c (* (- d c) x))) + (return (+ top (* (- bot top) z)))) + +(fn isotropic ((dx double) (dz double) (threshold double) (maximum double) (out (* double))) void + (var mag2 double (+ (* dx dx) (* dz dz))) + (var th2 double (* threshold threshold)) + (if (<= mag2 th2) + (do (= [out 0] 0) (= [out 1] 0) (return))) + (var base double (/ (- mag2 th2) mag2)) + (var max2 double (* maximum maximum)) + (var slide double (* base (/ max2 (- max2 th2)))) + (*= slide slide) + (var force double (* slide (/ (- maximum threshold) maximum))) + (= [out 0] (* dx force)) + (= [out 1] (* dz force))) + +;;; Heights of the columns of chunk (cx, cz) whose local x and z are +;;; multiples of STEP, into HEIGHTS[lz * 32 + lx]; the rest are left +;;; alone. A height is the top solid block, 0 if there is none. +(pub fn terra/chunk-heights ((t (* terra)) (cx int) (cz int) (step int) (heights (* u16))) void + (use-region t (/ cx 16) (/ cz 16)) + (var per-plate int (river-plate/chunks (& (. t config)))) + (var plate (* river-plate) (use-plate t (/ cx per-plate) (/ cz per-plate))) + (var seg-count int (river-plate/chunk-segments plate cx cz (. t segments))) + + (var ocean [int 4]) + (var upheaval [int 4]) + (chunk-corners (& (. t ocean-map)) cx cz ocean) + (chunk-corners (& (. t upheaval-map)) cx cz upheaval) + (var oceanicity-fac float (* (cast (/ (. t size-y) 256) float) (cast 0.33333 float))) + + (var n int (+ (. t landform-count) 1)) + (var w (* float) (calloc n (sizeof float))) + (var lf-inner int (- (. t landform-map size) (* 2 (. t landform-map pad-tl)))) + (var pixel float (cast (/ lf-inner 16) float)) + (var base-x float (* (cast (% cx 16) float) pixel)) + (var base-z float (* (cast (% cz 16) float) pixel)) + (var oct-a [double 64]) + (var oct-t [double 64]) + (for (var k int 0) (< k 4) (++ k) + (var ox float (if (& k 1) pixel 0)) + (var oz float (if (& k 2) pixel 0)) + (landform-weights/at (& (. t weights)) (+ base-x ox) (+ base-z oz) w n) + (interpolated-octaves t w (+ oct-a (* k 16)) (+ oct-t (* k 16)))) + + (var delta float (/ (cast 1 float) (cast 32 float))) + (var block-step float (* pixel delta)) + (var max-distortion double (* (+ 55 40 30 10) 1.4142135623730951)) + (var size-y int (. t size-y)) + (var top-y int (- size-y 2)) + (var taper int (cast (* (cast size-y float) (cast 0.9 float)) int)) + (var amps [double 16]) + (var ths [double 16]) + (var c (* river-config) (& (. t config))) + + (for (var lz int 0) (< lz 32) (+= lz step) + (for (var lx int 0) (< lx 32) (+= lx step) + (var wx int (+ (* cx 32) lx)) + (var wz int (+ (* cz 32) lz)) + (var sample river-sample (river-sampler/sample (& (. t sampler)) plate (. t segments) + seg-count wx wz)) + (var river-lerp float 1) + (if (< (. sample distance) (. c max-valley-width)) + (do + (var valley double (.get (& (. t valley)) wx wz)) + (= valley (* valley (. c noise-expansion))) + (if (< valley -1) (= valley -1)) + (if (> valley 1) (= valley 1)) + (+= valley 1) + (/= valley 2) + (var to-min double (- (cast 1 float) (. c valley-strength-min))) + (var to-max double (- (cast 1 float) (. c valley-strength-max))) + (= valley (+ (* (/ (- valley 0) (- 1 0)) (- to-max to-min)) to-min)) + (if (< valley 0.02) (= valley 0.02)) + (if (< valley 1) + (do + (var inv double (/ (- (. sample distance) 0) (- (. c max-valley-width) 0))) + (= river-lerp (cast (+ valley (* (- 1 valley) inv)) float)) + (= river-lerp (powf river-lerp 2)))))) + + (landform-weights/at (& (. t weights)) (+ base-x (* (cast lx float) block-step)) + (+ base-z (* (cast lz float) block-step)) w n) + (var fx double (* (cast lx float) delta)) + (var fz double (* (cast lz float) delta)) + (if (< river-lerp (cast 1 float)) + (do + (var blend float (- (cast 1 float) river-lerp)) + (for (var i int 0) (< i n) (++ i) + (*= [w i] river-lerp)) + (+= [w (. t river-index)] blend) + (for (var o int 0) (< o (. t octaves)) (++ o) + (var na double (bilerp [oct-a o] [oct-a (+ 16 o)] [oct-a (+ 32 o)] [oct-a (+ 48 o)] fx fz)) + (var nt double (bilerp [oct-t o] [oct-t (+ 16 o)] [oct-t (+ 32 o)] [oct-t (+ 48 o)] fx fz)) + (= [amps o] (+ na (* (- [(. t river octaves) o] na) blend))) + (= [ths o] (+ nt (* (- [(. t river octave-thresholds) o] nt) blend))))) + (for (var o int 0) (< o (. t octaves)) (++ o) + (= [amps o] (bilerp [oct-a o] [oct-a (+ 16 o)] [oct-a (+ 32 o)] [oct-a (+ 48 o)] fx fz)) + (= [ths o] (bilerp [oct-t o] [oct-t (+ 16 o)] [oct-t (+ 32 o)] [oct-t (+ 48 o)] fx fz)))) + + (var dist-x double) + (var dist-z double) + (fair-warp (. t distort-x) (. t distort-z) (/ wx 400.0) (/ wz 400.0) (& dist-x) (& dist-z)) + (var dt [double 2]) + (isotropic (* dist-x 4) (* dist-z 4) 40 (* 4 max-distortion) dt) + (var dg [double 2]) + (isotropic (* dist-x 10) (* dist-z 10) 10 (* 10 max-distortion) dg) + + (var upheaval-strength float (* (lerp-for-chunk upheaval lx lz) river-lerp)) + (var oceanicity float (* (lerp-for-chunk ocean lx lz) oceanicity-fac)) + (var geo float (* (cast (.noise-2d (. t geo-upheaval) (/ (+ wx [dg 0]) 400) + (/ (+ wz [dg 1]) 400)) float) + (cast 0.9 float))) + (var multiplier float (fminf 0 (- (cast 0.5 float) geo))) + (var dist-y float (+ oceanicity (* upheaval-strength multiplier))) + + (var col column-noise) + (column-noise/make (& (. t noise)) 0.25 amps ths (+ wx [dt 0]) (+ wz [dt 1]) (& col)) + (var slide float (- dist-y (cast (cast (floor dist-y) int) float))) + + (var bank-blocks int (cast (* (. sample bank) (- size-y (. t sea-level))) int)) + (var baseline int (+ (. t sea-level) (. c height-boost))) + (var carved bool (<= (. sample distance) 0)) + (var height int 0) + (for (var y int 1) (<= y top-y) (++ y) + (var yb int (cast (floor (+ (cast y float) dist-y)) int)) + (if (< yb 0) (= yb 0)) + (if (> yb top-y) (= yb top-y)) + (var threshold double 0) + (for (var i int 0) (< i n) (++ i) + (var wi float [w i]) + (if (== wi 0) + (continue)) + (var th (* float) [(. t y-thresholds) i]) + (var lerped float (+ [th yb] (* (- [th (+ yb 1)] [th yb]) slide))) + (+= threshold (* wi lerped))) + (if (&& (> y taper) (< dist-y -2)) + (do + (var up double (- dist-y)) + (if (< up (- y size-y)) (= up (- y size-y))) + (if (> up y) (= up y)) + (+= threshold (/ (* (- y taper) up) (* 40 255.0))))) + (var solid bool false) + (if (<= threshold (. col bound-min)) + (= solid true) + (! (< threshold (. col bound-max))) + (break) + (= solid (> (column-noise/sign (& col) y (- (tanh-curve-inverse threshold))) 0))) + (if (&& solid carved + (! (|| (<= y (- baseline bank-blocks)) + (>= (cast y float) (+ baseline (* bank-blocks (. c top-factor))))))) + (= solid false)) + (if solid (= height y))) + (= [heights (+ (* lz 32) lx)] (cast height u16)))) + (free w)) diff --git a/src/tiles.sex b/src/tiles.sex index 2d761b8..2699258 100644 --- a/src/tiles.sex +++ b/src/tiles.sex @@ -21,10 +21,13 @@ (import worldgen) (import fastnoise) (import rivers) +(import terra) (pub define MAX-TILES 16384) -;;; Not a worldgen map: Rivers' distance to the nearest river. +;;; Not worldgen maps: Rivers' distance to the nearest river, and the +;;; terrain height. (pub define LAYER-RIVERS 6) +(pub define LAYER-HEIGHT 7) ;;; River tiles are sampled at a resolution the viewer picks by zoom, ;;; in the key's `stratum': a column costs too much to sample them all ;;; for an overview. @@ -187,6 +190,52 @@ (= (* size) res) (return px)) +;;; Terrain height, shaded: water by depth under sea level, land by +;;; height, lit from the north-west. +(fn height-colour ((h int) (west int) (north int) (sea int) (size-y int)) u32 + (if (< h sea) + (return (lerp-colour 6400472 1186659 (/ (* (if (> (- sea h) 40) 40 (- sea h)) 255) 40)))) + (var t int (/ (* (- h sea) 255) (- size-y sea))) + (var base u32 (if (< t 32) (lerp-colour 5605944 8299066 (* t 8)) + (if (< t 96) (lerp-colour 8299066 9922899 (/ (* (- t 32) 255) 64)) + (lerp-colour 9922899 15263976 (/ (* (- t 96) 255) 159))))) + (var slope int (+ (- h west) (- h north))) + (var light int (+ 128 (* slope 24))) + (if (< light 0) (= light 0)) + (if (> light 255) (= light 255)) + (if (> light 128) + (return (lerp-colour base 16777215 (/ (* (- light 128) 160) 127)))) + (return (lerp-colour 0 base (+ 96 (/ (* light 159) 128))))) + +(fn render-heights ((tr (* terra)) (k tile-key) (size (* int))) (* u32) + (var res int (. k stratum)) + (var step int (/ 512 res)) + (var hs (* int) (malloc (* res res (sizeof int)))) + (var chunk [u16 1024]) + (var per-chunk int (/ 32 step)) + (if (< per-chunk 1) (= per-chunk 1)) + (for (var cz int 0) (< cz 16) (++ cz) + (for (var cx int 0) (< cx 16) (++ cx) + (if (|| (!= (% (* cx 32) step) 0) (!= (% (* cz 32) step) 0)) + (continue)) + (terra/chunk-heights tr (+ (* (. k rx) 16) cx) (+ (* (. k rz) 16) cz) (if (> step 32) 32 step) + chunk) + (for (var dz int 0) (< dz per-chunk) (++ dz) + (for (var dx int 0) (< dx per-chunk) (++ dx) + (= [hs (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)] + [chunk (+ (* dz step 32) (* dx step))]))))) + (var px (* u32) (malloc (* res res (sizeof u32)))) + (for (var z int 0) (< z res) (++ z) + (for (var x int 0) (< x res) (++ x) + (var h int [hs (+ (* z res) x)]) + (var west int (if (> x 0) [hs (+ (* z res) x -1)] h)) + (var north int (if (> z 0) [hs (+ (* (- z 1) res) x)] h)) + (= [px (+ (* z res) x)] + (c-bit-or 4278190080 (height-colour h west north (. tr sea-level) (. tr size-y)))))) + (free hs) + (= (* size) res) + (return px)) + ;;; Workers ------------------------------------------------------- (fn worker-main ((arg (* void))) (* void) @@ -195,6 +244,7 @@ (var g-generation int -1) (var cache river-cache) (memset (& cache) 0 (sizeof cache)) + (var tr (* terra) NULL) (pthread-mutex-lock (& (. t lock))) (while (! (. t quit)) (if (>= (. t queue-pos) (. t queue-len)) @@ -215,15 +265,20 @@ (if (!= g-generation generation) (do + (if tr (terra/free tr)) + (= tr NULL) (if g (worldgen/free g)) (release-river-cache (& cache)) (= g (worldgen/make settings (. t assets-dir))) + (if g (= tr (terra/make g rivers))) (= (. cache sampler) (river-sampler/make (& rivers) (. settings size-y))) (= g-generation generation))) (var size int 0) (var px (* u32) NULL) (if (&& g (== (. key map) LAYER-RIVERS)) (= px (render-rivers g (& cache) (& rivers) key (& size))) + (&& tr (== (. key map) LAYER-HEIGHT)) + (= px (render-heights tr key (& size))) g (= px (render g key (& size)))) @@ -238,6 +293,7 @@ (if (&& (== generation (. t generation)) (== (. tl state) TILE-WORKING)) (= (. tl state) TILE-QUEUED))))) (pthread-mutex-unlock (& (. t lock))) + (if tr (terra/free tr)) (if g (worldgen/free g)) (release-river-cache (& cache)) (return NULL)) diff --git a/src/verify.sex b/src/verify.sex index 62dd8a3..e4ae31e 100644 --- a/src/verify.sex +++ b/src/verify.sex @@ -12,6 +12,7 @@ (import worldgen) (import fastnoise) (import rivers) +(import terra) (import img) (define MAP-KINDS 6) @@ -173,3 +174,68 @@ (if plate (river-plate/free plate)) (free segments) (return (if (&& (== stored-matched stored-columns) (== unstored-wrong 0)) 0 1))) + +;;; Recomputes every stored map chunk's terrain height and compares it +;;; with WorldGenTerrainHeightMap. Mismatches are counted by how far off +;;; they are, which tells a missing step (a raise of a few blocks) from +;;; noise that is wrong. +(pub fn verify-heights ((s (* save)) (g (* worldgen)) (config river-config) (dir (* const char))) int + (var e extent (save/extent s "mapchunk")) + (var w int (* (+ (- (. e x1) (. e x0)) 1) 32)) + (var h int (* (+ (- (. e z1) (. e z0)) 1) 32)) + (var diff image (image/make w h)) + (var t (* terra) (terra/make g config)) + (var heights [u16 1024]) + (var columns i64 0) + (var matched i64 0) + (var by-delta [i64 9]) + (memset by-delta 0 (sizeof by-delta)) + ;; stored higher / lower, computed top below / at or above sea level + (var by-class [i64 4]) + (memset by-class 0 (sizeof by-class)) + (var t0 clock-t (clock)) + (var m chunk-maps) + (for (var cz int (. e z0)) (<= cz (. e z1)) (++ cz) + (for (var cx int (. e x0)) (<= cx (. e x1)) (++ cx) + (if (! (save/chunk s cx cz (& m))) + (continue)) + (terra/chunk-heights t cx cz 1 heights) + (for (var i int 0) (< i 1024) (++ i) + (var want int [(. m terrain-height) i]) + (var got int [heights i]) + (++ columns) + (var d int (- want got)) + (if (== d 0) (++ matched)) + (if (!= d 0) + (do + (var cls int 0) + (if (< d 0) (+= cls 2)) + (if (>= got (. t sea-level)) (+= cls 1)) + (++ [by-class cls]))) + ;; -4..+4, the ends counting everything beyond + (var bucket int (+ (if (< d -4) -4 (if (> d 4) 4 d)) 4)) + (++ [by-delta bucket]) + (var colour u32 (grey (/ (* got 255) (. g settings size-y)))) + (if (> d 0) (= colour 16719904)) + (if (< d 0) (= colour 2105599)) + (.set (& diff) (+ (* (- cx (. e x0)) 32) (% i 32)) (+ (* (- cz (. e z0)) 32) (/ i 32)) + colour)))) + (printf "heights %lld/%lld columns match, %.1f s\n" matched columns + (/ (cast (- (clock) t0) double) CLOCKS-PER-SEC)) + (printf " stored - computed: <=-4 %lld, -3 %lld, -2 %lld, -1 %lld, +1 %lld, +2 %lld, +3 %lld, >=+4 %lld\n" + [by-delta 0] [by-delta 1] [by-delta 2] [by-delta 3] [by-delta 5] [by-delta 6] [by-delta 7] + [by-delta 8]) + (printf " stored higher: %lld under water, %lld on land; stored lower: %lld under water, %lld on land\n" + [by-class 0] [by-class 1] [by-class 2] [by-class 3]) + (var path [char 1024]) + (snprintf path (sizeof path) "%s/diff-heights.png" dir) + (.write (& diff) path) + (.release (& diff)) + (terra/free t) + ;; Two later passes change the stored height after strata are laid: + ;; GenBlockLayers raises dry seabeds, GenCaves lowers where a cave + ;; opens the surface. Anything else is ours. + (var unexplained i64 (+ [by-class 1] [by-class 2])) + (printf " explained by the dry seabed raise and caves: all but %lld (%.3f%%)\n" + unexplained (/ (* 100.0 unexplained) columns)) + (return (if (< (* unexplained 1000) columns) 0 1))) diff --git a/src/viewer.sex b/src/viewer.sex index 0d116e8..c30c802 100644 --- a/src/viewer.sex +++ b/src/viewer.sex @@ -17,6 +17,7 @@ (import worldgen) (import fastnoise) (import rivers) +(import terra) (import settings) (import tiles) @@ -29,15 +30,16 @@ (define MIN-ZOOM 0.0625) (define MAX-ZOOM 32.0) -(var layer-names [(* const char) 7] +(var layer-names [(* const char) 8] #("Landform" "Climate" "Geologic province" "Upheaval" "Ocean" "Rock strata thickness" - "Rivers")) + "Rivers" "Terrain height")) (var climate-names [(* const char) 5] #("temperate" "hot" "warm" "cool" "icy")) ;;; What the region under the cursor holds, generated on the main ;;; thread when the cursor moves to another region. (record hover ((valid bool) (rx int) (rz int) (maps region-maps) - (plate (* river-plate)) (segments (* int)))) + (plate (* river-plate)) (segments (* int)) + (terra (* terra)) (cx int) (cz int) (has-chunk bool) (heights [u16 1024]))) (record app ((window (* SDL-Window)) (renderer (* SDL-Renderer)) (ctx (* struct nk-context)) @@ -90,7 +92,11 @@ (= (. a hover valid) false) (if (. a hover plate) (river-plate/free (. a hover plate))) - (= (. a hover plate) NULL)) + (= (. a hover plate) NULL) + (if (. a hover terra) + (terra/free (. a hover terra))) + (= (. a hover terra) NULL) + (= (. a hover has-chunk) false)) ;;; Makes SOURCE the world shown: a fresh generator for the panels, ;;; and every tile regenerated. @@ -148,6 +154,16 @@ (fn river-resolution ((zoom double)) int (return (if (<= zoom 8) 64 (if (<= zoom 16) 32 16)))) +;;; Height samples per region side: one per block close up, down to +;;; one per chunk for an overview, where a column costs ~11 us. +(fn height-resolution ((zoom double)) int + (if (< zoom 1) (return 512)) + (if (< zoom 2) (return 256)) + (if (< zoom 4) (return 128)) + (if (< zoom 8) (return 64)) + (if (< zoom 16) (return 32)) + (return 16)) + ;;; Requests the visible tiles, nearest the centre first, and draws ;;; those that are ready. (fn draw-map ((a (* app))) void @@ -178,7 +194,9 @@ (for (var i int 0) (< i n) (++ i) (var k tile-key) (= (. k map) (. a layer)) - (= (. k stratum) (if (== (. a layer) LAYER-RIVERS) (river-resolution (. a zoom)) (. a stratum))) + (= (. k stratum) (. a stratum)) + (if (== (. a layer) LAYER-RIVERS) (= (. k stratum) (river-resolution (. a zoom)))) + (if (== (. a layer) LAYER-HEIGHT) (= (. k stratum) (height-resolution (. a zoom)))) (= (. k rx) (. [list i] rx)) (= (. k rz) (. [list i] rz)) (var tex (* SDL-Texture) (.request (. a tiles) (. a renderer) k)) @@ -297,11 +315,11 @@ (var w int) (var h int) (window-size a (& w) (& h)) - (if (nk-begin ctx "Layer" (nk-rect (- w 250) 10 240 240) + (if (nk-begin ctx "Layer" (nk-rect (- w 250) 10 240 260) (| NK-WINDOW-BORDER NK-WINDOW-MOVABLE NK-WINDOW-TITLE NK-WINDOW-MINIMIZABLE)) (do (nk-layout-row-dynamic ctx 20 1) - (for (var i int 0) (< i 7) (++ i) + (for (var i int 0) (< i 8) (++ i) (if (nk-option-label ctx [layer-names i] (== (. a layer) i)) (= (. a layer) i))) (if (== (. a layer) MAP-STRATA) @@ -320,6 +338,20 @@ (var pz int (+ (. m pad-tl) (/ (* (- bz (* rz REGION)) inner) REGION))) (return [(. m data) (+ (* pz (. m size)) px)])) +;;; The terrain height at block (x, z), its chunk computed once. +(fn hover-height ((a (* app)) (x int) (z int)) int + (if (! (. a hover terra)) + (= (. a hover terra) (terra/make (. a g) (. a rivers)))) + (var cx int (/ x 32)) + (var cz int (/ z 32)) + (if (|| (! (. a hover has-chunk)) (!= (. a hover cx) cx) (!= (. a hover cz) cz)) + (do + (terra/chunk-heights (. a hover terra) cx cz 1 (. a hover heights)) + (= (. a hover cx) cx) + (= (. a hover cz) cz) + (= (. a hover has-chunk) true))) + (return [(. a hover heights) (+ (* (% z 32) 32) (% x 32))])) + ;;; Rivers' sample at block (x, z), building the plate it needs. (fn hover-river ((a (* app)) (x int) (z int)) river-sample (var per-plate int (river-plate/chunks (& (. a rivers)))) @@ -355,7 +387,7 @@ (= (. a hover valid) true) (= (. a hover rx) rx) (= (. a hover rz) rz))) - (if (nk-begin ctx "Info" (nk-rect 10 (- h 250) 290 240) + (if (nk-begin ctx "Info" (nk-rect 10 (- h 270) 290 260) (| NK-WINDOW-BORDER NK-WINDOW-MOVABLE NK-WINDOW-TITLE NK-WINDOW-MINIMIZABLE)) (do (nk-layout-row-dynamic ctx 18 1) @@ -378,7 +410,9 @@ (sample (& (. m upheaval)) rx rz bx bz)) (var r river-sample (hover-river a bx bz)) (nk-labelf ctx NK-TEXT-LEFT "river distance %.0f, bank depth %.3f" - (. r distance) (. r bank)))) + (. r distance) (. r bank)) + (nk-labelf ctx NK-TEXT-LEFT "terrain height %d (sea level %d)" + (hover-height a bx bz) (. a hover terra sea-level)))) (nk-labelf ctx NK-TEXT-LEFT "%d tiles pending" (. a pending)) (nk-label ctx (. a status) NK-TEXT-LEFT))) (nk-end ctx)) diff --git a/src/vsmv.sex b/src/vsmv.sex index edd59d0..af201d5 100644 --- a/src/vsmv.sex +++ b/src/vsmv.sex @@ -15,6 +15,7 @@ (import worldgen) (import fastnoise) (import rivers) +(import terra) (import settings) (import verify) @@ -89,7 +90,8 @@ (return 1)) (var s (* save) (save/open save-path)) (var failed int (+ (verify-stories s g) (verify-regions s g out) - (verify-rivers s g (river-config/defaults) out))) + (verify-rivers s g (river-config/defaults) out) + (verify-heights s g (river-config/defaults) out))) (save/close s) (return failed)) diff --git a/src/worldgen.sex b/src/worldgen.sex index cabf285..40c2756 100644 --- a/src/worldgen.sex +++ b/src/worldgen.sex @@ -276,12 +276,95 @@ (pub record landform ((code [char 64]) (weight double) (use-climate bool) (min-temp float) (max-temp float) (min-rain int) (max-rain int) (chance float) (first-mutation int) (mutation-count int) - (colour u32))) + (colour u32) + ;; terrain shape + (octaves [double 16]) (octave-count int) (octave-thresholds [double 16]) + (octave-threshold-count int) (y-keys [float 32]) (y-key-thresholds [float 32]) + (y-key-count int) (y-key-threshold-count int) (y-thresholds (* float)))) (fn json-number ((o (* cJSON)) (key (* const char)) (fallback double)) double (var v (* cJSON) (cJSON-GetObjectItem o key)) (return (if (cJSON-IsNumber v) (cJSON-GetNumberValue v) fallback))) +(fn json-doubles-into ((o (* cJSON)) (key (* const char)) (out (* double)) (max int)) int + (var arr (* cJSON) (cJSON-GetObjectItem o key)) + (if (! (cJSON-IsArray arr)) + (return -1)) + (var n int 0) + (for (var v (* cJSON) (. arr child)) (&& v (< n max)) (= v (. v next)) + (= [out n] (cJSON-GetNumberValue v)) + (++ n)) + (return n)) + +(fn json-floats-into ((o (* cJSON)) (key (* const char)) (out (* float)) (max int)) int + (var tmp [double 32]) + (var n int (json-doubles-into o key tmp max)) + (for (var i int 0) (< i n) (++ i) + (= [out i] (cast [tmp i] float))) + (return n)) + +;;; The terrain arrays of a landform or mutation; -1 counts mean the +;;; JSON left them out. TerrainOctaveThresholds defaults to 11 zeros. +(fn read-terrain ((o (* cJSON)) (l (* landform))) void + (= (. l octave-count) (json-doubles-into o "terrainOctaves" (. l octaves) 16)) + (= (. l octave-threshold-count) (json-doubles-into o "terrainOctaveThresholds" + (. l octave-thresholds) 16)) + (= (. l y-key-count) (json-floats-into o "terrainYKeyPositions" (. l y-keys) 32)) + (= (. l y-key-threshold-count) (json-floats-into o "terrainYKeyThresholds" + (. l y-key-thresholds) 32))) + +;;; LandformVariant.Init: octaves extended to the world height's count, +;;; and the Y thresholds lerped between the key positions, inverted. +(pub fn landform/init-terrain ((l (* landform)) (octaves int) (size-y int)) void + (var m int (- octaves (. l octave-count))) + (if (> m 0) + (do + (var last double [(. l octaves) (- (. l octave-count) 1)]) + (var ext [double 16]) + (var add-sum double 0) + (for (var i int 0) (< i m) (++ i) + (var v double (pow 0.8 (+ i 1))) + (= [ext i] (* last v)) + (+= add-sum v)) + (var prev-sum double 0) + (for (var i int 0) (< i (. l octave-count)) (++ i) + (+= prev-sum [(. l octaves) i])) + (for (var i int 0) (< i (. l octave-count)) (++ i) + (*= [(. l octaves) i] (/ (+ prev-sum add-sum) prev-sum))) + (for (var i int 0) (< i m) (++ i) + (= [(. l octaves) (+ (. l octave-count) i)] [ext i])) + (= (. l octave-count) octaves))) + (var n int (- octaves (. l octave-threshold-count))) + (if (> n 0) + (do + (var last double [(. l octave-thresholds) (- (. l octave-threshold-count) 1)]) + (for (var i int 0) (< i n) (++ i) + (= [(. l octave-thresholds) (+ (. l octave-threshold-count) i)] last)) + (= (. l octave-threshold-count) octaves))) + + (= (. l y-thresholds) (malloc (* size-y (sizeof float)))) + (var cur float 1) + (var cur-y float 0) + (var pos int -1) + (var size float (cast size-y float)) + (for (var y int 0) (< y size-y) (++ y) + (if (>= (+ pos 1) (. l y-key-threshold-count)) + (do (= [(. l y-thresholds) y] 1) (continue))) + (if (>= (cast y float) (* [(. l y-keys) (+ pos 1)] size)) + (do + (= cur [(. l y-key-thresholds) (+ pos 1)]) + (= cur-y (* [(. l y-keys) (+ pos 1)] size)) + (++ pos))) + (var next float 0) + (var next-y float size) + (if (< (+ pos 1) (. l y-key-threshold-count)) + (do + (= next [(. l y-key-thresholds) (+ pos 1)]) + (= next-y (* [(. l y-keys) (+ pos 1)] size)))) + (var range float (- next-y cur-y)) + (var distance float (/ (- (cast y float) cur-y) range)) + (= [(. l y-thresholds) y] (- (cast 1 float) (+ cur (* (- next cur) distance)))))) + (fn read-landform ((o (* cJSON)) (l (* landform))) void (memset l 0 (sizeof landform)) (var code (* cJSON) (cJSON-GetObjectItem o "code")) @@ -295,24 +378,53 @@ (= (. l max-rain) (cast (json-number o "maxRain" 255) int)) (= (. l chance) (cast (json-number o "chance" 0) float)) (= (. l colour) (hex-colour o)) + (read-terrain o l) + (if (< (. l octave-threshold-count) 0) + (do + (memset (. l octave-thresholds) 0 (sizeof (. l octave-thresholds))) + (= (. l octave-threshold-count) 11))) (= (. l first-mutation) -1)) (pub record landform-table ((all [landform MAX_LANDFORMS]) (count int) (variant-count int))) -(pub fn landform-table/load ((json (* cJSON)) (t (* landform-table))) void +(pub fn terrain-octave-count ((size-y int)) int + (return (+ 9 (/ (- size-y 256) 128)))) + +(pub fn landform-table/load ((json (* cJSON)) (t (* landform-table)) (size-y int)) void (memset t 0 (sizeof landform-table)) (var variants (* cJSON) (cJSON-GetObjectItem json "variants")) (for (var v (* cJSON) (. variants child)) v (= v (. v next)) (read-landform v (& [(. t all) (. t count)])) (++ (. t count))) (= (. t variant-count) (. t count)) + (var octaves int (terrain-octave-count size-y)) + (for (var k int 0) (< k (. t count)) (++ k) + (landform/init-terrain (& [(. t all) k]) octaves size-y)) (var i int 0) (for (var v (* cJSON) (. variants child)) v (= v (. v next)) (var mutations (* cJSON) (cJSON-GetObjectItem v "mutations")) (var parent (* landform) (& [(. t all) i])) (= (. parent first-mutation) (. t count)) (for (var m (* cJSON) (if mutations (. mutations child) NULL)) m (= m (. m next)) - (read-landform m (& [(. t all) (. t count)])) + (var mut (* landform) (& [(. t all) (. t count)])) + (read-landform m mut) + ;; Missing arrays are the parent's, as already extended; but not + ;; the octave thresholds, whose C# field has an initializer and so + ;; is never missing. + (if (< (. mut octave-count) 0) + (do + (memcpy (. mut octaves) (. parent octaves) (sizeof (. mut octaves))) + (= (. mut octave-count) (. parent octave-count)))) + (if (< (. mut y-key-count) 0) + (do + (memcpy (. mut y-keys) (. parent y-keys) (sizeof (. mut y-keys))) + (= (. mut y-key-count) (. parent y-key-count)))) + (if (< (. mut y-key-threshold-count) 0) + (do + (memcpy (. mut y-key-thresholds) (. parent y-key-thresholds) + (sizeof (. mut y-key-thresholds))) + (= (. mut y-key-threshold-count) (. parent y-key-threshold-count)))) + (landform/init-terrain mut octaves size-y) (++ (. t count)) (++ (. parent mutation-count))) (++ i))) @@ -871,7 +983,7 @@ (= (. g settings) settings) (var seed i64 (. settings seed)) (= (. g provinces) (province-layer/make (+ seed 3 5) provinces)) - (landform-table/load landforms (& (. g landform-table))) + (landform-table/load landforms (& (. g landform-table)) (. settings size-y)) (var climate climate-noise (climate-noise/make seed (& (. g settings)))) (= (. g landforms) (landform-layer/make (+ seed 4 12) (& (. g landform-table)) climate (& (. g settings)))) @@ -974,6 +1086,8 @@ (worldgen/map g MAP-STRATA i rx rz (& [(. out strata) i])))) (pub fn worldgen/free ((g (* worldgen))) void + (for (var i int 0) (< i (. g landform-table count)) (++ i) + (free (. [(. g landform-table all) i] y-thresholds))) (free (. g provinces wobble-x)) (free (. g provinces wobble-z)) (for (var i int 0) (< i (. g provinces count)) (++ i)