Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

strata.gno

39.87 Kb · 1251 lines
   1// Package strata (v2, "Derin Zaman") is a Sinopia engine: a geological
   2// plate of an invented earth. On the left a cross-section: beds of eight rock
   3// types, each with its own texture, folded by an integer sine field, cut by
   4// faults (every bed boundary steps along the fault plane), crossed by dikes,
   5// sills or quartz veins, sometimes truncated by an angular unconformity, with
   6// fossils in the beds and the present land surface on top (meadow, forest,
   7// bare rock or snow). On the right the stratigraphic column of the same
   8// beds: each formation named (Kızıldere, Akyayla, ...), dated in Ma, drawn
   9// with its true thickness and a width by its resistance (a weathering
  10// profile), fossils and events marked. Rare events tell a story: an aquifer
  11// with its well, a karst cave, an oil trap under an anticline with its
  12// derrick, a gold vein, an impact boundary.
  13//
  14// It is the successor of Strata v1 (p/.../art/strata/v1, which stays
  15// untouched): the same FNV-1a + splitmix64 streams (seed+"|traits" and
  16// seed+"|art") and the same integer sine table, a new picture.
  17// frontend/src/engines/stratav2.ts is a byte-identical TypeScript twin;
  18// strata_test.gno pins golden vectors that the twin asserts too.
  19//
  20// Unlike v1 the art reads Input.TokenID (the column's title, "Section 42").
  21// It never reads heights or moves, so the engine is not living. Pure integer
  22// maths: no floats, no time, no block data.
  23package strata
  24
  25import (
  26	"errors"
  27	"strconv"
  28	"strings"
  29
  30	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
  31)
  32
  33// traitTypes in the order Traits returns them.
  34var traitTypes = []string{"Era", "Event", "Fossil", "Intrusion", "Folding", "Tectonics", "Surface", "Rarity"}
  35
  36// MaxSVGBytes: the largest output measured is 16,755 B (10,000 default seeds
  37// and 8,000 params renders, docs/engines/strata-v2.md); about 1.7x margin,
  38// within the 28 KB budget.
  39const MaxSVGBytes = 28672
  40
  41// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
  42// in this property order; ValidateParams accepts exactly that or "".
  43const ParamsSchema = `{"type":"object","properties":{` +
  44	`"era":{"type":"string","title":"Era","enum":["Seeded","Red Beds","Chalk Sea","Volcanic Arc","Coal Age",` +
  45	`"Desert Dunes","Ice Age","Lapis Vein"],"default":"Seeded"},` +
  46	`"folding":{"type":"string","title":"Folding","enum":["Seeded","Flat","Gentle","Folded","Contorted"],"default":"Seeded"},` +
  47	`"surface":{"type":"string","title":"Surface","enum":["Seeded","Meadow","Forest","Bare Rock","Snow"],"default":"Seeded"}}}`
  48
  49// DefaultParams is the canonical form of the defaults; it renders exactly
  50// like "".
  51const DefaultParams = `{"era":"Seeded","folding":"Seeded","surface":"Seeded"}`
  52
  53// Manifest describes the engine. Author and FeeBps are set by the adapter.
  54func Manifest() engine.Manifest {
  55	return engine.Manifest{
  56		Name:    "Strata · Derin Zaman",
  57		Version: "2.0.0",
  58		Description: "Strata v2: a geological plate of an invented earth. A cross-section of textured beds, " +
  59			"folded, faulted and cut by dikes, with fossils and the land surface on top, beside the " +
  60			"stratigraphic column of the same beds: every formation named and dated. Rare events tell a " +
  61			"story: an aquifer, a karst cave, an oil trap, a gold vein, an impact boundary. The token " +
  62			"number titles the section.",
  63		License:      "CC-BY-NC-4.0",
  64		ParamsSchema: ParamsSchema,
  65		TraitTypes:   append([]string{}, traitTypes...),
  66		Living:       false,
  67		MaxSVGBytes:  MaxSVGBytes,
  68		Kind:         engine.KindSVG,
  69	}
  70}
  71
  72// Config is a parsed params string; -1 means drawn from the seed.
  73type Config struct {
  74	Era, Folding, Surface int
  75}
  76
  77// Defaults is the showcase look (params "").
  78func Defaults() Config { return Config{Era: -1, Folding: -1, Surface: -1} }
  79
  80var errParams = errors.New(`stratav2: params must be "" or ` +
  81	`{"era":<enum>,"folding":<enum>,"surface":<enum>} in that order, without spaces`)
  82
  83// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
  84func ParseParams(params string) (Config, error) {
  85	cfg := Defaults()
  86	if params == "" {
  87		return cfg, nil
  88	}
  89	v, rest, ok := strValue(params, `{"era":"`)
  90	if !ok {
  91		return cfg, errParams
  92	}
  93	if cfg.Era, ok = enumIndex(v, eras); !ok {
  94		return cfg, errParams
  95	}
  96	if v, rest, ok = strValue(rest, `","folding":"`); !ok {
  97		return cfg, errParams
  98	}
  99	if cfg.Folding, ok = enumIndex(v, foldings); !ok {
 100		return cfg, errParams
 101	}
 102	if v, rest, ok = strValue(rest, `","surface":"`); !ok {
 103		return cfg, errParams
 104	}
 105	if cfg.Surface, ok = enumIndex(v, surfaces); !ok {
 106		return cfg, errParams
 107	}
 108	if rest != `"}` {
 109		return cfg, errParams
 110	}
 111	return cfg, nil
 112}
 113
 114// strValue expects s to start with prefix and returns the text up to the
 115// next '"' and the remainder starting at that quote.
 116func strValue(s, prefix string) (string, string, bool) {
 117	if !strings.HasPrefix(s, prefix) {
 118		return "", "", false
 119	}
 120	s = s[len(prefix):]
 121	end := strings.IndexByte(s, '"')
 122	if end < 0 {
 123		return "", "", false
 124	}
 125	return s[:end], s[end:], true
 126}
 127
 128func enumIndex(v string, table []option) (int, bool) {
 129	if v == "Seeded" {
 130		return -1, true
 131	}
 132	for i, o := range table {
 133		if o.name == v {
 134			return i, true
 135		}
 136	}
 137	return 0, false
 138}
 139
 140// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
 141func ValidateParams(params string) error {
 142	_, err := ParseParams(params)
 143	return err
 144}
 145
 146func mustConfig(params string) Config {
 147	cfg, err := ParseParams(params)
 148	if err != nil {
 149		panic(err)
 150	}
 151	return cfg
 152}
 153
 154// Traits returns the eight traits of in.Seed in TraitTypes order. It never
 155// renders: eight draws and a score.
 156func Traits(in engine.Input) []engine.Trait {
 157	t := TraitsOf(in.Seed, mustConfig(in.Params))
 158	return []engine.Trait{
 159		{Type: "Era", Value: t.Era},
 160		{Type: "Event", Value: t.Event},
 161		{Type: "Fossil", Value: t.Fossil},
 162		{Type: "Intrusion", Value: t.Intrusion},
 163		{Type: "Folding", Value: t.Folding},
 164		{Type: "Tectonics", Value: t.Tectonics},
 165		{Type: "Surface", Value: t.Surface},
 166		{Type: "Rarity", Value: t.Rarity},
 167	}
 168}
 169
 170// Render returns the raw SVG for in.Seed, in.Params and in.TokenID.
 171func Render(in engine.Input) string { return SVG(in.Seed, mustConfig(in.Params), in.TokenID) }
 172
 173// ---------------------------------------------------------------------------
 174// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Strata
 175// v1's stream). Traits use seed+"|traits", the art seed+"|art".
 176// ---------------------------------------------------------------------------
 177
 178type rng struct{ state uint64 }
 179
 180func newRNG(seed string) *rng {
 181	h := uint64(14695981039346656037)
 182	for i := 0; i < len(seed); i++ {
 183		h ^= uint64(seed[i])
 184		h *= 1099511628211
 185	}
 186	if h == 0 {
 187		h = 1099511628211
 188	}
 189	return &rng{state: h}
 190}
 191
 192func (r *rng) next() uint64 {
 193	r.state += 0x9E3779B97F4A7C15
 194	z := r.state
 195	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
 196	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
 197	return z ^ (z >> 31)
 198}
 199
 200// intn is in [0, n); one draw whenever n > 0.
 201func (r *rng) intn(n int) int {
 202	if n <= 0 {
 203		return 0
 204	}
 205	return int(r.next() % uint64(n))
 206}
 207
 208// between is in [a, b].
 209func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
 210
 211// ---------------------------------------------------------------------------
 212// Tables
 213// ---------------------------------------------------------------------------
 214
 215type option struct {
 216	name   string
 217	weight int
 218	score  int // contribution to the rarity score when drawn (not pinned)
 219}
 220
 221func pick(r *rng, table []option) int {
 222	total := 0
 223	for _, o := range table {
 224		total += o.weight
 225	}
 226	x := r.intn(total)
 227	for i, o := range table {
 228		x -= o.weight
 229		if x < 0 {
 230			return i
 231		}
 232	}
 233	return len(table) - 1
 234}
 235
 236var eras = []option{
 237	{"Red Beds", 22, 0}, {"Chalk Sea", 18, 0}, {"Volcanic Arc", 14, 0}, {"Coal Age", 14, 0},
 238	{"Desert Dunes", 14, 0}, {"Ice Age", 10, 1}, {"Lapis Vein", 6, 4},
 239}
 240
 241const (
 242	eVolcanic = 2
 243	eDesert   = 4
 244	eLapis    = 6
 245)
 246
 247// eraSky: the sky gradient, top and bottom.
 248var eraSky = [][]string{
 249	{"#e9dcc4", "#f4ecdc"}, {"#dfe6e4", "#f2f2ea"}, {"#d8d2d6", "#eeeae6"}, {"#d6dccd", "#ecefe4"},
 250	{"#f0d9b0", "#f8eedc"}, {"#d6e2ea", "#eef3f5"}, {"#d9dbe6", "#f0eff2"},
 251}
 252
 253// eraRock: the rock colours in liths order.
 254var eraRock = [][]string{
 255	{"#c0643f", "#7a3426", "#d9b38c", "#a8553a", "#b98a6a", "#9a6b5a", "#3a2620", "#e8d6c0"},
 256	{"#d8c49a", "#8a8a7a", "#ece4cc", "#b8a684", "#cfc7a8", "#a7a294", "#33302a", "#f4efe2"},
 257	{"#8d7a76", "#4a3f48", "#b8aca8", "#6e5a5a", "#9a8c8c", "#b5a3b8", "#211d22", "#d9d0d4"},
 258	{"#b0a080", "#4c4a44", "#c4bca4", "#8a7c64", "#9c967e", "#8c8678", "#1b1a18", "#e2ddcc"},
 259	{"#dd9a55", "#9c5a36", "#e8cfa0", "#c07a45", "#d2a074", "#b88a6a", "#4a3022", "#f3e6cc"},
 260	{"#a9b2b0", "#5f6a72", "#d2d8d6", "#87908e", "#b4bcbc", "#9aa0a8", "#262b30", "#eef2f2"},
 261	{"#4a5a8a", "#1f2747", "#8a93b8", "#3a4670", "#6a73a0", "#5a5f86", "#141726", "#c9cde0"},
 262}
 263
 264var liths = []option{
 265	{"Sandstone", 26, 0}, {"Shale", 22, 0}, {"Limestone", 20, 0}, {"Conglomerate", 9, 0},
 266	{"Marl", 10, 0}, {"Tuff", 6, 0}, {"Coal", 4, 0}, {"Evaporite", 3, 0},
 267}
 268
 269const (
 270	lSandstone = 0
 271	lShale     = 1
 272	lLimestone = 2
 273	lCoal      = 6
 274)
 275
 276// lithW is the column width of each rock: resistant rocks stand out.
 277var lithW = []int{26, 16, 30, 28, 20, 22, 12, 18}
 278
 279const lithID = "kslcmtoe"
 280
 281var lithPat = []string{
 282	`<pattern id="k" width="14" height="10" patternUnits="userSpaceOnUse"><path d="M2 3h1M9 2h1M5 7h1M12 8h1" stroke="#000" stroke-opacity=".28" stroke-width="1.6" stroke-linecap="round"/></pattern>`,
 283	`<pattern id="s" width="22" height="6" patternUnits="userSpaceOnUse"><path d="M1 2h9M13 5h7" stroke="#000" stroke-opacity=".2"/></pattern>`,
 284	`<pattern id="l" width="28" height="14" patternUnits="userSpaceOnUse"><path d="M0 .5h28M0 7.5h28M7 0v7M21 7v7" stroke="#000" stroke-opacity=".16"/></pattern>`,
 285	`<pattern id="c" width="24" height="18" patternUnits="userSpaceOnUse"><ellipse cx="6" cy="5" rx="4" ry="3" fill="#fff" fill-opacity=".22" stroke="#000" stroke-opacity=".25"/><ellipse cx="17" cy="12" rx="5" ry="3.4" fill="#000" fill-opacity=".1" stroke="#000" stroke-opacity=".25"/><circle cx="20" cy="3" r="1.6" fill="#000" fill-opacity=".25"/></pattern>`,
 286	`<pattern id="m" width="16" height="8" patternUnits="userSpaceOnUse"><path d="M0 4h5M8 4h5" stroke="#000" stroke-opacity=".13"/><circle cx="12" cy="1.5" r=".9" fill="#000" fill-opacity=".2"/></pattern>`,
 287	`<pattern id="t" width="12" height="12" patternUnits="userSpaceOnUse"><path d="M2 2l2 1M8 7l1 2M4 9l2-1" stroke="#fff" stroke-opacity=".35"/><circle cx="10" cy="3" r="1" fill="#000" fill-opacity=".25"/></pattern>`,
 288	`<pattern id="o" width="10" height="4" patternUnits="userSpaceOnUse"><path d="M0 1h10" stroke="#fff" stroke-opacity=".08"/></pattern>`,
 289	`<pattern id="e" width="18" height="14" patternUnits="userSpaceOnUse"><path d="M4 4l3 3 3-3-3-3zM11 10l3 3 3-3-3-3z" fill="none" stroke="#000" stroke-opacity=".15"/></pattern>`,
 290}
 291
 292var foldings = []option{{"Flat", 22, 0}, {"Gentle", 34, 0}, {"Folded", 30, 0}, {"Contorted", 14, 1}}
 293
 294var foldAmp = []int{0, 18, 42, 70}
 295
 296var faultsT = []option{{"0", 30, 0}, {"1", 44, 0}, {"2", 26, 1}}
 297
 298var intrusions = []option{{"None", 46, 0}, {"Dike", 24, 0}, {"Sill", 16, 0}, {"Dike & Sill", 10, 1}, {"Vein Swarm", 4, 3}}
 299
 300const (
 301	iDike  = 1
 302	iSill  = 2
 303	iBoth  = 3
 304	iSwarm = 4
 305)
 306
 307var fossils = []option{
 308	{"None", 34, 0}, {"Ammonite", 20, 0}, {"Fish", 14, 0}, {"Leaf", 14, 0}, {"Sea Urchin", 12, 0}, {"Fossil Bed", 6, 2},
 309}
 310
 311const fBed = 5
 312
 313var fossilSym = []string{
 314	`<symbol id="fa" viewBox="-12 -12 24 24"><path d="M0 0a2 2 0 0 1 4 0a4 4 0 0 1-8 0a6 6 0 0 1 12 0a8 8 0 0 1-16 0a10 10 0 0 1 20 0M7 0h5M-5 1l-5 2M2-6l1-4M-1 7l-1 4" fill="none" stroke="currentColor" stroke-width="1.8"/></symbol>`,
 315	`<symbol id="fb" viewBox="-14 -7 28 14"><path d="M-12 0q10-9 21 0q-11 9-21 0zM9 0l4-4v8zM-9 0h18M-6-3l2 6M-2-4l2 8M2-4l2 8M6-3l1 6" fill="none" stroke="currentColor" stroke-width="1.2"/></symbol>`,
 316	`<symbol id="fy" viewBox="-8 -14 16 28"><path d="M0-12q8 8 0 22q-8-14 0-22zM0-10v24M0-4l4-3M0 1l4-3M0-4l-4-3M0 1l-4-3" fill="none" stroke="currentColor" stroke-width="1.2"/></symbol>`,
 317	`<symbol id="fd" viewBox="-10 -10 20 20"><circle r="8" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M0-6v12M-6 0h12M-4-4l8 8M4-4l-8 8" stroke="currentColor" stroke-dasharray="1 2"/></symbol>`,
 318}
 319
 320var fossilID = []string{"fa", "fb", "fy", "fd"}
 321
 322var events = []option{
 323	{"None", 64, 0}, {"Aquifer", 9, 3}, {"Karst Cave", 9, 3}, {"Oil Trap", 6, 3}, {"Gold Vein", 6, 3}, {"Impact Boundary", 6, 3},
 324}
 325
 326const (
 327	evAquifer = 1
 328	evKarst   = 2
 329	evOil     = 3
 330	evGold    = 4
 331	evImpact  = 5
 332)
 333
 334var surfaces = []option{{"Meadow", 40, 0}, {"Forest", 26, 0}, {"Bare Rock", 22, 0}, {"Snow", 12, 0}}
 335
 336const (
 337	sMeadow = 0
 338	sForest = 1
 339	sSnow   = 3
 340)
 341
 342const (
 343	unconfPct   = 28
 344	scoreUnconf = 1
 345)
 346
 347var tectonics = []string{"Undisturbed", "One Fault", "Two Faults", "Unconformity", "Unconformity + One Fault", "Unconformity + Two Faults"}
 348
 349// Rarity cut-offs on the summed score (10,000 default seeds: see
 350// docs/engines/strata-v2.md).
 351const (
 352	scoreMythic    = 8
 353	scoreLegendary = 6
 354	scoreRare      = 4
 355	scoreUncommon  = 2
 356)
 357
 358var namesA = []string{"Kızıl", "Ak", "Kara", "Sarı", "Boz", "Gök", "Demir", "Taş", "Çam", "Göl", "Kuru", "Ulu", "Ilı", "Yel", "Elma", "Dikmen"}
 359
 360var namesB = []string{"dere", "tepe", "kaya", "ova", "pınar", "bel", "yurt", "köy", "sırt", "yayla", "çay", "bük"}
 361
 362// ---------------------------------------------------------------------------
 363// Traits
 364// ---------------------------------------------------------------------------
 365
 366type draw struct {
 367	era, folding, faults, intrusion int
 368	unconf                          bool
 369	fossil, event, surface          int
 370	score                           int
 371	rarity                          string
 372}
 373
 374// derive draws the traits from seed+"|traits". The draw order is part of the
 375// contract: era, folding, faults, intrusion, unconformity (intn(100) < 28),
 376// fossil, event, surface. Params pin era/folding/surface after all draws, so
 377// a seed's other traits never move; a pinned trait scores 0.
 378func derive(seed string, cfg Config) draw {
 379	r := newRNG(seed + "|traits")
 380	d := draw{}
 381	d.era = pick(r, eras)
 382	d.folding = pick(r, foldings)
 383	d.faults = pick(r, faultsT)
 384	d.intrusion = pick(r, intrusions)
 385	d.unconf = r.intn(100) < unconfPct
 386	d.fossil = pick(r, fossils)
 387	d.event = pick(r, events)
 388	d.surface = pick(r, surfaces)
 389	score := faultsT[d.faults].score + intrusions[d.intrusion].score + fossils[d.fossil].score + events[d.event].score
 390	if d.unconf {
 391		score += scoreUnconf
 392	}
 393	if cfg.Era >= 0 {
 394		d.era = cfg.Era
 395	} else {
 396		score += eras[d.era].score
 397	}
 398	if cfg.Folding >= 0 {
 399		d.folding = cfg.Folding
 400	} else {
 401		score += foldings[d.folding].score
 402	}
 403	if cfg.Surface >= 0 {
 404		d.surface = cfg.Surface
 405	} else {
 406		score += surfaces[d.surface].score
 407	}
 408	d.score = score
 409	switch {
 410	case score >= scoreMythic:
 411		d.rarity = "Mythic"
 412	case score >= scoreLegendary:
 413		d.rarity = "Legendary"
 414	case score >= scoreRare:
 415		d.rarity = "Rare"
 416	case score >= scoreUncommon:
 417		d.rarity = "Uncommon"
 418	default:
 419		d.rarity = "Common"
 420	}
 421	return d
 422}
 423
 424// TraitSet is the decoded traits of a seed; the picture reads the same draw.
 425type TraitSet struct {
 426	Era, Event, Fossil, Intrusion, Folding, Tectonics, Surface, Rarity string
 427	Score                                                              int
 428}
 429
 430// TraitsOf returns the traits of a seed under cfg.
 431func TraitsOf(seed string, cfg Config) TraitSet {
 432	d := derive(seed, cfg)
 433	tec := d.faults
 434	if d.unconf {
 435		tec += 3
 436	}
 437	return TraitSet{
 438		Era:       eras[d.era].name,
 439		Event:     events[d.event].name,
 440		Fossil:    fossils[d.fossil].name,
 441		Intrusion: intrusions[d.intrusion].name,
 442		Folding:   foldings[d.folding].name,
 443		Tectonics: tectonics[tec],
 444		Surface:   surfaces[d.surface].name,
 445		Rarity:    d.rarity,
 446		Score:     d.score,
 447	}
 448}
 449
 450// SectionNumber is the number in the column title: Input.TokenID read as a
 451// decimal, modulo 1,000,000. Anything but ASCII digits (or "") is 0.
 452func SectionNumber(tokenID string) int {
 453	v := 0
 454	for i := 0; i < len(tokenID); i++ {
 455		c := tokenID[i]
 456		if c < '0' || c > '9' {
 457			return 0
 458		}
 459		v = (v*10 + int(c-'0')) % 1000000
 460	}
 461	return v
 462}
 463
 464// ---------------------------------------------------------------------------
 465// Integer helpers
 466// ---------------------------------------------------------------------------
 467
 468func iabs(a int) int {
 469	if a < 0 {
 470		return -a
 471	}
 472	return a
 473}
 474
 475func imin(a, b int) int {
 476	if a < b {
 477		return a
 478	}
 479	return b
 480}
 481
 482func imax(a, b int) int {
 483	if a > b {
 484		return a
 485	}
 486	return b
 487}
 488
 489// quarter is a quarter wave, 256 steps per turn, x1024 (Strata v1's table).
 490var quarter = []int{0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460,
 491	483, 505, 526, 548, 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822,
 492	837, 851, 865, 878, 891, 903, 915, 926, 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009,
 493	1013, 1016, 1019, 1021, 1023, 1024, 1024}
 494
 495func isin(a int) int {
 496	a %= 256
 497	if a < 0 {
 498		a += 256
 499	}
 500	switch {
 501	case a < 64:
 502		return quarter[a]
 503	case a < 128:
 504		return quarter[128-a]
 505	case a < 192:
 506		return -quarter[a-128]
 507	}
 508	return -quarter[256-a]
 509}
 510
 511func icos(a int) int { return isin(a + 64) }
 512
 513const hexDigits = "0123456789abcdef"
 514
 515func hexByte(c string, i int) int {
 516	return strings.IndexByte(hexDigits, c[i])*16 + strings.IndexByte(hexDigits, c[i+1])
 517}
 518
 519// mix is a + (b - a) * t / 100 per channel (truncated), "#rrggbb".
 520func mix(a, b string, t int) string {
 521	out := []byte{'#', 0, 0, 0, 0, 0, 0}
 522	for i := 1; i < 7; i += 2 {
 523		va, vb := hexByte(a, i), hexByte(b, i)
 524		v := va + (vb-va)*t/100
 525		out[i] = hexDigits[v>>4]
 526		out[i+1] = hexDigits[v&15]
 527	}
 528	return string(out)
 529}
 530
 531// contrast is a colour that reads on top of rock colour c.
 532func contrast(c string) string {
 533	luma := (299*hexByte(c, 1) + 587*hexByte(c, 3) + 114*hexByte(c, 5)) / 1000
 534	if luma > 110 {
 535		return mix(c, "#1a120c", 65)
 536	}
 537	return mix(c, "#ffffff", 60)
 538}
 539
 540func itoa(n int) string { return strconv.Itoa(n) }
 541
 542// ---------------------------------------------------------------------------
 543// The section
 544// ---------------------------------------------------------------------------
 545
 546const (
 547	sheetW = 640 // sheet
 548	sheetH = 800
 549	sx     = 16 // section box; the section is drawn in local coordinates
 550	sy     = 16
 551	sw     = 480
 552	sh     = 768
 553	bot    = sh + 40 // rock bodies close below the box
 554	step   = 16      // 30 steps, 31 samples
 555	ns     = sw / step
 556	colX   = 512 // the column
 557	colTop = 80
 558	colH   = 660
 559	none   = 99
 560)
 561
 562// relSteps writes the relative steps between consecutive points,
 563// "dx dy dx dy", with no separator before a minus; zero moves are skipped.
 564func relSteps(b *strings.Builder, xs, ys []int) {
 565	first := true
 566	px, py := xs[0], ys[0]
 567	for i := 1; i < len(xs); i++ {
 568		dx, dy := xs[i]-px, ys[i]-py
 569		if dx == 0 && dy == 0 {
 570			continue
 571		}
 572		if !first && dx >= 0 {
 573			b.WriteString(" ")
 574		}
 575		b.WriteString(itoa(dx))
 576		if dy >= 0 {
 577			b.WriteString(" ")
 578		}
 579		b.WriteString(itoa(dy))
 580		first = false
 581		px, py = xs[i], ys[i]
 582	}
 583}
 584
 585// openPath writes an open polyline "Mx yl...".
 586func openPath(b *strings.Builder, xs, ys []int) {
 587	b.WriteString("M")
 588	b.WriteString(itoa(xs[0]))
 589	b.WriteString(" ")
 590	b.WriteString(itoa(ys[0]))
 591	b.WriteString("l")
 592	relSteps(b, xs, ys)
 593}
 594
 595// bodyPath writes a rock body: the curve, continued 20 px past both sides,
 596// closed below the box.
 597func bodyPath(b *strings.Builder, xs, ys []int) {
 598	b.WriteString("M-20 " + itoa(bot) + "V" + itoa(ys[0]) + "h20l")
 599	relSteps(b, xs, ys)
 600	b.WriteString("h20V" + itoa(bot) + "z")
 601}
 602
 603type fault struct{ x0, sl, th int }
 604
 605type section struct {
 606	n, uIdx, a0, lam, ph, ph2, tilt, uTilt, anti int
 607	depth, surf                                  []int
 608	faults                                       []fault
 609}
 610
 611func (s *section) surfAt(x int) int {
 612	if x <= 0 {
 613		return s.surf[0]
 614	}
 615	if x >= sw {
 616		return s.surf[ns]
 617	}
 618	i := x / step
 619	rem := x - i*step
 620	return s.surf[i] + (s.surf[i+1]-s.surf[i])*rem/step
 621}
 622
 623func (s *section) fx(f fault, y int) int { return f.x0 + f.sl*(y-300)/100 }
 624
 625func (s *section) throwAt(x, y int) int {
 626	t := 0
 627	for _, f := range s.faults {
 628		if x > s.fx(f, y) {
 629			t += f.th
 630		}
 631	}
 632	return t
 633}
 634
 635// eAt is the erosion surface of the unconformity.
 636func (s *section) eAt(x int) int {
 637	return s.depth[s.uIdx] - 8 + (6*isin(3*x+s.ph)+3*isin(x*256/61+s.ph2))/1024
 638}
 639
 640// raw is boundary k (the top of bed k+1) at x before faulting.
 641func (s *section) raw(k, x int) int {
 642	if k == s.uIdx {
 643		return s.eAt(x)
 644	}
 645	old := k > s.uIdx
 646	a := s.a0 * k / (s.n + 4)
 647	if old {
 648		a = s.a0 + 26
 649	}
 650	y := s.depth[k] + a*isin(x*256/s.lam+s.ph+3*k)/1024 +
 651		(a>>2)*isin(x*256/97+s.ph2)/1024 + s.tilt*(x-240)*(k+2)/(100*s.n)
 652	if old {
 653		y += s.uTilt * (x - 240) / 100
 654	}
 655	if s.anti >= 0 && k >= 1 {
 656		d := iabs(x - s.anti)
 657		if d < 170 {
 658			y -= 15 * imin(k, 4) * (1024 + icos(d*128/170)) / 2048
 659		}
 660	}
 661	if old {
 662		y = imax(y, s.eAt(x)+1)
 663	}
 664	return y
 665}
 666
 667func (s *section) clampY(x, y int) int { return imin(imax(y, s.surfAt(x)+2), sh+20) }
 668
 669// at is boundary k at x after faulting, kept below the land surface.
 670func (s *section) at(k, x int) int {
 671	y0 := s.raw(k, x)
 672	return s.clampY(x, y0+s.throwAt(x, y0))
 673}
 674
 675// boundary samples boundary k every 16 px, with a step on the fault plane at
 676// every fault it crosses.
 677func (s *section) boundary(k int) ([]int, []int) {
 678	xs := make([]int, 0, ns+8)
 679	ys := make([]int, 0, ns+8)
 680	nf := len(s.faults)
 681	prev := make([]bool, nf)
 682	for x := 0; x <= sw; x += step {
 683		y0 := s.raw(k, x)
 684		for fi := 0; fi < nf; fi++ {
 685			f := s.faults[fi]
 686			side := x > s.fx(f, y0)
 687			if x > 0 && side != prev[fi] {
 688				xf := s.fx(f, y0)
 689				yb := s.raw(k, xf)
 690				// each side meets the fault plane at its own (thrown) depth
 691				yl, yr := yb+s.throwAt(xf-2, yb), yb+s.throwAt(xf+2, yb)
 692				xl, xr := s.fx(f, yl)-1, s.fx(f, yr)+1
 693				xs = append(xs, xl, xr)
 694				ys = append(ys, s.clampY(xl, yl), s.clampY(xr, yr))
 695			}
 696			prev[fi] = side
 697		}
 698		xs = append(xs, x)
 699		ys = append(ys, s.clampY(x, y0+s.throwAt(x, y0)))
 700	}
 701	return xs, ys
 702}
 703
 704// ---------------------------------------------------------------------------
 705// The plate
 706// ---------------------------------------------------------------------------
 707
 708// SVG renders a seed under cfg with the token number tokenID. The art
 709// stream's draw order is part of the contract (it mirrors stratav2.ts).
 710func SVG(seed string, cfg Config, tokenID string) string {
 711	d := derive(seed, cfg)
 712	r := newRNG(seed + "|art")
 713	rock := eraRock[d.era]
 714	sky := eraSky[d.era]
 715	s := &section{uIdx: none, anti: -1}
 716
 717	// --- the plan: beds, names, ages ---
 718	n := r.between(10, 14)
 719	s.n = n
 720	lith := make([]int, n)
 721	for i := 0; i < n; i++ {
 722		l := pick(r, liths)
 723		if d.event == evAquifer && i == 3 {
 724			l = lSandstone
 725		}
 726		if d.event == evKarst && i == 5 {
 727			l = lLimestone
 728		}
 729		if d.event == evOil && i == 4 {
 730			l = lShale // the cap rock
 731		}
 732		if d.event == evOil && i == 5 {
 733			l = lSandstone // the reservoir
 734		}
 735		lith[i] = l
 736	}
 737	thick := make([]int, n)
 738	total := 0
 739	for i := 0; i < n; i++ {
 740		if lith[i] == lCoal {
 741			thick[i] = r.between(10, 16)
 742		} else {
 743			thick[i] = r.between(30, 70)
 744		}
 745		total += thick[i]
 746	}
 747	names := make([]string, n)
 748	for i := 0; i < n; i++ {
 749		a := namesA[r.intn(len(namesA))]
 750		names[i] = a + namesB[r.intn(len(namesB))]
 751	}
 752	sBase := r.between(130, 190)
 753	sp1 := r.intn(256)
 754	sp2 := r.intn(256)
 755	sa1 := r.between(14, 40)
 756	sa2 := r.between(6, 16)
 757	if d.unconf {
 758		s.uIdx = r.between(3, imin(6, n-3))
 759	}
 760	ages := make([]int, n)
 761	age := r.between(2, 12)
 762	for i := 0; i < n; i++ {
 763		ages[i] = age
 764		age += r.between(4, 30)
 765		if i == s.uIdx {
 766			age += r.between(60, 200) // the hiatus
 767		}
 768	}
 769	s.a0 = foldAmp[d.folding]
 770	s.lam = r.between(150, 330)
 771	s.ph = r.intn(256)
 772	s.tilt = r.between(-14, 14)
 773	s.ph2 = r.intn(256)
 774	if d.unconf {
 775		s.uTilt = r.between(18, 34)
 776		if r.intn(2) != 0 {
 777			s.uTilt = -s.uTilt
 778		}
 779	}
 780	for f := 0; f < d.faults; f++ {
 781		x0 := r.between(90, sw-90)
 782		sl := r.between(-35, 35)
 783		th := r.between(16, 46)
 784		if r.intn(100) >= 70 {
 785			th = -th
 786		}
 787		s.faults = append(s.faults, fault{x0, sl, th})
 788	}
 789	if d.event == evOil {
 790		s.anti = r.between(170, sw-170)
 791	}
 792	seedR := r.between(1, 900)
 793	seedG := r.between(1, 900)
 794	sunX := r.between(60, 420)
 795	sunY := r.between(36, 80)
 796	sunR := r.between(16, 28)
 797	ridge := make([]int, 14)
 798	for i := 0; i < 14; i++ {
 799		ridge[i] = sBase - r.between(10, 60)
 800	}
 801	volc := -1
 802	if d.era == eVolcanic {
 803		volc = r.between(2, 10)
 804	}
 805
 806	// --- geometry ---
 807	s.surf = make([]int, ns+1)
 808	sxs := make([]int, ns+1)
 809	for i := 0; i <= ns; i++ {
 810		x := i * step
 811		sxs[i] = x
 812		s.surf[i] = sBase + (sa1*isin(x*256/700+sp1)+sa2*isin(x*256/190+sp2))/1024
 813	}
 814	top0 := sBase + 20
 815	span := sh - 40 - top0
 816	s.depth = make([]int, n-1)
 817	cum := 0
 818	for k := 0; k < n-1; k++ {
 819		cum += thick[k]
 820		s.depth[k] = top0 + span*cum/total
 821	}
 822	bx := make([][]int, n-1)
 823	by := make([][]int, n-1)
 824	for k := 0; k < n-1; k++ {
 825		bx[k], by[k] = s.boundary(k)
 826	}
 827
 828	// --- SVG ---
 829	tid := itoa(SectionNumber(tokenID))
 830	out := &strings.Builder{}
 831	out.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 800" width="640" height="800">`)
 832	out.WriteString(`<title>Strata · Section ` + tid + `</title><desc>` + eras[d.era].name + `: ` + itoa(n) +
 833		` formations, ` + names[0] + ` (` + itoa(ages[0]) + ` Ma) down to ` + names[n-1] + ` (` + itoa(ages[n-1]) + ` Ma)`)
 834	if d.event > 0 {
 835		out.WriteString("; " + events[d.event].name)
 836	}
 837	out.WriteString(`.</desc>`)
 838
 839	defs := &strings.Builder{}
 840	defs.WriteString(`<defs><linearGradient id="sk" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="` + sky[0] +
 841		`"/><stop offset="1" stop-color="` + sky[1] + `"/></linearGradient>`)
 842	used := make([]bool, 8)
 843	for _, l := range lith {
 844		used[l] = true
 845	}
 846	for l := 0; l < 8; l++ {
 847		if used[l] {
 848			defs.WriteString(lithPat[l])
 849		}
 850	}
 851	dunes := d.era == eDesert && used[lSandstone]
 852	if dunes {
 853		defs.WriteString(`<pattern id="x" width="40" height="22" patternUnits="userSpaceOnUse"><path d="M0 22l40-20M10 22l30-15M20 22l20-10" stroke="#000" stroke-opacity=".14" fill="none"/></pattern>`)
 854	}
 855	defs.WriteString(`<filter id="r" x="-2%" y="-2%" width="104%" height="104%"><feTurbulence type="fractalNoise" baseFrequency=".03" numOctaves="2" seed="` + itoa(seedR) + `"/>` +
 856		`<feDisplacementMap in="SourceGraphic" scale="6" xChannelSelector="R" yChannelSelector="G"/></filter>`)
 857	defs.WriteString(`<filter id="g" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".9" numOctaves="1" seed="` + itoa(seedG) + `"/>` +
 858		`<feColorMatrix values="0 0 0 0 .1 0 0 0 0 .08 0 0 0 0 .05 0 0 0 -1.4 .7"/><feComposite in2="SourceAlpha" operator="in"/></filter>`)
 859	var kinds []int
 860	if d.fossil == fBed {
 861		kinds = []int{0, 1, 2, 3}
 862	} else if d.fossil > 0 {
 863		kinds = []int{d.fossil - 1}
 864	}
 865	for _, fk := range kinds {
 866		defs.WriteString(fossilSym[fk])
 867	}
 868	defs.WriteString(`<clipPath id="cl"><rect width="480" height="768"/></clipPath><path id="L0" d="`)
 869	bodyPath(defs, sxs, s.surf)
 870	defs.WriteString(`"/>`)
 871	for k := 0; k < n-1; k++ {
 872		defs.WriteString(`<path id="L` + itoa(k+1) + `" d="`)
 873		bodyPath(defs, bx[k], by[k])
 874		defs.WriteString(`"/>`)
 875	}
 876
 877	// rock colour of each bed
 878	col := make([]string, n)
 879	for i := 0; i < n; i++ {
 880		if d.event == evAquifer && i == 3 {
 881			col[i] = mix(rock[lSandstone], "#3f7fa8", 45)
 882		} else {
 883			col[i] = rock[lith[i]]
 884		}
 885	}
 886
 887	body := &strings.Builder{}
 888	// sky, sun, distant ridge
 889	body.WriteString(`<rect width="480" height="768" fill="url(#sk)"/><circle cx="` + itoa(sunX) + `" cy="` + itoa(sunY) +
 890		`" r="` + itoa(sunR) + `" fill="#fbf6ea" opacity=".8"/>`)
 891	rxs := make([]int, 14)
 892	rys := make([]int, 14)
 893	for i := 0; i < 14; i++ {
 894		y := ridge[i]
 895		if volc >= 0 {
 896			y = imin(y, sBase-118+26*iabs(i-volc))
 897		}
 898		rxs[i] = -20 + 40*i
 899		rys[i] = y
 900	}
 901	body.WriteString(`<path d="M-20 ` + itoa(sBase+60) + `V` + itoa(rys[0]) + `l`)
 902	relSteps(body, rxs, rys)
 903	body.WriteString(`V` + itoa(sBase+60) + `z" fill="` + mix(sky[1], rock[lShale], 30) + `"/>`)
 904	if volc >= 0 {
 905		vx, vy := -20+40*volc, sBase-118
 906		body.WriteString(`<path d="M` + itoa(vx-6) + ` ` + itoa(vy-6) + `q-14-16 4-30q-8-18 14-28q14-12 30-2" fill="none" stroke="#fbf6ea" stroke-width="9" stroke-linecap="round" opacity=".7"/>`)
 907	}
 908
 909	// beds
 910	body.WriteString(`<g filter="url(#r)" stroke-width="1.2" stroke-opacity=".45">`)
 911	for i := 0; i < n; i++ {
 912		li := itoa(i)
 913		body.WriteString(`<use href="#L` + li + `" fill="` + col[i] + `" stroke="` + mix(col[i], "#000000", 55) +
 914			`"/><use href="#L` + li + `" fill="url(#` + lithID[lith[i]:lith[i]+1] + `)"/>`)
 915		if dunes && lith[i] == lSandstone {
 916			body.WriteString(`<use href="#L` + li + `" fill="url(#x)"/>`)
 917		}
 918	}
 919
 920	// intrusions cut the beds
 921	ign := "#4a3b38"
 922	if d.era == eVolcanic {
 923		ign = "#3a3036"
 924	}
 925	ignEdge := mix(ign, "#ffffff", 45)
 926	quartz := "#eee8dc" // vein swarm: pale quartz
 927	if d.era == eLapis {
 928		quartz = "#e9d9a0"
 929	}
 930	if d.intrusion == iDike || d.intrusion == iBoth || d.intrusion == iSwarm {
 931		nd := 1
 932		if d.intrusion == iSwarm {
 933			nd = 4
 934		}
 935		for k := 0; k < nd; k++ {
 936			x0 := r.between(60, sw-60)
 937			var w0 int
 938			if d.intrusion == iSwarm {
 939				w0 = r.between(4, 8)
 940			} else {
 941				w0 = r.between(14, 26)
 942			}
 943			sl := r.between(-20, 20)
 944			var top int
 945			if d.unconf {
 946				top = s.eAt(x0) + 6
 947			} else {
 948				top = sBase + r.between(20, 60)
 949			}
 950			var cx, cy []int
 951			for y := bot; y >= top; y -= 40 {
 952				cx = append(cx, x0+sl*(bot-y)/100+r.between(-3, 3))
 953				cy = append(cy, y)
 954			}
 955			m := len(cx)
 956			xs := make([]int, 0, 2*m+1)
 957			ys := make([]int, 0, 2*m+1)
 958			for i := 0; i < m; i++ {
 959				xs = append(xs, cx[i]-w0/2)
 960				ys = append(ys, cy[i])
 961			}
 962			xs = append(xs, cx[m-1])
 963			ys = append(ys, top-6)
 964			right := make([]int, m)
 965			for i := 0; i < m; i++ {
 966				right[i] = cx[i] + w0/2 + r.between(-2, 2)
 967			}
 968			for i := m - 1; i >= 0; i-- {
 969				xs = append(xs, right[i])
 970				ys = append(ys, cy[i])
 971			}
 972			body.WriteString(`<path d="`)
 973			openPath(body, xs, ys)
 974			if d.intrusion == iSwarm {
 975				body.WriteString(`z" fill="` + quartz + `" stroke="#6a5f55"/>`)
 976			} else {
 977				body.WriteString(`z" fill="` + ign + `" stroke="` + ignEdge + `" stroke-width="1.5"/>`)
 978			}
 979		}
 980	}
 981	if d.intrusion == iSill || d.intrusion == iBoth {
 982		k := imin(n-3, r.between(4, 8))
 983		bxs, bys := bx[k], by[k]
 984		i0 := r.between(2, 10)
 985		i1 := imin(len(bxs)-1, i0+r.between(12, 24))
 986		th := r.between(8, 14)
 987		var xs, ys []int
 988		for i := i0; i <= i1; i++ {
 989			xs = append(xs, bxs[i])
 990			ys = append(ys, bys[i])
 991		}
 992		for i := i1; i >= i0; i-- {
 993			xs = append(xs, bxs[i])
 994			ys = append(ys, bys[i]+th*imin(3, imin(i-i0, i1-i))/3)
 995		}
 996		if i1 > i0 {
 997			body.WriteString(`<path d="`)
 998			openPath(body, xs, ys)
 999			body.WriteString(`z" fill="` + ign + `" stroke="` + ignEdge + `"/>`)
1000		}
1001	}
1002	body.WriteString(`</g>`)
1003
1004	// the unconformity: a dashed erosion line
1005	if d.unconf {
1006		body.WriteString(`<path d="`)
1007		openPath(body, bx[s.uIdx], by[s.uIdx])
1008		body.WriteString(`" fill="none" stroke="#2a1d16" stroke-width="2.4" stroke-dasharray="10 3 2 3"/>`)
1009	}
1010
1011	// fossils
1012	fossilIn := make([]int, n)
1013	for i := range fossilIn {
1014		fossilIn[i] = -1
1015	}
1016	nfos := 0
1017	if d.fossil == fBed {
1018		nfos = 14
1019	} else if len(kinds) > 0 {
1020		nfos = r.between(3, 6)
1021	}
1022	for i := 0; i < nfos; i++ {
1023		fk := kinds[r.intn(len(kinds))]
1024		k := r.between(0, n-3)
1025		x := r.between(30, sw-30)
1026		sz0 := r.between(14, 26)
1027		rot := r.between(-40, 40)
1028		yt := s.at(k, x)
1029		gap := s.at(k+1, x) - yt
1030		if gap < 8 {
1031			continue
1032		}
1033		sz := imin(sz0, imax(8, gap-4))
1034		y := yt + gap/2
1035		body.WriteString(`<use href="#` + fossilID[fk] + `" x="` + itoa(x-sz/2) + `" y="` + itoa(y-sz/2) + `" width="` + itoa(sz) +
1036			`" height="` + itoa(sz) + `" transform="rotate(` + itoa(rot) + ` ` + itoa(x) + ` ` + itoa(y) + `)" color="` +
1037			contrast(col[k+1]) + `" opacity=".85"/>`)
1038		if fossilIn[k+1] < 0 {
1039			fossilIn[k+1] = fk
1040		}
1041	}
1042
1043	// events
1044	goldLayer, impactK := -1, -1
1045	if d.event == evImpact {
1046		impactK = r.between(1, n-4)
1047		defs.WriteString(`<path id="ib" d="`)
1048		openPath(defs, bx[impactK], by[impactK])
1049		defs.WriteString(`"/>`)
1050		body.WriteString(`<use href="#ib" fill="none" stroke="#111" stroke-width="3"/>` +
1051			`<use href="#ib" y="-4" fill="none" stroke="#c9a24a" stroke-width="1.4" stroke-dasharray="1 6" stroke-linecap="round"/>`)
1052	}
1053	if d.event == evKarst {
1054		// a chamber in the limestone: vaulted roof, flat floor with a pool, dripstones
1055		x := r.between(120, sw-120)
1056		rw := r.between(40, 64)
1057		rh := r.between(22, 34)
1058		yc := s.at(4, x) + rh + 6
1059		drip := mix(rock[lLimestone], "#ffffff", 40)
1060		st := &strings.Builder{}
1061		for xi := x - rw + 8; xi < x+rw-8; xi += r.between(6, 11) {
1062			dd := xi - x
1063			ln := r.between(3, 3+rh*(rw*rw-dd*dd)/(rw*rw*2))
1064			st.WriteString("M" + itoa(xi-1) + " " + itoa(yc-rh*(rw*rw-dd*dd)/(rw*rw)-1) + "l1 " + itoa(ln) + "l1-" + itoa(ln) + "z")
1065			if r.intn(3) == 0 {
1066				st.WriteString("M" + itoa(xi-2) + " " + itoa(yc+1) + "l2-" + itoa(ln/2+2) + "l2 " + itoa(ln/2+2) + "z")
1067			}
1068		}
1069		body.WriteString(`<path d="M` + itoa(x-rw) + ` ` + itoa(yc) + `q` + itoa(rw) + `-` + itoa(2*rh) + ` ` + itoa(2*rw) +
1070			` 0q-` + itoa(rw) + ` ` + itoa(rh/4) + `-` + itoa(2*rw) + ` 0z" fill="#1d1712"/>` +
1071			`<ellipse cx="` + itoa(x) + `" cy="` + itoa(yc+1) + `" rx="` + itoa(rw/2) + `" ry="2" fill="#4f86a6"/><path d="` +
1072			st.String() + `" fill="` + drip + `"/>`)
1073	}
1074	if d.event == evGold {
1075		defs.WriteString(`<linearGradient id="au" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f7e08a"/><stop offset=".5" stop-color="#c9952c"/><stop offset="1" stop-color="#fff2b0"/></linearGradient>`)
1076		x := r.between(80, sw-80)
1077		y := sh + 10
1078		p := &strings.Builder{}
1079		p.WriteString("M" + itoa(x) + " " + itoa(y))
1080		for i := 0; i < 14; i++ {
1081			dx := r.between(-26, 26)
1082			dy := -r.between(18, 34)
1083			p.WriteString("l" + itoa(dx) + " " + itoa(dy))
1084			x += dx
1085			y += dy
1086			if r.intn(100) < 30 {
1087				ex := r.between(-30, 30)
1088				ey := r.between(-20, 8)
1089				p.WriteString("l" + itoa(ex) + " " + itoa(ey) + "m" + itoa(-ex) + " " + itoa(-ey))
1090			}
1091		}
1092		body.WriteString(`<path d="` + p.String() + `" fill="none" stroke="url(#au)" stroke-width="3" stroke-linejoin="bevel"/>`)
1093		goldLayer = n - 1
1094	}
1095	if d.event == evOil {
1096		crest := s.at(4, s.anti)
1097		owc := crest + r.between(16, 26) // the oil-water contact is flat
1098		var xs, ys []int
1099		for x := s.anti - 140; x <= s.anti+140; x += 8 {
1100			xs = append(xs, x)
1101			ys = append(ys, imin(s.at(4, x), owc))
1102		}
1103		body.WriteString(`<path d="`)
1104		openPath(body, xs, ys)
1105		body.WriteString(`z" fill="#16130f" opacity=".88"/><path d="M` + itoa(s.anti-140) + ` ` + itoa(owc) +
1106			`h280" stroke="#4f86a6" stroke-dasharray="4 3"/>`)
1107		y := s.surfAt(s.anti)
1108		body.WriteString(`<path d="M` + itoa(s.anti-10) + ` ` + itoa(y) + `l10-46l10 46M` + itoa(s.anti-6) + ` ` + itoa(y-18) +
1109			`h12M` + itoa(s.anti-3) + ` ` + itoa(y-32) + `h6M` + itoa(s.anti) + ` ` + itoa(y) + `V` + itoa(crest+4) +
1110			`" fill="none" stroke="#2a2420" stroke-width="1.6"/>`)
1111	}
1112	if d.event == evAquifer {
1113		x := r.between(100, sw-100)
1114		y := s.surfAt(x)
1115		b := s.at(2, x) + 16
1116		well := `M` + itoa(x) + ` ` + itoa(y) + `V` + itoa(b)
1117		body.WriteString(`<path d="` + well + `" stroke="#2c2420" stroke-width="5"/><path d="` + well +
1118			`" stroke="#5e8fae" stroke-width="2" stroke-dasharray="3 5"/><path d="M` + itoa(x-12) + ` ` + itoa(y-2) +
1119			`h24v-14h-24zM` + itoa(x-14) + ` ` + itoa(y-16) + `h28l-14-10z" fill="#6b4a32"/>`)
1120	}
1121
1122	// faults: from the land surface down
1123	fl := ""
1124	for _, f := range s.faults {
1125		yt := s.surfAt(s.fx(f, sBase))
1126		fl += "M" + itoa(s.fx(f, yt)) + " " + itoa(yt) + "L" + itoa(s.fx(f, sh+10)) + " " + itoa(sh+10)
1127	}
1128	if fl != "" {
1129		body.WriteString(`<path d="` + fl + `" stroke="#21170f" stroke-width="2.2"/><path d="` + fl +
1130			`" stroke="#f0e6d6" stroke-width=".6" stroke-dasharray="6 9" stroke-opacity=".6"/>`)
1131	}
1132
1133	// the land surface
1134	body.WriteString(`<path d="`)
1135	openPath(body, sxs, s.surf)
1136	body.WriteString(`" fill="none" stroke="#3a2a1e" stroke-width="7" stroke-opacity=".55"/>`)
1137	if d.surface == sMeadow || d.surface == sForest {
1138		green := "#4d6b38"
1139		if d.surface == sMeadow {
1140			green = "#6f8a44"
1141		}
1142		body.WriteString(`<path d="`)
1143		openPath(body, sxs, offset(s.surf, 2))
1144		body.WriteString(`" fill="none" stroke="` + green + `" stroke-width="5"/>`)
1145	}
1146	if d.surface == sSnow {
1147		body.WriteString(`<path d="`)
1148		openPath(body, sxs, offset(s.surf, 3))
1149		body.WriteString(`" fill="none" stroke="#fbfbf7" stroke-width="7"/>`)
1150	}
1151	if d.surface == sMeadow || d.surface == sForest {
1152		t0 := &strings.Builder{}
1153		t1 := &strings.Builder{}
1154		var nt int
1155		if d.surface == sForest {
1156			nt = r.between(10, 18)
1157		} else {
1158			nt = r.between(2, 4)
1159		}
1160		for i := 0; i < nt; i++ {
1161			x := r.between(8, sw-8)
1162			h := r.between(16, 34)
1163			y := s.surfAt(x) + 1
1164			tr := "M" + itoa(x) + " " + itoa(y-h) + "l" + itoa(h/4) + " " + itoa(h) + "h-" + itoa(h/2) + "z"
1165			if r.intn(2) == 0 {
1166				t0.WriteString(tr)
1167			} else {
1168				t1.WriteString(tr)
1169			}
1170		}
1171		if t0.Len() > 0 {
1172			body.WriteString(`<path d="` + t0.String() + `" fill="#3f5a36"/>`)
1173		}
1174		if t1.Len() > 0 {
1175			body.WriteString(`<path d="` + t1.String() + `" fill="#536e3c"/>`)
1176		}
1177	}
1178	body.WriteString(`<use href="#L0" filter="url(#g)" opacity=".55"/>`)
1179
1180	defs.WriteString(`</defs>`)
1181	out.WriteString(defs.String())
1182	out.WriteString(`<rect width="640" height="800" fill="#f3eee4"/><g transform="translate(16 16)" clip-path="url(#cl)">`)
1183	out.WriteString(body.String())
1184	out.WriteString(`</g><rect x="16" y="16" width="480" height="768" fill="none" stroke="#2a2420" stroke-width="1.5"/><path d="`)
1185	for i := 1; i < 12; i++ {
1186		out.WriteString("M16 " + itoa(sy+64*i) + "h6")
1187	}
1188	out.WriteString(`" stroke="#2a2420"/>`)
1189
1190	// --- the stratigraphic column ---
1191	yb := make([]int, n+1)
1192	acc := 0
1193	for i := 0; i < n; i++ {
1194		yb[i] = colTop + colH*acc/total
1195		acc += thick[i]
1196	}
1197	yb[n] = colTop + colH
1198	leaders := &strings.Builder{}
1199	labels := &strings.Builder{}
1200	for i := 0; i < n; i++ {
1201		w, h := lithW[lith[i]], yb[i+1]-yb[i]
1202		box := `<rect x="512" y="` + itoa(yb[i]) + `" width="` + itoa(w) + `" height="` + itoa(h) + `" fill="`
1203		out.WriteString(box + col[i] + `"/>` + box + `url(#` + lithID[lith[i]:lith[i]+1] + `)" stroke="#2a2420" stroke-width=".6"/>`)
1204		mid := (yb[i] + yb[i+1]) / 2
1205		ly := colTop + colH*(2*i+1)/(2*n)
1206		leaders.WriteString("M" + itoa(colX+w+2) + " " + itoa(mid) + "L546 " + itoa(ly-5))
1207		labels.WriteString(`<text x="550" y="` + itoa(ly-2) + `">` + names[i] + `<tspan x="550" dy="10" font-size="7.5" fill="#7a6d60">` +
1208			itoa(ages[i]) + ` Ma · ` + liths[lith[i]].name + `</tspan></text>`)
1209		if fossilIn[i] >= 0 {
1210			out.WriteString(`<use href="#` + fossilID[fossilIn[i]] + `" x="` + itoa(colX+w/2-5) + `" y="` + itoa(mid-5) +
1211				`" width="10" height="10" color="` + contrast(col[i]) + `"/>`)
1212		}
1213	}
1214	if d.unconf {
1215		out.WriteString(`<path d="M510 ` + itoa(yb[s.uIdx+1]) + `q3-3 6 0t6 0t6 0t6 0t6 0" fill="none" stroke="#2a2420" stroke-width="1.4"/>`)
1216	}
1217	// event marks left of the column
1218	switch d.event {
1219	case evAquifer:
1220		out.WriteString(`<path d="M501 ` + itoa((yb[3]+yb[4])/2-2) + `q2-2 4 0t4 0m-8 4q2-2 4 0t4 0" fill="none" stroke="#3f7fa8" stroke-width="1.2"/>`)
1221	case evKarst:
1222		out.WriteString(`<path d="M501 ` + itoa((yb[5]+yb[6])/2+3) + `q4-9 8 0z" fill="#1d1712"/>`)
1223	case evOil:
1224		out.WriteString(`<path d="M505 ` + itoa((yb[5]+yb[6])/2-5) + `q5 6 0 9q-5-3 0-9z" fill="#16130f"/>`)
1225	}
1226	if goldLayer >= 0 {
1227		out.WriteString(`<path d="M505 ` + itoa((yb[goldLayer]+yb[goldLayer+1])/2-4) + `l3 4-3 4-3-4z" fill="#c9952c" stroke="#6a4a12" stroke-width=".6"/>`)
1228	}
1229	if impactK >= 0 {
1230		y := yb[impactK+1]
1231		out.WriteString(`<path d="M509 ` + itoa(y) + `h34" stroke="#111" stroke-width="2.4"/><text x="499" y="` + itoa(y+2) +
1232			`" font-family="Georgia, serif" font-size="6" fill="#111">Ir</text>`)
1233	}
1234	out.WriteString(`<path d="` + leaders.String() + `" fill="none" stroke="#8a7d70" stroke-width=".6"/>`)
1235	out.WriteString(`<g font-family="Georgia, serif" font-size="9.5" fill="#2a2420"><text x="512" y="38" font-size="14">Section ` + tid +
1236		`</text><text x="512" y="53" font-size="9" font-style="italic" fill="#6a5f55">` + eras[d.era].name +
1237		`</text><text x="512" y="66" font-size="7.5" fill="#7a6d60">` + itoa(n) + ` formations · ` + itoa(ages[0]) + `–` +
1238		itoa(ages[n-1]) + ` Ma</text>`)
1239	out.WriteString(labels.String())
1240	out.WriteString(`<path d="M512 766h50M512 762v8M537 764v4M562 762v8" stroke="#2a2420" stroke-width="1.2"/>` +
1241		`<text x="512" y="782" font-size="7.5">0 · 100 m</text><text x="628" y="782" font-size="7" font-style="italic" text-anchor="end" fill="#8a7d70">Derin Zaman</text></g></svg>`)
1242	return out.String()
1243}
1244
1245func offset(ys []int, d int) []int {
1246	o := make([]int, len(ys))
1247	for i, y := range ys {
1248		o[i] = y - d
1249	}
1250	return o
1251}