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.

giornate.gno

28.14 Kb · 953 lines
  1// Package giornate is a Sinopia showcase engine: a fresco wall caught
  2// mid-work. A fresco is painted on wet plaster one day-patch (giornata) at a
  3// time, from the top of the wall down. The wall is cut into irregular
  4// patches by slanted lines; one hidden composition runs under all of them.
  5// Finished patches show it in pigment, the rest still show the red-ochre
  6// sinopia underdrawing (outline, hatching, construction lines).
  7//
  8// Everything is integer maths (a 64-step quarter-sine table, truncating
  9// division), so the TypeScript twin in frontend/src/engines/giornate.ts is
 10// byte-identical. Two RNG streams come from the seed: seed+"|traits" decides
 11// the traits (cheap, no geometry: Traits never renders) and seed+"|art"
 12// draws the picture, so art draws never shift traits.
 13package giornate
 14
 15import (
 16	"errors"
 17	"strconv"
 18	"strings"
 19
 20	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia/engine/v1"
 21)
 22
 23// Trait types in the order Traits returns them.
 24var traitTypes = []string{"Pigments", "Giornate", "Completion", "Motif", "Hatch", "Construction", "Gilding", "Craquelure", "Rarity"}
 25
 26// MaxSVGBytes: measured max is 14,663 B over 20,000 default seeds and
 27// 15,005 B with params (docs/engines/giornate.md); 24 KiB leaves ~1.6x margin.
 28const MaxSVGBytes = 24576
 29
 30const paramsSchema = `{"type":"object","additionalProperties":false,"properties":{` +
 31	`"palette":{"type":"string","title":"Pigments","enum":["Seeded","Terra Verde","Lapis & Ochre","Cinnabar","Pompeian","Umber","Rose Madder","Verdaccio","Giotto Blue"],"default":"Seeded"},` +
 32	`"stage":{"type":"string","title":"Completion","enum":["Seeded","Pure Sinopia","Fresh Start","Half Wall","Advanced","Nearly Done","Finished"],"default":"Seeded"},` +
 33	`"patches":{"type":"string","title":"Giornate","enum":["Seeded","Few","Several","Many","Countless"],"default":"Seeded"},` +
 34	`"grain":{"type":"boolean","title":"Plaster grain","default":true}}}`
 35
 36// Manifest describes the engine. Author and FeeBps are set by the adapter.
 37func Manifest() engine.Manifest {
 38	return engine.Manifest{
 39		Name:    "Giornate",
 40		Version: "1.0.0",
 41		Description: "A fresco wall caught mid-work: finished day-patches (giornate) in pigment, " +
 42			"the rest still in the red sinopia underdrawing.",
 43		License:      "TBD",
 44		ParamsSchema: paramsSchema,
 45		TraitTypes:   append([]string{}, traitTypes...),
 46		Living:       false,
 47		MaxSVGBytes:  MaxSVGBytes,
 48	}
 49}
 50
 51// ---------------------------------------------------------------------------
 52// Params: "" (the showcase look) or exactly the canonical JSON Studio sends,
 53// keys in schema order, no whitespace:
 54//   {"palette":"Seeded","stage":"Pure Sinopia","patches":"Seeded","grain":true}
 55// "Seeded" leaves that trait to the seed. Anything else is rejected.
 56// ---------------------------------------------------------------------------
 57
 58type params struct {
 59	palette int // index into pigments, -1 = seeded
 60	stage   int // index into completions, -1 = seeded
 61	patches int // index into giornate, -1 = seeded
 62	grain   bool
 63}
 64
 65func defaultParams() params { return params{-1, -1, -1, true} }
 66
 67func parseParams(s string) (params, error) {
 68	p := defaultParams()
 69	if s == "" {
 70		return p, nil
 71	}
 72	rest := s
 73	var v string
 74	var ok bool
 75	if rest, ok = lit(rest, `{"palette":"`); !ok {
 76		return p, errors.New(`giornate params: expected {"palette":"…`)
 77	}
 78	if v, rest, ok = str(rest); !ok {
 79		return p, errors.New("giornate params: bad palette")
 80	}
 81	if p.palette, ok = lookup(v, pigmentNames()); !ok {
 82		return p, errors.New("giornate params: unknown palette " + strconv.Quote(v))
 83	}
 84	if rest, ok = lit(rest, `,"stage":"`); !ok {
 85		return p, errors.New("giornate params: expected stage")
 86	}
 87	if v, rest, ok = str(rest); !ok {
 88		return p, errors.New("giornate params: bad stage")
 89	}
 90	if p.stage, ok = lookup(v, stageNames()); !ok {
 91		return p, errors.New("giornate params: unknown stage " + strconv.Quote(v))
 92	}
 93	if rest, ok = lit(rest, `,"patches":"`); !ok {
 94		return p, errors.New("giornate params: expected patches")
 95	}
 96	if v, rest, ok = str(rest); !ok {
 97		return p, errors.New("giornate params: bad patches")
 98	}
 99	if p.patches, ok = lookup(v, bucketNames()); !ok {
100		return p, errors.New("giornate params: unknown patches " + strconv.Quote(v))
101	}
102	switch rest {
103	case `,"grain":true}`:
104		p.grain = true
105	case `,"grain":false}`:
106		p.grain = false
107	default:
108		return p, errors.New("giornate params: expected grain true|false and end of object")
109	}
110	return p, nil
111}
112
113func lit(s, prefix string) (string, bool) {
114	if !strings.HasPrefix(s, prefix) {
115		return s, false
116	}
117	return s[len(prefix):], true
118}
119
120// str reads a JSON string body up to its closing quote; escapes are never
121// needed by the enum values, so a backslash is rejected.
122func str(s string) (string, string, bool) {
123	for i := 0; i < len(s); i++ {
124		switch s[i] {
125		case '"':
126			return s[:i], s[i+1:], true
127		case '\\':
128			return "", s, false
129		}
130	}
131	return "", s, false
132}
133
134func lookup(v string, names []string) (int, bool) {
135	if v == "Seeded" {
136		return -1, true
137	}
138	for i, n := range names {
139		if n == v {
140			return i, true
141		}
142	}
143	return -1, false
144}
145
146// ValidateParams accepts "" and the canonical params JSON only.
147func ValidateParams(s string) error {
148	_, err := parseParams(s)
149	return err
150}
151
152// Traits returns the nine traits of in.Seed under in.Params. It never
153// renders: one 8-draw RNG pass and a few table walks.
154func Traits(in engine.Input) []engine.Trait {
155	t := TraitsWith(in.Seed, in.Params)
156	return []engine.Trait{
157		{Type: "Pigments", Value: t.Pigments},
158		{Type: "Giornate", Value: t.Giornate},
159		{Type: "Completion", Value: t.Completion},
160		{Type: "Motif", Value: t.Motif},
161		{Type: "Hatch", Value: t.Hatch},
162		{Type: "Construction", Value: t.Construction},
163		{Type: "Gilding", Value: t.Gilding},
164		{Type: "Craquelure", Value: t.Craquelure},
165		{Type: "Rarity", Value: t.Rarity},
166	}
167}
168
169// Render returns the raw SVG for in.Seed under in.Params. Core validates
170// params before every render; invalid params panic.
171func Render(in engine.Input) string { return SVGWith(in.Seed, in.Params) }
172
173// SVG renders a seed with the default (showcase) params.
174func SVG(seed string) string { return SVGWith(seed, "") }
175
176// TraitsOf decodes a seed with the default params.
177func TraitsOf(seed string) TraitSet { return TraitsWith(seed, "") }
178
179// ---------------------------------------------------------------------------
180// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Genesis).
181// ---------------------------------------------------------------------------
182
183const (
184	fnvOffset uint64 = 14695981039346656037
185	fnvPrime  uint64 = 1099511628211
186)
187
188type rng struct{ state uint64 }
189
190func newRNG(seed string) *rng {
191	h := fnvOffset
192	for i := 0; i < len(seed); i++ {
193		h ^= uint64(seed[i])
194		h *= fnvPrime
195	}
196	if h == 0 {
197		h = fnvPrime
198	}
199	return &rng{state: h}
200}
201
202func (r *rng) next() uint64 {
203	r.state += 0x9E3779B97F4A7C15
204	z := r.state
205	z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
206	z = (z ^ (z >> 27)) * 0x94D049BB133111EB
207	return z ^ (z >> 31)
208}
209
210// intn returns a value in [0, n).
211func (r *rng) intn(n int) int {
212	if n <= 0 {
213		return 0
214	}
215	return int(r.next() % uint64(n))
216}
217
218// rr returns a value in [a, b].
219func (r *rng) rr(a, b int) int { return a + r.intn(b-a+1) }
220
221// Quarter sine, 64 steps per quarter turn, scaled by 1024.
222var qsin = []int{0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460,
223	483, 505, 526, 548, 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822,
224	837, 851, 865, 878, 891, 903, 915, 926, 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009,
225	1013, 1016, 1019, 1021, 1023, 1024, 1024}
226
227// isin takes an angle in 1/256 turn and returns sin*1024.
228func isin(a int) int {
229	a = ((a % 256) + 256) % 256
230	switch {
231	case a < 64:
232		return qsin[a]
233	case a < 128:
234		return qsin[128-a]
235	case a < 192:
236		return -qsin[a-128]
237	}
238	return -qsin[256-a]
239}
240
241func icos(a int) int { return isin(a + 64) }
242
243// ---------------------------------------------------------------------------
244// Trait tables. Weights per table sum to 100 (they read as percents); score
245// feeds the rarity tier.
246// ---------------------------------------------------------------------------
247
248type option struct {
249	name   string
250	weight int
251	score  int
252}
253
254type pigment struct {
255	option
256	plaster, red, dark, wall string
257	cols                     []string
258}
259
260var pigments = []pigment{
261	{option{"Terra Verde", 20, 0}, "#ebe1ca", "#a4432c", "#2f2a22", "#d8c9a4", []string{"#7d8b6a", "#a9b38f", "#c9a96e", "#55634a", "#e6d8b5"}},
262	{option{"Lapis & Ochre", 18, 0}, "#ece3cd", "#9e3b26", "#1f2433", "#e2d3ae", []string{"#2f4f8f", "#c8962e", "#e3c27a", "#1c2f5c", "#b9a68a"}},
263	{option{"Cinnabar", 15, 0}, "#efe4cc", "#8f3a22", "#2a1d19", "#e8d3b0", []string{"#b5321f", "#e0a25a", "#3a2a24", "#7a2418", "#d9b98c"}},
264	{option{"Pompeian", 14, 0}, "#efe3c9", "#9a3a24", "#1d1a17", "#8e1f17", []string{"#1d1a17", "#d9a441", "#f2e6cc", "#5e1510", "#c98a5b"}},
265	{option{"Umber", 12, 0}, "#e4d6ba", "#93402a", "#1e1a17", "#c2a77d", []string{"#3b2f28", "#6b5440", "#a68a64", "#e9dcc0", "#8a3b26"}},
266	{option{"Rose Madder", 10, 1}, "#f0e5d2", "#a54a3a", "#3a2630", "#efd9c4", []string{"#c46a6a", "#6d3b47", "#e8b4a0", "#9a8a9e", "#f5e9d8"}},
267	{option{"Verdaccio", 7, 2}, "#e8e3cf", "#9d4a30", "#34362a", "#c3c3a8", []string{"#6f7258", "#4a4c3a", "#9a9c80", "#e2e0cc", "#8a7a58"}},
268	{option{"Giotto Blue", 4, 3}, "#f1e8d4", "#a03e28", "#141d3a", "#2b4c9a", []string{"#e9d8b4", "#c98f3f", "#1a2e66", "#f3ead6", "#8a3f2a"}},
269}
270
271// giornate buckets: patch-count ranges in lo/hi.
272type bucket struct {
273	option
274	lo, hi int
275}
276
277var giornate = []bucket{
278	{option{"Few", 24, 1}, 5, 8},
279	{option{"Several", 44, 0}, 9, 14},
280	{option{"Many", 24, 1}, 15, 21},
281	{option{"Countless", 8, 2}, 22, 30},
282}
283
284// completions: pct is the share of patches already painted.
285type stage struct {
286	option
287	pct int
288}
289
290var completions = []stage{
291	{option{"Fresh Start", 14, 1}, 25},
292	{option{"Half Wall", 28, 0}, 50},
293	{option{"Advanced", 30, 0}, 70},
294	{option{"Nearly Done", 18, 1}, 88},
295	{option{"Pure Sinopia", 5, 3}, 0},
296	{option{"Finished", 5, 3}, 100},
297}
298
299var motifs = []option{
300	{"Procession", 24, 0}, {"Tondi", 20, 0}, {"Arcade", 20, 0},
301	{"Stair", 14, 1}, {"Mandorla", 14, 1}, {"Annunciation", 8, 2},
302}
303var hatches = []option{{"Parallel", 50, 0}, {"Cross", 32, 0}, {"Stipple", 18, 1}}
304var constructions = []option{{"Axes", 45, 0}, {"Squaring Grid", 35, 0}, {"Compass Arcs", 20, 1}}
305var gildings = []option{{"None", 78, 0}, {"Leaf Halos", 17, 1}, {"Gold Ground", 5, 3}}
306var craquelures = []option{{"None", 55, 0}, {"Light", 33, 0}, {"Heavy", 12, 2}}
307
308func pigmentNames() []string {
309	out := make([]string, len(pigments))
310	for i, p := range pigments {
311		out[i] = p.name
312	}
313	return out
314}
315
316func stageNames() []string {
317	out := make([]string, len(completions))
318	for i, c := range completions {
319		out[i] = c.name
320	}
321	return out
322}
323
324func bucketNames() []string {
325	out := make([]string, len(giornate))
326	for i, g := range giornate {
327		out[i] = g.name
328	}
329	return out
330}
331
332// pickIndex walks the cumulative weights once.
333func pickIndex(r *rng, weights []int) int {
334	total := 0
335	for _, w := range weights {
336		total += w
337	}
338	roll := r.intn(total)
339	for i, w := range weights {
340		roll -= w
341		if roll < 0 {
342			return i
343		}
344	}
345	return len(weights) - 1
346}
347
348func optWeights(t []option) []int {
349	out := make([]int, len(t))
350	for i, o := range t {
351		out[i] = o.weight
352	}
353	return out
354}
355
356// Weights per table, computed once at package init (Traits runs for
357// hundreds of tokens per query).
358var (
359	pigmentW, giornateW, completionW = tableWeights()
360	motifW                           = optWeights(motifs)
361	hatchW                           = optWeights(hatches)
362	constructionW                    = optWeights(constructions)
363	gildingW                         = optWeights(gildings)
364	craquelureW                      = optWeights(craquelures)
365)
366
367func tableWeights() ([]int, []int, []int) {
368	pw := make([]int, len(pigments))
369	for i, q := range pigments {
370		pw[i] = q.weight
371	}
372	gw := make([]int, len(giornate))
373	for i, q := range giornate {
374		gw[i] = q.weight
375	}
376	cw := make([]int, len(completions))
377	for i, q := range completions {
378		cw[i] = q.weight
379	}
380	return pw, gw, cw
381}
382
383// Tier cut-offs on the score, chosen on a 10,000-seed simulation with
384// default params (docs/engines/giornate.md has the distribution).
385const (
386	scoreMythic    = 8
387	scoreLegendary = 6
388	scoreRare      = 4
389	scoreUncommon  = 2
390)
391
392// TraitSet is a decoded seed. The SVG builder and the trait list read the
393// same struct, so picture and metadata cannot disagree.
394type TraitSet struct {
395	Pigments, Giornate, Completion, Motif, Hatch, Construction, Gilding, Craquelure string
396	Score                                                                          int
397	Rarity                                                                         string
398
399	pig, gio, comp, motif, hatch, cons, gild, craq int // table indices actually used
400	grain                                          bool
401}
402
403// derive draws all eight picks in a fixed order (the order is part of the
404// contract), then applies params. A trait fixed by params or hidden by the
405// completion stage adds nothing to the score: rarity only counts what the
406// seed chose and the picture shows.
407func derive(seed string, p params) TraitSet {
408	r := newRNG(seed + "|traits")
409	t := TraitSet{
410		pig:   pickIndex(r, pigmentW),
411		gio:   pickIndex(r, giornateW),
412		comp:  pickIndex(r, completionW),
413		motif: pickIndex(r, motifW),
414		hatch: pickIndex(r, hatchW),
415		cons:  pickIndex(r, constructionW),
416		gild:  pickIndex(r, gildingW),
417		craq:  pickIndex(r, craquelureW),
418		grain: p.grain,
419	}
420	score := 0
421	if p.palette >= 0 {
422		t.pig = p.palette
423	}
424	if p.patches >= 0 {
425		t.gio = p.patches
426	} else {
427		score += giornate[t.gio].score
428	}
429	if p.stage >= 0 {
430		t.comp = p.stage
431	} else {
432		score += completions[t.comp].score
433	}
434	pct := completions[t.comp].pct
435	unpainted := pct == 0  // no pigment and no gold shows
436	finished := pct == 100 // no underdrawing shows
437
438	t.Pigments = pigments[t.pig].name
439	t.Giornate = giornate[t.gio].name
440	t.Completion = completions[t.comp].name
441	t.Motif = motifs[t.motif].name
442	t.Hatch = hatches[t.hatch].name
443	t.Construction = constructions[t.cons].name
444	t.Gilding = gildings[t.gild].name
445	t.Craquelure = craquelures[t.craq].name
446	score += motifs[t.motif].score + craquelures[t.craq].score
447	if unpainted {
448		t.Pigments = "Unpainted"
449		t.Gilding = "None"
450	} else {
451		score += gildings[t.gild].score
452		if p.palette < 0 {
453			score += pigments[t.pig].score
454		}
455	}
456	if finished {
457		t.Hatch = "None"
458		t.Construction = "None"
459	} else {
460		score += hatches[t.hatch].score + constructions[t.cons].score
461	}
462	t.Score = score
463	switch {
464	case score >= scoreMythic:
465		t.Rarity = "Mythic"
466	case score >= scoreLegendary:
467		t.Rarity = "Legendary"
468	case score >= scoreRare:
469		t.Rarity = "Rare"
470	case score >= scoreUncommon:
471		t.Rarity = "Uncommon"
472	default:
473		t.Rarity = "Common"
474	}
475	return t
476}
477
478// TraitsWith decodes a seed under params; invalid params panic.
479func TraitsWith(seed, ps string) TraitSet {
480	p, err := parseParams(ps)
481	if err != nil {
482		panic(err)
483	}
484	return derive(seed, p)
485}
486
487// ---------------------------------------------------------------------------
488// Geometry: convex polygons cut by lines, integer maths throughout.
489// ---------------------------------------------------------------------------
490
491const (
492	cW = 1000
493	cH = 1250
494)
495
496type pt struct{ x, y int }
497
498func area2(p []pt) int {
499	s := 0
500	n := len(p)
501	for i := 0; i < n; i++ {
502		a, b := p[i], p[(i+1)%n]
503		s += a.x*b.y - b.x*a.y
504	}
505	if s < 0 {
506		return -s
507	}
508	return s
509}
510
511// cut splits poly by the line through (px,py) with direction (dx,dy).
512func cut(poly []pt, px, py, dx, dy int) ([]pt, []pt) {
513	var a, b []pt
514	n := len(poly)
515	for i := 0; i < n; i++ {
516		p, q := poly[i], poly[(i+1)%n]
517		sa := dx*(p.y-py) - dy*(p.x-px)
518		sb := dx*(q.y-py) - dy*(q.x-px)
519		if sa >= 0 {
520			a = append(a, p)
521		}
522		if sa <= 0 {
523			b = append(b, p)
524		}
525		if (sa > 0 && sb < 0) || (sa < 0 && sb > 0) {
526			c := pt{p.x + (q.x-p.x)*sa/(sa-sb), p.y + (q.y-p.y)*sa/(sa-sb)}
527			a = append(a, c)
528			b = append(b, c)
529		}
530	}
531	return a, b
532}
533
534// subdivide cuts the wall into target patches, always cutting the largest.
535func subdivide(r *rng, target int) [][]pt {
536	polys := [][]pt{{{0, 0}, {cW, 0}, {cW, cH}, {0, cH}}}
537	areas := []int{2 * cW * cH}
538	mn := 2 * cW * cH / (target * 4)
539	for tries := 0; len(polys) < target && tries < 400; tries++ {
540		bi := 0
541		for i := 1; i < len(areas); i++ {
542			if areas[i] > areas[bi] {
543				bi = i
544			}
545		}
546		p := polys[bi]
547		minx, maxx, miny, maxy, sx, sy := p[0].x, p[0].x, p[0].y, p[0].y, 0, 0
548		for _, q := range p {
549			sx += q.x
550			sy += q.y
551			if q.x < minx {
552				minx = q.x
553			}
554			if q.x > maxx {
555				maxx = q.x
556			}
557			if q.y < miny {
558				miny = q.y
559			}
560			if q.y > maxy {
561				maxy = q.y
562			}
563		}
564		bw, bh := maxx-minx, maxy-miny
565		cx := sx/len(p) + r.rr(-bw/5, bw/5)
566		cy := sy/len(p) + r.rr(-bh/5, bh/5)
567		ang := r.rr(-12, 12)
568		if bw > bh {
569			ang += 64
570		}
571		a, b := cut(p, cx, cy, icos(ang), isin(ang))
572		if len(a) < 3 || len(b) < 3 {
573			continue
574		}
575		aa, ab := area2(a), area2(b)
576		if aa < mn || ab < mn {
577			continue
578		}
579		polys[bi], areas[bi] = a, aa
580		polys = append(polys, b)
581		areas = append(areas, ab)
582	}
583	return polys
584}
585
586func itoa(n int) string { return strconv.Itoa(n) }
587
588func pts(p []pt) string {
589	var b strings.Builder
590	for i, q := range p {
591		if i > 0 {
592			b.WriteByte(' ')
593		}
594		b.WriteString(itoa(q.x))
595		b.WriteByte(',')
596		b.WriteString(itoa(q.y))
597	}
598	return b.String()
599}
600
601// ---------------------------------------------------------------------------
602// The hidden composition: element geometry + colour index + halo flag.
603// ---------------------------------------------------------------------------
604
605type shape struct {
606	g    string // `rect x="…" …` without the leading '<' and the paint
607	ci   int
608	halo bool
609}
610
611func rect(x, y, w, h int) string {
612	return `rect x="` + itoa(x) + `" y="` + itoa(y) + `" width="` + itoa(w) + `" height="` + itoa(h) + `"`
613}
614
615func circle(cx, cy, rad int) string {
616	return `circle cx="` + itoa(cx) + `" cy="` + itoa(cy) + `" r="` + itoa(rad) + `"`
617}
618
619func composition(r *rng, motif string) []shape {
620	var sh []shape
621	add := func(g string, ci int, halo bool) { sh = append(sh, shape{g, ci, halo}) }
622	switch motif {
623	case "Procession":
624		n := r.rr(4, 7)
625		gap := (cW - 160) / n
626		base := r.rr(1000, 1120)
627		add(rect(40, base, 920, cH-base), 3, false)
628		for i := 0; i < n; i++ {
629			w := gap * 62 / 100
630			x := 80 + i*gap + (gap-w)/2
631			hgt := r.rr(480, 640)
632			y := base - hgt
633			add(rect(x, y, w, hgt+20)+` rx="`+itoa(w/2)+`"`, i%3, false)
634			hr := w * 30 / 100
635			cx := x + w/2
636			add(circle(cx, y-hr+10, hr+hr/2), 4, true)
637			add(circle(cx, y-hr+10, hr), 2, false)
638		}
639	case "Tondi":
640		n := r.rr(3, 6)
641		big := r.rr(260, 360)
642		bx := r.rr(380, 620)
643		by := r.rr(420, 700)
644		add(circle(bx, by, big), 0, true)
645		for i := 0; i < n; i++ {
646			rad := r.rr(50, 170)
647			cx := r.rr(rad, cW-rad)
648			cy := r.rr(rad, cH-rad)
649			add(circle(cx, cy, rad), 1+i%4, false)
650		}
651		cx := r.rr(400, 600)
652		cy := r.rr(500, 700)
653		add(circle(cx, cy, big/3), 2, false)
654	case "Arcade":
655		n := r.rr(2, 4)
656		span := (cW - 120) / n
657		top := r.rr(380, 560)
658		bot := r.rr(1050, 1180)
659		add(rect(0, top-r.rr(140, 220), cW, cH), 3, false)
660		for i := 0; i < n; i++ {
661			rad := span * r.rr(30, 42) / 100
662			cx := 60 + i*span + span/2
663			x0, x1 := cx-rad, cx+rad
664			add(`path d="M`+itoa(x0)+` `+itoa(bot)+`V`+itoa(top)+`A`+itoa(rad)+` `+itoa(rad)+` 0 0 1 `+
665				itoa(x1)+` `+itoa(top)+`V`+itoa(bot)+`Z"`, i%2, false)
666			add(circle(cx, top-rad/6, rad/3), 4, true)
667		}
668		add(rect(0, bot, cW, cH-bot), 2, false)
669	case "Stair":
670		steps := r.rr(4, 8)
671		sw := cW / steps
672		sh2 := 700 / steps
673		d := "M0 " + itoa(cH)
674		for i := 0; i < steps; i++ {
675			d += "V" + itoa(cH-120-i*sh2) + "H" + itoa((i+1)*sw)
676		}
677		d += "V" + itoa(cH) + "Z"
678		add(`path d="`+d+`"`, 0, false)
679		rad := r.rr(90, 160)
680		cx := r.rr(150, 400)
681		cy := r.rr(200, 380)
682		add(circle(cx, cy, rad), 4, true)
683		x := r.rr(500, 700)
684		y := r.rr(150, 300)
685		w := r.rr(60, 120)
686		h := r.rr(300, 500)
687		add(rect(x, y, w, h)+` rx="40"`, 1, false)
688	case "Mandorla":
689		cx := 500
690		cy := r.rr(560, 700)
691		hh := r.rr(380, 470)
692		rr := hh + r.rr(40, 160)
693		add(`path d="M`+itoa(cx)+` `+itoa(cy-hh)+`A`+itoa(rr)+` `+itoa(rr)+` 0 0 1 `+itoa(cx)+` `+itoa(cy+hh)+
694			`A`+itoa(rr)+` `+itoa(rr)+` 0 0 1 `+itoa(cx)+` `+itoa(cy-hh)+`Z"`, 0, true)
695		add(rect(cx-90, cy-hh+170, 180, 2*hh-260)+` rx="90"`, 1, false)
696		add(circle(cx, cy-hh+120, 95), 4, true)
697		add(circle(cx, cy-hh+120, 60), 2, false)
698		for side := -1; side <= 1; side += 2 {
699			sx := cx + side*r.rr(320, 390)
700			sy := r.rr(200, 320)
701			sr := r.rr(50, 90)
702			add(circle(sx, sy, sr), 3, false)
703		}
704	default: // Annunciation
705		base := r.rr(1080, 1160)
706		add(rect(0, base, cW, cH-base), 3, false)
707		add(`path d="M380 `+itoa(base)+`V420A120 120 0 0 1 620 420V`+itoa(base)+`Z"`, 2, false)
708		for i, cx := range []int{180, 820} {
709			add(rect(cx-80, base-560, 160, 580)+` rx="80"`, i, false)
710			add(circle(cx, base-620, 90), 4, true)
711			add(circle(cx, base-620, 58), 2, false)
712		}
713		x1 := r.rr(560, 700)
714		y1 := r.rr(560, 760)
715		x2 := r.rr(380, 470)
716		add(`path d="M0 0L`+itoa(x1)+` `+itoa(y1)+`L`+itoa(x2)+` 0Z"`, 4, true)
717	}
718	return sh
719}
720
721// ---------------------------------------------------------------------------
722// SVG
723// ---------------------------------------------------------------------------
724
725const gold = "#c9a24a"
726
727// SVGWith renders a seed under params as a standalone SVG document.
728func SVGWith(seed, ps string) string {
729	t := TraitsWith(seed, ps)
730	pg := pigments[t.pig]
731	cols := pg.cols
732	red, dark := pg.red, pg.dark
733	r := newRNG(seed + "|art")
734
735	// 1. the wall, cut into day-patches
736	g := giornate[t.gio]
737	polys := subdivide(r, r.rr(g.lo, g.hi))
738	n := len(polys)
739
740	// 2. painted top-down: the highest centroids first, with some jitter
741	key := make([]int, n)
742	order := make([]int, n)
743	for i, p := range polys {
744		sy := 0
745		for _, q := range p {
746			sy += q.y
747		}
748		key[i] = sy/len(p) + r.rr(0, 260)
749		order[i] = i
750	}
751	for i := 1; i < n; i++ { // stable insertion sort
752		for j := i; j > 0 && key[order[j-1]] > key[order[j]]; j-- {
753			order[j-1], order[j] = order[j], order[j-1]
754		}
755	}
756	k := (n*completions[t.comp].pct + 50) / 100
757	painted := make([]bool, n)
758	for i := 0; i < k; i++ {
759		painted[order[i]] = true
760	}
761
762	motif := motifs[t.motif].name
763	hatch := hatches[t.hatch].name
764	cons := constructions[t.cons].name
765	gild := gildings[t.gild].name
766	shapes := composition(r, motif)
767	hz := r.rr(380, 640)
768	fr := r.rr(50, 70)
769	rot := 45
770	if hatch == "Parallel" {
771		rot = r.rr(30, 60)
772	}
773	grainSeed := r.rr(1, 999)
774
775	var b strings.Builder
776	b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1250" width="1000" height="1250">`)
777	sinopia := k < n
778	fresco := k > 0
779	if sinopia || t.grain {
780		b.WriteString(`<defs>`)
781	}
782	if sinopia {
783		switch hatch {
784		case "Stipple":
785			b.WriteString(`<pattern id="h" width="14" height="14" patternUnits="userSpaceOnUse"><circle cx="4" cy="4" r="2.2" fill="` +
786				red + `" opacity=".6"/><circle cx="11" cy="10" r="1.6" fill="` + red + `" opacity=".5"/></pattern>`)
787		case "Cross":
788			b.WriteString(`<pattern id="h" width="16" height="16" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><path d="M0 0V16M0 0H16" stroke="` +
789				red + `" stroke-width="2.5" opacity=".5"/></pattern>`)
790		default:
791			b.WriteString(`<pattern id="h" width="16" height="16" patternUnits="userSpaceOnUse" patternTransform="rotate(` + itoa(rot) +
792				`)"><path d="M0 0V16" stroke="` + red + `" stroke-width="3" opacity=".55"/></pattern>`)
793		}
794	}
795	if t.grain {
796		b.WriteString(`<filter id="t" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency=".9" numOctaves="2" seed="` +
797			itoa(grainSeed) + `"/><feColorMatrix values="0 0 0 0 .35 0 0 0 0 .3 0 0 0 0 .25 0 0 0 .55 0"/></filter>`)
798	}
799	if sinopia && fresco {
800		for pass := 0; pass < 2; pass++ {
801			if pass == 0 {
802				b.WriteString(`<clipPath id="P">`)
803			} else {
804				b.WriteString(`<clipPath id="S">`)
805			}
806			for i, p := range polys {
807				if painted[i] == (pass == 0) {
808					b.WriteString(`<polygon points="` + pts(p) + `"/>`)
809				}
810			}
811			b.WriteString(`</clipPath>`)
812		}
813	}
814	if sinopia || t.grain {
815		b.WriteString(`</defs>`)
816	}
817	b.WriteString(`<rect width="1000" height="1250" fill="` + pg.plaster + `"/>`)
818
819	// 3. sinopia layer: the unfinished patches
820	if sinopia {
821		if fresco {
822			b.WriteString(`<g clip-path="url(#S)">`)
823		} else {
824			b.WriteString(`<g>`)
825		}
826		switch cons {
827		case "Squaring Grid":
828			step := r.rr(100, 140)
829			b.WriteString(`<path d="`)
830			for x := step; x < cW; x += step {
831				b.WriteString("M" + itoa(x) + " 0V1250")
832			}
833			for y := step; y < cH; y += step {
834				b.WriteString("M0 " + itoa(y) + "H1000")
835			}
836			b.WriteString(`" stroke="` + red + `" stroke-width="1.5" opacity=".45"/>`)
837		case "Compass Arcs":
838			cx := r.rr(300, 700)
839			cy := r.rr(300, 900)
840			step := r.rr(110, 170)
841			b.WriteString(`<g fill="none" stroke="` + red + `" stroke-width="1.5" opacity=".45">`)
842			for rad := 120; rad < 1300; rad += step {
843				b.WriteString(`<` + circle(cx, cy, rad) + `/>`)
844			}
845			b.WriteString(`</g>`)
846		}
847		b.WriteString(`<path d="M0 ` + itoa(fr) + `H1000M0 ` + itoa(cH-fr) + `H1000M0 ` + itoa(hz) + `H1000" stroke="` + red +
848			`" stroke-width="3" opacity=".6"/>`)
849		b.WriteString(`<path d="M500 0V1250M0 416H1000M0 833H1000M0 0L1000 1250M1000 0L0 1250" stroke="` + red +
850			`" stroke-width="2" opacity=".5"/>`)
851		for i, s := range shapes {
852			fill := "none"
853			if i%2 == 0 {
854				fill = "url(#h)"
855			}
856			b.WriteString(`<` + s.g + ` fill="` + fill + `" stroke="` + red + `" stroke-width="5" stroke-linejoin="round"/>`)
857			dx := r.rr(-9, 9)
858			dy := r.rr(-9, 9)
859			b.WriteString(`<` + s.g + ` fill="none" stroke="` + red + `" stroke-width="2" opacity=".5" transform="translate(` +
860				itoa(dx) + ` ` + itoa(dy) + `)"/>`)
861		}
862		b.WriteString(`</g>`)
863	}
864
865	// 4. fresco layer: the finished giornate
866	if fresco {
867		if sinopia {
868			b.WriteString(`<g clip-path="url(#P)">`)
869		} else {
870			b.WriteString(`<g>`)
871		}
872		if gild == "Gold Ground" {
873			b.WriteString(`<rect width="1000" height="1250" fill="` + gold + `"/>`)
874		} else {
875			b.WriteString(`<rect width="1000" height="1250" fill="` + pg.wall + `"/><rect width="1000" height="` + itoa(hz) +
876				`" fill="` + cols[3] + `"/><rect y="` + itoa(hz-14) + `" width="1000" height="14" fill="` + cols[2] + `"/>`)
877		}
878		for _, s := range shapes {
879			fill := cols[s.ci%5]
880			if s.halo && gild != "None" {
881				fill = gold
882			}
883			b.WriteString(`<` + s.g + ` fill="` + fill + `" stroke="` + dark + `" stroke-width="3" stroke-opacity=".35"/>`)
884		}
885		b.WriteString(`<path d="M0 0H1000V` + itoa(fr) + `H0ZM0 ` + itoa(cH-fr) + `H1000V1250H0Z" fill="` + dark + `"/>`)
886		b.WriteString(`<path d="`)
887		for x := 10; x < cW; x += 125 {
888			b.WriteString(`M` + itoa(x) + ` 10h115v` + itoa(fr-20) + `h-115zM` + itoa(x) + ` ` + itoa(cH-fr+10) + `h115v` + itoa(fr-20) + `h-115z`)
889		}
890		b.WriteString(`" fill="` + cols[1] + `"/><g fill="` + cols[2] + `">`)
891		for x := 67; x < cW; x += 125 {
892			b.WriteString(`<` + circle(x, fr/2, 9) + `/><` + circle(x, cH-fr/2, 9) + `/>`)
893		}
894		b.WriteString(`</g>`)
895		if gild != "None" {
896			for _, s := range shapes {
897				if s.halo {
898					b.WriteString(`<` + s.g + ` fill="none" stroke="#8a6a24" stroke-width="3"/>`)
899				}
900			}
901		}
902		if sinopia {
903			// today's giornata: the last painted patch, its intonaco still wet
904			b.WriteString(`<polygon points="` + pts(polys[order[k-1]]) + `" fill="` + dark + `" opacity=".09"/>`)
905		}
906		b.WriteString(`</g>`)
907	}
908
909	// 5. seams between the days, then cracks, then plaster grain
910	b.WriteString(`<path d="`)
911	for _, p := range polys {
912		for i, q := range p {
913			if i == 0 {
914				b.WriteString("M")
915			} else {
916				b.WriteString("L")
917			}
918			b.WriteString(itoa(q.x) + "," + itoa(q.y))
919		}
920		b.WriteString("Z")
921	}
922	b.WriteString(`" fill="none" stroke="` + dark + `" stroke-width="2.5" opacity=".35" stroke-linejoin="round"/>`)
923	cracks := 0
924	switch craquelures[t.craq].name {
925	case "Light":
926		cracks = 7
927	case "Heavy":
928		cracks = 20
929	}
930	if cracks > 0 {
931		b.WriteString(`<path d="`)
932		for c := 0; c < cracks; c++ {
933			x := r.rr(0, cW)
934			y := r.rr(0, cH)
935			b.WriteString("M" + itoa(x) + " " + itoa(y))
936			a := r.intn(256)
937			segs := r.rr(5, 12)
938			for s := 0; s < segs; s++ {
939				a += r.rr(-24, 24)
940				ln := r.rr(14, 46)
941				x += icos(a) * ln / 1024
942				y += isin(a) * ln / 1024
943				b.WriteString("L" + itoa(x) + " " + itoa(y))
944			}
945		}
946		b.WriteString(`" fill="none" stroke="` + dark + `" stroke-width="1.6" opacity=".45"/>`)
947	}
948	if t.grain {
949		b.WriteString(`<rect width="1000" height="1250" filter="url(#t)" opacity=".5"/>`)
950	}
951	b.WriteString(`</svg>`)
952	return b.String()
953}