-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage.tsx.txt
More file actions
3348 lines (2886 loc) · 147 KB
/
page.tsx.txt
File metadata and controls
3348 lines (2886 loc) · 147 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use client"
import { useEffect, useRef, useState, useMemo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Shuffle, Download, FileText, Plus, X, Copy } from 'lucide-react'
import Navigation from '@/components/Navigation'
import NFTExporter from '@/components/NFTExporter'
import Web3Minting from '@/components/Web3Minting'
import SimpleMinting from '@/components/SimpleMinting'
import Footer from '@/components/Footer'
import SevenSegmentDisplay from '@/components/SevenSegmentDisplay'
import { initPRNG, getPRNG, createDerivedPRNG } from '@/lib/DeterministicPRNG'
import { config } from '@/lib/config'
import { useChainId } from 'wagmi'
import { contractAddresses } from '@/lib/web3'
import { getChainDisplayName } from '@/lib/networks'
import { Metadata } from 'next'
import Head from 'next/head'
// SEO metadata for the generator page
const metadata: Metadata = {
title: "Rug Factory - Create Living Onchain Generative NFT Rugs | OnchainRugs",
description: "Create living onchain generative NFT rugs that require your care. Each rug is a living NFT - completely onchain, generative, and dynamic. Custom text, 102 palettes, authentic physics. Mint directly on Shape L2 blockchain.",
keywords: [
"NFT generator", "create NFT", "generative art", "custom NFT", "rug NFT",
"textile NFT", "woven art NFT", "blockchain art generator", "Shape L2 NFT",
"living NFT", "aging NFT", "NFT minting", "custom text NFT"
],
openGraph: {
title: "Rug Factory - Create Fully Onchain Living Generative NFT Rugs",
description: "Design and mint living onchain generative NFT rugs that require your care. Each rug is a living NFT - completely onchain, generative, and dynamic. Custom text, 102 palettes, authentic physics.",
url: 'https://onchainrugs.xyz/generator',
type: 'website',
images: [
{
url: '/generator-og.png',
width: 1200,
height: 630,
alt: 'Rug Factory - Create Onchain Rug NFTs',
},
],
},
twitter: {
card: 'summary_large_image',
title: "Rug Factory - Create Fully Onchain Living Generative NFT Rugs",
description: "Design and mint living onchain generative NFT rugs that require your care. Each rug is a living NFT.",
images: ['/generator-og.png'],
},
}
export default function GeneratorPage() {
const chainId = useChainId()
const contractAddress = contractAddresses[chainId] // No fallback - safer to show error than use wrong contract
const [isLoaded, setIsLoaded] = useState(false)
const [currentSeed, setCurrentSeed] = useState(42)
const [textInputs, setTextInputs] = useState([''])
const [currentRowCount, setCurrentRowCount] = useState(1)
const [palette, setPalette] = useState<any>(null)
const [traits, setTraits] = useState<any>(null)
const [stripeData, setStripeData] = useState<any[]>([])
const [showDirt, setShowDirt] = useState(false)
const [dirtLevel, setDirtLevel] = useState(0) // 0 = clean, 1 = 50% dirty, 2 = full dirty
const [lastDirtLevel, setLastDirtLevel] = useState(1) // Remember last non-zero dirt level
const [showTexture, setShowTexture] = useState(false)
const [textureLevel, setTextureLevel] = useState(0) // 0 = none, 1 = 7 days, 2 = 30 days
const [lastTextureLevel, setLastTextureLevel] = useState(1) // Remember last non-zero texture level
const [patinaLocked, setPatinaLocked] = useState(false)
const [focusNewRow, setFocusNewRow] = useState(false)
// Diamond frame aging (hardcoded - most impressive longevity)
const [warpThickness, setWarpThickness] = useState(2) // Default warp thickness
// Debounce timer for live updates
const liveUpdateTimerRef = useRef<NodeJS.Timeout | null>(null)
// Cleanup timer on unmount
useEffect(() => {
return () => {
if (liveUpdateTimerRef.current) {
clearTimeout(liveUpdateTimerRef.current)
}
}
}, [])
// Copy to clipboard function
const copyToClipboard = async (text: string, label: string) => {
try {
await navigator.clipboard.writeText(text)
// You could add a toast notification here
console.log(`${label} copied to clipboard`)
} catch (err) {
console.error('Failed to copy: ', err)
}
}
const canvasContainerRef = useRef<HTMLDivElement>(null)
const scriptsLoadedRef = useRef<Set<string>>(new Set())
const textInputRefs = useRef<(HTMLInputElement | null)[]>([])
// Clean P5.js loading - no global pollution
const loadP5 = () => {
return new Promise<void>((resolve) => {
// Check if P5.js is already loaded
if (typeof window !== 'undefined' && (window as any).p5) {
console.log('✅ P5.js already available')
resolve()
return
}
// Load P5.js from CDN
const script = document.createElement('script')
script.src = 'https://cdn.jsdelivr.net/npm/p5@1.11.10/lib/p5.min.js'
script.onload = () => {
console.log('✅ P5.js loaded successfully')
resolve()
}
script.onerror = () => {
console.error('❌ Failed to load P5.js from CDN')
resolve() // Continue anyway
}
document.head.appendChild(script)
})
}
// Load palette data (keeping it simple and accessible)
const loadPaletteData = () => {
return new Promise<void>((resolve) => {
// For transparency and simplicity, we'll just use embedded palettes
// This avoids loading issues and keeps everything in one place
if (typeof window !== 'undefined') {
;(window as any).paletteCollections = getEmbeddedPalettes()
console.log(`✅ Loaded ${getEmbeddedPalettes().length} palettes`)
}
resolve()
})
}
// Get all available palettes (transparently accessible)
const getEmbeddedPalettes = () => {
return [
// ===== GLOBAL PALETTES =====
{ name: "Classic Red & Black", colors: ['#8B0000', '#DC143C', '#B22222', '#000000', '#2F2F2F', '#696969', '#8B4513', '#A0522D'] },
{ name: "Natural Jute & Hemp", colors: ['#F5DEB3', '#DEB887', '#D2B48C', '#BC8F8F', '#8B7355', '#A0522D', '#654321', '#2F2F2F'] },
{ name: "Coastal Blue & White", colors: ['#4682B4', '#5F9EA0', '#87CEEB', '#B0E0E6', '#F8F8FF', '#F0F8FF', '#E6E6FA', '#B0C4DE'] },
{ name: "Rustic Farmhouse", colors: ['#8B4513', '#A0522D', '#CD853F', '#D2691E', '#F4A460', '#DEB887', '#F5DEB3', '#F4E4BC'] },
{ name: "Modern Gray & White", colors: ['#F5F5F5', '#FFFFFF', '#D3D3D3', '#C0C0C0', '#A9A9A9', '#808080', '#696969', '#2F2F2F'] },
{ name: "Autumn Harvest", colors: ['#8B4513', '#D2691E', '#CD853F', '#F4A460', '#8B0000', '#B22222', '#FF8C00', '#FFA500'] },
{ name: "Spring Garden", colors: ['#228B22', '#32CD32', '#90EE90', '#98FB98', '#FF69B4', '#FFB6C1', '#87CEEB', '#F0E68C'] },
{ name: "Industrial Metal", colors: ['#2F4F4F', '#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3', '#F5F5F5', '#000000'] },
{ name: "Mediterranean", colors: ['#FF6347', '#FF4500', '#FF8C00', '#FFA500', '#F4A460', '#DEB887', '#87CEEB', '#4682B4'] },
{ name: "Scandinavian", colors: ['#FFFFFF', '#F8F9FA', '#E9ECEF', '#DEE2E6', '#CED4DA', '#ADB5BD', '#6C757D', '#495057'] },
{ name: "Nordic Forest", colors: ['#2D5016', '#3A5F0B', '#4A7C59', '#5D8B66', '#6B8E23', '#8FBC8F', '#9ACD32', '#ADFF2F'] },
{ name: "Desert Sunset", colors: ['#CD853F', '#DEB887', '#F4A460', '#D2B48C', '#BC8F8F', '#8B4513', '#A0522D', '#D2691E'] },
{ name: "Arctic Ice", colors: ['#F0F8FF', '#E6E6FA', '#B0C4DE', '#87CEEB', '#B0E0E6', '#F0FFFF', '#E0FFFF', '#F5F5F5'] },
{ name: "Tropical Paradise", colors: ['#FF6347', '#FF4500', '#FF8C00', '#FFA500', '#32CD32', '#90EE90', '#98FB98', '#00CED1'] },
{ name: "Vintage Retro", colors: ['#8B4513', '#A0522D', '#CD853F', '#D2691E', '#BC8F8F', '#8B7355', '#F5DEB3', '#F4E4BC'] },
{ name: "Art Deco", colors: ['#000000', '#2F2F2F', '#696969', '#8B4513', '#A0522D', '#CD853F', '#F5DEB3', '#FFFFFF'] },
{ name: "Bohemian", colors: ['#8E44AD', '#9B59B6', '#E67E22', '#D35400', '#E74C3C', '#C0392B', '#16A085', '#1ABC9C'] },
{ name: "Minimalist", colors: ['#FFFFFF', '#F5F5F5', '#E0E0E0', '#CCCCCC', '#999999', '#666666', '#333333', '#000000'] },
{ name: "Corporate", colors: ['#2F4F4F', '#696969', '#808080', '#A9A9A9', '#C0C0C0', '#D3D3D3', '#F5F5F5', '#FFFFFF'] },
{ name: "Luxury", colors: ['#000000', '#2F2F2F', '#8B4513', '#A0522D', '#CD853F', '#D2691E', '#F5DEB3', '#FFD700'] },
{ name: "Pastel Dreams", colors: ['#FFB6C1', '#FFC0CB', '#FFE4E1', '#F0E68C', '#98FB98', '#90EE90', '#87CEEB', '#E6E6FA'] },
{ name: "Ocean Depths", colors: ['#000080', '#191970', '#4169E1', '#4682B4', '#5F9EA0', '#87CEEB', '#B0E0E6', '#E0FFFF'] },
{ name: "Mountain Mist", colors: ['#2F4F4F', '#4A5D6B', '#5F7A7A', '#6B8E8E', '#87CEEB', '#B0C4DE', '#E6E6FA', '#F0F8FF'] },
{ name: "Sunset Glow", colors: ['#FF6347', '#FF4500', '#FF8C00', '#FFA500', '#FFD700', '#DC143C', '#8B0000', '#2F2F2F'] },
// ===== INDIAN CULTURAL PALETTES =====
{ name: "Rajasthani", colors: ['#FF4500', '#FF6347', '#FF8C00', '#FFD700', '#FF1493', '#8B0000', '#4B0082', '#000080'] },
{ name: "Kerala", colors: ['#228B22', '#32CD32', '#90EE90', '#98FB98', '#00CED1', '#87CEEB', '#4682B4', '#000080'] },
{ name: "Gujarat", colors: ['#FF4500', '#FF6347', '#FFD700', '#FFA500', '#DC143C', '#4B0082', '#32CD32', '#FFFFFF'] },
{ name: "Bengal", colors: ['#228B22', '#32CD32', '#90EE90', '#F5DEB3', '#DEB887', '#8B4513', '#4682B4', '#000080'] },
{ name: "Kashmir", colors: ['#87CEEB', '#B0E0E6', '#E0FFFF', '#F0F8FF', '#E6E6FA', '#B0C4DE', '#4682B4', '#000080'] },
// ===== TAMIL CULTURAL PALETTES =====
{ name: "Chola Empire", colors: ['#8B0000', '#DC143C', '#B22222', '#FF4500', '#FF8C00', '#FFD700', '#228B22', '#006400'] },
{ name: "Chera Dynasty", colors: ['#228B22', '#32CD32', '#90EE90', '#8B4513', '#A0522D', '#FFD700', '#00CED1', '#000080'] },
{ name: "Jamakalam", colors: ['#8B0000', '#DC143C', '#FFD700', '#FFA500', '#228B22', '#32CD32', '#4B0082', '#000000'] },
// ===== NATURAL DYE PALETTES =====
{ name: "Madder Root", colors: ['#8B0000', '#DC143C', '#B22222', '#FF4500', '#FF6347', '#CD5C5C', '#F08080', '#FA8072'] },
{ name: "Turmeric", colors: ['#FFD700', '#FFA500', '#FF8C00', '#FF6347', '#FF4500', '#DAA520', '#B8860B', '#CD853F'] },
{ name: "Neem", colors: ['#228B22', '#32CD32', '#90EE90', '#98FB98', '#8B4513', '#A0522D', '#CD853F', '#D2691E'] },
{ name: "Marigold", colors: ['#FFD700', '#FFA500', '#FF8C00', '#FF6347', '#FF4500', '#FF1493', '#FF69B4', '#FFB6C1'] },
// ===== MADRAS CHECKS & TAMIL NADU INSPIRED PALETTES =====
{ name: "Madras Checks", colors: ['#8B0000', '#DC143C', '#FF4500', '#FF6347', '#FF8C00', '#FFD700', '#228B22', '#006400'] },
{ name: "Thanjavur Fresco", colors: ['#FFD700', '#FFA500', '#FF8C00', '#FF6347', '#FF4500', '#8B0000', '#228B22', '#006400'] },
// ===== WESTERN GHATS BIRDS PALETTES =====
{ name: "Indian Peacock", colors: ['#000080', '#191970', '#4169E1', '#4682B4', '#00CED1', '#40E0D0', '#48D1CC', '#20B2AA'] },
{ name: "Flamingo", colors: ['#FF69B4', '#FF1493', '#FFB6C1', '#FFC0CB', '#FF6347', '#FF4500', '#FF8C00', '#FFA500'] },
{ name: "Toucan", colors: ['#FFD700', '#FFA500', '#FF8C00', '#FF6347', '#FF4500', '#000000', '#FFFFFF', '#FF1493'] },
{ name: "Malabar Trogon", colors: ['#8B0000', '#DC143C', '#FFD700', '#FFA500', '#228B22', '#32CD32', '#000000', '#FFFFFF'] },
// ===== HISTORICAL DYNASTY & CULTURAL PALETTES =====
{ name: "Pandyas", colors: ['#FF4500', '#FF6347', '#FF8C00', '#FFD700', '#00CED1', '#87CEEB', '#4682B4', '#000080'] },
{ name: "Maurya Empire", colors: ['#000080', '#191970', '#4169E1', '#4682B4', '#FFD700', '#FFA500', '#8B4513', '#A0522D'] },
{ name: "Buddhist", colors: ['#FFD700', '#FFA500', '#8B4513', '#A0522D', '#228B22', '#32CD32', '#90EE90', '#FFFFFF'] },
// ===== FAMINE & HISTORICAL PERIOD PALETTES =====
{ name: "Indigo Famine", colors: ['#000080', '#191970', '#4169E1', '#4682B4', '#2F4F4F', '#696969', '#808080', '#A9A9A9'] },
{ name: "Bengal Famine", colors: ['#8B0000', '#DC143C', '#B22222', '#2F4F4F', '#696969', '#808080', '#A9A9A9', '#000000'] },
// ===== MADRAS GENERATOR GLOBAL PALETTES =====
{ name: "Natural Dyes", colors: ['#405BAA', '#B33A3A', '#D9A43B', '#1F1E1D', '#5A7A5A', '#8C5832', '#A48E7F', '#FAF1E3'] },
{ name: "Bleeding Vintage", colors: ['#3A62B3', '#C13D3D', '#D9A43B', '#7DAC9B', '#D87BA1', '#7A4E8A', '#F2E4BE', '#1F1E1D'] },
{ name: "Warm Tamil Madras", colors: ['#C13D3D', '#F5C03A', '#3E5F9A', '#88B0D3', '#ADC178', '#E77F37', '#FAF3EB', '#F2E4BE'] },
{ name: "Classic Red-Green", colors: ['#cc0033', '#ffee88', '#004477', '#ffffff', '#e63946', '#f1faee', '#a8dadc', '#457b9d'] },
{ name: "Vintage Tamil", colors: ['#e63946', '#f1faee', '#a8dadc', '#457b9d', '#ffd700', '#b8860b', '#8b0000', '#f7c873'] },
{ name: "Sunset Pondicherry", colors: ['#ffb347', '#ff6961', '#6a0572', '#fff8e7', '#1d3557', '#e63946', '#f7cac9', '#92a8d1'] },
{ name: "Madras Monsoon", colors: ['#1d3557', '#457b9d', '#a8dadc', '#f1faee', '#ffd700', '#e94f37', '#393e41', '#3f88c5'] },
{ name: "Kanchipuram Gold", colors: ['#ffd700', '#b8860b', '#8b0000', '#fff8e7', '#cc0033', '#004477', '#e63946', '#f1faee'] },
{ name: "Madras Summer", colors: ['#f7c873', '#e94f37', '#393e41', '#3f88c5', '#fff8e7', '#ffb347', '#ff6961', '#1d3557'] },
{ name: "Pondy Pastel", colors: ['#f7cac9', '#92a8d1', '#034f84', '#f7786b', '#fff8e7', '#393e41', '#ffb347', '#e94f37'] },
{ name: "Tamil Sunrise", colors: ['#ffb347', '#ff6961', '#fff8e7', '#1d3557', '#e63946', '#f7c873', '#e94f37', '#393e41'] },
{ name: "Chettinad Spice", colors: ['#d72631', '#a2d5c6', '#077b8a', '#5c3c92', '#f4f4f4', '#ffd700', '#8b0000', '#1a2634'] },
{ name: "Kerala Onam", colors: ['#fff8e7', '#ffd700', '#e94f37', '#393e41', '#3f88c5', '#f7c873', '#ffb347', '#ff6961'] },
{ name: "Bengal Indigo", colors: ['#1a2634', '#3f88c5', '#f7c873', '#e94f37', '#fff8e7', '#ffd700', '#393e41', '#1d3557'] },
{ name: "Goa Beach", colors: ['#f7cac9', '#f7786b', '#034f84', '#fff8e7', '#393e41', '#ffb347', '#e94f37', '#3f88c5'] },
{ name: "Sri Lankan Tea", colors: ['#a8dadc', '#457b9d', '#e63946', '#f1faee', '#fff8e7', '#ffd700', '#8b0000', '#1d3557'] },
{ name: "African Madras", colors: ['#ffb347', '#e94f37', '#393e41', '#3f88c5', '#ffd700', '#f7c873', '#ff6961', '#1d3557'] },
{ name: "Ivy League", colors: ['#002147', '#a6192e', '#f4f4f4', '#ffd700', '#005a9c', '#00356b', '#ffffff', '#8c1515'] },
// ===== ADDITIONAL UNIQUE PALETTES =====
{ name: "Yale Blue", colors: ['#00356b', '#ffffff', '#c4d8e2', '#8c1515'] },
{ name: "Harvard Crimson", colors: ['#a51c30', '#ffffff', '#000000', '#b7a57a'] },
{ name: "Cornell Red", colors: ['#b31b1b', '#ffffff', '#222222', '#e5e5e5'] },
{ name: "Princeton Orange", colors: ['#ff8f1c', '#000000', '#ffffff', '#e5e5e5'] },
{ name: "Dartmouth Green", colors: ['#00693e', '#ffffff', '#000000', '#a3c1ad'] },
{ name: "Indian Flag", colors: ['#ff9933', '#ffffff', '#138808', '#000080'] },
{ name: "Oxford Tartan", colors: ['#002147', '#c8102e', '#ffd700', '#ffffff', '#008272'] },
{ name: "Black Watch", colors: ['#1c2a3a', '#2e4a62', '#1e2d24', '#3a5f0b'] },
{ name: "Royal Stewart", colors: ['#e10600', '#ffffff', '#000000', '#ffd700', '#007a3d'] },
{ name: "Scottish Highland", colors: ['#005eb8', '#ffd700', '#e10600', '#ffffff', '#000000'] },
{ name: "French Riviera", colors: ['#0055a4', '#ffffff', '#ef4135', '#f7c873'] },
{ name: "Tokyo Metro", colors: ['#e60012', '#0089a7', '#f6aa00', '#ffffff'] },
{ name: "Cape Town Pastel", colors: ['#f7cac9', '#92a8d1', '#034f84', '#f7786b'] },
{ name: "Black & Red", colors: ['#000000', '#cc0033'] }
]
}
// Self-contained doormat generation (no external scripts needed)
const initializeDoormat = () => {
console.log('🎨 Initializing self-contained doormat generator...')
// Configuration
const config = {
DOORMAT_WIDTH: 800,
DOORMAT_HEIGHT: 1200,
FRINGE_LENGTH: 30,
WEFT_THICKNESS: 8,
WARP_THICKNESS: 2,
TEXT_SCALE: 2,
MAX_CHARS: 11,
MAX_TEXT_ROWS: 5
}
// Load color palettes from external file or fallback
let colorPalettes = getEmbeddedPalettes() // Start with embedded as fallback
if (typeof window !== 'undefined' && (window as any).paletteCollections) {
colorPalettes = (window as any).paletteCollections
console.log(`✅ Loaded external palettes: ${colorPalettes.length} palettes`)
} else {
console.log(`📦 Using embedded fallback palettes: ${colorPalettes.length} palettes`)
}
console.log(`🎨 Total palettes available: ${colorPalettes.length}`)
// Character map for text embedding
const characterMap = {
'A': ["01110","10001","10001","11111","10001","10001","10001"],
'B': ["11110","10001","10001","11110","10001","10001","11110"],
'C': ["01111","10000","10000","10000","10000","10000","01111"],
'D': ["11110","10001","10001","10001","10001","10001","11110"],
'E': ["11111","10000","10000","11110","10000","10000","11111"],
'F': ["11111","10000","10000","11110","10000","10000","10000"],
'G': ["01111","10000","10000","10011","10001","10001","01111"],
'H': ["10001","10001","10001","11111","10001","10001","10001"],
'I': ["11111","00100","00100","00100","00100","00100","11111"],
'J': ["11111","00001","00001","00001","00001","10001","01110"],
'K': ["10001","10010","10100","11000","10100","10010","10001"],
'L': ["10000","10000","10000","10000","10000","10000","11111"],
'M': ["10001","11011","10101","10001","10001","10001","10001"],
'N': ["10001","11001","10101","10011","10001","10001","10001"],
'O': ["01110","10001","10001","10001","10001","10001","01110"],
'P': ["11110","10001","10001","11110","10000","10000","10000"],
'Q': ["01110","10001","10001","10001","10101","10010","01101"],
'R': ["11110","10001","10001","11110","10100","10010","10001"],
'S': ["01111","10000","10000","01110","00001","00001","11110"],
'T': ["11111","00100","00100","00100","00100","00100","00100"],
'U': ["10001","10001","10001","10001","10001","10001","01110"],
'V': ["10001","10001","10001","10001","10001","01010","00100"],
'W': ["10001","10001","10001","10001","10101","11011","10001"],
'X': ["10001","10001","01010","00100","01010","10001","10001"],
'Y': ["10001","10001","01010","00100","00100","00100","00100"],
'Z': ["11111","00001","00010","00100","01000","10000","11111"],
' ': ["00000","00000","00000","00000","00000","00000","00000"],
'0': ["01110","10001","10011","10101","11001","10001","01110"],
'1': ["00100","01100","00100","00100","00100","00100","01110"],
'2': ["01110","10001","00001","00010","00100","01000","11111"],
'3': ["11110","00001","00001","01110","00001","00001","11110"],
'4': ["00010","00110","01010","10010","11111","00010","00010"],
'5': ["11111","10000","10000","11110","00001","00001","11110"],
'6': ["01110","10000","10000","11110","10001","10001","01110"],
'7': ["11111","00001","00010","00100","01000","01000","01000"],
'8': ["01110","10001","10001","01110","10001","10001","01110"],
'9': ["01110","10001","10001","01111","00001","00001","01110"],
'?': ["01110","10001","00001","00010","00100","00000","00100"],
'_': ["00000","00000","00000","00000","00000","00000","11111"],
'!': ["00100","00100","00100","00100","00100","00000","00100"],
'@': ["01110","10001","10111","10101","10111","10000","01110"],
'#': ["01010","01010","11111","01010","11111","01010","01010"],
'$': ["00100","01111","10000","01110","00001","11110","00100"],
'&': ["01100","10010","10100","01000","10101","10010","01101"],
'%': ["10001","00010","00100","01000","10000","10001","00000"],
'+': ["00000","00100","00100","11111","00100","00100","00000"],
'-': ["00000","00000","00000","11111","00000","00000","00000"],
'(': ["00010","00100","01000","01000","01000","00100","00010"],
')': ["01000","00100","00010","00010","00010","00100","01000"],
'[': ["01110","01000","01000","01000","01000","01000","01110"],
']': ["01110","00010","00010","00010","00010","00010","01110"],
'*': ["00000","00100","10101","01110","10101","00100","00000"],
'=': ["00000","00000","11111","00000","11111","00000","00000"],
"'": ["00100","00100","00100","00000","00000","00000","00000"],
'"': ["01010","01010","01010","00000","00000","00000","00000"],
'.': ["00000","00000","00000","00000","00000","00100","00100"],
'<': ["00010","00100","01000","10000","01000","00100","00010"],
'>': ["01000","00100","00010","00001","00010","00100","01000"]
}
// Global variables for NFTExporter
const selectedPalette = colorPalettes[0]
const stripeData: any[] = []
const textData: any[] = []
const doormatTextRows: string[] = []
const warpThickness = config.WARP_THICKNESS
// Text colors (chosen from palette) - MISSING FROM ORIGINAL
const lightTextColor: any = null
const darkTextColor: any = null
// Expose minimal globals for NFTExporter
if (typeof window !== 'undefined') {
;(window as any).selectedPalette = selectedPalette
;(window as any).stripeData = stripeData
;(window as any).DOORMAT_CONFIG = config
;(window as any).warpThickness = warpThickness
;(window as any).textData = textData
;(window as any).doormatTextRows = doormatTextRows
}
console.log('✅ Self-contained doormat generator initialized')
return { config, colorPalettes, characterMap, selectedPalette, stripeData, textData, doormatTextRows, warpThickness }
}
// Create P5.js instance using original doormat.js logic
const createP5Instance = () => {
return new Promise<void>((resolve) => {
if (typeof window !== 'undefined' && !(window as any).p5) {
console.error('❌ P5.js not available')
resolve()
return
}
// Wait for canvas container to exist
const waitForContainer = () => {
if (!canvasContainerRef.current) {
console.log('⏳ Waiting for canvas container...')
setTimeout(waitForContainer, 50)
return
}
// Prevent multiple instances
if (typeof window !== 'undefined' && (window as any).p5Instance) {
console.log('⚠️ P5.js instance already exists, removing old one')
;(window as any).p5Instance.remove()
delete (window as any).p5Instance
}
try {
// Use original doormat.js setup and draw functions
const p5Instance = typeof window !== 'undefined' ? new (window as any).p5((p: any) => {
// Original setup function from doormat.js
p.setup = () => {
// Get config from window.doormatData (set during initialization)
const baseDoormatData = (window as any).doormatData
if (!baseDoormatData) {
console.error('❌ Base doormatData not found in window')
return
}
// Create canvas with swapped dimensions for 90-degree rotation (original logic)
const canvas = p.createCanvas(baseDoormatData.config.DOORMAT_HEIGHT + (baseDoormatData.config.FRINGE_LENGTH * 4),
baseDoormatData.config.DOORMAT_WIDTH + (baseDoormatData.config.FRINGE_LENGTH * 4))
canvas.parent(canvasContainerRef.current)
// Let CSS handle positioning - don't set styles here
p.pixelDensity(2)
p.noLoop()
// Initialize flip state from external injection (for smart contracts) - read once only
const defaultFlipped = (window as any).__DEFAULT_FLIPPED__ === true
;(window as any).__RUG_FLIPPED__ = defaultFlipped
console.log('🎨 P5.js canvas created with original dimensions')
console.log('🔄 Default flip state:', defaultFlipped)
// Trigger initial render
p.redraw()
}
// Full rug drawing function (with true mirror flip)
const drawFullRug = (p: any, doormatData: any, seed: number, isFlipped: boolean = false) => {
// Use original doormat.js draw logic
p.background(222, 222, 222)
// Ensure PRNG is initialized with current seed before drawing
initPRNG(seed)
// Create derived PRNG for drawing operations
const drawingPRNG = createDerivedPRNG(2000)
// Apply transforms: translate to center, rotate 90°, mirror if flipped, translate back
p.push()
p.translate(p.width/2, p.height/2)
p.rotate(p.PI/2)
if (isFlipped) p.scale(1, -1) // Vertical mirror flip for correct physical axis
p.translate(-p.height/2, -p.width/2)
// Draw the main doormat area
p.push()
p.translate(doormatData.config.FRINGE_LENGTH * 2, doormatData.config.FRINGE_LENGTH * 2)
// Draw stripes (always in front order - transform handles flipping)
for (const stripe of doormatData.stripeData) {
drawStripeOriginal(p, stripe, doormatData, drawingPRNG, false) // Always front logic
}
// Add overall texture overlay if enabled
const currentShowTexture = (window as any).showTexture || false
const currentTextureLevel = (window as any).textureLevel || 0
if (currentShowTexture && currentTextureLevel > 0) {
drawTextureOverlayWithLevel(p, doormatData, currentTextureLevel)
}
// Draw fringe and selvedge (always front orientation - transform handles flipping)
drawFringeOriginal(p, doormatData, drawingPRNG, false) // Always front logic
drawSelvedgeEdgesOriginal(p, doormatData, drawingPRNG, false) // Always front logic
p.pop()
// Draw dirt overlay if enabled
const currentShowDirt = (window as any).showDirt || false
const currentDirtLevel = (window as any).dirtLevel || 0
if (currentShowDirt && currentDirtLevel > 0) {
drawDirtOverlay(p, doormatData, drawingPRNG, currentDirtLevel)
}
p.pop() // End all transforms
}
// P5 immediate-mode rendering - read ALL data from window
p.draw = () => {
// Read ALL data from authoritative window objects
const doormatData = (window as any).__DOORMAT_DATA__
const isFlipped = (window as any).__RUG_FLIPPED__ || false
if (doormatData) {
// Set authoritative text gate - no text on flipped side
doormatData.__ALLOW_TEXT__ = !isFlipped
// drawFullRug expects complete doormatData object with config
drawFullRug(p, doormatData, doormatData.seed || 42, isFlipped)
}
}
// Get intelligent pattern colors (same as text colors)
const getPatternColors = (doormatData: any, prng: any) => {
if (!doormatData.selectedPalette?.colors) return [p.color(100, 100, 100)]
const palette = doormatData.selectedPalette.colors
const intelligentColors = []
// Use the same color theory as text - select high contrast colors
for (let i = 0; i < Math.min(4, palette.length); i++) {
const colorIndex = (i * 2 + prng.range(0, 2)) % palette.length
intelligentColors.push(p.color(palette[colorIndex]))
}
return intelligentColors.length > 0 ? intelligentColors : [p.color(100, 100, 100)]
}
}) : null
// Store instance for later use
if (typeof window !== 'undefined') {
;(window as any).p5Instance = p5Instance
}
resolve()
} catch (error) {
console.error('❌ Failed to create P5.js instance:', error)
resolve()
}
}
// Start waiting for container
waitForContainer()
})
}
// Wrong generateDoormatCore removed - correct one defined later
const generateDoormatCore = (seed: number, doormatData: any) => {
console.log('🎨 Generating doormat with seed:', seed)
// Store seed globally for drawing function access
if (typeof window !== 'undefined') {
;(window as any).currentSeed = seed
}
// Initialize deterministic PRNG for this generation
initPRNG(seed)
const prng = getPRNG()
// Test PRNG determinism - log first few values
console.log('🧪 PRNG Test - First 5 values:', [
prng.next().toFixed(6),
prng.next().toFixed(6),
prng.next().toFixed(6),
prng.next().toFixed(6),
prng.next().toFixed(6)
])
// RARITY-BASED WARP THICKNESS SELECTION
// Limited to 1-4 to prevent text clipping with 5 lines
const warpThicknessWeights = {
1: 0.10, // 10% - Very thin
2: 0.25, // 25% chance (rare)
3: 0.35, // 35% chance (most common)
4: 0.30 // 30% chance
}
const warpThicknessRoll = prng.next()
let cumulativeWeight = 0
let selectedWarpThickness = 3 // Default to most common
console.log(`🎲 Warp Thickness Roll: ${warpThicknessRoll.toFixed(4)} (seed: ${seed})`)
for (const [thickness, weight] of Object.entries(warpThicknessWeights)) {
cumulativeWeight += weight
console.log(` Thickness ${thickness}: ${(weight * 100).toFixed(1)}% chance (cumulative: ${(cumulativeWeight * 100).toFixed(1)}%)`)
if (warpThicknessRoll <= cumulativeWeight) {
selectedWarpThickness = parseInt(thickness)
console.log(` ✅ SELECTED: Thickness ${thickness} (roll ${warpThicknessRoll.toFixed(4)} <= ${cumulativeWeight.toFixed(4)})`)
break
}
}
doormatData.warpThickness = selectedWarpThickness
// Generate stripes with seeded randomness
doormatData.stripeData = generateStripes(doormatData, seed)
setStripeData(doormatData.stripeData) // Update React state
setPalette(doormatData.selectedPalette) // Update palette React state
// Update text colors and generate text data (MISSING FROM ORIGINAL)
if (typeof window !== 'undefined' && (window as any).p5Instance) {
updateTextColors((window as any).p5Instance, doormatData)
generateTextData(doormatData)
}
// Write COMPLETE doormatData to single authoritative window object
if (typeof window !== 'undefined') {
;(window as any).__DOORMAT_DATA__ = {
// Include ALL necessary data for drawFullRug
...doormatData, // config, characterMap, etc.
seed: seed,
stripeData: doormatData.stripeData,
selectedPalette: doormatData.selectedPalette,
warpThickness: doormatData.warpThickness,
textData: doormatData.textData,
textRows: doormatData.doormatTextRows,
traits: doormatData.traits || {}
}
// Keep legacy properties for backward compatibility
;(window as any).selectedPalette = doormatData.selectedPalette
;(window as any).stripeData = doormatData.stripeData
;(window as any).DOORMAT_CONFIG = doormatData.config
;(window as any).warpThickness = doormatData.warpThickness
;(window as any).textData = doormatData.textData
;(window as any).doormatTextRows = doormatData.doormatTextRows
}
// Trigger p5 redraw (only redraw mechanism)
if (typeof window !== 'undefined' && (window as any).p5Instance) {
(window as any).p5Instance.redraw()
}
}
// Generate stripes with seeded randomness (complete original logic)
const generateStripes = (doormatData: any, seed: number) => {
const stripes = []
const { config, colorPalettes } = doormatData
// Use derived PRNG for stripe generation (based on actual seed)
const stripePRNG = createDerivedPRNG(seed)
// OBSCURED RARITY SYSTEM - Multi-layer mathematical transformations
// Rarity emerges from complex calculations, not explicit percentage labels
const rarityRoll = stripePRNG.next()
const secondaryRoll = stripePRNG.next()
const tertiaryRoll = stripePRNG.next()
// Seed transformation layer (makes input-output relationship non-obvious)
const seedTransform = Math.sin(seed * 0.001) * Math.cos(seed * 0.002) + Math.sin(seed * 0.003)
const transformedSeed = (seedTransform + 1) / 2 // Normalize to 0-1
// Complex transformation using multiple trigonometric and exponential functions
const transformedRarity = Math.sin(rarityRoll * Math.PI * 2.3) * Math.cos(secondaryRoll * Math.PI * 1.7) +
Math.sin(tertiaryRoll * Math.PI * 3.1) * 0.3 +
transformedSeed * 0.2
const normalizedRarity = (transformedRarity + 1.3) / 2.6 // Normalize to 0-1 range
const complexityFactor = Math.pow(tertiaryRoll, 2.718) % 1
const dynamicFactor = Math.sin(rarityRoll * secondaryRoll * Math.PI) * 0.1
// Dynamic tier determination using non-obvious, shifting thresholds
let selectedRarity = 'Common'
const baseThresholds = {
legendary: 0.085 + (complexityFactor * 0.03) + (dynamicFactor * 2),
epic: 0.22 + (secondaryRoll * 0.05) - (complexityFactor * 0.02),
rare: 0.42 + (tertiaryRoll * 0.04) + (dynamicFactor * 1.5),
uncommon: 0.65 + (rarityRoll * 0.03) - (secondaryRoll * 0.02)
}
if (normalizedRarity < baseThresholds.legendary) {
selectedRarity = 'Legendary'
} else if (normalizedRarity < baseThresholds.epic) {
selectedRarity = 'Epic'
} else if (normalizedRarity < baseThresholds.rare) {
selectedRarity = 'Rare'
} else if (normalizedRarity < baseThresholds.uncommon) {
selectedRarity = 'Uncommon'
}
// MANUAL PALETTE CONTROL - Explicit arrays for precise rarity tuning
const getTierPalettes = (tier: string, seed: number) => {
// Manually curated palette assignments for each rarity tier
// Easy to modify during development and testing
const legendaryPalettes = [
"Buddhist", "Maurya Empire", "Chola Empire", "Indigo Famine", "Bengal Famine", "Jamakalam"
]
const epicPalettes = [
"Indian Peacock", "Flamingo", "Toucan", "Madras Checks", "Kanchipuram Gold", "Natural Dyes",
"Bleeding Vintage", "Tamil Classical", "Sangam Era", "Pandyas", "Maratha Empire"
]
const rarePalettes = [
"Rajasthani", "Kerala", "Gujarat", "Bengal", "Kashmir", "Chera Dynasty", "Madder Root",
"Turmeric", "Neem", "Marigold", "Thanjavur Fresco", "Malabar Trogon", "Maurya Empire"
]
const uncommonPalettes = [
"Tamil Nadu Temple", "Kerala Onam", "Chettinad Spice", "Madras Monsoon", "Bengal Indigo",
"Goa Beach", "Sri Lankan Tea", "African Madras", "Ivy League", "Tamil Sunrise", "Chettinad Spice"
]
switch(tier) {
case 'Legendary':
return legendaryPalettes
case 'Epic':
return epicPalettes
case 'Rare':
return rarePalettes
case 'Uncommon':
return uncommonPalettes
default:
// Common: all palettes not assigned to higher tiers
const allHigherTierPalettes = [
...legendaryPalettes,
...epicPalettes,
...rarePalettes,
...uncommonPalettes
]
return colorPalettes
.map(p => p.name)
.filter(paletteName => !allHigherTierPalettes.includes(paletteName))
}
}
const tierPalettes = getTierPalettes(selectedRarity, seed)
// Select random palette from the rarity tier using PRNG
const tierPaletteIndex = Math.floor(stripePRNG.next() * tierPalettes.length)
const selectedPaletteName = tierPalettes[tierPaletteIndex]
const palette = colorPalettes.find(p => p.name === selectedPaletteName) || colorPalettes[0]
doormatData.selectedPalette = palette
console.log(`🎯 Generated ${selectedRarity} rarity doormat with palette: ${palette.name}`)
console.log(`📊 Available ${selectedRarity} palettes: ${tierPalettes.length} options`)
console.log(`🎨 Selected palette index: ${tierPaletteIndex}/${tierPalettes.length - 1}`)
// Original doormat.js stripe generation logic
const totalHeight = config.DOORMAT_HEIGHT
let currentY = 0
// Track previous stripe's weave type to prevent consecutive mixed stripes
let previousWeaveType = null
// Decide stripe density pattern for this doormat
const densityType = stripePRNG.next()
let minHeight, maxHeight
if (densityType < 0.2) {
// 20% chance: High density (many thin stripes)
minHeight = 15
maxHeight = 35
} else if (densityType < 0.4) {
// 20% chance: Low density (fewer thick stripes)
minHeight = 50
maxHeight = 90
} else {
// 60% chance: Mixed density (varied stripe sizes)
minHeight = 20
maxHeight = 80
}
while (currentY < totalHeight) {
// Dynamic stripe height based on density type
let stripeHeight
if (densityType >= 0.4) {
// Mixed density: add more randomization within the range
const variationType = stripePRNG.next()
if (variationType < 0.3) {
// 30% thin stripes within mixed
stripeHeight = minHeight + (stripePRNG.next() * 20)
} else if (variationType < 0.6) {
// 30% medium stripes within mixed
stripeHeight = minHeight + 15 + (stripePRNG.next() * (maxHeight - minHeight - 30))
} else {
// 40% thick stripes within mixed
stripeHeight = maxHeight - 25 + (stripePRNG.next() * 25)
}
} else {
// High/Low density: more consistent sizing
stripeHeight = minHeight + (stripePRNG.next() * (maxHeight - minHeight))
}
// Ensure we don't exceed the total height
if (currentY + stripeHeight > totalHeight) {
stripeHeight = totalHeight - currentY
}
// Select colors for this stripe
const primaryColor = palette.colors[Math.floor(stripePRNG.next() * palette.colors.length)]
// RARITY-BASED SECONDARY COLOR GENERATION
// Make blended colors rarer based on overall rarity
let secondaryColorChance = 0.15 // Base 15% chance
if (selectedRarity === 'Legendary') {
secondaryColorChance = 0.4 // 40% chance for Legendary
} else if (selectedRarity === 'Epic') {
secondaryColorChance = 0.3 // 30% chance for Epic
} else if (selectedRarity === 'Rare') {
secondaryColorChance = 0.25 // 25% chance for Rare
} else if (selectedRarity === 'Uncommon') {
secondaryColorChance = 0.2 // 20% chance for Uncommon
}
// Common keeps 15% chance
// Log secondary color chance for first stripe only
if (currentY === 0) {
console.log(`🎨 ${selectedRarity} Secondary Color Chance: ${(secondaryColorChance * 100).toFixed(1)}%`)
}
const hasSecondaryColor = stripePRNG.next() < secondaryColorChance
const secondaryColor = hasSecondaryColor ? palette.colors[Math.floor(stripePRNG.next() * palette.colors.length)] : null
// RARITY-BASED WEAVE PATTERN SELECTION
// Make complex patterns rarer based on overall rarity
const weaveRand = stripePRNG.next()
let weaveType
// Adjust probabilities based on palette rarity
let solidChance = 0.6, texturedChance = 0.2, mixedChance = 0.2
if (selectedRarity === 'Legendary') {
// Legendary: More complex patterns
solidChance = 0.3
texturedChance = 0.3
mixedChance = 0.4
} else if (selectedRarity === 'Epic') {
// Epic: Balanced with more complexity
solidChance = 0.4
texturedChance = 0.3
mixedChance = 0.3
} else if (selectedRarity === 'Rare') {
// Rare: Slightly more complex
solidChance = 0.5
texturedChance = 0.25
mixedChance = 0.25
} else if (selectedRarity === 'Uncommon') {
// Uncommon: Slightly more complex
solidChance = 0.55
texturedChance = 0.25
mixedChance = 0.2
}
// Common keeps original probabilities
// Log weave pattern probabilities for first stripe only
if (currentY === 0) {
console.log(`🎨 ${selectedRarity} Weave Pattern Probabilities:`)
console.log(` Solid: ${(solidChance * 100).toFixed(1)}%, Textured: ${(texturedChance * 100).toFixed(1)}%, Mixed: ${(mixedChance * 100).toFixed(1)}%`)
}
// Prevent consecutive mixed stripes to avoid text obfuscation
if (weaveRand < solidChance) {
weaveType = 's' // solid
} else if (weaveRand < solidChance + texturedChance) {
weaveType = 't' // textured
} else {
// Only use mixed if we actually have a secondary color AND previous stripe wasn't mixed
const wantsMixed = hasSecondaryColor && previousWeaveType !== 'm'
weaveType = wantsMixed ? 'm' : 's' // mixed only if secondary color exists AND not consecutive, otherwise fallback to solid
}
// Create stripe object (original structure)
const stripe = {
y: currentY,
height: stripeHeight,
primaryColor: primaryColor,
secondaryColor: secondaryColor,
weaveType: weaveType,
warpVariation: stripePRNG.next() * 0.4 + 0.1 // How much the weave varies
}
stripes.push(stripe)
previousWeaveType = weaveType // Track for preventing consecutive mixed stripes
currentY += stripeHeight
}
return stripes
}
// Original doormat.js drawStripe function
const drawStripeOriginal = (p: any, stripe: any, doormatData: any, drawingPRNG: any, isFlipped: boolean = false) => {
const config = doormatData.config
const warpSpacing = doormatData.warpThickness + 1
const weftSpacing = config.WEFT_THICKNESS + 1
// Draw character outlines first (for mixed weaves)
drawCharacterOutlines(p, stripe, doormatData)
// First, draw the warp threads (vertical) as the foundation
for (let x = 0; x < config.DOORMAT_WIDTH; x += warpSpacing) {
for (let y = stripe.y; y < stripe.y + stripe.height; y += weftSpacing) {
const warpColor = p.color(stripe.primaryColor)
// Check if this position should be modified for text (only on front side)
let isTextPixel = false
if (doormatData.__ALLOW_TEXT__ && doormatData.textData && doormatData.textData.length > 0) {
for (const textPixel of doormatData.textData) {
if (x >= textPixel.x && x < textPixel.x + textPixel.width &&
y >= textPixel.y && y < textPixel.y + textPixel.height) {
isTextPixel = true
break
}
}
}
// Add subtle variation to warp threads
let r = p.red(warpColor) + drawingPRNG.range(-15, 15)
let g = p.green(warpColor) + drawingPRNG.range(-15, 15)
let b = p.blue(warpColor) + drawingPRNG.range(-15, 15)
// Handle text pixels in warp threads
if (isTextPixel) {
// Draw shadow for text
p.fill(0, 0, 0, 120)
p.noStroke()
const warpCurve = p.sin(y * 0.05) * 0.5
p.rect(x + warpCurve + 0.5, y + 0.5, doormatData.warpThickness, weftSpacing)
// Use intelligent text color selection for warp threads
if (stripe.weaveType === 'm' && stripe.secondaryColor) {
// For mixed weaves, choose text color that contrasts best with BOTH colors
const primaryBrightness = (p.red(p.color(stripe.primaryColor)) + p.green(p.color(stripe.primaryColor)) + p.blue(p.color(stripe.primaryColor))) / 3
const secondaryBrightness = (p.red(p.color(stripe.secondaryColor)) + p.green(p.color(stripe.secondaryColor)) + p.blue(p.color(stripe.secondaryColor))) / 3
// Test contrast with black vs white
const blackContrastPrimary = Math.abs(primaryBrightness - 0)
const blackContrastSecondary = Math.abs(secondaryBrightness - 0)
const whiteContrastPrimary = Math.abs(primaryBrightness - 255)
const whiteContrastSecondary = Math.abs(secondaryBrightness - 255)
// Use the color that gives better minimum contrast
const blackMinContrast = Math.min(blackContrastPrimary, blackContrastSecondary)
const whiteMinContrast = Math.min(whiteContrastPrimary, whiteContrastSecondary)
if (whiteMinContrast > blackMinContrast) {
r = 255; g = 255; b = 255 // White
} else {
r = 0; g = 0; b = 0 // Black
}
} else {
r = 0; g = 0; b = 0 // Black for warp threads
}
} else {
// Normal warp thread color
r = p.red(warpColor) + drawingPRNG.range(-15, 15)
g = p.green(warpColor) + drawingPRNG.range(-15, 15)
b = p.blue(warpColor) + drawingPRNG.range(-15, 15)
}
r = p.constrain(r, 0, 255)
g = p.constrain(g, 0, 255)
b = p.constrain(b, 0, 255)
p.fill(r, g, b)
p.noStroke()
// Draw warp thread with slight curve for natural look
const warpCurve = p.sin(y * 0.05) * 0.5
p.rect(x + warpCurve, y, doormatData.warpThickness, weftSpacing)
}
}
// Now draw the weft threads (horizontal) that interlace with warp
for (let y = stripe.y; y < stripe.y + stripe.height; y += weftSpacing) {
for (let x = 0; x < config.DOORMAT_WIDTH; x += warpSpacing) {
let weftColor = p.color(stripe.primaryColor)
// Add variation based on weave type
if (stripe.weaveType === 'm' && stripe.secondaryColor) {
if (p.noise(x * 0.1, y * 0.1) > 0.5) {
weftColor = p.color(stripe.secondaryColor)
}
} else if (stripe.weaveType === 't') {
const noiseVal = p.noise(x * 0.05, y * 0.05)
weftColor = p.lerpColor(p.color(stripe.primaryColor), p.color(255), noiseVal * 0.15)
}
// Check if this position should be modified for text (only on front side)
let isTextPixel = false
if (doormatData.__ALLOW_TEXT__ && doormatData.textData && doormatData.textData.length > 0) {
for (const textPixel of doormatData.textData) {
if (x >= textPixel.x && x < textPixel.x + textPixel.width &&
y >= textPixel.y && y < textPixel.y + textPixel.height) {
isTextPixel = true
break
}
}
}
// Add fabric irregularities
let r = p.red(weftColor) + drawingPRNG.range(-20, 20)
let g = p.green(weftColor) + drawingPRNG.range(-20, 20)
let b = p.blue(weftColor) + drawingPRNG.range(-20, 20)
// Handle text pixels with special rendering
if (isTextPixel) {
// Draw shadow for text (works on all backgrounds)
p.fill(0, 0, 0, 120) // Semi-transparent black shadow
p.noStroke()
const weftCurve = p.cos(x * 0.05) * 0.5
p.rect(x + 0.5, y + weftCurve + 0.5, warpSpacing, config.WEFT_THICKNESS)
// Use high contrast text color
if (stripe.weaveType === 'm' && stripe.secondaryColor) {
// For mixed weaves: analyse local background and choose a high-contrast colour
const sampleColors: any[] = []
const checkRadius = 2
const stripeWidth = doormatData.config?.DOORMAT_WIDTH || config.DOORMAT_WIDTH
// Always include the current weft colour
sampleColors.push(p.color(weftColor))
for (let dx = -checkRadius; dx <= checkRadius; dx++) {
for (let dy = -checkRadius; dy <= checkRadius; dy++) {
if (dx === 0 && dy === 0) continue
const checkX = x + dx
const checkY = y + dy
if (checkY < stripe.y || checkY >= stripe.y + stripe.height) continue
if (checkX < 0 || checkX >= stripeWidth) continue
let checkWeftColor = p.color(stripe.primaryColor)
const noiseVal = p.noise(checkX * 0.1, checkY * 0.1)
if (noiseVal > 0.5) {