用于RenderToTarget的XNA第二个图形设备



我正在创建一个XNA游戏,它从多个精灵中创建随机岛屿。它在一个单独的线程中创建它们,然后使用RenderTarget2D将它们编译为单个纹理。

要创建RenderTarget2D,我需要一个图形设备。如果我使用自动创建的图形设备,除了主游戏线程中的draw调用与它冲突之外,大多数情况下都可以正常工作。在图形设备上使用lock()会导致闪烁,甚至有时纹理创建不正确。

如果我创建自己的Graphics设备,就不会有冲突,但岛屿永远不会正确渲染,而是呈现出纯黑色和白色。我不知道为什么会发生这种事。基本上,我需要一种方法来创建第二个图形设备,让我得到相同的结果,而不是黑/白。有人有什么想法吗?

以下是我用来创建第二个图形设备的代码,供TextureBuilder独家使用:

var presParams = game.GraphicsDevice.PresentationParameters.Clone();
// Configure parameters for secondary graphics device
GraphicsDevice2 = new GraphicsDevice(game.GraphicsDevice.Adapter, GraphicsProfile.HiDef, presParams);

以下是我用来将我的岛屿渲染为单个纹理的代码:

public IslandTextureBuilder(List<obj_Island> islands, List<obj_IslandDecor> decorations, SeaGame game, Vector2 TL, Vector2 BR, int width, int height)
{
gDevice = game.Game.GraphicsDevice; //default graphics
//gDevice = game.GraphicsDevice2 //created graphics
render = new RenderTarget2D(gDevice, width, height, false, SurfaceFormat.Color, DepthFormat.None);
this.islands = islands;
this.decorations = decorations;
this.game = game;
this.width = width;
this.height = height;
this.TL = TL; //top left coordinate
this.BR = BR; //bottom right coordinate
}
public Texture2D getTexture()
{
lock (gDevice)
{
//Set render target. Clear the screen.
gDevice.SetRenderTarget(render);
gDevice.Clear(Color.Transparent);
//Point camera at the island
Camera cam = new Camera(gDevice.Viewport);
cam.Position = TL;
cam.Update();
//Draw all of the textures to render
SpriteBatch batch = new SpriteBatch(gDevice);
batch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, cam.Transform);
{
foreach (obj_Island island in islands)
{
island.Draw(batch);
}
foreach (obj_IslandDecor decor in decorations)
{
decor.Draw(batch);
}
}
batch.End();
//Clear render target
gDevice.SetRenderTarget(null);
//Copy to texture2D for permanant storage
Texture2D texture = new Texture2D(gDevice, render.Width, render.Height);
Color[] color = new Color[render.Width * render.Height];
render.GetData<Color>(color);
texture.SetData<Color>(color);
Console.WriteLine("done");
return texture;
}

以下是在透明背景下应该发生的情况(如果我使用默认设备,通常会这样做)http://i110.photobucket.com/albums/n81/taumonkey/GoodIsland.png

当默认设备发生冲突,并且主线程设法调用Clear()(即使它也被锁定)时,就会发生这种情况NotSoGoodIsland.png(需要10个信誉…)

以下是我使用自己的图形设备时会发生的情况http://i110.photobucket.com/albums/n81/taumonkey/BadIsland.png

提前感谢您提供的任何帮助!

我可能已经解决了这个问题,方法是将RenderToTarget代码移动到Draw()方法中,并在第一次调用Draw(。

相关内容

最新更新