Engine_silk.NET/Nebulix/Rendering/Mesh.cs

69 lines
2.1 KiB
C#
Raw Normal View History

using Silk.NET.OpenGL;
namespace Nebulix.Rendering
{
public sealed class Mesh
{
public float[] Vertices { get => vertices; set { vertices = value; regenerate = true; } }
2024-01-02 14:17:50 +01:00
public nuint[] Indices { get => indices; set { indices = value; regenerate = true; } }
private uint vao = 0, vbo = 0, ebo = 0;
private bool regenerate = true;
private float[] vertices = [];
2024-01-02 14:17:50 +01:00
private nuint[] indices = [];
private float[] normals = [];
2024-01-02 14:17:50 +01:00
public void Clear()
{
vertices = [];
indices = [];
}
2024-01-02 14:17:50 +01:00
public void CalculateNormals()
{
throw new NotImplementedException();
}
// getting called by "Engine" which currently is in another assembly, meaning I probably need to make this public
// needs to be change for the real engine
public void Use(GL gl)
{
if (regenerate) Generate(gl);
gl.BindVertexArray(vao);
}
private unsafe void Generate(GL gl)
{
if(vao == 0)
vao = gl.CreateVertexArray();
if(vbo == 0)
vbo = gl.GenBuffer();
if(ebo == 0)
ebo = gl.GenBuffer();
gl.BindVertexArray(vao);
// TODO: meshData needs to also contain uv coords if I decide to add some
List<float> meshData = new(vertices.Length + normals.Length);
meshData.AddRange(vertices);
meshData.AddRange(normals);
ReadOnlySpan<float> data = new(meshData.ToArray());
gl.BindBuffer(BufferTargetARB.ArrayBuffer, vbo);
gl.BufferData(BufferTargetARB.ArrayBuffer, (nuint)(data.Length * sizeof(float)), data, BufferUsageARB.StaticDraw);
2024-01-02 14:17:50 +01:00
ReadOnlySpan<nuint> indicesData = new(indices);
gl.BindBuffer(BufferTargetARB.ElementArrayBuffer, ebo);
gl.BufferData(BufferTargetARB.ElementArrayBuffer, (nuint)(indicesData.Length * sizeof(uint)), indicesData, BufferUsageARB.StaticDraw);
// vertices
gl.EnableVertexAttribArray(0);
gl.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), (void*)0);
gl.EnableVertexAttribArray(1);
gl.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), (void*)(3 * sizeof(float)));
}
}
}