Ryujinx/Ryujinx.Graphics.Texture/Astc/AstcDecoder.cs
gdkchan 2232e4ae87
Vulkan backend (#2518)
* WIP Vulkan implementation

* No need to initialize attributes on the SPIR-V backend anymore

* Allow multithreading shaderc and vkCreateShaderModule

You'll only really see the benefit here with threaded-gal or parallel shader cache compile.

Fix shaderc multithreaded changes

Thread safety for shaderc Options constructor

Dunno how they managed to make a constructor not thread safe, but you do you. May avoid some freezes.

* Support multiple levels/layers for blit.

Fixes MK8D when scaled, maybe a few other games. AMD software "safe" blit not supported right now.

* TextureStorage should hold a ref of the foreign storage, otherwise it might be freed while in use

* New depth-stencil blit method for AMD

* Workaround for AMD driver bug

* Fix some tessellation related issues (still doesn't work?)

* Submit command buffer before Texture GetData. (UE4 fix)

* DrawTexture support

* Fix BGRA on OpenGL backend

* Fix rebase build break

* Support format aliasing on SetImage

* Fix uniform buffers being lost when bindings are out of order

* Fix storage buffers being lost when bindings are out of order

(also avoid allocations when changing bindings)

* Use current command buffer for unscaled copy (perf)

Avoids flushing commands and renting a command buffer when fulfilling copy dependencies and when games do unscaled copies.

* Update to .net6

* Update Silk.NET to version 2.10.1

Somehow, massive performance boost. Seems like their vtable for looking up vulkan methods was really slow before.

* Fix PrimitivesGenerated query, disable Transform Feedback queries for now

Lets Splatoon 2 work on nvidia. (mostly)

* Update counter queue to be similar to the OGL one

Fixes softlocks when games had to flush counters.

* Don't throw when ending conditional rendering for now

This should be re-enabled when conditional rendering is enabled on nvidia etc.

* Update findMSB/findLSB to match master's instruction enum

* Fix triangle overlay on SMO, Captain Toad, maybe others?

* Don't make Intel Mesa pay for Intel Windows bugs

* Fix samplers with MinFilter Linear or Nearest (fixes New Super Mario Bros U Deluxe black borders)

* Update Spv.Generator

* Add alpha test emulation on shader (but no shader specialisation yet...)

* Fix R4G4B4A4Unorm texture format permutation

* Validation layers should be enabled for any log level other than None

* Add barriers around vkCmdCopyImage

Write->Read barrier for src image (we want to wait for a write to read it)
Write->Read barrier for dst image (we want to wait for the copy to complete before use)

* Be a bit more careful with texture access flags, since it can be used for anything

* Device local mapping for all buffers

May avoid issues with drivers with NVIDIA on linux/older gpus on windows when using large buffers (?)
Also some performance things and fixes issues with opengl games loading textures weird.

* Cleanup, disable device local buffers for now.

* Add single queue support

Multiqueue seems to be a bit more responsive on NVIDIA. Should fix texture flush on intel. AMD has been forced to single queue for an experiment.

* Fix some validation errors around extended dynamic state

* Remove Intel bug workaround, it was fixed on the latest driver

* Use circular queue for checking consumption on command buffers

Speeds up games that spam command buffers a little. Avoids checking multiple command buffers if multiple are active at once.

* Use SupportBufferUpdater, add single layer flush

* Fix counter queue leak when game decides to use host conditional rendering

* Force device local storage for textures (fixes linux performance)

* Port #3019

* Insert barriers around vkCmdBlitImage (may fix some amd flicker)

* Fix transform feedback on Intel, gl_Position feedback and clears to inexistent depth buffers

* Don't pause transform feedback for multi draw

* Fix draw outside of render pass and missing capability

* Workaround for wrong last attribute on AMD (affects FFVII, STRIKERS1945, probably more)

* Better workaround for AMD vertex buffer size alignment issue

* More instructions + fixes on SPIR-V backend

* Allow custom aspect ratio on Vulkan

* Correct GTK UI status bar positions

* SPIR-V: Functions must always end with a return

* SPIR-V: Fix ImageQuerySizeLod

* SPIR-V: Set DepthReplacing execution mode when FragDepth is modified

* SPIR-V: Implement LoopContinue IR instruction

* SPIR-V: Geometry shader support

* SPIR-V: Use correct binding number on storage buffers array

* Reduce allocations for Spir-v serialization

Passes BinaryWriter instead of the stream to Write and WriteOperand

- Removes creation of BinaryWriter for each instruction
- Removes allocations for literal string

* Some optimizations to Spv.Generator

- Dictionary for lookups of type declarations, constants, extinst
- LiteralInteger internal data format -> ushort
- Deterministic HashCode implementation to avoid spirv result not being the same between runs
- Inline operand list instead of List<T>, falls back to array if many operands. (large performance boost)

TODO: improve instruction allocation, structured program creator, ssa?

* Pool Spv.Generator resources, cache delegates, spv opts

- Pools for Instructions and LiteralIntegers. Can be passed in when creating the generator module.
  - NewInstruction is called instead of new Instruction()
  - Ryujinx SpirvGenerator passes in some pools that are static. The idea is for these to be shared between threads eventually.
- Estimate code size when creating the output MemoryStream
- LiteralInteger pools using ThreadStatic pools that are initialized before and after creation... not sure of a better way since the way these are created is via implicit cast.

Also, cache delegates for Spv.Generator for functions that are passed around to GenerateBinary etc, since passing the function raw creates a delegate on each call.

TODO: update python spv cs generator to make the coregrammar with NewInstruction and the `params` overloads.

* LocalDefMap for Ssa Rewriter

Rather than allocating a large array of all registers for each block in the shader, allocate one array of all registers and clear it between blocks. Reduces allocations in the shader translator.

* SPIR-V: Transform feedback support

* SPIR-V: Fragment shader interlock support (and image coherency)

* SPIR-V: Add early fragment tests support

* SPIR-V: Implement SwizzleAdd, add missing Triangles ExecutionMode for geometry shaders, remove SamplerType field from TextureMeta

* Don't pass depth clip state right now (fix decals)

Explicitly disabling it is incorrect. OpenGL currently automatically disables based on depth clamp, which is the behaviour if this state is omitted.

* Multisampling support

* Multisampling: Use resolve if src samples count > dst samples count

* Multisampling: We can only resolve for unscaled copies

* SPIR-V: Only add FSI exec mode if used.

* SPIR-V: Use ConstantComposite for Texture Offset Vector

Fixes a bunch of freezes with SPIR-V on AMD hardware, and validation errors. Note: Obviously assumes input offsets are constant, which they currently are.

* SPIR-V: Don't OpReturn if we already OpExit'ed

Fixes spir-v parse failure and stack smashing in RADV (obviously you still need bolist)

* SPIR-V: Only use input attribute type for input attributes

Output vertex attributes should always be of type float.

* Multithreaded Pipeline Compilation

* Address some feedback

* Make this 32

* Update topology with GpuAccessorState

* Cleanup for merge (note: disables spir-v)

* Make more robust to shader compilation failure

- Don't freeze when GLSL compilation fails
- Background SPIR-V pipeline compile failure results in skipped draws, similar to GLSL compilation failure.

* Fix Multisampling

* Only update fragment scale count if a vertex texture needs a scale.

Fixes a performance regression introduced by texture scaling in the vertex stage where support buffer updates would be very frequent, even at 1x, if any textures were used on the vertex stage.

This check doesn't exactly look cheap (a flag in the shader stage would probably be preferred), but it is much cheaper than uploading scales in both vulkan and opengl, so it will do for now.

* Use a bitmap to do granular tracking for buffer uploads.

This path is only taken if the much faster check of "is the buffer rented at all" is triggered, so it doesn't actually end up costing too much, and the time saved by not ending render passes (and on gpu for not waiting on barriers) is probably helpful.

Avoids ending render passes to update buffer data (not all the time)
- 140-180 to 35-45 in SMO metro kingdom (these updates are in the UI)
- Very variable 60-150(!) to 16-25 in mario kart 8 (these updates are in the UI)

As well as allowing more data to be preloaded persistently, this will also allow more data to be loaded in the preload buffer, which should be faster as it doesn't need to insert barriers between draws. (and on tbdr, does not need to flush and reload tile memory)

Improves performance in GPU limited scenarios. Should notably improve performance on TBDR gpus. Still a lot more to do here.

* Copy query results after RP ends, rather than ending to copy

We need to end the render pass to get the data (submit command buffer) anyways...

Reduces render passes created in games that use queries.

* Rework Query stuff a bit to avoid render pass end

Tries to reset returned queries in background when possible, rather than ending the render pass.

Still ends render pass when resetting a counter after draws, but maybe that can be solved too. (by just pulling an empty object off the pool?)

* Remove unnecessary lines

Was for testing

* Fix validation error for query reset

Need to think of a better way to do this.

* SPIR-V: Fix SwizzleAdd and some validation errors

* SPIR-V: Implement attribute indexing and StoreAttribute

* SPIR-V: Fix TextureSize for MS and Buffer sampler types

* Fix relaunch issues

* SPIR-V: Implement LogicalExclusiveOr

* SPIR-V: Constant buffer indexing support

* Ignore unsupported attributes rather than throwing (matches current GLSL behaviour)

* SPIR-V: Implement tessellation support

* SPIR-V: Geometry shader passthrough support

* SPIR-V: Implement StoreShader8/16 and StoreStorage8/16

* SPIR-V: Resolution scale support and fix TextureSample multisample with LOD bug

* SPIR-V: Fix field index for scale count

* SPIR-V: Fix another case of wrong field index

* SPIRV/GLSL: More scaling related fixes

* SPIR-V: Fix ImageLoad CompositeExtract component type

* SPIR-V: Workaround for Intel FrontFacing bug

* Enable SPIR-V backend by default

* Allow null samplers (samplers are not required when only using texelFetch to access the texture)

* Fix some validation errors related to texel block view usage flag and invalid image barrier base level

* Use explicit subgroup size if we can (might fix some block flickering on AMD)

* Take componentMask and scissor into account when clearing framebuffer attachments

* Add missing barriers around CmdFillBuffer (fixes Monster Hunter Rise flickering on NVIDIA)

* Use ClampToEdge for Clamp sampler address mode on Vulkan (fixes Hollow Knight)

Clamp is unsupported on Vulkan, but ClampToEdge behaves almost the same. ClampToBorder on the other hand (which was being used before) is pretty different

* Shader specialization for new Vulkan required state (fixes remaining alpha test issues, vertex stretching on AMD on Crash Bandicoot, etc)

* Check if the subgroup size is supported before passing a explicit size

* Only enable ShaderFloat64 if the GPU supports it

* We don't need to recompile shaders if alpha test state changed but alpha test is disabled

* Enable shader cache on Vulkan and implement MultiplyHighS32/U32 on SPIR-V (missed those before)

* Fix pipeline state saving before it is updated.

This should fix a few warnings and potential stutters due to bad pipeline states being saved in the cache. You may need to clear your guest cache.

* Allow null samplers on OpenGL backend

* _unit0Sampler should be set only for binding 0

* Remove unused PipelineConverter format variable (was causing IOR)

* Raise textures limit to 64 on Vulkan

* No need to pack the shader binaries if shader cache is disabled

* Fix backbuffer not being cleared and scissor not being re-enabled on OpenGL

* Do not clear unbound framebuffer color attachments

* Geometry shader passthrough emulation

* Consolidate UpdateDepthMode and GetDepthMode implementation

* Fix A1B5G5R5 texture format and support R4G4 on Vulkan

* Add barrier before use of some modified images

* Report 32 bit query result on AMD windows (smo issue)

* Add texture recompression support (disabled for now)

It recompresses ASTC textures into BC7, which might reduce VRAM usage significantly on games that uses ASTC textures

* Do not report R4G4 format as supported on Vulkan

It was causing mario head to become white on Super Mario 64 (???)

* Improvements to -1 to 1 depth mode.

- Transformation is only applied on the last stage in the vertex pipeline.
- Should fix some issues with geometry and tessellation (hopefully)
- Reading back FragCoord Z on fragment will transform back to -1 to 1.

* Geometry Shader index count from ThreadsPerInputPrimitive

Generally fixes SPIR-V emitting too many triangles, may change games in OpenGL

* Remove gl_FragDepth scaling

This is always 0-1; the other two issues were causing the problems. Fixes regression with Xenoblade.

* Add Gl StencilOp enum values to Vulkan

* Update guest cache to v1.1 (due to specialization state changes)

This will explode your shader cache from earlier vulkan build, but it must be done. 😔

* Vulkan/SPIR-V support for viewport inverse

* Fix typo

* Don't create query pools for unsupported query types

* Return of the Vector Indexing Bug

One day, everyone will get this right.

* Check for transform feedback query support

Sometimes transform feedback is supported without the query type.

* Fix gl_FragCoord.z transformation

FragCoord.z is always in 0-1, even when the real depth range is -1 to 1. Turns out the only bug was geo and tess stage outputs.

Fixes Pokemon Sword/Shield, possibly others.

* Fix Avalonia Rebase

Vulkan is currently not available on Avalonia, but the build does work and you can use opengl.

* Fix headless build

* Add support for BC6 and BC7 decompression, decompress all BC formats if they are not supported by the host

* Fix BCn 4/5 conversion, GetTextureTarget

BCn 4/5 could generate invalid data when a line's size in bytes was not divisible by 4, which both backends expect.

GetTextureTarget was not creating a view with the replacement format.

* Fix dependency

* Fix inverse viewport transform vector type on SPIR-V

* Do not require null descriptors support

* If MultiViewport is not supported, do not try to set more than one viewport/scissor

* Bounds check on bitmap add.

* Flush queries on attachment change rather than program change

Occlusion queries are usually used in a depth only pass so the attachments changing is a better indication of the query block ending.

Write mask changes are also considered since some games do depth only pass by setting 0 write mask on all the colour targets.

* Add support for avalonia (#6)

* add avalonia support

* only lock around skia flush

* addressed review

* cleanup

* add fallback size if avalonia attempts to render but the window size is 0. read desktop scale after enabling dpi check

* fix getting window handle on linux. skip render is size is 0

* Combine non-buffer with buffer image descriptor sets

* Support multisample texture copy with automatic resolve on Vulkan

* Remove old CompileShader methods from the Vulkan backend

* Add minimal pipeline layouts that only contains used bindings

They are used by helper shaders, the intention is avoiding needing to recompile the shaders (from GLSL to SPIR-V) if the bindings changes on the translated guest shaders

* Pre-compile helper shader as SPIR-V, and some fixes

* Remove pre-compiled shaderc binary for Windows as its no longer needed by default

* Workaround RADV crash

Enabling the descriptor indexing extension, even if it is not used, forces the radv driver to use "bolist".

* Use RobustBufferAccess on NVIDIA gpus

Avoids the SMO waterfall triangle on older NVIDIA gpus.

* Implement GPU selector and expose texture recompression on the UI and config

* Fix and enable background compute shader compilation

Also disables warnings from shader cache pipeline misses.

* Fix error due to missing subpass dependency when Attachment Write -> Shader Read barriers are added

* If S8D24 is not supported, use D32FS8

* Ensure all fences are destroyed on dispose

* Pre-allocate arrays up front on DescriptorSetUpdater, allows the removal of some checks

* Add missing clear layer parameter after rebase

* Use selected gpu from config for avalonia (#7)

* use configured device

* address review

* Fix D32S8 copy workaround (AMD)

Fixes water in Pokemon Legends Arceus on AMD GPUs. Possibly fixes other things.

* Use push descriptors for uniform buffer updates (disabled for now)

* Push descriptor support check, buffer redundancy checks

Should make push descriptors faster, needs more testing though.

* Increase light command buffer pool to 2 command buffers, throw rather than returning invalid cbs

* Adjust bindings array sizes

* Force submit command buffers if memory in use by its resources is high

* Add workaround for AMD GCN cubemap view sins

`ImageCreateCubeCompatibleBit` seems to generally break 2D array textures with mipmaps... even if they are eventually aliased as a cubemap with mipmaps. Forcing a copy here works around the issue.

This could be used in future if enabling this bit reduces performance on certain GPUs. (mobile class is generally a worry)

Currently also enabled on Linux as I don't know if they managed to dodge this bug (someone please tell me). Not enabled on Vega at the moment, but easy to add if the issue is there.

* Add mobile, non-RX variants to the GCN regex.

Also make sure that the 3 digit ones only include numbers starting with 7 or 8.

* Increase image limit per stage from 8 to 16

Xenoblade Chronicles 2 was hiting the limit of 8

* Minor code cleanup

* Fix NRE caused by SupportBufferUpdater calling pipeline ClearBuffer

* Add gpu selector to Avalonia (#8)

* Add gpu selector to avalonia settings

* show backend label on window

* some fixes

* address review

* Minor changes to the Avalonia UI

* Update graphics window UI and locales. (#9)

* Update xaml and update locales

* locale updates

Did my best here but likely needs to be checked by native speakers, especially the use of ampersands in greek, russian and turkish?

* Fix locales with more (?) correct translations.

* add separator to render widget

* fix spanish and portuguese

* Add new IdList, replaces buffer list that could not remove elements and had unbounded growth

* Don't crash the settings window if Vulkan is not supported

* Fix Actions menu not being clickable on GTK UI after relaunch

* Rename VulkanGraphicsDevice to VulkanRenderer and Renderer to OpenGLRenderer

* Fix IdList and make it not thread safe

* Revert useless OpenGL format table changes

* Fix headless project build

* List throws ArgumentOutOfRangeException

* SPIR-V: Fix tessellation

* Increase shader cache version due to tessellation fix

* Reduce number of Sync objects created (improves perf in some specific titles)

* Fix vulkan validation errors for NPOT compressed upload and GCN workaround.

* Add timestamp to the shader cache and force rebuild if host cache is outdated

* Prefer Mail box present mode for popups (#11)

* Prefer Mail box present mode

* fix debug

* switch present mode when vsync is toggled

* only disable vsync on the main window

* SPIR-V: Fix geometry shader input load with transform feedback

* BC7 Encoder: Prefer more precision on alpha rather than RGB when alpha is 0

* Fix Avalonia build

* Address initial PR feedback

* Only set transform feedback outputs on last vertex stage

* Address riperiperi PR feedback

* Remove outdated comment

* Remove unused constructor

* Only throw for negative results

* Throw for QueueSubmit and other errors

No point in delaying the inevitable

* Transform feedback decorations inside gl_PerVertex struct breaks the NVIDIA compiler

* Fix some resolution scale issues

* No need for two UpdateScale calls

* Fix comments on SPIR-V generator project

* Try to fix shader local memory size

On DOOM, a shader is using local memory, but both Low and High size are 0, CRS size is 1536, it seems to store on that region?

* Remove RectangleF that is now unused

* Fix ImageGather with multiple offsets

Needs ImageGatherExtended capability, and must use `ConstantComposite` instead of `CompositeConstruct`

* Address PR feedback from jD in all projects except Avalonia

* Address most of jD PR feedback on Avalonia

* Remove unsafe

* Fix VulkanSkiaGpu

* move present mode request out of Create Swapchain method

* split more parts of create swapchain

* addressed reviews

* addressed review

* Address second batch of jD PR feedback

* Fix buffer <-> image copy row length and height alignment

AlignUp helper does not support NPOT alignment, and ASTC textures can have NPOT block sizes

* Better fix for NPOT alignment issue

* Use switch expressions on Vulkan EnumConversion

Thanks jD

* Fix Avalonia build

* Add Vulkan selection prompt on startup

* Grammar fixes on Vulkan prompt message

* Add missing Vulkan migration flag

Co-authored-by: riperiperi <rhy3756547@hotmail.com>
Co-authored-by: Emmanuel Hansen <emmausssss@gmail.com>
Co-authored-by: MutantAura <44103205+MutantAura@users.noreply.github.com>
2022-07-31 18:26:06 -03:00

1622 lines
54 KiB
C#

using Ryujinx.Common.Utilities;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Ryujinx.Graphics.Texture.Astc
{
// https://github.com/GammaUNC/FasTC/blob/master/ASTCEncoder/src/Decompressor.cpp
public class AstcDecoder
{
private ReadOnlyMemory<byte> InputBuffer { get; }
private Memory<byte> OutputBuffer { get; }
private int BlockSizeX { get; }
private int BlockSizeY { get; }
private AstcLevel[] Levels { get; }
private bool Success { get; set; }
public int TotalBlockCount { get; }
public AstcDecoder(
ReadOnlyMemory<byte> inputBuffer,
Memory<byte> outputBuffer,
int blockWidth,
int blockHeight,
int width,
int height,
int depth,
int levels,
int layers)
{
if ((uint)blockWidth > 12)
{
throw new ArgumentOutOfRangeException(nameof(blockWidth));
}
if ((uint)blockHeight > 12)
{
throw new ArgumentOutOfRangeException(nameof(blockHeight));
}
InputBuffer = inputBuffer;
OutputBuffer = outputBuffer;
BlockSizeX = blockWidth;
BlockSizeY = blockHeight;
Levels = new AstcLevel[levels * layers];
Success = true;
TotalBlockCount = 0;
int currentInputBlock = 0;
int currentOutputOffset = 0;
for (int i = 0; i < levels; i++)
{
for (int j = 0; j < layers; j++)
{
ref AstcLevel level = ref Levels[i * layers + j];
level.ImageSizeX = Math.Max(1, width >> i);
level.ImageSizeY = Math.Max(1, height >> i);
level.ImageSizeZ = Math.Max(1, depth >> i);
level.BlockCountX = (level.ImageSizeX + blockWidth - 1) / blockWidth;
level.BlockCountY = (level.ImageSizeY + blockHeight - 1) / blockHeight;
level.StartBlock = currentInputBlock;
level.OutputByteOffset = currentOutputOffset;
currentInputBlock += level.TotalBlockCount;
currentOutputOffset += level.PixelCount * 4;
}
}
TotalBlockCount = currentInputBlock;
}
private struct AstcLevel
{
public int ImageSizeX { get; set; }
public int ImageSizeY { get; set; }
public int ImageSizeZ { get; set; }
public int BlockCountX { get; set; }
public int BlockCountY { get; set; }
public int StartBlock { get; set; }
public int OutputByteOffset { get; set; }
public int TotalBlockCount => BlockCountX * BlockCountY * ImageSizeZ;
public int PixelCount => ImageSizeX * ImageSizeY * ImageSizeZ;
}
public static int QueryDecompressedSize(int sizeX, int sizeY, int sizeZ, int levelCount, int layerCount)
{
int size = 0;
for (int i = 0; i < levelCount; i++)
{
int levelSizeX = Math.Max(1, sizeX >> i);
int levelSizeY = Math.Max(1, sizeY >> i);
int levelSizeZ = Math.Max(1, sizeZ >> i);
size += levelSizeX * levelSizeY * levelSizeZ * layerCount;
}
return size * 4;
}
public void ProcessBlock(int index)
{
Buffer16 inputBlock = MemoryMarshal.Cast<byte, Buffer16>(InputBuffer.Span)[index];
Span<int> decompressedData = stackalloc int[144];
try
{
DecompressBlock(inputBlock, decompressedData, BlockSizeX, BlockSizeY);
}
catch (Exception)
{
Success = false;
}
Span<byte> decompressedBytes = MemoryMarshal.Cast<int, byte>(decompressedData);
AstcLevel levelInfo = GetLevelInfo(index);
WriteDecompressedBlock(decompressedBytes, OutputBuffer.Span.Slice(levelInfo.OutputByteOffset),
index - levelInfo.StartBlock, levelInfo);
}
private AstcLevel GetLevelInfo(int blockIndex)
{
foreach (AstcLevel levelInfo in Levels)
{
if (blockIndex < levelInfo.StartBlock + levelInfo.TotalBlockCount)
{
return levelInfo;
}
}
throw new AstcDecoderException("Invalid block index.");
}
private void WriteDecompressedBlock(ReadOnlySpan<byte> block, Span<byte> outputBuffer, int blockIndex, AstcLevel level)
{
int stride = level.ImageSizeX * 4;
int blockCordX = blockIndex % level.BlockCountX;
int blockCordY = blockIndex / level.BlockCountX;
int pixelCordX = blockCordX * BlockSizeX;
int pixelCordY = blockCordY * BlockSizeY;
int outputPixelsX = Math.Min(pixelCordX + BlockSizeX, level.ImageSizeX) - pixelCordX;
int outputPixelsY = Math.Min(pixelCordY + BlockSizeY, level.ImageSizeY * level.ImageSizeZ) - pixelCordY;
int outputStart = pixelCordX * 4 + pixelCordY * stride;
int outputOffset = outputStart;
int inputOffset = 0;
for (int i = 0; i < outputPixelsY; i++)
{
ReadOnlySpan<byte> blockRow = block.Slice(inputOffset, outputPixelsX * 4);
Span<byte> outputRow = outputBuffer.Slice(outputOffset);
blockRow.CopyTo(outputRow);
inputOffset += BlockSizeX * 4;
outputOffset += stride;
}
}
struct TexelWeightParams
{
public int Width;
public int Height;
public int MaxWeight;
public bool DualPlane;
public bool Error;
public bool VoidExtentLdr;
public bool VoidExtentHdr;
public int GetPackedBitSize()
{
// How many indices do we have?
int indices = Height * Width;
if (DualPlane)
{
indices *= 2;
}
IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(MaxWeight);
return intEncoded.GetBitLength(indices);
}
public int GetNumWeightValues()
{
int ret = Width * Height;
if (DualPlane)
{
ret *= 2;
}
return ret;
}
}
public static bool TryDecodeToRgba8(
ReadOnlyMemory<byte> data,
int blockWidth,
int blockHeight,
int width,
int height,
int depth,
int levels,
int layers,
out Span<byte> decoded)
{
byte[] output = new byte[QueryDecompressedSize(width, height, depth, levels, layers)];
AstcDecoder decoder = new AstcDecoder(data, output, blockWidth, blockHeight, width, height, depth, levels, layers);
for (int i = 0; i < decoder.TotalBlockCount; i++)
{
decoder.ProcessBlock(i);
}
decoded = output;
return decoder.Success;
}
public static bool TryDecodeToRgba8(
ReadOnlyMemory<byte> data,
Memory<byte> outputBuffer,
int blockWidth,
int blockHeight,
int width,
int height,
int depth,
int levels,
int layers)
{
AstcDecoder decoder = new AstcDecoder(data, outputBuffer, blockWidth, blockHeight, width, height, depth, levels, layers);
for (int i = 0; i < decoder.TotalBlockCount; i++)
{
decoder.ProcessBlock(i);
}
return decoder.Success;
}
public static bool TryDecodeToRgba8P(
ReadOnlyMemory<byte> data,
Memory<byte> outputBuffer,
int blockWidth,
int blockHeight,
int width,
int height,
int depth,
int levels,
int layers)
{
AstcDecoder decoder = new AstcDecoder(data, outputBuffer, blockWidth, blockHeight, width, height, depth, levels, layers);
// Lazy parallelism
Enumerable.Range(0, decoder.TotalBlockCount).AsParallel().ForAll(x => decoder.ProcessBlock(x));
return decoder.Success;
}
public static bool TryDecodeToRgba8P(
ReadOnlyMemory<byte> data,
int blockWidth,
int blockHeight,
int width,
int height,
int depth,
int levels,
int layers,
out byte[] decoded)
{
byte[] output = new byte[QueryDecompressedSize(width, height, depth, levels, layers)];
AstcDecoder decoder = new AstcDecoder(data, output, blockWidth, blockHeight, width, height, depth, levels, layers);
Enumerable.Range(0, decoder.TotalBlockCount).AsParallel().ForAll(x => decoder.ProcessBlock(x));
decoded = output;
return decoder.Success;
}
public static bool DecompressBlock(
Buffer16 inputBlock,
Span<int> outputBuffer,
int blockWidth,
int blockHeight)
{
BitStream128 bitStream = new BitStream128(inputBlock);
DecodeBlockInfo(ref bitStream, out TexelWeightParams texelParams);
if (texelParams.Error)
{
throw new AstcDecoderException("Invalid block mode");
}
if (texelParams.VoidExtentLdr)
{
FillVoidExtentLdr(ref bitStream, outputBuffer, blockWidth, blockHeight);
return true;
}
if (texelParams.VoidExtentHdr)
{
throw new AstcDecoderException("HDR void extent blocks are not supported.");
}
if (texelParams.Width > blockWidth)
{
throw new AstcDecoderException("Texel weight grid width should be smaller than block width.");
}
if (texelParams.Height > blockHeight)
{
throw new AstcDecoderException("Texel weight grid height should be smaller than block height.");
}
// Read num partitions
int numberPartitions = bitStream.ReadBits(2) + 1;
Debug.Assert(numberPartitions <= 4);
if (numberPartitions == 4 && texelParams.DualPlane)
{
throw new AstcDecoderException("Dual plane mode is incompatible with four partition blocks.");
}
// Based on the number of partitions, read the color endpoint mode for
// each partition.
// Determine partitions, partition index, and color endpoint modes
int planeIndices;
int partitionIndex;
Span<uint> colorEndpointMode = stackalloc uint[4];
BitStream128 colorEndpointStream = new BitStream128();
// Read extra config data...
uint baseColorEndpointMode = 0;
if (numberPartitions == 1)
{
colorEndpointMode[0] = (uint)bitStream.ReadBits(4);
partitionIndex = 0;
}
else
{
partitionIndex = bitStream.ReadBits(10);
baseColorEndpointMode = (uint)bitStream.ReadBits(6);
}
uint baseMode = (baseColorEndpointMode & 3);
// Remaining bits are color endpoint data...
int numberWeightBits = texelParams.GetPackedBitSize();
int remainingBits = bitStream.BitsLeft - numberWeightBits;
// Consider extra bits prior to texel data...
uint extraColorEndpointModeBits = 0;
if (baseMode != 0)
{
switch (numberPartitions)
{
case 2: extraColorEndpointModeBits += 2; break;
case 3: extraColorEndpointModeBits += 5; break;
case 4: extraColorEndpointModeBits += 8; break;
default: Debug.Assert(false); break;
}
}
remainingBits -= (int)extraColorEndpointModeBits;
// Do we have a dual plane situation?
int planeSelectorBits = 0;
if (texelParams.DualPlane)
{
planeSelectorBits = 2;
}
remainingBits -= planeSelectorBits;
// Read color data...
int colorDataBits = remainingBits;
while (remainingBits > 0)
{
int numberBits = Math.Min(remainingBits, 8);
int bits = bitStream.ReadBits(numberBits);
colorEndpointStream.WriteBits(bits, numberBits);
remainingBits -= 8;
}
// Read the plane selection bits
planeIndices = bitStream.ReadBits(planeSelectorBits);
// Read the rest of the CEM
if (baseMode != 0)
{
uint extraColorEndpointMode = (uint)bitStream.ReadBits((int)extraColorEndpointModeBits);
uint tempColorEndpointMode = (extraColorEndpointMode << 6) | baseColorEndpointMode;
tempColorEndpointMode >>= 2;
Span<bool> c = stackalloc bool[4];
for (int i = 0; i < numberPartitions; i++)
{
c[i] = (tempColorEndpointMode & 1) != 0;
tempColorEndpointMode >>= 1;
}
Span<byte> m = stackalloc byte[4];
for (int i = 0; i < numberPartitions; i++)
{
m[i] = (byte)(tempColorEndpointMode & 3);
tempColorEndpointMode >>= 2;
Debug.Assert(m[i] <= 3);
}
for (int i = 0; i < numberPartitions; i++)
{
colorEndpointMode[i] = baseMode;
if (!(c[i])) colorEndpointMode[i] -= 1;
colorEndpointMode[i] <<= 2;
colorEndpointMode[i] |= m[i];
}
}
else if (numberPartitions > 1)
{
uint tempColorEndpointMode = baseColorEndpointMode >> 2;
for (int i = 0; i < numberPartitions; i++)
{
colorEndpointMode[i] = tempColorEndpointMode;
}
}
// Make sure everything up till here is sane.
for (int i = 0; i < numberPartitions; i++)
{
Debug.Assert(colorEndpointMode[i] < 16);
}
Debug.Assert(bitStream.BitsLeft == texelParams.GetPackedBitSize());
// Decode both color data and texel weight data
Span<int> colorValues = stackalloc int[32]; // Four values * two endpoints * four maximum partitions
DecodeColorValues(colorValues, ref colorEndpointStream, colorEndpointMode, numberPartitions, colorDataBits);
EndPointSet endPoints;
unsafe { _ = &endPoints; } // Skip struct initialization
int colorValuesPosition = 0;
for (int i = 0; i < numberPartitions; i++)
{
ComputeEndpoints(endPoints.Get(i), colorValues, colorEndpointMode[i], ref colorValuesPosition);
}
// Read the texel weight data.
Buffer16 texelWeightData = inputBlock;
// Reverse everything
for (int i = 0; i < 8; i++)
{
byte a = ReverseByte(texelWeightData[i]);
byte b = ReverseByte(texelWeightData[15 - i]);
texelWeightData[i] = b;
texelWeightData[15 - i] = a;
}
// Make sure that higher non-texel bits are set to zero
int clearByteStart = (texelParams.GetPackedBitSize() >> 3) + 1;
texelWeightData[clearByteStart - 1] &= (byte)((1 << (texelParams.GetPackedBitSize() % 8)) - 1);
int cLen = 16 - clearByteStart;
for (int i = clearByteStart; i < clearByteStart + cLen; i++) texelWeightData[i] = 0;
IntegerSequence texelWeightValues;
unsafe { _ = &texelWeightValues; } // Skip struct initialization
texelWeightValues.Reset();
BitStream128 weightBitStream = new BitStream128(texelWeightData);
IntegerEncoded.DecodeIntegerSequence(ref texelWeightValues, ref weightBitStream, texelParams.MaxWeight, texelParams.GetNumWeightValues());
// Blocks can be at most 12x12, so we can have as many as 144 weights
Weights weights;
unsafe { _ = &weights; } // Skip struct initialization
UnquantizeTexelWeights(ref weights, ref texelWeightValues, ref texelParams, blockWidth, blockHeight);
ushort[] table = Bits.Replicate8_16Table;
// Now that we have endpoints and weights, we can interpolate and generate
// the proper decoding...
for (int j = 0; j < blockHeight; j++)
{
for (int i = 0; i < blockWidth; i++)
{
int partition = Select2dPartition(partitionIndex, i, j, numberPartitions, ((blockHeight * blockWidth) < 32));
Debug.Assert(partition < numberPartitions);
AstcPixel pixel = new AstcPixel();
for (int component = 0; component < 4; component++)
{
int component0 = endPoints.Get(partition)[0].GetComponent(component);
component0 = table[component0];
int component1 = endPoints.Get(partition)[1].GetComponent(component);
component1 = table[component1];
int plane = 0;
if (texelParams.DualPlane && (((planeIndices + 1) & 3) == component))
{
plane = 1;
}
int weight = weights.Get(plane)[j * blockWidth + i];
int finalComponent = (component0 * (64 - weight) + component1 * weight + 32) / 64;
if (finalComponent == 65535)
{
pixel.SetComponent(component, 255);
}
else
{
double finalComponentFloat = finalComponent;
pixel.SetComponent(component, (int)(255.0 * (finalComponentFloat / 65536.0) + 0.5));
}
}
outputBuffer[j * blockWidth + i] = pixel.Pack();
}
}
return true;
}
// Blocks can be at most 12x12, so we can have as many as 144 weights
[StructLayout(LayoutKind.Sequential, Size = 144 * sizeof(int) * Count)]
private struct Weights
{
private int _start;
public const int Count = 2;
public Span<int> this[int index]
{
get
{
if ((uint)index >= Count)
{
throw new ArgumentOutOfRangeException();
}
ref int start = ref Unsafe.Add(ref _start, index * 144);
return MemoryMarshal.CreateSpan(ref start, 144);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<int> Get(int index)
{
ref int start = ref Unsafe.Add(ref _start, index * 144);
return MemoryMarshal.CreateSpan(ref start, 144);
}
}
private static int Select2dPartition(int seed, int x, int y, int partitionCount, bool isSmallBlock)
{
return SelectPartition(seed, x, y, 0, partitionCount, isSmallBlock);
}
private static int SelectPartition(int seed, int x, int y, int z, int partitionCount, bool isSmallBlock)
{
if (partitionCount == 1)
{
return 0;
}
if (isSmallBlock)
{
x <<= 1;
y <<= 1;
z <<= 1;
}
seed += (partitionCount - 1) * 1024;
int rightNum = Hash52((uint)seed);
byte seed01 = (byte)(rightNum & 0xF);
byte seed02 = (byte)((rightNum >> 4) & 0xF);
byte seed03 = (byte)((rightNum >> 8) & 0xF);
byte seed04 = (byte)((rightNum >> 12) & 0xF);
byte seed05 = (byte)((rightNum >> 16) & 0xF);
byte seed06 = (byte)((rightNum >> 20) & 0xF);
byte seed07 = (byte)((rightNum >> 24) & 0xF);
byte seed08 = (byte)((rightNum >> 28) & 0xF);
byte seed09 = (byte)((rightNum >> 18) & 0xF);
byte seed10 = (byte)((rightNum >> 22) & 0xF);
byte seed11 = (byte)((rightNum >> 26) & 0xF);
byte seed12 = (byte)(((rightNum >> 30) | (rightNum << 2)) & 0xF);
seed01 *= seed01; seed02 *= seed02;
seed03 *= seed03; seed04 *= seed04;
seed05 *= seed05; seed06 *= seed06;
seed07 *= seed07; seed08 *= seed08;
seed09 *= seed09; seed10 *= seed10;
seed11 *= seed11; seed12 *= seed12;
int seedHash1, seedHash2, seedHash3;
if ((seed & 1) != 0)
{
seedHash1 = (seed & 2) != 0 ? 4 : 5;
seedHash2 = (partitionCount == 3) ? 6 : 5;
}
else
{
seedHash1 = (partitionCount == 3) ? 6 : 5;
seedHash2 = (seed & 2) != 0 ? 4 : 5;
}
seedHash3 = (seed & 0x10) != 0 ? seedHash1 : seedHash2;
seed01 >>= seedHash1; seed02 >>= seedHash2; seed03 >>= seedHash1; seed04 >>= seedHash2;
seed05 >>= seedHash1; seed06 >>= seedHash2; seed07 >>= seedHash1; seed08 >>= seedHash2;
seed09 >>= seedHash3; seed10 >>= seedHash3; seed11 >>= seedHash3; seed12 >>= seedHash3;
int a = seed01 * x + seed02 * y + seed11 * z + (rightNum >> 14);
int b = seed03 * x + seed04 * y + seed12 * z + (rightNum >> 10);
int c = seed05 * x + seed06 * y + seed09 * z + (rightNum >> 6);
int d = seed07 * x + seed08 * y + seed10 * z + (rightNum >> 2);
a &= 0x3F; b &= 0x3F; c &= 0x3F; d &= 0x3F;
if (partitionCount < 4) d = 0;
if (partitionCount < 3) c = 0;
if (a >= b && a >= c && a >= d) return 0;
else if (b >= c && b >= d) return 1;
else if (c >= d) return 2;
return 3;
}
static int Hash52(uint val)
{
val ^= val >> 15; val -= val << 17; val += val << 7; val += val << 4;
val ^= val >> 5; val += val << 16; val ^= val >> 7; val ^= val >> 3;
val ^= val << 6; val ^= val >> 17;
return (int)val;
}
static void UnquantizeTexelWeights(
ref Weights outputBuffer,
ref IntegerSequence weights,
ref TexelWeightParams texelParams,
int blockWidth,
int blockHeight)
{
int weightIndices = 0;
Weights unquantized;
unsafe { _ = &unquantized; } // Skip struct initialization
Span<IntegerEncoded> weightsList = weights.List;
Span<int> unquantized0 = unquantized[0];
Span<int> unquantized1 = unquantized[1];
for (int i = 0; i < weightsList.Length; i++)
{
unquantized0[weightIndices] = UnquantizeTexelWeight(weightsList[i]);
if (texelParams.DualPlane)
{
i++;
unquantized1[weightIndices] = UnquantizeTexelWeight(weightsList[i]);
if (i == weightsList.Length)
{
break;
}
}
if (++weightIndices >= texelParams.Width * texelParams.Height) break;
}
// Do infill if necessary (Section C.2.18) ...
int ds = (1024 + blockWidth / 2) / (blockWidth - 1);
int dt = (1024 + blockHeight / 2) / (blockHeight - 1);
int planeScale = texelParams.DualPlane ? 2 : 1;
for (int plane = 0; plane < planeScale; plane++)
{
Span<int> unquantizedSpan = unquantized.Get(plane);
Span<int> outputSpan = outputBuffer.Get(plane);
for (int t = 0; t < blockHeight; t++)
{
for (int s = 0; s < blockWidth; s++)
{
int cs = ds * s;
int ct = dt * t;
int gs = (cs * (texelParams.Width - 1) + 32) >> 6;
int gt = (ct * (texelParams.Height - 1) + 32) >> 6;
int js = gs >> 4;
int fs = gs & 0xF;
int jt = gt >> 4;
int ft = gt & 0x0F;
int w11 = (fs * ft + 8) >> 4;
int v0 = js + jt * texelParams.Width;
int weight = 8;
int wxh = texelParams.Width * texelParams.Height;
if (v0 < wxh)
{
weight += unquantizedSpan[v0] * (16 - fs - ft + w11);
if (v0 + 1 < wxh)
{
weight += unquantizedSpan[v0 + 1] * (fs - w11);
}
}
if (v0 + texelParams.Width < wxh)
{
weight += unquantizedSpan[v0 + texelParams.Width] * (ft - w11);
if (v0 + texelParams.Width + 1 < wxh)
{
weight += unquantizedSpan[v0 + texelParams.Width + 1] * w11;
}
}
outputSpan[t * blockWidth + s] = weight >> 4;
}
}
}
}
static int UnquantizeTexelWeight(IntegerEncoded intEncoded)
{
int bitValue = intEncoded.BitValue;
int bitLength = intEncoded.NumberBits;
int a = Bits.Replicate1_7(bitValue & 1);
int b = 0, c = 0, d = 0;
int result = 0;
switch (intEncoded.GetEncoding())
{
case IntegerEncoded.EIntegerEncoding.JustBits:
result = Bits.Replicate(bitValue, bitLength, 6);
break;
case IntegerEncoded.EIntegerEncoding.Trit:
{
d = intEncoded.TritValue;
Debug.Assert(d < 3);
switch (bitLength)
{
case 0:
{
result = d switch
{
0 => 0,
1 => 32,
2 => 63,
_ => 0
};
break;
}
case 1:
{
c = 50;
break;
}
case 2:
{
c = 23;
int b2 = (bitValue >> 1) & 1;
b = (b2 << 6) | (b2 << 2) | b2;
break;
}
case 3:
{
c = 11;
int cb = (bitValue >> 1) & 3;
b = (cb << 5) | cb;
break;
}
default:
throw new AstcDecoderException("Invalid trit encoding for texel weight.");
}
break;
}
case IntegerEncoded.EIntegerEncoding.Quint:
{
d = intEncoded.QuintValue;
Debug.Assert(d < 5);
switch (bitLength)
{
case 0:
{
result = d switch
{
0 => 0,
1 => 16,
2 => 32,
3 => 47,
4 => 63,
_ => 0
};
break;
}
case 1:
{
c = 28;
break;
}
case 2:
{
c = 13;
int b2 = (bitValue >> 1) & 1;
b = (b2 << 6) | (b2 << 1);
break;
}
default:
throw new AstcDecoderException("Invalid quint encoding for texel weight.");
}
break;
}
}
if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits && bitLength > 0)
{
// Decode the value...
result = d * c + b;
result ^= a;
result = (a & 0x20) | (result >> 2);
}
Debug.Assert(result < 64);
// Change from [0,63] to [0,64]
if (result > 32)
{
result += 1;
}
return result;
}
static byte ReverseByte(byte b)
{
// Taken from http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits
return (byte)((((b) * 0x80200802L) & 0x0884422110L) * 0x0101010101L >> 32);
}
static Span<uint> ReadUintColorValues(int number, Span<int> colorValues, ref int colorValuesPosition)
{
Span<int> ret = colorValues.Slice(colorValuesPosition, number);
colorValuesPosition += number;
return MemoryMarshal.Cast<int, uint>(ret);
}
static Span<int> ReadIntColorValues(int number, Span<int> colorValues, ref int colorValuesPosition)
{
Span<int> ret = colorValues.Slice(colorValuesPosition, number);
colorValuesPosition += number;
return ret;
}
static void ComputeEndpoints(
Span<AstcPixel> endPoints,
Span<int> colorValues,
uint colorEndpointMode,
ref int colorValuesPosition)
{
switch (colorEndpointMode)
{
case 0:
{
Span<uint> val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[0], (short)val[0]);
endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[1], (short)val[1]);
break;
}
case 1:
{
Span<uint> val = ReadUintColorValues(2, colorValues, ref colorValuesPosition);
int l0 = (int)((val[0] >> 2) | (val[1] & 0xC0));
int l1 = (int)Math.Max(l0 + (val[1] & 0x3F), 0xFFU);
endPoints[0] = new AstcPixel(0xFF, (short)l0, (short)l0, (short)l0);
endPoints[1] = new AstcPixel(0xFF, (short)l1, (short)l1, (short)l1);
break;
}
case 4:
{
Span<uint> val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
endPoints[1] = new AstcPixel((short)val[3], (short)val[1], (short)val[1], (short)val[1]);
break;
}
case 5:
{
Span<int> val = ReadIntColorValues(4, colorValues, ref colorValuesPosition);
Bits.BitTransferSigned(ref val[1], ref val[0]);
Bits.BitTransferSigned(ref val[3], ref val[2]);
endPoints[0] = new AstcPixel((short)val[2], (short)val[0], (short)val[0], (short)val[0]);
endPoints[1] = new AstcPixel((short)(val[2] + val[3]), (short)(val[0] + val[1]), (short)(val[0] + val[1]), (short)(val[0] + val[1]));
endPoints[0].ClampByte();
endPoints[1].ClampByte();
break;
}
case 6:
{
Span<uint> val = ReadUintColorValues(4, colorValues, ref colorValuesPosition);
endPoints[0] = new AstcPixel(0xFF, (short)(val[0] * val[3] >> 8), (short)(val[1] * val[3] >> 8), (short)(val[2] * val[3] >> 8));
endPoints[1] = new AstcPixel(0xFF, (short)val[0], (short)val[1], (short)val[2]);
break;
}
case 8:
{
Span<uint> val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
{
endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
endPoints[1] = new AstcPixel(0xFF, (short)val[1], (short)val[3], (short)val[5]);
}
else
{
endPoints[0] = AstcPixel.BlueContract(0xFF, (short)val[1], (short)val[3], (short)val[5]);
endPoints[1] = AstcPixel.BlueContract(0xFF, (short)val[0], (short)val[2], (short)val[4]);
}
break;
}
case 9:
{
Span<int> val = ReadIntColorValues(6, colorValues, ref colorValuesPosition);
Bits.BitTransferSigned(ref val[1], ref val[0]);
Bits.BitTransferSigned(ref val[3], ref val[2]);
Bits.BitTransferSigned(ref val[5], ref val[4]);
if (val[1] + val[3] + val[5] >= 0)
{
endPoints[0] = new AstcPixel(0xFF, (short)val[0], (short)val[2], (short)val[4]);
endPoints[1] = new AstcPixel(0xFF, (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
}
else
{
endPoints[0] = AstcPixel.BlueContract(0xFF, val[0] + val[1], val[2] + val[3], val[4] + val[5]);
endPoints[1] = AstcPixel.BlueContract(0xFF, val[0], val[2], val[4]);
}
endPoints[0].ClampByte();
endPoints[1].ClampByte();
break;
}
case 10:
{
Span<uint> val = ReadUintColorValues(6, colorValues, ref colorValuesPosition);
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));
endPoints[1] = new AstcPixel((short)val[5], (short)val[0], (short)val[1], (short)val[2]);
break;
}
case 12:
{
Span<uint> val = ReadUintColorValues(8, colorValues, ref colorValuesPosition);
if (val[1] + val[3] + val[5] >= val[0] + val[2] + val[4])
{
endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
endPoints[1] = new AstcPixel((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
}
else
{
endPoints[0] = AstcPixel.BlueContract((short)val[7], (short)val[1], (short)val[3], (short)val[5]);
endPoints[1] = AstcPixel.BlueContract((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
}
break;
}
case 13:
{
Span<int> val = ReadIntColorValues(8, colorValues, ref colorValuesPosition);
Bits.BitTransferSigned(ref val[1], ref val[0]);
Bits.BitTransferSigned(ref val[3], ref val[2]);
Bits.BitTransferSigned(ref val[5], ref val[4]);
Bits.BitTransferSigned(ref val[7], ref val[6]);
if (val[1] + val[3] + val[5] >= 0)
{
endPoints[0] = new AstcPixel((short)val[6], (short)val[0], (short)val[2], (short)val[4]);
endPoints[1] = new AstcPixel((short)(val[7] + val[6]), (short)(val[0] + val[1]), (short)(val[2] + val[3]), (short)(val[4] + val[5]));
}
else
{
endPoints[0] = AstcPixel.BlueContract(val[6] + val[7], val[0] + val[1], val[2] + val[3], val[4] + val[5]);
endPoints[1] = AstcPixel.BlueContract(val[6], val[0], val[2], val[4]);
}
endPoints[0].ClampByte();
endPoints[1].ClampByte();
break;
}
default:
throw new AstcDecoderException("Unsupported color endpoint mode (is it HDR?)");
}
}
static void DecodeColorValues(
Span<int> outputValues,
ref BitStream128 colorBitStream,
Span<uint> modes,
int numberPartitions,
int numberBitsForColorData)
{
// First figure out how many color values we have
int numberValues = 0;
for (int i = 0; i < numberPartitions; i++)
{
numberValues += (int)((modes[i] >> 2) + 1) << 1;
}
// Then based on the number of values and the remaining number of bits,
// figure out the max value for each of them...
int range = 256;
while (--range > 0)
{
IntegerEncoded intEncoded = IntegerEncoded.CreateEncoding(range);
int bitLength = intEncoded.GetBitLength(numberValues);
if (bitLength <= numberBitsForColorData)
{
// Find the smallest possible range that matches the given encoding
while (--range > 0)
{
IntegerEncoded newIntEncoded = IntegerEncoded.CreateEncoding(range);
if (!newIntEncoded.MatchesEncoding(intEncoded))
{
break;
}
}
// Return to last matching range.
range++;
break;
}
}
// We now have enough to decode our integer sequence.
IntegerSequence integerEncodedSequence;
unsafe { _ = &integerEncodedSequence; } // Skip struct initialization
integerEncodedSequence.Reset();
IntegerEncoded.DecodeIntegerSequence(ref integerEncodedSequence, ref colorBitStream, range, numberValues);
// Once we have the decoded values, we need to dequantize them to the 0-255 range
// This procedure is outlined in ASTC spec C.2.13
int outputIndices = 0;
foreach (ref IntegerEncoded intEncoded in integerEncodedSequence.List)
{
int bitLength = intEncoded.NumberBits;
int bitValue = intEncoded.BitValue;
Debug.Assert(bitLength >= 1);
int a = 0, b = 0, c = 0, d = 0;
// A is just the lsb replicated 9 times.
a = Bits.Replicate(bitValue & 1, 1, 9);
switch (intEncoded.GetEncoding())
{
case IntegerEncoded.EIntegerEncoding.JustBits:
{
outputValues[outputIndices++] = Bits.Replicate(bitValue, bitLength, 8);
break;
}
case IntegerEncoded.EIntegerEncoding.Trit:
{
d = intEncoded.TritValue;
switch (bitLength)
{
case 1:
{
c = 204;
break;
}
case 2:
{
c = 93;
// B = b000b0bb0
int b2 = (bitValue >> 1) & 1;
b = (b2 << 8) | (b2 << 4) | (b2 << 2) | (b2 << 1);
break;
}
case 3:
{
c = 44;
// B = cb000cbcb
int cb = (bitValue >> 1) & 3;
b = (cb << 7) | (cb << 2) | cb;
break;
}
case 4:
{
c = 22;
// B = dcb000dcb
int dcb = (bitValue >> 1) & 7;
b = (dcb << 6) | dcb;
break;
}
case 5:
{
c = 11;
// B = edcb000ed
int edcb = (bitValue >> 1) & 0xF;
b = (edcb << 5) | (edcb >> 2);
break;
}
case 6:
{
c = 5;
// B = fedcb000f
int fedcb = (bitValue >> 1) & 0x1F;
b = (fedcb << 4) | (fedcb >> 4);
break;
}
default:
throw new AstcDecoderException("Unsupported trit encoding for color values.");
}
break;
}
case IntegerEncoded.EIntegerEncoding.Quint:
{
d = intEncoded.QuintValue;
switch (bitLength)
{
case 1:
{
c = 113;
break;
}
case 2:
{
c = 54;
// B = b0000bb00
int b2 = (bitValue >> 1) & 1;
b = (b2 << 8) | (b2 << 3) | (b2 << 2);
break;
}
case 3:
{
c = 26;
// B = cb0000cbc
int cb = (bitValue >> 1) & 3;
b = (cb << 7) | (cb << 1) | (cb >> 1);
break;
}
case 4:
{
c = 13;
// B = dcb0000dc
int dcb = (bitValue >> 1) & 7;
b = (dcb << 6) | (dcb >> 1);
break;
}
case 5:
{
c = 6;
// B = edcb0000e
int edcb = (bitValue >> 1) & 0xF;
b = (edcb << 5) | (edcb >> 3);
break;
}
default:
throw new AstcDecoderException("Unsupported quint encoding for color values.");
}
break;
}
}
if (intEncoded.GetEncoding() != IntegerEncoded.EIntegerEncoding.JustBits)
{
int T = d * c + b;
T ^= a;
T = (a & 0x80) | (T >> 2);
outputValues[outputIndices++] = T;
}
}
// Make sure that each of our values is in the proper range...
for (int i = 0; i < numberValues; i++)
{
Debug.Assert(outputValues[i] <= 255);
}
}
static void FillVoidExtentLdr(ref BitStream128 bitStream, Span<int> outputBuffer, int blockWidth, int blockHeight)
{
// Don't actually care about the void extent, just read the bits...
for (int i = 0; i < 4; ++i)
{
bitStream.ReadBits(13);
}
// Decode the RGBA components and renormalize them to the range [0, 255]
ushort r = (ushort)bitStream.ReadBits(16);
ushort g = (ushort)bitStream.ReadBits(16);
ushort b = (ushort)bitStream.ReadBits(16);
ushort a = (ushort)bitStream.ReadBits(16);
int rgba = (r >> 8) | (g & 0xFF00) | ((b) & 0xFF00) << 8 | ((a) & 0xFF00) << 16;
for (int j = 0; j < blockHeight; j++)
{
for (int i = 0; i < blockWidth; i++)
{
outputBuffer[j * blockWidth + i] = rgba;
}
}
}
static void DecodeBlockInfo(ref BitStream128 bitStream, out TexelWeightParams texelParams)
{
texelParams = new TexelWeightParams();
// Read the entire block mode all at once
ushort modeBits = (ushort)bitStream.ReadBits(11);
// Does this match the void extent block mode?
if ((modeBits & 0x01FF) == 0x1FC)
{
if ((modeBits & 0x200) != 0)
{
texelParams.VoidExtentHdr = true;
}
else
{
texelParams.VoidExtentLdr = true;
}
// Next two bits must be one.
if ((modeBits & 0x400) == 0 || bitStream.ReadBits(1) == 0)
{
texelParams.Error = true;
}
return;
}
// First check if the last four bits are zero
if ((modeBits & 0xF) == 0)
{
texelParams.Error = true;
return;
}
// If the last two bits are zero, then if bits
// [6-8] are all ones, this is also reserved.
if ((modeBits & 0x3) == 0 && (modeBits & 0x1C0) == 0x1C0)
{
texelParams.Error = true;
return;
}
// Otherwise, there is no error... Figure out the layout
// of the block mode. Layout is determined by a number
// between 0 and 9 corresponding to table C.2.8 of the
// ASTC spec.
int layout;
if ((modeBits & 0x1) != 0 || (modeBits & 0x2) != 0)
{
// layout is in [0-4]
if ((modeBits & 0x8) != 0)
{
// layout is in [2-4]
if ((modeBits & 0x4) != 0)
{
// layout is in [3-4]
if ((modeBits & 0x100) != 0)
{
layout = 4;
}
else
{
layout = 3;
}
}
else
{
layout = 2;
}
}
else
{
// layout is in [0-1]
if ((modeBits & 0x4) != 0)
{
layout = 1;
}
else
{
layout = 0;
}
}
}
else
{
// layout is in [5-9]
if ((modeBits & 0x100) != 0)
{
// layout is in [7-9]
if ((modeBits & 0x80) != 0)
{
// layout is in [7-8]
Debug.Assert((modeBits & 0x40) == 0);
if ((modeBits & 0x20) != 0)
{
layout = 8;
}
else
{
layout = 7;
}
}
else
{
layout = 9;
}
}
else
{
// layout is in [5-6]
if ((modeBits & 0x80) != 0)
{
layout = 6;
}
else
{
layout = 5;
}
}
}
Debug.Assert(layout < 10);
// Determine R
int r = (modeBits >> 4) & 1;
if (layout < 5)
{
r |= (modeBits & 0x3) << 1;
}
else
{
r |= (modeBits & 0xC) >> 1;
}
Debug.Assert(2 <= r && r <= 7);
// Determine width & height
switch (layout)
{
case 0:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 7) & 0x3;
texelParams.Width = b + 4;
texelParams.Height = a + 2;
break;
}
case 1:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 7) & 0x3;
texelParams.Width = b + 8;
texelParams.Height = a + 2;
break;
}
case 2:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 7) & 0x3;
texelParams.Width = a + 2;
texelParams.Height = b + 8;
break;
}
case 3:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 7) & 0x1;
texelParams.Width = a + 2;
texelParams.Height = b + 6;
break;
}
case 4:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 7) & 0x1;
texelParams.Width = b + 2;
texelParams.Height = a + 2;
break;
}
case 5:
{
int a = (modeBits >> 5) & 0x3;
texelParams.Width = 12;
texelParams.Height = a + 2;
break;
}
case 6:
{
int a = (modeBits >> 5) & 0x3;
texelParams.Width = a + 2;
texelParams.Height = 12;
break;
}
case 7:
{
texelParams.Width = 6;
texelParams.Height = 10;
break;
}
case 8:
{
texelParams.Width = 10;
texelParams.Height = 6;
break;
}
case 9:
{
int a = (modeBits >> 5) & 0x3;
int b = (modeBits >> 9) & 0x3;
texelParams.Width = a + 6;
texelParams.Height = b + 6;
break;
}
default:
// Don't know this layout...
texelParams.Error = true;
break;
}
// Determine whether or not we're using dual planes
// and/or high precision layouts.
bool d = ((layout != 9) && ((modeBits & 0x400) != 0));
bool h = (layout != 9) && ((modeBits & 0x200) != 0);
if (h)
{
ReadOnlySpan<byte> maxWeights = new byte[] { 9, 11, 15, 19, 23, 31 };
texelParams.MaxWeight = maxWeights[r - 2];
}
else
{
ReadOnlySpan<byte> maxWeights = new byte[] { 1, 2, 3, 4, 5, 7 };
texelParams.MaxWeight = maxWeights[r - 2];
}
texelParams.DualPlane = d;
}
}
}