39 lines
1.5 KiB
C#

using System;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SlatedGameToolkit.Framework.Exceptions;
using SlatedGameToolkit.Framework.Graphics.OpenGL;
using SlatedGameToolkit.Framework.Graphics.Textures;
namespace SlatedGameToolkit.Commons.Loaders
{
public static class TextureLoader
{
/// <summary>
/// Loads a texture using SDL2's image library.
/// Therefore, technically, this function should be able to laod any format SDL2 Image can load.
/// </summary>
/// <param name="path">The path of the texture to load.</param>
/// <param name="glContext">The OpenGL context the texture is to be associated with. May be null.</param>
/// <returns>An OpenGL Texture associated with the given context.</returns>
public static Texture LoadTexture(string path, GLContext glContext)
{
TextureData textureData;
using (Image<Rgba32> image = Image.Load<Rgba32>(path))
{
byte[] pixelData;
Span<Rgba32> pixelDataSpan;
if (image.TryGetSinglePixelSpan(out pixelDataSpan)) {
pixelData = MemoryMarshal.AsBytes(pixelDataSpan).ToArray();
} else {
throw new FrameworkUsageException("Image too large!");
}
textureData = new TextureData(image.Width, image.Height, pixelData);
}
return new Texture(textureData, glContext);
}
}
}