// (Triforce, 11-29) ASTC block encoding (2D, LDR, one partition, one weight plane), for recolouring the game's textures: a
// texture is decoded with Astc.Decompress, recoloured, and the blocks whose texels changed are encoded again here. A block
// gets direct endpoints, CEM 8 (RGB) when every alpha in it is 255 and CEM 12 (RGBA) otherwise; a block of one colour is a
// void extent. The block modes, the trit and quint packing and the unquantised endpoint and weight values are all taken
// from the decoder's own code in Astc.cs (its block mode decoding, its trit/quint decoding enumerated backwards, its
// unquantisation), and the error of a fit is worked out with the decoder's own integer arithmetic, so what is written
// here decodes there as it was fitted.
//
// Per block: the principal axis of the texels gives the starting endpoints. Every legal weight grid and weight range for
// the footprint is scored quickly (grid weights fitted by least squares through the decoder's bilinear infill, endpoints
// rounded to the colour range the remaining bits leave), and the best few are refined over a few rounds: weights by
// projection onto the actual unquantised endpoints, grid weights moved a level at a time while that lowers the error,
// endpoints by least squares on the decoded weights, then moved a level at a time the same way. The best fit wins.
using System.Collections.Concurrent;
namespace Triforce.Core.GameFiles;
/// ASTC encoding of RGBA8 blocks and images (2D, LDR, single partition).
public static class AstcEncode
{
/// How many of the quickly scored block modes are refined fully.
const int Candidates = 8;
/// Refinement rounds per candidate.
const int Rounds = 4;
// ---- bits ----
/// Writes the low n bits of val at bit pos (bits counted from the low bit of the first byte upward).
static void PutBits(Span buf, int pos, uint val, int n)
{
for (var i = 0; i < n; i++, pos++)
{
var mask = (byte)(1 << (pos & 7));
if (((val >> i) & 1) != 0)
buf[pos >> 3] |= mask;
else
buf[pos >> 3] &= (byte)~mask;
}
}
// ---- bounded integer sequences ----
/// Five trits (t0 + 3 t1 + 9 t2 + 27 t3 + 81 t4) to the 8 packed bits the decoder reads back as them.
static readonly byte[] TritPack = MakePack(true);
/// Three quints (q0 + 5 q1 + 25 q2) to the 7 packed bits the decoder reads back as them.
static readonly byte[] QuintPack = MakePack(false);
/// The packing table, by running the decoder's own trit or quint block decoding over every packed value (with
/// no plain bits, the packed bits are read in order). Where several packed values give the same digits the smallest is
/// kept, which is the one whose top bits are zero when the last digits are zero padding (a short last group drops
/// those bits).
static byte[] MakePack(bool trits)
{
var digits = trits ? 5 : 3;
var count = trits ? 243 : 125;
var pack = new byte[count];
var seen = new bool[count];
var vec = new Astc.EncodedVector();
var one = new byte[1];
for (var packed = (trits ? 256 : 128) - 1; packed >= 0; packed--)
{
one[0] = (byte)packed;
vec.Clear();
var s = new Astc.InputBitStream(one);
if (trits)
Astc.DecodeTritBlock(ref s, vec, 0);
else
Astc.DecodeQuintBlock(ref s, vec, 0);
var idx = 0;
for (var i = digits - 1; i >= 0; i--)
idx = idx * (trits ? 3 : 5) + (int)vec.Items[i].QuintOrTritValue;
pack[idx] = (byte)packed;
seen[idx] = true;
}
if (Array.IndexOf(seen, false) >= 0)
throw new InvalidOperationException("ASTC " + (trits ? "trit" : "quint") + " packing does not cover every value");
return pack;
}
/// The values (each below the encoding's number of levels) written from bit pos as the decoder's
/// DecodeIntegerSequence reads them; returns the bit after the last one written.
static int WriteIse(Span buf, int pos, ReadOnlySpan values, Astc.IntegerEncodedValue enc)
{
var n = enc.NumBits;
var mask = (1 << n) - 1;
var total = enc.GetBitLength(values.Length);
Span tmp = stackalloc byte[64];
tmp.Clear();
Span m = stackalloc int[5];
Span d = stackalloc int[5];
var p = 0;
switch (enc.Encoding)
{
case Astc.IntegerEncoding.JustBits:
foreach (var v in values)
{
PutBits(tmp, p, (uint)v, n);
p += n;
}
break;
case Astc.IntegerEncoding.Trit:
for (var g = 0; g < values.Length; g += 5)
{
for (var i = 0; i < 5; i++)
{
var v = g + i < values.Length ? values[g + i] : 0;
m[i] = v & mask;
d[i] = v >> n;
}
uint T = TritPack[d[0] + 3 * d[1] + 9 * d[2] + 27 * d[3] + 81 * d[4]];
PutBits(tmp, p, (uint)m[0], n); p += n;
PutBits(tmp, p, T & 3, 2); p += 2;
PutBits(tmp, p, (uint)m[1], n); p += n;
PutBits(tmp, p, (T >> 2) & 3, 2); p += 2;
PutBits(tmp, p, (uint)m[2], n); p += n;
PutBits(tmp, p, (T >> 4) & 1, 1); p += 1;
PutBits(tmp, p, (uint)m[3], n); p += n;
PutBits(tmp, p, (T >> 5) & 3, 2); p += 2;
PutBits(tmp, p, (uint)m[4], n); p += n;
PutBits(tmp, p, (T >> 7) & 1, 1); p += 1;
}
break;
case Astc.IntegerEncoding.Quint:
for (var g = 0; g < values.Length; g += 3)
{
for (var i = 0; i < 3; i++)
{
var v = g + i < values.Length ? values[g + i] : 0;
m[i] = v & mask;
d[i] = v >> n;
}
uint Q = QuintPack[d[0] + 5 * d[1] + 25 * d[2]];
PutBits(tmp, p, (uint)m[0], n); p += n;
PutBits(tmp, p, Q & 7, 3); p += 3;
PutBits(tmp, p, (uint)m[1], n); p += n;
PutBits(tmp, p, (Q >> 3) & 3, 2); p += 2;
PutBits(tmp, p, (uint)m[2], n); p += n;
PutBits(tmp, p, (Q >> 5) & 3, 2); p += 2;
}
break;
}
// (a short last group is cut to the sequence's length, as the spec counts it)
for (var i = 0; i < total; i++)
PutBits(buf, pos + i, (uint)(tmp[i >> 3] >> (i & 7)) & 1, 1);
return pos + total;
}
/// The number of levels an encoding has (2^n, 3 * 2^n or 5 * 2^n).
static int Levels(Astc.IntegerEncodedValue enc) => enc.Encoding switch
{
Astc.IntegerEncoding.Trit => 3 << enc.NumBits,
Astc.IntegerEncoding.Quint => 5 << enc.NumBits,
_ => 1 << enc.NumBits,
};
// ---- quantisation ----
/// One quantisation range: its codes, what each unquantises to, and the way back.
sealed class Quant
{
public readonly Astc.IntegerEncodedValue Enc;
public readonly int Levels;
/// Code to unquantised value.
public readonly int[] Unq;
/// The codes in order of their unquantised values.
public readonly int[] Sorted;
/// Code to its place in Sorted.
public readonly int[] Rank;
/// A value (0 to the top) to the code that unquantises nearest it.
public readonly int[] Nearest;
public Quant(Astc.IntegerEncodedValue enc, int[] unq, int top)
{
Enc = enc;
Levels = unq.Length;
Unq = unq;
Sorted = Enumerable.Range(0, Levels).OrderBy(c => unq[c]).ThenBy(c => c).ToArray();
Rank = new int[Levels];
for (var i = 0; i < Levels; i++)
Rank[Sorted[i]] = i;
Nearest = new int[top + 1];
for (var v = 0; v <= top; v++)
{
var best = 0;
for (var c = 1; c < Levels; c++)
if (Math.Abs(unq[c] - v) < Math.Abs(unq[best] - v))
best = c;
Nearest[v] = best;
}
}
}
/// The weight ranges a block mode can name (its largest weight), each with the decoder's unquantised weights.
static readonly Dictionary WeightQuants = MakeWeightQuants();
static Dictionary MakeWeightQuants()
{
var d = new Dictionary();
foreach (var max in new uint[] { 1, 2, 3, 4, 5, 7, 9, 11, 15, 19, 23, 31 })
{
var enc = Astc.Encodings[max];
if (Levels(enc) != max + 1)
throw new InvalidOperationException("ASTC weight range " + max + " has no exact encoding");
var unq = new int[max + 1];
for (var v = 0; v <= max; v++)
unq[v] = (int)Astc.UnquantizeTexelWeight(new Astc.IntegerEncodedValue(enc.Encoding, enc.NumBits)
{
BitValue = (uint)(v & ((1 << enc.NumBits) - 1)),
QuintOrTritValue = (uint)(v >> enc.NumBits),
});
d[max] = new Quant(enc, unq, 64);
}
return d;
}
static readonly Dictionary ColourQuants = new();
/// The colour range of that many levels, its unquantised values found by encoding each code (all the block's
/// endpoint values set to it) and running the decoder's DecodeColorValues on it, with the bits that chose this range.
static Quant ColourQuant(int levels, uint cem, int nValues, int colourBits)
{
lock (ColourQuants)
{
if (ColourQuants.TryGetValue(levels, out var q))
return q;
var enc = Astc.Encodings[levels - 1];
var unq = new int[levels];
var data = new byte[16];
var values = new int[nValues];
var output = new uint[32];
var vec = new Astc.EncodedVector();
for (var v = 0; v < levels; v++)
{
Array.Fill(values, v);
Array.Clear(data);
WriteIse(data, 0, values, enc);
Astc.DecodeColorValues(output, data, new[] { cem }, 1, colourBits, vec);
for (var i = 1; i < nValues; i++)
if (output[i] != output[0])
throw new InvalidOperationException("ASTC colour value packing does not read back");
unq[v] = (int)output[0];
}
q = new Quant(enc, unq, 255);
ColourQuants[levels] = q;
return q;
}
}
/// The number of levels the decoder gives nValues endpoint values in that many bits (DecodeColorValues' search:
/// the largest range that fits), or 0.
static int ColourLevels(int nValues, int bits)
{
var range = 256;
while (--range > 0)
{
var val = Astc.Encodings[range];
if (val.GetBitLength(nValues) <= bits)
{
while (--range > 0)
{
if (!Astc.Encodings[range].MatchesEncoding(val))
break;
}
range++;
break;
}
}
if (range <= 0)
return 0;
var levels = Levels(Astc.Encodings[range]);
return levels - 1 == range ? levels : 0;
}
// ---- footprints ----
/// A weight grid on a footprint: the decoder's bilinear infill per texel, and its least squares inverse.
sealed class Grid
{
public int W, H, Count, Index;
/// Per texel, four grid points and their weights out of 16 (a point past the grid has weight 0).
public int[] Idx = Array.Empty(), Fac = Array.Empty();
/// The grid is the footprint itself, one weight per texel.
public bool Identity;
/// Count x texels: the grid weights whose infill is nearest (least squares) a set of texel weights.
public double[] Fit = Array.Empty();
/// Per grid point, the texels its weight reaches.
public int[][] Touch = Array.Empty();
}
/// One usable block mode: its 11 bits, grid, weight range and the colour range that leaves.
sealed class Mode
{
public uint Bits;
public Grid Grid = null!;
public Quant Weights = null!, Colours = null!;
public int WeightBits;
}
sealed class Footprint
{
public int Bw, Bh, T;
public Grid[] Grids = Array.Empty();
public Mode[] Rgb = Array.Empty(), Rgba = Array.Empty();
}
static readonly ConcurrentDictionary> Footprints = new();
static Footprint GetFootprint(int bw, int bh) =>
Footprints.GetOrAdd(bw * 16 + bh, _ => new Lazy(() => MakeFootprint(bw, bh))).Value;
/// Every block mode the decoder accepts for this footprint that is single plane and within the spec's limits
/// (at most 64 weights, 24 to 96 weight bits, a colour range of at least 6 levels), found by running all 2048 mode values
/// through the decoder's own block mode decoding.
static Footprint MakeFootprint(int bw, int bh)
{
var grids = new Dictionary<(uint, uint), Grid>();
var seen = new HashSet<(uint, uint, uint)>();
var rgb = new List();
var rgba = new List();
var bits = new byte[16];
for (var m = 0u; m < 2048; m++)
{
Array.Clear(bits);
bits[0] = (byte)m;
bits[1] = (byte)(m >> 8);
var s = new Astc.InputBitStream(bits);
var p = Astc.DecodeBlockInfo(ref s);
if (p.Error || p.VoidExtentLDR || p.VoidExtentHDR || p.DualPlane || p.Width > bw || p.Height > bh)
continue;
var weightBits = p.GetPackedBitSize();
if (p.Width * p.Height > 64 || weightBits < 24 || weightBits > 96 || !seen.Add((p.Width, p.Height, p.MaxWeight)))
continue;
if (!grids.TryGetValue((p.Width, p.Height), out var grid))
{
grid = MakeGrid(bw, bh, (int)p.Width, (int)p.Height);
grid.Index = grids.Count;
grids[(p.Width, p.Height)] = grid;
}
var colourBits = 128 - 17 - weightBits;
foreach (var cem in new uint[] { 8, 12 })
{
var nValues = cem == 8 ? 6 : 8;
var levels = ColourLevels(nValues, colourBits);
if (levels < 6)
continue;
var mode = new Mode
{
Bits = m,
Grid = grid,
Weights = WeightQuants[p.MaxWeight],
Colours = ColourQuant(levels, cem, nValues, colourBits),
WeightBits = weightBits,
};
(cem == 8 ? rgb : rgba).Add(mode);
}
}
return new Footprint
{
Bw = bw,
Bh = bh,
T = bw * bh,
Grids = grids.Values.OrderBy(g => g.Index).ToArray(),
Rgb = rgb.ToArray(),
Rgba = rgba.ToArray(),
};
}
/// The decoder's weight infill (UnquantizeTexelWeights) for a grid on a footprint, and its inverse.
static Grid MakeGrid(int bw, int bh, int gw, int gh)
{
var T = bw * bh;
var count = gw * gh;
var g = new Grid { W = gw, H = gh, Count = count, Idx = new int[T * 4], Fac = new int[T * 4] };
var Ds = (uint)((1024 + bw / 2) / (bw - 1));
var Dt = (uint)((1024 + bh / 2) / (bh - 1));
for (var t = 0; t < bh; t++)
for (var s = 0; s < bw; s++)
{
var cs = Ds * (uint)s;
var ct = Dt * (uint)t;
var gs = (cs * (uint)(gw - 1) + 32) >> 6;
var gt = (ct * (uint)(gh - 1) + 32) >> 6;
var js = gs >> 4;
var fs = gs & 0xF;
var jt = gt >> 4;
var ft = gt & 0xF;
var w11 = (fs * ft + 8) >> 4;
var w10 = ft - w11;
var w01 = fs - w11;
var w00 = 16 - fs - ft + w11;
var v0 = js + jt * (uint)gw;
var at = (t * bw + s) * 4;
for (var k = 0; k < 4; k++)
{
var i = v0 + (k == 1 || k == 3 ? 1u : 0u) + (k >= 2 ? (uint)gw : 0u);
var f = k switch { 0 => w00, 1 => w01, 2 => w10, _ => w11 };
// (the decoder reads a point past the grid as 0)
var inside = i < (uint)count;
g.Idx[at + k] = inside ? (int)i : 0;
g.Fac[at + k] = inside ? (int)f : 0;
}
}
g.Identity = gw == bw && gh == bh;
for (var t = 0; t < T && g.Identity; t++)
if (g.Idx[t * 4] != t || g.Fac[t * 4] != 16)
g.Identity = false;
var touch = Enumerable.Range(0, count).Select(_ => new List()).ToArray();
for (var t = 0; t < T; t++)
for (var k = 0; k < 4; k++)
if (g.Fac[t * 4 + k] > 0 && !touch[g.Idx[t * 4 + k]].Contains(t))
touch[g.Idx[t * 4 + k]].Add(t);
g.Touch = touch.Select(l => l.ToArray()).ToArray();
if (!g.Identity)
{
// (A: texels x grid points, the infill as fractions; Fit = (A'A + small)^-1 A')
var a = new double[T * count];
for (var t = 0; t < T; t++)
for (var k = 0; k < 4; k++)
a[t * count + g.Idx[t * 4 + k]] += g.Fac[t * 4 + k] / 16.0;
var n = count;
var mtm = new double[n * 2 * n];
for (var i = 0; i < n; i++)
{
for (var j = 0; j < n; j++)
{
double sum = 0;
for (var t = 0; t < T; t++)
sum += a[t * n + i] * a[t * n + j];
mtm[i * 2 * n + j] = sum + (i == j ? 1e-4 : 0);
}
mtm[i * 2 * n + n + i] = 1;
}
Invert(mtm, n);
g.Fit = new double[n * T];
for (var i = 0; i < n; i++)
for (var t = 0; t < T; t++)
{
double sum = 0;
for (var j = 0; j < n; j++)
sum += mtm[i * 2 * n + n + j] * a[t * n + j];
g.Fit[i * T + t] = sum;
}
}
return g;
}
/// Gauss-Jordan elimination on an n x 2n matrix [M | I], leaving [I | M^-1].
static void Invert(double[] m, int n)
{
var w = 2 * n;
for (var c = 0; c < n; c++)
{
var piv = c;
for (var r = c + 1; r < n; r++)
if (Math.Abs(m[r * w + c]) > Math.Abs(m[piv * w + c]))
piv = r;
if (piv != c)
for (var k = 0; k < w; k++)
(m[c * w + k], m[piv * w + k]) = (m[piv * w + k], m[c * w + k]);
var d = m[c * w + c];
for (var k = 0; k < w; k++)
m[c * w + k] /= d;
for (var r = 0; r < n; r++)
{
if (r == c)
continue;
var f = m[r * w + c];
if (f == 0)
continue;
for (var k = 0; k < w; k++)
m[r * w + k] -= f * m[c * w + k];
}
}
}
// ---- the decoder's arithmetic ----
/// One channel of a texel from two endpoint bytes and a weight 0..64, exactly as the decoder makes it.
static int Interp(int e0, int e1, int w)
{
var c0 = (uint)e0 * 257u;
var c1 = (uint)e1 * 257u;
var c = (c0 * (uint)(64 - w) + c1 * (uint)w + 32) / 64;
return c == 65535 ? 255 : (int)(255.0 * (c / 65536.0) + 0.5);
}
/// A texel's weight from the unquantised grid weights, as the decoder infills it.
static int InfillOne(Grid g, int[] gunq, int t)
{
var b = t * 4;
return (gunq[g.Idx[b]] * g.Fac[b] + gunq[g.Idx[b + 1]] * g.Fac[b + 1] + gunq[g.Idx[b + 2]] * g.Fac[b + 2]
+ gunq[g.Idx[b + 3]] * g.Fac[b + 3] + 8) >> 4;
}
// ---- per thread working memory ----
sealed class Work
{
public readonly int[] Px = new int[144 * 4];
public readonly double[] Ideal = new double[144];
public readonly double[][] GridFits = Enumerable.Range(0, 128).Select(_ => new double[64]).ToArray();
public readonly bool[] GridDone = new bool[128];
public readonly double[] GridF = new double[64];
public readonly int[] GCodes = new int[64], GUnq = new int[64], BestG = new int[64], CandG = new int[64];
public readonly int[] Tw = new int[144], Terr = new int[144];
public readonly int[] Lut = new int[4 * 65], LutTry = new int[65];
public readonly int[] C0 = new int[4], C1 = new int[4], BestC0 = new int[4], BestC1 = new int[4];
public readonly int[] CandC0 = new int[4], CandC1 = new int[4];
public readonly double[] E0 = new double[4], E1 = new double[4];
public long[] Quick = new long[256];
public int[] Order = new int[256];
}
[ThreadStatic] static Work? work;
// ---- the encoder ----
/// texels: blockWidth * blockHeight RGBA8 texels of one block, row-major. Returns 16 bytes: one ASTC block
/// (2D, LDR, single partition).
public static byte[] EncodeBlock(ReadOnlySpan texels, int blockWidth, int blockHeight)
{
var block = new byte[16];
EncodeBlock(texels, blockWidth, blockHeight, block);
return block;
}
/// A whole image (width x height RGBA8, row-major) to linear-order ASTC blocks (blocks in rows, 16 bytes each),
/// the edge blocks padded by repeating the last row and column. Rows of blocks are encoded on several threads.
public static byte[] Encode(ReadOnlySpan rgba, int width, int height, int blockWidth, int blockHeight)
{
CheckFootprint(blockWidth, blockHeight);
ImageLimits.Check(width, height);
if (rgba.Length < (long)width * height * 4)
throw new ArgumentException("the image is shorter than " + width + " x " + height + " RGBA8", nameof(rgba));
var cols = (width + blockWidth - 1) / blockWidth;
var rows = (height + blockHeight - 1) / blockHeight;
var src = rgba[..(width * height * 4)].ToArray();
var output = new byte[cols * rows * 16];
GetFootprint(blockWidth, blockHeight);
Parallel.For(0, rows, () => new byte[blockWidth * blockHeight * 4], (by, _, texels) =>
{
for (var bx = 0; bx < cols; bx++)
{
for (var y = 0; y < blockHeight; y++)
{
var sy = Math.Min(by * blockHeight + y, height - 1);
for (var x = 0; x < blockWidth; x++)
{
var sx = Math.Min(bx * blockWidth + x, width - 1);
Buffer.BlockCopy(src, (sy * width + sx) * 4, texels, (y * blockWidth + x) * 4, 4);
}
}
EncodeBlock(texels, blockWidth, blockHeight, output.AsSpan((by * cols + bx) * 16, 16));
}
return texels;
}, _ => { });
return output;
}
static void CheckFootprint(int bw, int bh)
{
if (bw < 4 || bw > 12 || bh < 4 || bh > 12)
throw new NotSupportedException("ASTC block " + bw + "x" + bh);
}
/// One block encoded into dest (16 bytes).
static void EncodeBlock(ReadOnlySpan texels, int bw, int bh, Span dest)
{
CheckFootprint(bw, bh);
var T = bw * bh;
if (texels.Length < T * 4)
throw new ArgumentException("a " + bw + "x" + bh + " block needs " + T * 4 + " bytes of texels", nameof(texels));
dest[..16].Clear();
// (one colour: a void extent block)
var solid = true;
var hasAlpha = false;
for (var t = 0; t < T; t++)
{
if (texels[t * 4 + 3] != 255)
hasAlpha = true;
if (solid && (texels[t * 4] != texels[0] || texels[t * 4 + 1] != texels[1] || texels[t * 4 + 2] != texels[2]
|| texels[t * 4 + 3] != texels[3]))
solid = false;
}
if (solid)
{
WriteVoidExtent(dest, texels[0], texels[1], texels[2], texels[3]);
return;
}
var fp = GetFootprint(bw, bh);
var modes = hasAlpha ? fp.Rgba : fp.Rgb;
var C = hasAlpha ? 4 : 3;
var wk = work ??= new Work();
var px = wk.Px;
for (var t = 0; t < T; t++)
for (var c = 0; c < 4; c++)
px[t * 4 + c] = texels[t * 4 + c];
PrincipalEndpoints(wk, T, C);
Project(wk, wk.E0, wk.E1, T, C);
// (every mode scored quickly)
if (wk.Quick.Length < modes.Length)
{
wk.Quick = new long[modes.Length];
wk.Order = new int[modes.Length];
}
Array.Clear(wk.GridDone);
for (var i = 0; i < modes.Length; i++)
{
wk.Quick[i] = QuickError(wk, modes[i], T, C);
wk.Order[i] = i;
}
Array.Sort(wk.Quick, wk.Order, 0, modes.Length);
// (the best few refined)
var best = long.MaxValue;
Mode? bestMode = null;
for (var i = 0; i < Math.Min(Candidates, modes.Length); i++)
{
var mode = modes[wk.Order[i]];
var err = Refine(wk, mode, T, C);
if (err < best)
{
best = err;
bestMode = mode;
Array.Copy(wk.CandC0, wk.BestC0, 4);
Array.Copy(wk.CandC1, wk.BestC1, 4);
Array.Copy(wk.CandG, wk.BestG, mode.Grid.Count);
}
}
WriteBlock(dest, bestMode!, hasAlpha, wk.BestC0, wk.BestC1, wk.BestG);
}
/// The ends of the texels' principal axis (power iteration on their covariance), clamped to 0..255 and ordered
/// so the second has the larger RGB sum (the decoder swaps and blue-contracts otherwise).
static void PrincipalEndpoints(Work wk, int T, int C)
{
var px = wk.Px;
Span mean = stackalloc double[4];
mean.Clear();
for (var t = 0; t < T; t++)
for (var c = 0; c < C; c++)
mean[c] += px[t * 4 + c];
for (var c = 0; c < C; c++)
mean[c] /= T;
Span cov = stackalloc double[16];
cov.Clear();
for (var t = 0; t < T; t++)
for (var i = 0; i < C; i++)
{
var di = px[t * 4 + i] - mean[i];
for (var j = 0; j < C; j++)
cov[i * 4 + j] += di * (px[t * 4 + j] - mean[j]);
}
// (start from the column of the channel that varies most)
var top = 0;
for (var c = 1; c < C; c++)
if (cov[c * 4 + c] > cov[top * 4 + top])
top = c;
Span v = stackalloc double[4];
Span nv = stackalloc double[4];
for (var c = 0; c < C; c++)
v[c] = cov[c * 4 + top];
for (var it = 0; it < 16; it++)
{
double len = 0;
for (var c = 0; c < C; c++)
len += v[c] * v[c];
len = Math.Sqrt(len);
if (len < 1e-12)
{
v.Clear();
v[top] = 1;
break;
}
for (var c = 0; c < C; c++)
v[c] /= len;
for (var i = 0; i < C; i++)
{
double sum = 0;
for (var j = 0; j < C; j++)
sum += cov[i * 4 + j] * v[j];
nv[i] = sum;
}
nv[..C].CopyTo(v);
}
{
double len = 0;
for (var c = 0; c < C; c++)
len += v[c] * v[c];
len = Math.Sqrt(len);
if (len < 1e-12)
{
v.Clear();
v[top] = 1;
len = 1;
}
for (var c = 0; c < C; c++)
v[c] /= len;
}
double tmin = double.MaxValue, tmax = double.MinValue;
for (var t = 0; t < T; t++)
{
double d = 0;
for (var c = 0; c < C; c++)
d += (px[t * 4 + c] - mean[c]) * v[c];
tmin = Math.Min(tmin, d);
tmax = Math.Max(tmax, d);
}
for (var c = 0; c < 4; c++)
{
wk.E0[c] = c < C ? Math.Clamp(mean[c] + tmin * v[c], 0, 255) : 255;
wk.E1[c] = c < C ? Math.Clamp(mean[c] + tmax * v[c], 0, 255) : 255;
}
if (wk.E1[0] + wk.E1[1] + wk.E1[2] < wk.E0[0] + wk.E0[1] + wk.E0[2])
for (var c = 0; c < 4; c++)
(wk.E0[c], wk.E1[c]) = (wk.E1[c], wk.E0[c]);
}
/// Each texel's weight (0..64, fractional) by projection onto the segment from e0 to e1, into wk.Ideal.
static void Project(Work wk, ReadOnlySpan e0, ReadOnlySpan e1, int T, int C)
{
Span d = stackalloc double[4];
double len2 = 0;
for (var c = 0; c < C; c++)
{
d[c] = e1[c] - e0[c];
len2 += d[c] * d[c];
}
for (var t = 0; t < T; t++)
{
if (len2 < 1e-9)
{
wk.Ideal[t] = 0;
continue;
}
double dot = 0;
for (var c = 0; c < C; c++)
dot += (wk.Px[t * 4 + c] - e0[c]) * d[c];
wk.Ideal[t] = Math.Clamp(dot / len2, 0, 1) * 64;
}
}
/// Grid weights (0..64, fractional) whose infill is nearest the texel weights in wk.Ideal.
static void FitGrid(Work wk, Grid g, int T, double[] into)
{
if (g.Identity)
{
Array.Copy(wk.Ideal, into, T);
return;
}
var fit = g.Fit;
for (var k = 0; k < g.Count; k++)
{
double sum = 0;
var row = k * T;
for (var t = 0; t < T; t++)
sum += fit[row + t] * wk.Ideal[t];
into[k] = Math.Clamp(sum, 0, 64);
}
}
static int RgbSum(Quant q, ReadOnlySpan codes) => q.Unq[codes[0]] + q.Unq[codes[1]] + q.Unq[codes[2]];
static int ToByte(double v) => (int)Math.Clamp(Math.Round(v), 0, 255);
/// The lookup of decoded channel values by weight for the current endpoint codes.
static void FillLut(Work wk, Quant cq, int C)
{
for (var c = 0; c < C; c++)
{
int d0 = cq.Unq[wk.C0[c]], d1 = cq.Unq[wk.C1[c]];
for (var w = 0; w <= 64; w++)
wk.Lut[c * 65 + w] = Interp(d0, d1, w);
}
}
static int TexelError(Work wk, int t, int w, int C)
{
var e = 0;
for (var c = 0; c < C; c++)
{
var d = wk.Lut[c * 65 + w] - wk.Px[t * 4 + c];
e += d * d;
}
return e;
}
/// A quick score for a mode: the principal-axis endpoints rounded to its colour range, the grid fitted to the
/// projected weights and rounded to its weight range.
static long QuickError(Work wk, Mode mode, int T, int C)
{
var g = mode.Grid;
var cq = mode.Colours;
var wq = mode.Weights;
var gf = wk.GridFits[g.Index];
if (!wk.GridDone[g.Index])
{
FitGrid(wk, g, T, gf);
wk.GridDone[g.Index] = true;
}
for (var c = 0; c < C; c++)
{
wk.C0[c] = cq.Nearest[ToByte(wk.E0[c])];
wk.C1[c] = cq.Nearest[ToByte(wk.E1[c])];
}
var flip = RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0);
if (flip)
for (var c = 0; c < C; c++)
(wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]);
for (var k = 0; k < g.Count; k++)
{
var v = flip ? 64 - gf[k] : gf[k];
wk.GUnq[k] = wq.Unq[wq.Nearest[(int)Math.Round(v)]];
}
FillLut(wk, cq, C);
long err = 0;
for (var t = 0; t < T; t++)
err += TexelError(wk, t, InfillOne(g, wk.GUnq, t), C);
return err;
}
/// A mode fitted fully; the best endpoint and grid codes found are left in wk.CandC0/CandC1/CandG.
static long Refine(Work wk, Mode mode, int T, int C)
{
var g = mode.Grid;
var cq = mode.Colours;
var wq = mode.Weights;
for (var c = 0; c < 4; c++)
{
wk.C0[c] = c < C ? cq.Nearest[ToByte(wk.E0[c])] : 0;
wk.C1[c] = c < C ? cq.Nearest[ToByte(wk.E1[c])] : 0;
}
if (RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0))
for (var c = 0; c < C; c++)
(wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]);
var best = long.MaxValue;
Span d0 = stackalloc double[4];
Span d1 = stackalloc double[4];
for (var round = 0; round < Rounds; round++)
{
// (weights: projection onto the actual endpoints, fitted to the grid and rounded)
for (var c = 0; c < C; c++)
{
d0[c] = cq.Unq[wk.C0[c]];
d1[c] = cq.Unq[wk.C1[c]];
}
Project(wk, d0, d1, T, C);
FitGrid(wk, g, T, wk.GridF);
for (var k = 0; k < g.Count; k++)
{
wk.GCodes[k] = wq.Nearest[(int)Math.Round(wk.GridF[k])];
wk.GUnq[k] = wq.Unq[wk.GCodes[k]];
}
FillLut(wk, cq, C);
long err = 0;
for (var t = 0; t < T; t++)
{
wk.Tw[t] = InfillOne(g, wk.GUnq, t);
wk.Terr[t] = TexelError(wk, t, wk.Tw[t], C);
err += wk.Terr[t];
}
err = DescendGrid(wk, g, wq, err, C);
if (err < best)
best = Keep(wk, g, err);
if (err == 0)
break;
// (endpoints: least squares on the decoded weights, rounded, then nudged)
if (!LeastSquaresEndpoints(wk, cq, T, C))
continue;
FillLut(wk, cq, C);
err = DescendEndpoints(wk, cq, T, C);
if (err < best)
best = Keep(wk, g, err);
}
return best;
}
static long Keep(Work wk, Grid g, long err)
{
Array.Copy(wk.C0, wk.CandC0, 4);
Array.Copy(wk.C1, wk.CandC1, 4);
Array.Copy(wk.GCodes, wk.CandG, g.Count);
return err;
}
/// Each grid weight moved a level up or down while that lowers the decoded error; returns the new error.
static long DescendGrid(Work wk, Grid g, Quant wq, long err, int C)
{
for (var pass = 0; pass < 3; pass++)
{
var changed = false;
for (var k = 0; k < g.Count; k++)
{
var rank = wq.Rank[wk.GCodes[k]];
var old = wk.GUnq[k];
for (var dir = -1; dir <= 1; dir += 2)
{
var r2 = rank + dir;
if (r2 < 0 || r2 >= wq.Levels)
continue;
var code = wq.Sorted[r2];
wk.GUnq[k] = wq.Unq[code];
long delta = 0;
foreach (var t in g.Touch[k])
delta += TexelError(wk, t, InfillOne(g, wk.GUnq, t), C) - wk.Terr[t];
if (delta < 0)
{
wk.GCodes[k] = code;
foreach (var t in g.Touch[k])
{
wk.Tw[t] = InfillOne(g, wk.GUnq, t);
wk.Terr[t] = TexelError(wk, t, wk.Tw[t], C);
}
err += delta;
changed = true;
old = wk.GUnq[k];
break;
}
wk.GUnq[k] = old;
}
}
if (!changed)
break;
}
return err;
}
/// Endpoints by least squares on the decoded texel weights, rounded to the colour range. False when the
/// result's order is the wrong way round (it is swapped for the next round's weights to follow).
static bool LeastSquaresEndpoints(Work wk, Quant cq, int T, int C)
{
for (var c = 0; c < C; c++)
{
double saa = 0, sab = 0, sbb = 0, sap = 0, sbp = 0, sp = 0;
for (var t = 0; t < T; t++)
{
var b = wk.Tw[t] / 64.0;
var a = 1 - b;
var p = wk.Px[t * 4 + c];
saa += a * a;
sab += a * b;
sbb += b * b;
sap += a * p;
sbp += b * p;
sp += p;
}
var det = saa * sbb - sab * sab;
double x0, x1;
if (Math.Abs(det) < 1e-9)
x0 = x1 = sp / T;
else
{
x0 = (sbb * sap - sab * sbp) / det;
x1 = (saa * sbp - sab * sap) / det;
}
wk.C0[c] = cq.Nearest[ToByte(x0)];
wk.C1[c] = cq.Nearest[ToByte(x1)];
}
if (RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0))
{
for (var c = 0; c < C; c++)
(wk.C0[c], wk.C1[c]) = (wk.C1[c], wk.C0[c]);
return false;
}
return true;
}
/// Each endpoint value moved a level up or down while that lowers the decoded error (keeping the endpoints'
/// order); returns the error.
static long DescendEndpoints(Work wk, Quant cq, int T, int C)
{
Span chan = stackalloc long[4];
for (var c = 0; c < C; c++)
{
long e = 0;
for (var t = 0; t < T; t++)
{
var d = wk.Lut[c * 65 + wk.Tw[t]] - wk.Px[t * 4 + c];
e += d * d;
}
chan[c] = e;
}
for (var pass = 0; pass < 3; pass++)
{
var changed = false;
for (var c = 0; c < C; c++)
for (var end = 0; end < 2; end++)
{
var codes = end == 0 ? wk.C0 : wk.C1;
var rank = cq.Rank[codes[c]];
for (var dir = -1; dir <= 1; dir += 2)
{
var r2 = rank + dir;
if (r2 < 0 || r2 >= cq.Levels)
continue;
var code = cq.Sorted[r2];
var old = codes[c];
codes[c] = code;
if (c < 3 && RgbSum(cq, wk.C1) < RgbSum(cq, wk.C0))
{
codes[c] = old;
continue;
}
int v0 = cq.Unq[wk.C0[c]], v1 = cq.Unq[wk.C1[c]];
for (var w = 0; w <= 64; w++)
wk.LutTry[w] = Interp(v0, v1, w);
long e = 0;
for (var t = 0; t < T; t++)
{
var d = wk.LutTry[wk.Tw[t]] - wk.Px[t * 4 + c];
e += d * d;
}
if (e < chan[c])
{
chan[c] = e;
Array.Copy(wk.LutTry, 0, wk.Lut, c * 65, 65);
changed = true;
break;
}
codes[c] = old;
}
}
if (!changed)
break;
}
long total = 0;
for (var c = 0; c < C; c++)
total += chan[c];
return total;
}
// ---- writing ----
/// The block's bits: mode, one partition, the CEM, the endpoint values from bit 17, the weights from bit 127 down.
static void WriteBlock(Span dest, Mode mode, bool hasAlpha, int[] c0, int[] c1, int[] gcodes)
{
PutBits(dest, 0, mode.Bits, 11);
PutBits(dest, 11, 0, 2);
PutBits(dest, 13, hasAlpha ? 12u : 8u, 4);
Span values = stackalloc int[8];
var n = hasAlpha ? 8 : 6;
for (var c = 0; c < n / 2; c++)
{
values[2 * c] = c0[c];
values[2 * c + 1] = c1[c];
}
WriteIse(dest, 17, values[..n], mode.Colours.Enc);
Span w = stackalloc byte[16];
w.Clear();
WriteIse(w, 0, gcodes.AsSpan(0, mode.Grid.Count), mode.Weights.Enc);
for (var i = 0; i < mode.WeightBits; i++)
if (((w[i >> 3] >> (i & 7)) & 1) != 0)
dest[(127 - i) >> 3] |= (byte)(1 << ((127 - i) & 7));
}
/// A void extent block (LDR, no extent given): the whole block is one colour, stored as UNORM16.
static void WriteVoidExtent(Span dest, byte r, byte g, byte b, byte a)
{
PutBits(dest, 0, 0x1FC, 9);
PutBits(dest, 9, 0, 1);
PutBits(dest, 10, 3, 2);
for (var i = 0; i < 4; i++)
PutBits(dest, 12 + 13 * i, 0x1FFF, 13);
PutBits(dest, 64, r * 257u, 16);
PutBits(dest, 80, g * 257u, 16);
PutBits(dest, 96, b * 257u, 16);
PutBits(dest, 112, a * 257u, 16);
}
}