kilim.gno
33.74 Kb · 1185 lines
1// Package kilim (v2, "Niyet") is a Sinopia engine: a flat-woven rug that
2// says something. The seed first chooses an intent (Protection, Abundance,
3// Wish, Strength), then a main motif and two companions from fourteen
4// Anatolian motif families, each with its traditional meaning (Elibelinde,
5// Koçboynuzu, Bereket, Nazarlık, ...). The motifs are woven cell by cell on a
6// 49 x 75 loom grid into one of five layouts inside one of five borders, and
7// the token number is woven into the bottom frame as a 14-bit band (the
8// "künye"). The meanings reach collectors through the traits (Main Motif,
9// Companions and Border carry them) and the SVG's <title>/<desc>.
10//
11// It is the successor of Kilim v1 (p/.../art/kilim/v1, which stays untouched):
12// the same loom, the same FNV-1a + splitmix64 streams (seed+"|traits" and
13// seed+"|art"), the same run-length SVG encoding, a richer field.
14// frontend/src/engines/kilimv2.ts is a byte-identical TypeScript twin;
15// kilim_test.gno pins golden vectors that the twin asserts too.
16//
17// Unlike v1 the art reads Input.TokenID (the künye). It never reads heights
18// or moves, so the engine is not living. Pure integer maths: no floats, no
19// time, no block data.
20package kilim
21
22import (
23 "errors"
24 "strconv"
25 "strings"
26
27 "gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/engine/v2"
28)
29
30// TraitTypes in the order Traits returns them.
31var traitTypes = []string{"Intent", "Main Motif", "Companions", "Layout", "Border", "Dyes", "Weaver's Mark", "Rarity"}
32
33// MaxSVGBytes: the largest output over 10,000 default seeds is about 14.6 KB
34// (docs/engines/kilim-v2.md); about 2x margin, within the 28 KB budget.
35const MaxSVGBytes = 28672
36
37// ParamsSchema is the Studio form. Studio sends JSON.stringify of the values
38// in this property order; ValidateParams accepts exactly that or "".
39const ParamsSchema = `{"type":"object","properties":{` +
40 `"intent":{"type":"string","title":"Intent","enum":["Seeded","Protection","Abundance","Wish","Strength"],"default":"Seeded"},` +
41 `"layout":{"type":"string","title":"Layout","enum":["Seeded","Three Göls","Great Göl","Lattice","Bands","Mihrab"],"default":"Seeded"},` +
42 `"dyes":{"type":"string","title":"Dyes","enum":["Seeded","Madder & Indigo","Buckthorn Gold","Walnut & Fleece",` +
43 `"Pomegranate","Night Indigo","Highland Green","Sinopia Earth","Saffron & Plum"],"default":"Seeded"}}}`
44
45// DefaultParams is the canonical form of the defaults; it renders exactly
46// like "".
47const DefaultParams = `{"intent":"Seeded","layout":"Seeded","dyes":"Seeded"}`
48
49// Manifest describes the engine. Author and FeeBps are set by the adapter.
50func Manifest() engine.Manifest {
51 return engine.Manifest{
52 Name: "Kilim · Niyet",
53 Version: "2.0.0",
54 Description: "Kilim v2: a flat-woven rug that speaks. Each rug chooses an intent (protection, abundance, " +
55 "a wish or strength) and weaves a main motif and two companions from fourteen Anatolian motif " +
56 "families, each with its traditional meaning, inside a meaningful border. The traits carry the " +
57 "meanings; the token number is woven into the bottom frame in binary.",
58 License: "CC-BY-NC-4.0",
59 ParamsSchema: ParamsSchema,
60 TraitTypes: append([]string{}, traitTypes...),
61 Living: false,
62 MaxSVGBytes: MaxSVGBytes,
63 Kind: engine.KindSVG,
64 }
65}
66
67// Config is a parsed params string; -1 means drawn from the seed.
68type Config struct {
69 Intent, Layout, Dyes int
70}
71
72// Defaults is the showcase look (params "").
73func Defaults() Config { return Config{Intent: -1, Layout: -1, Dyes: -1} }
74
75var errParams = errors.New(`kilimv2: params must be "" or ` +
76 `{"intent":<enum>,"layout":<enum>,"dyes":<enum>} in that order, without spaces`)
77
78// ParseParams accepts "" or the canonical JSON Studio produces, nothing else.
79func ParseParams(params string) (Config, error) {
80 cfg := Defaults()
81 if params == "" {
82 return cfg, nil
83 }
84 v, rest, ok := strValue(params, `{"intent":"`)
85 if !ok {
86 return cfg, errParams
87 }
88 if cfg.Intent, ok = enumIndex(v, intentOpts); !ok {
89 return cfg, errParams
90 }
91 if v, rest, ok = strValue(rest, `","layout":"`); !ok {
92 return cfg, errParams
93 }
94 if cfg.Layout, ok = enumIndex(v, layoutOpts); !ok {
95 return cfg, errParams
96 }
97 if v, rest, ok = strValue(rest, `","dyes":"`); !ok {
98 return cfg, errParams
99 }
100 if cfg.Dyes, ok = enumIndex(v, dyeOpts); !ok {
101 return cfg, errParams
102 }
103 if rest != `"}` {
104 return cfg, errParams
105 }
106 return cfg, nil
107}
108
109// strValue expects s to start with prefix and returns the text up to the
110// next '"' and the remainder starting at that quote.
111func strValue(s, prefix string) (string, string, bool) {
112 if !strings.HasPrefix(s, prefix) {
113 return "", "", false
114 }
115 s = s[len(prefix):]
116 end := strings.IndexByte(s, '"')
117 if end < 0 {
118 return "", "", false
119 }
120 return s[:end], s[end:], true
121}
122
123func enumIndex(v string, table []option) (int, bool) {
124 if v == "Seeded" {
125 return -1, true
126 }
127 for i, o := range table {
128 if o.name == v {
129 return i, true
130 }
131 }
132 return 0, false
133}
134
135// ValidateParams accepts "" (the showcase defaults) and the canonical JSON.
136func ValidateParams(params string) error {
137 _, err := ParseParams(params)
138 return err
139}
140
141func mustConfig(params string) Config {
142 cfg, err := ParseParams(params)
143 if err != nil {
144 panic(err)
145 }
146 return cfg
147}
148
149// Traits returns the eight traits of in.Seed in TraitTypes order. It never
150// renders: eleven draws and a score.
151func Traits(in engine.Input) []engine.Trait {
152 t := TraitsOf(in.Seed, mustConfig(in.Params))
153 return []engine.Trait{
154 {Type: "Intent", Value: t.Intent},
155 {Type: "Main Motif", Value: t.MainMotif},
156 {Type: "Companions", Value: t.Companions},
157 {Type: "Layout", Value: t.Layout},
158 {Type: "Border", Value: t.Border},
159 {Type: "Dyes", Value: t.Dyes},
160 {Type: "Weaver's Mark", Value: t.Mark},
161 {Type: "Rarity", Value: t.Rarity},
162 }
163}
164
165// Render returns the raw SVG for in.Seed, in.Params and in.TokenID.
166func Render(in engine.Input) string { return SVG(in.Seed, mustConfig(in.Params), in.TokenID) }
167
168// ---------------------------------------------------------------------------
169// Deterministic randomness: FNV-1a over the seed, then splitmix64 (Kilim v1's
170// stream). Traits use seed+"|traits", the art seed+"|art".
171// ---------------------------------------------------------------------------
172
173type rng struct{ state uint64 }
174
175func newRNG(seed string) *rng {
176 h := uint64(14695981039346656037)
177 for i := 0; i < len(seed); i++ {
178 h ^= uint64(seed[i])
179 h *= 1099511628211
180 }
181 if h == 0 {
182 h = 1099511628211
183 }
184 return &rng{state: h}
185}
186
187func (r *rng) next() uint64 {
188 r.state += 0x9E3779B97F4A7C15
189 z := r.state
190 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9
191 z = (z ^ (z >> 27)) * 0x94D049BB133111EB
192 return z ^ (z >> 31)
193}
194
195// intn is in [0, n); one draw whenever n > 0.
196func (r *rng) intn(n int) int {
197 if n <= 0 {
198 return 0
199 }
200 return int(r.next() % uint64(n))
201}
202
203// between is in [a, b].
204func (r *rng) between(a, b int) int { return a + r.intn(b-a+1) }
205
206// ---------------------------------------------------------------------------
207// Motifs. Bitmaps: '.' empty, '#' outline, '+' light, 'o' accent; drawn for
208// this engine on the loom grid (odd widths, stepped diagonals).
209// ---------------------------------------------------------------------------
210
211type motif struct {
212 name, gloss, meaning string
213 bm []string
214}
215
216var motifs = []motif{
217 {"Elibelinde", "motherhood", "motherhood and fertility", []string{
218 "....#o#....", "....###....", ".....#.....", ".#########.", "#.#.#+#.#.#", "#..##o##..#",
219 ".#..#+#..#.", "..#######..", "...#+o+#...", "..#+++++#..", ".#+++o+++#.", "###########"}},
220 {"Koçboynuzu", "strength", "strength, heroism and male fertility", []string{
221 ".###...###.", "#...#.#...#", "#.#.#.#.#.#", "#.###.###.#", "##...#...##", ".#...#...#.",
222 ".....#.....", "....#+#....", "...#+o+#...", "....#+#....", ".....#....."}},
223 {"Bereket", "plenty", "plenty and a fruitful home", []string{
224 "#....#....#", ".#..###..#.", "..#######..", ".##+#+#+##.", "###+o+o+###", ".##+#+#+##.",
225 "..#######..", ".#..###..#.", "#....#....#"}},
226 {"Nazarlık", "warding", "protection from the evil eye", []string{
227 ".....#.....", "....#+#....", "...#+++#...", "..#++o++#..", ".#++ooo++#.", "#++oo#oo++#",
228 ".#++ooo++#.", "..#++o++#..", "...#+++#...", "....#+#....", ".....#....."}},
229 {"Yıldız", "luck", "happiness, luck and guidance", []string{
230 ".....#.....", ".#...#...#.", "..#.###.#..", "...#####...", "..##+++##..", "####+o+####",
231 "..##+++##..", "...#####...", "..#.###.#..", ".#...#...#.", ".....#....."}},
232 {"Hayat Ağacı", "eternity", "immortality and the line that goes on", []string{
233 ".....o.....", "....###....", "..#..#..#..", ".###.#.###.", "..#.#+#.#..", ".....#.....",
234 ".#..###..#.", "###.#+#.###", ".#..#+#..#.", ".....#.....", "..#..#..#..", ".###+#+###.", "...#####..."}},
235 {"Pıtrak", "defence", "a thorn that wards off evil", []string{
236 "..#..#..#..", "...#.#.#...", "#...###...#", ".#.##+##.#.", "..##+o+##..", "####ooo####",
237 "..##+o+##..", ".#.##+##.#.", "#...###...#", "...#.#.#...", "..#..#..#.."}},
238 {"Akrep", "safety", "safety from scorpions and all harm", []string{
239 "..#.....#..", ".#.#...#.#.", "..#.###.#..", "...##+##...", "....#+#....", "..#######..",
240 ".#..#o#..#.", "#...#+#...#", "....###....", ".....#.....", "....#.#...."}},
241 {"Kurt İzi", "valour", "guarding the flock; courage", []string{
242 "...#...#...", "..###.###..", "...#...#...", ".#.......#.", "###.....###", ".#..###..#.",
243 "...#####...", "..###o###..", "...#####...", "....###...."}},
244 {"Saç Bağı", "marriage", "the wish to marry", []string{
245 "#.........#", "##.......##", "#+#.....#+#", "#++#...#++#", "#+++#.#+++#", ".####o####.",
246 "#+++#.#+++#", "#++#...#++#", "#+#.....#+#", "##.......##", "#.........#"}},
247 {"Bukağı", "unity", "unity; a family never parted", []string{
248 ".###...###.", "#...#.#...#", "#.#.###.#.#", "#.#..#..#.#", ".#..#+#..#.", "...#+o+#...",
249 ".#..#+#..#.", "#.#..#..#.#", "#.#.###.#.#", "#...#.#...#", ".###...###."}},
250 {"Muska", "talisman", "an amulet for luck and safety", []string{
251 ".....#.....", "....#+#....", "...#+o+#...", "..#+++++#..", ".#+o+o+o+#.", "###########",
252 "....#.#....", "....#.#....", "...#...#..."}},
253 {"Turna", "longing", "love, longing and news from afar", []string{
254 ".....#.....", "....###....", "#....#....#", "##..###..##", ".##.###.##.", "..#######..",
255 "...#####...", "....###....", "...#.#.#...", "..#..#..#.."}},
256 {"Sandık", "hope", "the dowry chest: hope and a new home", []string{
257 "###########", "#+++++++++#", "#+#######+#", "#+#ooooo#+#", "#+#######+#", "#+++++++++#",
258 "###########", ".#.......#."}},
259}
260
261const (
262 mElibelinde = iota
263 mKocboynuzu
264 mBereket
265 mNazarlik
266 mYildiz
267 mHayat
268 mPitrak
269 mAkrep
270 mKurtizi
271 mSacbagi
272 mBukagi
273 mMuska
274 mTurna
275 mSandik
276)
277
278var (
279 tohum = []string{".#.", "#o#", ".#."}
280 kgoz = []string{"..#..", ".#o#.", "#ooo#", ".#o#.", "..#.."}
281 kyildiz = []string{"#...#", ".#.#.", "..o..", ".#.#.", "#...#"}
282)
283
284// MotifMeaning returns the name, one-word gloss and meaning of motif i
285// (0..13), the dictionary collectors see in the traits.
286func MotifMeaning(i int) (name, gloss, meaning string) {
287 m := motifs[i]
288 return m.name, m.gloss, m.meaning
289}
290
291// MotifCount is the number of motif families.
292func MotifCount() int { return len(motifs) }
293
294// ---------------------------------------------------------------------------
295// Trait tables. A weight is a percent; score feeds the rarity tier.
296// ---------------------------------------------------------------------------
297
298type option struct {
299 name string
300 weight int
301 score int
302}
303
304func pick(r *rng, table []option) int {
305 total := 0
306 for _, o := range table {
307 total += o.weight
308 }
309 x := r.intn(total)
310 for i, o := range table {
311 x -= o.weight
312 if x < 0 {
313 return i
314 }
315 }
316 return len(table) - 1
317}
318
319var intentOpts = []option{{"Protection", 30, 0}, {"Abundance", 28, 0}, {"Wish", 26, 0}, {"Strength", 16, 0}}
320
321// families: the motif family of each intent.
322var families = [][]int{
323 {mNazarlik, mPitrak, mAkrep, mMuska, mKurtizi},
324 {mElibelinde, mBereket, mHayat, mKocboynuzu},
325 {mSacbagi, mBukagi, mSandik, mTurna, mYildiz},
326 {mKocboynuzu, mKurtizi, mAkrep, mYildiz},
327}
328
329const (
330 layThree = iota
331 layGreat
332 layLattice
333 layBands
334 layMihrab
335)
336
337var layoutOpts = []option{{"Three Göls", 30, 0}, {"Great Göl", 22, 1}, {"Lattice", 18, 0}, {"Bands", 18, 0}, {"Mihrab", 12, 2}}
338
339const (
340 bWolf = iota
341 bWater
342 bEyes
343 bAmulets
344 bStars
345)
346
347var borderOpts = []option{
348 {"Kurt Ağzı", 26, 0}, {"Su Yolu", 22, 0}, {"Göz Dizisi", 20, 0}, {"Muska Dizisi", 18, 0}, {"Yıldız Dizisi", 14, 0},
349}
350
351var borderMeanings = []string{
352 "teeth that guard the flock and the home",
353 "the flow of life, never broken",
354 "a row of eyes that seals the edge from harm",
355 "a belt of triangle amulets",
356 "guiding stars all around",
357}
358
359var dyeOpts = []option{
360 {"Madder & Indigo", 22, 0}, {"Buckthorn Gold", 14, 0}, {"Walnut & Fleece", 12, 0}, {"Pomegranate", 14, 0},
361 {"Night Indigo", 12, 0}, {"Highland Green", 10, 2}, {"Sinopia Earth", 8, 2}, {"Saffron & Plum", 8, 2},
362}
363
364// palettes: ground, dark, madder (m), saffron (s), light, accent, abrash ground.
365var palettes = [][]string{
366 {"#a6342b", "#1e2542", "#2e5578", "#d8a23b", "#ecdfc4", "#4b6e44", "#8f2c26"},
367 {"#d4a03c", "#3a2418", "#a33a28", "#2f4f6e", "#f1e4c6", "#6b7a3a", "#c2903a"},
368 {"#e6d9bf", "#3b2b20", "#7a5236", "#a8865c", "#f8f1e2", "#5a4433", "#d8caae"},
369 {"#6e1f28", "#1a1320", "#c0502e", "#e2b257", "#efe0c8", "#2f6a6a", "#5f1b24"},
370 {"#1f2b4a", "#0e1322", "#a9362d", "#d9b46a", "#e7dcc6", "#5b8a8c", "#28365a"},
371 {"#4e6a3f", "#22281c", "#b03a2c", "#e0b04a", "#eee2c8", "#2e4f74", "#435c36"},
372 {"#b4583c", "#2a1a14", "#e9d8ba", "#6d2a1e", "#f3e7d0", "#c9963c", "#a24e35"},
373 {"#5a2e55", "#1c1020", "#e0a630", "#c24a3a", "#f1e3c4", "#3f7a6a", "#4c2648"},
374}
375
376// darkGround: motifs on bare ground get a light outline on these dyes.
377var darkGround = []bool{false, false, false, true, true, false, false, true}
378
379const (
380 abrashNone = iota
381 abrashFaint
382 abrashStrong
383)
384
385var abrashOpts = []option{{"None", 30, 0}, {"Faint", 50, 0}, {"Strong", 20, 0}}
386
387const (
388 fringeLoose = iota
389 fringeKnotted
390 fringeBraided
391)
392
393var fringeOpts = []option{{"Loose", 50, 0}, {"Knotted", 35, 0}, {"Braided", 15, 0}}
394
395var marks = []string{"None", "Nazar Bead", "On the Loom", "Nazar Bead + On the Loom"}
396
397// Rarity: sum of the drawn traits' scores (a trait pinned by params scores
398// 0). Over 10,000 sample seeds with default params: Common 37.4% /
399// Uncommon 39.1% / Rare 17.0% / Legendary 5.2% / Mythic 1.3%.
400const (
401 scoreNazar = 3
402 scoreLoom = 4
403 scoreMainRare = 1 // Hayat Ağacı or Sandık as the main motif
404 scoreMythic = 7
405 scoreLegendary = 5
406 scoreRare = 3
407 scoreUncommon = 1
408)
409
410type draw struct {
411 intent int
412 main, second, third int
413 layout, border, dyes int
414 abrash, fringe int
415 nazar, loom bool
416 score int
417 rarity string
418}
419
420func derive(seed string, cfg Config) draw {
421 r := newRNG(seed + "|traits")
422 // Draw order is part of the contract: changing it changes every token.
423 var d draw
424 d.intent = pick(r, intentOpts)
425 r0, r1, r2, r3 := r.intn(60), r.intn(60), r.intn(100), r.intn(60)
426 d.layout = pick(r, layoutOpts)
427 d.border = pick(r, borderOpts)
428 d.dyes = pick(r, dyeOpts)
429 d.abrash = pick(r, abrashOpts)
430 d.fringe = pick(r, fringeOpts)
431 d.nazar = r.intn(100) < 9
432 d.loom = r.intn(100) < 5
433 // Params override after the draws, so the stream never shifts.
434 score := 0
435 if cfg.Intent >= 0 {
436 d.intent = cfg.Intent
437 } else {
438 score += intentOpts[d.intent].score
439 }
440 if cfg.Layout >= 0 {
441 d.layout = cfg.Layout
442 } else {
443 score += layoutOpts[d.layout].score
444 }
445 if cfg.Dyes >= 0 {
446 d.dyes = cfg.Dyes
447 } else {
448 score += dyeOpts[d.dyes].score
449 }
450 // the motif sentence: main and second from the intent's family, the
451 // third from anywhere (55%) or from the family
452 fam := families[d.intent]
453 n := len(fam)
454 d.main = fam[r0%n]
455 var rest []int
456 for _, k := range fam {
457 if k != d.main {
458 rest = append(rest, k)
459 }
460 }
461 d.second = rest[r1%(n-1)]
462 var pool []int
463 if r2 < 55 {
464 for k := 0; k < len(motifs); k++ {
465 if k != d.main && k != d.second {
466 pool = append(pool, k)
467 }
468 }
469 } else {
470 for _, k := range rest {
471 if k != d.second {
472 pool = append(pool, k)
473 }
474 }
475 }
476 d.third = pool[r3%len(pool)]
477 if d.main == mHayat || d.main == mSandik {
478 score += scoreMainRare
479 }
480 if d.nazar {
481 score += scoreNazar
482 }
483 if d.loom {
484 score += scoreLoom
485 }
486 d.score = score
487 switch {
488 case score >= scoreMythic:
489 d.rarity = "Mythic"
490 case score >= scoreLegendary:
491 d.rarity = "Legendary"
492 case score >= scoreRare:
493 d.rarity = "Rare"
494 case score >= scoreUncommon:
495 d.rarity = "Uncommon"
496 default:
497 d.rarity = "Common"
498 }
499 return d
500}
501
502// TraitSet is the decoded properties of a seed under a config.
503type TraitSet struct {
504 Intent, MainMotif, Companions, Layout, Border, Dyes, Mark string
505 Score int
506 Rarity string
507}
508
509// TraitsOf returns the decoded traits for a seed.
510func TraitsOf(seed string, cfg Config) TraitSet {
511 d := derive(seed, cfg)
512 m0, m1, m2 := motifs[d.main], motifs[d.second], motifs[d.third]
513 mark := 0
514 if d.nazar {
515 mark++
516 }
517 if d.loom {
518 mark += 2
519 }
520 return TraitSet{
521 Intent: intentOpts[d.intent].name,
522 MainMotif: m0.name + ": " + m0.meaning,
523 Companions: m1.name + " (" + m1.gloss + ") + " + m2.name + " (" + m2.gloss + ")",
524 Layout: layoutOpts[d.layout].name,
525 Border: borderOpts[d.border].name + ": " + borderMeanings[d.border],
526 Dyes: dyeOpts[d.dyes].name,
527 Mark: marks[mark],
528 Score: d.score,
529 Rarity: d.rarity,
530 }
531}
532
533// KunyeNumber is Input.TokenID read as a decimal, modulo 2^14 (the band has
534// 14 bits; core's supply cap is 10,000). Anything but ASCII digits is 0.
535func KunyeNumber(tokenID string) int {
536 v := 0
537 for i := 0; i < len(tokenID); i++ {
538 c := tokenID[i]
539 if c < '0' || c > '9' {
540 return 0
541 }
542 v = (v*10 + int(c-'0')) % 16384
543 }
544 return v
545}
546
547// ---------------------------------------------------------------------------
548// The loom
549// ---------------------------------------------------------------------------
550
551const (
552 gw, gh = 49, 75 // cells
553 fx0, fy0 = 8, 8
554 fx1, fy1 = gw - 9, gh - 9
555 cx, cy = 24, 37
556 ncol = 9
557 cell = 11
558 ox, oy = 24, 36
559 pw, ph = gw*cell + 2*ox, gh*cell + 2*oy
560)
561
562// colour indices
563const (
564 cG = iota // ground
565 cD // dark outline
566 cM // madder
567 cS // saffron
568 cL // light
569 cA // accent
570 cAB // abrash ground
571 cNZ // nazar blue
572 cNW // nazar white
573)
574
575func abs(a int) int {
576 if a < 0 {
577 return -a
578 }
579 return a
580}
581
582// floorMod is Python's % (b > 0); only the lattice has negative operands.
583func floorMod(a, b int) int {
584 m := a % b
585 if m < 0 {
586 m += b
587 }
588 return m
589}
590
591type loom struct{ g []int }
592
593// stamp paints a bitmap centred on (mx, my), clipped to the field.
594// cmap: colours of '#', '+', 'o'.
595func (lm *loom) stamp(bm []string, mx, my, sc int, cmap []int, mirror bool) {
596 h, w := len(bm), len(bm[0])
597 x0, y0 := mx-w*sc/2, my-h*sc/2
598 g := lm.g
599 for j := 0; j < h; j++ {
600 row := bm[j]
601 for i := 0; i < w; i++ {
602 ch := row[i]
603 if mirror {
604 ch = row[w-1-i]
605 }
606 if ch == '.' {
607 continue
608 }
609 c := cmap[2]
610 if ch == '#' {
611 c = cmap[0]
612 } else if ch == '+' {
613 c = cmap[1]
614 }
615 for a := 0; a < sc; a++ {
616 X := x0 + i*sc + a
617 if X < fx0 || X > fx1 {
618 continue
619 }
620 for b := 0; b < sc; b++ {
621 Y := y0 + j*sc + b
622 if Y >= fy0 && Y <= fy1 {
623 g[Y*gw+X] = c
624 }
625 }
626 }
627 }
628 }
629}
630
631// free: the box around a w x h motif plus one cell is inside the field and
632// all ground.
633func (lm *loom) free(mx, my, w, h int) bool {
634 y0, y1, x0, x1 := my-h/2-1, my+h/2+1, mx-w/2-1, mx+w/2+1
635 if x0 < fx0 || x1 > fx1 || y0 < fy0 || y1 > fy1 {
636 return false
637 }
638 for y := y0; y <= y1; y++ {
639 for x := x0; x <= x1; x++ {
640 if lm.g[y*gw+x] != cG {
641 return false
642 }
643 }
644 }
645 return true
646}
647
648// hexgol draws a stepped hexagonal göl: outline, a ring, the fill, and hooks
649// on its slopes.
650func (lm *loom) hexgol(gx, gy, a, b, c, fill, ring int) {
651 g := lm.g
652 for y := gy - b - 2; y <= gy+b+2; y++ {
653 if y < fy0 || y > fy1 {
654 continue
655 }
656 for x := gx - a - 2; x <= gx+a+2; x++ {
657 if x < fx0 || x > fx1 {
658 continue
659 }
660 dx, dy := x-gx, y-gy
661 ax, ay := abs(dx), abs(dy)
662 if ax <= a && ay <= b && ax+ay <= c {
663 col := fill
664 if ax+1 > a || ay+1 > b || ax+ay+1 > c {
665 col = cD
666 } else if ax+2 > a || ay+2 > b || ax+ay+2 > c {
667 col = ring
668 }
669 g[y*gw+x] = col
670 } else {
671 s := ax + ay
672 if s == c+1 && ay < b && ax < a && (dx+dy)&3 == 0 {
673 g[y*gw+x] = cD
674 }
675 if s == c+2 && ay < b-1 && ax < a-1 && (dx+dy)&3 == 1 {
676 g[y*gw+x] = cD
677 }
678 }
679 }
680 }
681}
682
683var (
684 onGround = []int{cD, cL, cS}
685 onDarkGround = []int{cL, cS, cM}
686 wolfUp = []int{0, 1, 2, 3, 2, 1}
687 wolfDown = []int{3, 2, 1, 0, 1, 2}
688 waterZ = []int{1, 2, 3, 4, 4, 3, 2, 1}
689 waterZP = []int{1, 1, 2, 3, 4, 4, 3, 2}
690)
691
692func onFill(f int) []int {
693 p, o := cL, cS
694 if f == cL {
695 p = cS
696 }
697 if f == cS {
698 o = cM
699 }
700 return []int{cD, p, o}
701}
702
703func (lm *loom) border(kind, bBg int) {
704 g := lm.g
705 for y := 0; y < gh; y++ {
706 for x := 0; x < gw; x++ {
707 if x >= fx0 && x <= fx1 && y >= fy0 && y <= fy1 {
708 continue
709 }
710 e := x
711 if y < e {
712 e = y
713 }
714 if gw-1-x < e {
715 e = gw - 1 - x
716 }
717 if gh-1-y < e {
718 e = gh - 1 - y
719 }
720 if e == 0 || e == 7 {
721 g[y*gw+x] = cD
722 continue
723 }
724 c := bBg
725 if (x < 7 || x > gw-8) && (y < 7 || y > gh-8) {
726 // corner rosette (centre 3.5 cells from the edges: doubled coordinates)
727 vx, vy := abs(2*x-7), abs(2*y-7)
728 if x >= 7 {
729 vx = abs(2*x - (2*gw - 9))
730 }
731 if y >= 7 {
732 vy = abs(2*y - (2*gh - 9))
733 }
734 v := vx + vy
735 switch {
736 case v <= 2:
737 c = cS
738 case v <= 4:
739 c = cD
740 case v <= 6:
741 c = cA
742 }
743 } else {
744 var t, dd int
745 switch {
746 case e == y:
747 t, dd = x, y-1
748 case e == gh-1-y:
749 t, dd = x, gh-2-y
750 case e == x:
751 t, dd = y, x-1
752 default:
753 t, dd = y, gw-2-x
754 }
755 switch kind {
756 case bWolf:
757 k := (t - 1) % 6
758 if dd < wolfUp[k] {
759 c = cD
760 } else if 5-dd < wolfDown[k] {
761 c = cS
762 }
763 case bWater:
764 k := t % 8
765 if dd == waterZ[k] || dd == waterZP[k] {
766 c = cD
767 } else if (k == 0 || k == 1) && dd == 4 {
768 c = cA
769 } else if (k == 4 || k == 5) && dd == 1 {
770 c = cS
771 }
772 case bEyes:
773 k := (t - 1) % 7
774 v := abs(2*k-6) + abs(2*dd-5)
775 if v <= 1 {
776 c = cL
777 } else if v <= 3 {
778 c = cA
779 } else if v <= 5 {
780 c = cD
781 }
782 case bAmulets:
783 k := (t - 1) % 12
784 lim := 2*dd - 4
785 if k < 6 {
786 lim = 2*(5-dd) - 4
787 }
788 if abs(2*(k%6)-5) <= lim {
789 c = cS
790 if k < 6 {
791 c = cD
792 }
793 }
794 default:
795 sx := (t-1)%7 - 1
796 if sx >= 0 && sx < 5 && dd < 5 {
797 ch := kyildiz[dd][sx]
798 if ch == 'o' {
799 c = cS
800 } else if ch != '.' {
801 c = cD
802 }
803 }
804 }
805 }
806 g[y*gw+x] = c
807 }
808 }
809}
810
811func (lm *loom) field(layout, main, second, third int, og []int) {
812 g := lm.g
813 switch layout {
814 case layThree:
815 // top to bottom the göls read as a sentence: second, main, third
816 fills := []int{cM, cA, cM}
817 ks := []int{second, main, third}
818 ys := []int{cy - 19, cy, cy + 19}
819 for i := 0; i < 3; i++ {
820 lm.hexgol(cx, ys[i], 13, 8, 17, fills[i], cL)
821 f := onFill(fills[i])
822 lm.stamp(motifs[ks[i]].bm, cx, ys[i], 1, f, false)
823 lm.stamp(tohum, cx-9, ys[i], 1, f, false)
824 lm.stamp(tohum, cx+9, ys[i], 1, f, false)
825 }
826 for _, yy := range []int{cy - 28, cy - 10, cy + 10, cy + 28} {
827 for _, xx := range []int{fx0 + 3, fx1 - 3} {
828 if lm.free(xx, yy, 3, 3) {
829 lm.stamp(tohum, xx, yy, 1, og, false)
830 }
831 }
832 }
833 for _, yy := range []int{cy - 9, cy + 9} {
834 for _, xx := range []int{fx0 + 5, fx1 - 5} {
835 if lm.free(xx, yy, 5, 5) {
836 lm.stamp(kgoz, xx, yy, 1, og, false)
837 }
838 }
839 }
840 case layGreat:
841 // end panels [second, third, second] around one great göl with the
842 // main motif twice its size
843 fa := onFill(cA)
844 for p := 0; p < 2; p++ {
845 y0, y1, sep := fy0, fy0+11, fy0+12
846 if p == 1 {
847 y0, y1, sep = fy1-11, fy1, fy1-12
848 }
849 for y := y0; y <= y1; y++ {
850 for x := fx0; x <= fx1; x++ {
851 g[y*gw+x] = cA
852 }
853 }
854 for x := fx0; x <= fx1; x++ {
855 g[sep*gw+x] = cD
856 }
857 my := y0 + 6
858 lm.stamp(motifs[second].bm, cx-11, my, 1, fa, false)
859 lm.stamp(motifs[third].bm, cx, my, 1, fa, false)
860 lm.stamp(motifs[second].bm, cx+11, my, 1, fa, true)
861 }
862 lm.hexgol(cx, cy, 14, 16, 26, cM, cL)
863 lm.hexgol(cx, cy, 10, 12, 18, cA, cL)
864 lm.stamp(motifs[main].bm, cx, cy, 2, fa, false)
865 for _, yy := range []int{cy - 13, cy + 13} {
866 for _, xx := range []int{fx0 + 2, fx1 - 2} {
867 if lm.free(xx, yy, 3, 3) {
868 lm.stamp(tohum, xx, yy, 1, og, false)
869 }
870 }
871 }
872 case layLattice:
873 for y := fy0; y <= fy1; y++ {
874 for x := fx0; x <= fx1; x++ {
875 u := floorMod(x-cx+(y-cy)+11, 22)
876 v := floorMod(x-cx-(y-cy)+11, 22)
877 if u == 0 || v == 0 {
878 g[y*gw+x] = cD
879 } else if u == 1 || v == 1 || u == 21 || v == 21 {
880 g[y*gw+x] = cS
881 }
882 }
883 }
884 // centre column: the main motif with the third above and below; the
885 // sides carry the second
886 centre := []int{cD, cL, cA}
887 if og[0] != cD {
888 centre = []int{cL, cS, cA}
889 }
890 for j := -3; j <= 3; j++ {
891 for i := -1; i <= 1; i++ {
892 if floorMod(i+j, 2) != 0 {
893 continue
894 }
895 if i == 0 {
896 k := third
897 if j == 0 {
898 k = main
899 }
900 lm.stamp(motifs[k].bm, cx, cy+11*j, 1, centre, false)
901 } else {
902 lm.stamp(motifs[second].bm, cx+11*i, cy+11*j, 1, og, i > 0)
903 }
904 }
905 }
906 case layBands:
907 ks := []int{main, second, third, main}
908 bgs := []int{cG, cM, cA, cG}
909 y := fy0 + 1
910 for bi := 0; bi < 4; bi++ {
911 bg := bgs[bi]
912 for yy := y; yy < y+13; yy++ {
913 for x := fx0; x <= fx1; x++ {
914 g[yy*gw+x] = bg
915 }
916 }
917 cm := og
918 if bg != cG {
919 cm = onFill(bg)
920 }
921 bm := motifs[ks[bi]].bm
922 lm.stamp(bm, cx-11, y+6, 1, cm, false)
923 lm.stamp(bm, cx, y+6, 1, cm, false)
924 lm.stamp(bm, cx+11, y+6, 1, cm, true)
925 y += 13
926 if bi < 3 {
927 for x := fx0; x <= fx1; x++ {
928 z := 0
929 if x&3 == 1 || x&3 == 2 {
930 z = 1
931 }
932 g[(y+z)*gw+x] = cD
933 g[(y+1-z)*gw+x] = cL
934 }
935 y += 2
936 }
937 }
938 default:
939 // mihrab: a stepped prayer niche over a base panel
940 top, base := fy0+1, fy1-14
941 inN := func(x, y int) bool {
942 ax := abs(x - cx)
943 return ax <= 13 && y >= top+ax && y <= base
944 }
945 for y := fy0; y <= fy1; y++ {
946 for x := fx0; x <= fx1; x++ {
947 c := cM
948 if y > base {
949 if y == base+1 {
950 c = cD
951 }
952 } else if inN(x, y) {
953 c = cG
954 if !inN(x+1, y) || !inN(x-1, y) || !inN(x, y-1) || !inN(x, y+1) {
955 c = cD
956 }
957 } else if inN(x+1, y) || inN(x-1, y) || inN(x, y+1) {
958 c = cL
959 }
960 g[y*gw+x] = c
961 }
962 }
963 fm := onFill(cM)
964 lm.stamp(motifs[second].bm, cx, top+12, 1, og, false)
965 lm.stamp(motifs[main].bm, cx, base-12, 2, og, false)
966 lm.stamp(motifs[third].bm, cx-9, base+7, 1, fm, false)
967 lm.stamp(motifs[third].bm, cx+9, base+7, 1, fm, true)
968 lm.stamp(kyildiz, fx0+3, fy0+4, 1, fm, false)
969 lm.stamp(kyildiz, fx1-3, fy0+4, 1, fm, false)
970 }
971}
972
973// ---------------------------------------------------------------------------
974// Rendering
975// ---------------------------------------------------------------------------
976
977const (
978 fringeShade = "#b3a27f"
979 fringeLight = "#e2d6bb"
980 fringeKnot = "#a8977a"
981 fringeBraid = "#8f7f63"
982)
983
984func fringeGroup(b *strings.Builder, y int, flip bool, knots string, braided bool) {
985 b.WriteString(`<g transform="translate(0 ` + strconv.Itoa(y) + ")")
986 if flip {
987 b.WriteString(` scale(1 -1)`)
988 }
989 b.WriteString(`"><use href="#f" stroke="` + fringeShade + `" stroke-width="3.2"/><use href="#f" stroke="` +
990 fringeLight + `" stroke-width="1.8"/>`)
991 if knots != "" {
992 b.WriteString(`<path d="` + knots + `" stroke="` + fringeKnot + `" stroke-width="5"/>`)
993 }
994 if braided {
995 b.WriteString(`<use href="#f" stroke="` + fringeBraid + `" stroke-width="1" stroke-dasharray="2 3"/>`)
996 }
997 b.WriteString(`</g>`)
998}
999
1000// SVG renders the artwork for a seed under cfg, with the token number
1001// tokenID woven into the künye band.
1002func SVG(seed string, cfg Config, tokenID string) string {
1003 d := derive(seed, cfg)
1004 pal := palettes[d.dyes]
1005 r := newRNG(seed + "|art") // separate stream: trait draws never shift the art
1006 lm := &loom{g: make([]int, gw*gh)}
1007 g := lm.g
1008 bBg := cL
1009 if r.intn(2) == 0 {
1010 bBg = cM
1011 }
1012 lm.border(d.border, bBg)
1013 og := onGround
1014 if darkGround[d.dyes] {
1015 og = onDarkGround
1016 }
1017 lm.field(d.layout, d.main, d.second, d.third, og)
1018
1019 // abrash: a new dye lot recolours the ground in a few weft bands
1020 if d.abrash != abrashNone {
1021 nb, hmax := 4, 7
1022 if d.abrash == abrashFaint {
1023 nb, hmax = 2, 4
1024 }
1025 for k := 0; k < nb; k++ {
1026 y0 := r.between(fy0, fy1-4)
1027 hh := r.between(2, hmax)
1028 for y := y0; y < y0+hh && y <= fy1; y++ {
1029 for x := fx0; x <= fx1; x++ {
1030 if g[y*gw+x] == cG {
1031 g[y*gw+x] = cAB
1032 }
1033 }
1034 }
1035 }
1036 }
1037 // nazar bead: one blue eye that breaks the symmetry on purpose (on bare
1038 // ground when one of 40 tries finds room, else over the last spot tried)
1039 if d.nazar {
1040 x, y := 0, 0
1041 for tries := 0; tries < 40; tries++ {
1042 x = r.between(fx0+3, fx1-3)
1043 y = r.between(fy0+3, fy1-3)
1044 if abs(x-cx) >= 4 && lm.free(x, y, 5, 5) {
1045 break
1046 }
1047 }
1048 for j := -2; j <= 2; j++ {
1049 for i := -2; i <= 2; i++ {
1050 v := abs(i) + abs(j)
1051 if v <= 2 {
1052 c := cD
1053 if v == 2 {
1054 c = cNZ
1055 } else if v == 1 {
1056 c = cNW
1057 }
1058 g[(y+j)*gw+x+i] = c
1059 }
1060 }
1061 }
1062 }
1063 // künye: the token number in 14 bits on the bottom frame line
1064 tokenNo := KunyeNumber(tokenID)
1065 ky := (gh - 8) * gw
1066 g[ky+cx-15] = cL
1067 g[ky+cx+15] = cL
1068 for i := 0; i < 14; i++ {
1069 c := cA
1070 if (tokenNo>>uint(13-i))&1 != 0 {
1071 c = cS
1072 }
1073 g[ky+cx-13+2*i] = c
1074 }
1075 // on the loom: the top rows are not woven yet
1076 cut := 0
1077 if d.loom {
1078 cut = r.between(10, 24)
1079 }
1080 noise := r.between(1, 999)
1081
1082 // run-length rows; the most frequent colour is the background rect
1083 var cnt [ncol]int
1084 for i := cut * gw; i < gw*gh; i++ {
1085 cnt[g[i]]++
1086 }
1087 bg := 0
1088 for i := 1; i < ncol; i++ {
1089 if cnt[i] > cnt[bg] {
1090 bg = i
1091 }
1092 }
1093 cols := []string{pal[0], pal[1], pal[2], pal[3], pal[4], pal[5], pal[6], "#2d6db5", "#f4f1ea"}
1094 paths := make([]strings.Builder, ncol)
1095 var last [ncol]int
1096 for y := cut; y < gh; y++ {
1097 for k := 0; k < ncol; k++ {
1098 last[k] = -1
1099 }
1100 row := y * gw
1101 sy := strconv.Itoa(y)
1102 x := 0
1103 for x < gw {
1104 c := g[row+x]
1105 e := x
1106 for e+1 < gw && g[row+e+1] == c {
1107 e++
1108 }
1109 if c != bg {
1110 p := &paths[c]
1111 if last[c] >= 0 {
1112 p.WriteString("m" + strconv.Itoa(x-last[c]) + " 0h" + strconv.Itoa(e-x+1))
1113 } else {
1114 p.WriteString("M" + strconv.Itoa(x) + " " + sy + "h" + strconv.Itoa(e-x+1))
1115 }
1116 last[c] = e + 1
1117 }
1118 x = e + 1
1119 }
1120 }
1121
1122 var b strings.Builder
1123 sPW, sPH := strconv.Itoa(pw), strconv.Itoa(ph)
1124 b.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ` + sPW + " " + sPH + `" width="` + sPW +
1125 `" height="` + sPH + `">`)
1126 b.WriteString(`<title>Kilim, Niyet: ` + intentOpts[d.intent].name + `</title><desc>`)
1127 for _, k := range []int{d.main, d.second, d.third} {
1128 b.WriteString(motifs[k].name + ": " + motifs[k].meaning + ". ")
1129 }
1130 b.WriteString(borderOpts[d.border].name + ": " + borderMeanings[d.border] + ". Künye " + strconv.Itoa(tokenNo) + ".</desc>")
1131 b.WriteString(`<defs><pattern id="w" width="11" height="11" patternUnits="userSpaceOnUse">` +
1132 `<path d="M0 1h11M0 6h11" stroke="#fff" stroke-opacity=".08"/><path d="M0 3.5h11M0 9h11" stroke="#000" stroke-opacity=".09"/>` +
1133 `<path d="M3 0v11M8 0v11" stroke="#000" stroke-opacity=".035"/></pattern>` +
1134 `<filter id="n" x="0" y="0" width="1" height="1"><feTurbulence type="fractalNoise" baseFrequency=".01 .5" numOctaves="2" seed="` +
1135 strconv.Itoa(noise) + `"/>` +
1136 `<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -2 1.1"/></filter>` +
1137 `<filter id="s" x="-.1" y="-.1" width="1.2" height="1.2"><feGaussianBlur stdDeviation="6"/></filter><path id="f" d="`)
1138 // fringe: warp ends in pairs, cut to uneven lengths
1139 for i := 0; i < 2*gw; i++ {
1140 b.WriteString("M" + strconv.Itoa(ox+3+(11*i+1)/2) + " 0v" + strconv.Itoa(16+r.intn(9)))
1141 }
1142 b.WriteString(`"/></defs><rect width="` + sPW + `" height="` + sPH + `" fill="#ece5d6"/>`)
1143 top := oy + cut*cell
1144 sTop, sRW, sRH := strconv.Itoa(top), strconv.Itoa(gw*cell), strconv.Itoa((gh-cut)*cell)
1145 b.WriteString(`<rect x="` + strconv.Itoa(ox+3) + `" y="` + strconv.Itoa(top+6) + `" width="` + sRW + `" height="` + sRH +
1146 `" fill="#000" opacity=".22" filter="url(#s)"/>`)
1147 knots := ""
1148 if d.fringe == fringeKnotted {
1149 for i := 0; i < 25; i++ {
1150 knots += "M" + strconv.Itoa(ox+6+22*i) + " 6h8"
1151 }
1152 }
1153 braided := d.fringe == fringeBraided
1154 if !d.loom {
1155 fringeGroup(&b, oy, true, knots, braided)
1156 }
1157 fringeGroup(&b, oy+gh*cell, false, knots, braided)
1158 b.WriteString(`<g transform="translate(` + strconv.Itoa(ox) + " " + strconv.Itoa(oy) + `) scale(11)" shape-rendering="crispEdges">`)
1159 sCut := strconv.Itoa(cut)
1160 if d.loom {
1161 b.WriteString(`<rect y="-4" width="49" height="` + strconv.Itoa(cut+4) + `" fill="#3b2f25"/><path d="`)
1162 sWarp := strconv.Itoa(cut + 4)
1163 for x := 0; x < gw; x++ {
1164 b.WriteString("M" + strconv.Itoa(x) + ".5 -4v" + sWarp)
1165 }
1166 b.WriteString(`" stroke="` + pal[4] + `" stroke-width=".22"/>`)
1167 }
1168 b.WriteString(`<rect y="` + sCut + `" width="49" height="` + strconv.Itoa(gh-cut) + `" fill="` + cols[bg] +
1169 `"/><g transform="translate(0 .5)" stroke-width="1.02">`)
1170 for c := 0; c < ncol; c++ {
1171 if paths[c].Len() > 0 {
1172 b.WriteString(`<path stroke="` + cols[c] + `" d="` + paths[c].String() + `"/>`)
1173 }
1174 }
1175 b.WriteString(`</g>`)
1176 if d.loom {
1177 b.WriteString(`<rect x="-1" y="` + strconv.Itoa(cut-1) + `" width="51" height="1" fill="#7a5a3a"/>`)
1178 b.WriteString(`<path d="M` + strconv.Itoa(r.between(5, 20)) + " " + sCut + `q4 3 9 1t8 4" stroke="` + pal[2] +
1179 `" stroke-width=".35" fill="none"/>`)
1180 }
1181 b.WriteString(`</g><rect x="` + strconv.Itoa(ox) + `" y="` + sTop + `" width="` + sRW + `" height="` + sRH + `" fill="url(#w)"/>`)
1182 b.WriteString(`<rect x="` + strconv.Itoa(ox) + `" y="` + sTop + `" width="` + sRW + `" height="` + sRH +
1183 `" filter="url(#n)" opacity=".3"/></svg>`)
1184 return b.String()
1185}