|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Runtime.InteropServices; |
| 4 | +using BCnComp.Net.Shared; |
| 5 | + |
| 6 | +namespace BCnComp.Net.Decoder |
| 7 | +{ |
| 8 | + internal interface IBcBlockDecoder { |
| 9 | + RawBlock4X4Rgba32[,] Decode(ReadOnlySpan<byte> data, int pixelWidth, int pixelHeight, out int blockWidth, |
| 10 | + out int blockHeight); |
| 11 | + } |
| 12 | + |
| 13 | + internal class Bc1NoAlphaDecoder : IBcBlockDecoder { |
| 14 | + public RawBlock4X4Rgba32[,] Decode(ReadOnlySpan<byte> data, int pixelWidth, int pixelHeight, out int blockWidth, out int blockHeight) { |
| 15 | + blockWidth = (int)MathF.Ceiling(pixelWidth / 4.0f); |
| 16 | + blockHeight = (int)MathF.Ceiling(pixelHeight / 4.0f); |
| 17 | + |
| 18 | + if (data.Length != (blockWidth * blockHeight * Marshal.SizeOf<Bc1Block>())) { |
| 19 | + throw new InvalidDataException(); |
| 20 | + } |
| 21 | + |
| 22 | + var encodedBlocks = MemoryMarshal.Cast<byte, Bc1Block>(data); |
| 23 | + |
| 24 | + RawBlock4X4Rgba32[,] output = new RawBlock4X4Rgba32[blockWidth, blockHeight]; |
| 25 | + |
| 26 | + for (int x = 0; x < blockWidth; x++) { |
| 27 | + for (int y = 0; y < blockHeight; y++) { |
| 28 | + output[x, y] = encodedBlocks[x + y * blockWidth].Decode(false); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + return output; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + internal class Bc1ADecoder : IBcBlockDecoder { |
| 37 | + public RawBlock4X4Rgba32[,] Decode(ReadOnlySpan<byte> data, int pixelWidth, int pixelHeight, out int blockWidth, out int blockHeight) { |
| 38 | + blockWidth = (int)MathF.Ceiling(pixelWidth / 4.0f); |
| 39 | + blockHeight = (int)MathF.Ceiling(pixelHeight / 4.0f); |
| 40 | + |
| 41 | + if (data.Length != (blockWidth * blockHeight * Marshal.SizeOf<Bc1Block>())) { |
| 42 | + throw new InvalidDataException(); |
| 43 | + } |
| 44 | + |
| 45 | + var encodedBlocks = MemoryMarshal.Cast<byte, Bc1Block>(data); |
| 46 | + |
| 47 | + RawBlock4X4Rgba32[,] output = new RawBlock4X4Rgba32[blockWidth, blockHeight]; |
| 48 | + |
| 49 | + for (int x = 0; x < blockWidth; x++) { |
| 50 | + for (int y = 0; y < blockHeight; y++) { |
| 51 | + output[x, y] = encodedBlocks[x + y * blockWidth].Decode(true); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return output; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments