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.

kilim.gno

22.47 Kb · 853 lines
  1// Package kilim is a Sinopia engine: a flat-woven rug computed cell by cell
  2// on a warp grid. Medallions are the stepped rings of an integer distance
  3// field (the grid turns every diagonal into a staircase, as on a loom), the
  4// border is a running sawtooth, diamond or stripe band, and "abrash" bands
  5// shift a dye lot mid-rug like hand-dyed wool.
  6//
  7// It is a port of the kilim prototype (Python). The RNG stream, trait
  8// tables and draw order are the prototype's; the deliberate changes are the
  9// Weaver's Flaw rule (now visible in every field), the params, and a compact
 10// SVG encoding that renders the same pixels. Python's // and % floor towards
 11// minus infinity and Go's truncate, so the lattice maths goes through
 12// floorDiv/floorMod; kilim_test.gno pins golden vectors produced by the
 13// Python reference, and frontend/src/engines/kilim.ts asserts the same ones.
 14//
 15// Pure integer maths: no floats, no time, no block data.
 16package kilim
 17
 18import (
 19	"errors"
 20	"strconv"
 21	"strings"
 22
 23	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
 24)
 25
 26// TraitTypes in the order Traits returns them.
 27var traitTypes = []string{"Dyes", "Field", "Motif", "Border", "Abrash", "Symmetry", "Fringe", "Rarity"}
 28
 29// MaxSVGBytes: the largest output over 10,000 default seeds is 8,514 B
 30// (Coarse loom: 5,984 B over 2,000 seeds x field); about 2x margin.
 31const MaxSVGBytes = 16384
 32
 33// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
 34// in this property order; ValidateParams accepts exactly that or "".
 35const ParamsSchema = `{"type":"object","properties":{` +
 36	`"dyes":{"type":"string","title":"Dyes","enum":["Seeded","Madder & Indigo","Saffron","Walnut & Bone",` +
 37	`"Pomegranate","Night Indigo","Steppe","Undyed","Sinopia Earth"],"default":"Seeded"},` +
 38	`"field":{"type":"string","title":"Field","enum":["Seeded","Medallion","Triple","Lattice","Banded","Ladder"],` +
 39	`"default":"Seeded"},` +
 40	`"loom":{"type":"string","title":"Loom","enum":["Fine","Coarse"],"default":"Fine"},` +
 41	`"abrash":{"type":"boolean","title":"Abrash dye lots","default":true}}}`
 42
 43// DefaultParams is the canonical form of the defaults; it renders exactly
 44// like "".
 45const DefaultParams = `{"dyes":"Seeded","field":"Seeded","loom":"Fine","abrash":true}`
 46
 47// Manifest describes the engine. Author and FeeBps are set by the adapter.
 48func Manifest() engine.Manifest {
 49	return engine.Manifest{
 50		Name:    "Kilim",
 51		Version: "1.0.0",
 52		Description: "A flat-woven rug computed cell by cell on the loom grid: stepped medallions from an " +
 53			"integer distance field, running borders and abrash dye-lot shifts.",
 54		License:      "TBD",
 55		ParamsSchema: ParamsSchema,
 56		TraitTypes:   append([]string{}, traitTypes...),
 57		Living:       false,
 58		MaxSVGBytes:  MaxSVGBytes,
 59	}
 60}
 61
 62// Config is a parsed params string.
 63type Config struct {
 64	Dyes   int  // -1: drawn from the seed, else an index into the dye table
 65	Field  int  // -1: drawn from the seed, else an index into the field table
 66	Coarse bool // 27 x 41 cells of 26 px instead of 37 x 55 cells of 20 px
 67	Abrash bool // false: no dye-lot bands (Abrash "None")
 68}
 69
 70// Defaults is the showcase look (params "").
 71func Defaults() Config { return Config{Dyes: -1, Field: -1, Abrash: true} }
 72
 73var errParams = errors.New(`kilim: params must be "" or ` +
 74	`{"dyes":<enum>,"field":<enum>,"loom":"Fine"|"Coarse","abrash":true|false} in that order, without spaces`)
 75
 76// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
 77func ParseParams(params string) (Config, error) {
 78	cfg := Defaults()
 79	if params == "" {
 80		return cfg, nil
 81	}
 82	v, rest, ok := strValue(params, `{"dyes":"`)
 83	if !ok {
 84		return cfg, errParams
 85	}
 86	if cfg.Dyes, ok = enumIndex(v, dyeOpts); !ok {
 87		return cfg, errParams
 88	}
 89	if v, rest, ok = strValue(rest, `","field":"`); !ok {
 90		return cfg, errParams
 91	}
 92	if cfg.Field, ok = enumIndex(v, fieldOpts); !ok {
 93		return cfg, errParams
 94	}
 95	if v, rest, ok = strValue(rest, `","loom":"`); !ok {
 96		return cfg, errParams
 97	}
 98	switch v {
 99	case "Fine":
100	case "Coarse":
101		cfg.Coarse = true
102	default:
103		return cfg, errParams
104	}
105	switch rest {
106	case `","abrash":true}`:
107	case `","abrash":false}`:
108		cfg.Abrash = false
109	default:
110		return cfg, errParams
111	}
112	return cfg, nil
113}
114
115// strValue expects s to start with prefix and returns the text up to the
116// next '"' and the remainder starting at that quote.
117func strValue(s, prefix string) (string, string, bool) {
118	if !strings.HasPrefix(s, prefix) {
119		return "", "", false
120	}
121	s = s[len(prefix):]
122	end := strings.IndexByte(s, '"')
123	if end < 0 {
124		return "", "", false
125	}
126	return s[:end], s[end:], true
127}
128
129func enumIndex(v string, table []option) (int, bool) {
130	if v == "Seeded" {
131		return -1, true
132	}
133	for i, o := range table {
134		if o.name == v {
135			return i, true
136		}
137	}
138	return 0, false
139}
140
141// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
142func ValidateParams(params string) error {
143	_, err := ParseParams(params)
144	return err
145}
146
147func mustConfig(params string) Config {
148	cfg, err := ParseParams(params)
149	if err != nil {
150		panic(err)
151	}
152	return cfg
153}
154
155// Traits returns the eight traits of in.Seed in TraitTypes order. It never
156// renders: seven table draws and a score.
157func Traits(in engine.Input) []engine.Trait {
158	t := TraitsOf(in.Seed, mustConfig(in.Params))
159	return []engine.Trait{
160		{Type: "Dyes", Value: t.Dyes},
161		{Type: "Field", Value: t.Field},
162		{Type: "Motif", Value: t.Motif},
163		{Type: "Border", Value: t.Border},
164		{Type: "Abrash", Value: t.Abrash},
165		{Type: "Symmetry", Value: t.Symmetry},
166		{Type: "Fringe", Value: t.Fringe},
167		{Type: "Rarity", Value: t.Rarity},
168	}
169}
170
171// Render returns the raw SVG for in.Seed and in.Params.
172func Render(in engine.Input) string { return SVG(in.Seed, mustConfig(in.Params)) }
173
174// ---------------------------------------------------------------------------
175// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Genesis's
176// stream). Traits use seed+"|traits", the art seed+"|art".
177// ---------------------------------------------------------------------------
178
179type rng struct{ state uint64 }
180
181func newRNG(seed string) *rng {
182	h := uint64(14695981039346656037)
183	for i := 0; i < len(seed); i++ {
184		h ^= uint64(seed[i])
185		h *= 1099511628211
186	}
187	if h == 0 {
188		h = 1099511628211
189	}
190	return &rng{state: h}
191}
192
193func (r *rng) next() uint64 {
194	r.state += 0x9E3779B97F4A7C15
195	z := r.state
196	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
197	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
198	return z ^ (z >> 31)
199}
200
201// intn is in [0, n); one draw whenever n > 0.
202func (r *rng) intn(n int) int {
203	if n <= 0 {
204		return 0
205	}
206	return int(r.next() % uint64(n))
207}
208
209// between is in [a, b].
210func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
211
212// ---------------------------------------------------------------------------
213// Trait tables. A weight is a percent; score feeds the rarity tier.
214// ---------------------------------------------------------------------------
215
216type option struct {
217	name   string
218	weight int
219	score  int
220}
221
222func pick(r *rng, table []option) int {
223	total := 0
224	for _, o := range table {
225		total += o.weight
226	}
227	x := r.intn(total)
228	for i, o := range table {
229		x -= o.weight
230		if x < 0 {
231			return i
232		}
233	}
234	return len(table) - 1
235}
236
237var dyeOpts = []option{
238	{"Madder & Indigo", 22, 0}, {"Saffron", 15, 0}, {"Walnut & Bone", 15, 0}, {"Pomegranate", 14, 0},
239	{"Night Indigo", 12, 1}, {"Steppe", 10, 1}, {"Undyed", 7, 2}, {"Sinopia Earth", 5, 3},
240}
241
242// palettes: 0 ground, 1..3 motif dyes, 4 dark outline, 5 light.
243var palettes = [][]string{
244	{"#9e2a22", "#1f2f5a", "#d9a441", "#4a7a6a", "#2a1712", "#ecdfc2"},
245	{"#d6962a", "#7a1f1f", "#2c3d5c", "#4f6b3a", "#3a2416", "#f1e4c6"},
246	{"#5a4030", "#a0806a", "#c49a5a", "#2b211b", "#1d1611", "#e9dfc8"},
247	{"#b2343b", "#3d5a4a", "#e0a35a", "#5a2a4a", "#2e1c22", "#f0e2cc"},
248	{"#1c2848", "#c23b2e", "#6b8fb0", "#d9a441", "#0b1020", "#e5d8b8"},
249	{"#4f6b3a", "#d9b45a", "#8c2f23", "#2c3d5c", "#1f2618", "#efe6cf"},
250	{"#e2d8c3", "#8a7c66", "#b8ab94", "#5e5346", "#3a332b", "#f3ede0"},
251	{"#8f3a26", "#c5643f", "#e8c49a", "#5e2a1a", "#3a150e", "#f4e6cf"},
252}
253
254const (
255	fieldMedallion = iota
256	fieldTriple
257	fieldLattice
258	fieldBanded
259	fieldLadder
260)
261
262var fieldOpts = []option{{"Medallion", 22, 0}, {"Triple", 22, 0}, {"Lattice", 26, 0}, {"Banded", 18, 0}, {"Ladder", 12, 1}}
263
264const (
265	motifDiamond = iota
266	motifHooked
267	motifStar
268	motifComb
269	motifEye
270)
271
272var motifOpts = []option{{"Diamond", 26, 0}, {"Hooked", 24, 0}, {"Star", 20, 0}, {"Comb", 18, 0}, {"Eye", 12, 1}}
273
274const (
275	borderSawtooth = iota
276	borderDiamonds
277	borderStripes
278	borderDouble
279	borderOpen
280)
281
282var borderOpts = []option{
283	{"Sawtooth", 32, 0}, {"Running Diamonds", 26, 0}, {"Stripes", 24, 0}, {"Double", 12, 1}, {"Open Field", 6, 3},
284}
285
286const (
287	abrashNone = iota
288	abrashFaint
289	abrashStrong
290)
291
292var abrashOpts = []option{{"None", 40, 0}, {"Faint", 40, 0}, {"Strong", 20, 1}}
293
294var symmetryOpts = []option{{"Mirrored", 82, 0}, {"Weaver's Flaw", 18, 2}}
295
296const (
297	fringeLoose = iota
298	fringeKnotted
299	fringeBound
300)
301
302var fringeOpts = []option{{"Loose", 50, 0}, {"Knotted", 38, 0}, {"Bound", 12, 1}}
303
304// Rarity tiers by score (sum of the drawn traits' scores; a trait fixed by
305// params scores 0). Over 10,000 sample seeds with default params:
306// Common 23.8% / Uncommon 47.9% / Rare 23.0% / Legendary 4.7% / Mythic 0.6%.
307const (
308	scoreMythic    = 7
309	scoreLegendary = 5
310	scoreRare      = 3
311	scoreUncommon  = 1
312)
313
314type draw struct {
315	dyes, field, motif, border, abrash, flaw, fringe int
316	score                                            int
317	rarity                                           string
318}
319
320func derive(seed string, cfg Config) draw {
321	r := newRNG(seed + "|traits")
322	// Draw order is part of the contract: changing it changes every token.
323	var d draw
324	d.dyes = pick(r, dyeOpts)
325	d.field = pick(r, fieldOpts)
326	d.motif = pick(r, motifOpts)
327	d.border = pick(r, borderOpts)
328	d.abrash = pick(r, abrashOpts)
329	d.flaw = pick(r, symmetryOpts)
330	d.fringe = pick(r, fringeOpts)
331	// Params override after the draws, so the stream never shifts.
332	score := motifOpts[d.motif].score + borderOpts[d.border].score +
333		symmetryOpts[d.flaw].score + fringeOpts[d.fringe].score
334	if cfg.Dyes >= 0 {
335		d.dyes = cfg.Dyes
336	} else {
337		score += dyeOpts[d.dyes].score
338	}
339	if cfg.Field >= 0 {
340		d.field = cfg.Field
341	} else {
342		score += fieldOpts[d.field].score
343	}
344	if !cfg.Abrash {
345		d.abrash = abrashNone
346	} else {
347		score += abrashOpts[d.abrash].score
348	}
349	d.score = score
350	switch {
351	case score >= scoreMythic:
352		d.rarity = "Mythic"
353	case score >= scoreLegendary:
354		d.rarity = "Legendary"
355	case score >= scoreRare:
356		d.rarity = "Rare"
357	case score >= scoreUncommon:
358		d.rarity = "Uncommon"
359	default:
360		d.rarity = "Common"
361	}
362	return d
363}
364
365// TraitSet is the decoded properties of a seed under a config.
366type TraitSet struct {
367	Dyes, Field, Motif, Border, Abrash, Symmetry, Fringe string
368	Score                                                int
369	Rarity                                               string
370}
371
372// TraitsOf returns the decoded traits for a seed.
373func TraitsOf(seed string, cfg Config) TraitSet {
374	d := derive(seed, cfg)
375	return TraitSet{
376		Dyes:     dyeOpts[d.dyes].name,
377		Field:    fieldOpts[d.field].name,
378		Motif:    motifOpts[d.motif].name,
379		Border:   borderOpts[d.border].name,
380		Abrash:   abrashOpts[d.abrash].name,
381		Symmetry: symmetryOpts[d.flaw].name,
382		Fringe:   fringeOpts[d.fringe].name,
383		Score:    d.score,
384		Rarity:   d.rarity,
385	}
386}
387
388// ---------------------------------------------------------------------------
389// Integer helpers. Python semantics where the prototype relied on them.
390// ---------------------------------------------------------------------------
391
392func abs(a int) int {
393	if a < 0 {
394		return -a
395	}
396	return a
397}
398
399// floorDiv and floorMod are Python's // and % (b > 0).
400func floorDiv(a, b int) int {
401	q := a / b
402	if a%b != 0 && a < 0 {
403		q--
404	}
405	return q
406}
407
408func floorMod(a, b int) int {
409	m := a % b
410	if m < 0 {
411		m += b
412	}
413	return m
414}
415
416// dist is the medallion's integer distance field (arguments >= 0 after abs,
417// so / is exact floor division here).
418func dist(motif, du, dv int) int {
419	au, av := abs(du), abs(dv)
420	switch motif {
421	case motifStar:
422		m := au
423		if av > m {
424			m = av
425		}
426		m = m * 3 / 2
427		if au+av < m {
428			return au + av
429		}
430		return m
431	case motifEye:
432		return au*3/2 + av
433	}
434	return au + av
435}
436
437// medallion returns the palette index of a ring cell, or -1 outside.
438func medallion(motif, ringw, du, dv, size int, s []int) int {
439	d := dist(motif, du, dv)
440	if d > size {
441		return -1
442	}
443	if d == size {
444		return 4
445	}
446	k := (size - d) / ringw
447	if motif == motifHooked && d >= size-2 && abs(du)%3 == 0 {
448		return 0
449	}
450	if motif == motifComb && d >= size-3 && abs(dv)%2 == 0 && abs(du) > 1 {
451		return 0
452	}
453	return s[k%len(s)]
454}
455
456// flawed is a Weaver's Flaw sequence: every dye moved one place along 1..5.
457func flawed(s []int) []int {
458	out := make([]int, len(s))
459	for i, c := range s {
460		out[i] = c%5 + 1
461	}
462	return out
463}
464
465func shade(col string, d int) string {
466	const hexd = "0123456789abcdef"
467	out := []byte{'#', 0, 0, 0, 0, 0, 0}
468	for i := 1; i < 7; i += 2 {
469		v := unhex(col[i])*16 + unhex(col[i+1]) + d
470		if v < 0 {
471			v = 0
472		}
473		if v > 255 {
474			v = 255
475		}
476		out[i], out[i+1] = hexd[v>>4], hexd[v&15]
477	}
478	return string(out)
479}
480
481func unhex(c byte) int {
482	if c >= 'a' {
483		return int(c-'a') + 10
484	}
485	return int(c - '0')
486}
487
488// ---------------------------------------------------------------------------
489// Rendering
490// ---------------------------------------------------------------------------
491
492const (
493	ox = 30 // rug offset in px
494	oy = 80
495)
496
497// SVG renders the artwork for a seed under cfg.
498func SVG(seed string, cfg Config) string {
499	t := derive(seed, cfg)
500	C, R, cell := 37, 55, 20
501	if cfg.Coarse {
502		C, R, cell = 27, 41, 26
503	}
504	W, H := C*cell+2*ox, R*cell+2*oy
505	r := newRNG(seed + "|art") // separate stream: trait draws never shift the art
506	pal := palettes[t.dyes]
507
508	bw := 0
509	if t.border == borderDouble {
510		bw = 6
511	} else if t.border != borderOpen {
512		bw = r.between(4, 5)
513	}
514	fw, fh := C-2*bw, R-2*bw
515	seq := make([]int, r.between(3, 5))
516	for i := range seq {
517		seq[i] = r.between(1, 5)
518	}
519	seq2 := make([]int, len(seq))
520	for i := range seq2 {
521		seq2[i] = r.between(1, 5)
522	}
523	ringw := r.between(1, 2)
524	grid := make([]int, R*C)
525
526	var cu, cv, cs []int // medallion centres and sizes
527	switch t.field {
528	case fieldMedallion:
529		sz := fw/2 - 1
530		if fh/2-1 < sz {
531			sz = fh/2 - 1
532		}
533		cu, cv, cs = []int{fw / 2}, []int{fh / 2}, []int{sz}
534	case fieldTriple:
535		sz := fw/2 - 1
536		if fh/6 < sz {
537			sz = fh / 6
538		}
539		for k := 1; k <= 5; k += 2 {
540			cu, cv, cs = append(cu, fw/2), append(cv, fh*k/6), append(cs, sz)
541		}
542	case fieldLadder:
543		sz := r.between(4, 6)
544		step := 2*sz + 2
545		n := fh / step
546		off := (fh-n*step)/2 + sz + 1
547		for k := 0; k < n; k++ {
548			cu, cv, cs = append(cu, fw/2), append(cv, off+k*step), append(cs, sz)
549		}
550	}
551	flaw := -1
552	if t.flaw == 1 {
553		if t.field == fieldLattice || t.field == fieldBanded {
554			flaw = r.intn(3)
555		} else {
556			n := len(cu)
557			if n < 1 {
558				n = 1
559			}
560			flaw = r.intn(n)
561		}
562	}
563	lat := r.between(5, 7)
564	filler := r.between(5, 7)
565	band := r.between(7, 10)
566	nbands := (fh + band - 1) / band
567	seqF, seq2F := flawed(seq), flawed(seq2)
568	motif := t.motif
569
570	for v := 0; v < fh; v++ {
571		row := (v + bw) * C
572		for u := 0; u < fw; u++ {
573			c := 0
574			switch t.field {
575			case fieldMedallion, fieldTriple, fieldLadder:
576				for i := 0; i < len(cu); i++ {
577					odd := i == flaw
578					if t.field == fieldMedallion {
579						odd = flaw >= 0 && u > cu[i] && v < cv[i]
580					}
581					s := seq
582					if odd {
583						s = seq2
584					}
585					if m := medallion(motif, ringw, u-cu[i], v-cv[i], cs[i], s); m >= 0 {
586						c = m
587						break
588					}
589				}
590				if c == 0 && t.field != fieldLadder {
591					fu, fv := u%filler-filler/2, v%filler-filler/2
592					if abs(fu)+abs(fv) <= 1 {
593						near := false
594						for i := 0; i < len(cu); i++ {
595							if dist(motif, u-cu[i], v-cv[i])-cs[i] <= 2 {
596								near = true
597								break
598							}
599						}
600						if !near {
601							c = seq[len(seq)-1]
602						}
603					}
604				}
605				if t.field == fieldLadder && c == 0 && (u < 3 || u >= fw-3) && u%2 == 0 {
606					c = seq[(v/2)%len(seq)]
607				}
608			case fieldLattice:
609				p := 2 * lat
610				x, y := u-fw/2, v-fh/2
611				du, dv := floorMod(x, p)-lat, floorMod(y, p)-lat
612				odd := floorMod(floorDiv(x+lat, p)+floorDiv(y+lat, p), 2) != 0
613				isFlaw := flaw >= 0 && floorDiv(x, p) == 0 && floorDiv(y, p) == flaw-1
614				s := seq
615				if odd {
616					s = seq2
617				}
618				if isFlaw {
619					s = seqF
620					if odd {
621						s = seq2F
622					}
623				}
624				if m := medallion(motif, ringw, du, dv, lat-1, s); m >= 0 {
625					c = m
626				} else if floorMod(du+dv, 2) == 0 && abs(du) == abs(dv) {
627					c = 4
628				}
629			default: // fieldBanded
630				bi := v / band
631				dv := v%band - band/2
632				if dv == -(band / 2) {
633					c = 4
634				} else {
635					per := band - 1
636					du := (u+(bi%2)*(per/2))%per - per/2
637					s := seq
638					if bi%2 != 0 {
639						s = seq2
640					}
641					if flaw >= 0 && bi == nbands/2-1+flaw {
642						s = seqF
643						if bi%2 != 0 {
644							s = seq2F
645						}
646					}
647					if m := medallion(motif, ringw, du, dv, band/2-1, s); m >= 0 {
648						c = m
649					} else if bi%3 == 2 {
650						c = 5
651					}
652				}
653			}
654			grid[row+u+bw] = c
655		}
656	}
657
658	if bw > 0 {
659		bc0 := r.between(1, 3)
660		bc2 := r.between(1, 3)
661		bc := []int{bc0, 5, bc2}
662		for v := 0; v < R; v++ {
663			for u := 0; u < C; u++ {
664				s := u
665				if v < s {
666					s = v
667				}
668				if C-1-u < s {
669					s = C - 1 - u
670				}
671				if R-1-v < s {
672					s = R - 1 - v
673				}
674				if s >= bw {
675					continue
676				}
677				along := v
678				if s == v || s == R-1-v {
679					along = u
680				}
681				c := 0
682				switch {
683				case s == 0 || s == bw-1:
684					c = 4
685				case t.border == borderStripes:
686					c = bc[s%3]
687				case t.border == borderSawtooth || (t.border == borderDouble && s >= 3):
688					span, ss := bw-2, s-1
689					if t.border == borderDouble {
690						span, ss = 2, s-3
691					}
692					c = 5
693					if ss < abs(along%(2*span)-span) {
694						c = bc[0]
695					}
696				case t.border == borderDiamonds:
697					p := 2 * (bw - 2)
698					e := 0
699					if bw%2 == 0 {
700						e = 1
701					}
702					c = 5
703					if abs(along%p-p/2)+abs(s-(bw-1)/2-e) <= (bw-2)/2 {
704						c = bc[2]
705					}
706				default: // Double, inner stripes
707					c = bc[s%2]
708				}
709				grid[v*C+u] = c
710			}
711		}
712	}
713
714	// abrash: dye lots change in horizontal bands. Both counts are always
715	// drawn (the prototype evaluated a dict literal).
716	nFaint := r.between(1, 2)
717	nStrong := r.between(2, 3)
718	nab, amt := 0, 30
719	if t.abrash == abrashFaint {
720		nab, amt = nFaint, 14
721	} else if t.abrash == abrashStrong {
722		nab = nStrong
723	}
724	var la, lb, lc, ld []int
725	for k := 0; k < nab; k++ {
726		y0 := r.between(bw, R-bw-4)
727		la = append(la, y0)
728		lb = append(lb, y0+r.between(2, 8))
729		lc = append(lc, r.between(0, 3))
730		if r.intn(2) != 0 {
731			ld = append(ld, amt)
732		} else {
733			ld = append(ld, -amt)
734		}
735	}
736
737	// run-length rows; colours keyed by their final hex string, first-seen order
738	var cols []string
739	var counts []int
740	var ru, rv, rn, rc []int
741	for v := 0; v < R; v++ {
742		u := 0
743		for u < C {
744			c := grid[v*C+u]
745			col := pal[c]
746			for k := 0; k < len(la); k++ {
747				if la[k] <= v && v < lb[k] && lc[k] == c {
748					col = shade(col, ld[k])
749				}
750			}
751			e := u + 1
752			for e < C && grid[v*C+e] == c {
753				e++
754			}
755			ci := -1
756			for k := 0; k < len(cols); k++ {
757				if cols[k] == col {
758					ci = k
759					break
760				}
761			}
762			if ci < 0 {
763				ci = len(cols)
764				cols = append(cols, col)
765				counts = append(counts, 0)
766			}
767			counts[ci]++
768			ru, rv, rn, rc = append(ru, u), append(rv, v), append(rn, e-u), append(rc, ci)
769			u = e
770		}
771	}
772	bg := 0
773	for k := 1; k < len(counts); k++ {
774		if counts[k] > counts[bg] {
775			bg = k
776		}
777	}
778
779	var b strings.Builder
780	sW, sH, sC, sR, sOX, sOY := strconv.Itoa(W), strconv.Itoa(H), strconv.Itoa(C), strconv.Itoa(R), strconv.Itoa(ox), strconv.Itoa(oy)
781	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 `)
782	b.WriteString(sW + " " + sH + `" width="` + sW + `" height="` + sH + `">`)
783	b.WriteString(`<defs><pattern id="w" width="4" height="2" patternUnits="userSpaceOnUse">` +
784		`<path d="M0 1.6L4 .4" stroke="#000" stroke-width=".7" opacity=".22"/></pattern>` +
785		`<pattern id="k" width="1" height="1" patternUnits="userSpaceOnUse">` +
786		`<path d="M0 0h1" stroke="#fff" stroke-width=".12" opacity=".2"/></pattern><path id="f" d="`)
787	// fringe (warp ends), drawn after the lots: the stream order is the prototype's
788	loose := t.fringe == fringeLoose
789	top, bottom := strconv.Itoa(oy), strconv.Itoa(oy+R*cell)
790	for u := 0; u < C; u++ {
791		x := strconv.Itoa(ox + u*cell + cell/2)
792		for side := 0; side < 2; side++ {
793			ln, sway := 50, 0
794			if loose {
795				ln = r.between(46, 62)
796				sway = r.between(-6, 6)
797			}
798			b.WriteString("M" + x + " ")
799			if side == 0 {
800				b.WriteString(top + "l" + strconv.Itoa(sway) + " " + strconv.Itoa(-ln))
801			} else {
802				b.WriteString(bottom + "l" + strconv.Itoa(sway) + " " + strconv.Itoa(ln))
803			}
804		}
805	}
806	b.WriteString(`"/></defs><rect width="` + sW + `" height="` + sH + `" fill="#e9e4da"/>`)
807	b.WriteString(`<use href="#f" stroke="#e7dcc4" stroke-width="5" stroke-linecap="round"/>` +
808		`<use href="#f" stroke="#b9ab8e" stroke-width="1.2" opacity=".6"/>`)
809	switch t.fringe {
810	case fringeKnotted:
811		b.WriteString(`<g fill="#d8cbb0">`)
812		kw := strconv.Itoa(4*cell - 16)
813		y1, y2 := strconv.Itoa(oy-22), strconv.Itoa(oy+R*cell+12)
814		for u := 1; u < C-3; u += 4 {
815			x := strconv.Itoa(ox + u*cell - 2)
816			b.WriteString(`<rect x="` + x + `" y="` + y1 + `" width="` + kw + `" height="10" rx="5"/>`)
817			b.WriteString(`<rect x="` + x + `" y="` + y2 + `" width="` + kw + `" height="10" rx="5"/>`)
818		}
819		b.WriteString(`</g>`)
820	case fringeBound:
821		rw := strconv.Itoa(C * cell)
822		b.WriteString(`<path d="M` + sOX + " " + strconv.Itoa(oy-6) + "h" + rw + "M" + sOX + " " +
823			strconv.Itoa(oy+R*cell+6) + "h" + rw + `" stroke="` + pal[4] + `" stroke-width="12"/>`)
824	}
825	b.WriteString(`<g transform="translate(` + sOX + " " + sOY + ") scale(" + strconv.Itoa(cell) +
826		`)" shape-rendering="crispEdges"><rect width="` + sC + `" height="` + sR + `" fill="` + cols[bg] +
827		`"/><g transform="translate(0 .5)">`)
828	// every run except the background colour's is a one-cell-wide stroke on
829	// its row's centre line; same-row runs continue with a relative move
830	for k := 0; k < len(cols); k++ {
831		if k == bg {
832			continue
833		}
834		b.WriteString(`<path d="`)
835		lastV, lastE := -1, 0
836		for i := 0; i < len(rc); i++ {
837			if rc[i] != k {
838				continue
839			}
840			if rv[i] == lastV {
841				b.WriteString("m" + strconv.Itoa(ru[i]-lastE) + " 0h" + strconv.Itoa(rn[i]))
842			} else {
843				b.WriteString("M" + strconv.Itoa(ru[i]) + " " + strconv.Itoa(rv[i]) + "h" + strconv.Itoa(rn[i]))
844			}
845			lastV, lastE = rv[i], ru[i]+rn[i]
846		}
847		b.WriteString(`" stroke="` + cols[k] + `"/>`)
848	}
849	b.WriteString(`</g><rect width="` + sC + `" height="` + sR + `" fill="url(#k)"/></g>`)
850	b.WriteString(`<rect x="` + sOX + `" y="` + sOY + `" width="` + strconv.Itoa(C*cell) + `" height="` +
851		strconv.Itoa(R*cell) + `" fill="url(#w)"/></svg>`)
852	return b.String()
853}