Debian Codegraph @

modules/betsy/bc1.glsl

raw
1 #[versions]
2
3 standard = "";
4 dithered = "#define BC1_DITHER";
5
6 #[compute]
7 #version 450
8
9 #VERSION_DEFINES
10
11 #define FLT_MAX 340282346638528859811704183484516925440.0f
12
13 layout(binding = 0) uniform sampler2D srcTex;
14 layout(binding = 1, rg32ui) uniform restrict writeonly uimage2D dstTexture;
15
16 layout(std430, binding = 2) readonly restrict buffer globalBuffer {
17 vec2 c_oMatch5[256];
18 vec2 c_oMatch6[256];
19 };
20
21 layout(push_constant, std430) uniform Params {
22 uint p_numRefinements;
23 uint p_padding[3];
24 }
25 params;
26
27 layout(local_size_x = 8, //
28 local_size_y = 8, //
29 local_size_z = 1) in;
30
31 vec3 rgb565to888(float rgb565) {
32 vec3 retVal;
33 retVal.x = floor(rgb565 / 2048.0f);
34 retVal.y = floor(mod(rgb565, 2048.0f) / 32.0f);
35 retVal.z = floor(mod(rgb565, 32.0f));
36
37 // This is the correct 565 to 888 conversion:
38 // rgb = floor( rgb * ( 255.0f / vec3( 31.0f, 63.0f, 31.0f ) ) + 0.5f )
39 //
40 // However stb_dxt follows a different one:
41 // rb = floor( rb * ( 256 / 32 + 8 / 32 ) );
42 // g = floor( g * ( 256 / 64 + 4 / 64 ) );
43 //
44 // I'm not sure exactly why but it's possible this is how the S3TC specifies it should be decoded
45 // It's quite possible this is the reason:
46 // http://www.ludicon.com/castano/blog/2009/03/gpu-dxt-decompression/
47 //
48 // Or maybe it's just because it's cheap to do with integer shifts.
49 // Anyway, we follow stb_dxt's conversion just in case
50 // (gives almost the same result, with 1 or -1 of difference for a very few values)
51 //
52 // Perhaps when we make 888 -> 565 -> 888 it doesn't matter
53 // because they end up mapping to the original number
54
55 return floor(retVal * vec3(8.25f, 4.0625f, 8.25f));
56 }
57
58 float rgb888to565(vec3 rgbValue) {
59 rgbValue.rb = floor(rgbValue.rb * 31.0f / 255.0f + 0.5f);
60 rgbValue.g = floor(rgbValue.g * 63.0f / 255.0f + 0.5f);
61
62 return rgbValue.r * 2048.0f + rgbValue.g * 32.0f + rgbValue.b;
63 }
64
65 // linear interpolation at 1/3 point between a and b, using desired rounding type
66 vec3 lerp13(vec3 a, vec3 b) {
67 #ifdef STB_DXT_USE_ROUNDING_BIAS
68 // with rounding bias
69 return a + floor((b - a) * (1.0f / 3.0f) + 0.5f);
70 #else
71 // without rounding bias
72 return floor((2.0f * a + b) / 3.0f);
73 #endif
74 }
75
76 /// Unpacks a block of 4 colors from two 16-bit endpoints
77 void EvalColors(out vec3 colors[4], float c0, float c1) {
78 colors[0] = rgb565to888(c0);
79 colors[1] = rgb565to888(c1);
80 colors[2] = lerp13(colors[0], colors[1]);
81 colors[3] = lerp13(colors[1], colors[0]);
82 }
83
84 /** The color optimization function. (Clever code, part 1)
85 @param outMinEndp16 [out]
86 Minimum endpoint, in RGB565
87 @param outMaxEndp16 [out]
88 Maximum endpoint, in RGB565
89 */
90 void OptimizeColorsBlock(const uint srcPixelsBlock[16], out float outMinEndp16, out float outMaxEndp16) {
91 // determine color distribution
92 vec3 avgColor;
93 vec3 minColor;
94 vec3 maxColor;
95
96 avgColor = minColor = maxColor = unpackUnorm4x8(srcPixelsBlock[0]).xyz;
97 for (int i = 1; i < 16; ++i) {
98 const vec3 currColorUnorm = unpackUnorm4x8(srcPixelsBlock[i]).xyz;
99 avgColor += currColorUnorm;
100 minColor = min(minColor, currColorUnorm);
101 maxColor = max(maxColor, currColorUnorm);
102 }
103
104 avgColor = round(avgColor * 255.0f / 16.0f);
105 maxColor *= 255.0f;
106 minColor *= 255.0f;
107
108 // determine covariance matrix
109 float cov[6];
110 for (int i = 0; i < 6; ++i) {
111 cov[i] = 0;
112 }
113
114 for (int i = 0; i < 16; ++i) {
115 const vec3 currColor = unpackUnorm4x8(srcPixelsBlock[i]).xyz * 255.0f;
116 vec3 rgbDiff = currColor - avgColor;
117
118 cov[0] += rgbDiff.r * rgbDiff.r;
119 cov[1] += rgbDiff.r * rgbDiff.g;
120 cov[2] += rgbDiff.r * rgbDiff.b;
121 cov[3] += rgbDiff.g * rgbDiff.g;
122 cov[4] += rgbDiff.g * rgbDiff.b;
123 cov[5] += rgbDiff.b * rgbDiff.b;
124 }
125
126 // convert covariance matrix to float, find principal axis via power iter
127 for (int i = 0; i < 6; ++i) {
128 cov[i] /= 255.0f;
129 }
130
131 vec3 vF = maxColor - minColor;
132
133 const int nIterPower = 4;
134 for (int iter = 0; iter < nIterPower; ++iter) {
135 const float r = vF.r * cov[0] + vF.g * cov[1] + vF.b * cov[2];
136 const float g = vF.r * cov[1] + vF.g * cov[3] + vF.b * cov[4];
137 const float b = vF.r * cov[2] + vF.g * cov[4] + vF.b * cov[5];
138
139 vF.r = r;
140 vF.g = g;
141 vF.b = b;
142 }
143
144 float magn = max(abs(vF.r), max(abs(vF.g), abs(vF.b)));
145 vec3 v;
146
147 if (magn < 4.0f) { // too small, default to luminance
148 v.r = 299.0f; // JPEG YCbCr luma coefs, scaled by 1000.
149 v.g = 587.0f;
150 v.b = 114.0f;
151 } else {
152 v = trunc(vF * (512.0f / magn));
153 }
154
155 // Pick colors at extreme points
156 vec3 minEndpoint, maxEndpoint;
157 float minDot = FLT_MAX;
158 float maxDot = -FLT_MAX;
159 for (int i = 0; i < 16; ++i) {
160 const vec3 currColor = unpackUnorm4x8(srcPixelsBlock[i]).xyz * 255.0f;
161 const float dotValue = dot(currColor, v);
162
163 if (dotValue < minDot) {
164 minDot = dotValue;
165 minEndpoint = currColor;
166 }
167
168 if (dotValue > maxDot) {
169 maxDot = dotValue;
170 maxEndpoint = currColor;
171 }
172 }
173
174 outMinEndp16 = rgb888to565(minEndpoint);
175 outMaxEndp16 = rgb888to565(maxEndpoint);
176 }
177
178 // The color matching function
179 uint MatchColorsBlock(const uint srcPixelsBlock[16], vec3 color[4]) {
180 uint mask = 0u;
181 vec3 dir = color[0] - color[1];
182 float stops[4];
183
184 for (int i = 0; i < 4; ++i) {
185 stops[i] = dot(color[i], dir);
186 }
187
188 // think of the colors as arranged on a line; project point onto that line, then choose
189 // next color out of available ones. we compute the crossover points for "best color in top
190 // half"/"best in bottom half" and then the same inside that subinterval.
191 //
192 // relying on this 1d approximation isn't always optimal in terms of euclidean distance,
193 // but it's very close and a lot faster.
194 // http://cbloomrants.blogspot.com/2008/12/12-08-08-dxtc-summary.html
195
196 float c0Point = trunc((stops[1] + stops[3]) * 0.5f);
197 float halfPoint = trunc((stops[3] + stops[2]) * 0.5f);
198 float c3Point = trunc((stops[2] + stops[0]) * 0.5f);
199
200 #ifndef BC1_DITHER
201 // the version without dithering is straightforward
202 for (uint i = 16u; i-- > 0u;) {
203 const vec3 currColor = unpackUnorm4x8(srcPixelsBlock[i]).xyz * 255.0f;
204
205 const float dotValue = dot(currColor, dir);
206 mask <<= 2u;
207
208 if (dotValue < halfPoint) {
209 mask |= ((dotValue < c0Point) ? 1u : 3u);
210 } else {
211 mask |= ((dotValue < c3Point) ? 2u : 0u);
212 }
213 }
214 #else
215 // with floyd-steinberg dithering
216 vec4 ep1 = vec4(0, 0, 0, 0);
217 vec4 ep2 = vec4(0, 0, 0, 0);
218
219 c0Point *= 16.0f;
220 halfPoint *= 16.0f;
221 c3Point *= 16.0f;
222
223 for (uint y = 0u; y < 4u; ++y) {
224 float ditherDot;
225 uint lmask, step;
226
227 vec3 currColor;
228 float dotValue;
229
230 currColor = unpackUnorm4x8(srcPixelsBlock[y * 4 + 0]).xyz * 255.0f;
231 dotValue = dot(currColor, dir);
232
233 ditherDot = (dotValue * 16.0f) + (3 * ep2[1] + 5 * ep2[0]);
234 if (ditherDot < halfPoint) {
235 step = (ditherDot < c0Point) ? 1u : 3u;
236 } else {
237 step = (ditherDot < c3Point) ? 2u : 0u;
238 }
239 ep1[0] = dotValue - stops[step];
240 lmask = step;
241
242 currColor = unpackUnorm4x8(srcPixelsBlock[y * 4 + 1]).xyz * 255.0f;
243 dotValue = dot(currColor, dir);
244
245 ditherDot = (dotValue * 16.0f) + (7 * ep1[0] + 3 * ep2[2] + 5 * ep2[1] + ep2[0]);
246 if (ditherDot < halfPoint) {
247 step = (ditherDot < c0Point) ? 1u : 3u;
248 } else {
249 step = (ditherDot < c3Point) ? 2u : 0u;
250 }
251 ep1[1] = dotValue - stops[step];
252 lmask |= step << 2u;
253
254 currColor = unpackUnorm4x8(srcPixelsBlock[y * 4 + 2]).xyz * 255.0f;
255 dotValue = dot(currColor, dir);
256
257 ditherDot = (dotValue * 16.0f) + (7 * ep1[1] + 3 * ep2[3] + 5 * ep2[2] + ep2[1]);
258 if (ditherDot < halfPoint) {
259 step = (ditherDot < c0Point) ? 1u : 3u;
260 } else {
261 step = (ditherDot < c3Point) ? 2u : 0u;
262 }
263 ep1[2] = dotValue - stops[step];
264 lmask |= step << 4u;
265
266 currColor = unpackUnorm4x8(srcPixelsBlock[y * 4 + 2]).xyz * 255.0f;
267 dotValue = dot(currColor, dir);
268
269 ditherDot = (dotValue * 16.0f) + (7 * ep1[2] + 5 * ep2[3] + ep2[2]);
270 if (ditherDot < halfPoint) {
271 step = (ditherDot < c0Point) ? 1u : 3u;
272 } else {
273 step = (ditherDot < c3Point) ? 2u : 0u;
274 }
275 ep1[3] = dotValue - stops[step];
276 lmask |= step << 6u;
277
278 mask |= lmask << (y * 8u);
279 {
280 vec4 tmp = ep1;
281 ep1 = ep2;
282 ep2 = tmp;
283 } // swap
284 }
285 #endif
286
287 return mask;
288 }
289
290 // The refinement function. (Clever code, part 2)
291 // Tries to optimize colors to suit block contents better.
292 // (By solving a least squares system via normal equations+Cramer's rule)
293 bool RefineBlock(const uint srcPixelsBlock[16], uint mask, inout float inOutMinEndp16,
294 inout float inOutMaxEndp16) {
295 float newMin16, newMax16;
296 const float oldMin = inOutMinEndp16;
297 const float oldMax = inOutMaxEndp16;
298
299 if ((mask ^ (mask << 2u)) < 4u) // all pixels have the same index?
300 {
301 // yes, linear system would be singular; solve using optimal
302 // single-color match on average color
303 vec3 rgbVal = vec3(8.0f / 255.0f, 8.0f / 255.0f, 8.0f / 255.0f);
304 for (int i = 0; i < 16; ++i) {
305 rgbVal += unpackUnorm4x8(srcPixelsBlock[i]).xyz;
306 }
307
308 rgbVal = floor(rgbVal * (255.0f / 16.0f));
309
310 newMax16 = c_oMatch5[uint(rgbVal.r)][0] * 2048.0f + //
311 c_oMatch6[uint(rgbVal.g)][0] * 32.0f + //
312 c_oMatch5[uint(rgbVal.b)][0];
313 newMin16 = c_oMatch5[uint(rgbVal.r)][1] * 2048.0f + //
314 c_oMatch6[uint(rgbVal.g)][1] * 32.0f + //
315 c_oMatch5[uint(rgbVal.b)][1];
316 } else {
317 const float w1Tab[4] = { 3, 0, 2, 1 };
318 const float prods[4] = { 589824.0f, 2304.0f, 262402.0f, 66562.0f };
319 // ^some magic to save a lot of multiplies in the accumulating loop...
320 // (precomputed products of weights for least squares system, accumulated inside one 32-bit
321 // register)
322
323 float akku = 0.0f;
324 uint cm = mask;
325 vec3 at1 = vec3(0, 0, 0);
326 vec3 at2 = vec3(0, 0, 0);
327 for (int i = 0; i < 16; ++i, cm >>= 2u) {
328 const vec3 currColor = unpackUnorm4x8(srcPixelsBlock[i]).xyz * 255.0f;
329
330 const uint step = cm & 3u;
331 const float w1 = w1Tab[step];
332 akku += prods[step];
333 at1 += currColor * w1;
334 at2 += currColor;
335 }
336
337 at2 = 3.0f * at2 - at1;
338
339 // extract solutions and decide solvability
340 const float xx = floor(akku / 65535.0f);
341 const float yy = floor(mod(akku, 65535.0f) / 256.0f);
342 const float xy = mod(akku, 256.0f);
343
344 vec2 f_rb_g;
345 f_rb_g.x = 3.0f * 31.0f / 255.0f / (xx * yy - xy * xy);
346 f_rb_g.y = f_rb_g.x * 63.0f / 31.0f;
347
348 // solve.
349 const vec3 newMaxVal = clamp(floor((at1 * yy - at2 * xy) * f_rb_g.xyx + 0.5f),
350 vec3(0.0f, 0.0f, 0.0f), vec3(31, 63, 31));
351 newMax16 = newMaxVal.x * 2048.0f + newMaxVal.y * 32.0f + newMaxVal.z;
352
353 const vec3 newMinVal = clamp(floor((at2 * xx - at1 * xy) * f_rb_g.xyx + 0.5f),
354 vec3(0.0f, 0.0f, 0.0f), vec3(31, 63, 31));
355 newMin16 = newMinVal.x * 2048.0f + newMinVal.y * 32.0f + newMinVal.z;
356 }
357
358 inOutMinEndp16 = newMin16;
359 inOutMaxEndp16 = newMax16;
360
361 return oldMin != newMin16 || oldMax != newMax16;
362 }
363
364 #ifdef BC1_DITHER
365 /// Quantizes 'srcValue' which is originally in 888 (full range),
366 /// converting it to 565 and then back to 888 (quantized)
367 vec3 quant(vec3 srcValue) {
368 srcValue = clamp(srcValue, 0.0f, 255.0f);
369 // Convert 888 -> 565
370 srcValue = floor(srcValue * vec3(31.0f / 255.0f, 63.0f / 255.0f, 31.0f / 255.0f) + 0.5f);
371 // Convert 565 -> 888 back
372 srcValue = floor(srcValue * vec3(8.25f, 4.0625f, 8.25f));
373
374 return srcValue;
375 }
376
377 void DitherBlock(const uint srcPixBlck[16], out uint dthPixBlck[16]) {
378 vec3 ep1[4] = { vec3(0, 0, 0), vec3(0, 0, 0), vec3(0, 0, 0), vec3(0, 0, 0) };
379 vec3 ep2[4] = { vec3(0, 0, 0), vec3(0, 0, 0), vec3(0, 0, 0), vec3(0, 0, 0) };
380
381 for (uint y = 0u; y < 16u; y += 4u) {
382 vec3 srcPixel, dithPixel;
383
384 srcPixel = unpackUnorm4x8(srcPixBlck[y + 0u]).xyz * 255.0f;
385 dithPixel = quant(srcPixel + trunc((3 * ep2[1] + 5 * ep2[0]) * (1.0f / 16.0f)));
386 ep1[0] = srcPixel - dithPixel;
387 dthPixBlck[y + 0u] = packUnorm4x8(vec4(dithPixel * (1.0f / 255.0f), 1.0f));
388
389 srcPixel = unpackUnorm4x8(srcPixBlck[y + 1u]).xyz * 255.0f;
390 dithPixel = quant(
391 srcPixel + trunc((7 * ep1[0] + 3 * ep2[2] + 5 * ep2[1] + ep2[0]) * (1.0f / 16.0f)));
392 ep1[1] = srcPixel - dithPixel;
393 dthPixBlck[y + 1u] = packUnorm4x8(vec4(dithPixel * (1.0f / 255.0f), 1.0f));
394
395 srcPixel = unpackUnorm4x8(srcPixBlck[y + 2u]).xyz * 255.0f;
396 dithPixel = quant(
397 srcPixel + trunc((7 * ep1[1] + 3 * ep2[3] + 5 * ep2[2] + ep2[1]) * (1.0f / 16.0f)));
398 ep1[2] = srcPixel - dithPixel;
399 dthPixBlck[y + 2u] = packUnorm4x8(vec4(dithPixel * (1.0f / 255.0f), 1.0f));
400
401 srcPixel = unpackUnorm4x8(srcPixBlck[y + 3u]).xyz * 255.0f;
402 dithPixel = quant(srcPixel + trunc((7 * ep1[2] + 5 * ep2[3] + ep2[2]) * (1.0f / 16.0f)));
403 ep1[3] = srcPixel - dithPixel;
404 dthPixBlck[y + 3u] = packUnorm4x8(vec4(dithPixel * (1.0f / 255.0f), 1.0f));
405
406 // swap( ep1, ep2 )
407 for (uint i = 0u; i < 4u; ++i) {
408 vec3 tmp = ep1[i];
409 ep1[i] = ep2[i];
410 ep2[i] = tmp;
411 }
412 }
413 }
414 #endif
415
416 void main() {
417 uint srcPixelsBlock[16];
418
419 bool bAllColorsEqual = true;
420
421 // Load the whole 4x4 block
422 const uvec2 pixelsToLoadBase = gl_GlobalInvocationID.xy << 2u;
423 for (uint i = 0u; i < 16u; ++i) {
424 const uvec2 pixelsToLoad = pixelsToLoadBase + uvec2(i & 0x03u, i >> 2u);
425 const vec3 srcPixels0 = texelFetch(srcTex, ivec2(pixelsToLoad), 0).xyz;
426 srcPixelsBlock[i] = packUnorm4x8(vec4(srcPixels0, 1.0f));
427 bAllColorsEqual = bAllColorsEqual && srcPixelsBlock[0] == srcPixelsBlock[i];
428 }
429
430 float maxEndp16, minEndp16;
431 uint mask = 0u;
432
433 if (bAllColorsEqual) {
434 const uvec3 rgbVal = uvec3(unpackUnorm4x8(srcPixelsBlock[0]).xyz * 255.0f);
435 mask = 0xAAAAAAAAu;
436 maxEndp16 =
437 c_oMatch5[rgbVal.r][0] * 2048.0f + c_oMatch6[rgbVal.g][0] * 32.0f + c_oMatch5[rgbVal.b][0];
438 minEndp16 =
439 c_oMatch5[rgbVal.r][1] * 2048.0f + c_oMatch6[rgbVal.g][1] * 32.0f + c_oMatch5[rgbVal.b][1];
440 } else {
441 #ifdef BC1_DITHER
442 uint ditherPixelsBlock[16];
443 // first step: compute dithered version for PCA if desired
444 DitherBlock(srcPixelsBlock, ditherPixelsBlock);
445 #else
446 #define ditherPixelsBlock srcPixelsBlock
447 #endif
448
449 // second step: pca+map along principal axis
450 OptimizeColorsBlock(ditherPixelsBlock, minEndp16, maxEndp16);
451 if (minEndp16 != maxEndp16) {
452 vec3 colors[4];
453 EvalColors(colors, maxEndp16, minEndp16); // Note min/max are inverted
454 mask = MatchColorsBlock(srcPixelsBlock, colors);
455 }
456
457 // third step: refine (multiple times if requested)
458 bool bStopRefinement = false;
459 for (uint i = 0u; i < params.p_numRefinements && !bStopRefinement; ++i) {
460 const uint lastMask = mask;
461
462 if (RefineBlock(ditherPixelsBlock, mask, minEndp16, maxEndp16)) {
463 if (minEndp16 != maxEndp16) {
464 vec3 colors[4];
465 EvalColors(colors, maxEndp16, minEndp16); // Note min/max are inverted
466 mask = MatchColorsBlock(srcPixelsBlock, colors);
467 } else {
468 mask = 0u;
469 bStopRefinement = true;
470 }
471 }
472
473 bStopRefinement = mask == lastMask || bStopRefinement;
474 }
475 }
476
477 // write the color block
478 if (maxEndp16 < minEndp16) {
479 const float tmpValue = minEndp16;
480 minEndp16 = maxEndp16;
481 maxEndp16 = tmpValue;
482 mask ^= 0x55555555u;
483 }
484
485 uvec2 outputBytes;
486 outputBytes.x = uint(maxEndp16) | (uint(minEndp16) << 16u);
487 outputBytes.y = mask;
488
489 uvec2 dstUV = gl_GlobalInvocationID.xy;
490 imageStore(dstTexture, ivec2(dstUV), uvec4(outputBytes.xy, 0u, 0u));
491 }