AstcDecoder.cs 54 KB

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