使用光照时,顶点着色无法使用动态创建的网格

时间:2013-06-17 18:47:36

标签: java 3d desktop-application libgdx

我使用以下代码创建了一个包含位置,法线和颜色信息的Mesh对象:

final Vector3[] vertexVectors = this.getVertexVectors();
final short[] indices = this.getIndices();
final Vector3[] vertexNormals = this.getNormals(vertexVectors, indices);
final float[] vertices = new float[vertexVectors.length * 7];

for (int index = 0; index < vertexVectors.length; index++)
{
    vertices[(index * 7) + 0] = vertexVectors[index].x;
    vertices[(index * 7) + 1] = vertexVectors[index].y;
    vertices[(index * 7) + 2] = vertexVectors[index].z;

    vertices[(index * 7) + 3] = vertexNormals[index].x;
    vertices[(index * 7) + 4] = vertexNormals[index].y;
    vertices[(index * 7) + 5] = vertexNormals[index].z;

    vertices[(index * 7) + 6] = Color.toFloatBits(0, 255, 0, 255);
}

final Mesh mesh = new Mesh(true, vertices.length / 3, indices.length, new VertexAttribute(Usage.Position, 3, "a_position"), new VertexAttribute(Usage.Normal, 3, "a_normal"), new VertexAttribute(Usage.ColorPacked, 4, "a_color"));
mesh.setVertices(vertices);
mesh.setIndices(indices);
return mesh;

然后我使用以下代码从网格创建一个Model对象和一个ModelInstance对象:

private Model model;
private ModelInstance instance;

final ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
modelBuilder.part("0", this.getCustomMesh(), GL10.GL_TRIANGLES, new Material());
this.model = modelBuilder.end();
this.instance = new ModelInstance(this.model);

我使用以下代码渲染ModelInstance:

Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

this.modelBatch.begin(this.cam);
this.modelBatch.render(this.instance, this.lights);
this.modelBatch.end();

我的问题是模型没有颜色。根据顶点颜色,模型应为绿色,但只要我使用光照,模型就会显示为白色。如果我删除了灯光,模型会按预期显示为绿色(但没有漂亮的阴影)。我尝试将Gdx.gl.glEnable(GL10.GL_COLOR_MATERIAL);添加到this question的构造函数中,但这只会使模型看起来更亮但仍然是白色的。我的模型需要哪些其他设置才能使用光照渲染顶点颜色?

1 个答案:

答案 0 :(得分:0)

似乎在模型的材料中添加ColorAttribute.createDiffuse可以解决问题。这意味着更改此行:

modelBuilder.part("0", this.getCustomMesh(), GL10.GL_TRIANGLES, new Material());

用这个:

modelBuilder.part("0", this.getCustomMesh(), GL10.GL_TRIANGLES, new Material(ColorAttribute.createDiffuse(0, 0, 0, 0)));

我不完全理解为什么并且作为一个额外的好奇心,传递给createDiffuse方法的值似乎对模型没有明显的影响。