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