我为一个游戏“我的世界”风格的项目工作。
我开始使用“模型实例化”来生成大量拥有相同模型的立方体。到现在为止还挺好。我的问题是,如果我增加矩阵的大小以从 [500-1-500 ]( 250,000 立方米)的 [300-1-300]( 90,000 立方米)中提取,我的程序会大大减慢。它从 60fps 到 20...
我真的不明白为什么。但是我正确地使用了“硬件实例化”技术。我还在论坛上注意到,这种技术可以让 XNA 绘制多达 700 万立方!!你知道我的问题出在哪里吗?
十分感谢
这是我绘制实例化模型的函数:
// Draw the 3D map (world) of game
public void drawWorld(GameTime gameTime)
{
/ * Draw all the structures that make up the world with the instancing system * /
Array.Resize(ref instanceTransforms, smallListInstance.Count);
for (int i = 0; i < ListInstance.Count; i++)
{
instanceTransforms[i] = ListInstance[i].Transform;
}
DrawModelHardwareInstancing(myModel, myTexture2D,instancedModelBones,instanceTransforms, arcadia.camera.View, arcadia.camera.Projection);
}
// ### end function drawWorld
这是我的函数 [DrawModelHardwareInstancing] ,它使用 microsoft 示例中使用的方法[Hardware Instancing]绘制模型。
// Function that will draw all the models instantiated in the list
void DrawModelHardwareInstancing(Model model,Texture2D texture, Matrix[] modelBones,
Matrix[] instances, Matrix view, Matrix projection)
{
Game.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;
if (instances.Length == 0)
return;
// If we have more instances than room in our vertex buffer, grow it to the neccessary size.
if ((instanceVertexBuffer == null) ||
(instances.Length > instanceVertexBuffer.VertexCount))
{
if (instanceVertexBuffer != null)
instanceVertexBuffer.Dispose();
instanceVertexBuffer = new DynamicVertexBuffer(Game.GraphicsDevice, instanceVertexDeclaration,
instances.Length, BufferUsage.WriteOnly);
}
// Transfer the latest instance transform matrices into the instanceVertexBuffer.
instanceVertexBuffer.SetData(instances, 0, instances.Length, SetDataOptions.Discard);
foreach (ModelMesh mesh in model.Meshes)
{
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
// Tell the GPU to read from both the model vertex buffer plus our instanceVertexBuffer.
Game.GraphicsDevice.SetVertexBuffers(
new VertexBufferBinding(meshPart.VertexBuffer, meshPart.VertexOffset, 0),
new VertexBufferBinding(instanceVertexBuffer, 0, 1)
);
Game.GraphicsDevice.Indices = meshPart.IndexBuffer;
// Set up the instance rendering effect.
Effect effect = meshPart.Effect;
//effect.CurrentTechnique = effect.Techniques["HardwareInstancing"];
effect.Parameters["World"].SetValue(modelBones[mesh.ParentBone.Index]);
effect.Parameters["View"].SetValue(view);
effect.Parameters["Projection"].SetValue(projection);
effect.Parameters["Texture"].SetValue(texture);
// Draw all the instance copies in a single call.
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Apply();
Game.GraphicsDevice.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0,
meshPart.NumVertices, meshPart.StartIndex,
meshPart.PrimitiveCount, instances.Length);
}
}
}
}
// ### end function DrawModelHardwareInstancing