AstcDecoder.cs 48 KB

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