我正在使用Pencil.Gaming库运行一个C#项目,该库是GLFW的C#绑定,它使用OpenTK来包装OpenGL函数。我试图在vbo中绘制一个顶点数组,一旦我到达GL.DrawArrays
,当我调用System.AccessViolationException
时,它会给我Invalid Operation
和GL.GetError()
错误。下面是我的Mesh类代码,错误的屏幕截图是Visual Studio。我想要绘制的对象和我的Vertex类的副本也在下面。
static Mesh mesh;
mesh = new Mesh();
Vertex[] data = new Vertex[] {new Vertex(new Vector3(-1,-1,0)),
new Vertex(new Vector3(0,1,0)),
new Vertex(new Vector3(1,-1,0))};
mesh.addVertices(data);
mesh.draw();
顶点类:
struct Vertex
{
public static readonly int SIZE = 3;
private Vector3 position;
public Vertex(Vector3 position)
{
this.position = position;
}
}
Mesh类:
using System;
using Pencil.Gaming.Graphics;
using Pencil.Gaming.MathUtils;
namespace Practicalis.Rendering
{
class Mesh
{
private int size;
private int vbo;
public Mesh()
{
size = 0;
GL.GenBuffers(size, out vbo);
}
public void addVertices(Vertex[] vertices)
{
size = vertices.Length * sizeof(float);
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)size, (IntPtr)vbo, BufferUsageHint.StaticDraw);
}
public void draw()
{
GL.EnableVertexAttribArray(0);
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, Vertex.SIZE * 4, 0);
Console.WriteLine(GL.GetError());
GL.DrawArrays(BeginMode.Triangles, 0, size);
GL.DisableVertexAttribArray(0);
}
}
}
答案 0 :(得分:1)
在add vertice函数中,我没有传入我的实际Vertex数组,只是指向vbo的指针。正确的功能如下。
public void addVertices(Vertex[] vertices)
{
size = vertices.Length * Vector3.SizeInBytes;
Vector3[] vertsData = new Vector3[vertices.Length];
GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
for (int i = 0; i < vertices.Length; i++)
vertsData[i] = vertices[i].Position;
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)size, vertsData, BufferUsageHint.StaticDraw);
}
答案 1 :(得分:0)
GL.GenBuffers(size, out vbo);
在此行之前,您的大小为0.应该至少有一个,因为这是生成缓冲区的数量。