set up the build, the viewer window and the vsmv cli

The generator must reproduce .NET arithmetic bit for bit, so every unit
builds with -ffp-contract=off and -fwrapv. Nuklear goes through the
SDL3_Renderer backend, keeping the viewer off macOS's deprecated GL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 17:39:10 +03:00
commit d72ae437ae
10 changed files with 32800 additions and 0 deletions

13
.gitignore vendored Normal file
View File

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

40
Makefile Normal file
View File

@@ -0,0 +1,40 @@
# The generator has to reproduce .NET arithmetic bit for bit, so every
# unit is built without FMA contraction (clang on arm64 fuses a*b+c,
# .NET does not) and with wrapping signed overflow (C# is unchecked).
SEXC ?= $(HOME)/dev/sex/sexc
CFLAGS ?= -O2 -g
CFLAGS += -std=c11 -Wall -ffp-contract=off -fwrapv
CPPFLAGS += -Isrc -Ithird_party/nuklear -IcJSON $(shell pkg-config --cflags sdl3)
SDL_LIBS := $(shell pkg-config --libs sdl3)
B = build
all: $(B)/vsmv $(B)/vs-map-viewer
# sexc writes no dependency files, and an import pastes the imported
# module's public forms into the importer, so any Sex source may change
# any Sex object.
SEX_SRC := $(wildcard src/*.sex)
$(B)/%.o: src/%.sex $(SEX_SRC) | $(B)
$(SEXC) $< -c -o $@ -- $(CFLAGS) $(CPPFLAGS)
$(B)/nk.o: src/nk.c src/nk.h | $(B)
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
$(B)/cJSON.o: cJSON/cJSON.c cJSON/cJSON.h | $(B)
$(CC) $(CFLAGS) -c $< -o $@
$(B)/vsmv: $(B)/vsmv.o $(B)/cJSON.o
$(CC) $^ -o $@ -lsqlite3
$(B)/vs-map-viewer: $(B)/viewer.o $(B)/nk.o
$(CC) $^ -o $@ $(SDL_LIBS)
$(B):
mkdir -p $@
clean:
rm -rf $(B)
.PHONY: all clean

355
Plan.org Normal file
View File

@@ -0,0 +1,355 @@
#+TITLE: vs-map-viewer: plan
* Goal
A desktop app that takes a Vintage Story 1.22.7 seed and world settings,
reimplements the standard world generator plus the Rivers 5.0.3 mod, and
shows:
- a zoomable top-down map of the world;
- a rock overlay: each column colored by its rock at the surface, at a
chosen depth below the surface, or at an absolute Y. Clicking a rock in
the legend highlights only that rock, which is how you find a given
stratum.
Decisions so far:
- The generator is our own port, written in Sex (~/dev/sex). This app is a
field test for the language. No .NET and no game DLLs, at runtime or
in development.
- When something doesn't match the save, we stop and show the diffs.
Whether to bring in more tooling is decided case by case.
- The GUI is Nuklear on SDL3, using its SDL_Renderer backend (Metal on
macOS). Map tiles are SDL textures.
- Rivers is included, using its default config. A =rivers.json= can be
loaded to override it.
- Ground truth is the save in this directory,
=ktt9s village story-new.vcdbs=. It was made with Rivers 5.0.3 and the
default Rivers config.
- *Frugal by design.* We compute only what the viewer window shows. The
world is 2,048,000 × 25,600 blocks with height 320 (confirmed from the
save's =gamedata=), and nothing ever iterates over the whole of it.
* Upstream sources
Upstream is anegostudios/vsapi, vsessentialsmod and vssurvivalmod at
their =master= heads. Each head is the "Updated to Version 1.22.7" commit
from 2026-08-17. Since 1.22, the worldgen lives in *vsessentialsmod*.
Rivers is at github.com/glutzer/Rivers-Mod, HEAD 98f75e8, which is the
5.0.3 release. All of this code is proprietary or All Rights Reserved: we
may "read it and learn from it". We write our own port and never
redistribute their code verbatim.
| Area | Upstream |
|--------------------------+-----------------------------------------------------------------------|
| Seed string → int | =vsapi/Math/GameMath.cs= =DotNetStringHash= |
| RNG | =vsapi= =LCGRandom= |
| Noise | =vsapi= =SimplexNoise=, =NormalizedSimplexNoise=, =NewNormalizedSimplexFractalNoise=, =SimplexOctave= |
| 2D containers | =vsapi= =IntDataMap2D=, =NaturalShape= |
| Region maps | =vsessentialsmod/Systems/WorldGen/Standard/ChunkGen/0.GenMaps/=, =MapLayer*=, =NoiseBase=, =LerpedWeightedIndex2DMap= |
| Terrain height | =Rivers/src/WorldGenSystems/NewGenTerra.cs=. This is a copy of vanilla =.../1.GenTerra/GenTerra.cs= plus the river code. |
| River layout | =Rivers/src/Rivers/RiverRegion.cs=, =RiverNode.cs=, =RiverGenerator.cs= (=SampleRiver=), =Api/RiversApi.cs= (the river landform) |
| River noise | =Rivers/src/Noise/FastNoise.cs=, =Noise.cs= |
| Rock strata | =.../ChunkGen/2.GenRockStrata/GenRockStrata.cs= (=GenRockStrataNew=) |
| Strata for one column | =vssurvivalmod/Systems/Prospecting/ProPickWorkSpace.cs= =GetRockColumn= |
| Dry-climate height raise | =.../GenBlockLayers.cs:185=, patched by =Rivers/src/Patches/BlockLayersPatches.cs= |
| Forced story landforms | =vssurvivalmod= =GenStoryStructures=, plus =GenMaps.ForceLandformAt= / =ForceClimateAt= |
Assets come from =assets/survival/worldgen/=: =landforms.json=,
=geologicprovinces.json=, =rockstrata.json=, =storystructures.json=,
=blocklayers.json= and =deposits.json=. They are local and never
committed. They are *not strict JSON*: keys are unquoted, and they may
contain comments and trailing commas. Newtonsoft reads them leniently;
cJSON does not. So the =assets= module needs a small JSON5-ish normalising
pass before cJSON, or we patch cJSON to accept these files.
* How the computation is structured
Everything is a 2D function of the column. We never build 3D chunks.
| Level | Size (blocks) | What | Cost |
|-----------------+----------------+---------------------------------------------------------+-------------------------------|
| River plate | 32768 × 32768 | 128×128 zone ocean flags, distance to ocean, river tree | ~410k ocean-noise samples, once per plate |
| Map region | 512 × 512 | climate, ocean, upheaval, province, landform, strata thickness maps | cheap 2D noise |
| Chunk (32 × 32) | 32 × 32 | the set of river segments near the chunk (exactness depends on it) | a filter over the plate's segments |
| Column | 1 × 1 | river sample → valley blend → =surfaceY= → strata column | 10–50 µs, dominated by 3D noise |
The frugality rule: the view asks for tiles, and a tile asks for exactly
the columns it shows. Columns pull in the regions, chunk segment sets and
plates they need. Each of these is cached with an LRU. Nothing is ever
computed "just in case".
*The one unavoidable wide dependency is the river plate.*
- Rivers lays out the river network for a whole 32768-block plate at once.
To know whether a river passes through the window, you need that
plate's layout.
- It is coarse (256-block zones) and runs once per plate.
- Our port samples the ocean map 25 times per zone, about 410k samples
per plate, where the original does about 11M. That should come in well
under a second.
- The world is 62.5 × 0.78 plates, so a window touches 1–2 plates.
- The plate is computed lazily, in the background, and the map shows
terrain without rivers until it is ready. Plates are independent of
each other and deterministic.
* Facts that shape the port
** Vanilla
- *A rock column needs only 2D data.* It depends on the region maps, the
seed and =surfaceY=. =ProPickWorkSpace.GetRockColumn= does exactly this
in the game.
- *Strata see the height before the dry-climate raise.* Strata run at
order 0.1, and =GenBlockLayers= (0.4) can later raise the stored
=WorldGenTerrainHeightMap= in dry climates below sea level. For
validation we compare against the raised value. Strata use the
unraised one.
- *The seed hash is verified.* =DotNetStringHash("письки+жопки")= is
-90319180, which matches the seed stored in the save.
- *Story structures force landform and climate near spawn.* The save's
=gamedata= stores =storystructurelocations=, which gives us ground
truth for the placement code.
- *Rock strata noise uses its own seeds.* The distortion noises are
seeded from =SeaLevel+9876/9877=, not from the world seed.
- *Order matters* in two places:
- =rockstrata.json= list order changes the result;
- =NoiseClimateRealistic= draws its ZOffset from an unpositioned LCG.
** Rivers
- *Layout RNG.* It is =LCGRandom(0)=, positioned at the plate
coordinates. The world only enters through the ocean map: the blurred
=MapLayerOceans= at seed+1873, with =landcover= and =oceanscale= applied.
- *The ocean map ignores forced land.* Rivers samples it with
=requireLandAt= (forced land at spawn and story locations) emptied. Our
ocean layer needs a "no forced land" mode.
- *Zone ocean test.* A zone is ocean if, at its centre chunk, the blurred
ocean value × =oceanicityFactor= > =oceanThreshold= (30). The blur is a
separable 5-tap integer box blur, truncating after each pass. The
=oceanicityFactor= is =MapSizeY/256*0.33333f=, with integer division.
- *Distance to ocean.* Upstream computes it with a BFS that is equivalent
to the exact Euclidean distance between zone centres. We use a distance
transform: same result, without the O(n²) cost.
- *RNG call order is the contract.* We have to replicate it exactly:
- zone scan, x outer and z inner;
- =FindHighestZone=, a stable sort;
- the FIFO generation queue;
- per-river =NextInt=, =NextDouble= and =NextFloat= calls in upstream
order. This includes =AddLake= rolling =NextInt= before its bounds
check.
- *River sample per column.* It is computed in plate-local coordinates
and distorted by FastNoise (seeds 0 and 2). It yields =riverDistance=
and =bankFactor=.
- The candidate segments are the chunk's segment set, not the plate's.
The distortion can reach segments outside a segment's envelope, so
using the plate's set would give different results.
- *Valley blend.* Applies when =riverDistance < maxValleyWidth= (150). A
river landform is appended as the last landform index. Landform
weights, octave amplitudes, thresholds and upheaval are lerped toward
it, using valley noise (seed 0, freq 0.0008).
- *Carving.* Applies when =riverDistance <= 0=. It removes blocks between
=baseline - bank= and =baseline + bank*topFactor=. =surfaceY= is the
highest solid block that remains, which can be a tunnel ceiling.
- *What Rivers leaves alone.* Region maps and strata are not patched;
strata change only through =surfaceY=.
- Gravel beaches are cosmetic and only matter top-down: gravel on top,
with the strata underneath. That's a later, optional layer.
- We skip boulders.
- *FastNoise subset.* We need OpenSimplex2 2D with FBm only, in its
double-coordinate build. Perlin, Value, Cellular, Ridged and the other
variants are dead code here.
- *Config is not in the save.* It is read from =ModConfig/rivers.json=,
which here means the defaults (=RiverConfig.cs=).
- *Not reproducible in the original either:* an on-disk zone cache that
ignores config changes, and live =/riversettings= edits. Neither
applies to this world.
- *Ground truth for rivers is in the save.* =mapchunk= moddata
="riverDistance"= is a =ushort[1024]=, stored wherever some column has a
distance ≤ 300. We can validate the layout and the per-column sample
before touching terrain.
* Determinism rules for the port
C# semantics that a naive C port gets wrong. Encode them once, in a
=cs-compat= module, and use only that module:
- *Integer overflow wraps* in C# (unchecked). This covers the LCG
(=x*6364136223846793005+1442695040888963407= on =long=) and the int
hashes. In C, do the arithmetic in unsigned types, and also build with
=-fwrapv=.
- *No FMA contraction.* Clang on arm64 fuses =a*b+c= by default; .NET
does not. Build with =-ffp-contract=off= and never with =-ffast-math=.
- *Keep float and double exactly as upstream has them.* Both the vanilla
noise layers and Rivers (=riverSize=, =GetProjection=, =MathF.Pow=)
mix the two.
- *Truncating =/= and =%= on negatives* match between C99 and C#. Use
explicit floor helpers where upstream calls =Math.Floor= or =FastFloor=.
- *Casting an out-of-range float to =(int)=* is undefined behaviour in C.
Clamp it, or mirror the .NET x64 result (=INT_MIN=).
- *Statics.* Upstream keeps mutable static state (=NoiseLandforms=,
=NoiseGeoProvince=). We keep it in an explicit worldgen context struct
instead, so changing settings regenerates cleanly.
=Math.Pow=, =Sin=, =Cos= and =Atan2= may differ from macOS libm by an ulp.
Accept that until validation says otherwise. In Rivers it could
theoretically flip a node acceptance test.
* Architecture
#+begin_example
settings (serverconfig.json / .vcdbs gamedata / UI) ──┐
assets/survival/worldgen/*.json (lenient JSON → cJSON) ┤
rivers.json (optional, else defaults) ─────────────────┤
▼
worldgen context (seed, sizes, parsed assets, river config)
│
plate cache (LRU) ── region cache (LRU) ── chunk segment-set cache (LRU)
│
column query: river sample → valley blend → surfaceY → strata → rock at surface/depth/Y
│
tile workers (pthreads): tiles in the view only, centre first, cancelled when the view moves
│
Nuklear/SDL_Renderer UI: map, layers, settings, legend, probe
#+end_example
Modules. Each is a Sex module; the =vsmv= CLI and the GUI share them.
- =cs-compat=: wrapping int math, LCG, =DotNetStringHash=, floor and
lerp helpers, and the =GameMath= subset.
- =noise=: vanilla simplex family and =NaturalShape=.
- =fastnoise=: OpenSimplex2 2D with FBm.
- =maplayers=: =IntDataMap2D=, =NoiseBase=, =MapLayer*= (including the
ocean layer's no-forced-land mode), =LerpedWeightedIndex2DMap=,
=GenMaps= region generation and story-structure forcing.
- =rivers=: plate generation (zones, distance to ocean, river tree),
chunk segment sets, =SampleRiver=, and the river landform.
- =terra=: per-column =surfaceY= with the valley blend and carving, plus
the dry-climate raise for validation.
- =strata=: =genBlockColumn=, plus queries for "rock at depth d" and
"rock at Y".
- =assets=: lenient JSON loading and asset structs, plus a rock color
palette. Hardcode the palette at first; take block texture averages
later.
- =save=: reads the .vcdbs through SQLite3, with a minimal protobuf wire
reader. =gamedata= turned out to be plain protobuf.
- =tiles=: tile pyramid, LRU caches, worker pool, cancellation.
- =ui=: Nuklear + SDL3 SDL_Renderer. Tiles are SDL textures under the
Nuklear panels.
Coordinates are shown like the in-game HUD, relative to the map centre
=((MapSizeX+32)/2, (MapSizeZ+32)/2)=, with absolute coordinates available
too. The viewer opens at spawn.
* Phases
Each phase ends with a check against the save. A mismatch means stop,
produce diff images and numbers, and decide together.
** 0. Skeleton
- Repo layout, Makefile (=sexc ... -- -ffp-contract=off -fwrapv=), and a
=.gitignore= for =*.vcdbs*=, =*.zip= and =assets/=.
- Vendor =nuklear.h=. Take SDL3 from brew and sqlite3 from the system;
cJSON is already here.
- Create =Sex-field-notes.org=: a running log of language bugs and
friction found while building this.
** 1. Save reader + seed + assets
- =save=: decode =gamedata=:
- seed;
- MapSizeX/Y/Z;
- world config;
- block id → code table (=BlockIDs=);
- =storystructurelocations=.
- Decode =mapregion= blobs: =IntDataMap2D= fields, including
=RockStrata[]=.
- Decode =mapchunk= blobs: =WorldGenTerrainHeightMap=, =TopRockIdMap= if
present, and the ="riverDistance"= moddata.
- Take the layouts from vsapi's =[ProtoMember]= attributes, and check
whether the blobs are compressed.
- =cs-compat=: =DotNetStringHash= reproduces -90319180.
- =assets=: all six worldgen JSONs load.
- CLI: =vsmv dump --region X Z= and =vsmv dump --chunk X Z= write PNGs
of the stored data. This is our ground-truth viewer.
** 2. Region maps
- Port =noise= and =maplayers=, then =GenMaps=, in this order:
1. geologic province
2. landform
3. ocean
4. upheaval
5. climate
6. strata thickness
- Then the story-structure placement and forcing. Check the placement
against =storystructurelocations=.
- =vsmv verify-regions= diffs all 118 stored regions and reports the
percentage of exact pixel matches per map type. The target is 100%.
** 3. Minimal viewer
- Nuklear panels, a pannable and zoomable tile map, and a
layer switcher for the region maps.
- Settings panel:
- seed, world size, worldHeight;
- landcover, oceanscale, landformScale, upheavelCommonness,
geologicActivity;
- worldClimate, polarEquatorDistance, globalTemperature/Precipitation,
startingClimate.
- River config section, with load from =rivers.json=.
- Load settings from =serverconfig.json= or a =.vcdbs=.
- Hover readout: coordinates, province, landform, climate.
- Tiles exist only for the view.
** 4. Rivers layout
- Port =fastnoise= (OpenSimplex2 2D FBm) and =rivers=:
- zone ocean flags;
- distance to ocean;
- river tree, with the exact RNG call order;
- chunk segment sets;
- =SampleRiver=.
- =vsmv verify-rivers= compares per-column =riverDistance= against the
saved moddata in every stored map chunk.
- Viewer: river layer (segments plus the =riverDistance= field), computed
per plate in the background.
** 5. Terrain height
- Port =NewGenTerra='s per-column path:
- landform weights (lerped, radius 3) with the river landform;
- valley blend;
- warp distortion (seed+9876/+9878);
- oceanicity and upheaval distY;
- =NoiseSign= with the bounds early-out;
- carving.
- Port the dry-climate raise from =GenBlockLayers=, with the Rivers patch
factor applied, so we can compare against stored heights. The Rivers
transpiler is IL pattern matching, so whether it applies in 1.22.7
will show up in the diff.
- =vsmv verify-height= compares against =WorldGenTerrainHeightMap= for
all 11,414 stored map chunks. It reports the match percentage and
writes a diff PNG.
- Viewer: hillshaded terrain with water.
** 6. Rock strata + overlay
- Port =GenRockStrataNew.genBlockColumn=:
- province weights (lerped, radius 2) → per-group thickness budget;
- distortion noises;
- BottomUp/TopDown fill and the sedimentary thinning.
- Queries: rock at the surface, at depth /d/, at absolute Y, and the full
column.
- Validation: surface rock against =TopRockIdMap= (if stored). Decode
=chunk= blobs for full columns only if that isn't enough.
- Viewer:
- rock overlay with a mode switch (surface / depth / Y) and a slider;
- legend with per-rock highlight;
- click probe that shows the strata stack (rock, Y range, thickness).
** 7. Performance + polish
- Level of detail:
- zoomed out: one column per N blocks;
- zoomed in: refined down to one per block.
- Rough budget: a 1920×1080 view at 1 block/px is about 2M columns. That
is about 60 s on one core, or under 10 s on all cores, rendered
progressively.
- Optional disk cache of tiles and plates, keyed by a hash of the
settings.
- Go-to-coordinates, PNG export of the current view.
- Later: gravel-beach layer; ore deposits (=GenDeposits.GeneratePartial=
is already on the =ProPickWorkSpace= path).
* Risks
- *Bit-exactness* of the noise and the Rivers trigonometry. The
mitigations are the cs-compat rules and validating each phase before
the next.
- *Undocumented blob layouts or compression* in the vcdbs.
- *Mismatch between the Rivers source and the 5.0.3 build.* The source
HEAD and the DLL share a date, but we haven't verified the build. If
the river diff says so, we can compare symbols against
=rivers_5.0.3.zip=.
- *Sex gaps*: threads, function pointers, unions, varargs interop. Log
them in the field notes, and use small C shims when they block.
- *Version drift.* Pin to VS 1.22.7 and Rivers 5.0.3.

42
Sex-field-notes.org Normal file
View File

@@ -0,0 +1,42 @@
#+TITLE: Sex field notes
Language bugs and friction met while building vs-map-viewer, against
sexc at ~/dev/sex. Newest first.
* A malformed =for= crashes the compiler
sexc dfafe8b. Writing the C-style grouped header
#+begin_src scheme
(for ((var i int 0) (< i 4) (++ i))
...)
#+end_src
instead of =(for (var i int 0) (< i 4) (++ i) ...)= dies inside the
writer with no source location:
#+begin_example
Error: (caddr) bad argument type: ()
fmt-c-writer.scm:112: scheme#symbol->string
#+end_example
Expected: a diagnostic naming the file, the line and the expected shape
of =for=.
* Spurious "cannot type this" on a header pointer
sexc dfafe8b. In =src/viewer.sex=:
#+begin_src scheme
(var font (* struct nk-font) (nk-font-atlas-add-default ...))
(/= (. font handle height) scale)
#+end_src
This warns =cannot type this; `.' reads it as a value font=, yet the
emitted C is the correct =font->handle.height /= scale;=. The variable's
type is written out, so the warning is wrong on both counts: the type
is known, and the access isn't read as a value. The nearby
=(& (. font handle))= gives no warning.
* No dependency output
sexc has nothing like =cc -MD=. An =import= pastes the imported
module's public forms into the importer, so the Makefile has to make
every Sex object depend on every =.sex= source.

3
src/nk.c Normal file
View File

@@ -0,0 +1,3 @@
#define NK_IMPLEMENTATION
#define NK_SDL3_RENDERER_IMPLEMENTATION
#include "nk.h"

23
src/nk.h Normal file
View File

@@ -0,0 +1,23 @@
/* Nuklear with the SDL3_Renderer backend, configured once.
*
* Nuklear's struct layouts depend on these defines, so every unit that
* touches a nk_context has to see the same set: include this header,
* never nuklear.h directly. nk.c holds the implementation. */
#ifndef VSMV_NK_H
#define VSMV_NK_H
#include <SDL3/SDL.h>
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_STANDARD_BOOL
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_INCLUDE_COMMAND_USERDATA
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#include "nuklear.h"
#include "nuklear_sdl3_renderer.h"
#endif

82
src/viewer.sex Normal file
View File

@@ -0,0 +1,82 @@
;;; The map viewer window: SDL3 for the window, events and rendering,
;;; Nuklear for the panels drawn over the map.
(include "nk.h")
(define WINDOW-WIDTH 1280)
(define WINDOW-HEIGHT 800)
(define FONT-SIZE 13.0)
(fn fail ((what (* const char))) int
(SDL-Log "%s: %s" what (SDL-GetError))
(return 1))
;;; Bakes Nuklear's default font at the display scale, then shrinks the
;;; reported height back, so text is crisp on a Retina display and still
;;; laid out in window units.
(fn setup-font ((ctx (* struct nk-context)) (scale float)) void
(var config (struct nk-font-config) (nk-font-config 0))
(var atlas (* struct nk-font-atlas) (nk-sdl-font-stash-begin ctx))
(var font (* struct nk-font)
(nk-font-atlas-add-default atlas (* FONT-SIZE scale) (& config)))
(nk-sdl-font-stash-end ctx)
(/= (. font handle height) scale)
(nk-style-set-font ctx (& (. font handle))))
(fn draw-ui ((ctx (* struct nk-context)) (frame-ms double)) void
(if (nk-begin ctx "vs-map-viewer" (nk-rect 10 10 260 120)
(| NK-WINDOW-BORDER NK-WINDOW-MOVABLE NK-WINDOW-TITLE
NK-WINDOW-MINIMIZABLE))
(do
(nk-layout-row-dynamic ctx 20 1)
(nk-label ctx "Vintage Story 1.22.7 + Rivers 5.0.3" NK-TEXT-LEFT)
(nk-labelf ctx NK-TEXT-LEFT "frame %.1f ms" frame-ms)))
(nk-end ctx))
(pub fn main ((argc int) (argv [* char])) int
(if (! (SDL-Init SDL-INIT-VIDEO))
(return (fail "SDL_Init")))
(var window (* SDL-Window) NULL)
(var renderer (* SDL-Renderer) NULL)
(if (! (SDL-CreateWindowAndRenderer "vs-map-viewer" WINDOW-WIDTH WINDOW-HEIGHT
(| SDL-WINDOW-RESIZABLE
SDL-WINDOW-HIGH-PIXEL-DENSITY)
(& window) (& renderer)))
(return (fail "SDL_CreateWindowAndRenderer")))
(SDL-SetRenderVSync renderer 1)
(var scale float (SDL-GetWindowDisplayScale window))
(SDL-SetRenderScale renderer scale scale)
(var ctx (* struct nk-context) (nk-sdl-init window renderer (nk-sdl-allocator)))
(setup-font ctx scale)
(var running bool true)
(var last-ns u64 (SDL-GetTicksNS))
(while running
(var now-ns u64 (SDL-GetTicksNS))
(var frame-ms double (/ (cast (- now-ns last-ns) double) 1e6))
(= last-ns now-ns)
(var event SDL-Event)
(nk-input-begin ctx)
(while (SDL-PollEvent (& event))
(if (== (. event type) SDL-EVENT-QUIT)
(= running false))
(SDL-ConvertEventToRenderCoordinates renderer (& event))
(nk-sdl-handle-event ctx (& event)))
(nk-sdl-update-TextInput ctx)
(nk-input-end ctx)
(draw-ui ctx frame-ms)
(SDL-SetRenderDrawColor renderer 24 32 40 255)
(SDL-RenderClear renderer)
(nk-sdl-render ctx NK-ANTI-ALIASING-ON)
(SDL-RenderPresent renderer))
(nk-sdl-shutdown ctx)
(SDL-DestroyRenderer renderer)
(SDL-DestroyWindow window)
(SDL-Quit)
(return 0))

43
src/vsmv.sex Normal file
View File

@@ -0,0 +1,43 @@
;;; 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)
(var save-tables [(* const char) 4] #("gamedata" "mapregion" "mapchunk" "chunk"))
(fn usage () int
(fputs "usage: vsmv info SAVE.vcdbs\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)
(return 0))
(pub fn main ((argc int) (argv [* char])) int
(if (&& (== argc 3) (== (strcmp [argv 1] "info") 0))
(return (info [argv 2])))
(return (usage)))

31468
third_party/nuklear/nuklear.h vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,731 @@
/* nuklear - public domain */
/*
* ==============================================================
*
* API
*
* ===============================================================
*/
#ifndef NK_SDL3_RENDERER_H_
#define NK_SDL3_RENDERER_H_
#if SDL_MAJOR_VERSION < 3
#error "nk_sdl3_renderer requires at least SDL 3.0.0"
#endif
#ifndef NK_INCLUDE_COMMAND_USERDATA
#error "nk_sdl3_renderer requires the NK_INCLUDE_COMMAND_USERDATA define"
#endif
#ifndef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#error "nk_sdl3_renderer requires the NK_INCLUDE_VERTEX_BUFFER_OUTPUT define"
#endif
/* We have to redefine it because demos do not include any headers
* This is the same default value as the one from "src/nuklear_internal.h" */
#ifndef NK_BUFFER_DEFAULT_INITIAL_SIZE
#define NK_BUFFER_DEFAULT_INITIAL_SIZE (4*1024)
#endif
#ifdef __cplusplus
extern "C"{
#endif
NK_API struct nk_context* nk_sdl_init(SDL_Window *win, SDL_Renderer *renderer, struct nk_allocator allocator);
#ifdef NK_INCLUDE_FONT_BAKING
NK_API struct nk_font_atlas* nk_sdl_font_stash_begin(struct nk_context* ctx);
NK_API void nk_sdl_font_stash_end(struct nk_context* ctx);
#endif
NK_API int nk_sdl_handle_event(struct nk_context* ctx, SDL_Event *evt);
NK_API void nk_sdl_render(struct nk_context* ctx, enum nk_anti_aliasing);
NK_API void nk_sdl_update_TextInput(struct nk_context* ctx);
NK_API void nk_sdl_shutdown(struct nk_context* ctx);
NK_API nk_handle nk_sdl_get_userdata(struct nk_context* ctx);
NK_API void nk_sdl_set_userdata(struct nk_context* ctx, nk_handle userdata);
NK_API void nk_sdl_style_set_debug_font(struct nk_context* ctx);
NK_API struct nk_allocator nk_sdl_allocator(void);
#ifdef __cplusplus
}
#endif
#endif /* NK_SDL3_RENDERER_H_ */
/*
* ==============================================================
*
* IMPLEMENTATION
*
* ===============================================================
*/
#ifdef NK_SDL3_RENDERER_IMPLEMENTATION
#ifndef NK_SDL3_RENDERER_IMPLEMENTATION_ONCE
#define NK_SDL3_RENDERER_IMPLEMENTATION_ONCE
struct nk_sdl_device {
struct nk_buffer cmds;
struct nk_draw_null_texture tex_null;
SDL_Texture *font_tex;
};
struct nk_sdl_vertex {
float position[2];
float uv[2];
float col[4];
};
struct nk_sdl {
SDL_Window *win;
SDL_Renderer *renderer;
struct nk_user_font* debug_font;
struct nk_sdl_device ogl;
struct nk_context ctx;
#ifdef NK_INCLUDE_FONT_BAKING
struct nk_font_atlas atlas;
#endif
struct nk_allocator allocator;
nk_handle userdata;
Uint64 last_render;
bool insert_toggle;
bool edit_was_active;
};
NK_API nk_handle
nk_sdl_get_userdata(struct nk_context* ctx) {
struct nk_sdl* sdl;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
return sdl->userdata;
}
NK_API void
nk_sdl_set_userdata(struct nk_context* ctx, nk_handle userdata) {
struct nk_sdl* sdl;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
sdl->userdata = userdata;
}
NK_INTERN void *
nk_sdl_alloc(nk_handle user, void *old, nk_size size)
{
NK_UNUSED(user);
/* FIXME: nk_sdl_alloc should use SDL_realloc here, not SDL_malloc
* but this could cause a double-free due to bug within Nuklear, see:
* https://github.com/Immediate-Mode-UI/Nuklear/issues/768
* */
#if 0
return SDL_realloc(old, size);
#else
NK_UNUSED(old);
return SDL_malloc(size);
#endif
}
NK_INTERN void
nk_sdl_free(nk_handle user, void *old)
{
NK_UNUSED(user);
SDL_free(old);
}
NK_API struct nk_allocator
nk_sdl_allocator()
{
struct nk_allocator allocator;
allocator.userdata.ptr = 0;
allocator.alloc = nk_sdl_alloc;
allocator.free = nk_sdl_free;
return allocator;
}
NK_INTERN void
nk_sdl_device_upload_atlas(struct nk_context* ctx, const void *image, int width, int height)
{
struct nk_sdl* sdl;
NK_ASSERT(ctx);
NK_ASSERT(image);
NK_ASSERT(width > 0);
NK_ASSERT(height > 0);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
/* Clean up if the texture already exists. */
if (sdl->ogl.font_tex != NULL) {
SDL_DestroyTexture(sdl->ogl.font_tex);
sdl->ogl.font_tex = NULL;
}
sdl->ogl.font_tex = SDL_CreateTexture(sdl->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, width, height);
NK_ASSERT(sdl->ogl.font_tex);
SDL_UpdateTexture(sdl->ogl.font_tex, NULL, image, 4 * width);
SDL_SetTextureBlendMode(sdl->ogl.font_tex, SDL_BLENDMODE_BLEND);
}
NK_API void
nk_sdl_update_TextInput(struct nk_context* ctx)
{
struct nk_sdl* sdl;
bool active;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
/* Determine if Nuklear is using any top-level "edit" widget.
* Popups take higher priority because they block any incomming input.
* This will not work, if the widget is not updating context state properly. */
if (!ctx->active)
active = false;
else if (ctx->active->popup.win)
active = ctx->active->popup.win->edit.active;
else
active = ctx->active->edit.active;
/* decide, if TextInputActive should be unchanged/stoped/started
* and change its state accordingly for owned SDL Window */
if (active != sdl->edit_was_active)
{
const bool window_edit_active = SDL_TextInputActive(sdl->win);
/* If you ever hit this check, it means that the demo and your app
* (or something else) are all trying to manage TextInputActive state.
* This can cause subtle bugs where the state won't be what you expect.
* You can safely remove this assert and the demo will keep working,
* but make sure it does not cause any issues for you */
NK_ASSERT(window_edit_active == sdl->edit_was_active && "something else changed TextInputActive state for this Window");
if (!window_edit_active && !sdl->edit_was_active && active)
SDL_StartTextInput(sdl->win);
else if (window_edit_active && sdl->edit_was_active && !active)
SDL_StopTextInput(sdl->win);
sdl->edit_was_active = active;
}
/* FIXME:
* for full SDL3 integration, you also need to find current edit widget
* bounds and the text cursor offset, and pass this data into SDL_SetTextInputArea.
* This is currently not possible to do safely as Nuklear does not support it.
* https://wiki.libsdl.org/SDL3/SDL_SetTextInputArea
* https://github.com/Immediate-Mode-UI/Nuklear/pull/857
*/
}
NK_API void
nk_sdl_render(struct nk_context* ctx, enum nk_anti_aliasing AA)
{
/* setup global state */
struct nk_sdl* sdl;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
{ /* setup internal delta time that Nuklear needs for animations */
const Uint64 now = SDL_GetTicksNS();
ctx->delta_time_seconds = (float)(now - sdl->last_render) / (float)SDL_NS_PER_SECOND;
sdl->last_render = now;
}
{
SDL_Rect saved_clip;
SDL_BlendMode saved_blend;
bool clipping_enabled;
int vs = sizeof(struct nk_sdl_vertex);
size_t vp = NK_OFFSETOF(struct nk_sdl_vertex, position);
size_t vt = NK_OFFSETOF(struct nk_sdl_vertex, uv);
size_t vc = NK_OFFSETOF(struct nk_sdl_vertex, col);
/* convert from command queue into draw list and draw to screen */
const struct nk_draw_command *cmd;
const nk_draw_index *offset = NULL;
struct nk_buffer vbuf, ebuf;
/* fill converting configuration */
struct nk_convert_config config;
static const struct nk_draw_vertex_layout_element vertex_layout[] = {
{NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_sdl_vertex, position)},
{NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct nk_sdl_vertex, uv)},
{NK_VERTEX_COLOR, NK_FORMAT_R32G32B32A32_FLOAT, NK_OFFSETOF(struct nk_sdl_vertex, col)},
{NK_VERTEX_LAYOUT_END}
};
NK_MEMSET(&config, 0, sizeof(config));
config.vertex_layout = vertex_layout;
config.vertex_size = sizeof(struct nk_sdl_vertex);
config.vertex_alignment = NK_ALIGNOF(struct nk_sdl_vertex);
config.tex_null = sdl->ogl.tex_null;
config.circle_segment_count = 22;
config.curve_segment_count = 22;
config.arc_segment_count = 22;
config.global_alpha = 1.0f;
config.shape_AA = AA;
config.line_AA = AA;
/* convert shapes into vertices */
nk_buffer_init(&vbuf, &sdl->allocator, NK_BUFFER_DEFAULT_INITIAL_SIZE);
nk_buffer_init(&ebuf, &sdl->allocator, NK_BUFFER_DEFAULT_INITIAL_SIZE);
nk_convert(&sdl->ctx, &sdl->ogl.cmds, &vbuf, &ebuf, &config);
/* iterate over and execute each draw command */
offset = (const nk_draw_index*)nk_buffer_memory_const(&ebuf);
clipping_enabled = SDL_RenderClipEnabled(sdl->renderer);
SDL_GetRenderClipRect(sdl->renderer, &saved_clip);
/* Ensure alpha blending is enabled for geometry rendering. */
saved_blend = SDL_BLENDMODE_INVALID;
SDL_GetRenderDrawBlendMode(sdl->renderer, &saved_blend);
SDL_SetRenderDrawBlendMode(sdl->renderer, SDL_BLENDMODE_BLEND);
nk_draw_foreach(cmd, &sdl->ctx, &sdl->ogl.cmds)
{
if (!cmd->elem_count) continue;
{
SDL_Rect r;
r.x = cmd->clip_rect.x;
r.y = cmd->clip_rect.y;
r.w = cmd->clip_rect.w;
r.h = cmd->clip_rect.h;
SDL_SetRenderClipRect(sdl->renderer, &r);
}
{
const void *vertices = nk_buffer_memory_const(&vbuf);
SDL_RenderGeometryRaw(
sdl->renderer,
(SDL_Texture *)cmd->texture.ptr,
(const float*)((const nk_byte*)vertices + vp), vs,
(const SDL_FColor*)((const nk_byte*)vertices + vc), vs,
(const float*)((const nk_byte*)vertices + vt), vs,
(vbuf.needed / vs),
(void *) offset, cmd->elem_count, 2);
offset += cmd->elem_count;
}
}
/* Restore the original blend mode. */
if (saved_blend != SDL_BLENDMODE_INVALID) {
SDL_SetRenderDrawBlendMode(sdl->renderer, saved_blend);
}
SDL_SetRenderClipRect(sdl->renderer, &saved_clip);
if (!clipping_enabled) {
SDL_SetRenderClipRect(sdl->renderer, NULL);
}
nk_clear(&sdl->ctx);
nk_buffer_clear(&sdl->ogl.cmds);
nk_buffer_free(&vbuf);
nk_buffer_free(&ebuf);
}
}
NK_INTERN void
nk_sdl_clipboard_paste(nk_handle usr, struct nk_text_edit *edit)
{
char *text;
int len;
NK_UNUSED(usr);
/* this function returns empty string on failure, not NULL */
text = SDL_GetClipboardText();
NK_ASSERT(text);
if (text[0] != '\0') {
/* FIXME: there is a bug in Nuklear that affects UTF8 clipboard handling
* "len" should be a buffer length, but due to bug it must be a glyph count
* see: https://github.com/Immediate-Mode-UI/Nuklear/pull/841 */
#if 0
len = nk_strlen(text);
#else
len = SDL_utf8strlen(text);
#endif
nk_textedit_paste(edit, text, len);
}
SDL_free(text);
}
NK_INTERN void
nk_sdl_clipboard_copy(nk_handle usr, const char *text, int len)
{
const char *ptext;
char *str;
size_t buflen;
int i;
struct nk_sdl* sdl = (struct nk_sdl*)usr.ptr;
NK_ASSERT(sdl);
if (len <= 0 || text == NULL) return;
/* FIXME: there is a bug in Nuklear that affects UTF8 clipboard handling
* "len" is expected to be a buffer length, but due to bug it actually is a glyph count
* see: https://github.com/Immediate-Mode-UI/Nuklear/pull/841 */
#if 0
buflen = len + 1;
NK_UNUSED(ptext);
#else
ptext = text;
for (i = len; i > 0; i--)
(void)SDL_StepUTF8(&ptext, NULL);
buflen = (size_t)(ptext - text) + 1;
#endif
str = (char*)sdl->allocator.alloc(sdl->allocator.userdata, 0, buflen);
if (!str) return;
SDL_strlcpy(str, text, buflen);
SDL_SetClipboardText(str);
sdl->allocator.free(sdl->allocator.userdata, str);
}
NK_API struct nk_context*
nk_sdl_init(SDL_Window *win, SDL_Renderer *renderer, struct nk_allocator allocator)
{
struct nk_sdl* sdl;
NK_ASSERT(win);
NK_ASSERT(renderer);
NK_ASSERT(allocator.alloc);
NK_ASSERT(allocator.free);
sdl = (struct nk_sdl*)allocator.alloc(allocator.userdata, 0, sizeof(*sdl));
NK_ASSERT(sdl);
SDL_zerop(sdl);
sdl->allocator.userdata = allocator.userdata;
sdl->allocator.alloc = allocator.alloc;
sdl->allocator.free = allocator.free;
sdl->win = win;
sdl->renderer = renderer;
nk_init(&sdl->ctx, &sdl->allocator, 0);
sdl->ctx.userdata = nk_handle_ptr((void*)sdl);
sdl->ctx.clip.copy = nk_sdl_clipboard_copy;
sdl->ctx.clip.paste = nk_sdl_clipboard_paste;
sdl->ctx.clip.userdata = nk_handle_ptr((void*)sdl);
nk_buffer_init(&sdl->ogl.cmds, &sdl->allocator, NK_BUFFER_DEFAULT_INITIAL_SIZE);
sdl->edit_was_active = false;
sdl->insert_toggle = false;
sdl->last_render = SDL_GetTicksNS();
return &sdl->ctx;
}
#ifdef NK_INCLUDE_FONT_BAKING
NK_API struct nk_font_atlas*
nk_sdl_font_stash_begin(struct nk_context* ctx)
{
struct nk_sdl* sdl;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
nk_font_atlas_init(&sdl->atlas, &sdl->allocator);
nk_font_atlas_begin(&sdl->atlas);
return &sdl->atlas;
}
#endif
#ifdef NK_INCLUDE_FONT_BAKING
NK_API void
nk_sdl_font_stash_end(struct nk_context* ctx)
{
struct nk_sdl* sdl;
const void *image; int w, h;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
image = nk_font_atlas_bake(&sdl->atlas, &w, &h, NK_FONT_ATLAS_RGBA32);
NK_ASSERT(image);
nk_sdl_device_upload_atlas(&sdl->ctx, image, w, h);
nk_font_atlas_end(&sdl->atlas, nk_handle_ptr(sdl->ogl.font_tex), &sdl->ogl.tex_null);
if (sdl->atlas.default_font) {
nk_style_set_font(&sdl->ctx, &sdl->atlas.default_font->handle);
}
}
#endif
NK_API int
nk_sdl_handle_event(struct nk_context* ctx, SDL_Event *evt)
{
struct nk_sdl* sdl;
NK_ASSERT(ctx);
NK_ASSERT(evt);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
/* We only care about Window currently used by Nuklear */
if (sdl->win != SDL_GetWindowFromEvent(evt)) {
return 0;
}
switch(evt->type)
{
case SDL_EVENT_KEY_UP: /* KEYUP & KEYDOWN share same routine */
case SDL_EVENT_KEY_DOWN:
{
int down = evt->type == SDL_EVENT_KEY_DOWN;
int ctrl_down = evt->key.mod & SDL_KMOD_CTRL;
switch(evt->key.key)
{
case SDLK_LALT:
case SDLK_RALT: nk_input_key(ctx, NK_KEY_ALT, down); break;
case SDLK_RSHIFT: /* RSHIFT & LSHIFT share same routine */
case SDLK_LSHIFT: nk_input_key(ctx, NK_KEY_SHIFT, down); break;
case SDLK_DELETE: nk_input_key(ctx, NK_KEY_DEL, down); break;
case SDLK_KP_ENTER:
case SDLK_RETURN: nk_input_key(ctx, NK_KEY_ENTER, down); break;
case SDLK_TAB: nk_input_key(ctx, NK_KEY_TAB, down); break;
case SDLK_BACKSPACE: nk_input_key(ctx, NK_KEY_BACKSPACE, down); break;
case SDLK_HOME: nk_input_key(ctx, NK_KEY_TEXT_START, down);
nk_input_key(ctx, NK_KEY_SCROLL_START, down); break;
case SDLK_END: nk_input_key(ctx, NK_KEY_TEXT_END, down);
nk_input_key(ctx, NK_KEY_SCROLL_END, down); break;
case SDLK_PAGEDOWN: nk_input_key(ctx, NK_KEY_SCROLL_DOWN, down); break;
case SDLK_PAGEUP: nk_input_key(ctx, NK_KEY_SCROLL_UP, down); break;
case SDLK_F1: nk_input_key(ctx, NK_KEY_F1, down); break;
case SDLK_F2: nk_input_key(ctx, NK_KEY_F2, down); break;
case SDLK_F3: nk_input_key(ctx, NK_KEY_F3, down); break;
case SDLK_F4: nk_input_key(ctx, NK_KEY_F4, down); break;
case SDLK_F5: nk_input_key(ctx, NK_KEY_F5, down); break;
case SDLK_F6: nk_input_key(ctx, NK_KEY_F6, down); break;
case SDLK_F7: nk_input_key(ctx, NK_KEY_F7, down); break;
case SDLK_F8: nk_input_key(ctx, NK_KEY_F8, down); break;
case SDLK_F9: nk_input_key(ctx, NK_KEY_F9, down); break;
case SDLK_F10: nk_input_key(ctx, NK_KEY_F10, down); break;
case SDLK_F11: nk_input_key(ctx, NK_KEY_F11, down); break;
case SDLK_F12: nk_input_key(ctx, NK_KEY_F12, down); break;
case SDLK_A: nk_input_key(ctx, NK_KEY_TEXT_SELECT_ALL, down && ctrl_down); break;
case SDLK_Z: nk_input_key(ctx, NK_KEY_TEXT_UNDO, down && ctrl_down); break;
case SDLK_R: nk_input_key(ctx, NK_KEY_TEXT_REDO, down && ctrl_down); break;
case SDLK_C: nk_input_key(ctx, NK_KEY_COPY, down && ctrl_down); break;
case SDLK_V: nk_input_key(ctx, NK_KEY_PASTE, down && ctrl_down); break;
case SDLK_X: nk_input_key(ctx, NK_KEY_CUT, down && ctrl_down); break;
case SDLK_B: nk_input_key(ctx, NK_KEY_TEXT_LINE_START, down && ctrl_down); break;
case SDLK_E: nk_input_key(ctx, NK_KEY_TEXT_LINE_END, down && ctrl_down); break;
case SDLK_UP: nk_input_key(ctx, NK_KEY_UP, down); break;
case SDLK_DOWN: nk_input_key(ctx, NK_KEY_DOWN, down); break;
case SDLK_ESCAPE: nk_input_key(ctx, NK_KEY_TEXT_RESET_MODE, down); break;
case SDLK_INSERT:
if (down) sdl->insert_toggle = !sdl->insert_toggle;
if (sdl->insert_toggle) {
nk_input_key(ctx, NK_KEY_TEXT_INSERT_MODE, down);
} else {
nk_input_key(ctx, NK_KEY_TEXT_REPLACE_MODE, down);
}
break;
case SDLK_LEFT:
if (ctrl_down)
nk_input_key(ctx, NK_KEY_TEXT_WORD_LEFT, down);
else
nk_input_key(ctx, NK_KEY_LEFT, down);
break;
case SDLK_RIGHT:
if (ctrl_down)
nk_input_key(ctx, NK_KEY_TEXT_WORD_RIGHT, down);
else
nk_input_key(ctx, NK_KEY_RIGHT, down);
break;
default:
return 0;
}
return 1;
}
case SDL_EVENT_MOUSE_BUTTON_UP: /* MOUSEBUTTONUP & MOUSEBUTTONDOWN share same routine */
case SDL_EVENT_MOUSE_BUTTON_DOWN:
{
const int x = evt->button.x, y = evt->button.y;
const int down = evt->button.down;
switch(evt->button.button)
{
case SDL_BUTTON_LEFT:
if (evt->button.clicks > 1)
nk_input_button(ctx, NK_BUTTON_DOUBLE, x, y, down);
nk_input_button(ctx, NK_BUTTON_LEFT, x, y, down);
break;
case SDL_BUTTON_MIDDLE: nk_input_button(ctx, NK_BUTTON_MIDDLE, x, y, down); break;
case SDL_BUTTON_RIGHT: nk_input_button(ctx, NK_BUTTON_RIGHT, x, y, down); break;
case SDL_BUTTON_X1: nk_input_button(ctx, NK_BUTTON_X1, x, y, down); break;
case SDL_BUTTON_X2: nk_input_button(ctx, NK_BUTTON_X2, x, y, down); break;
default:
return 0;
}
}
return 1;
case SDL_EVENT_MOUSE_MOTION:
ctx->input.mouse.pos.x = evt->motion.x;
ctx->input.mouse.pos.y = evt->motion.y;
ctx->input.mouse.delta.x = ctx->input.mouse.pos.x - ctx->input.mouse.prev.x;
ctx->input.mouse.delta.y = ctx->input.mouse.pos.y - ctx->input.mouse.prev.y;
return 1;
case SDL_EVENT_TEXT_INPUT:
{
nk_glyph glyph;
nk_size len;
NK_ASSERT(evt->text.text);
len = SDL_strlen(evt->text.text);
NK_ASSERT(len <= NK_UTF_SIZE);
NK_MEMCPY(glyph, evt->text.text, len);
nk_input_glyph(ctx, glyph);
}
return 1;
case SDL_EVENT_MOUSE_WHEEL:
nk_input_scroll(ctx, nk_vec2(evt->wheel.x, evt->wheel.y));
return 1;
}
return 0;
}
NK_API
void nk_sdl_shutdown(struct nk_context* ctx)
{
struct nk_sdl* sdl;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
#ifdef NK_INCLUDE_FONT_BAKING
if (sdl->atlas.font_num > 0)
nk_font_atlas_clear(&sdl->atlas);
#endif
nk_buffer_free(&sdl->ogl.cmds);
if (sdl->ogl.font_tex != NULL) {
SDL_DestroyTexture(sdl->ogl.font_tex);
sdl->ogl.font_tex = NULL;
}
nk_free(ctx);
sdl->allocator.free(sdl->allocator.userdata, sdl->debug_font);
sdl->allocator.free(sdl->allocator.userdata, sdl);
}
/* Debug Font Width/Height of internal texture atlas
* This is a result of: ceil(sqrt('~' - ' '))
* There is a sanity check for this value in nk_sdl_style_set_debug_font */
#define NK_SDL_DFWH (10)
NK_INTERN float
nk_sdl_query_debug_font_width(nk_handle handle, float height,
const char *text, int len)
{
NK_UNUSED(handle);
return nk_utf_len(text, len) * height;
}
NK_INTERN void
nk_sdl_query_debug_font_glypth(nk_handle handle, float height,
struct nk_user_font_glyph *glyph,
nk_rune codepoint, nk_rune next_codepoint)
{
char ascii;
int idx, x, y;
NK_UNUSED(next_codepoint);
NK_UNUSED(handle);
/* replace non-ASCII characters with question mark */
ascii = (codepoint < (nk_rune)' ' || codepoint > (nk_rune)'~')
? '?' : (char)codepoint;
NK_ASSERT(ascii >= ' ' && ascii <= '~');
idx = (int)(ascii - ' ');
x = idx / NK_SDL_DFWH;
y = idx % NK_SDL_DFWH;
NK_ASSERT(x >= 0 && x < NK_SDL_DFWH);
NK_ASSERT(y >= 0 && y < NK_SDL_DFWH);
glyph->height = height;
glyph->width = height;
glyph->xadvance = height;
glyph->uv[0].x = (float)(x + 0) / NK_SDL_DFWH;
glyph->uv[0].y = (float)(y + 0) / NK_SDL_DFWH;
glyph->uv[1].x = (float)(x + 1) / NK_SDL_DFWH;
glyph->uv[1].y = (float)(y + 1) / NK_SDL_DFWH;
glyph->offset.x = 0.0f;
glyph->offset.y = 0.0f;
}
NK_API void
nk_sdl_style_set_debug_font(struct nk_context* ctx)
{
struct nk_user_font* font;
struct nk_sdl* sdl;
SDL_Surface *surface;
SDL_Renderer *renderer;
char buf[2];
int x, y;
bool success;
NK_ASSERT(ctx);
sdl = (struct nk_sdl*)ctx->userdata.ptr;
NK_ASSERT(sdl);
if (sdl->debug_font) {
sdl->allocator.free(sdl->allocator.userdata, sdl->debug_font);
sdl->debug_font = 0;
}
/* sanity check: formal proof of NK_SDL_DFWH value (which is 10) */
NK_ASSERT(SDL_ceil(SDL_sqrt('~' - ' ')) == NK_SDL_DFWH);
/* We use another Software Renderer just to make sure
* that we won't mutate any state in the main Renderer. */
surface = SDL_CreateSurface(
NK_SDL_DFWH * SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE,
NK_SDL_DFWH * SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE,
SDL_PIXELFORMAT_RGBA32);
NK_ASSERT(surface);
renderer = SDL_CreateSoftwareRenderer(surface);
NK_ASSERT(renderer);
success = SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
NK_ASSERT(success);
/* SPACE is the first printable ASCII character */
NK_MEMCPY(buf, " ", sizeof(buf));
for (x = 0; x < NK_SDL_DFWH; x++)
{
for (y = 0; y < NK_SDL_DFWH; y++)
{
success = SDL_RenderDebugText(
renderer,
(float)(x * SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE),
(float)(y * SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE),
buf);
NK_ASSERT(success);
buf[0]++;
/* TILDE is the last printable ASCII character */
if (buf[0] > '~')
break;
}
}
success = SDL_RenderPresent(renderer);
NK_ASSERT(success);
font = (struct nk_user_font*)sdl->allocator.alloc(sdl->allocator.userdata, 0, sizeof(*font));
NK_ASSERT(font);
font->userdata.ptr = sdl;
font->height = SDL_DEBUG_TEXT_FONT_CHARACTER_SIZE;
font->width = &nk_sdl_query_debug_font_width;
font->query = &nk_sdl_query_debug_font_glypth;
/* HACK: nk_sdl_device_upload_atlas turns pixels into SDL_Texture
* and sets said Texture into sdl->ogl.font_tex
* then nk_sdl_render expects same Texture at font->texture */
nk_sdl_device_upload_atlas(ctx, surface->pixels, surface->w, surface->h);
font->texture.ptr = sdl->ogl.font_tex;
sdl->debug_font = font;
nk_style_set_font(ctx, font);
SDL_DestroyRenderer(renderer);
SDL_DestroySurface(surface);
}
#endif /* NK_SDL3_RENDERER_IMPLEMENTATION_ONCE */
#endif /* NK_SDL3_RENDERER_IMPLEMENTATION */