#+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= | | Ore maps | =.../ChunkGen/5.GenDeposits/GenDeposits.cs= (=initWorldGen=, =getOrCreateMapLayer=), =DepositVariant.cs=, =GenMaps.GetOreMap=, =NoiseOre=, =MapLayerOre=, =MapLayerPerlinWobble= | | Prospecting readings | =vssurvivalmod/Systems/Prospecting/ItemProspectingPick.cs= (=GenProbeResults=), =ProPickWorkSpace.cs=, =DiscGenerator.cs= (=GetPropickReading=, =GetAbsAvgQuantity=), each disc generator's =GetYMinMax=, =PropickReading.cs= | 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". - =ores=: ore maps and the prospecting pick's density reading. - =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=. | 8 | ore maps: entries {1: mineral code, 2: map}, 33 (0 top-left, 1 bottom-right) | Not used: forest, shrub, flower and beach (2, 5, 6, 15), 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) | - *=chunk=*: one 32 x 32 x 32 chunk per row, keyed by =x | z << 27 | y << 54= in chunks. All of this save's chunks are from 1.22.7 (field 12). | Field | Contents | |-------+----------| | 1 | solid blocks, see below | | 8 | block entities | | 9 | mod data, e.g. ="flowVectors"= | | 12 | game version that generated it | The block layer is an int32 n, then the palette of block ids: raw in -n bytes if n is negative, zstd-compressed in n bytes if not. Then one zstd frame of bit planes, 4096 bytes each, plane k holding bit k of every block's palette index, block =(y * 32 + z) * 32 + x= at bit i % 8 of byte i / 8. A layer that is just n = 0 holds no blocks: all air. 53,855 of the 114,140 chunks are like that. Water is not in this layer; fields 2 and 3 are the likely fluid and light layers, not read yet. - *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:* 126,543. 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 (done) =src/strata.sex= ports =GenRockStrataNew.genBlockColumn=: - *Budget.* Rock-group thickness budgets come from the geologic provinces, blended by =LerpedWeightedIndex2DMap= with radius 2. - *Distortion.* A thickness distortion seeded from the sea level. - *Fill.* Strata are laid in =rockstrata.json= order, from the bottom or the top, against their thickness maps. Sedimentary strata thin above sea level; granite only consumes budget. - *Missing groups.* A province that leaves out a group has a maximum of 0 for it, not the class default of 99. Validation: - *Surface rock.* =vsmv verify= compares our rock at the top solid block with the save's =TopRockIdMap=. That block is =min(stored, computed)= height, since caves lower the stored top. - *Result.* 11,675,804 / 11,675,818 columns match, 99.9999%. The 14 others likely carry structures placed later. A further 12,118 columns have no rock on top. - *Deeper layers.* Checked against the chunk blocks since; see "Chunk blocks". Viewer: - *Rock layer.* Modes: surface, depth below the surface, or absolute Y (water or air above the surface). - *Legend.* Click a rock to grey out all others. That's the "find a stratum" view: chalk at 20 blocks down across the whole world length takes one click. - *Palette tiles.* Rock tiles keep per-sample rock indices and are coloured on upload, so changing the highlight re-uploads drawn tiles without recomputing them. - *Probe.* A click (without dragging) opens a Probe window with the column's strata, top down, with Y ranges and thicknesses. - *Hover info.* Shows the surface rock. - *Command line.* =--rock-depth=, =--rock-y=, =--highlight= and =--probe= set it all up for screenshots. - *Tile keys.* Now injective bit fields. The old =map * 64 + stratum= packing could alias once resolutions passed 64. ** Interface pass (after phase 6) - *Multi-select.* The legend highlights any number of rocks; Show all clears it. - *Coverage.* Each legend entry shows its share of the visible map, counted from the drawn rock tiles' values. - *Find nearest* (=src/search.sex=). - Order: regions nearest the view centre first. - Sampling: every 16 blocks, on cores - 1 threads, each with its own generator. - Stopping: once the next region can't hold anything nearer. - Refinement: block by block in the 3 x 3 chunks around the hit. - Range: 24 regions, about 12,000 blocks. - Result: the view jumps there, and the column is pinned and probed. - Caveat: a patch smaller than the 16-block sampling can be missed. - *Pins.* Every probe drops a numbered pin; clicking a pin probes it again. The Probe window has Go to and Clear pins. - *Info panel.* Wider, one fact per line. - *Font.* A system monospace font with Cyrillic: Menlo, or DejaVu Sans Mono on Linux. Nuklear's built-in font is ASCII only, so a Cyrillic seed read from =serverconfig.json= showed as =??????=. - *Layout.* Panels are sized from the window at start; Probe sits left of the Layer panel. - *Command line.* =--find= and repeated =--highlight= for screenshot tests. ** Layers and Rocks window - *Base.* One base layer, opaque: Ocean, Rivers, or Terrain height (the default). - *Overlays.* Any number, drawn over the base with one opacity slider (default 50%): Landform, Climate, Geologic province, Upheaval, Rock strata thickness (with its stratum picker), Rock. - *Draw and queue order.* Layer by layer, base first; each layer's tiles nearest the centre first. - *Rocks window.* Always shown: mode, depth or Y, the legend with highlights, Find nearest. Coverage percentages appear while the Rock overlay is on. - *Rock overlay transparency.* Water, air, and every rock not highlighted are transparent, so the base shows through. - *Ticks.* Checkboxes and options get an accent; Nuklear's default draws a ticked box darker, as if empty. - *Tile cache.* Holds 65,536 tiles, since every region now has several. - *Command line.* =--base=, =--overlay= (repeatable) and =--opacity= replace =--layer=. ** Side panels - *Layout.* Two opaque panels, pinned to the window's edges every frame: - left, 310 points: World, Info and Probe; - right, 300 points: Layers and Rocks. Each section is a collapsible Nuklear tree tab. - *Map viewport.* The map is the rectangle between the panels. All world/window conversions, drawing (clipped), zoom-at-cursor, the visible tile range and the coverage counts use it, so the panels hide nothing and coverage counts only what is on screen. - *Default window.* 1600 x 960. - *Story locations checkbox.* Toggles the spawn and story markers; off by default. - *Rock under cursor checkbox.* A label beside the cursor naming the rock there in the Rocks mode (surface, depth or Y), or water, air or mantle. ** Hover worker - *The lag.* Info and the cursor label used to compute on the UI thread: a whole chunk of heights (about 11 ms) per new chunk, region maps per new region, and a river plate (80 ms) per new plate. Moving the cursor stalled frames, and the label lagged behind the cursor. - *The worker* (=src/hover.sex=). A thread with its own generators answers "what is at this block". The answer covers: - height; - the rock in the Rocks mode, and the surface rock; - landform, province, climate, ocean, upheaval; - river distance and bank depth. - *Newest only.* The viewer posts the cursor's block every frame. The worker takes the newest and drops stale requests; the viewer shows its newest answer. - *The label* moves with the cursor every frame, whatever the answer's age. While the worker owes an answer, the viewer keeps drawing. - *Single columns.* =terra/column-height= computes one column (about 11 us). Probes on the main thread use it too. - *Test flag.* =--mouse X Y= places the cursor for screenshot tests. ** Minerals: prospecting density What the prospecting pick's density mode reads, per column and mineral (=src/ores.sex=). Exact deposit placement is a later phase. - *Ore maps.* One per mineral code: =NoiseOre= cells every 16 pixels, smoothstep-lerped, then =MapLayerPerlinWobble= (5 octaves, scale 110, intensity 16.5). Region maps are 32 pixels plus one of bottom-right padding. - *Seeds.* World seed plus the code's =GetNonRandomizedHashCode=, the newer .NET hash. It rotates instead of shifting and reads the string's terminator, so it differs from =DotNetStringHash=. The sums wrap as C# ints. - *Which deposit counts.* Deposit files load in path order, and their variants in file order with children after their parent. - The map of a code takes the parameters of the first deposit that asks for it. A child's map takes its parent's scale, contrast and sub. - The reading of a code comes from the last deposit with it (the pick's =depositsByCode=). So cassiterite reads with its second, rare variant, silver with quartz's child, and peridot with olivine's child. - *Reading.* The ore map's low byte over 255, times the share of the column (y below the surface, with the default rock at y = 0) that is host rock inside the deposit's Y range. The Y range depends on the generator: - follow surface: =yPosRel= times the height; - follow sea level: =yPosRel= times the sea level; - follow surface below: the height minus =depth=. ppt is the total times =GetAbsAvgQuantity= (100 radius and thickness draws from a fresh =LCGRandom= of the world seed), over height x 1024, x 1000. Categories: over 0.025, =(int)(total x 7.5)= from very poor up to ultra high; over 0.002, miniscule. - *Not reproduced.* - The game takes the Y range from 100 draws of the shared deposit RNG, whose state depends on what ran before; we take the distribution's limits. - The pick's column already holds the ore of the deposits generated in its chunk. - Children (silver, gold, peridot) are hosted by their parent's ore, so they need the deposits themselves. Validation: - *Ore maps.* =vsmv verify= compares every mineral's map in every stored region: 3,658 maps, 3,983,562 / 3,983,562 pixels including padding. - *Readings.* The save keeps the pick readings players took (=oreMapMarkers-PLAYER= in game mod data: position, then code, TotalFactor, PartsPerThousand per mineral). Thirteen are stored. Both gaps above only lower the game's reading, so the check is that ours is never below the game's and at most 15% above it. 42 of 42 pass; the game's is 0.875 to 1.00 of ours. 38 of 42 fall in the same category, and the 4 others sit at a category edge. Viewer: - *Minerals overlay.* Tiles keep =64 + category= per sample and share the rock palette, so they cost one more palette range, not a new tile kind. - *Minerals panel.* Picks the mineral from a list: the readable ones, then silver, gold and peridot as "(ore map)". Its legend gives each category's share of the view. Find nearest takes a least category (decent by default) and runs as search mode 4. - *Ore map only.* For the three the pick can't read, the overlay, Find nearest and the cursor use the ore map's value in sevenths (=ores/map-category=). Those tiles need neither heights nor strata. The legend says it isn't a reading, and the Probe lists their ore maps on a line of their own. - *Cursor and Info.* A second label line gives the reading under the cursor while the Minerals overlay is on. - *Probe.* Lists the pick's full reading for the column, highest first, then the miniscule amounts, as the pick words it. - *Command line.* =--overlay mineral=, =--mineral CODE=, =--min-reading NAME= and =--find-mineral=. ** 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; deposits, see below. ** Chunk blocks (done) =save/chunk-blocks= decodes a stored chunk's solid blocks (format under the =chunk= table above), with zstd from the system. =vsmv verify= now compares the rock of every stored block from y = 1 up to the lower of our height and the stored one. The strata are laid against our height, since the game laid them before the dry seabed raise changed the stored height. Laying them against the stored height put a whole raised area (around z 7440-7900) one stratum off. Result: 1,375,064,177 of 1,376,283,630 stratum rock blocks match (99.9114%). The rest: - 26,042 in columns whose height differs from ours; - 1,075,584 basalt at y 18 or below: deep cave lava (y 11 and below) turns the rock around it to basalt; - 103,165 granite, the default rock, in pockets with air, =stalagsection-granite=, =sand-granite= and =cobblestone-granite=. Cave walls and underground structures write it after the strata. Some of it later turned to =ore-quartz-granite=, so it predates the deposits. - 14,662 others (0.0011%), nearly all in one area near the explored edge (x 1024100-1024700, z 7340-7630). There the layer boundaries sit a few blocks off ours: peridotite, slate and sandstone, all ordinary strata. Not explained yet. The province map cache is keyed so that regions can't collide (=regionMapSize= is 8000 here), so that isn't it. The check passes under 0.01% unexplained. Where the save has no stratum rock (247 million blocks), it tallies what is there instead: crackedrock 123 million, ore 66 million, soil 20 million, air 18 million, glacier ice 9 million, gravel, sand, saltpeter, and 373 thousand other rock (halite, marble, obsidian, travertine). That is what the deposits, caves and block layers wrote, and what the deposits phase can be checked against. ** Next: deposits (planned) Placing the deposits themselves, not just the pick's reading of them. Soil deposits come first: they sit at the surface, so they don't need the 3D rock column, and the steps up to the disc are the first half of exact ore deposits anyway. *Soil deposits.* Clay (red, blue, fire), peat, and terra preta (=soil-compost=) from =deposits/soil/*.json=. All use =disc-followsurfacebelow= at depth 0, with a climate gate and =maxYRoughness= 1. They have no ore map, so the pick never reads them; showing them means placing them. 1. *Where each deposit starts.* =GenDeposits.GeneratePartial= runs one =chunkRand=, positioned at the chunk, through every top-level deposit in load order. Per deposit it takes one =NextInt(100)= for the fractional try. Per try it takes two =NextInt(32)= for the position and one =NextInt(10000000)= for the deposit's own seed. A deposit's try count depends only on its ore map, which matches the save already. The deposit's own work runs on =depositRand=, and a failed climate check returns before using =chunkRand=. So every deposit's centre and seed per chunk replays without generating any ore. Child deposits come after the main loop and don't disturb it. 2. *Climate gate* (=GenDeposits.GenDeposit=). Uses rain and temperature from the climate map at the centre, adjusted for the =RainHeightMap= height, and the relative Y against =minY=/=maxY=. The climate map and the terrain height are ported. =RainHeightMap= at this pass should be the terrain or the water surface; check that. 3. *Disc shape.* =DiscGenerator.GenDeposit=: radius, the shape distortion noise, =maxYRoughness=, and thickness. The ore deposits need the same port. 4. *Topsoil.* =inblock= is =soil-{fertility}-{cover}=, low or medium fertility with cover none to normal; fire clay wants bauxite sand or gravel. Fertility and grass cover come from =GenBlockLayers= and =blocklayers.json=, which are not ported. Without them, patches show where the game puts them on sand, gravel or rich soil. - *Checking.* Against the chunk blocks: clay, peat and compost soil where the save has them, at the top of the column. *Exact ore deposits.* The same replay, then the disc, sea-level, anywhere and child generators placing into the strata column. That places real ore blocks and makes the pick readings exact: the pick's column holds the ore of its own chunk's deposits. It also reads silver and gold (children of quartz) and peridot (a child of olivine), whose host is their parent's ore. Checking: against the save's ore blocks, which the strata check already counts (66 million). * 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.