forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
color.d
2242 lines (1861 loc) · 57.8 KB
/
color.d
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
/++
Base module for working with colors and in-memory image pixmaps.
Also has various basic data type definitions that are generally
useful with images like [Point], [Size], and [Rectangle].
+/
module arsd.color;
import arsd.core;
@safe:
// importing phobos explodes the size of this code 10x, so not doing it.
private {
double toInternal(T)(scope const(char)[] s) {
double accumulator = 0.0;
size_t i = s.length;
foreach(idx, c; s) {
if(c >= '0' && c <= '9') {
accumulator *= 10;
accumulator += c - '0';
} else if(c == '.') {
i = idx + 1;
break;
} else {
string wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute = "bad char to make double from ";
wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute ~= s;
throw new Exception(wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute);
}
}
double accumulator2 = 0.0;
double count = 1;
foreach(c; s[i .. $]) {
if(c >= '0' && c <= '9') {
accumulator2 *= 10;
accumulator2 += c - '0';
count *= 10;
} else {
string wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute = "bad char to make double from ";
wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute ~= s;
throw new Exception(wtfIsWrongWithThisStupidLanguageWithItsBrokenSafeAttribute);
}
}
return accumulator + accumulator2 / count;
}
package(arsd) @trusted
string toInternal(T)(long a) {
if(a == 0)
return "0";
char[] ret;
bool neg;
if(a < 0) {
neg = true;
a = -a;
}
while(a) {
ret ~= (a % 10) + '0';
a /= 10;
}
for(int i = 0; i < ret.length / 2; i++) {
char c = ret[i];
ret[i] = ret[$ - i - 1];
ret[$ - i - 1] = c;
}
if(neg)
ret = "-" ~ ret;
return cast(string) ret;
}
string toInternal(T)(double a) {
// a simplifying assumption here is the fact that we only use this in one place: toInternal!string(cast(double) a / 255)
// thus we know this will always be between 0.0 and 1.0, inclusive.
if(a <= 0.0)
return "0.0";
if(a >= 1.0)
return "1.0";
string ret = "0.";
// I wonder if I can handle round off error any better. Phobos does, but that isn't worth 100 KB of code.
int amt = cast(int)(a * 1000);
return ret ~ toInternal!string(amt);
}
nothrow @safe @nogc pure
double absInternal(double a) { return a < 0 ? -a : a; }
nothrow @safe @nogc pure
double minInternal(double a, double b, double c) {
auto m = a;
if(b < m) m = b;
if(c < m) m = c;
return m;
}
nothrow @safe @nogc pure
double maxInternal(double a, double b, double c) {
auto m = a;
if(b > m) m = b;
if(c > m) m = c;
return m;
}
nothrow @safe @nogc pure
bool startsWithInternal(in char[] a, in char[] b) {
return (a.length >= b.length && a[0 .. b.length] == b);
}
void splitInternal(scope inout(char)[] a, char c, scope void delegate(int, scope inout(char)[]) @safe dg) {
int count;
size_t previous = 0;
foreach(i, char ch; a) {
if(ch == c) {
dg(count++, a[previous .. i]);
previous = i + 1;
}
}
if(previous != a.length)
dg(count++, a[previous .. $]);
}
}
// done with mini-phobos
/// Represents an RGBA color
struct Color {
@system static Color fromJsVar(T)(T v) { // it is a template so i don't have to actually import arsd.jsvar...
return Color.fromString(v.get!string);
}
@safe:
ubyte[4] components; /// [r, g, b, a]
// The color components are available as individual bytes and a uint through this property functions.
// Unlike an anonymous union, this works with CTFE as well.
@safe pure nothrow @nogc {
// individual rgb components
pragma(inline, true) ref inout(ubyte) r() inout scope return { return components[0]; } /// red
pragma(inline, true) ref inout(ubyte) g() inout scope return { return components[1]; } /// green
pragma(inline, true) ref inout(ubyte) b() inout scope return { return components[2]; } /// blue
pragma(inline, true) ref inout(ubyte) a() inout scope return { return components[3]; } /// alpha. 255 == opaque
/*
pragma(inline, true) void r(ubyte value) { components[0] = value; } /// red
pragma(inline, true) void g(ubyte value) { components[1] = value; } /// green
pragma(inline, true) void b(ubyte value) { components[2] = value; } /// blue
pragma(inline, true) void a(ubyte value) { components[3] = value; } /// alpha. 255 == opaque
*/
/// The components as a single 32 bit value (beware of endian issues!)
uint asUint() inout {
if (__ctfe) {
version (LittleEndian)
return (r) | (g << 8) | (b << 16) | (a << 24);
else version (BigEndian)
return (r << 24) | (g << 16) | (b << 8) | (a);
else
static assert(false, "Unsupported endianness");
} else {
return (cast(inout(uint)[1]) components)[0];
}
}
/// ditto
void asUint(uint value) {
if (__ctfe) {
version (LittleEndian) {
r = (value & 0xFF);
g = ((value & 0xFF_00) >> 8);
b = ((value & 0xFF_00_00) >> 16);
a = ((value & 0xFF_00_00_00) >> 24);
} else version (BigEndian) {
r = ((value & 0xFF_00_00_00) >> 24);
g = ((value & 0xFF_00_00) >> 16);
b = ((value & 0xFF_00) >> 8);
a = (value & 0xFF);
} else {
static assert(false, "Unsupported endianness");
}
} else {
components = function(uint value) @trusted {
return *(cast(ubyte[4]*) cast(void*) &value);
}(value);
}
}
/// ditto
uint opCast(T : uint)() inout { return this.asUint; }
}
/++
Returns a value compatible with [https://docs.microsoft.com/en-us/windows/win32/gdi/colorref|a Win32 COLORREF].
Please note that the alpha value is lost in translation.
History:
Added November 27, 2021 (dub v10.4)
See_Also:
[fromWindowsColorRef]
+/
nothrow pure @nogc
uint asWindowsColorRef() {
uint cr;
cr |= b << 16;
cr |= g << 8;
cr |= r;
return cr;
}
/++
Constructs a Color from [https://docs.microsoft.com/en-us/windows/win32/gdi/colorref|a Win32 COLORREF].
History:
Added November 27, 2021 (dub v10.4)
See_Also:
[asWindowsColorRef]
+/
nothrow pure @nogc
static Color fromWindowsColorRef(uint cr) {
return Color(cr & 0xff, (cr >> 8) & 0xff, (cr >> 16) & 0xff);
}
/++
Like the constructor, but this makes sure they are in range before casting. If they are out of range, it saturates: anything less than zero becomes zero and anything greater than 255 becomes 255.
+/
nothrow pure @nogc
static Color fromIntegers(int red, int green, int blue, int alpha = 255) {
return Color(clampToByte(red), clampToByte(green), clampToByte(blue), clampToByte(alpha));
}
/// Construct a color with the given values. They should be in range 0 <= x <= 255, where 255 is maximum intensity and 0 is minimum intensity.
nothrow pure @nogc
this(int red, int green, int blue, int alpha = 255) {
this.r = cast(ubyte) red;
this.g = cast(ubyte) green;
this.b = cast(ubyte) blue;
this.a = cast(ubyte) alpha;
}
/++
Construct a color from components[0 .. 4]. It must have length of at least 4 and be in r, g, b, a order.
History:
Added July 18, 2022 (dub v10.9)
+/
nothrow pure @nogc
this(scope ubyte[] components) {
this.components[] = components[0 .. 4];
}
/++
Constructs a color from floating-point rgba components, each between 0 and 1.0.
History:
Added December 1, 2022 (dub v10.10)
+/
this(float r, float g, float b, float a = 1.0) {
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
if(r > 1) r = 1;
if(g > 1) g = 1;
if(b > 1) b = 1;
/*
assert(r >= 0.0 && r <= 1.0, to!string(r));
assert(g >= 0.0 && g <= 1.0, to!string(g));
assert(b >= 0.0 && b <= 1.0, to!string(b));
assert(a >= 0.0 && a <= 1.0, to!string(a));
*/
this.r = cast(ubyte) (r * 255);
this.g = cast(ubyte) (g * 255);
this.b = cast(ubyte) (b * 255);
this.a = cast(ubyte) (a * 255);
}
/++
Constructs a color from a [ColorF] (floating-point)
History:
Added December 20, 2023
+/
nothrow pure @nogc
this(const ColorF colorF) {
this.r = cast(ubyte) (colorF.r * 255);
this.g = cast(ubyte) (colorF.g * 255);
this.b = cast(ubyte) (colorF.b * 255);
this.a = cast(ubyte) (colorF.a * 255);
}
/// Static convenience functions for common color names
nothrow pure @nogc
static Color transparent() { return Color(0, 0, 0, 0); }
/// Ditto
nothrow pure @nogc
static Color white() { return Color(255, 255, 255); }
/// Ditto
nothrow pure @nogc
static Color gray() { return Color(128, 128, 128); }
/// Ditto
nothrow pure @nogc
static Color black() { return Color(0, 0, 0); }
/// Ditto
nothrow pure @nogc
static Color red() { return Color(255, 0, 0); }
/// Ditto
nothrow pure @nogc
static Color green() { return Color(0, 255, 0); }
/// Ditto
nothrow pure @nogc
static Color blue() { return Color(0, 0, 255); }
/// Ditto
nothrow pure @nogc
static Color yellow() { return Color(255, 255, 0); }
/// Ditto
nothrow pure @nogc
static Color teal() { return Color(0, 255, 255); }
/// Ditto
nothrow pure @nogc
static Color purple() { return Color(128, 0, 128); }
/// Ditto
nothrow pure @nogc
static Color magenta() { return Color(255, 0, 255); }
/// Ditto
nothrow pure @nogc
static Color brown() { return Color(128, 64, 0); }
nothrow pure @nogc
void premultiply() {
r = (r * a) / 255;
g = (g * a) / 255;
b = (b * a) / 255;
}
nothrow pure @nogc
void unPremultiply() {
r = cast(ubyte)(r * 255 / a);
g = cast(ubyte)(g * 255 / a);
b = cast(ubyte)(b * 255 / a);
}
/*
ubyte[4] toRgbaArray() {
return [r,g,b,a];
}
*/
/// Return black-and-white color
Color toBW() () nothrow pure @safe @nogc {
// FIXME: gamma?
int intens = clampToByte(cast(int)(0.2126*r+0.7152*g+0.0722*b));
return Color(intens, intens, intens, a);
}
/// Makes a string that matches CSS syntax for websites
string toCssString() const {
if(a == 255)
return "#" ~ toHexInternal(r) ~ toHexInternal(g) ~ toHexInternal(b);
else {
return "rgba("~toInternal!string(r)~", "~toInternal!string(g)~", "~toInternal!string(b)~", "~toInternal!string(cast(double)a / 255.0)~")";
}
}
/// Makes a hex string RRGGBBAA (aa only present if it is not 255)
string toString() const {
if(a == 255)
return toCssString()[1 .. $];
else
return toRgbaHexString();
}
/// returns RRGGBBAA, even if a== 255
string toRgbaHexString() const {
return toHexInternal(r) ~ toHexInternal(g) ~ toHexInternal(b) ~ toHexInternal(a);
}
/// Gets a color by name, iff the name is one of the static members listed above
static Color fromNameString(string s) {
Color c;
foreach(member; __traits(allMembers, Color)) {
static if(__traits(compiles, c = __traits(getMember, Color, member))) {
if(s == member)
return __traits(getMember, Color, member);
}
}
throw new Exception("Unknown color " ~ s);
}
/++
Reads a CSS style string to get the color. Understands #rrggbb, rgba(), hsl(), and rrggbbaa
History:
The short-form hex string parsing (`#fff`) was added on April 10, 2020. (v7.2.0)
+/
static Color fromString(scope const(char)[] s) {
s = s.stripInternal();
Color c;
c.a = 255;
// trying named colors via the static no-arg methods here
foreach(member; __traits(allMembers, Color)) {
static if(__traits(compiles, c = __traits(getMember, Color, member))) {
if(s == member)
return __traits(getMember, Color, member);
}
}
// try various notations borrowed from CSS (though a little extended)
// hsl(h,s,l,a) where h is degrees and s,l,a are 0 >= x <= 1.0
if(s.startsWithInternal("hsl(") || s.startsWithInternal("hsla(")) {
assert(s[$-1] == ')');
s = s[s.startsWithInternal("hsl(") ? 4 : 5 .. $ - 1]; // the closing paren
double[3] hsl;
ubyte a = 255;
s.splitInternal(',', (int i, scope const(char)[] part) {
if(i < 3)
hsl[i] = toInternal!double(part.stripInternal);
else
a = clampToByte(cast(int) (toInternal!double(part.stripInternal) * 255));
});
c = .fromHsl(hsl);
c.a = a;
return c;
}
// rgb(r,g,b,a) where r,g,b are 0-255 and a is 0-1.0
if(s.startsWithInternal("rgb(") || s.startsWithInternal("rgba(")) {
assert(s[$-1] == ')');
s = s[s.startsWithInternal("rgb(") ? 4 : 5 .. $ - 1]; // the closing paren
s.splitInternal(',', (int i, scope const(char)[] part) {
// lol the loop-switch pattern
auto v = toInternal!double(part.stripInternal);
switch(i) {
case 0: // red
c.r = clampToByte(cast(int) v);
break;
case 1:
c.g = clampToByte(cast(int) v);
break;
case 2:
c.b = clampToByte(cast(int) v);
break;
case 3:
c.a = clampToByte(cast(int) (v * 255));
break;
default: // ignore
}
});
return c;
}
// otherwise let's try it as a hex string, really loosely
if(s.length && s[0] == '#')
s = s[1 .. $];
// support short form #fff for example
if(s.length == 3 || s.length == 4) {
string n;
n.reserve(8);
foreach(ch; s) {
n ~= ch;
n ~= ch;
}
s = n;
}
// not a built in... do it as a hex string
if(s.length >= 2) {
c.r = fromHexInternal(s[0 .. 2]);
s = s[2 .. $];
}
if(s.length >= 2) {
c.g = fromHexInternal(s[0 .. 2]);
s = s[2 .. $];
}
if(s.length >= 2) {
c.b = fromHexInternal(s[0 .. 2]);
s = s[2 .. $];
}
if(s.length >= 2) {
c.a = fromHexInternal(s[0 .. 2]);
s = s[2 .. $];
}
return c;
}
/// from hsl
static Color fromHsl(double h, double s, double l) {
return .fromHsl(h, s, l);
}
// this is actually branch-less for ints on x86, and even for longs on x86_64
static ubyte clampToByte(T) (T n) pure nothrow @safe @nogc if (__traits(isIntegral, T)) {
static if (__VERSION__ > 2067) pragma(inline, true);
static if (T.sizeof == 2 || T.sizeof == 4) {
static if (__traits(isUnsigned, T)) {
return cast(ubyte)(n&0xff|(255-((-cast(int)(n < 256))>>24)));
} else {
n &= -cast(int)(n >= 0);
return cast(ubyte)(n|((255-cast(int)n)>>31));
}
} else static if (T.sizeof == 1) {
static assert(__traits(isUnsigned, T), "clampToByte: signed byte? no, really?");
return cast(ubyte)n;
} else static if (T.sizeof == 8) {
static if (__traits(isUnsigned, T)) {
return cast(ubyte)(n&0xff|(255-((-cast(long)(n < 256))>>56)));
} else {
n &= -cast(long)(n >= 0);
return cast(ubyte)(n|((255-cast(long)n)>>63));
}
} else {
static assert(false, "clampToByte: integer too big");
}
}
/** this mixin can be used to alphablend two `uint` colors;
* `colu32name` is variable that holds color to blend,
* `destu32name` is variable that holds "current" color (from surface, for example).
* alpha value of `destu32name` doesn't matter.
* alpha value of `colu32name` means: 255 for replace color, 0 for keep `destu32name`.
*
* WARNING! This function does blending in RGB space, and RGB space is not linear!
*/
public enum ColorBlendMixinStr(string colu32name, string destu32name) = "{
immutable uint a_tmp_ = (256-(255-(("~colu32name~")>>24)))&(-(1-(((255-(("~colu32name~")>>24))+1)>>8))); // to not lose bits, but 255 should become 0
immutable uint dc_tmp_ = ("~destu32name~")&0xffffff;
immutable uint srb_tmp_ = (("~colu32name~")&0xff00ff);
immutable uint sg_tmp_ = (("~colu32name~")&0x00ff00);
immutable uint drb_tmp_ = (dc_tmp_&0xff00ff);
immutable uint dg_tmp_ = (dc_tmp_&0x00ff00);
immutable uint orb_tmp_ = (drb_tmp_+(((srb_tmp_-drb_tmp_)*a_tmp_+0x800080)>>8))&0xff00ff;
immutable uint og_tmp_ = (dg_tmp_+(((sg_tmp_-dg_tmp_)*a_tmp_+0x008000)>>8))&0x00ff00;
("~destu32name~") = (orb_tmp_|og_tmp_)|0xff000000; /*&0xffffff;*/
}";
/// Perform alpha-blending of `fore` to this color, return new color.
/// WARNING! This function does blending in RGB space, and RGB space is not linear!
Color alphaBlend (Color fore) const pure nothrow @trusted @nogc {
version(LittleEndian) {
static if (__VERSION__ > 2067) pragma(inline, true);
Color res;
res.asUint = asUint;
mixin(ColorBlendMixinStr!("fore.asUint", "res.asUint"));
return res;
} else {
alias foreground = fore;
alias background = this;
foreach(idx, ref part; foreground.components)
part = cast(ubyte) (part * foreground.a / 255 + background.components[idx] * (255 - foreground.a) / 255);
return foreground;
}
}
}
/++
Represents an RGBA color in floating-point (from 0 to 1.0).
$(NOTE
Most of the time, you’ll probably want to use [Color] instead.
This primarily exists to provide a tested out-of-the-box solution
when utilizing APIs that work with FP colors.
Constructors and setters come with $(B `in`-contracts)
to assert one won’t run into out-of-range color values.
)
History:
Added December 20, 2023
+/
struct ColorF {
private float[4] _components;
@safe pure nothrow @nogc:
///
public this(const float[4] components)
in(isValidComponent(components[0]))
in(isValidComponent(components[1]))
in(isValidComponent(components[2]))
in(isValidComponent(components[3])) {
_components = components;
}
/// ditto
public this(float r, float g, float b, float a = 1.0f)
in(isValidComponent(r))
in(isValidComponent(g))
in(isValidComponent(b))
in(isValidComponent(a)) {
_components = [r, g, b, a];
}
/++
Constructs a FP color from an integer one
+/
public this(const Color integer) {
_components[] = integer.components[] / 255.0f;
}
///
float[4] components() inout { return _components; }
// component getters
float r() inout { return _components[0]; } /// red
float g() inout { return _components[1]; } /// green
float b() inout { return _components[2]; } /// blue
float a() inout { return _components[3]; } /// alpha
// component setters
void r(float v) in(isValidComponent(v)) { _components[0] = v; } /// red
void g(float v) in(isValidComponent(v)) { _components[1] = v; } /// green
void b(float v) in(isValidComponent(v)) { _components[2] = v; } /// blue
void a(float v) in(isValidComponent(v)) { _components[3] = v; } /// alpha
///
static bool isValidComponent(const float v) {
return (v >= 0.0f && v <= 1.0f);
}
}
/++
OKLab colorspace conversions to/from [Color]. See: [https://bottosson.github.io/posts/oklab/]
L = perceived lightness. From 0 to 1.0.
a = how green/red the color is. Apparently supposed to be from -.233887 to .276216
b = how blue/yellow the color is. Apparently supposed to be from -.311528 to 0.198570.
History:
Added December 1, 2022 (dub v10.10)
Bugs:
Seems to be some but i might just not understand what the result is supposed to be.
+/
struct Lab {
float L = 0.0;
float a = 0.0;
float b = 0.0;
float alpha = 1.0;
float C() const {
import core.stdc.math;
return sqrtf(a * a + b * b);
}
float h() const {
import core.stdc.math;
return atan2f(b, a);
}
/++
L's useful range is between 0 and 1.0
C's useful range is between 0 and 0.4
H can be 0 to 360 for degrees, or 0 to 2pi for radians.
+/
static Lab fromLChDegrees(float L, float C, float h, float alpha = 1.0) {
return fromLChRadians(L, C, h * 3.14159265358979323f / 180.0f, alpha);
}
/// ditto
static Lab fromLChRadians(float L, float C, float h, float alpha = 1.0) {
import core.stdc.math;
// if(C > 0.4) C = 0.4;
return Lab(L, C * cosf(h), C * sinf(h), alpha);
}
}
/// ditto
Lab toOklab(Color c) {
import core.stdc.math;
// this algorithm requires linear sRGB
float f(float w) {
w = srbgToLinear(w);
if(w < 0)
w = 0;
if(w > 1)
w = 1;
return w;
}
float r = f(cast(float) c.r / 255);
float g = f(cast(float) c.g / 255);
float b = f(cast(float) c.b / 255);
float l = 0.4122214708f * r + 0.5363325363f * g + 0.0514459929f * b;
float m = 0.2119034982f * r + 0.6806995451f * g + 0.1073969566f * b;
float s = 0.0883024619f * r + 0.2817188376f * g + 0.6299787005f * b;
float l_ = cbrtf(l);
float m_ = cbrtf(m);
float s_ = cbrtf(s);
return Lab(
0.2104542553f*l_ + 0.7936177850f*m_ - 0.0040720468f*s_,
1.9779984951f*l_ - 2.4285922050f*m_ + 0.4505937099f*s_,
0.0259040371f*l_ + 0.7827717662f*m_ - 0.8086757660f*s_,
cast(float) c.a / 255
);
}
/// ditto
Color fromOklab(Lab c) {
float l_ = c.L + 0.3963377774f * c.a + 0.2158037573f * c.b;
float m_ = c.L - 0.1055613458f * c.a - 0.0638541728f * c.b;
float s_ = c.L - 0.0894841775f * c.a - 1.2914855480f * c.b;
float l = l_*l_*l_;
float m = m_*m_*m_;
float s = s_*s_*s_;
float f(float w) {
w = linearToSrbg(w);
if(w < 0)
w = 0;
if(w > 1)
w = 1;
return w;
}
return Color(
f(+4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s),
f(-1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s),
f(-0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s),
c.alpha
);
}
// from https://bottosson.github.io/posts/colorwrong/#what-can-we-do%3F
float linearToSrbg(float x) { // aka f
import core.stdc.math;
if (x >= 0.0031308)
return (1.055) * powf(x, (1.0/2.4)) - 0.055;
else
return 12.92 * x;
}
float srbgToLinear(float x) { // aka f_inv
import core.stdc.math;
if (x >= 0.04045)
return powf((x + 0.055)/(1 + 0.055), 2.4);
else
return x / 12.92;
}
/+
float[3] colorToYCbCr(Color c) {
return matrixMultiply(
[
+0.2126, +0.7152, +0.0722,
-0.1146, -0.3854, +0.5000,
+0.5000, -0.4542, -0.0458
],
[float(c.r) / 255, float(c.g) / 255, float(c.b) / 255]
);
}
Color YCbCrToColor(float Y, float Cb, float Cr) {
/*
Y = Y * 255;
Cb = Cb * 255;
Cr = Cr * 255;
int r = cast(int) (Y + 1.40200 * (Cr - 0x80));
int g = cast(int) (Y - 0.34414 * (Cb - 0x80) - 0.71414 * (Cr - 0x80));
int b = cast(int) (Y + 1.77200 * (Cb - 0x80));
void clamp(ref int item, int min, int max) {
if(item < min) item = min;
if(item > max) item = max;
}
clamp(r, 0, 255);
clamp(g, 0, 255);
clamp(b, 0, 255);
return Color(r, g, b);
*/
float f(float w) {
if(w < 0 || w > 1)
return 0;
assert(w >= 0.0);
assert(w <= 1.0);
//w = linearToSrbg(w);
if(w < 0)
w = 0;
if(w > 1)
w = 1;
return w;
}
auto rgb = matrixMultiply(
[
1, +0.0000, +1.5748,
1, -0.1873, -0.4681,
1, +1.8556, +0.0000
],
[Y, Cb, Cr]
);
return Color(f(rgb[0]), f(rgb[1]), f(rgb[2]));
}
private float[3] matrixMultiply(float[9] matrix, float[3] vector) {
return [
matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2],
matrix[3] * vector[0] + matrix[4] * vector[1] + matrix[5] * vector[2],
matrix[6] * vector[0] + matrix[7] * vector[1] + matrix[8] * vector[2],
];
}
+/
void premultiplyBgra(ubyte[] bgra) pure @nogc @safe nothrow in { assert(bgra.length == 4); } do {
auto a = bgra[3];
bgra[2] = (bgra[2] * a) / 255;
bgra[1] = (bgra[1] * a) / 255;
bgra[0] = (bgra[0] * a) / 255;
}
void unPremultiplyRgba(ubyte[] rgba) pure @nogc @safe nothrow in { assert(rgba.length == 4); } do {
auto a = rgba[3];
if(a == 0)
return;
rgba[0] = cast(ubyte)(rgba[0] * 255 / a);
rgba[1] = cast(ubyte)(rgba[1] * 255 / a);
rgba[2] = cast(ubyte)(rgba[2] * 255 / a);
}
unittest {
Color c = Color.fromString("#fff");
assert(c == Color.white);
assert(c == Color.fromString("#ffffff"));
c = Color.fromString("#f0f");
assert(c == Color.fromString("rgb(255, 0, 255)"));
}
nothrow @safe
private string toHexInternal(ubyte b) {
string s;
if(b < 16)
s ~= '0';
else {
ubyte t = (b & 0xf0) >> 4;
if(t >= 10)
s ~= 'A' + t - 10;
else
s ~= '0' + t;
b &= 0x0f;
}
if(b >= 10)
s ~= 'A' + b - 10;
else
s ~= '0' + b;
return s;
}
nothrow @safe @nogc pure
private ubyte fromHexInternal(in char[] s) {
int result = 0;
int exp = 1;
//foreach(c; retro(s)) { // FIXME: retro doesn't work right in dtojs
foreach_reverse(c; s) {
if(c >= 'A' && c <= 'F')
result += exp * (c - 'A' + 10);
else if(c >= 'a' && c <= 'f')
result += exp * (c - 'a' + 10);
else if(c >= '0' && c <= '9')
result += exp * (c - '0');
else
// throw new Exception("invalid hex character: " ~ cast(char) c);
return 0;
exp *= 16;
}
return cast(ubyte) result;
}
/// Converts hsl to rgb
Color fromHsl(real[3] hsl) nothrow pure @safe @nogc {
return fromHsl(cast(double) hsl[0], cast(double) hsl[1], cast(double) hsl[2]);
}
Color fromHsl(double[3] hsl) nothrow pure @safe @nogc {
return fromHsl(hsl[0], hsl[1], hsl[2]);
}
/// Converts hsl to rgb
Color fromHsl(double h, double s, double l, double a = 255) nothrow pure @safe @nogc {
h = h % 360;
double C = (1 - absInternal(2 * l - 1)) * s;
double hPrime = h / 60;
double X = C * (1 - absInternal(hPrime % 2 - 1));
double r, g, b;
if(h is double.nan)
r = g = b = 0;
else if (hPrime >= 0 && hPrime < 1) {
r = C;
g = X;
b = 0;
} else if (hPrime >= 1 && hPrime < 2) {
r = X;
g = C;
b = 0;
} else if (hPrime >= 2 && hPrime < 3) {
r = 0;
g = C;
b = X;
} else if (hPrime >= 3 && hPrime < 4) {
r = 0;
g = X;
b = C;
} else if (hPrime >= 4 && hPrime < 5) {
r = X;
g = 0;
b = C;
} else if (hPrime >= 5 && hPrime < 6) {
r = C;
g = 0;
b = X;
}
double m = l - C / 2;
r += m;
g += m;
b += m;
return Color(
cast(int)(r * 255),
cast(int)(g * 255),
cast(int)(b * 255),
cast(int)(a));
}
/// Assumes the input `u` is already between 0 and 1 fyi.
nothrow pure @safe @nogc
double srgbToLinearRgb(double u) {
if(u < 0.4045)
return u / 12.92;
else
return pow((u + 0.055) / 1.055, 2.4);
// return ((u + 0.055) / 1.055) ^^ 2.4;
}
// could use the ^^ operator but that drags in some phobos. In this case, the import is
// actually insignificant, it doesn't really impact compile time, but it does complicate
// the dmd -v | grep std check to confirm i didn't miss any.
private extern(C) nothrow pure @safe @nogc double pow(double, double);
/// Converts an RGB color into an HSL triplet. useWeightedLightness will try to get a better value for luminosity for the human eye, which is more sensitive to green than red and more to red than blue. If it is false, it just does average of the rgb.
double[3] toHsl(Color c, bool useWeightedLightness = false) nothrow pure @trusted @nogc {
double r1 = cast(double) c.r / 255;
double g1 = cast(double) c.g / 255;
double b1 = cast(double) c.b / 255;
double maxColor = maxInternal(r1, g1, b1);
double minColor = minInternal(r1, g1, b1);
double L = (maxColor + minColor) / 2 ;
if(useWeightedLightness) {
// the colors don't affect the eye equally
// this is a little more accurate than plain HSL numbers
L = 0.2126*srgbToLinearRgb(r1) + 0.7152*srgbToLinearRgb(g1) + 0.0722*srgbToLinearRgb(b1);
// maybe a better number is 299, 587, 114
}
double S = 0;