我一直试图在我的代码中找出这个错误很长一段时间,现在我正在寻求stackoverflow的帮助!无论如何,我已经创建了一个用于在openGL中创建模型的类。它处理给定模型的VBO,VAO和EBO,但是当我创建两个并显示它们时,第二个总是覆盖前一个/一个我不明白为什么,我向我的一个朋友展示它,我们一起一无所获。这是模型类:
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using System;
namespace YISOPENGLEVIL.Components.Objects
{
struct Vertex
{
Vector3 Position;
Vector3 Color;
public Vertex(Vector3 position, Vector3 color)
{
Position = position;
Color = color;
}
}
class Model
{
public int VBO, VAO, EBO;
public Vertex[] Data;
public int[] Indices;
public Model() { }
public Model(Vertex[] data, int[] indices)
{
Data = data;
Indices = indices;
VAO = GL.GenVertexArray();
VBO = GL.GenBuffer();
EBO = GL.GenBuffer();
GL.BindVertexArray(VAO);
GL.BindBuffer(BufferTarget.ArrayBuffer, VBO);
GL.BufferData(BufferTarget.ArrayBuffer, Data.Length * 24, Data, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 24, 0);
GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 24, 12);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, EBO);
GL.BufferData(BufferTarget.ElementArrayBuffer, Indices.Length * 4, Indices, BufferUsageHint.StaticDraw);
GL.EnableVertexAttribArray(0);
GL.EnableVertexAttribArray(1);
}
protected static Vector3 toVec3(Color4 c)
{
return new Vector3(c.R, c.G, c.B);
}
public void Render()
{
//GL.DrawArrays(PrimitiveType.Triangles, 0, Data.Length);
GL.DrawElements(BeginMode.Triangles, Indices.Length, DrawElementsType.UnsignedInt, 0);
}
}
}
然后我的Element类被传递给Model,然后用它来显示它,
using OpenTK;
using System.Collections.Generic;
using OpenTK.Graphics.OpenGL4;
namespace YISOPENGLEVIL.Components.Objects
{
class Element
{
private int transform;
private int s;
public Vector3 Position;
public Vector3 Rotation;
private Matrix4 View;
private Model Model;
public Element(Model m, int Shader)
{
s = Shader;
Model = m;
Position = new Vector3(0, 0, 0);
Rotation = new Vector3(0, 0, 0);
}
public void Render()
{
var t = Matrix4.CreateTranslation(Position.X, Position.Y, Position.Z);
var rx = Matrix4.CreateRotationX(Rotation.X);
var ry = Matrix4.CreateRotationY(Rotation.Y);
var rz = Matrix4.CreateRotationZ(Rotation.Z);
View = t * rx * ry * rz;
transform = GL.GetUniformLocation(s, "transform");
GL.UniformMatrix4(transform, false, ref View);
Model.Render();
}
public static void RenderAll()
{
}
}
}
这是实施:
m1 = new Cube(1.5f, Color4.Aqua);
m2 = new Cube(1f, Color4.Red);
e1 = new Element(m1, s.Program);
e2 = new Element(m2, s.Program);
e1.Position = new Vector3(0, 0, 0);
e2.Position = new Vector3(0, 0, 1);
和
e1.Render();
e2.Render();
cube类扩展了Model,并通过创建顶点数组的私有静态方法将数据传递给Model构造函数。真正奇怪的是,如果我把print语句显示两个元素都被定义得很好并且有正确的数据,那么最后一个总是覆盖前一个(在正确的位置有两个对象,但都显示红色的小立方体) 。我不明白......有什么想法吗?