Compare commits

...

29 Commits

Author SHA1 Message Date
e42e7b46b5 Add ability to set custom spawn location 2026-10-15 23:53:45 +03:00
dc15ec21a4 add cJSON as submodule 2026-10-11 18:52:21 +03:00
40defbd367 place hot springs as GenHotSprings does, and find the nearest
Carving records hot spring candidates where the game does: deep, wide
tunnel steps that pass the water check where geologic activity is
over 128. A candidate becomes a hot spring unless the surface over
twice its radius, after caves, is rough, below sea level + 1 or high
in the mountains, or a story location keeps hot springs away; carved
chunks are kept so their neighbours' heights come cheap. The Caves
overlay paints them as discs, and Find nearest looks for one.

Against the save, 173 of the 180 stored candidates match in centre and
radius; five differ only in the radius's last float bits, from a
rounding not yet found. Of the 102 hot springs placed, 84 hold the
save's sludgy gravel, and 94.8% of that gravel lies in one. Which edge
blocks are gravel or mat the game rolls each time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:24:10 +03:00
82774445af show the caves on the map, and find the nearest entrance
A Caves overlay colours each column by how far below the surface its
topmost cave starts, and marks where a cave opens at the surface; its
legend gives each band's share of the view. Find nearest entrance
carves the chunks it scans and looks at every column. The cursor label
and the probe list a column's caves, air or lava, top down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:34:26 +03:00
aeb6d3be22 carve caves as GenCaves does, and check them block by block
A cave's course depends only on the seed and the chunk it starts in,
so each source chunk's tunnels are traced once, in its own
coordinates, as the ellipsoids they carve. A chunk is carved as the
game carves it: its eleven by eleven sources in order, each ellipsoid
skipped where the terrain's water or earlier lava is near, lava and
basalt below y 12 by geologic activity, the height map lowered where a
cave opens. The terrain now keeps whether each block is solid, which
makes the water exact; story locations keep caves away as theirs do.

vsmv verify compares every stored block below our surface: 96.1% of
the 18.5 million carved blocks agree, and of the rest all but 0.28%
are what later passes put in caves or made of air themselves, the
vugs and the block layers above all. Carving lifts the columns
matching the stored height by 71,379.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:34:00 +03:00
2c16f8caef read the save's chunk blocks, and check the rock below the surface
A chunk's solid blocks are a palette of block ids, raw or zstd, and a
zstd frame of bit planes; a layer of a lone 0 is all air. With them,
vsmv verify compares the rock of every stored block below the surface
with the strata laid against our own heights, which predate the dry
seabed raise: 99.91% of 1.38 billion blocks match. Lava basalt near the
bottom, the granite of cave walls and structures, and columns whose
height differs explain all but 0.0011%, nearly all of that in one area
at the explored edge whose layer boundaries are not explained yet.

What the save has instead of stratum rock is tallied too, as the
ground truth the deposits phase can be checked against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 11:59:26 +03:00
53950a465c show silver, gold and peridot by their ore maps
The pick reads them from ore inside quartz and olivine deposits, which
are not placed yet, so for them the Minerals list shows the ore map
instead, marked as such: the overlay, Find nearest and the cursor work
on its value in sevenths, and the probe lists them on a line of their
own. Their maps already match the save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 11:59:20 +03:00
d3a53acbdb update plan and notes 2026-10-09 22:10:17 +03:00
ce445ce27a depend on the modules each Sex unit reads
sexc writes the rule now (sex#40), so a module's change rebuilds the
units that read it rather than every Sex object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:24:03 +03:00
1b6ac779a8 import only the modules each unit uses
An import brings the types and constants its interface needs now
(sex#58): a module pub-imports what its pub forms hold, and sexc
refuses one that does not. Every unit had imported its whole
dependency chain in order to make up for it.

worldgen also pub-imports json, whose cJSON.h its pub fns take
pointers into; a type only C knows is not something sexc can check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:22:41 +03:00
b8030b86bc make shape-cell private again
A pub record may point to a private one now (sex#57); its importers
are handed the declaration. natfloat stays pub: a mineral holds one by
value, so importers need its size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:19:00 +03:00
f82d2499c6 name the identifier predicates with a ?
sexc spells ? in a C name now (sex#49).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:18:20 +03:00
10ec6236fd order pb's methods by topic, and read rock-mode in the literal
A method can call one written below it now (sex#44), so pb's read as
an API: making one, asking about it, reading it, then the private
helpers. A path inside a compound literal follows the pointer
(sex#45). bytes keeps its local: the window starts where self stood
before it moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:17:55 +03:00
fee9a1c28e make the wire types an enum
Explicit enum values are converted now (sex#46).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:16:56 +03:00
c9daae367f write the noise constants the C# divides as divisions
A define's body is walked and parenthesised now (sex#55). The four
written as divisions fold to exactly the doubles they replace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:16:06 +03:00
3ff6dcaa74 drop the blocks around case bodies, and size block codes by type
A case body that declares is its own block now (sex#51), and sizeof
takes a pointer type (sex#52).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:12:51 +03:00
7cb49f83cd name the colour function type
A typedef of a function pointer type compiles now (sex#53).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:12:04 +03:00
e0901f6c8a pass the river colour as a conditional, with #line on every statement
A #line no longer lands inside a ?: (sex#54), so the build goes back
to statement-level directives, which is what lands a debugger on the
right line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:11:37 +03:00
e4ab3e875f put conditional operands back where they are used
A conditional expression as an operand keeps its parentheses now
(sex#59), so the clamps and offsets are written inline again. The
story's z direction stays a local: it is drawn before the distances,
and inlining it would reorder the draws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:11:17 +03:00
d40455d824 read the compared distances through the casts
A cast as the object of `.' keeps its parentheses now (sex#61), so
the comparator takes the two distances straight from its arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:10:24 +03:00
b74c445b25 cast the odd lattice coordinates to float directly
A cast of a bitwise expression keeps its parentheses now (sex#62), so
the int locals that held them are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:10:00 +03:00
d2721b55f7 write -INFINITY
sexc reads a dash before a name as negation now (sex#63).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:09:34 +03:00
74200559b8 write masks, colours and hash constants in hex
sexc reads hex literals now (sex#47). The OpenSimplex constants are
spelled as the C# spells them, and the colours as the comments that
stood in for them did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:09:08 +03:00
9bc1167782 size the thread and file arrays by their constants
An array of a header type takes a symbolic size now (sex#60). The
records holding them are pub, so their constants are too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:07:07 +03:00
d299ba05ac size arrays by the constants' own names
sexc converts an array bound's name now (sex#50), so MAX_STRATA and
the like go back to being written as defined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:06:24 +03:00
28f0e8acac pub-import the modules a unit's interface holds by value
sexc now checks that importers can see every type a pub form holds,
and asks for pub where the type comes from another import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 18:05:14 +03:00
a3a68df048 mark the public natfloat record as a sex#57 workaround
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:46:06 +03:00
e174bff7e2 show what the prospecting pick reads, and find it
The ore maps GenDeposits makes are ported and match the save's for all
31 minerals in every stored region. With them and the strata, a column
reads as the pick's density mode would read it: a Minerals overlay
colours the map by reading, the probe lists every mineral the pick
finds, and Find nearest looks for a mineral read at least so high.

Readings run slightly high: the pick's column already holds the ore of
its chunk's deposits, which are not generated yet. The check against
the 13 readings stored in the save asserts exactly that direction.
Silver, gold and peridot are read from ore inside other deposits, so
they wait for the deposits themselves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:02:34 +03:00
75d734c2d6 find one rock at any depth
A new rock mode looks for the one highlighted rock anywhere between the
surface and the mantle: the overlay shows the columns that hold it, the
cursor label how deep it starts, and Find nearest the nearest such
column. It can be chosen only while one rock is highlighted, and while
it is on, clicking a rock in the legend highlights that one instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:35:24 +03:00
30 changed files with 3821 additions and 574 deletions

6
.gitignore vendored
View File

@@ -1,11 +1,9 @@
/build/
# Inputs that stay local: the game's assets, the Rivers release, the
# test world and its server config, and the cJSON checkout the build
# compiles from.
# Inputs that stay local: the game's assets, the Rivers release, and
# the test world and its server config.
/assets/
/serverconfig.json
/cJSON/
*.zip
*.vcdbs
*.vcdbs-*

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "cJSON"]
path = cJSON
url = https://github.com/DaveGamble/cJSON.git

View File

@@ -4,28 +4,23 @@
SEXC ?= $(HOME)/dev/sex/sexc
CFLAGS ?= -O2 -g
CFLAGS += -std=c11 -Wall -ffp-contract=off -fwrapv
CPPFLAGS += -Isrc -Ithird_party/nuklear -Ithird_party/stb -IcJSON $(shell pkg-config --cflags sdl3)
CPPFLAGS += -Isrc -Ithird_party/nuklear -Ithird_party/stb -IcJSON $(shell pkg-config --cflags sdl3 libzstd)
# Sex writes C with only the parentheses precedence needs.
SEX_CFLAGS = -Wno-logical-op-parentheses -Wno-bitwise-op-parentheses -Wno-shift-op-parentheses
SDL_LIBS := $(shell pkg-config --libs sdl3)
ZSTD_LIBS := $(shell pkg-config --libs libzstd)
B = build
all: $(B)/vsmv $(B)/vs-map-viewer
# sexc writes no dependency files, and an import pastes the imported
# module's public forms into the importer, so any Sex source may change
# any Sex object.
# TODO sex#40: depend on what each unit imports once sexc writes
# dependency files.
SEX_SRC := $(wildcard src/*.sex)
# An import pastes the imported module's public forms into the
# importer, so a Sex object depends on every module it reads; sexc
# names them in a .d beside the object.
$(B)/%.o: src/%.sex | $(B)
$(SEXC) $< -c -o $@ --depfile=$(@:.o=.d) -- $(CFLAGS) $(SEX_CFLAGS) $(CPPFLAGS)
# Statement-level #line directives can land inside a ?: and break the
# C (see Sex-field-notes.org), so they are kept to toplevel forms.
# TODO sex#54: drop --line-directives=toplevel once #line no longer
# lands inside a ?:.
$(B)/%.o: src/%.sex $(SEX_SRC) | $(B)
$(SEXC) --line-directives=toplevel $< -c -o $@ -- $(CFLAGS) $(SEX_CFLAGS) $(CPPFLAGS)
-include $(wildcard $(B)/*.d)
$(B)/nk.o: src/nk.c src/nk.h | $(B)
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
@@ -36,15 +31,15 @@ $(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 terra strata settings verify cJSON stb
VSMV_OBJ = vsmv cs pb json maps save img dump lcg noise shape worldgen fastnoise rivers terra strata ores caves settings verify cJSON stb
$(B)/vsmv: $(VSMV_OBJ:%=$(B)/%.o)
$(CC) $^ -o $@ -lsqlite3
$(CC) $^ -o $@ -lsqlite3 $(ZSTD_LIBS)
VIEWER_OBJ = viewer tiles search hover settings worldgen fastnoise rivers terra strata shape noise lcg maps save pb json cs nk cJSON stb
VIEWER_OBJ = viewer tiles search hover settings worldgen fastnoise rivers terra strata ores caves shape noise lcg maps save pb json cs nk cJSON stb
$(B)/vs-map-viewer: $(VIEWER_OBJ:%=$(B)/%.o)
$(CC) $^ -o $@ $(SDL_LIBS) -lsqlite3
$(CC) $^ -o $@ $(SDL_LIBS) -lsqlite3 $(ZSTD_LIBS)
$(B):
mkdir -p $@

290
Plan.org
View File

@@ -50,6 +50,8 @@ redistribute their code verbatim.
| 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=,
@@ -215,6 +217,7 @@ Modules. Each is a Sex module; the =vsmv= CLI and the GUI share them.
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.
@@ -224,9 +227,14 @@ Modules. Each is a Sex module; the =vsmv= CLI and the GUI share them.
- =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.
Coordinates are shown as the game shows them, relative to the world's
spawn (=DefaultSpawnPosition=, which =GuiDialogWorldMap= subtracts):
=SaveGame.DefaultSpawn= when the world has one (game data field 40, a
=PlayerSpawnPos= {1: x, 2: y, 3: z, 7: remaining uses}; this save's is
1023719, 142, 12553), or =serverconfig.json='s =DefaultSpawn=, else
the map's middle. A spawn of one's own can be set over it, by clicking
the map after /Set spawn/ or with =--spawn X Z=. Absolute
coordinates are shown too. The viewer opens at the spawn.
* Phases
Each phase ends with a check against the save. A mismatch means stop,
@@ -274,9 +282,11 @@ What the save turned out to be:
=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).
| 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.
@@ -287,6 +297,25 @@ What the save turned out to be:
| 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.
@@ -464,9 +493,8 @@ Validation:
- *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* go through the same code but aren't checked against
chunk blocks. Decoding those blobs is the remaining step, if it is
ever needed.
- *Deeper layers.* Checked against the chunk blocks since; see
"Chunk blocks".
Viewer:
- *Rock layer.* Modes: surface, depth below the surface, or absolute
@@ -565,6 +593,78 @@ Viewer:
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;
@@ -575,8 +675,176 @@ Viewer:
- 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).
- 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.
** Caves (done)
=src/caves.sex= ports =GenCaves= (terrain pass, after the strata).
- *Starts.* =chunkRand= (world seed), positioned at the chunk, starts
a cave with chance 0.37: a position, size and shape from its draws,
then =caveRand= reseeded from it. Tunnels run 108 to 144 steps, so
they reach 5 chunks; they branch (horizontally, and at level 0 into
vertical shafts that end in a fan of tunnels), widen, flatten, go
tall, and near y 12 open lava caverns. =FastSin=/=FastCos= are the
game's 4096-entry tables.
- *Traced once.* A tunnel's course depends only on the seed and its
chunk. It is traced once per source chunk, as the ordered list of
=SetBlocks= ellipsoids, in the source chunk's coordinates. The game
works in the target chunk's coordinates; the double sums are exact
at that size, so the two differ by whole chunks only. World
coordinates would round.
- *Carved per chunk.* A target chunk replays its 11 x 11 sources in
=GenPartial='s order (x outer, z inner):
- Each ellipsoid that reaches the chunk is skipped if any liquid is
in it or one size around it: the water the terrain pass left in
every open block below sea level, or lava an earlier ellipsoid put.
- Below y 12 a carved block becomes basalt above
=geologic activity * 16 / 128= and lava at or below it. At y 11,
=basaltNoise= over 0.65 makes basalt.
- A carve at the column's height lowers it, which later carving
reads through =CaveHeightDistort=.
- Story locations skip caves for chunks whose centre lies in their
"caves" radius, or in the village's footprint (195 x 225; the
story schematics aren't in the assets read here).
- *Terrain solidity.* =terra/chunk-solidity= keeps every block's solid
or open from the height scan, so the water check is exact, overhang
pockets below sea level included.
- *Hot springs* (=GenHotSprings=, terrain features pass).
- Candidates: a tunnel step at -5 < y < 16 with radii over 4 and 2
flags its ellipsoid. Carving it, if it passes the water check, the
region's geologic activity is over 128, and its centre is in the
chunk, records it in the chunk's "hotspringlocations": keyed by
its whole centre, a later one at the same key taking its place.
- Placement: over a disc of twice the radius, the surface after caves
of the 3 x 3 chunks around (carved on demand, and kept, 512 chunks
a carver). Rejected when the surface varies by 4 or more, dips
below sea level + 1, or is above 88% of the world height, and
where a story location's "hotsprings" radius covers the chunk.
The game also rejects water standing at the surface; above sea
level that can only be a pond, which comes later, or a neighbour's.
- The disc sits at the average surface, rounded half to even:
boiling water in the middle (=xzdist= under 0.1), sludgy gravel a
base 3 deep and walls beside liquid, bacterial mats by distance.
The game jitters each column's distance with its unseeded random
generator, so the edges of those rings vary from run to run.
Validation (=vsmv verify=, every stored chunk, blocks below our
terrain height):
- 17,794,389 of our 18,521,333 carved blocks agree with the save
(96.08%): air or lava where the save has air (lava is a fluid, so its
solid block is air), basalt where it has basalt, or basalt a deposit
later made obsidian, ore or cracked rock. Of the rest, 667,823 hold
what later passes put in caves (stalactites, gravel, ice).
- Air the save has where we leave rock: 656,515 inside generated
structures (vugs above all), 292,212 at or above the save's surface
(the block layers take away top blocks, glaciers especially),
26,749 otherwise.
- Rock the save has where we carve air: 28,562 inside structures,
25,388 otherwise. The 52,137 unexplained are 0.28% of what we carve;
the check fails over 0.5%.
- The terrain's own pockets: 334,438 air blocks, 99.4% matching.
- Hot spring candidates against the 44 map chunks that store some: 173
of 180 the same, centre and radius. Five differ in the radius's last
bit or two, four of those from one tunnel, so some float step
somewhere rounds differently; not found yet. Two differ more.
- Hot springs: 102 placed, 84 with the save's sludgy gravel in them;
18,973 of the save's 20,024 sludgy gravel blocks lie in one (from 2
below the disc to 4 above, base and walls).
- Terrain height after carving: 11,552,740 of 11,687,936 columns match
the stored height, against 11,481,361 before. The caves make up most
of the "stored lower on land" columns of the height check.
Viewer:
- *Caves overlay.* Per column: none, an entrance (a cave lowered the
surface), or the depth of the topmost cave below the surface in
bands: 10, 25, 50, 100, deeper. Tiles carve every chunk they sample
whole, so a view takes some 30 s to fill on all cores.
- *Caves panel.* The legend with each band's share of the view, and
Find nearest entrance (search mode 5, every column of each chunk it
carves) or hot spring (mode 6).
- *Hot springs* are painted over the caves as discs, from the chunks of
the tile and one ring around it, whose discs can reach in.
- *Cursor label and Probe.* The column's cave runs, air or lava, top
down, and whether a cave opens there.
** 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

View File

@@ -5,36 +5,25 @@ settings, and it generates the world the way the game would and shows
it as a zoomable top-down map: terrain, rivers, oceans, climate,
landforms, geologic provinces, and rock strata at any depth. It is
mostly for finding rock: where chalk, bauxite or limestone lie, at the
surface or 20 blocks down, and which one is nearest.
surface or 20 blocks down, and which one is nearest. It also shows
what the prospecting pick would read for an ore, anywhere on the map,
and where the caves run.
[[file:doc/screenshot.png]]
It covers Vintage Story 1.22.7 with the Rivers 5.0.3 mod. The
generator is a port of the game's own, written in [[https://git.kotobank.ch/alex-eg/sex][Sex]]. It is checked
against a real save, and matches it:
| What | Matches |
|-------------------------------------------+-----------------------------------------|
| Region maps: landform, climate, province, ocean, upheaval, strata | every pixel of 118 regions |
| Story structure locations | all 6 |
| Rivers' distance to the nearest river | 100% of 6.5 million columns |
| Terrain height | 98.2% of 11.7 million columns |
| Rock at the surface | all but 14 of 11.7 million columns |
All but 0.02% of the other heights come from two passes that run after
the strata are laid: caves that open the surface, and the raise of dry
seabeds. Neither changes which rock is where.
=Plan.org= has the details.
generator is a port of the game's own, written in [[https://git.kotobank.ch/alex-eg/sex][Sex]].
** Building
You need:
- the Sex compiler, expected at =~/dev/sex/sexc= (or set =SEXC=);
- the Sex compiler;
- a C compiler;
- SDL3 (=brew install sdl3=);
- SDL3;
- SQLite3;
- a checkout of [[https://github.com/DaveGamble/cJSON][cJSON]] in =./cJSON=.
- zstd;
Nuklear and stb_image_write are vendored in =third_party/=.
сJSON is a submodule, so use =git submodule update --init= before building.
#+begin_src sh
make
@@ -58,8 +47,9 @@ WORLD is where the seed and settings come from:
real size;
- or a =serverconfig.json=: the seed as typed and the world config.
Without WORLD it opens =./serverconfig.json=. It starts at spawn, in the
middle of the map.
Without WORLD it opens =./serverconfig.json=. It starts at the world's
spawn: the one the save or config names, else the middle of the map,
as in the game.
Options:
@@ -68,12 +58,19 @@ Options:
| =--assets DIR= | where the game's =assets= are; default =./assets= |
| =--zoom Z= | blocks per screen point, 1/16 to 32; default 4 |
| =--base LAYER= | the base layer: =ocean=, =rivers= or =height=; default =height= |
| =--overlay NAME= | turn on an overlay: =landform=, =climate=, =province=, =upheaval=, =strata=, =rock=; repeatable |
| =--overlay NAME= | turn on an overlay: =landform=, =climate=, =province=, =upheaval=, =strata=, =rock=, =mineral=, =caves=; repeatable |
| =--opacity F= | overlay opacity, 0 to 1; default 0.5 |
| =--rock-depth N= / =--rock-y Y= | rocks at N blocks under the surface, or at height Y |
| =--rock-any= | the one highlighted rock at any depth |
| =--highlight ROCK= | highlight a rock, e.g. =chalk=; repeatable |
| =--find= | find the nearest highlighted rock on start |
| =--mineral CODE= | show a mineral's readings, e.g. =nativecopper= |
| =--min-reading NAME= | Find nearest's least reading for minerals, e.g. =high= or =very-poor=, or an ore map band, e.g. =86-100%=; default =decent= |
| =--find-mineral= | find the nearest such reading on start |
| =--find-cave= | find the nearest cave entrance on start |
| =--find-hot-spring= | find the nearest hot spring on start |
| =--probe X Z= | probe the column at block X, Z on start |
| =--spawn X Z= | count coordinates from block X, Z instead of the world's spawn |
| =--screenshot FILE.png= | wait until everything is drawn, save the window, quit |
| =--mouse X Y= | place the cursor, for screenshots |
@@ -90,12 +87,15 @@ The map fills the middle of the window, between two panels.
*** The map
- Drag with the left mouse button to pan.
- Scroll to zoom, around the cursor.
- Click (without dragging) to probe that column: its rock strata appear
in the Probe section, and a numbered pin marks the place. Click a pin
to probe it again.
- Click (without dragging) to probe that column: its rock strata and
the prospecting pick's reading there appear in the Probe section, and
a numbered pin marks the place. Click a pin to probe it again.
- With /Rock under cursor/ on, a label by the cursor names the rock
under it, as the Rocks section is set (at the surface, at a depth, or
at a height).
at a height). At any depth, it gives the Y of the rock's topmost block
and how far down that is, or says the column has none. With the
Minerals overlay on, another line gives the mineral's reading; with
the Caves overlay on, another gives the column's caves, top down.
The further out you zoom, the coarser the terrain is sampled: every
block when zoomed in close, one in 32 when far out. Only what is on screen is computed;
@@ -109,9 +109,13 @@ when nothing is left to compute, the viewer sleeps.
- Change any setting (seed, sizes, landcover, scales, climate...)
and press /Apply/ to generate that world instead. The seed can be
any text, as typed into the game.
- /Go to spawn/ goes back to the centre of the map.
- /Go to spawn/ goes back to the spawn.
- /Set spawn/, then a click on the map, sets the spawn that
coordinates count from there, as the game counts them from the
world's; Escape or the button again gives up. It starts as the
world's spawn; /World's spawn/ goes back to it.
- *Info*: what is under the cursor:
- coordinates, absolute and from the map centre, and the region;
- coordinates, absolute and from the spawn, and the region;
- landform and geologic province;
- climate: temperature at sea level, rain, geologic activity;
- ocean and upheaval values;
@@ -120,7 +124,11 @@ when nothing is left to compute, the viewer sleeps.
Below it, how many tiles are still being generated.
- *Probe*: the last column probed: its surface height and its strata,
top down, with the Y range and thickness of each.
top down, with the Y range and thickness of each. Below them, what
the prospecting pick reads there: every mineral it finds, highest
first, with its parts per thousand, then the miniscule amounts. Then
its caves, top down: air or lava, with the Y range of each, and
whether a cave opens at the surface there.
- /Go to/ centres it.
- /Clear pins/ removes the pins.
- /Close/ hides it.
@@ -129,13 +137,17 @@ when nothing is left to compute, the viewer sleeps.
- *Layers*:
- *Base*: one of Ocean, Rivers or Terrain height. Drawn opaque.
- *Overlays*: any of Landform, Climate, Geologic province, Upheaval,
Rock strata thickness (pick the stratum below it) and Rock. Drawn
over the base at the /Overlay opacity/.
- /Story locations/ marks spawn and the story structures.
Rock strata thickness (pick the stratum below it), Rock and
Minerals. Drawn over the base at the /Overlay opacity/.
- /Story locations/ marks the spawn, the world's spawn if the one set
differs, and the story structures.
- /Rock under cursor/ turns the cursor label on and off.
- *Rocks*: finding rock.
- Choose where to look: at the /Surface/, at a /Depth below
surface/, or /At Y/, and set the depth or Y.
surface/, or /At Y/, and set the depth or Y. /Any depth/ looks for
one rock anywhere from the surface down to the mantle; it can be
chosen while exactly one rock is highlighted, and while it is on,
clicking a rock in the legend highlights that one instead.
- The legend lists every rock with its share of the visible map,
while the Rock overlay is on.
- Click rocks in the legend to highlight them. With any highlighted,
@@ -145,6 +157,31 @@ when nothing is left to compute, the viewer sleeps.
the view, up to about 12,000 blocks out, jumps to the nearest one
and probes it. It samples every 16 blocks before it refines, so a
patch smaller than that can be missed. /Cancel/ stops it.
- *Minerals*: finding ore, the way the prospecting pick's density mode
does.
- Choose a mineral. The Minerals overlay colours the map by what the
pick would read there: miniscule, then very poor up to ultra high.
The legend gives each reading's share of the view.
- A reading combines the mineral's regional ore map with how much of
the column is its host rock, at the depths its deposits are placed
in. It says how likely the ore is near, not where the ore blocks
are.
- /Find nearest/ looks for the nearest column that reads at least
/Find at least/, as Rocks' /Find nearest/ does.
- Silver, gold and peridot are listed as /(ore map)/. For them the
overlay shows the mineral's ore map, how common it is there, in
bands of sevenths, and Find nearest looks for a band.
- *Caves*: the caves the game carves.
- The Caves overlay colours each column by how far below the
surface its topmost cave starts, and marks entrances, where a cave
opens at the surface. Hot springs show over it as discs. The legend
gives each band's share of the view.
- /Nearest entrance/ and /Nearest hot spring/ look for the nearest
cave entrance or hot spring around the centre of the view.
- A hot spring's place and size come from the seed; which blocks at
its edge are gravel or bacterial mat the game rolls each time.
- Caves are carved a chunk at a time, every block of it, so the
overlay is slow to fill when zoomed out.
** vsmv
The command-line side, mostly for checking the generator against a
@@ -158,16 +195,29 @@ save:
| =vsmv dump SAVE.vcdbs OUT= | PNGs of the maps the save stored |
| =vsmv verify SAVE.vcdbs DIR OUT= | regenerates everything the save stored and compares it; diff images go to OUT |
=verify= takes a few minutes, most of it on the terrain heights of
every stored chunk.
=verify= takes about eight minutes, most of it on the terrain heights
of every stored chunk and on the caves. It also compares the ore maps,
the prospecting pick readings players took in the save, if there are
any, and every stored block below the surface: its rock, and whether
it is a cave.
** Limits
- Only the /realistic/ world climate is supported, not /patchy/.
- Strata below the surface use the same code as the surface rock,
which is checked, but they are not checked against the save's blocks.
- Rivers' settings are not stored in a save. Without a =rivers.json=,
the mod's defaults are assumed.
- Other mods that change worldgen are not modelled.
- Caves leave out what later passes put in them: stalactites, gravel,
and the structures some of them hold. Of the blocks the
save has where caves are carved, 3.6% are such things.
- Prospecting readings come out a little higher than the game's: in
the readings checked, the game's was up to 12.5% lower, which can
move one across a category edge. The game's column already holds the ore of the
deposits generated in its chunk, and those deposits are not
generated here.
- The pick can't be reproduced for silver, gold and peridot. The game
reads them from ore inside other deposits (quartz and olivine),
which needs the deposits themselves. Minerals shows their ore maps
instead.
** Notes
- =Plan.org= is the design and how each part was checked.

View File

@@ -3,13 +3,17 @@
Language bugs and friction met while building vs-map-viewer, against
sexc at ~/dev/sex. Newest first. Unless said otherwise, sexc dfafe8b.
* =-INFINITY= is one symbol
* DONE =-INFINITY= is one symbol
Fixed in sexc f9fafd7 (sex#63): =-NAME= reads as =(- NAME)=.
=(var best double -INFINITY)= emits =_INFINITY=: the reader takes
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
* DONE A cast of a bitwise expression loses its parentheses
Fixed in sexc db98013 (sex#62).
=(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
@@ -19,20 +23,26 @@ 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
* DONE A cast as the object of =.= loses its parentheses
Fixed in sexc db98013 (sex#61).
=(. (cast pa (* const wanted)) distance)= emits
=(const wanted *)pa->distance=, which C reads as a cast of
=pa->distance= on a =void *=. Like the conditional entry below, the
writer doesn't parenthesize a lower-precedence operand. Bound to a
typed local first, it works.
* Arrays of a header type with a symbolic size misparse
* DONE Arrays of a header type with a symbolic size misparse
Fixed in sexc 97eb123 (sex#60).
=(workers [pthread-t MAX_WORKERS])= emits =pthread_t MAX_WORKERS
workers[];=, reading =MAX_WORKERS= as a second type word. =[u16
CHUNK_AREA]= works, presumably because =u16= is known to Sex and
=pthread_t= only to C. A literal size, =[pthread-t 32]=, works.
* A conditional expression as an operand loses its parentheses
* DONE A conditional expression as an operand loses its parentheses
Fixed in sexc db98013 (sex#59).
#+begin_src scheme
(/ (* 100.0 matched) (if (> compared 0) compared 1))
#+end_src
@@ -60,7 +70,11 @@ this project found four such sites that had compiled cleanly with
Only the generated C showed them. The fix is the same: bind to a
variable first.
* An import doesn't bring the types its interface needs
* DONE An import doesn't bring the types its interface needs
Fixed in sexc 360470d and a8f8b23 (sex#58): a module =pub import=s
what its pub forms hold, constants included, and sexc refuses one
that doesn't. A type only C knows, like =cJSON=, it can't check.
Module =save= takes a =(* region-maps)= from module =maps=. Importing
=save= pastes its prototypes but not =region-maps=, so every importer
has to import =maps= itself, and before =save=:
@@ -72,13 +86,19 @@ save.sex:284:52: error: unknown type name 'region_maps'
=vsmv.sex= now imports eight modules in dependency order to use three.
Imports are at least idempotent (a diamond works).
* A pub record with a field of a private record type
* DONE A pub record with a field of a private record type
Fixed in sexc 360470d (sex#57): behind a pointer, the type's
declaration goes out with the pub forms; held by value, it is an error
at the definition.
=(pub record natural-shape (... (slots (* shape-cell)) ...))= with
=shape-cell= not =pub= compiles in its own module, and in the importer
fails with =unknown type name 'shape_cell'=. Either an error at the
definition or exporting the type would do.
* =[(* T) N]= fields break in importers
* DONE =[(* T) N]= fields break in importers
Fixed in sexc 97eb123 (sex#56).
A pub record field =(noises [(* simplex-sum) 32])= compiles in its own
module but not when pasted into an importer:
=Error: pointer chains are written flat, as (* * T), not nested:
@@ -86,7 +106,9 @@ module but not when pasted into an importer:
=[* simplex-sum MAX_STRATA]= works, while a local
=(var names [(* const char) 6])= is fine either way.
* =define= bodies are pasted raw
* DONE =define= bodies are pasted raw
Fixed in sexc df3aa17 (sex#55).
=(define K (/ (cast 255 float) (cast 60 float)))= emits
=#define K cast(255, float) / cast(60, float)=: not translated, and
not parenthesized. With =(define D (/ -1.0 6.0))=, =(* x D)= becomes
@@ -94,7 +116,9 @@ not parenthesized. With =(define D (/ -1.0 6.0))=, =(* x D)= becomes
from multiplying by the folded constant. Bit-exact code needs literal
values or typed =var=s.
* =#line= splits a ternary in a call argument
* DONE =#line= splits a ternary in a call argument
Fixed in sexc ea0bed6 (sex#54).
=(if c a b)= in expression position becomes =c ? a : b=. Inside a
multi-line call, though, the statement anchor lands between the
ternary's parts, and the C doesn't compile:
@@ -110,7 +134,9 @@ dump.sex:128:1: error: expected expression
=-C= output, without the directives, is fine. The build now passes
=--line-directives=toplevel= to every Sex unit.
* A typedef of a function pointer type crashes the compiler
* DONE A typedef of a function pointer type crashes the compiler
Fixed in sexc 8774400 (sex#53).
#+begin_src scheme
(typedef colour-fn (fn ((i32)) u32))
#+end_src
@@ -120,59 +146,83 @@ Error: (cdr) bad argument type: u32
No location. The same type written inline in a parameter list works.
* =sizeof= of a pointer type reads as a dereference
* DONE =sizeof= of a pointer type reads as a dereference
Fixed in sexc 08044ce (sex#52).
=(sizeof (* char))= becomes =sizeof(*char)=. There's no way to spell
the type; =(sizeof x)= on an expression works.
* =case= bodies share one scope
* DONE =case= bodies share one scope
Fixed in sexc 1dc0c1a (sex#51): a body that declares is braced.
A =case= body isn't braced, so =(var bits u64 ...)= in one case and
=(var bits u32 ...)= in the next is a C redefinition. Clang also warns
"label followed by a declaration is a C23 extension". Wrapping each
body in =(do ...)= works around it; the writer could do that itself.
* Constants in array types aren't kebab-converted
* DONE Constants in array types aren't kebab-converted
Fixed in sexc 9a490a9 (sex#50).
=(var xs [u16 CHUNK-AREA])= and record fields like
=(terrain-height [u16 CHUNK-AREA])= emit =CHUNK-AREA= literally, while
=CHUNK-AREA= in an expression becomes =CHUNK_AREA=. Writing
=CHUNK_AREA= in the type works around it.
* =?= is not mangled in names
* DONE =?= is not mangled in names
Fixed in sexc d5b003e (sex#49): =?= becomes =ʔ= and =!= =ꜝ=, letters
C takes.
=(fn ident-start? ...)= emits =ident_start?=, which isn't C. Lisp
predicates want =?=; =-= is mangled to =_=, so =?= could become =_p=.
* Relative =SEX_MODULE_PATH= entries resolve from the root
* DONE Relative =SEX_MODULE_PATH= entries resolve from the root
Fixed in sexc 0d26b1f (sex#48).
=SEX_MODULE_PATH=src sexc ...= searches =/src/=. An absolute path works.
* No hex literals
* DONE No hex literals
Fixed in sexc 448b908 (sex#47): written to C in decimal.
=0x80= reaches C as =|0x80|= (the Scheme printer escaping a symbol
that looks numeric), and =#x80= is rejected by the reader:
"Unsupported # syntax: #\x". Masks and code points have to be written
in decimal, which hurts in bit-twiddling code: =(& c 224)= instead of
=(& c 0xE0)=.
* Explicit enum values emit raw names
* DONE Explicit enum values emit raw names
Fixed in sexc 504f357 (sex#46).
#+begin_src scheme
(pub enum wire ((wire-varint 0) (wire-fixed64 1)))
#+end_src
emits =wire-varint = 0, ...=, neither kebab-converted nor accepted by
C. Plain =(enum name (a b c))= works; explicit values need =define=s.
* Member access inside a compound literal ignores the operand's type
* DONE Member access inside a compound literal ignores the operand's type
Fixed in sexc b73cf36 (sex#45).
With =self= a =(* pb)=, =#(pb : (. self p) (. self p) true)= emits
=self.p=, not =self->p=. The same =(. self p)= outside a literal is
right. Bound to a local first, it works.
* Methods can only call methods above them
* DONE Methods can only call methods above them
Fixed in sexc 2d4e5f6 (sex#44).
Inside one =ops= block, calling a method defined further down fails
with =no such method on pb len=. C needs prototypes, so this is
consistent, but the block could declare its methods before their
bodies.
* =-o -= crashes instead of meaning stdout
* DONE =-o -= crashes instead of meaning stdout
Fixed in sexc ce236d8 (sex#43).
=--help= says -C output defaults to stdout without =-o=; passing =-o -=
explicitly dies in getopt-long's argument handling.
* A malformed =for= crashes the compiler
* DONE A malformed =for= crashes the compiler
Fixed in sexc baf2f92 (sex#42): a grouped header is an error naming
the line.
sexc dfafe8b. Writing the C-style grouped header
#+begin_src scheme
@@ -191,7 +241,10 @@ Error: (caddr) bad argument type: ()
Expected: a diagnostic naming the file, the line and the expected shape
of =for=.
* Spurious "cannot type this" on a header pointer
* DONE Spurious "cannot type this" on a header pointer
Fixed in sexc 79d9860 (sex#41): the warning stays, and names
=(. font handle)=, the part a struct only C knows leaves untyped.
sexc dfafe8b. In =src/viewer.sex=:
#+begin_src scheme
@@ -205,7 +258,9 @@ type is written out, so the warning is wrong on both counts: the type
is known, and the access isn't read as a value. The nearby
=(& (. font handle))= gives no warning.
* No dependency output
* DONE No dependency output
Fixed in sexc 1998344 (sex#40): =--depfile=.
sexc has nothing like =cc -MD=. An =import= pastes the imported
module's public forms into the importer, so the Makefile has to make
every Sex object depend on every =.sex= source.

1
cJSON Submodule

Submodule cJSON added at 6d9f2443ab

734
src/caves.sex Normal file
View File

@@ -0,0 +1,734 @@
;;; Caves as GenCaves carves them, during the terrain pass right after
;;; the strata.
;;;
;;; A chunk starts a cave with chance 0.37: a tunnel that wanders,
;;; widens and branches for up to about 140 steps, so it reaches up to
;;; five chunks away. Each step carves an ellipsoid. Its course depends
;;; only on the seed and the chunk, so it is traced once per source
;;; chunk, in that chunk's own coordinates, as the list of ellipsoids
;;; it carves.
;;;
;;; Carving them is per target chunk, as the game does it: the eleven
;;; by eleven source chunks around it in order, each ellipsoid skipped
;;; when there is liquid in or around it, water from the terrain or
;;; lava an earlier one left. Below y 12 a carved block becomes lava or
;;; basalt, by the region's geologic activity. Where a cave reaches the
;;; surface it lowers the height map, which later carving reads.
;;;
;;; Positions are kept relative to the source chunk. The game keeps them
;;; relative to the target chunk; at that size both sums are exact, so
;;; the two differ by whole chunks only, where world coordinates would
;;; round.
(include stdlib.h string.h math.h)
(pub import maps)
(import lcg)
(import noise)
(pub import worldgen)
(pub import terra)
;;; How many chunks a cave reaches, and the states of a carved column.
(pub define CAVE-RANGE 5)
(pub define CAVE-UNTOUCHED 0)
(pub define CAVE-AIR 1)
(pub define CAVE-LAVA 2)
(pub define CAVE-BASALT 3)
(define CHUNK 32)
(pub define SIN-COUNT 4096)
(pub define TRACE-SLOTS 4096)
;;; One SetBlocks call: the ellipsoid's centre in its source chunk's
;;; coordinates, its radii, and whether it may make a hot spring.
(record carve ((x double) (y double) (z double) (hr float) (vr float) (hot bool)))
;;; The carves of one source chunk's cave, in order.
(pub record trace ((sx int) (sz int) (valid bool) (carves (* carve)) (count int) (cap int)))
;;; A place a hot spring may go, as SetBlocks records it in its chunk's
;;; "hotspringlocations": the centre within the chunk, and the radius.
(pub record spring-candidate ((x int) (y int) (z int) (radius double)))
(pub define MAX-CANDIDATES 16)
;;; A carved chunk column, kept: its heights after carving and its
;;; candidates, in the order they were first recorded.
(pub record carved
((cx int) (cz int) (valid bool) (heights [int 1024]) (count int)
(candidates [spring-candidate MAX-CANDIDATES])))
(pub define CARVED-SLOTS 512)
(pub record caves
((g (* worldgen)) (seed i32) (size-y int) (sea-level int)
(height-noise (* simplex-noise)) (basalt-noise (* simplex-noise))
;; GameMath.FastSin and FastCos
(sin [float SIN-COUNT]) (cos [float SIN-COUNT]) (rad-to-index float)
(traces [trace TRACE-SLOTS])
;; the climate map of the region last asked about
(climate int-map) (climate-rx int) (climate-rz int)
;; the trace being made, and its random numbers
(cave-rand lcg) (current (* trace))
(carved [carved CARVED-SLOTS])
;; room to carve a neighbour in, for hot springs
(scratch-states (* u8)) (scratch-solid (* u32))))
(define PI-F 3.14159274)
(pub fn caves/make ((g (* worldgen))) (* caves)
(var c (* caves) (calloc 1 (sizeof caves)))
(= (. c g) g)
(= (. c seed) (. g settings seed))
(= (. c size-y) (. g settings size-y))
(= (. c sea-level) (cast (* 0.4313725490196078 (. g settings size-y)) int))
;; Seed + 12, as a C# int
(var seed i32 (cast (+ (cast (. c seed) u32) 12) i32))
(= (. c height-noise) (simplex-noise/octaves 3 (/ (cast 1 float) (cast 20 float)) (cast 0.9 float) seed))
(= (. c basalt-noise) (simplex-noise/octaves 2 (/ (cast 1 float) (cast 3.5 float)) (cast 0.9 float) seed))
(var rad-full float (cast (* M-PI 2.0) float))
(= (. c rad-to-index) (/ (cast SIN-COUNT float) rad-full))
(for (var i int 0) (< i SIN-COUNT) (++ i)
(var a float (* (/ (+ (cast i float) (cast 0.5 float)) (cast SIN-COUNT float)) rad-full))
(= [(. c sin) i] (cast (sin (cast a double)) float))
(= [(. c cos) i] (cast (cos (cast a double)) float)))
(return c))
(pub fn caves/free ((c (* caves))) void
(for (var i int 0) (< i TRACE-SLOTS) (++ i)
(free (. [(. c traces) i] carves)))
(free (. c climate data))
(free (. c scratch-states))
(free (. c scratch-solid))
(free (. c height-noise))
(free (. c basalt-noise))
(free c))
(fn fast-sin ((c (* const caves)) (rad float)) float
(return [(. c sin) (& (cast (* rad (. c rad-to-index)) int) (- SIN-COUNT 1))]))
(fn fast-cos ((c (* const caves)) (rad float)) float
(return [(. c cos) (& (cast (* rad (. c rad-to-index)) int) (- SIN-COUNT 1))]))
(fn clampf ((v float) (lo float) (hi float)) float
(if (< v lo) (return lo))
(if (> v hi) (return hi))
(return v))
(fn clampd ((v double) (lo double) (hi double)) double
(if (< v lo) (return lo))
(if (> v hi) (return hi))
(return v))
;;; Tracing ----------------------------------------------------------
(fn add-carve ((c (* caves)) (x double) (y double) (z double) (hr float) (vr float) (hot bool)) void
(var t (* trace) (. c current))
(if (>= (. t count) (. t cap))
(do
(= (. t cap) (if (> (. t cap) 0) (* (. t cap) 2) 256))
(= (. t carves) (realloc (. t carves) (* (. t cap) (sizeof carve))))))
(= [(. t carves) (. t count)] #(carve : x y z hr vr hot))
(++ (. t count)))
;; declared ahead: a tunnel branches into shafts, a shaft into tunnels
(fn carve-tunnel ((c (* caves)) (pos-x double) (pos-y double) (pos-z double) (hor-angle float)
(vert-angle float) (horizontal-size float) (vertical-size float)
(current-iteration int) (max-iterations int) (branch-level int)
(extra-branchy bool) (curviness float) (large-near-lava bool)) void)
;;; CarveShaft: a vertical branch that ends in a few horizontal ones.
(fn carve-shaft ((c (* caves)) (pos-x double) (pos-y double) (pos-z double) (hor-angle float)
(vert-angle float) (horizontal-size float) (vertical-size float)
(cave-current-iteration int) (max-iterations int) (branch-level int)) void
(var r (* lcg) (& (. c cave-rand)))
(var vert-angle-change float 0)
(var current-iteration int 0)
(while (< current-iteration max-iterations)
(++ current-iteration)
(var rel-pos float (/ (cast current-iteration float) (cast max-iterations float)))
(var hor-radius float (* horizontal-size (- (cast 1 float) (* rel-pos (cast 0.33 float)))))
(var vert-radius float (* hor-radius vertical-size))
(var advance-hor float (fast-cos c vert-angle))
(var advance-ver float (fast-sin c vert-angle))
(if (< vert-radius (cast 1 float))
(*= vert-angle (cast 0.1 float)))
(+= pos-x (* (fast-cos c hor-angle) advance-hor))
(+= pos-y (clampf advance-ver (- vert-radius) vert-radius))
(+= pos-z (* (fast-sin c hor-angle) advance-hor))
(+= vert-angle (* (cast 0.1 float) vert-angle-change))
(var a float (.next-float r))
(var b float (.next-float r))
(var d float (.next-float r))
(= vert-angle-change (+ (* (cast 0.9 float) vert-angle-change)
(/ (* (- a b) d) (cast 3 float))))
;; the horizontal branches at the bottom
(if (< (- max-iterations current-iteration) 10)
(do
(var num int (+ 3 (.next-int r 4)))
(for (var i int 0) (< i num) (++ i)
(var h float (* (.next-float r) (* (cast 2 float) (cast PI-F float))))
(var v float (* (- (.next-float r) (cast 0.5 float)) (cast 0.25 float)))
(carve-tunnel c pos-x pos-y pos-z h v (+ horizontal-size (cast 1 float)) vertical-size
cave-current-iteration max-iterations 1 false (cast 0.1 float) false))
(return)))
(if (&& (== (.next-int r 5) 0) (>= hor-radius (cast 2 float)))
(continue))
(add-carve c pos-x pos-y pos-z hor-radius vert-radius false)))
;;; CarveTunnel.
(fn carve-tunnel ((c (* caves)) (pos-x double) (pos-y double) (pos-z double) (hor-angle float)
(vert-angle float) (horizontal-size float) (vertical-size float)
(current-iteration int) (max-iterations int) (branch-level int)
(extra-branchy bool) (curviness float) (large-near-lava bool)) void
(var r (* lcg) (& (. c cave-rand)))
(var sea int (. c sea-level))
(var pi float (cast PI-F float))
(var hor-angle-change float 0)
(var vert-angle-change float 0)
(var hor-radius-gain float 0)
(var hor-radius-loss float 0)
(var hor-radius-gain-accum float 0)
(var hor-radius-loss-accum float 0)
(var ver-height-gain float 0)
(var ver-height-loss float 0)
(var ver-height-gain-accum float 0)
(var ver-height-loss-accum float 0)
(var size-change-speed-accum float (cast 0.15 float))
(var size-change-speed-gain float 0)
(var branch-rand int (* (+ branch-level 1) (if extra-branchy 12 25)))
(while (< current-iteration max-iterations)
(++ current-iteration)
(var rel-pos float (/ (cast current-iteration float) (cast max-iterations float)))
(var s float (fast-sin c (* rel-pos pi)))
(var hor-radius float (+ (+ (cast 1.5 float) (* s horizontal-size)) hor-radius-gain-accum))
(= hor-radius (fminf hor-radius (fmaxf (cast 1 float) (- hor-radius hor-radius-loss-accum))))
(var vert-radius float (+ (+ (cast 1.5 float)
(* s (+ vertical-size (/ hor-radius-loss-accum (cast 4 float)))))
ver-height-gain-accum))
(= vert-radius (fminf vert-radius (fmaxf (cast 0.6 float) (- vert-radius ver-height-loss-accum))))
(var advance-hor float (fast-cos c vert-angle))
(var advance-ver float (fast-sin c vert-angle))
;; caves get bigger near y 12
(if large-near-lava
(do
(var near float (- (cast 1 float) (/ (cast (fabs (- pos-y 12.0)) float) (cast 10 float))))
(var factor float (+ (cast 1 float) (fmaxf (cast 0 float) near)))
(*= hor-radius factor)
(*= vert-radius factor)))
(if (< vert-radius (cast 1 float))
(*= vert-angle (cast 0.1 float)))
(+= pos-x (* (fast-cos c hor-angle) advance-hor))
(+= pos-y (clampf advance-ver (- vert-radius) vert-radius))
(+= pos-z (* (fast-sin c hor-angle) advance-hor))
(*= vert-angle (cast 0.8 float))
(var rrnd int (.next-int r 800000))
(if (== (/ rrnd 10000) 0)
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= size-change-speed-gain (/ (* a b) (cast 2 float)))))
;; one draw picks among the rare changes: the game subtracts each
;; one's share in turn, which is these running totals
(var rnd int (% rrnd 10000))
(if (<= rnd 30)
(= hor-angle (* (.next-float r) (* (cast 2 float) pi)))
(<= rnd 106)
(+= hor-angle (- (* (.next-float r) pi) (/ pi (cast 2 float))))
(<= rnd 166)
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= hor-radius-gain (* (* a b) (cast 3.5 float))))
(<= rnd 226)
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= hor-radius-loss (* (* a b) (cast 10 float))))
(<= rnd 276)
(if (< pos-y (- sea 10))
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= ver-height-loss (* (* a b) (cast 12 float)))
(var e float (.next-float r))
(var f float (.next-float r))
(= hor-radius-gain (fmaxf hor-radius-gain (* (* e f) (cast 3 float))))))
(<= rnd 285)
(if (< pos-y (- sea 20))
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= hor-radius-gain (+ (cast 1 float) (* (* a b) (cast 5 float))))))
(<= rnd 294)
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= ver-height-gain (+ (cast 2 float) (* (* a b) (cast 7 float)))))
(<= rnd 394)
(if (< pos-y 19)
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= ver-height-gain (+ (cast 2 float) (* (* a b) (cast 5 float))))
(var e float (.next-float r))
(var f float (.next-float r))
(= hor-radius-gain (+ (cast 4 float) (* (* e f) (cast 9 float)))))))
;; deep and wide enough for a hot spring, if the carving gets there
(var hot bool (&& (> pos-y -5) (< pos-y 16) (> hor-radius (cast 4 float))
(> vert-radius (cast 2 float))))
(= size-change-speed-accum (fmaxf (cast 0.1 float) (+ size-change-speed-accum
(* size-change-speed-gain (cast 0.05 float)))))
(-= size-change-speed-gain (cast 0.02 float))
(= hor-radius-gain-accum (fmaxf (cast 0 float) (+ hor-radius-gain-accum (* hor-radius-gain size-change-speed-accum))))
(-= hor-radius-gain (cast 0.45 float))
(= hor-radius-loss-accum (fmaxf (cast 0 float) (+ hor-radius-loss-accum (* hor-radius-loss size-change-speed-accum))))
(-= hor-radius-loss (cast 0.4 float))
(= ver-height-gain-accum (fmaxf (cast 0 float) (+ ver-height-gain-accum (* ver-height-gain size-change-speed-accum))))
(-= ver-height-gain (cast 0.45 float))
(= ver-height-loss-accum (fmaxf (cast 0 float) (+ ver-height-loss-accum (* ver-height-loss size-change-speed-accum))))
(-= ver-height-loss (cast 0.4 float))
(+= hor-angle (* curviness hor-angle-change))
(+= vert-angle (* curviness vert-angle-change))
(var m1 float (.next-float-minus-to-plus-one r))
(var f1 float (.next-float r))
(= vert-angle-change (+ (* (cast 0.9 float) vert-angle-change) (* (* m1 f1) (cast 3 float))))
(var m2 float (.next-float-minus-to-plus-one r))
(var f2 float (.next-float r))
(= hor-angle-change (+ (* (cast 0.9 float) hor-angle-change) (* m2 f2)))
(if (== (% rrnd 140) 0)
(*= hor-angle-change (* (.next-float r) (cast 6 float))))
;; a horizontal branch, less likely above sea level
(var depth int (- (cast pos-y int) (- sea 20)))
(var brand int (+ branch-rand (* 2 (if (> depth 0) depth 0))))
(if (&& (< branch-level 3) (|| (> vert-radius (cast 1 float)) (> hor-radius (cast 1 float)))
(== (.next-int r brand) 0))
(do
(var a float (.next-float r))
(var b float (.next-float r))
(var h float (+ (+ hor-angle (- (+ a b) (cast 1 float))) pi))
(var e float (.next-float r))
(var f float (.next-float r))
(var v float (+ vert-angle (* (- e (cast 0.5 float)) (- f (cast 0.5 float)))))
(var k float (.next-float r))
(var shorter int (cast (* (* (cast k double) 0.5) max-iterations) int))
(carve-tunnel c pos-x (+ pos-y (/ ver-height-gain-accum (cast 2 float))) pos-z h v
horizontal-size (+ vertical-size ver-height-gain-accum) current-iteration
(- max-iterations shorter) (+ branch-level 1) false (cast 0.1 float) false)))
;; a vertical one
(if (&& (< branch-level 1) (> hor-radius (cast 3 float)) (> pos-y 60) (== (.next-int r 60) 0))
(do
(var a float (.next-float r))
(var b float (.next-float r))
(var h float (+ (+ hor-angle (- (+ a b) (cast 1 float))) pi))
(var e float (.next-float r))
(var v float (+ (- (- (/ pi (cast 2 float))) (cast 0.1 float)) (* (cast 0.2 float) e)))
(var k float (.next-float r))
(var shorter int (cast (* (* (cast k double) 0.5) max-iterations) int))
(var l float (.next-float r))
(var longer int (cast (* (/ pos-y 5) (cast (+ (cast 0.5 float) (* (cast 0.5 float) l)) double)) int))
(carve-shaft c pos-x (+ pos-y (/ ver-height-gain-accum (cast 2 float))) pos-z h v
(fminf (cast 3.5 float) (- hor-radius (cast 1 float)))
(+ vertical-size ver-height-gain-accum) current-iteration
(+ (- max-iterations shorter) longer) branch-level)
(++ branch-level)))
(if (&& (>= hor-radius (cast 2 float)) (== (% rrnd 5) 0))
(continue))
(add-carve c pos-x (+ pos-y (/ ver-height-gain-accum (cast 2 float))) pos-z hor-radius
(+ vert-radius ver-height-gain-accum) hot)))
;;; GeneratePartial's cave for source chunk (sx, sz), into T.
(fn trace-chunk ((c (* caves)) (t (* trace)) (sx int) (sz int)) void
(= (. t sx) sx)
(= (. t sz) sz)
(= (. t count) 0)
(= (. t valid) true)
(= (. c current) t)
(var r lcg (lcg/make (. c seed)))
(.init-position (& r) sx sz)
(if (! (< (.next-int (& r) 100) (* 0.37 100)))
(return))
(var rnd int (.next-int (& r) (* CHUNK CHUNK (- (. c size-y) 20))))
(var pos-x int (% rnd CHUNK))
(/= rnd CHUNK)
(var pos-z int (% rnd CHUNK))
(/= rnd CHUNK)
(var pos-y int (+ rnd 8))
(var pi float (cast PI-F float))
(var hor-angle float (* (.next-float (& r)) (* (cast 2 float) pi)))
(var vert-angle float (* (- (.next-float (& r)) (cast 0.5 float)) (cast 0.25 float)))
(var a float (.next-float (& r)))
(var b float (.next-float (& r)))
(var horizontal-size float (+ (* a (cast 2 float)) b))
(var vertical-size float (+ (cast 0.75 float) (* (.next-float (& r)) (cast 0.4 float))))
(= rnd (.next-int (& r) (* 100 50 1000 100)))
(if (< (% rnd 100) 4)
(do
(var e float (.next-float (& r)))
(var f float (.next-float (& r)))
(var g float (.next-float (& r)))
(= horizontal-size (+ (+ (* e (cast 2 float)) f) g))
(= vertical-size (+ (cast 0.25 float) (* (.next-float (& r)) (cast 0.2 float)))))
(== (% rnd 100) 4)
(do
(= horizontal-size (+ (cast 0.75 float) (.next-float (& r))))
(var e float (.next-float (& r)))
(var f float (.next-float (& r)))
(= vertical-size (+ (* e (cast 2 float)) f))))
(/= rnd 100)
(var extra-branchy bool (&& (< pos-y (/ (. c sea-level) 2)) (== (% rnd 50) 0)))
(/= rnd 50)
(var rnd1000 int (% rnd 1000))
(/= rnd 1000)
(var large-near-lava bool (< (% rnd1000 10) 3))
(var curviness float (cast 0.1 float))
(if (== rnd 0) (= curviness (cast 0.035 float))
(< rnd1000 30) (= curviness (cast 0.5 float)))
(var max-iterations int (- (* CAVE-RANGE CHUNK) (/ CHUNK 2)))
(-= max-iterations (.next-int (& r) (/ max-iterations 4)))
(.reseed (& (. c cave-rand)) (.next-int (& r) 10000000))
(.init-position (& (. c cave-rand)) sx sz)
(carve-tunnel c pos-x pos-y pos-z hor-angle vert-angle horizontal-size vertical-size 0
max-iterations 0 extra-branchy curviness large-near-lava))
;;; Source chunk (sx, sz)'s trace, traced once and kept.
(fn trace-of ((c (* caves)) (sx int) (sz int)) (* trace)
(var h u32 (+ (* (cast sx u32) 73856093) (* (cast sz u32) 19349663)))
(var t (* trace) (& [(. c traces) (% h TRACE-SLOTS)]))
(if (! (&& (. t valid) (== (. t sx) sx) (== (. t sz) sz)))
(trace-chunk c t sx sz))
(return t))
;;; Carving ----------------------------------------------------------
;;; getGeologicActivity: the climate map's low byte at the chunk.
(fn geologic-activity ((c (* caves)) (x int) (z int)) int
(var rx int (/ x 512))
(var rz int (/ z 512))
(if (|| (! (. c climate data)) (!= (. c climate-rx) rx) (!= (. c climate-rz) rz))
(do
(free (. c climate data))
(worldgen/map (. c g) MAP-CLIMATE 0 rx rz (& (. c climate)))
(= (. c climate-rx) rx)
(= (. c climate-rz) rz)))
(var m (* int-map) (& (. c climate)))
(var lx int (% (/ x CHUNK) 16))
(var lz int (% (/ z CHUNK) 16))
(return (& [(. m data) (+ (* (+ lz (. m pad-tl)) (. m size)) lx (. m pad-tl))] 255)))
;;; A target chunk column while it is carved.
(record column
((tx int) (tz int) (states (* u8)) (heights (* int)) (water-top (* int)) (distort [u8 1024])
(solid (* const u32)) (words int)
(candidates [spring-candidate MAX-CANDIDATES]) (count int)))
;;; The terrain pass put water in every block below sea level that it
;;; left open; with the terrain's solidity at hand that is exact, else
;;; it is the column above its surface.
(fn liquid-at ((c (* const caves)) (k (* const column)) (lx int) (y int) (lz int)) bool
(var i int (+ (* lz CHUNK) lx))
(if (< y (. c sea-level))
(if (. k solid)
(if (== (& (>> [(. k solid) (+ (* i (. k words)) (/ y 32))] (% y 32)) 1) 0)
(return true))
(> y [(. k water-top) i])
(return true)))
(return (== [(. k states) (+ (* (+ (* y CHUNK) lz) CHUNK) lx)] CAVE-LAVA)))
;;; SetBlocks, at centre (x, y, z) in the target chunk's coordinates.
(fn set-blocks ((c (* caves)) (k (* column)) (hor-radius float) (vert-radius float)
(x double) (y double) (z double) (hot bool)) void
(var top int (- (. c size-y) 1))
;; one size more, to see whether it would run into liquid
(+= hor-radius (cast 1 float))
(+= vert-radius (cast 2 float))
(var min-x int (cast (clampd (- x hor-radius) 0 (- CHUNK 1)) int))
(var max-x int (cast (clampd (+ (+ x hor-radius) 1) 0 (- CHUNK 1)) int))
(var min-y int (cast (clampd (- y (* vert-radius (cast 0.7 float))) 1 top) int))
(var max-y int (cast (clampd (+ (+ y vert-radius) 1) 1 top) int))
(var min-z int (cast (clampd (- z hor-radius) 0 (- CHUNK 1)) int))
(var max-z int (cast (clampd (+ (+ z hor-radius) 1) 0 (- CHUNK 1)) int))
(var h-sq double (* hor-radius hor-radius))
(var v-sq double (* vert-radius vert-radius))
(var distort-strength double (clampd (/ vert-radius 4.0) 0 0.1))
(for (var lx int min-x) (<= lx max-x) (++ lx)
(var xd double (/ (* (- lx x) (- lx x)) h-sq))
(for (var lz int min-z) (<= lz max-z) (++ lz)
(var zd double (/ (* (- lz z) (- lz z)) h-sq))
(var height-rnd double (* (- [(. k distort) (+ (* lz CHUNK) lx)] 127) distort-strength))
(for (var ly int min-y) (<= ly (+ max-y 10)) (++ ly)
(var dy double (- ly y))
(var off double 0)
(if (> dy 0) (= off (* height-rnd height-rnd)))
(var yd double (/ (* dy dy) (+ v-sq off)))
(if (|| (> (+ xd yd zd) 1.0) (> ly top))
(continue))
(if (liquid-at c k lx ly lz)
(return)))))
(-= hor-radius (cast 1 float))
(-= vert-radius (cast 2 float))
(= min-x (cast (clampd (- x hor-radius) 0 (- CHUNK 1)) int))
(= max-x (cast (clampd (+ (+ x hor-radius) 1) 0 (- CHUNK 1)) int))
(= min-z (cast (clampd (- z hor-radius) 0 (- CHUNK 1)) int))
(= max-z (cast (clampd (+ (+ z hor-radius) 1) 0 (- CHUNK 1)) int))
(= min-y (cast (clampd (- y (* vert-radius (cast 0.7 float))) 1 top) int))
(= max-y (cast (clampd (+ (+ y vert-radius) 1) 1 top) int))
(= h-sq (* hor-radius hor-radius))
(= v-sq (* vert-radius vert-radius))
(var geo int (geologic-activity c (+ (* (. k tx) CHUNK) (cast x int)) (+ (* (. k tz) CHUNK) (cast z int))))
;; a hot spring candidate, keyed by its whole centre as the game's
;; dictionary is: a later one at the same key takes its place there
(if (&& hot (> geo 128) (>= x 0) (< x CHUNK) (>= z 0) (< z CHUNK))
(do
(var cand spring-candidate #(spring-candidate : (cast x int) (cast y int) (cast z int) hor-radius))
(var i int 0)
(while (&& (< i (. k count))
(! (&& (== (. [(. k candidates) i] x) (. cand x)) (== (. [(. k candidates) i] y) (. cand y))
(== (. [(. k candidates) i] z) (. cand z)))))
(++ i))
(if (< i MAX-CANDIDATES)
(do
(= [(. k candidates) i] cand)
(if (== i (. k count)) (++ (. k count)))))))
(var lava-top int (/ (* geo 16) 128))
(for (var lx int min-x) (<= lx max-x) (++ lx)
(var xd double (/ (* (- lx x) (- lx x)) h-sq))
(for (var lz int min-z) (<= lz max-z) (++ lz)
(var zd double (/ (* (- lz z) (- lz z)) h-sq))
(var i int (+ (* lz CHUNK) lx))
(var height-rnd double (* (- [(. k distort) i] 127) distort-strength))
(var surface int [(. k heights) i])
(for (var ly int (+ max-y 10)) (>= ly min-y) (-- ly)
(var dy double (- ly y))
(var off double 0)
(if (> dy 0)
(do
(var near double (/ (abs (- ly surface)) 10.0))
(= off (* height-rnd height-rnd (fmin 1 near)))))
(var yd double (/ (* dy dy) (+ v-sq off)))
(if (|| (> ly top) (> (+ xd yd zd) 1.0))
(continue))
(if (== [(. k heights) i] ly)
(= [(. k heights) i] (- ly 1)))
(var b (* u8) (& [(. k states) (+ (* (+ (* ly CHUNK) lz) CHUNK) lx)]))
(if (== ly 11)
(if (> (.noise-2d (. c basalt-noise) (+ (* (. k tx) CHUNK) lx) (+ (* (. k tz) CHUNK) lz)) 0.65)
(do
(= (* b) CAVE-BASALT)
(if (< [(. k heights) i] 11) (= [(. k heights) i] 11)))
(> ly lava-top) (= (* b) CAVE-BASALT)
(= (* b) CAVE-LAVA))
(< ly 12)
(if (> ly lava-top) (= (* b) CAVE-BASALT) (= (* b) CAVE-LAVA))
(= (* b) CAVE-AIR))))))
;;; Carves chunk column (tx, tz): STATES, 32 x 32 x size-y by
;;; (y * 32 + z) * 32 + x, gets each block's CAVE- state; HEIGHTS, the
;;; terrain heights by z * 32 + x, are lowered where caves reach the
;;; surface. SOLID, terra/chunk-solidity's bits with WORDS per column,
;;; tells where the terrain left water; without it, NULL, water is
;;; taken to be the columns above their surface.
(fn slot-of ((c (* caves)) (cx int) (cz int)) (* carved)
(var h u32 (+ (* (cast cx u32) 73856093) (* (cast cz u32) 19349663)))
(return (& [(. c carved) (% h CARVED-SLOTS)])))
;;; Keeps a carved chunk's heights and candidates.
(fn keep-carved ((c (* caves)) (cx int) (cz int) (heights (* const int))
(candidates (* const spring-candidate)) (count int)) void
(var e (* carved) (slot-of c cx cz))
(= (. e cx) cx)
(= (. e cz) cz)
(= (. e valid) true)
(memcpy (. e heights) heights (sizeof (. e heights)))
(= (. e count) count)
(if (> count 0)
(memcpy (. e candidates) candidates (* count (sizeof spring-candidate)))))
(pub fn caves/carve-column ((c (* caves)) (tx int) (tz int) (heights (* int)) (solid (* const u32))
(words int) (states (* u8))) void
(memset states 0 (* CHUNK CHUNK (. c size-y)))
(if (worldgen/caves-blocked (. c g) (+ (* tx CHUNK) 16) (+ (* tz CHUNK) 16))
(do
(keep-carved c tx tz heights NULL 0)
(return)))
(var k column)
(= (. k count) 0)
(= (. k tx) tx)
(= (. k tz) tz)
(= (. k states) states)
(= (. k heights) heights)
(= (. k solid) solid)
(= (. k words) words)
;; the terrain pass left water in every column below sea level above
;; its surface
(var water-top [int 1024])
(memcpy water-top heights (sizeof water-top))
(= (. k water-top) water-top)
;; GenCaves.OnMapChunkGen: CaveHeightDistort
(for (var lz int 0) (< lz CHUNK) (++ lz)
(for (var lx int 0) (< lx CHUNK) (++ lx)
(var v double (- (.noise-2d (. c height-noise) (+ (* tx CHUNK) lx) (+ (* tz CHUNK) lz)) 0.5))
(if (> v 0)
(= v (fmax 0 (- v 0.07)))
(= v (fmin 0 (+ v 0.07))))
(= [(. k distort) (+ (* lz CHUNK) lx)] (cast (cast (+ (* 128 v) 127) int) u8))))
(for (var dx int (- CAVE-RANGE)) (<= dx CAVE-RANGE) (++ dx)
(for (var dz int (- CAVE-RANGE)) (<= dz CAVE-RANGE) (++ dz)
(var t (* trace) (trace-of c (+ tx dx) (+ tz dz)))
(for (var i int 0) (< i (. t count)) (++ i)
(var cv (* carve) (& [(. t carves) i]))
(var x double (+ (. cv x) (* dx CHUNK)))
(var z double (+ (. cv z) (* dz CHUNK)))
;; only what reaches this chunk
(var reach float (* (. cv hr) (cast 2 float)))
(if (|| (<= x (- reach)) (>= x (+ CHUNK reach)) (<= z (- reach)) (>= z (+ CHUNK reach)))
(continue))
(set-blocks c (& k) (. cv hr) (. cv vr) x (. cv y) z (. cv hot)))))
(keep-carved c tx tz heights (. k candidates) (. k count)))
;;; The hot spring candidates of the chunk column last carved at (cx,
;;; cz), into OUT; how many, or -1 if it isn't kept.
(pub fn caves/candidates ((c (* caves)) (cx int) (cz int) (out (* spring-candidate)) (max int)) int
(var e (* carved) (slot-of c cx cz))
(if (! (&& (. e valid) (== (. e cx) cx) (== (. e cz) cz)))
(return -1))
(var n int (if (< (. e count) max) (. e count) max))
(if (> n 0)
(memcpy out (. e candidates) (* n (sizeof spring-candidate))))
(return n))
;;; Columns ----------------------------------------------------------
;;; How a column's caves show on the map: none; an entrance, where a
;;; cave reached the surface; or how deep below the surface the topmost
;;; one starts.
(pub define CAVE-NONE 0)
(pub define CAVE-ENTRANCE 1)
;;; Not a column's own: what the Caves overlay paints over a hot spring.
(pub define CAVE-HOT-SPRING 7)
(pub define CAVE-CATEGORIES 8)
(var depth-bands [int 4] #(10 25 50 100))
;;; The category of column (lx, lz) of a carved chunk column: SURFACE is
;;; its terrain height before carving, CARVED after.
(pub fn caves/category ((c (* const caves)) (states (* const u8)) (lx int) (lz int) (surface int)
(carved int)) int
(if (< carved surface)
(return CAVE-ENTRANCE))
(for (var y int surface) (>= y 1) (-- y)
(var s u8 [states (+ (* (+ (* y CHUNK) lz) CHUNK) lx)])
(if (|| (== s CAVE-AIR) (== s CAVE-LAVA))
(do
(var depth int (- surface y))
(for (var b int 0) (< b 4) (++ b)
(if (<= depth [depth-bands b])
(return (+ 2 b))))
(return 6))))
(return CAVE-NONE))
;;; A column's caves as runs of air or lava, top down: run i is from
;;; TOPS[i] down to BOTTOMS[i], lava when LAVA[i]. Returns how many, up
;;; to MAX.
(pub fn caves/runs ((c (* const caves)) (states (* const u8)) (lx int) (lz int) (surface int)
(tops (* int)) (bottoms (* int)) (lava (* bool)) (max int)) int
(var n int 0)
(var prev u8 CAVE-UNTOUCHED)
(for (var y int surface) (>= y 1) (-- y)
(var s u8 [states (+ (* (+ (* y CHUNK) lz) CHUNK) lx)])
(if (== s CAVE-BASALT) (= s CAVE-UNTOUCHED))
(if (&& (!= s CAVE-UNTOUCHED) (== s prev) (> n 0))
(= [bottoms (- n 1)] y)
(&& (!= s CAVE-UNTOUCHED) (< n max))
(do
(= [tops n] y)
(= [bottoms n] y)
(= [lava n] (== s CAVE-LAVA))
(++ n)))
(= prev s))
(return n))
;;; Hot springs ------------------------------------------------------
;;; A hot spring GenHotSprings makes: a disc of RADIUS around (x, z) at
;;; height y. Its middle, out to about a third of the radius, is boiling
;;; water, the rest sludgy gravel and bacterial mats; where exactly the
;;; edge of each falls the game rolls with a random generator of its
;;; own.
(pub record hot-spring ((x int) (y int) (z int) (radius double)))
;;; Chunk column (cx, cz) carved, from what is kept or carved now.
(fn carved-of ((c (* caves)) (tr (* terra)) (cx int) (cz int)) (* carved)
(var e (* carved) (slot-of c cx cz))
(if (&& (. e valid) (== (. e cx) cx) (== (. e cz) cz))
(return e))
(var words int (terra/solid-words tr))
(if (! (. c scratch-states))
(do
(= (. c scratch-states) (malloc (* CHUNK CHUNK (. c size-y))))
(= (. c scratch-solid) (malloc (* 1024 words (sizeof u32))))))
(var heights16 [u16 1024])
(var heights [int 1024])
(terra/chunk-solidity tr cx cz heights16 (. c scratch-solid))
(for (var i int 0) (< i 1024) (++ i)
(= [heights i] [heights16 i]))
(caves/carve-column c cx cz heights (. c scratch-solid) words (. c scratch-states))
(return (slot-of c cx cz)))
(fn surface-at ((c (* caves)) (tr (* terra)) (x int) (z int)) int
(var e (* carved) (carved-of c tr (/ x CHUNK) (/ z CHUNK)))
(return [(. e heights) (+ (* (% z CHUNK) CHUNK) (% x CHUNK))]))
;;; GenHotSprings for chunk column (cx, cz): its candidates that become
;;; hot springs, into OUT; how many, up to MAX. A candidate is kept
;;; unless the ground over twice its radius is rough (4 or more blocks
;;; between highest and lowest), anywhere below sea level + 1, or high
;;; in the mountains. The game also leaves out one with water standing
;;; at the surface; above sea level that can only be a pond, which comes
;;; later, or a neighbour's, which it does not see here.
(pub fn caves/hot-springs ((c (* caves)) (tr (* terra)) (cx int) (cz int) (out (* hot-spring)) (max int))
int
(if (worldgen/springs-blocked (. c g) (+ (* cx CHUNK) 16) (+ (* cz CHUNK) 16))
(return 0))
(var candidates [spring-candidate MAX-CANDIDATES])
(var e (* carved) (carved-of c tr cx cz))
(var count int (. e count))
(memcpy candidates (. e candidates) (* count (sizeof spring-candidate)))
(var n int 0)
(var base-x int (* cx CHUNK))
(var base-z int (* cz CHUNK))
(for (var k int 0) (&& (< k count) (< n max)) (++ k)
(var cand (* spring-candidate) (& [candidates k]))
(var radius double (* 2 (. cand radius)))
(var min-x int (cast (clampd (- (. cand x) radius) (- CHUNK) (- (* 2 CHUNK) 1)) int))
(var max-x int (cast (clampd (+ (+ (. cand x) radius) 1) (- CHUNK) (- (* 2 CHUNK) 1)) int))
(var min-z int (cast (clampd (- (. cand z) radius) (- CHUNK) (- (* 2 CHUNK) 1)) int))
(var max-z int (cast (clampd (+ (+ (. cand z) radius) 1) (- CHUNK) (- (* 2 CHUNK) 1)) int))
(var r-sq double (* radius radius))
(var lowest int 99999)
(var highest int 0)
(var checks int 0)
(var sum i64 0)
(for (var lx int min-x) (<= lx max-x) (++ lx)
(var xd double (/ (* (- lx (. cand x)) (- lx (. cand x))) r-sq))
(for (var lz int min-z) (<= lz max-z) (++ lz)
(var zd double (/ (* (- lz (. cand z)) (- lz (. cand z))) r-sq))
(if (>= (+ xd zd) 1)
(continue))
(var surface int (surface-at c tr (+ base-x lx) (+ base-z lz)))
(if (< surface lowest) (= lowest surface))
(if (> surface highest) (= highest surface))
(++ checks)
(+= sum surface)))
(if (== checks 0)
(continue))
;; Math.Round rounds halves to even, as rint does
(var average int (cast (rint (/ (cast sum double) checks)) int))
(if (|| (>= (- highest lowest) 4) (< lowest (+ (. c sea-level) 1))
(> lowest (* (cast (. c size-y) float) (cast 0.88 float))))
(continue))
(= [out n] #(hot-spring : (+ base-x (. cand x)) average (+ base-z (. cand z)) radius))
(++ n))
(return n))

View File

@@ -10,17 +10,15 @@
(var p (* const u8) (* s))
(var c u32 [p 0])
(var n int 0)
;; TODO sex#47: write the UTF-8 masks in hex once there are hex
;; literals.
(if (< c 128) (= n 0)
(== (& c 224) 192) (do (= n 1) (&= c 31))
(== (& c 240) 224) (do (= n 2) (&= c 15))
(== (& c 248) 240) (do (= n 3) (&= c 7))
(do (= (* s) (+ p 1)) (return 65533)))
(if (< c 0x80) (= n 0)
(== (& c 0xE0) 0xC0) (do (= n 1) (&= c 0x1F))
(== (& c 0xF0) 0xE0) (do (= n 2) (&= c 0x0F))
(== (& c 0xF8) 0xF0) (do (= n 3) (&= c 0x07))
(do (= (* s) (+ p 1)) (return 0xFFFD)))
(for (var i int 1) (<= i n) (++ i)
(if (!= (& [p i] 192) 128)
(do (= (* s) (+ p i)) (return 65533)))
(= c (c-bit-or (<< c 6) (& [p i] 63))))
(if (!= (& [p i] 0xC0) 0x80)
(do (= (* s) (+ p i)) (return 0xFFFD)))
(= c (c-bit-or (<< c 6) (& [p i] 0x3F))))
(= (* s) (+ p n 1))
(return c))
@@ -34,16 +32,14 @@
(var p (* const u8) (cast text (* const u8)))
(while (* p)
(var c u32 (utf8-next (& p)))
(if (< c 65536)
(if (< c 0x10000)
(do
(= [units n] c)
(+= n 1))
(do
;; TODO sex#47: write the surrogate constants in hex once
;; there are hex literals.
(-= c 65536)
(= [units n] (+ 55296 (>> c 10)))
(= [units (+ n 1)] (+ 56320 (& c 1023)))
(-= c 0x10000)
(= [units n] (+ 0xD800 (>> c 10)))
(= [units (+ n 1)] (+ 0xDC00 (& c 0x3FF)))
(+= n 2))))
(= (* out) units)
(return n))
@@ -71,9 +67,7 @@
(if (> len 0)
(= h1 (hash-step h1 (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16)))))
(free units)
;; TODO sex#47: write the multiplier (0x5D588B65) in hex once there
;; are hex literals.
(return (cast (+ (cast h1 u32) (* (cast h2 u32) (cast 1566083941 u32))) i32)))
(return (cast (+ (cast h1 u32) (* (cast h2 u32) (cast 0x5D588B65 u32))) i32)))
;;; The world seed from the seed text in world settings. A number is
;;; taken as it is, anything else is hashed.
@@ -87,3 +81,26 @@
(>= v INT32_MIN) (<= v INT32_MAX))
(return (cast v i32)))
(return (dotnet-string-hash text)))
(fn rotl5 ((h u32)) u32
(return (c-bit-or (<< h 5) (>> h 27))))
;;; StringUtil.GetNonRandomizedHashCode: the newer .NET string hash the
;;; game seeds ore maps with. Unlike dotnet-string-hash it rotates, and
;;; it reads past the end into the terminator.
;;; (nonrandomized-string-hash "lignite")
(pub fn nonrandomized-string-hash ((text (* const char))) i32
(var units (* u16) NULL)
(var len int (cast (utf16 text (& units)) int))
(var h1 u32 (+ (<< (cast 5381 u32) 16) 5381))
(var h2 u32 h1)
(var i int 0)
(while (> len 2)
(-= len 4)
(= h1 (^ (+ (rotl5 h1) h1) (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16))))
(= h2 (^ (+ (rotl5 h2) h2) (c-bit-or [units (+ i 2)] (<< (cast [units (+ i 3)] u32) 16))))
(+= i 4))
(if (> len 0)
(= h2 (^ (+ (rotl5 h2) h2) (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16)))))
(free units)
(return (cast (+ h1 (* h2 (cast 0x5D588B65 u32))) i32)))

View File

@@ -9,17 +9,16 @@
(fn landform-colour ((v i32)) u32 (return (palette (cast v u32))))
(fn province-colour ((v i32)) u32 (return (palette (+ (cast v u32) 100))))
;; TODO sex#47: write the mask in hex once there are hex literals.
(fn climate-colour ((v i32)) u32 (return (& (cast v u32) 16777215)))
(fn climate-colour ((v i32)) u32 (return (& (cast v u32) 0xFFFFFF)))
(fn byte-colour ((v i32)) u32 (return (grey v)))
(typedef colour-fn (fn ((i32)) u32))
;;; The inner square of one region's map, placed at (ox, oz) and
;;; stretched to CELL pixels a side, so maps of different resolutions
;;; line up pixel for pixel across mosaics.
;; TODO sex#53: name the colour function type with a typedef once that
;; no longer crashes sexc.
(fn paint-map ((im (* image)) (m (* const int-map)) (ox int) (oz int) (cell int)
(colour (fn ((i32)) u32))) void
(colour colour-fn)) void
(var inner int (- (. m size) (. m pad-tl) (. m pad-br)))
(if (<= inner 0)
(return))
@@ -51,9 +50,7 @@
(var province image (image/make w h))
(var ocean image (image/make w h))
(var upheaval image (image/make w h))
;; TODO sex#50: write MAX-STRATA once constants in array types are
;; kebab-converted.
(var strata [image MAX_STRATA])
(var strata [image MAX-STRATA])
(var strata-count int 0)
(var m region-maps)
@@ -131,14 +128,8 @@
(if (. m has-river-distance)
(do
(var d int [(. m river-distance) i])
;; TODO sex#54: pass the colour as an (if ...) argument to
;; .set once #line no longer splits it.
(var c u32 (grey (- 255 d)))
;; TODO sex#47: write the colours in hex once there are
;; hex literals.
(if (== d 0) (= c 4219071))
(.set (& river) x y c))
(.set (& river) x y 2105376)))))
(.set (& river) x y (if (== d 0) 0x4060BF (grey (- 255 d)))))
(.set (& river) x y 0x202020)))))
(write-image (& height) dir "height")
(write-image (& rock) dir "toprock")

View File

@@ -9,30 +9,36 @@
(pub include pthread.h)
(include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(import noise)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(pub import worldgen)
(pub import rivers)
(import terra)
(import strata)
(pub import ores)
(import caves)
(pub record hover-query ((x int) (z int) (mode int) (value int)))
;;; The most cave runs a column's answer lists.
(pub define MAX-CAVE-RUNS 4)
;;; MINERAL is the mineral whose reading is wanted, or -1; CAVES whether
;;; the caves are.
(pub record hover-query ((x int) (z int) (mode int) (value int) (mineral int) (caves bool)))
(pub record hover-result
((valid bool) (query hover-query)
(height int) (sea-level int)
;; rock index at the query's surface, depth or Y; -1 when the block
;; there is water or air, -2 below the mantle
;; there is water or air, -2 below the mantle. At any depth (mode
;; 3, the value a rock index), that rock and the Y of its topmost
;; block, or -3 when the column has none of it.
(rock int) (rock-y int) (surface-rock int)
(landform int) (province int) (climate int) (ocean int) (upheaval int)
(river-distance double) (bank double)))
(river-distance double) (bank double)
;; the pick's reading of the query's mineral, and its ore map's value
(mineral mineral-reading) (mineral-map double)
;; the column's caves, top down, when asked for
(cave-entrance bool) (cave-runs int) (cave-tops [int MAX-CAVE-RUNS])
(cave-bottoms [int MAX-CAVE-RUNS]) (cave-lava [bool MAX-CAVE-RUNS])))
(pub record hover-worker
((lock pthread-mutex-t) (wake pthread-cond-t) (thread pthread-t) (quit bool)
@@ -47,10 +53,16 @@
;;; The worker's generators and the region and plate it has at hand.
(record kit
((g (* worldgen)) (tr (* terra)) (rocks (* strata)) (generation int)
((g (* worldgen)) (tr (* terra)) (rocks (* strata)) (minerals (* ores)) (generation int)
(rx int) (rz int) (maps [int-map 5]) (has-region bool)
;; the ore map last asked for: its mineral and region
(ore-map int-map) (ore-mineral int) (ore-rx int) (ore-rz int)
(plate (* river-plate)) (segments (* int)) (sampler river-sampler)
(column (* u8))))
(column (* u8))
;; the chunk last carved for caves: its heights before and after, and
;; its blocks' states
(caves (* caves)) (cave-cx int) (cave-cz int) (has-cave-chunk bool) (cave-states (* u8))
(cave-before [int 1024]) (cave-after [int 1024]) (cave-solid (* u32))))
(var region-kinds [int 5] #(0 2 1 4 3))
@@ -59,6 +71,11 @@
(for (var i int 0) (< i 5) (++ i)
(free (. [(. k maps) i] data))))
(if (. k plate) (river-plate/free (. k plate)))
(free (. k ore-map data))
(if (. k minerals) (ores/free (. k minerals)))
(if (. k caves) (caves/free (. k caves)))
(free (. k cave-states))
(free (. k cave-solid))
(if (. k rocks) (strata/free (. k rocks)))
(if (. k tr) (terra/free (. k tr)))
(if (. k g) (worldgen/free (. k g)))
@@ -108,6 +125,50 @@
(= (. r sea-level) (. (. k tr) sea-level))
(strata/column (. k rocks) (/ x 32) (/ z 32) (% x 32) (% z 32) h (. k column))
(= (. r surface-rock) [(. k column) h])
(if (&& (. q caves) (. k caves))
(do
(var cx int (/ x 32))
(var cz int (/ z 32))
(if (|| (! (. k has-cave-chunk)) (!= (. k cave-cx) cx) (!= (. k cave-cz) cz))
(do
(var heights [u16 1024])
(terra/chunk-solidity (. k tr) cx cz heights (. k cave-solid))
(for (var i int 0) (< i 1024) (++ i)
(= [(. k cave-before) i] [heights i])
(= [(. k cave-after) i] [heights i]))
(caves/carve-column (. k caves) cx cz (. k cave-after) (. k cave-solid)
(terra/solid-words (. k tr)) (. k cave-states))
(= (. k cave-cx) cx)
(= (. k cave-cz) cz)
(= (. k has-cave-chunk) true)))
(var i int (+ (* (% z 32) 32) (% x 32)))
(= (. r cave-entrance) (< [(. k cave-after) i] [(. k cave-before) i]))
(= (. r cave-runs) (caves/runs (. k caves) (. k cave-states) (% x 32) (% z 32)
[(. k cave-before) i] (. r cave-tops) (. r cave-bottoms)
(. r cave-lava) MAX-CAVE-RUNS))))
(if (&& (. k minerals) (>= (. q mineral) 0) (< (. q mineral) (. (. k minerals) count)))
(do
(if (|| (! (. k ore-map data)) (!= (. k ore-mineral) (. q mineral)) (!= (. k ore-rx) rx)
(!= (. k ore-rz) rz))
(do
(free (. k ore-map data))
(ores/map (. k minerals) (. q mineral) rx rz (& (. k ore-map)))
(= (. k ore-mineral) (. q mineral))
(= (. k ore-rx) rx)
(= (. k ore-rz) rz)))
(= (. r mineral) (ores/reading (. k minerals) (. q mineral) (& (. k ore-map)) x z (. k column) h))
(= (. r mineral-map) (ores/map-factor (& (. k ore-map)) x z))))
(if (== (. q mode) 3)
(do
(= (. r rock) -3)
(for (var y int h) (>= y 1) (-- y)
(if (== [(. k column) y] (. q value))
(do
(= (. r rock) (. q value))
(= (. r rock-y) y)
(break))))
(= (. r valid) true)
(return)))
(var y int h)
(if (== (. q mode) 1) (= y (- h (. q value)))
(== (. q mode) 2) (= y (. q value)))
@@ -143,6 +204,10 @@
(do
(= (. k tr) (terra/make (. k g) (. w rivers)))
(= (. k rocks) (strata/make (. k g) (. w assets-dir)))
(= (. k minerals) (ores/make settings (. w assets-dir) (. k rocks)))
(= (. k caves) (caves/make (. k g)))
(= (. k cave-states) (malloc (* 1024 (. settings size-y))))
(= (. k cave-solid) (malloc (* 1024 (terra/solid-words (. k tr)) (sizeof u32))))
(= (. k sampler) (river-sampler/make (& (. w rivers)) (. settings size-y)))
(= (. k column) (malloc (+ (. settings size-y) 1)))))
(= (. k generation) generation)))
@@ -180,7 +245,9 @@
(pub fn hover-worker/ask ((w (* hover-worker)) (q hover-query)) void
(pthread-mutex-lock (& (. w lock)))
(if (|| (!= (. w query x) (. q x)) (!= (. w query z) (. q z)) (!= (. w query mode) (. q mode))
(!= (. w query value) (. q value)) (! (. w result valid)))
(!= (. w query value) (. q value)) (!= (. w query mineral) (. q mineral))
(!= (. w query caves) (. q caves))
(! (. w result valid)))
(do
(= (. w query) q)
(= (. w pending) true)

View File

@@ -27,12 +27,10 @@
;;; A distinct, stable colour per small integer: landform and province
;;; indices, block ids.
(pub fn palette ((i u32)) u32
;; TODO sex#47: write the multiplier (0x9E3779B1) and masks in hex
;; once there are hex literals.
(var h u32 (* (+ i 1) (cast 2654435761 u32)))
(return (c-bit-or (<< (+ 48 (& (>> h 24) 191)) 16)
(<< (+ 48 (& (>> h 16) 191)) 8)
(+ 48 (& (>> h 8) 191)))))
(var h u32 (* (+ i 1) (cast 0x9E3779B1 u32)))
(return (c-bit-or (<< (+ 48 (& (>> h 24) 0xBF)) 16)
(<< (+ 48 (& (>> h 16) 0xBF)) 8)
(+ 48 (& (>> h 8) 0xBF)))))
(pub fn grey ((v int)) u32
(if (< v 0) (= v 0))

View File

@@ -6,12 +6,11 @@
(pub include "cJSON.h")
(include stdio.h stdlib.h string.h ctype.h)
;; TODO sex#49: rename to ident-start? once ? is mangled in names.
(fn ident-start-char ((c char)) bool
(fn ident-start? ((c char)) bool
(return (|| (isalpha (cast c u8)) (== c #\_) (== c #\$))))
(fn ident-char ((c char)) bool
(return (|| (ident-start-char c) (isdigit (cast c u8)))))
(fn ident-char? ((c char)) bool
(return (|| (ident-start? c) (isdigit (cast c u8)))))
;;; Drops a comma that was the last thing written before a closing
;;; bracket: `[1, 2, ]' -> `[1, 2 ]'.
@@ -58,10 +57,10 @@
(do
(= n (drop-trailing-comma out n))
(= [out n] c) (+= n 1) (+= p 1))
(ident-start-char c)
(ident-start? c)
(do
(var start (* const char) p)
(while (ident-char (* p))
(while (ident-char? (* p))
(+= p 1))
(var len size-t (cast (- p start) size-t))
(var bare bool (|| (&& (== len 4) (|| (== (strncmp start "true" 4) 0)

View File

@@ -62,6 +62,12 @@
(pub fn next-float ((self (* lcg))) float
(return (/ (cast (.next-bits self) float) (cast INT32_MAX float))))
;; NextFloatMinusToPlusOne: -1 to 1, most likely near 0, the
;; difference of two numbers below 46341 that one draw holds.
(pub fn next-float-minus-to-plus-one ((self (* lcg))) float
(var r int (.next-bits self))
(return (/ (cast (- (% r 46341) (/ r 46341)) float) (cast 46340 float))))
(pub fn next-double ((self (* lcg))) double
(var r u32 (cast (>> (cast (. self current) i64) 24) u32))
(.advance self)

View File

@@ -10,11 +10,9 @@
;;; (size - pad-tl - pad-br) square.
(pub record int-map ((data (* i32)) (size i32) (pad-tl i32) (pad-br i32)))
;; TODO sex#50: write MAX-STRATA once constants in array types are
;; kebab-converted.
(pub record region-maps
((landform int-map) (climate int-map) (geoprov int-map) (upheaval int-map)
(ocean int-map) (strata [int-map MAX_STRATA]) (strata-count int)))
(ocean int-map) (strata [int-map MAX-STRATA]) (strata-count int)))
(pub fn region-maps/free ((m (* region-maps))) void
(free (. m landform data))

View File

@@ -7,16 +7,14 @@
(pub include stdint.h)
(include stdlib.h math.h)
;;; The C# folds these at compile time; written as divisions here they
;;; would be unparenthesized macros and round differently in context.
;; TODO sex#55: write the divisions, e.g. (/ -1.0 6.0), once define
;; bodies are translated and parenthesized.
;;; As the C# writes them. Its divisions are folded at compile time,
;;; and C's are too, to the same doubles.
(define STRETCH-2D -0.211324865405187)
(define SQUISH-2D 0.366025403784439)
(define STRETCH-3D -0.16666666666666666)
(define SQUISH-3D 0.3333333333333333)
(define NORM-2D 0.02127659574468085)
(define NORM-3D 0.009708737864077669)
(define STRETCH-3D (/ -1.0 6.0))
(define SQUISH-3D (/ 1.0 3.0))
(define NORM-2D (/ 1.0 47.0))
(define NORM-3D (/ 1.0 103.0))
(define NORM-2D-WARP 0.020435461373899677)
(pub define MAX-VALUE-3D 0.9871465422297019)
(define VALUE-MULTIPLIER 1.2)
@@ -250,12 +248,10 @@
;;; NormalizedSimplexNoise. Octave i samples at frequencies[i] and is
;;; weighted so the sum stays in a known range before tanh.
;; TODO sex#50: write MAX-OCTAVES once constants in array types are
;; kebab-converted.
(pub record simplex-noise
((count int) (frequencies [double MAX_OCTAVES]) (amplitudes [double MAX_OCTAVES])
(scaled-2d [double MAX_OCTAVES]) (scaled-3d [double MAX_OCTAVES])
(octaves [simplex-octave MAX_OCTAVES])))
((count int) (frequencies [double MAX-OCTAVES]) (amplitudes [double MAX-OCTAVES])
(scaled-2d [double MAX-OCTAVES]) (scaled-3d [double MAX-OCTAVES])
(octaves [simplex-octave MAX-OCTAVES])))
(ops simplex-noise
(pub fn make ((amplitudes (* const double)) (frequencies (* const double)) (count int)
@@ -280,10 +276,8 @@
;; PERSISTENCE^i.
(pub fn octaves ((count int) (base-frequency double) (persistence double) (seed i64))
(* simplex-noise)
;; TODO sex#50: write MAX-OCTAVES once constants in array types are
;; kebab-converted.
(var frequencies [double MAX_OCTAVES])
(var amplitudes [double MAX_OCTAVES])
(var frequencies [double MAX-OCTAVES])
(var amplitudes [double MAX-OCTAVES])
(for (var i int 0) (< i count) (++ i)
(= [frequencies i] (* (pow 2 i) base-frequency))
(= [amplitudes i] (pow persistence i)))
@@ -307,11 +301,9 @@
;;; SimplexNoise: plain octave sums, no normalising and no tanh. The
;;; rock strata thickness maps and the strata distortion use it.
;; TODO sex#50: write MAX-OCTAVES once constants in array types are
;; kebab-converted.
(pub record simplex-sum
((count int) (frequencies [double MAX_OCTAVES]) (amplitudes [double MAX_OCTAVES])
(octaves [simplex-octave MAX_OCTAVES])))
((count int) (frequencies [double MAX-OCTAVES]) (amplitudes [double MAX-OCTAVES])
(octaves [simplex-octave MAX-OCTAVES])))
(ops simplex-sum
(pub fn make ((amplitudes (* const double)) (frequencies (* const double)) (count int)

552
src/ores.sex Normal file
View File

@@ -0,0 +1,552 @@
;;; Ore deposits as the prospecting pick's density mode sees them: per
;;; mineral, the region ore map GenDeposits makes, and the reading the
;;; pick gives for a column.
;;;
;;; A reading is the ore map's value there times the share of the
;;; column that is the mineral's host rock within the Y range its
;;; deposits are placed in (DiscDepositGenerator.GetPropickReading).
;;; It says how likely ore is near, not where the ore blocks are.
;;;
;;; Two things the game folds into a reading are left out:
;;; - The game draws a deposit's Y range from 100 random samples each
;;; time, from an RNG whose state depends on what ran before. The
;;; limits of the distribution are taken instead, so a range can be
;;; a block or two wider than the game's.
;;; - The pick's column includes the deposits generated in its own
;;; chunk. Those are not generated here, so a column is all host rock
;;; where the game may already have put ore in some of it. And a
;;; child deposit (silver, gold, and peridot, whose reading comes from
;;; the peridot inside olivine) is hosted by its parent's ore, so it
;;; can't be read at all without the deposits. For those, only the
;;; ore map is shown.
(include stdio.h stdlib.h string.h math.h dirent.h)
(import cs)
(import maps)
(pub import lcg)
(import noise)
(import shape)
(import json)
(pub import worldgen)
(import terra)
(import strata)
(pub define MAX-MINERALS 48)
(define MAX-DEPOSIT-FILES 64)
;;; TerraGenConfig: ore map pixels per region side, and the scales of
;;; the ore noise and its wobble.
(define ORE-MAP-SIZE 32)
(define ORE-SUB-SCALE 16)
(define ORE-WOBBLE-SCALE 110)
;;; The reading's categories, as the pick words them: none, miniscule
;;; amounts, then very poor up to ultra high.
(pub define READING-CATEGORIES 8)
;;; Where a deposit generator puts its deposits, for the reading's Y
;;; range.
(define PLACE-NONE 0)
(define PLACE-FOLLOW-SURFACE 1)
(define PLACE-FOLLOW-SEALEVEL 2)
(define PLACE-FOLLOW-SURFACE-BELOW 3)
;;; NatFloat, with the distributions the deposits use.
(define DIST-UNIFORM 0)
(define DIST-GAUSSIAN 1)
(define DIST-INVEXP 2)
(define DIST-STRONGINVEXP 3)
(define DIST-TRIANGLE 4)
(define DIST-NARROWGAUSSIAN 5)
(define DIST-STRONGERINVEXP 6)
;;; pub because a mineral holds one, and its importers need the size
(pub record natfloat ((dist int) (avg float) (var float)))
;;; A mineral is one code with an ore map. Its map is made with the
;;; parameters of the first deposit that asks for it; its reading comes
;;; from the last deposit with that code, as in ProPickWorkSpace.
(pub record mineral
((code [char 32])
;; the ore map: NoiseOre, MapLayerOre and MapLayerPerlinWobble
(noise lcg) (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))
(scale float) (contrast float) (sub float)
;; the reading
(readable bool) (place int) (y natfloat) (abs-avg double) (bearing u32)))
(pub record ores
((minerals [mineral MAX-MINERALS]) (count int) (granite int) (sea-level int)))
;;; The reading at one column: TotalFactor and PartsPerThousand.
(pub record mineral-reading ((total double) (ppt double)))
;;; NatFloat ---------------------------------------------------------
(var dist-names [(* const char) 7]
#("uniform" "gaussian" "invexp" "stronginvexp" "triangle" "narrowgaussian" "strongerinvexp"))
(fn read-natfloat ((o (* cJSON))) natfloat
(var n natfloat #(natfloat : DIST-UNIFORM 0 0))
(if (! o)
(return n))
(var dist (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem o "dist")))
(for (var i int 0) (&& dist (< i 7)) (++ i)
(if (== (strcasecmp dist [dist-names i]) 0)
(= (. n dist) i)))
(= (. n avg) (cast (cJSON-GetNumberValue (cJSON-GetObjectItem o "avg")) float))
(= (. n var) (cast (cJSON-GetNumberValue (cJSON-GetObjectItem o "var")) float))
(if (isnan (. n avg)) (= (. n avg) 0))
(if (isnan (. n var)) (= (. n var) 0))
(return n))
;;; NatFloat.nextFloat(1, rand).
(fn natfloat-next ((n (* const natfloat)) (r (* lcg))) float
(var half float (cast 0.5 float))
(var two float (cast 2 float))
(var rnd float 0)
(switch (. n dist)
(case DIST-GAUSSIAN
(do
(var a float (.next-float r))
(var b float (.next-float r))
(var c float (.next-float r))
(= rnd (- (/ (+ a b c) (cast 3 float)) half)))
(return (+ (. n avg) (* rnd two (. n var)))))
(case DIST-NARROWGAUSSIAN
(do
(var sum float 0)
(for (var i int 0) (< i 6) (++ i)
(+= sum (.next-float r)))
(= rnd (- (/ sum (cast 6 float)) half)))
(return (+ (. n avg) (* rnd two (. n var)))))
(case DIST-INVEXP
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= rnd (* a b)))
(return (+ (. n avg) (* rnd (. n var)))))
(case DIST-STRONGINVEXP
(do
(var a float (.next-float r))
(var b float (.next-float r))
(var c float (.next-float r))
(= rnd (* a b c)))
(return (+ (. n avg) (* rnd (. n var)))))
(case DIST-STRONGERINVEXP
(do
(var a float (.next-float r))
(var b float (.next-float r))
(var c float (.next-float r))
(var d float (.next-float r))
(= rnd (* a b c d)))
(return (+ (. n avg) (* rnd (. n var)))))
(case DIST-TRIANGLE
(do
(var a float (.next-float r))
(var b float (.next-float r))
(= rnd (- (/ (+ a b) two) half)))
(return (+ (. n avg) (* rnd two (. n var)))))
(default
(= rnd (- (.next-float r) half))
(return (+ (. n avg) (* rnd two (. n var)))))))
;;; The least and greatest values the distribution gives.
(fn natfloat-min ((n (* const natfloat))) float
(if (|| (== (. n dist) DIST-INVEXP) (== (. n dist) DIST-STRONGINVEXP)
(== (. n dist) DIST-STRONGERINVEXP))
(return (fminf (. n avg) (+ (. n avg) (. n var)))))
(return (fminf (- (. n avg) (. n var)) (+ (. n avg) (. n var)))))
(fn natfloat-max ((n (* const natfloat))) float
(if (|| (== (. n dist) DIST-INVEXP) (== (. n dist) DIST-STRONGINVEXP)
(== (. n dist) DIST-STRONGERINVEXP))
(return (fmaxf (. n avg) (+ (. n avg) (. n var)))))
(return (fmaxf (- (. n avg) (. n var)) (+ (. n avg) (. n var)))))
;;; Deposits ---------------------------------------------------------
(fn find-mineral ((o (* ores)) (code (* const char))) int
(for (var i int 0) (< i (. o count)) (++ i)
(if (== (strcmp (. [(. o minerals) i] code) code) 0)
(return i)))
(return -1))
(fn json-float ((o (* cJSON)) (key (* const char)) (fallback float)) float
(var v (* cJSON) (cJSON-GetObjectItem o key))
(if (cJSON-IsNumber v)
(return (cast (cJSON-GetNumberValue v) float)))
(return fallback))
;;; GenDeposits.getOrCreateMapLayer: the map for CODE, with the
;;; parameters of the deposit that asks first. Seeds are C# ints, so
;;; their sums wrap.
(fn add-map ((o (* ores)) (seed i32) (code (* const char)) (params (* cJSON))) void
(if (|| (>= (find-mineral o code) 0) (>= (. o count) MAX-MINERALS))
(return))
(var m (* mineral) (& [(. o minerals) (. o count)]))
(memset m 0 (sizeof mineral))
(snprintf (. m code) (sizeof (. m code)) "%s" code)
(var hash u32 (cast (nonrandomized-string-hash code) u32))
(var noise-seed i32 (cast (+ (cast seed u32) hash) i32))
(var map-seed i32 (cast (+ (cast seed u32) hash 1) i32))
(= (. m noise) (lcg/make noise-seed))
(var wobble-seed i64 (+ (cast map-seed i64) 2))
(var frequency float (/ (cast 1 float) (cast ORE-WOBBLE-SCALE float)))
(= (. m wobble-x) (simplex-noise/octaves 5 frequency (cast 0.85 float) wobble-seed))
(= (. m wobble-z) (simplex-noise/octaves 5 frequency (cast 0.85 float) (+ wobble-seed 1231296)))
(= (. m scale) (* (cast ORE-SUB-SCALE float) (json-float params "oreMapScale" 1)))
(= (. m contrast) (json-float params "oreMapContrast" 1))
(= (. m sub) (json-float params "oreMapSub" 0))
(++ (. o count)))
;;; Whether rock CODE is one INBLOCK's code and allowedVariants take.
(fn in-block-matches ((inblock (* cJSON)) (code (* const char))) bool
(var pattern (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem inblock "code")))
(if (! pattern)
(return false))
(var star (* const char) (strchr pattern #\*))
(if (! star)
(return (== (strcmp pattern code) 0)))
(var prefix size-t (cast (- star pattern) size-t))
(if (!= (strncmp pattern code prefix) 0)
(return false))
(var allowed (* cJSON) (cJSON-GetObjectItem inblock "allowedVariants"))
(if (! allowed)
(return true))
(for (var v (* cJSON) (. allowed child)) v (= v (. v next))
(var s (* const char) (cJSON-GetStringValue v))
(if (&& s (== (strcmp s (+ code prefix)) 0))
(return true)))
(return false))
;;; DiscDepositGenerator.GetAbsAvgQuantity with a fresh LCGRandom of
;;; the world seed, as Init calls it.
(fn abs-avg-quantity ((seed i32) (radius (* const natfloat)) (thickness (* const natfloat))
(tries float)) double
(var r lcg (lcg/make seed))
(var rs float 0)
(var ts float 0)
(for (var j int 0) (< j 100) (++ j)
(+= rs (natfloat-next radius (& r)))
(+= ts (natfloat-next thickness (& r))))
(/= rs (cast 100 float))
(/= ts (cast 100 float))
(var pi float (cast M-PI float))
(return (* ts rs rs pi tries)))
;;; The reading for CODE now comes from deposit V; a child deposit,
;;; hosted by its parent's ore, can't be read.
(fn set-reading ((o (* ores)) (v (* cJSON)) (child bool) (seed i32) (rocks (* const strata))) void
(var i int (find-mineral o (cJSON-GetStringValue (cJSON-GetObjectItem v "code"))))
(if (< i 0)
(return))
(var m (* mineral) (& [(. o minerals) i]))
(= (. m readable) false)
(= (. m place) PLACE-NONE)
(var gen (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem v "generator")))
(var attributes (* cJSON) (cJSON-GetObjectItem v "attributes"))
(if (|| child (! gen) (! attributes))
(return))
(if (== (strcmp gen "disc-followsurface") 0)
(do
(= (. m place) PLACE-FOLLOW-SURFACE)
(= (. m y) (read-natfloat (cJSON-GetObjectItem attributes "yPosRel"))))
(== (strcmp gen "disc-followsealevel") 0)
(do
(= (. m place) PLACE-FOLLOW-SEALEVEL)
(= (. m y) (read-natfloat (cJSON-GetObjectItem attributes "yPosRel")))
;; FollowSealevelDiscGenerator.Init
(*= (. m y avg) (cast (. o sea-level) float))
(*= (. m y var) (cast (. o sea-level) float)))
(== (strcmp gen "disc-followsurfacebelow") 0)
(do
(= (. m place) PLACE-FOLLOW-SURFACE-BELOW)
(= (. m y) (read-natfloat (cJSON-GetObjectItem attributes "depth"))))
(return))
(var radius natfloat (read-natfloat (cJSON-GetObjectItem attributes "radius")))
(if (! (cJSON-GetObjectItem attributes "radius"))
(= radius #(natfloat : DIST-UNIFORM 10 0)))
(var thickness natfloat (read-natfloat (cJSON-GetObjectItem attributes "thickness")))
(= (. m abs-avg) (abs-avg-quantity seed (& radius) (& thickness) (json-float v "triesPerChunk" 0)))
(var inblock (* cJSON) (cJSON-GetObjectItem attributes "inblock"))
(= (. m bearing) 0)
(for (var r int 0) (&& inblock (< r (. rocks rock-count)) (< r 32)) (++ r)
(if (in-block-matches inblock [(. rocks rock-codes) r])
(c-bit-or= (. m bearing) (<< (cast 1 u32) r))))
(= (. m readable) true))
(fn by-name ((pa (* const void)) (pb (* const void))) int
(var a (* * char) (cast pa (* * char)))
(var b (* * char) (cast pb (* * char)))
(return (strcmp (* a) (* b))))
;;; The JSON files under DIR, relative to ROOT, into PATHS.
(fn list-files ((root (* const char)) (dir (* const char)) (paths (* * char)) (n (* int))) void
(var full [char 1024])
(snprintf full (sizeof full) "%s/%s" root dir)
(var d (* DIR) (opendir full))
(if (! d)
(return))
(var ent (* struct dirent) NULL)
(while (&& (= ent (readdir d)) (< (* n) MAX-DEPOSIT-FILES))
(var name (* const char) (. ent d-name))
(if (== [name 0] #\.)
(continue))
(var rel [char 1024])
(if (* dir)
(snprintf rel (sizeof rel) "%s/%s" dir name)
(snprintf rel (sizeof rel) "%s" name))
(var len size-t (strlen name))
(if (== (. ent d-type) DT-DIR)
(list-files root rel paths n)
(&& (> len 5) (== (strcmp (+ name (- len 5)) ".json") 0))
(do
(= [paths (* n)] (strdup rel))
(++ (* n)))))
(closedir d))
;;; GenDeposits.initAssets and initWorldGen, and ProPickWorkSpace's
;;; depositsByCode: deposits/*.json in path order, each file's
;;; variants in order, children after their parent.
(pub fn ores/make ((settings world-settings) (assets-dir (* const char)) (rocks (* const strata)))
(* ores)
(var o (* ores) (calloc 1 (sizeof ores)))
(= (. o granite) (. rocks granite))
(= (. o sea-level) (cast (* 0.4313725490196078 (. settings size-y)) int))
(var root [char 1024])
(snprintf root (sizeof root) "%s/survival/worldgen/deposits" assets-dir)
(var paths [* char MAX-DEPOSIT-FILES])
(var n int 0)
(list-files root "" paths (& n))
(qsort paths n (sizeof [paths 0]) by-name)
(var files [* cJSON MAX-DEPOSIT-FILES])
(for (var f int 0) (< f n) (++ f)
(var path [char 1024])
(snprintf path (sizeof path) "%s/%s" root [paths f])
(= [files f] (json-load path))
(free [paths f]))
(var seed i32 (. settings seed))
;; the maps, first come first served
(for (var f int 0) (< f n) (++ f)
(for (var v (* cJSON) (if [files f] (. [files f] child) NULL)) v (= v (. v next))
(if (cJSON-IsTrue (cJSON-GetObjectItem v "withOreMap"))
(add-map o seed (cJSON-GetStringValue (cJSON-GetObjectItem v "code")) v))
(var children (* cJSON) (cJSON-GetObjectItem v "childDeposits"))
(for (var c (* cJSON) (if children (. children child) NULL)) c (= c (. c next))
;; a child's map takes its parent's parameters
(if (cJSON-IsTrue (cJSON-GetObjectItem c "withOreMap"))
(add-map o seed (cJSON-GetStringValue (cJSON-GetObjectItem c "code")) v)))))
;; the readings, last come last served
(for (var f int 0) (< f n) (++ f)
(for (var v (* cJSON) (if [files f] (. [files f] child) NULL)) v (= v (. v next))
(if (cJSON-IsTrue (cJSON-GetObjectItem v "withOreMap"))
(set-reading o v false seed rocks))
(var children (* cJSON) (cJSON-GetObjectItem v "childDeposits"))
(for (var c (* cJSON) (if children (. children child) NULL)) c (= c (. c next))
(if (cJSON-IsTrue (cJSON-GetObjectItem c "withOreMap"))
(set-reading o c true seed rocks)))))
(for (var f int 0) (< f n) (++ f)
(if [files f] (cJSON-Delete [files f])))
(return o))
(pub fn ores/free ((o (* ores))) void
(for (var i int 0) (< i (. o count)) (++ i)
(free (. [(. o minerals) i] wobble-x))
(free (. [(. o minerals) i] wobble-z)))
(free o))
(pub fn ores/find ((o (* const ores)) (code (* const char))) int
(for (var i int 0) (< i (. o count)) (++ i)
(if (== (strcmp (. [(. o minerals) i] code) code) 0)
(return i)))
(return -1))
;;; Ore maps ---------------------------------------------------------
(fn smooth-step ((x float)) float
(return (* x x (- (cast 3 float) (* (cast 2 float) x)))))
(fn lerp-byte ((t float) (a int) (b int)) int
(return (cast (cast (+ (* (- (cast 1 float) t) (cast a float)) (* t (cast b float))) int) u8)))
;;; NoiseOre.GetRandomOre: density in the low byte, hyper-rich at 256,
;;; quality at 1024 and 2048.
(fn random-ore ((r (* lcg))) int
(var rnd int (.next-int r 1024))
(var quality int 0)
(if (> (.next-int r 2) 0)
(= quality 1)
(if (> (.next-int r 50) 15) (= quality 0) (= quality 2)))
(= quality (<< quality 10))
(if (< rnd 1) (return (c-bit-or quality 256 255)))
(if (< rnd 30) (return (c-bit-or quality 255)))
(if (< rnd 105) (return (c-bit-or quality (+ 75 (.next-int r 100)))))
(if (< rnd 190) (return (c-bit-or quality (+ 20 (.next-int r 20)))))
(return 0))
(fn max4 ((a int) (b int) (c int) (d int) (mask int)) int
(var m int (& a mask))
(if (> (& b mask) m) (= m (& b mask)))
(if (> (& c mask) m) (= m (& c mask)))
(if (> (& d mask) m) (= m (& d mask)))
(return m))
;;; NoiseOre.GetLerpedOreValueAt.
(fn lerped-ore ((x double) (z double) (cache (* const int)) (w int) (contrast float)
(sub float)) int
(var xi int (cast x int))
(var zi int (cast z int))
(var lt int [cache (+ (* zi w) xi)])
(var rt int [cache (+ (* zi w) xi 1)])
(var lb int [cache (+ (* (+ zi 1) w) xi)])
(var rb int [cache (+ (* (+ zi 1) w) xi 1)])
(var fx float (smooth-step (cast (- x xi) float)))
(var fz float (smooth-step (cast (- z zi) float)))
(var top int (lerp-byte fx (& lt 255) (& rt 255)))
(var bottom int (lerp-byte fx (& lb 255) (& rb 255)))
(var v float (cast (lerp-byte fz top bottom) float))
(var c float (- (+ (* (- v (cast 128 float)) contrast) (cast 128 float)) sub))
(if (< c (cast 0 float)) (= c 0))
(if (> c (cast 255 float)) (= c 255))
(var val int (cast (cast c int) u8))
(if (== val 0)
(return 0))
(return (c-bit-or val (max4 lt rt lb rb 0xFF0000) (max4 lt rt lb rb 0xFF00))))
;;; MapLayerOre.GenLayer.
(fn gen-unwobbled ((m (* const mineral)) (x0 int) (z0 int) (size-x int) (size-z int)
(out (* int))) void
(var noise lcg (. m noise))
(var scale float (. m scale))
(var cache-w int (+ (cast (ceil (cast (/ (cast size-x float) scale) double)) int) 1))
(var cache-h int (+ (cast (ceil (cast (/ (cast size-z float) scale) double)) int) 1))
(var cx int (cast (/ (cast x0 float) scale) int))
(var cz int (cast (/ (cast z0 float) scale) int))
(var cache (* int) (malloc (* cache-w cache-h (sizeof int))))
(for (var x int 0) (< x cache-w) (++ x)
(for (var z int 0) (< z cache-h) (++ z)
(.init-position (& noise) (+ cx x) (+ cz z))
(= [cache (+ (* z cache-w) x)] (random-ore (& noise)))))
(for (var x int 0) (< x size-x) (++ x)
(for (var z int 0) (< z size-z) (++ z)
(= [out (+ (* z size-x) x)]
(lerped-ore (/ x (cast scale double)) (/ z (cast scale double)) cache cache-w
(. m contrast) (. m sub)))))
(free cache))
;;; MapLayerPerlinWobble over MapLayerOre, for region (rx, rz): the map
;;; DepositVariant.OnMapRegionGen stores, 33 pixels a side with one of
;;; padding at the bottom right.
(pub fn ores/map ((o (* const ores)) (i int) (rx int) (rz int) (out (* int-map))) void
(var m (* const mineral) (& [(. o minerals) i]))
(var size int (+ ORE-MAP-SIZE 1))
(var x0 int (* rx ORE-MAP-SIZE))
(var z0 int (* rz ORE-MAP-SIZE))
(var intensity float (* (cast ORE-WOBBLE-SCALE float) (cast 0.15 float)))
(var margin int (cast (ceil (cast intensity double)) int))
(var pw int (+ size (* 2 margin)))
(var in (* int) (malloc (* pw pw (sizeof int))))
(gen-unwobbled m (- x0 margin) (- z0 margin) pw pw in)
(= (. out size) size)
(= (. out pad-tl) 0)
(= (. out pad-br) 1)
(= (. out data) (malloc (* size size (sizeof i32))))
(for (var y int 0) (< y size) (++ y)
(for (var x int 0) (< x size) (++ x)
(var nx double (+ x0 x margin))
(var nz double (+ z0 y margin))
(var ox int (cast (* intensity (.noise-2d (. m wobble-x) nx nz)) int))
(var oz int (cast (* intensity (.noise-2d (. m wobble-z) nx nz)) int))
(var sx int (% (+ (% (+ x ox (/ margin 2)) pw) pw) pw))
(var sz int (% (+ (% (+ y oz (/ margin 2)) pw) pw) pw))
(= [(. out data) (+ (* y size) x)] [in (+ (* sz pw) sx)])))
(free in))
;;; Readings ---------------------------------------------------------
;;; The ore map's value at column (x, z), 0 to 1: the low byte of
;;; IntDataMap2D.GetUnpaddedColorLerped over 255.
(pub fn ores/map-factor ((map (* const int-map)) (x int) (z int)) double
(var inner int (- (. map size) (. map pad-tl) (. map pad-br)))
(var px float (* (/ (cast (% x 512) float) (cast 512 float)) (cast inner float)))
(var pz float (* (/ (cast (% z 512) float) (cast 512 float)) (cast inner float)))
(var ix int (cast px int))
(var iz int (cast pz int))
(var fx float (- px (cast ix float)))
(var fz float (- pz (cast iz float)))
(var i int (+ (* (+ iz (. map pad-tl)) (. map size)) ix (. map pad-tl)))
(var lt float (cast (& [(. map data) i] 255) float))
(var rt float (cast (& [(. map data) (+ i 1)] 255) float))
(var lb float (cast (& [(. map data) (+ i (. map size))] 255) float))
(var rb float (cast (& [(. map data) (+ i (. map size) 1)] 255) float))
(var top float (+ lt (* (- rt lt) fx)))
(var bottom float (+ lb (* (- rb lb) fx)))
(var v int (& (cast (+ top (* (- bottom top) fz)) int) 255))
(return (/ v 255.0)))
;;; The pick's reading of mineral I at column (x, z): MAP is the
;;; mineral's ore map of the column's region, COLUMN the column's
;;; strata up to its surface at HEIGHT.
(pub fn ores/reading ((o (* const ores)) (i int) (map (* const int-map)) (x int) (z int)
(column (* const u8)) (height int)) mineral-reading
(var r mineral-reading #(mineral-reading : 0 0))
(var m (* const mineral) (& [(. o minerals) i]))
(if (|| (! (. m readable)) (< height 1))
(return r))
;; GetYMinMax
(var miny double 0)
(var maxy double 0)
(if (== (. m place) PLACE-FOLLOW-SURFACE)
(do
(= miny (* (natfloat-min (& (. m y))) (cast height float)))
(= maxy height))
(== (. m place) PLACE-FOLLOW-SEALEVEL)
(do
(= miny (natfloat-min (& (. m y))))
(= maxy (natfloat-max (& (. m y)))))
(do
(= miny (- height (natfloat-max (& (. m y)))))
(= maxy height)))
;; oreBearingBlockQuantityRelative over the pick's column, y below
;; the surface; it has the default rock at y = 0, not the mantle
(var q int 0)
(for (var y int 0) (< y height) (++ y)
(if (|| (< y miny) (> y maxy))
(continue))
(var rock int (if (== y 0) (. o granite) [column y]))
(if (&& (< rock 32) (!= (& (. m bearing) (<< (cast 1 u32) rock)) 0))
(++ q)))
(var rock-factor double (/ (cast q double) height))
(= (. r total) (* (ores/map-factor map x z) rock-factor))
(var blocks int (* height 1024))
(= (. r ppt) (* (/ (* (. r total) (. m abs-avg)) blocks) 1000))
(return r))
;;; The category the pick words a reading in: 0 nothing, 1 miniscule
;;; amounts, 2 very poor to 7 ultra high.
(pub fn ores/category ((total double)) int
(if (<= total 0.002)
(return 0))
(if (<= total 0.025)
(return 1))
(var k double (* total (cast 7.5 float)))
(if (> k 5) (= k 5))
(return (+ 2 (cast k int))))
;;; A band of the ore map's value, for a mineral the pick can't read:
;;; 0 where it is 0, then 1 to 7 by sevenths.
(pub fn ores/map-category ((factor double)) int
(if (<= factor 0)
(return 0))
(var k int (cast (* factor 7) int))
(if (> k 6) (= k 6))
(return (+ 1 k)))
;;; What the Minerals overlay shows for mineral I at a column, 0 to
;;; READING-CATEGORIES - 1: the pick's reading where it can read the
;;; mineral, else the ore map's band.
(pub fn ores/category-at ((o (* const ores)) (i int) (map (* const int-map)) (x int) (z int)
(column (* const u8)) (height int)) int
(if (. [(. o minerals) i] readable)
(return (ores/category (. (ores/reading o i map x z column height) total))))
(return (ores/map-category (ores/map-factor map x z))))

View File

@@ -8,51 +8,26 @@
(pub include stddef.h)
(include string.h)
;; TODO sex#46: make these a (pub enum wire ...) once explicit enum
;; values are kebab-converted.
(pub define WIRE-VARINT 0)
(pub define WIRE-FIXED64 1)
(pub define WIRE-BYTES 2)
(pub define WIRE-FIXED32 5)
(pub enum wire ((WIRE-VARINT 0) (WIRE-FIXED64 1) (WIRE-BYTES 2) (WIRE-FIXED32 5)))
(pub record pb ((p (* const u8)) (end (* const u8)) (err bool)))
;; TODO sex#44: the methods are ordered so each calls only those above
;; it; order them by topic once a method can call one below.
(ops pb
(pub fn of ((data (* const void)) (len size-t)) pb
(var p (* const u8) data)
(return #(pb : p (+ p len) false)))
(fn fail ((self (* pb))) void
(= (. self err) true)
(= (. self p) (. self end)))
(pub fn more ((self (* const pb))) bool
(return (< (. self p) (. self end))))
(pub fn len ((self (* const pb))) size-t
(return (cast (- (. self end) (. self p)) size-t)))
(pub fn varint ((self (* pb))) u64
(var v u64 0)
(for (var shift int 0) (< shift 64) (+= shift 7)
(if (>= (. self p) (. self end))
(break))
(var b u8 (* (. self p)))
(++ (. self p))
;; TODO sex#47: write the varint masks in hex once there are hex
;; literals.
(c-bit-or= v (<< (cast (& b 127) u64) shift))
(if (< b 128)
(return v)))
(.fail self)
(return 0))
;; A packed or repeated `int' field: negative values arrive as ten
;; byte varints and keep their meaning when truncated.
(pub fn int32 ((self (* pb))) i32
(return (cast (.varint self) i32)))
;; True when the rest of the window spells exactly S, e.g. a map
;; entry's key against "riverDistance".
(pub fn equals ((self (* const pb)) (s (* const char))) bool
(var n size-t (.len self))
(return (&& (== (strlen s) n) (== (memcmp (. self p) s n) 0))))
;; The next field's number, or 0 at the end. WIRE gets its wire type.
(pub fn field ((self (* pb)) (wire (* int))) u32
@@ -62,12 +37,29 @@
(= (* wire) (cast (& key 7) int))
(return (cast (>> key 3) u32)))
(pub fn varint ((self (* pb))) u64
(var v u64 0)
(for (var shift int 0) (< shift 64) (+= shift 7)
(if (>= (. self p) (. self end))
(break))
(var b u8 (* (. self p)))
(++ (. self p))
(c-bit-or= v (<< (cast (& b 0x7F) u64) shift))
(if (< b 0x80)
(return v)))
(.fail self)
(return 0))
;; A packed or repeated `int' field: negative values arrive as ten
;; byte varints and keep their meaning when truncated.
(pub fn int32 ((self (* pb))) i32
(return (cast (.varint self) i32)))
;; A length-delimited field as a reader of its own: a submessage, a
;; string, or a packed array.
(pub fn bytes ((self (* pb))) pb
(var len u64 (.varint self))
;; TODO sex#45: use (. self p) in the literals once member access
;; inside a compound literal follows the pointer.
;; where the window starts, before self moves past it
(var p (* const u8) (. self p))
(if (> len (.len self))
(do
@@ -76,21 +68,19 @@
(+= (. self p) len)
(return #(pb : p (+ p len) false)))
;; True when the rest of the window spells exactly S, e.g. a map
;; entry's key against "riverDistance".
(pub fn equals ((self (* const pb)) (s (* const char))) bool
(var n size-t (.len self))
(return (&& (== (strlen s) n) (== (memcmp (. self p) s n) 0))))
(fn advance ((self (* pb)) (n size-t)) void
(if (> n (.len self))
(.fail self)
(+= (. self p) n)))
(pub fn skip ((self (* pb)) (wire int)) void
(switch wire
(case WIRE-VARINT (.varint self) (break))
(case WIRE-BYTES (.bytes self) (break))
(case WIRE-FIXED64 (.advance self 8) (break))
(case WIRE-FIXED32 (.advance self 4) (break))
(default (.fail self)))))
(default (.fail self))))
(fn advance ((self (* pb)) (n size-t)) void
(if (> n (.len self))
(.fail self)
(+= (. self p) n)))
(fn fail ((self (* pb))) void
(= (. self err) true)
(= (. self p) (. self end))))

View File

@@ -10,16 +10,11 @@
;;; every RNG call is the mod's: it is what the layout depends on.
(include stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(import noise)
(pub import lcg)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(pub import fastnoise)
(pub record river-config
((min-fork-angle int) (fork-variation int) (normal-angle int)
@@ -151,11 +146,7 @@
(var dy double (- (. end y) (. start y)))
(var v double (+ (* (- (. p x) (. start x)) dx) (* (- (. p y) (. start y)) dy)))
(/= v (+ (* dx dx) (* dy dy)))
;; TODO sex#59: clamp inside the cast once a conditional operand
;; keeps its parentheses.
(if (< v 0) (= v 0))
(if (> v 1) (= v 1))
(return (cast v float)))
(return (cast (if (< v 0) 0 (if (> v 1) 1 v)) float)))
(fn distance-to-line ((p vec2) (s vec2) (e vec2)) double
(if (<= (+ (* (- (. s x) (. e x)) (- (. p x) (. e x))) (* (- (. s y) (. e y)) (- (. p y) (. e y)))) 0)
@@ -481,8 +472,7 @@
(var n int (. p config zones-in-region))
(var best-x int x)
(var best-z int z)
;; TODO sex#63: write -INFINITY once it reads as a negation.
(var best double (- INFINITY))
(var best double -INFINITY)
(var found bool false)
(for (var dx int -1) (<= dx 1) (++ dx)
(for (var dz int -1) (<= dz 1) (++ dz)

View File

@@ -7,7 +7,7 @@
;;; data itself, matched against the map sizes in TerraGenConfig.
(pub include sqlite3.h)
(include stdio.h stdlib.h string.h)
(include stdio.h stdlib.h string.h zstd.h)
(import pb)
(import maps)
@@ -15,24 +15,30 @@
(pub define REGION-SIZE 512)
(pub define CHUNK-SIZE 32)
(pub define CHUNK-AREA 1024)
(pub define CHUNK-VOLUME 32768)
(pub define MAX-STORIES 32)
;; TODO sex#50: write CHUNK-AREA once constants in array types are
;; kebab-converted.
(pub record chunk-maps
((terrain-height [u16 CHUNK_AREA]) (rain-height [u16 CHUNK_AREA])
(top-rock [i32 CHUNK_AREA]) (river-distance [u16 CHUNK_AREA])
((terrain-height [u16 CHUNK-AREA]) (rain-height [u16 CHUNK-AREA])
(top-rock [i32 CHUNK-AREA]) (river-distance [u16 CHUNK-AREA])
(has-river-distance bool)))
(pub record story-location ((code [char 64]) (x i32) (y i32) (z i32)))
;;; One mineral of a prospecting pick reading a player took: where,
;;; and the reading's TotalFactor and PartsPerThousand.
(pub record pick-reading ((x int) (y int) (z int) (code [char 32]) (total double) (ppt double)))
(pub record save
((db (* sqlite3)) (seed i32) (size-x i32) (size-y i32) (size-z i32)
(config-keys (* * char)) (config-values (* * char)) (config-count int)
(block-codes (* * char)) (block-count int)
;; TODO sex#50: write MAX-STORIES once constants in array types are
;; kebab-converted.
(stories [story-location MAX_STORIES]) (story-count int)))
(stories [story-location MAX-STORIES]) (story-count int)
;; every player's stored pick readings
(pick-readings (* pick-reading)) (pick-reading-count int)
;; SaveGame.DefaultSpawn, when the world has one: where the game counts
;; its coordinates from
(has-spawn bool) (spawn-x i32) (spawn-y i32) (spawn-z i32)))
;;; Map regions and map chunks share one key: x in the low 27 bits,
;;; z above them.
@@ -77,21 +83,17 @@
(switch type
(case 1 (snprintf value 64 "%d" (cast (read-le (& r) 4) i32)) (break))
(case 2 (snprintf value 64 "%lld" (cast (read-le (& r) 8) i64)) (break))
;; TODO sex#51: drop the (do ...) around case bodies once each
;; case gets its own scope.
(case 3
(do
(var bits u64 (read-le (& r) 8))
(var d double)
(memcpy (& d) (& bits) 8)
(snprintf value 64 "%.17g" d))
(var bits u64 (read-le (& r) 8))
(var d double)
(memcpy (& d) (& bits) 8)
(snprintf value 64 "%.17g" d)
(break))
(case 4
(do
(var bits u32 (cast (read-le (& r) 4) u32))
(var f float)
(memcpy (& f) (& bits) 4)
(snprintf value 64 "%.9g" (cast f double)))
(var bits u32 (cast (read-le (& r) 4) u32))
(var f float)
(memcpy (& f) (& bits) 4)
(snprintf value 64 "%.9g" (cast f double))
(break))
(case 5
(add-config s key (read-dotnet-string (& r)))
@@ -126,9 +128,7 @@
(if (> id max-id) (= max-id id)))
(.skip (& entry) wire))))
(= (. s block-count) (+ max-id 1))
;; TODO sex#52: write (sizeof (* char)) once sizeof takes a pointer
;; type.
(= (. s block-codes) (calloc (+ max-id 1) (sizeof [(. s block-codes) 0])))
(= (. s block-codes) (calloc (+ max-id 1) (sizeof (* char))))
(while (> (.field (& r) (& wire)) 0)
(var entry pb (.bytes (& r)))
(var id int -1)
@@ -172,6 +172,59 @@
(.skip (& body) wire))))
(++ (. s story-count))))
(fn read-double ((r (* pb))) double
(var bits u64 (read-le r 8))
(var d double)
(memcpy (& d) (& bits) 8)
(return d))
(fn add-pick-reading ((s (* save)) (reading pick-reading)) void
(var n int (. s pick-reading-count))
(= (. s pick-readings) (realloc (. s pick-readings) (* (+ n 1) (sizeof pick-reading))))
(= [(. s pick-readings) n] reading)
(= (. s pick-reading-count) (+ n 1)))
;;; oreMapMarkers-PLAYER: List<PropickReading>, entries {1: position
;;; {1: x, 2: y, 3: z}, 2: {1: code, 2: {2: total, 3: ppt}}*}.
(fn read-pick-readings ((s (* save)) (r pb)) void
(var wire int)
(while (> (.field (& r) (& wire)) 0)
(var body pb (.bytes (& r)))
(var at pick-reading)
(memset (& at) 0 (sizeof at))
(var f u32)
(while (> (= f (.field (& body) (& wire))) 0)
(if (== f 1)
(do
(var position pb (.bytes (& body)))
(var g u32)
(while (> (= g (.field (& position) (& wire))) 0)
(if (== g 1) (= (. at x) (cast (read-double (& position)) int))
(== g 2) (= (. at y) (cast (read-double (& position)) int))
(== g 3) (= (. at z) (cast (read-double (& position)) int))
(.skip (& position) wire))))
(== f 2)
(do
(var entry pb (.bytes (& body)))
(var reading pick-reading at)
(var g u32)
(while (> (= g (.field (& entry) (& wire))) 0)
(if (== g 1)
(do
(var code pb (.bytes (& entry)))
(snprintf (. reading code) 32 "%.*s" (cast (.len code) int) (. code p)))
(== g 2)
(do
(var value pb (.bytes (& entry)))
(var h u32)
(while (> (= h (.field (& value) (& wire))) 0)
(if (== h 2) (= (. reading total) (read-double (& value)))
(== h 3) (= (. reading ppt) (read-double (& value)))
(.skip (& value) wire))))
(.skip (& entry) wire)))
(add-pick-reading s reading))
(.skip (& body) wire)))))
;;; Game data --------------------------------------------------------
(fn read-gamedata ((s (* save)) (r pb)) void
@@ -183,6 +236,17 @@
(== f 3) (= (. s size-z) (.int32 (& r)))
(== f 7) (= (. s seed) (.int32 (& r)))
(== f 31) (read-tree-attribute s (.bytes (& r)))
;; DefaultSpawn, a PlayerSpawnPos: {1: x, 2: y, 3: z, ...}
(== f 40)
(do
(var spawn pb (.bytes (& r)))
(var g u32)
(= (. s has-spawn) true)
(while (> (= g (.field (& spawn) (& wire))) 0)
(if (== g 1) (= (. s spawn-x) (.int32 (& spawn)))
(== g 2) (= (. s spawn-y) (.int32 (& spawn)))
(== g 3) (= (. s spawn-z) (.int32 (& spawn)))
(.skip (& spawn) wire))))
(== f 11)
(do
(var entry pb (.bytes (& r)))
@@ -194,7 +258,10 @@
(== g 2) (= value (.bytes (& entry)))
(.skip (& entry) wire)))
(if (.equals key "BlockIDs") (read-block-ids s value)
(.equals key "storystructurelocations") (read-stories s value)))
(.equals key "storystructurelocations") (read-stories s value)
(&& (. key p) (>= (.len key) 14)
(== (strncmp (cast (. key p) (* const char)) "oreMapMarkers-" 14) 0))
(read-pick-readings s value)))
(.skip (& r) wire))))
(fn query-blob ((s (* const save)) (sql (* const char)) (key i64)
@@ -243,6 +310,7 @@
(for (var i int 0) (< i (. s block-count)) (++ i)
(free [(. s block-codes) i]))
(free (. s block-codes))
(free (. s pick-readings))
(sqlite3-close (. s db))
(free s))
@@ -299,6 +367,68 @@
(sqlite3-finalize stmt)
(return found))
;;; ServerMapRegion field 8, OreMaps: one {1: code, 2: IntDataMap2D}
;;; entry per mineral. Fills up to MAX of CODES (each strdup'd) and
;;; MAPS, and returns how many; -1 when the save has no such region.
(pub fn save/ore-maps ((s (* const save)) (rx i32) (rz i32) (codes (* * char)) (maps (* int-map))
(max int)) int
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from mapregion where position = ?1"
(position rx rz) (& stmt)))
(if (. r err)
(do (sqlite3-finalize stmt) (return -1)))
(var n int 0)
(var wire int)
(var f u32)
(while (> (= f (.field (& r) (& wire))) 0)
(if (|| (!= f 8) (>= n max))
(do (.skip (& r) wire) (continue)))
(var entry pb (.bytes (& r)))
(= [codes n] NULL)
(= [maps n] #(int-map : NULL 0 0 0))
(var g u32)
(while (> (= g (.field (& entry) (& wire))) 0)
(if (== g 1) (= [codes n] (strndup-pb (.bytes (& entry))))
(== g 2) (read-int-map (.bytes (& entry)) (& [maps n]))
(.skip (& entry) wire)))
(if [codes n]
(++ n)
(free (. [maps n] data))))
(sqlite3-finalize stmt)
(return n))
;;; ServerMapRegion field 11, GeneratedStructures: one {1: code, 3: box
;;; {1: x1, 2: y1, 3: z1, 4: x2, 5: y2, 6: z2}} per structure the
;;; region's chunks placed. Fills up to MAX boxes, six ints each, and
;;; returns how many.
(pub fn save/structure-boxes ((s (* const save)) (rx i32) (rz i32) (boxes (* i32)) (max int)) int
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from mapregion where position = ?1"
(position rx rz) (& stmt)))
(var n int 0)
(var wire int)
(var f u32)
(while (&& (! (. r err)) (> (= f (.field (& r) (& wire))) 0))
(if (|| (!= f 11) (>= n max))
(do (.skip (& r) wire) (continue)))
(var entry pb (.bytes (& r)))
(var g u32)
(while (> (= g (.field (& entry) (& wire))) 0)
(if (== g 3)
(do
(var box pb (.bytes (& entry)))
(var b (* i32) (+ boxes (* n 6)))
(memset b 0 (* 6 (sizeof i32)))
(var k u32)
(while (> (= k (.field (& box) (& wire))) 0)
(if (&& (>= k 1) (<= k 6))
(= [b (- k 1)] (.int32 (& box)))
(.skip (& box) wire)))
(++ n))
(.skip (& entry) wire))))
(sqlite3-finalize stmt)
(return n))
;;; Map chunks -------------------------------------------------------
;;; A repeated ushort field arrives one value per field, or packed.
@@ -360,6 +490,146 @@
(sqlite3-finalize stmt)
(return found))
;;; Chunks ------------------------------------------------------------
;;; A zstd frame, whole, into a fresh buffer; NULL if it isn't one.
(fn unzstd ((p (* const u8)) (len size-t) (out-len (* size-t))) (* u8)
(var size u64 (ZSTD-getFrameContentSize p len))
(if (>= size ZSTD-CONTENTSIZE-ERROR)
(return NULL))
(var out (* u8) (malloc (+ size 1)))
(var got size-t (ZSTD-decompress out size p len))
(if (ZSTD-isError got)
(do (free out) (return NULL)))
(= (* out-len) got)
(return out))
;;; A chunk's block layer: an int32, then the palette of block ids,
;;; raw in -n bytes if it is negative and zstd in n if not; then a zstd
;;; frame of bit planes, 4096 bytes each, plane k holding bit k of each
;;; block's palette index, block i at bit i % 8 of byte i / 8. A layer
;;; of 0 alone holds no blocks: all air.
(fn read-blocks ((p (* const u8)) (len size-t) (out (* i32))) bool
(if (< len 4)
(return false))
(var n i32 (cast (c-bit-or [p 0] (<< [p 1] 8) (<< [p 2] 16) (<< (cast [p 3] u32) 24)) i32))
(if (&& (== n 0) (== len 4))
(do
(memset out 0 (* CHUNK-VOLUME (sizeof i32)))
(return true)))
(var palette (* u8) NULL)
(var palette-len size-t 0)
(var rest (* const u8) NULL)
(if (< n 0)
(do
(= palette-len (cast (- n) size-t))
(if (> (+ 4 palette-len) len) (return false))
(= palette (malloc palette-len))
(memcpy palette (+ p 4) palette-len)
(= rest (+ p 4 palette-len)))
(do
(if (> (+ 4 (cast n size-t)) len) (return false))
(= palette (unzstd (+ p 4) (cast n size-t) (& palette-len)))
(= rest (+ p 4 n))))
(var planes-len size-t 0)
(var planes (* u8) (if palette (unzstd rest (cast (- (+ p len) rest) size-t) (& planes-len)) NULL))
(var count int (cast (/ palette-len 4) int))
(var bits int (cast (/ planes-len 4096) int))
(var ok bool (&& palette planes (> count 0)))
(if ok
(do
(var index (* i32) (calloc CHUNK-VOLUME (sizeof i32)))
(for (var k int 0) (< k bits) (++ k)
(var plane (* const u8) (+ planes (* k 4096)))
(for (var i int 0) (< i CHUNK-VOLUME) (++ i)
(if (& (>> [plane (/ i 8)] (% i 8)) 1)
(c-bit-or= [index i] (<< 1 k)))))
(for (var i int 0) (< i CHUNK-VOLUME) (++ i)
(var k int [index i])
(var id i32 -1)
(if (< k count)
(memcpy (& id) (+ palette (* k 4)) 4))
(= [out i] id))
(free index)))
(free palette)
(free planes)
(return ok))
;;; The blocks of stored chunk (cx, cy, cz), by (y * 32 + z) * 32 + x,
;;; as block ids (see save/block-code). False when the save has no such
;;; chunk or its blocks don't read.
(pub fn save/chunk-blocks ((s (* const save)) (cx i32) (cy i32) (cz i32) (out (* i32))) bool
(var stmt (* sqlite3-stmt) NULL)
(var key i64 (c-bit-or (position cx cz) (<< (cast cy i64) 54)))
(var r pb (query-blob s "select data from chunk where position = ?1" key (& stmt)))
(var ok bool false)
(if (! (. r err))
(do
(var wire int)
(var f u32)
(while (> (= f (.field (& r) (& wire))) 0)
(if (== f 1)
(do
(var blocks pb (.bytes (& r)))
(= ok (read-blocks (. blocks p) (.len blocks) out)))
(.skip (& r) wire)))))
(sqlite3-finalize stmt)
(return ok))
;;; A hot spring candidate GenCaves stored in a map chunk's
;;; "hotspringlocations": centre within the chunk, and radius.
(pub record saved-spring ((x i32) (y i32) (z i32) (radius double)))
;;; The map chunk's "hotspringlocations" (mod data, field 1): a
;;; Dictionary<Vec3i, HotSpringGenData> of {1: {1: x, 2: y, 3: z},
;;; 2: {1: radius}} entries. Fills up to MAX and returns how many.
(pub fn save/hot-spring-locations ((s (* const save)) (cx i32) (cz i32) (out (* saved-spring)) (max int))
int
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from mapchunk where position = ?1" (position cx cz) (& stmt)))
(var n int 0)
(var wire int)
(var f u32)
(while (&& (! (. r err)) (> (= f (.field (& r) (& wire))) 0))
(if (!= f 1)
(do (.skip (& r) wire) (continue)))
(var entry pb (.bytes (& r)))
(var key pb #(pb : NULL NULL false))
(var value pb #(pb : NULL NULL false))
(var g u32)
(while (> (= g (.field (& entry) (& wire))) 0)
(if (== g 1) (= key (.bytes (& entry)))
(== g 2) (= value (.bytes (& entry)))
(.skip (& entry) wire)))
(if (! (.equals key "hotspringlocations"))
(continue))
(while (&& (< n max) (> (.field (& value) (& wire)) 0))
(var item pb (.bytes (& value)))
(var spring saved-spring #(saved-spring : 0 0 0 0))
(var h u32)
(while (> (= h (.field (& item) (& wire))) 0)
(if (== h 1)
(do
(var pos pb (.bytes (& item)))
(var k u32)
(while (> (= k (.field (& pos) (& wire))) 0)
(if (== k 1) (= (. spring x) (.int32 (& pos)))
(== k 2) (= (. spring y) (.int32 (& pos)))
(== k 3) (= (. spring z) (.int32 (& pos)))
(.skip (& pos) wire))))
(== h 2)
(do
(var data pb (.bytes (& item)))
(var k u32)
(while (> (= k (.field (& data) (& wire))) 0)
(if (== k 1) (= (. spring radius) (read-double (& data)))
(.skip (& data) wire))))
(.skip (& item) wire)))
(= [out n] spring)
(++ n)))
(sqlite3-finalize stmt)
(return n))
;;; The stored extent of a table, in its own units (regions or chunks):
;;; inclusive bounds and the row count.
(pub record extent ((x0 i32) (z0 i32) (x1 i32) (z1 i32) (count i64)))

View File

@@ -1,5 +1,7 @@
;;; Finds the block nearest a point where one of a set of rocks lies, at
;;; the surface, at a depth below it or at a Y.
;;; the surface, at a depth below it, at a Y or at any depth; where the
;;; prospecting pick reads a mineral at least so high; where a cave
;;; opens at the surface; or a hot spring.
;;;
;;; Regions are taken in order of their distance from the point and
;;; sampled every 16 blocks by several threads at once, each with its
@@ -10,28 +12,27 @@
(pub include pthread.h)
(include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(import noise)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(pub import worldgen)
(pub import rivers)
(import terra)
(import strata)
(import ores)
(import caves)
(pub define SEARCH-RADIUS-REGIONS 24)
;;; The mode that looks for a mineral: the value is the mineral, the
;;; mask the least reading category.
(pub define SEARCH-MINERAL 4)
;;; The mode that looks for a cave entrance.
(pub define SEARCH-CAVE-ENTRANCE 5)
;;; The mode that looks for a hot spring.
(pub define SEARCH-HOT-SPRING 6)
(define SEARCH-STEP 16)
(define MAX-SEARCH-THREADS 16)
(pub define MAX-SEARCH-THREADS 16)
;; TODO sex#60: size threads with MAX-SEARCH-THREADS once arrays of a
;; header type take a symbolic size.
(pub record search
((lock pthread-mutex-t) (threads [pthread-t 16]) (thread-count int) (running bool)
((lock pthread-mutex-t) (threads [pthread-t MAX-SEARCH-THREADS]) (thread-count int) (running bool)
(cancel bool)
;; the question
(settings world-settings) (rivers river-config) (assets-dir [char 1024])
@@ -44,11 +45,16 @@
(record region-order ((rx int) (rz int) (distance double)))
(fn by-distance ((pa (* const void)) (pb (* const void))) int
;; TODO sex#61: cast inside the field access once a cast as the object
;; of . keeps its parentheses.
(var a (* const region-order) pa)
(var b (* const region-order) pb)
(return (- (> (. a distance) (. b distance)) (< (. a distance) (. b distance)))))
(var a _ (. (cast pa (* const region-order)) distance))
(var b _ (. (cast pb (* const region-order)) distance))
(return (- (> a b) (< a b))))
;;; A thread's generators, and the searched mineral's ore map of the
;;; region it last scanned in; for caves, a chunk's terrain and states.
(record scanner
((tr (* terra)) (rocks (* strata)) (minerals (* ores)) (column (* u8))
(ore-map int-map) (ore-rx int) (ore-rz int)
(caves (* caves)) (solid (* u32)) (states (* u8))))
(fn region-distance ((s (* const search)) (rx int) (rz int)) double
(var x0 double (* rx 512.0))
@@ -70,6 +76,33 @@
(fn matches ((s (* const search)) (rock int)) bool
(return (&& (>= rock 0) (< rock 32) (!= (& (. s mask) (<< (cast 1 u32) rock)) 0))))
;;; Whether column (x, z), with the strata in the scanner's column,
;;; holds what is searched for: a rock where the mode looks, at any
;;; depth (mode 3) anywhere from y = 1 to the surface; or a reading of
;;; the mineral, or its ore map's band where the pick can't read it, of
;;; at least the mask's category.
(fn column-matches ((s (* const search)) (sc (* scanner)) (x int) (z int) (height int)) bool
(var column (* const u8) (. sc column))
(if (== (. s mode) SEARCH-MINERAL)
(do
(var rx int (/ x 512))
(var rz int (/ z 512))
(if (|| (! (. sc ore-map data)) (!= (. sc ore-rx) rx) (!= (. sc ore-rz) rz))
(do
(free (. sc ore-map data))
(ores/map (. sc minerals) (. s value) rx rz (& (. sc ore-map)))
(= (. sc ore-rx) rx)
(= (. sc ore-rz) rz)))
(return (>= (ores/category-at (. sc minerals) (. s value) (& (. sc ore-map)) x z column
height)
(cast (. s mask) int)))))
(if (!= (. s mode) 3)
(return (matches s (rock-at column height (. s mode) (. s value)))))
(for (var y int 1) (<= y height) (++ y)
(if (matches s [column y])
(return true)))
(return false))
(fn offer ((s (* search)) (x int) (z int)) void
(var dx double (- (+ x 0.5) (. s x)))
(var dz double (- (+ z 0.5) (. s z)))
@@ -84,24 +117,57 @@
(pthread-mutex-unlock (& (. s lock))))
;;; Every STEP-th column of chunk (cx, cz) against the mask.
(fn scan-chunk ((s (* search)) (tr (* terra)) (rocks (* strata)) (cx int) (cz int) (step int)
(column (* u8))) void
(fn scan-chunk ((s (* search)) (sc (* scanner)) (cx int) (cz int) (step int)) void
(var heights [u16 1024])
(terra/chunk-heights tr cx cz step heights)
;; caves are carved a chunk at a time, so every column is looked at:
;; an entrance can be a block wide
(if (== (. s mode) SEARCH-HOT-SPRING)
(do
(var springs [hot-spring MAX-CANDIDATES])
(var n int (caves/hot-springs (. sc caves) (. sc tr) cx cz springs MAX-CANDIDATES))
(for (var i int 0) (< i n) (++ i)
(offer s (. [springs i] x) (. [springs i] z)))
(return)))
(if (== (. s mode) SEARCH-CAVE-ENTRANCE)
(do
(var carved [int 1024])
(terra/chunk-solidity (. sc tr) cx cz heights (. sc solid))
(for (var i int 0) (< i 1024) (++ i)
(= [carved i] [heights i]))
(caves/carve-column (. sc caves) cx cz carved (. sc solid) (terra/solid-words (. sc tr))
(. sc states))
(for (var i int 0) (< i 1024) (++ i)
(if (< [carved i] [heights i])
(offer s (+ (* cx 32) (% i 32)) (+ (* cz 32) (/ i 32)))))
(return)))
(terra/chunk-heights (. sc tr) cx cz step heights)
(for (var lz int 0) (< lz 32) (+= lz step)
(for (var lx int 0) (< lx 32) (+= lx step)
(var h int [heights (+ (* lz 32) lx)])
(strata/column rocks cx cz lx lz h column)
(if (matches s (rock-at column h (. s mode) (. s value)))
(offer s (+ (* cx 32) lx) (+ (* cz 32) lz))))))
(var x int (+ (* cx 32) lx))
(var z int (+ (* cz 32) lz))
(strata/column (. sc rocks) cx cz lx lz h (. sc column))
(if (column-matches s sc x z h)
(offer s x z)))))
(fn search-thread ((arg (* void))) (* void)
(var s (* search) arg)
(var g (* worldgen) (worldgen/make (. s settings) (. s assets-dir)))
(var tr (* terra) (if g (terra/make g (. s rivers)) NULL))
(var rocks (* strata) (if g (strata/make g (. s assets-dir)) NULL))
(var column (* u8) (malloc (+ (. s settings size-y) 1)))
(while (&& tr rocks)
(var sc scanner)
(memset (& sc) 0 (sizeof sc))
(= (. sc tr) (if g (terra/make g (. s rivers)) NULL))
(= (. sc rocks) (if g (strata/make g (. s assets-dir)) NULL))
(if (&& (. sc rocks) (== (. s mode) SEARCH-MINERAL))
(= (. sc minerals) (ores/make (. s settings) (. s assets-dir) (. sc rocks))))
(= (. sc column) (malloc (+ (. s settings size-y) 1)))
(if (&& g (. sc tr) (|| (== (. s mode) SEARCH-CAVE-ENTRANCE) (== (. s mode) SEARCH-HOT-SPRING)))
(do
(= (. sc caves) (caves/make g))
(= (. sc solid) (malloc (* 1024 (terra/solid-words (. sc tr)) (sizeof u32))))
(= (. sc states) (malloc (* 1024 (. s settings size-y))))))
(var ready bool (&& (. sc tr) (. sc rocks) (|| (!= (. s mode) SEARCH-MINERAL) (. sc minerals))
(|| (< (. s mode) SEARCH-CAVE-ENTRANCE) (. sc caves))))
(while ready
(pthread-mutex-lock (& (. s lock)))
(var i int (. s next))
(var stop bool (|| (. s cancel) (>= i (. s region-count))))
@@ -117,7 +183,7 @@
(var rz int [(. s regions) (+ (* i 2) 1)])
(for (var cz int 0) (< cz 16) (++ cz)
(for (var cx int 0) (< cx 16) (++ cx)
(scan-chunk s tr rocks (+ (* rx 16) cx) (+ (* rz 16) cz) SEARCH-STEP column)))
(scan-chunk s (& sc) (+ (* rx 16) cx) (+ (* rz 16) cz) SEARCH-STEP)))
(pthread-mutex-lock (& (. s lock)))
(++ (. s done-count))
(pthread-mutex-unlock (& (. s lock))))
@@ -131,16 +197,21 @@
(var bx int (. s best-x))
(var bz int (. s best-z))
(pthread-mutex-unlock (& (. s lock)))
(if (&& last tr rocks)
(if (&& last ready)
(for (var dz int -1) (<= dz 1) (++ dz)
(for (var dx int -1) (<= dx 1) (++ dx)
(var cx int (+ (/ bx 32) dx))
(var cz int (+ (/ bz 32) dz))
(if (&& (>= cx 0) (>= cz 0) (< (* cx 32) (. s settings size-x)) (< (* cz 32) (. s settings size-z)))
(scan-chunk s tr rocks cx cz 1 column)))))
(free column)
(if rocks (strata/free rocks))
(if tr (terra/free tr))
(scan-chunk s (& sc) cx cz 1)))))
(free (. sc column))
(free (. sc ore-map data))
(if (. sc caves) (caves/free (. sc caves)))
(free (. sc solid))
(free (. sc states))
(if (. sc minerals) (ores/free (. sc minerals)))
(if (. sc rocks) (strata/free (. sc rocks)))
(if (. sc tr) (terra/free (. sc tr)))
(if g (worldgen/free g))
(return NULL))
@@ -162,7 +233,9 @@
(free (. s regions))
(= (. s regions) NULL))
;;; Starts looking for MASK's rocks nearest (x, z); see search/poll.
;;; Starts looking for MASK's rocks nearest (x, z), or in mode
;;; SEARCH-MINERAL for mineral VALUE read as category MASK or higher;
;;; see search/poll.
(pub fn search/start ((s (* search)) (settings world-settings) (rivers river-config)
(assets-dir (* const char)) (mode int) (value int) (mask u32)
(x double) (z double) (threads int)) void

View File

@@ -3,20 +3,15 @@
;;; has the seed as typed and the world config as strings.
(include stdio.h stdlib.h string.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import cs)
(import json)
(import maps)
(import lcg)
(import noise)
(import shape)
(import save)
(import worldgen)
(pub import worldgen)
;;; Settings plus the seed as the user would type it.
(pub record world-source ((settings world-settings) (seed-text [char 128])))
;;; Settings plus the seed as the user would type it, and the world's
;;; spawn if it names one; the game's default is the map's middle.
(pub record world-source
((settings world-settings) (seed-text [char 128]) (has-spawn bool) (spawn-x int) (spawn-z int)))
(fn ends-with ((s (* const char)) (suffix (* const char))) bool
(var n size-t (strlen s))
@@ -35,6 +30,9 @@
(= (. out settings size-y) (. s size-y))
(= (. out settings size-z) (. s size-z))
(snprintf (. out seed-text) (sizeof (. out seed-text)) "%d" (. s seed))
(= (. out has-spawn) (. s has-spawn))
(= (. out spawn-x) (. s spawn-x))
(= (. out spawn-z) (. s spawn-z))
(save/close s)
(return true))
@@ -55,6 +53,14 @@
(var map-size-y (* cJSON) (cJSON-GetObjectItem world "MapSizeY"))
(if (cJSON-IsNumber map-size-y)
(= (. out settings size-y) (cast (cJSON-GetNumberValue map-size-y) int)))
;; DefaultSpawn: a PlayerSpawnPos, null unless set
(var spawn (* cJSON) (cJSON-GetObjectItem json "DefaultSpawn"))
(if (&& (cJSON-IsObject spawn) (cJSON-IsNumber (cJSON-GetObjectItem spawn "x"))
(cJSON-IsNumber (cJSON-GetObjectItem spawn "z")))
(do
(= (. out has-spawn) true)
(= (. out spawn-x) (cast (cJSON-GetNumberValue (cJSON-GetObjectItem spawn "x")) int))
(= (. out spawn-z) (cast (cJSON-GetNumberValue (cJSON-GetObjectItem spawn "z")) int))))
(var config (* cJSON) (cJSON-GetObjectItem world "WorldConfiguration"))
(for (var item (* cJSON) (if config (. config child) NULL)) item (= item (. item next))
(var text [char 64])
@@ -70,6 +76,7 @@
(pub fn world-source/load ((path (* const char)) (out (* world-source))) bool
(= (. out settings) (world-settings/defaults))
(snprintf (. out seed-text) (sizeof (. out seed-text)) "0")
(= (. out has-spawn) false)
(if (ends-with path ".vcdbs")
(return (from-save path out)))
(return (from-server-config path out)))

View File

@@ -100,9 +100,7 @@
;;; NaturalShape -----------------------------------------------------
;; TODO sex#57: make this private again once a pub record can use a
;; private type.
(pub record shape-cell ((x int) (z int) (open [bool 4]) (live bool)))
(record shape-cell ((x int) (z int) (open [bool 4]) (live bool)))
(pub record natural-shape
((rng (* lcg))
@@ -240,9 +238,7 @@
(for (var i int 0) (< i (. in cap)) (++ i)
(if (== [(. in state) i] 1)
(.put set (+ x0 (cast (>> [(. in keys) i] 32) i32))
;; TODO sex#47: write the mask in hex once there are hex
;; literals.
(+ z0 (cast (& [(. in keys) i] 4294967295) i32)) 1))))
(+ z0 (cast (& [(. in keys) i] 0xFFFFFFFF) i32)) 1))))
(pub fn release ((self (* natural-shape))) void
(free (. self slots))

View File

@@ -10,18 +10,11 @@
;;; if it were rock, as the game's prospecting assumes too.
(include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(pub import maps)
(import noise)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(import terra)
(pub import terra)
(pub define MAX-ROCKS 32)
;;; A column entry below any rock: the mantle at y = 0.

View File

@@ -10,27 +10,20 @@
;;; certainly air above.
(include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(pub import maps)
(import noise)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(pub import worldgen)
(pub import fastnoise)
(pub import rivers)
;;; NewSimplexNoiseLayer --------------------------------------------
;; TODO sex#47: write these in hex, as the C# does, once there are hex
;; literals.
(define PRIME-X 5910200641878280303)
(define PRIME-Y 6452764530575939509)
(define PRIME-Z 6614699811220273867)
(define HASH-MULTIPLIER 6026932503003350773)
(define SEED-FLIP -5968755714895566377)
(define PRIME-X 0x5205402B9270C86F)
(define PRIME-Y 0x598CD327003817B5)
(define PRIME-Z 0x5BCC226E9FA0BACB)
(define HASH-MULTIPLIER 0x53A3F72DEEC546F5)
(define SEED-FLIP -0x52D547B2E96ED629)
(define NORMALIZER-3D 0.2781926117527186)
(define MAX-Y-SLOPE 5.0)
@@ -145,14 +138,9 @@
(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))
;; TODO sex#62: cast (c-bit-or xn 1) to float directly once a cast of
;; a bitwise expression keeps its parentheses.
(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 xs float (cast (c-bit-or xn 1) float))
(var ys float (cast (c-bit-or yn 1) float))
(var zs float (cast (c-bit-or zn 1) float))
(var skip5 bool false)
(var a2 float (+ xf0 a0))
@@ -285,8 +273,7 @@
;;; *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
;; TODO sex#63: write -INFINITY once it reads as a negation.
(if (<= v 0.0) (return (- INFINITY)))
(if (<= v 0.0) (return -INFINITY))
(if (>= v 1.0) (return INFINITY))
(return (* 0.5 (log (/ v (- 1.0 v))))))
@@ -658,8 +645,11 @@
;;; A height is the top solid block, 0 if there is none.
;;; Heights of the columns of chunk (cx, cz) from local (lx0, lz0) to
;;; (lx1, lz1) inclusive, every STEP-th, into HEIGHTS[lz * 32 + lx].
;;; SOLID-BITS, unless NULL, gets every column's solid blocks below the top
;;; too, overhangs and pockets showing as gaps: bit y % 32 of word
;;; (lz * 32 + lx) * WORDS + y / 32, set where solid; it starts zeroed.
(fn heights-in ((t (* terra)) (cx int) (cz int) (lx0 int) (lz0 int) (lx1 int) (lz1 int)
(step int) (heights (* u16))) void
(step int) (heights (* u16)) (solid-bits (* u32)) (words int)) 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)))
@@ -680,11 +670,9 @@
(var oct-a [double 64])
(var oct-t [double 64])
(for (var k int 0) (< k 4) (++ k)
;; TODO sex#59: put the (if ...)s in the sums below once a
;; conditional operand keeps its parentheses.
(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)
(landform-weights/at (& (. t weights))
(+ base-x (if (& k 1) pixel 0)) (+ base-z (if (& k 2) pixel 0))
w n)
(interpolated-octaves t w (+ oct-a (* k 16)) (+ oct-t (* k 16))))
(var delta float (/ (cast 1 float) (cast 32 float)))
@@ -793,7 +781,11 @@
(! (|| (<= y (- baseline bank-blocks))
(>= (cast y float) (+ baseline (* bank-blocks (. c top-factor)))))))
(= solid false))
(if solid (= height y)))
(if solid
(do
(= height y)
(if solid-bits
(c-bit-or= [solid-bits (+ (* (+ (* lz 32) lx) words) (/ y 32))] (<< (cast 1 u32) (% y 32)))))))
(= [heights (+ (* lz 32) lx)] (cast height u16))))
(free w))
@@ -801,7 +793,19 @@
;;; multiples of STEP, into HEIGHTS[lz * 32 + lx]; the rest are left
;;; alone.
(pub fn terra/chunk-heights ((t (* terra)) (cx int) (cz int) (step int) (heights (* u16))) void
(heights-in t cx cz 0 0 31 31 step heights))
(heights-in t cx cz 0 0 31 31 step heights NULL 0))
;;; Words per column of terra/chunk-solidity's bits.
(pub fn terra/solid-words ((t (* const terra))) int
(return (/ (+ (. t size-y) 31) 32)))
;;; Every block of chunk (cx, cz): its heights as terra/chunk-heights,
;;; and SOLID, 1024 * terra/solid-words words, bit y % 32 of word
;;; (lz * 32 + lx) * words + y / 32 set where the terrain is solid.
(pub fn terra/chunk-solidity ((t (* terra)) (cx int) (cz int) (heights (* u16)) (solid (* u32))) void
(var words int (terra/solid-words t))
(memset solid 0 (* 1024 words (sizeof u32)))
(heights-in t cx cz 0 0 31 31 1 heights solid words))
;;; The height of the one column at block (x, z): 1/1024th of a chunk's
;;; work, for a cursor or a probe.
@@ -809,5 +813,5 @@
(var heights [u16 1024])
(var lx int (% x 32))
(var lz int (% z 32))
(heights-in t (/ x 32) (/ z 32) lx lz lx lz 1 heights)
(heights-in t (/ x 32) (/ z 32) lx lz lx lz 1 heights NULL 0)
(return [heights (+ (* lz 32) lx)]))

View File

@@ -13,36 +13,42 @@
(pub include pthread.h SDL3/SDL.h)
(include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import json)
(import maps)
(import lcg)
(import noise)
(import shape)
(import worldgen)
(pub import shape)
(pub import worldgen)
(import fastnoise)
(import rivers)
(pub import rivers)
(import terra)
(import strata)
(import ores)
(import caves)
(pub define MAX-TILES 65536)
;;; Not worldgen maps: Rivers' distance to the nearest river, the
;;; terrain height, and the rock at the surface, at a depth or at a Y.
;;; terrain height, and the rock at the surface, at a depth or at a Y,
;;; or where one rock lies at any depth; and the prospecting pick's
;;; reading of one mineral.
(pub define LAYER-RIVERS 6)
(pub define LAYER-HEIGHT 7)
(pub define LAYER-ROCK 8)
(pub define LAYER-MINERAL 9)
(pub define LAYER-CAVES 10)
(pub define ROCK-AT-SURFACE 0)
(pub define ROCK-AT-DEPTH 1)
(pub define ROCK-AT-Y 2)
;;; The param's value is then the rock's index.
(pub define ROCK-ANY-DEPTH 3)
;;; Mineral tile values: this plus the reading's category.
(pub define MINERAL-VALUE-BASE 64)
;;; Cave tile values: this plus the column's cave category.
(pub define CAVE-VALUE-BASE 80)
;;; Rock tile values besides rock indices.
(pub define VALUE-WATER 253)
(pub define VALUE-AIR 254)
;;; 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.
(define MAX-WORKERS 32)
(pub define MAX-WORKERS 32)
(define TILE-FREE 0)
(define TILE-QUEUED 1)
@@ -51,65 +57,57 @@
(define TILE-DRAWN 4)
;;; STRATUM is the stratum for MAP-STRATA, the samples per region side
;;; for the sampled layers; PARAM is the rock layer's mode * 1024 + value.
;;; for the sampled layers; PARAM is the rock layer's mode * 1024 + value,
;;; or the mineral layer's mineral.
(pub record tile-key ((map int) (stratum int) (rx int) (rz int) (param int)))
;;; Rock tiles keep their VALUES, rock indices, and are coloured from
;;; the palette on upload, so a new palette only re-uploads them.
;;; Rock and mineral tiles keep their VALUES, rock indices or reading
;;; categories, and are coloured from the palette on upload, so a new
;;; palette only re-uploads them.
(pub record tile
((key tile-key) (state int) (generation int) (size int) (pixels (* u32)) (values (* u8))
(texture (* SDL-Texture)) (last-used u64)))
(pub record tiles
((lock pthread-mutex-t) (wake pthread-cond-t)
;; TODO sex#50: write MAX-TILES once constants in array types are
;; kebab-converted.
(slots [tile MAX_TILES]) (index cell-map)
(queue [int MAX_TILES]) (queue-len int) (queue-pos int)
(free-slots [int MAX_TILES]) (free-count int)
(slots [tile MAX-TILES]) (index cell-map)
(queue [int MAX-TILES]) (queue-len int) (queue-pos int)
(free-slots [int MAX-TILES]) (free-count int)
(settings world-settings) (rivers river-config) (assets-dir [char 1024]) (generation int)
;; TODO sex#60: size with MAX-WORKERS once arrays of a header type
;; take a symbolic size.
(workers [pthread-t 32]) (worker-count int) (quit bool) (frame u64) (waiting int)
(workers [pthread-t MAX-WORKERS]) (worker-count int) (quit bool) (frame u64) (waiting int)
(palette [u32 256])))
(fn key-hash ((k tile-key)) u64
;; one-to-one: region x and z 16 bits each, map 4, stratum or
;; resolution 10, param 18
;; TODO sex#47: write the field masks in hex once there are hex
;; literals.
(return (c-bit-or (cast (& (. k rx) 65535) u64)
(<< (cast (& (. k rz) 65535) u64) 16)
(<< (cast (& (. k map) 15) u64) 32)
(<< (cast (& (. k stratum) 1023) u64) 36)
(<< (cast (& (. k param) 262143) u64) 46))))
(return (c-bit-or (cast (& (. k rx) 0xFFFF) u64)
(<< (cast (& (. k rz) 0xFFFF) u64) 16)
(<< (cast (& (. k map) 0xF) u64) 32)
(<< (cast (& (. k stratum) 0x3FF) u64) 36)
(<< (cast (& (. k param) 0x3FFFF) u64) 46))))
;;; The tile index is a cell-map keyed by (x, z): the hash is split
;;; over the two halves.
;; TODO sex#47: write the low-half masks below in hex once there are hex
;; literals.
(fn index-get ((t (* tiles)) (k tile-key)) int
(var h u64 (key-hash k))
(return (.get (& (. t index)) (cast (>> h 32) int) (cast (& h 4294967295) int))))
(return (.get (& (. t index)) (cast (>> h 32) int) (cast (& h 0xFFFFFFFF) int))))
(fn index-put ((t (* tiles)) (k tile-key) (slot int)) void
(var h u64 (key-hash k))
(.put (& (. t index)) (cast (>> h 32) int) (cast (& h 4294967295) int) slot))
(.put (& (. t index)) (cast (>> h 32) int) (cast (& h 0xFFFFFFFF) int) slot))
(fn index-remove ((t (* tiles)) (k tile-key)) void
(var h u64 (key-hash k))
(.remove (& (. t index)) (cast (>> h 32) int) (cast (& h 4294967295) int)))
(.remove (& (. t index)) (cast (>> h 32) int) (cast (& h 0xFFFFFFFF) int)))
;;; Colouring -----------------------------------------------------
;;; A distinct, stable colour per landform index.
(fn landform-colour ((i u32)) u32
;; TODO sex#47: write the multiplier (0x9E3779B1) and masks in hex
;; once there are hex literals.
(var h u32 (* (+ i 1) (cast 2654435761 u32)))
(return (c-bit-or (<< (+ 48 (& (>> h 24) 191)) 16)
(<< (+ 48 (& (>> h 16) 191)) 8)
(+ 48 (& (>> h 8) 191)))))
(var h u32 (* (+ i 1) (cast 0x9E3779B1 u32)))
(return (c-bit-or (<< (+ 48 (& (>> h 24) 0xBF)) 16)
(<< (+ 48 (& (>> h 16) 0xBF)) 8)
(+ 48 (& (>> h 8) 0xBF)))))
(fn lerp-colour ((a u32) (b u32) (t int)) u32
(var r u32 0)
@@ -120,20 +118,18 @@
(return r))
(fn colour-of ((g (* const worldgen)) (map int) (v int)) u32
;; TODO sex#47: write the colours and masks in hex once there are hex
;; literals.
(switch map
;; landforms.json gives most landforms the same green, so these
;; are coloured by index instead
(case MAP-LANDFORM (return (landform-colour (cast v u32))))
(case MAP-PROVINCE
(return (if (&& (>= v 0) (< v (. g provinces count))) [(. g provinces colours) v] 0)))
(case MAP-CLIMATE (return (& (cast v u32) 16777215)))
(case MAP-OCEAN (return (lerp-colour 6326847 1919884 v)))
(case MAP-CLIMATE (return (& (cast v u32) 0xFFFFFF)))
(case MAP-OCEAN (return (lerp-colour 0x608A3F 0x1D4B8C v)))
(default
(if (< v 0) (= v 0))
(if (> v 255) (= v 255))
(return (* (cast v u32) 65793)))))
(return (* (cast v u32) 0x010101)))))
;;; The tile's inner pixels, coloured, as ARGB.
(fn render ((g (* worldgen)) (k tile-key) (size (* int))) (* u32)
@@ -144,9 +140,7 @@
(for (var z int 0) (< z inner) (++ z)
(for (var x int 0) (< x inner) (++ x)
(var v int [(. m data) (+ (* (+ z (. m pad-tl)) (. m size)) x (. m pad-tl))])
;; TODO sex#47: write the opaque alpha in hex once there are hex
;; literals.
(= [px (+ (* z inner) x)] (c-bit-or 4278190080 (colour-of g (. k map) v)))))
(= [px (+ (* z inner) x)] (c-bit-or 0xFF000000 (colour-of g (. k map) v)))))
(free (. m data))
(= (* size) inner)
(return px))
@@ -187,12 +181,11 @@
(= (. c segments) (realloc (. c segments) (* (. c segment-cap) (sizeof int))))))
(return p))
;; TODO sex#47: write the colours in hex once there are hex literals.
(fn river-colour ((distance int) (valley int) (ocean bool)) u32
(if ocean (return 1784427))
(if (== distance 0) (return 3043288))
(if (< distance valley) (return (lerp-colour 8369128 5143098 (/ (* distance 255) valley))))
(return 4022062))
(if ocean (return 0x1B3A6B))
(if (== distance 0) (return 0x2E6FD8))
(if (< distance valley) (return (lerp-colour 0x7FB3E8 0x4E7A3A (/ (* distance 255) valley))))
(return 0x3D5F2E))
(fn render-rivers ((g (* worldgen)) (cache (* river-cache)) (config (* const river-config))
(k tile-key) (size (* int))) (* u32)
@@ -220,32 +213,26 @@
(var ox int (+ (* cx (/ 32 step)) dx))
(var oz int (+ (* cz (/ 32 step)) dz))
(= [px (+ (* oz res) ox)]
;; TODO sex#47: write the opaque alpha in hex once there
;; are hex literals.
(c-bit-or 4278190080 (river-colour d valley (river-plate/ocean-at p x z))))))))
(c-bit-or 0xFF000000 (river-colour d valley (river-plate/ocean-at p x z))))))))
(= (* size) res)
(return px))
;;; Terrain height, shaded: water by depth under sea level, land by
;;; height, lit from the north-west.
;; TODO sex#47: write the colours in hex once there are hex literals.
(fn height-colour ((h int) (west int) (north int) (sea int) (size-y int)) u32
;; TODO sex#59: clamp the depth inline once a conditional operand
;; keeps its parentheses.
(var depth int (- sea h))
(if (> depth 40) (= depth 40))
(if (< h sea)
(return (lerp-colour 6400472 1186659 (/ (* depth 255) 40))))
(return (lerp-colour 0x61A9D8 0x121B63 (/ (* (if (> depth 40) 40 depth) 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 base u32 (if (< t 32) (lerp-colour 0x558A38 0x7EA23A (* t 8))
(if (< t 96) (lerp-colour 0x7EA23A 0x976953 (/ (* (- t 32) 255) 64))
(lerp-colour 0x976953 0xE8E8E8 (/ (* (- 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 base 0xFFFFFF (/ (* (- light 128) 160) 127))))
(return (lerp-colour 0 base (+ 96 (/ (* light 159) 128)))))
(fn render-heights ((tr (* terra)) (k tile-key) (size (* int))) (* u32)
@@ -272,15 +259,15 @@
(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)]
;; TODO sex#47: write the opaque alpha in hex once there are
;; hex literals.
(c-bit-or 4278190080 (height-colour h west north (. tr sea-level) (. tr size-y))))))
(c-bit-or 0xFF000000 (height-colour h west north (. tr sea-level) (. tr size-y))))))
(free hs)
(= (* size) res)
(return px))
;;; The rock tile: per sample, the rock at the surface, at a depth
;;; below it, or at an absolute Y (water or air above the surface).
;;; below it, or at an absolute Y (water or air above the surface); or,
;;; at any depth, the rock where the column holds it at all and air
;;; where it doesn't.
(fn render-rocks ((tr (* terra)) (rocks (* strata)) (k tile-key) (size (* int))) (* u8)
(var res int (. k stratum))
(var step int (/ 512 res))
@@ -308,7 +295,10 @@
(if (== mode ROCK-AT-DEPTH) (= y (- h value))
(== mode ROCK-AT-Y) (= y value))
(var v u8 VALUE-AIR)
(if (< y 0) (= v ROCK-MANTLE)
(if (== mode ROCK-ANY-DEPTH)
(for (var ry int 1) (<= ry h) (++ ry)
(if (== [column ry] value) (= v (cast value u8))))
(< y 0) (= v ROCK-MANTLE)
(<= y h) (= v [column y])
(< y (. tr sea-level)) (= v VALUE-WATER))
(= [out (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)] v)))))
@@ -316,6 +306,106 @@
(= (* size) res)
(return out))
;;; The mineral tile: per sample, MINERAL-VALUE-BASE plus the category
;;; of the pick's reading there, or of the ore map where the pick can't
;;; read the mineral; that needs neither heights nor strata.
(fn render-minerals ((tr (* terra)) (rocks (* strata)) (o (* ores)) (k tile-key) (size (* int)))
(* u8)
(var res int (. k stratum))
(var step int (/ 512 res))
(var map int-map)
(ores/map o (. k param) (. k rx) (. k rz) (& map))
(var out (* u8) (malloc (* res res)))
(var heights [u16 1024])
(var column (* u8) (malloc (+ (. tr size-y) 1)))
(var readable bool (. [(. o minerals) (. k param)] readable))
(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))
(var chunk-x int (+ (* (. k rx) 16) cx))
(var chunk-z int (+ (* (. k rz) 16) cz))
(if readable
(terra/chunk-heights tr chunk-x chunk-z (if (> step 32) 32 step) heights))
(for (var dz int 0) (< dz per-chunk) (++ dz)
(for (var dx int 0) (< dx per-chunk) (++ dx)
(var lx int (* dx step))
(var lz int (* dz step))
(var h int 0)
(if readable
(do
(= h [heights (+ (* lz 32) lx)])
(strata/column rocks chunk-x chunk-z lx lz h column)))
(var c int (ores/category-at o (. k param) (& map) (+ (* chunk-x 32) lx)
(+ (* chunk-z 32) lz) column h))
(= [out (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)]
(cast (+ MINERAL-VALUE-BASE c) u8))))))
(free column)
(free (. map data))
(= (* size) res)
(return out))
;;; The cave tile: per sample, CAVE-VALUE-BASE plus its column's cave
;;; category, or CAVE-HOT-SPRING inside a hot spring. Caves are carved chunk by chunk, and a chunk needs every
;;; block of its terrain, so this costs a whole chunk per sample when
;;; zoomed out.
(fn render-caves ((tr (* terra)) (c (* caves)) (k tile-key) (size (* int))) (* u8)
(var res int (. k stratum))
(var step int (/ 512 res))
(var out (* u8) (malloc (* res res)))
(var heights [u16 1024])
(var carved [int 1024])
(var words int (terra/solid-words tr))
(var solid (* u32) (malloc (* 1024 words (sizeof u32))))
(var states (* u8) (malloc (* 1024 (. tr size-y))))
(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))
(var chunk-x int (+ (* (. k rx) 16) cx))
(var chunk-z int (+ (* (. k rz) 16) cz))
(terra/chunk-solidity tr chunk-x chunk-z heights solid)
(for (var i int 0) (< i 1024) (++ i)
(= [carved i] [heights i]))
(caves/carve-column c chunk-x chunk-z carved solid words states)
(for (var dz int 0) (< dz per-chunk) (++ dz)
(for (var dx int 0) (< dx per-chunk) (++ dx)
(var lx int (* dx step))
(var lz int (* dz step))
(var i int (+ (* lz 32) lx))
(var cat int (caves/category c states lx lz [heights i] [carved i]))
(= [out (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)]
(cast (+ CAVE-VALUE-BASE cat) u8))))))
;; hot springs over it, from the chunks of the region and around it,
;; whose discs may reach in
(var springs [hot-spring MAX-CANDIDATES])
(for (var cz int -1) (<= cz 16) (++ cz)
(for (var cx int -1) (<= cx 16) (++ cx)
(var chunk-x int (+ (* (. k rx) 16) cx))
(var chunk-z int (+ (* (. k rz) 16) cz))
(if (|| (< chunk-x 0) (< chunk-z 0) (>= (* chunk-x 32) (. (. c g) settings size-x))
(>= (* chunk-z 32) (. (. c g) settings size-z)))
(continue))
(var n int (caves/hot-springs c tr chunk-x chunk-z springs MAX-CANDIDATES))
(for (var i int 0) (< i n) (++ i)
(var sp (* hot-spring) (& [springs i]))
(for (var iz int 0) (< iz res) (++ iz)
(var dz double (- (+ (* (. k rz) 512) (* iz step)) (. sp z)))
(if (> (fabs dz) (. sp radius))
(continue))
(for (var ix int 0) (< ix res) (++ ix)
(var dx double (- (+ (* (. k rx) 512) (* ix step)) (. sp x)))
(if (< (+ (* dx dx) (* dz dz)) (* (. sp radius) (. sp radius)))
(= [out (+ (* iz res) ix)] (cast (+ CAVE-VALUE-BASE CAVE-HOT-SPRING) u8))))))))
(free solid)
(free states)
(= (* size) res)
(return out))
;;; Workers -------------------------------------------------------
(fn worker-main ((arg (* void))) (* void)
@@ -326,6 +416,8 @@
(memset (& cache) 0 (sizeof cache))
(var tr (* terra) NULL)
(var rocks (* strata) NULL)
(var minerals (* ores) NULL)
(var cave-gen (* caves) NULL)
(pthread-mutex-lock (& (. t lock)))
(while (! (. t quit))
(if (>= (. t queue-pos) (. t queue-len))
@@ -348,6 +440,10 @@
(do
(if tr (terra/free tr))
(= tr NULL)
(if minerals (ores/free minerals))
(= minerals NULL)
(if cave-gen (caves/free cave-gen))
(= cave-gen NULL)
(if rocks (strata/free rocks))
(= rocks NULL)
(if g (worldgen/free g))
@@ -355,6 +451,8 @@
(= g (worldgen/make settings (. t assets-dir)))
(if g (= tr (terra/make g rivers)))
(if g (= rocks (strata/make g (. t assets-dir))))
(if rocks (= minerals (ores/make settings (. t assets-dir) rocks)))
(if g (= cave-gen (caves/make g)))
(= (. cache sampler) (river-sampler/make (& rivers) (. settings size-y)))
(= g-generation generation)))
(var size int 0)
@@ -366,6 +464,10 @@
(= px (render-heights tr key (& size)))
(&& tr rocks (== (. key map) LAYER-ROCK))
(= values (render-rocks tr rocks key (& size)))
(&& tr rocks minerals (== (. key map) LAYER-MINERAL))
(= values (render-minerals tr rocks minerals key (& size)))
(&& tr cave-gen (== (. key map) LAYER-CAVES))
(= values (render-caves tr cave-gen key (& size)))
g
(= px (render g key (& size))))
@@ -382,6 +484,8 @@
(if (&& (== generation (. t generation)) (== (. tl state) TILE-WORKING))
(= (. tl state) TILE-QUEUED)))))
(pthread-mutex-unlock (& (. t lock)))
(if minerals (ores/free minerals))
(if cave-gen (caves/free cave-gen))
(if rocks (strata/free rocks))
(if tr (terra/free tr))
(if g (worldgen/free g))

View File

@@ -2,24 +2,22 @@
;;; region over everything the save has. A port is right when every
;;; map matches to the pixel, padding included.
(include stdio.h stdlib.h string.h time.h)
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(include stdio.h stdlib.h string.h math.h time.h)
(import maps)
(import lcg)
(import noise)
(import json)
(import shape)
(import save)
(import worldgen)
(import fastnoise)
(import rivers)
(pub import rivers)
(import terra)
(import strata)
(import ores)
(import caves)
(import img)
(define MAP-KINDS 6)
;;; How far below the computed reading the game's may be; see
;;; verify-readings.
(define READING-SLACK 0.85)
(var map-names [(* const char) 6] #("landform" "climate" "province" "upheaval" "ocean" "strata"))
@@ -116,6 +114,552 @@
(.release (& [diffs k])))
(return failed))
;;; Regenerates the ore map of every mineral in every region the save
;;; stored and compares them; one diff image for all minerals, a region
;;; red where any of its ore maps differs.
(pub fn verify-ores ((s (* save)) (o (* ores)) (dir (* const char))) int
(var e extent (save/extent s "mapregion"))
(var cell int 32)
(var diff image (image/make (* (+ (- (. e x1) (. e x0)) 1) cell) (* (+ (- (. e z1) (. e z0)) 1) cell)))
(var codes [* char MAX-MINERALS])
(var want [int-map MAX-MINERALS])
(var t tally)
(memset (& t) 0 (sizeof t))
(var unknown int 0)
(for (var rz int (. e z0)) (<= rz (. e z1)) (++ rz)
(for (var rx int (. e x0)) (<= rx (. e x1)) (++ rx)
(var n int (save/ore-maps s rx rz codes want MAX-MINERALS))
(var ox int (* (- rx (. e x0)) cell))
(var oz int (* (- rz (. e z0)) cell))
(var ok bool true)
(for (var i int 0) (< i n) (++ i)
(var k int (ores/find o [codes i]))
(if (< k 0)
(++ unknown)
(do
(var got int-map)
(ores/map o k rx rz (& got))
(++ (. t regions))
(if (!= (. got size) (. [want i] size))
(do (++ (. t size-mismatch)) (= ok false))
(for (var p int 0) (< p (* (. got size) (. got size))) (++ p)
(++ (. t compared))
(if (== [(. got data) p] [(. [want i] data) p])
(++ (. t matched))
(= ok false))))
(free (. got data))))
(free [codes i])
(free (. [want i] data)))
(if (> n 0)
(for (var y int 0) (< y cell) (++ y)
(for (var x int 0) (< x cell) (++ x)
(.set (& diff) (+ ox x) (+ oz y) (if ok (grey 96) 16719904)))))))
(var percent double (if (> (. t compared) 0) (/ (* 100.0 (. t matched)) (. t compared)) 0))
(printf "%-9s %4d maps %10lld/%-10lld px %8.4f%%%s\n" "ore" (. t regions)
(. t matched) (. t compared) percent
(if (. t size-mismatch) " (size mismatch)" ""))
(if (> unknown 0)
(printf "ore %d stored maps of minerals the deposits don't define\n" unknown))
(var path [char 1024])
(snprintf path (sizeof path) "%s/diff-ore.png" dir)
(.write (& diff) path)
(.release (& diff))
(return (if (|| (!= (. t matched) (. t compared)) (> unknown 0)) 1 0)))
;;; What a block of the save is, for the strata check.
(define BLOCK-OTHER -1)
;;; a rock- block whose rock is not a stratum, e.g. a deposit's halite
(define BLOCK-OTHER-ROCK -2)
;;; Kinds of blocks the save has where the strata put rock, by the code
;;; up to its first hyphen, e.g. "ore" or "crackedrock".
(define MAX-KINDS 64)
(record kind-count ((name [char 24]) (count i64)))
(fn count-kind ((kinds (* kind-count)) (n (* int)) (code (* const char))) void
(var len int (cast (strcspn code "-") int))
(for (var i int 0) (< i (* n)) (++ i)
(if (&& (== (cast (strlen (. [kinds i] name)) int) len)
(== (strncmp (. [kinds i] name) code len) 0))
(do (++ (. [kinds i] count)) (return))))
(if (>= (* n) MAX-KINDS)
(return))
(snprintf (. [kinds (* n)] name) 24 "%.*s" len code)
(= (. [kinds (* n)] count) 1)
(++ (* n)))
(fn by-count ((pa (* const void)) (pb (* const void))) int
(var a (* const kind-count) pa)
(var b (* const kind-count) pb)
(return (- (< (. a count) (. b count)) (> (. a count) (. b count)))))
;;; Lava in caves sits at y 11 and below and turns the rock around it
;;; to basalt, a few blocks further up.
(define LAVA-BASALT-TOP 18)
;;; Compares the rock below the surface with the save's blocks, chunk
;;; by chunk: every block from y = 1 up to the lower of our height and
;;; the stored one. The strata are laid against our height, as the game
;;; laid them against its height before the dry seabed raise.
;;;
;;; Where the save has a stratum rock, it should be ours. Three things
;;; written after the strata explain where it isn't: the column's height
;;; differs from ours, so its strata sit differently; basalt around cave
;;; lava near the bottom; and the default rock, which cave walls and
;;; underground structures are built of. Where the save has anything
;;; else, ore, caves, deposits, it is counted by kind.
(pub fn verify-strata ((s (* save)) (g (* worldgen)) (config river-config) (rocks (* strata))
(dir (* const char))) int
(var t (* terra) (terra/make g config))
(var heights [u16 1024])
(var basalt int -1)
(for (var r int 0) (< r (. rocks rock-count)) (++ r)
(if (== (strcmp [(. rocks rock-codes) r] "rock-basalt") 0)
(= basalt r)))
(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 t0 clock-t (clock))
;; block id -> strata rock index, or a BLOCK- kind
(var rock-of (* int) (malloc (* (+ (. s block-count) 1) (sizeof int))))
(for (var id int 0) (< id (. s block-count)) (++ id)
(var code (* const char) (save/block-code s id))
(= [rock-of id] BLOCK-OTHER)
(if (== (strncmp code "rock-" 5) 0)
(do
(= [rock-of id] BLOCK-OTHER-ROCK)
(for (var r int 0) (< r (. rocks rock-count)) (++ r)
(if (== (strcmp code [(. rocks rock-codes) r]) 0)
(= [rock-of id] r))))))
(var size-y int (. s size-y))
(var columns (* u8) (malloc (* CHUNK-AREA (+ size-y 1))))
(var blocks (* i32) (malloc (* CHUNK-VOLUME (sizeof i32))))
;; ours x theirs, for strata rocks that differ
(var confusion (* i64) (calloc (* MAX-ROCKS MAX-ROCKS) (sizeof i64)))
(var kinds [kind-count MAX-KINDS])
(var kind-n int 0)
(var compared i64 0)
(var matched i64 0)
(var other-rock i64 0)
(var other i64 0)
(var chunks i64 0)
(var unreadable i64 0)
(var other-height i64 0)
(var lava i64 0)
(var default-rock i64 0)
(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))
(var top int 0)
(terra/chunk-heights t cx cz 1 heights)
(for (var i int 0) (< i CHUNK-AREA) (++ i)
(var hi int [heights i])
(if (> hi top) (= top hi))
(strata/column rocks cx cz (% i 32) (/ i 32) hi (+ columns (* i (+ size-y 1)))))
(var bad [bool 1024])
(memset bad 0 (sizeof bad))
(for (var cy int 0) (&& (<= (* cy 32) top) (< (* cy 32) size-y)) (++ cy)
(if (! (save/chunk-blocks s cx cy cz blocks))
(do
(++ unreadable)
(continue)))
(++ chunks)
(for (var i int 0) (< i CHUNK-VOLUME) (++ i)
(var y int (+ (* cy 32) (/ i 1024)))
(var col int (% i 1024))
(if (|| (< y 1) (> y [(. m terrain-height) col]) (> y [heights col]))
(continue))
(var id i32 [blocks i])
(var theirs int (if (&& (>= id 0) (< id (. s block-count))) [rock-of id] BLOCK-OTHER))
(var ours int [columns (+ (* col (+ size-y 1)) y)])
(if (>= theirs 0)
(do
(++ compared)
(if (== theirs ours)
(++ matched)
(!= [heights col] [(. m terrain-height) col])
(++ other-height)
(&& (== theirs basalt) (<= y LAVA-BASALT-TOP))
(++ lava)
(== theirs (. rocks granite))
(++ default-rock)
(do
(= [bad col] true)
(if (< ours MAX-ROCKS)
(++ [confusion (+ (* ours MAX-ROCKS) theirs)])))))
(== theirs BLOCK-OTHER-ROCK)
(do
(++ other-rock)
(count-kind kinds (& kind-n) (save/block-code s id)))
(do
(++ other)
(count-kind kinds (& kind-n) (if (>= id 0) (save/block-code s id) "?"))))))
(for (var i int 0) (< i CHUNK-AREA) (++ i)
(var colour u32 (if [bad i] 0xFF2020 (grey 96)))
(.set (& diff) (+ (* (- cx (. e x0)) 32) (% i 32)) (+ (* (- cz (. e z0)) 32) (/ i 32))
colour))))
(var unexplained i64 (- compared matched other-height lava default-rock))
(printf "strata %lld/%lld rock blocks below the surface match (%.4f%%), %lld chunks, %.1f s\n"
matched compared (if (> compared 0) (/ (* 100.0 matched) compared) 0.0) chunks
(/ (cast (- (clock) t0) double) CLOCKS-PER-SEC))
(printf " explained: %lld where the height differs, %lld lava basalt, %lld default rock; %lld others (%.4f%%):\n"
other-height lava default-rock unexplained
(if (> compared 0) (/ (* 100.0 unexplained) compared) 0.0))
(if (> unreadable 0)
(printf " %lld chunks missing or unreadable\n" unreadable))
;; the commonest confusions
(for (var shown int 0) (< shown 8) (++ shown)
(var best int -1)
(for (var k int 0) (< k (* MAX-ROCKS MAX-ROCKS)) (++ k)
(if (&& (> [confusion k] 0) (|| (< best 0) (> [confusion k] [confusion best])))
(= best k)))
(if (< best 0)
(break))
(printf " ours %-16s save %-16s %lld\n" [(. rocks rock-codes) (/ best MAX-ROCKS)]
[(. rocks rock-codes) (% best MAX-ROCKS)] [confusion best])
(= [confusion best] 0))
(qsort kinds kind-n (sizeof kind-count) by-count)
(printf " where the save has no stratum rock: %lld blocks, %lld of them other rock;" (+ other other-rock)
other-rock)
(for (var k int 0) (&& (< k kind-n) (< k 12)) (++ k)
(printf " %s %lld" (. [kinds k] name) (. [kinds k] count)))
(printf "\n")
(var path [char 1024])
(snprintf path (sizeof path) "%s/diff-strata.png" dir)
(.write (& diff) path)
(.release (& diff))
(free columns)
(free blocks)
(free confusion)
(free rock-of)
(terra/free t)
(return (if (< (* unexplained 10000) compared) 0 1)))
;;; The save's block, as the cave check sees it. Obsidian and anything
;;; else of basalt, ore or cracked rock, is what the deposits made of it.
(define SAVED-AIR 0)
(define SAVED-BASALT 1)
(define SAVED-ROCK 2)
(define SAVED-OTHER 3)
(define SAVED-FROM-BASALT 4)
(define SAVED-KINDS 5)
;;; Ours: the CAVE- states, and one more for the gaps the terrain itself
;;; leaves below its surface.
(define TERRAIN-AIR 4)
(define OUR-KINDS 5)
(var cave-state-names [(* const char) 5] #("rock" "air" "lava" "basalt" "terrain air"))
(var saved-names [(* const char) 5] #("air" "basalt" "rock" "other" "deposit in basalt"))
(define MAX-STRUCTURES 8192)
;;; Whether block (x, y, z) is inside one of N structure boxes.
(fn in-structure ((boxes (* const i32)) (n int) (x int) (y int) (z int)) bool
(for (var i int 0) (< i n) (++ i)
(var b (* const i32) (+ boxes (* i 6)))
(if (&& (>= x [b 0]) (<= x [b 3]) (>= y [b 1]) (<= y [b 4]) (>= z [b 2]) (<= z [b 5]))
(return true)))
(return false))
;;; Carves every stored chunk column and compares its blocks below our
;;; terrain height with the save's: where we carve air or lava the save
;;; should have air (lava is a fluid, so its solid block is air), where
;;; we put basalt it should have basalt, and where we leave rock it
;;; should not have air. Later passes put things in caves too, so air
;;; next to "other" is not wrong by itself. Also compares the terrain
;;; heights after carving with the stored ones.
(pub fn verify-caves ((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 t0 clock-t (clock))
(var t (* terra) (terra/make g config))
(var c (* caves) (caves/make g))
(var size-y int (. s size-y))
;; hot springs: the stored candidates against ours, and ours placed
;; against the sludgy gravel the save has
(var sludgy int -1)
(var gravel (* i32) NULL)
(var gravel-count int 0)
(var gravel-cap int 0)
(var springs (* hot-spring) NULL)
(var spring-count int 0)
(var spring-cap int 0)
(var cand-same i64 0)
(var cand-ours-only i64 0)
(var cand-saved-only i64 0)
(var saved (* u8) (malloc (+ (. s block-count) 1)))
(for (var id int 0) (< id (. s block-count)) (++ id)
(var code (* const char) (save/block-code s id))
(= [saved id] SAVED-OTHER)
(var len size-t (strlen code))
(if (== (strcmp code "sludgygravel") 0) (= sludgy id))
(if (== id 0) (= [saved id] SAVED-AIR)
(== (strcmp code "rock-basalt") 0) (= [saved id] SAVED-BASALT)
(|| (== (strcmp code "rock-obsidian") 0)
(&& (> len 7) (== (strcmp (+ code (- len 7)) "-basalt") 0)))
(= [saved id] SAVED-FROM-BASALT)
(|| (== (strncmp code "rock-" 5) 0) (== (strncmp code "crackedrock-" 12) 0)
(== (strncmp code "ore-" 4) 0))
(= [saved id] SAVED-ROCK)))
(var states (* u8) (malloc (* 1024 size-y)))
(var blocks (* i32) (malloc (* CHUNK-VOLUME (sizeof i32))))
(var tally [i64 25])
(var words int (terra/solid-words t))
(var solid (* u32) (malloc (* 1024 words (sizeof u32))))
(memset tally 0 (sizeof tally))
;; the structure boxes of the regions around the column
(var boxes (* i32) (malloc (* MAX-STRUCTURES 6 (sizeof i32))))
(var box-count int 0)
(var boxes-rx int -1)
(var boxes-rz int -1)
(var missed-in i64 0)
(var missed-out i64 0)
(var over-in i64 0)
(var over-out i64 0)
(var missed-surface i64 0)
(var heights [u16 1024])
(var before [int 1024])
(var after [int 1024])
(var columns i64 0)
(var height-before i64 0)
(var height-after i64 0)
(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-solidity t cx cz heights solid)
;; the region's structures; boxes reach into neighbours only a
;; little, so the region itself is enough for a tally
(if (|| (!= boxes-rx (/ cx 16)) (!= boxes-rz (/ cz 16)))
(do
(= boxes-rx (/ cx 16))
(= boxes-rz (/ cz 16))
(= box-count (save/structure-boxes s boxes-rx boxes-rz boxes MAX-STRUCTURES))))
(var top int 0)
(for (var i int 0) (< i 1024) (++ i)
(= [before i] [heights i])
(= [after i] [heights i])
(if (> [heights i] top) (= top [heights i])))
(caves/carve-column c cx cz after solid words states)
;; the candidates, each against the stored one at its key
(var ours [spring-candidate MAX-CANDIDATES])
(var mine int (caves/candidates c cx cz ours MAX-CANDIDATES))
(var theirs-c [saved-spring MAX-CANDIDATES])
(var stored int (save/hot-spring-locations s cx cz theirs-c MAX-CANDIDATES))
(for (var a int 0) (< a mine) (++ a)
(var hit bool false)
(for (var b int 0) (< b stored) (++ b)
(if (&& (== (. [ours a] x) (. [theirs-c b] x)) (== (. [ours a] y) (. [theirs-c b] y))
(== (. [ours a] z) (. [theirs-c b] z)) (== (. [ours a] radius) (. [theirs-c b] radius)))
(= hit true)))
(if hit (++ cand-same) (++ cand-ours-only)))
(for (var b int 0) (< b stored) (++ b)
(var hit bool false)
(for (var a int 0) (< a mine) (++ a)
(if (&& (== (. [ours a] x) (. [theirs-c b] x)) (== (. [ours a] y) (. [theirs-c b] y))
(== (. [ours a] z) (. [theirs-c b] z)) (== (. [ours a] radius) (. [theirs-c b] radius)))
(= hit true)))
(if (! hit) (++ cand-saved-only)))
;; and which of ours become hot springs
(if (> mine 0)
(do
(var placed [hot-spring MAX-CANDIDATES])
(var n int (caves/hot-springs c t cx cz placed MAX-CANDIDATES))
(for (var a int 0) (< a n) (++ a)
(if (>= spring-count spring-cap)
(do
(= spring-cap (+ (* spring-cap 2) 16))
(= springs (realloc springs (* spring-cap (sizeof hot-spring))))))
(= [springs spring-count] [placed a])
(++ spring-count))))
(for (var i int 0) (< i 1024) (++ i)
(++ columns)
(if (== [before i] [(. m terrain-height) i]) (++ height-before))
(if (== [after i] [(. m terrain-height) i]) (++ height-after)))
(var over [bool 1024])
(var missed [bool 1024])
(memset over 0 (sizeof over))
(memset missed 0 (sizeof missed))
(for (var cy int 0) (&& (<= (* cy 32) top) (< (* cy 32) size-y)) (++ cy)
(if (! (save/chunk-blocks s cx cy cz blocks))
(continue))
(for (var i int 0) (< i CHUNK-VOLUME) (++ i)
(var y int (+ (* cy 32) (/ i 1024)))
(var col int (% i 1024))
(if (&& (== [blocks i] sludgy) (>= sludgy 0))
(do
(if (>= (+ gravel-count 3) gravel-cap)
(do
(= gravel-cap (+ (* gravel-cap 2) 768))
(= gravel (realloc gravel (* gravel-cap (sizeof i32))))))
(= [gravel gravel-count] (+ (* cx 32) (% col 32)))
(= [gravel (+ gravel-count 1)] y)
(= [gravel (+ gravel-count 2)] (+ (* cz 32) (/ col 32)))
(+= gravel-count 3)))
(if (|| (< y 1) (> y [before col]))
(continue))
(var id i32 [blocks i])
(var theirs int (if (&& (>= id 0) (< id (. s block-count))) [saved id] SAVED-OTHER))
(var ours int [states (+ (* y 1024) col)])
(if (&& (== ours CAVE-UNTOUCHED)
(== (& (>> [solid (+ (* col words) (/ y 32))] (% y 32)) 1) 0))
(= ours TERRAIN-AIR))
(++ [tally (+ (* ours SAVED-KINDS) theirs)])
(var bx int (+ (* cx 32) (% col 32)))
(var bz int (+ (* cz 32) (/ col 32)))
(if (&& (== ours CAVE-AIR) (== theirs SAVED-ROCK))
(if (in-structure boxes box-count bx y bz)
(++ over-in)
(do (++ over-out) (= [over col] true))))
;; air the save has and we don't: structures, the save's own
;; surface block (the block layers take some away, glaciers
;; above all) and anything above it, or ours to explain
(if (&& (== ours CAVE-UNTOUCHED) (== theirs SAVED-AIR))
(if (in-structure boxes box-count bx y bz)
(++ missed-in)
(>= y [(. m terrain-height) col])
(++ missed-surface)
(do (++ missed-out) (= [missed col] true))))))
(for (var i int 0) (< i 1024) (++ i)
(var colour u32 (grey 96))
(if [missed i] (= colour 0x2020FF))
(if [over i] (= colour 0xFF2020))
(.set (& diff) (+ (* (- cx (. e x0)) 32) (% i 32)) (+ (* (- cz (. e z0)) 32) (/ i 32)) colour))))
(printf "caves ours by the save's, below our terrain height, %.1f s:\n"
(/ (cast (- (clock) t0) double) CLOCKS-PER-SEC))
(for (var o int 0) (< o OUR-KINDS) (++ o)
(printf " %-11s" [cave-state-names o])
(for (var k int 0) (< k SAVED-KINDS) (++ k)
(printf " %s %lld" [saved-names k] [tally (+ (* o SAVED-KINDS) k)]))
(printf "\n"))
(var carved i64 (+ [tally (+ (* CAVE-AIR SAVED-KINDS) SAVED-AIR)]
[tally (+ (* CAVE-LAVA SAVED-KINDS) SAVED-AIR)]
[tally (+ (* CAVE-BASALT SAVED-KINDS) SAVED-BASALT)]
[tally (+ (* CAVE-BASALT SAVED-KINDS) SAVED-FROM-BASALT)]))
(var ours-carved i64 0)
(for (var k int 0) (< k SAVED-KINDS) (++ k)
(+= ours-carved (+ [tally (+ (* CAVE-AIR SAVED-KINDS) k)] [tally (+ (* CAVE-LAVA SAVED-KINDS) k)]
[tally (+ (* CAVE-BASALT SAVED-KINDS) k)])))
(printf " %lld of our %lld carved blocks agree (%.2f%%)\n" carved ours-carved
(if (> ours-carved 0) (/ (* 100.0 carved) ours-carved) 0.0))
(printf " air the save has where we leave rock: %lld in generated structures, %lld at or above the save's surface, %lld otherwise\n"
missed-in missed-surface missed-out)
(printf " rock the save has where we carve air: %lld in generated structures, %lld otherwise\n"
over-in over-out)
(printf " terrain height: %lld/%lld columns before carving, %lld after\n" height-before columns
height-after)
;; each sludgy gravel block, in one of our hot springs at its height?
(var gravel-in int 0)
(var found (* bool) (calloc (+ spring-count 1) (sizeof bool)))
(for (var g3 int 0) (< g3 gravel-count) (+= g3 3)
(var gx int [gravel g3])
(var gy int [gravel (+ g3 1)])
(var gz int [gravel (+ g3 2)])
(var in bool false)
(for (var k int 0) (< k spring-count) (++ k)
(var sp (* hot-spring) (& [springs k]))
(var dx double (- gx (. sp x)))
(var dz double (- gz (. sp z)))
;; the base goes 2 below, the walls up to the surface + 1
(if (&& (>= gy (- (. sp y) 2)) (<= gy (+ (. sp y) 4))
(< (+ (* dx dx) (* dz dz)) (* (+ (. sp radius) 1) (+ (. sp radius) 1))))
(do (= in true) (= [found k] true))))
(if in (++ gravel-in)))
(var springs-found int 0)
(for (var k int 0) (< k spring-count) (++ k)
(if [found k] (++ springs-found)))
(printf "hot springs candidates: %lld as stored, %lld only ours, %lld only stored\n" cand-same cand-ours-only
cand-saved-only)
(printf " %d placed, %d of them with the save's sludgy gravel; %d of %d sludgy gravel blocks in one\n"
spring-count springs-found gravel-in (/ gravel-count 3))
(free found)
(free gravel)
(free springs)
(var path [char 1024])
(snprintf path (sizeof path) "%s/diff-caves.png" dir)
(.write (& diff) path)
(.release (& diff))
(free states)
(free blocks)
(free saved)
(free boxes)
(free solid)
(caves/free c)
(terra/free t)
(return (if (< (* (+ missed-out over-out) 200) ours-carved) 0 1)))
;;; Recomputes the prospecting pick readings players took in the save
;;; and compares each mineral's TotalFactor: per reading, every
;;; mineral the save has or this reads above nothing.
;;;
;;; They can't match exactly. The pick's column already has the ore of
;;; the deposits generated in its chunk, which no longer counts as host
;;; rock, and the game's Y range is drawn from samples where this takes
;;; the distribution's limits. Both only ever make the game's reading
;;; lower, so a reading passes when the game's is at most this much
;;; below it, and never above.
(pub fn verify-readings ((s (* save)) (g (* worldgen)) (config river-config) (rocks (* strata))
(o (* ores))) int
(if (== (. s pick-reading-count) 0)
(do (printf "readings none stored\n") (return 0)))
(var t (* terra) (terra/make g config))
(var column [u8 1024])
(var compared int 0)
(var passed int 0)
(var same-category int 0)
(var unreadable int 0)
(var worst double 1)
(var i int 0)
(while (< i (. s pick-reading-count))
;; the minerals of one reading are stored one after another
(var at (* pick-reading) (& [(. s pick-readings) i]))
(var end int i)
(while (&& (< end (. s pick-reading-count)) (== (. [(. s pick-readings) end] x) (. at x))
(== (. [(. s pick-readings) end] z) (. at z)))
(++ end))
(var x int (. at x))
(var z int (. at z))
(var h int (terra/column-height t x z))
(strata/column rocks (/ x 32) (/ z 32) (% x 32) (% z 32) h column)
(printf "reading %d, %d: stored height %d, computed %d\n" x z (. at y) h)
(for (var k int 0) (< k (. o count)) (++ k)
(var m (* mineral) (& [(. o minerals) k]))
(var stored (* pick-reading) NULL)
(for (var j int i) (< j end) (++ j)
(if (== (strcmp (. [(. s pick-readings) j] code) (. m code)) 0)
(= stored (& [(. s pick-readings) j]))))
(var map int-map)
(ores/map o k (/ x 512) (/ z 512) (& map))
(var r mineral-reading (ores/reading o k (& map) x z column h))
(free (. map data))
(var want double (if stored (. stored total) 0))
(if (&& (! stored) (== (ores/category (. r total)) 0))
(continue))
(if (! (. m readable))
(do
(++ unreadable)
(printf " %-14s %9.6f (not read here)\n" (. m code) want)
(continue)))
(++ compared)
;; the game's reading over this one's
(var ratio double (if (> (. r total) 0) (/ want (. r total)) 0))
(var ok bool (&& (<= want (+ (. r total) 1e-9)) (>= ratio READING-SLACK)))
(var category bool (== (ores/category want) (ores/category (. r total))))
(if ok (++ passed))
(if category (++ same-category))
(if (< ratio worst) (= worst ratio))
(printf " %-14s %9.6f %9.6f %5.3f %s\n" (. m code) want (. r total) ratio
(if ok "ok" "MISMATCH")))
(= i end))
(terra/free t)
(printf "readings %d of %d no higher than computed and within %.0f%% of it (worst %.3f); %d of %d in the same category; %d child deposits not read\n"
passed compared (* 100 (- 1 READING-SLACK)) worst same-category compared unreadable)
(return (if (== passed compared) 0 1)))
;;; Recomputes Rivers' per-column riverDistance for every map chunk the
;;; save stored and compares it with the moddata Rivers saved: exactly
;;; where it saved some, and "nothing within 300 blocks" where it saved
@@ -218,19 +762,9 @@
(if (== d 0) (++ matched))
(if (!= d 0)
(do
;; TODO sex#59: sum two (if ...)s once a conditional
;; operand keeps its parentheses.
(var cls int 0)
(if (< d 0) (+= cls 2))
(if (>= got (. t sea-level)) (+= cls 1))
(++ [by-class cls])))
(++ [by-class (+ (if (< d 0) 2 0) (if (>= got (. t sea-level)) 1 0))])))
;; -4..+4, the ends counting everything beyond
;; TODO sex#59: clamp inline once a conditional operand keeps its
;; parentheses.
(var clamped int d)
(if (< clamped -4) (= clamped -4))
(if (> clamped 4) (= clamped 4))
(var bucket int (+ clamped 4))
(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))

File diff suppressed because it is too large Load Diff

View File

@@ -2,25 +2,15 @@
;;; against a saved world and dumps what either side produced.
(include stdio.h string.h)
;; An import brings in a module's own public forms but not the types
;; they mention, so dependencies come first.
;; TODO sex#58: import only the modules used here once an import brings
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import cs)
(import json)
(import maps)
(import lcg)
(import noise)
(import shape)
(import save)
(import dump)
(import worldgen)
(import fastnoise)
(import rivers)
(import terra)
(import strata)
(import settings)
(import ores)
(import verify)
(var worldgen-assets [(* const char) 6]
@@ -38,6 +28,9 @@
(return 1))
(printf "seed %d\n" (. s seed))
(printf "size %d x %d x %d\n" (. s size-x) (. s size-y) (. s size-z))
(if (. s has-spawn)
(printf "spawn %d %d %d\n" (. s spawn-x) (. s spawn-y) (. s spawn-z))
(printf "spawn the map's middle\n"))
(printf "block ids %d\n" (. s block-count))
(printf "world config, %d values:\n" (. s config-count))
(for (var i int 0) (< i (. s config-count)) (++ i)
@@ -93,9 +86,15 @@
(if (! g)
(return 1))
(var s (* save) (save/open save-path))
(var rocks (* strata) (strata/make g assets-dir))
(var minerals (* ores) (ores/make (. source settings) assets-dir rocks))
(var failed int (+ (verify-stories s g) (verify-regions s g out)
(verify-ores s minerals out)
(verify-readings s g (river-config/defaults) rocks minerals)
(verify-strata s g (river-config/defaults) rocks out)
(verify-caves s g (river-config/defaults) out)
(verify-rivers s g (river-config/defaults) out)
(verify-heights s g (river-config/defaults) (strata/make g assets-dir) out)))
(verify-heights s g (river-config/defaults) rocks out)))
(save/close s)
(return failed))

View File

@@ -4,11 +4,11 @@
;;; the worldgen assets and the region's coordinates.
(include stdio.h stdlib.h string.h math.h)
(import maps)
(import lcg)
(pub import maps)
(pub import lcg)
(import noise)
(import json)
(import shape)
(pub import json)
(pub import shape)
(pub define MAX-PROVINCES 32)
@@ -80,11 +80,9 @@
;;; NoiseGeoProvince plus MapLayerGeoProvince: a weighted random
;;; province per 64x64 cell of province-map pixels, sampled through a
;;; wobble so the cells don't show.
;; TODO sex#50: write MAX-PROVINCES once constants in array types are
;; kebab-converted.
(pub record province-layer
((rng lcg) (weights [int MAX_PROVINCES]) (count int) (weight-sum int)
(codes [* char MAX_PROVINCES]) (colours [u32 MAX_PROVINCES])
((rng lcg) (weights [int MAX-PROVINCES]) (count int) (weight-sum int)
(codes [* char MAX-PROVINCES]) (colours [u32 MAX-PROVINCES])
(wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))))
(define GEOPROV-MAP-SCALE 64)
@@ -167,10 +165,7 @@
(= [map (+ start (* i stride))] (cast [tmp i] i32))))
(fn box-blur ((map (* i32)) (w int) (h int) (range int)) void
;; TODO sex#59: inline the longer side once a conditional operand
;; keeps its parentheses.
(var longest int (if (> w h) w h))
(var tmp (* u32) (malloc (* longest (sizeof u32))))
(var tmp (* u32) (malloc (* (if (> w h) w h) (sizeof u32))))
(for (var y int 0) (< y h) (++ y)
(blur-line map (* y w) 1 w range tmp))
(for (var x int 0) (< x w) (++ x)
@@ -390,9 +385,7 @@
(= (. l octave-threshold-count) 11)))
(= (. l first-mutation) -1))
;; TODO sex#50: write MAX-LANDFORMS once constants in array types are
;; kebab-converted.
(pub record landform-table ((all [landform MAX_LANDFORMS]) (count int) (variant-count int)))
(pub record landform-table ((all [landform MAX-LANDFORMS]) (count int) (variant-count int)))
(pub fn terrain-octave-count ((size-y int)) int
(return (+ 9 (/ (- size-y 256) 128))))
@@ -452,11 +445,9 @@
(return (|| (!= (- rain clamped-rain) 0) (!= (- t clamped-temp) 0))))
;;; MapLayerLandforms over NoiseLandforms.
;; TODO sex#50: write MAX-LANDFORMS once constants in array types are
;; kebab-converted.
(pub record landform-layer
((rng lcg) (table (* const landform-table)) (climate climate-noise) (scale float)
(weights [double MAX_LANDFORMS])
(weights [double MAX-LANDFORMS])
(wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))))
(define LANDFORM-MAP-SCALE 16)
@@ -724,11 +715,9 @@
;;; MapLayerCustomPerlin per stratum of rockstrata.json: how thick
;;; that stratum may be, in blocks, per 16 blocks of region.
;; TODO sex#50: write MAX-STRATA once constants in array types are
;; kebab-converted.
(pub record strata-layer
((count int) (noises [* simplex-sum MAX_STRATA]) (thresholds [* double MAX_STRATA])
(codes [* char MAX_STRATA])))
((count int) (noises [* simplex-sum MAX-STRATA]) (thresholds [* double MAX-STRATA])
(codes [* char MAX-STRATA])))
(fn json-doubles ((o (* cJSON)) (key (* const char)) (out (* double)) (max int)) int
(var arr (* cJSON) (cJSON-GetObjectItem o key))
@@ -744,10 +733,8 @@
(memset (& l) 0 (sizeof l))
(var variants (* cJSON) (cJSON-GetObjectItem rockstrata "variants"))
(for (var v (* cJSON) (. variants child)) (&& v (< (. l count) MAX-STRATA)) (= v (. v next))
;; TODO sex#50: write MAX-OCTAVES once constants in array types
;; are kebab-converted.
(var amplitudes [double MAX_OCTAVES])
(var frequencies [double MAX_OCTAVES])
(var amplitudes [double MAX-OCTAVES])
(var frequencies [double MAX-OCTAVES])
(var th (* double) (calloc MAX-OCTAVES (sizeof double)))
(var n int (json-doubles v "amplitudes" amplitudes MAX-OCTAVES))
(json-doubles v "frequencies" frequencies MAX-OCTAVES)
@@ -780,7 +767,18 @@
;;; forces on the region maps around it.
(pub record story
((code [char 64]) (x int) (z int) (dir-x int) (landform-radius int)
(landform int) (forces-climate bool) (climate int)))
(landform int) (forces-climate bool) (climate int)
;; skipGenerationCategories' "caves" and "hotsprings": none within
;; this radius, or in the schematic's footprint when it is 0; -1 when
;; not skipped
(cave-skip int) (spring-skip int) (size-x int) (size-z int)))
;;; The footprints of the story schematics that skip caves by footprint
;;; rather than by radius. The schematics are not among the assets this
;;; reads, so their sizes are written here, as the 1.22.7 save records
;;; the village's.
(record story-size ((code (* const char)) (x int) (z int)))
(var story-sizes [story-size 1] #(#(story-size : "village" 195 225)))
(fn json-int ((o (* cJSON)) (key (* const char)) (fallback int)) int
(return (cast (json-number o key fallback) int)))
@@ -827,8 +825,7 @@
(= base-z (. parent z))
(= dir-x (. parent dir-x)))
(continue))
;; TODO sex#59: put the (if ...) in the product below once a
;; conditional operand keeps its parentheses.
;; drawn here, before the distances, as GenStoryStructures draws it
(var dir-z int (if (> (.next-float (& rng)) 0.5) -1 1))
(var dist-x int (+ min-x (.next-int (& rng) (- (+ max-x 1) min-x))))
(var dist-z int (+ min-z (.next-int (& rng) (- (+ max-z 1) min-z))))
@@ -840,6 +837,16 @@
(= (. st z) (+ base-z (* dist-z dir-z)))
(= (. st dir-x) dir-x)
(= (. st landform-radius) (json-int c "landformRadius" 0))
(var skips (* cJSON) (cJSON-GetObjectItem c "skipGenerationCategories"))
(var skip (* cJSON) (cJSON-GetObjectItem skips "caves"))
(= (. st cave-skip) (if (cJSON-IsNumber skip) (cast (cJSON-GetNumberValue skip) int) -1))
(var spring-skip (* cJSON) (cJSON-GetObjectItem skips "hotsprings"))
(= (. st spring-skip) (if (cJSON-IsNumber spring-skip) (cast (cJSON-GetNumberValue spring-skip) int) -1))
(for (var k int 0) (< k 1) (++ k)
(if (== (strcmp (. [story-sizes k] code) (. st code)) 0)
(do
(= (. st size-x) (. [story-sizes k] x))
(= (. st size-z) (. [story-sizes k] z)))))
(var landform (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem c "requireLandform")))
(= (. st landform) (if landform (landform-table/find landforms landform) -1))
(var force-temp (* cJSON) (cJSON-GetObjectItem c "forceTemperature"))
@@ -981,7 +988,7 @@
((settings world-settings) (provinces province-layer) (landform-table landform-table)
(landforms landform-layer) (oceans ocean-layer) (upheaval upheaval-layer)
(climate climate-layer) (strata strata-layer)
(stories [story MAX_STORY_LOCATIONS]) (story-count int)
(stories [story MAX-STORY-LOCATIONS]) (story-count int)
(story-wobble-x (* simplex-noise)) (story-wobble-z (* simplex-noise))))
(pub fn worldgen/make ((settings world-settings) (assets-dir (* const char))) (* worldgen)
@@ -1100,6 +1107,39 @@
(for (var i int 0) (< i (. g strata count)) (++ i)
(worldgen/map g MAP-STRATA i rx rz (& [(. out strata) i]))))
;;; GenStoryStructures.GetBlockingStructureAt: whether a story location
;;; keeps a category out of block column (x, z), by the radius SKIP
;;; reads off it.
(fn story-blocks ((g (* const worldgen)) (x int) (z int) (springs bool)) bool
(for (var i int 0) (< i (. g story-count)) (++ i)
(var st (* const story) (& [(. g stories) i]))
(var r int (if springs (. st spring-skip) (. st cave-skip)))
(if (< r 0)
(continue))
(if (== r 0)
(do
;; the schematic's cuboid, X2 = X1 + SizeX
(var x1 int (- (. st x) (/ (. st size-x) 2)))
(var z1 int (- (. st z) (/ (. st size-z) 2)))
(if (&& (>= x x1) (<= x (+ x1 (. st size-x))) (>= z z1) (<= z (+ z1 (. st size-z))))
(return true))
(continue)))
;; BlockPos.HorDistanceSqTo: in doubles, returned as a float
(var dx double (- x (. st x)))
(var dz double (- z (. st z)))
(var d float (cast (+ (* dx dx) (* dz dz)) float))
(if (< d (cast (* r r) float))
(return true)))
(return false))
;;; For the "caves" category.
(pub fn worldgen/caves-blocked ((g (* const worldgen)) (x int) (z int)) bool
(return (story-blocks g x z false)))
;;; For the "hotsprings" category.
(pub fn worldgen/springs-blocked ((g (* const worldgen)) (x int) (z int)) bool
(return (story-blocks g x z true)))
(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)))