Algorithmadvanced
Adaptive scalable texture compression
Also called ASTC.
A block texture format with 128 bits per block for footprints from 4x4 to 12x12 texels, whose color endpoints and weights are packed with trits, quints and bits by integer sequence coding.
- Time
- Θ(N) worst
- Space
- Θ(1) extra
- Where
- N = the number of texels decoded
- Model
- Word RAM
- Properties
- deterministicnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jørn Nystad, Anders Lassen, Andy Pomianowski, Sean Ellis, Tom Olson, 2012
Adaptive scalable texture compression, ASTC, is a fixed-rate block format like S3 texture compression, but every block has 128 bits, whatever its footprint. A 2D footprint goes from to texels, so one format gives rates from 8 down to bits per texel. In S3TC each texel has its own 2-bit index and the endpoints are always RGB565. In ASTC the block stores a smaller grid of weights that the decoder interpolates up to the texels, the color endpoints can have many precisions and channel layouts, and both are packed in ranges that are not powers of two. This page describes the decoding of a block and the bounded integer sequence encoding (BISE) that packs the numbers. The code covers a stated subset: BISE in both directions, and the decoding of a 2D LDR block with one partition, one weight plane and the RGB or RGBA direct endpoint modes.
In plain words
Each block of the texture gets the same 16 bytes, but the encoder decides how to spend them. It stores two end colors and a small grid of mixing weights. To color a texel, the decoder looks up the weight at that place in the grid, smoothly between grid points, and mixes the two end colors by that weight.
The trick is how numbers are stored. A number from 0 to 2 needs more than one bit but less than two. So ASTC packs five such numbers into 8 bits, and three numbers from 0 to 4 into 7 bits. That way no bit goes to waste, and the encoder can pick almost any precision for the colors and the weights.
The problem
The decoder gets one block of 128 bits and the footprint of the texture, which is fixed for the whole image. It must return the color of every texel of the block, as a fixed function of these bits, so that the texture unit can fetch a texel at a known address and decode it alone. The encoder gets the texels and must choose the block mode, the endpoints and the weights that give the smallest error. That is a search, and its quality is measured, not proved.
The rate follows from the footprint:
| footprint | bits per texel |
|---|---|
| 8 | |
| 2 | |
A block of one partition has this layout:
| bits | field |
|---|---|
| 0 to 10 | block mode: the weight grid , the weight range , and dual plane |
| 11 to 12 | the number of partitions minus 1 |
| 13 to 16 | the color endpoint mode, CEM |
| 17 upward | the color values, one BISE stream |
| 127 downward | the weights, one BISE stream, with bit of the stream at bit |
The bits between the two streams are not used. A range in BISE has , or . A value is , with its low bits and a trit or a quint. Five trits pack into 8 bits and three quints into 7, which costs or bits per value.
The algorithm
ASTC-DECODE(block, Bs, Bt)- 1
(N, M, wmax, dual) ← BLOCK-MODE(bits 0..10); error if reserved, N > Bs or M > Bt - 2
partitions ← bits 11..12 + 1; CEM ← bits 13..16 ▷ here 1 partition, no dual plane - 3
wbits ← ISE-BITS(N M, wmax); error unless N M ≤ 64 and 24 ≤ wbits ≤ 96 - 4
cmax ← the largest color range with ISE-BITS(2 (CEM div 4 + 1), cmax) ≤ 111 - wbits - 5
v ← UNQUANT-COLOR(ISE-DECODE(bits from 17 upward, cmax)) ▷ to 0..255 - 6
(E0, E1) ← ENDPOINTS(CEM, v) ▷ swap and blue contraction if the sums fall - 7
w ← UNQUANT-WEIGHT(ISE-DECODE(bits from 127 downward, wmax)) ▷ to 0..64 - 8
for each texel (s, t): i ← INFILL(w, s, t) ▷ fixed-point bilinear - 9
C ← floor((257 E0 (64 - i) + 257 E1 i + 32) / 64) ▷ per channel, 16 bits - 10
return the texels ISE-DECODE(stream, count, max) ▷ max + 1 = 2^n, 3 2^n or 5 2^n- 11
set the bits at and past ISE-BITS(count, max) to 0 - 12
for each group of 5 values (trits) or 3 (quints), read m_j and the code bits between them - 13
(h_0, h_1, ...) ← TABLE[code] - 14
value_j ← h_j 2^n + m_j
Line L4 is why the format needs no field for the color precision: the decoder gives the colors all the bits that the weights leave, at the largest range that fits. Line L6, for the modes 8 (RGB) and 12 (RGBA), compares the sums and . If the second is smaller, it swaps the endpoints and moves red and green halfway toward blue, which gives more precision to colors near gray. This costs no bits, in the same way as the order of the endpoints in S3TC. Line L8 maps the texel to the weight grid with the step and mixes four weights with factors in sixteenths.
The trit and quint tables of line L13 come from short bit formulas in the format specification. Their values are not in order: in the weight range , the stored values unquantize to .
Example
BISE. Store the five values in the range , so .
| value | 7 | 0 | 11 | 4 | 9 |
|---|---|---|---|---|---|
| trit | 1 | 0 | 2 | 1 | 2 |
| low bits | 3 | 0 | 3 | 0 | 1 |
The trits pack into the code . The stream is , , , , , , , , , , which is bits. Fixed 4-bit fields would take 20 bits, and the information content is bits.
A block. Take a footprint with a weight grid in the range and CEM 8. The weights take bits. That leaves bits for 6 color values, and the largest range that fits is , at 48 bits. Let the colors be . The sums are and , so there is no swap: and . Let each row of weights store , which unquantize to . The grid has the size of the block, so the infill is the identity. The second texel of a row has , and its red channel is , about 82.5 on a scale of 255. The code writes this block as the 16 bytes 51 02 51 90 c9 b8 65 78 40 97 d0 2a 38 1e ba 04.
Correctness
The proof file shows four things for the subset. First, a BISE stream of values has or bits, and decoding returns what the encoder wrote, also for a short last group, whatever the bits past the end hold. The proof uses the fact that the smallest code of a tuple padded with zeros has its high bits zero, which is checked on every short tuple. Second, the color unquantization of a trit or quint range is one to one onto values from 0 to 255, and flipping the lowest bit mirrors the value. Third, the infill factors are nonnegative and sum to 16, a neighbor past the grid always has the factor 0, and the corners get the corner weights. Fourth, the whole decode reads only the 128 bits and the footprint, and the color and weight streams never overlap.
Proof: BISE decodes what it encodes, and a one-partition ASTC block decodes as a fixed function of its 128 bitsfull
We use the pseudocode and the notation of the page. The proof covers the subset of the code: BISE for every range of the format, and one 2D LDR block with one partition, one weight plane and the color endpoint modes 8 and 12. All arithmetic is on integers. Some facts are about finite tables of the format, and for those the proof is an enumeration that the code tests carry out. We say so where it happens.
A BISE range is with , or . A value splits into its low bits and its high part , which is a bit-free number, a trit in or a quint in . A group holds 1 value (plain bits), 5 values (trits) or 3 values (quints). Its high parts are packed into a code of , 8 or 7 bits, and the group is written as , then bits of , then , then bits of , and so on, with for trits and for quints. Let be the table that maps a code to its tuple of high parts (lines L13), and let the encoder use .
Lemma 1 (the tables are onto). The trit table maps the 256 codes of 8 bits onto all tuples, and the quint table maps the 128 codes of 7 bits onto all tuples. So is defined for every tuple.
Proof. By enumeration of the 384 codes, in test_packed_fields_cover_every_tuple.
Theorem 1 (the layout and the rate). A sequence of values in takes bits for trits, for quints and for plain bits. This is with the exact rate , or bits per value.
Proof. A full group of trits holds bits for 5 values, and a full group of quints for 3 values. A last group with values ends right after the code bits that follow . Those are bits. For trits the partial sums are for , which equal , and for quints they are for , which equal . Adding the full groups gives the formula, and is an integer, so it equals .
The rate is close to the information content or . The excess per value is bits for trits and bits for quints.
Theorem 2 (round trip). For every range and every sequence in it, the encoder writes no bit at or past position , and ISE-DECODE returns , whatever the bits past the end hold.
Proof. Line L11 masks the stream to its length, so the bits past the end read as zero. Lines L12 and L14 read the low bits in the same places where the encoder wrote them, by Theorem 1, so comes back unchanged. In a full group, line L13 reads the code and returns , the high parts.
In a last group with values, the encoder pads the tuple with zeros to and writes all of it. The bits past the end are the padded low bits, which are zero, and the code bits from position upward. For every such tuple there is a code below that maps to it, by enumeration of the trit tuples and the quint tuples, in test_round_trip_every_short_trit_and_quint_group. Then the smallest code is also below , so its bits from upward are zero. The decoder therefore reads the code in full, gets from line L13, and drops the padded values. The code asserts that no bit past the end is set.
Lemma 2 (the unquantization). For each color range of a trit or a quint, the map of line L5 to is one to one, has and in its image, and flipping the lowest bit of a value maps to .
Proof. The one to one part and the end values are by enumeration of the 17 color ranges, in test_unquantization_tables. For the mirror, line L5 computes , where does not depend on , then with or , then . For every range in the table, , since and the largest is . So and . With the result is , and with it is , which is minus the first.
The weight tables of line L7 have the same form with 7 bits and the bound , and then add 1 to every value above 32, which maps them into . The test checks that each is one to one with the end values and .
Lemma 3 (the infill). For a grid of weights in and a legal footprint with and , line L8 returns a value in . The four factors are nonnegative and sum to 16, so a constant grid gives the same constant. A neighbor past the grid always has the factor 0. The corner texels and get the corner weights.
Proof. Let and . The sum is . Since , we get , so . Since , we get , and is an integer, so . A weighted sum with these factors of values in , plus 8 and divided by 16, lies in . For a constant it is .
The step is . For the widths 4, 5, 6, 8, 10 and 12, the product is 1026, 1024, 1025, 1022, 1026 and 1023. So for every , , because . Then , and forces , so the right neighbor has the factor 0. The same holds for . At , . At , also , so , and .
When the grid has the size of the block, the infill is the identity. This is by enumeration over the 14 footprints, in test_infill_identity_and_constants.
Lemma 4 (the interpolation). With , line L9 gives at , at , and a value that moves monotonically from to as grows.
Proof. At it is , and at it is . The numerator is , monotone in , and the floor keeps the order.
Theorem 3 (decoding is a fixed function of the block). Lines L1 to L10 read only the 128 bits of the block and the footprint. For every block in the subset they return either the error color for every texel or one RGBA value of 16 bits per channel for each texel. The color stream and the weight stream do not overlap.
Proof. Lines L1 to L4 read fixed fields and fixed tables, and each test that fails returns the error color. The color range of line L4 is chosen so that its stream fits in bits, so it ends at bit , below the first weight bit . Line L5 uses Theorem 2 on the bits from 17 upward, and line L7 on the bits from 127 downward. Lines L6, L8 and L9 are integer formulas, defined for all inputs, by Lemmas 3 and 4. No step reads another block.
So any texel at needs only the block , at a fixed address, and the rate is bits per texel.
Cost. A block holds at most 64 weights and here 6 or 8 color values, so lines L1 to L7 take time, and lines L8 and L9 take per texel. Decoding one texel alone needs only the weights of its four neighbors, so it is too.
Complexity
A block has at most 64 weights and at most 18 color values, so the work before the texel loop is . Each texel then takes operations on small integers, in the word-RAM model. So decoding texels takes time and extra space per block. A texture of texels takes bits. Encoding is far more costly: a good encoder tries many block modes, partitions and endpoint fits per block.
Properties
- Fixed rate and random access. Every block has 128 bits and decodes alone. This is proved for the subset and is a property of the whole format.
- Near-optimal packing. BISE costs less than 0.016 bits per value above the information content for trits and less than 0.012 for quints. This follows from and .
- One decoder for many rates. The footprint sets the rate, and the block mode sets how the bits split between the weights and the colors.
- Bit-exact decoding. The specification gives every step in integer arithmetic, so all conforming decoders agree on every bit, unlike S3TC.
- Measured quality. Nystad and others compare ASTC with other formats at equal bit rates on test images. Such results are measurements of a given encoder on given images.
Variants and improvements
- Partitions. A block can split its texels into 2, 3 or 4 partitions, each with its own endpoints. A 10-bit seed and a hash function of the texel position choose the partition of each texel, so the format needs no table of shapes.
- Dual plane. A second weight grid for one channel, for example alpha or one channel of a normal map, lets that channel vary on its own.
- Other color endpoint modes. There are 16 modes: luminance, luminance with alpha, RGB with a scale, base and offset forms, and HDR modes.
- 3D blocks. Footprints from to texels code volume textures.
- Void extent. A special block mode stores one constant color for the block, with the extent of the area that has this color.
- Profiles. The LDR profile is the most common in hardware. The HDR profile adds the HDR endpoint modes.
- Encoders. Encoders search the block modes and partitions with heuristics and give presets from fast to thorough. The search time is tuning, and the quality is measured.
When to use it
Use it on GPUs that support it, which includes most mobile GPUs, when you need one format for many kinds of textures and rates, or a rate below 2 bits per texel for large, smooth textures. It handles color, alpha, normal maps and HDR with the same decoder. On desktop GPUs without ASTC, use S3TC or the later BC formats. For textures that need exact values, do not use any lossy format.
Pitfalls
- The footprint is not in the block. The decoder must get the footprint from the texture format. The same 16 bytes decode to a different image with another footprint.
- Quantized values are not in order. In trit and quint ranges, the stored integer and the unquantized value have different orders. An encoder that rounds to the nearest stored integer gives wrong colors. Map through the tables.
- The weight stream is reversed. The weights start at bit 127 and run down, bit by bit. Reading them from bit 0 upward gives garbage.
- Illegal blocks. A weight grid larger than the block, more than 64 weights, or too many bits all give the error color. The decoder must check every condition, because the block mode field has many values that are reserved or illegal.
- sRGB and output formats. The 16-bit result of line L9 converts to the output format by rules of the profile, and sRGB textures use other rules for the expansion of the endpoints. The code of this page returns the 16-bit values only.
- Low rates on detailed textures. A large footprint has few weights per texel, which blurs fine detail. Choose the footprint per texture.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-scalable-texture-compression/. The authors are listed in prov/XB2HVD.jsonl.
"""A stated subset of the ASTC decoder: bounded integer sequence encoding
(BISE) in both directions, and the decoding of one 2D LDR block with one
partition, one weight plane and the color endpoint modes 8 (RGB direct) and
12 (RGBA direct).
Every block has 128 bits:
- bits 0..10: the block mode (weight grid size, weight range, dual plane);
- bits 11..12: the partition count minus 1;
- bits 13..16: the color endpoint mode (for one partition);
- bits 17 upward: the color values, as one BISE stream;
- bits 127 downward: the weights, as one BISE stream with the bit order
reversed (bit k of the stream is bit 127 - k of the block).
Out of the subset (an error is raised): void-extent blocks, dual-plane
blocks, more than one partition, other color endpoint modes, HDR, sRGB and
3D blocks. Illegal blocks decode to the LDR error color.
The decoder returns the 16-bit values that the interpolation produces, before
the conversion to the output format. Nothing here is an encoder in the
sense of a search: pack_block only writes given fields into a block.
"""
from fractions import Fraction
from math import ceil
BLOCK_BITS = 128
FOOTPRINTS = [(4, 4), (5, 4), (5, 5), (6, 5), (6, 6), (8, 5), (8, 6), (8, 8),
(10, 5), (10, 6), (10, 8), (10, 10), (12, 10), (12, 12)]
ERROR_COLOR = (0xFFFF, 0, 0xFFFF, 0xFFFF) # opaque magenta, the LDR error color
def bits_per_texel(width, height):
return Fraction(BLOCK_BITS, width * height)
# ---------------------------------------------------------------- BISE
# kind -> (values per group, packed bits per group, packed bits after each value)
GROUP = {
"bits": (1, 0, (0,)),
"trit": (5, 8, (2, 2, 1, 2, 1)), # m0 T[1:0] m1 T[3:2] m2 T[4] m3 T[6:5] m4 T[7]
"quint": (3, 7, (3, 2, 2)), # m0 Q[2:0] m1 Q[4:3] m2 Q[6:5]
}
def ise_params(max_value):
"""A range 0..max_value with max_value + 1 = 2^n, 3 * 2^n or 5 * 2^n."""
count = max_value + 1
for kind, f in (("bits", 1), ("trit", 3), ("quint", 5)):
if count % f == 0:
q = count // f
if q & (q - 1) == 0:
return kind, q.bit_length() - 1
raise ValueError(f"0..{max_value} is not a BISE range")
def ise_rate(max_value):
"""The exact number of bits per value, n + 8/5 for trits, n + 7/3 for quints."""
kind, n = ise_params(max_value)
size, packed, _ = GROUP[kind]
return n + Fraction(packed, size)
def ise_bits(count, max_value):
return ceil(count * ise_rate(max_value))
def bit(x, i):
return (x >> i) & 1
def decode_trits(t):
"""The 8-bit packed field T -> five trits (t0, ..., t4)."""
if (t >> 2) & 7 == 7:
c = ((t >> 5) & 7) << 2 | (t & 3)
t4 = t3 = 2
else:
c = t & 31
if (t >> 5) & 3 == 3:
t4, t3 = 2, bit(t, 7)
else:
t4, t3 = bit(t, 7), (t >> 5) & 3
if c & 3 == 3:
t2, t1, t0 = 2, bit(c, 4), bit(c, 3) << 1 | (bit(c, 2) & (1 - bit(c, 3)))
elif (c >> 2) & 3 == 3:
t2, t1, t0 = 2, 2, c & 3
else:
t2, t1, t0 = bit(c, 4), (c >> 2) & 3, bit(c, 1) << 1 | (bit(c, 0) & (1 - bit(c, 1)))
return (t0, t1, t2, t3, t4)
def decode_quints(q):
"""The 7-bit packed field Q -> three quints (q0, q1, q2)."""
if (q >> 1) & 3 == 3 and (q >> 5) & 3 == 0:
nq0 = 1 - bit(q, 0)
q2 = bit(q, 0) << 2 | (bit(q, 4) & nq0) << 1 | (bit(q, 3) & nq0)
return (4, 4, q2)
if (q >> 1) & 3 == 3:
q2 = 4
c = ((q >> 3) & 3) << 3 | (3 - ((q >> 5) & 3)) << 1 | bit(q, 0)
else:
q2 = (q >> 5) & 3
c = q & 31
if c & 7 == 5:
q1, q0 = 4, (c >> 3) & 3
else:
q1, q0 = (c >> 3) & 3, c & 7
return (q0, q1, q2)
DECODE_TABLE = {
"bits": [(0,)],
"trit": [decode_trits(t) for t in range(256)],
"quint": [decode_quints(q) for q in range(128)],
}
# The encoder uses the smallest packed field for each tuple. For a short last
# group this keeps the bits past the end of the stream zero (see the proof).
ENCODE_TABLE = {}
for _kind, _table in DECODE_TABLE.items():
ENCODE_TABLE[_kind] = {}
for _code, _tuple in enumerate(_table):
ENCODE_TABLE[_kind].setdefault(_tuple, _code)
def ise_encode(values, max_value):
"""Values in 0..max_value -> (stream, length in bits)."""
kind, n = ise_params(max_value)
size, _, split = GROUP[kind]
if any(not 0 <= v <= max_value for v in values):
raise ValueError("value out of range")
stream = pos = 0
for g in range(0, len(values), size):
group = list(values[g:g + size]) + [0] * (size - len(values[g:g + size]))
code = ENCODE_TABLE[kind][tuple(v >> n for v in group)]
used = 0
for j, v in enumerate(group):
stream |= (v & ((1 << n) - 1)) << pos
pos += n
stream |= ((code >> used) & ((1 << split[j]) - 1)) << pos
pos += split[j]
used += split[j]
length = ise_bits(len(values), max_value)
assert stream >> length == 0, "a bit past the end of the stream is set"
return stream, length
def ise_decode(stream, count, max_value):
"""Read count values in 0..max_value from the low bits of stream."""
kind, n = ise_params(max_value)
size, _, split = GROUP[kind]
stream &= (1 << ise_bits(count, max_value)) - 1 # @line L11
out, pos = [], 0
while len(out) < count:
low, code, used = [], 0, 0
for j in range(size):
low.append((stream >> pos) & ((1 << n) - 1)) # @line L12
pos += n
code |= ((stream >> pos) & ((1 << split[j]) - 1)) << used
pos += split[j]
used += split[j]
high = DECODE_TABLE[kind][code] # @line L13
out.extend(h << n | m for h, m in zip(high, low)) # @line L14
return out[:count]
# ---------------------------------------------------------------- unquantization
COLOR_RANGES = [5, 7, 9, 11, 15, 19, 23, 31, 39, 47, 63, 79, 95, 127, 159, 191, 255]
# max value -> (pattern of B from bit 8 down to bit 0, C); a is bit 0 of the low bits.
COLOR_TQ = {
5: ("000000000", 204), 9: ("000000000", 113), 11: ("b000b0bb0", 93),
19: ("b0000bb00", 54), 23: ("cb000cbcb", 44), 39: ("cb0000cbc", 26),
47: ("dcb000dcb", 22), 79: ("dcb0000dc", 13), 95: ("edcb000ed", 11),
159: ("edcb0000e", 6), 191: ("fedcb000f", 5),
}
WEIGHT_TQ = {
5: ("0000000", 50), 9: ("0000000", 28), 11: ("b000b0b", 23),
19: ("b0000b0", 13), 23: ("cb000cb", 11),
}
WEIGHT_DIRECT = {2: (0, 32, 63), 4: (0, 16, 32, 47, 63)}
# (H, R) of the block mode -> the largest weight value
WEIGHT_RANGES = {(0, 2): 1, (0, 3): 2, (0, 4): 3, (0, 5): 4, (0, 6): 5, (0, 7): 7,
(1, 2): 9, (1, 3): 11, (1, 4): 15, (1, 5): 19, (1, 6): 23, (1, 7): 31}
def replicate(value, n, width):
"""Repeat the n-bit pattern of value from the top until width bits are filled."""
out, filled = 0, 0
while filled < width:
out, filled = out << n | value, filled + n
return out >> (filled - width)
def pattern_value(pattern, low):
v = 0
for ch in pattern:
v = v << 1 | (0 if ch == "0" else bit(low, ord(ch) - ord("a")))
return v
def unquant_color(value, max_value):
"""A color value in 0..max_value -> 0..255."""
kind, n = ise_params(max_value)
if kind == "bits":
return replicate(value, n, 8)
d, low = value >> n, value & ((1 << n) - 1)
a = 0x1FF if low & 1 else 0
pattern, c = COLOR_TQ[max_value]
t = (d * c + pattern_value(pattern, low)) ^ a
return (a & 0x80) | (t >> 2)
def unquant_weight(value, max_value):
"""A weight in 0..max_value -> 0..64."""
kind, n = ise_params(max_value)
if kind == "bits":
t = replicate(value, n, 6)
elif max_value in WEIGHT_DIRECT:
t = WEIGHT_DIRECT[max_value][value]
else:
d, low = value >> n, value & ((1 << n) - 1)
a = 0x7F if low & 1 else 0
pattern, c = WEIGHT_TQ[max_value]
t = (d * c + pattern_value(pattern, low)) ^ a
t = (a & 0x20) | (t >> 2)
return t + 1 if t > 32 else t
# ---------------------------------------------------------------- block decoding
def decode_block_mode(mode):
"""11 bits -> (grid width, grid height, largest weight, dual plane),
"void" for a void-extent block, or None for a reserved mode."""
if mode & 0x1FF == 0x1FC:
return "void"
a, h, d = (mode >> 5) & 3, bit(mode, 9), bit(mode, 10)
if mode & 3:
r = bit(mode, 4) | (mode & 3) << 1
b, layout = (mode >> 7) & 3, (mode >> 2) & 3
if layout == 0:
w, g = b + 4, a + 2
elif layout == 1:
w, g = b + 8, a + 2
elif layout == 2:
w, g = a + 2, b + 8
elif bit(mode, 8) == 0:
w, g = a + 2, bit(mode, 7) + 6
else:
w, g = bit(mode, 7) + 2, a + 2
else:
r = bit(mode, 4) | ((mode >> 2) & 3) << 1
if r < 2:
return None
layout = (mode >> 7) & 3
if layout == 0:
w, g = 12, a + 2
elif layout == 1:
w, g = a + 2, 12
elif layout == 2:
w, g = a + 6, ((mode >> 9) & 3) + 6
h = d = 0
elif bit(mode, 6):
return None
else:
w, g = (10, 6) if bit(mode, 5) else (6, 10)
return w, g, WEIGHT_RANGES[(h, r)], d
def color_range(cem, weight_bits):
"""The largest color range whose values fit in the bits left over."""
count = 2 * (cem // 4 + 1)
room = BLOCK_BITS - 17 - weight_bits
fits = [r for r in COLOR_RANGES if ise_bits(count, r) <= room]
return fits[-1] if fits else None
def blue_contract(r, g, b, a):
return ((r + b) >> 1, (g + b) >> 1, b, a)
def endpoints(cem, v):
"""Modes 8 and 12: 6 or 8 values in 0..255 -> two RGBA endpoints."""
if cem == 8:
v = list(v) + [255, 255]
if v[1] + v[3] + v[5] >= v[0] + v[2] + v[4]:
return (v[0], v[2], v[4], v[6]), (v[1], v[3], v[5], v[7])
return blue_contract(v[1], v[3], v[5], v[7]), blue_contract(v[0], v[2], v[4], v[6])
def infill(w, n, m, bw, bh, s, t):
"""The weight of texel (s, t) from the n x m grid w, by the fixed-point
bilinear rule of the format."""
ds = (1024 + bw // 2) // (bw - 1)
dt = (1024 + bh // 2) // (bh - 1)
gs = (ds * s * (n - 1) + 32) >> 6
gt = (dt * t * (m - 1) + 32) >> 6
js, fs, jt, ft = gs >> 4, gs & 15, gt >> 4, gt & 15
v0 = js + jt * n
w11 = (fs * ft + 8) >> 4
w10, w01 = ft - w11, fs - w11
w00 = 16 - fs - ft + w11
def at(k): # a neighbor past the grid always has the factor 0
return w[k] if k < len(w) else 0
return (at(v0) * w00 + at(v0 + 1) * w01 + at(v0 + n) * w10 + at(v0 + n + 1) * w11 + 8) >> 4
def interpolate(e0, e1, i):
c0, c1 = e0 << 8 | e0, e1 << 8 | e1
return (c0 * (64 - i) + c1 * i + 32) >> 6
def decode_block(block, bw, bh):
"""16 bytes -> bw * bh RGBA texels of 16-bit values, in raster order."""
if len(block) != 16 or (bw, bh) not in FOOTPRINTS:
raise ValueError("a block has 16 bytes and a legal 2D footprint")
bits = int.from_bytes(block, "little")
mode = decode_block_mode(bits & 0x7FF) # @line L1
if mode == "void":
raise NotImplementedError("void-extent blocks are outside this subset")
error = [ERROR_COLOR] * (bw * bh)
if mode is None or mode[0] > bw or mode[1] > bh:
return error
n, m, wmax, dual = mode
parts, cem = ((bits >> 11) & 3) + 1, (bits >> 13) & 15 # @line L2
if dual or parts != 1 or cem not in (8, 12):
raise NotImplementedError("only one plane, one partition and modes 8 and 12")
wbits = ise_bits(n * m, wmax) # @line L3
if n * m > 64 or not 24 <= wbits <= 96:
return error
cmax = color_range(cem, wbits) # @line L4
if cmax is None:
return error
raw = ise_decode(bits >> 17, 2 * (cem // 4 + 1), cmax)
v = [unquant_color(x, cmax) for x in raw] # @line L5
e0, e1 = endpoints(cem, v) # @line L6
wstream = sum(bit(bits, 127 - k) << k for k in range(wbits))
w = [unquant_weight(x, wmax) for x in ise_decode(wstream, n * m, wmax)] # @line L7
out = []
for t in range(bh):
for s in range(bw):
i = infill(w, n, m, bw, bh, s, t) # @line L8
out.append(tuple(interpolate(a, b, i) for a, b in zip(e0, e1))) # @line L9
return out # @line L10
# ---------------------------------------------------------------- packing (for tests)
MODE_OF = {}
for _mode in range(2048):
_info = decode_block_mode(_mode)
if isinstance(_info, tuple) and _info[3] == 0:
MODE_OF.setdefault(_info[:3], _mode)
def pack_block(n, m, wmax, cem, colors, weights):
"""Write a one-partition, one-plane block from raw (quantized) values."""
wbits = ise_bits(n * m, wmax)
cmax = color_range(cem, wbits)
if len(colors) != 2 * (cem // 4 + 1) or len(weights) != n * m or cmax is None:
raise ValueError("the fields do not fit")
cstream, _ = ise_encode(colors, cmax)
wstream, _ = ise_encode(weights, wmax)
bits = MODE_OF[(n, m, wmax)] | cem << 13 | cstream << 17
for k in range(wbits):
bits |= bit(wstream, k) << (127 - k)
return bits.to_bytes(16, "little"), cmax
test_adaptive_scalable_texture_compression.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-scalable-texture-compression/. The authors are listed in prov/XB2HVD.jsonl.
"""Tests of the ASTC subset: the BISE layout and round trip, the
unquantization tables, the block modes, and the decoding of one-partition
LDR blocks with the color endpoint modes 8 and 12."""
import random
from fractions import Fraction
from math import ceil, log2
from adaptive_scalable_texture_compression import (
COLOR_RANGES,
DECODE_TABLE,
ERROR_COLOR,
FOOTPRINTS,
MODE_OF,
WEIGHT_RANGES,
bits_per_texel,
decode_block,
decode_block_mode,
endpoints,
infill,
interpolate,
ise_bits,
ise_decode,
ise_encode,
ise_params,
ise_rate,
pack_block,
unquant_color,
unquant_weight,
)
ALL_RANGES = sorted(set(COLOR_RANGES) | set(WEIGHT_RANGES.values()))
def test_rates_and_layout():
assert bits_per_texel(4, 4) == 8 and bits_per_texel(12, 12) == Fraction(8, 9)
assert bits_per_texel(6, 6) == Fraction(32, 9)
assert ise_rate(11) == 2 + Fraction(8, 5) and ise_rate(9) == 1 + Fraction(7, 3)
for mx in ALL_RANGES:
kind, n = ise_params(mx)
# The rate is at most 1% above the information content log2(mx + 1).
assert log2(mx + 1) <= ise_rate(mx) <= 1.01 * log2(mx + 1) + 1e-12
for count in range(1, 70):
extra = {"bits": 0, "trit": ceil(8 * count / 5), "quint": ceil(7 * count / 3)}[kind]
assert ise_bits(count, mx) == count * n + extra
def test_packed_fields_cover_every_tuple():
trits, quints = DECODE_TABLE["trit"], DECODE_TABLE["quint"]
assert len(trits) == 256 and len(set(trits)) == 3 ** 5
assert len(quints) == 128 and len(set(quints)) == 5 ** 3
def test_trit_group_bit_positions():
# Five values in 0..47 (n = 4): m0 T[1:0] m1 T[3:2] m2 T[4] m3 T[6:5] m4 T[7].
rng = random.Random(1)
for _ in range(200):
vals = [rng.randrange(48) for _ in range(5)]
stream, length = ise_encode(vals, 47)
assert length == 28
for j, start in enumerate((0, 6, 12, 17, 23)):
assert (stream >> start) & 15 == vals[j] & 15
t = ((stream >> 4) & 3) | ((stream >> 10) & 3) << 2 | ((stream >> 16) & 1) << 4 \
| ((stream >> 21) & 3) << 5 | ((stream >> 27) & 1) << 7
assert DECODE_TABLE["trit"][t] == tuple(v >> 4 for v in vals)
def test_round_trip_all_ranges_and_partial_groups():
rng = random.Random(2)
for mx in ALL_RANGES:
for count in range(1, 40):
vals = [rng.randrange(mx + 1) for _ in range(count)]
stream, length = ise_encode(vals, mx)
assert stream < 1 << length
assert ise_decode(stream, count, mx) == vals
# Bits past the end are read as zero, whatever the block holds there.
noise = rng.getrandbits(64) << length
assert ise_decode(stream | noise, count, mx) == vals
def test_round_trip_every_short_trit_and_quint_group():
for mx, size in ((2, 5), (5, 5), (4, 3), (9, 3)):
kind, n = ise_params(mx)
for count in range(1, size + 1):
for high in range(3 ** count if kind == "trit" else 5 ** count):
digits, h = [], high
for _ in range(count):
digits.append(h % (3 if kind == "trit" else 5))
h //= 3 if kind == "trit" else 5
vals = [d << n | (j & ((1 << n) - 1)) for j, d in enumerate(digits)]
stream, length = ise_encode(vals, mx)
assert ise_decode(stream, count, mx) == vals
def test_unquantization_tables():
for mx in COLOR_RANGES:
u = [unquant_color(v, mx) for v in range(mx + 1)]
assert len(set(u)) == mx + 1 and min(u) == 0 and max(u) == 255
kind, n = ise_params(mx)
if kind != "bits": # flipping the lowest bit mirrors the value
assert all(unquant_color(v ^ 1, mx) == 255 - unquant_color(v, mx) for v in range(mx + 1))
for mx in sorted(set(WEIGHT_RANGES.values())):
u = sorted(unquant_weight(v, mx) for v in range(mx + 1))
assert len(set(u)) == mx + 1 and u[0] == 0 and u[-1] == 64
# The levels are close to even: every gap is within 3 of 64 / mx.
assert all(abs((b - a) - 64 / mx) < 3 for a, b in zip(u, u[1:]))
# The quantized order is not the order of the values.
assert [unquant_weight(v, 11) for v in range(4)] == [0, 64, 17, 47]
def test_block_modes():
infos = [decode_block_mode(m) for m in range(2048)]
assert sum(1 for x in infos if x == "void") == 4
for info in infos:
if isinstance(info, tuple):
w, h, wmax, dual = info
assert 2 <= w <= 12 and 2 <= h <= 12 and wmax in WEIGHT_RANGES.values()
for (w, h, wmax), mode in MODE_OF.items():
assert decode_block_mode(mode) == (w, h, wmax, 0)
assert (4, 4, 11) in MODE_OF and (8, 8, 1) in MODE_OF and (6, 10, 3) in MODE_OF
assert max(w * h for w, h, _ in MODE_OF) == 81 # 9 x 9, more than the 64 weights allowed
def test_infill_identity_and_constants():
rng = random.Random(3)
for bw, bh in FOOTPRINTS:
w = [rng.randrange(65) for _ in range(bw * bh)]
assert all(infill(w, bw, bh, bw, bh, s, t) == w[t * bw + s] for t in range(bh) for s in range(bw))
for n in range(2, bw + 1):
for m in range(2, bh + 1):
c = rng.randrange(65)
assert all(infill([c] * (n * m), n, m, bw, bh, s, t) == c
for t in range(bh) for s in range(bw))
g = [rng.randrange(65) for _ in range(n * m)]
assert infill(g, n, m, bw, bh, 0, 0) == g[0]
assert infill(g, n, m, bw, bh, bw - 1, bh - 1) == g[-1]
def test_interpolation_ends():
for e0 in range(0, 256, 15):
for e1 in range(0, 256, 17):
assert interpolate(e0, e1, 0) == 257 * e0 and interpolate(e0, e1, 64) == 257 * e1
row = [interpolate(e0, e1, i) for i in range(65)]
assert row == sorted(row) or row == sorted(row, reverse=True)
def test_decode_matches_the_fields():
rng = random.Random(4)
cases = [((4, 4), (4, 4)), ((6, 6), (3, 5)), ((8, 8), (5, 4)), ((12, 12), (6, 6)), ((10, 5), (10, 5))]
for (bw, bh), (n, m) in cases:
for wmax in sorted(set(WEIGHT_RANGES.values())):
if (n, m, wmax) not in MODE_OF or not 24 <= ise_bits(n * m, wmax) <= 96:
continue
for cem in (8, 12):
try:
probe = pack_block(n, m, wmax, cem, [0] * (2 * (cem // 4 + 1)), [0] * (n * m))
except ValueError:
continue
cmax = probe[1]
colors = [rng.randrange(cmax + 1) for _ in range(2 * (cem // 4 + 1))]
weights = [rng.randrange(wmax + 1) for _ in range(n * m)]
block, _ = pack_block(n, m, wmax, cem, colors, weights)
e0, e1 = endpoints(cem, [unquant_color(c, cmax) for c in colors])
w = [unquant_weight(x, wmax) for x in weights]
out = decode_block(block, bw, bh)
for t in range(bh):
for s in range(bw):
i = infill(w, n, m, bw, bh, s, t)
want = tuple((257 * a * (64 - i) + 257 * b * i + 32) // 64 for a, b in zip(e0, e1))
assert out[t * bw + s] == want
def test_blue_contraction_and_constant_blocks():
assert endpoints(8, [40, 200, 100, 220, 50, 60]) == ((40, 100, 50, 255), (200, 220, 60, 255))
assert endpoints(8, [200, 40, 220, 100, 60, 50]) == ((45, 75, 50, 255), (130, 140, 60, 255))
assert endpoints(12, [200, 40, 220, 100, 60, 50, 7, 9]) == ((45, 75, 50, 9), (130, 140, 60, 7))
block, cmax = pack_block(4, 4, 11, 8, [40, 200, 100, 220, 50, 60], [0] * 16)
assert cmax == 255
assert decode_block(block, 4, 4) == [(40 * 257, 100 * 257, 50 * 257, 65535)] * 16
block, _ = pack_block(4, 4, 11, 8, [40, 200, 100, 220, 50, 60], [1] * 16) # 1 means 64
assert decode_block(block, 4, 4) == [(200 * 257, 220 * 257, 60 * 257, 65535)] * 16
def test_error_blocks_and_random_access():
block, _ = pack_block(8, 8, 1, 8, [10, 20, 30, 40, 50, 60], [0, 1] * 32)
assert decode_block(block, 8, 8)[0] != ERROR_COLOR
assert decode_block(block, 6, 6) == [ERROR_COLOR] * 36 # the grid is larger than the block
bits = int.from_bytes(block, "little") & ~0x7FF # mode 0 is reserved
assert decode_block(bits.to_bytes(16, "little"), 8, 8) == [ERROR_COLOR] * 64
# A block decodes alone: the same 16 bytes give the same texels.
assert decode_block(bytes(block), 8, 8) == decode_block(block, 8, 8)
History
Jørn Nystad, Anders Lassen, Andy Pomianowski, Sean Ellis and Tom Olson designed ASTC and presented it at High Performance Graphics in 2012. Their goal was one format for all kinds of content and many bit rates, in place of several formats with fixed rates. Khronos adopted it as an extension for OpenGL and OpenGL ES, with an LDR and an HDR profile, and later Vulkan supported it too. It became the main compressed texture format on mobile GPUs.
References
- Jørn Nystad, Anders Lassen, Andy Pomianowski, Sean Ellis and Tom Olson, Adaptive scalable texture compression, High Performance Graphics 2012, pages 105 to 114 (the block layout, bounded integer sequence encoding, the color endpoint modes and partitions, and the quality measurements)
- Khronos Group, KHR_texture_compression_astc_hdr and KHR_texture_compression_astc_ldr, OpenGL extension specification, the appendix on the ASTC format (block mode table, weight ranges, integer sequence encoding, unquantization tables, color endpoint modes and weight infill)
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Section 6.2, Image Texturing, the part on texture compression (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XB2HVD Edit this page History Report an error Markdown