AstcDecoder.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. namespace Ryujinx.Graphics.Texture.Astc
  7. {
  8. // https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp
  9. public static class AstcDecoder
  10. {
  11. struct TexelWeightParams
  12. {
  13. public int Width;
  14. public int Height;
  15. public bool DualPlane;
  16. public int MaxWeight;
  17. public bool Error;
  18. public bool VoidExtentLdr;
  19. public bool VoidExtentHdr;
  20. public int GetPackedBitSize()
  21. {
  22. // How many indices do we have?
  23. int indices = Height * Width;
  24. if (DualPlane)
  25. {
  26. indices *= 2;
  27. }
  28. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight);
  29. return intEncoded.GetBitLength(indices);
  30. }
  31. public int GetNumWeightValues()
  32. {
  33. int ret = Width * Height;
  34. if (DualPlane)
  35. {
  36. ret *= 2;
  37. }
  38. return ret;
  39. }
  40. }
  41. public static Span<byte> DecodeToRgba8(
  42. Span<byte> data,
  43. int blockWidth,
  44. int blockHeight,
  45. int blockDepth,
  46. int width,
  47. int height,
  48. int depth)
  49. {
  50. using (MemoryStream inputStream = new MemoryStream(data.ToArray()))
  51. {
  52. BinaryReader binReader = new BinaryReader(inputStream);
  53. if (blockWidth > 12 || blockHeight > 12)
  54. {
  55. throw new AstcDecoderException("Invalid block size.");
  56. }
  57. if (blockDepth != 1 || depth != 1)
  58. {
  59. // TODO: Support 3D textures.
  60. throw new NotImplementedException("3D compressed textures are not unsupported.");
  61. }
  62. using (MemoryStream outputStream = new MemoryStream())
  63. {
  64. int blockIndex = 0;
  65. for (int j = 0; j < height; j += blockHeight)
  66. {
  67. for (int i = 0; i < width; i += blockWidth)
  68. {
  69. int[] decompressedData = new int[144];
  70. DecompressBlock(binReader.ReadBytes(0x10), decompressedData, blockWidth, blockHeight);
  71. int decompressedWidth = Math.Min(blockWidth, width - i);
  72. int decompressedHeight = Math.Min(blockHeight, height - j);
  73. int baseOffsets = (j * width + i) * 4;
  74. for (int jj = 0; jj < decompressedHeight; jj++)
  75. {
  76. outputStream.Seek(baseOffsets + jj * width * 4, SeekOrigin.Begin);
  77. byte[] outputBuffer = new byte[decompressedData.Length * sizeof(int)];
  78. Buffer.BlockCopy(decompressedData, 0, outputBuffer, 0, outputBuffer.Length);
  79. outputStream.Write(outputBuffer, jj * blockWidth * 4, decompressedWidth * 4);
  80. }
  81. blockIndex++;
  82. }
  83. }
  84. return outputStream.ToArray();
  85. }
  86. }
  87. }
  88. public static bool DecompressBlock(
  89. byte[] inputBuffer,
  90. int[] outputBuffer,
  91. int blockWidth,
  92. int blockHeight)
  93. {
  94. BitArrayStream bitStream = new BitArrayStream(new BitArray(inputBuffer));
  95. TexelWeightParams texelParams = DecodeBlockInfo(bitStream);
  96. if (texelParams.Error)
  97. {
  98. throw new AstcDecoderException("Invalid block mode.");
  99. }
  100. if (texelParams.VoidExtentLdr)
  101. {
  102. FillVoidExtentLdr(bitStream, outputBuffer, blockWidth, blockHeight);
  103. return true;
  104. }
  105. if (texelParams.VoidExtentHdr)
  106. {
  107. throw new AstcDecoderException("HDR void extent blocks are not supported.");
  108. }
  109. if (texelParams.Width > blockWidth)
  110. {
  111. throw new AstcDecoderException("Texel weight grid width should be smaller than block width.");
  112. }
  113. if (texelParams.Height > blockHeight)
  114. {
  115. throw new AstcDecoderException("Texel weight grid height should be smaller than block height.");
  116. }
  117. // Read num partitions
  118. int numberPartitions = bitStream.ReadBits(2) + 1;
  119. Debug.Assert(numberPartitions <= 4);
  120. if (numberPartitions == 4 && texelParams.DualPlane)
  121. {
  122. throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks.");
  123. }
  124. // Based on the number of partitions, read the color endpoint mode for
  125. // each partition.
  126. // Determine partitions, partition index, and color endpoint modes
  127. int planeIndices = -1;
  128. int partitionIndex;
  129. uint[] colorEndpointMode = { 0, 0, 0, 0 };
  130. BitArrayStream colorEndpointStream = new BitArrayStream(new BitArray(16 * 8));
  131. // Read extra config data...
  132. uint baseColorEndpointMode = 0;
  133. if (numberPartitions == 1)
  134. {
  135. colorEndpointMode[0] = (uint)bitStream.ReadBits(4);
  136. partitionIndex = 0;
  137. }
  138. else
  139. {
  140. partitionIndex = bitStream.ReadBits(10);
  141. baseColorEndpointMode = (uint)bitStream.ReadBits(6);
  142. }
  143. uint baseMode = (baseColorEndpointMode & 3);
  144. // Remaining bits are color endpoint data...
  145. int numberWeightBits = texelParams.GetPackedBitSize();
  146. int remainingBits = 128 - numberWeightBits - bitStream.Position;
  147. // Consider extra bits prior to texel data...
  148. uint extraColorEndpointModeBits = 0;
  149. if (baseMode != 0)
  150. {
  151. switch (numberPartitions)
  152. {
  153. case 2: extraColorEndpointModeBits += 2; break;
  154. case 3: extraColorEndpointModeBits += 5; break;
  155. case 4: extraColorEndpointModeBits += 8; break;
  156. default: Debug.Assert(false); break;
  157. }
  158. }
  159. remainingBits -= (int)extraColorEndpointModeBits;
  160. // Do we have a dual plane situation?
  161. int planeSelectorBits = 0;
  162. if (texelParams.DualPlane)
  163. {
  164. planeSelectorBits = 2;
  165. }
  166. remainingBits -= planeSelectorBits;
  167. // Read color data...
  168. int colorDataBits = remainingBits;
  169. while (remainingBits > 0)
  170. {
  171. int numberBits = Math.Min(remainingBits, 8);
  172. int bits = bitStream.ReadBits(numberBits);
  173. colorEndpointStream.WriteBits(bits, numberBits);
  174. remainingBits -= 8;
  175. }
  176. // Read the plane selection bits
  177. planeIndices = bitStream.ReadBits(planeSelectorBits);
  178. // Read the rest of the CEM
  179. if (baseMode != 0)
  180. {
  181. uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits);
  182. uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode;
  183. tempColorEndpointMode >>= 2;
  184. bool[] c = new bool[4];
  185. for (int i = 0; i < numberPartitions; i++)
  186. {
  187. c[i] = (tempColorEndpointMode & 1) != 0;
  188. tempColorEndpointMode >>= 1;
  189. }
  190. byte[] m = new byte[4];
  191. for (int i = 0; i < numberPartitions; i++)
  192. {
  193. m[i] = (byte)(tempColorEndpointMode & 3);
  194. tempColorEndpointMode >>= 2;
  195. Debug.Assert(m[i] <= 3);
  196. }
  197. for (int i = 0; i < numberPartitions; i++)
  198. {
  199. colorEndpointMode[i] = baseMode;
  200. if (!(c[i])) colorEndpointMode[i] -= 1;
  201. colorEndpointMode[i] <<= 2;
  202. colorEndpointMode[i] |= m[i];
  203. }
  204. }
  205. else if (numberPartitions > 1)
  206. {
  207. uint tempColorEndpointMode = baseColorEndpointMode >> 2;
  208. for (uint i = 0; i < numberPartitions; i++)
  209. {
  210. colorEndpointMode[i] = tempColorEndpointMode;
  211. }
  212. }
  213. // Make sure everything up till here is sane.
  214. for (int i = 0; i < numberPartitions; i++)
  215. {
  216. Debug.Assert(colorEndpointMode[i] < 16);
  217. }
  218. Debug.Assert(bitStream.Position + texelParams.GetPackedBitSize() == 128);
  219. // Decode both color data and texel weight data
  220. int[] colorValues = new int[32]; // Four values * two endpoints * four maximum partitions
  221. DecodeColorValues(colorValues, colorEndpointStream.ToByteArray(), colorEndpointMode, numberPartitions, colorDataBits);
  222. AstcPixel[][] endPoints = new AstcPixel[4][];
  223. endPoints[0] = new AstcPixel[2];
  224. endPoints[1] = new AstcPixel[2];
  225. endPoints[2] = new AstcPixel[2];
  226. endPoints[3] = new AstcPixel[2];
  227. int colorValuesPosition = 0;
  228. for (int i = 0; i < numberPartitions; i++)
  229. {
  230. ComputeEndpoints(endPoints[i], colorValues, colorEndpointMode[i], ref colorValuesPosition);
  231. }
  232. // Read the texel weight data.
  233. byte[] texelWeightData = (byte[])inputBuffer.Clone();
  234. // Reverse everything
  235. for (int i = 0; i < 8; i++)
  236. {
  237. byte a = ReverseByte(texelWeightData[i]);
  238. byte b = ReverseByte(texelWeightData[15 - i]);
  239. texelWeightData[i] = b;
  240. texelWeightData[15 - i] = a;
  241. }
  242. // Make sure that higher non-texel bits are set to zero
  243. int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1;
  244. texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1);
  245. int cLen = 16 - clearByteStart;
  246. for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0;
  247. List<IntegerEncoded> texelWeightValues = new List<IntegerEncoded>();
  248. BitArrayStream weightBitStream = new BitArrayStream(new BitArray(texelWeightData));
  249. IntegerEncoded.DecodeIntegerSequence(texelWeightValues, weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues());
  250. // Blocks can be at most 12x12, so we can have as many as 144 weights
  251. int[][] weights = new int[2][];
  252. weights[0] = new int[144];
  253. weights[1] = new int[144];
  254. UnquantizeTexelWeights(weights, texelWeightValues, texelParams, blockWidth, blockHeight);
  255. // Now that we have endpoints and weights, we can interpolate and generate
  256. // the proper decoding...
  257. for (int j = 0; j < blockHeight; j++)
  258. {
  259. for (int i = 0; i < blockWidth; i++)
  260. {
  261. int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32));
  262. Debug.Assert(partition < numberPartitions);
  263. AstcPixel pixel = new AstcPixel(0, 0, 0, 0);
  264. for (int component = 0; component < 4; component++)
  265. {
  266. int component0 = endPoints[partition][0].GetComponent(component);
  267. component0 = BitArrayStream.Replicate(component0, 8, 16);
  268. int component1 = endPoints[partition][1].GetComponent(component);
  269. component1 = BitArrayStream.Replicate(component1, 8, 16);
  270. int plane = 0;
  271. if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component))
  272. {
  273. plane = 1;
  274. }
  275. int weight = weights[plane][j * blockWidth + i];
  276. int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64;
  277. if (finalComponent == 65535)
  278. {
  279. pixel.SetComponent(component, 255);
  280. }
  281. else
  282. {
  283. double finalComponentFloat = finalComponent;
  284. pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5));
  285. }
  286. }
  287. outputBuffer[j * blockWidth + i] = pixel.Pack();
  288. }
  289. }
  290. return true;
  291. }
  292. private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock)
  293. {
  294. return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock);
  295. }
  296. private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock)
  297. {
  298. if (partitionCount == 1)
  299. {
  300. return 0;
  301. }
  302. if (isSmallBlock)
  303. {
  304. x <<= 1;
  305. y <<= 1;
  306. z <<= 1;
  307. }
  308. seed += (partitionCount - 1) * 1024;
  309. int rightNum = Hash52((uint)seed);
  310. byte seed01 = (byte)(rightNum & 0xF);
  311. byte seed02 = (byte)((rightNum >> 4) & 0xF);
  312. byte seed03 = (byte)((rightNum >> 8) & 0xF);
  313. byte seed04 = (byte)((rightNum >> 12) & 0xF);
  314. byte seed05 = (byte)((rightNum >> 16) & 0xF);
  315. byte seed06 = (byte)((rightNum >> 20) & 0xF);
  316. byte seed07 = (byte)((rightNum >> 24) & 0xF);
  317. byte seed08 = (byte)((rightNum >> 28) & 0xF);
  318. byte seed09 = (byte)((rightNum >> 18) & 0xF);
  319. byte seed10 = (byte)((rightNum >> 22) & 0xF);
  320. byte seed11 = (byte)((rightNum >> 26) & 0xF);
  321. byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF);
  322. seed01 *= seed01; seed02 *= seed02;
  323. seed03 *= seed03; seed04 *= seed04;
  324. seed05 *= seed05; seed06 *= seed06;
  325. seed07 *= seed07; seed08 *= seed08;
  326. seed09 *= seed09; seed10 *= seed10;
  327. seed11 *= seed11; seed12 *= seed12;
  328. int seedHash1, seedHash2, seedHash3;
  329. if ((seed & 1) != 0)
  330. {
  331. seedHash1 = (seed & 2) != 0 ? 4 : 5;
  332. seedHash2 = (partitionCount == 3) ? 6 : 5;
  333. }
  334. else
  335. {
  336. seedHash1 = (partitionCount == 3) ? 6 : 5;
  337. seedHash2 = (seed & 2) != 0 ? 4 : 5;
  338. }
  339. seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2;
  340. seed01 >>= seedHash1; seed02 >>= seedHash2; seed03 >>= seedHash1; seed04 >>= seedHash2;
  341. seed05 >>= seedHash1; seed06 >>= seedHash2; seed07 >>= seedHash1; seed08 >>= seedHash2;
  342. seed09 >>= seedHash3; seed10 >>= seedHash3; seed11 >>= seedHash3; seed12 >>= seedHash3;
  343. int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14);
  344. int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10);
  345. int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6);
  346. int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2);
  347. a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F;
  348. if (partitionCount < 4) d = 0;
  349. if (partitionCount < 3) c = 0;
  350. if (a >= b && a >= c && a >= d) return 0;
  351. else if (b >= c && b >= d) return 1;
  352. else if (c >= d) return 2;
  353. return 3;
  354. }
  355. static int Hash52(uint val)
  356. {
  357. val ^= val >> 15; val -= val << 17; val += val << 7; val += val << 4;
  358. val ^= val >> 5; val += val << 16; val ^= val >> 7; val ^= val >> 3;
  359. val ^= val << 6; val ^= val >> 17;
  360. return (int)val;
  361. }
  362. static void UnquantizeTexelWeights(
  363. int[][] outputBuffer,
  364. List<IntegerEncoded> weights,
  365. TexelWeightParams texelParams,
  366. int blockWidth,
  367. int blockHeight)
  368. {
  369. int weightIndices = 0;
  370. int[][] unquantized = new int[2][];
  371. unquantized[0] = new int[144];
  372. unquantized[1] = new int[144];
  373. for (int i = 0; i < weights.Count; i++)
  374. {
  375. unquantized[0][weightIndices] = UnquantizeTexelWeight(weights[i]);
  376. if (texelParams.DualPlane)
  377. {
  378. i++;
  379. unquantized[1][weightIndices] = UnquantizeTexelWeight(weights[i]);
  380. if (i == weights.Count)
  381. {
  382. break;
  383. }
  384. }
  385. if (++weightIndices >= (texelParams.Width * texelParams.Height)) break;
  386. }
  387. // Do infill if necessary (Section C.2.18) ...
  388. int ds = (1024 + (blockWidth / 2)) / (blockWidth - 1);
  389. int dt = (1024 + (blockHeight / 2)) / (blockHeight - 1);
  390. int planeScale = texelParams.DualPlane ? 2 : 1;
  391. for (int plane = 0; plane < planeScale; plane++)
  392. {
  393. for (int t = 0; t < blockHeight; t++)
  394. {
  395. for (int s = 0; s < blockWidth; s++)
  396. {
  397. int cs = ds * s;
  398. int ct = dt * t;
  399. int gs = (cs * (texelParams.Width - 1) + 32) >> 6;
  400. int gt = (ct * (texelParams.Height - 1) + 32) >> 6;
  401. int js = gs >> 4;
  402. int fs = gs & 0xF;
  403. int jt = gt >> 4;
  404. int ft = gt & 0x0F;
  405. int w11 = (fs * ft + 8) >> 4;
  406. int w10 = ft - w11;
  407. int w01 = fs - w11;
  408. int w00 = 16 - fs - ft + w11;
  409. int v0 = js + jt * texelParams.Width;
  410. int p00 = 0;
  411. int p01 = 0;
  412. int p10 = 0;
  413. int p11 = 0;
  414. if (v0 < (texelParams.Width * texelParams.Height))
  415. {
  416. p00 = unquantized[plane][v0];
  417. }
  418. if (v0 + 1 < (texelParams.Width * texelParams.Height))
  419. {
  420. p01 = unquantized[plane][v0 + 1];
  421. }
  422. if (v0 + texelParams.Width < (texelParams.Width * texelParams.Height))
  423. {
  424. p10 = unquantized[plane][v0 + texelParams.Width];
  425. }
  426. if (v0 + texelParams.Width + 1 < (texelParams.Width * texelParams.Height))
  427. {
  428. p11 = unquantized[plane][v0 + texelParams.Width + 1];
  429. }
  430. outputBuffer[plane][t * blockWidth + s] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4;
  431. }
  432. }
  433. }
  434. }
  435. static int UnquantizeTexelWeight(IntegerEncoded intEncoded)
  436. {
  437. int bitValue = intEncoded.BitValue;
  438. int bitLength = intEncoded.NumberBits;
  439. int a = BitArrayStream.Replicate(bitValue & 1, 1, 7);
  440. int b = 0, c = 0, d = 0;
  441. int result = 0;
  442. switch (intEncoded.GetEncoding())
  443. {
  444. case IntegerEncoded.EIntegerEncoding.JustBits:
  445. result = BitArrayStream.Replicate(bitValue, bitLength, 6);
  446. break;
  447. case IntegerEncoded.EIntegerEncoding.Trit:
  448. {
  449. d = intEncoded.TritValue;
  450. Debug.Assert(d < 3);
  451. switch (bitLength)
  452. {
  453. case 0:
  454. {
  455. int[] results = { 0, 32, 63 };
  456. result = results[d];
  457. break;
  458. }
  459. case 1:
  460. {
  461. c = 50;
  462. break;
  463. }
  464. case 2:
  465. {
  466. c = 23;
  467. int b2 = (bitValue >> 1) & 1;
  468. b = (b2 << 6) | (b2 << 2) | b2;
  469. break;
  470. }
  471. case 3:
  472. {
  473. c = 11;
  474. int cb = (bitValue >> 1) & 3;
  475. b = (cb << 5) | cb;
  476. break;
  477. }
  478. default:
  479. throw new AstcDecoderException("Invalid trit encoding for texel weight.");
  480. }
  481. break;
  482. }
  483. case IntegerEncoded.EIntegerEncoding.Quint:
  484. {
  485. d = intEncoded.QuintValue;
  486. Debug.Assert(d < 5);
  487. switch (bitLength)
  488. {
  489. case 0:
  490. {
  491. int[] results = { 0, 16, 32, 47, 63 };
  492. result = results[d];
  493. break;
  494. }
  495. case 1:
  496. {
  497. c = 28;
  498. break;
  499. }
  500. case 2:
  501. {
  502. c = 13;
  503. int b2 = (bitValue >> 1) & 1;
  504. b = (b2 << 6) | (b2 << 1);
  505. break;
  506. }
  507. default:
  508. throw new AstcDecoderException("Invalid quint encoding for texel weight.");
  509. }
  510. break;
  511. }
  512. }
  513. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0)
  514. {
  515. // Decode the value...
  516. result = d * c + b;
  517. result ^= a;
  518. result = (a & 0x20) | (result >> 2);
  519. }
  520. Debug.Assert(result < 64);
  521. // Change from [0,63] to [0,64]
  522. if (result > 32)
  523. {
  524. result += 1;
  525. }
  526. return result;
  527. }
  528. static byte ReverseByte(byte b)
  529. {
  530. // Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits
  531. return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32);
  532. }
  533. static uint[] ReadUintColorValues(int number, int[] colorValues, ref int colorValuesPosition)
  534. {
  535. uint[] ret = new uint[number];
  536. for (int i = 0; i < number; i++)
  537. {
  538. ret[i] = (uint)colorValues[colorValuesPosition++];
  539. }
  540. return ret;
  541. }
  542. static int[] ReadIntColorValues(int number, int[] colorValues, ref int colorValuesPosition)
  543. {
  544. int[] ret = new int[number];
  545. for (int i = 0; i < number; i++)
  546. {
  547. ret[i] = colorValues[colorValuesPosition++];
  548. }
  549. return ret;
  550. }
  551. static void ComputeEndpoints(
  552. AstcPixel[] endPoints,
  553. int[] colorValues,
  554. uint colorEndpointMode,
  555. ref int colorValuesPosition)
  556. {
  557. switch (colorEndpointMode)
  558. {
  559. case 0:
  560. {
  561. uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  562. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]);
  563. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]);
  564. break;
  565. }
  566. case 1:
  567. {
  568. uint[] val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
  569. int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0));
  570. int l1 = (int)Math.Max(l0 + (val[1] & 0x3F), 0xFFU);
  571. endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0);
  572. endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1);
  573. break;
  574. }
  575. case 4:
  576. {
  577. uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  578. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  579. endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]);
  580. break;
  581. }
  582. case 5:
  583. {
  584. int[] val = ReadIntColorValues(4, colorValues, ref colorValuesPosition);
  585. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  586. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  587. endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
  588. endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1]));
  589. endPoints[0].ClampByte();
  590. endPoints[1].ClampByte();
  591. break;
  592. }
  593. case 6:
  594. {
  595. uint[] val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
  596. endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  597. endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]);
  598. break;
  599. }
  600. case 8:
  601. {
  602. uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  603. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  604. {
  605. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  606. endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  607. }
  608. else
  609. {
  610. endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]);
  611. endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  612. }
  613. break;
  614. }
  615. case 9:
  616. {
  617. int[] val = ReadIntColorValues(6, colorValues, ref colorValuesPosition);
  618. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  619. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  620. BitArrayStream.BitTransferSigned(ref val[5], ref val[4]);
  621. if (val[1] + val[3] + val[5] >= 0)
  622. {
  623. endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
  624. endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  625. }
  626. else
  627. {
  628. endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  629. endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]);
  630. }
  631. endPoints[0].ClampByte();
  632. endPoints[1].ClampByte();
  633. break;
  634. }
  635. case 10:
  636. {
  637. uint[] val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
  638. endPoints[0] = new AstcPixel((short)val[4], (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
  639. endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]);
  640. break;
  641. }
  642. case 12:
  643. {
  644. uint[] val = ReadUintColorValues(8, colorValues, ref colorValuesPosition);
  645. if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
  646. {
  647. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  648. endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  649. }
  650. else
  651. {
  652. endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
  653. endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  654. }
  655. break;
  656. }
  657. case 13:
  658. {
  659. int[] val = ReadIntColorValues(8, colorValues, ref colorValuesPosition);
  660. BitArrayStream.BitTransferSigned(ref val[1], ref val[0]);
  661. BitArrayStream.BitTransferSigned(ref val[3], ref val[2]);
  662. BitArrayStream.BitTransferSigned(ref val[5], ref val[4]);
  663. BitArrayStream.BitTransferSigned(ref val[7], ref val[6]);
  664. if (val[1] + val[3] + val[5] >= 0)
  665. {
  666. endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
  667. endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
  668. }
  669. else
  670. {
  671. endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]);
  672. endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]);
  673. }
  674. endPoints[0].ClampByte();
  675. endPoints[1].ClampByte();
  676. break;
  677. }
  678. default:
  679. throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)");
  680. }
  681. }
  682. static void DecodeColorValues(
  683. int[] outputValues,
  684. byte[] inputData,
  685. uint[] modes,
  686. int numberPartitions,
  687. int numberBitsForColorData)
  688. {
  689. // First figure out how many color values we have
  690. int numberValues = 0;
  691. for (int i = 0; i < numberPartitions; i++)
  692. {
  693. numberValues += (int)((modes[i] >> 2) + 1) << 1;
  694. }
  695. // Then based on the number of values and the remaining number of bits,
  696. // figure out the max value for each of them...
  697. int range = 256;
  698. while (--range > 0)
  699. {
  700. IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range);
  701. int bitLength = intEncoded.GetBitLength(numberValues);
  702. if (bitLength <= numberBitsForColorData)
  703. {
  704. // Find the smallest possible range that matches the given encoding
  705. while (--range > 0)
  706. {
  707. IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range);
  708. if (!newIntEncoded.MatchesEncoding(intEncoded))
  709. {
  710. break;
  711. }
  712. }
  713. // Return to last matching range.
  714. range++;
  715. break;
  716. }
  717. }
  718. // We now have enough to decode our integer sequence.
  719. List<IntegerEncoded> integerEncodedSequence = new List<IntegerEncoded>();
  720. BitArrayStream colorBitStream = new BitArrayStream(new BitArray(inputData));
  721. IntegerEncoded.DecodeIntegerSequence(integerEncodedSequence, colorBitStream, range, numberValues);
  722. // Once we have the decoded values, we need to dequantize them to the 0-255 range
  723. // This procedure is outlined in ASTC spec C.2.13
  724. int outputIndices = 0;
  725. foreach (IntegerEncoded intEncoded in integerEncodedSequence)
  726. {
  727. int bitLength = intEncoded.NumberBits;
  728. int bitValue = intEncoded.BitValue;
  729. Debug.Assert(bitLength >= 1);
  730. int a = 0, b = 0, c = 0, d = 0;
  731. // A is just the lsb replicated 9 times.
  732. a = BitArrayStream.Replicate(bitValue & 1, 1, 9);
  733. switch (intEncoded.GetEncoding())
  734. {
  735. case IntegerEncoded.EIntegerEncoding.JustBits:
  736. {
  737. outputValues[outputIndices++] = BitArrayStream.Replicate(bitValue, bitLength, 8);
  738. break;
  739. }
  740. case IntegerEncoded.EIntegerEncoding.Trit:
  741. {
  742. d = intEncoded.TritValue;
  743. switch (bitLength)
  744. {
  745. case 1:
  746. {
  747. c = 204;
  748. break;
  749. }
  750. case 2:
  751. {
  752. c = 93;
  753. // B = b000b0bb0
  754. int b2 = (bitValue >> 1) & 1;
  755. b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1);
  756. break;
  757. }
  758. case 3:
  759. {
  760. c = 44;
  761. // B = cb000cbcb
  762. int cb = (bitValue >> 1) & 3;
  763. b = (cb << 7) | (cb << 2) | cb;
  764. break;
  765. }
  766. case 4:
  767. {
  768. c = 22;
  769. // B = dcb000dcb
  770. int dcb = (bitValue >> 1) & 7;
  771. b = (dcb << 6) | dcb;
  772. break;
  773. }
  774. case 5:
  775. {
  776. c = 11;
  777. // B = edcb000ed
  778. int edcb = (bitValue >> 1) & 0xF;
  779. b = (edcb << 5) | (edcb >> 2);
  780. break;
  781. }
  782. case 6:
  783. {
  784. c = 5;
  785. // B = fedcb000f
  786. int fedcb = (bitValue >> 1) & 0x1F;
  787. b = (fedcb << 4) | (fedcb >> 4);
  788. break;
  789. }
  790. default:
  791. throw new AstcDecoderException("Unsupported trit encoding for color values.");
  792. }
  793. break;
  794. }
  795. case IntegerEncoded.EIntegerEncoding.Quint:
  796. {
  797. d = intEncoded.QuintValue;
  798. switch (bitLength)
  799. {
  800. case 1:
  801. {
  802. c = 113;
  803. break;
  804. }
  805. case 2:
  806. {
  807. c = 54;
  808. // B = b0000bb00
  809. int b2 = (bitValue >> 1) & 1;
  810. b = (b2 << 8) | (b2 << 3) | (b2 << 2);
  811. break;
  812. }
  813. case 3:
  814. {
  815. c = 26;
  816. // B = cb0000cbc
  817. int cb = (bitValue >> 1) & 3;
  818. b = (cb << 7) | (cb << 1) | (cb >> 1);
  819. break;
  820. }
  821. case 4:
  822. {
  823. c = 13;
  824. // B = dcb0000dc
  825. int dcb = (bitValue >> 1) & 7;
  826. b = (dcb << 6) | (dcb >> 1);
  827. break;
  828. }
  829. case 5:
  830. {
  831. c = 6;
  832. // B = edcb0000e
  833. int edcb = (bitValue >> 1) & 0xF;
  834. b = (edcb << 5) | (edcb >> 3);
  835. break;
  836. }
  837. default:
  838. throw new AstcDecoderException("Unsupported quint encoding for color values.");
  839. }
  840. break;
  841. }
  842. }
  843. if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits)
  844. {
  845. int T = d * c + b;
  846. T ^= a;
  847. T = (a & 0x80) | (T >> 2);
  848. outputValues[outputIndices++] = T;
  849. }
  850. }
  851. // Make sure that each of our values is in the proper range...
  852. for (int i = 0; i < numberValues; i++)
  853. {
  854. Debug.Assert(outputValues[i] <= 255);
  855. }
  856. }
  857. static void FillVoidExtentLdr(BitArrayStream bitStream, int[] outputBuffer, int blockWidth, int blockHeight)
  858. {
  859. // Don't actually care about the void extent, just read the bits...
  860. for (int i = 0; i < 4; ++i)
  861. {
  862. bitStream.ReadBits(13);
  863. }
  864. // Decode the RGBA components and renormalize them to the range [0, 255]
  865. ushort r = (ushort)bitStream.ReadBits(16);
  866. ushort g = (ushort)bitStream.ReadBits(16);
  867. ushort b = (ushort)bitStream.ReadBits(16);
  868. ushort a = (ushort)bitStream.ReadBits(16);
  869. int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16;
  870. for (int j = 0; j < blockHeight; j++)
  871. {
  872. for (int i = 0; i < blockWidth; i++)
  873. {
  874. outputBuffer[j * blockWidth + i] = rgba;
  875. }
  876. }
  877. }
  878. static TexelWeightParams DecodeBlockInfo(BitArrayStream bitStream)
  879. {
  880. TexelWeightParams texelParams = new TexelWeightParams();
  881. // Read the entire block mode all at once
  882. ushort modeBits = (ushort)bitStream.ReadBits(11);
  883. // Does this match the void extent block mode?
  884. if ((modeBits & 0x01FF) == 0x1FC)
  885. {
  886. if ((modeBits & 0x200) != 0)
  887. {
  888. texelParams.VoidExtentHdr = true;
  889. }
  890. else
  891. {
  892. texelParams.VoidExtentLdr = true;
  893. }
  894. // Next two bits must be one.
  895. if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0)
  896. {
  897. texelParams.Error = true;
  898. }
  899. return texelParams;
  900. }
  901. // First check if the last four bits are zero
  902. if ((modeBits & 0xF) == 0)
  903. {
  904. texelParams.Error = true;
  905. return texelParams;
  906. }
  907. // If the last two bits are zero, then if bits
  908. // [6-8] are all ones, this is also reserved.
  909. if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0)
  910. {
  911. texelParams.Error = true;
  912. return texelParams;
  913. }
  914. // Otherwise, there is no error... Figure out the layout
  915. // of the block mode. Layout is determined by a number
  916. // between 0 and 9 corresponding to table C.2.8 of the
  917. // ASTC spec.
  918. int layout = 0;
  919. if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0)
  920. {
  921. // layout is in [0-4]
  922. if ((modeBits & 0x8) != 0)
  923. {
  924. // layout is in [2-4]
  925. if ((modeBits & 0x4) != 0)
  926. {
  927. // layout is in [3-4]
  928. if ((modeBits & 0x100) != 0)
  929. {
  930. layout = 4;
  931. }
  932. else
  933. {
  934. layout = 3;
  935. }
  936. }
  937. else
  938. {
  939. layout = 2;
  940. }
  941. }
  942. else
  943. {
  944. // layout is in [0-1]
  945. if ((modeBits & 0x4) != 0)
  946. {
  947. layout = 1;
  948. }
  949. else
  950. {
  951. layout = 0;
  952. }
  953. }
  954. }
  955. else
  956. {
  957. // layout is in [5-9]
  958. if ((modeBits & 0x100) != 0)
  959. {
  960. // layout is in [7-9]
  961. if ((modeBits & 0x80) != 0)
  962. {
  963. // layout is in [7-8]
  964. Debug.Assert((modeBits & 0x40) == 0);
  965. if ((modeBits & 0x20) != 0)
  966. {
  967. layout = 8;
  968. }
  969. else
  970. {
  971. layout = 7;
  972. }
  973. }
  974. else
  975. {
  976. layout = 9;
  977. }
  978. }
  979. else
  980. {
  981. // layout is in [5-6]
  982. if ((modeBits & 0x80) != 0)
  983. {
  984. layout = 6;
  985. }
  986. else
  987. {
  988. layout = 5;
  989. }
  990. }
  991. }
  992. Debug.Assert(layout < 10);
  993. // Determine R
  994. int r = (modeBits >> 4) & 1;
  995. if (layout < 5)
  996. {
  997. r |= (modeBits & 0x3) << 1;
  998. }
  999. else
  1000. {
  1001. r |= (modeBits & 0xC) >> 1;
  1002. }
  1003. Debug.Assert(2 <= r && r <= 7);
  1004. // Determine width & height
  1005. switch (layout)
  1006. {
  1007. case 0:
  1008. {
  1009. int a = (modeBits >> 5) & 0x3;
  1010. int b = (modeBits >> 7) & 0x3;
  1011. texelParams.Width = b + 4;
  1012. texelParams.Height = a + 2;
  1013. break;
  1014. }
  1015. case 1:
  1016. {
  1017. int a = (modeBits >> 5) & 0x3;
  1018. int b = (modeBits >> 7) & 0x3;
  1019. texelParams.Width = b + 8;
  1020. texelParams.Height = a + 2;
  1021. break;
  1022. }
  1023. case 2:
  1024. {
  1025. int a = (modeBits >> 5) & 0x3;
  1026. int b = (modeBits >> 7) & 0x3;
  1027. texelParams.Width = a + 2;
  1028. texelParams.Height = b + 8;
  1029. break;
  1030. }
  1031. case 3:
  1032. {
  1033. int a = (modeBits >> 5) & 0x3;
  1034. int b = (modeBits >> 7) & 0x1;
  1035. texelParams.Width = a + 2;
  1036. texelParams.Height = b + 6;
  1037. break;
  1038. }
  1039. case 4:
  1040. {
  1041. int a = (modeBits >> 5) & 0x3;
  1042. int b = (modeBits >> 7) & 0x1;
  1043. texelParams.Width = b + 2;
  1044. texelParams.Height = a + 2;
  1045. break;
  1046. }
  1047. case 5:
  1048. {
  1049. int a = (modeBits >> 5) & 0x3;
  1050. texelParams.Width = 12;
  1051. texelParams.Height = a + 2;
  1052. break;
  1053. }
  1054. case 6:
  1055. {
  1056. int a = (modeBits >> 5) & 0x3;
  1057. texelParams.Width = a + 2;
  1058. texelParams.Height = 12;
  1059. break;
  1060. }
  1061. case 7:
  1062. {
  1063. texelParams.Width = 6;
  1064. texelParams.Height = 10;
  1065. break;
  1066. }
  1067. case 8:
  1068. {
  1069. texelParams.Width = 10;
  1070. texelParams.Height = 6;
  1071. break;
  1072. }
  1073. case 9:
  1074. {
  1075. int a = (modeBits >> 5) & 0x3;
  1076. int b = (modeBits >> 9) & 0x3;
  1077. texelParams.Width = a + 6;
  1078. texelParams.Height = b + 6;
  1079. break;
  1080. }
  1081. default:
  1082. // Don't know this layout...
  1083. texelParams.Error = true;
  1084. break;
  1085. }
  1086. // Determine whether or not we're using dual planes
  1087. // and/or high precision layouts.
  1088. bool d = ((layout != 9) && ((modeBits & 0x400) != 0));
  1089. bool h = (layout != 9) && ((modeBits & 0x200) != 0);
  1090. if (h)
  1091. {
  1092. int[] maxWeights = { 9, 11, 15, 19, 23, 31 };
  1093. texelParams.MaxWeight = maxWeights[r - 2];
  1094. }
  1095. else
  1096. {
  1097. int[] maxWeights = { 1, 2, 3, 4, 5, 7 };
  1098. texelParams.MaxWeight = maxWeights[r - 2];
  1099. }
  1100. texelParams.DualPlane = d;
  1101. return texelParams;
  1102. }
  1103. }
  1104. }