File: bgracolorquantization.pas

package info (click to toggle)
lazpaint 7.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 56,000 kB
  • sloc: pascal: 277,538; python: 2,494; makefile: 233; sh: 221
file content (2051 lines) | stat: -rw-r--r-- 65,567 bytes parent folder | download
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
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
// SPDX-License-Identifier: LGPL-3.0-linking-exception

{ Color quantization i.e. the reduction to a palette using dithering or not,
  provided by TBGRAColorQuantizer class. }
unit BGRAColorQuantization;

{$mode objfpc}{$H+}

interface

uses
  BGRAClasses, SysUtils, BGRAPalette, BGRABitmapTypes;

type
  TBGRAColorBox = class;
  TBGRAColorTree = class;
  TBGRAApproxPalette = class;
  TBiggestLeafMethod = (blMix, blApparentInterval, blWeight);

  { Range according to one dimension of a color }
  TDimensionMinMax = object
    Minimum: UInt32;
    Maximum: UInt32;
    function Size: UInt32;
    function Contains(AValue: UInt32): boolean;
    function PointLike: boolean;
    procedure SetAsPoint(AValue: UInt32);
    function GetCenter: UInt32;
    procedure GrowToInclude(AValue: UInt32);
  end;

  TColorDimension = (cdFast,cdRed,cdGreen,cdBlue,cdAlpha,cdRGB,cdRG,cdGB,cdRB,cdRInvG,cdGInvB,cdRInvB,cdRInvGB,cdGInvRB,cdBInvRG,
                     cdSaturation);
  TColorDimensions = set of TColorDimension;

  { @abstract(Implementation of color quantization.)

Example saving an image into 8-bit PNG file:
```pascal
uses BGRAColorQuantization, BGRABitmapTypes, BGRABitmap;
var
  quant : TBGRAColorQuantizer;
  sourceBmp: TBGRABitmap;
begin
  sourceBmp := TBGRABitmap.Create('picture_in_32_bits.bmp');
  quant := TBGRAColorQuantizer.Create(sourceBmp, acFullChannelInPalette);
  // by default, reduces to 256 colors
  quant.SaveBitmapToFile(daFloydSteinberg, sourceBmp, 'picture_in_8_bits.png');
  quant.Free;
  sourceBmp.Free;
end;
```
  }
  TBGRAColorQuantizer = class(TBGRACustomColorQuantizer)
  private
    FColors: ArrayOfWeightedColor;
    FPalette: TBGRAApproxPalette;
    FReductionColorCount: Integer;
    FReductionKeepContrast: boolean;
    FSeparateAlphaChannel: boolean;
    procedure Init(ABox: TBGRAColorBox);
    procedure NormalizeArrayOfColors(AColors: ArrayOfTBGRAPixel; ARedBounds, AGreenBounds, ABlueBounds, AAlphaBounds: TDimensionMinMax; AUniform: boolean); overload;
    procedure NormalizeArrayOfColors(AColors: ArrayOfTBGRAPixel; AColorBounds, AAlphaBounds: TDimensionMinMax); overload;
  protected
    function GetPalette: TBGRACustomApproxPalette; override;
    function GetSourceColor(AIndex: integer): TBGRAPixel; override;
    function GetSourceColorCount: Integer; override;
    function GetReductionColorCount: integer; override;
    procedure SetReductionColorCount(AValue: Integer); override;
  public
    constructor Create(APalette: TBGRACustomPalette; ASeparateAlphaChannel: boolean); override;
    constructor Create(ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption); override;
    constructor Create(APalette: TBGRACustomPalette; ASeparateAlphaChannel: boolean; AReductionColorCount: integer); override;
    constructor Create(ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption; AReductionColorCount: integer); override;
    destructor Destroy; override;
    procedure ApplyDitheringInplace(AAlgorithm: TDitheringAlgorithm; ABitmap: TBGRACustomBitmap; ABounds: TRect); override;
    function GetDitheredBitmap(AAlgorithm: TDitheringAlgorithm; ABitmap: TBGRACustomBitmap; ABounds: TRect): TBGRACustomBitmap; overload; override;
    function GetDitheredBitmapIndexedData(ABitDepth: integer; AByteOrder: TRawImageByteOrder; AAlgorithm: TDitheringAlgorithm;
      ABitmap: TBGRACustomBitmap; out AScanlineSize: PtrInt): Pointer; overload; override;
    procedure SaveBitmapToStream(AAlgorithm: TDitheringAlgorithm;
      ABitmap: TBGRACustomBitmap; AStream: TStream; AFormat: TBGRAImageFormat); override;
  end;

  { Palette approximating color base on a color tree }
  TBGRAApproxPalette = class(TBGRACustomApproxPalette)
  private
    FTree: TBGRAColorTree;
    FColors: ArrayOfWeightedColor;
  protected
    function GetCount: integer; override;
    function GetColorByIndex(AIndex: integer): TBGRAPixel; override;
    function GetWeightByIndex(AIndex: Integer): UInt32; override;
    procedure Init(const AColors: ArrayOfTBGRAPixel);
  public
    constructor Create(const AColors: ArrayOfTBGRAPixel); overload;
    constructor Create(const AColors: ArrayOfWeightedColor); overload;
    constructor Create(AOwnedSplitTree: TBGRAColorTree); overload;
    destructor Destroy; override;
    function ContainsColor(AValue: TBGRAPixel): boolean; override;
    function IndexOfColor(AValue: TBGRAPixel): integer; override;
    function FindNearestColor(AValue: TBGRAPixel): TBGRAPixel; override;
    function FindNearestColorIndex(AValue: TBGRAPixel): integer; override;
    function GetAsArrayOfColor: ArrayOfTBGRAPixel; override;
    function GetAsArrayOfWeightedColor: ArrayOfWeightedColor; override;
  end;

  { Palette approximating via a large palette }
  TBGRAApproxPaletteViaLargerPalette = class(TBGRAApproxPalette)
  private
    FLarger: TBGRACustomApproxPalette;
    FLargerColors: array of record
      approxColor: TBGRAPixel;
      approxColorIndex: integer;
    end;
    FLargerOwned: boolean;
    FTransparentColorIndex: integer;
  protected
    function FindNearestLargerColorIndex(AValue: TBGRAPixel): integer; virtual;
    function SlowFindNearestColorIndex(AValue: TBGRAPixel): integer;
  public
    constructor Create(const AColors: ArrayOfTBGRAPixel; ALarger: TBGRACustomApproxPalette; ALargerOwned: boolean);
    destructor Destroy; override;
    function FindNearestColor(AValue: TBGRAPixel): TBGRAPixel; override;
    function FindNearestColorIndex(AValue: TBGRAPixel): integer; override;
    function GetAsArrayOfWeightedColor: ArrayOfWeightedColor; override;
  end;

  TIsChannelStrictlyGreaterFunc = TBGRAPixelComparer;
  TIsChannelGreaterThanOrEqualToValueFunc = function (p : PBGRAPixel; v: UInt32): boolean;

  TColorBoxBounds = array[TColorDimension] of TDimensionMinMax;

  { Box area in the colorspace allowing to split in two different areas }
  TBGRAColorBox = class
  private
    FBounds: TColorBoxBounds;
    FTotalWeight: UInt32;
    FColors: ArrayOfWeightedColor;
    FDimensions: TColorDimensions;
    FPureTransparentColorCount: integer;
    function GetApparentInterval(ADimension: TColorDimension): UInt32;
    function GetAverageColor: TBGRAPixel;
    function GetAverageColorOrMainColor: TBGRAPixel;
    function GetBounds(ADimension: TColorDimension): TDimensionMinMax;
    function GetColorCount(ACountPureTransparent: boolean): integer;
    function GetHasPureTransparentColor: boolean;
    function GetInferiorColor: TBGRAPixel;
    function GetLargestApparentDimension: TColorDimension;
    function GetLargestApparentInterval: UInt32;
    function GetPointLike: boolean;
    function GetSuperiorColor: TBGRAPixel;
    procedure Init(AColors: ArrayOfWeightedColor; AOwner: boolean);
    procedure SortBy(ADimension: TColorDimension);
    function GetMedianIndex(ADimension : TColorDimension; AMinValue, AMaxValue: UInt32): integer;
  public
    constructor Create(ADimensions: TColorDimensions; AColors: ArrayOfWeightedColor; AOwner: boolean); overload;
    constructor Create(ADimensions: TColorDimensions; const AColors: ArrayOfTBGRAPixel; AAlpha: TAlphaChannelPaletteOption = acFullChannelInPalette); overload;
    constructor Create(ADimensions: TColorDimensions; ABounds: TColorBoxBounds); overload;
    constructor Create(ADimensions: TColorDimensions; APalette: TBGRACustomPalette); overload;
    constructor Create(ADimensions: TColorDimensions; ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption); overload;
    constructor Create(ADimensions: TColorDimensions; AColors: PBGRAPixel; ANbPixels: integer; AAlpha: TAlphaChannelPaletteOption); overload;
    function BoundsContain(AColor: TBGRAPixel): boolean;
    function MedianCut(ADimension: TColorDimension; out SuperiorMiddle: UInt32): TBGRAColorBox;
    function Duplicate : TBGRAColorBox;
    property Bounds[ADimension: TColorDimension]: TDimensionMinMax read GetBounds;
    property ApparentInterval[AChannel: TColorDimension]: UInt32 read GetApparentInterval;
    property LargestApparentDimension: TColorDimension read GetLargestApparentDimension;
    property LargestApparentInterval: UInt32 read GetLargestApparentInterval;
    property PointLike: boolean read GetPointLike;
    property AverageColor: TBGRAPixel read GetAverageColor;
    property SuperiorColor: TBGRAPixel read GetSuperiorColor;
    property InferiorColor: TBGRAPixel read GetInferiorColor;
    property AverageColorOrMainColor: TBGRAPixel read GetAverageColorOrMainColor;
    function GetAsArrayOfColors(AIncludePureTransparent: boolean): ArrayOfTBGRAPixel;
    property TotalWeight: UInt32 read FTotalWeight;
    property ColorCount[ACountPureTransparent: boolean]: integer read GetColorCount;
    property HasPureTransparentColor: boolean read GetHasPureTransparentColor;
    property PureTransparentColorCount: integer read FPureTransparentColorCount;
  end;

  TBGRALeafColorMode = (lcAverage, lcCenter, lcExtremum, lcMix);

  { Binary tree of colors for color approximation }
  TBGRAColorTree = class
  private
    FLeaf: TBGRAColorBox;
    FIsLeaf: boolean;
    FLargestApparentInterval: integer;
    FWeight: UInt32;

    FLeafColor: TBGRAPixel;
    FLeafColorIndex: integer;
    FLeafColorComputed: boolean;
    FMinBorder, FMaxBorder: array[TColorDimension] of boolean;
    FCenterColor: TBGRAPixel;
    FAverageColor: TBGRAPixel;

    FPureTransparentColorCount: integer;
    FPureTransparentColorIndex: integer;
    FDimension: TColorDimension;
    FPixelValueComparer: TIsChannelGreaterThanOrEqualToValueFunc;
    FSuperiorMiddle: UInt32;
    FInferiorBranch, FSuperiorBranch: TBGRAColorTree;
    function GetApproximatedColorCount: integer;
    function GetHasPureTransparentColor: boolean;
    function GetLeafCount: integer;
    procedure Init(ALeaf: TBGRAColorBox; AOwned: boolean);
    procedure InternalComputeLeavesColor(ALeafColor: TBGRALeafColorMode; var AStartIndex: integer);
    procedure CheckColorComputed;
  public
    constructor Create(ABox: TBGRAColorBox; AOwned: boolean); overload;
    constructor Create(ADimensions: TColorDimensions; APalette: TBGRACustomPalette); overload;
    constructor Create(ADimensions: TColorDimensions; ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption); overload;
    destructor Destroy; override;
    procedure FreeLeaves;
    function FindBiggestLeaf(AMethod: TBiggestLeafMethod): TBGRAColorTree;
    property LargestApparentInterval: integer read FLargestApparentInterval;
    property Weight: UInt32 read FWeight;
    property IsLeaf: boolean read FIsLeaf;
    function TrySplitLeaf: boolean;
    procedure ComputeLeavesColor(ALeafColor: TBGRALeafColorMode);
    function ApproximateColor(AColor: TBGRAPixel): TBGRAPixel;
    function ApproximateColorIndex(AColor: TBGRAPixel): integer;
    function GetAsArrayOfApproximatedColors: ArrayOfTBGRAPixel;
    function GetAsArrayOfWeightedColors: ArrayOfWeightedColor;
    procedure SplitIntoPalette(ACount: integer; AMethod: TBiggestLeafMethod;
      ALeafColor: TBGRALeafColorMode);
    function SplitIntoPaletteWithSubPalette(ACount: integer; AMethod: TBiggestLeafMethod;
      ALeafColor: TBGRALeafColorMode; ASubPaletteCount: integer): ArrayOfTBGRAPixel;
    property LeafCount: integer read GetLeafCount;
    property ApproximatedColorCount: integer read GetApproximatedColorCount;
    property HasPureTransparentColor: boolean read GetHasPureTransparentColor;
    property PureTransparentColorCount: integer read FPureTransparentColorCount;
  end;

function GetPixelStrictComparer(ADimension: TColorDimension): TIsChannelStrictlyGreaterFunc;
function GetPixelValueComparer(ADimension: TColorDimension): TIsChannelGreaterThanOrEqualToValueFunc;
function BGRAColorCount(ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption): integer;

const AllColorDimensions = [cdRed,cdGreen,cdBlue,cdAlpha,cdRGB,cdRG,cdGB,cdRB,cdRInvG,cdGInvB,cdRInvB,cdRInvGB,cdGInvRB,cdBInvRG,
                            cdSaturation];

implementation

uses BGRADithering, FPimage, FPWriteBMP, BGRAWritePNG, math;

const MedianMinPercentage = 0.2;

const RedShift = 1;
      GreenShift = 2;
      AlphaShift = 1;
      SaturationShift = 2;

function GetDimensionValue(APixel: TBGRAPixel; ADimension: TColorDimension): UInt32;
var v: UInt32;
begin
  case ADimension of
  cdFast: result := LongWord(APixel);
  cdRed: result := GammaExpansionTab[APixel.red] shl RedShift;
  cdGreen: result := GammaExpansionTab[APixel.green] shl GreenShift;
  cdBlue: result := GammaExpansionTab[APixel.blue];
  cdAlpha: result := (APixel.alpha + (APixel.alpha shl 8)) shl AlphaShift;
  cdRGB: result := GammaExpansionTab[APixel.blue] + (GammaExpansionTab[APixel.red] shl RedShift) + (GammaExpansionTab[APixel.green] shl GreenShift);
  cdRG: result := (GammaExpansionTab[APixel.red] shl RedShift) + (GammaExpansionTab[APixel.green] shl GreenShift);
  cdGB: result := GammaExpansionTab[APixel.blue] + (GammaExpansionTab[APixel.green] shl GreenShift);
  cdRB: result := (GammaExpansionTab[APixel.red] shl RedShift) + GammaExpansionTab[APixel.blue];
  cdRInvG: result := (GammaExpansionTab[APixel.red] shl RedShift) + ((not GammaExpansionTab[APixel.green]) shl GreenShift);
  cdGInvB: result := (GammaExpansionTab[APixel.green] shl GreenShift) + (not GammaExpansionTab[APixel.blue]);
  cdRInvB: result := (GammaExpansionTab[APixel.red] shl RedShift) + (not GammaExpansionTab[APixel.blue]);
  cdRInvGB: result := (GammaExpansionTab[APixel.red] shl RedShift) + ((not GammaExpansionTab[APixel.green]) shl GreenShift) + (not GammaExpansionTab[APixel.blue]);
  cdGInvRB: result := (GammaExpansionTab[APixel.green] shl GreenShift) + ((not GammaExpansionTab[APixel.red]) shl RedShift) + (not GammaExpansionTab[APixel.blue]);
  cdBInvRG: result := (GammaExpansionTab[APixel.blue]) + ((not GammaExpansionTab[APixel.red]) shl RedShift) + ((not GammaExpansionTab[APixel.green]) shl GreenShift);
  cdSaturation: with GammaExpansion(APixel) do
    begin
       v := red;
       if green>v then v := green;
       if blue>v then v := blue;
       result := v;
       v := red;
       if green<v then v := green;
       if blue<v then v := blue;
       dec(result, v);
       result := result shl SaturationShift;
    end
  else raise exception.Create('Unknown dimension');
  end;
end;

function IsRGBGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := ((GammaExpansionTab[p1^.red] shl RedShift)+(GammaExpansionTab[p1^.green] shl GreenShift)+GammaExpansionTab[p1^.blue]) >
     ((GammaExpansionTab[p2^.red] shl RedShift)+(GammaExpansionTab[p2^.green] shl GreenShift)+GammaExpansionTab[p2^.blue]);
end;

function IsRGBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := ((GammaExpansionTab[red] shl RedShift)+(GammaExpansionTab[green] shl GreenShift)+GammaExpansionTab[blue]) >= v;
end;

function IsRGGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := ((GammaExpansionTab[p1^.red] shl RedShift)+(GammaExpansionTab[p1^.green] shl GreenShift)) >
     ((GammaExpansionTab[p2^.red] shl RedShift)+(GammaExpansionTab[p2^.green] shl GreenShift));
end;

function IsRGGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := ((GammaExpansionTab[red] shl RedShift)+(GammaExpansionTab[green] shl GreenShift)) >= v;
end;

function IsGBGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := ((GammaExpansionTab[p1^.green] shl GreenShift)+GammaExpansionTab[p1^.blue]) >
  ((GammaExpansionTab[p2^.green] shl GreenShift)+GammaExpansionTab[p2^.blue]);
end;

function IsGBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := ((GammaExpansionTab[green] shl GreenShift)+GammaExpansionTab[blue]) >= v;
end;

function IsRBGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := ((GammaExpansionTab[p1^.red] shl RedShift)+GammaExpansionTab[p1^.blue]) >
  ((GammaExpansionTab[p2^.red] shl RedShift)+GammaExpansionTab[p2^.blue]);
end;

function IsRBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := ((GammaExpansionTab[red] shl RedShift)+GammaExpansionTab[blue]) >= v;
end;

function IsRInvGGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.red]+ ((not GammaExpansionTab[p1^.green]) shl GreenShift)) >
          (GammaExpansionTab[p2^.red]+((not GammaExpansionTab[p2^.green]) shl GreenShift));
end;

function IsRInvGGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[red]+((not GammaExpansionTab[green]) shl GreenShift)) >= v;
end;

function IsGInvBGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.green] shl GreenShift + not GammaExpansionTab[p1^.blue]) >
     (GammaExpansionTab[p2^.green] shl GreenShift + not GammaExpansionTab[p2^.blue]);
end;

function IsGInvBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[green] shl GreenShift + not GammaExpansionTab[blue]) >= v;
end;

function IsRInvBGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.red] shl RedShift + not GammaExpansionTab[p1^.blue]) >
    (GammaExpansionTab[p2^.red] shl RedShift + not GammaExpansionTab[p2^.blue]);
end;

function IsRInvBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[red] shl RedShift + not GammaExpansionTab[blue]) >= v;
end;

function IsRInvGBGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.red] shl RedShift + ((not GammaExpansionTab[p1^.green]) shl GreenShift) + not GammaExpansionTab[p1^.blue]) >
          (GammaExpansionTab[p2^.red] shl RedShift + ((not GammaExpansionTab[p2^.green]) shl GreenShift) + not GammaExpansionTab[p2^.blue]);
end;

function IsRInvGBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[red] shl RedShift + ((not GammaExpansionTab[green]) shl GreenShift) + not GammaExpansionTab[blue]) >= v;
end;

function IsGInvRBGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.green] shl GreenShift + ((not GammaExpansionTab[p1^.red]) shl RedShift) + not GammaExpansionTab[p1^.blue]) >
     (GammaExpansionTab[p2^.green] shl GreenShift + ((not GammaExpansionTab[p2^.red]) shl RedShift) + not GammaExpansionTab[p2^.blue]);
end;

function IsGInvRBGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[green] shl GreenShift + ((not GammaExpansionTab[red]) shl RedShift) + not GammaExpansionTab[blue]) >= v;
end;

function IsBInvRGGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := (GammaExpansionTab[p1^.blue] + ((not GammaExpansionTab[p1^.red]) shl RedShift) + ((not GammaExpansionTab[p1^.green]) shl GreenShift)) >
    (GammaExpansionTab[p2^.blue] + ((not GammaExpansionTab[p2^.red]) shl RedShift) + ((not GammaExpansionTab[p2^.green]) shl GreenShift));
end;

function IsBInvRGGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  with p^ do
    result := (GammaExpansionTab[blue] + ((not GammaExpansionTab[red]) shl RedShift) + ((not GammaExpansionTab[green]) shl GreenShift)) >= v;
end;

function IsSaturationGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := GetDimensionValue(p1^,cdSaturation) > GetDimensionValue(p2^,cdSaturation);
end;

function IsSaturationGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := GetDimensionValue(p^,cdSaturation) >= v;
end;

function IsRedGreater(p1, p2: PBGRAPixel): boolean;
begin
  result := p1^.red > p2^.red;
end;

function IsRedGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := GammaExpansionTab[p^.red] shl RedShift >= v;
end;

function IsGreenGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := p1^.green > p2^.green;
end;

function IsGreenGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := GammaExpansionTab[p^.green] shl GreenShift >= v;
end;

function IsBlueGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := p1^.blue > p2^.blue;
end;

function IsBlueGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := GammaExpansionTab[p^.blue] >= v;
end;

function IsAlphaGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := p1^.alpha > p2^.alpha;
end;

function IsAlphaGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := (p^.alpha + p^.alpha shl 8) shl AlphaShift >= v;
end;

function IsDWordGreater(p1, p2: PBGRAPixel
  ): boolean;
begin
  result := LongWord(p1^) > LongWord(p2^);
end;

function IsDWordGreaterThanValue(p: PBGRAPixel;
  v: UInt32): boolean;
begin
  result := LongWord(p^) >= v;
end;

function GetPixelStrictComparer(ADimension: TColorDimension
  ): TIsChannelStrictlyGreaterFunc;
begin
  case ADimension of
  cdFast: result := @IsDWordGreater;
  cdRed: result := @IsRedGreater;
  cdGreen: result := @IsGreenGreater;
  cdBlue: result := @IsBlueGreater;
  cdAlpha: result := @IsAlphaGreater;
  cdRGB: result := @IsRGBGreater;
  cdRG: result := @IsRGGreater;
  cdGB: result := @IsGBGreater;
  cdRB: result := @IsRBGreater;
  cdRInvG: result := @IsRInvGGreater;
  cdGInvB: result := @IsGInvBGreater;
  cdRInvB: result := @IsRInvBGreater;
  cdRInvGB: result := @IsRInvGBGreater;
  cdGInvRB: result := @IsGInvRBGreater;
  cdBInvRG: result := @IsBInvRGGreater;
  cdSaturation: result := @IsSaturationGreater;
  else raise Exception.Create('Unknown dimension');
  end;
end;

function GetPixelValueComparer(ADimension: TColorDimension
  ): TIsChannelGreaterThanOrEqualToValueFunc;
begin
  case ADimension of
  cdFast: result := @IsDWordGreaterThanValue;
  cdRed: result := @IsRedGreaterThanValue;
  cdGreen: result := @IsGreenGreaterThanValue;
  cdBlue: result := @IsBlueGreaterThanValue;
  cdAlpha: result := @IsAlphaGreaterThanValue;
  cdRGB: result := @IsRGBGreaterThanValue;
  cdRG: result := @IsRGGreaterThanValue;
  cdGB: result := @IsGBGreaterThanValue;
  cdRB: result := @IsRBGreaterThanValue;
  cdRInvG: result := @IsRInvGGreaterThanValue;
  cdGInvB: result := @IsGInvBGreaterThanValue;
  cdRInvB: result := @IsRInvBGreaterThanValue;
  cdRInvGB: result := @IsRInvGBGreaterThanValue;
  cdGInvRB: result := @IsGInvRBGreaterThanValue;
  cdBInvRG: result := @IsBInvRGGreaterThanValue;
  cdSaturation: result := @IsSaturationGreaterThanValue;
  else raise Exception.Create('Unknown dimension');
  end;
end;

function BGRAColorCount(ABitmap: TBGRACustomBitmap;
  AAlpha: TAlphaChannelPaletteOption): integer;
var
  box: TBGRAColorBox;
begin
  box := TBGRAColorBox.Create(AllColorDimensions,ABitmap,AAlpha);
  result := box.ColorCount[True];
  box.Free;
end;

const
  ApproxPaletteDimensions = [cdAlpha,cdRInvG,cdGInvB,cdRInvB,cdRInvGB,cdGInvRB,cdBInvRG,cdRGB];

{ TBGRAApproxPaletteViaLargerPalette }

function TBGRAApproxPaletteViaLargerPalette.FindNearestLargerColorIndex(
  AValue: TBGRAPixel): integer;
begin
  result := FLarger.FindNearestColorIndex(AValue);
end;

function TBGRAApproxPaletteViaLargerPalette.SlowFindNearestColorIndex(
  AValue: TBGRAPixel): integer;
var diff,curDiff: Int32or64;
  i: Int32or64;
begin
  if AValue.alpha = 0 then
  begin
    result := FTransparentColorIndex;
    exit;
  end;
  diff := BGRAWordDiff(AValue, FColors[0].Color);
  result := 0;
  for i := 0 to high(FColors) do
  begin
    curDiff := BGRAWordDiff(AValue, FColors[i].Color);
    if curDiff < diff then
    begin
      result := i;
      diff := curDiff;
    end;
  end;
end;

constructor TBGRAApproxPaletteViaLargerPalette.Create(
  const AColors: ArrayOfTBGRAPixel; ALarger: TBGRACustomApproxPalette; ALargerOwned: boolean);
var i: integer;
  largeWeighted: ArrayOfWeightedColor;
begin
  inherited Create(AColors);
  FTransparentColorIndex:= -1;
  for i := 0 to high(FColors) do
  begin
    FColors[i].Weight := 0;
    if FColors[i].Color.alpha = 0 then FTransparentColorIndex:= i;
  end;
  FLarger := ALarger;
  FLargerOwned := ALargerOwned;
  largeWeighted := FLarger.GetAsArrayOfWeightedColor;
  setlength(FLargerColors, length(largeWeighted));
  for i := 0 to high(FLargerColors) do
  with FLargerColors[i] do
  begin
    approxColorIndex := SlowFindNearestColorIndex(largeWeighted[i].Color);
    if approxColorIndex = -1 then
      approxColor := BGRAPixelTransparent
    else
    begin
      approxColor := FColors[approxColorIndex].Color;
      inc(FColors[approxColorIndex].Weight, largeWeighted[i].Weight);
    end;
  end;
end;

destructor TBGRAApproxPaletteViaLargerPalette.Destroy;
begin
  if FLargerOwned then FreeAndNil(FLarger);
  inherited Destroy;
end;

function TBGRAApproxPaletteViaLargerPalette.FindNearestColor(AValue: TBGRAPixel
  ): TBGRAPixel;
var index: integer;
begin
  index := FindNearestLargerColorIndex(AValue);
  if index = -1 then
    result := BGRAPixelTransparent
  else
    Result:= FLargerColors[index].approxColor;
end;

function TBGRAApproxPaletteViaLargerPalette.FindNearestColorIndex(
  AValue: TBGRAPixel): integer;
var index: integer;
begin
  index := FindNearestLargerColorIndex(AValue);
  if index = -1 then
    result := -1
  else
    Result:= FLargerColors[index].approxColorIndex;
end;

function TBGRAApproxPaletteViaLargerPalette.GetAsArrayOfWeightedColor: ArrayOfWeightedColor;
var
  i: Integer;
begin
  setlength(result, length(FColors));
  for i := 0 to high(FColors) do
    result[i] := FColors[i];
end;

{ TBGRAApproxPalette }

function TBGRAApproxPalette.GetCount: integer;
begin
  result := length(FColors);
end;

function TBGRAApproxPalette.GetColorByIndex(AIndex: integer): TBGRAPixel;
begin
  if (AIndex < 0) or (AIndex >= length(FColors)) then
    raise ERangeError.Create('Index out of bounds');
  result := FColors[AIndex].Color;
end;

function TBGRAApproxPalette.GetWeightByIndex(AIndex: Integer): UInt32;
begin
  if (AIndex < 0) or (AIndex >= length(FColors)) then
    raise ERangeError.Create('Index out of bounds');
  result := FColors[AIndex].Weight;
end;

procedure TBGRAApproxPalette.Init(const AColors: ArrayOfTBGRAPixel);
var
  weightedColors: ArrayOfWeightedColor;
  i: Int32or64;
begin
  setlength(weightedColors, length(AColors));
  for i := 0 to high(weightedColors) do
  with weightedColors[i] do
  begin
    Color := AColors[i];
    Weight := 1;
  end;
  FTree := TBGRAColorTree.Create(TBGRAColorBox.Create(ApproxPaletteDimensions,weightedColors,True),True);
  FTree.SplitIntoPalette(length(AColors),blApparentInterval,lcAverage);

  FColors := FTree.GetAsArrayOfWeightedColors;
end;

constructor TBGRAApproxPalette.Create(const AColors: ArrayOfTBGRAPixel);
begin
  Init(AColors);
end;

constructor TBGRAApproxPalette.Create(const AColors: ArrayOfWeightedColor);
begin
  FTree := TBGRAColorTree.Create(TBGRAColorBox.Create(ApproxPaletteDimensions,AColors,True),True);
  FTree.SplitIntoPalette(length(AColors),blApparentInterval,lcAverage);

  FColors := FTree.GetAsArrayOfWeightedColors;
end;

constructor TBGRAApproxPalette.Create(AOwnedSplitTree: TBGRAColorTree);
begin
  FTree := AOwnedSplitTree;
  FColors := FTree.GetAsArrayOfWeightedColors;
end;

destructor TBGRAApproxPalette.Destroy;
begin
  FreeAndNil(FTree);
  inherited Destroy;
end;

function TBGRAApproxPalette.ContainsColor(AValue: TBGRAPixel): boolean;
begin
  result := (IndexOfColor(AValue)<>-1);
end;

function TBGRAApproxPalette.IndexOfColor(AValue: TBGRAPixel): integer;
begin
  result := FTree.ApproximateColorIndex(AValue);
  if (result <> -1) and not (LongWord(FColors[result].Color) = LongWord(AValue)) then result := -1;
end;

function TBGRAApproxPalette.FindNearestColor(AValue: TBGRAPixel): TBGRAPixel;
begin
  result := FTree.ApproximateColor(AValue);
end;

function TBGRAApproxPalette.FindNearestColorIndex(AValue: TBGRAPixel): integer;
begin
  result := FTree.ApproximateColorIndex(AValue);
end;

function TBGRAApproxPalette.GetAsArrayOfColor: ArrayOfTBGRAPixel;
var
  i: Int32or64;
begin
  setlength(result, length(FColors));
  for i := 0 to high(result) do
    result[i] := FColors[i].Color;
end;

function TBGRAApproxPalette.GetAsArrayOfWeightedColor: ArrayOfWeightedColor;
var
  i: Int32or64;
begin
  if Assigned(FTree) then
    result := FTree.GetAsArrayOfWeightedColors
  else
  begin
    setlength(result, length(FColors));
    for i := 0 to high(result) do
      result[i] := FColors[i];
  end;
end;

{ TBGRAColorQuantizer }

procedure TBGRAColorQuantizer.Init(ABox: TBGRAColorBox);
begin
  FColors := ABox.FColors;
  if ABox.HasPureTransparentColor then
  begin
    setlength(FColors,length(FColors)+1);
    with FColors[high(FColors)] do
    begin
      Color := BGRAPixelTransparent;
      Weight:= ABox.PureTransparentColorCount;
    end;
  end;
  ABox.FColors := nil;
  ABox.Free;
  FReductionColorCount := 256;
  FReductionKeepContrast := true;
end;

procedure TBGRAColorQuantizer.SetReductionColorCount(AValue: Integer);
begin
  if AValue < 1 then AValue := 1;
  if FReductionColorCount=AValue then Exit;
  FReductionColorCount:=AValue;
  FreeAndNil(FPalette);
end;

procedure TBGRAColorQuantizer.NormalizeArrayOfColors(
  AColors: ArrayOfTBGRAPixel; ARedBounds, AGreenBounds, ABlueBounds,
  AAlphaBounds: TDimensionMinMax; AUniform: boolean);
var
  curRedBounds, curGreenBounds, curBlueBounds, curAlphaBounds: TDimensionMinMax;
  RedSub,RedMul,RedDiv,RedAdd: UInt32or64;
  GreenSub,GreenMul,GreenDiv,GreenAdd: UInt32or64;
  BlueSub,BlueMul,BlueDiv,BlueAdd: UInt32or64;
  AlphaSub,AlphaMul,AlphaDiv,AlphaAdd: UInt32or64;
  i: Int32or64;
  colorBounds: TDimensionMinMax;
begin
  if length(AColors)=0 then exit;
  if AUniform then
  begin
    colorBounds := ABlueBounds;
    colorBounds.GrowToInclude(AGreenBounds.Minimum shr GreenShift);
    colorBounds.GrowToInclude(AGreenBounds.Maximum shr GreenShift);
    colorBounds.GrowToInclude(ARedBounds.Minimum shr RedShift);
    colorBounds.GrowToInclude(ARedBounds.Maximum shr RedShift);
    NormalizeArrayOfColors(AColors, colorBounds, AAlphaBounds);
    exit;
  end;
  curRedBounds.SetAsPoint(GetDimensionValue(AColors[0],cdRed));
  curGreenBounds.SetAsPoint(GetDimensionValue(AColors[0],cdGreen));
  curBlueBounds.SetAsPoint(GetDimensionValue(AColors[0],cdBlue));
  curAlphaBounds.SetAsPoint(GetDimensionValue(AColors[0],cdAlpha));
  for i := 1 to high(AColors) do
  with AColors[i] do
  begin
    curRedBounds.GrowToInclude(GetDimensionValue(AColors[i],cdRed));
    curGreenBounds.GrowToInclude(GetDimensionValue(AColors[i],cdGreen));
    curBlueBounds.GrowToInclude(GetDimensionValue(AColors[i],cdBlue));
    curAlphaBounds.GrowToInclude(GetDimensionValue(AColors[i],cdAlpha));
  end;
  RedSub := curRedBounds.Minimum shr RedShift;
  RedMul := ARedBounds.Size shr RedShift;
  RedDiv := curRedBounds.Size shr RedShift;
  RedAdd := ARedBounds.Minimum shr RedShift;
  if RedDiv = 0 then RedDiv := 1;
  GreenSub := curGreenBounds.Minimum shr GreenShift;
  GreenMul := AGreenBounds.Size shr GreenShift;
  GreenDiv := curGreenBounds.Size shr GreenShift;
  GreenAdd := AGreenBounds.Minimum shr GreenShift;
  if GreenDiv = 0 then GreenDiv := 1;
  BlueSub := curBlueBounds.Minimum;
  BlueMul := ABlueBounds.Size;
  BlueDiv := curBlueBounds.Size;
  BlueAdd := ABlueBounds.Minimum;
  if BlueDiv = 0 then BlueDiv := 1;
  AlphaSub := curAlphaBounds.Minimum shr (AlphaShift+8);
  AlphaMul := AAlphaBounds.Size shr (AlphaShift+8);
  AlphaDiv := curAlphaBounds.Size shr (AlphaShift+8);
  AlphaAdd := AAlphaBounds.Minimum shr (AlphaShift+8);
  if AlphaDiv = 0 then AlphaDiv := 1;
  for i := 0 to high(AColors) do
  with AColors[i] do
  begin
    red := GammaCompressionTab[((GammaExpansionTab[red]-RedSub)*RedMul+(RedDiv shr 1)) div RedDiv + RedAdd];
    green := GammaCompressionTab[((GammaExpansionTab[green]-GreenSub)*GreenMul+(GreenDiv shr 1)) div GreenDiv + GreenAdd];
    blue := GammaCompressionTab[((GammaExpansionTab[blue]-BlueSub)*BlueMul+(BlueDiv shr 1)) div BlueDiv + BlueAdd];
    alpha := ((alpha-AlphaSub)*AlphaMul+(AlphaDiv shr 1)) div AlphaDiv + AlphaAdd;
  end;
end;

procedure TBGRAColorQuantizer.NormalizeArrayOfColors(
  AColors: ArrayOfTBGRAPixel; AColorBounds, AAlphaBounds: TDimensionMinMax);
var
  curColorBounds, curAlphaBounds: TDimensionMinMax;
  ColorSub,ColorMul,ColorDiv,ColorAdd: UInt32or64;
  AlphaSub,AlphaMul,AlphaDiv,AlphaAdd: UInt32or64;
  i: Int32or64;
begin
  if length(AColors)=0 then exit;
  curColorBounds.SetAsPoint(GammaExpansionTab[AColors[0].red]);
  curColorBounds.GrowToInclude(GammaExpansionTab[AColors[0].green]);
  curColorBounds.GrowToInclude(GammaExpansionTab[AColors[0].blue]);
  curAlphaBounds.SetAsPoint(AColors[0].alpha);
  for i := 1 to high(AColors) do
  with AColors[i] do
  begin
    curColorBounds.GrowToInclude(GammaExpansionTab[red]);
    curColorBounds.GrowToInclude(GammaExpansionTab[green]);
    curColorBounds.GrowToInclude(GammaExpansionTab[blue]);
    curAlphaBounds.GrowToInclude(alpha);
  end;
  ColorSub := curColorBounds.Minimum;
  ColorMul := AColorBounds.Size;
  ColorDiv := curColorBounds.Size;
  ColorAdd := AColorBounds.Minimum;
  if ColorDiv = 0 then ColorDiv := 1;
  AlphaSub := curAlphaBounds.Minimum;
  AlphaMul := AAlphaBounds.Size shr 8;
  AlphaDiv := curAlphaBounds.Size;
  AlphaAdd := AAlphaBounds.Minimum shr 8;
  if AlphaDiv = 0 then AlphaDiv := 1;
  for i := 0 to high(AColors) do
  with AColors[i] do
  begin
    red := GammaCompressionTab[((GammaExpansionTab[red]-ColorSub)*ColorMul+(ColorDiv shr 1)) div ColorDiv + ColorAdd];
    green := GammaCompressionTab[((GammaExpansionTab[green]-ColorSub)*ColorMul+(ColorDiv shr 1)) div ColorDiv + ColorAdd];
    blue := GammaCompressionTab[((GammaExpansionTab[blue]-ColorSub)*ColorMul+(ColorDiv shr 1)) div ColorDiv + ColorAdd];
    alpha := ((alpha-AlphaSub)*AlphaMul+(AlphaDiv shr 1)) div AlphaDiv + AlphaAdd;
  end;
end;

function TBGRAColorQuantizer.GetSourceColorCount: Integer;
begin
  result := length(FColors);
end;

function TBGRAColorQuantizer.GetReductionColorCount: integer;
begin
  result := FReductionColorCount;
end;

function TBGRAColorQuantizer.GetPalette: TBGRACustomApproxPalette;
var
  tree: TBGRAColorTree;

  procedure MakeTreeErrorDiffusionFriendly;
  var moreColors: ArrayOfWeightedColor;
    box: TBGRAColorBox;
  begin
    moreColors := tree.GetAsArrayOfWeightedColors;
    tree.free;
    box := TBGRAColorBox.Create([cdRed,cdGreen,cdBlue,cdAlpha],moreColors,True);
    tree := TBGRAColorTree.Create(box,True);
    tree.SplitIntoPalette(box.ColorCount[true], blApparentInterval, lcAverage);
  end;

var
  originalBox: TBGRAColorBox;
  colors: ArrayOfTBGRAPixel;
  bounds: array[TColorDimension] of TDimensionMinMax;
  nbLarge,nbOriginal: integer;

begin
  if not Assigned(FPalette) then
  if FReductionColorCount >= length(FColors) then
  begin
    originalBox := TBGRAColorBox.Create([cdRed,cdGreen,cdBlue,cdAlpha],FColors, False);
    tree := TBGRAColorTree.Create(originalBox,True);
    tree.SplitIntoPalette(originalBox.ColorCount[true], blApparentInterval, lcAverage);
    FPalette := TBGRAApproxPalette.Create(tree);
  end else
  begin
    originalBox := TBGRAColorBox.Create(AllColorDimensions, FColors, False);
    bounds[cdRed] := originalBox.Bounds[cdRed];
    bounds[cdGreen] := originalBox.Bounds[cdGreen];
    bounds[cdBlue] := originalBox.Bounds[cdBlue];
    bounds[cdAlpha] := originalBox.Bounds[cdAlpha];
    if originalBox.HasPureTransparentColor then bounds[cdAlpha].Minimum := 0;
    if FReductionColorCount = 1 then
    begin
      setlength(colors,1);
      colors[0] := originalBox.AverageColor;
      originalBox.Free;
      FPalette := TBGRAApproxPalette.Create(colors);
    end else
    begin
      tree := TBGRAColorTree.Create(originalBox,True);
      if FReductionColorCount <= 64 then
      begin
        nbLarge := 128;
        nbOriginal := originalBox.ColorCount[True];
        if nbOriginal < 128 then nbLarge:= nbOriginal;
        colors := tree.SplitIntoPaletteWithSubPalette(nbLarge, blMix,lcMix, FReductionColorCount);
        MakeTreeErrorDiffusionFriendly;
        if FReductionColorCount <= 4 then
          NormalizeArrayOfColors(colors, bounds[cdRed],bounds[cdGreen],bounds[cdBlue],bounds[cdAlpha],true);
        FPalette := TBGRAApproxPaletteViaLargerPalette.Create(colors, TBGRAApproxPalette.Create(tree), True);
      end else
      begin
        tree.SplitIntoPalette(FReductionColorCount, blMix,lcMix);
        MakeTreeErrorDiffusionFriendly;
        FPalette := TBGRAApproxPalette.Create(tree);
      end;
    end;
  end;
  result := FPalette;
end;

function TBGRAColorQuantizer.GetSourceColor(AIndex: integer): TBGRAPixel;
begin
  if (AIndex < 0) or (AIndex >= length(FColors)) then
    raise ERangeError.Create('Index out of bounds');
  result := FColors[AIndex].Color;
end;

constructor TBGRAColorQuantizer.Create(APalette: TBGRACustomPalette; ASeparateAlphaChannel: boolean);
begin
  FSeparateAlphaChannel:= ASeparateAlphaChannel;
  Init(TBGRAColorBox.Create(AllColorDimensions, APalette));
end;

constructor TBGRAColorQuantizer.Create(ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption);
begin
  FSeparateAlphaChannel:= (AAlpha = acIgnore);
  Init(TBGRAColorBox.Create(AllColorDimensions, ABitmap, AAlpha));
end;

constructor TBGRAColorQuantizer.Create(APalette: TBGRACustomPalette;
  ASeparateAlphaChannel: boolean; AReductionColorCount: integer);
begin
  FSeparateAlphaChannel:= ASeparateAlphaChannel;
  Init(TBGRAColorBox.Create(AllColorDimensions, APalette));
  ReductionColorCount := AReductionColorCount;
end;

constructor TBGRAColorQuantizer.Create(ABitmap: TBGRACustomBitmap;
  AAlpha: TAlphaChannelPaletteOption; AReductionColorCount: integer);
begin
  FSeparateAlphaChannel:= (AAlpha = acIgnore);
  Init(TBGRAColorBox.Create(AllColorDimensions, ABitmap, AAlpha));
  ReductionColorCount := AReductionColorCount;
end;

destructor TBGRAColorQuantizer.Destroy;
begin
  FreeAndNil(FPalette);
  inherited Destroy;
end;

procedure TBGRAColorQuantizer.ApplyDitheringInplace(AAlgorithm: TDitheringAlgorithm; ABitmap: TBGRACustomBitmap;
  ABounds: TRect);
var task: TDitheringTask;
begin
  task := CreateDitheringTask(AAlgorithm, ABitmap, ReducedPalette, FSeparateAlphaChannel, ABounds);
  task.Destination := ABitmap;
  task.Execute;
  task.Free;
end;

function TBGRAColorQuantizer.GetDitheredBitmap(AAlgorithm: TDitheringAlgorithm;
  ABitmap: TBGRACustomBitmap; ABounds: TRect): TBGRACustomBitmap;
var task: TDitheringTask;
begin
  task := CreateDitheringTask(AAlgorithm, ABitmap, ReducedPalette, FSeparateAlphaChannel, ABounds);
  result := task.Execute;
  task.Free;
end;

function TBGRAColorQuantizer.GetDitheredBitmapIndexedData(
  ABitDepth: integer; AByteOrder: TRawImageByteOrder; AAlgorithm: TDitheringAlgorithm; ABitmap: TBGRACustomBitmap;
  out AScanlineSize: PtrInt): Pointer;
var
  indexer: TDitheringToIndexedImage;
begin
  indexer := TDitheringToIndexedImage.Create(ReducedPalette, FSeparateAlphaChannel, ABitDepth, AByteOrder);
  indexer.DefaultTransparentColorIndex := ReducedPalette.IndexOfColor(BGRAPixelTransparent);
  AScanlineSize:= indexer.ComputeMinimumScanlineSize(ABitmap.Width);
  result := indexer.DitherImage(AAlgorithm, ABitmap, AScanlineSize);
  indexer.Free;
end;

procedure TBGRAColorQuantizer.SaveBitmapToStream(AAlgorithm: TDitheringAlgorithm; ABitmap: TBGRACustomBitmap;
  AStream: TStream; AFormat: TBGRAImageFormat);
var
  dithered: TBGRACustomBitmap;
  hasTransp: boolean;
  writer: TFPCustomImageWriter;
  depth: integer;
begin
  dithered := GetDitheredBitmap(AAlgorithm, ABitmap);
  try
    ReducedPalette.AssignTo(dithered);
    hasTransp := dithered.HasTransparentPixels;
    writer := CreateBGRAImageWriter(AFormat, hasTransp);
    try
      if writer is TBGRAWriterPNG then TBGRAWriterPNG(writer).Indexed := true else
      if writer is TFPWriterBMP then
      begin
        if not hasTransp then
        begin
          depth := BGRARequiredBitDepth(ReducedPalette);
          if depth < 8 then
          begin
            if depth > 4 then
              depth := 8
            else if depth > 1 then
              depth := 4;
          end;
          TFPWriterBMP(writer).BitsPerPixel := depth;
        end;
      end;
      dithered.SaveToStream(AStream, writer);
    finally
      writer.Free;
    end;
  finally
    dithered.Free;
  end;
end;

{ TBGRAColorTree }

function TBGRAColorTree.TrySplitLeaf: boolean;
var
  dim: TColorDimension;
  box2: TBGRAColorBox;
  mid: UInt32;
begin
  result := false;
  if IsLeaf and Assigned(FLeaf) and not FLeaf.PointLike then
  begin
    dim := FLeaf.LargestApparentDimension;
    box2 := FLeaf.MedianCut(dim,mid);
    if box2 <> nil then
    begin
      FInferiorBranch := TBGRAColorTree.Create(FLeaf,True);
      FSuperiorBranch := TBGRAColorTree.Create(box2,True);

      FInferiorBranch.FMinBorder := FMinBorder;
      FInferiorBranch.FMaxBorder := FMaxBorder;
      FSuperiorBranch.FMinBorder := FMinBorder;
      FSuperiorBranch.FMaxBorder := FMaxBorder;
      FInferiorBranch.FMaxBorder[dim] := false;
      FSuperiorBranch.FMinBorder[dim] := false;

      FLeaf := nil;
      FIsLeaf:= false;
      FDimension := dim;
      FPixelValueComparer := GetPixelValueComparer(FDimension);
      FSuperiorMiddle := mid;
      result := true;
    end;
  end;
end;

procedure TBGRAColorTree.ComputeLeavesColor(ALeafColor: TBGRALeafColorMode);
var index: integer;
begin
  index := 0;
  if HasPureTransparentColor then
  begin
    FPureTransparentColorIndex:= index;
    inc(index);
  end;
  InternalComputeLeavesColor(ALeafColor,{%H-}index);
end;

procedure TBGRAColorTree.InternalComputeLeavesColor(
  ALeafColor: TBGRALeafColorMode; var AStartIndex: integer);
var nbMin,nbMax: Int32or64;
  c: TColorDimension;
  extremumColor: TBGRAPixel;
  extremumColorRelevant: Boolean;
begin
  if IsLeaf then
  begin
    FLeafColorIndex := AStartIndex;
    inc(AStartIndex);
    if Assigned(FLeaf) then
    begin
      if not FLeafColorComputed then
      begin
        FLeafColorComputed := true;
        FCenterColor.alpha:= min(FLeaf.FBounds[cdAlpha].GetCenter shr AlphaShift, 255);
        FCenterColor.red:= GammaCompressionTab[min(FLeaf.FBounds[cdRed].GetCenter shr RedShift, 65535)];
        FCenterColor.green:= GammaCompressionTab[min(FLeaf.FBounds[cdGreen].GetCenter shr GreenShift, 65535)];
        FCenterColor.blue:= GammaCompressionTab[min(FLeaf.FBounds[cdBlue].GetCenter, 65535)];
        FAverageColor := FLeaf.AverageColorOrMainColor;
        extremumColor := FAverageColor;

        if ALeafColor in [lcMix,lcExtremum] then
        begin
          nbMax := 0;
          nbMin := 0;
          for c := succ(low(TColorDimension)) to high(TColorDimension) do
          begin
            if FMinBorder[c] then inc(nbMin);
            if FMaxBorder[c] then inc(nbMax);
          end;

          if nbMin > nbMax then
            extremumColor := FLeaf.InferiorColor
          else if nbMax > nbMin then
            extremumColor := FLeaf.SuperiorColor;
        end;

        case ALeafColor of
        lcAverage,lcMix: FLeafColor := FAverageColor;
        lcExtremum: FLeafColor := extremumColor;
        else FLeafColor := FCenterColor;
        end;

        if ALeafColor = lcMix then
        begin
          extremumColorRelevant := false;
          for c := succ(low(TColorDimension)) to high(TColorDimension) do
            if UInt32(abs(GetDimensionValue(extremumColor,c) - GetDimensionValue(FLeafColor,c))) >
               FLeaf.FBounds[c].Size div 7 then
            begin
              extremumColorRelevant := true;
              break;
            end;
          if extremumColorRelevant then FLeafColor := extremumColor;
        end;
      end;
    end else
    begin
      FLeafColor := BGRAPixelTransparent;
      FCenterColor := BGRAPixelTransparent;
    end;
  end else
  begin
    if Assigned(FInferiorBranch) then FInferiorBranch.InternalComputeLeavesColor(ALeafColor, AStartIndex);
    if Assigned(FSuperiorBranch) then FSuperiorBranch.InternalComputeLeavesColor(ALeafColor, AStartIndex);
  end;
end;

procedure TBGRAColorTree.CheckColorComputed;
begin
  if not FLeafColorComputed then
    raise exception.Create('Color not computed. Call ComputeLeavesColor first.');
end;

function TBGRAColorTree.ApproximateColor(AColor: TBGRAPixel): TBGRAPixel;
var branch: TBGRAColorTree;
begin
  if AColor.alpha = 0 then
  begin
    result := BGRAPixelTransparent;
    exit;
  end;
  if IsLeaf then
  begin
    CheckColorComputed;
    result := FLeafColor;
  end else
  begin
    if FPixelValueComparer(@AColor,FSuperiorMiddle) then
      branch := FSuperiorBranch else branch := FInferiorBranch;
    if Assigned(branch) then
      result := branch.ApproximateColor(AColor)
    else
      result := BGRAPixelTransparent;
  end;
end;

function TBGRAColorTree.ApproximateColorIndex(AColor: TBGRAPixel): integer;
var branch: TBGRAColorTree;
begin
  if AColor.alpha = 0 then
  begin
    result := FPureTransparentColorIndex;
    exit;
  end;
  if IsLeaf then
  begin
    CheckColorComputed;
    result := FLeafColorIndex;
  end else
  begin
    if FPixelValueComparer(@AColor,FSuperiorMiddle) then
      branch := FSuperiorBranch else branch := FInferiorBranch;
    if Assigned(branch) then
      result := branch.ApproximateColorIndex(AColor)
    else
      result := FPureTransparentColorIndex;
  end;
end;

function TBGRAColorTree.GetAsArrayOfApproximatedColors: ArrayOfTBGRAPixel;
var a,b: ArrayOfTBGRAPixel;
  idx,i: integer;
begin
  if IsLeaf then
  begin
    CheckColorComputed;
    setlength(result,1+byte(HasPureTransparentColor));
    idx := 0;
    if HasPureTransparentColor then
    begin
      result[idx] := BGRAPixelTransparent;
      inc(idx);
    end;
    result[idx] := FLeafColor;
  end else
  begin
    a := FInferiorBranch.GetAsArrayOfApproximatedColors;
    b := FSuperiorBranch.GetAsArrayOfApproximatedColors;
    setlength(result, length(a)+length(b)+byte(HasPureTransparentColor));
    idx := 0;
    if HasPureTransparentColor then
    begin
      result[idx] := BGRAPixelTransparent;
      inc(idx);
    end;
    for i := 0 to high(a) do
    begin
      result[idx] := a[i];
      inc(idx);
    end;
    for i := 0 to high(b) do
    begin
      result[idx] := b[i];
      inc(idx);
    end;
  end;
end;

function TBGRAColorTree.GetAsArrayOfWeightedColors: ArrayOfWeightedColor;
var a,b: ArrayOfWeightedColor;
  idx,i: integer;
begin
  if IsLeaf then
  begin
    CheckColorComputed;
    setlength(result,1+byte(HasPureTransparentColor));
    idx := 0;
    if HasPureTransparentColor then
    begin
      result[idx].Color := BGRAPixelTransparent;
      result[idx].Weight := PureTransparentColorCount;
      inc(idx);
    end;
    result[idx].Color := FLeafColor;
    result[idx].Weight := Weight;
  end else
  begin
    a := FInferiorBranch.GetAsArrayOfWeightedColors;
    b := FSuperiorBranch.GetAsArrayOfWeightedColors;
    setlength(result, length(a)+length(b)+byte(HasPureTransparentColor));
    idx := 0;
    if HasPureTransparentColor then
    begin
      result[idx].Color := BGRAPixelTransparent;
      result[idx].Weight := PureTransparentColorCount;
      inc(idx);
    end;
    for i := 0 to high(a) do
    begin
      result[idx] := a[i];
      inc(idx);
    end;
    for i := 0 to high(b) do
    begin
      result[idx] := b[i];
      inc(idx);
    end;
  end;
end;

procedure TBGRAColorTree.SplitIntoPalette(ACount: integer;
  AMethod: TBiggestLeafMethod; ALeafColor: TBGRALeafColorMode);
var nbColors: integer;
  leaf: TBGRAColorTree;
begin
  nbColors := ApproximatedColorCount;
  while nbColors < ACount do
  begin
    leaf := FindBiggestLeaf(AMethod);
    if not leaf.TrySplitLeaf then break;
    inc(nbColors);
  end;
  ComputeLeavesColor(ALeafColor);
  FreeLeaves;
end;

function TBGRAColorTree.SplitIntoPaletteWithSubPalette(ACount: integer;
  AMethod: TBiggestLeafMethod; ALeafColor: TBGRALeafColorMode;
  ASubPaletteCount: integer): ArrayOfTBGRAPixel;
var nbColors: integer;
  leaf: TBGRAColorTree;
begin
  result := nil;
  nbColors := ApproximatedColorCount;
  if ASubPaletteCount > ACount then ASubPaletteCount:= ACount;
  if nbColors = ASubPaletteCount then
  begin
    ComputeLeavesColor(ALeafColor);
    result := GetAsArrayOfApproximatedColors;
  end;
  while nbColors < ACount do
  begin
    leaf := FindBiggestLeaf(AMethod);
    if not leaf.TrySplitLeaf then break;
    inc(nbColors);
    if nbColors = ASubPaletteCount then
    begin
      ComputeLeavesColor(ALeafColor);
      result := GetAsArrayOfApproximatedColors;
    end;
  end;
  ComputeLeavesColor(ALeafColor);
  FreeLeaves;
end;

function TBGRAColorTree.GetLeafCount: integer;
begin
  if IsLeaf then
    result := 1
  else
  begin
    result := 0;
    if Assigned(FInferiorBranch) then inc(result, FInferiorBranch.LeafCount);
    if Assigned(FSuperiorBranch) then inc(result, FSuperiorBranch.LeafCount);
  end;
end;

function TBGRAColorTree.GetApproximatedColorCount: integer;
begin
  if IsLeaf then
    result := 1
  else
  begin
    result := 0;
    if Assigned(FInferiorBranch) then inc(result, FInferiorBranch.ApproximatedColorCount);
    if Assigned(FSuperiorBranch) then inc(result, FSuperiorBranch.ApproximatedColorCount);
  end;
  if HasPureTransparentColor then inc(result);
end;

function TBGRAColorTree.GetHasPureTransparentColor: boolean;
begin
  result := FPureTransparentColorCount > 0;
end;

procedure TBGRAColorTree.Init(ALeaf: TBGRAColorBox; AOwned: boolean);
var
  c: TColorDimension;
begin
  if not AOwned then
    FLeaf := ALeaf.Duplicate
  else
    FLeaf := ALeaf;
  FLargestApparentInterval:= FLeaf.LargestApparentInterval;
  FWeight := FLeaf.TotalWeight;
  FIsLeaf:= true;
  for c := low(TColorDimension) to high(TColorDimension) do
  begin
    FMinBorder[c] := true;
    FMaxBorder[c] := true;
  end;
  FPureTransparentColorCount:= FLeaf.PureTransparentColorCount;
  FPureTransparentColorIndex:= -1;
end;

constructor TBGRAColorTree.Create(ABox: TBGRAColorBox; AOwned: boolean);
begin
  Init(ABox,AOwned);
end;

constructor TBGRAColorTree.Create(ADimensions: TColorDimensions; APalette: TBGRACustomPalette);
begin
  Init(TBGRAColorBox.Create(ADimensions, APalette),True);
end;

constructor TBGRAColorTree.Create(ADimensions: TColorDimensions; ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption);
begin
  Init(TBGRAColorBox.Create(ADimensions, ABitmap, AAlpha),True);
end;

destructor TBGRAColorTree.Destroy;
begin
  FreeAndNil(FInferiorBranch);
  FreeAndNil(FSuperiorBranch);
  FreeAndNil(FLeaf);
  inherited Destroy;
end;

procedure TBGRAColorTree.FreeLeaves;
begin
  if IsLeaf then
    FreeAndNil(FLeaf)
  else
  begin
    if Assigned(FInferiorBranch) then FInferiorBranch.FreeLeaves;
    if Assigned(FSuperiorBranch) then FSuperiorBranch.FreeLeaves;
  end;
end;

function TBGRAColorTree.FindBiggestLeaf(AMethod: TBiggestLeafMethod
  ): TBGRAColorTree;
var infLeaf,supLeaf: TBGRAColorTree;
begin
  if IsLeaf then
    result := self
  else
  begin
    infLeaf := FInferiorBranch.FindBiggestLeaf(AMethod);
    supLeaf := FSuperiorBranch.FindBiggestLeaf(AMethod);
    case AMethod of
    blApparentInterval:
      if infLeaf.LargestApparentInterval >= supLeaf.LargestApparentInterval then
        result := infLeaf
      else
        result := supLeaf;
    blWeight:
      if (infLeaf.LargestApparentInterval > 0) and (infLeaf.Weight >= supLeaf.Weight) then
        result := infLeaf
      else
        result := supLeaf;
    else{blMix:}
      if (sqrt(infLeaf.Weight/FWeight)*(infLeaf.LargestApparentInterval/LargestApparentInterval) >=
          sqrt(supLeaf.Weight/FWeight)*(supLeaf.LargestApparentInterval/LargestApparentInterval) ) then
        result := infLeaf
      else
        result := supLeaf;
    end;
  end;
end;

{ TDimensionMinMax }

function TDimensionMinMax.Size: UInt32;
begin
  if Maximum>Minimum then
    result := Maximum-Minimum
  else
    result := 0;
end;

function TDimensionMinMax.Contains(AValue: UInt32): boolean;
begin
  result := (AValue >= Minimum) and (AValue <= Maximum);
end;

function TDimensionMinMax.PointLike: boolean;
begin
  result := (Minimum = Maximum);
end;

procedure TDimensionMinMax.SetAsPoint(AValue: UInt32);
begin
  Minimum := AValue;
  Maximum := AValue;
end;

function TDimensionMinMax.GetCenter: UInt32;
begin
  result := (Minimum+Maximum) shr 1;
end;

procedure TDimensionMinMax.GrowToInclude(AValue: UInt32);
begin
  if AValue < Minimum then Minimum := AValue
  else if AValue > Maximum then Maximum := AValue;
end;

{ TBGRAColorBox }

function TBGRAColorBox.GetApparentInterval(ADimension: TColorDimension): UInt32;
var factor: single;
begin
  if not (ADimension in FDimensions) then result := 0
  else
  begin
    factor := 1;
    case ADimension of
    cdRGB: factor := 0.7;
    end;
    result := round(FBounds[ADimension].Size*factor);
  end;
end;

function TBGRAColorBox.GetAverageColor: TBGRAPixel;
var
  n:     integer;
  r, g, b, a: double;
  cura: double;
  w: UInt32;
begin
  a := 0;
  r := 0;
  g := 0;
  b := 0;
  w := 0;
  for n := 0 to high(FColors) do
  with FColors[n].Color do
  begin
    cura := (alpha / 255)*FColors[n].Weight;
    IncF(a, cura);
    IncF(r, GammaExpansionTab[red] * cura);
    IncF(g, GammaExpansionTab[green] * cura);
    IncF(b, GammaExpansionTab[blue] * cura);
    Inc(w, FColors[n].Weight);
  end;
  if w = 0 then
    Result := BGRAPixelTransparent
  else
  begin
    result.alpha := round(a*255/w);
    if result.alpha = 0 then result := BGRAPixelTransparent
    else
    begin
      result.red := GammaCompressionTab[round(r / a)];
      result.green := GammaCompressionTab[round(g / a)];
      result.blue := GammaCompressionTab[round(b / a)];
    end;
  end;
end;

function TBGRAColorBox.GetAverageColorOrMainColor: TBGRAPixel;
var i: integer;
  maxWeight: UInt32;
begin
  result := BGRAPixelTransparent;
  maxWeight:= 0;
  for i := 0 to high(FColors) do
    with FColors[i] do
    begin
      if Weight > maxWeight then
      begin
        maxWeight:= Weight;
        result := Color;
      end;
    end;
  if maxWeight <= 3*FTotalWeight shr 2 then
    result := GetAverageColor;
end;

function TBGRAColorBox.GetBounds(ADimension: TColorDimension): TDimensionMinMax;
begin
  result := FBounds[ADimension];
end;

function TBGRAColorBox.GetColorCount(ACountPureTransparent: boolean): integer;
begin
  result := length(FColors);
  if ACountPureTransparent and HasPureTransparentColor then inc(result);
end;

function TBGRAColorBox.GetHasPureTransparentColor: boolean;
begin
  result := FPureTransparentColorCount > 0;
end;

function TBGRAColorBox.GetInferiorColor: TBGRAPixel;
var
  n:     integer;
  r, g, b, a: double;
  w: UInt32;
  cura: double;
  wantedWeight: UInt32;
begin
  a := 0;
  r := 0;
  g := 0;
  b := 0;
  w := 0;
  wantedWeight:= FTotalWeight div 10;
  for n := 0 to high(FColors) do
  with FColors[n].Color do
  begin
    cura := (alpha / 255)*FColors[n].Weight;
    IncF(a, cura);
    IncF(r, red * cura);
    IncF(g, green * cura);
    IncF(b, blue * cura);
    Inc(w, FColors[n].Weight);
    if w >= wantedWeight then break;
  end;
  if w = 0 then
    Result := BGRAPixelTransparent
  else
  begin
    result.alpha := round(a*255/w);
    if result.alpha = 0 then result := BGRAPixelTransparent
    else
    begin
      result.red := round(r / a);
      result.green := round(g / a);
      result.blue := round(b / a);
    end;
  end;
end;

function TBGRAColorBox.GetLargestApparentDimension: TColorDimension;
var c: TColorDimension;
  curApparentInterval, maxApparentInterval: UInt32;
begin
  c := succ(low(TColorDimension));
  result := c;
  maxApparentInterval:= ApparentInterval[c];
  while c < high(TColorDimension) do
  begin
    inc(c);
    curApparentInterval:= ApparentInterval[c];
    if curApparentInterval > maxApparentInterval then
    begin
      maxApparentInterval:= curApparentInterval;
      result := c;
    end;
  end;
end;

function TBGRAColorBox.GetLargestApparentInterval: UInt32;
var
  curApparentInterval: UInt32;
  c: TColorDimension;
begin
  result:= ApparentInterval[succ(low(TColorDimension))];
  for c := succ(succ(low(TColorDimension))) to high(TColorDimension) do
  begin
    curApparentInterval:= ApparentInterval[c];
    if curApparentInterval > result then
      result := curApparentInterval;
  end;
end;

function TBGRAColorBox.GetPointLike: boolean;
var c: TColorDimension;
begin
  for c := succ(low(TColorDimension)) to high(TColorDimension) do
    if not FBounds[c].PointLike then
    begin
      result := false;
      exit;
    end;
  result := true;
end;

function TBGRAColorBox.GetSuperiorColor: TBGRAPixel;
var
  n:     integer;
  r, g, b, a: double;
  w: UInt32;
  cura: double;
  wantedWeight: UInt32;
begin
  a := 0;
  r := 0;
  g := 0;
  b := 0;
  w := 0;
  wantedWeight:= FTotalWeight div 10;
  for n := high(FColors) downto 0 do
  with FColors[n].Color do
  begin
    cura := (alpha / 255)*FColors[n].Weight;
    IncF(a, cura);
    IncF(r, red * cura);
    IncF(g, green * cura);
    IncF(b, blue * cura);
    Inc(w, FColors[n].Weight);
    if w >= wantedWeight then break;
  end;
  if w = 0 then
    Result := BGRAPixelTransparent
  else
  begin
    result.alpha := round(a*255/w);
    if result.alpha = 0 then result := BGRAPixelTransparent
    else
    begin
      result.red := round(r / a);
      result.green := round(g / a);
      result.blue := round(b / a);
    end;
  end;
end;

procedure TBGRAColorBox.Init(AColors: ArrayOfWeightedColor; AOwner: boolean);
var
  i,idx: Int32or64;
  FirstColor: boolean;
  c: TColorDimension;
begin
  FPureTransparentColorCount:= 0;
  FTotalWeight:= 0;
  for c := low(TColorDimension) to high(TColorDimension) do
    FBounds[c].SetAsPoint(0);
  FirstColor := True;
  if AOwner then
    FColors := AColors
  else
    SetLength(FColors, length(AColors));
  idx := 0;
  for i := 0 to high(AColors) do
  with AColors[i] do
  begin
    if Color.alpha > 0 then
    begin
      if FirstColor then
      begin
        for c := low(TColorDimension) to high(TColorDimension) do
          FBounds[c].SetAsPoint(GetDimensionValue(Color,c));
        FirstColor := false;
      end else
      begin
        for c := low(TColorDimension) to high(TColorDimension) do
          FBounds[c].GrowToInclude(GetDimensionValue(Color,c));
      end;
      inc(FTotalWeight, Weight);
      if not AOwner or (idx <> i) then
        FColors[idx] := AColors[i];
      inc(idx);
    end else
      inc(FPureTransparentColorCount, Weight);
  end;
  setlength(FColors,idx);
end;

procedure TBGRAColorBox.SortBy(ADimension: TColorDimension);
var comparer: TIsChannelStrictlyGreaterFunc;
begin
  comparer := GetPixelStrictComparer(ADimension);
  if comparer = nil then exit;
  ArrayOfWeightedColor_QuickSort(FColors,0,high(FColors),comparer)
end;

function TBGRAColorBox.GetMedianIndex(ADimension: TColorDimension;
    AMinValue, AMaxValue: UInt32
  ): integer;
var i: integer;
  sum,goal: UInt32;
  valueComparer: TIsChannelGreaterThanOrEqualToValueFunc;
  strictComparer: TIsChannelStrictlyGreaterFunc;
  ofs: integer;
begin
  if length(FColors) = 1 then
  begin
    result := 0;
    exit;
  end else
  if length(FColors) = 0 then
  begin
    result := -1;
    exit;
  end;
  valueComparer:= GetPixelValueComparer(ADimension);
  sum := 0;
  goal := (FTotalWeight+1) shr 1;
  result := high(FColors) shr 1;
  for i := 0 to high(FColors) do
  begin
    inc(sum, FColors[i].Weight);
    if (sum>=goal) and (valueComparer(@FColors[i].Color, AMinValue)) then
    begin
      result := i;
      while (result > 0) and (valueComparer(@FColors[result].Color, AMaxValue+1)) do dec(result);
      break;
    end;
  end;
  if result = 0 then inc(result);
  //check that there it is not splitting consecutive colors with the same value
  strictComparer := GetPixelStrictComparer(ADimension);
  ofs := 0;
  while true do
  begin
    if (result-ofs < 1) and (result+ofs > high(FColors)) then break;
    if (result-ofs >= 1) and strictComparer(@FColors[result-ofs].Color,@FColors[result-ofs-1].Color) then
    begin
      result := result-ofs;
      exit;
    end;
    if (result+ofs <= high(FColors)) and strictComparer(@FColors[result+ofs].Color,@FColors[result+ofs-1].Color) then
    begin
      result := result+ofs;
      exit;
    end;
    inc(ofs);
  end;
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions; AColors: ArrayOfWeightedColor; AOwner: boolean);
begin
  FDimensions:= ADimensions;
  Init(AColors,AOwner);
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions;
  const AColors: ArrayOfTBGRAPixel; AAlpha: TAlphaChannelPaletteOption = acFullChannelInPalette);
var weightedColors: ArrayOfWeightedColor;
  i: Integer;
begin
  if AAlpha = acFullChannelInPalette then
  begin
    FDimensions:= ADimensions;
    setlength(weightedColors, length(AColors));
    for i := 0 to high(weightedColors) do
    with weightedColors[i] do
    begin
      color := AColors[i];
      Weight:= 1;
    end;
    Init(weightedColors,True);
  end else
    Create(ADimensions, @AColors[0], length(AColors), AAlpha);
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions; ABounds: TColorBoxBounds);
begin
  FDimensions:= ADimensions;
  FBounds := ABounds;
  FTotalWeight:= 0;
  FPureTransparentColorCount:= 0;
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions; APalette: TBGRACustomPalette);
begin
  FDimensions:= ADimensions;
  Init(APalette.GetAsArrayOfWeightedColor,False);
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions;
  ABitmap: TBGRACustomBitmap; AAlpha: TAlphaChannelPaletteOption);
begin
  Create(ADimensions, ABitmap.Data, ABitmap.NbPixels, AAlpha);
end;

constructor TBGRAColorBox.Create(ADimensions: TColorDimensions; AColors: PBGRAPixel; ANbPixels: integer; AAlpha: TAlphaChannelPaletteOption);
var i,j,prev,idx: integer;
  p: PBGRAPixel;
  skip: boolean;
  alphaMask: LongWord;
  transpIndex: integer;
begin
  if AAlpha <> acFullChannelInPalette then
    alphaMask := LEtoN($FF000000)
  else
    alphaMask := 0;
  FDimensions:= ADimensions;
  transpIndex := -1;
  SetLength(FColors,ANbPixels);
  if length(FColors)>0 then
  begin
    p := AColors;
    idx := 0;
    for i := 0 to ANbPixels-1 do
    begin
      if (p^.alpha = 0) or ((AAlpha = acTransparentEntry) and (p^.alpha < 128)) then
      begin
        skip := true;
        if not (AAlpha = acIgnore) then
        begin
          if (transpIndex=-1) then
          begin
            transpIndex := idx;
            with FColors[idx] do
            begin
              Color := BGRAPixelTransparent;
              Weight:= 1;
            end;
            inc(idx);
          end else
            inc(FColors[transpIndex].Weight);
        end;
        if (p^.alpha = 0) then
        begin
          inc(p);
          continue;
        end;
      end;
      skip := false;
      for j := idx-1 downto idx-10 do
        if j < 0 then
          break
        else
        with FColors[j] do
        if LongWord(Color)=LongWord(p^) or alphaMask then
        begin
          skip := true;
          inc(Weight);
          break;
        end;
      if skip then
      begin
        inc(p);
        continue;
      end;
      with FColors[idx] do
      begin
        Color := p^;
        if AAlpha <> acFullChannelInPalette then Color.alpha := 255;
        Weight := 1;
        inc(p);
        inc(idx);
      end;
    end;
    setLength(FColors, idx);

    ArrayOfWeightedColor_QuickSort(FColors,0,high(FColors),@IsDWordGreater);
    prev := 0;
    for i := 1 to high(FColors) do
    begin
      if LongWord(FColors[i].Color)=LongWord(FColors[prev].Color) then
        inc(FColors[prev].Weight, FColors[i].Weight)
      else
      begin
        inc(prev);
        if i <> prev then
          FColors[prev] := FColors[i];
      end;
    end;
    setlength(FColors, prev+1);
  end;
  Init(FColors,True);
end;

function TBGRAColorBox.BoundsContain(AColor: TBGRAPixel): boolean;
var c: TColorDimension;
begin
  for c := succ(low(TColorDimension)) to high(TColorDimension) do
    if not FBounds[c].Contains(GetDimensionValue(AColor,c)) then
    begin
      result := false;
      exit;
    end;
  result := true;
end;

function TBGRAColorBox.MedianCut(ADimension: TColorDimension; out SuperiorMiddle: UInt32
  ): TBGRAColorBox;
var idxSplit: Int32or64;
  secondArray: ArrayOfWeightedColor;
  i: Int32or64;
begin
  result := nil;
  SuperiorMiddle := 0;
  if FBounds[ADimension].PointLike then exit;
  if length(FColors) <= 1 then exit;
  SortBy(ADimension);
  idxSplit := GetMedianIndex(ADimension,
    round(FBounds[ADimension].Minimum*(1-MedianMinPercentage)+FBounds[ADimension].Maximum*MedianMinPercentage),
    round(FBounds[ADimension].Minimum*MedianMinPercentage+FBounds[ADimension].Maximum*(1-MedianMinPercentage)));
  if idxSplit = -1 then exit;
  setlength(secondArray, length(FColors)-idxSplit);
  for i := idxSplit to high(FColors) do
    secondArray[i-idxSplit] := FColors[i];
  result := TBGRAColorBox.Create(FDimensions, secondArray,True);
  setlength(FColors, idxSplit);
  Init(FColors,True);
  SuperiorMiddle := (FBounds[ADimension].Maximum + result.FBounds[ADimension].Minimum + 1) shr 1;
end;

function TBGRAColorBox.Duplicate: TBGRAColorBox;
var
  i: Int32or64;
begin
  result := TBGRAColorBox.Create(FDimensions, FBounds);
  result.FTotalWeight := FTotalWeight;
  setlength(result.FColors, length(FColors));
  for i := 0 to high(FColors) do
    result.FColors[i] := FColors[i];
end;

function TBGRAColorBox.GetAsArrayOfColors(AIncludePureTransparent: boolean): ArrayOfTBGRAPixel;
var i,idx: integer;
begin
  if AIncludePureTransparent and HasPureTransparentColor then
  begin
    setlength(result, length(FColors)+1);
    result[0] := BGRAPixelTransparent;
    idx := 1;
  end else
  begin
    setlength(result, length(FColors));
    idx := 0;
  end;
  for i:= 0 to high(FColors) do
  begin
    result[idx] := FColors[i].Color;
    inc(idx);
  end;
end;

end.