Reworked the VBO

This commit is contained in:
Michel Fedde 2021-03-26 10:41:29 +01:00
parent 3bc90dd83b
commit ee732240f7
11 changed files with 174 additions and 253 deletions

View file

@ -163,7 +163,7 @@ namespace SM.Base
private static void GLDebugAction(DebugSource source, DebugType type, DebugSeverity severity, string msg) private static void GLDebugAction(DebugSource source, DebugType type, DebugSeverity severity, string msg)
{ {
if (type.HasFlag(DebugType.DebugTypeError)) throw new Exception("[GLError] " + msg); if (type.HasFlag(DebugType.DebugTypeError)) throw new Exception("[GLError] " + msg);
Write(type != DebugType.DontCare ? type.ToString().Substring(9) : "DontCare", ConsoleColor.Gray, msg); Write("GL"+ (type != DebugType.DontCare ? type.ToString().Substring(9) : "DontCare"), ConsoleColor.Gray, msg);
} }
[DebuggerStepThrough] [DebuggerStepThrough]

View file

@ -1,5 +1,7 @@
#region usings #region usings
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.OGL.Mesh; using SM.OGL.Mesh;
@ -21,19 +23,19 @@ namespace SM.Base.Objects
/// </param> /// </param>
public InstancedMesh(PrimitiveType type, string[] enabledAttibute) : base(type) public InstancedMesh(PrimitiveType type, string[] enabledAttibute) : base(type)
{ {
Attributes["vertex"] = Vertex = new VBO(); Attributes["vertex"] = Vertex = new VBO<Vector3>();
foreach (string attribute in enabledAttibute) foreach (string attribute in enabledAttibute)
switch (attribute) switch (attribute)
{ {
case "uv": case "uv":
Attributes["uv"] = UVs = new VBO(pointerSize: 2); Attributes["uv"] = UVs = new VBO<Vector2>();
break; break;
case "normals": case "normals":
Attributes["normal"] = Normals = new VBO(); Attributes["normal"] = Normals = new VBO<Vector3>();
break; break;
case "color": case "color":
Attributes["color"] = Color = new VBO(pointerSize: 4); Attributes["color"] = Color = new VBO<Color4>();
break; break;
} }
} }

View file

@ -1,5 +1,6 @@
#region usings #region usings
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.OGL.Mesh; using SM.OGL.Mesh;
@ -22,7 +23,7 @@ namespace SM.Base.Objects
/// <summary> /// <summary>
/// Contains vertex colors /// Contains vertex colors
/// </summary> /// </summary>
public virtual VBO Color { get; protected set; } public virtual VBO<Color4> Color { get; protected set; }
/// <inheritdoc /> /// <inheritdoc />
public float LineWidth { get; set; } = 1; public float LineWidth { get; set; } = 1;

View file

@ -1,5 +1,6 @@
#region usings #region usings
using OpenTK;
using OpenTK.Graphics; using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.OGL.Mesh; using SM.OGL.Mesh;
@ -27,18 +28,18 @@ namespace SM.Base.Objects.Static
} }
/// <inheritdoc /> /// <inheritdoc />
public override VBO Vertex { get; protected set; } = new VBO public override VBO<Vector3> Vertex { get; protected set; } = new VBO<Vector3>
{ {
{0, 0, 0}, new Vector3(0, 0, 0),
{.5f, 0, 0}, new Vector3(.5f, 0, 0),
{0, 0, 0}, new Vector3(0, 0, 0),
{0, .5f, 0}, new Vector3(0, .5f, 0),
{0, 0, -.5f}, new Vector3(0, 0, -.5f),
{0, 0, .5f} new Vector3(0, 0, .5f)
}; };
/// <inheritdoc /> /// <inheritdoc />
public override VBO Color { get; protected set; } = new VBO(pointerSize: 4) public override VBO<Color4> Color { get; protected set; } = new VBO<Color4>
{ {
Color4.White, Color4.White,
Color4.Red, Color4.Red,

View file

@ -25,21 +25,21 @@ namespace SM.Base.Objects.Static
} }
/// <inheritdoc /> /// <inheritdoc />
public override VBO Vertex { get; protected set; } = new VBO public override VBO<Vector3> Vertex { get; protected set; } = new VBO<Vector3>
{ {
{-.5f, -.5f, 0}, new Vector3(-.5f, -.5f, 0),
{-.5f, .5f, 0}, new Vector3(-.5f, .5f, 0),
{.5f, .5f, 0}, new Vector3(.5f, .5f, 0),
{.5f, -.5f, 0} new Vector3(.5f, -.5f, 0),
}; };
/// <inheritdoc /> /// <inheritdoc />
public override VBO UVs { get; protected set; } = new VBO(pointerSize: 2) public override VBO<Vector2> UVs { get; protected set; } = new VBO<Vector2>
{ {
{0, 1}, new Vector2(0, 1),
{0, 0}, new Vector2(0, 0),
{1, 0}, new Vector2(1, 0),
{1, 1} new Vector2(1, 1),
}; };
/// <inheritdoc /> /// <inheritdoc />

View file

@ -124,7 +124,7 @@ namespace SM.OGL.Mesh
public void Update(GenericMesh mesh) public void Update(GenericMesh mesh)
{ {
int pos = 0; int pos = 0;
foreach (float f in mesh.Vertex) foreach (float f in mesh.Vertex.GetFloats())
{ {
Min[pos] = Math.Min(Min[pos], f); Min[pos] = Math.Min(Min[pos], f);
Max[pos] = Math.Max(Max[pos], f); Max[pos] = Math.Max(Max[pos], f);

View file

@ -1,6 +1,7 @@
#region usings #region usings
using System; using System;
using OpenTK;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
#endregion #endregion
@ -29,17 +30,17 @@ namespace SM.OGL.Mesh
/// <summary> /// <summary>
/// Contains the vertices for the mesh. /// Contains the vertices for the mesh.
/// </summary> /// </summary>
public virtual VBO Vertex { get; protected set; } public virtual VBO<Vector3> Vertex { get; protected set; }
/// <summary> /// <summary>
/// Contains the texture coords for the mesh. /// Contains the texture coords for the mesh.
/// </summary> /// </summary>
public virtual VBO UVs { get; protected set; } public virtual VBO<Vector2> UVs { get; protected set; }
/// <summary> /// <summary>
/// Contains the normals for the mesh. /// Contains the normals for the mesh.
/// </summary> /// </summary>
public virtual VBO Normals { get; protected set; } public virtual VBO<Vector3> Normals { get; protected set; }
/// <summary> /// <summary>
/// Represents the bounding box. /// Represents the bounding box.
@ -98,7 +99,11 @@ namespace SM.OGL.Mesh
UpdateBoundingBox(); UpdateBoundingBox();
foreach (var kvp in Attributes) foreach (var kvp in Attributes)
kvp.ConnectedVBO?.BindBuffer(kvp.Index); {
if (kvp.ConnectedVBO == null) continue;
kvp.ConnectedVBO.AttributeID = kvp.Index;
kvp.ConnectedVBO.Compile();
}
GL.BindVertexArray(0); GL.BindVertexArray(0);
} }

View file

@ -1,246 +1,155 @@
#region usings using OpenTK;
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics; using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using System;
#endregion using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SM.OGL.Mesh namespace SM.OGL.Mesh
{ {
/// <summary> public abstract class VBO : GLObject
/// Represents a Vertex Buffer Object used for meshes.
/// </summary>
public class VBO : List<float>
{ {
/// <summary> private float[] _floatArray;
/// The ID for the buffer.
/// </summary>
public int BufferID { get; private set; }
/// <summary> protected override bool AutoCompile { get => false; set { return; } }
/// Specifies the expected usage pattern of the data store. public override ObjectLabelIdentifier TypeIdentifier => ObjectLabelIdentifier.Buffer;
/// </summary>
public BufferUsageHint BufferUsageHint;
/// <summary> public bool Active { get; set; } = true;
/// Normalise floats? public bool CanBeUpdated { get; set; } = true;
/// </summary>
public bool Normalised;
/// <summary> public bool Normalized { get; protected set; }
/// Specifies a offset of the first component of the first generic vertex attribute in the array in the data store of public int PointerOffset { get; protected set; }
/// the buffer currently bound to the GL_ARRAY_BUFFER target. public int PointerStride { get; protected set; }
/// </summary> public int PointerSize { get; protected set; }
public int PointerOffset; public BufferUsageHint UsageHint { get; protected set; }
public VertexAttribPointerType PointerType { get; protected set; }
/// <summary> public int AttributeID { get; internal set; }
/// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
/// </summary>
public int PointerSize;
/// <summary> public abstract int Count { get; }
/// Specifies the byte offset between consecutive generic vertex attributes.
/// </summary>
public int PointerStride;
/// <summary>
/// The VBO gets ignored when true.
/// <para>Default: true</para>
/// </summary>
public bool Active = true;
/// <summary>
/// Specifies the data type of each component in the array.
/// </summary>
public VertexAttribPointerType PointerType;
/// <summary>
/// If true it can be updated, otherwise it will get ignored, when the mesh gets updated.
/// </summary>
public bool CanBeUpdated = false;
/// <summary>
/// Generates a VBO for inserting mesh data.
/// </summary>
/// <param name="bufferUsageHint">
/// Specifies the expected usage pattern of the data store.
/// <para>Default: StaticDraw</para>
/// </param>
/// <param name="pointerType">
/// Specifies the data type of each component in the array.
/// <para>Default: Float</para>
/// </param>
/// <param name="pointerSize">
/// Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, 4.
/// <para>Default: 3</para>
/// </param>
/// <param name="pointerStride">
/// Specifies the byte offset between consecutive generic vertex attributes.
/// <para>Default: 0</para>
/// </param>
/// <param name="pointerOffset">
/// Specifies a offset of the first component of the first generic vertex attribute in the
/// array in the data store of the buffer currently bound to the GL_ARRAY_BUFFER target.
/// <para>Default: 0</para>
/// </param>
/// <param name="normalised">
/// Normalise floats?
/// <para>Default: false</para>
/// </param>
public VBO(BufferUsageHint bufferUsageHint = BufferUsageHint.StaticDraw, public VBO(BufferUsageHint bufferUsageHint = BufferUsageHint.StaticDraw,
VertexAttribPointerType pointerType = VertexAttribPointerType.Float, int pointerSize = 3,
int pointerStride = 0, int pointerOffset = 0, bool normalised = false) int pointerStride = 0, int pointerOffset = 0, bool normalised = false)
{ {
BufferUsageHint = bufferUsageHint; UsageHint = bufferUsageHint;
PointerType = pointerType;
PointerSize = pointerSize;
PointerStride = pointerStride; PointerStride = pointerStride;
PointerOffset = pointerOffset; PointerOffset = pointerOffset;
Normalised = normalised; Normalized = normalised;
} }
public void Add(float x) public override void Compile()
{ {
CanBeUpdated = true; base.Compile();
}
/// <summary>
/// Adds two values to the VBO.
/// </summary>
public void Add(float x, float y)
{
AddRange(new[] {x, y});
CanBeUpdated = true;
}
/// <summary>
/// Adds three values to the VBO.
/// </summary>
public void Add(float x, float y, float z)
{
AddRange(new[] {x, y, z});
CanBeUpdated = true;
}
/// <summary>
/// Adds four values to the VBO.
/// </summary>
public void Add(float x, float y, float z, float w)
{
AddRange(new[] {x, y, z, w});
CanBeUpdated = true;
}
/// <summary>
/// Adds a Vector2.
/// </summary>
public void Add(Vector2 vector)
{
Add(vector.X, vector.Y);
}
/// <summary>
/// Adds a Vector2 and a value.
/// </summary>
public void Add(Vector2 vector, float z)
{
Add(vector.X, vector.Y, z);
}
/// <summary>
/// Adds a Vector2 and two values.
/// </summary>
public void Add(Vector2 vector, float z, float w)
{
Add(vector.X, vector.Y, z, w);
}
/// <summary>
/// Adds a array of vector2s.
/// </summary>
/// <param name="vectors"></param>
public void Add(params Vector2[] vectors)
{
foreach (Vector2 vector in vectors)
{
Add(vector);
}
}
/// <summary>
/// Adds a Vector3.
/// </summary>
public void Add(Vector3 vector)
{
Add(vector.X, vector.Y, vector.Z);
}
/// <summary>
/// Adds a Vector3 and a value.
/// </summary>
public void Add(Vector3 vector, float w)
{
Add(vector.X, vector.Y, vector.Z, w);
}
/// <summary>
/// Adds a array of Vector3s.
/// </summary>
/// <param name="vectors"></param>
public void Add(params Vector3[] vectors)
{
foreach (Vector3 vector in vectors)
{
Add(vector);
}
}
/// <summary>
/// Adds a vector4.
/// </summary>
/// <param name="vector"></param>
public void Add(Vector4 vector)
{
Add(vector.X, vector.Y, vector.Z, vector.W);
}
/// <summary>
/// Adds a color.
/// </summary>
public void Add(Color4 color)
{
Add(color.R, color.G, color.B, color.A);
}
/// <summary>
/// Binds the buffer to the active VAO.
/// </summary>
/// <param name="attribID">The id for the attribute.</param>
internal void BindBuffer(int attribID)
{
if (!Active) return; if (!Active) return;
var data = ToArray(); float[] data = ToFloat();
BufferID = GL.GenBuffer(); _id = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, BufferID); GL.BindBuffer(BufferTarget.ArrayBuffer, _id);
GL.BufferData(BufferTarget.ArrayBuffer, data.Length * sizeof(float), data, BufferUsageHint); GL.BufferData(BufferTarget.ArrayBuffer, data.Length * sizeof(float), data, UsageHint);
GL.VertexAttribPointer(attribID, PointerSize, PointerType, Normalised, PointerStride, PointerOffset); GL.VertexAttribPointer(AttributeID, PointerSize, PointerType, Normalized, PointerStride, PointerOffset);
GL.EnableVertexAttribArray(attribID); GL.EnableVertexAttribArray(AttributeID);
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
CanBeUpdated = false; CanBeUpdated = false;
} }
internal void Update() public void Update()
{ {
var data = ToArray(); float[] data = GetFloats();
GL.BindBuffer(BufferTarget.ArrayBuffer, BufferID); GL.BindBuffer(BufferTarget.ArrayBuffer, _id);
GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, data.Length * sizeof(float), data); GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, data.Length * sizeof(float), data);
CanBeUpdated = false;
}
public override void Dispose()
{
GL.DeleteBuffer(_id);
base.Dispose();
}
public float[] GetFloats()
{
if (_floatArray == null || CanBeUpdated)
{
_floatArray = ToFloat();
}
return _floatArray;
}
protected abstract float[] ToFloat();
}
public class VBO<TType> : VBO, IEnumerable<TType>
where TType : struct
{
static Dictionary<Type, Tuple<int, VertexAttribPointerType>> _pointerSizes = new Dictionary<Type, Tuple<int, VertexAttribPointerType>>()
{
{ typeof(float), new Tuple<int, VertexAttribPointerType>(1, VertexAttribPointerType.Float) },
{ typeof(Vector2), new Tuple<int, VertexAttribPointerType>(2, VertexAttribPointerType.Float) },
{ typeof(Vector3), new Tuple<int, VertexAttribPointerType>(3, VertexAttribPointerType.Float) },
{ typeof(Vector4), new Tuple<int, VertexAttribPointerType>(4, VertexAttribPointerType.Float) },
{ typeof(Color4), new Tuple<int, VertexAttribPointerType>(4, VertexAttribPointerType.Float) },
};
private List<TType> _values = new List<TType>();
public override int Count => _values.Count;
public VBO(BufferUsageHint bufferUsageHint = BufferUsageHint.StaticDraw,
int pointerStride = 0, int pointerOffset = 0, bool normalised = false) : base(bufferUsageHint, pointerStride, pointerOffset, normalised)
{
if (!_pointerSizes.ContainsKey(typeof(TType)))
throw new NotSupportedException($"The type '{typeof(TType).FullName}' is not applicable for VBOs.");
PointerSize = _pointerSizes[typeof(TType)].Item1;
PointerType = _pointerSizes[typeof(TType)].Item2;
}
public void Add(TType value)
{
_values.Add(value);
CanBeUpdated = true;
}
public void RemoveAt(int pos)
{
_values.RemoveAt(pos);
CanBeUpdated = true;
}
public IEnumerator<TType> GetEnumerator()
{
return _values.GetEnumerator();
}
protected override float[] ToFloat()
{
List<float> floats = new List<float>();
foreach (TType value in _values)
{
switch (value)
{
case float f: floats.Add(f); break;
case Vector2 v: floats.AddRange(new[] { v.X, v.Y }); break;
case Vector3 v: floats.AddRange(new[] { v.X, v.Y, v.Z }); break;
case Vector4 v: floats.AddRange(new[] { v.X, v.Y, v.Z, v.W }); break;
case Color4 v: floats.AddRange(new[] { v.R, v.G, v.B, v.A }); break;
}
}
return floats.ToArray();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _values.GetEnumerator();
} }
} }
} }

View file

@ -144,7 +144,7 @@ namespace SM.OGL.Shaders
if (mesh.Indices != null) if (mesh.Indices != null)
GL.DrawElementsInstanced(mesh.PrimitiveType, 0, DrawElementsType.UnsignedInt, mesh.Indices, amount); GL.DrawElementsInstanced(mesh.PrimitiveType, 0, DrawElementsType.UnsignedInt, mesh.Indices, amount);
else else
GL.DrawArraysInstanced(mesh.PrimitiveType, 0, mesh.Vertex.Count / mesh.Vertex.PointerSize, amount); GL.DrawArraysInstanced(mesh.PrimitiveType, 0, mesh.Vertex.Count, amount);
} }
/// <summary> /// <summary>
/// Draws the mesh while forcing a primitive type instead of using the mesh type. /// Draws the mesh while forcing a primitive type instead of using the mesh type.
@ -157,7 +157,7 @@ namespace SM.OGL.Shaders
if (mesh.Indices != null) if (mesh.Indices != null)
GL.DrawElementsInstanced(modelType, 0, DrawElementsType.UnsignedInt, mesh.Indices, amount); GL.DrawElementsInstanced(modelType, 0, DrawElementsType.UnsignedInt, mesh.Indices, amount);
else else
GL.DrawArraysInstanced(modelType, 0, mesh.Vertex.Count / mesh.Vertex.PointerSize, amount); GL.DrawArraysInstanced(modelType, 0, mesh.Vertex.Count, amount);
} }
/// <summary> /// <summary>

View file

@ -3,6 +3,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using OpenTK; using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4; using OpenTK.Graphics.OpenGL4;
using SM.Base.Objects; using SM.Base.Objects;
using SM.OGL.Mesh; using SM.OGL.Mesh;
@ -17,13 +18,13 @@ namespace SM2D.Object
public class Polygon : Mesh public class Polygon : Mesh
{ {
/// <inheritdoc /> /// <inheritdoc />
public override VBO Vertex { get; protected set; } = new VBO(); public override VBO<Vector3> Vertex { get; protected set; } = new VBO<Vector3>();
/// <inheritdoc /> /// <inheritdoc />
public override VBO UVs { get; protected set; } = new VBO(pointerSize: 2); public override VBO<Vector2> UVs { get; protected set; } = new VBO<Vector2>();
/// <inheritdoc /> /// <inheritdoc />
public override VBO Color { get; protected set; } = new VBO(pointerSize: 4); public override VBO<Color4> Color { get; protected set; } = new VBO<Color4>();
/// <inheritdoc /> /// <inheritdoc />
public override PrimitiveType PrimitiveType { get; protected set; } = PrimitiveType.TriangleFan; public override PrimitiveType PrimitiveType { get; protected set; } = PrimitiveType.TriangleFan;
@ -38,7 +39,7 @@ namespace SM2D.Object
foreach (var vertex in vertices) foreach (var vertex in vertices)
{ {
Vertex.Add(vertex, 0); Vertex.Add(new Vector3(vertex));
} }
UpdateBoundingBox(); UpdateBoundingBox();
@ -55,7 +56,7 @@ namespace SM2D.Object
foreach (var polygonVertex in vertices) foreach (var polygonVertex in vertices)
{ {
Color.Add(polygonVertex.Color); Color.Add(polygonVertex.Color);
Vertex.Add(polygonVertex.Position, 0); Vertex.Add(new Vector3(polygonVertex.Position.X, polygonVertex.Position.Y, 0));
} }
UpdateBoundingBox(); UpdateBoundingBox();

View file

@ -53,9 +53,11 @@ namespace SM_TEST
private static void WindowOnUpdateFrame(object sender, FrameEventArgs e) private static void WindowOnUpdateFrame(object sender, FrameEventArgs e)
{ {
if (SM.Base.Controls.Mouse.LeftClick)
line.Vertex.Add(Vector3.Zero);
line.Vertex.RemoveRange(3, 3); line.Vertex.RemoveAt(1);
line.Vertex.Add(Mouse2D.InWorld(window.ViewportCamera as Camera), 0); line.Vertex.Add(new Vector3(Mouse2D.InWorld(window.ViewportCamera as Camera)));
line.Update(); line.Update();