use super::texture::TextureFormat;
#[inline]
fn expand5(v: u8) -> u8 {
(v << 3) | (v >> 2)
}
#[inline]
fn expand6(v: u8) -> u8 {
(v << 2) | (v >> 4)
}
#[inline]
fn to565(c: [f32; 3]) -> u16 {
let q = |v: f32, bits: f32| -> u16 {
let m = (1u16 << bits as u16) - 1;
((v / 255.0 * m as f32).round().clamp(0.0, m as f32)) as u16
};
(q(c[0], 5.0) << 11) | (q(c[1], 6.0) << 5) | q(c[2], 5.0)
}
#[inline]
fn from565(w: u16) -> [f32; 3] {
[
expand5(((w >> 11) & 0x1f) as u8) as f32,
expand6(((w >> 5) & 0x3f) as u8) as f32,
expand5((w & 0x1f) as u8) as f32,
]
}
#[inline]
fn palette(c0: u16, c1: u16) -> [[f32; 3]; 4] {
let a = from565(c0);
let b = from565(c1);
let mut p = [[0.0; 3]; 4];
for i in 0..3 {
p[0][i] = a[i];
p[1][i] = b[i];
p[2][i] = ((2.0 * a[i] + b[i]) / 3.0).round();
p[3][i] = ((a[i] + 2.0 * b[i]) / 3.0).round();
}
p
}
#[inline]
fn dist2(a: [f32; 3], b: [f32; 3]) -> f32 {
let (x, y, z) = (a[0] - b[0], a[1] - b[1], a[2] - b[2]);
x * x + y * y + z * z
}
fn principal_endpoints(px: &[[f32; 3]; 16]) -> ([f32; 3], [f32; 3]) {
let mut mean = [0.0f32; 3];
for p in px.iter() {
for i in 0..3 {
mean[i] += p[i];
}
}
for m in mean.iter_mut() {
*m /= 16.0;
}
let (mut xx, mut xy, mut xz, mut yy, mut yz, mut zz) = (0.0f32, 0.0, 0.0, 0.0, 0.0, 0.0);
for p in px.iter() {
let d = [p[0] - mean[0], p[1] - mean[1], p[2] - mean[2]];
xx += d[0] * d[0];
xy += d[0] * d[1];
xz += d[0] * d[2];
yy += d[1] * d[1];
yz += d[1] * d[2];
zz += d[2] * d[2];
}
let mut v = if xx > yy && xx > zz {
[1.0, 0.0, 0.0]
} else if yy > zz {
[0.0, 1.0, 0.0]
} else {
[0.0, 0.0, 1.0]
};
for _ in 0..8 {
let n = [
xx * v[0] + xy * v[1] + xz * v[2],
xy * v[0] + yy * v[1] + yz * v[2],
xz * v[0] + yz * v[1] + zz * v[2],
];
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
if len < 1e-8 {
break; }
v = [n[0] / len, n[1] / len, n[2] / len];
}
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
for p in px.iter() {
let t = (p[0] - mean[0]) * v[0] + (p[1] - mean[1]) * v[1] + (p[2] - mean[2]) * v[2];
lo = lo.min(t);
hi = hi.max(t);
}
let at = |t: f32| {
[
(mean[0] + v[0] * t).clamp(0.0, 255.0),
(mean[1] + v[1] * t).clamp(0.0, 255.0),
(mean[2] + v[2] * t).clamp(0.0, 255.0),
]
};
(at(hi), at(lo))
}
fn assign(px: &[[f32; 3]; 16], pal: &[[f32; 3]; 4]) -> ([u8; 16], f32) {
let mut idx = [0u8; 16];
let mut err = 0.0;
for (i, p) in px.iter().enumerate() {
let (mut best, mut bd) = (0u8, f32::MAX);
for (j, c) in pal.iter().enumerate() {
let d = dist2(*p, *c);
if d < bd {
bd = d;
best = j as u8;
}
}
idx[i] = best;
err += bd;
}
(idx, err)
}
fn refit(px: &[[f32; 3]; 16], idx: &[u8; 16]) -> Option<([f32; 3], [f32; 3])> {
const W: [f32; 4] = [1.0, 0.0, 2.0 / 3.0, 1.0 / 3.0];
let (mut aa, mut ab, mut bb) = (0.0f32, 0.0, 0.0);
let mut ax = [0.0f32; 3];
let mut bx = [0.0f32; 3];
for (i, p) in px.iter().enumerate() {
let a = W[idx[i] as usize];
let b = 1.0 - a;
aa += a * a;
ab += a * b;
bb += b * b;
for c in 0..3 {
ax[c] += a * p[c];
bx[c] += b * p[c];
}
}
let det = aa * bb - ab * ab;
if det.abs() < 1e-6 {
return None; }
let mut e0 = [0.0f32; 3];
let mut e1 = [0.0f32; 3];
for c in 0..3 {
e0[c] = ((bb * ax[c] - ab * bx[c]) / det).clamp(0.0, 255.0);
e1[c] = ((aa * bx[c] - ab * ax[c]) / det).clamp(0.0, 255.0);
}
Some((e0, e1))
}
fn encode_block(px: &[[f32; 3]; 16]) -> [u8; 8] {
let (mut a, mut b) = principal_endpoints(px);
let (mut best_w, mut best_idx, mut best_err) = (None, [0u8; 16], f32::MAX);
for _ in 0..3 {
let (mut w0, mut w1) = (to565(a), to565(b));
if w0 == w1 {
let mut out = [0u8; 8];
out[0..2].copy_from_slice(&w0.to_le_bytes());
out[2..4].copy_from_slice(&w1.to_le_bytes());
return out; }
let mut swapped = false;
if w0 < w1 {
std::mem::swap(&mut w0, &mut w1);
swapped = true;
}
let pal = palette(w0, w1);
let (idx, err) = assign(px, &pal);
if err < best_err {
best_err = err;
best_idx = idx;
best_w = Some((w0, w1));
}
match refit(px, &idx) {
Some((n0, n1)) => {
if swapped {
b = n0;
a = n1;
} else {
a = n0;
b = n1;
}
}
None => break,
}
}
let (w0, w1) = best_w.expect("at least one round always runs");
let mut out = [0u8; 8];
out[0..2].copy_from_slice(&w0.to_le_bytes());
out[2..4].copy_from_slice(&w1.to_le_bytes());
for (i, &v) in best_idx.iter().enumerate() {
out[4 + i / 4] |= v << ((i % 4) * 2);
}
out
}
pub fn encode(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
let (w, h) = (width.max(1) as usize, height.max(1) as usize);
assert!(
rgba.len() >= w * h * 4,
"bc1::encode: {} bytes for {w}x{h}, need {}",
rgba.len(),
w * h * 4
);
let (bx, by) = (w.div_ceil(4), h.div_ceil(4));
let mut out = Vec::with_capacity(bx * by * 8);
let mut block = [[0.0f32; 3]; 16];
for byi in 0..by {
for bxi in 0..bx {
for r in 0..4 {
let y = (byi * 4 + r).min(h - 1);
for c in 0..4 {
let x = (bxi * 4 + c).min(w - 1);
let i = (y * w + x) * 4;
block[r * 4 + c] = [rgba[i] as f32, rgba[i + 1] as f32, rgba[i + 2] as f32];
}
}
out.extend_from_slice(&encode_block(&block));
}
}
out
}
pub fn decode(blocks: &[u8], width: u32, height: u32) -> Vec<u8> {
let (w, h) = (width.max(1) as usize, height.max(1) as usize);
let (bx, by) = (w.div_ceil(4), h.div_ceil(4));
let mut out = vec![0u8; w * h * 4];
for byi in 0..by {
for bxi in 0..bx {
let o = (byi * bx + bxi) * 8;
if o + 8 > blocks.len() {
break;
}
let c0 = u16::from_le_bytes([blocks[o], blocks[o + 1]]);
let c1 = u16::from_le_bytes([blocks[o + 2], blocks[o + 3]]);
let pal = if c0 > c1 {
palette(c0, c1)
} else {
let (a, b) = (from565(c0), from565(c1));
let mid = [
((a[0] + b[0]) / 2.0).round(),
((a[1] + b[1]) / 2.0).round(),
((a[2] + b[2]) / 2.0).round(),
];
[a, b, mid, [0.0, 0.0, 0.0]]
};
let bits =
u32::from_le_bytes([blocks[o + 4], blocks[o + 5], blocks[o + 6], blocks[o + 7]]);
for r in 0..4 {
let y = byi * 4 + r;
if y >= h {
break;
}
for c in 0..4 {
let x = bxi * 4 + c;
if x >= w {
break;
}
let i = r * 4 + c;
let v = ((bits >> (i * 2)) & 3) as usize;
let p = pal[v];
let d = (y * w + x) * 4;
out[d] = p[0] as u8;
out[d + 1] = p[1] as u8;
out[d + 2] = p[2] as u8;
out[d + 3] = if c0 <= c1 && v == 3 { 0 } else { 255 };
}
}
}
}
out
}
pub fn encode_with_mips(rgba: &[u8], width: u32, height: u32) -> (Vec<u8>, Vec<Vec<u8>>) {
let level0 = encode(rgba, width, height);
let mut mips = Vec::new();
let (mut w, mut h) = (width.max(1), height.max(1));
let mut src = rgba.to_vec();
let dec: Vec<f32> = (0..256)
.map(|i| {
let c = i as f32 / 255.0;
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
})
.collect();
let enc = |v: f32| -> u8 {
let c = if v <= 0.0031308 {
v * 12.92
} else {
1.055 * v.powf(1.0 / 2.4) - 0.055
};
(c.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
};
while w > 1 || h > 1 {
let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
let mut next = vec![0u8; (nw * nh * 4) as usize];
for y in 0..nh {
for x in 0..nw {
let mut acc = [0.0f32; 4];
let mut n = 0.0f32;
for dy in 0..2 {
let sy = (y * 2 + dy).min(h - 1);
for dx in 0..2 {
let sx = (x * 2 + dx).min(w - 1);
let i = ((sy * w + sx) * 4) as usize;
acc[0] += dec[src[i] as usize];
acc[1] += dec[src[i + 1] as usize];
acc[2] += dec[src[i + 2] as usize];
acc[3] += src[i + 3] as f32;
n += 1.0;
}
}
let o = ((y * nw + x) * 4) as usize;
next[o] = enc(acc[0] / n);
next[o + 1] = enc(acc[1] / n);
next[o + 2] = enc(acc[2] / n);
next[o + 3] = (acc[3] / n) as u8;
}
}
mips.push(encode(&next, nw, nh));
src = next;
w = nw;
h = nh;
}
(level0, mips)
}
pub fn size_with_mips(width: u32, height: u32) -> usize {
let f = TextureFormat::Bc1RgbaUnormSrgb;
let (mut w, mut h) = (width.max(1), height.max(1));
let mut total = f.data_len(w, h);
while w > 1 || h > 1 {
w = (w / 2).max(1);
h = (h / 2).max(1);
total += f.data_len(w, h);
}
total
}
pub fn mip_levels(width: u32, height: u32) -> usize {
let (mut w, mut h) = (width.max(1), height.max(1));
let mut n = 0;
while w > 1 || h > 1 {
w = (w / 2).max(1);
h = (h / 2).max(1);
n += 1;
}
n
}
#[cfg(test)]
mod tests {
use super::*;
fn rmse(a: &[u8], b: &[u8]) -> f64 {
let mut s = 0.0;
let mut n = 0.0;
for (x, y) in a.chunks_exact(4).zip(b.chunks_exact(4)) {
for c in 0..3 {
let d = x[c] as f64 - y[c] as f64;
s += d * d;
n += 1.0;
}
}
(s / n).sqrt()
}
#[test]
fn flat_blocks_stay_opaque_and_exact() {
for colour in [[0u8, 0, 0], [255, 255, 255], [37, 140, 201], [8, 8, 8]] {
let px: Vec<u8> = std::iter::repeat_n([colour[0], colour[1], colour[2], 255], 16)
.flatten()
.collect();
let enc = encode(&px, 4, 4);
let dec = decode(&enc, 4, 4);
for p in dec.chunks_exact(4) {
assert_eq!(p[3], 255, "flat {colour:?} decoded transparent");
for c in 0..3 {
assert!(
(p[c] as i32 - colour[c] as i32).abs() <= 4,
"flat {colour:?} -> {:?}",
&p[..3]
);
}
}
}
}
#[test]
fn a_hard_edge_survives_exactly() {
let (land, sea) = ([120u8, 96, 48], [16u8, 40, 120]);
let mut px = Vec::new();
for r in 0..4 {
for _ in 0..4 {
let c = if r < 2 { land } else { sea };
px.extend_from_slice(&[c[0], c[1], c[2], 255]);
}
}
let dec = decode(&encode(&px, 4, 4), 4, 4);
assert!(rmse(&px, &dec) < 3.0, "edge rmse {}", rmse(&px, &dec));
for p in dec.chunks_exact(4) {
assert_eq!(p[3], 255);
}
}
#[test]
fn principal_axis_beats_a_bounding_box_fit() {
let mut px = Vec::new();
for i in 0..16 {
let t = i as f32 / 15.0;
px.extend_from_slice(&[
(20.0 + 200.0 * t) as u8,
(200.0 - 150.0 * t) as u8,
(60.0 + 40.0 * t) as u8,
255,
]);
}
let ours = rmse(&px, &decode(&encode(&px, 4, 4), 4, 4));
let mut lo = [255f32; 3];
let mut hi = [0f32; 3];
for p in px.chunks_exact(4) {
for c in 0..3 {
lo[c] = lo[c].min(p[c] as f32);
hi[c] = hi[c].max(p[c] as f32);
}
}
let (w0, w1) = (to565(hi), to565(lo));
let (w0, w1) = if w0 > w1 { (w0, w1) } else { (w1, w0) };
let pal = palette(w0, w1);
let mut boxed = Vec::new();
for p in px.chunks_exact(4) {
let c = [p[0] as f32, p[1] as f32, p[2] as f32];
let best = pal
.iter()
.min_by(|a, b| dist2(c, **a).partial_cmp(&dist2(c, **b)).unwrap())
.unwrap();
boxed.extend_from_slice(&[best[0] as u8, best[1] as u8, best[2] as u8, 255]);
}
let box_err = rmse(&px, &boxed);
assert!(
ours <= box_err,
"principal axis {ours:.2} should beat bounding box {box_err:.2}"
);
}
#[test]
fn sizes_and_partial_blocks() {
let f = TextureFormat::Bc1RgbaUnormSrgb;
assert_eq!(f.data_len(4, 4), 8);
assert_eq!(f.data_len(1, 1), 8);
assert_eq!(f.data_len(5, 5), 4 * 8);
assert_eq!(f.data_len(1024, 512), (1024 / 4) * (512 / 4) * 8);
let px = vec![128u8; 7 * 5 * 4];
assert_eq!(encode(&px, 7, 5).len(), f.data_len(7, 5));
}
#[test]
fn mip_chain_is_complete_and_correctly_sized() {
let (w, h) = (64u32, 32u32);
let mut px = Vec::new();
for y in 0..h {
for x in 0..w {
px.extend_from_slice(&[(x * 4) as u8, (y * 8) as u8, 128, 255]);
}
}
let (level0, mips) = encode_with_mips(&px, w, h);
let f = TextureFormat::Bc1RgbaUnormSrgb;
assert_eq!(level0.len(), f.data_len(w, h));
assert_eq!(mips.len(), 6, "chain must reach 1x1");
assert_eq!(mip_levels(w, h), mips.len());
let (mut lw, mut lh) = (w, h);
for (i, m) in mips.iter().enumerate() {
lw = (lw / 2).max(1);
lh = (lh / 2).max(1);
assert_eq!(m.len(), f.data_len(lw, lh), "mip {} size", i + 1);
}
assert_eq!(
size_with_mips(w, h),
level0.len() + mips.iter().map(|m| m.len()).sum::<usize>()
);
}
}