AstcDecoder.cs 57 KB

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