summaryrefslogtreecommitdiff
path: root/Plugins/MonoGame.Extended/source/MonoGame.Extended.Graphics/RenderTarget2DExtensions.cs
blob: f09060380a7f0faf7de46418e5045138f0c7f924 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace MonoGame.Extended.Graphics
{
    public static class RenderTarget2DExtensions
    {
        public static IDisposable BeginDraw(this RenderTarget2D renderTarget, GraphicsDevice graphicsDevice,
            Color backgroundColor)
        {
            return new RenderTargetOperation(renderTarget, graphicsDevice, backgroundColor);
        }

        private class RenderTargetOperation : IDisposable
        {
            private readonly GraphicsDevice _graphicsDevice;
            private readonly RenderTargetUsage _previousRenderTargetUsage;
            private readonly Viewport _viewport;

            public RenderTargetOperation(RenderTarget2D renderTarget, GraphicsDevice graphicsDevice,
                Color backgroundColor)
            {
                _graphicsDevice = graphicsDevice;
                _viewport = _graphicsDevice.Viewport;
                _previousRenderTargetUsage = _graphicsDevice.PresentationParameters.RenderTargetUsage;

                _graphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
                _graphicsDevice.SetRenderTarget(renderTarget);
                _graphicsDevice.Clear(backgroundColor);
            }

            public void Dispose()
            {
                _graphicsDevice.SetRenderTarget(null);
                _graphicsDevice.PresentationParameters.RenderTargetUsage = _previousRenderTargetUsage;
                _graphicsDevice.Viewport = _viewport;
            }
        }
    }
}