XNA中的ToggleFullScreen会导致丢失的设备错误

时间:2011-01-17 06:56:30

标签: xna fullscreen xna-4.0

我正在尝试编写我的第一个XNA游戏,并且我希望包含ALT + ENTER功能以在全屏和窗口模式之间切换。我的游戏现在非常基本,没什么特别的。我可以让它在我的LoadContent函数中以窗口(默认)或全屏(通过调用ToggleFullScreen)运行,一切都很好。

然而,当我在Update函数中调用ToggleFullScreen时,使用完全相同的代码,我的游戏失败了。如果我开始窗口并切换到全屏,它似乎冻结,只显示一帧而不接受键盘输入(我必须CTRL + ALT + DEL)。如果我启动全屏并切换到窗口,则在DrawIndexedPrimitive上出现错误,并显示消息“当前顶点声明不包括当前顶点着色器所需的所有元素。缺少Normal0。” (这不是真的;我的顶点缓冲区是VertexPositionNormalTexture并且包含数据,并且GraphicsDevice状态是Normal)。

这两个问题似乎都指向某种方式与设备失去联系,但我无法弄清楚原因。我在网上找到的每一种资源都说切换全屏就像调用ToggleFullScreen函数一样简单,没有提到重置设备或缓冲区。有什么想法吗?

编辑:这是一些代码,遗漏了无关的东西:

    protected override void LoadContent()
    {
        graphics.PreferredBackBufferWidth = 800; 
        graphics.PreferredBackBufferHeight = 600;
        graphics.ToggleFullScreen();

        basicEffect = new BasicEffect(graphics.GraphicsDevice);
        // etc.
    }

    protected override void Update(GameTime gameTime)
    {
        if (k.IsKeyDown(Keys.Enter) && (k.IsKeyDown(Keys.LeftAlt) || k.IsKeyDown(Keys.RightAlt)) && !oldKeys.Contains(Keys.Enter)) {
            graphics.ToggleFullScreen();
            gameWorld.Refresh();
        }
         // update the world's graphics; this fills my buffers
        GraphicsBuffers gb = gameWorld.Render(graphics.GraphicsDevice);
        graphics.GraphicsDevice.SetVertexBuffer(gb.vb, 0);
        graphics.GraphicsDevice.Indices = gb.ib;
   }

    protected override void Draw(GameTime gameTime)
    {
        // buffer reference again; these are persistent once filled in Update, they don't get created anew
        GraphicsBuffers gb = gameWorld.Render(graphics.GraphicsDevice);

        foreach (EffectPass effectPass in basicEffect.CurrentTechnique.Passes)
        {
            effectPass.Apply();

            basicEffect.Texture = textures;
            graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, gb.vb.VertexCount, 0, gb.ib.IndexCount / 3);
        }
    }

4 个答案:

答案 0 :(得分:4)

XNA Game类和相关的GraphicsDeviceManager围绕Update函数用于更新游戏状态的概念构建,Draw函数用于渲染该状态。在Update功能期间设置图形设备的状态时,您会破坏该假设。

当您切换到全屏时,设备会丢失。框架中幕后发生了很多神奇的事情,以隐藏这种复杂性。必须重新创建与设备关联的资源等。框架假设您在下一个Draw函数之前不会再执行任何渲染操作,因此在发生这种情况之前不保证一致状态。

所以......在更新功能期间,不要在图形设备上设置缓冲区。在绘图功能开始时执行此操作。

我不确定这是在任何地方明确记录的。方法文档更隐含了这一点。 Game.Draw文档说:

  

当游戏确定时调用   画框的时间。覆盖这个   具有游戏特定渲染的方法   代码。

并且更新方法说:

  

当游戏确定时调用   游戏逻辑需要处理。   这可能包括管理   游戏状态,用户的处理   输入或模拟的更新   数据。用。覆盖此方法   游戏专用逻辑。

答案 1 :(得分:3)

根据App Hub论坛上的一个答案,您必须确保重建投影矩阵。

http://forums.create.msdn.com/forums/p/31773/182231.aspx

来自该链接......

  

另外,要注意不同   切换为满时的宽高比   屏幕。如果你是3D,你需要   重建您的投影矩阵。如果   你是二维的,你可能需要   将缩放矩阵传递给您的   SpriteBatch.Begin函数。这个   文章有关于做的信息   这是2D。

所以你要确保你这样做(不幸的是,帖子链接到的文章是在Ziggyware上并且该网站已经消失了很长一段时间以便找到他们链接到你的2D示例可能必须如果你有兴趣查看它,可以使用像WaybackMachine这样的档案网站,因为你正在做3D我觉得它可能不是很有意思。)

答案 2 :(得分:2)

我可以使用以下类切换全屏/窗口模式:

/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    private Model grid;
    Model tank;
    int zoom = 1;

    Texture2D thumb;
    Vector2 position = new Vector2( 400, 240 );
    Vector2 velocity = new Vector2( -1, -1 );
    Matrix projection, view;
    public Game1()
    {
        graphics = new GraphicsDeviceManager( this );
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();

        projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4,
                                                                GraphicsDevice.Viewport.AspectRatio,
                                                                10,
                                                                20000 );

        view = Matrix.CreateLookAt( new Vector3( 1500, 550, 0 ) * zoom + new Vector3( 0, 150, 0 ),
                                          new Vector3( 0, 150, 0 ),
                                          Vector3.Up );

    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch( GraphicsDevice );

        // TODO: use this.Content to load your game content here
        thumb = Content.Load<Texture2D>( "GameThumbnail" );
        grid = Content.Load<Model>( "grid" );
        tank = Content.Load<Model>( "tank" );

    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    int ToggleDelay = 0;
    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update( GameTime gameTime )
    {
        // Allows the game to exit
        if ( GamePad.GetState( PlayerIndex.One ).Buttons.Back == ButtonState.Pressed )
            this.Exit();

        var kbState = Keyboard.GetState();
        if ( ( kbState.IsKeyDown( Keys.LeftAlt ) || kbState.IsKeyDown( Keys.RightAlt ) ) &&
             kbState.IsKeyDown( Keys.Enter ) && ToggleDelay <= 0 )
        {
            graphics.ToggleFullScreen();
            ToggleDelay = 1000;
        }

        if ( ToggleDelay >= 0 )
        {
            ToggleDelay -= gameTime.ElapsedGameTime.Milliseconds;
        }
        // TODO: Add your update logic here

        int x, y;
        x = (int)position.X;
        y = (int)position.Y;

        x += (int)velocity.X;
        y += (int)velocity.Y;
        if ( x > 480 - 64 )
            velocity.X = +1;
        if ( x < 0 )
            velocity.X = -1;
        if ( y < 0 )
            velocity.Y = +1;
        if ( y > 800 - 64 )
            velocity.Y = -1;

        position.X = x;
        position.Y = y;

        base.Update( gameTime );
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw( GameTime gameTime )
    {
        GraphicsDevice.Clear( Color.CornflowerBlue );

        Matrix rotation = Matrix.CreateRotationY( gameTime.TotalGameTime.Seconds * 0.1f );

        // Set render states.
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[ 0 ] = SamplerState.LinearWrap;

        grid.Draw( rotation, view, projection );

        DrawModel( tank, rotation, view, projection );

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw( thumb, new Rectangle( (int)position.X, (int)position.Y, 64, 64 ), Color.White );
        spriteBatch.End();

        base.Draw( gameTime );
    }

    public void DrawModel( Model model, Matrix world, Matrix view, Matrix projection )
    {
        // Set the world matrix as the root transform of the model.
        model.Root.Transform = world;

        // Allocate the transform matrix array.
        Matrix[] boneTransforms = new Matrix[ model.Bones.Count ];

        // Look up combined bone matrices for the entire model.
        model.CopyAbsoluteBoneTransformsTo( boneTransforms );

        // Draw the model.
        foreach ( ModelMesh mesh in model.Meshes )
        {
            foreach ( BasicEffect effect in mesh.Effects )
            {
                effect.World = boneTransforms[ mesh.ParentBone.Index ];
                effect.View = view;
                effect.Projection = projection;

                //switch (lightMode)
                //{
                //    case LightingMode.NoLighting:
                //        effect.LightingEnabled = false;
                //        break;

                //    case LightingMode.OneVertexLight:
                //        effect.EnableDefaultLighting();
                //        effect.PreferPerPixelLighting = false;
                //        effect.DirectionalLight1.Enabled = false;
                //        effect.DirectionalLight2.Enabled = false;
                //        break;

                //    case LightingMode.ThreeVertexLights:
                //effect.EnableDefaultLighting();
                //effect.PreferPerPixelLighting = false;
                //        break;

                //    case LightingMode.ThreePixelLights:
                //        effect.EnableDefaultLighting();
                //        effect.PreferPerPixelLighting = true;
                //        break;
                //}

                effect.SpecularColor = new Vector3( 0.8f, 0.8f, 0.6f );
                effect.SpecularPower = 16;
                effect.TextureEnabled = true;
            }

            mesh.Draw();
        }
    }
}

答案 3 :(得分:0)

因此,经过一些测试后,看起来切换全屏会丢失顶点缓冲区。也就是说, my 缓冲区仍然存在,但它不再连接到设备。当我从我的Update函数中取出这一行并将其添加到我的Draw函数时,一切正常:

    graphics.GraphicsDevice.SetVertexBuffer(gb.vb, 0);

奇怪的是,索引缓冲区似乎没有受到影响。

我仍然不明白为什么会出现这种情况,因为我无法在任何地方找到引用此现象。我甚至不知道这是否是我的配置特有的,或顶点缓冲区和全屏的一般问题,或什么。如果有人有任何线索,我将不胜感激。