我正在为 XNA 4.0 开发图形引擎,但遇到了一个我找不到任何解决方案的问题。目前我正在尝试通过使用着色器来实现灯光效果。图形引擎还包含一个粒子引擎,因此至少考虑性能对我来说非常重要。这两件事的结合产生了问题。
首先,我已经做了很多阅读和研究,据我所知,你做的绘制调用越少,性能越好。通过绘制调用,我的意思是当 spritebatch 将实际几何体和纹理发送到 GPU 时。因此,我试图在一个批次中尽可能多地绘制。
现在问题来了。我的引擎绘图方法有 2 个重载:
public static void Draw(Texture texture)
{
// Call spriteBatch.Draw(...);
}
public static void Draw(Light light)
{
// Call spriteBatch.Draw(...);
}
第一个重载只是要使用默认着色器绘制普通纹理。第二个重载将绘制使用另一个着色器的灯光。我想做的是:
public static void Draw(Texture texture)
{
// Use default shader
// Call spriteBatch.Draw(...);
}
public static void Draw(Light light)
{
// Use light shader
// Call spriteBatch.Draw(...);
}
但是,SpriteBatch 一次不支持多个着色器,因此我尝试使用效果通道来执行此操作:
public static void Draw(Texture texture)
{
effect.CurrentTechnique.Passes[0].Apply();
// Call spriteBatch.Draw(...);
}
public static void Draw(Light light)
{
effect.CurrentTechnique.Passes[1].Apply();
// Call spriteBatch.Draw(...);
}
这也不起作用,因为调用 spriteBatch.Draw() 时不使用着色器,而是调用 spriteBatch.End() 时使用着色器。因此,上面的代码使用我最后应用的 pass 渲染了所有内容。
我的第三次尝试是使用 2 个 SpriteBatches:
public static void Begin()
{
spriteBatchColor.Begin([...], null); // Default shader.
spriteBatchLight.Begin([...], effect); // Light shader.
}
public static void Draw(Texture texture)
{
// Call spriteBatchColor.Draw(...);
}
public static void Draw(Light light)
{
// Call spriteBatchLight.Draw(...);
}
public static void End()
{
spriteBatchColor.End();
spriteBatchLight.End();
}
这确实有效,但是我的图层深度完全搞砸了,这并不奇怪,因为 spriteBatchLight.End() 是最后调用的,所以它总是会绘制在 spriteBatchColor 绘制的所有内容之上。
我知道我可以将 SpriteSortMode 设置为 SpriteSortMode.Immediate,但是我会受到很大的性能损失,因为该模式会直接绘制所有内容。由于在这种情况下性能非常重要,因此我想通过尽可能少地对 GPU 进行绘制调用来进行优化,SpriteSortMode.Immediate 对我来说不是一个选项。
所以,我的问题是:
有什么方法可以在一批中使用 2 种不同的效果/技术/通道?或者有什么方法可以让我使用 2 个不同的 SpriteBatches,然后在我进行最终绘制时将它们组合起来,这样图层深度就不会被弄乱?