diff --git a/Source.Bitmap/ColorConversion.cs b/Source.Bitmap/ColorConversion.cs new file mode 100644 index 000000000..c12bbf1b7 --- /dev/null +++ b/Source.Bitmap/ColorConversion.cs @@ -0,0 +1,473 @@ +using Source.Common.Bitmap; + +using System.Runtime.InteropServices; + +namespace Source.Bitmap; + +public static partial class ImageLoader +{ + delegate void UserFormatToRGBA8888Func(ReadOnlySpan src, Span dst, int numPixels); + delegate void RGBA8888ToUserFormatFunc(ReadOnlySpan src, Span dst, int numPixels); + + static UserFormatToRGBA8888Func? GetUserFormatToRGBA8888Func(ImageFormat srcImageFormat) { + switch (srcImageFormat) { + case ImageFormat.RGBA8888: + return RGBA8888ToRGBA8888; + case ImageFormat.ABGR8888: + return ABGR8888ToRGBA8888; + case ImageFormat.RGB888: + return RGB888ToRGBA8888; + case ImageFormat.BGR888: + return BGR888ToRGBA8888; + case ImageFormat.RGB565: + return null; + case ImageFormat.I8: + return I8ToRGBA8888; + case ImageFormat.IA88: + return IA88ToRGBA8888; + case ImageFormat.A8: + return A8ToRGBA8888; + case ImageFormat.RGB888_Bluescreen: + return RGB888_BLUESCREENToRGBA8888; + case ImageFormat.BGR888_Bluescreen: + return BGR888_BLUESCREENToRGBA8888; + case ImageFormat.ARGB8888: + return ARGB8888ToRGBA8888; + case ImageFormat.BGRA8888: + return BGRA8888ToRGBA8888; + case ImageFormat.BGRX8888: + return BGRX8888ToRGBA8888; + case ImageFormat.BGR565: + return BGR565ToRGBA8888; + case ImageFormat.BGRX5551: + return BGRX5551ToRGBA8888; + case ImageFormat.BGRA5551: + return BGRA5551ToRGBA8888; + case ImageFormat.BGRA4444: + return BGRA4444ToRGBA8888; + case ImageFormat.UV88: + return UV88ToRGBA8888; + case ImageFormat.UVWQ8888: + return UVWQ8888ToRGBA8888; + case ImageFormat.UVLX8888: + return UVLX8888ToRGBA8888; + case ImageFormat.RGBA16161616: + return RGBA16161616ToRGBA8888; + case ImageFormat.RGBA16161616F: + return null; + default: + return null; + } + } + + static RGBA8888ToUserFormatFunc? GetRGBA8888ToUserFormatFunc(ImageFormat dstImageFormat) { + switch (dstImageFormat) { + case ImageFormat.RGBA8888: + return RGBA8888ToRGBA8888; + case ImageFormat.ABGR8888: + return RGBA8888ToABGR8888; + case ImageFormat.RGB888: + return RGBA8888ToRGB888; + case ImageFormat.BGR888: + return RGBA8888ToBGR888; + case ImageFormat.RGB565: + return null; + case ImageFormat.I8: + return RGBA8888ToI8; + case ImageFormat.IA88: + return RGBA8888ToIA88; + case ImageFormat.A8: + return RGBA8888ToA8; + case ImageFormat.RGB888_Bluescreen: + return RGBA8888ToRGB888_BLUESCREEN; + case ImageFormat.BGR888_Bluescreen: + return RGBA8888ToBGR888_BLUESCREEN; + case ImageFormat.ARGB8888: + return RGBA8888ToARGB8888; + case ImageFormat.BGRA8888: + return RGBA8888ToBGRA8888; + case ImageFormat.BGRX8888: + return RGBA8888ToBGRX8888; + case ImageFormat.BGR565: + return RGBA8888ToBGR565; + case ImageFormat.BGRX5551: + return RGBA8888ToBGRX5551; + case ImageFormat.BGRA5551: + return RGBA8888ToBGRA5551; + case ImageFormat.BGRA4444: + return RGBA8888ToBGRA4444; + case ImageFormat.UV88: + return RGBA8888ToUV88; + case ImageFormat.UVWQ8888: + return RGBA8888ToUVWQ8888; + case ImageFormat.UVLX8888: + return RGBA8888ToUVLX8888; + case ImageFormat.RGBA16161616F: + return null; + default: + return null; + } + } + + static bool ConvertUncompressedImageFormat(ReadOnlySpan src, ImageFormat srcImageFormat, Span dst, ImageFormat dstImageFormat, int width, int height, int srcStride, int dstStride) { + int srcPixelSize = SizeInBytes(srcImageFormat); + int dstPixelSize = SizeInBytes(dstImageFormat); + + if (srcStride == 0) + srcStride = srcPixelSize * width; + + if (dstStride == 0) + dstStride = dstPixelSize * width; + + if (srcImageFormat == dstImageFormat || (srcImageFormat == ImageFormat.BGRA8888 && dstImageFormat == ImageFormat.BGRX8888)) { + for (int line = 0; line < height; ++line) + src.Slice(line * srcStride, width * srcPixelSize).CopyTo(dst[(line * dstStride)..]); + + return true; + } + + UserFormatToRGBA8888Func? userFormatToRGBA8888Func = GetUserFormatToRGBA8888Func(srcImageFormat); + RGBA8888ToUserFormatFunc? rgba8888ToUserFormatFunc = GetRGBA8888ToUserFormatFunc(dstImageFormat); + if (userFormatToRGBA8888Func == null || rgba8888ToUserFormatFunc == null) + return false; + + Span lineBufRGBA8888 = width * 4 <= 16384 ? stackalloc byte[width * 4] : new byte[width * 4]; + + for (int line = 0; line < height; line++) { + userFormatToRGBA8888Func(src[(line * srcStride)..], lineBufRGBA8888, width); + rgba8888ToUserFormatFunc(lineBufRGBA8888, dst[(line * dstStride)..], width); + } + + return true; + } + + static void RGBA8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + src[..(4 * numPixels)].CopyTo(dst); + } + + static void RGBA8888ToABGR8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 3]; + dst[d + 1] = src[s + 2]; + dst[d + 2] = src[s + 1]; + dst[d + 3] = src[s + 0]; + } + } + + static void RGBA8888ToRGB888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 3) { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 2]; + } + } + + static void RGBA8888ToBGR888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 3) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + } + } + + static void RGBA8888ToI8(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 1) + dst[d] = (byte)(0.299f * src[s + 0] + 0.587f * src[s + 1] + 0.114f * src[s + 2]); + } + + static void RGBA8888ToIA88(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 2) { + dst[d + 0] = (byte)(0.299f * src[s + 0] + 0.587f * src[s + 1] + 0.114f * src[s + 2]); + dst[d + 1] = src[s + 3]; + } + } + + static void RGBA8888ToA8(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 1) + dst[d] = src[s + 3]; + } + + static void RGBA8888ToRGB888_BLUESCREEN(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 3) { + if (src[s + 3] == 0) { + dst[d + 0] = 0; + dst[d + 1] = 0; + dst[d + 2] = 255; + } + else { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 2]; + } + } + } + + static void RGBA8888ToBGR888_BLUESCREEN(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 3) { + if (src[s + 3] == 0) { + dst[d + 2] = 0; + dst[d + 1] = 0; + dst[d + 0] = 255; + } + else { + dst[d + 2] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 0] = src[s + 2]; + } + } + } + + static void RGBA8888ToARGB8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 3]; + dst[d + 1] = src[s + 0]; + dst[d + 2] = src[s + 1]; + dst[d + 3] = src[s + 2]; + } + } + + static void RGBA8888ToBGRA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + dst[d + 3] = src[s + 3]; + } + } + + static void RGBA8888ToBGRX8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + } + } + + static void RGBA8888ToBGR565(ReadOnlySpan src, Span dst, int numPixels) { + Span dstShort = MemoryMarshal.Cast(dst); + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d++) + dstShort[d] = (ushort)(((src[s + 0] >> 3) << 11) | ((src[s + 1] >> 2) << 5) | (src[s + 2] >> 3)); + } + + static void RGBA8888ToBGRX5551(ReadOnlySpan src, Span dst, int numPixels) { + Span dstShort = MemoryMarshal.Cast(dst); + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d++) + dstShort[d] = (ushort)(((src[s + 0] >> 3) << 10) | ((src[s + 1] >> 3) << 5) | (src[s + 2] >> 3)); + } + + static void RGBA8888ToBGRA5551(ReadOnlySpan src, Span dst, int numPixels) { + Span dstShort = MemoryMarshal.Cast(dst); + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d++) + dstShort[d] = (ushort)(((src[s + 0] >> 3) << 10) | ((src[s + 1] >> 3) << 5) | (src[s + 2] >> 3) | ((src[s + 3] >> 7) << 15)); + } + + static void RGBA8888ToBGRA4444(ReadOnlySpan src, Span dst, int numPixels) { + Span dstShort = MemoryMarshal.Cast(dst); + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d++) + dstShort[d] = (ushort)(((src[s + 0] >> 4) << 8) | ((src[s + 1] >> 4) << 4) | (src[s + 2] >> 4) | ((src[s + 3] >> 4) << 12)); + } + + static void RGBA8888ToUV88(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 2) { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + } + } + + static void RGBA8888ToUVWQ8888(ReadOnlySpan src, Span dst, int numPixels) => RGBA8888ToRGBA8888(src, dst, numPixels); + static void RGBA8888ToUVLX8888(ReadOnlySpan src, Span dst, int numPixels) => RGBA8888ToRGBA8888(src, dst, numPixels); + + static void ABGR8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 3]; + dst[d + 1] = src[s + 2]; + dst[d + 2] = src[s + 1]; + dst[d + 3] = src[s + 0]; + } + } + + static void RGB888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 3; s < end; s += 3, d += 4) { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 2]; + dst[d + 3] = 255; + } + } + + static void BGR888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 3; s < end; s += 3, d += 4) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + dst[d + 3] = 255; + } + } + + static void I8ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0; s < numPixels; s += 1, d += 4) { + dst[d + 0] = src[s]; + dst[d + 1] = src[s]; + dst[d + 2] = src[s]; + dst[d + 3] = 255; + } + } + + static void IA88ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 2; s < end; s += 2, d += 4) { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 0]; + dst[d + 2] = src[s + 0]; + dst[d + 3] = src[s + 1]; + } + } + + static void A8ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0; s < numPixels; s += 1, d += 4) { + dst[d + 0] = src[s]; + dst[d + 1] = src[s]; + dst[d + 2] = src[s]; + dst[d + 3] = src[s]; + } + } + + static void RGB888_BLUESCREENToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 3; s < end; s += 3, d += 4) { + if (src[s + 0] == 0 && src[s + 1] == 0 && src[s + 2] == 255) { + dst[d + 0] = 0; + dst[d + 1] = 0; + dst[d + 2] = 0; + dst[d + 3] = 0; + } + else { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 2]; + dst[d + 3] = 255; + } + } + } + + static void BGR888_BLUESCREENToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 3; s < end; s += 3, d += 4) { + if (src[s + 2] == 0 && src[s + 1] == 0 && src[s + 0] == 255) { + dst[d + 0] = 0; + dst[d + 1] = 0; + dst[d + 2] = 0; + dst[d + 3] = 0; + } + else { + dst[d + 2] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 0] = src[s + 2]; + dst[d + 3] = 255; + } + } + } + + static void ARGB8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 1]; + dst[d + 1] = src[s + 2]; + dst[d + 2] = src[s + 3]; + dst[d + 3] = src[s + 0]; + } + } + + static void BGRA8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + dst[d + 3] = src[s + 3]; + } + } + + static void BGRX8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = src[s + 2]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = src[s + 0]; + dst[d + 3] = 255; + } + } + + static void BGR565ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + ReadOnlySpan srcShort = MemoryMarshal.Cast(src); + for (int s = 0, d = 0; s < numPixels; s++, d += 4) { + uint blue = srcShort[s] & 0x1FU; + uint green = (uint)(srcShort[s] >> 5) & 0x3FU; + uint red = (uint)(srcShort[s] >> 11) & 0x1FU; + dst[d + 0] = (byte)((red << 3) | (red >> 2)); + dst[d + 1] = (byte)((green << 2) | (green >> 4)); + dst[d + 2] = (byte)((blue << 3) | (blue >> 2)); + dst[d + 3] = 255; + } + } + + static void BGRX5551ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + ReadOnlySpan srcShort = MemoryMarshal.Cast(src); + for (int s = 0, d = 0; s < numPixels; s++, d += 4) { + uint blue = srcShort[s] & 0x1FU; + uint green = (uint)(srcShort[s] >> 5) & 0x1FU; + uint red = (uint)(srcShort[s] >> 10) & 0x1FU; + dst[d + 0] = (byte)((red << 3) | (red >> 2)); + dst[d + 1] = (byte)((green << 3) | (green >> 2)); + dst[d + 2] = (byte)((blue << 3) | (blue >> 2)); + dst[d + 3] = 255; + } + } + + static void BGRA5551ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + ReadOnlySpan srcShort = MemoryMarshal.Cast(src); + for (int s = 0, d = 0; s < numPixels; s++, d += 4) { + uint blue = srcShort[s] & 0x1FU; + uint green = (uint)(srcShort[s] >> 5) & 0x1FU; + uint red = (uint)(srcShort[s] >> 10) & 0x1FU; + uint alpha = (uint)(srcShort[s] & (1 << 15)); + dst[d + 0] = (byte)((red << 3) | (red >> 2)); + dst[d + 1] = (byte)((green << 3) | (green >> 2)); + dst[d + 2] = (byte)((blue << 3) | (blue >> 2)); + if (alpha != 0) + dst[d + 3] = 255; + else + dst[d + 3] = 0; + } + } + + static void BGRA4444ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + ReadOnlySpan srcShort = MemoryMarshal.Cast(src); + for (int s = 0, d = 0; s < numPixels; s++, d += 4) { + uint blue = srcShort[s] & 0xFU; + uint green = (uint)(srcShort[s] >> 4) & 0xFU; + uint red = (uint)(srcShort[s] >> 8) & 0xFU; + uint alpha = (uint)(srcShort[s] >> 12) & 0xFU; + dst[d + 0] = (byte)((red << 4) | (red >> 4)); + dst[d + 1] = (byte)((green << 4) | (green >> 4)); + dst[d + 2] = (byte)((blue << 4) | (blue >> 4)); + dst[d + 3] = (byte)((alpha << 4) | (alpha >> 4)); + } + } + + static void UV88ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + for (int s = 0, d = 0, end = numPixels * 2; s < end; s += 2, d += 4) { + dst[d + 0] = src[s + 0]; + dst[d + 1] = src[s + 1]; + dst[d + 2] = 0; + dst[d + 3] = 0; + } + } + + static void UVWQ8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) => RGBA8888ToRGBA8888(src, dst, numPixels); + static void UVLX8888ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) => RGBA8888ToRGBA8888(src, dst, numPixels); + + static void RGBA16161616ToRGBA8888(ReadOnlySpan src, Span dst, int numPixels) { + ReadOnlySpan srcShort = MemoryMarshal.Cast(src); + for (int s = 0, d = 0, end = numPixels * 4; s < end; s += 4, d += 4) { + dst[d + 0] = (byte)Math.Min((ushort)255, (ushort)(srcShort[s + 0] >> 4)); + dst[d + 1] = (byte)Math.Min((ushort)255, (ushort)(srcShort[s + 1] >> 4)); + dst[d + 2] = (byte)Math.Min((ushort)255, (ushort)(srcShort[s + 2] >> 4)); + dst[d + 3] = (byte)Math.Min((ushort)255, (ushort)(srcShort[s + 3] >> 8)); + } + } +} diff --git a/Source.Bitmap/ColorConversionDXT.cs b/Source.Bitmap/ColorConversionDXT.cs new file mode 100644 index 000000000..d06a980cf --- /dev/null +++ b/Source.Bitmap/ColorConversionDXT.cs @@ -0,0 +1,556 @@ +using Source.Common.Bitmap; +using Source.Common.Mathematics; + +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; + +namespace Source.Bitmap; + +public interface IDestPixel where TSelf : unmanaged, IDestPixel +{ + static abstract TSelf From(BGRA8888 src); +} + +public interface IChannelDestPixel : IDestPixel where TSelf : unmanaged, IChannelDestPixel +{ + static abstract void SetR(ref TSelf pixel, byte value); + static abstract void SetG(ref TSelf pixel, byte value); + static abstract void SetB(ref TSelf pixel, byte value); + static abstract void SetA(ref TSelf pixel, byte value); +} + +public struct RGB888 : IDestPixel +{ + public byte R; + public byte G; + public byte B; + + public static RGB888 From(BGRA8888 src) => new() { R = src.R, G = src.G, B = src.B }; +} + +public struct BGR888 : IDestPixel +{ + public byte B; + public byte G; + public byte R; + + public static BGR888 From(BGRA8888 src) => new() { R = src.R, G = src.G, B = src.B }; +} + +public struct BGR565 : IDestPixel +{ + public ushort Value; + + public static BGR565 From(BGRA8888 src) => new() { Value = (ushort)((src.B >> 3) | ((src.G >> 2) << 5) | ((src.R >> 3) << 11)) }; +} + +public struct BGRA5551 : IChannelDestPixel +{ + public ushort Value; + + public static BGRA5551 From(BGRA8888 src) => new() { Value = (ushort)((src.B >> 3) | ((src.G >> 3) << 5) | ((src.R >> 3) << 10) | ((src.A >> 7) << 15)) }; + + public static void SetB(ref BGRA5551 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x001F) | (value & 0x1F)); + public static void SetG(ref BGRA5551 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x03E0) | ((value & 0x1F) << 5)); + public static void SetR(ref BGRA5551 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x7C00) | ((value & 0x1F) << 10)); + public static void SetA(ref BGRA5551 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x8000) | ((value & 0x1) << 15)); +} + +public struct BGRA4444 : IChannelDestPixel +{ + public ushort Value; + + public static BGRA4444 From(BGRA8888 src) => new() { Value = (ushort)((src.B >> 4) | ((src.G >> 4) << 4) | ((src.R >> 4) << 8) | ((src.A >> 4) << 12)) }; + + public static void SetB(ref BGRA4444 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x000F) | (value & 0xF)); + public static void SetG(ref BGRA4444 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x00F0) | ((value & 0xF) << 4)); + public static void SetR(ref BGRA4444 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0x0F00) | ((value & 0xF) << 8)); + public static void SetA(ref BGRA4444 pixel, byte value) => pixel.Value = (ushort)((pixel.Value & ~0xF000) | ((value & 0xF) << 12)); +} + +public static partial class ImageLoader +{ + const int DXT_COL_BLOCK_SIZE = 8; + const int DXT_ALPHA_BLOCK_SIZE = 8; + + static void GetColorBlockColorsBGRA8888(ReadOnlySpan block, out BGRA8888 col_0, out BGRA8888 col_1, out BGRA8888 col_2, out BGRA8888 col_3) { + ushort color0 = BinaryPrimitives.ReadUInt16LittleEndian(block); + ushort color1 = BinaryPrimitives.ReadUInt16LittleEndian(block[2..]); + + col_0.A = 0xff; + col_0.R = (byte)(((color0 >> 11) & 0x1F) << 3); + col_0.G = (byte)(((color0 >> 5) & 0x3F) << 2); + col_0.B = (byte)((color0 & 0x1F) << 3); + + col_1.A = 0xff; + col_1.R = (byte)(((color1 >> 11) & 0x1F) << 3); + col_1.G = (byte)(((color1 >> 5) & 0x3F) << 2); + col_1.B = (byte)((color1 & 0x1F) << 3); + + if (color0 > color1) { + col_2.R = (byte)((col_0.R * 2 + col_1.R) / 3); + col_2.G = (byte)((col_0.G * 2 + col_1.G) / 3); + col_2.B = (byte)((col_0.B * 2 + col_1.B) / 3); + col_2.A = 0xff; + + col_3.R = (byte)((col_0.R + col_1.R * 2) / 3); + col_3.G = (byte)((col_0.G + col_1.G * 2) / 3); + col_3.B = (byte)((col_0.B + col_1.B * 2) / 3); + col_3.A = 0xff; + } + else { + col_2.R = (byte)((col_0.R + col_1.R) / 2); + col_2.G = (byte)((col_0.G + col_1.G) / 2); + col_2.B = (byte)((col_0.B + col_1.B) / 2); + col_2.A = 0xff; + + col_3.R = 0x00; + col_3.G = 0xff; + col_3.B = 0xff; + col_3.A = 0x00; + } + } + + static void DecodeColorBlock(Span outputImage, ReadOnlySpan colorBlock, int width, in BGRA8888 col_0, in BGRA8888 col_1, in BGRA8888 col_2, in BGRA8888 col_3) where T : unmanaged, IDestPixel { + int output = 0; + for (int r = 0; r < 4; r++, output += width - 4) { + for (int n = 0; n < 4; n++) { + int bits = (colorBlock[4 + r] >> (n * 2)) & 3; + switch (bits) { + case 0: + outputImage[output] = T.From(col_0); + output++; + break; + case 1: + outputImage[output] = T.From(col_1); + output++; + break; + case 2: + outputImage[output] = T.From(col_2); + output++; + break; + case 3: + outputImage[output] = T.From(col_3); + output++; + break; + } + } + } + } + + static void DecodeAlpha3BitLinear(Span image, ReadOnlySpan alphaBlock, int width, int channelSelect = 3) where T : unmanaged, IChannelDestPixel { + Span bitCodes = stackalloc byte[16]; + Span alphas = stackalloc ushort[8]; + + alphas[0] = alphaBlock[0]; + alphas[1] = alphaBlock[1]; + + if (alphas[0] > alphas[1]) { + alphas[2] = (ushort)((6 * alphas[0] + alphas[1]) / 7); + alphas[3] = (ushort)((5 * alphas[0] + 2 * alphas[1]) / 7); + alphas[4] = (ushort)((4 * alphas[0] + 3 * alphas[1]) / 7); + alphas[5] = (ushort)((3 * alphas[0] + 4 * alphas[1]) / 7); + alphas[6] = (ushort)((2 * alphas[0] + 5 * alphas[1]) / 7); + alphas[7] = (ushort)((alphas[0] + 6 * alphas[1]) / 7); + } + else { + alphas[2] = (ushort)((4 * alphas[0] + alphas[1]) / 5); + alphas[3] = (ushort)((3 * alphas[0] + 2 * alphas[1]) / 5); + alphas[4] = (ushort)((2 * alphas[0] + 3 * alphas[1]) / 5); + alphas[5] = (ushort)((alphas[0] + 4 * alphas[1]) / 5); + alphas[6] = 0; + alphas[7] = 255; + } + + const uint mask = 0x00000007; + + uint bits = (uint)(alphaBlock[2] | (alphaBlock[3] << 8) | (alphaBlock[4] << 16)); + for (int i = 0; i < 8; i++) { + bitCodes[i] = (byte)(bits & mask); + bits >>= 3; + } + + bits = (uint)(alphaBlock[5] | (alphaBlock[6] << 8) | (alphaBlock[7] << 16)); + for (int i = 8; i < 16; i++) { + bitCodes[i] = (byte)(bits & mask); + bits >>= 3; + } + + int pos = 0; + for (int row = 0; row < 4; row++, pos += width - 4) { + for (int pix = 0; pix < 4; pix++) { + byte alpha = (byte)alphas[bitCodes[row * 4 + pix]]; + ref T pixel = ref image[pos]; + switch (channelSelect) { + case 0: + T.SetR(ref pixel, alpha); + T.SetG(ref pixel, 0); + T.SetB(ref pixel, 0); + T.SetA(ref pixel, 0); + break; + case 1: + T.SetG(ref pixel, alpha); + break; + case 2: + T.SetB(ref pixel, alpha); + break; + default: + case 3: + T.SetA(ref pixel, alpha); + break; + } + pos++; + } + } + } + + static void ConvertFromDXT1(ReadOnlySpan src, Span dst, int width, int height) where T : unmanaged, IDestPixel { + int realWidth = 0; + int realHeight = 0; + Span realDst = default; + + if (width < 4 || height < 4) { + realWidth = width; + realHeight = height; + + width = (width + 3) & ~3; + height = (height + 3) & ~3; + + realDst = dst; + dst = new T[width * height]; + } + + Assert((width % 4) == 0); + Assert((height % 4) == 0); + + int xblocks = width >> 2; + int yblocks = height >> 2; + + for (int j = 0; j < yblocks; j++) { + int block = j * xblocks * DXT_COL_BLOCK_SIZE; + for (int i = 0; i < xblocks; i++, block += DXT_COL_BLOCK_SIZE) { + ReadOnlySpan colorBlock = src.Slice(block, DXT_COL_BLOCK_SIZE); + GetColorBlockColorsBGRA8888(colorBlock, out BGRA8888 col_0, out BGRA8888 col_1, out BGRA8888 col_2, out BGRA8888 col_3); + + Span dstScan = dst[(i * 4 + j * 4 * width)..]; + DecodeColorBlock(dstScan, colorBlock, width, col_0, col_1, col_2, col_3); + } + } + + if (!realDst.IsEmpty) { + for (int y = 0; y < realHeight; y++) + for (int x = 0; x < realWidth; x++) + realDst[x + (y * realWidth)] = dst[x + (y * width)]; + } + } + + static void ConvertFromDXT5(ReadOnlySpan src, Span dst, int width, int height) where T : unmanaged, IChannelDestPixel { + int realWidth = 0; + int realHeight = 0; + Span realDst = default; + + if (width < 4 || height < 4) { + realWidth = width; + realHeight = height; + + width = (width + 3) & ~3; + height = (height + 3) & ~3; + + realDst = dst; + dst = new T[width * height]; + } + + Assert((width % 4) == 0); + Assert((height % 4) == 0); + + int xblocks = width >> 2; + int yblocks = height >> 2; + + for (int j = 0; j < yblocks; j++) { + int block = j * xblocks * (DXT_ALPHA_BLOCK_SIZE + DXT_COL_BLOCK_SIZE); + for (int i = 0; i < xblocks; i++, block += DXT_ALPHA_BLOCK_SIZE + DXT_COL_BLOCK_SIZE) { + ReadOnlySpan alphaBlock = src.Slice(block, DXT_ALPHA_BLOCK_SIZE); + ReadOnlySpan colorBlock = src.Slice(block + DXT_ALPHA_BLOCK_SIZE, DXT_COL_BLOCK_SIZE); + + GetColorBlockColorsBGRA8888(colorBlock, out BGRA8888 col_0, out BGRA8888 col_1, out BGRA8888 col_2, out BGRA8888 col_3); + + Span dstScan = dst[(i * 4 + j * 4 * width)..]; + + DecodeColorBlock(dstScan, colorBlock, width, col_0, col_1, col_2, col_3); + + DecodeAlpha3BitLinear(dstScan, alphaBlock, width); + } + } + + if (!realDst.IsEmpty) { + for (int y = 0; y < realHeight; y++) + for (int x = 0; x < realWidth; x++) + realDst[x + (y * realWidth)] = dst[x + (y * width)]; + } + } + + static void ConvertFromDXT5IgnoreAlpha(ReadOnlySpan src, Span dst, int width, int height) where T : unmanaged, IDestPixel { + int realWidth = 0; + int realHeight = 0; + Span realDst = default; + + if (width < 4 || height < 4) { + realWidth = width; + realHeight = height; + + width = (width + 3) & ~3; + height = (height + 3) & ~3; + + realDst = dst; + dst = new T[width * height]; + } + + Assert((width % 4) == 0); + Assert((height % 4) == 0); + + int xblocks = width >> 2; + int yblocks = height >> 2; + + for (int j = 0; j < yblocks; j++) { + int block = j * xblocks * (DXT_ALPHA_BLOCK_SIZE + DXT_COL_BLOCK_SIZE); + for (int i = 0; i < xblocks; i++, block += DXT_ALPHA_BLOCK_SIZE + DXT_COL_BLOCK_SIZE) { + ReadOnlySpan colorBlock = src.Slice(block + DXT_ALPHA_BLOCK_SIZE, DXT_COL_BLOCK_SIZE); + + GetColorBlockColorsBGRA8888(colorBlock, out BGRA8888 col_0, out BGRA8888 col_1, out BGRA8888 col_2, out BGRA8888 col_3); + + Span dstScan = dst[(i * 4 + j * 4 * width)..]; + + DecodeColorBlock(dstScan, colorBlock, width, col_0, col_1, col_2, col_3); + } + } + + if (!realDst.IsEmpty) { + for (int y = 0; y < realHeight; y++) + for (int x = 0; x < realWidth; x++) + realDst[x + (y * realWidth)] = dst[x + (y * width)]; + } + } + + static void ConvertFromATIxN(ReadOnlySpan src, Span dst, int width, int height, bool ati2n) where T : unmanaged, IChannelDestPixel { + int realWidth = 0; + int realHeight = 0; + Span realDst = default; + + if (width < 4 || height < 4) { + realWidth = width; + realHeight = height; + + width = (width + 3) & ~3; + height = (height + 3) & ~3; + + realDst = dst; + dst = new T[width * height]; + } + + Assert((width % 4) == 0); + Assert((height % 4) == 0); + + int xblocks = width >> 2; + int yblocks = height >> 2; + + int bytesPerBlock = ati2n ? 16 : 8; + + for (int j = 0; j < yblocks; j++) { + int block = j * xblocks * bytesPerBlock; + for (int i = 0; i < xblocks; i++, block += DXT_ALPHA_BLOCK_SIZE) { + Span dstScan = dst[(i * 4 + j * 4 * width)..]; + + DecodeAlpha3BitLinear(dstScan, src.Slice(block, DXT_ALPHA_BLOCK_SIZE), width, 0); + + if (ati2n) { + block += DXT_ALPHA_BLOCK_SIZE; + DecodeAlpha3BitLinear(dstScan, src.Slice(block, DXT_ALPHA_BLOCK_SIZE), width, 1); + } + } + } + + if (!realDst.IsEmpty) { + for (int y = 0; y < realHeight; y++) + for (int x = 0; x < realWidth; x++) + realDst[x + (y * realWidth)] = dst[x + (y * width)]; + } + } + + static void ConvertImageFormat_RGBA16161616_To_RGB323232F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int s = 0, d = 0; s < srcSize; s += 4, d += 3) { + dstImage[d + 0] = srcImage[s + 0] * (1.0f / (1 << 12)); + dstImage[d + 1] = srcImage[s + 1] * (1.0f / (1 << 12)); + dstImage[d + 2] = srcImage[s + 2] * (1.0f / (1 << 12)); + } + } + + static void ConvertImageFormat_RGB323232F_To_RGBA16161616(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 3; + for (int s = 0, d = 0; s < srcSize; s += 3, d += 4) { + dstImage[d + 0] = (ushort)(int)Math.Min(65535.0f, srcImage[s + 0] * (1 << 12)); + dstImage[d + 1] = (ushort)(int)Math.Min(65535.0f, srcImage[s + 1] * (1 << 12)); + dstImage[d + 2] = (ushort)(int)Math.Min(65535.0f, srcImage[s + 2] * (1 << 12)); + dstImage[d + 3] = 65535; + } + } + + static void ConvertImageFormat_RGBA16161616F_To_RGB323232F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int s = 0, d = 0; s < srcSize; s += 4, d += 3) { + dstImage[d + 0] = Float16.Convert16bitFloatTo32bits(srcImage[s + 0]); + dstImage[d + 1] = Float16.Convert16bitFloatTo32bits(srcImage[s + 1]); + dstImage[d + 2] = Float16.Convert16bitFloatTo32bits(srcImage[s + 2]); + } + } + + static void ConvertImageFormat_RGBA16161616F_To_RGBA323232F(ReadOnlySpan srcImage, Span dstImage, int width, int height, int srcStride) { + int stride = srcStride / 2; + int src = 0; + int dst = 0; + for (int y = 0; y < height; y++) { + int srcScan = src; + int dstScan = dst; + for (int x = 0; x < width; x++) { + dstImage[dstScan + 0] = Float16.Convert16bitFloatTo32bits(srcImage[srcScan + 0]); + dstImage[dstScan + 1] = Float16.Convert16bitFloatTo32bits(srcImage[srcScan + 1]); + dstImage[dstScan + 2] = Float16.Convert16bitFloatTo32bits(srcImage[srcScan + 2]); + dstImage[dstScan + 3] = Float16.Convert16bitFloatTo32bits(srcImage[srcScan + 3]); + dstScan += 4; + srcScan += 4; + } + src += stride; + dst += 4 * width; + } + } + + static void ConvertImageFormat_RGB323232F_To_RGBA16161616F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 3; + for (int s = 0, d = 0; s < srcSize; s += 3, d += 4) { + dstImage[d + 0] = Float16.ConvertFloatTo16bits(srcImage[s + 0]); + dstImage[d + 1] = Float16.ConvertFloatTo16bits(srcImage[s + 1]); + dstImage[d + 2] = Float16.ConvertFloatTo16bits(srcImage[s + 2]); + } + } + + static FloatBitMap CompressRGB323232FTo8Bits(ReadOnlySpan srcImage, int width, int height) { + FloatBitMap flbm = new(); + flbm.AllocateRGB(width, height); + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + int pf = 3 * (x + width * y); + PixRGBAF fpix; + fpix.Red = srcImage[pf + 0]; + fpix.Green = srcImage[pf + 1]; + fpix.Blue = srcImage[pf + 2]; + fpix.Alpha = 0.0f; + flbm.WritePixelRGBAF(x, y, fpix); + } + } + + flbm.CompressTo8Bits(8.0f); + return flbm; + } + + static void ConvertImageFormat_RGB323232F_To_RGBA8888(ReadOnlySpan srcImage, Span dst, int width, int height) { + FloatBitMap flbm = CompressRGB323232FTo8Bits(srcImage, width, height); + + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + PixRGBAF fpix = flbm.PixelRGBAF(x, y); + PixRGBA8 pix8 = fpix.To8(fpix); + int pch = 4 * (x + width * y); + dst[pch + 0] = pix8.Red; + dst[pch + 1] = pix8.Green; + dst[pch + 2] = pix8.Blue; + dst[pch + 3] = pix8.Alpha; + } + } + } + + static void ConvertImageFormat_RGB323232F_To_BGRA8888(ReadOnlySpan srcImage, Span dst, int width, int height) { + FloatBitMap flbm = CompressRGB323232FTo8Bits(srcImage, width, height); + + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + PixRGBAF fpix = flbm.PixelRGBAF(x, y); + PixRGBA8 pix8 = fpix.To8(fpix); + int pch = 4 * (x + width * y); + dst[pch + 0] = pix8.Blue; + dst[pch + 1] = pix8.Green; + dst[pch + 2] = pix8.Red; + dst[pch + 3] = pix8.Alpha; + } + } + } + + static void ConvertImageFormat_RGBA16161616_To_RGBA16161616F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int i = 0; i < srcSize; i += 4) { + dstImage[i + 0] = Float16.ConvertFloatTo16bits(srcImage[i + 0] * (1.0f / (1 << 16))); + dstImage[i + 1] = Float16.ConvertFloatTo16bits(srcImage[i + 1] * (1.0f / (1 << 16))); + dstImage[i + 2] = Float16.ConvertFloatTo16bits(srcImage[i + 2] * (1.0f / (1 << 16))); + dstImage[i + 3] = Float16.ConvertFloatTo16bits(srcImage[i + 3] * (1.0f / (1 << 16))); + } + } + + static void ConvertImageFormat_RGBA16161616F_To_RGBA16161616(ReadOnlySpan srcImage, Span dstImage, int width, int height) { + int srcSize = width * height * 4; + for (int i = 0; i < srcSize; i += 4) { + for (int j = 0; j < 4; j++) { + float val = Float16.Convert16bitFloatTo32bits(srcImage[i + j]); + val *= 1 << 12; + val = Math.Max(val, 0.0f); + val = Math.Min(val, 65535.0f); + dstImage[i + j] = (ushort)val; + } + } + } + + public static void ConvertNormalMapRGBA8888ToDUDVMapUVWQ8888(ReadOnlySpan src, int width, int height, Span dst) { + int lastPixel = width * height * 4; + for (int s = 0, d = 0; s < lastPixel; s += 4, d += 4) { + dst[d + 0] = unchecked((byte)(src[s + 0] - 127)); + dst[d + 1] = unchecked((byte)(src[s + 1] - 127)); + dst[d + 2] = unchecked((byte)(src[s + 2] - 127)); + dst[d + 3] = unchecked((byte)(src[s + 3] - 127)); + } + } + + public static void ConvertNormalMapRGBA8888ToDUDVMapUVLX8888(ReadOnlySpan src, int width, int height, Span dst) { + int lastPixel = width * height * 4; + for (int s = 0, d = 0; s < lastPixel; s += 4, d += 4) { + dst[d + 0] = unchecked((byte)(src[s + 0] - 127)); + dst[d + 1] = unchecked((byte)(src[s + 1] - 127)); + dst[d + 2] = src[s + 3]; + dst[d + 3] = 0xFF; + } + } + + public static void ConvertNormalMapRGBA8888ToDUDVMapUV88(ReadOnlySpan src, int width, int height, Span dst) { + int lastPixel = width * height * 4; + for (int s = 0, d = 0; s < lastPixel; s += 4, d += 2) { + dst[d + 0] = unchecked((byte)(src[s + 0] - 127)); + dst[d + 1] = unchecked((byte)(src[s + 1] - 127)); + } + } + + public static void NormalizeNormalMapRGBA8888(Span src, int numTexels) { + int lastPixel = numTexels * 4; + for (int i = 0; i < lastPixel; i += 4) { + float x = (src[i + 0] - 128.0f) * (1.0f / 127.0f); + float y = (src[i + 1] - 128.0f) * (1.0f / 127.0f); + float z = (src[i + 2] - 128.0f) * (1.0f / 127.0f); + + float sqlen = x * x + y * y + z * z + 1.0e-10f; + float invlen = Sse.IsSupported ? Sse.ReciprocalSqrtScalar(Vector128.CreateScalarUnsafe(sqlen)).ToScalar() : MathF.ReciprocalSqrtEstimate(sqlen); + invlen = (3.0f - invlen * invlen * sqlen) * 0.5f * invlen; + + src[i + 0] = unchecked((byte)(int)(x * invlen * 127.0f + 128.0f)); + src[i + 1] = unchecked((byte)(int)(y * invlen * 127.0f + 128.0f)); + src[i + 2] = unchecked((byte)(int)(z * invlen * 127.0f + 128.0f)); + } + } +} diff --git a/Source.Bitmap/ImageLoader.cs b/Source.Bitmap/ImageLoader.cs index a738b8a4a..a97afeb2f 100644 --- a/Source.Bitmap/ImageLoader.cs +++ b/Source.Bitmap/ImageLoader.cs @@ -7,23 +7,37 @@ namespace Source.Bitmap; -public struct RGBA8888 +public struct RGBA8888 : IChannelDestPixel { public byte R; public byte G; public byte B; public byte A; + + public static RGBA8888 From(BGRA8888 src) => new() { R = src.R, G = src.G, B = src.B, A = src.A }; + + public static void SetR(ref RGBA8888 pixel, byte value) => pixel.R = value; + public static void SetG(ref RGBA8888 pixel, byte value) => pixel.G = value; + public static void SetB(ref RGBA8888 pixel, byte value) => pixel.B = value; + public static void SetA(ref RGBA8888 pixel, byte value) => pixel.A = value; } -public struct BGRA8888 +public struct BGRA8888 : IChannelDestPixel { public byte B; public byte G; public byte R; public byte A; + + public static BGRA8888 From(BGRA8888 src) => src; + + public static void SetR(ref BGRA8888 pixel, byte value) => pixel.R = value; + public static void SetG(ref BGRA8888 pixel, byte value) => pixel.G = value; + public static void SetB(ref BGRA8888 pixel, byte value) => pixel.B = value; + public static void SetA(ref BGRA8888 pixel, byte value) => pixel.A = value; } -public static class ImageLoader +public static partial class ImageLoader { static readonly ImageFormatInfo[] g_ImageFormatInfo = [ new( "UNKNOWN", 0, 0, 0, 0, 0, false ), // IMAGE_FORMAT_UNKNOWN, @@ -366,76 +380,168 @@ public static int GetNumMipMapLevels(int width, int height, int depth) { _ => throw new NotSupportedException($"GetGLImageFormat: unexpected format '{format}'"), }; - public static bool ConvertImageFormat(Span srcData, ImageFormat srcFormat, Span dstData, ImageFormat dstFormat, int width, int height) { - if (srcFormat == dstFormat) { - memcpy(dstData, srcData); - return true; + public static bool ConvertImageFormat(Span srcData, ImageFormat srcFormat, Span dstData, ImageFormat dstFormat, int width, int height, int srcStride = 0, int dstStride = 0) { +#if GMOD_DLL + if (srcData.IsEmpty || dstData.IsEmpty) { + Warning("ConvertImageFormat: Invalid source or target image!\n"); + return false; } - switch (srcFormat) { - case ImageFormat.DXT5: - switch (dstFormat) { - case ImageFormat.RGBA8888: - ConvertFromDXT5(srcData, MemoryMarshal.Cast(dstData), width, height); - return true; - } - break; - case ImageFormat.RGBA16161616: - switch (dstFormat) { - case ImageFormat.RGBA16161616F: - ConvertImageFormat_RGBA16161616_To_RGBA16161616F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); - return true; - } - break; - case ImageFormat.RGBA16161616F: - switch (dstFormat) { - case ImageFormat.RGBA16161616: - ConvertImageFormat_RGBA16161616F_To_RGBA16161616(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); - return true; - } - break; + if (width <= 0 || height <= 0) { + Warning($"ConvertImageFormat: Invalid image size {width}x{height}!\n"); + return false; } +#endif - AssertMsg(false, $"No good way to convert {srcFormat} to {dstFormat}, expect issues\n"); - return false; - } - - static void ConvertImageFormat_RGBA16161616_To_RGBA16161616F(ReadOnlySpan srcImage, Span dstImage, int width, int height) { - int srcSize = width * height * 4; - for (int i = 0; i < srcSize; i += 4) { - dstImage[i + 0] = (Half)(srcImage[i + 0] * (1.0f / (float)(1 << 16))); - dstImage[i + 1] = (Half)(srcImage[i + 1] * (1.0f / (float)(1 << 16))); - dstImage[i + 2] = (Half)(srcImage[i + 2] * (1.0f / (float)(1 << 16))); - dstImage[i + 3] = (Half)(srcImage[i + 3] * (1.0f / (float)(1 << 16))); + if (srcFormat == ImageFormat.RGBA16161616) { + if (dstFormat == ImageFormat.RGB323232F) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGBA16161616_To_RGB323232F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGBA16161616F) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGBA16161616_To_RGBA16161616F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } } - } - - static void ConvertImageFormat_RGBA16161616F_To_RGBA16161616(ReadOnlySpan srcImage, Span dstImage, int width, int height) { - int srcSize = width * height * 4; - for (int i = 0; i < srcSize; i += 4) { - for (int j = 0; j < 4; j++) { - float val = (float)srcImage[i + j]; - val *= (float)(1 << 12); - val = Math.Max(val, 0); - val = Math.Min(val, 65535.0f); - dstImage[i + j] = (ushort)val; + else if (srcFormat == ImageFormat.RGBA16161616F) { + if (dstFormat == ImageFormat.RGB323232F) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGBA16161616F_To_RGB323232F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGBA32323232F) { + Assert(dstStride == 0); + ConvertImageFormat_RGBA16161616F_To_RGBA323232F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height, srcStride); + return true; + } + if (dstFormat == ImageFormat.RGBA16161616) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGBA16161616F_To_RGBA16161616(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + } + else if (srcFormat == ImageFormat.RGB323232F) { + if (dstFormat == ImageFormat.RGBA16161616) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGB323232F_To_RGBA16161616(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGBA16161616F) { + Assert(srcStride == 0 && dstStride == 0); + ConvertImageFormat_RGB323232F_To_RGBA16161616F(MemoryMarshal.Cast(srcData), MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGBA8888) { + Assert(srcStride == 0); + ConvertImageFormat_RGB323232F_To_RGBA8888(MemoryMarshal.Cast(srcData), dstData, width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA8888) { + Assert(srcStride == 0); + ConvertImageFormat_RGB323232F_To_BGRA8888(MemoryMarshal.Cast(srcData), dstData, width, height); + return true; } } - } - - private static void ConvertFromDXT5(Span srcData, Span span, int width, int height) { - int realWidth = 0; - int realHeight = 0; - - if (width < 4 || height < 4) - Assert(false); - - Assert((width % 4) == 0); - Assert((height % 4) == 0); - - int xblocks = width >> 2, yblocks = height >> 2; - BGRA8888 col0, col1, col2, col3; - throw new Exception("I don't care enough to implement ConvertFromDXT5 right now will do it later"); + if ((dstFormat == ImageFormat.DXT1 || dstFormat == ImageFormat.DXT3 || dstFormat == ImageFormat.DXT5 || dstFormat == ImageFormat.ATI1N || dstFormat == ImageFormat.ATI2N) && srcFormat == dstFormat) { + int memRequired = GetMemRequired(width, height, 1, srcFormat, false); + srcData[..memRequired].CopyTo(dstData); + return true; + } + else if ((srcFormat == ImageFormat.RGBA8888 || srcFormat == ImageFormat.RGB888 || srcFormat == ImageFormat.BGRA8888 || srcFormat == ImageFormat.BGRX8888) && + (dstFormat == ImageFormat.DXT1 || dstFormat == ImageFormat.DXT3 || dstFormat == ImageFormat.DXT5)) { + return false; + } + else if (srcFormat == ImageFormat.ARGB8888 && (dstFormat == ImageFormat.ATI1N || dstFormat == ImageFormat.ATI2N)) { + return false; + } + else if ((dstFormat == ImageFormat.RGBA8888 || dstFormat == ImageFormat.BGRX8888 || dstFormat == ImageFormat.BGRA8888 || dstFormat == ImageFormat.BGRA4444 || + dstFormat == ImageFormat.BGRA5551 || dstFormat == ImageFormat.BGRX5551 || dstFormat == ImageFormat.BGR565 || dstFormat == ImageFormat.BGR888 || dstFormat == ImageFormat.RGB888) && + (srcFormat == ImageFormat.DXT1 || srcFormat == ImageFormat.DXT3 || srcFormat == ImageFormat.DXT5 || srcFormat == ImageFormat.ATI1N || srcFormat == ImageFormat.ATI2N)) { + if (srcStride != 0 || dstStride != 0) + return false; + + if (srcFormat == ImageFormat.DXT1) { + if (dstFormat == ImageFormat.RGBA8888) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA8888 || dstFormat == ImageFormat.BGRX8888) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGB888) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGR888) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGR565) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA5551 || dstFormat == ImageFormat.BGRX5551) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA4444) { + ConvertFromDXT1(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + } + else if (srcFormat == ImageFormat.ATI2N) { + if (dstFormat == ImageFormat.BGRA8888) { + ConvertFromATIxN(srcData, MemoryMarshal.Cast(dstData), width, height, true); + return true; + } + } + else if (srcFormat == ImageFormat.ATI1N) { + if (dstFormat == ImageFormat.BGRA8888) { + ConvertFromATIxN(srcData, MemoryMarshal.Cast(dstData), width, height, false); + return true; + } + } + else if (srcFormat == ImageFormat.DXT5) { + if (dstFormat == ImageFormat.RGBA8888) { + ConvertFromDXT5(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA8888 || dstFormat == ImageFormat.BGRX8888) { + ConvertFromDXT5(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.RGB888) { + ConvertFromDXT5IgnoreAlpha(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGR888) { + ConvertFromDXT5IgnoreAlpha(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGR565) { + ConvertFromDXT5IgnoreAlpha(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA5551 || dstFormat == ImageFormat.BGRX5551) { + ConvertFromDXT5(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + if (dstFormat == ImageFormat.BGRA4444) { + ConvertFromDXT5(srcData, MemoryMarshal.Cast(dstData), width, height); + return true; + } + } + return false; + } + else if (dstFormat == ImageFormat.DXT1 || dstFormat == ImageFormat.DXT3 || dstFormat == ImageFormat.DXT5 || dstFormat == ImageFormat.ATI1N || dstFormat == ImageFormat.ATI2N || + srcFormat == ImageFormat.DXT1 || srcFormat == ImageFormat.DXT3 || srcFormat == ImageFormat.DXT5 || srcFormat == ImageFormat.ATI1N || srcFormat == ImageFormat.ATI2N) { + return false; + } + else + return ConvertUncompressedImageFormat(srcData, srcFormat, dstData, dstFormat, width, height, srcStride, dstStride); } } diff --git a/Source.Bitmap/Resample.cs b/Source.Bitmap/Resample.cs new file mode 100644 index 000000000..d51b28bb1 --- /dev/null +++ b/Source.Bitmap/Resample.cs @@ -0,0 +1,565 @@ +using Source.Common.Bitmap; +using Source.Common.Mathematics; + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Source.Bitmap; + +[Flags] +public enum ResampleFlags +{ + NormalMap = 0x1, + AlphaTest = 0x2, + NiceFilter = 0x4, + ClampS = 0x8, + ClampT = 0x10, + ClampU = 0x20 +} + +public ref struct ResampleInfo +{ + public Span Src; + public Span Dest; + + public int SrcWidth; + public int SrcHeight; + public int SrcDepth; + + public int DestWidth; + public int DestHeight; + public int DestDepth; + + public float SrcGamma; + public float DestGamma; + + public InlineArray4 ColorScale; + public InlineArray4 ColorGoal; + + public float AlphaThreshhold; + public float AlphaHiFreqThreshhold; + + public ResampleFlags Flags; + + public ResampleInfo() { + Flags = 0; + AlphaThreshhold = 0.4f; + AlphaHiFreqThreshhold = 0.4f; + SrcDepth = 1; + DestDepth = 1; + + ColorScale[0] = 1.0f; ColorGoal[0] = 0.0f; + ColorScale[1] = 1.0f; ColorGoal[1] = 0.0f; + ColorScale[2] = 1.0f; ColorGoal[2] = 0.0f; + ColorScale[3] = 1.0f; ColorGoal[3] = 0.0f; + } +} + +public static partial class ImageLoader +{ + static void ConstructFloatGammaTable(Span table, float srcGamma, float dstGamma) { + for (int i = 0; i < table.Length; i++) + table[i] = 255.0f * MathF.Pow((float)i / 255.0f, srcGamma / dstGamma); + } + + static void ConstructGammaTable(Span table, float srcGamma, float dstGamma) { + for (int i = 0; i < table.Length; i++) { + float f = 255.0f * MathF.Pow((float)i / 255.0f, srcGamma / dstGamma); + int v = (int)(f + 0.5f); + if (v < 0) + v = 0; + else if (v > 255) + v = 255; + table[i] = (byte)v; + } + } + + public static void GammaCorrectRGBA8888(ReadOnlySpan src, Span dst, int width, int height, int depth, ReadOnlySpan gammaTable) { + for (int h = 0; h < depth; ++h) { + for (int i = 0; i < height; ++i) { + for (int j = 0; j < width; ++j) { + int idx = (h * width * height + i * width + j) * 4; + + dst[idx] = gammaTable[src[idx]]; + dst[idx + 1] = gammaTable[src[idx + 1]]; + dst[idx + 2] = gammaTable[src[idx + 2]]; + } + } + } + } + + static readonly byte[] s_Gamma = new byte[256]; + static float s_GammaLastSrcGamma = -1; + static float s_GammaLastDstGamma = -1; + + public static void GammaCorrectRGBA8888(Span src, Span dst, int width, int height, int depth, float srcGamma, float dstGamma) { + if (srcGamma == dstGamma) { + if (!Unsafe.AreSame(ref MemoryMarshal.GetReference(src), ref MemoryMarshal.GetReference(dst))) + src[..GetMemRequired(width, height, depth, ImageFormat.RGBA8888, false)].CopyTo(dst); + return; + } + + if (s_GammaLastSrcGamma != srcGamma || s_GammaLastDstGamma != dstGamma) { + ConstructGammaTable(s_Gamma, srcGamma, dstGamma); + s_GammaLastSrcGamma = srcGamma; + s_GammaLastDstGamma = dstGamma; + } + + GammaCorrectRGBA8888(src, dst, width, height, depth, s_Gamma); + } + + static void GenerateNiceFilter(float wratio, float hratio, float dratio, int kernelDiameter, Span kernel, Span invKernel) { + int h, i, j; + int kernelWidth = (int)(kernelDiameter * wratio); + int kernelHeight = (int)(kernelDiameter * hratio); + int kernelDepth = (dratio != 0) ? (int)(kernelDiameter * dratio) : 1; + + float dx = 1.0f / (float)wratio; + float dy = 1.0f / (float)hratio; + float z, dz; + + if (dratio != 0.0f) { + dz = 1.0f / (float)dratio; + z = -((float)kernelDiameter - dz) * 0.5f; + } + else { + dz = 0.0f; + z = 0.0f; + } + + float total = 0.0f; + for (h = 0; h < kernelDepth; ++h) { + float y = -((float)kernelDiameter - dy) * 0.5f; + for (i = 0; i < kernelHeight; ++i) { + float x = -((float)kernelDiameter - dx) * 0.5f; + for (j = 0; j < kernelWidth; ++j) { + int kernelIndex = kernelWidth * (i + h * kernelHeight) + j; + + float d = MathF.Sqrt(x * x + y * y + z * z); + if (d > kernelDiameter * 0.5f) { + kernel[kernelIndex] = 0.0f; + } + else { + float t = (float)(Math.PI * (double)d); + if (t != 0) { + float sinc = MathF.Sin(t) / t; + float sinc3 = 3.0f * MathF.Sin(t / 3.0f) / t; + kernel[kernelIndex] = sinc * sinc3; + } + else { + kernel[kernelIndex] = 1.0f; + } + total += kernel[kernelIndex]; + } + x += dx; + } + y += dy; + } + z += dz; + } + + float invFactor = (dratio == 0) ? wratio * hratio : dratio * wratio * hratio; + float invTotal = (total != 0.0f) ? 1.0f / total : 1.0f; + + for (h = 0; h < kernelDepth; ++h) { + for (i = 0; i < kernelHeight; ++i) { + int pixel = kernelWidth * (h * kernelHeight + i); + for (j = 0; j < kernelWidth; ++j) { + kernel[pixel + j] *= invTotal; + invKernel[pixel + j] = invFactor * kernel[pixel + j]; + } + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool IsPowerOfTwo(int x) => (x & (x - 1)) == 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static byte ResampleClamp(float x) { + int idx = (int)(x + 0.5f); + return (byte)Math.Clamp(idx, 0, 255); + } + + ref struct KernelInfo + { + public ReadOnlySpan Kernel; + public ReadOnlySpan InvKernel; + public int Width; + public int Height; + public int Depth; + public int Diameter; + } + + enum KernelType + { + Default = 0, + NormalMap, + AlphaTest + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int ActualX(int x, in ResampleInfo info) { + if ((info.Flags & ResampleFlags.ClampS) != 0) + return Math.Clamp(x, 0, info.SrcWidth - 1); + + return x & (info.SrcWidth - 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int ActualY(int y, in ResampleInfo info) { + if ((info.Flags & ResampleFlags.ClampT) != 0) + return Math.Clamp(y, 0, info.SrcHeight - 1); + + return y & (info.SrcHeight - 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int ActualZ(int z, in ResampleInfo info) { + if ((info.Flags & ResampleFlags.ClampU) != 0) + return Math.Clamp(z, 0, info.SrcDepth - 1); + + return z & (info.SrcDepth - 1); + } + + static void ComputeAveragedColor(KernelType type, bool niceFilter, in KernelInfo kernel, in ResampleInfo info, int startX, int startY, int startZ, ReadOnlySpan gammaToLinear, Span total) { + total[0] = total[1] = total[2] = total[3] = 0.0f; + for (int j = 0, srcZ = startZ; j < kernel.Depth; ++j, ++srcZ) { + int sz = ActualZ(srcZ, info); + sz *= info.SrcWidth * info.SrcHeight; + + for (int k = 0, srcY = startY; k < kernel.Height; ++k, ++srcY) { + int sy = ActualY(srcY, info); + sy *= info.SrcWidth; + + int kernelIdx; + if (niceFilter) + kernelIdx = kernel.Width * (k + j * kernel.Height); + else + kernelIdx = 0; + + for (int l = 0, srcX = startX; l < kernel.Width; ++l, ++srcX, ++kernelIdx) { + int sx = ActualX(srcX, info); + int srcPixel = (sz + sy + sx) << 2; + + float kernelFactor; + if (niceFilter) { + kernelFactor = kernel.Kernel[kernelIdx]; + if (kernelFactor == 0.0f) + continue; + } + else { + kernelFactor = kernel.Kernel[0]; + } + + if (type == KernelType.NormalMap) { + total[0] += kernelFactor * info.Src[srcPixel + 0]; + total[1] += kernelFactor * info.Src[srcPixel + 1]; + total[2] += kernelFactor * info.Src[srcPixel + 2]; + total[3] += kernelFactor * info.Src[srcPixel + 3]; + } + else if (type == KernelType.AlphaTest) { + total[0] += kernelFactor * gammaToLinear[info.Src[srcPixel + 0]]; + total[1] += kernelFactor * gammaToLinear[info.Src[srcPixel + 1]]; + total[2] += kernelFactor * gammaToLinear[info.Src[srcPixel + 2]]; + if (info.Src[srcPixel + 3] > 192) + total[3] += kernelFactor * 255.0f; + } + else { + total[0] += kernelFactor * gammaToLinear[info.Src[srcPixel + 0]]; + total[1] += kernelFactor * gammaToLinear[info.Src[srcPixel + 1]]; + total[2] += kernelFactor * gammaToLinear[info.Src[srcPixel + 2]]; + total[3] += kernelFactor * info.Src[srcPixel + 3]; + } + } + } + } + } + + static void AddAlphaToAlphaResult(bool niceFilter, in KernelInfo kernel, in ResampleInfo info, int startX, int startY, int startZ, float alpha, Span alphaResult) { + for (int j = 0, srcZ = startZ; j < kernel.Depth; ++j, ++srcZ) { + int sz = ActualZ(srcZ, info); + sz *= info.SrcWidth * info.SrcHeight; + + for (int k = 0, srcY = startY; k < kernel.Height; ++k, ++srcY) { + int sy = ActualY(srcY, info); + sy *= info.SrcWidth; + + int kernelIdx; + if (niceFilter) + kernelIdx = k * kernel.Width + j * kernel.Width * kernel.Height; + else + kernelIdx = 0; + + for (int l = 0, srcX = startX; l < kernel.Width; ++l, ++srcX, ++kernelIdx) { + int sx = ActualX(srcX, info); + int srcPixel = sz + sy + sx; + + float kernelFactor; + if (niceFilter) { + kernelFactor = kernel.InvKernel[kernelIdx]; + if (kernelFactor == 0.0f) + continue; + } + else { + kernelFactor = kernel.InvKernel[0]; + } + + alphaResult[srcPixel] += kernelFactor * alpha; + } + } + } + } + + static void AdjustAlphaChannel(in KernelInfo kernel, in ResampleInfo info, int wratio, int hratio, int dratio, Span alphaResult) { + for (int k = 0; k < info.SrcDepth; ++k) { + for (int i = 0; i < info.SrcHeight; ++i) { + int dstPixel = i * info.SrcWidth + k * info.SrcWidth * info.SrcHeight; + for (int j = 0; j < info.SrcWidth; ++j, ++dstPixel) + alphaResult[dstPixel] = MathF.Abs(alphaResult[dstPixel] - info.Src[dstPixel * 4 + 3]); + } + } + + int initialZ = (dratio >> 1) - ((dratio * kernel.Diameter) >> 1); + int initialY = (hratio >> 1) - ((hratio * kernel.Diameter) >> 1); + int initialX = (wratio >> 1) - ((wratio * kernel.Diameter) >> 1); + + float alphaThreshhold = (info.AlphaHiFreqThreshhold >= 0.0f) ? 255.0f * info.AlphaHiFreqThreshhold : 255.0f * 0.4f; + + float invFactor = (dratio == 0) ? 1.0f / (hratio * wratio) : 1.0f / (hratio * wratio * dratio); + + for (int h = 0; h < info.DestDepth; ++h) { + int startZ = dratio * h + initialZ; + for (int i = 0; i < info.DestHeight; ++i) { + int startY = hratio * i + initialY; + int dstPixel = (info.DestWidth * (i + h * info.DestHeight)) << 2; + for (int j = 0; j < info.DestWidth; ++j, dstPixel += 4) { + if (info.Dest[dstPixel + 3] == 255) + continue; + + int startX = wratio * j + initialX; + float alphaDelta = 0.0f; + + for (int m = 0, srcZ = startZ; m < dratio; ++m, ++srcZ) { + int sz = ActualZ(srcZ, info); + sz *= info.SrcWidth * info.SrcHeight; + + for (int k = 0, srcY = startY; k < hratio; ++k, ++srcY) { + int sy = ActualY(srcY, info); + sy *= info.SrcWidth; + + for (int l = 0, srcX = startX; l < wratio; ++l, ++srcX) { + int sx = ActualX(srcX, info); + + int srcPixel = sz + sy + sx; + alphaDelta += alphaResult[srcPixel]; + } + } + } + + alphaDelta *= invFactor; + if (alphaDelta > alphaThreshhold) + info.Dest[dstPixel + 3] = 255; + } + } + } + } + + static void ApplyKernel(KernelType type, bool niceFilter, in KernelInfo kernel, in ResampleInfo info, int wratio, int hratio, int dratio, ReadOnlySpan gammaToLinear, Span alphaResult) { + float invDstGamma = 1.0f / info.DestGamma; + + int initialZ = (dratio >> 1) - ((dratio * kernel.Diameter) >> 1); + int initialY = (hratio >> 1) - ((hratio * kernel.Diameter) >> 1); + int initialX = (wratio >> 1) - ((wratio * kernel.Diameter) >> 1); + + float alphaThreshhold = (info.AlphaThreshhold >= 0.0f) ? 255.0f * info.AlphaThreshhold : 255.0f * 0.4f; + Span total = stackalloc float[4]; + for (int k = 0; k < info.DestDepth; ++k) { + int startZ = dratio * k + initialZ; + + for (int i = 0; i < info.DestHeight; ++i) { + int startY = hratio * i + initialY; + int dstPixel = (i * info.DestWidth + k * info.DestWidth * info.DestHeight) << 2; + + for (int j = 0; j < info.DestWidth; ++j, dstPixel += 4) { + int startX = wratio * j + initialX; + + ComputeAveragedColor(type, niceFilter, kernel, info, startX, startY, startZ, gammaToLinear, total); + + if (type == KernelType.NormalMap) { + for (int ch = 0; ch < 4; ++ch) + info.Dest[dstPixel + ch] = ResampleClamp(info.ColorGoal[ch] + (info.ColorScale[ch] * (total[ch] - info.ColorGoal[ch]))); + } + else if (type == KernelType.AlphaTest) { + float alpha = (total[3] >= alphaThreshhold) ? 255.0f : 0; + + for (int ch = 0; ch < 3; ++ch) + info.Dest[dstPixel + ch] = ResampleClamp(255.0f * MathF.Pow((info.ColorGoal[ch] + (info.ColorScale[ch] * ((total[ch] > 0 ? total[ch] : 0) - info.ColorGoal[ch]))) / 255.0f, invDstGamma)); + info.Dest[dstPixel + 3] = ResampleClamp(alpha); + + AddAlphaToAlphaResult(niceFilter, kernel, info, startX, startY, startZ, alpha, alphaResult); + } + else { + for (int ch = 0; ch < 3; ++ch) + info.Dest[dstPixel + ch] = ResampleClamp(255.0f * MathF.Pow((info.ColorGoal[ch] + (info.ColorScale[ch] * ((total[ch] > 0 ? total[ch] : 0) - info.ColorGoal[ch]))) / 255.0f, invDstGamma)); + info.Dest[dstPixel + 3] = ResampleClamp(info.ColorGoal[3] + (info.ColorScale[3] * (total[3] - info.ColorGoal[3]))); + } + } + } + + if (type == KernelType.AlphaTest) + AdjustAlphaChannel(kernel, info, wratio, hratio, dratio, alphaResult); + } + } + + static readonly float[] s_GammaToLinear = new float[256]; + static float s_LastSrcGamma = -1; + static readonly float[]?[] s_KernelCache = new float[]?[10]; + static readonly float[]?[] s_InvKernelCache = new float[]?[10]; + + public static bool ResampleRGBA8888(in ResampleInfo info) { + if (info.SrcWidth == info.DestWidth && info.SrcHeight == info.DestHeight && info.SrcDepth == info.DestDepth) { + GammaCorrectRGBA8888(info.Src, info.Dest, info.SrcWidth, info.SrcHeight, info.SrcDepth, info.SrcGamma, info.DestGamma); + return true; + } + + if (!IsPowerOfTwo(info.SrcWidth) || !IsPowerOfTwo(info.SrcHeight) || !IsPowerOfTwo(info.SrcDepth) || + !IsPowerOfTwo(info.DestWidth) || !IsPowerOfTwo(info.DestHeight) || !IsPowerOfTwo(info.DestDepth)) { + return false; + } + + if ((info.SrcWidth < info.DestWidth) || (info.SrcHeight < info.DestHeight) || (info.SrcDepth < info.DestDepth)) + return false; + + if (s_LastSrcGamma != info.SrcGamma) { + ConstructFloatGammaTable(s_GammaToLinear, info.SrcGamma, 1.0f); + s_LastSrcGamma = info.SrcGamma; + } + + int wratio = info.SrcWidth / info.DestWidth; + int hratio = info.SrcHeight / info.DestHeight; + int dratio = (info.SrcDepth != info.DestDepth) ? info.SrcDepth / info.DestDepth : 0; + + scoped KernelInfo kernel = default; + + Span boxKernel = stackalloc float[1]; + Span boxInvKernel = stackalloc float[1]; + if ((info.Flags & ResampleFlags.NiceFilter) != 0) { + kernel.Diameter = 6; + + kernel.Width = kernel.Diameter * wratio; + kernel.Height = kernel.Diameter * hratio; + kernel.Depth = kernel.Diameter * dratio; + if (kernel.Depth == 0) + kernel.Depth = 1; + + int power = -1; + + if ((wratio == hratio) && (dratio == 0)) { + power = 0; + int tempWidth = wratio; + while (tempWidth > 1) { + ++power; + tempWidth >>= 1; + } + + if (power >= 10) + power = -1; + } + + if (power >= 0) { + if (s_KernelCache[power] == null) { + s_KernelCache[power] = new float[kernel.Width * kernel.Height]; + s_InvKernelCache[power] = new float[kernel.Width * kernel.Height]; + GenerateNiceFilter(wratio, hratio, dratio, kernel.Diameter, s_KernelCache[power], s_InvKernelCache[power]); + } + + kernel.Kernel = s_KernelCache[power]; + kernel.InvKernel = s_InvKernelCache[power]; + } + else { + float[] tempMemory = new float[kernel.Width * kernel.Height * kernel.Depth]; + float[] tempInvMemory = new float[kernel.Width * kernel.Height * kernel.Depth]; + GenerateNiceFilter(wratio, hratio, dratio, kernel.Diameter, tempMemory, tempInvMemory); + kernel.Kernel = tempMemory; + kernel.InvKernel = tempInvMemory; + } + } + else { + kernel.Width = wratio; + kernel.Height = hratio; + kernel.Depth = dratio != 0 ? dratio : 1; + + kernel.Diameter = 1; + + boxKernel[0] = 1.0f / (float)(kernel.Width * kernel.Height * kernel.Depth); + boxInvKernel[0] = 1.0f; + kernel.Kernel = boxKernel; + kernel.InvKernel = boxInvKernel; + } + + float[]? alphaResult = null; + KernelType type; + if ((info.Flags & ResampleFlags.NormalMap) != 0) { + type = KernelType.NormalMap; + } + else if ((info.Flags & ResampleFlags.AlphaTest) != 0) { + nint size = (nint)info.SrcHeight * info.SrcWidth * info.SrcDepth; + alphaResult = new float[size]; + type = KernelType.AlphaTest; + } + else { + type = KernelType.Default; + } + + ApplyKernel(type, (info.Flags & ResampleFlags.NiceFilter) != 0, kernel, info, wratio, hratio, dratio, s_GammaToLinear, alphaResult); + + return true; + } + + public static bool ResampleRGB323232F(in ResampleInfo info) { + Assert(IsPowerOfTwo(info.SrcWidth)); + Assert(IsPowerOfTwo(info.SrcHeight)); + Assert(IsPowerOfTwo(info.DestWidth)); + Assert(IsPowerOfTwo(info.DestHeight)); + + Assert(info.SrcWidth >= info.DestWidth); + Assert(info.SrcHeight >= info.DestHeight); + + int sampleWidth = info.SrcWidth / info.DestWidth; + int sampleHeight = info.SrcHeight / info.DestHeight; + + ReadOnlySpan src = MemoryMarshal.Cast(info.Src); + Span dst = MemoryMarshal.Cast(info.Dest); + + Span accum = stackalloc float[4]; + for (int y = 0; y < info.DestHeight; y++) { + int yMultiplier = y * sampleHeight; + + for (int x = 0; x < info.DestWidth; x++) { + accum.Clear(); + int xMultiplier = x * sampleWidth; + + for (int sampleY = 0; sampleY < sampleHeight; sampleY++) { + int yIndex = (yMultiplier + sampleY) * info.SrcWidth; + + for (int sampleX = 0; sampleX < sampleWidth; sampleX++) { + int xIndex = xMultiplier + sampleX; + int baseIndex = (xIndex + yIndex) * 3; + + accum[0] += src[baseIndex + 0]; + accum[1] += src[baseIndex + 1]; + accum[2] += src[baseIndex + 2]; + } + } + + int destIndex = (x + y * info.DestWidth) * 3; + for (int i = 0; i < 3; i++) { + accum[i] /= (sampleWidth * sampleHeight); + dst[destIndex + i] = accum[i]; + } + } + } + return true; + } +} diff --git a/Source.Common/Bitmap/FloatBitMap.cs b/Source.Common/Bitmap/FloatBitMap.cs index 369be7f91..facad6931 100644 --- a/Source.Common/Bitmap/FloatBitMap.cs +++ b/Source.Common/Bitmap/FloatBitMap.cs @@ -18,13 +18,18 @@ public struct PixRGBAF public PixRGBA8 To8(in PixRGBAF f) { PixRGBA8 x = new() { - Red = (byte)(Math.Max(0f, Math.Min(255f, 255f * f.Red))), - Green = (byte)(Math.Max(0f, Math.Min(255f, 255f * f.Green))), - Blue = (byte)(Math.Max(0f, Math.Min(255f, 255f * f.Blue))), - Alpha = (byte)(Math.Max(0f, Math.Min(255f, 255f * f.Alpha))) + Red = To8(f.Red), + Green = To8(f.Green), + Blue = To8(f.Blue), + Alpha = To8(f.Alpha) }; return x; } + + static byte To8(float f) { + double v = 255.0 * (double)f; + return v < 0 ? (byte)0 : (v > 255.0 ? (byte)255 : (byte)(int)v); + } } public struct PixRGBA8 @@ -174,6 +179,51 @@ public void ScaleRGB(float scaleFactor) { Pixel(x, y, c) *= scaleFactor; } + static float ScaleValue(float f, float overbright) { + int ival = (int)f; + return (float)(ival * ((double)overbright / 255.0)); + } + + static float IScaleValue(float f, float overbright) { + f = (float)((double)f * (1.0 / (double)overbright)); + double ival = Math.Ceiling((double)f * 255.0); + return ival > 255.0 ? 255.0f : (float)(int)ival; + } + + public void CompressTo8Bits(float overbright) { + FloatBitMap tmp = new(Width, Height); + + for (int y = 0; y < Height; y++) + for (int x = 0; x < Width; x++) + for (int c = 0; c < 3; c++) { + float value = Pixel(x, y, c); + Pixel(x, y, c) = value < overbright ? value : overbright; + } + + for (int y = 0; y < Height; y++) + for (int x = 0; x < Width; x++) { + float maxc = Math.Max(Pixel(x, y, 0), Math.Max(Pixel(x, y, 1), Pixel(x, y, 2))); + if (maxc == 0) { + for (int c = 0; c < 4; c++) + tmp.Pixel(x, y, c) = 0; + } + else { + float desiredFloatScale = maxc; + float closestIScale = IScaleValue(desiredFloatScale, overbright); + float scaleValueWeGot = ScaleValue(closestIScale, overbright); + tmp.Pixel(x, y, 3) = closestIScale; + for (int c = 0; c < 3; c++) + tmp.Pixel(x, y, c) = Pixel(x, y, c) / scaleValueWeGot; + } + } + + tmp.RGBAData.AsSpan(0, Width * Height * 4).CopyTo(RGBAData); + + for (int y = 0; y < Height; y++) + for (int x = 0; x < Width; x++) + Pixel(x, y, 3) = (float)((double)Pixel(x, y, 3) * (1.0 / 255.0)); + } + public float[] AllocateRGB(int width, int height) { RGBAData = null; RGBAData = new float[width * height * sizeof(float)]; diff --git a/Source.Common/MaterialSystem/PixelWriter.cs b/Source.Common/MaterialSystem/PixelWriter.cs index 862e59c8d..9089367f4 100644 --- a/Source.Common/MaterialSystem/PixelWriter.cs +++ b/Source.Common/MaterialSystem/PixelWriter.cs @@ -1,6 +1,7 @@ using CommunityToolkit.HighPerformance; using Source.Common.Bitmap; +using Source.Common.Mathematics; using System.Runtime.CompilerServices; @@ -16,10 +17,6 @@ public enum PixelWriterUsing : byte public static partial class FloatHelpers { - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_value")] - static extern ref ushort getBits(ref Half half); - public static ushort GetBits(this ref Half half) => getBits(ref half); - public static uint FloatBits(this ref readonly float r) => new ReadOnlySpan(in r).Cast()[0]; } @@ -266,17 +263,17 @@ public static void WritePixelF(ref PixelWriterState State, Span Base, floa public static void WritePixelNoAdvanceF(ref PixelWriterState State, Span Base, float r, float g, float b, float a) { Assert(IsUsingFloatFormat(ref State)); if ((State.Flags & PixelWriterUsing.Float16) != 0) { - Span fp16 = stackalloc Half[4]; - fp16[0] = (Half)r; - fp16[1] = (Half)g; - fp16[2] = (Half)b; - fp16[3] = (Half)a; + Span fp16 = stackalloc ushort[4]; + fp16[0] = Float16.ConvertFloatTo16bits(r); + fp16[1] = Float16.ConvertFloatTo16bits(g); + fp16[2] = Float16.ConvertFloatTo16bits(b); + fp16[3] = Float16.ConvertFloatTo16bits(a); Span buf = stackalloc ushort[4]; - buf[State.RShift >> 4] |= (ushort)((fp16[0].GetBits() & State.RMask) << (State.RShift & 0xF)); - buf[State.GShift >> 4] |= (ushort)((fp16[1].GetBits() & State.GMask) << (State.GShift & 0xF)); - buf[State.BShift >> 4] |= (ushort)((fp16[2].GetBits() & State.BMask) << (State.BShift & 0xF)); - buf[State.AShift >> 4] |= (ushort)((fp16[3].GetBits() & State.AMask) << (State.AShift & 0xF)); - memcpy(Base[..State.Size], buf[..State.Size].Cast()); + buf[State.RShift >> 4] |= (ushort)((fp16[0] & State.RMask) << (State.RShift & 0xF)); + buf[State.GShift >> 4] |= (ushort)((fp16[1] & State.GMask) << (State.GShift & 0xF)); + buf[State.BShift >> 4] |= (ushort)((fp16[2] & State.BMask) << (State.BShift & 0xF)); + buf[State.AShift >> 4] |= (ushort)((fp16[3] & State.AMask) << (State.AShift & 0xF)); + memcpy(Base.Slice(State.Bits, State.Size), buf.Cast()[..State.Size]); } else { Span buf = stackalloc uint[4]; @@ -284,7 +281,7 @@ public static void WritePixelNoAdvanceF(ref PixelWriterState State, Span B buf[State.GShift >> 5] |= (g.FloatBits() & State.GMask) << (State.GShift & 0x1F); buf[State.BShift >> 5] |= (b.FloatBits() & State.BMask) << (State.BShift & 0x1F); buf[State.AShift >> 5] |= (a.FloatBits() & State.AMask) << (State.AShift & 0x1F); - memcpy(Base[..State.Size], buf[..State.Size].Cast()); + memcpy(Base.Slice(State.Bits, State.Size), buf.Cast()[..State.Size]); } } diff --git a/Source.Common/Mathematics/CompressedVector.cs b/Source.Common/Mathematics/CompressedVector.cs index 20298a1b3..2e2723e83 100644 --- a/Source.Common/Mathematics/CompressedVector.cs +++ b/Source.Common/Mathematics/CompressedVector.cs @@ -4,6 +4,45 @@ public static class Float16 { public const float maxfloat16bits = 65504.0f; + public static ushort ConvertFloatTo16bits(float input) { + if (input > maxfloat16bits) + input = maxfloat16bits; + else if (input < -maxfloat16bits) + input = -maxfloat16bits; + + uint bits = BitConverter.SingleToUInt32Bits(input); + uint inMantissa = bits & 0x7FFFFF; + uint inBiasedExponent = (bits >> 23) & 0xFF; + uint sign = bits >> 31; + + uint mantissa = 0; + uint biased_exponent = 0; + + if (inBiasedExponent == 0xFF && inMantissa == 0) { + mantissa = 0x3FF; + biased_exponent = 0x1E; + } + else if (inBiasedExponent != 0 && inBiasedExponent != 0xFF) { + int new_exp = (int)inBiasedExponent - 127; + + if (new_exp < -14) { + uint exp_val = (uint)(-14 - new_exp); + if (exp_val > 0 && exp_val < 11) + mantissa = (1u << (int)(10 - exp_val)) + (inMantissa >> (int)(13 + exp_val)); + } + else if (new_exp > 15) { + mantissa = 0x3FF; + biased_exponent = 0x1E; + } + else { + biased_exponent = (uint)(new_exp + 15); + mantissa = inMantissa >> 13; + } + } + + return (ushort)((mantissa & 0x3FF) | ((biased_exponent & 0x1F) << 10) | (sign << 15)); + } + public static float Convert16bitFloatTo32bits(ushort input) { int sign = input >> 15; int mantissa = input & 1023; diff --git a/Source.Common/VTF.cs b/Source.Common/VTF.cs index e9737b7c3..53b74b069 100644 --- a/Source.Common/VTF.cs +++ b/Source.Common/VTF.cs @@ -87,6 +87,37 @@ public enum LookDir NegZ } +[Flags] +public enum VtfProcessingFlags : uint +{ + DecayR = 0x00000001, + DecayG = 0x00000002, + DecayB = 0x00000004, + DecayA = 0x00000008, + + DecayExpR = 0x00000010, + DecayExpG = 0x00000020, + DecayExpB = 0x00000040, + DecayExpA = 0x00000080, + + NoCompress = 0x00000100, + NormalDuDv = 0x00000200, + FilterNice = 0x00000400, + + SetAlphaOneOverMip = 0x00001000, + PremultColorOneOverMip = 0x00002000, + MipAlphaTest = 0x00004000 +} + +public struct VtfProcessingOptions +{ + public uint Size; + public VtfProcessingFlags Flags0; + public InlineArray4 DecayGoal; + public InlineArray4 NumNotDecayMips; + public InlineArray4 DecayExponentBase; +} + public interface IVTFTexture : IDisposable { bool Init(int width, int height, int depth, ImageFormat format, int flags, int frameCount, int forceMipCount = -1); @@ -150,13 +181,20 @@ bool Serialize(IFileHandle? handle) Span LowResImageData(); void ConvertImageFormat(ImageFormat format, bool normalToDUDV); + void GenerateSpheremap(LookDir lookDir = LookDir.Z); + void FixCubemapFaceOrientation(); void GenerateMipmaps(); + void PutOneOverMipLevelInAlpha(); void ComputeReflectivity(); void ComputeAlphaFlags(); void ConstructLowResImage(); + void PostProcess(bool generateSpheremap, LookDir lookDir = LookDir.Z, bool allowFixCubemapOrientation = true); + void SetAlphaTestThreshholds(float baseThreshhold, float highFreq); + void SetPostProcessingSettings(in VtfProcessingOptions options); public const int VTF_MAJOR_VERSION = 7; + public const ImageFormat IMAGE_FORMAT_DEFAULT = (ImageFormat)(-2); public const int VTF_MINOR_VERSION = 4; // Implementation of VTF can add these factory methods. diff --git a/Source.MaterialSystem/Texture.cs b/Source.MaterialSystem/Texture.cs index 1e566536d..3a5ee5244 100644 --- a/Source.MaterialSystem/Texture.cs +++ b/Source.MaterialSystem/Texture.cs @@ -783,12 +783,7 @@ private bool ConvertToActualFormat(IVTFTexture vtfTexture) { private ImageFormat ComputeActualFormat(ImageFormat srcFormat) { ImageFormat dstFormat; bool bIsCompressed = srcFormat.IsCompressed(); - if (materials.HardwareConfig.SupportsCompressedTextures() && bIsCompressed) { - // for the runtime compressed formats the srcFormat won't equal the dstFormat, and we need to return srcFormat here - if (srcFormat.IsRuntimeCompressed()) { - return srcFormat; - } - + if (materials.Config.CompressedTextures && materials.HardwareConfig.SupportsCompressedTextures() && bIsCompressed) { // don't do anything since we are already in a compressed format. dstFormat = materials.ShaderAPI.GetNearestSupportedFormat(srcFormat); Assert(dstFormat == srcFormat); diff --git a/Source.VTF/VTFTexture.cs b/Source.VTF/VTFTexture.cs index 8ce31ef08..f87cfc9f2 100644 --- a/Source.VTF/VTFTexture.cs +++ b/Source.VTF/VTFTexture.cs @@ -1,6 +1,7 @@ using Source.Bitmap; using Source.Common; using Source.Common.Bitmap; +using Source.Common.Mathematics; using System.Buffers; using System.Diagnostics; @@ -17,7 +18,7 @@ public sealed class VTFTexture : IVTFTexture readonly int[] Version = new int[2]; int Width; int Height; - int Depth; + int Depth = 1; ImageFormat Format; int MipCount; @@ -27,8 +28,8 @@ public sealed class VTFTexture : IVTFTexture int Flags; byte[]? ImageData; - Vector3 Reflectivity; - float BumpScale; + Vector3 Reflectivity = new(1.0f, 1.0f, 1.0f); + float BumpScale = 1.0f; int StartFrame; @@ -37,8 +38,10 @@ public sealed class VTFTexture : IVTFTexture int LowResImageHeight; byte[]? LowResImageData; - float AlphaThreshold; - float AlphaHiFreqThreshold; + float AlphaThreshold = -1.0f; + float AlphaHiFreqThreshold = -1.0f; + + VtfProcessingOptions Options = new() { Size = (uint)Unsafe.SizeOf() }; int FinestMipmapLevel; int CoarsestMipmapLevel; @@ -48,7 +51,52 @@ public sealed class VTFTexture : IVTFTexture float IVTFTexture.BumpScale() => BumpScale; public void ComputeAlphaFlags() { - throw new NotImplementedException(); + if (Format != ImageFormat.RGBA8888) { + Flags &= ~(int)(TextureFlags.EightBitAlpha | TextureFlags.OneBitAlpha); + Options.Flags0 &= ~VtfProcessingFlags.MipAlphaTest; + return; + } + + Flags &= ~(int)(TextureFlags.EightBitAlpha | TextureFlags.OneBitAlpha); + + if ((Options.Flags0 & VtfProcessingFlags.SetAlphaOneOverMip) != 0) { + Flags |= (int)TextureFlags.EightBitAlpha; + return; + } + + for (int frame = 0; frame < FrameCount; ++frame) { + for (int face = 0; face < FaceCount; ++face) { + for (int mipLevel = 0; mipLevel < MipCount; ++mipLevel) { + bool hasZero = false; + bool has255 = false; + + Span srcBits = GetImageData(frame, face, mipLevel); + + ComputeMipLevelDimensions(mipLevel, out int mipWidth, out int mipHeight, out int mipDepth); + int numPixels = mipWidth * mipHeight * mipDepth; + + int src = 0; + while (--numPixels >= 0) { + if (srcBits[src + 3] == 0) { + hasZero = true; + } + else if (srcBits[src + 3] == 255) { + has255 = true; + } + else { + Flags &= ~(int)TextureFlags.OneBitAlpha; + Flags |= (int)TextureFlags.EightBitAlpha; + return; + } + + src += 4; + } + + if (hasZero && has255) + Flags |= (int)TextureFlags.OneBitAlpha; + } + } + } } public int ComputeFaceSize(int startingMipLevel = 0) { @@ -121,7 +169,32 @@ public int ComputeMipSize(int mipLevel, ImageFormat format) { } public void ComputeReflectivity() { - throw new NotImplementedException(); + if (Format != ImageFormat.RGBA8888) { + Reflectivity = new(0.2f, 0.2f, 0.2f); + return; + } + + int divisor = 0; + Reflectivity = new(0.0f, 0.0f, 0.0f); + for (int frame = 0; frame < FrameCount; ++frame) { + for (int face = 0; face < FaceCount; ++face) { + Vector3 faceReflect = default; + Span src = GetImageData(frame, face, 0); + int numPixels = Width * Height * Depth; + + for (int i = 0, p = 0; i < numPixels; ++i, p += 4) { + faceReflect.X += MathLib.TextureToLinear(src[p + 0]); + faceReflect.Y += MathLib.TextureToLinear(src[p + 1]); + faceReflect.Z += MathLib.TextureToLinear(src[p + 2]); + } + + faceReflect *= 1.0f / (float)numPixels; + + Reflectivity += faceReflect; + ++divisor; + } + } + Reflectivity *= 1.0f / (float)divisor; } public int ComputeTotalSize() { @@ -141,6 +214,17 @@ public void ConvertImageFormat(ImageFormat fmt, bool normalToDUDV) { if (ImageData == null) return; + if (fmt == IVTFTexture.IMAGE_FORMAT_DEFAULT) + fmt = ImageFormat.RGBA8888; + + if (normalToDUDV && !(fmt == ImageFormat.UV88 || fmt == ImageFormat.UVWQ8888 || fmt == ImageFormat.UVLX8888)) { + Assert(false); + return; + } + + if (Format == fmt) + return; + nint convertedSize = ComputeTotalSize(fmt); byte[] convertedImage = ArrayPool.Shared.Rent((int)convertedSize); @@ -154,8 +238,17 @@ public void ConvertImageFormat(ImageFormat fmt, bool normalToDUDV) { Span dstData = convertedImage.AsSpan()[(int)GetImageOffset(frame, face, mip, fmt)..]; for (int z = 0; z < depth; ++z, srcData = srcData[(int)srcFaceStride..], dstData = dstData[(int)dstFaceStride..]) { if (normalToDUDV) { - Error("No\n"); - return; + if (fmt == ImageFormat.UV88) + ImageLoader.ConvertNormalMapRGBA8888ToDUDVMapUV88(srcData, width, height, dstData); + else if (fmt == ImageFormat.UVWQ8888) + ImageLoader.ConvertNormalMapRGBA8888ToDUDVMapUVWQ8888(srcData, width, height, dstData); + else if (fmt == ImageFormat.UVLX8888) + ImageLoader.ConvertNormalMapRGBA8888ToDUDVMapUVLX8888(srcData, width, height, dstData); + else { + Assert(false); + ArrayPool.Shared.Return(convertedImage, true); + return; + } } else { ImageLoader.ConvertImageFormat(srcData, Format, dstData, fmt, width, height); @@ -165,6 +258,11 @@ public void ConvertImageFormat(ImageFormat fmt, bool normalToDUDV) { } } + if (!AllocateImageData(convertedSize)) { + ArrayPool.Shared.Return(convertedImage, true); + return; + } + memcpy(ImageData, convertedImage[..(int)convertedSize]); Format = fmt; @@ -183,7 +281,7 @@ public void ConvertImageFormat(ImageFormat fmt, bool normalToDUDV) { } } else { - if ((fmt == ImageFormat.DXT5) || (fmt == ImageFormat.ATI2N) || (fmt == ImageFormat.ATI1N)) { + if ((fmt == ImageFormat.DXT1) || (fmt == ImageFormat.ATI2N) || (fmt == ImageFormat.ATI1N)) { Flags &= ~(int)(TextureFlags.OneBitAlpha | TextureFlags.EightBitAlpha); } } @@ -221,10 +319,194 @@ public int FileSize(int mipSkipCount = 0) { int IVTFTexture.FrameCount() => FrameCount; - public void GenerateMipmaps() { + public void GenerateSpheremap(LookDir lookDir = LookDir.Z) { + throw new NotImplementedException(); + } + + public void FixCubemapFaceOrientation() { throw new NotImplementedException(); } + public void NormalizeTopMipLevel() { + if (!IsNormalMap()) + return; + + int srcMipLevel = 0; + ComputeMipLevelDimensions(srcMipLevel, out int srcWidth, out int srcHeight, out int srcDepth); + for (int frame = 0; frame < FrameCount; ++frame) { + for (int face = 0; face < FaceCount; ++face) { + Span srcLevel = GetImageData(frame, face, srcMipLevel); + ImageLoader.NormalizeNormalMapRGBA8888(srcLevel, srcWidth * srcHeight * srcDepth); + } + } + } + + public void GenerateMipmaps() { + ResampleInfo info = new(); + info.SrcWidth = Width; + info.SrcHeight = Height; + info.SrcDepth = Depth; + info.SrcGamma = 2.2f; + info.DestGamma = 2.2f; + info.DestDepth = 1; + + bool normalMap = (Flags & (int)TextureFlags.Normal) != 0 || (Options.Flags0 & VtfProcessingFlags.NormalDuDv) != 0; + bool alphaTest = (Options.Flags0 & VtfProcessingFlags.MipAlphaTest) != 0; + if (alphaTest) { + info.Flags |= ResampleFlags.AlphaTest; + if (AlphaThreshold >= 0) + info.AlphaThreshhold = AlphaThreshold; + if (AlphaHiFreqThreshold >= 0) + info.AlphaHiFreqThreshhold = AlphaHiFreqThreshold; + } + + if ((Options.Flags0 & VtfProcessingFlags.FilterNice) != 0) + info.Flags |= ResampleFlags.NiceFilter; + + if ((Flags & (int)TextureFlags.ClampS) != 0) + info.Flags |= ResampleFlags.ClampS; + if ((Flags & (int)TextureFlags.ClampT) != 0) + info.Flags |= ResampleFlags.ClampT; + if ((Flags & (int)TextureFlags.ClampU) != 0) + info.Flags |= ResampleFlags.ClampU; + + int numMipsClampedLod = 0; + Span lodInfo = GetResourceData(ResourceEntryType.TextureLOD); + if (!lodInfo.IsEmpty) { + int clampX = 1 << Math.Min(lodInfo[0], lodInfo[2]); +#if GMOD_DLL + int clampY = 1 << Math.Min(lodInfo[0], lodInfo[2]); +#else + int clampY = 1 << Math.Min(lodInfo[1], lodInfo[3]); +#endif + + while (clampX < Width || clampY < Height) { + ++numMipsClampedLod; + clampX <<= 1; + clampY <<= 1; + } + } + + Span channelNames = ['R', 'G', 'B', 'A']; + for (int mipLevel = 1; mipLevel < MipCount; ++mipLevel) { + ComputeMipLevelDimensions(mipLevel, out info.DestWidth, out info.DestHeight, out info.DestDepth); + + if ((Options.Flags0 & VtfProcessingFlags.PremultColorOneOverMip) != 0) + info.ColorScale[0] = info.ColorScale[1] = info.ColorScale[2] = 1.0f / (float)(1 << mipLevel); + + bool blending = false; + for (int ch = 0; ch < 4; ++ch) { + int lastNonDecayMip = numMipsClampedLod + Options.NumNotDecayMips[ch]; + if (lastNonDecayMip > MipCount) + lastNonDecayMip = MipCount - 1; + + int numDecayMips = MipCount - lastNonDecayMip - 1; + if (numDecayMips < 1) + numDecayMips = 1; + + if ((mipLevel == MipCount - 1 || mipLevel > lastNonDecayMip) && ((uint)Options.Flags0 & ((uint)VtfProcessingFlags.DecayR << ch)) != 0) { + info.ColorGoal[ch] = Options.DecayGoal[ch]; + + if (mipLevel == MipCount - 1) { + info.ColorScale[ch] = 0.0f; + } + else if (((uint)Options.Flags0 & ((uint)VtfProcessingFlags.DecayExpR << ch)) != 0) { +#if GMOD_DLL + info.ColorScale[ch] = (float)Math.Pow((double)Options.DecayExponentBase[ch], (double)(mipLevel - lastNonDecayMip)); +#else + info.ColorScale[ch] = MathF.Pow(Options.DecayExponentBase[ch], (float)(mipLevel - lastNonDecayMip)); +#endif + } + else { + info.ColorScale[ch] = 1.0f - (float)(mipLevel - lastNonDecayMip) / (float)numDecayMips; + } + + if (!blending) { + blending = true; + Msg($"Blending mip{mipLevel} {info.DestWidth}x{info.DestHeight} to"); + } + + Msg($" {channelNames[ch]}={Options.DecayGoal[ch]} ~{(int)((1.0f - info.ColorScale[ch]) * 100.0f + 0.5f)}%"); + } + } + if (blending) + Msg("\n"); + + if (normalMap) { + info.Flags |= ResampleFlags.NormalMap; + info.ColorGoal[0] = info.ColorGoal[1] = info.ColorGoal[2] = 127.0f; + } + + for (int frame = 0; frame < FrameCount; ++frame) { + for (int face = 0; face < FaceCount; ++face) { + int srcMipLevel = Math.Max(0, mipLevel - 4); + info.Src = GetImageData(frame, face, srcMipLevel); + info.Dest = GetImageData(frame, face, mipLevel); + ComputeMipLevelDimensions(srcMipLevel, out info.SrcWidth, out info.SrcHeight, out info.SrcDepth); + + if (Format == ImageFormat.RGB323232F) + ImageLoader.ResampleRGB323232F(info); + else + ImageLoader.ResampleRGBA8888(info); + + if (IsNormalMap()) + ImageLoader.NormalizeNormalMapRGBA8888(info.Dest, info.DestWidth * info.DestHeight * info.DestDepth); + } + } + } + } + + public void PutOneOverMipLevelInAlpha() { + Assert(Format == ImageFormat.RGBA8888); + + for (int mipLevel = 0; mipLevel < MipCount; ++mipLevel) { + ComputeMipLevelDimensions(mipLevel, out int mipWidth, out int mipHeight, out int mipDepth); + int size = mipWidth * mipHeight * mipDepth; + byte ooMipLevel = (byte)(255.0f * (1.0f / (float)(1 << mipLevel))); + + for (int frame = 0; frame < FrameCount; ++frame) { + for (int face = 0; face < FaceCount; ++face) { + Span dstLevel = GetImageData(frame, face, mipLevel); + for (int dst = 0; dst < size * 4; dst += 4) + dstLevel[dst + 3] = ooMipLevel; + } + } + } + } + + public void PostProcess(bool generateSpheremap, LookDir lookDir = LookDir.Z, bool allowFixCubemapOrientation = true) { + if (IsCubeMap()) { + if (allowFixCubemapOrientation) + FixCubemapFaceOrientation(); + + if (generateSpheremap) + GenerateSpheremap(lookDir); + } + + NormalizeTopMipLevel(); + + GenerateMipmaps(); + + if ((Options.Flags0 & VtfProcessingFlags.SetAlphaOneOverMip) != 0) + PutOneOverMipLevelInAlpha(); + + ComputeReflectivity(); + + ComputeAlphaFlags(); + } + + public void SetAlphaTestThreshholds(float baseThreshhold, float highFreq) { + AlphaThreshold = baseThreshhold; + AlphaHiFreqThreshold = highFreq; + } + + public void SetPostProcessingSettings(in VtfProcessingOptions options) { + Options = default; + uint size = Math.Min((uint)Unsafe.SizeOf(), options.Size); + Unsafe.CopyBlockUnaligned(ref Unsafe.As(ref Options), ref Unsafe.As(ref Unsafe.AsRef(in options)), size); + Options.Size = (uint)Unsafe.SizeOf(); + } + public Span GetResourceData(ResourceEntryType type) => ResourcesData.TryGetValue(type & ~ResourceEntryType.Flag_Mask, out byte[]? data) ? data : default; @@ -684,7 +966,7 @@ private bool AllocateImageData(nint imageSize) { } private static bool GenericAllocateReusableData(ref byte[]? imageData, nint numRequested) { - if (imageData == null || imageData.Length < numRequested) + if (imageData == null || imageData.Length < numRequested || (numRequested > 0 && imageData.Length > 16 * numRequested)) imageData = new byte[numRequested]; return true; }