mirl 9.2.0

Miners Rust Lib - A massive collection of ever growing and changing functions, structs, and enums. Check the description for compatibility and toggleable features! (Most of the lib is controlled by flags/features so the lib can continue to be lightweight despite its size)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
#![allow(clippy::inline_always)]
#![allow(clippy::cast_lossless)]

#[allow(unused_imports)]
use crate::extensions::*;

#[cfg(feature = "random")]
#[cfg(not(target_arch = "wasm32"))]
mod random;

#[cfg(feature = "random")]
#[cfg(not(target_arch = "wasm32"))]
pub use random::*;

/// Presets for common colors
pub mod colors;
mod interpolation;
pub use interpolation::*;
/// Convert an r b g format into u32 argb format
#[inline(always)]
#[must_use]
pub const fn rgb_u8_to_u32(r: u8, g: u8, b: u8) -> u32 {
    (r as u32) << 16 | (g as u32) << 8 | (b as u32)
}

/// Convert an r b g format into u32 argb format
#[inline(always)]
#[must_use]
pub const fn rgb_to_u32(r: u32, g: u32, b: u32) -> u32 {
    r << 16 | g << 8 | b
}
#[inline(always)]
#[must_use]
/// Convert r g b a in argb format
pub const fn rgba_u8_to_u32(r: u8, g: u8, b: u8, a: u8) -> u32 {
    (a as u32) << 24 | (r as u32) << 16 | (g as u32) << 8 | b as u32
}
#[inline(always)]
#[must_use]
/// Convert r g b a into u32 argb
pub const fn rgba_to_u32(r: u32, g: u32, b: u32, a: u32) -> u32 {
    (a) << 24 | (r) << 16 | (g) << 8 | b
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to r g b
pub const fn u32_to_rgb_u8(color: u32) -> (u8, u8, u8) {
    let red = ((color >> 16) & 0xFF) as u8;
    let green = ((color >> 8) & 0xFF) as u8;
    let blue = (color & 0xFF) as u8;
    (red, green, blue)
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to r g b
pub const fn u32_to_rgb(color: u32) -> (u32, u32, u32) {
    let red = (color >> 16) & 0xFF;
    let green = (color >> 8) & 0xFF;
    let blue = color & 0xFF;
    (red, green, blue)
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to r g b a or u32 rgba to a g b r
pub const fn u32_to_rgba_u8(color: u32) -> (u8, u8, u8, u8) {
    let alpha = ((color >> 24) & 0xFF) as u8;
    let red = ((color >> 16) & 0xFF) as u8;
    let green = ((color >> 8) & 0xFF) as u8;
    let blue = (color & 0xFF) as u8;
    (red, green, blue, alpha)
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to r g b a or u32 rgba to a g b r
pub const fn u32_to_rgba(color: u32) -> (u32, u32, u32, u32) {
    let alpha = (color >> 24) & 0xFF;
    let red = (color >> 16) & 0xFF;
    let green = (color >> 8) & 0xFF;
    let blue = color & 0xFF;
    (red, green, blue, alpha)
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to a g b r or u32 rgba to r g b a
pub const fn u32_to_argb_u8(color: u32) -> (u8, u8, u8, u8) {
    let alpha = ((color >> 24) & 0xFF) as u8;
    let red = ((color >> 16) & 0xFF) as u8;
    let green = ((color >> 8) & 0xFF) as u8;
    let blue = (color & 0xFF) as u8;
    (alpha, red, green, blue)
}
#[inline(always)]
#[must_use]
/// Convert u32 argb to a g b r or u32 rgba to r g b a
pub const fn u32_to_argb(color: u32) -> (u32, u32, u32, u32) {
    let alpha = (color >> 24) & 0xFF;
    let red = (color >> 16) & 0xFF;
    let green = (color >> 8) & 0xFF;
    let blue = color & 0xFF;
    (alpha, red, green, blue)
}

#[inline(always)]
#[must_use]
/// Get the alpha of a u32 in argb style, get red rgba style
pub const fn get_alpha_of_u32_in_u8(color: u32) -> u8 {
    ((color >> 24) & 0xFF) as u8
}

#[inline(always)]
#[must_use]
/// Get the red of a u32 in argb style, get alpha rgba style
pub const fn get_red_of_u32_in_u8(color: u32) -> u8 {
    ((color >> 16) & 0xFF) as u8
}
#[inline(always)]
#[must_use]
/// Get the green of a u32
pub const fn get_green_of_u32_in_u8(color: u32) -> u8 {
    ((color >> 8) & 0xFF) as u8
}
#[inline(always)]
#[must_use]
/// Get the blue of a u32
pub const fn get_blue_of_u32_in_u8(color: u32) -> u8 {
    (color & 0xFF) as u8
}
//

#[inline(always)]
#[must_use]
/// Get the alpha of a u32 in argb style, get red rgba style
pub const fn get_alpha_of_u32(color: u32) -> u32 {
    (color >> 24) & 0xFF
}

#[inline(always)]
#[must_use]
/// Get the red of a u32 in argb style, get alpha rgba style
pub const fn get_red_of_u32(color: u32) -> u32 {
    (color >> 16) & 0xFF
}
#[inline(always)]
#[must_use]
/// Get the green of a u32
pub const fn get_green_of_u32(color: u32) -> u32 {
    (color >> 8) & 0xFF
}
#[inline(always)]
#[must_use]
/// Get the blue of a u32
pub const fn get_blue_of_u32(color: u32) -> u32 {
    color & 0xFF
}
/// Image support for mirl
#[cfg(feature = "imagery")]
#[cfg(feature = "std")]
pub mod imagery;
#[cfg(feature = "std")]
use std::collections::HashSet;

#[cfg(feature = "imagery")]
#[cfg(feature = "std")]
pub use imagery::*;

#[inline]
#[must_use]
#[allow(clippy::float_cmp)]
/// Get hue of rgb (hsl space)
pub fn get_hue_of_rgb(r: f32, g: f32, b: f32) -> f32 {
    let max = r.max(g).max(b);
    let min = r.min(g).min(b);

    if max == min {
        0.0
    } else if max == r {
        ((g - b) / core::f32::math::rem_euclid(max - min, 6.0)) * 60.0
    } else if max == g {
        ((b - r) / (max - min) + 2.0) * 60.0
    } else {
        ((r - g) / (max - min) + 4.0) * 60.0
    }
}

#[inline]
#[must_use]
#[allow(clippy::cast_precision_loss)]
/// Change the brightness of a hsl space
pub fn adjust_brightness_hsl_of_rgb(color: u32, change: f32) -> u32 {
    let alpha = (color >> 24) & 0xFF;
    let red = (color >> 16) & 0xFF;
    let green = (color >> 8) & 0xFF;
    let blue = color & 0xFF;

    let (h, s, l) = rgb_to_hsl(red as u8, green as u8, blue as u8);

    // Adjust lightness in HSL space (most perceptually accurate)
    let l_new = (l + change).clamp(0.0, 100.0);

    let (r_new, g_new, b_new) = hsl_to_rgb_u32(h, s, l_new);

    (alpha << 24) | (r_new << 16) | (g_new << 8) | b_new
}
#[inline]
#[must_use]
#[allow(clippy::cast_possible_truncation)]
/// Convert hsl space to rgb space
pub const fn hsl_to_rgb_f32(
    hue: f32,
    saturation: f32,
    lightness: f32,
) -> (f32, f32, f32) {
    let c = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
    let x = c * (1.0 - ((hue / 60.0) % 2.0 - 1.0).abs());
    let m = lightness - c / 2.0;

    let (r1, g1, b1) = match hue as i32 {
        0..=59 => (c, x, 0.0),
        60..=119 => (x, c, 0.0),
        120..=179 => (0.0, c, x),
        180..=239 => (0.0, x, c),
        240..=299 => (x, 0.0, c),
        300..=359 => (c, 0.0, x),
        _ => (0.0, 0.0, 0.0),
    };

    (r1 + m, g1 + m, b1 + m)
}

#[inline]
#[must_use]
#[allow(clippy::float_cmp)]
/// Convert rgb space to hsl space
pub const fn rgb_to_hsl(r: u8, g: u8, b: u8) -> (f32, f32, f32) {
    let r_norm = r as f32 / 255.0;
    let g_norm = g as f32 / 255.0;
    let b_norm = b as f32 / 255.0;

    let max = r_norm.max(g_norm).max(b_norm);
    let min = r_norm.min(g_norm).min(b_norm);
    let delta = max - min;

    let lightness = f32::midpoint(max, min);

    let saturation = if delta < 0.0001 {
        0.0 // achromatic (gray)
    } else if lightness < 0.5 {
        delta / (max + min)
    } else {
        delta / (2.0 - max - min)
    };

    let hue = if delta < 0.0001 {
        0.0 // achromatic (gray)
    } else if max == r_norm {
        60.0 * (((g_norm - b_norm) / delta) % 6.0)
    } else if max == g_norm {
        60.0 * ((b_norm - r_norm) / delta + 2.0)
    } else {
        60.0 * ((r_norm - g_norm) / delta + 4.0)
    };

    (hue, saturation * 100.0, lightness * 100.0)
}

#[inline]
#[must_use]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
/// Convert hsl space to rgb space
pub fn hsl_to_rgb_u32(
    hue: f32,
    saturation: f32,
    lightness: f32,
) -> (u32, u32, u32) {
    let h_norm = hue / 360.0;
    let s_norm = saturation / 100.0;
    let l_norm = lightness / 100.0;

    if s_norm < 0.0001 {
        let gray = core::f32::math::round(l_norm * 255.0) as u32;
        return (gray, gray, gray);
    }

    let hue_to_rgb = |p: f32, q: f32, t: f32| -> f32 {
        let t_adj = if t < 0.0 {
            t + 1.0
        } else if t > 1.0 {
            t - 1.0
        } else {
            t
        };

        if t_adj < 1.0 / 6.0 {
            core::f32::math::mul_add((q - p) * 6.0, t_adj, p)
        } else if t_adj < 1.0 / 2.0 {
            q
        } else if t_adj < 2.0 / 3.0 {
            core::f32::math::mul_add((q - p) * (2.0 / 3.0 - t_adj), 6.0, p)
        } else {
            p
        }
    };

    let q = if l_norm < 0.5 {
        l_norm * (1.0 + s_norm)
    } else {
        core::f32::math::mul_add(l_norm, -s_norm, l_norm + s_norm)
    };
    let p = core::f32::math::mul_add(2.0f32, l_norm, -q);

    let red = hue_to_rgb(p, q, h_norm + 1.0 / 3.0);
    let green = hue_to_rgb(p, q, h_norm);
    let blue = hue_to_rgb(p, q, h_norm - 1.0 / 3.0);

    let r_8bit = core::f32::math::round(red * 255.0) as u32;
    let g_8bit = core::f32::math::round(green * 255.0) as u32;
    let b_8bit = core::f32::math::round(blue * 255.0) as u32;

    (r_8bit, g_8bit, b_8bit)
}

// /// Higher-level function that provides both perceptual models
// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
// #[cfg_attr(feature = "c_compatible", repr(C))] pub enum BrightnessModel {
//     /// Uses RGB with perceptual weights
//     LinearWeighted,
//     /// Uses HSL color space
//     HSL,
// }
// #[inline]
// #[must_use]
// #[allow(clippy::cast_sign_loss)]
// #[allow(clippy::cast_precision_loss)]
// #[allow(clippy::cast_possible_truncation)]
// #[allow(clippy::cast_possible_wrap)]
// /// Change the brightness of an rgba color
// pub fn adjust_brightness_based_on_human_eye(
//     color: u32,
//     x: f32,
//     model: BrightnessModel,
// ) -> u32 {
//     match model {
//         BrightnessModel::LinearWeighted => {
//             // Extract color components
//             let (alpha, red, green, blue): (u32, f32, f32, f32) =
//                 u32_to_argb(color).try_tuple_into();
//             // Apply perceptual weights to adjustment
//             let r_adj = x * 0.2126;
//             let g_adj = x * 0.7152;
//             let b_adj = x * 0.0722;

//             // Apply adjustments with clamping
//             let r_new = (red + r_adj).clamp(0.0, 255.0) as u32;
//             let g_new = (green + g_adj).clamp(0.0, 255.0) as u32;
//             let b_new = (blue + b_adj).clamp(0.0, 255.0) as u32;

//             // Recombine with alpha
//             (alpha << 24) | (r_new << 16) | (g_new << 8) | b_new
//         }
//         BrightnessModel::HSL => adjust_brightness_hsl_of_rgb(color, x),
//     }
// }

#[inline]
#[must_use]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_precision_loss)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_possible_wrap)]
/// Shift the color (hue) of rgb
pub fn shift_color_rgb(
    red: u8,
    green: u8,
    blue: u8,
    hue_shift: f32,
) -> (u32, u32, u32) {
    let (hue, saturation, lightness) = rgb_to_hsl(red, green, blue);

    let new_h = (hue + hue_shift) % 360.0;

    let l_norm = lightness / 100.0;
    let s_norm = saturation / 100.0;

    let new_s = if l_norm > 0.5 {
        // Brighter colors - reduce saturation as lightness increases
        s_norm * core::f32::math::mul_add(l_norm - 0.5, -2.0, 1.0) * 100.0
    } else {
        // Darker colors - reduce saturation as lightness decreases
        s_norm * core::f32::math::mul_add(0.5 - l_norm, -2.0, 1.0) * 100.0
    };

    let new_l = if l_norm > 0.5 {
        // Brighter colors - darken slightly to maintain balance
        l_norm * 0.95 * 100.0
    } else {
        // Darker colors - lighten slightly, but don't go over 100
        (l_norm * 1.1).min(1.0) * 100.0
    };

    let new_s = new_s.clamp(0.0, 100.0);
    let new_l = new_l.clamp(0.0, 100.0);

    hsl_to_rgb_u32(new_h, new_s, new_l)
}

#[must_use]
/// Shift the hue of rgb, isn't there another function that does the exact same?
pub fn shift_hue_rgb(
    r: u8,
    g: u8,
    b: u8,
    hue_shift_degrees: f32,
) -> (u32, u32, u32) {
    // Convert to floating point RGB
    let mut hsv = rgb_to_hsl(r, g, b);

    // Shift hue
    hsv.0 = (hsv.0 + hue_shift_degrees) % 360.0;

    // Convert back to integer RGB
    let (r, g, b) = hsl_to_rgb_u32(hsv.0, hsv.1, hsv.2);
    (r, g, b)
}
#[must_use]
/// Shift the hue of a rgba u32
pub fn shift_hue_u32(color: u32, hue_shift: f32) -> u32 {
    let (r, g, b) = u32_to_rgb_u8(color);
    let (r, g, b) = shift_hue_rgb(r, g, b, hue_shift);
    rgb_to_u32(r, g, b)
}
#[inline]
#[must_use]
/// Shift the color of a rgba u32
pub fn shift_color_u32(color: u32, hue_shift: f32) -> u32 {
    let alpha = (color >> 24) & 0xFF;
    let red = (color >> 16) & 0xFF;
    let green = (color >> 8) & 0xFF;
    let blue = color & 0xFF;

    let (r_new, g_new, b_new) =
        shift_color_rgb(red as u8, green as u8, blue as u8, hue_shift);

    rgba_to_u32(r_new, g_new, b_new, alpha)
}

#[must_use]
#[inline]
#[allow(clippy::cast_sign_loss)]
/// Adjust the brightness of a rgba u32 color faster than with the function that does it with with human perception in mind
pub fn adjust_brightness_fast(color: u32, x: i32) -> u32 {
    // Extract color components
    let (red, green, blue): (i32, i32, i32) =
        u32_to_rgb(color).try_tuple_into().unwrap_or((0, 0, 0));

    // Calculate new values with clamping
    let r_new = (red + x).clamp(0, 255) as u32;
    let g_new = (green + x).clamp(0, 255) as u32;
    let b_new = (blue + x).clamp(0, 255) as u32;

    // Recombine into a single color value
    (r_new << 16) | (g_new << 8) | b_new
}
/// Desaturate the current color without caring that much about human vision
#[inline]
#[must_use]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_precision_loss)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_possible_wrap)]
pub fn desaturate_fast(color: u32, amount: f32) -> u32 {
    // Extract color components
    let red = ((color >> 16) & 0xFF) as f32;
    let green = ((color >> 8) & 0xFF) as f32;
    let blue = (color & 0xFF) as f32;

    // Compute grayscale (luminance approximation)
    let gray = core::f32::math::mul_add(
        0.114f32,
        blue,
        core::f32::math::mul_add(0.299f32, red, 0.587 * green),
    );

    // Interpolate between color and gray based on amount (0.0 to 1.0)
    let r_new = core::f32::math::mul_add(red, 1.0 - amount, gray * amount)
        .clamp(0.0, 255.0) as u32;
    let g_new = core::f32::math::mul_add(green, 1.0 - amount, gray * amount)
        .clamp(0.0, 255.0) as u32;
    let b_new = core::f32::math::mul_add(blue, 1.0 - amount, gray * amount)
        .clamp(0.0, 255.0) as u32;

    // Recombine
    (r_new << 16) | (g_new << 8) | b_new
}
#[allow(clippy::missing_errors_doc)]
/// Rasterize an svg in the desired dimensions
#[cfg(feature = "svg")]
pub fn rasterize_svg(
    svg_data: &[u8],
    width: u32,
    height: u32,
) -> Result<resvg::tiny_skia::Pixmap, Option<resvg::usvg::Error>> {
    let opt = resvg::usvg::Options::default();
    //let fontdb = usvg::fontdb::Database::new();

    let tree = match resvg::usvg::Tree::from_data(svg_data, &opt) {
        Ok(value) => value,
        Err(error) => return Err(Some(error)),
    };

    // Create a pixmap with desired size (from SVG's size)
    let mut pixmap =
        resvg::tiny_skia::Pixmap::new(width, height).ok_or(None)?;

    // Render the SVG
    resvg::render(
        &tree,
        resvg::usvg::Transform::default(),
        &mut pixmap.as_mut(),
    );

    Ok(pixmap)
}
#[cfg(feature = "svg")]
#[cfg(feature = "std")]
#[allow(clippy::unwrap_used, clippy::missing_panics_doc)]
/// To use this function, enable the "`svg`" feature
/// Converts a `resvg::tiny_skia::Pixmap` to a `mirl::Buffer`
#[must_use]
pub fn pixmap_to_buffer(pixmap: &resvg::tiny_skia::Pixmap) -> Buffer {
    let mut data = Vec::new();
    for y in 0..pixmap.height() {
        for x in 0..pixmap.width() {
            let color = unsafe { pixmap.pixel(x, y).unwrap_unchecked() };
            data.push(rgba_u8_to_u32(
                color.red(),
                color.green(),
                color.blue(),
                color.alpha(),
            ));
        }
    }
    unsafe {
        Buffer::new((pixmap.width() as usize, pixmap.height() as usize), data)
            .unwrap_unchecked()
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "glfw")]
#[cfg(feature = "std")]
use glfw::PixelImage;
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "glfw")]
/// Convert a Buffer into a `glfw::PixelImage`
#[inline(always)]
#[must_use]
#[allow(clippy::cast_precision_loss)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[cfg(feature = "std")]
pub fn buffer_to_pixel_image(buffer: &Buffer) -> glfw::PixelImage {
    glfw::PixelImage {
        width: buffer.width as u32,
        height: buffer.height as u32,
        pixels: switch_red_and_blue_list(&buffer.data),
    }
}
/// Convert a `glfw::PixelImage` into a Buffer
#[cfg(feature = "glfw")]
#[cfg(not(target_arch = "wasm32"))]
#[inline(always)]
#[must_use]
#[cfg(feature = "std")]
#[allow(clippy::missing_panics_doc, clippy::unwrap_used)]
pub fn pixel_image_to_buffer(pixel_image: &glfw::PixelImage) -> Buffer {
    Buffer::new(
        (pixel_image.width as usize, pixel_image.height as usize),
        rgba_list_to_argb_list(&pixel_image.pixels),
    )
    .unwrap()
}
// /// A Buffer to be accessed without compression
// /// What is the difference between Buffer and Buffer? Buffer has more attributes ig :|
// #[derive(Debug, Clone, PartialEq, Eq)]
// #[cfg_attr(feature = "c_compatible", repr(C))]
// pub struct Buffer {
//     /// The Raw Data
//     pub data: Box<[u32]>,
//     /// The width of the image
//     pub width: usize,
//     /// The height of the image
//     pub height: usize,
// }

// impl Buffer {
//     /// Create a new Buffer with some data, if you want to create an empty image use Buffer::new_empty()
//     pub fn new(data: Vec<u32>, width: usize, height: usize) -> Self {
//         Self {
//             data: data.into_boxed_slice(),
//             width,
//             height,
//         }
//     }
//     /// Create a new, empty, Buffer instance. If you already have data to fill it with you can use Buffer::new()
//     pub fn new_empty(width: usize, height: usize) -> Self {
//         Self {
//             data: repeat_data(0, width * height).into(),
//             width: width,
//             height: height,
//         }
//     }
//     /// Gets the pixel color at the requested 3d coordinates
//     pub fn get_pixel(&self, pos: (usize, usize)) -> u32 {
//         return self.data[pos.1 * self.width + pos.0];
//     }
//     /// Generate a error texture with the desired size
//     pub fn generate_fallback(
//         width: usize,
//         height: usize,
//         square_size: usize,
//     ) -> Self {
//         let mut data = Vec::with_capacity(width * height);

//         let purple = rgb_to_u32(128, 0, 128);
//         let black = rgb_to_u32(0, 0, 0);

//         for y in 0..height {
//             for x in 0..width {
//                 let square_x = x / square_size;
//                 let square_y = y / square_size;

//                 let color = if (square_x + square_y) % 2 == 0 {
//                     purple
//                 } else {
//                     black
//                 };

//                 data.push(color);
//             }
//         }

//         Self::new(data, width, height)
//     }
//     /// Optimizes the image by removing empty space around the image
//     pub fn remove_margins(&mut self) {
//         // Remove all margins in one pass to avoid multiple data copies
//         let (top_trim, bottom_trim, left_trim, right_trim) =
//             self.calculate_trims();

//         if top_trim > 0 || bottom_trim > 0 || left_trim > 0 || right_trim > 0 {
//             self.apply_trim(top_trim, bottom_trim, left_trim, right_trim);
//         }
//     }
//     /// Calculates the empty space around the image
//     pub fn calculate_trims(&self) -> (usize, usize, usize, usize) {
//         let mut top_trim = 0;
//         let mut bottom_trim = 0;
//         let mut left_trim = 0;
//         let mut right_trim = 0;

//         // Calculate top trim
//         for row in 0..self.height {
//             if self.is_row_transparent(row) {
//                 top_trim += 1;
//             } else {
//                 break;
//             }
//         }

//         // Calculate bottom trim
//         for row in (0..self.height).rev() {
//             if self.is_row_transparent(row) {
//                 bottom_trim += 1;
//             } else {
//                 break;
//             }
//         }

//         // Calculate left trim
//         for col in 0..self.width {
//             if self.is_col_transparent(col) {
//                 left_trim += 1;
//             } else {
//                 break;
//             }
//         }

//         // Calculate right trim
//         for col in (0..self.width).rev() {
//             if self.is_col_transparent(col) {
//                 right_trim += 1;
//             } else {
//                 break;
//             }
//         }

//         (top_trim, bottom_trim, left_trim, right_trim)
//     }
//     /// Checks if the requested row only has fully transparent pixels
//     pub fn is_row_transparent(&self, row: usize) -> bool {
//         let start = row * self.width;
//         let end = start + self.width;
//         self.data[start..end]
//             .iter()
//             .all(|&pixel| get_u32_alpha_of_u32(pixel) == 0)
//     }
//     /// Checks if the requested column only has fully transparent pixels
//     pub fn is_col_transparent(&self, col: usize) -> bool {
//         (0..self.height).all(|row| {
//             get_u32_alpha_of_u32(self.data[row * self.width + col]) == 0
//         })
//     }
//     /// Trims the image by the given restrictions
//     pub fn apply_trim(
//         &mut self,
//         top: usize,
//         bottom: usize,
//         left: usize,
//         right: usize,
//     ) {
//         let new_width = self.width - left - right;
//         let new_height = self.height - top - bottom;
//         let mut new_data = Vec::with_capacity(new_width * new_height);

//         for row in top..(self.height - bottom) {
//             let row_start = row * self.width + left;
//             let row_end = row_start + new_width;
//             new_data.extend_from_slice(&self.data[row_start..row_end]);
//         }

//         self.data = new_data.into();
//         self.width = new_width;
//         self.height = new_height;
//     }
// }

// impl From<Buffer> for Buffer {
//     fn from(p: Buffer) -> Self {
//         Buffer {
//             data: p.buffer,
//             width: p.width,
//             height: p.height,
//         }
//     }
// }
// impl From<Buffer> for Buffer {
//     fn from(p: Buffer) -> Self {
//         let mut buffer = Buffer::new(p.width, p.height);
//         buffer.buffer = p.data;
//         return buffer;
//     }
// }
mod pixel;
pub use pixel::*;

#[cfg(feature = "imagery")]
#[cfg(feature = "std")]
use crate::platform::file_system::file_system_traits::FileSystemTrait;
#[cfg(feature = "std")]
use crate::{prelude::Buffer, settings::MapType};
/// Convert u32 argb to hex
#[inline(always)]
#[must_use]
#[cfg(feature = "std")]
pub fn u32_to_hex_without_alpha(color: u32) -> String {
    let (r, g, b) = u32_to_rgb_u8(color);
    format!("{r:02x}{g:02x}{b:02x}")
}
/// Convert u32 argb to hex
#[inline(always)]
#[must_use]
#[cfg(feature = "std")]
pub fn u32_to_hex(color: u32) -> String {
    let (r, g, b, a) = u32_to_rgba_u8(color);
    format!("{r:02x}{g:02x}{b:02x}{a:02x}")
}

/// Convert hex into u32 argb
///
/// # Errors
/// If the hex is not valid - The function expects for there to not be a # before the hex values
#[inline(always)]
pub fn hex_to_u32(hex: &str) -> Result<u32, core::num::ParseIntError> {
    let alpha = u8::from_str_radix(&hex[0..2], 16)?;
    let red = u8::from_str_radix(&hex[2..4], 16)?;
    let green = u8::from_str_radix(&hex[4..6], 16)?;
    let blue = u8::from_str_radix(&hex[6..8], 16)?;
    Ok(rgba_u8_to_u32(red, green, blue, alpha))
}

/// Convert hex into u32 rgba
///
/// # Errors
/// If the hex is not valid - The function expects for there to not be a # before the hex values
#[inline(always)]
#[cfg(feature = "std")]
pub fn hex_to_u32_rgba(hex: &str) -> Result<u32, core::num::ParseIntError> {
    let red = u8::from_str_radix(&hex[0..2], 16)?;
    let green = u8::from_str_radix(&hex[2..4], 16)?;
    let blue = u8::from_str_radix(&hex[4..6], 16)?;
    let alpha = u8::from_str_radix(&hex[6..8], 16)?;
    Ok(argb_to_rgba(rgba_u8_to_u32(red, green, blue, alpha)))
}

/// Convert hex into u32 rgb
///
/// # Errors
/// If the hex is not valid - The function expects for there to not be a # before the hex values
#[inline(always)]
#[cfg(feature = "std")]
pub fn hex_to_u32_rgb(hex: &str) -> Result<u32, core::num::ParseIntError> {
    let red = u8::from_str_radix(&hex[2..4], 16)?;
    let green = u8::from_str_radix(&hex[4..6], 16)?;
    let blue = u8::from_str_radix(&hex[6..8], 16)?;
    Ok(rgb_u8_to_u32(red, green, blue))
}
#[must_use]
/// Converts rgb into hex
#[inline(always)]
#[cfg(feature = "std")]
pub fn rgb_to_hex(r: u8, g: u8, b: u8) -> String {
    format!("{r:02x}{g:02x}{b:02x}")
}
/// Converts argb to rgba color
#[must_use]
pub const fn argb_to_rgba(color: u32) -> u32 {
    let (a, r, g, b) = u32_to_argb_u8(color);
    rgba_u8_to_u32(a, g, b, r)
}
/// Converts argb to abgr color
#[must_use]
pub const fn switch_red_and_blue(color: u32) -> u32 {
    let (a, r, g, b) = u32_to_argb_u8(color);
    rgba_u8_to_u32(b, g, r, a)
}
/// Converts argb to abgr color
#[must_use]
pub const fn switch_alpha_and_blue(color: u32) -> u32 {
    let (a, r, g, b) = u32_to_argb_u8(color);
    rgba_u8_to_u32(r, g, a, b)
}
#[must_use]
/// Converts a list of argb to rgba and vice versa
#[inline(always)]
#[cfg(feature = "std")]
pub fn switch_alpha_and_blue_list(input: &[u32]) -> Vec<u32> {
    input.iter().map(|&argb| switch_alpha_and_blue(argb)).collect()
}
#[must_use]
/// Converts a list of argb to rgba and vice versa
#[inline(always)]
#[cfg(feature = "std")]
pub fn switch_red_and_blue_list(input: &[u32]) -> Vec<u32> {
    input.iter().map(|&argb| switch_red_and_blue(argb)).collect()
}
#[must_use]
/// Converts a list of argb to rgba and vice versa
#[inline(always)]
#[cfg(feature = "std")]
pub fn argb_list_to_rgba_list(input: &[u32]) -> Vec<u32> {
    input.iter().map(|&argb| argb_to_rgba(argb)).collect()
}
#[must_use]
#[cfg(feature = "std")]
/// Converts a list of rgba to argb and vice versa
pub fn rgba_list_to_argb_list(input: &[u32]) -> Vec<u32> {
    argb_list_to_rgba_list(input)
}

#[cfg(feature = "std")]
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "glfw")]
impl From<Buffer> for glfw::PixelImage {
    fn from(buffer: Buffer) -> Self {
        buffer_to_pixel_image(&buffer)
    }
}

#[cfg(feature = "std")]
#[cfg(feature = "glfw")]
#[cfg(not(target_arch = "wasm32"))]
impl From<glfw::PixelImage> for Buffer {
    fn from(pixel_image: PixelImage) -> Self {
        pixel_image_to_buffer(&pixel_image)
    }
}
#[must_use]
#[inline]
/// Get the next color in line
pub const fn advance_color(red: u8, green: u8, blue: u8) -> (u8, u8, u8) {
    if blue == 255 {
        if green == 255 {
            if red == 255 {
                return (0, 0, 0);
            }
            return (red + 1, green, blue);
        }
        return (red, green + 1, blue);
    }
    (red, green, blue + 1)
}
#[must_use]
#[cfg(feature = "std")]
/// This is quite expensive
pub fn get_unused_color(
    buffer: &[u8],
    current_color: (u8, u8, u8),
) -> (u8, u8, u8) {
    let mut current_color = current_color;
    let mut unique_colors = HashSet::new();
    for i in buffer.chunks_exact(4) {
        if i[0] != 0 {
            unique_colors.insert((i[1], i[2], i[3]));
        }
    }
    while unique_colors.contains(&current_color) {
        current_color =
            advance_color(current_color.0, current_color.1, current_color.2);
    }
    current_color
}
#[must_use]
#[cfg(feature = "std")]
/// A function specifically designed and optimized to work with the buffer of this lib
pub fn get_unused_color_of_buffer(
    buffer: &mut Buffer,
    current_color: (u8, u8, u8),
) -> (u8, u8, u8) {
    let mut current_color = current_color;
    let mut unique_colors = HashSet::new();
    for index in 0..buffer.total_size {
        unsafe {
            let i = u32_to_argb_u8(*buffer.pointer().add(index));
            if i.0 != 0 {
                unique_colors.insert((i.1, i.2, i.3));
            }
        }
    }
    while unique_colors.contains(&current_color) {
        current_color =
            advance_color(current_color.0, current_color.1, current_color.2);
    }
    current_color
}

// #[must_use]
// #[allow(clippy::cast_sign_loss)]
// #[allow(clippy::cast_precision_loss)]
// #[allow(clippy::cast_possible_truncation)]
// #[allow(clippy::cast_possible_wrap)]
// /// Interpolate a u32 rgba based on 4 other u32 rgba
// pub fn bilinear_interpolate_f32(
//     top_left: u32,
//     top_right: u32,
//     bottom_left: u32,
//     bottom_right: u32,
//     progress_x: f32,
//     progress_y: f32,
// ) -> u32 {
//     let (r1, g1, b1, a1) = u32_to_rgba(top_left).into_value();
//     let (r2, g2, b2, a2) = u32_to_rgba(top_right).into_value();
//     let (r3, g3, b3, a3) = u32_to_rgba(bottom_left).into_value();
//     let (r4, g4, b4, a4) = u32_to_rgba(bottom_right).into_value();

//     let interpolate_channel = |c1: f32, c2: f32, c3: f32, c4: f32| -> u8 {
//         let top = core::f32::math::mul_add(c1, 1.0 - progress_x, c2 * progress_x);
//         let bottom =
//             core::f32::math::mul_add(c3, 1.0 - progress_x, c4 * progress_x);
//         let result = core::f32::math::mul_add(
//             top,
//             1.0 - progress_y,
//             bottom * progress_y,
//         );
//         core::f32::math::round(result).clamp(0.0, 255.0) as u8
//     };

//     let red = interpolate_channel(r1, r2, r3, r4);
//     let green = interpolate_channel(g1, g2, g3, g4);
//     let blue = interpolate_channel(b1, b2, b3, b4);
//     let alpha = interpolate_channel(a1, a2, a3, a4);

//     rgba_u8_to_u32(red, green, blue, alpha)
// }

#[must_use]
/// Interpolate between 2 numbers linearly
/// progress should be from 0 to 255
pub const fn interpolate_color_rgb_u32(
    from: u32,
    to: u32,
    progress: u32,
) -> u32 {
    // Convert progress to fixed-point (8.8 format)
    //let progress_fixed = (progress * 256.0) as u32;
    let inv_progress = 256 - progress;

    let r1 = (from >> 24) & 0xFF;
    let g1 = (from >> 16) & 0xFF;
    let b1 = (from >> 8) & 0xFF;
    let r2 = (to >> 24) & 0xFF;
    let g2 = (to >> 16) & 0xFF;
    let b2 = (to >> 8) & 0xFF;

    let r = (r1 * inv_progress + r2 * progress) >> 8;
    let g = (g1 * inv_progress + g2 * progress) >> 8;
    let b = (b1 * inv_progress + b2 * progress) >> 8;

    (r << 24) | (g << 16) | (b << 8) | 0xFF
}
macro_rules! interpolate_color_rgb_u32 {
    ($t:ty, $name:ident) => {
        /// Interpolate between 2 colors linearly based on a scale of 0 to 1
        #[must_use]
        #[allow(clippy::cast_sign_loss)]
        #[allow(clippy::cast_precision_loss)]
        #[allow(clippy::cast_possible_truncation)]
        #[allow(clippy::cast_possible_wrap)]
        pub const fn $name(from: u32, to: u32, progress: $t) -> u32 {
            let (r1, g1, b1) = u32_to_rgb(from);
            let (r2, g2, b2) = u32_to_rgb(to);
            let red = crate::math::interpolate(r1 as $t, r2 as $t, progress);
            let green = crate::math::interpolate(g1 as $t, g2 as $t, progress);
            let blue = crate::math::interpolate(b1 as $t, b2 as $t, progress);
            rgba_to_u32(red as u32, green as u32, blue as u32, 255)
        }
    };
}
interpolate_color_rgb_u32!(f32, interpolate_color_rgb_u32_f32);
interpolate_color_rgb_u32!(f64, interpolate_color_rgb_u32_f64);
interpolate_color_rgb_u32!(f16, interpolate_color_rgb_u32_f16);
interpolate_color_rgb_u32!(f128, interpolate_color_rgb_u32_f128);

/// Inverts the rgb channels of the given color
#[must_use]
pub const fn invert_color(color: u32) -> u32 {
    let (r, g, b, a) = u32_to_rgba_u8(color);
    rgba_u8_to_u32(255 - r, 255 - g, 255 - b, a)
}
// /// Generates a random color (+random alpha)
// ///
// /// # Errors
// /// See [`getrandom::Error`]
// #[inline]
// pub fn generate_random_color() -> Result<u32, getrandom::Error> {
//     getrandom::u32()
// }
// /// Generates a random color (with alpha of 0)
// ///
// /// # Errors
// /// See [`getrandom::Error`]
// #[inline]
// pub fn generate_random_color_stable_alpha(
//     alpha: u32,
// ) -> Result<u32, getrandom::Error> {
//     let color = getrandom::u32()?;
//     Ok(set_alpha(color, alpha))
// }

/// # Features/Flag
/// `imagery` - Grands access to automatic texture lookup -> Define a filepath for a texture and lazy load it
///
/// `texture_manager_cleanup` - Grands accessability to `cleanup_unused`
#[cfg_attr(all(feature = "std", not(feature = "ahash")), derive(Default))]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(feature = "std")]
#[cfg_attr(feature = "c_compatible", repr(C))]
pub struct TextureManager {
    /// The raw images in Buffer form
    pub textures: Vec<Option<Buffer>>,
    /// Map texture indexes to String
    pub lookup: MapType<String, usize>,
    /// A list of empty spaces -> Images cannot be popped when removed as that would move their index
    pub free_list: Vec<usize>,
    #[cfg(feature = "imagery")]
    /// Map textures to files to lazy loading
    pub texture_lookup: MapType<String, String>,
    /// A list of timestamps for when a texture has last been used
    #[cfg(feature = "texture_manager_cleanup")]
    pub last_used: Vec<u64>,
    /// 'Current' frame time for the textures to compare to
    #[cfg(feature = "texture_manager_cleanup")]
    pub current_frame: u64,
}

#[cfg(feature = "std")]
impl TextureManager {
    #[must_use]
    #[allow(clippy::new_without_default)]
    /// Create a texture manager -> Request textures for visual applications
    pub fn new() -> Self {
        use crate::settings::SettingsMapType;

        Self {
            textures: Vec::new(),
            lookup: MapType::new_map(),
            free_list: Vec::new(),
            #[cfg(feature = "imagery")]
            texture_lookup: MapType::new_map(),
            #[cfg(feature = "texture_manager_cleanup")]
            last_used: Vec::new(),
            #[cfg(feature = "texture_manager_cleanup")]
            current_frame: 0,
        }
    }
    /// Registering a texture means being able to lazy load it upon request
    #[cfg(feature = "imagery")]
    pub fn register_texture(&mut self, name: String, file_path: String) {
        self.texture_lookup.insert(name, file_path);
    }
    #[must_use]
    /// Returns None if the requested image cannot be found
    pub fn get_from_idx(&self, index: usize) -> Option<&Buffer> {
        // #[cfg(feature = "texture_manager_cleanup")]
        // if index < self.last_used.len() {
        //     self.last_used[index] = self.current_frame;
        // }
        self.textures.get(index).and_then(|v| v.as_ref())
    }
    #[must_use]
    /// Get the raw image idx from the given name
    pub fn get_idx(&self, name: &String) -> Option<usize> {
        self.lookup.get(name).copied()
    }
    /// Get a texture
    /// Returns None if the requested image cannot be found
    pub fn get(&mut self, name: &str) -> Option<&Buffer> {
        #[cfg(feature = "texture_manager_cleanup")]
        if let Some(&index) = self.lookup.get(name) {
            if index < self.last_used.len() {
                self.last_used[index] = self.current_frame;
            }
            return self.textures[index].as_ref();
        }

        // First check if it's already loaded
        if let Some(&index) = self.lookup.get(name) {
            return self.textures[index].as_ref();
        }

        None
    }
    #[cfg(feature = "imagery")]
    /// Get a texture -> Enable 'imagery' feature for lazy loading
    /// Returns None if the requested image cannot be found
    ///
    /// # Errors
    /// When there was a problem with accessing the file
    pub fn get_or_load<F: FileSystemTrait>(
        &mut self,
        name: &str,
        file_system: &F,
        remove_margins: bool,
    ) -> Result<Option<&Buffer>, Box<dyn std::error::Error>> {
        #[cfg(feature = "texture_manager_cleanup")]
        if let Some(&index) = self.lookup.get(name) {
            if index < self.last_used.len() {
                self.last_used[index] = self.current_frame;
            }
            return self.textures[index].as_ref();
        }

        // First check if it's already loaded
        if let Some(&index) = self.lookup.get(name) {
            return Ok(self.textures[index].as_ref());
        }

        #[cfg(feature = "imagery")]
        // If not loaded, try to load from file
        if let Some(file_path) = self.texture_lookup.get(name) {
            match self.load_texture_from_file(file_path, file_system) {
                Ok(mut buffer) => {
                    if remove_margins {
                        buffer.remove_margins();
                    }
                    self.insert_texture(name.to_string(), buffer);
                    if let Some(&index) = self.lookup.get(name) {
                        return Ok(self.textures[index].as_ref());
                    }
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }

        Ok(None)
    }
    /// Load texture from file to memory
    /// # Errors
    /// When the file was not found
    #[cfg(feature = "imagery")]
    pub fn load_texture_from_file<F: FileSystemTrait>(
        &self,
        file_path: &str,
        file_system: &F,
    ) -> Result<Buffer, Box<dyn core::error::Error>> {
        let file = file_system.get_file_contents(file_path)?;
        let img = file.to_image()?;
        Ok(img.into())
    }
    /// Manually insert a texture with a corresponding name into cache
    pub fn insert_texture(&mut self, name: String, texture: Buffer) -> usize {
        let index = if let Some(free) = self.free_list.pop() {
            self.textures[free] = Some(texture);
            free
        } else {
            self.textures.push(Some(texture));
            self.textures.len() - 1
        };
        self.lookup.insert(name, index);
        index
    }
    /// Unloads/Deletes the specified image from cache if found
    pub fn unload_texture(&mut self, name: &str) {
        if let Some(&index) = self.lookup.get(name) {
            use crate::settings::SettingsMapType;

            self.textures[index] = None;
            self.free_list.push(index);
            self.lookup.remove_thingy(&name.to_string());
        }
    }
    /// Checks if a an image is already registered for lazy loading
    #[cfg(feature = "imagery")]
    #[must_use]
    pub fn is_texture_registered(&self, name: &str) -> bool {
        self.texture_lookup.contains_key(name)
    }
    /// Preload registered image instead of letting it lazy load
    ///
    /// # Errors
    /// When the file cannot be loaded
    #[cfg(feature = "imagery")]
    pub fn preload_texture<F: FileSystemTrait>(
        &mut self,
        name: &str,
        file_system: &F,
    ) -> Result<(), Box<dyn core::error::Error>> {
        if !self.lookup.contains_key(name) {
            if let Some(file_path) = self.texture_lookup.get(name) {
                let buffer =
                    self.load_texture_from_file(file_path, file_system)?;
                self.insert_texture(name.to_string(), buffer);
            }
        }
        Ok(())
    }
    /// Remove textures that haven't been used in X ticks -> Call `tick()` every frame for this to work properly
    /// Set to 0 if you only ever want the images you need in memory
    /// Setting it to at least 1 however is recommended
    #[cfg(feature = "texture_manager_cleanup")]
    #[allow(arithmetic_overflow)]
    pub fn cleanup_unused(&mut self, frames_unused: u64) {
        // This calculation is 100% wrong, future me; Fix it.
        let cutoff = self.current_frame.saturating_sub(frames_unused);

        // Collect names to remove (avoid borrowing issues)
        let to_remove: Vec<String> = self
            .lookup
            .iter()
            .filter(|(_, &index)| {
                index < self.last_used.len() && self.last_used[index] < cutoff
            })
            .map(|(name, _)| name.clone())
            .collect();

        for name in &to_remove {
            self.unload_texture(name);
        }
    }
    #[allow(arithmetic_overflow)]
    #[cfg(feature = "texture_manager_cleanup")]
    /// Tick the texture manager -> Only thing it does is increment a single value, required for `cleanup_unused()`
    pub const fn tick(&mut self) {
        self.current_frame += 1;
    }
}

/// A trait for changing or retrieving a single channel of a color
pub const trait ColorManipulation {
    /// Set the alpha channel
    fn with_alpha(&self, alpha: u32) -> u32;
    /// Set the red channel
    fn with_red(&self, red: u32) -> u32;
    /// Set the green channel
    fn with_green(&self, green: u32) -> u32;
    /// Set the blue channel
    fn with_blue(&self, blue: u32) -> u32;

    /// Get the alpha channel
    fn alpha(&self) -> u32;
    /// Get the red channel
    fn red(&self) -> u32;
    /// Get the green channel
    fn green(&self) -> u32;
    /// Get the blue channel
    fn blue(&self) -> u32;

    /// Add X to the blue channel
    fn add_blue(&self, other: u32) -> u32;
    /// Add X to the red channel
    fn add_red(&self, other: u32) -> u32;
    /// Add X to the green channel
    fn add_green(&self, other: u32) -> u32;
    /// Add X to the alpha channel
    fn add_alpha(&self, other: u32) -> u32;

    /// Subtract X from the blue channel
    fn sub_blue(&self, other: u32) -> u32;
    /// Subtract X from the red channel
    fn sub_red(&self, other: u32) -> u32;
    /// Subtract X from the green channel
    fn sub_green(&self, other: u32) -> u32;
    /// Subtract X from the alpha channel
    fn sub_alpha(&self, other: u32) -> u32;

    /// Add to all color channels - Alpha excluded
    fn add_all_color_channels(&self, other: u32) -> u32;

    /// Sub from all color channels - Alpha excluded
    fn sub_all_color_channels(&self, other: u32) -> u32;
}

impl const ColorManipulation for u32 {
    #[inline(always)]
    fn with_alpha(&self, alpha: u32) -> u32 {
        rgba_to_u32(
            get_red_of_u32(*self),
            get_green_of_u32(*self),
            get_blue_of_u32(*self),
            alpha,
        )
    }

    #[inline(always)]
    fn with_red(&self, red: u32) -> u32 {
        rgba_to_u32(
            red,
            get_green_of_u32(*self),
            get_blue_of_u32(*self),
            get_alpha_of_u32(*self),
        )
    }

    #[inline(always)]
    fn with_green(&self, green: u32) -> u32 {
        rgba_to_u32(
            get_red_of_u32(*self),
            green,
            get_blue_of_u32(*self),
            get_alpha_of_u32(*self),
        )
    }

    #[inline(always)]
    fn with_blue(&self, blue: u32) -> u32 {
        rgba_to_u32(
            get_red_of_u32(*self),
            get_green_of_u32(*self),
            blue,
            get_alpha_of_u32(*self),
        )
    }

    #[inline(always)]
    fn alpha(&self) -> u32 {
        get_alpha_of_u32(*self)
    }

    #[inline(always)]
    fn red(&self) -> u32 {
        get_red_of_u32(*self)
    }

    #[inline(always)]
    fn green(&self) -> u32 {
        get_green_of_u32(*self)
    }

    #[inline(always)]
    fn blue(&self) -> u32 {
        get_blue_of_u32(*self)
    }
    #[inline(always)]
    fn add_alpha(&self, other: u32) -> u32 {
        self.with_alpha(self.alpha() + other)
    }
    #[inline(always)]
    fn add_red(&self, other: u32) -> u32 {
        self.with_red(self.red() + other)
    }
    #[inline(always)]
    fn add_green(&self, other: u32) -> u32 {
        self.with_green(self.green() + other)
    }
    #[inline(always)]
    fn add_blue(&self, other: u32) -> u32 {
        self.with_blue(self.blue() + other)
    }
    #[inline(always)]
    fn sub_alpha(&self, other: u32) -> u32 {
        self.with_alpha(self.alpha() - other)
    }
    #[inline(always)]
    fn sub_red(&self, other: u32) -> u32 {
        self.with_red(self.red() - other)
    }
    #[inline(always)]
    fn sub_green(&self, other: u32) -> u32 {
        self.with_green(self.green() - other)
    }
    #[inline(always)]
    fn sub_blue(&self, other: u32) -> u32 {
        self.with_blue(self.blue() - other)
    }

    fn add_all_color_channels(&self, other: u32) -> u32 {
        self.add_blue(other).add_red(other).add_green(other)
    }
    fn sub_all_color_channels(&self, other: u32) -> u32 {
        self.sub_blue(other).sub_red(other).sub_green(other)
    }
}

#[must_use]
#[cfg(feature = "std")]
/// Convert the image the buffer is holding into a bmp
pub fn create_bmp(image: &Buffer) -> Vec<u8> {
    let mut bmp_buffer: Vec<u8> = Vec::new();

    let width = image.width as u32;
    let height = image.height as u32;

    // BMP File Header (14 bytes)
    bmp_buffer.extend(&[0x42, 0x4D]); // "BM" signature

    let row_stride = (width * 32).div_ceil(32) * 4;
    let pixel_array_size = row_stride * height;
    let bmp_header_size = 40;
    let file_header_size = 14;
    let file_size = file_header_size + bmp_header_size + pixel_array_size;
    let pixel_data_offset = file_header_size + bmp_header_size;

    bmp_buffer.extend(&file_size.to_le_bytes()); // File size
    bmp_buffer.extend(&[0x00, 0x00]); // Reserved
    bmp_buffer.extend(&[0x00, 0x00]); // Reserved
    bmp_buffer.extend(&pixel_data_offset.to_le_bytes()); // Pixel data offset

    // BITMAPINFOHEADER (40 bytes)
    bmp_buffer.extend(&40u32.to_le_bytes()); // Header size
    bmp_buffer.extend(&(width as i32).to_le_bytes()); // Width
    bmp_buffer.extend(&(height as i32).to_le_bytes()); // Height (no x2 for BMP)
    bmp_buffer.extend(&1u16.to_le_bytes()); // Planes
    bmp_buffer.extend(&32u16.to_le_bytes()); // Bit count
    bmp_buffer.extend(&0u32.to_le_bytes()); // Compression
    bmp_buffer.extend(&pixel_array_size.to_le_bytes()); // Image size
    bmp_buffer.extend(&0u32.to_le_bytes()); // X pixels per meter
    bmp_buffer.extend(&0u32.to_le_bytes()); // Y pixels per meter
    bmp_buffer.extend(&0u32.to_le_bytes()); // Colors used
    bmp_buffer.extend(&0u32.to_le_bytes()); // Important colors

    // Pixel data (BGR + Alpha format)
    for pixel in &image.flip_vertically().data {
        let (r, g, b, a) = u32_to_rgba_u8(*pixel);
        #[allow(clippy::tuple_array_conversions)]
        bmp_buffer.extend(&[b, g, r, a]);
    }

    bmp_buffer
}
#[must_use]
#[cfg(feature = "std")]
/// Convert the image the buffer is holding into a .cur
pub fn create_ico(image: &Buffer) -> Vec<u8> {
    let mut ico_buffer: Vec<u8> = Vec::new();

    let width = image.width as u8;
    let height = image.height as u8;

    // ICONDIR (6 bytes)
    ico_buffer.extend(&[0x00, 0x00]); // Reserved
    ico_buffer.extend(&[0x01, 0x00]); // Image type (1 = icon, not 2)
    ico_buffer.extend(&[0x01, 0x00]); // Number of images

    // ICONDIRENTRY (16 bytes)
    ico_buffer.push(width); // Width
    ico_buffer.push(height); // Height
    ico_buffer.push(0); // Color count
    ico_buffer.push(0); // Reserved
    ico_buffer.extend(&[0x00, 0x00]); // Color planes (0 for icons)
    ico_buffer.extend(&[0x20, 0x00]); // Bits per pixel (32)

    let image_data_offset = 6 + 16;
    let row_stride = (u32::from(width) * 32).div_ceil(32) * 4;
    let pixel_array_size = row_stride * u32::from(height);
    let bmp_header_size = 40;
    let and_mask_size = u32::from(height) * (u32::from(width).div_ceil(32) * 4);
    let size_in_bytes = bmp_header_size + pixel_array_size + and_mask_size;

    ico_buffer.extend(&size_in_bytes.to_le_bytes()); // Image size
    ico_buffer.extend(&(image_data_offset as u32).to_le_bytes()); // Image offset

    // BITMAPINFOHEADER (40 bytes)
    let mut bmp_data: Vec<u8> = Vec::with_capacity(size_in_bytes as usize);
    bmp_data.extend(&40u32.to_le_bytes()); // Header size
    bmp_data.extend(&i32::from(width).to_le_bytes()); // Width
    bmp_data.extend(&(2 * i32::from(height)).to_le_bytes()); // Height (x2 for AND mask)
    bmp_data.extend(&1u16.to_le_bytes()); // Planes
    bmp_data.extend(&32u16.to_le_bytes()); // Bit count
    bmp_data.extend(&0u32.to_le_bytes()); // Compression
    bmp_data.extend(&0u32.to_le_bytes()); // Image size
    bmp_data.extend(&0u32.to_le_bytes()); // X pixels per meter
    bmp_data.extend(&0u32.to_le_bytes()); // Y pixels per meter
    bmp_data.extend(&0u32.to_le_bytes()); // Colors used
    bmp_data.extend(&0u32.to_le_bytes()); // Important colors

    // Pixel data
    for pixel in &image.flip_vertically().data {
        let (r, g, b, a) = u32_to_rgba_u8(*pixel);
        #[allow(clippy::tuple_array_conversions)]
        bmp_data.extend(&[b, g, r, a]);
    }

    // AND mask (all zero = fully visible)
    bmp_data.extend(vec![0u8; and_mask_size as usize]);

    // Combine all into buffer
    ico_buffer.extend(bmp_data);

    ico_buffer
}

/// Reorder color from ((r1, r2), (g1, g2), (b1, b2)) to ((r1, g1, b1), (r2, g2, b2))
#[must_use]
pub const fn reorder_color_range(
    color_range: ((u32, u32), (u32, u32), (u32, u32)),
) -> ((u32, u32, u32), (u32, u32, u32)) {
    (
        (color_range.0 .0, color_range.1 .0, color_range.2 .0),
        (color_range.0 .1, color_range.1 .1, color_range.2 .1),
    )
}