Compare commits

..

26 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
30 changed files with 2560 additions and 614 deletions

6
.gitignore vendored
View File

@@ -1,11 +1,9 @@
/build/ /build/
# Inputs that stay local: the game's assets, the Rivers release, the # Inputs that stay local: the game's assets, the Rivers release, and
# test world and its server config, and the cJSON checkout the build # the test world and its server config.
# compiles from.
/assets/ /assets/
/serverconfig.json /serverconfig.json
/cJSON/
*.zip *.zip
*.vcdbs *.vcdbs
*.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 SEXC ?= $(HOME)/dev/sex/sexc
CFLAGS ?= -O2 -g CFLAGS ?= -O2 -g
CFLAGS += -std=c11 -Wall -ffp-contract=off -fwrapv 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 writes C with only the parentheses precedence needs.
SEX_CFLAGS = -Wno-logical-op-parentheses -Wno-bitwise-op-parentheses -Wno-shift-op-parentheses SEX_CFLAGS = -Wno-logical-op-parentheses -Wno-bitwise-op-parentheses -Wno-shift-op-parentheses
SDL_LIBS := $(shell pkg-config --libs sdl3) SDL_LIBS := $(shell pkg-config --libs sdl3)
ZSTD_LIBS := $(shell pkg-config --libs libzstd)
B = build B = build
all: $(B)/vsmv $(B)/vs-map-viewer all: $(B)/vsmv $(B)/vs-map-viewer
# sexc writes no dependency files, and an import pastes the imported # An import pastes the imported module's public forms into the
# module's public forms into the importer, so any Sex source may change # importer, so a Sex object depends on every module it reads; sexc
# any Sex object. # names them in a .d beside the object.
# TODO sex#40: depend on what each unit imports once sexc writes $(B)/%.o: src/%.sex | $(B)
# dependency files. $(SEXC) $< -c -o $@ --depfile=$(@:.o=.d) -- $(CFLAGS) $(SEX_CFLAGS) $(CPPFLAGS)
SEX_SRC := $(wildcard src/*.sex)
# Statement-level #line directives can land inside a ?: and break the -include $(wildcard $(B)/*.d)
# 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)
$(B)/nk.o: src/nk.c src/nk.h | $(B) $(B)/nk.o: src/nk.c src/nk.h | $(B)
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ $(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) $(B)/stb.o: src/stb.c third_party/stb/stb_image_write.h | $(B)
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ $(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
VSMV_OBJ = vsmv cs pb json maps save img dump lcg noise shape worldgen fastnoise rivers terra strata ores 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) $(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 ores 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) $(B)/vs-map-viewer: $(VIEWER_OBJ:%=$(B)/%.o)
$(CC) $^ -o $@ $(SDL_LIBS) -lsqlite3 $(CC) $^ -o $@ $(SDL_LIBS) -lsqlite3 $(ZSTD_LIBS)
$(B): $(B):
mkdir -p $@ mkdir -p $@

223
Plan.org
View File

@@ -227,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 - =ui=: Nuklear + SDL3 SDL_Renderer. Tiles are SDL textures under the
Nuklear panels. Nuklear panels.
Coordinates are shown like the in-game HUD, relative to the map centre Coordinates are shown as the game shows them, relative to the world's
=((MapSizeX+32)/2, (MapSizeZ+32)/2)=, with absolute coordinates available spawn (=DefaultSpawnPosition=, which =GuiDialogWorldMap= subtracts):
too. The viewer opens at spawn. =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 * Phases
Each phase ends with a check against the save. A mismatch means stop, Each phase ends with a check against the save. A mismatch means stop,
@@ -292,6 +297,25 @@ What the save turned out to be:
| 7 | =WorldGenTerrainHeightMap= | | 7 | =WorldGenTerrainHeightMap= |
| 13 | =TopRockIdMap= (block ids) | | 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 - *Assets.* The six worldgen JSONs (and all 910 asset JSONs) parse
after a relaxing pass: comments, unquoted keys and trailing commas. after a relaxing pass: comments, unquoted keys and trailing commas.
There are 48 landforms, 6 provinces and 16 strata. There are 48 landforms, 6 provinces and 16 strata.
@@ -469,9 +493,8 @@ Validation:
- *Result.* 11,675,804 / 11,675,818 columns match, 99.9999%. The 14 - *Result.* 11,675,804 / 11,675,818 columns match, 99.9999%. The 14
others likely carry structures placed later. A further 12,118 others likely carry structures placed later. A further 12,118
columns have no rock on top. columns have no rock on top.
- *Deeper layers* go through the same code but aren't checked against - *Deeper layers.* Checked against the chunk blocks since; see
chunk blocks. Decoding those blobs is the remaining step, if it is "Chunk blocks".
ever needed.
Viewer: Viewer:
- *Rock layer.* Modes: surface, depth below the surface, or absolute - *Rock layer.* Modes: surface, depth below the surface, or absolute
@@ -626,10 +649,15 @@ Viewer:
- *Minerals overlay.* Tiles keep =64 + category= per sample and share - *Minerals overlay.* Tiles keep =64 + category= per sample and share
the rock palette, so they cost one more palette range, not a new the rock palette, so they cost one more palette range, not a new
tile kind. tile kind.
- *Minerals panel.* Picks the mineral from a list of the readable ones. - *Minerals panel.* Picks the mineral from a list: the readable ones,
Its legend gives each category's share of the view. Find nearest then silver, gold and peridot as "(ore map)". Its legend gives each
takes a least category (decent by default) and runs as search mode category's share of the view. Find nearest takes a least category
4. (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 and Info.* A second label line gives the reading under the
cursor while the Minerals overlay is on. cursor while the Minerals overlay is on.
- *Probe.* Lists the pick's full reading for the column, highest first, - *Probe.* Lists the pick's full reading for the column, highest first,
@@ -647,11 +675,176 @@ Viewer:
- Optional disk cache of tiles and plates, keyed by a hash of the - Optional disk cache of tiles and plates, keyed by a hash of the
settings. settings.
- Go-to-coordinates, PNG export of the current view. - Go-to-coordinates, PNG export of the current view.
- Later: gravel-beach layer; exact ore deposits - Later: gravel-beach layer; deposits, see below.
(=GenDeposits.GeneratePartial= and the disc generators). That would
place real ore blocks, make the pick readings exact, and read ** Chunk blocks (done)
silver, gold and peridot. Checking it needs the save's chunk =save/chunk-blocks= decodes a stored chunk's solid blocks (format under
blocks decoded. 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 * Risks
- *Bit-exactness* of the noise and the Rivers trigonometry. The - *Bit-exactness* of the noise and the Rivers trigonometry. The

View File

@@ -6,38 +6,24 @@ it as a zoomable top-down map: terrain, rivers, oceans, climate,
landforms, geologic provinces, and rock strata at any depth. It is landforms, geologic provinces, and rock strata at any depth. It is
mostly for finding rock: where chalk, bauxite or limestone lie, at the mostly for finding rock: where chalk, bauxite or limestone lie, at the
surface or 20 blocks down, and which one is nearest. It also shows 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. what the prospecting pick would read for an ore, anywhere on the map,
and where the caves run.
[[file:doc/screenshot.png]] [[file:doc/screenshot.png]]
It covers Vintage Story 1.22.7 with the Rivers 5.0.3 mod. The 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 generator is a port of the game's own, written in [[https://git.kotobank.ch/alex-eg/sex][Sex]].
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 |
| Ore maps, 31 minerals | every pixel of 118 regions |
| Prospecting pick readings | 38 of 42 in the game's category; see Limits |
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.
** Building ** Building
You need: You need:
- the Sex compiler, expected at =~/dev/sex/sexc= (or set =SEXC=); - the Sex compiler;
- a C compiler; - a C compiler;
- SDL3 (=brew install sdl3=); - SDL3;
- SQLite3; - SQLite3;
- a checkout of [[https://github.com/DaveGamble/cJSON][cJSON]] in =./cJSON=. - zstd;
Nuklear and stb_image_write are vendored in =third_party/=. 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 #+begin_src sh
make make
@@ -61,8 +47,9 @@ WORLD is where the seed and settings come from:
real size; real size;
- or a =serverconfig.json=: the seed as typed and the world config. - or a =serverconfig.json=: the seed as typed and the world config.
Without WORLD it opens =./serverconfig.json=. It starts at spawn, in the Without WORLD it opens =./serverconfig.json=. It starts at the world's
middle of the map. spawn: the one the save or config names, else the middle of the map,
as in the game.
Options: Options:
@@ -71,16 +58,19 @@ Options:
| =--assets DIR= | where the game's =assets= are; default =./assets= | | =--assets DIR= | where the game's =assets= are; default =./assets= |
| =--zoom Z= | blocks per screen point, 1/16 to 32; default 4 | | =--zoom Z= | blocks per screen point, 1/16 to 32; default 4 |
| =--base LAYER= | the base layer: =ocean=, =rivers= or =height=; default =height= | | =--base LAYER= | the base layer: =ocean=, =rivers= or =height=; default =height= |
| =--overlay NAME= | turn on an overlay: =landform=, =climate=, =province=, =upheaval=, =strata=, =rock=, =mineral=; 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 | | =--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-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 | | =--rock-any= | the one highlighted rock at any depth |
| =--highlight ROCK= | highlight a rock, e.g. =chalk=; repeatable | | =--highlight ROCK= | highlight a rock, e.g. =chalk=; repeatable |
| =--find= | find the nearest highlighted rock on start | | =--find= | find the nearest highlighted rock on start |
| =--mineral CODE= | show a mineral's readings, e.g. =nativecopper= | | =--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=; default =decent= | | =--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-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 | | =--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 | | =--screenshot FILE.png= | wait until everything is drawn, save the window, quit |
| =--mouse X Y= | place the cursor, for screenshots | | =--mouse X Y= | place the cursor, for screenshots |
@@ -104,7 +94,8 @@ The map fills the middle of the window, between two panels.
under it, as the Rocks section is set (at the surface, at a depth, or under it, as the Rocks section is set (at the surface, at a depth, or
at a height). At any depth, it gives the Y of the rock's topmost block 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 and how far down that is, or says the column has none. With the
Minerals overlay on, a second line gives the mineral's reading. 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 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; block when zoomed in close, one in 32 when far out. Only what is on screen is computed;
@@ -118,9 +109,13 @@ when nothing is left to compute, the viewer sleeps.
- Change any setting (seed, sizes, landcover, scales, climate...) - Change any setting (seed, sizes, landcover, scales, climate...)
and press /Apply/ to generate that world instead. The seed can be and press /Apply/ to generate that world instead. The seed can be
any text, as typed into the game. 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: - *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; - landform and geologic province;
- climate: temperature at sea level, rain, geologic activity; - climate: temperature at sea level, rain, geologic activity;
- ocean and upheaval values; - ocean and upheaval values;
@@ -131,7 +126,9 @@ when nothing is left to compute, the viewer sleeps.
- *Probe*: the last column probed: its surface height and its strata, - *Probe*: the last column probed: its surface height and its strata,
top down, with the Y range and thickness of each. Below them, what top down, with the Y range and thickness of each. Below them, what
the prospecting pick reads there: every mineral it finds, highest the prospecting pick reads there: every mineral it finds, highest
first, with its parts per thousand, then the miniscule amounts. 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. - /Go to/ centres it.
- /Clear pins/ removes the pins. - /Clear pins/ removes the pins.
- /Close/ hides it. - /Close/ hides it.
@@ -142,7 +139,8 @@ when nothing is left to compute, the viewer sleeps.
- *Overlays*: any of Landform, Climate, Geologic province, Upheaval, - *Overlays*: any of Landform, Climate, Geologic province, Upheaval,
Rock strata thickness (pick the stratum below it), Rock and Rock strata thickness (pick the stratum below it), Rock and
Minerals. Drawn over the base at the /Overlay opacity/. Minerals. Drawn over the base at the /Overlay opacity/.
- /Story locations/ marks spawn and the story structures. - /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. - /Rock under cursor/ turns the cursor label on and off.
- *Rocks*: finding rock. - *Rocks*: finding rock.
- Choose where to look: at the /Surface/, at a /Depth below - Choose where to look: at the /Surface/, at a /Depth below
@@ -170,6 +168,20 @@ when nothing is left to compute, the viewer sleeps.
are. are.
- /Find nearest/ looks for the nearest column that reads at least - /Find nearest/ looks for the nearest column that reads at least
/Find at least/, as Rocks' /Find nearest/ does. /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 ** vsmv
The command-line side, mostly for checking the generator against a The command-line side, mostly for checking the generator against a
@@ -183,25 +195,29 @@ save:
| =vsmv dump SAVE.vcdbs OUT= | PNGs of the maps the save stored | | =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 | | =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 =verify= takes about eight minutes, most of it on the terrain heights
every stored chunk. It also compares the ore maps, and the prospecting of every stored chunk and on the caves. It also compares the ore maps,
pick readings players took in the save, if there are any. 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 ** Limits
- Only the /realistic/ world climate is supported, not /patchy/. - 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=, - Rivers' settings are not stored in a save. Without a =rivers.json=,
the mod's defaults are assumed. the mod's defaults are assumed.
- Other mods that change worldgen are not modelled. - 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 - 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 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 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 deposits generated in its chunk, and those deposits are not
generated here. generated here.
- Silver, gold and peridot are left out of Minerals. The game reads - The pick can't be reproduced for silver, gold and peridot. The game
them from ore inside other deposits (quartz and olivine), reads them from ore inside other deposits (quartz and olivine),
which needs the deposits themselves. which needs the deposits themselves. Minerals shows their ore maps
instead.
** Notes ** Notes
- =Plan.org= is the design and how each part was checked. - =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 Language bugs and friction met while building vs-map-viewer, against
sexc at ~/dev/sex. Newest first. Unless said otherwise, sexc dfafe8b. 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 =(var best double -INFINITY)= emits =_INFINITY=: the reader takes
the whole token as a symbol and the leading =-= is mangled like any the whole token as a symbol and the leading =-= is mangled like any
other. =(- INFINITY)= works. Negative literals like =-1= are fine, so other. =(- INFINITY)= works. Negative literals like =-1= are fine, so
it's only symbolic constants, but the mangled name reads like a typo. 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 =(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 =((float)xn) | 1=: a compile error here, but with an integer target
type it would silently cast only =xn=. Arithmetic operands are 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 together, mostly through =(if ...)= in arithmetic, which keeps coming
back because it reads so naturally. 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 =(. (cast pa (* const wanted)) distance)= emits
=(const wanted *)pa->distance=, which C reads as a cast of =(const wanted *)pa->distance=, which C reads as a cast of
=pa->distance= on a =void *=. Like the conditional entry below, the =pa->distance= on a =void *=. Like the conditional entry below, the
writer doesn't parenthesize a lower-precedence operand. Bound to a writer doesn't parenthesize a lower-precedence operand. Bound to a
typed local first, it works. 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 [pthread-t MAX_WORKERS])= emits =pthread_t MAX_WORKERS
workers[];=, reading =MAX_WORKERS= as a second type word. =[u16 workers[];=, reading =MAX_WORKERS= as a second type word. =[u16
CHUNK_AREA]= works, presumably because =u16= is known to Sex and CHUNK_AREA]= works, presumably because =u16= is known to Sex and
=pthread_t= only to C. A literal size, =[pthread-t 32]=, works. =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 #+begin_src scheme
(/ (* 100.0 matched) (if (> compared 0) compared 1)) (/ (* 100.0 matched) (if (> compared 0) compared 1))
#+end_src #+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 Only the generated C showed them. The fix is the same: bind to a
variable first. 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 Module =save= takes a =(* region-maps)= from module =maps=. Importing
=save= pastes its prototypes but not =region-maps=, so every importer =save= pastes its prototypes but not =region-maps=, so every importer
has to import =maps= itself, and before =save=: 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. =vsmv.sex= now imports eight modules in dependency order to use three.
Imports are at least idempotent (a diamond works). 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 =(pub record natural-shape (... (slots (* shape-cell)) ...))= with
=shape-cell= not =pub= compiles in its own module, and in the importer =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 fails with =unknown type name 'shape_cell'=. Either an error at the
definition or exporting the type would do. 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 A pub record field =(noises [(* simplex-sum) 32])= compiles in its own
module but not when pasted into an importer: module but not when pasted into an importer:
=Error: pointer chains are written flat, as (* * T), not nested: =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 =[* simplex-sum MAX_STRATA]= works, while a local
=(var names [(* const char) 6])= is fine either way. =(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)))= emits
=#define K cast(255, float) / cast(60, float)=: not translated, and =#define K cast(255, float) / cast(60, float)=: not translated, and
not parenthesized. With =(define D (/ -1.0 6.0))=, =(* x D)= becomes 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 from multiplying by the folded constant. Bit-exact code needs literal
values or typed =var=s. 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 =(if c a b)= in expression position becomes =c ? a : b=. Inside a
multi-line call, though, the statement anchor lands between the multi-line call, though, the statement anchor lands between the
ternary's parts, and the C doesn't compile: 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 =-C= output, without the directives, is fine. The build now passes
=--line-directives=toplevel= to every Sex unit. =--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 #+begin_src scheme
(typedef colour-fn (fn ((i32)) u32)) (typedef colour-fn (fn ((i32)) u32))
#+end_src #+end_src
@@ -120,59 +146,83 @@ Error: (cdr) bad argument type: u32
No location. The same type written inline in a parameter list works. 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 =(sizeof (* char))= becomes =sizeof(*char)=. There's no way to spell
the type; =(sizeof x)= on an expression works. 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 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 =(var bits u32 ...)= in the next is a C redefinition. Clang also warns
"label followed by a declaration is a C23 extension". Wrapping each "label followed by a declaration is a C23 extension". Wrapping each
body in =(do ...)= works around it; the writer could do that itself. 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 =(var xs [u16 CHUNK-AREA])= and record fields like
=(terrain-height [u16 CHUNK-AREA])= emit =CHUNK-AREA= literally, while =(terrain-height [u16 CHUNK-AREA])= emit =CHUNK-AREA= literally, while
=CHUNK-AREA= in an expression becomes =CHUNK_AREA=. Writing =CHUNK-AREA= in an expression becomes =CHUNK_AREA=. Writing
=CHUNK_AREA= in the type works around it. =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 =(fn ident-start? ...)= emits =ident_start?=, which isn't C. Lisp
predicates want =?=; =-= is mangled to =_=, so =?= could become =_p=. 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. =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 =0x80= reaches C as =|0x80|= (the Scheme printer escaping a symbol
that looks numeric), and =#x80= is rejected by the reader: that looks numeric), and =#x80= is rejected by the reader:
"Unsupported # syntax: #\x". Masks and code points have to be written "Unsupported # syntax: #\x". Masks and code points have to be written
in decimal, which hurts in bit-twiddling code: =(& c 224)= instead of in decimal, which hurts in bit-twiddling code: =(& c 224)= instead of
=(& c 0xE0)=. =(& c 0xE0)=.
* Explicit enum values emit raw names * DONE Explicit enum values emit raw names
Fixed in sexc 504f357 (sex#46).
#+begin_src scheme #+begin_src scheme
(pub enum wire ((wire-varint 0) (wire-fixed64 1))) (pub enum wire ((wire-varint 0) (wire-fixed64 1)))
#+end_src #+end_src
emits =wire-varint = 0, ...=, neither kebab-converted nor accepted by emits =wire-varint = 0, ...=, neither kebab-converted nor accepted by
C. Plain =(enum name (a b c))= works; explicit values need =define=s. 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 With =self= a =(* pb)=, =#(pb : (. self p) (. self p) true)= emits
=self.p=, not =self->p=. The same =(. self p)= outside a literal is =self.p=, not =self->p=. The same =(. self p)= outside a literal is
right. Bound to a local first, it works. 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 Inside one =ops= block, calling a method defined further down fails
with =no such method on pb len=. C needs prototypes, so this is with =no such method on pb len=. C needs prototypes, so this is
consistent, but the block could declare its methods before their consistent, but the block could declare its methods before their
bodies. 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 -= =--help= says -C output defaults to stdout without =-o=; passing =-o -=
explicitly dies in getopt-long's argument handling. 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 sexc dfafe8b. Writing the C-style grouped header
#+begin_src scheme #+begin_src scheme
@@ -191,7 +241,10 @@ Error: (caddr) bad argument type: ()
Expected: a diagnostic naming the file, the line and the expected shape Expected: a diagnostic naming the file, the line and the expected shape
of =for=. 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=: sexc dfafe8b. In =src/viewer.sex=:
#+begin_src scheme #+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 is known, and the access isn't read as a value. The nearby
=(& (. font handle))= gives no warning. =(& (. 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 sexc has nothing like =cc -MD=. An =import= pastes the imported
module's public forms into the importer, so the Makefile has to make module's public forms into the importer, so the Makefile has to make
every Sex object depend on every =.sex= source. 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 p (* const u8) (* s))
(var c u32 [p 0]) (var c u32 [p 0])
(var n int 0) (var n int 0)
;; TODO sex#47: write the UTF-8 masks in hex once there are hex (if (< c 0x80) (= n 0)
;; literals. (== (& c 0xE0) 0xC0) (do (= n 1) (&= c 0x1F))
(if (< c 128) (= n 0) (== (& c 0xF0) 0xE0) (do (= n 2) (&= c 0x0F))
(== (& c 224) 192) (do (= n 1) (&= c 31)) (== (& c 0xF8) 0xF0) (do (= n 3) (&= c 0x07))
(== (& c 240) 224) (do (= n 2) (&= c 15)) (do (= (* s) (+ p 1)) (return 0xFFFD)))
(== (& c 248) 240) (do (= n 3) (&= c 7))
(do (= (* s) (+ p 1)) (return 65533)))
(for (var i int 1) (<= i n) (++ i) (for (var i int 1) (<= i n) (++ i)
(if (!= (& [p i] 192) 128) (if (!= (& [p i] 0xC0) 0x80)
(do (= (* s) (+ p i)) (return 65533))) (do (= (* s) (+ p i)) (return 0xFFFD)))
(= c (c-bit-or (<< c 6) (& [p i] 63)))) (= c (c-bit-or (<< c 6) (& [p i] 0x3F))))
(= (* s) (+ p n 1)) (= (* s) (+ p n 1))
(return c)) (return c))
@@ -34,16 +32,14 @@
(var p (* const u8) (cast text (* const u8))) (var p (* const u8) (cast text (* const u8)))
(while (* p) (while (* p)
(var c u32 (utf8-next (& p))) (var c u32 (utf8-next (& p)))
(if (< c 65536) (if (< c 0x10000)
(do (do
(= [units n] c) (= [units n] c)
(+= n 1)) (+= n 1))
(do (do
;; TODO sex#47: write the surrogate constants in hex once (-= c 0x10000)
;; there are hex literals. (= [units n] (+ 0xD800 (>> c 10)))
(-= c 65536) (= [units (+ n 1)] (+ 0xDC00 (& c 0x3FF)))
(= [units n] (+ 55296 (>> c 10)))
(= [units (+ n 1)] (+ 56320 (& c 1023)))
(+= n 2)))) (+= n 2))))
(= (* out) units) (= (* out) units)
(return n)) (return n))
@@ -71,9 +67,7 @@
(if (> len 0) (if (> len 0)
(= h1 (hash-step h1 (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16))))) (= h1 (hash-step h1 (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16)))))
(free units) (free units)
;; TODO sex#47: write the multiplier (0x5D588B65) in hex once there (return (cast (+ (cast h1 u32) (* (cast h2 u32) (cast 0x5D588B65 u32))) i32)))
;; are hex literals.
(return (cast (+ (cast h1 u32) (* (cast h2 u32) (cast 1566083941 u32))) i32)))
;;; The world seed from the seed text in world settings. A number is ;;; The world seed from the seed text in world settings. A number is
;;; taken as it is, anything else is hashed. ;;; taken as it is, anything else is hashed.
@@ -109,6 +103,4 @@
(if (> len 0) (if (> len 0)
(= h2 (^ (+ (rotl5 h2) h2) (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16))))) (= h2 (^ (+ (rotl5 h2) h2) (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16)))))
(free units) (free units)
;; TODO sex#47: write the multiplier (0x5D588B65) in hex once there (return (cast (+ h1 (* h2 (cast 0x5D588B65 u32))) i32)))
;; are hex literals.
(return (cast (+ h1 (* h2 (cast 1566083941 u32))) i32)))

View File

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

View File

@@ -9,23 +9,20 @@
(pub include pthread.h) (pub include pthread.h)
(include stdio.h stdlib.h string.h math.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 maps)
(import lcg) (pub import worldgen)
(import noise) (pub import rivers)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(import terra) (import terra)
(import strata) (import strata)
(import ores) (pub import ores)
(import caves)
;;; MINERAL is the mineral whose reading is wanted, or -1. ;;; The most cave runs a column's answer lists.
(pub record hover-query ((x int) (z int) (mode int) (value int) (mineral int))) (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 (pub record hover-result
((valid bool) (query hover-query) ((valid bool) (query hover-query)
@@ -37,8 +34,11 @@
(rock int) (rock-y int) (surface-rock int) (rock int) (rock-y int) (surface-rock int)
(landform int) (province int) (climate int) (ocean int) (upheaval 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 ;; the pick's reading of the query's mineral, and its ore map's value
(mineral mineral-reading))) (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 (pub record hover-worker
((lock pthread-mutex-t) (wake pthread-cond-t) (thread pthread-t) (quit bool) ((lock pthread-mutex-t) (wake pthread-cond-t) (thread pthread-t) (quit bool)
@@ -58,7 +58,11 @@
;; the ore map last asked for: its mineral and region ;; the ore map last asked for: its mineral and region
(ore-map int-map) (ore-mineral int) (ore-rx int) (ore-rz int) (ore-map int-map) (ore-mineral int) (ore-rx int) (ore-rz int)
(plate (* river-plate)) (segments (* int)) (sampler river-sampler) (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)) (var region-kinds [int 5] #(0 2 1 4 3))
@@ -69,6 +73,9 @@
(if (. k plate) (river-plate/free (. k plate))) (if (. k plate) (river-plate/free (. k plate)))
(free (. k ore-map data)) (free (. k ore-map data))
(if (. k minerals) (ores/free (. k minerals))) (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 rocks) (strata/free (. k rocks)))
(if (. k tr) (terra/free (. k tr))) (if (. k tr) (terra/free (. k tr)))
(if (. k g) (worldgen/free (. k g))) (if (. k g) (worldgen/free (. k g)))
@@ -118,6 +125,27 @@
(= (. r sea-level) (. (. k tr) sea-level)) (= (. r sea-level) (. (. k tr) sea-level))
(strata/column (. k rocks) (/ x 32) (/ z 32) (% x 32) (% z 32) h (. k column)) (strata/column (. k rocks) (/ x 32) (/ z 32) (% x 32) (% z 32) h (. k column))
(= (. r surface-rock) [(. k column) h]) (= (. 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))) (if (&& (. k minerals) (>= (. q mineral) 0) (< (. q mineral) (. (. k minerals) count)))
(do (do
(if (|| (! (. k ore-map data)) (!= (. k ore-mineral) (. q mineral)) (!= (. k ore-rx) rx) (if (|| (! (. k ore-map data)) (!= (. k ore-mineral) (. q mineral)) (!= (. k ore-rx) rx)
@@ -128,7 +156,8 @@
(= (. k ore-mineral) (. q mineral)) (= (. k ore-mineral) (. q mineral))
(= (. k ore-rx) rx) (= (. k ore-rx) rx)
(= (. k ore-rz) rz))) (= (. k ore-rz) rz)))
(= (. r mineral) (ores/reading (. k minerals) (. q mineral) (& (. k ore-map)) x z (. k column) h)))) (= (. 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) (if (== (. q mode) 3)
(do (do
(= (. r rock) -3) (= (. r rock) -3)
@@ -176,6 +205,9 @@
(= (. k tr) (terra/make (. k g) (. w rivers))) (= (. k tr) (terra/make (. k g) (. w rivers)))
(= (. k rocks) (strata/make (. k g) (. w assets-dir))) (= (. k rocks) (strata/make (. k g) (. w assets-dir)))
(= (. k minerals) (ores/make settings (. w assets-dir) (. k rocks))) (= (. 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 sampler) (river-sampler/make (& (. w rivers)) (. settings size-y)))
(= (. k column) (malloc (+ (. settings size-y) 1))))) (= (. k column) (malloc (+ (. settings size-y) 1)))))
(= (. k generation) generation))) (= (. k generation) generation)))
@@ -214,6 +246,7 @@
(pthread-mutex-lock (& (. w lock))) (pthread-mutex-lock (& (. w lock)))
(if (|| (!= (. w query x) (. q x)) (!= (. w query z) (. q z)) (!= (. w query mode) (. q mode)) (if (|| (!= (. w query x) (. q x)) (!= (. w query z) (. q z)) (!= (. w query mode) (. q mode))
(!= (. w query value) (. q value)) (!= (. w query mineral) (. q mineral)) (!= (. w query value) (. q value)) (!= (. w query mineral) (. q mineral))
(!= (. w query caves) (. q caves))
(! (. w result valid))) (! (. w result valid)))
(do (do
(= (. w query) q) (= (. w query) q)

View File

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

View File

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

View File

@@ -62,6 +62,12 @@
(pub fn next-float ((self (* lcg))) float (pub fn next-float ((self (* lcg))) float
(return (/ (cast (.next-bits self) float) (cast INT32_MAX 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 (pub fn next-double ((self (* lcg))) double
(var r u32 (cast (>> (cast (. self current) i64) 24) u32)) (var r u32 (cast (>> (cast (. self current) i64) 24) u32))
(.advance self) (.advance self)

View File

@@ -10,11 +10,9 @@
;;; (size - pad-tl - pad-br) square. ;;; (size - pad-tl - pad-br) square.
(pub record int-map ((data (* i32)) (size i32) (pad-tl i32) (pad-br i32))) (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 (pub record region-maps
((landform int-map) (climate int-map) (geoprov int-map) (upheaval int-map) ((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 (pub fn region-maps/free ((m (* region-maps))) void
(free (. m landform data)) (free (. m landform data))

View File

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

View File

@@ -17,21 +17,17 @@
;;; where the game may already have put ore in some of it. And a ;;; where the game may already have put ore in some of it. And a
;;; child deposit (silver, gold, and peridot, whose reading comes from ;;; child deposit (silver, gold, and peridot, whose reading comes from
;;; the peridot inside olivine) is hosted by its parent's ore, so it ;;; the peridot inside olivine) is hosted by its parent's ore, so it
;;; can't be read at all without the deposits. ;;; 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) (include stdio.h stdlib.h string.h math.h dirent.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 cs)
(import maps) (import maps)
(import lcg) (pub import lcg)
(import noise) (import noise)
(import shape) (import shape)
(import json) (import json)
(import worldgen) (pub import worldgen)
(import fastnoise)
(import rivers)
(import terra) (import terra)
(import strata) (import strata)
@@ -63,8 +59,7 @@
(define DIST-NARROWGAUSSIAN 5) (define DIST-NARROWGAUSSIAN 5)
(define DIST-STRONGERINVEXP 6) (define DIST-STRONGERINVEXP 6)
;; TODO sex#57: make this private again once a pub record can use a ;;; pub because a mineral holds one, and its importers need the size
;; private type.
(pub record natfloat ((dist int) (avg float) (var float))) (pub record natfloat ((dist int) (avg float) (var float)))
;;; A mineral is one code with an ore map. Its map is made with the ;;; A mineral is one code with an ore map. Its map is made with the
@@ -78,10 +73,8 @@
;; the reading ;; the reading
(readable bool) (place int) (y natfloat) (abs-avg double) (bearing u32))) (readable bool) (place int) (y natfloat) (abs-avg double) (bearing u32)))
;; TODO sex#50: write MAX-MINERALS once constants in array types are
;; kebab-converted.
(pub record ores (pub record ores
((minerals [mineral MAX_MINERALS]) (count int) (granite int) (sea-level int))) ((minerals [mineral MAX-MINERALS]) (count int) (granite int) (sea-level int)))
;;; The reading at one column: TotalFactor and PartsPerThousand. ;;; The reading at one column: TotalFactor and PartsPerThousand.
(pub record mineral-reading ((total double) (ppt double))) (pub record mineral-reading ((total double) (ppt double)))
@@ -321,13 +314,11 @@
(= (. o sea-level) (cast (* 0.4313725490196078 (. settings size-y)) int)) (= (. o sea-level) (cast (* 0.4313725490196078 (. settings size-y)) int))
(var root [char 1024]) (var root [char 1024])
(snprintf root (sizeof root) "%s/survival/worldgen/deposits" assets-dir) (snprintf root (sizeof root) "%s/survival/worldgen/deposits" assets-dir)
(var paths [* char MAX_DEPOSIT_FILES]) (var paths [* char MAX-DEPOSIT-FILES])
(var n int 0) (var n int 0)
(list-files root "" paths (& n)) (list-files root "" paths (& n))
(qsort paths n (sizeof [paths 0]) by-name) (qsort paths n (sizeof [paths 0]) by-name)
;; TODO sex#60: size with MAX-DEPOSIT-FILES once arrays of a header (var files [* cJSON MAX-DEPOSIT-FILES])
;; type take a symbolic size.
(var files [* cJSON 64])
(for (var f int 0) (< f n) (++ f) (for (var f int 0) (< f n) (++ f)
(var path [char 1024]) (var path [char 1024])
(snprintf path (sizeof path) "%s/%s" root [paths f]) (snprintf path (sizeof path) "%s/%s" root [paths f])
@@ -420,9 +411,7 @@
(var val int (cast (cast c int) u8)) (var val int (cast (cast c int) u8))
(if (== val 0) (if (== val 0)
(return 0)) (return 0))
;; TODO sex#47: write the masks (0xFF0000, 0xFF00) in hex once there (return (c-bit-or val (max4 lt rt lb rb 0xFF0000) (max4 lt rt lb rb 0xFF00))))
;; are hex literals.
(return (c-bit-or val (max4 lt rt lb rb 16711680) (max4 lt rt lb rb 65280))))
;;; MapLayerOre.GenLayer. ;;; MapLayerOre.GenLayer.
(fn gen-unwobbled ((m (* const mineral)) (x0 int) (z0 int) (size-x int) (size-z int) (fn gen-unwobbled ((m (* const mineral)) (x0 int) (z0 int) (size-x int) (size-z int)
@@ -475,8 +464,9 @@
;;; Readings --------------------------------------------------------- ;;; Readings ---------------------------------------------------------
;;; IntDataMap2D.GetUnpaddedColorLerped, the low byte only. ;;; The ore map's value at column (x, z), 0 to 1: the low byte of
(fn ore-factor ((map (* const int-map)) (x int) (z int)) double ;;; 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 inner int (- (. map size) (. map pad-tl) (. map pad-br)))
(var px float (* (/ (cast (% x 512) float) (cast 512 float)) (cast inner float))) (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 pz float (* (/ (cast (% z 512) float) (cast 512 float)) (cast inner float)))
@@ -527,7 +517,7 @@
(if (&& (< rock 32) (!= (& (. m bearing) (<< (cast 1 u32) rock)) 0)) (if (&& (< rock 32) (!= (& (. m bearing) (<< (cast 1 u32) rock)) 0))
(++ q))) (++ q)))
(var rock-factor double (/ (cast q double) height)) (var rock-factor double (/ (cast q double) height))
(= (. r total) (* (ore-factor map x z) rock-factor)) (= (. r total) (* (ores/map-factor map x z) rock-factor))
(var blocks int (* height 1024)) (var blocks int (* height 1024))
(= (. r ppt) (* (/ (* (. r total) (. m abs-avg)) blocks) 1000)) (= (. r ppt) (* (/ (* (. r total) (. m abs-avg)) blocks) 1000))
(return r)) (return r))
@@ -542,3 +532,21 @@
(var k double (* total (cast 7.5 float))) (var k double (* total (cast 7.5 float)))
(if (> k 5) (= k 5)) (if (> k 5) (= k 5))
(return (+ 2 (cast k int)))) (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) (pub include stddef.h)
(include string.h) (include string.h)
;; TODO sex#46: make these a (pub enum wire ...) once explicit enum (pub enum wire ((WIRE-VARINT 0) (WIRE-FIXED64 1) (WIRE-BYTES 2) (WIRE-FIXED32 5)))
;; 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 record pb ((p (* const u8)) (end (* const u8)) (err bool))) (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 (ops pb
(pub fn of ((data (* const void)) (len size-t)) pb (pub fn of ((data (* const void)) (len size-t)) pb
(var p (* const u8) data) (var p (* const u8) data)
(return #(pb : p (+ p len) false))) (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 (pub fn more ((self (* const pb))) bool
(return (< (. self p) (. self end)))) (return (< (. self p) (. self end))))
(pub fn len ((self (* const pb))) size-t (pub fn len ((self (* const pb))) size-t
(return (cast (- (. self end) (. self p)) size-t))) (return (cast (- (. self end) (. self p)) size-t)))
(pub fn varint ((self (* pb))) u64 ;; True when the rest of the window spells exactly S, e.g. a map
(var v u64 0) ;; entry's key against "riverDistance".
(for (var shift int 0) (< shift 64) (+= shift 7) (pub fn equals ((self (* const pb)) (s (* const char))) bool
(if (>= (. self p) (. self end)) (var n size-t (.len self))
(break)) (return (&& (== (strlen s) n) (== (memcmp (. self p) s n) 0))))
(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)))
;; The next field's number, or 0 at the end. WIRE gets its wire type. ;; The next field's number, or 0 at the end. WIRE gets its wire type.
(pub fn field ((self (* pb)) (wire (* int))) u32 (pub fn field ((self (* pb)) (wire (* int))) u32
@@ -62,12 +37,29 @@
(= (* wire) (cast (& key 7) int)) (= (* wire) (cast (& key 7) int))
(return (cast (>> key 3) u32))) (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 ;; A length-delimited field as a reader of its own: a submessage, a
;; string, or a packed array. ;; string, or a packed array.
(pub fn bytes ((self (* pb))) pb (pub fn bytes ((self (* pb))) pb
(var len u64 (.varint self)) (var len u64 (.varint self))
;; TODO sex#45: use (. self p) in the literals once member access ;; where the window starts, before self moves past it
;; inside a compound literal follows the pointer.
(var p (* const u8) (. self p)) (var p (* const u8) (. self p))
(if (> len (.len self)) (if (> len (.len self))
(do (do
@@ -76,21 +68,19 @@
(+= (. self p) len) (+= (. self p) len)
(return #(pb : p (+ p len) false))) (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 (pub fn skip ((self (* pb)) (wire int)) void
(switch wire (switch wire
(case WIRE-VARINT (.varint self) (break)) (case WIRE-VARINT (.varint self) (break))
(case WIRE-BYTES (.bytes self) (break)) (case WIRE-BYTES (.bytes self) (break))
(case WIRE-FIXED64 (.advance self 8) (break)) (case WIRE-FIXED64 (.advance self 8) (break))
(case WIRE-FIXED32 (.advance self 4) (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. ;;; every RNG call is the mod's: it is what the layout depends on.
(include stdlib.h string.h math.h) (include stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings (pub import lcg)
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(import noise)
(import shape) (import shape)
(import json) (import json)
(import worldgen) (import worldgen)
(import fastnoise) (pub import fastnoise)
(pub record river-config (pub record river-config
((min-fork-angle int) (fork-variation int) (normal-angle int) ((min-fork-angle int) (fork-variation int) (normal-angle int)
@@ -151,11 +146,7 @@
(var dy double (- (. end y) (. start y))) (var dy double (- (. end y) (. start y)))
(var v double (+ (* (- (. p x) (. start x)) dx) (* (- (. p y) (. start y)) dy))) (var v double (+ (* (- (. p x) (. start x)) dx) (* (- (. p y) (. start y)) dy)))
(/= v (+ (* dx dx) (* dy dy))) (/= v (+ (* dx dx) (* dy dy)))
;; TODO sex#59: clamp inside the cast once a conditional operand (return (cast (if (< v 0) 0 (if (> v 1) 1 v)) float)))
;; keeps its parentheses.
(if (< v 0) (= v 0))
(if (> v 1) (= v 1))
(return (cast v float)))
(fn distance-to-line ((p vec2) (s vec2) (e vec2)) double (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) (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 n int (. p config zones-in-region))
(var best-x int x) (var best-x int x)
(var best-z int z) (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) (var found bool false)
(for (var dx int -1) (<= dx 1) (++ dx) (for (var dx int -1) (<= dx 1) (++ dx)
(for (var dz int -1) (<= dz 1) (++ dz) (for (var dz int -1) (<= dz 1) (++ dz)

View File

@@ -7,7 +7,7 @@
;;; data itself, matched against the map sizes in TerraGenConfig. ;;; data itself, matched against the map sizes in TerraGenConfig.
(pub include sqlite3.h) (pub include sqlite3.h)
(include stdio.h stdlib.h string.h) (include stdio.h stdlib.h string.h zstd.h)
(import pb) (import pb)
(import maps) (import maps)
@@ -15,13 +15,12 @@
(pub define REGION-SIZE 512) (pub define REGION-SIZE 512)
(pub define CHUNK-SIZE 32) (pub define CHUNK-SIZE 32)
(pub define CHUNK-AREA 1024) (pub define CHUNK-AREA 1024)
(pub define CHUNK-VOLUME 32768)
(pub define MAX-STORIES 32) (pub define MAX-STORIES 32)
;; TODO sex#50: write CHUNK-AREA once constants in array types are
;; kebab-converted.
(pub record chunk-maps (pub record chunk-maps
((terrain-height [u16 CHUNK_AREA]) (rain-height [u16 CHUNK_AREA]) ((terrain-height [u16 CHUNK-AREA]) (rain-height [u16 CHUNK-AREA])
(top-rock [i32 CHUNK_AREA]) (river-distance [u16 CHUNK_AREA]) (top-rock [i32 CHUNK-AREA]) (river-distance [u16 CHUNK-AREA])
(has-river-distance bool))) (has-river-distance bool)))
(pub record story-location ((code [char 64]) (x i32) (y i32) (z i32))) (pub record story-location ((code [char 64]) (x i32) (y i32) (z i32)))
@@ -34,11 +33,12 @@
((db (* sqlite3)) (seed i32) (size-x i32) (size-y i32) (size-z i32) ((db (* sqlite3)) (seed i32) (size-x i32) (size-y i32) (size-z i32)
(config-keys (* * char)) (config-values (* * char)) (config-count int) (config-keys (* * char)) (config-values (* * char)) (config-count int)
(block-codes (* * char)) (block-count int) (block-codes (* * char)) (block-count int)
;; TODO sex#50: write MAX-STORIES once constants in array types are (stories [story-location MAX-STORIES]) (story-count int)
;; kebab-converted.
(stories [story-location MAX_STORIES]) (story-count int)
;; every player's stored pick readings ;; every player's stored pick readings
(pick-readings (* pick-reading)) (pick-reading-count int))) (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, ;;; Map regions and map chunks share one key: x in the low 27 bits,
;;; z above them. ;;; z above them.
@@ -83,21 +83,17 @@
(switch type (switch type
(case 1 (snprintf value 64 "%d" (cast (read-le (& r) 4) i32)) (break)) (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)) (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 (case 3
(do
(var bits u64 (read-le (& r) 8)) (var bits u64 (read-le (& r) 8))
(var d double) (var d double)
(memcpy (& d) (& bits) 8) (memcpy (& d) (& bits) 8)
(snprintf value 64 "%.17g" d)) (snprintf value 64 "%.17g" d)
(break)) (break))
(case 4 (case 4
(do
(var bits u32 (cast (read-le (& r) 4) u32)) (var bits u32 (cast (read-le (& r) 4) u32))
(var f float) (var f float)
(memcpy (& f) (& bits) 4) (memcpy (& f) (& bits) 4)
(snprintf value 64 "%.9g" (cast f double))) (snprintf value 64 "%.9g" (cast f double))
(break)) (break))
(case 5 (case 5
(add-config s key (read-dotnet-string (& r))) (add-config s key (read-dotnet-string (& r)))
@@ -132,9 +128,7 @@
(if (> id max-id) (= max-id id))) (if (> id max-id) (= max-id id)))
(.skip (& entry) wire)))) (.skip (& entry) wire))))
(= (. s block-count) (+ max-id 1)) (= (. s block-count) (+ max-id 1))
;; TODO sex#52: write (sizeof (* char)) once sizeof takes a pointer (= (. s block-codes) (calloc (+ max-id 1) (sizeof (* char))))
;; type.
(= (. s block-codes) (calloc (+ max-id 1) (sizeof [(. s block-codes) 0])))
(while (> (.field (& r) (& wire)) 0) (while (> (.field (& r) (& wire)) 0)
(var entry pb (.bytes (& r))) (var entry pb (.bytes (& r)))
(var id int -1) (var id int -1)
@@ -242,6 +236,17 @@
(== f 3) (= (. s size-z) (.int32 (& r))) (== f 3) (= (. s size-z) (.int32 (& r)))
(== f 7) (= (. s seed) (.int32 (& r))) (== f 7) (= (. s seed) (.int32 (& r)))
(== f 31) (read-tree-attribute s (.bytes (& 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) (== f 11)
(do (do
(var entry pb (.bytes (& r))) (var entry pb (.bytes (& r)))
@@ -392,6 +397,38 @@
(sqlite3-finalize stmt) (sqlite3-finalize stmt)
(return n)) (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 ------------------------------------------------------- ;;; Map chunks -------------------------------------------------------
;;; A repeated ushort field arrives one value per field, or packed. ;;; A repeated ushort field arrives one value per field, or packed.
@@ -453,6 +490,146 @@
(sqlite3-finalize stmt) (sqlite3-finalize stmt)
(return found)) (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): ;;; The stored extent of a table, in its own units (regions or chunks):
;;; inclusive bounds and the row count. ;;; inclusive bounds and the row count.
(pub record extent ((x0 i32) (z0 i32) (x1 i32) (z1 i32) (count i64))) (pub record extent ((x0 i32) (z0 i32) (x1 i32) (z1 i32) (count i64)))

View File

@@ -1,6 +1,7 @@
;;; Finds the block nearest a point where one of a set of rocks lies, at ;;; Finds the block nearest a point where one of a set of rocks lies, at
;;; the surface, at a depth below it, at a Y or at any depth; or where ;;; the surface, at a depth below it, at a Y or at any depth; where the
;;; the prospecting pick reads a mineral at least so high. ;;; 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 ;;; Regions are taken in order of their distance from the point and
;;; sampled every 16 blocks by several threads at once, each with its ;;; sampled every 16 blocks by several threads at once, each with its
@@ -11,32 +12,27 @@
(pub include pthread.h) (pub include pthread.h)
(include stdio.h stdlib.h string.h math.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 maps)
(import lcg) (pub import worldgen)
(import noise) (pub import rivers)
(import shape)
(import json)
(import worldgen)
(import fastnoise)
(import rivers)
(import terra) (import terra)
(import strata) (import strata)
(import ores) (import ores)
(import caves)
(pub define SEARCH-RADIUS-REGIONS 24) (pub define SEARCH-RADIUS-REGIONS 24)
;;; The mode that looks for a mineral: the value is the mineral, the ;;; The mode that looks for a mineral: the value is the mineral, the
;;; mask the least reading category. ;;; mask the least reading category.
(pub define SEARCH-MINERAL 4) (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 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 (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) (cancel bool)
;; the question ;; the question
(settings world-settings) (rivers river-config) (assets-dir [char 1024]) (settings world-settings) (rivers river-config) (assets-dir [char 1024])
@@ -49,17 +45,16 @@
(record region-order ((rx int) (rz int) (distance double))) (record region-order ((rx int) (rz int) (distance double)))
(fn by-distance ((pa (* const void)) (pb (* const void))) int (fn by-distance ((pa (* const void)) (pb (* const void))) int
;; TODO sex#61: cast inside the field access once a cast as the object (var a _ (. (cast pa (* const region-order)) distance))
;; of . keeps its parentheses. (var b _ (. (cast pb (* const region-order)) distance))
(var a (* const region-order) pa) (return (- (> a b) (< a b))))
(var b (* const region-order) pb)
(return (- (> (. a distance) (. b distance)) (< (. a distance) (. b distance)))))
;;; A thread's generators, and the searched mineral's ore map of the ;;; A thread's generators, and the searched mineral's ore map of the
;;; region it last scanned in. ;;; region it last scanned in; for caves, a chunk's terrain and states.
(record scanner (record scanner
((tr (* terra)) (rocks (* strata)) (minerals (* ores)) (column (* u8)) ((tr (* terra)) (rocks (* strata)) (minerals (* ores)) (column (* u8))
(ore-map int-map) (ore-rx int) (ore-rz int))) (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 (fn region-distance ((s (* const search)) (rx int) (rz int)) double
(var x0 double (* rx 512.0)) (var x0 double (* rx 512.0))
@@ -84,7 +79,8 @@
;;; Whether column (x, z), with the strata in the scanner's column, ;;; 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 ;;; 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 ;;; depth (mode 3) anywhere from y = 1 to the surface; or a reading of
;;; the mineral of at least the mask's category. ;;; 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 (fn column-matches ((s (* const search)) (sc (* scanner)) (x int) (z int) (height int)) bool
(var column (* const u8) (. sc column)) (var column (* const u8) (. sc column))
(if (== (. s mode) SEARCH-MINERAL) (if (== (. s mode) SEARCH-MINERAL)
@@ -97,9 +93,9 @@
(ores/map (. sc minerals) (. s value) rx rz (& (. sc ore-map))) (ores/map (. sc minerals) (. s value) rx rz (& (. sc ore-map)))
(= (. sc ore-rx) rx) (= (. sc ore-rx) rx)
(= (. sc ore-rz) rz))) (= (. sc ore-rz) rz)))
(var r mineral-reading (ores/reading (. sc minerals) (. s value) (& (. sc ore-map)) x z (return (>= (ores/category-at (. sc minerals) (. s value) (& (. sc ore-map)) x z column
column height)) height)
(return (>= (ores/category (. r total)) (cast (. s mask) int))))) (cast (. s mask) int)))))
(if (!= (. s mode) 3) (if (!= (. s mode) 3)
(return (matches s (rock-at column height (. s mode) (. s value))))) (return (matches s (rock-at column height (. s mode) (. s value)))))
(for (var y int 1) (<= y height) (++ y) (for (var y int 1) (<= y height) (++ y)
@@ -123,6 +119,27 @@
;;; Every STEP-th column of chunk (cx, cz) against the mask. ;;; Every STEP-th column of chunk (cx, cz) against the mask.
(fn scan-chunk ((s (* search)) (sc (* scanner)) (cx int) (cz int) (step int)) void (fn scan-chunk ((s (* search)) (sc (* scanner)) (cx int) (cz int) (step int)) void
(var heights [u16 1024]) (var heights [u16 1024])
;; 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) (terra/chunk-heights (. sc tr) cx cz step heights)
(for (var lz int 0) (< lz 32) (+= lz step) (for (var lz int 0) (< lz 32) (+= lz step)
(for (var lx int 0) (< lx 32) (+= lx step) (for (var lx int 0) (< lx 32) (+= lx step)
@@ -143,7 +160,13 @@
(if (&& (. sc rocks) (== (. s mode) SEARCH-MINERAL)) (if (&& (. sc rocks) (== (. s mode) SEARCH-MINERAL))
(= (. sc minerals) (ores/make (. s settings) (. s assets-dir) (. sc rocks)))) (= (. sc minerals) (ores/make (. s settings) (. s assets-dir) (. sc rocks))))
(= (. sc column) (malloc (+ (. s settings size-y) 1))) (= (. sc column) (malloc (+ (. s settings size-y) 1)))
(var ready bool (&& (. sc tr) (. sc rocks) (|| (!= (. s mode) SEARCH-MINERAL) (. sc minerals)))) (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 (while ready
(pthread-mutex-lock (& (. s lock))) (pthread-mutex-lock (& (. s lock)))
(var i int (. s next)) (var i int (. s next))
@@ -183,6 +206,9 @@
(scan-chunk s (& sc) cx cz 1))))) (scan-chunk s (& sc) cx cz 1)))))
(free (. sc column)) (free (. sc column))
(free (. sc ore-map data)) (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 minerals) (ores/free (. sc minerals)))
(if (. sc rocks) (strata/free (. sc rocks))) (if (. sc rocks) (strata/free (. sc rocks)))
(if (. sc tr) (terra/free (. sc tr))) (if (. sc tr) (terra/free (. sc tr)))

View File

@@ -3,20 +3,15 @@
;;; has the seed as typed and the world config as strings. ;;; has the seed as typed and the world config as strings.
(include stdio.h stdlib.h string.h) (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 cs)
(import json) (import json)
(import maps)
(import lcg)
(import noise)
(import shape)
(import save) (import save)
(import worldgen) (pub import worldgen)
;;; Settings plus the seed as the user would type it. ;;; Settings plus the seed as the user would type it, and the world's
(pub record world-source ((settings world-settings) (seed-text [char 128]))) ;;; 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 (fn ends-with ((s (* const char)) (suffix (* const char))) bool
(var n size-t (strlen s)) (var n size-t (strlen s))
@@ -35,6 +30,9 @@
(= (. out settings size-y) (. s size-y)) (= (. out settings size-y) (. s size-y))
(= (. out settings size-z) (. s size-z)) (= (. out settings size-z) (. s size-z))
(snprintf (. out seed-text) (sizeof (. out seed-text)) "%d" (. s seed)) (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) (save/close s)
(return true)) (return true))
@@ -55,6 +53,14 @@
(var map-size-y (* cJSON) (cJSON-GetObjectItem world "MapSizeY")) (var map-size-y (* cJSON) (cJSON-GetObjectItem world "MapSizeY"))
(if (cJSON-IsNumber map-size-y) (if (cJSON-IsNumber map-size-y)
(= (. out settings size-y) (cast (cJSON-GetNumberValue map-size-y) int))) (= (. 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")) (var config (* cJSON) (cJSON-GetObjectItem world "WorldConfiguration"))
(for (var item (* cJSON) (if config (. config child) NULL)) item (= item (. item next)) (for (var item (* cJSON) (if config (. config child) NULL)) item (= item (. item next))
(var text [char 64]) (var text [char 64])
@@ -70,6 +76,7 @@
(pub fn world-source/load ((path (* const char)) (out (* world-source))) bool (pub fn world-source/load ((path (* const char)) (out (* world-source))) bool
(= (. out settings) (world-settings/defaults)) (= (. out settings) (world-settings/defaults))
(snprintf (. out seed-text) (sizeof (. out seed-text)) "0") (snprintf (. out seed-text) (sizeof (. out seed-text)) "0")
(= (. out has-spawn) false)
(if (ends-with path ".vcdbs") (if (ends-with path ".vcdbs")
(return (from-save path out))) (return (from-save path out)))
(return (from-server-config path out))) (return (from-server-config path out)))

View File

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

View File

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

View File

@@ -10,27 +10,20 @@
;;; certainly air above. ;;; certainly air above.
(include stdio.h stdlib.h string.h math.h) (include stdio.h stdlib.h string.h math.h)
;; TODO sex#58: import only the modules used here once an import brings (pub import maps)
;; the types its interface needs; until then, every dependency, in
;; dependency order.
(import maps)
(import lcg)
(import noise) (import noise)
(import shape) (import shape)
(import json) (pub import worldgen)
(import worldgen) (pub import fastnoise)
(import fastnoise) (pub import rivers)
(import rivers)
;;; NewSimplexNoiseLayer -------------------------------------------- ;;; NewSimplexNoiseLayer --------------------------------------------
;; TODO sex#47: write these in hex, as the C# does, once there are hex (define PRIME-X 0x5205402B9270C86F)
;; literals. (define PRIME-Y 0x598CD327003817B5)
(define PRIME-X 5910200641878280303) (define PRIME-Z 0x5BCC226E9FA0BACB)
(define PRIME-Y 6452764530575939509) (define HASH-MULTIPLIER 0x53A3F72DEEC546F5)
(define PRIME-Z 6614699811220273867) (define SEED-FLIP -0x52D547B2E96ED629)
(define HASH-MULTIPLIER 6026932503003350773)
(define SEED-FLIP -5968755714895566377)
(define NORMALIZER-3D 0.2781926117527186) (define NORMALIZER-3D 0.2781926117527186)
(define MAX-Y-SLOPE 5.0) (define MAX-Y-SLOPE 5.0)
@@ -145,14 +138,9 @@
(var xf1 float (- (* (cast (- -2 (* xn 4)) float) x1) one)) (var xf1 float (- (* (cast (- -2 (* xn 4)) float) x1) one))
(var yf1 float (- (* (cast (- -2 (* yn 4)) float) y1) one)) (var yf1 float (- (* (cast (- -2 (* yn 4)) float) y1) one))
(var zf1 float (- (* (cast (- -2 (* zn 4)) float) z1) 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 (var xs float (cast (c-bit-or xn 1) float))
;; a bitwise expression keeps its parentheses. (var ys float (cast (c-bit-or yn 1) float))
(var xsi int (c-bit-or xn 1)) (var zs float (cast (c-bit-or zn 1) float))
(var ysi int (c-bit-or yn 1))
(var zsi int (c-bit-or zn 1))
(var xs float xsi)
(var ys float ysi)
(var zs float zsi)
(var skip5 bool false) (var skip5 bool false)
(var a2 float (+ xf0 a0)) (var a2 float (+ xf0 a0))
@@ -285,8 +273,7 @@
;;; *tanh* curve. GenTerra turns its threshold into a noise value with ;;; *tanh* curve. GenTerra turns its threshold into a noise value with
;;; this one, though the column bounds use the new noise's own curve. ;;; this one, though the column bounds use the new noise's own curve.
(fn tanh-curve-inverse ((v double)) double (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)) (if (>= v 1.0) (return INFINITY))
(return (* 0.5 (log (/ v (- 1.0 v)))))) (return (* 0.5 (log (/ v (- 1.0 v))))))
@@ -658,8 +645,11 @@
;;; A height is the top solid block, 0 if there is none. ;;; 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 ;;; Heights of the columns of chunk (cx, cz) from local (lx0, lz0) to
;;; (lx1, lz1) inclusive, every STEP-th, into HEIGHTS[lz * 32 + lx]. ;;; (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) (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)) (use-region t (/ cx 16) (/ cz 16))
(var per-plate int (river-plate/chunks (& (. t config)))) (var per-plate int (river-plate/chunks (& (. t config))))
(var plate (* river-plate) (use-plate t (/ cx per-plate) (/ cz per-plate))) (var plate (* river-plate) (use-plate t (/ cx per-plate) (/ cz per-plate)))
@@ -680,11 +670,9 @@
(var oct-a [double 64]) (var oct-a [double 64])
(var oct-t [double 64]) (var oct-t [double 64])
(for (var k int 0) (< k 4) (++ k) (for (var k int 0) (< k 4) (++ k)
;; TODO sex#59: put the (if ...)s in the sums below once a (landform-weights/at (& (. t weights))
;; conditional operand keeps its parentheses. (+ base-x (if (& k 1) pixel 0)) (+ base-z (if (& k 2) pixel 0))
(var ox float (if (& k 1) pixel 0)) w n)
(var oz float (if (& k 2) pixel 0))
(landform-weights/at (& (. t weights)) (+ base-x ox) (+ base-z oz) w n)
(interpolated-octaves t w (+ oct-a (* k 16)) (+ oct-t (* k 16)))) (interpolated-octaves t w (+ oct-a (* k 16)) (+ oct-t (* k 16))))
(var delta float (/ (cast 1 float) (cast 32 float))) (var delta float (/ (cast 1 float) (cast 32 float)))
@@ -793,7 +781,11 @@
(! (|| (<= y (- baseline bank-blocks)) (! (|| (<= y (- baseline bank-blocks))
(>= (cast y float) (+ baseline (* bank-blocks (. c top-factor))))))) (>= (cast y float) (+ baseline (* bank-blocks (. c top-factor)))))))
(= solid false)) (= 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)))) (= [heights (+ (* lz 32) lx)] (cast height u16))))
(free w)) (free w))
@@ -801,7 +793,19 @@
;;; multiples of STEP, into HEIGHTS[lz * 32 + lx]; the rest are left ;;; multiples of STEP, into HEIGHTS[lz * 32 + lx]; the rest are left
;;; alone. ;;; alone.
(pub fn terra/chunk-heights ((t (* terra)) (cx int) (cz int) (step int) (heights (* u16))) void (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 ;;; The height of the one column at block (x, z): 1/1024th of a chunk's
;;; work, for a cursor or a probe. ;;; work, for a cursor or a probe.
@@ -809,5 +813,5 @@
(var heights [u16 1024]) (var heights [u16 1024])
(var lx int (% x 32)) (var lx int (% x 32))
(var lz int (% z 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)])) (return [heights (+ (* lz 32) lx)]))

View File

@@ -13,20 +13,15 @@
(pub include pthread.h SDL3/SDL.h) (pub include pthread.h SDL3/SDL.h)
(include stdio.h stdlib.h string.h math.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 maps)
(import lcg) (pub import shape)
(import noise) (pub import worldgen)
(import shape)
(import worldgen)
(import fastnoise) (import fastnoise)
(import rivers) (pub import rivers)
(import terra) (import terra)
(import strata) (import strata)
(import ores) (import ores)
(import caves)
(pub define MAX-TILES 65536) (pub define MAX-TILES 65536)
;;; Not worldgen maps: Rivers' distance to the nearest river, the ;;; Not worldgen maps: Rivers' distance to the nearest river, the
@@ -37,6 +32,7 @@
(pub define LAYER-HEIGHT 7) (pub define LAYER-HEIGHT 7)
(pub define LAYER-ROCK 8) (pub define LAYER-ROCK 8)
(pub define LAYER-MINERAL 9) (pub define LAYER-MINERAL 9)
(pub define LAYER-CAVES 10)
(pub define ROCK-AT-SURFACE 0) (pub define ROCK-AT-SURFACE 0)
(pub define ROCK-AT-DEPTH 1) (pub define ROCK-AT-DEPTH 1)
(pub define ROCK-AT-Y 2) (pub define ROCK-AT-Y 2)
@@ -44,13 +40,15 @@
(pub define ROCK-ANY-DEPTH 3) (pub define ROCK-ANY-DEPTH 3)
;;; Mineral tile values: this plus the reading's category. ;;; Mineral tile values: this plus the reading's category.
(pub define MINERAL-VALUE-BASE 64) (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. ;;; Rock tile values besides rock indices.
(pub define VALUE-WATER 253) (pub define VALUE-WATER 253)
(pub define VALUE-AIR 254) (pub define VALUE-AIR 254)
;;; River tiles are sampled at a resolution the viewer picks by zoom, ;;; 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 ;;; in the key's `stratum': a column costs too much to sample them all
;;; for an overview. ;;; for an overview.
(define MAX-WORKERS 32) (pub define MAX-WORKERS 32)
(define TILE-FREE 0) (define TILE-FREE 0)
(define TILE-QUEUED 1) (define TILE-QUEUED 1)
@@ -72,54 +70,44 @@
(pub record tiles (pub record tiles
((lock pthread-mutex-t) (wake pthread-cond-t) ((lock pthread-mutex-t) (wake pthread-cond-t)
;; TODO sex#50: write MAX-TILES once constants in array types are (slots [tile MAX-TILES]) (index cell-map)
;; kebab-converted. (queue [int MAX-TILES]) (queue-len int) (queue-pos int)
(slots [tile MAX_TILES]) (index cell-map) (free-slots [int MAX-TILES]) (free-count int)
(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) (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 (workers [pthread-t MAX-WORKERS]) (worker-count int) (quit bool) (frame u64) (waiting int)
;; take a symbolic size.
(workers [pthread-t 32]) (worker-count int) (quit bool) (frame u64) (waiting int)
(palette [u32 256]))) (palette [u32 256])))
(fn key-hash ((k tile-key)) u64 (fn key-hash ((k tile-key)) u64
;; one-to-one: region x and z 16 bits each, map 4, stratum or ;; one-to-one: region x and z 16 bits each, map 4, stratum or
;; resolution 10, param 18 ;; resolution 10, param 18
;; TODO sex#47: write the field masks in hex once there are hex (return (c-bit-or (cast (& (. k rx) 0xFFFF) u64)
;; literals. (<< (cast (& (. k rz) 0xFFFF) u64) 16)
(return (c-bit-or (cast (& (. k rx) 65535) u64) (<< (cast (& (. k map) 0xF) u64) 32)
(<< (cast (& (. k rz) 65535) u64) 16) (<< (cast (& (. k stratum) 0x3FF) u64) 36)
(<< (cast (& (. k map) 15) u64) 32) (<< (cast (& (. k param) 0x3FFFF) u64) 46))))
(<< (cast (& (. k stratum) 1023) u64) 36)
(<< (cast (& (. k param) 262143) u64) 46))))
;;; The tile index is a cell-map keyed by (x, z): the hash is split ;;; The tile index is a cell-map keyed by (x, z): the hash is split
;;; over the two halves. ;;; 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 (fn index-get ((t (* tiles)) (k tile-key)) int
(var h u64 (key-hash k)) (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 (fn index-put ((t (* tiles)) (k tile-key) (slot int)) void
(var h u64 (key-hash k)) (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 (fn index-remove ((t (* tiles)) (k tile-key)) void
(var h u64 (key-hash k)) (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 ----------------------------------------------------- ;;; Colouring -----------------------------------------------------
;;; A distinct, stable colour per landform index. ;;; A distinct, stable colour per landform index.
(fn landform-colour ((i u32)) u32 (fn landform-colour ((i u32)) u32
;; TODO sex#47: write the multiplier (0x9E3779B1) and masks in hex (var h u32 (* (+ i 1) (cast 0x9E3779B1 u32)))
;; once there are hex literals. (return (c-bit-or (<< (+ 48 (& (>> h 24) 0xBF)) 16)
(var h u32 (* (+ i 1) (cast 2654435761 u32))) (<< (+ 48 (& (>> h 16) 0xBF)) 8)
(return (c-bit-or (<< (+ 48 (& (>> h 24) 191)) 16) (+ 48 (& (>> h 8) 0xBF)))))
(<< (+ 48 (& (>> h 16) 191)) 8)
(+ 48 (& (>> h 8) 191)))))
(fn lerp-colour ((a u32) (b u32) (t int)) u32 (fn lerp-colour ((a u32) (b u32) (t int)) u32
(var r u32 0) (var r u32 0)
@@ -130,20 +118,18 @@
(return r)) (return r))
(fn colour-of ((g (* const worldgen)) (map int) (v int)) u32 (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 (switch map
;; landforms.json gives most landforms the same green, so these ;; landforms.json gives most landforms the same green, so these
;; are coloured by index instead ;; are coloured by index instead
(case MAP-LANDFORM (return (landform-colour (cast v u32)))) (case MAP-LANDFORM (return (landform-colour (cast v u32))))
(case MAP-PROVINCE (case MAP-PROVINCE
(return (if (&& (>= v 0) (< v (. g provinces count))) [(. g provinces colours) v] 0))) (return (if (&& (>= v 0) (< v (. g provinces count))) [(. g provinces colours) v] 0)))
(case MAP-CLIMATE (return (& (cast v u32) 16777215))) (case MAP-CLIMATE (return (& (cast v u32) 0xFFFFFF)))
(case MAP-OCEAN (return (lerp-colour 6326847 1919884 v))) (case MAP-OCEAN (return (lerp-colour 0x608A3F 0x1D4B8C v)))
(default (default
(if (< v 0) (= v 0)) (if (< v 0) (= v 0))
(if (> v 255) (= v 255)) (if (> v 255) (= v 255))
(return (* (cast v u32) 65793))))) (return (* (cast v u32) 0x010101)))))
;;; The tile's inner pixels, coloured, as ARGB. ;;; The tile's inner pixels, coloured, as ARGB.
(fn render ((g (* worldgen)) (k tile-key) (size (* int))) (* u32) (fn render ((g (* worldgen)) (k tile-key) (size (* int))) (* u32)
@@ -154,9 +140,7 @@
(for (var z int 0) (< z inner) (++ z) (for (var z int 0) (< z inner) (++ z)
(for (var x int 0) (< x inner) (++ x) (for (var x int 0) (< x inner) (++ x)
(var v int [(. m data) (+ (* (+ z (. m pad-tl)) (. m size)) x (. m pad-tl))]) (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 (= [px (+ (* z inner) x)] (c-bit-or 0xFF000000 (colour-of g (. k map) v)))))
;; literals.
(= [px (+ (* z inner) x)] (c-bit-or 4278190080 (colour-of g (. k map) v)))))
(free (. m data)) (free (. m data))
(= (* size) inner) (= (* size) inner)
(return px)) (return px))
@@ -197,12 +181,11 @@
(= (. c segments) (realloc (. c segments) (* (. c segment-cap) (sizeof int)))))) (= (. c segments) (realloc (. c segments) (* (. c segment-cap) (sizeof int))))))
(return p)) (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 (fn river-colour ((distance int) (valley int) (ocean bool)) u32
(if ocean (return 1784427)) (if ocean (return 0x1B3A6B))
(if (== distance 0) (return 3043288)) (if (== distance 0) (return 0x2E6FD8))
(if (< distance valley) (return (lerp-colour 8369128 5143098 (/ (* distance 255) valley)))) (if (< distance valley) (return (lerp-colour 0x7FB3E8 0x4E7A3A (/ (* distance 255) valley))))
(return 4022062)) (return 0x3D5F2E))
(fn render-rivers ((g (* worldgen)) (cache (* river-cache)) (config (* const river-config)) (fn render-rivers ((g (* worldgen)) (cache (* river-cache)) (config (* const river-config))
(k tile-key) (size (* int))) (* u32) (k tile-key) (size (* int))) (* u32)
@@ -230,32 +213,26 @@
(var ox int (+ (* cx (/ 32 step)) dx)) (var ox int (+ (* cx (/ 32 step)) dx))
(var oz int (+ (* cz (/ 32 step)) dz)) (var oz int (+ (* cz (/ 32 step)) dz))
(= [px (+ (* oz res) ox)] (= [px (+ (* oz res) ox)]
;; TODO sex#47: write the opaque alpha in hex once there (c-bit-or 0xFF000000 (river-colour d valley (river-plate/ocean-at p x z))))))))
;; are hex literals.
(c-bit-or 4278190080 (river-colour d valley (river-plate/ocean-at p x z))))))))
(= (* size) res) (= (* size) res)
(return px)) (return px))
;;; Terrain height, shaded: water by depth under sea level, land by ;;; Terrain height, shaded: water by depth under sea level, land by
;;; height, lit from the north-west. ;;; 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 (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)) (var depth int (- sea h))
(if (> depth 40) (= depth 40))
(if (< h sea) (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 t int (/ (* (- h sea) 255) (- size-y sea)))
(var base u32 (if (< t 32) (lerp-colour 5605944 8299066 (* t 8)) (var base u32 (if (< t 32) (lerp-colour 0x558A38 0x7EA23A (* t 8))
(if (< t 96) (lerp-colour 8299066 9922899 (/ (* (- t 32) 255) 64)) (if (< t 96) (lerp-colour 0x7EA23A 0x976953 (/ (* (- t 32) 255) 64))
(lerp-colour 9922899 15263976 (/ (* (- t 96) 255) 159))))) (lerp-colour 0x976953 0xE8E8E8 (/ (* (- t 96) 255) 159)))))
(var slope int (+ (- h west) (- h north))) (var slope int (+ (- h west) (- h north)))
(var light int (+ 128 (* slope 24))) (var light int (+ 128 (* slope 24)))
(if (< light 0) (= light 0)) (if (< light 0) (= light 0))
(if (> light 255) (= light 255)) (if (> light 255) (= light 255))
(if (> light 128) (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))))) (return (lerp-colour 0 base (+ 96 (/ (* light 159) 128)))))
(fn render-heights ((tr (* terra)) (k tile-key) (size (* int))) (* u32) (fn render-heights ((tr (* terra)) (k tile-key) (size (* int))) (* u32)
@@ -282,9 +259,7 @@
(var west int (if (> x 0) [hs (+ (* z res) x -1)] h)) (var west int (if (> x 0) [hs (+ (* z res) x -1)] h))
(var north int (if (> z 0) [hs (+ (* (- z 1) res) x)] h)) (var north int (if (> z 0) [hs (+ (* (- z 1) res) x)] h))
(= [px (+ (* z res) x)] (= [px (+ (* z res) x)]
;; TODO sex#47: write the opaque alpha in hex once there are (c-bit-or 0xFF000000 (height-colour h west north (. tr sea-level) (. tr size-y))))))
;; hex literals.
(c-bit-or 4278190080 (height-colour h west north (. tr sea-level) (. tr size-y))))))
(free hs) (free hs)
(= (* size) res) (= (* size) res)
(return px)) (return px))
@@ -332,7 +307,8 @@
(return out)) (return out))
;;; The mineral tile: per sample, MINERAL-VALUE-BASE plus the category ;;; The mineral tile: per sample, MINERAL-VALUE-BASE plus the category
;;; of the pick's reading there. ;;; 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))) (fn render-minerals ((tr (* terra)) (rocks (* strata)) (o (* ores)) (k tile-key) (size (* int)))
(* u8) (* u8)
(var res int (. k stratum)) (var res int (. k stratum))
@@ -342,6 +318,7 @@
(var out (* u8) (malloc (* res res))) (var out (* u8) (malloc (* res res)))
(var heights [u16 1024]) (var heights [u16 1024])
(var column (* u8) (malloc (+ (. tr size-y) 1))) (var column (* u8) (malloc (+ (. tr size-y) 1)))
(var readable bool (. [(. o minerals) (. k param)] readable))
(var per-chunk int (/ 32 step)) (var per-chunk int (/ 32 step))
(if (< per-chunk 1) (= per-chunk 1)) (if (< per-chunk 1) (= per-chunk 1))
(for (var cz int 0) (< cz 16) (++ cz) (for (var cz int 0) (< cz 16) (++ cz)
@@ -350,22 +327,85 @@
(continue)) (continue))
(var chunk-x int (+ (* (. k rx) 16) cx)) (var chunk-x int (+ (* (. k rx) 16) cx))
(var chunk-z int (+ (* (. k rz) 16) cz)) (var chunk-z int (+ (* (. k rz) 16) cz))
(terra/chunk-heights tr chunk-x chunk-z (if (> step 32) 32 step) heights) (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 dz int 0) (< dz per-chunk) (++ dz)
(for (var dx int 0) (< dx per-chunk) (++ dx) (for (var dx int 0) (< dx per-chunk) (++ dx)
(var lx int (* dx step)) (var lx int (* dx step))
(var lz int (* dz step)) (var lz int (* dz step))
(var h int [heights (+ (* lz 32) lx)]) (var h int 0)
(strata/column rocks chunk-x chunk-z lx lz h column) (if readable
(var r mineral-reading (ores/reading o (. k param) (& map) (+ (* chunk-x 32) lx) (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)) (+ (* chunk-z 32) lz) column h))
(= [out (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)] (= [out (+ (* (+ (/ (* cz 32) step) dz) res) (/ (* cx 32) step) dx)]
(cast (+ MINERAL-VALUE-BASE (ores/category (. r total))) u8)))))) (cast (+ MINERAL-VALUE-BASE c) u8))))))
(free column) (free column)
(free (. map data)) (free (. map data))
(= (* size) res) (= (* size) res)
(return out)) (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 ------------------------------------------------------- ;;; Workers -------------------------------------------------------
(fn worker-main ((arg (* void))) (* void) (fn worker-main ((arg (* void))) (* void)
@@ -377,6 +417,7 @@
(var tr (* terra) NULL) (var tr (* terra) NULL)
(var rocks (* strata) NULL) (var rocks (* strata) NULL)
(var minerals (* ores) NULL) (var minerals (* ores) NULL)
(var cave-gen (* caves) NULL)
(pthread-mutex-lock (& (. t lock))) (pthread-mutex-lock (& (. t lock)))
(while (! (. t quit)) (while (! (. t quit))
(if (>= (. t queue-pos) (. t queue-len)) (if (>= (. t queue-pos) (. t queue-len))
@@ -401,6 +442,8 @@
(= tr NULL) (= tr NULL)
(if minerals (ores/free minerals)) (if minerals (ores/free minerals))
(= minerals NULL) (= minerals NULL)
(if cave-gen (caves/free cave-gen))
(= cave-gen NULL)
(if rocks (strata/free rocks)) (if rocks (strata/free rocks))
(= rocks NULL) (= rocks NULL)
(if g (worldgen/free g)) (if g (worldgen/free g))
@@ -409,6 +452,7 @@
(if g (= tr (terra/make g rivers))) (if g (= tr (terra/make g rivers)))
(if g (= rocks (strata/make g (. t assets-dir)))) (if g (= rocks (strata/make g (. t assets-dir))))
(if rocks (= minerals (ores/make settings (. t assets-dir) rocks))) (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))) (= (. cache sampler) (river-sampler/make (& rivers) (. settings size-y)))
(= g-generation generation))) (= g-generation generation)))
(var size int 0) (var size int 0)
@@ -422,6 +466,8 @@
(= values (render-rocks tr rocks key (& size))) (= values (render-rocks tr rocks key (& size)))
(&& tr rocks minerals (== (. key map) LAYER-MINERAL)) (&& tr rocks minerals (== (. key map) LAYER-MINERAL))
(= values (render-minerals tr rocks minerals key (& size))) (= values (render-minerals tr rocks minerals key (& size)))
(&& tr cave-gen (== (. key map) LAYER-CAVES))
(= values (render-caves tr cave-gen key (& size)))
g g
(= px (render g key (& size)))) (= px (render g key (& size))))
@@ -439,6 +485,7 @@
(= (. tl state) TILE-QUEUED))))) (= (. tl state) TILE-QUEUED)))))
(pthread-mutex-unlock (& (. t lock))) (pthread-mutex-unlock (& (. t lock)))
(if minerals (ores/free minerals)) (if minerals (ores/free minerals))
(if cave-gen (caves/free cave-gen))
(if rocks (strata/free rocks)) (if rocks (strata/free rocks))
(if tr (terra/free tr)) (if tr (terra/free tr))
(if g (worldgen/free g)) (if g (worldgen/free g))

View File

@@ -3,21 +3,15 @@
;;; map matches to the pixel, padding included. ;;; map matches to the pixel, padding included.
(include stdio.h stdlib.h string.h math.h time.h) (include stdio.h stdlib.h string.h math.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.
(import maps) (import maps)
(import lcg)
(import noise)
(import json)
(import shape) (import shape)
(import save) (import save)
(import worldgen) (import worldgen)
(import fastnoise) (pub import rivers)
(import rivers)
(import terra) (import terra)
(import strata) (import strata)
(import ores) (import ores)
(import caves)
(import img) (import img)
(define MAP-KINDS 6) (define MAP-KINDS 6)
@@ -127,10 +121,8 @@
(var e extent (save/extent s "mapregion")) (var e extent (save/extent s "mapregion"))
(var cell int 32) (var cell int 32)
(var diff image (image/make (* (+ (- (. e x1) (. e x0)) 1) cell) (* (+ (- (. e z1) (. e z0)) 1) cell))) (var diff image (image/make (* (+ (- (. e x1) (. e x0)) 1) cell) (* (+ (- (. e z1) (. e z0)) 1) cell)))
;; TODO sex#50: write MAX-MINERALS once constants in array types are (var codes [* char MAX-MINERALS])
;; kebab-converted. (var want [int-map MAX-MINERALS])
(var codes [* char MAX_MINERALS])
(var want [int-map MAX_MINERALS])
(var t tally) (var t tally)
(memset (& t) 0 (sizeof t)) (memset (& t) 0 (sizeof t))
(var unknown int 0) (var unknown int 0)
@@ -174,6 +166,432 @@
(.release (& diff)) (.release (& diff))
(return (if (|| (!= (. t matched) (. t compared)) (> unknown 0)) 1 0))) (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 ;;; Recomputes the prospecting pick readings players took in the save
;;; and compares each mineral's TotalFactor: per reading, every ;;; and compares each mineral's TotalFactor: per reading, every
;;; mineral the save has or this reads above nothing. ;;; mineral the save has or this reads above nothing.
@@ -344,19 +762,9 @@
(if (== d 0) (++ matched)) (if (== d 0) (++ matched))
(if (!= d 0) (if (!= d 0)
(do (do
;; TODO sex#59: sum two (if ...)s once a conditional (++ [by-class (+ (if (< d 0) 2 0) (if (>= got (. t sea-level)) 1 0))])))
;; operand keeps its parentheses.
(var cls int 0)
(if (< d 0) (+= cls 2))
(if (>= got (. t sea-level)) (+= cls 1))
(++ [by-class cls])))
;; -4..+4, the ends counting everything beyond ;; -4..+4, the ends counting everything beyond
;; TODO sex#59: clamp inline once a conditional operand keeps its (var bucket int (+ (if (< d -4) -4 (if (> d 4) 4 d)) 4))
;; parentheses.
(var clamped int d)
(if (< clamped -4) (= clamped -4))
(if (> clamped 4) (= clamped 4))
(var bucket int (+ clamped 4))
(++ [by-delta bucket]) (++ [by-delta bucket])
(var colour u32 (grey (/ (* got 255) (. g settings size-y)))) (var colour u32 (grey (/ (* got 255) (. g settings size-y))))
(if (> d 0) (= colour 16719904)) (if (> d 0) (= colour 16719904))

View File

@@ -4,7 +4,8 @@
;;; vs-map-viewer [--assets DIR] [--zoom BLOCKS-PER-POINT] ;;; vs-map-viewer [--assets DIR] [--zoom BLOCKS-PER-POINT]
;;; [--base ocean|rivers|height] [--overlay NAME]... [--opacity F] ;;; [--base ocean|rivers|height] [--overlay NAME]... [--opacity F]
;;; [--rock-depth N | --rock-y Y | --rock-any] [--highlight ROCK]... [--find] ;;; [--rock-depth N | --rock-y Y | --rock-any] [--highlight ROCK]... [--find]
;;; [--mineral CODE] [--min-reading NAME] [--find-mineral] ;;; [--mineral CODE] [--min-reading NAME] [--find-mineral] [--find-cave]
;;; [--find-hot-spring] [--spawn X Z]
;;; [--probe X Z] [--mouse X Y] ;;; [--probe X Z] [--mouse X Y]
;;; [--screenshot FILE.png] [WORLD.vcdbs | serverconfig.json] ;;; [--screenshot FILE.png] [WORLD.vcdbs | serverconfig.json]
;;; ;;;
@@ -12,21 +13,15 @@
;;; quits, which is how the viewer is checked without looking at it. ;;; quits, which is how the viewer is checked without looking at it.
(include stdio.h stdlib.h string.h math.h unistd.h "nk.h" "stb_image_write.h") (include stdio.h stdlib.h string.h math.h unistd.h "nk.h" "stb_image_write.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 cs)
(import json)
(import maps) (import maps)
(import lcg)
(import noise) (import noise)
(import shape)
(import worldgen) (import worldgen)
(import fastnoise)
(import rivers) (import rivers)
(import terra) (import terra)
(import strata) (import strata)
(import ores) (import ores)
(import caves)
(import search) (import search)
(import hover) (import hover)
(import settings) (import settings)
@@ -49,16 +44,17 @@
(var base-layers [int 3] #(4 6 7)) (var base-layers [int 3] #(4 6 7))
(var base-names [(* const char) 3] #("ocean" "rivers" "height")) (var base-names [(* const char) 3] #("ocean" "rivers" "height"))
(var base-labels [(* const char) 3] #("Ocean" "Rivers" "Terrain height")) (var base-labels [(* const char) 3] #("Ocean" "Rivers" "Terrain height"))
(var overlay-layers [int 7] #(0 1 2 3 5 8 9)) (var overlay-layers [int 8] #(0 1 2 3 5 8 9 10))
(var overlay-names [(* const char) 7] (var overlay-names [(* const char) 8]
#("landform" "climate" "province" "upheaval" "strata" "rock" "mineral")) #("landform" "climate" "province" "upheaval" "strata" "rock" "mineral" "caves"))
;;; The Rock and Minerals overlays' bits in `overlays'. ;;; The Rock and Minerals overlays' bits in `overlays'.
(define ROCK-OVERLAY-BIT 32) (define ROCK-OVERLAY-BIT 32)
(define MINERAL-OVERLAY-BIT 64) (define MINERAL-OVERLAY-BIT 64)
(define OVERLAY-COUNT 7) (define CAVES-OVERLAY-BIT 128)
(var overlay-labels [(* const char) 7] (define OVERLAY-COUNT 8)
(var overlay-labels [(* const char) 8]
#("Landform" "Climate" "Geologic province" "Upheaval" "Rock strata thickness" "Rock" #("Landform" "Climate" "Geologic province" "Upheaval" "Rock strata thickness" "Rock"
"Minerals")) "Minerals" "Caves"))
(var rock-mode-names [(* const char) 4] #("Surface" "Depth below surface" "At Y" "Any depth")) (var rock-mode-names [(* const char) 4] #("Surface" "Depth below surface" "At Y" "Any depth"))
;;; Rock colours, roughly as they look in game; others get a stable one. ;;; Rock colours, roughly as they look in game; others get a stable one.
@@ -66,44 +62,66 @@
#("rock-granite" "rock-andesite" "rock-basalt" "rock-peridotite" "rock-kimberlite" #("rock-granite" "rock-andesite" "rock-basalt" "rock-peridotite" "rock-kimberlite"
"rock-claystone" "rock-sandstone" "rock-shale" "rock-conglomerate" "rock-limestone" "rock-claystone" "rock-sandstone" "rock-shale" "rock-conglomerate" "rock-limestone"
"rock-chert" "rock-chalk" "rock-bauxite" "rock-slate" "rock-phyllite")) "rock-chert" "rock-chalk" "rock-bauxite" "rock-slate" "rock-phyllite"))
;; TODO sex#47: write the colours in hex once there are hex literals.
(var rock-colour-values [u32 15] (var rock-colour-values [u32 15]
;; Sex has no hex literals: B49A8C 6E6A66 3A3A3D 4F6B3A 5A6E7A C08A5A D8C38A #(0xB49A8C 0x6E6A66 0x3A3A3D 0x4F6B3A 0x5A6E7A 0xC08A5A 0xD8C38A 0x5E6470
;; 5E6470 9A7B5C C9C7B8 8A5A48 F0F0E8 B5532E 4A5568 7D8A7A 0x9A7B5C 0xC9C7B8 0x8A5A48 0xF0F0E8 0xB5532E 0x4A5568 0x7D8A7A))
#(11836044 7236198 3815997 5204794 5926522 12618330 14205834 6186096 10124124 13223864 9067080 15790312 11883310 4871528 8227450))
(var climate-names [(* const char) 5] #("temperate" "hot" "warm" "cool" "icy")) (var climate-names [(* const char) 5] #("temperate" "hot" "warm" "cool" "icy"))
;;; The pick's reading categories, ores/category's numbering, and their ;;; The pick's reading categories, ores/category's numbering, and their
;;; colours on the Minerals overlay. ;;; colours on the Minerals overlay.
(var reading-names [(* const char) 8] (var reading-names [(* const char) 8]
#("none" "miniscule" "very poor" "poor" "decent" "high" "very high" "ultra high")) #("none" "miniscule" "very poor" "poor" "decent" "high" "very high" "ultra high"))
;; TODO sex#47: write the colours in hex once there are hex literals.
(var reading-colours [u32 8] (var reading-colours [u32 8]
;; Sex has no hex literals: 000000 5A6E7A 3B6FB6 2BA3A3 7BC043 F3C623 F37735 D11141 #(0x000000 0x5A6E7A 0x3B6FB6 0x2BA3A3 0x7BC043 0xF3C623 0xF37735 0xD11141))
#(0 5926522 3895222 2859939 8110147 15975971 15955765 13701441)) ;;; The same numbering for a mineral the pick can't read, whose ore map
;;; is shown instead: its value in sevenths (ores/map-category).
(var map-band-names [(* const char) 8]
#("none" "0-14%" "14-29%" "29-43%" "43-57%" "57-71%" "71-86%" "86-100%"))
;;; Find nearest's least reading, unless set: decent. ;;; Find nearest's least reading, unless set: decent.
(define DEFAULT-MIN-READING 4) (define DEFAULT-MIN-READING 4)
;;; The category NAME names, with a hyphen for a space ("very-high"), ;;; The category NAME names, a reading with a hyphen for a space
;;; from miniscule up; the default for a name it doesn't know. ;;; ("very-high") or an ore map band ("43-57%"), from the lowest up; the
;;; default for a name it doesn't know.
(fn reading-named ((name (* const char))) int (fn reading-named ((name (* const char))) int
(for (var c int 1) (< c 8) (++ c) (for (var c int 1) (< c 8) (++ c)
(var hyphenated [char 16]) (var hyphenated [char 16])
(snprintf hyphenated (sizeof hyphenated) "%s" [reading-names c]) (snprintf hyphenated (sizeof hyphenated) "%s" [reading-names c])
(for (var p (* char) hyphenated) (* p) (++ p) (for (var p (* char) hyphenated) (* p) (++ p)
(if (== (* p) #\space) (= (* p) #\-))) (if (== (* p) #\space) (= (* p) #\-)))
(if (== (strcmp hyphenated name) 0) (if (|| (== (strcmp hyphenated name) 0) (== (strcmp [map-band-names c] name) 0))
(return c))) (return c)))
(return DEFAULT-MIN-READING)) (return DEFAULT-MIN-READING))
;;; A mineral's name in the panel's list.
(record item-label ((text [char 40])))
;;; The cave categories, caves/category's numbering, and their colours
;;; on the Caves overlay: entrances stand out, then the deeper the
;;; topmost cave, the darker.
(var cave-names [(* const char) 8]
#("none" "entrance" "10 deep or less" "11-25 deep" "26-50 deep" "51-100 deep" "deeper"
"hot spring"))
(var cave-colours [u32 8]
#(0x000000 0x00E5FF 0xFFD54F 0xFF9800 0xE64A19 0x8E24AA 0x303F9F 0xFF4081))
;;; What Find nearest is looking for, for which panel shows its status.
(define FIND-ROCK 0)
(define FIND-MINERAL 1)
(define FIND-CAVE 2)
(define FIND-HOT-SPRING 3)
(define MAX-PROBE-CAVES 16)
;;; The strata of the column clicked last: top down, as (rock, top y, ;;; The strata of the column clicked last: top down, as (rock, top y,
;;; bottom y) runs; and the pick's readings there, highest first. ;;; bottom y) runs; the pick's readings there, highest first; and the
;; TODO sex#50: write MAX-MINERALS once constants in array types are ;;; ore maps of the minerals the pick can't read.
;; kebab-converted.
(record probe ((valid bool) (x int) (z int) (height int) (count int) (record probe ((valid bool) (x int) (z int) (height int) (count int)
(rocks [int 64]) (tops [int 64]) (bottoms [int 64]) (rocks [int 64]) (tops [int 64]) (bottoms [int 64])
(reading-count int) (reading-minerals [int MAX_MINERALS]) (reading-count int) (reading-minerals [int MAX-MINERALS])
(readings [mineral-reading MAX_MINERALS]))) (readings [mineral-reading MAX-MINERALS])
(map-count int) (map-minerals [int MAX-MINERALS]) (map-factors [double MAX-MINERALS])
(cave-entrance bool) (cave-count int) (cave-tops [int MAX-PROBE-CAVES])
(cave-bottoms [int MAX-PROBE-CAVES]) (cave-lava [bool MAX-PROBE-CAVES])))
(record app (record app
((window (* SDL-Window)) (renderer (* SDL-Renderer)) (ctx (* struct nk-context)) ((window (* SDL-Window)) (renderer (* SDL-Renderer)) (ctx (* struct nk-context))
@@ -120,15 +138,24 @@
(coverage [i64 256]) (coverage-total i64) (coverage [i64 256]) (coverage-total i64)
(pins [int 64]) (pin-count int) (pins [int 64]) (pin-count int)
(search (* search)) (searching bool) (search-status [char 160]) (find-requested bool) (search (* search)) (searching bool) (search-status [char 160]) (find-requested bool)
;; minerals: the one shown, the readable ones for the panel's list, ;; minerals: the one shown, the panel's list of them, its share of
;; its share of the view per category, and what Find nearest wants ;; the view per category, and what Find nearest wants
(minerals (* ores)) (mineral int) (mineral-code (* const char)) (minerals (* ores)) (mineral int) (mineral-code (* const char))
;; TODO sex#50: write MAX-MINERALS once constants in array types (mineral-labels [item-label MAX-MINERALS])
;; are kebab-converted. (mineral-items [* const char MAX-MINERALS]) (mineral-ids [int MAX-MINERALS])
(mineral-items [* const char MAX_MINERALS]) (mineral-ids [int MAX_MINERALS])
(mineral-item-count int) (mineral-item-count int)
(mineral-coverage [i64 256]) (mineral-coverage-total i64) (mineral-coverage [i64 256]) (mineral-coverage-total i64)
(min-reading int) (find-mineral-requested bool) (searching-mineral bool) (min-reading int) (find-mineral-requested bool)
;; caves: their share of the view per category, the probe's carver
(cave-coverage [i64 256]) (cave-coverage-total i64) (find-cave-requested bool)
(find-spring-requested bool)
(probe-caves (* caves))
(search-kind int)
;; where coordinates count from: the world's spawn unless set, and one
;; given on the command line
(spawn-x int) (spawn-z int) (spawn-arg bool) (arg-spawn-x int) (arg-spawn-z int)
;; the next click on the map sets the spawn instead of probing
(picking-spawn bool)
(show-stories bool) (show-cursor-rock bool) (show-stories bool) (show-cursor-rock bool)
;; what is under the cursor, from the hover worker; and a terrain ;; what is under the cursor, from the hover worker; and a terrain
;; generator of the main thread's own, for probes ;; generator of the main thread's own, for probes
@@ -217,16 +244,34 @@
(var r SDL-FRect (map-rect a)) (var r SDL-FRect (map-rect a))
(return (&& (>= x (. r x)) (< x (+ (. r x) (. r w))) (>= y (. r y)) (< y (+ (. r y) (. r h)))))) (return (&& (>= x (. r x)) (< x (+ (. r x) (. r w))) (>= y (. r y)) (< y (+ (. r y) (. r h))))))
;;; The world's own spawn: the one its save or server config names,
;;; else the map's middle, the game's default.
(fn world-spawn ((a (* app)) (x (* int)) (z (* int))) void
(if (. a source has-spawn)
(do
(= (* x) (. a source spawn-x))
(= (* z) (. a source spawn-z)))
(do
(= (* x) (/ (. a source settings size-x) 2))
(= (* z) (/ (. a source settings size-z) 2)))))
(fn reset-spawn ((a (* app))) void
(world-spawn a (& (. a spawn-x)) (& (. a spawn-z))))
(fn go-to-spawn ((a (* app))) void (fn go-to-spawn ((a (* app))) void
(= (. a center-x) (/ (. a source settings size-x) 2.0)) (= (. a center-x) (+ (. a spawn-x) 0.5))
(= (. a center-z) (/ (. a source settings size-z) 2.0))) (= (. a center-z) (+ (. a spawn-z) 0.5)))
;;; Applying settings ---------------------------------------------- ;;; Applying settings ----------------------------------------------
(fn release-probe-terra ((a (* app))) void (fn release-probe-terra ((a (* app))) void
(if (. a probe-terra) (if (. a probe-terra)
(terra/free (. a probe-terra))) (terra/free (. a probe-terra)))
(= (. a probe-terra) NULL)) (= (. a probe-terra) NULL)
;; it carves with the generator of the world being let go
(if (. a probe-caves)
(caves/free (. a probe-caves)))
(= (. a probe-caves) NULL))
;;; The colour of rock index I. ;;; The colour of rock index I.
(fn rock-colour ((a (* app)) (i int)) u32 (fn rock-colour ((a (* app)) (i int)) u32
@@ -234,32 +279,31 @@
(for (var k int 0) (< k 15) (++ k) (for (var k int 0) (< k 15) (++ k)
(if (== (strcmp code [rock-colour-codes k]) 0) (if (== (strcmp code [rock-colour-codes k]) 0)
(return [rock-colour-values k]))) (return [rock-colour-values k])))
;; TODO sex#47: write the multiplier and mask in hex once there are (var hash u32 (* (cast (+ i 41) u32) (cast 0x9E3779B1 u32)))
;; hex literals. (return (& hash 0xFFFFFF)))
(var hash u32 (* (cast (+ i 41) u32) (cast 2654435761 u32)))
(return (& hash 16777215)))
;;; The rock overlay's palette: every rock in its colour, or only the ;;; The rock overlay's palette: every rock in its colour, or only the
;;; highlighted ones, the rest transparent. ;;; highlighted ones, the rest transparent.
(fn update-palette ((a (* app))) void (fn update-palette ((a (* app))) void
(var p [u32 256]) (var p [u32 256])
(for (var i int 0) (< i 256) (++ i) (for (var i int 0) (< i 256) (++ i)
;; TODO sex#47: write the palette colours and alpha in hex once (= [p i] 0xFF202020))
;; there are hex literals.
(= [p i] 4280295456))
;; the base layer shows through water, air and the rocks not looked for ;; the base layer shows through water, air and the rocks not looked for
(= [p VALUE-WATER] 0) (= [p VALUE-WATER] 0)
(= [p VALUE-AIR] 0) (= [p VALUE-AIR] 0)
(= [p ROCK-MANTLE] 0) (= [p ROCK-MANTLE] 0)
(for (var i int 0) (< i (. a rocks rock-count)) (++ i) (for (var i int 0) (< i (. a rocks rock-count)) (++ i)
(var c u32 (rock-colour a i)) (var c u32 (rock-colour a i))
(= [p i] (c-bit-or 4278190080 c)) (= [p i] (c-bit-or 0xFF000000 c))
(if (&& (!= (. a highlight) 0) (== (& (. a highlight) (<< (cast 1 u32) i)) 0)) (if (&& (!= (. a highlight) 0) (== (& (. a highlight) (<< (cast 1 u32) i)) 0))
(= [p i] 0))) (= [p i] 0)))
;; the base shows through where the pick reads nothing ;; the base shows through where the pick reads nothing
(= [p MINERAL-VALUE-BASE] 0) (= [p MINERAL-VALUE-BASE] 0)
(for (var c int 1) (< c READING-CATEGORIES) (++ c) (for (var c int 1) (< c READING-CATEGORIES) (++ c)
(= [p (+ MINERAL-VALUE-BASE c)] (c-bit-or 4278190080 [reading-colours c]))) (= [p (+ MINERAL-VALUE-BASE c)] (c-bit-or 0xFF000000 [reading-colours c])))
(= [p CAVE-VALUE-BASE] 0)
(for (var c int 1) (< c CAVE-CATEGORIES) (++ c)
(= [p (+ CAVE-VALUE-BASE c)] (c-bit-or 0xFF000000 [cave-colours c])))
(.set-palette (. a tiles) p)) (.set-palette (. a tiles) p))
;;; The highlighted rock when it is the only one, else -1. ;;; The highlighted rock when it is the only one, else -1.
@@ -290,16 +334,24 @@
(if (. a minerals) (if (. a minerals)
(ores/free (. a minerals))) (ores/free (. a minerals)))
(= (. a minerals) o) (= (. a minerals) o)
;; the panel's list: nothing, then every mineral the pick can read ;; the panel's list: nothing, then every mineral the pick can read,
;; then the ones shown by their ore map
(= [(. a mineral-items) 0] "(none)") (= [(. a mineral-items) 0] "(none)")
(= [(. a mineral-ids) 0] -1) (= [(. a mineral-ids) 0] -1)
(= (. a mineral-item-count) 1) (= (. a mineral-item-count) 1)
(for (var pass int 0) (< pass 2) (++ pass)
(for (var i int 0) (< i (. o count)) (++ i) (for (var i int 0) (< i (. o count)) (++ i)
(if (. [(. o minerals) i] readable) (var m (* mineral) (& [(. o minerals) i]))
(do (if (!= (. m readable) (== pass 0))
(= [(. a mineral-items) (. a mineral-item-count)] (. [(. o minerals) i] code)) (continue))
(= [(. a mineral-ids) (. a mineral-item-count)] i) (var n int (. a mineral-item-count))
(++ (. a mineral-item-count))))) (var label (* char) (. [(. a mineral-labels) n] text))
(if (. m readable)
(snprintf label 40 "%s" (. m code))
(snprintf label 40 "%s (ore map)" (. m code)))
(= [(. a mineral-items) n] label)
(= [(. a mineral-ids) n] i)
(++ (. a mineral-item-count))))
(= (. a mineral-code) (if (>= (. a mineral) 0) (. [(. o minerals) (. a mineral)] code) NULL))) (= (. a mineral-code) (if (>= (. a mineral) 0) (. [(. o minerals) (. a mineral)] code) NULL)))
;;; Makes SOURCE the world shown: a fresh generator for the panels, ;;; Makes SOURCE the world shown: a fresh generator for the panels,
@@ -349,6 +401,7 @@
(if (world-source/load (. a world-path) (& source)) (if (world-source/load (. a world-path) (& source))
(do (do
(apply a source) (apply a source)
(reset-spawn a)
(go-to-spawn a)) (go-to-spawn a))
(snprintf (. a status) (sizeof (. a status)) "cannot load %s" (. a world-path)))) (snprintf (. a status) (sizeof (. a status)) "cannot load %s" (. a world-path))))
@@ -396,7 +449,9 @@
(== layer LAYER-MINERAL) (== layer LAYER-MINERAL)
(do (do
(= (. k stratum) (height-resolution (. a zoom))) (= (. k stratum) (height-resolution (. a zoom)))
(= (. k param) (. a mineral)))) (= (. k param) (. a mineral)))
(== layer LAYER-CAVES)
(= (. k stratum) (height-resolution (. a zoom))))
(return k)) (return k))
;;; Adds a value tile's samples that fall inside the visible world ;;; Adds a value tile's samples that fall inside the visible world
@@ -444,10 +499,12 @@
(= (. a coverage-total) 0) (= (. a coverage-total) 0)
(memset (. a mineral-coverage) 0 (sizeof (. a mineral-coverage))) (memset (. a mineral-coverage) 0 (sizeof (. a mineral-coverage)))
(= (. a mineral-coverage-total) 0) (= (. a mineral-coverage-total) 0)
(memset (. a cave-coverage) 0 (sizeof (. a cave-coverage)))
(= (. a cave-coverage-total) 0)
(.begin-frame (. a tiles)) (.begin-frame (. a tiles))
;; layer by layer, each nearest the centre first: the base fills in ;; layer by layer, each nearest the centre first: the base fills in
;; before the overlays start ;; before the overlays start
(var layers [int 9]) (var layers [int 10])
(var layer-count int 0) (var layer-count int 0)
(= [layers 0] (. a base)) (= [layers 0] (. a base))
(= layer-count 1) (= layer-count 1)
@@ -470,6 +527,9 @@
x0 z0 x1 z1) x0 z0 x1 z1)
(&& values (== [layers l] LAYER-MINERAL)) (&& values (== [layers l] LAYER-MINERAL))
(count-visible (. a mineral-coverage) (& (. a mineral-coverage-total)) values size (count-visible (. a mineral-coverage) (& (. a mineral-coverage-total)) values size
(. k rx) (. k rz) x0 z0 x1 z1)
(&& values (== [layers l] LAYER-CAVES))
(count-visible (. a cave-coverage) (& (. a cave-coverage-total)) values size
(. k rx) (. k rz) x0 z0 x1 z1)) (. k rx) (. k rz) x0 z0 x1 z1))
(SDL-SetTextureBlendMode tex SDL-BLENDMODE-BLEND) (SDL-SetTextureBlendMode tex SDL-BLENDMODE-BLEND)
(SDL-SetTextureAlphaMod tex (if (== l 0) 255 alpha)) (SDL-SetTextureAlphaMod tex (if (== l 0) 255 alpha))
@@ -491,12 +551,23 @@
(var g (* worldgen) (. a g)) (var g (* worldgen) (. a g))
(SDL-SetRenderDrawColor r 255 255 255 255) (SDL-SetRenderDrawColor r 255 255 255 255)
(var stories int (. g story-count)) (var stories int (. g story-count))
(if (! (. a show-stories)) (= stories -1)) (if (! (. a show-stories)) (= stories -2))
(for (var i int -1) (< i stories) (++ i) ;; the spawn, the world's own if the one set differs, then the stories
(var x double (/ (. a source settings size-x) 2.0)) (var wx int)
(var z double (/ (. a source settings size-z) 2.0)) (var wz int)
(world-spawn a (& wx) (& wz))
(for (var i int -2) (< i stories) (++ i)
(var x double (+ (. a spawn-x) 0.5))
(var z double (+ (. a spawn-z) 0.5))
(var name (* const char) "spawn") (var name (* const char) "spawn")
(if (>= i 0) (if (== i -1)
(do
(if (&& (== wx (. a spawn-x)) (== wz (. a spawn-z)))
(continue))
(= x (+ wx 0.5))
(= z (+ wz 0.5))
(= name "world spawn"))
(>= i 0)
(do (do
(= x (. [(. g stories) i] x)) (= x (. [(. g stories) i] x))
(= z (. [(. g stories) i] z)) (= z (. [(. g stories) i] z))
@@ -596,6 +667,19 @@
(apply a source))) (apply a source)))
(if (nk-button-label ctx "Go to spawn") (if (nk-button-label ctx "Go to spawn")
(go-to-spawn a)) (go-to-spawn a))
;; the spawn coordinates count from, by default the world's: set
;; by a click on the map
(nk-layout-row-dynamic ctx 26 2)
(if (nk-button-label ctx (if (. a picking-spawn) "Click the map" "Set spawn"))
(= (. a picking-spawn) (! (. a picking-spawn))))
(var wx int)
(var wz int)
(world-spawn a (& wx) (& wz))
(var moved bool (|| (!= wx (. a spawn-x)) (!= wz (. a spawn-z))))
(if (! moved) (nk-widget-disable-begin ctx))
(if (nk-button-label ctx "World's spawn")
(reset-spawn a))
(if (! moved) (nk-widget-disable-end ctx))
(nk-tree-pop ctx)))) (nk-tree-pop ctx))))
;;; The rock layer's mode, its depth or Y, and the legend: clicking rocks ;;; The rock layer's mode, its depth or Y, and the legend: clicking rocks
@@ -650,7 +734,7 @@
(nk-layout-row-dynamic ctx 24 2) (nk-layout-row-dynamic ctx 24 2)
(if (nk-button-label ctx "Show all") (if (nk-button-label ctx "Show all")
(do (= (. a highlight) 0) (update-palette a))) (do (= (. a highlight) 0) (update-palette a)))
(if (&& (. a searching) (! (. a searching-mineral))) (if (&& (. a searching) (== (. a search-kind) FIND-ROCK))
(if (nk-button-label ctx "Cancel") (if (nk-button-label ctx "Cancel")
(do (do
(search/stop (. a search)) (search/stop (. a search))
@@ -658,7 +742,7 @@
(snprintf (. a search-status) (sizeof (. a search-status)) "cancelled"))) (snprintf (. a search-status) (sizeof (. a search-status)) "cancelled")))
(if (nk-button-label ctx "Find nearest") (if (nk-button-label ctx "Find nearest")
(= (. a find-requested) true))))) (= (. a find-requested) true)))))
(if (&& (* (. a search-status)) (! (. a searching-mineral))) (if (&& (* (. a search-status)) (== (. a search-kind) FIND-ROCK))
(do (do
(nk-layout-row-dynamic ctx 34 1) (nk-layout-row-dynamic ctx 34 1)
(nk-label-wrap ctx (. a search-status))))) (nk-label-wrap ctx (. a search-status)))))
@@ -713,8 +797,25 @@
(draw-rock-controls a) (draw-rock-controls a)
(nk-tree-pop ctx)))) (nk-tree-pop ctx))))
;;; The names of the mineral shown's categories: the pick's readings, or
;;; its ore map's bands where the pick can't read it.
(fn category-names ((a (* app))) (* * const char)
(if (&& (>= (. a mineral) 0) (! (. [(. (. a minerals) minerals) (. a mineral)] readable)))
(return map-band-names))
(return reading-names))
;;; What the cursor label and Info say of the mineral shown at the
;;; cursor, into TEXT.
(fn mineral-at-cursor ((a (* app)) (r (* const hover-result)) (text (* char)) (size size-t)) void
(var m (* mineral) (& [(. (. a minerals) minerals) (. r query mineral)]))
(if (. m readable)
(snprintf text size "%s %s, %.2f ppt" (. m code)
[reading-names (ores/category (. r mineral total))] (. r mineral ppt))
(snprintf text size "%s ore map %.0f%%" (. m code) (* 100 (. r mineral-map)))))
;;; The mineral shown, the legend of the pick's readings with each one's ;;; The mineral shown, the legend of the pick's readings with each one's
;;; share of the view, and Find nearest for a reading at least so high. ;;; share of the view, and Find nearest for a reading at least so high.
;;; A mineral the pick can't read is shown by its ore map, in bands.
(fn draw-mineral-controls ((a (* app))) void (fn draw-mineral-controls ((a (* app))) void
(var ctx (* struct nk-context) (. a ctx)) (var ctx (* struct nk-context) (. a ctx))
(var current int 0) (var current int 0)
@@ -727,12 +828,18 @@
(if (!= chosen current) (if (!= chosen current)
(do (do
(= (. a mineral) [(. a mineral-ids) chosen]) (= (. a mineral) [(. a mineral-ids) chosen])
(= (. a mineral-code) (if (>= (. a mineral) 0) [(. a mineral-items) chosen] NULL)))) (= (. a mineral-code)
(if (>= (. a mineral) 0) (. [(. (. a minerals) minerals) (. a mineral)] code) NULL))))
(if (< (. a mineral) 0) (if (< (. a mineral) 0)
(do (do
(nk-layout-row-dynamic ctx 34 1) (nk-layout-row-dynamic ctx 34 1)
(nk-label-wrap ctx "Choose a mineral to see what the prospecting pick reads") (nk-label-wrap ctx "Choose a mineral to see what the prospecting pick reads")
(return))) (return)))
(var names (* * const char) (category-names a))
(if (! (. [(. (. a minerals) minerals) (. a mineral)] readable))
(do
(nk-layout-row-dynamic ctx 50 1)
(nk-label-wrap ctx "The pick reads this from ore inside other deposits; this is its ore map, how common it is here")))
(nk-layout-row-dynamic ctx 8 1) (nk-layout-row-dynamic ctx 8 1)
(nk-spacing ctx 1) (nk-spacing ctx 1)
(var shown bool (&& (> (. a mineral-coverage-total) 0) (var shown bool (&& (> (. a mineral-coverage-total) 0)
@@ -746,18 +853,18 @@
(nk-button-color ctx (nk-rgb (cast (& (>> colour 16) 255) int) (cast (& (>> colour 8) 255) int) (nk-button-color ctx (nk-rgb (cast (& (>> colour 16) 255) int) (cast (& (>> colour 8) 255) int)
(cast (& colour 255) int))) (cast (& colour 255) int)))
(if shown (if shown
(nk-labelf ctx NK-TEXT-LEFT "%-13s %5.1f%%" [reading-names c] (nk-labelf ctx NK-TEXT-LEFT "%-13s %5.1f%%" [names c]
(/ (* 100.0 [(. a mineral-coverage) (+ MINERAL-VALUE-BASE c)]) (/ (* 100.0 [(. a mineral-coverage) (+ MINERAL-VALUE-BASE c)])
(. a mineral-coverage-total))) (. a mineral-coverage-total)))
(nk-label ctx [reading-names c] NK-TEXT-LEFT))) (nk-label ctx [names c] NK-TEXT-LEFT)))
(nk-layout-row-dynamic ctx 22 2) (nk-layout-row-dynamic ctx 22 2)
(nk-label ctx "Find at least" NK-TEXT-LEFT) (nk-label ctx "Find at least" NK-TEXT-LEFT)
;; from miniscule up ;; from miniscule up
(= (. a min-reading) (= (. a min-reading)
(+ 1 (nk-combo ctx (+ reading-names 1) (- READING-CATEGORIES 1) (- (. a min-reading) 1) 20 (+ 1 (nk-combo ctx (+ names 1) (- READING-CATEGORIES 1) (- (. a min-reading) 1) 20
(nk-vec2 140 200)))) (nk-vec2 140 200))))
(nk-layout-row-dynamic ctx 24 1) (nk-layout-row-dynamic ctx 24 1)
(if (&& (. a searching) (. a searching-mineral)) (if (&& (. a searching) (== (. a search-kind) FIND-MINERAL))
(if (nk-button-label ctx "Cancel") (if (nk-button-label ctx "Cancel")
(do (do
(search/stop (. a search)) (search/stop (. a search))
@@ -765,11 +872,56 @@
(snprintf (. a search-status) (sizeof (. a search-status)) "cancelled"))) (snprintf (. a search-status) (sizeof (. a search-status)) "cancelled")))
(if (nk-button-label ctx "Find nearest") (if (nk-button-label ctx "Find nearest")
(= (. a find-mineral-requested) true))) (= (. a find-mineral-requested) true)))
(if (&& (* (. a search-status)) (. a searching-mineral)) (if (&& (* (. a search-status)) (== (. a search-kind) FIND-MINERAL))
(do (do
(nk-layout-row-dynamic ctx 34 1) (nk-layout-row-dynamic ctx 34 1)
(nk-label-wrap ctx (. a search-status))))) (nk-label-wrap ctx (. a search-status)))))
;;; The legend of the Caves overlay, with each category's share of the
;;; view, and Find nearest for a cave entrance.
(fn draw-cave-controls ((a (* app))) void
(var ctx (* struct nk-context) (. a ctx))
(var shown bool (&& (> (. a cave-coverage-total) 0) (!= (& (. a overlays) CAVES-OVERLAY-BIT) 0)))
(nk-layout-row-dynamic ctx 18 1)
(nk-label ctx "The topmost cave below the surface" NK-TEXT-LEFT)
(for (var c int 1) (< c CAVE-CATEGORIES) (++ c)
(nk-layout-row-template-begin ctx 18)
(nk-layout-row-template-push-static ctx 18)
(nk-layout-row-template-push-dynamic ctx)
(nk-layout-row-template-end ctx)
(var colour u32 [cave-colours c])
(nk-button-color ctx (nk-rgb (cast (& (>> colour 16) 255) int) (cast (& (>> colour 8) 255) int)
(cast (& colour 255) int)))
(if shown
(nk-labelf ctx NK-TEXT-LEFT "%-16s %5.1f%%" [cave-names c]
(/ (* 100.0 [(. a cave-coverage) (+ CAVE-VALUE-BASE c)]) (. a cave-coverage-total)))
(nk-label ctx [cave-names c] NK-TEXT-LEFT)))
(nk-layout-row-dynamic ctx 24 2)
(var finding bool (&& (. a searching) (|| (== (. a search-kind) FIND-CAVE)
(== (. a search-kind) FIND-HOT-SPRING))))
(if finding
(if (nk-button-label ctx "Cancel")
(do
(search/stop (. a search))
(= (. a searching) false)
(snprintf (. a search-status) (sizeof (. a search-status)) "cancelled")))
(do
(if (nk-button-label ctx "Nearest entrance")
(= (. a find-cave-requested) true))
(if (nk-button-label ctx "Nearest hot spring")
(= (. a find-spring-requested) true))))
(if (&& (* (. a search-status)) (|| (== (. a search-kind) FIND-CAVE) (== (. a search-kind) FIND-HOT-SPRING)))
(do
(nk-layout-row-dynamic ctx 34 1)
(nk-label-wrap ctx (. a search-status)))))
(fn draw-caves ((a (* app))) void
(var ctx (* struct nk-context) (. a ctx))
(if (nk-tree-push ctx NK-TREE-TAB "Caves" NK-MAXIMIZED)
(do
(draw-cave-controls a)
(nk-tree-pop ctx))))
(fn draw-minerals ((a (* app))) void (fn draw-minerals ((a (* app))) void
(var ctx (* struct nk-context) (. a ctx)) (var ctx (* struct nk-context) (. a ctx))
(if (nk-tree-push ctx NK-TREE-TAB "Minerals" NK-MAXIMIZED) (if (nk-tree-push ctx NK-TREE-TAB "Minerals" NK-MAXIMIZED)
@@ -826,16 +978,42 @@
(= [(. p tops) (. p count)] y) (= [(. p tops) (. p count)] y)
(= [(. p bottoms) (. p count)] y) (= [(. p bottoms) (. p count)] y)
(++ (. p count))))) (++ (. p count)))))
;; the caves through the column
(if (! (. a probe-caves))
(= (. a probe-caves) (caves/make (. a g))))
(var words int (terra/solid-words (. a probe-terra)))
(var solid (* u32) (malloc (* 1024 words (sizeof u32))))
(var states (* u8) (malloc (* 1024 (. a source settings size-y))))
(var heights [u16 1024])
(var carved [int 1024])
(terra/chunk-solidity (. a probe-terra) (/ x 32) (/ z 32) heights solid)
(for (var i int 0) (< i 1024) (++ i)
(= [carved i] [heights i]))
(caves/carve-column (. a probe-caves) (/ x 32) (/ z 32) carved solid words states)
(var ci int (+ (* (% z 32) 32) (% x 32)))
(= (. p cave-entrance) (< [carved ci] [heights ci]))
(= (. p cave-count) (caves/runs (. a probe-caves) states (% x 32) (% z 32) [heights ci]
(. p cave-tops) (. p cave-bottoms) (. p cave-lava) MAX-PROBE-CAVES))
(free solid)
(free states)
;; what the pick reads here: every mineral it can, highest first ;; what the pick reads here: every mineral it can, highest first
(var o (* ores) (. a minerals)) (var o (* ores) (. a minerals))
(= (. p reading-count) 0) (= (. p reading-count) 0)
(= (. p map-count) 0)
(for (var i int 0) (< i (. o count)) (++ i) (for (var i int 0) (< i (. o count)) (++ i)
(if (! (. [(. o minerals) i] readable))
(continue))
(var m int-map) (var m int-map)
(ores/map o i (/ x 512) (/ z 512) (& m)) (ores/map o i (/ x 512) (/ z 512) (& m))
(var r mineral-reading (ores/reading o i (& m) x z (. a column) h)) (var r mineral-reading (ores/reading o i (& m) x z (. a column) h))
(var factor double (ores/map-factor (& m) x z))
(free (. m data)) (free (. m data))
(if (! (. [(. o minerals) i] readable))
(do
(if (> factor 0)
(do
(= [(. p map-minerals) (. p map-count)] i)
(= [(. p map-factors) (. p map-count)] factor)
(++ (. p map-count))))
(continue)))
(if (== (ores/category (. r total)) 0) (if (== (ores/category (. r total)) 0)
(continue)) (continue))
(var n int (. p reading-count)) (var n int (. p reading-count))
@@ -855,10 +1033,8 @@
(if (nk-tree-push ctx NK-TREE-TAB "Probe" NK-MAXIMIZED) (if (nk-tree-push ctx NK-TREE-TAB "Probe" NK-MAXIMIZED)
(do (do
(nk-layout-row-dynamic ctx 18 1) (nk-layout-row-dynamic ctx 18 1)
(var s (* world-settings) (& (. a source settings)))
(nk-labelf ctx NK-TEXT-LEFT "x %d z %d" (. p x) (. p z)) (nk-labelf ctx NK-TEXT-LEFT "x %d z %d" (. p x) (. p z))
(nk-labelf ctx NK-TEXT-LEFT "from centre %d, %d" (- (. p x) (/ (. s size-x) 2)) (nk-labelf ctx NK-TEXT-LEFT "from spawn %d, %d" (- (. p x) (. a spawn-x)) (- (. p z) (. a spawn-z)))
(- (. p z) (/ (. s size-z) 2)))
(nk-labelf ctx NK-TEXT-LEFT "surface at y %d" (. p height)) (nk-labelf ctx NK-TEXT-LEFT "surface at y %d" (. p height))
(nk-layout-row-dynamic ctx 22 3) (nk-layout-row-dynamic ctx 22 3)
(if (nk-button-label ctx "Go to") (if (nk-button-label ctx "Go to")
@@ -901,6 +1077,28 @@
(nk-label-wrap ctx text)) (nk-label-wrap ctx text))
(== shown 0) (== shown 0)
(nk-label ctx "nothing" NK-TEXT-LEFT)) (nk-label ctx "nothing" NK-TEXT-LEFT))
(if (> (. p map-count) 0)
(do
(var maps [char 300])
(var used int (snprintf maps (sizeof maps) "ore maps, not read by the pick:"))
(for (var i int 0) (&& (< i (. p map-count)) (< used (cast (sizeof maps) int))) (++ i)
(+= used (snprintf (+ maps used) (- (sizeof maps) used) "%s %s %.0f%%"
(if (> i 0) "," "")
(. [(. (. a minerals) minerals) [(. p map-minerals) i]] code)
(* 100 [(. p map-factors) i]))))
(nk-layout-row-dynamic ctx 34 1)
(nk-label-wrap ctx maps)))
(nk-layout-row-dynamic ctx 6 1)
(nk-spacing ctx 1)
(nk-layout-row-dynamic ctx 18 1)
(nk-label ctx (if (. p cave-entrance) "Caves: an entrance here" "Caves") NK-TEXT-LEFT)
(if (== (. p cave-count) 0)
(nk-label ctx "none" NK-TEXT-LEFT))
(for (var i int 0) (< i (. p cave-count)) (++ i)
(var top int [(. p cave-tops) i])
(var bottom int [(. p cave-bottoms) i])
(nk-labelf ctx NK-TEXT-LEFT "%3d-%-3d %-14s %3d" top bottom
(if [(. p cave-lava) i] "lava" "air") (+ (- top bottom) 1)))
(nk-tree-pop ctx)))) (nk-tree-pop ctx))))
;;; The block under the cursor; false when the cursor is not on the ;;; The block under the cursor; false when the cursor is not on the
@@ -920,11 +1118,10 @@
(if (cursor-block a (& bx) (& bz)) (if (cursor-block a (& bx) (& bz))
(do (do
(var value int (rock-query-value a)) (var value int (rock-query-value a))
;; TODO sex#45: use (. a rock-mode) in the literal once member
;; access inside a compound literal follows the pointer.
(var mode int (. a rock-mode))
(var mineral int (if (!= (& (. a overlays) MINERAL-OVERLAY-BIT) 0) (. a mineral) -1)) (var mineral int (if (!= (& (. a overlays) MINERAL-OVERLAY-BIT) 0) (. a mineral) -1))
(hover-worker/ask (. a hover-worker) #(hover-query : bx bz mode value mineral)))) (var caves bool (!= (& (. a overlays) CAVES-OVERLAY-BIT) 0))
(hover-worker/ask (. a hover-worker)
#(hover-query : bx bz (. a rock-mode) value mineral caves))))
(= (. a hover) (hover-worker/result (. a hover-worker)))) (= (. a hover) (hover-worker/result (. a hover-worker))))
(fn rock-name ((a (* app)) (rock int)) (* const char) (fn rock-name ((a (* app)) (rock int)) (* const char)
@@ -934,7 +1131,6 @@
(fn draw-info ((a (* app))) void (fn draw-info ((a (* app))) void
(var ctx (* struct nk-context) (. a ctx)) (var ctx (* struct nk-context) (. a ctx))
(var s (* world-settings) (& (. a source settings)))
(var bx int) (var bx int)
(var bz int) (var bz int)
(var inside bool (cursor-block a (& bx) (& bz))) (var inside bool (cursor-block a (& bx) (& bz)))
@@ -943,7 +1139,7 @@
(do (do
(nk-layout-row-dynamic ctx 18 1) (nk-layout-row-dynamic ctx 18 1)
(nk-labelf ctx NK-TEXT-LEFT "x %d z %d" bx bz) (nk-labelf ctx NK-TEXT-LEFT "x %d z %d" bx bz)
(nk-labelf ctx NK-TEXT-LEFT "from centre %d, %d" (- bx (/ (. s size-x) 2)) (- bz (/ (. s size-z) 2))) (nk-labelf ctx NK-TEXT-LEFT "from spawn %d, %d" (- bx (. a spawn-x)) (- bz (. a spawn-z)))
(nk-labelf ctx NK-TEXT-LEFT "region %d, %d zoom %.3g blocks/pt" (/ bx REGION) (/ bz REGION) (nk-labelf ctx NK-TEXT-LEFT "region %d, %d zoom %.3g blocks/pt" (/ bx REGION) (/ bz REGION)
(. a zoom)) (. a zoom))
(if (&& inside (. r valid)) (if (&& inside (. r valid))
@@ -960,9 +1156,10 @@
(nk-labelf ctx NK-TEXT-LEFT "terrain height %d (sea level %d)" (. r height) (. r sea-level)) (nk-labelf ctx NK-TEXT-LEFT "terrain height %d (sea level %d)" (. r height) (. r sea-level))
(nk-labelf ctx NK-TEXT-LEFT "surface rock %s" (rock-name a (. r surface-rock))) (nk-labelf ctx NK-TEXT-LEFT "surface rock %s" (rock-name a (. r surface-rock)))
(if (>= (. r query mineral) 0) (if (>= (. r query mineral) 0)
(nk-labelf ctx NK-TEXT-LEFT "%s %s, %.2f ppt" (do
(. [(. (. a minerals) minerals) (. r query mineral)] code) (var text [char 96])
[reading-names (ores/category (. r mineral total))] (. r mineral ppt))))) (mineral-at-cursor a r text (sizeof text))
(nk-label ctx text NK-TEXT-LEFT)))))
(nk-labelf ctx NK-TEXT-LEFT "%d tiles pending" (. a pending)) (nk-labelf ctx NK-TEXT-LEFT "%d tiles pending" (. a pending))
(nk-label ctx (. a status) NK-TEXT-LEFT) (nk-label ctx (. a status) NK-TEXT-LEFT)
(nk-tree-pop ctx)))) (nk-tree-pop ctx))))
@@ -978,7 +1175,7 @@
(. a rock-mode) value (. a highlight) (. a center-x) (. a center-z) (. a rock-mode) value (. a highlight) (. a center-x) (. a center-z)
(- (SDL-GetNumLogicalCPUCores) 1)) (- (SDL-GetNumLogicalCPUCores) 1))
(= (. a searching) true) (= (. a searching) true)
(= (. a searching-mineral) false))) (= (. a search-kind) FIND-ROCK)))
(if (. a find-mineral-requested) (if (. a find-mineral-requested)
(do (do
(= (. a find-mineral-requested) false) (= (. a find-mineral-requested) false)
@@ -988,7 +1185,23 @@
SEARCH-MINERAL (. a mineral) (cast (. a min-reading) u32) SEARCH-MINERAL (. a mineral) (cast (. a min-reading) u32)
(. a center-x) (. a center-z) (- (SDL-GetNumLogicalCPUCores) 1)) (. a center-x) (. a center-z) (- (SDL-GetNumLogicalCPUCores) 1))
(= (. a searching) true) (= (. a searching) true)
(= (. a searching-mineral) true))))) (= (. a search-kind) FIND-MINERAL)))))
(if (. a find-cave-requested)
(do
(= (. a find-cave-requested) false)
(search/start (. a search) (. a source settings) (. a rivers) (. a assets-dir)
SEARCH-CAVE-ENTRANCE 0 0 (. a center-x) (. a center-z)
(- (SDL-GetNumLogicalCPUCores) 1))
(= (. a searching) true)
(= (. a search-kind) FIND-CAVE)))
(if (. a find-spring-requested)
(do
(= (. a find-spring-requested) false)
(search/start (. a search) (. a source settings) (. a rivers) (. a assets-dir)
SEARCH-HOT-SPRING 0 0 (. a center-x) (. a center-z)
(- (SDL-GetNumLogicalCPUCores) 1))
(= (. a searching) true)
(= (. a search-kind) FIND-HOT-SPRING)))
(if (! (. a searching)) (if (! (. a searching))
(return)) (return))
(var s (* search) (. a search)) (var s (* search) (. a search))
@@ -1030,7 +1243,8 @@
(do (do
(draw-layers a) (draw-layers a)
(draw-rocks a) (draw-rocks a)
(draw-minerals a))) (draw-minerals a)
(draw-caves a)))
(nk-end ctx)) (nk-end ctx))
;;; A label by the cursor naming the rock under it, as the Rocks ;;; A label by the cursor naming the rock under it, as the Rocks
@@ -1043,7 +1257,8 @@
(fn draw-cursor-rock ((a (* app))) void (fn draw-cursor-rock ((a (* app))) void
(var bx int) (var bx int)
(var bz int) (var bz int)
(if (|| (! (. a show-cursor-rock)) (. a dragging) (! (cursor-block a (& bx) (& bz)))) (if (|| (&& (! (. a show-cursor-rock)) (! (. a picking-spawn))) (. a dragging)
(! (cursor-block a (& bx) (& bz))))
(return)) (return))
(var r (* hover-result) (& (. a hover))) (var r (* hover-result) (& (. a hover)))
(var text [char 64]) (var text [char 64])
@@ -1060,10 +1275,29 @@
(var reading [char 96]) (var reading [char 96])
(= [reading 0] 0) (= [reading 0] 0)
(if (&& (. r valid) (>= (. r query mineral) 0)) (if (&& (. r valid) (>= (. r query mineral) 0))
(snprintf reading (sizeof reading) "%s %s, %.2f ppt" (mineral-at-cursor a r reading (sizeof reading)))
(. [(. (. a minerals) minerals) (. r query mineral)] code) ;; and the caves through the column, top down
[reading-names (ores/category (. r mineral total))] (. r mineral ppt))) (var caves [char 96])
(var height float (if [reading 0] 50 30)) (= [caves 0] 0)
(if (&& (. r valid) (. r query caves))
(if (. r cave-entrance)
(snprintf caves (sizeof caves) "cave entrance")
(== (. r cave-runs) 0)
(snprintf caves (sizeof caves) "no caves")
(do
(var used int (snprintf caves (sizeof caves) "caves y"))
(for (var i int 0) (&& (< i (. r cave-runs)) (< i 3) (< used 80)) (++ i)
(+= used (snprintf (+ caves used) (- (sizeof caves) used) "%s %d-%d%s" (if (> i 0) "," "")
[(. r cave-tops) i] [(. r cave-bottoms) i]
(if [(. r cave-lava) i] " lava" "")))))))
;; or, while the next click sets the spawn, only that
(if (. a picking-spawn)
(do
(snprintf text (sizeof text) "click to set the spawn here")
(= [reading 0] 0)
(= [caves 0] 0)))
(var lines int (+ 1 (if [reading 0] 1 0) (if [caves 0] 1 0)))
(var height float (+ 12 (* 18 lines)))
;; beside the cursor, not under it, so it never takes the map's input ;; beside the cursor, not under it, so it never takes the map's input
(var ctx (* struct nk-context) (. a ctx)) (var ctx (* struct nk-context) (. a ctx))
(var bounds (struct nk-rect) (nk-rect (+ (. a mouse-x) 16) (+ (. a mouse-y) 16) 260 height)) (var bounds (struct nk-rect) (nk-rect (+ (. a mouse-x) 16) (+ (. a mouse-y) 16) 260 height))
@@ -1073,7 +1307,9 @@
(nk-layout-row-dynamic ctx 18 1) (nk-layout-row-dynamic ctx 18 1)
(nk-label ctx text NK-TEXT-LEFT) (nk-label ctx text NK-TEXT-LEFT)
(if [reading 0] (if [reading 0]
(nk-label ctx reading NK-TEXT-LEFT)))) (nk-label ctx reading NK-TEXT-LEFT))
(if [caves 0]
(nk-label ctx caves NK-TEXT-LEFT))))
(nk-end ctx)) (nk-end ctx))
;;; Events --------------------------------------------------------- ;;; Events ---------------------------------------------------------
@@ -1119,11 +1355,21 @@
(var bx int (cast (floor (to-world-x a (. event button x))) int)) (var bx int (cast (floor (to-world-x a (. event button x))) int))
(var bz int (cast (floor (to-world-z a (. event button y))) int)) (var bz int (cast (floor (to-world-z a (. event button y))) int))
(var pin int (pin-at a (. event button x) (. event button y))) (var pin int (pin-at a (. event button x) (. event button y)))
(if (>= pin 0) (var on-world bool (&& (>= bx 0) (>= bz 0) (< bx (. a source settings size-x))
(< bz (. a source settings size-z))))
(if (&& (. a picking-spawn) on-world)
(do
(= (. a spawn-x) bx)
(= (. a spawn-z) bz)
(= (. a picking-spawn) false))
(>= pin 0)
(probe-at a [(. a pins) (* pin 2)] [(. a pins) (+ (* pin 2) 1)]) (probe-at a [(. a pins) (* pin 2)] [(. a pins) (+ (* pin 2) 1)])
(&& (>= bx 0) (>= bz 0) (< bx (. a source settings size-x)) (< bz (. a source settings size-z))) on-world
(probe-at a bx bz)))) (probe-at a bx bz))))
(= (. a dragging) false)) (= (. a dragging) false))
;; Escape gives up setting the spawn
(&& (== type SDL-EVENT-KEY-DOWN) (== (. event key key) SDLK-ESCAPE))
(= (. a picking-spawn) false)
(&& (== type SDL-EVENT-MOUSE-WHEEL) (! (. a ui-hovered))) (&& (== type SDL-EVENT-MOUSE-WHEEL) (! (. a ui-hovered)))
(zoom-at a (pow 1.25 (- (. event wheel y))))) (zoom-at a (pow 1.25 (- (. event wheel y)))))
(nk-sdl-handle-event (. a ctx) event) (nk-sdl-handle-event (. a ctx) event)
@@ -1187,6 +1433,12 @@
(= (. a mouse-x) (cast (atof [argv (+ i 1)]) float)) (= (. a mouse-x) (cast (atof [argv (+ i 1)]) float))
(= (. a mouse-y) (cast (atof [argv (+ i 2)]) float)) (= (. a mouse-y) (cast (atof [argv (+ i 2)]) float))
(+= i 2)) (+= i 2))
(&& (== (strcmp [argv i] "--spawn") 0) (< (+ i 2) argc))
(do
(= (. a spawn-arg) true)
(= (. a arg-spawn-x) (atoi [argv (+ i 1)]))
(= (. a arg-spawn-z) (atoi [argv (+ i 2)]))
(+= i 2))
(&& (== (strcmp [argv i] "--probe") 0) (< (+ i 2) argc)) (&& (== (strcmp [argv i] "--probe") 0) (< (+ i 2) argc))
(do (do
(= (. a probe-x) (atoi [argv (+ i 1)])) (= (. a probe-x) (atoi [argv (+ i 1)]))
@@ -1200,6 +1452,10 @@
(do (++ i) (= (. a min-reading) (reading-named [argv i]))) (do (++ i) (= (. a min-reading) (reading-named [argv i])))
(== (strcmp [argv i] "--find-mineral") 0) (== (strcmp [argv i] "--find-mineral") 0)
(= (. a find-mineral-requested) true) (= (. a find-mineral-requested) true)
(== (strcmp [argv i] "--find-cave") 0)
(= (. a find-cave-requested) true)
(== (strcmp [argv i] "--find-hot-spring") 0)
(= (. a find-spring-requested) true)
(&& (== (strcmp [argv i] "--highlight") 0) more) (&& (== (strcmp [argv i] "--highlight") 0) more)
(do (do
(++ i) (++ i)
@@ -1240,6 +1496,11 @@
(do (do
(fprintf stderr "%s\n" (. a status)) (fprintf stderr "%s\n" (. a status))
(return 1))) (return 1)))
(reset-spawn a)
(if (. a spawn-arg)
(do
(= (. a spawn-x) (. a arg-spawn-x))
(= (. a spawn-z) (. a arg-spawn-z))))
(go-to-spawn a) (go-to-spawn a)
(if (|| (. a probe-x) (. a probe-z)) (if (|| (. a probe-x) (. a probe-z))
(probe-at a (. a probe-x) (. a probe-z))) (probe-at a (. a probe-x) (. a probe-z)))
@@ -1281,7 +1542,8 @@
(SDL-SetRenderClipRect (. a renderer) NULL) (SDL-SetRenderClipRect (. a renderer) NULL)
(nk-sdl-render (. a ctx) NK-ANTI-ALIASING-ON) (nk-sdl-render (. a ctx) NK-ANTI-ALIASING-ON)
(if (&& (. a screenshot) (== (. a pending) 0) (! (. a searching)) (! (. a find-requested)) (if (&& (. a screenshot) (== (. a pending) 0) (! (. a searching)) (! (. a find-requested))
(! (. a find-mineral-requested))) (! (. a find-mineral-requested)) (! (. a find-cave-requested))
(! (. a find-spring-requested)))
(do (do
(if (! (save-screenshot a)) (if (! (save-screenshot a))
(fprintf stderr "%s: %s\n" (. a screenshot) (SDL-GetError))) (fprintf stderr "%s: %s\n" (. a screenshot) (SDL-GetError)))

View File

@@ -2,23 +2,12 @@
;;; against a saved world and dumps what either side produced. ;;; against a saved world and dumps what either side produced.
(include stdio.h string.h) (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 cs)
(import json) (import json)
(import maps)
(import lcg)
(import noise)
(import shape)
(import save) (import save)
(import dump) (import dump)
(import worldgen) (import worldgen)
(import fastnoise)
(import rivers) (import rivers)
(import terra)
(import strata) (import strata)
(import settings) (import settings)
(import ores) (import ores)
@@ -39,6 +28,9 @@
(return 1)) (return 1))
(printf "seed %d\n" (. s seed)) (printf "seed %d\n" (. s seed))
(printf "size %d x %d x %d\n" (. s size-x) (. s size-y) (. s size-z)) (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 "block ids %d\n" (. s block-count))
(printf "world config, %d values:\n" (. s config-count)) (printf "world config, %d values:\n" (. s config-count))
(for (var i int 0) (< i (. s config-count)) (++ i) (for (var i int 0) (< i (. s config-count)) (++ i)
@@ -99,6 +91,8 @@
(var failed int (+ (verify-stories s g) (verify-regions s g out) (var failed int (+ (verify-stories s g) (verify-regions s g out)
(verify-ores s minerals out) (verify-ores s minerals out)
(verify-readings s g (river-config/defaults) rocks minerals) (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-rivers s g (river-config/defaults) out)
(verify-heights s g (river-config/defaults) rocks out))) (verify-heights s g (river-config/defaults) rocks out)))
(save/close s) (save/close s)

View File

@@ -4,11 +4,11 @@
;;; the worldgen assets and the region's coordinates. ;;; the worldgen assets and the region's coordinates.
(include stdio.h stdlib.h string.h math.h) (include stdio.h stdlib.h string.h math.h)
(import maps) (pub import maps)
(import lcg) (pub import lcg)
(import noise) (import noise)
(import json) (pub import json)
(import shape) (pub import shape)
(pub define MAX-PROVINCES 32) (pub define MAX-PROVINCES 32)
@@ -80,11 +80,9 @@
;;; NoiseGeoProvince plus MapLayerGeoProvince: a weighted random ;;; NoiseGeoProvince plus MapLayerGeoProvince: a weighted random
;;; province per 64x64 cell of province-map pixels, sampled through a ;;; province per 64x64 cell of province-map pixels, sampled through a
;;; wobble so the cells don't show. ;;; 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 (pub record province-layer
((rng lcg) (weights [int MAX_PROVINCES]) (count int) (weight-sum int) ((rng lcg) (weights [int MAX-PROVINCES]) (count int) (weight-sum int)
(codes [* char MAX_PROVINCES]) (colours [u32 MAX_PROVINCES]) (codes [* char MAX-PROVINCES]) (colours [u32 MAX-PROVINCES])
(wobble-x (* simplex-noise)) (wobble-z (* simplex-noise)))) (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))))
(define GEOPROV-MAP-SCALE 64) (define GEOPROV-MAP-SCALE 64)
@@ -167,10 +165,7 @@
(= [map (+ start (* i stride))] (cast [tmp i] i32)))) (= [map (+ start (* i stride))] (cast [tmp i] i32))))
(fn box-blur ((map (* i32)) (w int) (h int) (range int)) void (fn box-blur ((map (* i32)) (w int) (h int) (range int)) void
;; TODO sex#59: inline the longer side once a conditional operand (var tmp (* u32) (malloc (* (if (> w h) w h) (sizeof u32))))
;; keeps its parentheses.
(var longest int (if (> w h) w h))
(var tmp (* u32) (malloc (* longest (sizeof u32))))
(for (var y int 0) (< y h) (++ y) (for (var y int 0) (< y h) (++ y)
(blur-line map (* y w) 1 w range tmp)) (blur-line map (* y w) 1 w range tmp))
(for (var x int 0) (< x w) (++ x) (for (var x int 0) (< x w) (++ x)
@@ -390,9 +385,7 @@
(= (. l octave-threshold-count) 11))) (= (. l octave-threshold-count) 11)))
(= (. l first-mutation) -1)) (= (. l first-mutation) -1))
;; TODO sex#50: write MAX-LANDFORMS once constants in array types are (pub record landform-table ((all [landform MAX-LANDFORMS]) (count int) (variant-count int)))
;; kebab-converted.
(pub record landform-table ((all [landform MAX_LANDFORMS]) (count int) (variant-count int)))
(pub fn terrain-octave-count ((size-y int)) int (pub fn terrain-octave-count ((size-y int)) int
(return (+ 9 (/ (- size-y 256) 128)))) (return (+ 9 (/ (- size-y 256) 128))))
@@ -452,11 +445,9 @@
(return (|| (!= (- rain clamped-rain) 0) (!= (- t clamped-temp) 0)))) (return (|| (!= (- rain clamped-rain) 0) (!= (- t clamped-temp) 0))))
;;; MapLayerLandforms over NoiseLandforms. ;;; MapLayerLandforms over NoiseLandforms.
;; TODO sex#50: write MAX-LANDFORMS once constants in array types are
;; kebab-converted.
(pub record landform-layer (pub record landform-layer
((rng lcg) (table (* const landform-table)) (climate climate-noise) (scale float) ((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)))) (wobble-x (* simplex-noise)) (wobble-z (* simplex-noise))))
(define LANDFORM-MAP-SCALE 16) (define LANDFORM-MAP-SCALE 16)
@@ -724,11 +715,9 @@
;;; MapLayerCustomPerlin per stratum of rockstrata.json: how thick ;;; MapLayerCustomPerlin per stratum of rockstrata.json: how thick
;;; that stratum may be, in blocks, per 16 blocks of region. ;;; 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 (pub record strata-layer
((count int) (noises [* simplex-sum MAX_STRATA]) (thresholds [* double MAX_STRATA]) ((count int) (noises [* simplex-sum MAX-STRATA]) (thresholds [* double MAX-STRATA])
(codes [* char MAX_STRATA]))) (codes [* char MAX-STRATA])))
(fn json-doubles ((o (* cJSON)) (key (* const char)) (out (* double)) (max int)) int (fn json-doubles ((o (* cJSON)) (key (* const char)) (out (* double)) (max int)) int
(var arr (* cJSON) (cJSON-GetObjectItem o key)) (var arr (* cJSON) (cJSON-GetObjectItem o key))
@@ -744,10 +733,8 @@
(memset (& l) 0 (sizeof l)) (memset (& l) 0 (sizeof l))
(var variants (* cJSON) (cJSON-GetObjectItem rockstrata "variants")) (var variants (* cJSON) (cJSON-GetObjectItem rockstrata "variants"))
(for (var v (* cJSON) (. variants child)) (&& v (< (. l count) MAX-STRATA)) (= v (. v next)) (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 (var amplitudes [double MAX-OCTAVES])
;; are kebab-converted. (var frequencies [double MAX-OCTAVES])
(var amplitudes [double MAX_OCTAVES])
(var frequencies [double MAX_OCTAVES])
(var th (* double) (calloc MAX-OCTAVES (sizeof double))) (var th (* double) (calloc MAX-OCTAVES (sizeof double)))
(var n int (json-doubles v "amplitudes" amplitudes MAX-OCTAVES)) (var n int (json-doubles v "amplitudes" amplitudes MAX-OCTAVES))
(json-doubles v "frequencies" frequencies MAX-OCTAVES) (json-doubles v "frequencies" frequencies MAX-OCTAVES)
@@ -780,7 +767,18 @@
;;; forces on the region maps around it. ;;; forces on the region maps around it.
(pub record story (pub record story
((code [char 64]) (x int) (z int) (dir-x int) (landform-radius int) ((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 (fn json-int ((o (* cJSON)) (key (* const char)) (fallback int)) int
(return (cast (json-number o key fallback) int))) (return (cast (json-number o key fallback) int)))
@@ -827,8 +825,7 @@
(= base-z (. parent z)) (= base-z (. parent z))
(= dir-x (. parent dir-x))) (= dir-x (. parent dir-x)))
(continue)) (continue))
;; TODO sex#59: put the (if ...) in the product below once a ;; drawn here, before the distances, as GenStoryStructures draws it
;; conditional operand keeps its parentheses.
(var dir-z int (if (> (.next-float (& rng)) 0.5) -1 1)) (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-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)))) (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 z) (+ base-z (* dist-z dir-z)))
(= (. st dir-x) dir-x) (= (. st dir-x) dir-x)
(= (. st landform-radius) (json-int c "landformRadius" 0)) (= (. 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"))) (var landform (* const char) (cJSON-GetStringValue (cJSON-GetObjectItem c "requireLandform")))
(= (. st landform) (if landform (landform-table/find landforms landform) -1)) (= (. st landform) (if landform (landform-table/find landforms landform) -1))
(var force-temp (* cJSON) (cJSON-GetObjectItem c "forceTemperature")) (var force-temp (* cJSON) (cJSON-GetObjectItem c "forceTemperature"))
@@ -981,7 +988,7 @@
((settings world-settings) (provinces province-layer) (landform-table landform-table) ((settings world-settings) (provinces province-layer) (landform-table landform-table)
(landforms landform-layer) (oceans ocean-layer) (upheaval upheaval-layer) (landforms landform-layer) (oceans ocean-layer) (upheaval upheaval-layer)
(climate climate-layer) (strata strata-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)))) (story-wobble-x (* simplex-noise)) (story-wobble-z (* simplex-noise))))
(pub fn worldgen/make ((settings world-settings) (assets-dir (* const char))) (* worldgen) (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) (for (var i int 0) (< i (. g strata count)) (++ i)
(worldgen/map g MAP-STRATA i rx rz (& [(. out strata) 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 (pub fn worldgen/free ((g (* worldgen))) void
(for (var i int 0) (< i (. g landform-table count)) (++ i) (for (var i int 0) (< i (. g landform-table count)) (++ i)
(free (. [(. g landform-table all) i] y-thresholds))) (free (. [(. g landform-table all) i] y-thresholds)))