using Brutal.TextureApi;
namespace Brutal.GltfApi;
///
/// Interface for a glTF loader
///
public interface IGltfLoader
{
///
/// Gltf Json object
///
public Gltf GltfJson { get; }
///
/// Gets a span of bytes for a specific buffer view
///
/// Index of buffer view
/// Buffer view as byte span
public ReadOnlySpan GetBufferView(int bufferViewIndex);
}
///
/// Interface for a glTF loader that caches loaded data
///
public interface IGltfCachedLoader : IGltfLoader
{
///
/// Gets a cached buffer or loads it from the glTF file if not already loaded.
///
/// Index of buffer
/// Buffer's contents as byte span
public ReadOnlySpan GetOrLoadBuffer(int bufferIndex);
///
/// Gets a cached image or loads it from the glTF file if not already loaded.
///
/// Index of image
/// Optional texture load info
/// Image loaded as ITexture
public ITexture GetOrLoadImage(int imageIndex, TextureLoadSettings? loadInfo = null);
}
///
/// Helper class for loading glTF files
/// This class caches loaded glTF json and binary buffers
///
public class GltfLoader : IGltfCachedLoader, IDisposable
{
///
/// Source path of the glTF file, if loaded from a file
///
public string FilePath { get; set; } = string.Empty;
///
/// Optional function to resolve image data externally
/// This can be used to load images from a custom source, such as a network or
/// a custom image format.
/// If empty, the loader will attempt to load images as files relative to the glTF file path
///
public Func? ExternalResolveImage { get; set; }
///
/// Optional function to resolve binary buffer data externally
/// This can be used to load binary buffers from a custom source
/// If empty, the loader will attempt to load buffers as files relative to the glTF file path
/// This is useful for cases where the glTF file references external binary buffers.
///
public Func? ExternalResolveBuffer { get; set; }
///
/// Parsed Gltf Json object
/// This contains all the metadata about the glTF file, such as meshes, materials,
/// textures, and animations.
///
public Gltf GltfJson { get; }
///
/// Array of loaded binary buffers, cached as byte arrays when needed
/// Each buffer corresponds to a buffer in the glTF file.
/// If a buffer is not loaded, it will be null in the array.
/// This is used to avoid reloading buffers multiple times during a load operation.
///
public byte[]?[] LoadedBuffers { get; }
///
/// Array of loaded images, cached as ITexture objects
/// Each image corresponds to a texture in the glTF file.
/// This is used to avoid reloading images multiple times during a load operation.
/// If an image is not loaded, it will be null in the array.
///
public ITexture?[] LoadedImages { get; }
///
/// Constructor for GltfLoader
/// Initializes the GltfJson object by loading the glTF file from the specified file path
/// and initializes the LoadedBuffers and LoadedImages arrays.
///
/// Path to glTF file
public GltfLoader(string filePath)
{
GltfJson = GltfUtility.LoadModel(filePath);
LoadedBuffers = new byte[GltfJson.Buffers?.Length ?? 0][];
LoadedImages = new ITexture[GltfJson.Images?.Length ?? 0];
FilePath = filePath;
}
///
public void Dispose()
{
for (var index = 0; index < LoadedImages.Length; index++)
{
var image = LoadedImages[index];
if (image is not null)
TextureApi.TextureLoader.Unload(image);
LoadedImages[index] = null;
}
}
///
/// Accesses cached loaded buffer or loads it from the glTF file if not already loaded.
///
/// Buffer index
/// Span of bytes encompassing entire buffer
///
///
public ReadOnlySpan GetOrLoadBuffer(int bufferIndex)
{
if (bufferIndex < 0 || bufferIndex >= LoadedBuffers.Length)
throw new IndexOutOfRangeException($"Buffer index {bufferIndex} is out of range.");
var buffer = LoadedBuffers[bufferIndex];
if (buffer == null)
{
// Load the buffer from the glTF file
if (ExternalResolveBuffer is null)
buffer = GltfJson.LoadBinaryBuffer(bufferIndex, FilePath);
else
buffer = GltfJson.LoadBinaryBuffer(bufferIndex, ExternalResolveBuffer);
// Cache the loaded buffer
LoadedBuffers[bufferIndex] =
buffer ?? throw new InvalidOperationException($"Failed to load buffer at index {bufferIndex}.");
}
return new ReadOnlySpan(buffer);
}
///
/// Accesses a span of buffer memory for a specific buffer view.
/// This method retrieves the buffer view from the glTF JSON and returns a span of bytes
/// Buffers are loaded on demand and cached for future access.
///
/// Index of buffer view
/// Span of bytes matching buffer view
///
public ReadOnlySpan GetBufferView(int bufferViewIndex)
{
if (bufferViewIndex < 0 || bufferViewIndex >= GltfJson.BufferViews.Length)
throw new IndexOutOfRangeException($"Buffer view index {bufferViewIndex} is out of range.");
// Get the buffer view from the glTF JSON
var bufferIndex = GltfJson.BufferViews[bufferViewIndex].Buffer;
var bufferSpan = GetOrLoadBuffer(bufferIndex);
return bufferSpan.Slice(
GltfJson.BufferViews[bufferViewIndex].ByteOffset,
GltfJson.BufferViews[bufferViewIndex].ByteLength
);
}
///
/// Load image with different strategies based on how it is embedded in the glTF file.
///
///
///
///
///
protected ITexture LoadImage(int imageIndex, TextureLoadSettings? loadInfo)
{
var image = GltfJson.Images[imageIndex];
// If texture embedded in buffer, extract it here
if (image.BufferView.HasValue)
{
var bufferViewSpan = GetBufferView(image.BufferView.Value);
if (image.MimeType is null)
throw new InvalidOperationException(
$"Image at index {imageIndex} is embedded in a buffer view but has no mime type."
);
return TextureLoader.LoadFromMemory(
bufferViewSpan,
image.MimeType switch
{
Image.MimeTypeJpeg => TextureLoader.FormatType.Jpg,
Image.MimeTypePng => TextureLoader.FormatType.Png,
_ => throw new NotSupportedException(
$"Image at index {imageIndex} has MIME type '{image.MimeType}', which this loader cannot decode."
),
},
loadInfo
);
}
// If texture embedded in URI, load it from the embedded data
if (image.IsEmbedded())
{
var embedded = image.OpenEmbeddedImage(out var extension);
if (string.IsNullOrEmpty(extension))
throw new InvalidOperationException($"Image at index {imageIndex} is embedded but has no extension.");
if (extension[0] != '.')
extension = "." + extension;
return TextureLoader.LoadFromMemory(embedded, TextureLoader.GetFormatType(extension), loadInfo);
}
if (string.IsNullOrEmpty(image.Uri))
throw new InvalidOperationException($"Image at index {imageIndex} has no URI or buffer view.");
// If image is not embedded, load it from file or external source
if (ExternalResolveImage is not null)
{
// Use external resolver if provided
var imageData = ExternalResolveImage(image.Uri);
if (imageData is not { Length: > 0 })
throw new InvalidOperationException(
$"Failed to resolve image at index {imageIndex} using external resolver."
);
return TextureLoader.LoadFromMemory(imageData, TextureLoader.GetFormatType(image.Uri), loadInfo);
}
return TextureLoader.LoadFromFile(
Path.Combine(Path.GetDirectoryName(FilePath) ?? string.Empty, image.Uri),
loadInfo
);
}
///
/// Gets an image by index: loads it if not already loaded.
/// This method retrieves an image from the cache or loads it from the glTF file if it has not been loaded yet.
/// The image is cached in the LoadedImages array to avoid reloading it multiple times.
///
/// Index of image
///
/// Image loaded as ITexture
///
public ITexture GetOrLoadImage(int imageIndex, TextureLoadSettings? loadInfo = null)
{
if (imageIndex < 0 || imageIndex >= LoadedImages.Length)
throw new IndexOutOfRangeException($"Image index {imageIndex} is out of range.");
var image = LoadedImages[imageIndex];
if (image is null)
{
image = LoadImage(imageIndex, loadInfo);
LoadedImages[imageIndex] = image;
}
return image;
}
///
/// Save GLTF data to a packed .GLB file
///
/// File path to save .glb
///
///
public void SaveAsGlb(string outputFilePath)
{
using var stream = File.Create(outputFilePath);
SaveAsGlb(stream);
}
///
/// Save as GLB file to an output stream
///
/// Stream to write .glb
public void SaveAsGlb(Stream outputStream)
{
// Deep copy so that PackBufferData's in-place remapping of BufferViews/Buffers/Images
// does not corrupt the cached GltfJson state for subsequent use of this loader.
var workingCopy = GltfUtility.DeserializeModelJson(GltfJson.SerializeModelJson());
// Ensure all buffers are loaded, then coerce byte[]?[] → byte[][] (all non-null after load)
for (int i = 0; i < LoadedBuffers.Length; i++)
GetOrLoadBuffer(i);
var buffers = Array.ConvertAll(LoadedBuffers, b => b!);
using var wb = new BinaryWriter(outputStream);
if (ExternalResolveImage is not null)
workingCopy.SaveBinaryModelPacked(wb, buffers, ExternalResolveImage);
else
workingCopy.SaveBinaryModelPacked(wb, buffers, FilePath);
}
}
///
/// Extension methods for IGltfLoader
///
public static partial class GltfLoaderExtensions
{
///
/// Gets a span of bytes for a specific glTF accessor.
/// This method retrieves the buffer view associated with the accessor and returns a span of bytes
/// corresponding to the accessor's data.
/// Note: Sparse accessors are not supported in this implementation.
///
/// Gltf loader
/// Accessor index
/// Span of bytes accessor want to access
///
public static ReadOnlySpan GetAccessorBufferSpan(this IGltfLoader loader, int accessorIndex)
{
var accessor = loader.GltfJson.Accessors[accessorIndex];
if (accessor.BufferView is null)
throw new Exception("No bufferview assigned to accessor! Sparse accessors not supported");
var bufferView = loader.GltfJson.BufferViews[accessor.BufferView.Value];
var bufferViewSpan = loader.GetBufferView(accessor.BufferView.Value);
var stride = bufferView.ByteStride ?? (int)accessor.ElementSize();
return bufferViewSpan.Slice(accessor.ByteOffset, accessor.Count * stride);
}
///
/// Saves gltf data as a .gltf file
///
/// Gltf loader
/// Target file
public static void SaveAsGltf(this IGltfLoader loader, string filePath) => loader.GltfJson.SaveModel(filePath);
///
/// Saves gltf data to stream
///
/// Gltf loader
/// Output stream
public static void SaveAsGltf(this IGltfLoader loader, Stream stream) => loader.GltfJson.SaveModel(stream);
}