AstcDecoder.cs 54 KB

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