#+TITLE: vs-map-viewer: plan * Goal A desktop app that takes a Vintage Story 1.22.7 seed and world settings, reimplements the standard world generator plus the Rivers 5.0.3 mod, and shows: - a zoomable top-down map of the world; - a rock overlay: each column colored by its rock at the surface, at a chosen depth below the surface, or at an absolute Y. Clicking a rock in the legend highlights only that rock, which is how you find a given stratum. Decisions so far: - The generator is our own port, written in Sex (~/dev/sex). This app is a field test for the language. No .NET and no game DLLs, at runtime or in development. - When something doesn't match the save, we stop and show the diffs. Whether to bring in more tooling is decided case by case. - The GUI is Nuklear on SDL3, using its SDL_Renderer backend (Metal on macOS). Map tiles are SDL textures. - Rivers is included, using its default config. A =rivers.json= can be loaded to override it. - Ground truth is the save in this directory, =ktt9s village story-new.vcdbs=. It was made with Rivers 5.0.3 and the default Rivers config. - *Frugal by design.* We compute only what the viewer window shows. The world is 2,048,000 × 25,600 blocks with height 320 (confirmed from the save's =gamedata=), and nothing ever iterates over the whole of it. * Upstream sources Upstream is anegostudios/vsapi, vsessentialsmod and vssurvivalmod at their =master= heads. Each head is the "Updated to Version 1.22.7" commit from 2026-08-17. Since 1.22, the worldgen lives in *vsessentialsmod*. Rivers is at github.com/glutzer/Rivers-Mod, HEAD 98f75e8, which is the 5.0.3 release. All of this code is proprietary or All Rights Reserved: we may "read it and learn from it". We write our own port and never redistribute their code verbatim. | Area | Upstream | |--------------------------+-----------------------------------------------------------------------| | Seed string → int | =vsapi/Math/GameMath.cs= =DotNetStringHash= | | RNG | =vsapi= =LCGRandom= | | Noise | =vsapi= =SimplexNoise=, =NormalizedSimplexNoise=, =NewNormalizedSimplexFractalNoise=, =SimplexOctave= | | 2D containers | =vsapi= =IntDataMap2D=, =NaturalShape= | | Region maps | =vsessentialsmod/Systems/WorldGen/Standard/ChunkGen/0.GenMaps/=, =MapLayer*=, =NoiseBase=, =LerpedWeightedIndex2DMap= | | Terrain height | =Rivers/src/WorldGenSystems/NewGenTerra.cs=. This is a copy of vanilla =.../1.GenTerra/GenTerra.cs= plus the river code. | | River layout | =Rivers/src/Rivers/RiverRegion.cs=, =RiverNode.cs=, =RiverGenerator.cs= (=SampleRiver=), =Api/RiversApi.cs= (the river landform) | | River noise | =Rivers/src/Noise/FastNoise.cs=, =Noise.cs= | | Rock strata | =.../ChunkGen/2.GenRockStrata/GenRockStrata.cs= (=GenRockStrataNew=) | | Strata for one column | =vssurvivalmod/Systems/Prospecting/ProPickWorkSpace.cs= =GetRockColumn= | | Dry-climate height raise | =.../GenBlockLayers.cs:185=, patched by =Rivers/src/Patches/BlockLayersPatches.cs= | | Forced story landforms | =vssurvivalmod= =GenStoryStructures=, plus =GenMaps.ForceLandformAt= / =ForceClimateAt= | Assets come from =assets/survival/worldgen/=: =landforms.json=, =geologicprovinces.json=, =rockstrata.json=, =storystructures.json=, =blocklayers.json= and =deposits.json=. They are local and never committed. They are *not strict JSON*: keys are unquoted, and they may contain comments and trailing commas. Newtonsoft reads them leniently; cJSON does not. So the =assets= module needs a small JSON5-ish normalising pass before cJSON, or we patch cJSON to accept these files. * How the computation is structured Everything is a 2D function of the column. We never build 3D chunks. | Level | Size (blocks) | What | Cost | |-----------------+----------------+---------------------------------------------------------+-------------------------------| | River plate | 32768 × 32768 | 128×128 zone ocean flags, distance to ocean, river tree | ~410k ocean-noise samples, once per plate | | Map region | 512 × 512 | climate, ocean, upheaval, province, landform, strata thickness maps | cheap 2D noise | | Chunk (32 × 32) | 32 × 32 | the set of river segments near the chunk (exactness depends on it) | a filter over the plate's segments | | Column | 1 × 1 | river sample → valley blend → =surfaceY= → strata column | 10–50 µs, dominated by 3D noise | The frugality rule: the view asks for tiles, and a tile asks for exactly the columns it shows. Columns pull in the regions, chunk segment sets and plates they need. Each of these is cached with an LRU. Nothing is ever computed "just in case". *The one unavoidable wide dependency is the river plate.* - Rivers lays out the river network for a whole 32768-block plate at once. To know whether a river passes through the window, you need that plate's layout. - It is coarse (256-block zones) and runs once per plate. - Our port samples the ocean map 25 times per zone, about 410k samples per plate, where the original does about 11M. That should come in well under a second. - The world is 62.5 × 0.78 plates, so a window touches 1–2 plates. - The plate is computed lazily, in the background, and the map shows terrain without rivers until it is ready. Plates are independent of each other and deterministic. * Facts that shape the port ** Vanilla - *A rock column needs only 2D data.* It depends on the region maps, the seed and =surfaceY=. =ProPickWorkSpace.GetRockColumn= does exactly this in the game. - *Strata see the height before the dry-climate raise.* Strata run at order 0.1, and =GenBlockLayers= (0.4) can later raise the stored =WorldGenTerrainHeightMap= in dry climates below sea level. For validation we compare against the raised value. Strata use the unraised one. - *The seed hash is verified.* =DotNetStringHash("письки+жопки")= is -90319180, which matches the seed stored in the save. - *Story structures force landform and climate near spawn.* The save's =gamedata= stores =storystructurelocations=, which gives us ground truth for the placement code. - *Rock strata noise uses its own seeds.* The distortion noises are seeded from =SeaLevel+9876/9877=, not from the world seed. - *Order matters* in two places: - =rockstrata.json= list order changes the result; - =NoiseClimateRealistic= draws its ZOffset from an unpositioned LCG. ** Rivers - *Layout RNG.* It is =LCGRandom(0)=, positioned at the plate coordinates. The world only enters through the ocean map: the blurred =MapLayerOceans= at seed+1873, with =landcover= and =oceanscale= applied. - *The ocean map ignores forced land.* Rivers samples it with =requireLandAt= (forced land at spawn and story locations) emptied. Our ocean layer needs a "no forced land" mode. - *Zone ocean test.* A zone is ocean if, at its centre chunk, the blurred ocean value × =oceanicityFactor= > =oceanThreshold= (30). The blur is a separable 5-tap integer box blur, truncating after each pass. The =oceanicityFactor= is =MapSizeY/256*0.33333f=, with integer division. - *Distance to ocean.* Upstream computes it with a BFS that is equivalent to the exact Euclidean distance between zone centres. We use a distance transform: same result, without the O(n²) cost. - *RNG call order is the contract.* We have to replicate it exactly: - zone scan, x outer and z inner; - =FindHighestZone=, a stable sort; - the FIFO generation queue; - per-river =NextInt=, =NextDouble= and =NextFloat= calls in upstream order. This includes =AddLake= rolling =NextInt= before its bounds check. - *River sample per column.* It is computed in plate-local coordinates and distorted by FastNoise (seeds 0 and 2). It yields =riverDistance= and =bankFactor=. - The candidate segments are the chunk's segment set, not the plate's. The distortion can reach segments outside a segment's envelope, so using the plate's set would give different results. - *Valley blend.* Applies when =riverDistance < maxValleyWidth= (150). A river landform is appended as the last landform index. Landform weights, octave amplitudes, thresholds and upheaval are lerped toward it, using valley noise (seed 0, freq 0.0008). - *Carving.* Applies when =riverDistance <= 0=. It removes blocks between =baseline - bank= and =baseline + bank*topFactor=. =surfaceY= is the highest solid block that remains, which can be a tunnel ceiling. - *What Rivers leaves alone.* Region maps and strata are not patched; strata change only through =surfaceY=. - Gravel beaches are cosmetic and only matter top-down: gravel on top, with the strata underneath. That's a later, optional layer. - We skip boulders. - *FastNoise subset.* We need OpenSimplex2 2D with FBm only, in its double-coordinate build. Perlin, Value, Cellular, Ridged and the other variants are dead code here. - *Config is not in the save.* It is read from =ModConfig/rivers.json=, which here means the defaults (=RiverConfig.cs=). - *Not reproducible in the original either:* an on-disk zone cache that ignores config changes, and live =/riversettings= edits. Neither applies to this world. - *Ground truth for rivers is in the save.* =mapchunk= moddata ="riverDistance"= is a =ushort[1024]=, stored wherever some column has a distance ≤ 300. We can validate the layout and the per-column sample before touching terrain. * Determinism rules for the port C# semantics that a naive C port gets wrong. Encode them once, in a =cs-compat= module, and use only that module: - *Integer overflow wraps* in C# (unchecked). This covers the LCG (=x*6364136223846793005+1442695040888963407= on =long=) and the int hashes. In C, do the arithmetic in unsigned types, and also build with =-fwrapv=. - *No FMA contraction.* Clang on arm64 fuses =a*b+c= by default; .NET does not. Build with =-ffp-contract=off= and never with =-ffast-math=. - *Keep float and double exactly as upstream has them.* Both the vanilla noise layers and Rivers (=riverSize=, =GetProjection=, =MathF.Pow=) mix the two. - *Truncating =/= and =%= on negatives* match between C99 and C#. Use explicit floor helpers where upstream calls =Math.Floor= or =FastFloor=. - *Casting an out-of-range float to =(int)=* is undefined behaviour in C. Clamp it, or mirror the .NET x64 result (=INT_MIN=). - *Statics.* Upstream keeps mutable static state (=NoiseLandforms=, =NoiseGeoProvince=). We keep it in an explicit worldgen context struct instead, so changing settings regenerates cleanly. =Math.Pow=, =Sin=, =Cos= and =Atan2= may differ from macOS libm by an ulp. Accept that until validation says otherwise. In Rivers it could theoretically flip a node acceptance test. * Architecture #+begin_example settings (serverconfig.json / .vcdbs gamedata / UI) ──┐ assets/survival/worldgen/*.json (lenient JSON → cJSON) ┤ rivers.json (optional, else defaults) ─────────────────┤ ▼ worldgen context (seed, sizes, parsed assets, river config) │ plate cache (LRU) ── region cache (LRU) ── chunk segment-set cache (LRU) │ column query: river sample → valley blend → surfaceY → strata → rock at surface/depth/Y │ tile workers (pthreads): tiles in the view only, centre first, cancelled when the view moves │ Nuklear/SDL_Renderer UI: map, layers, settings, legend, probe #+end_example Modules. Each is a Sex module; the =vsmv= CLI and the GUI share them. - =cs-compat=: wrapping int math, LCG, =DotNetStringHash=, floor and lerp helpers, and the =GameMath= subset. - =noise=: vanilla simplex family and =NaturalShape=. - =fastnoise=: OpenSimplex2 2D with FBm. - =maplayers=: =IntDataMap2D=, =NoiseBase=, =MapLayer*= (including the ocean layer's no-forced-land mode), =LerpedWeightedIndex2DMap=, =GenMaps= region generation and story-structure forcing. - =rivers=: plate generation (zones, distance to ocean, river tree), chunk segment sets, =SampleRiver=, and the river landform. - =terra=: per-column =surfaceY= with the valley blend and carving, plus the dry-climate raise for validation. - =strata=: =genBlockColumn=, plus queries for "rock at depth d" and "rock at Y". - =assets=: lenient JSON loading and asset structs, plus a rock color palette. Hardcode the palette at first; take block texture averages later. - =save=: reads the .vcdbs through SQLite3, with a minimal protobuf wire reader. =gamedata= turned out to be plain protobuf. - =tiles=: tile pyramid, LRU caches, worker pool, cancellation. - =ui=: Nuklear + SDL3 SDL_Renderer. Tiles are SDL textures under the Nuklear panels. Coordinates are shown like the in-game HUD, relative to the map centre =((MapSizeX+32)/2, (MapSizeZ+32)/2)=, with absolute coordinates available too. The viewer opens at spawn. * Phases Each phase ends with a check against the save. A mismatch means stop, produce diff images and numbers, and decide together. ** 0. Skeleton - Repo layout, Makefile (=sexc ... -- -ffp-contract=off -fwrapv=), and a =.gitignore= for =*.vcdbs*=, =*.zip= and =assets/=. - Vendor =nuklear.h=. Take SDL3 from brew and sqlite3 from the system; cJSON is already here. - Create =Sex-field-notes.org=: a running log of language bugs and friction found while building this. ** 1. Save reader + seed + assets (done) =vsmv info=, =vsmv seed=, =vsmv assets= and =vsmv dump= exist. The dump renders the save's stored maps as mosaics over the explored area, one per map. That turned out more useful than single-region dumps. What the save turned out to be: - *Encoding.* Every blob is plain protobuf, with no compression. Rows are keyed by =x | z << 27=, in region units for =mapregion= and in chunk units for =mapchunk=. - *=gamedata=:* | Field | Contents | |-------+----------| | 1, 2, 3 | MapSizeX/Y/Z: 2048000 × 320 × 25600 | | 7 | seed | | 11 | mod data: key/value entries, including =BlockIDs= and =storystructurelocations= | | 31 | world config, as a binary TreeAttribute (type byte, .NET string key, value) | - *=mapregion=* (=ServerMapRegion=). Every map is an =IntDataMap2D= with fields =1 data (packed), 2 size, 3 pad-tl, 4 pad-br=. | Field | Map | Size (pad) | |-------+-----+------------| | 1 | landform | 40 (4) | | 3 | climate | 20 (2) | | 4 | geologic province | 14 (3) | | 12 | rock strata, one per stratum, in =rockstrata.json= order | 36 (2) | | 17 | upheaval | 22 (3) | | 18 | ocean | 26 (5) | The landform map is stored at =landformMapScale= 16 regardless of =landformScale=, which only scales the noise inside =MapLayerLandforms=. Not used: forest, shrub, flower and beach (2, 5, 6, 15), ore maps (8), mod data (9), ore distortion (13, 14), block patch maps (16), animal spawn maps (21). - *=mapchunk=* (=ServerMapChunk=). All ushort arrays are repeated, not packed. | Field | Contents | |-------+----------| | 1 | mod data; Rivers' ="riverDistance"= is a serialized =ushort[1024]= | | 3 | rain height | | 7 | =WorldGenTerrainHeightMap= | | 13 | =TopRockIdMap= (block ids) | - *Assets.* The six worldgen JSONs (and all 910 asset JSONs) parse after a relaxing pass: comments, unquoted keys and trailing commas. There are 48 landforms, 6 provinces and 16 strata. - *Seed.* A numeric seed is assumed to be used as is. That is unverified, since the parse is in the closed engine. ** 2. Region maps (done) =vsmv verify SAVE ASSETS OUT= generates every region the save stored and diffs each map, padding included. It also writes a diff image per map. All of them match exactly: | Map | Pixels matched | |-----+----------------| | province | 23,128 / 23,128 | | landform | 188,800 / 188,800 | | ocean | 79,768 / 79,768 | | upheaval | 57,112 / 57,112 | | climate | 47,200 / 47,200 | | strata (16 per region) | 2,446,848 / 2,446,848 | All six story locations land where the save has them. Generating the 118 regions takes about 0.26 s. Ported, in =src/=: - =lcg= (the game's RNG); - =noise= (SimplexNoiseOctave 2D/3D, NormalizedSimplexNoise, SimplexNoise); - =shape= (NaturalShape); - =worldgen= (the layers, GenMaps' forcing and story placement). Quirks that had to be reproduced, beyond those listed under [[*Determinism rules for the port]]: - *=LCGRandom.SetWorldSeed=* sets =currentSeed= from the /previous/ mapGenSeed. Story placement re-seeds one RNG per structure, so each structure's first draw depends on the previous structure's seed. - *Unpositioned RNG.* An RNG that is never positioned always starts at =currentSeed = 1442695040888963407=. NoiseClimateRealistic draws its ZOffset from it. - *NaturalShape* picks cells with =Dictionary.ElementAt(n)=. Enumeration follows .NET's slot order, where removed slots are reused last-in-first-out, and =shape.sex= keeps those slots. - *GenMaps.ForceClimate* is passed the landform map's padding (4) instead of the climate map's (2), and it matters. - *MapLayerLandforms* samples climate at =finalX / 32= in integer division, so its climate lerp is always at a cell corner. - *Float vs double.* C# =float= expressions are kept in =float=. That includes =1 / scale=-style frequencies, but not =0.5 / scale=, which is double. - *Evaluation order.* =a() + b() + c()= is evaluated left to right in C# and in unspecified order in C. Draws are sequenced through variables (NatFloat's Gauss sum). Not ported yet: the =patchy= world climate (=worldClimate= other than =realistic=), and the forest, shrub, flower and beach maps, which nothing here uses. ** 3. Minimal viewer (done) =vs-map-viewer [--assets DIR] [--zoom Z] [--layer N] [--screenshot F] [WORLD]=, where WORLD is a =.vcdbs= or a =serverconfig.json=. - *Map.* Pan by dragging, zoom with the wheel around the cursor, from 1/16 to 32 blocks per point. At 32, the window shows the full 25,600-block length of the test world. - *Layers.* Landform, climate, province, upheaval, ocean, and rock strata thickness with a stratum picker. Spawn and the story locations are marked. - *World panel.* Every setting worldgen reads, with Apply, and Load for a save or a server config. - *Info panel.* Block and region under the cursor, with landform, province, climate, ocean and upheaval there. - *Tiles* (=tiles.sex=). A tile is one region of one map. They are generated by =cores - 1= worker threads, each with its own worldgen. The queue is rebuilt every frame from the visible tiles, nearest the centre first. Up to 16,384 tiles are cached and evicted least recently drawn first. - *Idle.* With nothing pending, the loop sleeps on events (about 2% CPU). - *Speed.* A full window at maximum zoom-out renders in 1.1 s for landforms and under 0.5 s for the other layers. - *Screenshots.* =--screenshot= saves the window once no tile is pending, and quits. That is how the viewer gets checked without looking at it. Deferred: the river config section moves to phase 4, where there is something to configure. ** 4. Rivers layout (done) =src/rivers.sex= and =src/fastnoise.sex= port Rivers 5.0.3's layout and its per-column sampler. =vsmv verify= now also recomputes =riverDistance= for every stored map chunk: - *6,558,720 / 6,558,720* columns match where Rivers stored the moddata. - *5,009 / 5,009* chunks without it rightly have no river within 300 blocks. How the port works: - *Ocean test.* The ocean test per zone is one blurred ocean pixel at the zone centre's chunk: 25 raw samples instead of the mod's whole region map per zone. =ocean-layer.blurred-at= computes it. - *Ocean distance.* An expanding-ring search returns exactly what the mod's pruned BFS finds, the Euclidean distance to the nearest ocean zone. - *Generation.* A FIFO queue and an LCG with the mod's call order. =FindHighestZone='s stable sort is kept, ties to the first neighbour in x-then-z order. - *NaN directions.* .NET 10 converts NaN to int 0, saturating, and =saturating-int= mirrors it. A NaN direction arises when the uphill target is the start zone. - *Speed.* A plate takes about 0.08 s. - *Chunk lookups.* Segment lookups per chunk go through a 64 x 64 grid over the plate. Viewer: - *Rivers layer.* Water, valley distance and Rivers' ocean zones. The sample density follows the zoom: 64, 32 or 16 samples per region side. - *Plate cache.* Each worker keeps its last four plates. With one, workers rebuilt plates constantly and the overview took 19 s; with four, 0.7 s. - *Hover info.* River distance and bank depth. - *World panel.* A rivers config path; empty means the mod's defaults. ** 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=: - province weights (lerped, radius 2) → per-group thickness budget; - distortion noises; - BottomUp/TopDown fill and the sedimentary thinning. - Queries: rock at the surface, at depth /d/, at absolute Y, and the full column. - Validation: surface rock against =TopRockIdMap= (if stored). Decode =chunk= blobs for full columns only if that isn't enough. - Viewer: - rock overlay with a mode switch (surface / depth / Y) and a slider; - legend with per-rock highlight; - click probe that shows the strata stack (rock, Y range, thickness). ** 7. Performance + polish - Level of detail: - zoomed out: one column per N blocks; - zoomed in: refined down to one per block. - Rough budget: a 1920×1080 view at 1 block/px is about 2M columns. That is about 60 s on one core, or under 10 s on all cores, rendered progressively. - Optional disk cache of tiles and plates, keyed by a hash of the settings. - Go-to-coordinates, PNG export of the current view. - Later: gravel-beach layer; ore deposits (=GenDeposits.GeneratePartial= is already on the =ProPickWorkSpace= path). * Risks - *Bit-exactness* of the noise and the Rivers trigonometry. The mitigations are the cs-compat rules and validating each phase before the next. - *Undocumented blob layouts or compression* in the vcdbs. - *Mismatch between the Rivers source and the 5.0.3 build.* The source HEAD and the DLL share a date, but we haven't verified the build. If the river diff says so, we can compare symbols against =rivers_5.0.3.zip=. - *Sex gaps*: threads, function pointers, unions, varargs interop. Log them in the field notes, and use small C shims when they block. - *Version drift.* Pin to VS 1.22.7 and Rivers 5.0.3.