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

23.98 Kb · 885 lines
  1// Package strata is a Sinopia engine: cross-sections of an invented earth.
  2// Sediment beds are folded by a two-term integer sine field and cut by
  3// faults (each fault block shows the same bed drawing shifted by its throw
  4// inside a clip polygon), crossed by dikes and sills, sometimes truncated by
  5// an angular unconformity. Beds are drawn top to bottom and each is filled
  6// from its top surface down, so a bed costs one curve.
  7//
  8// The RNG stream, tables, draw order and geometry are the prototype's
  9// (koleksiyon-fikirleri/strata/strata.py) for empty params; the only output
 10// change is that curves are written with relative steps (same points, ~20%
 11// fewer bytes, so less render and allowlist gas). The pre-change port was
 12// checked byte for byte against the prototype on 2,011 seeds. Pure integer
 13// maths: no floats, no time, no block data.
 14package strata
 15
 16import (
 17	"errors"
 18	"strconv"
 19	"strings"
 20
 21	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
 22)
 23
 24// traitTypes in the order Traits returns them.
 25var traitTypes = []string{"Era", "Section", "Folding", "Faults", "Intrusion", "Bedding", "Unconformity", "Fossil", "Rarity"}
 26
 27// MaxSVGBytes: the largest output measured is 17,083 B (3,000 seeds x the
 28// heaviest params; 15,657 B over 3,000 default seeds, docs/engines/strata.md);
 29// this leaves ~1.4x.
 30const MaxSVGBytes = 24576
 31
 32// ParamsSchema is the Studio form. "Any" (the default) leaves the trait to
 33// the seed; any other value fixes it for the whole collection. Params are
 34// the canonical JSON Studio sends (all four keys, schema order), or "".
 35const ParamsSchema = `{"type":"object","properties":{` +
 36	`"era":{"type":"string","title":"Era (palette)","enum":["Any","Sinopia Redbeds","Ochre Coast","Painted Desert","Chalk Cliff","Terra Verde","Basalt Coast","Lapis Vein"],"default":"Any"},` +
 37	`"section":{"type":"string","title":"Section","enum":["Any","Cliff","Outcrop","Cores"],"default":"Any"},` +
 38	`"bedding":{"type":"string","title":"Bedding","enum":["Any","Massive","Bedded","Laminated"],"default":"Any"},` +
 39	`"folding":{"type":"string","title":"Folding","enum":["Any","Flat","Gentle","Folded","Contorted"],"default":"Any"}}}`
 40
 41// Manifest describes the engine. Author and FeeBps are set by the adapter
 42// realm that registers it.
 43func Manifest() engine.Manifest {
 44	return engine.Manifest{
 45		Name:         "Strata",
 46		Version:      "1.0.0",
 47		Description:  "Cross-sections of an invented earth: folded red beds, faults, dikes and unconformities in earth pigments.",
 48		License:      "TBD",
 49		ParamsSchema: ParamsSchema,
 50		TraitTypes:   append([]string{}, traitTypes...),
 51		Living:       false,
 52		MaxSVGBytes:  MaxSVGBytes,
 53	}
 54}
 55
 56// ValidateParams accepts "" and the canonical params JSON only.
 57func ValidateParams(params string) error {
 58	_, err := parseParams(params)
 59	return err
 60}
 61
 62// Traits returns the nine traits of in.Seed under in.Params, in TraitTypes
 63// order. It never renders.
 64func Traits(in engine.Input) []engine.Trait {
 65	t := TraitsWith(in.Seed, in.Params)
 66	return []engine.Trait{
 67		{Type: "Era", Value: t.Era},
 68		{Type: "Section", Value: t.Section},
 69		{Type: "Folding", Value: t.Folding},
 70		{Type: "Faults", Value: t.Faults},
 71		{Type: "Intrusion", Value: t.Intrusion},
 72		{Type: "Bedding", Value: t.Bedding},
 73		{Type: "Unconformity", Value: t.Unconformity},
 74		{Type: "Fossil", Value: t.Fossil},
 75		{Type: "Rarity", Value: t.Rarity},
 76	}
 77}
 78
 79// Render returns the raw SVG for in.Seed under in.Params.
 80func Render(in engine.Input) string { return SVGWith(in.Seed, in.Params) }
 81
 82// ---------------------------------------------------------------------------
 83// Params
 84// ---------------------------------------------------------------------------
 85
 86// params holds a fixed table index per overridable trait, -1 = by seed.
 87type params struct {
 88	era, section, bedding, folding int
 89}
 90
 91var paramKeys = []string{"era", "section", "bedding", "folding"}
 92
 93// paramLeads[i] is the canonical text before the i-th value.
 94var paramLeads = []string{`{"era":"`, `,"section":"`, `,"bedding":"`, `,"folding":"`}
 95
 96func parseParams(s string) (params, error) {
 97	p := params{-1, -1, -1, -1}
 98	if s == "" {
 99		return p, nil
100	}
101	tables := [][]option{eras, sections, beddings, foldings}
102	got := []int{-1, -1, -1, -1}
103	rest := s
104	for i, k := range paramKeys {
105		lead := paramLeads[i]
106		if !strings.HasPrefix(rest, lead) {
107			return p, errors.New("strata params: want canonical JSON {\"era\",\"section\",\"bedding\",\"folding\"}")
108		}
109		rest = rest[len(lead):]
110		j := strings.IndexByte(rest, '"')
111		if j < 0 {
112			return p, errors.New("strata params: unterminated value for " + k)
113		}
114		v := rest[:j]
115		rest = rest[j+1:]
116		if v == "Any" {
117			continue
118		}
119		idx := -1
120		for n, o := range tables[i] {
121			if o.name == v {
122				idx = n
123				break
124			}
125		}
126		if idx < 0 {
127			return p, errors.New("strata params: unknown " + k + " value")
128		}
129		got[i] = idx
130	}
131	if rest != "}" {
132		return p, errors.New("strata params: trailing data")
133	}
134	return params{got[0], got[1], got[2], got[3]}, nil
135}
136
137func mustParams(s string) params {
138	p, err := parseParams(s)
139	if err != nil {
140		panic(err.Error())
141	}
142	return p
143}
144
145// ---------------------------------------------------------------------------
146// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Genesis).
147// ---------------------------------------------------------------------------
148
149const (
150	fnvOffset uint64 = 14695981039346656037
151	fnvPrime  uint64 = 1099511628211
152)
153
154type rng struct {
155	state uint64
156}
157
158func newRNG(seed string) *rng {
159	h := fnvOffset
160	for i := 0; i < len(seed); i++ {
161		h ^= uint64(seed[i])
162		h *= fnvPrime
163	}
164	if h == 0 {
165		h = fnvPrime
166	}
167	return &rng{state: h}
168}
169
170func (r *rng) next() uint64 {
171	r.state += 0x9E3779B97F4A7C15
172	z := r.state
173	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
174	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
175	return z ^ (z >> 31)
176}
177
178// n returns a value in [0, k).
179func (r *rng) n(k int) int {
180	if k <= 0 {
181		return 0
182	}
183	return int(r.next() % uint64(k))
184}
185
186// rr returns a value in [a, b].
187func (r *rng) rr(a, b int) int { return a + r.n(b-a+1) }
188
189// ---------------------------------------------------------------------------
190// Weighted trait tables. Weights sum to 100, so a weight reads as a percent.
191// lo/hi are the art ranges a trait sets (bed count, fold amplitude, faults).
192// ---------------------------------------------------------------------------
193
194type option struct {
195	name   string
196	weight int
197	score  int // contribution to the rarity score
198	lo, hi int
199}
200
201func pick(r *rng, table []option) int {
202	total := 0
203	for _, o := range table {
204		total += o.weight
205	}
206	x := r.n(total)
207	for i, o := range table {
208		x -= o.weight
209		if x < 0 {
210			return i
211		}
212	}
213	return len(table) - 1
214}
215
216var eras = []option{
217	{"Sinopia Redbeds", 22, 0, 0, 0},
218	{"Ochre Coast", 18, 0, 0, 0},
219	{"Painted Desert", 16, 0, 0, 0},
220	{"Chalk Cliff", 14, 1, 0, 0},
221	{"Terra Verde", 12, 1, 0, 0},
222	{"Basalt Coast", 12, 1, 0, 0},
223	{"Lapis Vein", 6, 3, 0, 0},
224}
225
226var eraCols = [][]string{
227	{"#8e3b25", "#b4573a", "#d08a5c", "#e8c4a0", "#6e2a1c", "#c9a27a"},
228	{"#c8962e", "#e3c27a", "#a8692e", "#f0dfb8", "#7a4a22", "#d6a85a"},
229	{"#b5523b", "#e0a07a", "#efd8b8", "#8c5a7a", "#c97a4a", "#6a3a4a"},
230	{"#efeadf", "#d8d2c4", "#bfb6a3", "#f7f4ec", "#8e8676", "#e4ddce"},
231	{"#6f7a55", "#9aa27a", "#c4c39a", "#4e573c", "#d9d3b0", "#8a8458"},
232	{"#2a2a2c", "#45403c", "#6a625a", "#8d8378", "#1a1a1b", "#b0a898"},
233	{"#2c3340", "#3d4757", "#56657a", "#1f2430", "#7a8aa0", "#2b4fa8"},
234}
235
236var eraDark = []string{"#2a2a2c", "#3a3a3a", "#2a2622", "#3a3a3a", "#2a2a2c", "#e8e2d4", "#e8d9a8"}
237
238var sections = []option{
239	{"Cliff", 45, 0, 0, 0},
240	{"Outcrop", 35, 0, 0, 0},
241	{"Cores", 20, 1, 0, 0},
242}
243
244var foldings = []option{
245	{"Flat", 22, 0, 0, 10},
246	{"Gentle", 36, 0, 20, 60},
247	{"Folded", 28, 1, 70, 130},
248	{"Contorted", 14, 2, 140, 210},
249}
250
251var faultsT = []option{
252	{"0", 38, 0, 0, 0},
253	{"1", 34, 0, 1, 0},
254	{"2", 20, 1, 2, 0},
255	{"3", 8, 2, 3, 0},
256}
257
258var intrusions = []option{
259	{"None", 52, 0, 0, 0},
260	{"Dike", 20, 1, 0, 0},
261	{"Sill", 14, 1, 0, 0},
262	{"Dike & Sill", 8, 2, 0, 0},
263	{"Vein Swarm", 6, 3, 0, 0},
264}
265
266var beddings = []option{
267	{"Massive", 25, 0, 7, 10},
268	{"Bedded", 50, 0, 12, 18},
269	{"Laminated", 25, 1, 22, 30},
270}
271
272var unconfs = []option{
273	{"None", 84, 0, 0, 0},
274	{"Angular", 16, 2, 0, 0},
275}
276
277var fossils = []option{
278	{"None", 88, 0, 0, 0},
279	{"Ammonite", 12, 2, 0, 0},
280}
281
282// Rarity cut-offs on the summed score (20,000-seed simulation, empty params):
283// Common 39.9% / Uncommon 37.7% / Rare 17.6% / Legendary 4.2% / Mythic 0.6%.
284const (
285	scoreMythic    = 9
286	scoreLegendary = 7
287	scoreRare      = 5
288	scoreUncommon  = 3
289)
290
291// TraitSet is the decoded properties of a seed. The SVG builder and the
292// trait list both read it, so picture and metadata cannot disagree.
293type TraitSet struct {
294	Era          string
295	Section      string
296	Folding      string
297	Faults       string
298	Intrusion    string
299	Bedding      string
300	Unconformity string
301	Fossil       string
302	Score        int
303	Rarity       string
304}
305
306type derived struct {
307	era, section, folding, faults, intrusion, bedding, unconf, fossil int
308}
309
310// derive draws every trait from seed+"|traits" in the prototype's order,
311// then applies the params. Forced traits are still drawn, so fixing one
312// trait never shifts the others.
313func derive(seed string, p params) derived {
314	r := newRNG(seed + "|traits")
315	d := derived{
316		era:       pick(r, eras),
317		section:   pick(r, sections),
318		folding:   pick(r, foldings),
319		faults:    pick(r, faultsT),
320		intrusion: pick(r, intrusions),
321		bedding:   pick(r, beddings),
322		unconf:    pick(r, unconfs),
323		fossil:    pick(r, fossils),
324	}
325	if p.era >= 0 {
326		d.era = p.era
327	}
328	if p.section >= 0 {
329		d.section = p.section
330	}
331	if p.bedding >= 0 {
332		d.bedding = p.bedding
333	}
334	if p.folding >= 0 {
335		d.folding = p.folding
336	}
337	return d
338}
339
340func (d derived) traitSet() TraitSet {
341	t := TraitSet{
342		Era:          eras[d.era].name,
343		Section:      sections[d.section].name,
344		Folding:      foldings[d.folding].name,
345		Faults:       faultsT[d.faults].name,
346		Intrusion:    intrusions[d.intrusion].name,
347		Bedding:      beddings[d.bedding].name,
348		Unconformity: unconfs[d.unconf].name,
349		Fossil:       fossils[d.fossil].name,
350	}
351	score := eras[d.era].score + sections[d.section].score + foldings[d.folding].score +
352		faultsT[d.faults].score + intrusions[d.intrusion].score + beddings[d.bedding].score +
353		unconfs[d.unconf].score + fossils[d.fossil].score
354	t.Score = score
355	switch {
356	case score >= scoreMythic:
357		t.Rarity = "Mythic"
358	case score >= scoreLegendary:
359		t.Rarity = "Legendary"
360	case score >= scoreRare:
361		t.Rarity = "Rare"
362	case score >= scoreUncommon:
363		t.Rarity = "Uncommon"
364	default:
365		t.Rarity = "Common"
366	}
367	return t
368}
369
370// TraitsOf returns the traits of a seed under default params.
371func TraitsOf(seed string) TraitSet { return derive(seed, params{-1, -1, -1, -1}).traitSet() }
372
373// TraitsWith returns the traits of a seed under params; it panics on
374// params ValidateParams rejects.
375func TraitsWith(seed, ps string) TraitSet { return derive(seed, mustParams(ps)).traitSet() }
376
377// TraitString is "Type=Value;..." in TraitTypes order (golden vectors).
378func TraitString(seed, ps string) string {
379	t := TraitsWith(seed, ps)
380	vals := []string{t.Era, t.Section, t.Folding, t.Faults, t.Intrusion, t.Bedding, t.Unconformity, t.Fossil, t.Rarity}
381	var b strings.Builder
382	for i, v := range vals {
383		if i > 0 {
384			b.WriteString(";")
385		}
386		b.WriteString(traitTypes[i])
387		b.WriteString("=")
388		b.WriteString(v)
389	}
390	return b.String()
391}
392
393// ---------------------------------------------------------------------------
394// Integer trigonometry: a quarter-wave table, 256 steps per turn, x1024.
395// ---------------------------------------------------------------------------
396
397var quarter = []int{0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460,
398	483, 505, 526, 548, 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822,
399	837, 851, 865, 878, 891, 903, 915, 926, 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009,
400	1013, 1016, 1019, 1021, 1023, 1024, 1024}
401
402func isin(a int) int {
403	a %= 256 // Euclidean, as the prototype's Python %
404	if a < 0 {
405		a += 256
406	}
407	switch {
408	case a < 64:
409		return quarter[a]
410	case a < 128:
411		return quarter[128-a]
412	case a < 192:
413		return -quarter[a-128]
414	}
415	return -quarter[256-a]
416}
417
418func icos(a int) int { return isin(a + 64) }
419
420// ---------------------------------------------------------------------------
421// Drawing
422// ---------------------------------------------------------------------------
423
424const (
425	canvas = 1000
426	step   = 25
427	npts   = canvas/step + 1 // 41 sample columns, x = 0, 25, ... 1000
428)
429
430const hexDigits = "0123456789abcdef"
431
432func hexVal(c byte) int {
433	if c >= 'a' {
434		return int(c-'a') + 10
435	}
436	return int(c - '0')
437}
438
439// shade adds d to each channel of "#rrggbb", clamped to 0..255.
440func shade(c string, d int) string {
441	out := []byte{'#', 0, 0, 0, 0, 0, 0}
442	for i := 0; i < 3; i++ {
443		v := hexVal(c[1+2*i])*16 + hexVal(c[2+2*i]) + d
444		if v < 0 {
445			v = 0
446		}
447		if v > 255 {
448			v = 255
449		}
450		out[1+2*i] = hexDigits[v/16]
451		out[2+2*i] = hexDigits[v%16]
452	}
453	return string(out)
454}
455
456type art struct {
457	b    strings.Builder
458	tilt int
459	p2   int
460}
461
462func (a *art) curve(base, amp, ph, fr1, fr2 int) []int {
463	ys := make([]int, npts)
464	amp3 := amp / 3
465	for i := 0; i < npts; i++ {
466		x := i * step
467		y := base + a.tilt*(x-500)/1000
468		y += amp * isin(fr1*x*256/2000+ph) / 1024
469		y += amp3 * isin(fr2*x*256/2000+a.p2) / 1024
470		ys[i] = y
471	}
472	return ys
473}
474
475func wInt(b *strings.Builder, n int) { b.WriteString(strconv.Itoa(n)) }
476
477func wPt(b *strings.Builder, x, y int) {
478	b.WriteString(strconv.Itoa(x))
479	b.WriteString(" ")
480	b.WriteString(strconv.Itoa(y))
481}
482
483// wRel writes the relative pairs "dx dy dx dy..." that follow an `l`
484// between consecutive ys; a negative dy needs no separator.
485func wRel(b *strings.Builder, ys []int, dx string) {
486	for i := 1; i < len(ys); i++ {
487		if i > 1 {
488			b.WriteString(" ")
489		}
490		b.WriteString(dx)
491		d := ys[i] - ys[i-1]
492		if d >= 0 {
493			b.WriteString(" ")
494		}
495		b.WriteString(strconv.Itoa(d))
496	}
497}
498
499// wPts writes a full curve from x = 0: the absolute first point, then
500// relative 25 px steps (same geometry as absolute points, ~20% fewer bytes).
501func wPts(b *strings.Builder, ys []int) {
502	b.WriteString("0 ")
503	b.WriteString(strconv.Itoa(ys[0]))
504	b.WriteString("l")
505	wRel(b, ys, "25")
506}
507
508// wRibbon writes the closed shape from a curve down past the canvas.
509func wRibbon(b *strings.Builder, ys []int) {
510	b.WriteString("M-400 2400L-400 ")
511	wInt(b, ys[0])
512	b.WriteString("L")
513	wPts(b, ys)
514	b.WriteString("L1400 ")
515	wInt(b, ys[len(ys)-1])
516	b.WriteString("L1400 2400Z")
517}
518
519// SVG renders a seed under default params.
520func SVG(seed string) string { return render(seed, params{-1, -1, -1, -1}) }
521
522// SVGWith renders a seed under params; it panics on params ValidateParams
523// rejects.
524func SVGWith(seed, ps string) string { return render(seed, mustParams(ps)) }
525
526func render(seed string, p params) string {
527	d := derive(seed, p)
528	r := newRNG(seed + "|art")
529	cols, dark := eraCols[d.era], eraDark[d.era]
530	eraName := eras[d.era].name
531	section := sections[d.section].name
532
533	nb := r.rr(beddings[d.bedding].lo, beddings[d.bedding].hi)
534	amp := r.rr(foldings[d.folding].lo, foldings[d.folding].hi)
535	f1 := r.rr(2, 5)
536	f2 := r.rr(6, 14)
537	p1 := r.n(256)
538	p2 := r.n(256)
539	tilt := r.rr(-160, 160)
540	a := &art{tilt: tilt, p2: p2}
541	top := -260
542	if section == "Outcrop" {
543		top = 230
544	}
545	span := 1300 - top
546
547	// bed colours walk the palette with occasional repeats (cyclothems)
548	seqc := make([]string, nb+1)
549	for k := 0; k <= nb; k++ {
550		m := r.rr(1, 3)
551		seqc[k] = cols[(k*m+r.n(2))%len(cols)]
552	}
553	patt := make([]int, nb+1) // 0,1 plain; 2 sandstone, 3 shale, 4 conglomerate
554	for k := 0; k <= nb; k++ {
555		patt[k] = r.n(5)
556	}
557	thick := make([]int, nb)
558	tsum := 0
559	for k := 0; k < nb; k++ {
560		thick[k] = r.rr(4, 14)
561		tsum += thick[k]
562	}
563	beds := make([][]int, nb)
564	acc := 0
565	for k := 0; k < nb; k++ {
566		base := top + span*acc/tsum
567		if k == 0 {
568			base -= 300
569		}
570		acc += thick[k]
571		ak := amp + amp*k/(nb*2) // deeper beds fold more
572		beds[k] = a.curve(base, ak, p1+k*r.rr(0, 3), f1, f2)
573	}
574
575	b := &a.b
576	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000" width="1000" height="1000"><defs>`)
577	b.WriteString(`<pattern id="s" width="12" height="12" patternUnits="userSpaceOnUse"><circle cx="3" cy="3" r="1.4" fill="#000" opacity=".22"/>` +
578		`<circle cx="9" cy="8" r="1" fill="#fff" opacity=".25"/></pattern>`)
579	b.WriteString(`<pattern id="h" width="40" height="7" patternUnits="userSpaceOnUse"><path d="M0 3.5H28" stroke="#000" stroke-width="1.2" opacity=".2"/></pattern>`)
580	b.WriteString(`<pattern id="c" width="34" height="30" patternUnits="userSpaceOnUse"><ellipse cx="9" cy="9" rx="7" ry="5" fill="#fff" opacity=".22"/>` +
581		`<ellipse cx="25" cy="22" rx="5" ry="4" fill="#000" opacity=".18"/></pattern>`)
582
583	// g: the block drawing (beds, unconformity, intrusions, fossil), shown
584	// once per fault block through <use>.
585	g := &strings.Builder{}
586	for k := 0; k < nb; k++ {
587		col := seqc[k]
588		g.WriteString(`<g fill="`)
589		g.WriteString(col)
590		g.WriteString(`"><path id="r`)
591		wInt(g, k)
592		g.WriteString(`" d="`)
593		wRibbon(g, beds[k])
594		g.WriteString(`" stroke="`)
595		g.WriteString(shade(col, -45))
596		g.WriteString(`" stroke-width="2"/></g>`)
597		if patt[k] >= 2 {
598			g.WriteString(`<use href="#r`)
599			wInt(g, k)
600			g.WriteString(`" fill="url(#`)
601			g.WriteString("shc"[patt[k]-2 : patt[k]-1])
602			g.WriteString(`)"/>`)
603		}
604	}
605	if unconfs[d.unconf].name == "Angular" {
606		ey := top + span*r.rr(28, 42)/100
607		ea := r.rr(8, 20)
608		eph := r.n(256)
609		er := a.curve(ey, ea, eph, 1, 3)
610		b.WriteString(`<clipPath id="u"><path d="`)
611		wRibbon(b, er)
612		b.WriteString(`"/></clipPath>`)
613		ng := r.rr(3, 6)
614		ng2 := &strings.Builder{}
615		for k := 0; k < ng; k++ {
616			fy := top - 300
617			if k > 0 {
618				fy = top + (ey-top)*k/ng
619			}
620			fc := make([]int, 11)
621			for i := 0; i < 11; i++ {
622				fc[i] = fy + tilt*(i*100-500)/4000
623			}
624			ng2.WriteString(`<path d="M-400 2400L-400 `)
625			wInt(ng2, fc[0])
626			ng2.WriteString("L")
627			for i, y := range fc {
628				if i > 0 {
629					ng2.WriteString("L")
630				}
631				wPt(ng2, i*100, y)
632			}
633			ng2.WriteString("L1400 ")
634			wInt(ng2, fc[10])
635			ng2.WriteString(`L1400 2400Z" fill="`)
636			ng2.WriteString(cols[(k*2+1)%len(cols)])
637			ng2.WriteString(`"/>`)
638		}
639		ng2.WriteString(`<g clip-path="url(#u)">`)
640		ng2.WriteString(g.String())
641		ng2.WriteString(`</g><path d="M`)
642		wPts(ng2, er)
643		ng2.WriteString(`" fill="none" stroke="`)
644		ng2.WriteString(dark)
645		ng2.WriteString(`" stroke-width="3" opacity=".6"/>`)
646		g = ng2
647	}
648
649	// intrusions belong to the block before faulting
650	intr := intrusions[d.intrusion].name
651	if intr == "Sill" || intr == "Dike & Sill" {
652		k := r.rr(2, nb-2)
653		c := beds[k]
654		th := r.rr(18, 40)
655		g.WriteString(`<path d="M`)
656		wPts(g, c)
657		g.WriteString("L1000 ")
658		wInt(g, c[npts-1]+th)
659		g.WriteString("l")
660		back := make([]int, npts)
661		for i := range back {
662			back[i] = c[npts-1-i]
663		}
664		wRel(g, back, "-25")
665		g.WriteString(`Z" fill="`)
666		g.WriteString(dark)
667		g.WriteString(`"/>`)
668	}
669	if intr == "Dike" || intr == "Dike & Sill" {
670		x0 := r.rr(150, 850)
671		dx := r.rr(-200, 200)
672		w := r.rr(24, 60)
673		g.WriteString(`<path d="M`)
674		wInt(g, x0)
675		g.WriteString(` -400L`)
676		wInt(g, x0+w)
677		g.WriteString(` -400L`)
678		wInt(g, x0+w+dx)
679		g.WriteString(` 1400L`)
680		wInt(g, x0+dx)
681		g.WriteString(` 1400Z" fill="`)
682		g.WriteString(dark)
683		g.WriteString(`"/>`)
684	}
685	if intr == "Vein Swarm" {
686		g.WriteString(`<path d="`)
687		nv := r.rr(10, 18)
688		for v := 0; v < nv; v++ {
689			x := r.rr(0, canvas)
690			y := r.rr(0, canvas)
691			g.WriteString("M")
692			wPt(g, x, y)
693			g.WriteString("l")
694			wPt(g, r.rr(-60, 60), r.rr(-200, 200))
695			g.WriteString("l")
696			wPt(g, r.rr(-40, 40), r.rr(-120, 120))
697		}
698		g.WriteString(`" fill="none" stroke="`)
699		if eraName == "Lapis Vein" {
700			g.WriteString(cols[5])
701		} else {
702			g.WriteString("#f4efe4")
703		}
704		g.WriteString(`" stroke-width="3" opacity=".85"/>`)
705	}
706	if fossils[d.fossil].name == "Ammonite" {
707		k := r.rr(2, nb-1)
708		c := beds[k]
709		i := r.rr(6, npts-7)
710		fx := i * step
711		fy := c[i] + r.rr(30, 60)
712		path := &strings.Builder{}
713		ribs := &strings.Builder{}
714		path.WriteString("M")
715		wPt(path, fx, fy)
716		rad, ang := 2, 0
717		for rad < 46 {
718			ang += 12
719			rad++
720			px := fx + icos(ang)*rad/1024
721			py := fy + isin(ang)*rad/1024
722			path.WriteString("L")
723			wPt(path, px, py)
724			if ang%24 == 0 && rad > 12 {
725				ribs.WriteString("M")
726				wPt(ribs, px, py)
727				ribs.WriteString("L")
728				wPt(ribs, fx+icos(ang)*(rad-9)/1024, fy+isin(ang)*(rad-9)/1024)
729			}
730		}
731		g.WriteString(`<circle cx="`)
732		wInt(g, fx)
733		g.WriteString(`" cy="`)
734		wInt(g, fy)
735		g.WriteString(`" r="`)
736		wInt(g, rad)
737		g.WriteString(`" fill="`)
738		g.WriteString(cols[3])
739		g.WriteString(`" opacity=".9"/><path d="`)
740		g.WriteString(path.String())
741		g.WriteString(ribs.String())
742		g.WriteString(`" fill="none" stroke="`)
743		g.WriteString(dark)
744		g.WriteString(`" stroke-width="2.5"/>`)
745	}
746	b.WriteString(`<g id="b">`)
747	b.WriteString(g.String())
748	b.WriteString(`</g>`)
749
750	// fault blocks: polygons between fault lines, each with its own throw
751	nf := faultsT[d.faults].lo
752	div := nf
753	if div < 1 {
754		div = 1
755	}
756	fxs := make([]int, nf)
757	fds := make([]int, nf)
758	for k := 0; k < nf; k++ {
759		fxs[k] = r.rr(120+760*k/div, 120+760*(k+1)/div)
760		fds[k] = r.rr(-180, 180)
761	}
762	// sort by (x, throw), as the prototype's sorted() of tuples
763	for i := 1; i < nf; i++ {
764		for j := i; j > 0 && (fxs[j] < fxs[j-1] || (fxs[j] == fxs[j-1] && fds[j] < fds[j-1])); j-- {
765			fxs[j], fxs[j-1] = fxs[j-1], fxs[j]
766			fds[j], fds[j-1] = fds[j-1], fds[j]
767		}
768	}
769	throws := make([]int, nf+1)
770	px0, px1 := -10, -10 // previous fault line: top x, bottom x
771	throw := 0
772	for k := 0; k <= nf; k++ {
773		cx0, cx1 := canvas+10, canvas+10
774		if k < nf {
775			cx0, cx1 = fxs[k]+fds[k], fxs[k]-fds[k]
776		}
777		b.WriteString(`<clipPath id="f`)
778		wInt(b, k)
779		b.WriteString(`"><path d="M`)
780		wPt(b, px0, -10)
781		b.WriteString("L")
782		wPt(b, cx0, -10)
783		b.WriteString("L")
784		wPt(b, cx1, canvas+10)
785		b.WriteString("L")
786		wPt(b, px1, canvas+10)
787		b.WriteString(`Z"/></clipPath>`)
788		throws[k] = throw
789		px0, px1 = cx0, cx1
790		m := r.rr(30, 140)
791		if r.n(2) != 0 {
792			throw += m
793		} else {
794			throw -= m
795		}
796	}
797	if section == "Cores" {
798		b.WriteString(`<clipPath id="k">`)
799		writeCoreRects(b)
800		b.WriteString(`</clipPath>`)
801	}
802	var surf []int
803	if section == "Outcrop" {
804		sa := r.rr(30, 60)
805		sph := r.n(256)
806		surf = a.curve(top+20, sa, sph, 1, 2)
807		b.WriteString(`<clipPath id="o"><path d="`)
808		wRibbon(b, surf)
809		b.WriteString(`"/></clipPath>`)
810	}
811	b.WriteString(`</defs>`)
812	switch section {
813	case "Cores":
814		b.WriteString(`<rect width="1000" height="1000" fill="#ece6da"/><path d="`)
815		for k := 0; k < 4; k++ {
816			for y := 150; y < 880; y += 25 {
817				b.WriteString("M")
818				wPt(b, 80+200*k, y)
819				if y%100 == 0 {
820					b.WriteString("h14")
821				} else {
822					b.WriteString("h7")
823				}
824			}
825		}
826		b.WriteString(`" stroke="#6a6258" stroke-width="2"/><g clip-path="url(#k)">`)
827	case "Outcrop":
828		sky := "#e9e1cf"
829		if eraName == "Basalt Coast" {
830			sky = "#c9d3d8"
831		} else if eraName == "Lapis Vein" {
832			sky = "#d9dde6"
833		}
834		b.WriteString(`<rect width="1000" height="1000" fill="`)
835		b.WriteString(sky)
836		b.WriteString(`"/><circle cx="`)
837		wInt(b, r.rr(150, 850))
838		b.WriteString(`" cy="`)
839		wInt(b, r.rr(70, 150))
840		b.WriteString(`" r="`)
841		wInt(b, r.rr(34, 60))
842		b.WriteString(`" fill="#f4efe2"/><g clip-path="url(#o)">`)
843	default:
844		b.WriteString(`<g>`)
845	}
846	for k := 0; k <= nf; k++ {
847		b.WriteString(`<g clip-path="url(#f`)
848		wInt(b, k)
849		b.WriteString(`)"><use href="#b" y="`)
850		wInt(b, throws[k])
851		b.WriteString(`"/></g>`)
852	}
853	for k := 0; k < nf; k++ {
854		b.WriteString(`<path d="M`)
855		wPt(b, fxs[k]+fds[k], -10)
856		b.WriteString("L")
857		wPt(b, fxs[k]-fds[k], canvas+10)
858		b.WriteString(`" stroke="`)
859		b.WriteString(dark)
860		b.WriteString(`" stroke-width="4" opacity=".75"/>`)
861	}
862	b.WriteString(`</g>`)
863	if section == "Outcrop" {
864		b.WriteString(`<path d="M`)
865		wPts(b, surf)
866		b.WriteString(`" fill="none" stroke="#4a5a3a" stroke-width="7" stroke-linecap="round"/>`)
867	}
868	if section == "Cores" {
869		b.WriteString(`<g fill="none" stroke="#3a342c" stroke-width="3">`)
870		writeCoreRects(b)
871		b.WriteString(`</g>`)
872	}
873	b.WriteString(`</svg>`)
874	return b.String()
875}
876
877func writeCoreRects(b *strings.Builder) {
878	for k := 0; k < 4; k++ {
879		b.WriteString(`<rect x="`)
880		wInt(b, 110+200*k)
881		b.WriteString(`" y="`)
882		wInt(b, 120+30*(k%2))
883		b.WriteString(`" width="150" height="760" rx="75"/>`)
884	}
885}