ebru.gno
34.15 Kb · 1309 lines
1// Package ebru is a Sinopia engine: Turkish paper marbling, computed. Paint
2// drops are laid on a bath and every drop pushes the boundaries already
3// floating outwards while keeping their area
4// (P' = C + (P - C) * sqrt(1 + r^2 / |P - C|^2)); styluses and combs then drag
5// the paint. The pattern types are the real ebru styles (Battal, Gelgit,
6// Taraklı, Şal, Hatip, Bülbül Yuvası, Çiçekli), drawn originally.
7//
8// It is a port of the Ebru prototype in the engine gallery (JavaScript),
9// redesigned for the on-chain gas budget: a drop's stretch comes from a
10// 1,024-entry table instead of two square roots per point, combs are one
11// pass over a precomputed displacement table, points beyond the margin are
12// pruned in runs and a point budget bounds the work and the output.
13// frontend/src/engines/ebru.ts is a byte-identical TypeScript twin;
14// ebru_test.gno and ebru.test.ts pin the same golden vectors.
15//
16// Pure integer maths: no floats, no time, no block data.
17package ebru
18
19import (
20 "errors"
21 "strconv"
22 "strings"
23
24 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
25)
26
27// TraitTypes in the order Traits returns them.
28var traitTypes = []string{"Pattern", "Palette", "Ground", "Stones", "Flow", "Finish", "Frame", "Rarity"}
29
30// MaxSVGBytes bounds the output (the point budget keeps it far below).
31const MaxSVGBytes = 28672
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 `"pattern":{"type":"string","title":"Pattern","enum":["Seeded","Battal","Gelgit","Taraklı","Şal","Hatip",` +
37 `"Bülbül Yuvası","Çiçekli"],"default":"Seeded"},` +
38 `"palette":{"type":"string","title":"Palette","enum":["Seeded","Lahore & Ochre","Spring","Night","Earth","Sea",` +
39 `"Soot & Gold","Sinopia"],"default":"Seeded"}}}`
40
41// DefaultParams is the canonical form of the defaults; it renders exactly
42// like "".
43const DefaultParams = `{"pattern":"Seeded","palette":"Seeded"}`
44
45// Manifest describes the engine. Author and FeeBps are set by the adapter.
46func Manifest() engine.Manifest {
47 return engine.Manifest{
48 Name: "Ebru",
49 Version: "1.0.0",
50 Description: "Turkish paper marbling computed on chain: every drop of paint pushes the paint already " +
51 "floating, then the stylus and the comb drag it. Battal, Gelgit, Taraklı, Şal, Hatip, Bülbül Yuvası, Çiçekli.",
52 License: "CC-BY-NC-4.0",
53 ParamsSchema: ParamsSchema,
54 TraitTypes: append([]string{}, traitTypes...),
55 Living: false,
56 MaxSVGBytes: MaxSVGBytes,
57 Kind: engine.KindSVG,
58 }
59}
60
61// Config is a parsed params string.
62type Config struct {
63 Pattern int // -1: drawn from the seed, else an index into the patterns
64 Palette int // -1: drawn from the seed, else an index into the palettes
65}
66
67// Defaults is the showcase look (params "").
68func Defaults() Config { return Config{Pattern: -1, Palette: -1} }
69
70var errParams = errors.New(`ebru: params must be "" or {"pattern":<enum>,"palette":<enum>} without spaces`)
71
72func enumIndex(table []option, v string) int {
73 if v == "Seeded" {
74 return -1
75 }
76 for i, o := range table {
77 if o.name == v {
78 return i
79 }
80 }
81 return -2
82}
83
84// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
85func ParseParams(params string) (Config, error) {
86 cfg := Defaults()
87 if params == "" {
88 return cfg, nil
89 }
90 const pre, mid, post = `{"pattern":"`, `","palette":"`, `"}`
91 if !strings.HasPrefix(params, pre) || !strings.HasSuffix(params, post) || len(params) < len(pre)+len(mid)+len(post) {
92 return cfg, errParams
93 }
94 body := params[len(pre) : len(params)-len(post)]
95 i := strings.Index(body, mid)
96 if i < 0 {
97 return cfg, errParams
98 }
99 a, b := body[:i], body[i+len(mid):]
100 if strings.IndexByte(a, '"') >= 0 || strings.IndexByte(b, '"') >= 0 {
101 return cfg, errParams
102 }
103 cfg.Pattern, cfg.Palette = enumIndex(patternOpts, a), enumIndex(paletteOpts, b)
104 if cfg.Pattern < -1 || cfg.Palette < -1 {
105 return Defaults(), errParams
106 }
107 return cfg, nil
108}
109
110// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
111func ValidateParams(params string) error {
112 _, err := ParseParams(params)
113 return err
114}
115
116func mustConfig(params string) Config {
117 cfg, err := ParseParams(params)
118 if err != nil {
119 panic(err)
120 }
121 return cfg
122}
123
124// Traits returns the eight traits of in.Seed in TraitTypes order. It never
125// renders: seven table draws.
126func Traits(in engine.Input) []engine.Trait {
127 t := TraitsOf(in.Seed, mustConfig(in.Params))
128 return []engine.Trait{
129 {Type: "Pattern", Value: t.Pattern},
130 {Type: "Palette", Value: t.Palette},
131 {Type: "Ground", Value: t.Ground},
132 {Type: "Stones", Value: t.Stones},
133 {Type: "Flow", Value: t.Flow},
134 {Type: "Finish", Value: t.Finish},
135 {Type: "Frame", Value: t.Frame},
136 {Type: "Rarity", Value: t.Rarity},
137 }
138}
139
140// Render returns the raw SVG for in.Seed and in.Params.
141func Render(in engine.Input) string { return SVG(in.Seed, mustConfig(in.Params)) }
142
143// ---------------------------------------------------------------------------
144// Deterministic randomness: FNV-1a over the seed, then splitmix64 (the stream
145// of every Sinopia engine). Traits use seed+"|traits", the art seed+"|art".
146// ---------------------------------------------------------------------------
147
148type rng struct{ state uint64 }
149
150func newRNG(seed string) *rng {
151 h := uint64(14695981039346656037)
152 for i := 0; i < len(seed); i++ {
153 h ^= uint64(seed[i])
154 h *= 1099511628211
155 }
156 if h == 0 {
157 h = 1099511628211
158 }
159 return &rng{state: h}
160}
161
162func (r *rng) intn(n int) int {
163 if n <= 0 {
164 return 0
165 }
166 r.state += 0x9E3779B97F4A7C15
167 z := r.state
168 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
169 z = (z ^ (z >> 27)) * 0x94D049BB133111EB
170 return int((z ^ (z >> 31)) % uint64(n))
171}
172
173func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
174
175// ---------------------------------------------------------------------------
176// Trait tables (weights out of the table total).
177// ---------------------------------------------------------------------------
178
179type option struct {
180 name string
181 weight int
182}
183
184func pick(r *rng, table []option) int {
185 total := 0
186 for _, o := range table {
187 total += o.weight
188 }
189 x := r.intn(total)
190 for i, o := range table {
191 x -= o.weight
192 if x < 0 {
193 return i
194 }
195 }
196 return len(table) - 1
197}
198
199var patternOpts = []option{
200 {"Battal", 24}, {"Gelgit", 18}, {"Taraklı", 15}, {"Şal", 13}, {"Hatip", 12}, {"Bülbül Yuvası", 10}, {"Çiçekli", 8},
201}
202
203const (
204 pBattal = iota
205 pGelgit
206 pTarakli
207 pSal
208 pHatip
209 pBulbul
210 pCicekli
211)
212
213// palette: five paints in throwing order and the leaf paint for Çiçekli.
214type palette struct {
215 name string
216 weight int
217 paints []string
218 leaf int
219}
220
221var palettes = []palette{
222 {"Lahore & Ochre", 20, []string{"#2f4f8f", "#a63a2a", "#d9a63a", "#f2ece0", "#4f7a4a"}, 4},
223 {"Spring", 16, []string{"#d98a9a", "#4f7a4a", "#e8c25a", "#f4efe4", "#8a6aa8"}, 1},
224 {"Night", 14, []string{"#1f2d55", "#c9a24a", "#7a2a3a", "#e8e2d4", "#3f6a7a"}, 4},
225 {"Earth", 14, []string{"#8a5a3a", "#c98a4a", "#3a4a3a", "#e9dcc4", "#a63a2a"}, 2},
226 {"Sea", 13, []string{"#2a6a8a", "#7ab0c0", "#e0d2a8", "#1f3a4a", "#c96a4a"}, 3},
227 {"Soot & Gold", 8, []string{"#2a2624", "#b8902f", "#f0e8d8", "#8a3a2a", "#5a5a5a"}, 4},
228 {"Sinopia", 5, []string{"#b5432c", "#2e4a3a", "#e3b35a", "#efe4cc", "#6a3a5a"}, 1},
229}
230
231var paletteOpts = func() []option {
232 o := make([]option, len(palettes))
233 for i, p := range palettes {
234 o[i] = option{p.name, p.weight}
235 }
236 return o
237}()
238
239const (
240 palSoot = 5
241 palSinopia = 6
242)
243
244var groundOpts = []option{{"Cream", 40}, {"Celadon", 18}, {"Rose", 16}, {"Mustard", 14}, {"Indigo", 12}}
245var groundColors = []string{"#efe6d2", "#cfe0d6", "#f0d8d4", "#d9b45a", "#22305a"}
246
247const gIndigo = 4
248
249var stoneOpts = []option{{"Large", 30}, {"Medium", 45}, {"Small", 25}}
250var flowOpts = []option{{"Vertical", 60}, {"Horizontal", 40}}
251var finishOpts = []option{{"Clean", 72}, {"Zerefşan", 14}, {"Neftli", 14}}
252
253const (
254 fZerefsan = 1
255 fNeftli = 2
256)
257
258var frameOpts = []option{{"Full Sheet", 72}, {"Cetvel", 18}, {"Kenar", 10}}
259
260const (
261 frCetvel = 1
262 frKenar = 2
263)
264
265var tiers = []string{"Common", "Uncommon", "Rare", "Legendary", "Mythic"}
266
267type draw struct {
268 pattern, palette, ground, stones, flow, finish, frame int
269}
270
271func derive(seed string, cfg Config) draw {
272 r := newRNG(seed + "|traits")
273 // Draw order is part of the contract: changing it changes every token.
274 var d draw
275 d.pattern = pick(r, patternOpts)
276 d.palette = pick(r, paletteOpts)
277 d.ground = pick(r, groundOpts)
278 d.stones = pick(r, stoneOpts)
279 d.flow = pick(r, flowOpts)
280 d.finish = pick(r, finishOpts)
281 d.frame = pick(r, frameOpts)
282 // Params override after the draws, so the stream never shifts.
283 if cfg.Pattern >= 0 {
284 d.pattern = cfg.Pattern
285 }
286 if cfg.Palette >= 0 {
287 d.palette = cfg.Palette
288 }
289 return d
290}
291
292// combed: patterns with a comb or stylus pass along the flow axis.
293func combed(p int) bool { return p == pGelgit || p == pTarakli || p == pSal || p == pBulbul }
294
295func rarity(d draw) int {
296 s := 0
297 switch d.pattern {
298 case pBulbul, pCicekli:
299 s += 3
300 case pHatip:
301 s += 2
302 case pSal:
303 s++
304 }
305 if d.palette == palSinopia {
306 s += 3
307 } else if d.palette == palSoot {
308 s += 2
309 }
310 if d.ground == gIndigo {
311 s++
312 }
313 if d.finish != 0 {
314 s++
315 }
316 if d.frame == frKenar {
317 s += 3
318 } else if d.frame == frCetvel {
319 s++
320 }
321 switch {
322 case s >= 8:
323 return 4
324 case s >= 6:
325 return 3
326 case s >= 4:
327 return 2
328 case s >= 2:
329 return 1
330 }
331 return 0
332}
333
334// TraitSet is one token's traits by name.
335type TraitSet struct {
336 Pattern, Palette, Ground, Stones, Flow, Finish, Frame, Rarity string
337}
338
339// TraitsOf returns the traits for seed under cfg.
340func TraitsOf(seed string, cfg Config) TraitSet {
341 d := derive(seed, cfg)
342 flow := "Still"
343 if combed(d.pattern) {
344 flow = flowOpts[d.flow].name
345 }
346 return TraitSet{
347 Pattern: patternOpts[d.pattern].name,
348 Palette: paletteOpts[d.palette].name,
349 Ground: groundOpts[d.ground].name,
350 Stones: stoneOpts[d.stones].name,
351 Flow: flow,
352 Finish: finishOpts[d.finish].name,
353 Frame: frameOpts[d.frame].name,
354 Rarity: tiers[rarity(d)],
355 }
356}
357
358// ---------------------------------------------------------------------------
359// Integer helpers (Go's truncating / everywhere; the TS twin uses Math.trunc).
360// ---------------------------------------------------------------------------
361
362// isqrt is floor(sqrt(n)) for 0 <= n < 2^46, bit by bit.
363func isqrt(n int) int {
364 if n <= 0 {
365 return 0
366 }
367 res, bit := 0, 1<<44
368 for bit > n {
369 bit >>= 2
370 }
371 for bit != 0 {
372 if n >= res+bit {
373 n -= res + bit
374 res = res>>1 + bit
375 } else {
376 res >>= 1
377 }
378 bit >>= 2
379 }
380 return res
381}
382
383// sinT is a 256-step sine table, Q10, from the quarter wave every Sinopia
384// engine uses.
385var sinT = func() []int {
386 q := []int{
387 0, 25, 50, 75, 100, 125, 150, 175, 200, 224, 249, 273, 297, 321, 345, 369, 392, 415, 438, 460, 483, 505, 526, 548,
388 569, 590, 610, 630, 650, 669, 688, 706, 724, 742, 759, 775, 792, 807, 822, 837, 851, 865, 878, 891, 903, 915, 926,
389 936, 946, 955, 964, 972, 980, 987, 993, 999, 1004, 1009, 1013, 1016, 1019, 1021, 1023, 1024, 1024,
390 }
391 t := make([]int, 256)
392 for i := 0; i < 256; i++ {
393 j := i & 127
394 v := 0
395 if j <= 64 {
396 v = q[j]
397 } else {
398 v = q[128-j]
399 }
400 if i >= 128 {
401 v = -v
402 }
403 t[i] = v
404 }
405 return t
406}()
407
408// flut is the drop factor table, Q12: flut[t] = sqrt(1024 / (t + 1/2)) for
409// the bucket t = floor(1024 * d^2 / (d^2 + r^2)), i.e. the stretch
410// sqrt(1 + r^2/d^2) at the bucket's middle. Below bucket 32 (points near the
411// drop's centre) the drop uses exact square roots.
412var flut = func() []int {
413 t := make([]int, 1024)
414 for i := 0; i < 1024; i++ {
415 t[i] = isqrt((1 << 35) / (2*i + 1))
416 }
417 return t
418}()
419
420// ---------------------------------------------------------------------------
421// The bath
422// ---------------------------------------------------------------------------
423
424const (
425 q8 = 8 // sub-pixel scale of the simulation (coordinates are px * q8)
426 sw = 600 // sheet width, px
427 sh = 800 // sheet height, px
428 mg = 160 // points this far outside the sheet (px) are pruned in runs
429 maxPoints = 2800 // point budget (also bounds the SVG size)
430)
431
432type bath struct {
433 xs, ys [][]int
434 cols []string
435 x0, x1, y0, y1 []int // per-polygon boxes: a superset after drops, exact after bounds
436 fresh bool
437 total, limit int
438}
439
440// bounds recomputes every bounding box (after a pass that moved points
441// without tracking them).
442func (b *bath) bounds() {
443 n := len(b.xs)
444 b.x0, b.x1, b.y0, b.y1 = make([]int, n), make([]int, n), make([]int, n), make([]int, n)
445 for p, xs := range b.xs {
446 ys := b.ys[p]
447 x0, x1, y0, y1 := xs[0], xs[0], ys[0], ys[0]
448 for i, x := range xs {
449 if x < x0 {
450 x0 = x
451 } else if x > x1 {
452 x1 = x
453 }
454 if y := ys[i]; y < y0 {
455 y0 = y
456 } else if y > y1 {
457 y1 = y
458 }
459 }
460 b.x0[p], b.x1[p], b.y0[p], b.y1[p] = x0, x1, y0, y1
461 }
462 b.fresh = true
463}
464
465// drop lays a drop of radius rp px at (cxp, cyp). It pushes every boundary
466// within 3r out (the area-preserving stretch up to 1.5r, tapered to nothing
467// at 3r so far paint stays in place), refines the edges within 1.5r inside the
468// point budget, then floats a circle of n points.
469func (b *bath) drop(cxp, cyp, rp int, col string, n, rot int) {
470 if !b.fresh {
471 b.bounds()
472 }
473 cx, cy, r := cxp*q8, cyp*q8, rp*q8
474 r2 := r * r
475 far, far2, near2 := 3*r, 9*r2, 9*r2/4
476 taper := far2 - near2
477 lim := 6 * q8
478 if r/2 > lim {
479 lim = r / 2
480 }
481 total, limit := b.total, b.limit
482 for p, xs := range b.xs {
483 x0, x1, y0, y1 := b.x0[p], b.x1[p], b.y0[p], b.y1[p]
484 if x1 < cx-far || x0 > cx+far || y1 < cy-far || y0 > cy+far {
485 continue
486 }
487 ys := b.ys[p]
488 ln := len(xs)
489 fx, fy := xs[0], ys[0]
490 var mids []int
491 for i, x := range xs {
492 dx, dy := x-cx, ys[i]-cy
493 d2 := dx*dx + dy*dy
494 if d2 >= far2 || d2 == 0 {
495 continue
496 }
497 t := d2 * 1024 / (d2 + r2)
498 if t < 709 && total < limit {
499 y := cy + dy
500 ex, ey := fx-x, fy-y
501 if i+1 < ln {
502 ex, ey = xs[i+1]-x, ys[i+1]-y
503 }
504 if absi(ex)+absi(ey) > lim {
505 mx, my := pushed(x+ex/2, y+ey/2, cx, cy, r2)
506 mids = append(mids, i, mx, my)
507 if mx < x0 {
508 x0 = mx
509 } else if mx > x1 {
510 x1 = mx
511 }
512 if my < y0 {
513 y0 = my
514 } else if my > y1 {
515 y1 = my
516 }
517 total++
518 }
519 }
520 var y int
521 if t < 32 {
522 s, q := isqrt(d2+r2), isqrt(d2)
523 x, y = cx+dx*s/q, cy+dy*s/q
524 } else {
525 f := flut[t] - 4096
526 if d2 > near2 {
527 f = f * (far2 - d2) / taper
528 }
529 x, y = x+dx*f/4096, cy+dy+dy*f/4096
530 }
531 xs[i], ys[i] = x, y
532 if x < x0 {
533 x0 = x
534 } else if x > x1 {
535 x1 = x
536 }
537 if y < y0 {
538 y0 = y
539 } else if y > y1 {
540 y1 = y
541 }
542 }
543 if len(mids) > 0 {
544 nx := make([]int, 0, ln+len(mids)/3)
545 ny := make([]int, 0, ln+len(mids)/3)
546 k := 0
547 for i, x := range xs {
548 nx = append(nx, x)
549 ny = append(ny, ys[i])
550 if k < len(mids) && mids[k] == i {
551 nx = append(nx, mids[k+1])
552 ny = append(ny, mids[k+2])
553 k += 3
554 }
555 }
556 b.xs[p], b.ys[p] = nx, ny
557 }
558 b.x0[p], b.x1[p], b.y0[p], b.y1[p] = x0, x1, y0, y1
559 }
560 xs, ys := make([]int, n), make([]int, n)
561 for k := 0; k < n; k++ {
562 a := (rot + k*256/n) & 255
563 xs[k] = cx + r*sinT[(a+64)&255]/1024
564 ys[k] = cy + r*sinT[a]/1024
565 }
566 b.xs = append(b.xs, xs)
567 b.ys = append(b.ys, ys)
568 b.cols = append(b.cols, col)
569 b.x0, b.x1 = append(b.x0, cx-r), append(b.x1, cx+r)
570 b.y0, b.y1 = append(b.y0, cy-r), append(b.y1, cy+r)
571 b.total = total + n
572}
573
574// pushed is one point pushed by a drop (the refinement midpoints), as in
575// drop.
576func pushed(x, y, cx, cy, r2 int) (int, int) {
577 dx, dy := x-cx, y-cy
578 d2 := dx*dx + dy*dy
579 if d2 >= 9*r2 || d2 == 0 {
580 return x, y
581 }
582 t := d2 * 1024 / (d2 + r2)
583 if t < 32 {
584 s, q := isqrt(d2+r2), isqrt(d2)
585 return cx + dx*s/q, cy + dy*s/q
586 }
587 f := flut[t] - 4096
588 if near2 := 9 * r2 / 4; d2 > near2 {
589 f = f * (9*r2 - d2) / (9*r2 - near2)
590 }
591 return x + dx*f/4096, y + dy*f/4096
592}
593
594func zone(x, y int) int {
595 switch {
596 case x < -mg*q8:
597 return 1
598 case x > (sw+mg)*q8:
599 return 2
600 case y < -mg*q8:
601 return 3
602 case y > (sh+mg)*q8:
603 return 4
604 }
605 return 0
606}
607
608func absi(v int) int {
609 if v < 0 {
610 return -v
611 }
612 return v
613}
614
615// resample prunes the inside of every run of points beyond one edge of the
616// margin (exact for what the sheet shows: no later operation brings them
617// back) and halves the edges longer than maxLen px that touch the margin
618// box, within the point budget. Polygons left with fewer than 3 points are
619// dropped. (zone() is inlined here and in pathOf: a call costs more than the
620// comparisons in GnoVM.)
621func (b *bath) resample(maxLen int) {
622 m := maxLen * q8
623 lo, hx, hy := -mg*q8, (sw+mg)*q8, (sh+mg)*q8
624 oxs := make([][]int, 0, len(b.xs))
625 oys := make([][]int, 0, len(b.xs))
626 ocols := make([]string, 0, len(b.xs))
627 total, limit := b.total, b.limit
628 for p, xs := range b.xs {
629 ys := b.ys[p]
630 ln := len(xs)
631 zs := make([]int, ln)
632 for i, x := range xs {
633 if x < lo {
634 zs[i] = 1
635 } else if x > hx {
636 zs[i] = 2
637 } else if y := ys[i]; y < lo {
638 zs[i] = 3
639 } else if y > hy {
640 zs[i] = 4
641 }
642 }
643 nx, ny := make([]int, 2*ln), make([]int, 2*ln)
644 k, h := 0, zs[ln-1]
645 for i, x := range xs {
646 z, j := zs[i], i+1
647 if j == ln {
648 j = 0
649 }
650 zj := zs[j]
651 if z != 0 && h == z && zj == z {
652 total--
653 continue
654 }
655 h = z
656 y := ys[i]
657 nx[k], ny[k] = x, y
658 k++
659 if total < limit && (z == 0 || zj == 0) {
660 ex, ey := xs[j]-x, ys[j]-y
661 ax, ay := ex, ey
662 if ax < 0 {
663 ax = -ax
664 }
665 if ay < 0 {
666 ay = -ay
667 }
668 if ax+ay > m {
669 nx[k], ny[k] = x+ex/2, y+ey/2
670 k++
671 total++
672 }
673 }
674 }
675 if k < 3 {
676 total -= k
677 continue
678 }
679 oxs = append(oxs, nx[:k])
680 oys = append(oys, ny[:k])
681 ocols = append(ocols, b.cols[p])
682 }
683 b.xs, b.ys, b.cols, b.total = oxs, oys, ocols, total
684 b.fresh = false
685}
686
687// combTable is the summed drag of tines at pos (px along the cross axis),
688// each moving the paint by z px with fall-off lam px, tapered to 0 at rr px.
689// Index = px + mg; values in q8 units.
690func combTable(size int, pos, dirs []int, z, lam, rr int) []int {
691 t := make([]int, size+2*mg)
692 for k := 0; k < len(pos); k++ {
693 for d := -rr; d <= rr; d++ {
694 idx := pos[k] + d + mg
695 if idx < 0 || idx >= len(t) {
696 continue
697 }
698 ad := absi(d)
699 t[idx] += dirs[k] * (z * q8 * lam * (rr - ad) / ((ad + lam) * rr))
700 }
701 }
702 return t
703}
704
705// comb applies a comb table: horizontal false moves y by t[x] (vertical
706// tines), true moves x by t[y]. wave (optional, indexed by the moved axis)
707// bends the tines into a serpentine.
708func (b *bath) comb(t []int, horizontal bool, wave []int) {
709 b.fresh = false
710 top := len(t) - 1
711 for p := 0; p < len(b.xs); p++ {
712 along, moved := b.xs[p], b.ys[p]
713 if horizontal {
714 along, moved = b.ys[p], b.xs[p]
715 }
716 for i := 0; i < len(along); i++ {
717 a := along[i]
718 if wave != nil {
719 w := moved[i]/q8 + mg
720 if w < 0 {
721 w = 0
722 } else if w >= len(wave) {
723 w = len(wave) - 1
724 }
725 a -= wave[w]
726 }
727 idx := a/q8 + mg
728 if idx < 0 {
729 idx = 0
730 } else if idx > top {
731 idx = top
732 }
733 moved[i] += t[idx]
734 }
735 }
736}
737
738// stroke drags a stylus along the y axis (x when horizontal) at cross
739// position c from a to e (px): points near the line move by z px towards e,
740// fading with the distance (fall-off lam, cut at 6 lam) and at both ends.
741// Polygons whose box misses the stroke's reach are skipped (exact: none of
742// their points could move); the boxes of the others grow with their points.
743func (b *bath) stroke(c, a, e, z, lam int, horizontal bool) {
744 if !b.fresh {
745 b.bounds()
746 }
747 dir, lo, hi := 1, a*q8, e*q8
748 if e < a {
749 dir, lo, hi = -1, e*q8, a*q8
750 }
751 cq, lamQ, zq := c*q8, lam*q8, z*q8
752 rq := 6 * lamQ
753 ramp := 3 * lamQ
754 if zq+lamQ > ramp {
755 ramp = zq + lamQ
756 }
757 for p := range b.xs {
758 ac0, ac1, al0, al1 := b.x0[p], b.x1[p], b.y0[p], b.y1[p]
759 across, along := b.xs[p], b.ys[p]
760 if horizontal {
761 ac0, ac1, al0, al1 = b.y0[p], b.y1[p], b.x0[p], b.x1[p]
762 across, along = b.ys[p], b.xs[p]
763 }
764 if ac1 <= cq-rq || ac0 >= cq+rq || al1 <= lo-ramp || al0 >= hi+ramp {
765 continue
766 }
767 for i, v := range along {
768 d := across[i] - cq
769 if d < 0 {
770 d = -d
771 }
772 if d >= rq || v <= lo-ramp || v >= hi+ramp {
773 continue
774 }
775 w := 256
776 if v < lo {
777 w = (v - lo + ramp) * 256 / ramp
778 } else if v > hi {
779 w = (hi + ramp - v) * 256 / ramp
780 }
781 v += dir * (zq * lamQ * (rq - d) / ((d + lamQ) * rq) * w / 256)
782 along[i] = v
783 if v < al0 {
784 al0 = v
785 } else if v > al1 {
786 al1 = v
787 }
788 }
789 if horizontal {
790 b.x0[p], b.x1[p] = al0, al1
791 } else {
792 b.y0[p], b.y1[p] = al0, al1
793 }
794 }
795}
796
797// nestGrid is the bülbül yuvası grid: centres (px), columns, cell size
798// (px) and the squared disc radius (q8 units). Every disc lies inside its
799// cell.
800type nestGrid struct {
801 cx, cy []int
802 cols, cw, ch, r2 int
803}
804
805// at returns the nest whose disc holds (x, y) (q8 units), or -1.
806func (n *nestGrid) at(x, y int) int {
807 if x < 0 || y < 0 {
808 return -1
809 }
810 ci := x / (n.cw * q8)
811 k := y/(n.ch*q8)*n.cols + ci
812 if ci >= n.cols || k >= len(n.cx) {
813 return -1
814 }
815 dx, dy := x-n.cx[k]*q8, y-n.cy[k]*q8
816 if dx*dx+dy*dy < n.r2 {
817 return k
818 }
819 return -1
820}
821
822// nests are bülbül yuvası: stylus spirals; each turns the paint by
823// turns*(1-d^2/R^2)^2 (256 = one turn).
824func (b *bath) nests(n *nestGrid, turns []int) {
825 b.fresh = false
826 r2 := n.r2
827 for p, xs := range b.xs {
828 ys := b.ys[p]
829 for i, x := range xs {
830 y := ys[i]
831 k := n.at(x, y)
832 if k < 0 {
833 continue
834 }
835 kx, ky := n.cx[k]*q8, n.cy[k]*q8
836 dx, dy := x-kx, y-ky
837 u := (r2 - dx*dx - dy*dy) * 256 / r2
838 a := (turns[k] * u * u / 65536) & 255
839 c, s := sinT[(a+64)&255], sinT[a]
840 xs[i] = kx + (dx*c-dy*s)/1024
841 ys[i] = ky + (dx*s+dy*c)/1024
842 }
843 }
844}
845
846// refineDiscs splits the edges inside the nests' discs before they turn. A
847// first pass measures them, so the piece length (at least minLen px) spreads
848// the remaining point budget evenly over every disc.
849func (b *bath) refineDiscs(n *nestGrid, minLen int) {
850 b.fresh = false
851 sum := 0
852 for p, xs := range b.xs {
853 ys := b.ys[p]
854 ln := len(xs)
855 for i, x := range xs {
856 j := i + 1
857 if j == ln {
858 j = 0
859 }
860 ex, ey := xs[j]-x, ys[j]-ys[i]
861 if n.at(x+ex/2, ys[i]+ey/2) >= 0 {
862 sum += absi(ex) + absi(ey)
863 }
864 }
865 }
866 budget := b.limit - b.total
867 if budget <= 0 {
868 return
869 }
870 m := sum/budget + 1
871 if minLen*q8 > m {
872 m = minLen * q8
873 }
874 total, limit := b.total, b.limit
875 for p, xs := range b.xs {
876 ys := b.ys[p]
877 ln := len(xs)
878 nx := make([]int, 0, ln+8)
879 ny := make([]int, 0, ln+8)
880 for i, x := range xs {
881 j := i + 1
882 if j == ln {
883 j = 0
884 }
885 y := ys[i]
886 nx = append(nx, x)
887 ny = append(ny, y)
888 ex, ey := xs[j]-x, ys[j]-y
889 l := absi(ex) + absi(ey)
890 if l <= m || n.at(x+ex/2, y+ey/2) < 0 {
891 continue
892 }
893 pieces := l/m + 1
894 for q := 1; q < pieces && total < limit; q++ {
895 nx = append(nx, x+ex*q/pieces)
896 ny = append(ny, y+ey*q/pieces)
897 total++
898 }
899 }
900 b.xs[p], b.ys[p] = nx, ny
901 }
902 b.total = total
903}
904
905// ---------------------------------------------------------------------------
906// Composition
907// ---------------------------------------------------------------------------
908
909// stoneSizes: radius lo, hi and the count of the first layer, per Stones.
910var stoneSizes = [][3]int{{110, 150, 14}, {84, 118, 20}, {60, 90, 24}}
911
912type painter struct {
913 R *rng
914 pal []string
915 ci int
916}
917
918func (pt *painter) next() string {
919 c := pt.pal[pt.ci%5]
920 pt.ci++
921 return c
922}
923
924// stones is the stone layer: big drops, then smaller ones in between
925// (battal).
926func (b *bath) stones(pt *painter, size int, light bool) {
927 R, sr := pt.R, stoneSizes[size]
928 n1 := sr[2]
929 if light {
930 n1 = sr[2] * 2 / 3
931 }
932 for k := 0; k < n1; k++ {
933 r := R.between(sr[0], sr[1])
934 x := R.between(0, sw)
935 y := R.between(0, sh)
936 col := pt.next()
937 b.drop(x, y, r, col, r/4, R.intn(256))
938 }
939 b.resample(12)
940 n2 := n1 / 2
941 for k := 0; k < n2; k++ {
942 r := R.between(sr[0]/2, sr[1]/2)
943 x := R.between(10, sw-10)
944 y := R.between(10, sh-10)
945 col := pt.next()
946 b.drop(x, y, r, col, r/3, R.intn(256))
947 }
948 b.resample(12)
949}
950
951// gelgit is a stylus drawn back and forth along lines sp px apart, in two
952// half strokes; more = another comb follows.
953func (b *bath) gelgit(R *rng, horizontal bool, sp, z int, more bool) {
954 size := sw
955 if horizontal {
956 size = sh
957 }
958 var pos, dirs []int
959 dir := -1
960 if R.intn(2) == 1 {
961 dir = 1
962 }
963 for x := R.between(4, sp); x < size; x += sp {
964 pos = append(pos, x)
965 dirs = append(dirs, dir)
966 dir = -dir
967 }
968 t := combTable(size, pos, dirs, z/2, 12, 3*sp)
969 b.comb(t, horizontal, nil)
970 b.resample(10)
971 b.comb(t, horizontal, nil)
972 if more { // only when another comb follows
973 b.resample(12)
974 }
975}
976
977// teeth are the positions of a one-way comb, sp px apart.
978func teeth(R *rng, size, sp int) ([]int, []int) {
979 var pos, dirs []int
980 for y := R.between(2, sp); y < size; y += sp {
981 pos = append(pos, y)
982 dirs = append(dirs, 1)
983 }
984 return pos, dirs
985}
986
987// SVG renders seed under cfg.
988func SVG(seed string, cfg Config) string {
989 d := derive(seed, cfg)
990 R := newRNG(seed + "|art") // separate stream: trait draws never shift the art
991 pal := palettes[d.palette]
992 pt := &painter{R: R, pal: pal.paints}
993 pt.ci = R.intn(5)
994 b := &bath{limit: maxPoints}
995 hz := d.flow == 1
996
997 switch d.pattern {
998 case pBattal:
999 b.stones(pt, d.stones, false)
1000 n3 := R.between(5, 8)
1001 for k := 0; k < n3; k++ {
1002 x := R.between(10, sw-10)
1003 y := R.between(10, sh-10)
1004 r := R.between(14, 26)
1005 col := pt.next()
1006 b.drop(x, y, r, col, 20, R.intn(256))
1007 }
1008 case pGelgit:
1009 b.stones(pt, d.stones, false)
1010 sp := R.between(34, 46)
1011 b.gelgit(R, hz, sp, R.between(110, 150), false)
1012 case pTarakli:
1013 b.stones(pt, d.stones, false)
1014 sp := R.between(40, 52)
1015 b.gelgit(R, hz, sp, R.between(100, 130), true)
1016 size := sh
1017 if hz {
1018 size = sw
1019 }
1020 sp = R.between(22, 28)
1021 pos, dirs := teeth(R, size, sp)
1022 b.comb(combTable(size, pos, dirs, 18, 7, 2*sp), !hz, nil)
1023 case pSal:
1024 b.stones(pt, d.stones, false)
1025 sp := R.between(40, 52)
1026 b.gelgit(R, hz, sp, R.between(100, 130), true)
1027 size, other := sh, sw
1028 if hz {
1029 size, other = sw, sh
1030 }
1031 sp = R.between(44, 56)
1032 amp := R.between(16, 26)
1033 per := R.between(70, 110)
1034 pos, dirs := teeth(R, size, sp)
1035 wave := make([]int, other+2*mg)
1036 for i := range wave {
1037 wave[i] = amp * q8 * sinT[((i-mg)*256/per)&255] / 1024
1038 }
1039 b.comb(combTable(size, pos, dirs, 30, 16, 2*sp), !hz, wave)
1040 case pHatip:
1041 b.stones(pt, d.stones, true)
1042 cols := R.between(2, 3)
1043 rows := 3
1044 var cx, cy, rr []int
1045 for j := 0; j < rows; j++ {
1046 for i := 0; i < cols; i++ {
1047 x := sw*(2*i+1)/(2*cols) + R.between(-12, 12)
1048 y := sh*(2*j+1)/(2*rows) + R.between(-12, 12)
1049 r := R.between(34, 48)
1050 cx, cy, rr = append(cx, x), append(cy, y), append(rr, r)
1051 for k := 0; k < 4; k++ {
1052 col := pt.next()
1053 b.drop(x, y, r*(4-k)/4, col, 36-6*k, R.intn(256))
1054 }
1055 }
1056 }
1057 b.resample(10)
1058 down := R.intn(2) == 1
1059 for k := range cx {
1060 r := rr[k]
1061 if down {
1062 b.stroke(cx[k], cy[k]-r*3/2, cy[k]+r*3/2, r*4/5, r/7, false)
1063 } else {
1064 b.stroke(cx[k], cy[k]+r*3/2, cy[k]-r*3/2, r*4/5, r/7, false)
1065 }
1066 }
1067 case pBulbul:
1068 b.limit = maxPoints - 1400 // the nests need points of their own
1069 b.stones(pt, d.stones, false)
1070 sp := R.between(36, 46)
1071 b.gelgit(R, hz, sp, R.between(90, 120), false)
1072 b.limit = maxPoints
1073 n := &nestGrid{cols: 3, cw: sw / 3, ch: sh / 4}
1074 rad := n.cw * 7 / 20
1075 if n.ch < n.cw {
1076 rad = n.ch * 7 / 20
1077 }
1078 n.r2 = rad * rad * q8 * q8
1079 var turns []int
1080 spin := -1
1081 if R.intn(2) == 1 {
1082 spin = 1
1083 }
1084 for j := 0; j < 4; j++ {
1085 for i := 0; i < 3; i++ {
1086 x := i*n.cw + n.cw/2 + R.between(-6, 6)
1087 y := j*n.ch + n.ch/2 + R.between(-6, 6)
1088 n.cx, n.cy = append(n.cx, x), append(n.cy, y)
1089 turns = append(turns, spin*R.between(150, 230))
1090 }
1091 }
1092 b.refineDiscs(n, 3)
1093 b.nests(n, turns)
1094 case pCicekli:
1095 b.stones(pt, d.stones, true)
1096 leaf := pal.paints[pal.leaf]
1097 n := R.between(3, 4)
1098 var fx, fy, fr []int
1099 for k := 0; k < n; k++ {
1100 x := sw*(2*k+1)/(2*n) + R.between(-10, 10)
1101 y := R.between(250, 430) + (k%2)*90
1102 r := R.between(40, 52)
1103 fx, fy, fr = append(fx, x), append(fy, y), append(fr, r)
1104 // stem and leaves first: the cup floats on top of them
1105 b.drop(x, y+r*5/3, r/4, leaf, 16, 0)
1106 b.drop(x-r*3/4, y+r*5/2, r/3, leaf, 20, 0)
1107 b.drop(x+r*3/4, y+r*5/2, r/3, leaf, 20, 0)
1108 petal := pt.next()
1109 b.drop(x, y, r, petal, 40, 0)
1110 b.drop(x, y+r/6, r*3/5, pt.next(), 32, 0)
1111 b.drop(x, y+r/4, r/4, petal, 20, 0)
1112 }
1113 b.resample(8)
1114 for k := 0; k < n; k++ {
1115 x, y, r := fx[k], fy[k], fr[k]
1116 // three petal tips: the stylus pulled up through the cup
1117 b.stroke(x-r*2/5, y+r/3, y-r*3/2, r*3/5, r/8, false)
1118 b.stroke(x+r*2/5, y+r/3, y-r*3/2, r*3/5, r/8, false)
1119 b.stroke(x, y, y-r*7/4, r*4/5, r/8, false)
1120 // stem pulled down, leaves pulled up and out
1121 b.stroke(x, y+r*3/2, y+r*9/2, r*5/2, r/10, false)
1122 b.stroke(x-r*3/4, y+r*3, y+r*3/2, r*3/2, r/8, false)
1123 b.stroke(x+r*3/4, y+r*3, y+r*3/2, r*3/2, r/8, false)
1124 }
1125 }
1126 return b.svg(R, d, groundColors[d.ground])
1127}
1128
1129// ---------------------------------------------------------------------------
1130// Output
1131// ---------------------------------------------------------------------------
1132
1133// nums holds the decimal strings of -127..127: 99.99 % of the path steps
1134// (strconv.Itoa is the dearest primitive an SVG writer has in GnoVM, and a
1135// bigger table costs storage for every deploy).
1136var nums = func() []string {
1137 t := make([]string, 255)
1138 for i := range t {
1139 t[i] = strconv.Itoa(i - 127)
1140 }
1141 return t
1142}()
1143
1144func num(v int) string {
1145 if v >= -127 && v <= 127 {
1146 return nums[v+127]
1147 }
1148 return strconv.Itoa(v)
1149}
1150
1151// pathOf is the path of one polygon: rounded to px, runs beyond the margin
1152// pruned, steps under 2 px merged.
1153func pathOf(xs, ys []int) string {
1154 ln := len(xs)
1155 lo, hx, hy := -mg*q8, (sw+mg)*q8, (sh+mg)*q8
1156 zs := make([]int, ln)
1157 inside := false
1158 for i, x := range xs {
1159 if x < lo {
1160 zs[i] = 1
1161 } else if x > hx {
1162 zs[i] = 2
1163 } else if y := ys[i]; y < lo {
1164 zs[i] = 3
1165 } else if y > hy {
1166 zs[i] = 4
1167 } else {
1168 inside = true
1169 }
1170 }
1171 if !inside {
1172 // a polygon fully beyond the margin is drawn only when it may cover the sheet
1173 x0, x1, y0, y1 := xs[0], xs[0], ys[0], ys[0]
1174 for i, x := range xs {
1175 if x < x0 {
1176 x0 = x
1177 } else if x > x1 {
1178 x1 = x
1179 }
1180 if y := ys[i]; y < y0 {
1181 y0 = y
1182 } else if y > y1 {
1183 y1 = y
1184 }
1185 }
1186 if x1 < 0 || x0 > sw*q8 || y1 < 0 || y0 > sh*q8 {
1187 return ""
1188 }
1189 }
1190 d := ""
1191 px, py, cnt, h := 0, 0, 0, zs[ln-1]
1192 for i, x := range xs {
1193 z, j := zs[i], i+1
1194 if j == ln {
1195 j = 0
1196 }
1197 if z != 0 && h == z && zs[j] == z {
1198 continue
1199 }
1200 h = z
1201 y := ys[i]
1202 if x < 0 {
1203 x = (x - 4) / q8
1204 } else {
1205 x = (x + 4) / q8
1206 }
1207 if y < 0 {
1208 y = (y - 4) / q8
1209 } else {
1210 y = (y + 4) / q8
1211 }
1212 if cnt == 0 {
1213 d = "M" + num(x) + " " + num(y) + "l"
1214 px, py, cnt = x, y, 1
1215 continue
1216 }
1217 dx, dy := x-px, y-py
1218 ax, ay := dx, dy
1219 if ax < 0 {
1220 ax = -ax
1221 }
1222 if ay < 0 {
1223 ay = -ay
1224 }
1225 if ax+ay < 2 {
1226 continue
1227 }
1228 sx, sy := "", ""
1229 if ax < 128 {
1230 sx = nums[dx+127]
1231 } else {
1232 sx = strconv.Itoa(dx)
1233 }
1234 if ay < 128 {
1235 sy = nums[dy+127]
1236 } else {
1237 sy = strconv.Itoa(dy)
1238 }
1239 if dy >= 0 {
1240 sy = " " + sy
1241 }
1242 if cnt > 1 && dx >= 0 {
1243 d += " " + sx + sy
1244 } else {
1245 d += sx + sy
1246 }
1247 px, py = x, y
1248 cnt++
1249 }
1250 if cnt < 3 {
1251 return ""
1252 }
1253 return d + "z"
1254}
1255
1256func (b *bath) svg(R *rng, d draw, ground string) string {
1257 s1 := R.between(1, 900)
1258 s2 := R.between(1, 900)
1259 body := ""
1260 for p := 0; p < len(b.xs); p++ {
1261 path := pathOf(b.xs[p], b.ys[p])
1262 if path != "" {
1263 body += `<path fill="` + b.cols[p] + `" d="` + path + `"/>`
1264 }
1265 }
1266 defs := `<filter id="o" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".02" numOctaves="2" seed="` +
1267 num(s1) + `"/>` +
1268 `<feDisplacementMap in="SourceGraphic" scale="5" xChannelSelector="R" yChannelSelector="G"/></filter>` +
1269 `<filter id="p" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".7" numOctaves="2" seed="` +
1270 num(s2) + `"/>` +
1271 `<feColorMatrix values="0 0 0 0 .3 0 0 0 0 .25 0 0 0 0 .2 0 0 0 -1.6 .78"/></filter>`
1272 paint := `<g filter="url(#o)" stroke="#1a1410" stroke-opacity=".14" stroke-width="1.2">` + body + `</g>`
1273 if d.finish == fNeftli {
1274 // turpentine: the paint breaks into small cells that show the bath
1275 defs += `<filter id="n" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".09" numOctaves="1" seed="` +
1276 num(R.between(1, 900)) + `"/>` +
1277 `<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 12 0 0 0 -3.3"/><feComposite in="SourceGraphic" operator="in"/></filter>`
1278 paint = `<g filter="url(#n)">` + paint + `</g>`
1279 }
1280 over := ""
1281 if d.finish == fZerefsan {
1282 // gold dust shaken over the sheet
1283 a := R.between(0, 89)
1284 c := R.between(0, 89)
1285 defs += `<pattern id="z" width="37" height="41" patternUnits="userSpaceOnUse" patternTransform="rotate(` + num(a) + `)">` +
1286 `<circle cx="5" cy="9" r="1.3"/><circle cx="23" cy="4" r=".8"/><circle cx="17" cy="27" r="1.6"/><circle cx="31" cy="33" r=".9"/></pattern>` +
1287 `<pattern id="y" width="53" height="47" patternUnits="userSpaceOnUse" patternTransform="rotate(` + num(c) + `)">` +
1288 `<circle cx="11" cy="20" r="1.1"/><circle cx="40" cy="12" r="1.8"/><circle cx="29" cy="41" r=".7"/></pattern>`
1289 over = `<g fill="#c9a24a" opacity=".85"><rect width="600" height="800" fill="url(#z)"/><rect width="600" height="800" fill="url(#y)"/></g>`
1290 }
1291 frame := ""
1292 switch d.frame {
1293 case frCetvel:
1294 frame = `<g fill="none" stroke="#c9a24a"><rect x="16" y="16" width="568" height="768" stroke-width="3"/>` +
1295 `<rect x="23" y="23" width="554" height="754" stroke-width="1"/></g>`
1296 case frKenar:
1297 // the sheet as the margin (kenar) of a calligraphy panel: a plain field ruled in gold, with gilt corner pieces
1298 defs += `<path id="k" d="M0 0h58q-30 26-58 58z" fill="#c9a24a"/>`
1299 frame = `<rect x="120" y="160" width="360" height="480" fill="#f4ecda"/>` +
1300 `<use href="#k" transform="translate(128 168)"/><use href="#k" transform="translate(472 168) scale(-1 1)"/>` +
1301 `<use href="#k" transform="translate(128 632) scale(1 -1)"/><use href="#k" transform="translate(472 632) scale(-1 -1)"/>` +
1302 `<g fill="none" stroke="#c9a24a"><rect x="120" y="160" width="360" height="480" stroke-width="4"/>` +
1303 `<rect x="128" y="168" width="344" height="464" stroke-width="1"/>` +
1304 `<rect x="112" y="152" width="376" height="496" stroke="#1a1410" stroke-opacity=".5" stroke-width="1"/></g>`
1305 }
1306 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 800"><defs>` + defs + `</defs>` +
1307 `<rect width="600" height="800" fill="` + ground + `"/>` + paint + over +
1308 `<rect width="600" height="800" filter="url(#p)" opacity=".35"/>` + frame + `</svg>`
1309}