Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
2022-09-04 13:23:45 +02:00

73 lines
2.2 KiB
C#

using System.IO;
using StbiSharp;
using static OpenGL.GL;
namespace OpenGLTutorial.Rendering.Display {
public class Texture {
public static Texture Empty => new(null);
public int Width { get; private set; }
public int Height { get; private set; }
private uint Address { get; set; }
private string Path { get; }
private bool _loaded = false;
public Texture(string path) {
Path = path;
}
public unsafe void Load() {
if (_loaded) return;
_loaded = true;
Address = glGenTexture();
glBindTexture(GL_TEXTURE_2D, Address);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
if (string.IsNullOrEmpty(Path)) {
LoadEmpty();
return;
}
using var stream = File.OpenRead(Path);
using var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
StbiImage image = Stbi.LoadFromMemory(memoryStream, 0);
int format = image.NumChannels == 3 ? GL_RGB : GL_RGBA;
fixed(byte* data = &image.Data[0])
glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, data);
Width = image.Width;
Height = image.Height;
glBindTexture(GL_TEXTURE_2D, 0);
}
private unsafe void LoadEmpty() {
byte[] pixels = {255, 255, 255, 255};
fixed (byte* data = &pixels[0]) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
}
Width = 1;
Height = 1;
glBindTexture(GL_TEXTURE_2D, 0);
}
public void Use() {
glBindTexture(GL_TEXTURE_2D, Address);
}
public void Delete() {
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTexture(Address);
}
}
}