SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
5 changed files with 768360 additions and 0 deletions

View file

@ -0,0 +1,113 @@
using Brutal.KtxApi;
namespace Brutal.TextureApi.Ktx;
/// <summary>
/// Static class that provides conversion functions from other formats to a KtxTexture.
/// </summary>
public static partial class Converter
{
/// <summary>
/// Takes any ITexture and creates a KTX version 2 ITexture from it. The original
/// texture is kept as is and it is up to the caller to unload it if it is no longer
/// used.
/// </summary>
/// <param name="texture">The ITexture to use as the source</param>
/// <returns>The KTX Version 2 texture created from the source texture</returns>
public static KtxTexture ToV2KtxTexture(ITexture texture)
{
var saveData = new TextureDescriptor
{
Data = texture.Data,
Extent = texture.Extent,
Format = texture.Format,
LayerCount = texture.LayerCount,
FaceCount = texture.FaceCount,
MipmapCount = texture.LevelCount,
IsCubemap = texture.IsCubemap,
};
return new KtxTexture(ToKtxTexture2Handle(saveData));
}
/// <summary>
/// Creates a KTX version 2 texture handle from a TextureSaveInfo structure.
/// It is your responsibility to free the texture handle.
/// </summary>
/// <param name="descriptor">The structure describing the texture to build</param>
/// <returns>KtxTexture2Handle of the created texture</returns>
/// <exception cref="KtxTextureException">Thrown if the texture could not be created, or
/// the new texture data size is different to the source data size</exception>
internal static unsafe KtxTexture2Handle ToKtxTexture2Handle(TextureDescriptor descriptor)
{
ValidateSaveInfo(descriptor);
var createInfo = new KtxTextureCreateInfo()
{
BaseWidth = (uint)descriptor.Extent.X,
BaseHeight = (uint)descriptor.Extent.Y,
BaseDepth = (uint)descriptor.Extent.Z,
GenerateMipmaps = false,
NumLevels = (uint)descriptor.MipmapCount,
NumLayers = (uint)descriptor.LayerCount,
NumDimensions = CalculateDimensions(descriptor),
NumFaces = (uint)descriptor.FaceCount,
IsArray =
descriptor.Extent.X > 0
&& descriptor.LayerCount > 1
&& (descriptor.FaceCount == 1 || descriptor.IsCubemap),
PDfd = null,
VkFormat = (uint)descriptor.Format,
GlInternalformat = 0, // Ignored
};
var createResult = KtxTexture2.Create(
ref createInfo,
KtxTextureCreateStorageEnum.TextureCreateAllocStorage,
out var texture2Handle
);
if (createResult != KtxErrorCode.Success)
throw new KtxTextureException(
$"Failed to create texture to save. KtxErrorCode:{createResult}",
createResult
);
if (descriptor.Data.Length != (int)texture2Handle.GetDataSize())
throw new KtxTextureException(
$"Size mismatch. Brutal.Ktx allocated {texture2Handle.GetDataSize()} bytes but the save data had {descriptor.Data.Length}"
);
descriptor.Data.CopyTo(new Span<byte>(texture2Handle.GetData(), (int)texture2Handle.GetDataSize()));
return texture2Handle;
}
private static void ValidateSaveInfo(TextureDescriptor descriptor)
{
if (descriptor.Extent.X == 0)
throw new KtxTextureException("Texture width cannot be 0");
if (descriptor.FaceCount == 6 && (descriptor.Extent.Y != descriptor.Extent.X || descriptor.Extent.Z != 1))
throw new KtxTextureException(
"Cubemap textures must have 6 faces, have the same width and height, and have a depth of 1"
);
}
private static uint CalculateDimensions(TextureDescriptor descriptor)
{
if (descriptor.IsCubemap)
return 2;
var saveDataExtent = descriptor.Extent;
// A depth of 1 is a 2D texture, not a 3D one. Only Z > 1 denotes a true 3D (volume) texture.
if (saveDataExtent is { X: > 0, Y: > 0, Z: > 1 })
return 3;
if (saveDataExtent is { X: > 0, Y: > 0, Z: 1 })
return 2;
if (saveDataExtent is { X: > 0, Y: 1, Z: 1 })
return 1;
throw new KtxTextureException(
$"Invalid extent for dimension calculation. extent: {saveDataExtent.X}, {saveDataExtent.Y}, {saveDataExtent.Z}"
);
}
}

View file

@ -0,0 +1,196 @@
using System.Text;
using Brutal.KtxApi;
using Brutal.KtxApi.Abstractions;
namespace Brutal.TextureApi.Ktx;
/*
* If facecount == 6 (IsCubemap == true) then width and height must be the same and depth must be 0
* pixelHeight must not be 0 for block-compressed formats, including BasisLZ/ETC1S and UASTC.
* pixelDepth must not be 0 for block formats that have block depth > 1
* pixelDepth must be 0 for depth or stencil formats.
*
* layercount is number of array elements. If not an array then layercount must be 0.
*
* faceCount specifies the number of cubemap faces.
* For cubemaps and cubemap arrays this must be 6. For non cubemaps this must be 1.
* Cubemap faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z in a left-handed coordinate system with
* +Y up and, with the +Z face forward, +X on the on the right.
* All faces must have the same orientation which must be rd (top-left origin) which is assumed in the absence of
* Section 5.2, “KTXorientation” metadata. See Appendix A, Cubemap Orientation for details.
* Applications wanting to store incomplete cubemaps should flatten faces into a 2D array and use the metadata described in
* Section 5.1, “KTXcubemapIncomplete” to signal which faces are present.
*
* Type pixelWidth pixelHeight pixelDepth layerCount faceCount
* 1D > 0 0 0 0 1
* 2D > 0 > 0 0 0 1
* 3D > 0 > 0 >0 0 1
* Cubemap > 0 > 0 0 0 6
* 1D Array > 0 0 0 >0 1
* 2d Array > 0 > 0 0 >0 1
* 3d Array > 0 > 0 >0 >0 1
* Cubemap Arr > 0 > 0 0 >0 6
*/
public class KtxTexture : ITexture
{
/// <summary>
/// Create a KtxTexture from an existing KtxTextureHandle.
/// </summary>
/// <remarks> The commonTextureHandle must not currently be supercompressed.</remarks>
/// <param name="commonTextureHandle">A native handle to a KTX V1 or V2 texture</param>
/// <exception cref="TextureException">Thrown if the texture referenced by commonTextureHandle is super compressed</exception>
public KtxTexture(KtxTextureHandle commonTextureHandle)
{
_commonTextureHandle = commonTextureHandle;
if (_commonTextureHandle.NeedsTranscoding())
throw new TextureException("Texture is supercompressed.");
}
#region ITexture Implementation
/// <inheritdoc cref="ITexture.Data"/>
public unsafe Span<byte> Data
{
get
{
EnsureLoaded();
return new Span<byte>(_commonTextureHandle.GetData(), (int)_commonTextureHandle.GetDataSize());
}
}
/// <inheritdoc cref="ITexture.Extent"/>
public TexelCount3 Extent =>
new(
(int)_commonTextureHandle.BaseWidth,
(int)_commonTextureHandle.BaseHeight,
(int)_commonTextureHandle.BaseDepth
);
/// <inheritdoc cref="ITexture.Format"/>
public TextureFormat Format => (TextureFormat)_commonTextureHandle.GetVkFormat();
/// <inheritdoc cref="ITexture.LayerCount"/>
public int LayerCount => (int)_commonTextureHandle.NumLayers;
/// <inheritdoc cref="ITexture.LevelCount"/>
public int LevelCount => (int)_commonTextureHandle.NumLevels;
/// <inheritdoc cref="ITexture.FaceCount"/>
public int FaceCount => (int)_commonTextureHandle.NumFaces;
/// <inheritdoc cref="ITexture.IsCubemap"/>
public bool IsCubemap => _commonTextureHandle.IsCubemap;
/// <inheritdoc cref="ITexture.IsArray"/>
public bool IsArray => _commonTextureHandle.IsArray;
/// <inheritdoc cref="ITexture.DimensionCount"/>
public int DimensionCount => (int)_commonTextureHandle.NumDimensions;
/// <inheritdoc cref="ITexture.RowPitch"/>
public unsafe ByteSize RowPitch(int level)
{
if (level < 0 || level >= LevelCount)
throw new ArgumentOutOfRangeException(nameof(level), level, $"Level must be in range [0, {LevelCount})");
_rowPitch ??= new ByteSize[LevelCount];
if (_rowPitch[level] != 0)
return _rowPitch[level];
if (_commonTextureHandle.ClassId == ClassId.Texture2C)
{
var formatSize = _commonTextureHandle.Protected->FormatSize;
var blocksWide = Math.Max(1, (_commonTextureHandle.BaseWidth / formatSize.BlockWidth) >> level);
_rowPitch[level] = ByteSize.Of(blocksWide * ((int)formatSize.BlockSizeInBits >> 3));
return _rowPitch[level];
}
_rowPitch[level] = (ByteSize)_commonTextureHandle.GetRowPitch((uint)level);
return _rowPitch[level];
}
/// <inheritdoc cref="ITexture.ImageData"/>
public Span<byte> ImageData(int level, int layer, int face)
{
EnsureLoaded();
var getResult = _commonTextureHandle.GetImageData((uint)level, (uint)layer, (uint)face, out var data);
if (getResult != KtxErrorCode.Success)
throw new TextureException(
$"Cannot get image data for KtxTexture. level:{level} layer:{layer} face:{face} error:{getResult}"
);
return data;
}
#endregion
/// <summary>
/// Returns a native handle to the KtxTexture
/// </summary>
/// <value></value>
public KtxTextureHandle UnderlyingKtxTextureHandle => _commonTextureHandle;
/// <summary>
/// Frees all resources held by the the KtxTexture. After calling Destroy() the
/// KtxTexture object is unusable.
/// </summary>
public void Destroy()
{
if (_commonTextureHandle.IsNotNull())
{
_commonTextureHandle.Destroy();
_commonTextureHandle = default;
}
}
/// <summary>
/// Saves a KtxTexture to a file on disk.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public KtxErrorCode SaveToFile(string filePath)
{
EnsureLoaded();
return _commonTextureHandle.WriteToNamedFile(Encoding.UTF8.GetBytes(filePath));
}
/// <summary>
/// Returns whether the row pitch for the texture has been padded to 4 bytes.
/// <remarks>
/// This is a special requirement for V1 Ktx files. The spec required the alignment of rows of uncompresed textures to 4 bytes.
/// This requirement was removed for V2 textures but we do need to know if packing is occurring for V1 if using OpenGl,
/// so we can set GL_UNPACK_ALIGNMENT.
/// If this function returns true, then set GL_UNPACK_ALIGNMENT to 4 before uploading the texture otherwise
/// set it to 1.</remarks>
/// </summary>
/// <param name="level">What level to check for padding</param>
/// <returns>True if row pitch was padded to 4 bytes, false if not.</returns>
/// <exception cref="TextureException">Thrown if the image is supercompressed</exception>
public bool IsRow4BytePadded(int level)
{
if (_commonTextureHandle.ClassId == ClassId.Texture2C)
return false;
// Catches compressed textures (All multiple of 4 in element size), and uncompressed with 4 byte elements
if (_commonTextureHandle.GetElementSize() % 4 == 0)
return false;
return _commonTextureHandle.GetRowPitch((uint)level)
!= _commonTextureHandle.GetElementSize() * (_commonTextureHandle.BaseWidth >> level);
}
#region Private
private unsafe void EnsureLoaded()
{
if (_commonTextureHandle.GetData() != null)
return;
var loadResult = _commonTextureHandle.LoadImageData(null);
if (loadResult != KtxErrorCode.Success)
throw new TextureException($"Cannot load image data for KtxTexture. KtxErrorCode:{loadResult}");
}
private KtxTextureHandle _commonTextureHandle;
private ByteSize[]? _rowPitch;
#endregion
}

View file

@ -0,0 +1,15 @@
using Brutal.KtxApi;
using Brutal.TextureApi;
namespace Brutal.TextureApi.Ktx;
public class KtxTextureException : TextureException
{
public KtxTextureException(string message, KtxErrorCode? errorCode = null)
: base(message)
{
ErrorCode = errorCode;
}
public KtxErrorCode? ErrorCode { get; }
}

View file

@ -0,0 +1,94 @@
using System.Collections.Frozen;
using System.Text;
using Brutal.KtxApi;
using Brutal.KtxApi.Abstractions;
namespace Brutal.TextureApi.Ktx;
public static partial class Loader
{
/// <summary>
/// Loads a ktx texture from a file.
/// </summary>
/// <param name="filePath">Path to file</param>
/// <param name="loadOptions">Options for the load</param>
/// <returns>Texture that was loaded</returns>
/// <exception cref="KtxTextureException">If the texture could not be loaded.
/// e.g The SuperCompressionFamily was not compatible with the texture's data,
/// The file could not be found etc.
/// </exception>
public static KtxTexture LoadFromFile(string filePath, LoadSettings? loadOptions = null)
{
var loadSettings = loadOptions ?? LoadSettings.Default;
var loadResult = KtxApi.KtxTexture.CreateFromNamedFile(
Encoding.UTF8.GetBytes(filePath),
LoadFlags(loadSettings),
out var textureHandle
);
if (loadResult != KtxErrorCode.Success)
{
textureHandle.Dispose();
throw new KtxTextureException(
$"Failed to load texture from filePath \"{filePath}\". error:{loadResult}",
loadResult
);
}
if (!textureHandle.NeedsTranscoding())
return new KtxTexture(textureHandle);
var result = Transcode(textureHandle, loadSettings.SuperCompressionTranscodeFormat);
if (result == KtxErrorCode.Success)
return new KtxTexture(textureHandle);
textureHandle.Dispose();
throw new KtxTextureException($"Failed to transcode supercompressed texture. KtxErrorCode:{result}");
}
public static KtxTexture LoadFromMemory(ReadOnlySpan<byte> data, LoadSettings? loadData = null)
{
var loadSettings = loadData ?? new LoadSettings();
var createResult = KtxTexture2.CreateFromMemory(data, LoadFlags(loadSettings), out var texture2Handle);
if (createResult != KtxErrorCode.Success)
throw new KtxTextureException("Failed to create texture from memory", createResult);
return new KtxTexture(texture2Handle);
}
public class LoadSettings : TextureLoadSettings
{
public static LoadSettings Default { get; } = new();
/// <summary>
/// If the texture is supercompressed, this indicates the format to transcode it to on load.
/// </summary>
/// <value>Defaults to KtxTranscodeFmt.Bc7Rgba</value>
public KtxTranscodeFmt SuperCompressionTranscodeFormat = KtxTranscodeFmt.Bc7Rgba;
/// <summary>
/// If true, does not immediately load the texture data.
/// Data is loaded when accessed.
/// This flag is ignored if the texture is super compressed and needs transcoding because transcoding
/// will happen when loading the file.
/// </summary>
public bool LazyLoad = false;
}
private static KtxTextureCreateFlagBits LoadFlags(LoadSettings loadSettings)
{
return loadSettings.LazyLoad ? KtxTextureCreateFlagBits.NoFlags : KtxTextureCreateFlagBits.LoadImageDataBit;
}
private static KtxErrorCode Transcode(KtxTextureHandle textureHandle, KtxTranscodeFmt transcodeFormat)
{
var ktxTexture2Handle = textureHandle.AsKtxTexture2Handle();
var result = ktxTexture2Handle.TranscodeBasis(transcodeFormat, KtxTranscodeFlagBits.HighQuality);
return result;
}
public static FrozenSet<string> SupportedExtensions { get; } =
FrozenSet.Create(StringComparer.OrdinalIgnoreCase, [".ktx", ".ktx2"]);
}

View file

@ -0,0 +1,34 @@
using Brutal.KtxApi;
namespace Brutal.TextureApi.Ktx;
public static partial class Writer
{
/// <summary>
/// Writes an ITexture
/// </summary>
/// <param name="texture"></param>
/// <param name="filePath"></param>
/// <exception cref="KtxTextureException"></exception>
public static void SaveToFile(ITexture texture, string filePath)
{
var ktxTexture = texture as KtxTexture ?? Converter.ToV2KtxTexture(texture);
try
{
var saveResult = ktxTexture.SaveToFile(filePath);
if (saveResult != KtxErrorCode.Success)
throw new KtxTextureException($"Failed to save texture KtxErrorCode:{saveResult}", saveResult);
}
finally
{
if (texture is not KtxTexture)
ktxTexture.Destroy();
}
}
public static void SaveToFile(TextureDescriptor descriptor, string filePath)
{
var texture2Handle = Converter.ToKtxTexture2Handle(descriptor);
SaveToFile(new KtxTexture(texture2Handle), filePath);
}
}