Beispiel #1
0
        private void initializeDeferredShading(IXNAGame _game, int backBufferWidth, int backBufferHeight)
        {
            shadowMapRT = new RenderTarget2D(_game.GraphicsDevice, shadowMapSize,
                                             shadowMapSize, 1, SurfaceFormat.Single);
            shadowMapDS = new DepthStencilBuffer(GraphicsDevice,
                                                 shadowMapSize,
                                                 shadowMapSize,
                                                 GraphicsDevice.DepthStencilBuffer.Format);

            lightRT = new RenderTarget2D(GraphicsDevice, backBufferWidth,
                                         backBufferHeight, 1, SurfaceFormat.HalfVector4, RenderTargetUsage.PreserveContents);

            deferredFinalRT = new RenderTarget2D(GraphicsDevice, backBufferWidth,
                                                 backBufferHeight, 1, SurfaceFormat.HalfVector4, RenderTargetUsage.PreserveContents);


            directionalLightShader = loadShader("DirectionalLight.fx");
            directionalLightShader.SetTechnique("Technique0");

            finalCombineEffect = loadShader("CombineFinal.fx");
            finalCombineEffect.SetTechnique("Technique1");


            pointLightShader = loadShader("PointLight.fx");
            pointLightShader.SetTechnique("Technique1");


            spotLightShader = loadShader("SpotLight.fx");
            spotLightShader.SetTechnique("Technique1");

            shadowMapShader = loadShader("ShadowMap.fx");
        }
Beispiel #2
0
        public override void Initialize()
        {
            base.Initialize();

            bool isDepthStencilAsShaderResourceRequired = RenderSystem.ConfigContext.RenderPassPlugins.Any(plugin => plugin.Value.Tags.Get(RenderTargetKeys.RequireDepthStencilShaderResource));

            // By default, the MainPlugin is using the back buffer as the render target
            RenderTarget = GraphicsDevice.BackBuffer;

            // Create depth stencil
#if SILICONSTUDIO_XENKO_GRAPHICS_API_OPENGLES
            var depthStencilFormat = PixelFormat.D16_UNorm;
#else
            var depthStencilFormat = PixelFormat.D24_UNorm_S8_UInt;
#endif

            if (GraphicsDevice.DepthStencilBuffer != null)
            {
                DepthStencil = GraphicsDevice.DepthStencilBuffer;
            }
            else
            {
                var depthStencil = Texture.New2D(GraphicsDevice, RenderTarget.Width, RenderTarget.Height, depthStencilFormat, TextureFlags.DepthStencil | (isDepthStencilAsShaderResourceRequired ? TextureFlags.ShaderResource : TextureFlags.None));
                DepthStencil = depthStencil.ToDepthStencilBuffer(false);
            }

            if (DepthStencilBuffer.IsReadOnlySupported(GraphicsDevice))
            {
                DepthStencilReadOnly = DepthStencil.Texture.ToDepthStencilBuffer(true);
            }
        }
Beispiel #3
0
        public static Texture2D CalculateShadowMapForScene(GraphicsDevice graphicsDevice, RenderTarget2D renderTarget, DepthStencilBuffer depthBuffer, Vector3 lightDirection, BoundingSphere bounds, int SceneId)
        {
            DepthStencilBuffer old = SetupShadowMap(graphicsDevice, ref renderTarget, ref depthBuffer);

            ShaderManager.SetCurrentEffect(ShaderManager.EFFECT_ID.SHADOWMAP);
            ShaderManager.SetValue("LightProj", CalcLightProjection(bounds, lightDirection, graphicsDevice.Viewport));
            ShaderManager.SetValue("LightView", Matrix.CreateLookAt(lightDirection * bounds.Radius + bounds.Center, bounds.Center, Vector3.Up));

            foreach (DrawableSceneComponent
                     dsc in ObjectManager.drawableSceneComponents[SceneId])
            {
                if (!dsc.Visible)
                {
                    continue;
                }

                if (dsc is AnimatedModel)
                {
                    dsc.DrawWithEffect(ShaderManager.EFFECT_ID.SHADOWMAP, "ShadowMapRenderAnimation");
                }
                else
                {
                    dsc.DrawWithEffect(ShaderManager.EFFECT_ID.SHADOWMAP, "ShadowMapRenderStatic");
                }
            }
            ResetGraphicsDevice(graphicsDevice, old);

            return(renderTarget.GetTexture());
        }
Beispiel #4
0
        public void TestDepthStencilBufferWithNativeReadonly()
        {
            //// Without shaders, it is difficult to check this method without accessing internals
            //// Force to create a device
            var device = GraphicsDevice.New(DeviceCreationFlags.None, GraphicsProfile.Level_11_0);

            // Check that reaonly is not supported for depth stencil buffer
            Assert.That(DepthStencilBuffer.IsReadOnlySupported(device), Is.True);

            // Check texture creation with an array of data, with usage default to later allow SetData
            var texture = Texture2D.New(device, 256, 256, PixelFormat.D32_Float, TextureFlags.ShaderResource | TextureFlags.DepthStencil);

            // Creates a new depth stencil buffer
            var depthStencilBuffer = texture.ToDepthStencilBuffer(true);

            // Clear the depth stencil buffer with a value of 0.5f, but the depth buffer is readonly
            device.Clear(depthStencilBuffer, DepthStencilClearOptions.DepthBuffer, 0.5f);

            var values = texture.GetData <float>();

            Assert.That(values.Length, Is.EqualTo(256 * 256));
            Assert.That(values[0], Is.EqualTo(0.0f));

            // Dispose the depth stencil buffer
            depthStencilBuffer.Dispose();

            device.Dispose();
        }
Beispiel #5
0
        protected void InitializeRendering(GraphicsDevice graphicsDevice)
        {
            // Get our initial render target size
            // The scaling factor doesn't seem to affect the image quality. There is no golden value for this as stated in the SDK documentation
            var renderTargetSize = HMD.GetDefaultRenderTargetSize(1.5f);

            // Create the render target texture that is shown on the HMD
            RenderTarget = RenderTarget2D.New(graphicsDevice, renderTargetSize.Width, renderTargetSize.Height, new MipMapCount(1), PixelFormat.R8G8B8A8.UNorm);

            // The created texture can have a different size due to hardware limitations so the render target size needs to be updated
            renderTargetSize.Width  = RenderTarget.Width;
            renderTargetSize.Height = RenderTarget.Height;

            DepthStencilBuffer = DepthStencilBuffer.New(graphicsDevice, renderTargetSize.Width, renderTargetSize.Height, DepthFormat.Depth32, true);

            // Compute the virtual cameras' viewports
            EyeViewport[0] = new Rect(0, 0, renderTargetSize.Width / 2, renderTargetSize.Height);
            EyeViewport[1] = new Rect((renderTargetSize.Width + 1) / 2, 0, EyeViewport[0].Width, EyeViewport[0].Height);

            // Create HMD's eye texture data
            EyeTextureData = new D3D11TextureData[2];
            EyeTextureData[0].Header.API            = RenderAPIType.D3D11;
            EyeTextureData[0].Header.TextureSize    = renderTargetSize;
            EyeTextureData[0].Header.RenderViewport = EyeViewport[0];
            EyeTextureData[0].pTexture = ((SharpDX.Direct3D11.Texture2D)RenderTarget).NativePointer;
            EyeTextureData[0].pSRView  = ((ShaderResourceView)RenderTarget).NativePointer;
            // Right eye holds the same values except for the viewport
            EyeTextureData[1] = EyeTextureData[0];
            EyeTextureData[1].Header.RenderViewport = EyeViewport[1];
        }
        protected override async Task LoadContent()
        {
            await base.LoadContent();

            var view       = Matrix.LookAtRH(new Vector3(2, 2, 2), new Vector3(0, 0, 0), Vector3.UnitY);
            var projection = Matrix.PerspectiveFovRH((float)Math.PI / 4.0f, (float)GraphicsDevice.BackBuffer.Width / GraphicsDevice.BackBuffer.Height, 0.1f, 100.0f);

            worldViewProjection = Matrix.Multiply(view, projection);

            geometry     = GeometricPrimitive.Cube.New(GraphicsDevice);
            simpleEffect = new SimpleEffect(GraphicsDevice)
            {
                Texture = UVTexture
            };

            // TODO DisposeBy is not working with device reset
            offlineTarget0 = Texture2D.New(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this).ToRenderTarget().DisposeBy(this);

            offlineTarget1 = Texture2D.New(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this).ToRenderTarget().DisposeBy(this);
            offlineTarget2 = Texture2D.New(GraphicsDevice, 512, 512, PixelFormat.R8G8B8A8_UNorm, TextureFlags.ShaderResource | TextureFlags.RenderTarget).DisposeBy(this).ToRenderTarget().DisposeBy(this);

            depthBuffer = Texture2D.New(GraphicsDevice, 512, 512, PixelFormat.D16_UNorm, TextureFlags.DepthStencil).DisposeBy(this).ToDepthStencilBuffer(false).DisposeBy(this);

            width  = GraphicsDevice.BackBuffer.Width;
            height = GraphicsDevice.BackBuffer.Height;
        }
Beispiel #7
0
        public HolographicGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters, HolographicSpace holographicSpace)
            : base(device, presentationParameters)
        {
            if (GraphicsDevice.RenderTargetViewAllocator.DescriptorHeap.Description.DescriptorCount != BufferCount)
            {
                GraphicsDevice.RenderTargetViewAllocator.Dispose();
                GraphicsDevice.RenderTargetViewAllocator = new DescriptorAllocator(GraphicsDevice, DescriptorHeapType.RenderTargetView, descriptorCount: BufferCount);
            }

            using (IDXGIDevice dxgiDevice = GraphicsDevice.NativeDirect3D11Device.QueryInterface <IDXGIDevice>())
            {
                IDirect3DDevice direct3DInteropDevice = Direct3DInterop.CreateDirect3DDevice(dxgiDevice);

                HolographicSpace = holographicSpace;
                HolographicSpace.SetDirect3D11Device(direct3DInteropDevice);
            }

            HolographicDisplay = HolographicDisplay.GetDefault();
            SpatialStationaryFrameOfReference = HolographicDisplay.SpatialLocator.CreateStationaryFrameOfReferenceAtCurrentLocation();

            HolographicFrame      = HolographicSpace.CreateNextFrame();
            HolographicSurface    = HolographicFrame.GetRenderingParameters(HolographicFrame.CurrentPrediction.CameraPoses[0]).Direct3D11BackBuffer;
            HolographicBackBuffer = GetHolographicBackBuffer();

            renderTarget           = CreateRenderTarget();
            direct3D11RenderTarget = CreateDirect3D11RenderTarget();

            DepthStencilBuffer.Dispose();
            DepthStencilBuffer = CreateDepthStencilBuffer();
        }
Beispiel #8
0
        public Lighting(World world)
        {
            this.world = world;

            pSunColor       = Shaders.Common.Parameters["vSunColor"];
            pSunVector      = Shaders.Common.Parameters["vSunVector"];
            pAmbientColor   = Shaders.Common.Parameters["vAmbientColor"];
            pAmbientLight   = Shaders.Common.Parameters["fAmbient"];
            pNumberOfLights = Shaders.Common.Parameters["iNumLights"];
            pSunIntensity   = Shaders.Common.Parameters["fSunIntensity"];
            pFogColor       = Shaders.Common.Parameters["vFogColor"];

            //Shaders.Common.Parameters["tCloudShadowMap"].SetValue(world.Game.Content.Load<Texture2D>(@"textures\sky\clouds"));

            Random r = new Random();

            if (lights[0] == null)
            {
                for (int i = 0; i < lights.Length; i++)
                {
                    Vector3 color = new Vector3(r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f, r.Next(1000) / 1000.0f);
                    lights[i] = new PointLight(Vector3.Zero, color, Shaders.Common.Parameters["lights"].Elements[i]);
                }
            }

            // setup the shadowmap render target
            GraphicsDevice         g  = world.GraphicsDevice;
            PresentationParameters pp = world.GraphicsDevice.PresentationParameters;
            int shadowWidth           = pp.BackBufferWidth;
            int shadowHeight          = pp.BackBufferHeight;

            smapTarget        = new RenderTarget2D(g, shadowWidth, shadowHeight, 1, SurfaceFormat.Single);
            smapStencilBuffer = new DepthStencilBuffer(g, shadowWidth, shadowHeight, g.DepthStencilBuffer.Format);
        }
Beispiel #9
0
 private void SetOutputInternal(DepthStencilBuffer depthStencilBuffer, params RenderTarget[] views)
 {
     // TODO: Do we want to handle the output the same way we handle the input textures?
     outputDepthStencilBuffer = depthStencilBuffer;
     outputRenderTargetView   = null;
     outputRenderTargetViews  = views;
 }
Beispiel #10
0
 private void SetOutputInternal(RenderTarget view, DepthStencilBuffer depthStencilBuffer)
 {
     // TODO: Do we want to handle the output the same way we handle the input textures?
     outputDepthStencilBuffer = depthStencilBuffer;
     outputRenderTargetView   = view;
     outputRenderTargetViews  = null;
 }
Beispiel #11
0
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {
                if (DepthStencilBuffer != null)
                {
                    DepthStencilBuffer.Dispose();
                }
                if (RenderTarget != null)
                {
                    RenderTarget.Dispose();
                }
                if (HMD != null)
                {
                    HMD.Dispose();
                }
                OVR.Shutdown();
            }
            _disposed = true;
        }
        public override void Initialize()
        {
            var device = DeviceService.DirectXDevice;

            if (outputRule == OutputRule.NewRenderTarget)
            {
                renderTarget           = ToDispose(RenderTarget2D.New(device, textureDescription));
                renderTarget.DebugName = string.Format("RT2D_{0}", Name);
                var depthStencilDesc = new Texture2DDescription()
                {
                    ArraySize         = 1,
                    MipLevels         = 1,
                    BindFlags         = BindFlags.DepthStencil,
                    Format            = device.DepthStencilBuffer.Format,
                    Width             = textureDescription.Width,
                    Height            = textureDescription.Height,
                    SampleDescription = textureDescription.SampleDescription,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Usage             = ResourceUsage.Default,
                    OptionFlags       = ResourceOptionFlags.None
                };

                depthStencil = ToDispose(DepthStencilBuffer.New(device, depthStencilDesc));
            }

            Output = renderTarget;
        }
Beispiel #13
0
        internal void SetGraphicsDevice(GraphicsDevice graphics)
        {
            //calculate a system wide unique id for the graphics device
#if XBOX360
            this.graphicsId = 999;
#else
            this.graphicsId = System.Diagnostics.Process.GetCurrentProcess().Id;
#endif
            this.screenFormat = graphics.PresentationParameters.BackBufferFormat;
            this.depthFormat  = graphics.PresentationParameters.EnableAutoDepthStencil ? graphics.PresentationParameters.AutoDepthStencilFormat : DepthFormat.Unknown;
            screenMultisample = graphics.PresentationParameters.MultiSampleType;

            if (graphics != this.graphics)
            {
                graphicsIndex++;
            }

            this.graphicsId ^= graphicsIndex << 16;
            this.graphicsId ^= (int)(DateTime.Now.Ticks & 0xFFFF);

            //directly accessing graphics.DepthStencilBuffer will memory leak.. so it's only used here
            this.defaultDepthStencil = graphics.DepthStencilBuffer;
            this.initalised          = true;
            this.graphics            = graphics;

            this.windowWidth  = graphics.PresentationParameters.BackBufferWidth;
            this.windowHeight = graphics.PresentationParameters.BackBufferHeight;
        }
        public void Draw(GameTime gameTime)
        {
            ICamera cameraBackup = game.Renderer.Camera;

            game.Renderer.Camera = scene.Camera;

            game.Graphics.Device.SetRenderTarget(0, renderTarget);

            DepthStencilBuffer depthStencilBufferBackup = game.Graphics.Device.DepthStencilBuffer;

            if (depthStencilBuffer != null)
            {
                game.Graphics.Device.DepthStencilBuffer = depthStencilBuffer;
            }

            game.Graphics.Device.Clear(ClearOptions.DepthBuffer, Color.White, 1.0f, 0);

            OnDrawBegin();

            scene.Draw(gameTime);

            OnDrawEnd();

            if (depthStencilBuffer != null)
            {
                game.Graphics.Device.DepthStencilBuffer = depthStencilBufferBackup;
            }

            game.Graphics.Device.SetRenderTarget(0, null);

            game.Renderer.Camera = cameraBackup;

            renderedAtLeastOnce = true;
        }
Beispiel #15
0
 public void Shutdown()
 {
     DepthStencilView?.Dispose();
     DepthStencilView = null;
     DepthStencilBuffer?.Dispose();
     DepthStencilBuffer = null;
     for (int i = 0; i < BUFFER_COUNT; i++)
     {
         ShaderResourceViewArray[i]?.Dispose();
         ShaderResourceViewArray[i] = null;
     }
     ShaderResourceViewArray = null;
     for (int i = 0; i < BUFFER_COUNT; i++)
     {
         RenderTargetViewArray[i]?.Dispose();
         RenderTargetViewArray[i] = null;
     }
     RenderTargetViewArray = null;
     for (int i = 0; i < BUFFER_COUNT; i++)
     {
         RenderTargetTexture2DArray[i]?.Dispose();
         RenderTargetTexture2DArray[i] = null;
     }
     RenderTargetTexture2DArray = null;
 }
        public RenderTarget2DAdapter(ICanyonShooterGame game, int width, int height, int numberLevels, SurfaceFormat format, RenderTargetUsage usage, DepthFormat depthFormat)
        {
            this.game = game;
            CreateRenderTarget(format, width, height, numberLevels, usage);

            depthStencilBuffer = new DepthStencilBuffer(game.Graphics.Device, width, height, depthFormat, MultiSampleType.None, 0);
        }
Beispiel #17
0
 public void ShutDown()
 {
     SwapChain?.SetFullscreenState(false, null);
     AlphaEnableBlendingState?.Dispose();
     AlphaEnableBlendingState = null;
     AlphaDisableBlendingState?.Dispose();
     AlphaDisableBlendingState = null;
     DepthDisabledStencilState?.Dispose();
     DepthDisabledStencilState = null;
     RasterState?.Dispose();
     RasterState = null;
     RasterStateNoCulling?.Dispose();
     RasterStateNoCulling = null;
     RasterStateWirefram?.Dispose();
     RasterStateWirefram = null;
     DepthStencilView?.Dispose();
     DepthStencilView = null;
     DepthStencilState?.Dispose();
     DepthStencilState = null;
     DepthStencilBuffer?.Dispose();
     DepthStencilBuffer = null;
     RenderTargetView?.Dispose();
     RenderTargetView = null;
     DeviceContext?.Dispose();
     DeviceContext = null;
     Device?.Dispose();
     Device = null;
     SwapChain?.Dispose();
     SwapChain = null;
 }
        public void Render(GraphicsDevice gd)
        {
            DepthStencilBuffer buff = gd.DepthStencilBuffer;

            gd.DepthStencilBuffer = null;
            UpdatePartcles(gd);
            gd.DepthStencilBuffer = buff;


            _renderEffect.Parameters["View"].SetValue(Matrix.Identity);
            _renderEffect.Parameters["Projection"].SetValue(_proj);
            _renderEffect.Parameters["World"].SetValue(Matrix.Identity);
            _renderEffect.Parameters["PositionsTexture"].SetValue(_positions[_currentTargetIn].GetTexture());
            _renderEffect.Parameters["ParticleSize"].SetValue(2);

            gd.VertexDeclaration = _dec;

            _renderEffect.Begin();
            gd.RenderState.AlphaBlendEnable = true;
            //gd.Clear(Color.Black);

            foreach (EffectPass pass in _renderEffect.CurrentTechnique.Passes)
            {
                pass.Begin();
                gd.Textures[0] = _particleTexture;
                gd.DrawUserPrimitives(PrimitiveType.PointList, _verts, 0, _maxParticles);
                pass.End();
            }
            _renderEffect.End();

            int tmp = _currentTargetOut;

            _currentTargetOut = _currentTargetIn;
            _currentTargetIn  = tmp;
        }
Beispiel #19
0
        /// <summary>
        /// Draws the gameplay scene.
        /// </summary>
        private void DrawGameplayScene()
        {
            // Render explosions to texture
            if (renderTarget != null && stampSpriteList.Count > 0)
            {
                device.SetRenderTarget(0, renderTarget);
                DepthStencilBuffer old = device.DepthStencilBuffer;
                device.DepthStencilBuffer = depthStencilBuffer;
                spriteBatch.Begin(SpriteBlendMode.None, SpriteSortMode.Deferred, SaveStateMode.None);
                DrawTerrain(Model.TerrainTexture);
                foreach (StampSprite e in stampSpriteList)
                {
                    spriteBatch.Draw(e.Texture, e.Position, Color.White);
                }
                stampSpriteList.Clear();
                spriteBatch.End();

                device.SetRenderTarget(0, null);
                device.DepthStencilBuffer = old;

                Model.TerrainTexture = renderTarget.GetTexture();
            }
            device.Clear(backgroundColor);

            /* Draw background image */
            Rectangle screenRect = new Rectangle(0, 0, device.PresentationParameters.BackBufferWidth,
                                                 device.PresentationParameters.BackBufferHeight);

            spriteBatch.Begin();
            spriteBatch.Draw(Model.BackGround, screenRect, Color.White);
            spriteBatch.End();

            /* Draw terrain, entities and lines */
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None, Camera.Transform);
            DrawTerrain(Model.TerrainTexture);
            DrawEntities(Model.EntityList);
            DrawPlayerInfo(Model.PlayerList);
            DrawLines();
            spriteBatch.End();

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.None);
            DrawScores(Model.PlayerList);

            if (Model.GameOver)
            {
                //Draw end game and win notice
                Color   color        = ColorFromPlayerIndex(Model.GetWinner());
                string  gameOver     = "Game Over! Player " + Model.GetWinner() + " wins!";
                string  quit         = "Press ESC to go back to the menu.";
                Vector2 gameOverSize = Sprites.MenuRegularFont.MeasureString(gameOver);
                Vector2 quitSize     = Sprites.MenuRegularFont.MeasureString(quit);
                spriteBatch.DrawString(Sprites.MenuRegularFont, gameOver, Camera.Position - new Vector2(gameOverSize.X / 2, gameOverSize.Y), color);
                spriteBatch.DrawString(Sprites.MenuRegularFont, quit, Camera.Position - new Vector2(quitSize.X / 2, 0), color);
            }

            spriteBatch.End();

            /* Update camera */
            UpdateCamera();
        }
Beispiel #20
0
        private void GenerateExplosionMap()
        {
            GraphicsDevice     gd  = GraphicsDevice;
            DepthStencilBuffer dsb = gd.DepthStencilBuffer;

            gd.DepthStencilBuffer = null;

            gd.SetRenderTarget(0, _explosionMaps[_currentTargetOut]);
            SpriteBatch batch = PrimalDevistation.Instance.Batch;

            batch.Begin();
            batch.Draw(_explosionMaps[_currentTargetIn].GetTexture(), new Rectangle(0, 0, (int)_size.X, (int)_size.Y), Color.White);
            batch.End();

            batch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            Vector2 cam = PrimalDevistation.Instance.Camera.Position;

            for (int i = 0; i < _explosions.Count; i++)
            {
                int       size  = (int)(_explosions[i].Z);
                int       hSize = size / 2;
                Texture2D tex   = _explosionTextures[size];
                batch.Draw(tex, new Rectangle((int)(_explosions[i].X - hSize), (int)(_explosions[i].Y - hSize), size, size), Color.White);
            }
            batch.End();
            gd.SetRenderTarget(0, null);
            gd.DepthStencilBuffer = dsb;
            _explosions.Clear();

            int tmp = _currentTargetOut;

            _currentTargetOut = _currentTargetIn;
            _currentTargetIn  = tmp;
        }
Beispiel #21
0
 public void Begin(int backBufferWidth, int backBufferHeight, SurfaceFormat bufferFormat, MultiSampleType multiSampleType)
 {
     if (renderTarget == null ||
         renderTargetWidth != backBufferWidth ||
         renderTargetHeight != backBufferHeight)
     {
         if (renderTarget != null)
         {
             renderTarget.Dispose();
             depthBuffer.Dispose();
         }
         renderTarget =
             new RenderTarget2D(graphicsDevice,
                                backBufferWidth, backBufferHeight,
                                1, bufferFormat,
                                multiSampleType, 0);
         depthBuffer =
             new DepthStencilBuffer(graphicsDevice,
                                    backBufferWidth, backBufferHeight,
                                    graphicsDevice.DepthStencilBuffer.Format,
                                    multiSampleType, 0);
         renderTargetWidth  = backBufferWidth;
         renderTargetHeight = backBufferHeight;
     }
     graphicsDevice.SetRenderTarget(0, renderTarget);
     savedDepthBuffer = graphicsDevice.DepthStencilBuffer;
     graphicsDevice.DepthStencilBuffer = depthBuffer;
 }
Beispiel #22
0
        protected virtual void CreateBuffers()
        {
            if (_buffersCreated)
            {
                return;
            }

            var width  = _targetSize.Width;
            var height = _targetSize.Height;

            /*
             * Note that the front buffer doesn't need any multisampling/antialiasing (AA)
             * because all rendering is done to the back buffer, which is then copied to
             * the front buffer.  This works out well because D3DImage can only use AA with
             * an IDirect3DDevice9Ex, and XNA only supports IDirect3DDevice9.
             */
            var device = Graphics.GraphicsDevice;

            if (device == null)
            {
                return;
            }

            _frontBuffer = new RenderTarget2D(
                device,
                width,
                height,
                1,
                device.PresentationParameters.BackBufferFormat,
                MultiSampleType.None,
                0);

            _backBuffer = new RenderTarget2D(
                device,
                width,
                height,
                1,
                device.PresentationParameters.BackBufferFormat,
                device.PresentationParameters.MultiSampleType,
                device.PresentationParameters.MultiSampleQuality);

            _frontBufferPointer = GetRenderTargetPointer(_frontBuffer);

            if (GraphicsOptions.EnableDepthStencil)
            {
                _depthStencilBuffer = new DepthStencilBuffer(
                    device,
                    width,
                    height,
                    device.DepthStencilBuffer.Format,
                    device.DepthStencilBuffer.MultiSampleType,
                    device.DepthStencilBuffer.MultiSampleQuality);

                _deviceDepthStencilBuffer = device.DepthStencilBuffer;

                device.DepthStencilBuffer = _depthStencilBuffer;
            }

            _buffersCreated = true;
        }
        public void ShutDown()
        {
            // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception.
            SwapChain?.SetFullscreenState(false, null);

            // Dispose of all objects.
            DepthDisabledStencilState?.Dispose();
            DepthDisabledStencilState = null;
            RasterState?.Dispose();
            RasterState = null;
            DepthStencilView?.Dispose();
            DepthStencilView = null;
            DepthStencilState?.Dispose();
            DepthStencilState = null;
            DepthStencilBuffer?.Dispose();
            DepthStencilBuffer = null;
            RenderTargetView?.Dispose();
            RenderTargetView = null;
            DeviceContext?.Dispose();
            DeviceContext = null;
            Device?.Dispose();
            Device = null;
            SwapChain?.Dispose();
            SwapChain = null;
        }
Beispiel #24
0
 public RenderTargetState(GraphicsDevice GraphicsDevice, int renderTargetIndex)
 {
     this.GraphicsDevice = GraphicsDevice;
     RenderTarget        = (RenderTarget2D)GraphicsDevice.GetRenderTarget(renderTargetIndex);
     DepthBuffer         = GraphicsDevice.DepthStencilBuffer;
     CreatedBuffers      = false;
 }
Beispiel #25
0
        /// <summary>
        /// Event handler called when the graphics device is reset
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        private void CreateDepthBuffer(object sender, EventArgs e)
        {
            int bbw = mGraphics.GraphicsDevice.PresentationParameters.BackBufferWidth;
            int bbh = mGraphics.GraphicsDevice.PresentationParameters.BackBufferHeight;

            mDepthBuffer = new DepthStencilBuffer(mGraphics.GraphicsDevice, bbw, bbh,
                                                  mGraphics.GraphicsDevice.DepthStencilBuffer.Format);
        }
Beispiel #26
0
        /// <summary>
        /// Sets the render target outputs.
        /// </summary>
        /// <param name="depthStencilBuffer">The depth stencil buffer.</param>
        /// <param name="views">The render target output views.</param>
        /// <returns>PostEffectBase.</returns>
        /// <exception cref="System.ArgumentNullException">views</exception>
        public void SetOutput(DepthStencilBuffer depthStencilBuffer, params RenderTarget[] views)
        {
            if (views == null)
            {
                throw new ArgumentNullException("views");
            }

            SetOutputInternal(depthStencilBuffer, views);
        }
        /// <summary>
        /// This is where it all happens. Grabs a scene that has already been rendered,
        /// and uses postprocess magic to add a glowing bloom effect over the top of it.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            DepthStencilBuffer oldBuffer = GraphicsDevice.DepthStencilBuffer;

            GraphicsDevice.DepthStencilBuffer = null;
            // Resolve the scene into a texture, so we can
            // use it as input data for the bloom processing.
            GraphicsDevice.ResolveBackBuffer(resolveTarget);

            // Pass 1: draw the scene into rendertarget 1, using a
            // shader that extracts only the brightest parts of the image.
            bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
                Settings.BloomThreshold);

            DrawFullscreenQuad(resolveTarget, renderTarget1,
                               bloomExtractEffect,
                               IntermediateBuffer.PreBloom);

            // Pass 2: draw from rendertarget 1 into rendertarget 2,
            // using a shader to apply a horizontal gaussian blur filter.
            SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);

            DrawFullscreenQuad(renderTarget1.GetTexture(), renderTarget2,
                               gaussianBlurEffect,
                               IntermediateBuffer.BlurredHorizontally);

            // Pass 3: draw from rendertarget 2 back into rendertarget 1,
            // using a shader to apply a vertical gaussian blur filter.
            SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);

            DrawFullscreenQuad(renderTarget2.GetTexture(), renderTarget1,
                               gaussianBlurEffect,
                               IntermediateBuffer.BlurredBothWays);

            // Pass 4: draw both rendertarget 1 and the original scene
            // image back into the main backbuffer, using a shader that
            // combines them to produce the final bloomed result.
            GraphicsDevice.SetRenderTarget(0, null);

            EffectParameterCollection parameters = bloomCombineEffect.Parameters;

            parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
            parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
            parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
            parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);

            GraphicsDevice.Textures[1] = resolveTarget;

            Viewport viewport = GraphicsDevice.Viewport;

            DrawFullscreenQuad(renderTarget1.GetTexture(),
                               viewport.Width, viewport.Height,
                               bloomCombineEffect,
                               IntermediateBuffer.FinalResult);

            GraphicsDevice.DepthStencilBuffer = oldBuffer;
        }
Beispiel #28
0
        /**
         * DrawableGameComponent
         */
        public override void LoadContent()
        {
            heightmap = ResourceMgr.Instance.Game.Content.Load <Texture2D>("Ice/height_map");

            buildGeometry();

            vertex_buffer = new VertexBuffer(ResourceMgr.Instance.Game.GraphicsDevice, VertexCount * VertexData.SizeInBytes, BufferUsage.WriteOnly);
            vertex_buffer.SetData(vertex_data);

            index_buffer = new IndexBuffer(ResourceMgr.Instance.Game.GraphicsDevice, typeof(short), IndexCount, BufferUsage.WriteOnly);
            index_buffer.SetData(vertex_indices);

            vertex_declaration = new VertexDeclaration(ResourceMgr.Instance.Game.GraphicsDevice, VertexData.VertexElements);

            particle_vertex_declaration = new VertexDeclaration(ResourceMgr.Instance.Game.GraphicsDevice, ParticleData.VertexElements);

            effect = ResourceMgr.Instance.Game.Content.Load <Effect>("Ice/Ice");
            effect.Parameters["low_color"].SetValue(low_color);
            effect.Parameters["high_color"].SetValue(high_color);
            effect.Parameters["height_scale"].SetValue(height_scale);

            temporaryRT = new RenderTarget2D(ResourceMgr.Instance.Game.GraphicsDevice, particle_count, particle_count, 1, SurfaceFormat.Vector4,
                                             ResourceMgr.Instance.Game.GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            positionRT = new RenderTarget2D(ResourceMgr.Instance.Game.GraphicsDevice, particle_count, particle_count, 1, SurfaceFormat.Vector4,
                                            ResourceMgr.Instance.Game.GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            velocityRT = new RenderTarget2D(ResourceMgr.Instance.Game.GraphicsDevice, particle_count, particle_count, 1, SurfaceFormat.Vector4,
                                            ResourceMgr.Instance.Game.GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            simulationDepthBuffer = new DepthStencilBuffer(ResourceMgr.Instance.Game.GraphicsDevice, particle_count, particle_count, ResourceMgr.Instance.Game.GraphicsDevice.DepthStencilBuffer.Format,
                                                           ResourceMgr.Instance.Game.GraphicsDevice.PresentationParameters.MultiSampleType, 0);
            spriteBatch = new SpriteBatch(ResourceMgr.Instance.Game.GraphicsDevice);

            physics_effect = ResourceMgr.Instance.Game.Content.Load <Effect>("Ice/SnowPhysics");
            physics_effect.Parameters["windStrength"].SetValue(1.0f * 5.0f);
            physics_effect.Parameters["windDirection"].SetValue(new Vector4(-0.5f, -2.0f, 0.1f, 0.0f));

            Random rand = new Random();

            random_texture = new Texture2D(ResourceMgr.Instance.Game.GraphicsDevice, particle_count, particle_count, 1, TextureUsage.None, SurfaceFormat.Vector4);
            Vector4[] pointsarray = new Vector4[particle_count * particle_count];
            for (int i = 0; i < particle_count * particle_count; i++)
            {
                pointsarray[i]   = new Vector4();
                pointsarray[i].X = (float)rand.NextDouble() - 0.5f;
                pointsarray[i].Y = (float)rand.NextDouble() - 0.5f;
                pointsarray[i].Z = (float)rand.NextDouble() - 0.5f;
                pointsarray[i].W = (float)rand.NextDouble() - 0.5f;
            }
            random_texture.SetData <Vector4>(pointsarray);


            snow_effect = ResourceMgr.Instance.Game.Content.Load <Effect>("Ice/SnowPointSprite");
            snow_effect.Parameters["sprite_map"].SetValue(ResourceMgr.Instance.Game.Content.Load <Texture2D>("Ice/snow"));

            reset_physics = true;

            base.LoadContent();
        }
Beispiel #29
0
 /// <summary>
 /// Creates full view render targets on demand.
 /// </summary>
 public void CreateFullViewRenderTarget()
 {
     // TODO: check previous status to dispose the rendertarget?
     if (textureCube != null)
     {
         RenderTarget = textureCube.ToRenderTarget(ViewType.Full, 0, 0);
         DepthStencil = Texture2D.New(textureCube.GraphicsDevice, Size, Size, PixelFormat.D24_UNorm_S8_UInt, TextureFlags.DepthStencil, 6).ToDepthStencilBuffer(false);
     }
 }
Beispiel #30
0
        /// <summary>
        /// Sets the render target output.
        /// </summary>
        /// <param name="view">The render target output view.</param>
        /// <param name="depthStencilBuffer">The depth stencil buffer.</param>
        /// <exception cref="System.ArgumentNullException">view</exception>
        public void SetOutput(RenderTarget view, DepthStencilBuffer depthStencilBuffer = null)
        {
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            SetOutputInternal(view, depthStencilBuffer);
        }