read the save, the seed and the worldgen assets

The engine's save classes are closed, so the protobuf field numbers
were read off the data and matched to the map sizes TerraGenConfig
gives. vsmv dump renders what the save stored, as the reference the
generator will be diffed against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 17:56:14 +03:00
parent d72ae437ae
commit 90b5d50fa5
12 changed files with 2807 additions and 51 deletions

83
src/cs.sex Normal file
View File

@@ -0,0 +1,83 @@
;;; C# semantics the generator depends on, written once. Integer math
;;; that C# lets wrap goes through unsigned types here, because in C
;;; signed overflow is undefined.
(include stdlib.h string.h stdint.h errno.h)
;;; Decodes one UTF-8 sequence at *S into a code point and advances *S.
;;; A malformed byte decodes as U+FFFD, as .NET's decoder does.
(fn utf8-next ((s (* * const u8))) u32
(var p (* const u8) (* s))
(var c u32 [p 0])
(var n int 0)
(if (< c 128) (= n 0)
(== (& c 224) 192) (do (= n 1) (&= c 31))
(== (& c 240) 224) (do (= n 2) (&= c 15))
(== (& c 248) 240) (do (= n 3) (&= c 7))
(do (= (* s) (+ p 1)) (return 65533)))
(for (var i int 1) (<= i n) (++ i)
(if (!= (& [p i] 192) 128)
(do (= (* s) (+ p i)) (return 65533)))
(= c (c-bit-or (<< c 6) (& [p i] 63))))
(= (* s) (+ p n 1))
(return c))
;;; The UTF-16 code units of a UTF-8 string, which is what a C# string
;;; is in memory. Returns the unit count; the buffer is zero padded
;;; past it, standing in for the terminator .NET keeps after a string.
(fn utf16 ((text (* const char)) (out (* * u16))) size-t
(var len size-t (strlen text))
(var units (* u16) (calloc (+ (* 2 len) 4) (sizeof u16)))
(var n size-t 0)
(var p (* const u8) (cast text (* const u8)))
(while (* p)
(var c u32 (utf8-next (& p)))
(if (< c 65536)
(do
(= [units n] c)
(+= n 1))
(do
(-= c 65536)
(= [units n] (+ 55296 (>> c 10)))
(= [units (+ n 1)] (+ 56320 (& c 1023)))
(+= n 2))))
(= (* out) units)
(return n))
(fn hash-step ((h i32) (word u32)) i32
(var u u32 (cast h u32))
(return (cast (^ (+ (<< u 5) u (cast (>> h 27) u32)) word) i32)))
;;; GameMath.DotNetStringHash: .NET Framework's 32-bit string hash,
;;; which the game persists, so it has to be the old one and not the
;;; randomized hash .NET has now. It reads the string two UTF-16 units
;;; at a time.
;;; (dotnet-string-hash "письки+жопки") => -90319180
(pub fn dotnet-string-hash ((text (* const char))) i32
(var units (* u16) NULL)
(var len int (cast (utf16 text (& units)) int))
(var h1 i32 (+ (<< 5381 16) 5381))
(var h2 i32 h1)
(var i int 0)
(while (> len 2)
(= h1 (hash-step h1 (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16))))
(= h2 (hash-step h2 (c-bit-or [units (+ i 2)] (<< (cast [units (+ i 3)] u32) 16))))
(+= i 4)
(-= len 4))
(if (> len 0)
(= h1 (hash-step h1 (c-bit-or [units i] (<< (cast [units (+ i 1)] u32) 16)))))
(free units)
(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
;;; taken as it is, anything else is hashed.
;;; (world-seed "12345") => 12345
;;; (world-seed "письки+жопки") => -90319180
(pub fn world-seed ((text (* const char))) i32
(var end (* char) NULL)
(= errno 0)
(var v long (strtol text (& end) 10))
(if (&& (* text) (== (* end) 0) (== errno 0)
(>= v INT32_MIN) (<= v INT32_MAX))
(return (cast v i32)))
(return (dotnet-string-hash text)))

149
src/dump.sex Normal file
View File

@@ -0,0 +1,149 @@
;;; Renders what a save stored into PNG mosaics over its whole explored
;;; area: one image per region map, one per chunk map. These are the
;;; pictures the generator's own output is diffed against.
(include stdio.h stdlib.h string.h)
(import save)
(import img)
(fn landform-colour ((v i32)) u32 (return (palette (cast v u32))))
(fn province-colour ((v i32)) u32 (return (palette (+ (cast v u32) 100))))
(fn climate-colour ((v i32)) u32 (return (& (cast v u32) 16777215)))
(fn byte-colour ((v i32)) u32 (return (grey v)))
;;; The inner square of one region's map, placed at (ox, oz) and
;;; stretched to CELL pixels a side, so maps of different resolutions
;;; line up pixel for pixel across mosaics.
(fn paint-map ((im (* image)) (m (* const int-map)) (ox int) (oz int) (cell int)
(colour (fn ((i32)) u32))) void
(var inner int (- (. m size) (. m pad-tl) (. m pad-br)))
(if (<= inner 0)
(return))
(for (var y int 0) (< y cell) (++ y)
(for (var x int 0) (< x cell) (++ x)
(var mx int (+ (. m pad-tl) (/ (* x inner) cell)))
(var mz int (+ (. m pad-tl) (/ (* y inner) cell)))
(.set im (+ ox x) (+ oz y) (colour [(. m data) (+ (* mz (. m size)) mx)])))))
(fn write-image ((im (* image)) (dir (* const char)) (name (* const char))) void
(var path [char 1024])
(snprintf path (sizeof path) "%s/%s.png" dir name)
(if (.write im path)
(printf " %s (%dx%d)\n" path (. im w) (. im h))
(fprintf stderr "%s: cannot write\n" path)))
;;; Region maps at 1 pixel per 16 blocks (32 per region), which is the
;;; landform and strata resolution; coarser maps are stretched.
(fn dump-regions ((s (* save)) (dir (* const char))) void
(var e extent (save/extent s "mapregion"))
(var cell int 32)
(var w int (* (+ (- (. e x1) (. e x0)) 1) cell))
(var h int (* (+ (- (. e z1) (. e z0)) 1) cell))
(printf "regions %d..%d x %d..%d, %lld stored\n"
(. e x0) (. e x1) (. e z0) (. e z1) (. e count))
(var landform image (image/make w h))
(var climate image (image/make w h))
(var province image (image/make w h))
(var ocean image (image/make w h))
(var upheaval image (image/make w h))
(var strata [image MAX_STRATA])
(var strata-count int 0)
(var m region-maps)
(for (var rz int (. e z0)) (<= rz (. e z1)) (++ rz)
(for (var rx int (. e x0)) (<= rx (. e x1)) (++ rx)
(if (! (save/region s rx rz (& m)))
(continue))
(var ox int (* (- rx (. e x0)) cell))
(var oz int (* (- rz (. e z0)) cell))
(paint-map (& landform) (& (. m landform)) ox oz cell landform-colour)
(paint-map (& climate) (& (. m climate)) ox oz cell climate-colour)
(paint-map (& province) (& (. m geoprov)) ox oz cell province-colour)
(paint-map (& ocean) (& (. m ocean)) ox oz cell byte-colour)
(paint-map (& upheaval) (& (. m upheaval)) ox oz cell byte-colour)
(while (< strata-count (. m strata-count))
(= [strata strata-count] (image/make w h))
(++ strata-count))
(for (var i int 0) (< i (. m strata-count)) (++ i)
(paint-map (& [strata i]) (& [(. m strata) i]) ox oz cell byte-colour))
(region-maps/free (& m))))
(write-image (& landform) dir "landform")
(write-image (& climate) dir "climate")
(write-image (& province) dir "province")
(write-image (& ocean) dir "ocean")
(write-image (& upheaval) dir "upheaval")
(for (var i int 0) (< i strata-count) (++ i)
(var name [char 32])
(snprintf name (sizeof name) "strata-%02d" i)
(write-image (& [strata i]) dir name)
(.release (& [strata i])))
(.release (& landform))
(.release (& climate))
(.release (& province))
(.release (& ocean))
(.release (& upheaval)))
;;; Terrain height, shaded against sea level: land in greys, water
;;; columns in blues.
(fn height-colour ((height int) (sea-level int) (size-y int)) u32
(if (< height sea-level)
(return (c-bit-or (<< (cast (/ (* height 128) sea-level) u32) 8)
(+ 128 (cast (/ (* height 127) sea-level) u32)))))
(return (grey (+ 64 (/ (* (- height sea-level) 191) (- size-y sea-level))))))
;;; Chunk maps at a pixel per block: worldgen terrain height, the top
;;; rock, and Rivers' distance to the nearest river.
(fn dump-chunks ((s (* save)) (dir (* const char))) void
(var e extent (save/extent s "mapchunk"))
(var w int (* (+ (- (. e x1) (. e x0)) 1) CHUNK-SIZE))
(var h int (* (+ (- (. e z1) (. e z0)) 1) CHUNK-SIZE))
(printf "chunks %d..%d x %d..%d, %lld stored\n"
(. e x0) (. e x1) (. e z0) (. e z1) (. e count))
;; GameMath: sea level is 0.4313725 of the world height.
(var sea-level int (cast (* 0.4313725 (. s size-y)) int))
(var height image (image/make w h))
(var rock image (image/make w h))
(var river image (image/make w h))
(var rock-counts (* i64) (calloc (+ (. s block-count) 1) (sizeof i64)))
(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))
(for (var i int 0) (< i CHUNK-AREA) (++ i)
(var x int (+ (* (- cx (. e x0)) CHUNK-SIZE) (% i CHUNK-SIZE)))
(var y int (+ (* (- cz (. e z0)) CHUNK-SIZE) (/ i CHUNK-SIZE)))
(.set (& height) x y (height-colour [(. m terrain-height) i] sea-level (. s size-y)))
(var id i32 [(. m top-rock) i])
(.set (& rock) x y (palette (cast id u32)))
(if (&& (>= id 0) (< id (. s block-count)))
(++ [rock-counts id]))
(if (. m has-river-distance)
(do
(var d int [(. m river-distance) i])
(var c u32 (grey (- 255 d)))
(if (== d 0) (= c 4219071))
(.set (& river) x y c))
(.set (& river) x y 2105376)))))
(write-image (& height) dir "height")
(write-image (& rock) dir "toprock")
(write-image (& river) dir "river-distance")
(.release (& height))
(.release (& rock))
(.release (& river))
(printf "top rock columns:\n")
(for (var id int 0) (< id (. s block-count)) (++ id)
(if (> [rock-counts id] 0)
(printf " %6d %-28s #%06x %lld\n" id (save/block-code s id)
(palette (cast id u32)) [rock-counts id])))
(free rock-counts))
(pub fn dump ((s (* save)) (dir (* const char))) void
(dump-regions s dir)
(dump-chunks s dir))

38
src/img.sex Normal file
View File

@@ -0,0 +1,38 @@
;;; RGB images, written as PNG: the dumps the generator and the save
;;; are compared by.
(include stdlib.h "stb_image_write.h")
(pub record image ((w int) (h int) (rgb (* u8))))
(ops image
;; Black, w×h.
(pub fn make ((w int) (h int)) image
(return #(image : w h (calloc (* (cast w size-t) h 3) 1))))
;; COLOUR is 0xRRGGBB.
(pub fn set ((self (* image)) (x int) (y int) (colour u32)) void
(var p (* u8) (+ (. self rgb) (* (+ (* (cast y size-t) (. self w)) x) 3)))
(= [p 0] (cast (& (>> colour 16) 255) u8))
(= [p 1] (cast (& (>> colour 8) 255) u8))
(= [p 2] (cast (& colour 255) u8)))
(pub fn write ((self (* const image)) (path (* const char))) bool
(return (!= (stbi-write-png path (. self w) (. self h) 3 (. self rgb) (* (. self w) 3)) 0)))
(pub fn release ((self (* image))) void
(free (. self rgb))
(= (. self rgb) NULL)))
;;; A distinct, stable colour per small integer: landform and province
;;; indices, block ids.
(pub fn palette ((i u32)) u32
(var h u32 (* (+ i 1) (cast 2654435761 u32)))
(return (c-bit-or (<< (+ 48 (& (>> h 24) 191)) 16)
(<< (+ 48 (& (>> h 16) 191)) 8)
(+ 48 (& (>> h 8) 191)))))
(pub fn grey ((v int)) u32
(if (< v 0) (= v 0))
(if (> v 255) (= v 255))
(return (* (cast v u32) 65793)))

116
src/json.sex Normal file
View File

@@ -0,0 +1,116 @@
;;; Loads the game's asset JSON. The game reads it with Newtonsoft,
;;; which takes comments, unquoted keys and trailing commas; cJSON
;;; takes none of them. So each file is first rewritten into strict
;;; JSON, line for line, and then handed to cJSON.
(pub include "cJSON.h")
(include stdio.h stdlib.h string.h ctype.h)
(fn ident-start-char ((c char)) bool
(return (|| (isalpha (cast c u8)) (== c #\_) (== c #\$))))
(fn ident-char ((c char)) bool
(return (|| (ident-start-char c) (isdigit (cast c u8)))))
;;; Drops a comma that was the last thing written before a closing
;;; bracket: `[1, 2, ]' -> `[1, 2 ]'.
(fn drop-trailing-comma ((out (* char)) (n size-t)) size-t
(var k size-t n)
(while (&& (> k 0) (isspace (cast [out (- k 1)] u8)))
(-= k 1))
(if (&& (> k 0) (== [out (- k 1)] #\,))
(= [out (- k 1)] #\space))
(return n))
;;; {code: "x", // note
;;; values: [1, 2,],}
;;; -> {"code": "x",
;;; "values": [1, 2 ] }
;;; Newlines are kept, so cJSON's error offsets map back to source lines.
(pub fn json-strict ((src (* const char))) (* char)
(var out (* char) (malloc (+ (* 3 (strlen src)) 1)))
(var n size-t 0)
(var p (* const char) src)
(while (* p)
(var c char (* p))
(if (== c #\")
(do
(= [out n] c) (+= n 1) (+= p 1)
(while (&& (* p) (!= (* p) #\"))
(if (&& (== (* p) #\\) [p 1])
(do (= [out n] (* p)) (+= n 1) (+= p 1)))
(= [out n] (* p)) (+= n 1) (+= p 1))
(if (* p)
(do (= [out n] (* p)) (+= n 1) (+= p 1))))
(&& (== c #\/) (== [p 1] #\/))
(while (&& (* p) (!= (* p) #\newline))
(+= p 1))
(&& (== c #\/) (== [p 1] #\*))
(do
(+= p 2)
(while (&& (* p) (! (&& (== (* p) #\*) (== [p 1] #\/))))
(if (== (* p) #\newline)
(do (= [out n] #\newline) (+= n 1)))
(+= p 1))
(if (* p) (+= p 2)))
(|| (== c #\]) (== c #\}))
(do
(= n (drop-trailing-comma out n))
(= [out n] c) (+= n 1) (+= p 1))
(ident-start-char c)
(do
(var start (* const char) p)
(while (ident-char (* p))
(+= p 1))
(var len size-t (cast (- p start) size-t))
(var bare bool (|| (&& (== len 4) (|| (== (strncmp start "true" 4) 0)
(== (strncmp start "null" 4) 0)))
(&& (== len 5) (== (strncmp start "false" 5) 0))))
(if (! bare)
(do (= [out n] #\") (+= n 1)))
(memcpy (+ out n) start len)
(+= n len)
(if (! bare)
(do (= [out n] #\") (+= n 1))))
(do
(= [out n] c) (+= n 1) (+= p 1))))
(= [out n] 0)
(return out))
(fn read-file ((path (* const char))) (* char)
(var f (* FILE) (fopen path "rb"))
(if (! f)
(return NULL))
(fseek f 0 SEEK-END)
(var len long (ftell f))
(fseek f 0 SEEK-SET)
(var text (* char) (malloc (+ len 1)))
(var got size-t (fread text 1 len f))
(fclose f)
(= [text got] 0)
(return text))
(fn line-of ((text (* const char)) (at (* const char))) int
(var line int 1)
(for (var p (* const char) text) (< p at) (++ p)
(if (== (* p) #\newline)
(++ line)))
(return line))
;;; The parsed file, or NULL after saying what went wrong on stderr.
;;; The caller frees it with cJSON-Delete.
(pub fn json-load ((path (* const char))) (* cJSON)
(var text (* char) (read-file path))
(if (! text)
(do
(fprintf stderr "%s: cannot read\n" path)
(return NULL)))
(var strict (* char) (json-strict text))
(free text)
(var end (* const char) NULL)
(var json (* cJSON) (cJSON-ParseWithOpts strict (& end) 1))
(if (! json)
(fprintf stderr "%s:%d: not JSON even after relaxing it\n"
path (line-of strict end)))
(free strict)
(return json))

88
src/pb.sex Normal file
View File

@@ -0,0 +1,88 @@
;;; Protobuf wire reader for the blobs in a .vcdbs save. The engine's
;;; message classes are closed, so callers walk fields by number and
;;; keep only what they know; everything else is skipped.
;;;
;;; A reader is a window over borrowed bytes. A malformed blob sets
;;; `err' and empties the window, so a loop on `more' always ends.
(pub include stddef.h)
(include string.h)
(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)))
(ops pb
(pub fn of ((data (* const void)) (len size-t)) pb
(var p (* const u8) data)
(return #(pb : p (+ p len) false)))
(fn fail ((self (* pb))) void
(= (. self err) true)
(= (. self p) (. self end)))
(pub fn more ((self (* const pb))) bool
(return (< (. self p) (. self end))))
(pub fn len ((self (* const pb))) size-t
(return (cast (- (. self end) (. self p)) size-t)))
(pub fn varint ((self (* pb))) u64
(var v u64 0)
(for (var shift int 0) (< shift 64) (+= shift 7)
(if (>= (. self p) (. self end))
(break))
(var b u8 (* (. self p)))
(++ (. self p))
(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.
(pub fn field ((self (* pb)) (wire (* int))) u32
(if (! (.more self))
(return 0))
(var key u64 (.varint self))
(= (* wire) (cast (& key 7) int))
(return (cast (>> key 3) u32)))
;; A length-delimited field as a reader of its own: a submessage, a
;; string, or a packed array.
(pub fn bytes ((self (* pb))) pb
(var len u64 (.varint self))
(var p (* const u8) (. self p))
(if (> len (.len self))
(do
(.fail self)
(return #(pb : p p true))))
(+= (. self p) len)
(return #(pb : p (+ p len) false)))
;; True when the rest of the window spells exactly S, e.g. a map
;; entry's key against "riverDistance".
(pub fn equals ((self (* const pb)) (s (* const char))) bool
(var n size-t (.len self))
(return (&& (== (strlen s) n) (== (memcmp (. self p) s n) 0))))
(fn advance ((self (* pb)) (n size-t)) void
(if (> n (.len self))
(.fail self)
(+= (. self p) n)))
(pub fn skip ((self (* pb)) (wire int)) void
(switch wire
(case WIRE-VARINT (.varint self) (break))
(case WIRE-BYTES (.bytes self) (break))
(case WIRE-FIXED64 (.advance self 8) (break))
(case WIRE-FIXED32 (.advance self 4) (break))
(default (.fail self)))))

390
src/save.sex Normal file
View File

@@ -0,0 +1,390 @@
;;; Reads a Vintage Story save (.vcdbs): the world's settings, and the
;;; maps worldgen stored per map region and per map chunk. This is the
;;; ground truth the generator is checked against.
;;;
;;; The save is SQLite with protobuf blobs. The message classes live
;;; in the closed engine, so the field numbers below were read off the
;;; data itself, matched against the map sizes in TerraGenConfig.
(pub include sqlite3.h)
(include stdio.h stdlib.h string.h)
(import pb)
;;; RegionSize is the closed engine's; Rivers hardcodes the same 512.
(pub define REGION-SIZE 512)
(pub define CHUNK-SIZE 32)
(pub define CHUNK-AREA 1024)
(pub define MAX-STRATA 32)
(pub define MAX-STORIES 32)
;;; IntDataMap2D: a square map whose border pixels only feed lerps
;;; and blurs. The region's own pixels are the inner
;;; (size - pad-tl - pad-br) square.
(pub record int-map ((data (* i32)) (size i32) (pad-tl i32) (pad-br i32)))
(pub record region-maps
((landform int-map) (climate int-map) (geoprov int-map) (upheaval int-map)
(ocean int-map) (strata [int-map MAX_STRATA]) (strata-count int)))
(pub record chunk-maps
((terrain-height [u16 CHUNK_AREA]) (rain-height [u16 CHUNK_AREA])
(top-rock [i32 CHUNK_AREA]) (river-distance [u16 CHUNK_AREA])
(has-river-distance bool)))
(pub record story-location ((code [char 64]) (x i32) (y i32) (z i32)))
(pub record save
((db (* sqlite3)) (seed i32) (size-x i32) (size-y i32) (size-z i32)
(config-keys (* * char)) (config-values (* * char)) (config-count int)
(block-codes (* * char)) (block-count int)
(stories [story-location MAX_STORIES]) (story-count int)))
;;; Map regions and map chunks share one key: x in the low 27 bits,
;;; z above them.
(fn position ((x i32) (z i32)) i64
(return (c-bit-or (cast x i64) (<< (cast z i64) 27))))
(fn strndup-pb ((r pb)) (* char)
(return (strndup (cast (. r p) (* const char)) (.len r))))
;;; World config ----------------------------------------------------
(fn add-config ((s (* save)) (key (* char)) (value (* char))) void
(var n int (. s config-count))
(= (. s config-keys) (realloc (. s config-keys) (* (+ n 1) (sizeof key))))
(= (. s config-values) (realloc (. s config-values) (* (+ n 1) (sizeof value))))
(= [(. s config-keys) n] key)
(= [(. s config-values) n] value)
(= (. s config-count) (+ n 1)))
(fn read-le ((r (* pb)) (n int)) u64
(var v u64 0)
(for (var i int 0) (< i n) (++ i)
(if (! (.more r))
(do (= (. r err) true) (return 0)))
(c-bit-or= v (<< (cast (* (. r p)) u64) (* 8 i)))
(++ (. r p)))
(return v))
;;; .NET BinaryWriter strings carry the same LEB128 length as protobuf.
(fn read-dotnet-string ((r (* pb))) (* char)
(return (strndup-pb (.bytes r))))
;;; A TreeAttribute in its binary form: (type byte, key, value)* 0.
;;; Values are kept as the text the world config would show them as.
(fn read-tree-attribute ((s (* save)) (r pb)) void
(while (.more r)
(var type int (cast (read-le (& r) 1) int))
(if (== type 0)
(return))
(var key (* char) (read-dotnet-string (& r)))
(var value [char 64])
(switch type
(case 1 (snprintf value 64 "%d" (cast (read-le (& r) 4) i32)) (break))
(case 2 (snprintf value 64 "%lld" (cast (read-le (& r) 8) i64)) (break))
(case 3
(do
(var bits u64 (read-le (& r) 8))
(var d double)
(memcpy (& d) (& bits) 8)
(snprintf value 64 "%.17g" d))
(break))
(case 4
(do
(var bits u32 (cast (read-le (& r) 4) u32))
(var f float)
(memcpy (& f) (& bits) 4)
(snprintf value 64 "%.9g" (cast f double)))
(break))
(case 5
(add-config s key (read-dotnet-string (& r)))
(continue))
(case 9 (snprintf value 64 "%s" (if (read-le (& r) 1) "true" "false")) (break))
(default
(fprintf stderr "world config: attribute type %d of `%s' unsupported, stopping\n"
type key)
(free key)
(return)))
(add-config s key (strdup value))))
(pub fn save/config ((s (* const save)) (key (* const char))) (* const char)
(for (var i int 0) (< i (. s config-count)) (++ i)
(if (== (strcmp [(. s config-keys) i] key) 0)
(return [(. s config-values) i])))
(return NULL))
;;; Mod data entries -------------------------------------------------
;;; Dictionary<int, string> BlockIDs: entries {1: id, 2: code}.
(fn read-block-ids ((s (* save)) (r pb)) void
(var scan pb r)
(var max-id int -1)
(var wire int)
(while (> (.field (& scan) (& wire)) 0)
(var entry pb (.bytes (& scan)))
(while (> (.field (& entry) (& wire)) 0)
(if (== wire WIRE-VARINT)
(do
(var id int (cast (.varint (& entry)) int))
(if (> id max-id) (= max-id id)))
(.skip (& entry) wire))))
(= (. s block-count) (+ max-id 1))
(= (. s block-codes) (calloc (+ max-id 1) (sizeof [(. s block-codes) 0])))
(while (> (.field (& r) (& wire)) 0)
(var entry pb (.bytes (& r)))
(var id int -1)
(var code (* char) NULL)
(var f u32)
(while (> (= f (.field (& entry) (& wire))) 0)
(if (== f 1) (= id (cast (.varint (& entry)) int))
(== f 2) (= code (strndup-pb (.bytes (& entry))))
(.skip (& entry) wire)))
(if (>= id 0)
(= [(. s block-codes) id] code)
(free code))))
;;; Dictionary<string, StoryStructureLocation>: entries {1: key,
;;; 2: {1: code, 2: centre {1: x, 2: y, 3: z}, ...}}.
(fn read-stories ((s (* save)) (r pb)) void
(var wire int)
(while (&& (< (. s story-count) MAX-STORIES) (> (.field (& r) (& wire)) 0))
(var entry pb (.bytes (& r)))
(var loc (* story-location) (& [(. s stories) (. s story-count)]))
(var f u32)
(while (> (= f (.field (& entry) (& wire))) 0)
(if (!= f 2)
(do (.skip (& entry) wire) (continue)))
(var body pb (.bytes (& entry)))
(var g u32)
(while (> (= g (.field (& body) (& wire))) 0)
(if (== g 1)
(do
(var code pb (.bytes (& body)))
(snprintf (. loc code) 64 "%.*s" (cast (.len code) int) (. code p)))
(== g 2)
(do
(var centre pb (.bytes (& body)))
(var h u32)
(while (> (= h (.field (& centre) (& wire))) 0)
(if (== h 1) (= (. loc x) (.int32 (& centre)))
(== h 2) (= (. loc y) (.int32 (& centre)))
(== h 3) (= (. loc z) (.int32 (& centre)))
(.skip (& centre) wire))))
(.skip (& body) wire))))
(++ (. s story-count))))
;;; Game data --------------------------------------------------------
(fn read-gamedata ((s (* save)) (r pb)) void
(var wire int)
(var f u32)
(while (> (= f (.field (& r) (& wire))) 0)
(if (== f 1) (= (. s size-x) (.int32 (& r)))
(== f 2) (= (. s size-y) (.int32 (& r)))
(== f 3) (= (. s size-z) (.int32 (& r)))
(== f 7) (= (. s seed) (.int32 (& r)))
(== f 31) (read-tree-attribute s (.bytes (& r)))
(== f 11)
(do
(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 "BlockIDs") (read-block-ids s value)
(.equals key "storystructurelocations") (read-stories s value)))
(.skip (& r) wire))))
(fn query-blob ((s (* const save)) (sql (* const char)) (key i64)
(out (* * sqlite3-stmt))) pb
(var stmt (* sqlite3-stmt) NULL)
(sqlite3-prepare-v2 (. s db) sql -1 (& stmt) NULL)
(sqlite3-bind-int64 stmt 1 key)
(= (* out) stmt)
(if (!= (sqlite3-step stmt) SQLITE-ROW)
(return #(pb : NULL NULL true)))
(return (pb/of (sqlite3-column-blob stmt 0)
(cast (sqlite3-column-bytes stmt 0) size-t))))
(pub fn save/open ((path (* const char))) (* save)
(var s (* save) (calloc 1 (sizeof save)))
(if (!= (sqlite3-open-v2 path (& (. s db)) SQLITE-OPEN-READONLY NULL) SQLITE-OK)
(do
(fprintf stderr "%s: %s\n" path (sqlite3-errmsg (. s db)))
(sqlite3-close (. s db))
(free s)
(return NULL)))
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from gamedata limit ?1" 1 (& stmt)))
(if (. r err)
(do
(fprintf stderr "%s: no game data\n" path)
(sqlite3-finalize stmt)
(sqlite3-close (. s db))
(free s)
(return NULL)))
(read-gamedata s r)
(sqlite3-finalize stmt)
(return s))
(pub fn save/block-code ((s (* const save)) (id int)) (* const char)
(if (&& (>= id 0) (< id (. s block-count)) [(. s block-codes) id])
(return [(. s block-codes) id]))
(return "?"))
(pub fn save/close ((s (* save))) void
(for (var i int 0) (< i (. s config-count)) (++ i)
(free [(. s config-keys) i])
(free [(. s config-values) i]))
(free (. s config-keys))
(free (. s config-values))
(for (var i int 0) (< i (. s block-count)) (++ i)
(free [(. s block-codes) i]))
(free (. s block-codes))
(sqlite3-close (. s db))
(free s))
;;; Map regions ------------------------------------------------------
;;; IntDataMap2D: {1: packed data, 2: size, 3: pad-tl, 4: pad-br}.
(fn read-int-map ((r pb) (m (* int-map))) void
(var wire int)
(var f u32)
(= (* m) #(int-map : NULL 0 0 0))
(while (> (= f (.field (& r) (& wire))) 0)
(if (== f 1)
(do
(var packed pb (.bytes (& r)))
(var count pb packed)
(var n size-t 0)
(while (.more count)
(.varint (& count))
(++ n))
(= (. m data) (malloc (* (+ n 1) (sizeof i32))))
(for (var i size-t 0) (< i n) (++ i)
(= [(. m data) i] (.int32 (& packed)))))
(== f 2) (= (. m size) (.int32 (& r)))
(== f 3) (= (. m pad-tl) (.int32 (& r)))
(== f 4) (= (. m pad-br) (.int32 (& r)))
(.skip (& r) wire))))
;;; ServerMapRegion, the fields we use: 1 landform, 3 climate,
;;; 4 geologic province, 12 rock strata (one per stratum), 17 upheaval,
;;; 18 ocean.
(fn read-region ((r pb) (m (* region-maps))) void
(memset m 0 (sizeof region-maps))
(var wire int)
(var f u32)
(while (> (= f (.field (& r) (& wire))) 0)
(if (== f 1) (read-int-map (.bytes (& r)) (& (. m landform)))
(== f 3) (read-int-map (.bytes (& r)) (& (. m climate)))
(== f 4) (read-int-map (.bytes (& r)) (& (. m geoprov)))
(== f 17) (read-int-map (.bytes (& r)) (& (. m upheaval)))
(== f 18) (read-int-map (.bytes (& r)) (& (. m ocean)))
(&& (== f 12) (< (. m strata-count) MAX-STRATA))
(do
(read-int-map (.bytes (& r)) (& [(. m strata) (. m strata-count)]))
(++ (. m strata-count)))
(.skip (& r) wire))))
(pub fn region-maps/free ((m (* region-maps))) void
(free (. m landform data))
(free (. m climate data))
(free (. m geoprov data))
(free (. m upheaval data))
(free (. m ocean data))
(for (var i int 0) (< i (. m strata-count)) (++ i)
(free (. [(. m strata) i] data))))
(pub fn save/region ((s (* const save)) (rx i32) (rz i32) (out (* region-maps))) bool
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from mapregion where position = ?1"
(position rx rz) (& stmt)))
(var found bool (! (. r err)))
(if found
(read-region r out))
(sqlite3-finalize stmt)
(return found))
;;; Map chunks -------------------------------------------------------
;;; A repeated ushort field arrives one value per field, or packed.
(fn read-u16s ((r (* pb)) (wire int) (out (* u16)) (n (* int))) void
(if (== wire WIRE-BYTES)
(do
(var packed pb (.bytes r))
(while (&& (.more packed) (< (* n) CHUNK-AREA))
(= [out (* n)] (cast (.varint (& packed)) u16))
(++ (* n))))
(do
(var v u16 (cast (.varint r) u16))
(if (< (* n) CHUNK-AREA)
(do (= [out (* n)] v) (++ (* n)))))))
;;; Rivers stores riverDistance as a serialized ushort[]: {1: value}*.
(fn read-river-distance ((r pb) (m (* chunk-maps))) void
(var wire int)
(var n int 0)
(while (> (.field (& r) (& wire)) 0)
(read-u16s (& r) wire (. m river-distance) (& n)))
(= (. m has-river-distance) (== n CHUNK-AREA)))
;;; ServerMapChunk, the fields we use: 1 mod data, 3 rain height,
;;; 7 worldgen terrain height, 13 top rock id.
(fn read-chunk ((r pb) (m (* chunk-maps))) void
(memset m 0 (sizeof chunk-maps))
(var wire int)
(var f u32)
(var rain int 0)
(var terrain int 0)
(var rock int 0)
(while (> (= f (.field (& r) (& wire))) 0)
(if (== f 3) (read-u16s (& r) wire (. m rain-height) (& rain))
(== f 7) (read-u16s (& r) wire (. m terrain-height) (& terrain))
(&& (== f 13) (< rock CHUNK-AREA))
(do
(= [(. m top-rock) rock] (.int32 (& r)))
(++ rock))
(== f 1)
(do
(var entry pb (.bytes (& r)))
(var key pb #(pb : NULL NULL false))
(var g u32)
(while (> (= g (.field (& entry) (& wire))) 0)
(if (== g 1) (= key (.bytes (& entry)))
(&& (== g 2) (.equals key "riverDistance"))
(read-river-distance (.bytes (& entry)) m)
(.skip (& entry) wire))))
(.skip (& r) wire))))
(pub fn save/chunk ((s (* const save)) (cx i32) (cz i32) (out (* chunk-maps))) bool
(var stmt (* sqlite3-stmt) NULL)
(var r pb (query-blob s "select data from mapchunk where position = ?1"
(position cx cz) (& stmt)))
(var found bool (! (. r err)))
(if found
(read-chunk r out))
(sqlite3-finalize stmt)
(return found))
;;; The stored extent of a table, in its own units (regions or chunks):
;;; inclusive bounds and the row count.
(pub record extent ((x0 i32) (z0 i32) (x1 i32) (z1 i32) (count i64)))
(pub fn save/extent ((s (* const save)) (table (* const char))) extent
(var sql [char 160])
(snprintf sql (sizeof sql)
"select min(position & 134217727), min(position >> 27), max(position & 134217727), max(position >> 27), count(*) from %s"
table)
(var stmt (* sqlite3-stmt) NULL)
(var e extent #(extent : 0 0 -1 -1 0))
(sqlite3-prepare-v2 (. s db) sql -1 (& stmt) NULL)
(if (== (sqlite3-step stmt) SQLITE-ROW)
(= e #(extent : (sqlite3-column-int stmt 0) (sqlite3-column-int stmt 1)
(sqlite3-column-int stmt 2) (sqlite3-column-int stmt 3)
(sqlite3-column-int64 stmt 4))))
(sqlite3-finalize stmt)
(return e))

2
src/stb.c Normal file
View File

@@ -0,0 +1,2 @@
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

View File

@@ -1,43 +1,89 @@
;;; vsmv: the command-line side of the viewer. It checks the generator
;;; against a saved world and dumps what either side produced.
(include stdio.h string.h sqlite3.h)
(include stdio.h string.h)
(import cs)
(import json)
(import save)
(import dump)
(var save-tables [(* const char) 4] #("gamedata" "mapregion" "mapchunk" "chunk"))
(var worldgen-assets [(* const char) 6]
#("landforms" "geologicprovinces" "rockstrata" "storystructures"
"blocklayers" "deposits"))
(fn usage () int
(fputs "usage: vsmv info SAVE.vcdbs\n" stderr)
(fputs "usage: vsmv info SAVE.vcdbs\n vsmv seed TEXT...\n vsmv assets ASSETS-DIR\n vsmv dump SAVE.vcdbs OUT-DIR\n"
stderr)
(return 2))
(fn count-rows ((db (* sqlite3)) (table (* const char))) i64
(var sql [char 64])
(snprintf sql (sizeof sql) "select count(*) from %s" table)
(var stmt (* sqlite3-stmt) NULL)
(if (!= (sqlite3-prepare-v2 db sql -1 (& stmt) NULL) SQLITE-OK)
(return -1))
(var n i64 -1)
(if (== (sqlite3-step stmt) SQLITE-ROW)
(= n (sqlite3-column-int64 stmt 0)))
(sqlite3-finalize stmt)
(return n))
;;; vsmv info world.vcdbs
;;; gamedata 1
;;; mapregion 118
;;; ...
(fn info ((path (* const char))) int
(var db (* sqlite3) NULL)
(if (!= (sqlite3-open-v2 path (& db) SQLITE-OPEN-READONLY NULL) SQLITE-OK)
(do
(fprintf stderr "%s: %s\n" path (sqlite3-errmsg db))
(sqlite3-close db)
(return 1)))
(for (var i int 0) (< i 4) (++ i)
(printf "%-10s %8lld\n" [save-tables i] (count-rows db [save-tables i])))
(sqlite3-close db)
(var s (* save) (save/open path))
(if (! s)
(return 1))
(printf "seed %d\n" (. s seed))
(printf "size %d x %d x %d\n" (. s size-x) (. s size-y) (. s size-z))
(printf "block ids %d\n" (. s block-count))
(printf "world config, %d values:\n" (. s config-count))
(for (var i int 0) (< i (. s config-count)) (++ i)
(printf " %-28s %s\n" [(. s config-keys) i] [(. s config-values) i]))
(printf "story locations:\n")
(for (var i int 0) (< i (. s story-count)) (++ i)
(var l (* story-location) (& [(. s stories) i]))
(printf " %-24s %8d %4d %6d\n" (. l code) (. l x) (. l y) (. l z)))
(var regions extent (save/extent s "mapregion"))
(var chunks extent (save/extent s "mapchunk"))
(printf "map regions %lld, x %d..%d z %d..%d\n" (. regions count)
(. regions x0) (. regions x1) (. regions z0) (. regions z1))
(printf "map chunks %lld, x %d..%d z %d..%d\n" (. chunks count)
(. chunks x0) (. chunks x1) (. chunks z0) (. chunks z1))
(save/close s)
(return 0))
;;; vsmv assets assets -> each worldgen file's top-level arrays and
;;; the rock strata in generation order, which the result depends on.
(fn assets ((dir (* const char))) int
(var bad int 0)
(for (var i int 0) (< i 6) (++ i)
(var path [char 1024])
(snprintf path (sizeof path) "%s/survival/worldgen/%s.json" dir [worldgen-assets i])
(var j (* cJSON) (json-load path))
(if (! j)
(do (++ bad) (continue)))
(printf "%s:" [worldgen-assets i])
(for (var item (* cJSON) (. j child)) item (= item (. item next))
(if (cJSON-IsArray item)
(printf " %s[%d]" (. item string) (cJSON-GetArraySize item))))
(printf "\n")
(if (== (strcmp [worldgen-assets i] "rockstrata") 0)
(do
(var variants (* cJSON) (cJSON-GetObjectItemCaseSensitive j "variants"))
(for (var v (* cJSON) (. variants child)) v (= v (. v next))
(printf " %-20s %-12s %s\n"
(cJSON-GetStringValue (cJSON-GetObjectItemCaseSensitive v "blockcode"))
(cJSON-GetStringValue (cJSON-GetObjectItemCaseSensitive v "rockGroup"))
(cJSON-GetStringValue (cJSON-GetObjectItemCaseSensitive v "genDir"))))))
(cJSON-Delete j))
(return bad))
(pub fn main ((argc int) (argv [* char])) int
(if (&& (== argc 3) (== (strcmp [argv 1] "info") 0))
(if (< argc 2)
(return (usage)))
(var cmd (* const char) [argv 1])
(if (&& (== (strcmp cmd "info") 0) (== argc 3))
(return (info [argv 2])))
(if (&& (== (strcmp cmd "seed") 0) (>= argc 3))
(do
(for (var i int 2) (< i argc) (++ i)
(printf "%d\t%s\n" (world-seed [argv i]) [argv i]))
(return 0)))
(if (&& (== (strcmp cmd "assets") 0) (== argc 3))
(return (assets [argv 2])))
(if (&& (== (strcmp cmd "dump") 0) (== argc 4))
(do
(var s (* save) (save/open [argv 2]))
(if (! s)
(return 1))
(dump s [argv 3])
(save/close s)
(return 0)))
(return (usage)))