bc1.glsl 15 KB

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