private void BuildDescriptors()
        {
            // Create SRV to resource so we can sample the shadow map in a shader program.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = D3DUtil.DefaultShader4ComponentMapping,
                Format    = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource
                {
                    MostDetailedMip     = 0,
                    MipLevels           = 1,
                    ResourceMinLODClamp = 0.0f,
                    PlaneSlice          = 0
                }
            };

            _device.CreateShaderResourceView(Resource, srvDesc, _cpuSrv);

            // Create DSV to resource so we can render to the shadow map.
            var dsvDesc = new DepthStencilViewDescription
            {
                Flags     = DepthStencilViewFlags.None,
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D24_UNorm_S8_UInt,
                Texture2D = new DepthStencilViewDescription.Texture2DResource
                {
                    MipSlice = 0
                }
            };

            _device.CreateDepthStencilView(Resource, dsvDesc, _cpuDsv);
        }
        private void CreateDepthStencilView(int width, int height, Device device)
        {
            // Create Depth Stencil
            Texture2DDescription depthTexDescription;

            depthTexDescription.Width     = width;
            depthTexDescription.Height    = height;
            depthTexDescription.MipLevels = 1;
            depthTexDescription.ArraySize = 1;
            depthTexDescription.Format    = Format.D24_UNorm_S8_UInt;
            depthTexDescription.SampleDescription.Count   = MSAASampleCount;
            depthTexDescription.SampleDescription.Quality = 0;
            depthTexDescription.Usage          = ResourceUsage.Default;
            depthTexDescription.BindFlags      = BindFlags.DepthStencil;
            depthTexDescription.CpuAccessFlags = CpuAccessFlags.None;
            depthTexDescription.OptionFlags    = ResourceOptionFlags.None;

            DepthStencilTexture?.Dispose();
            DepthStencilTexture = new Texture2D(device, depthTexDescription);

            DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = MSAASampleCount > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
                Texture2D = { MipSlice = 0 }
            };

            DepthStencilView?.Dispose();
            DepthStencilView = new DepthStencilView(device, DepthStencilTexture, depthViewDesc);
        }
Beispiel #3
0
        public D3DDepthStencil CreateDepthStencil(int width, int height)
        {
            var description = new Texture2DDescription();

            description.Width                   = width;
            description.Height                  = height;
            description.ArraySize               = 1;
            description.BindFlags               = BindFlags.DepthStencil | BindFlags.ShaderResource;
            description.CpuAccessFlags          = CpuAccessFlags.None;
            description.MipLevels               = 1;
            description.OptionFlags             = ResourceOptionFlags.None;
            description.SampleDescription.Count = 1;
            description.Usage                   = ResourceUsage.Default;
            description.Format                  = Format.R32_Typeless;

            var texture          = new Texture2D(device, description);
            var depthDescription = new DepthStencilViewDescription();

            depthDescription.Dimension          = DepthStencilViewDimension.Texture2D;
            depthDescription.Flags              = DepthStencilViewFlags.None;
            depthDescription.Format             = Format.D32_Float;
            depthDescription.Texture2D.MipSlice = 0;
            var depthStencil = new DepthStencilView(device, texture, depthDescription);

            var srvDescription = new ShaderResourceViewDescription();

            srvDescription.Format                    = Format.R32_Float;
            srvDescription.Dimension                 = ShaderResourceViewDimension.Texture2D;
            srvDescription.Texture2D.MipLevels       = 1;
            srvDescription.Texture2D.MostDetailedMip = 0;
            var depthSrv = new ShaderResourceView(device, texture, srvDescription);

            return(new D3DDepthStencil(texture, depthStencil, depthSrv));
        }
Beispiel #4
0
        void OnResize()
        {
            Helpers.Dispose(ref depthBuffer);
            Helpers.Dispose(ref dsv);
            Helpers.Dispose(ref colorBuffer);
            Helpers.Dispose(ref rtv);

            var resolution = Surface.Resolution;

            TextBatcher.Resolution   = resolution;
            UILineBatcher.Resolution = resolution;

            depthBuffer = new Texture2D(Surface.Device, new Texture2DDescription
            {
                Format            = Format.R32_Typeless,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = resolution.X,
                Height            = resolution.Y,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });
            depthBuffer.DebugName = "Depth Buffer";

            var depthStencilViewDescription = new DepthStencilViewDescription
            {
                Flags     = DepthStencilViewFlags.None,
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float,
                Texture2D = { MipSlice = 0 }
            };

            dsv           = new DepthStencilView(Surface.Device, depthBuffer, depthStencilViewDescription);
            dsv.DebugName = "Depth DSV";

            //Using a 64 bit texture in the demos for lighting is pretty silly. But we gon do it.
            colorBuffer = new Texture2D(Surface.Device, new Texture2DDescription
            {
                Format            = Format.R16G16B16A16_Float,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = resolution.X,
                Height            = resolution.Y,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });
            colorBuffer.DebugName = "Color Buffer";

            srv           = new ShaderResourceView(Surface.Device, colorBuffer);
            srv.DebugName = "Color SRV";

            rtv           = new RenderTargetView(Surface.Device, colorBuffer);
            rtv.DebugName = "Color RTV";
        }
        private void InitializeDepthStencil(uint nWidth, uint nHeight)
        {
            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width             = nWidth,
                Height            = nHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D16UNorm,
                SampleDescription = new SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                BindingOptions = BindingOptions.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format        = descDepth.Format,
                ViewDimension =
                    DepthStencilViewDimension.
                    Texture2D
            };

            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);
        }
Beispiel #6
0
        protected virtual bool BuildRenderTarget()
        {
            var renderTargetResourceChanged = ResourceManager.ValidateRenderTargetResource(ref _renderTargetResource, OperatorPart, D3DDevice.Device,
                                                                                           (int)_usedViewport.Width, (int)_usedViewport.Height);

            if (renderTargetResourceChanged)
            {
                Utilities.DisposeObj(ref _renderTargetView);
                _renderTargetView = new RenderTargetView(D3DDevice.Device, _renderTargetResource.Texture);
            }

            var depthStencilResourceChanged = false;

            if (NeedsDepth)
            {
                depthStencilResourceChanged = ResourceManager.ValidateDepthStencilResource(ref _renderDepthResource, OperatorPart, D3DDevice.Device,
                                                                                           (int)_usedViewport.Width, (int)_usedViewport.Height);
                if (depthStencilResourceChanged)
                {
                    Utilities.DisposeObj(ref _renderTargetDepthView);

                    var depthViewDesc = new DepthStencilViewDescription
                    {
                        Format    = Format.D32_Float,
                        Dimension = DepthStencilViewDimension.Texture2D
                    };

                    _renderTargetDepthView = new DepthStencilView(D3DDevice.Device, _renderDepthResource.Texture, depthViewDesc);
                }
            }

            return(renderTargetResourceChanged || depthStencilResourceChanged);
        }
Beispiel #7
0
        //============================================================
        // 创建缓冲
        //============================================================
        public void Create(int width, int height)
        {
            // 设置信息
            _size.Set(width, height);
            // 创建纹理资源
            Texture2DDescription description = new Texture2DDescription {
                Format            = Format.D32_Float,
                Width             = width,
                Height            = height,
                ArraySize         = 1,
                MipLevels         = 1,
                BindFlags         = BindFlags.DepthStencil,
                Usage             = ResourceUsage.Default,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
            };

            _nativeTexture = new Texture2D(_device.NativeAdapter, description);
            // 创建渲染目标资源
            DepthStencilViewDescription depthDescription = new DepthStencilViewDescription()
            {
                Format    = description.Format,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice  = 0,
            };

            _nativeDepth = new DepthStencilView(_device.NativeAdapter, _nativeTexture, depthDescription);
        }
        public DX11CubeDepthStencil(DX11RenderContext context, int size, SampleDescription sd, Format format)
        {
            this.context = context;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = 6,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = size,
                Width = size,
                OptionFlags = ResourceOptionFlags.TextureCube,
                SampleDescription = sd,
                Usage = ResourceUsage.Default,
                MipLevels = 1
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            this.desc = texBufferDesc;

            //Create faces SRV/RTV
            this.SliceDSV = new DX11SliceDepthStencil[6];

            ShaderResourceViewDescription svd = new ShaderResourceViewDescription()
            {
                Dimension = ShaderResourceViewDimension.TextureCube,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                MipLevels = 1,
                MostDetailedMip = 0,
                First2DArrayFace = 0
            };

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize= 6,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                FirstArraySlice = 0,
                Format = DepthFormatsHelper.GetDepthFormat(format),
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            if (context.IsFeatureLevel11)
            {
                dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

                this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);
            }

            this.SRV = new ShaderResourceView(context.Device, this.Resource, svd);

            for (int i = 0; i < 6; i++)
            {
                this.SliceDSV[i] = new DX11SliceDepthStencil(context, this, i, DepthFormatsHelper.GetDepthFormat(format));
            }
        }
Beispiel #9
0
        public void InitDepthStencil()
        {
            var depthStencilTextureDesc = new Texture2DDescription
            {
                Width             = FormObject.ClientSize.Width,
                Height            = FormObject.ClientSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };
            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                Format    = depthStencilTextureDesc.Format,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice  = 0
            };

            _depthStencilTexture = new Texture2D(_device, depthStencilTextureDesc);
            _depthStencilView    = new DepthStencilView(_device, _depthStencilTexture, depthStencilViewDesc);
            _deviceContext.OutputMerger.SetTargets(_depthStencilView, _renderTargetView);
        }
Beispiel #10
0
        private void CreateRenderTargets(int width, int height)
        {
            var backBuffer = Resource.FromSwapChain <Texture2D>(SwapChain, 0);

            RenderTargetView = new RenderTargetView(Device, backBuffer);

            var depthDescription = new Texture2DDescription {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.D32_Float,
                Height            = backBuffer.Description.Height,
                Width             = backBuffer.Description.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(4, 4),
                Usage             = ResourceUsage.Default
            };

            var depthBuffer = new Texture2D(Device, depthDescription);

            var depthStencilViewDescription = new DepthStencilViewDescription {
                Format    = depthDescription.Format,
                Flags     = DepthStencilViewFlags.None,
                Dimension = depthDescription.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
                MipSlice  = 0
            };

            DepthStencilView = new DepthStencilView(Device, depthBuffer, depthStencilViewDescription);

            Device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0f, 1f));

            backBuffer.Dispose();
            depthBuffer.Dispose();
        }
Beispiel #11
0
        public D3D11Framebuffer(Device device, ref FramebufferDescription description)
            : base(description.DepthTarget, description.ColorTargets)
        {
            if (description.DepthTarget != null)
            {
                D3D11Texture d3dDepthTarget         = Util.AssertSubtype <Texture, D3D11Texture>(description.DepthTarget);
                DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription()
                {
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Format    = D3D11Formats.GetDepthFormat(d3dDepthTarget.Format)
                };
                DepthStencilView = new DepthStencilView(device, d3dDepthTarget.DeviceTexture, dsvDesc);
            }

            if (description.ColorTargets != null && description.ColorTargets.Length > 0)
            {
                RenderTargetViews = new RenderTargetView[description.ColorTargets.Length];
                for (int i = 0; i < RenderTargetViews.Length; i++)
                {
                    D3D11Texture d3dColorTarget         = Util.AssertSubtype <Texture, D3D11Texture>(description.ColorTargets[i]);
                    RenderTargetViewDescription rtvDesc = new RenderTargetViewDescription
                    {
                        Format    = D3D11Formats.ToDxgiFormat(d3dColorTarget.Format, false),
                        Dimension = RenderTargetViewDimension.Texture2D,
                    };
                    RenderTargetViews[i] = new RenderTargetView(device, d3dColorTarget.DeviceTexture, rtvDesc);
                }
            }
            else
            {
                RenderTargetViews = Array.Empty <RenderTargetView>();
            }
        }
Beispiel #12
0
        private DepthStencilView GetDepthStencilView(out bool hasStencil)
        {
            hasStencil = false;
            if (!IsDepthStencil)
            {
                return(null);
            }

            // Check that the format is supported
            if (ComputeShaderResourceFormatFromDepthFormat(ViewFormat) == PixelFormat.None)
            {
                throw new NotSupportedException("Depth stencil format [{0}] not supported".ToFormat(ViewFormat));
            }

            // Setup the HasStencil flag
            hasStencil = IsStencilFormat(ViewFormat);

            // Create a Depth stencil view on this texture2D
            var depthStencilViewDescription = new DepthStencilViewDescription
            {
                Format = ComputeDepthViewFormatFromTextureFormat(ViewFormat),
                Flags  = DepthStencilViewFlags.None,
            };

            if (ArraySize > 1)
            {
                depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DArray;
                depthStencilViewDescription.Texture2DArray.ArraySize       = ArraySize;
                depthStencilViewDescription.Texture2DArray.FirstArraySlice = 0;
                depthStencilViewDescription.Texture2DArray.MipSlice        = 0;
            }
            else
            {
                depthStencilViewDescription.Dimension          = DepthStencilViewDimension.Texture2D;
                depthStencilViewDescription.Texture2D.MipSlice = 0;
            }

            if (MultisampleCount > MultisampleCount.None)
            {
                depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
            }

            if (IsDepthStencilReadOnly)
            {
                if (!IsDepthStencilReadOnlySupported(GraphicsDevice))
                {
                    throw new NotSupportedException("Cannot instantiate ReadOnly DepthStencilBuffer. Not supported on this device.");
                }

                // Create a Depth stencil view on this texture2D
                depthStencilViewDescription.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (HasStencil)
                {
                    depthStencilViewDescription.Flags |= DepthStencilViewFlags.ReadOnlyStencil;
                }
            }

            return(new DepthStencilView(GraphicsDevice.NativeDevice, NativeResource, depthStencilViewDescription));
        }
Beispiel #13
0
        private void InitD3D()
        {
            Texture2DDescription colordesc = new Texture2DDescription();

            colordesc.BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource;
            colordesc.Format            = Format.B8G8R8A8_UNorm;
            colordesc.Width             = Width;
            colordesc.Height            = Height;
            colordesc.MipLevels         = 1;
            colordesc.ArraySize         = 1;
            colordesc.SampleDescription = new SampleDescription(1, 0);
            colordesc.Usage             = ResourceUsage.Default;
            colordesc.OptionFlags       = ResourceOptionFlags.Shared;
            colordesc.CpuAccessFlags    = CpuAccessFlags.None;
            SharedTexture = new Texture2D(App.D3DDevice, colordesc);

            RenderTargetViewDescription rtDesc = new RenderTargetViewDescription();

            rtDesc.Format    = colordesc.Format;
            rtDesc.Dimension = RenderTargetViewDimension.Texture2D;//RenderTargetViewDimension.Texture2DMultisampled;
            rtDesc.MipSlice  = 0;
            RenderView       = new RenderTargetView(App.D3DDevice, SharedTexture, rtDesc);



            Texture2DDescription depthStencilTexDesc = new Texture2DDescription();

            depthStencilTexDesc.Width             = Width;
            depthStencilTexDesc.Height            = Height;
            depthStencilTexDesc.MipLevels         = 1;
            depthStencilTexDesc.ArraySize         = 1;
            depthStencilTexDesc.Format            = Format.R24G8_Typeless;
            depthStencilTexDesc.Usage             = ResourceUsage.Default;
            depthStencilTexDesc.SampleDescription = new SampleDescription(1, 0);
            depthStencilTexDesc.BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource;
            depthStencilTexDesc.OptionFlags       = ResourceOptionFlags.None;
            depthStencilTexDesc.CpuAccessFlags    = CpuAccessFlags.None;
            DepthStencilTexture = new Texture2D(App.D3DDevice, depthStencilTexDesc);


            DepthStencilViewDescription depthDesc = new DepthStencilViewDescription();

            depthDesc.Format    = Format.D24_UNorm_S8_UInt;
            depthDesc.Dimension = DepthStencilViewDimension.Texture2D;
            depthDesc.MipSlice  = 0;
            DepthView           = new DepthStencilView(App.D3DDevice, DepthStencilTexture, depthDesc);



            ShaderResourceViewDescription resDesc = new ShaderResourceViewDescription();

            resDesc.Format          = Format.R24_UNorm_X8_Typeless;
            resDesc.Dimension       = ShaderResourceViewDimension.Texture2D;
            resDesc.MostDetailedMip = 0;
            resDesc.MipLevels       = 1;
            DepthStencilSRV         = new ShaderResourceView(App.D3DDevice, DepthStencilTexture, resDesc);

            DepthStencilTexture.Dispose();
        }
Beispiel #14
0
        private void BuildDepthStencilView(int w, int h)
        {
            var depthBufferDesc = new Texture2DDescription()
            {
                Width             = w,
                Height            = h,
                MipLevels         = 0,
                ArraySize         = 1,
                Format            = Format.D24_UNorm_S8_UInt,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            };

            m_depthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            var depthStencilDecs = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask  = 0xFF,
                StencilWriteMask = 0xFF,
                FrontFace        = new DepthStencilOperationDescription()
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always,
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation      = StencilOperation.Keep,
                    Comparison         = Comparison.Always
                }
            };

            DepthStencilState = new DepthStencilState(Device, depthStencilDecs);
            DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

            var depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format    = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            m_DepthStencilView = new DepthStencilView(Device, m_depthStencilBuffer, depthStencilViewDesc);
            DeviceContext.OutputMerger.SetTargets(m_DepthStencilView, m_RenderTargetView);
        }
Beispiel #15
0
        /// <summary>
        /// Creates render target
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencilCube( GraphicsDevice device, DepthFormat format, int size, int samples, string debugName = "" )
            : base(device)
        {
            bool msaa	=	samples > 1;

            CheckSamplesCount( samples );

            SampleCount	=	samples;

            Format		=	format;
            SampleCount	=	samples;
            Width		=	size;
            Height		=	size;
            Depth		=	1;

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	Width;
                texDesc.Height				=	Height;
                texDesc.ArraySize			=	6;
                texDesc.BindFlags			=	BindFlags.RenderTarget | BindFlags.ShaderResource;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.TextureCube;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            texCube	=	new D3D.Texture2D( device.Device, texDesc );

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            SRV		=	new ShaderResourceView( device.Device, texCube );

            //
            //	Create surfaces :
            //
            surfaces	=	new DepthStencilSurface[ 6 ];

            for ( int face=0; face<6; face++) {

                var rtvDesc = new DepthStencilViewDescription();
                    rtvDesc.Texture2DArray.MipSlice			=	0;
                    rtvDesc.Texture2DArray.FirstArraySlice	=	face;
                    rtvDesc.Texture2DArray.ArraySize		=	1;
                    rtvDesc.Dimension						=	msaa ? DepthStencilViewDimension.Texture2DMultisampledArray : DepthStencilViewDimension.Texture2DArray;
                    rtvDesc.Format							=	Converter.ConvertToDSV( format );

                var dsv	=	new DepthStencilView( device.Device, texCube, rtvDesc );

                int subResId	=	Resource.CalculateSubResourceIndex( 0, face, 1 );

                surfaces[face]	=	new DepthStencilSurface( dsv, format, Width, Height, SampleCount );
            }
        }
Beispiel #16
0
 /// <summary>
 /// Creates the view.
 /// </summary>
 /// <param name="desc">The desc.</param>
 public void CreateView(DepthStencilViewDescription desc)
 {
     RemoveAndDispose(ref depthStencilView);
     if (resource == null)
     {
         return;
     }
     depthStencilView = Collect(new DepthStencilView(device, resource, desc));
 }
        private void PlatformConstruct(GraphicsDevice graphicsDevice, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
        {
            // Create one render target view per cube map face.
            _renderTargetViews = new RenderTargetView[6];
            for (int i = 0; i < _renderTargetViews.Length; i++)
            {
                var renderTargetViewDescription = new RenderTargetViewDescription
                {
                    Dimension      = RenderTargetViewDimension.Texture2DArray,
                    Format         = SharpDXHelper.ToFormat(preferredFormat),
                    Texture2DArray =
                    {
                        ArraySize       = 1,
                        FirstArraySlice = i,
                        MipSlice        = 0
                    }
                };

                _renderTargetViews[i] = new RenderTargetView(graphicsDevice._d3dDevice, GetTexture(), renderTargetViewDescription);
            }

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
            {
                return;
            }

            var sampleDescription = new SampleDescription(1, 0);

            if (preferredMultiSampleCount > 1)
            {
                sampleDescription.Count   = preferredMultiSampleCount;
                sampleDescription.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            var depthStencilDescription = new Texture2DDescription
            {
                Format            = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = size,
                Height            = size,
                SampleDescription = sampleDescription,
                BindFlags         = BindFlags.DepthStencil,
            };

            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, depthStencilDescription))
            {
                var depthStencilViewDescription = new DepthStencilViewDescription
                {
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Format    = SharpDXHelper.ToFormat(preferredDepthFormat),
                };
                _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer, depthStencilViewDescription);
            }
        }
Beispiel #18
0
        private DepthStencilViewDescription FillOutDSVDescription()
        {
            DepthStencilViewDescription desc = new DepthStencilViewDescription();

            desc.Flags              = DepthStencilViewFlags.None;
            desc.Format             = SharpDX.DXGI.Format.D24_UNorm_S8_UInt;
            desc.Dimension          = DepthStencilViewDimension.Texture2D;
            desc.Texture2D.MipSlice = 0;
            return(desc);
        }
Beispiel #19
0
        protected override void OnResize(System.EventArgs e)
        {
            if (SwapChain != null)
            {
                // Do things here.
                Util.ReleaseCom(ref RenderTargetView);
                Util.ReleaseCom(ref DepthStencilView);
                Util.ReleaseCom(ref DepthStencilBuffer);

                // Resize the render target
                SwapChain.ResizeBuffers(1, ClientSize.Width, ClientSize.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);
                using (var resource = SlimDX.Direct3D11.Resource.FromSwapChain <Texture2D>(SwapChain, 0))
                {
                    RenderTargetView = new RenderTargetView(Device, resource);
                }

                // Create the depth/stencil buffer and view
                var depthBufferDesc = new Texture2DDescription
                {
                    ArraySize         = 1,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    Format            = Format.D32_Float,
                    Height            = ClientSize.Height,
                    Width             = ClientSize.Width,
                    MipLevels         = 1,
                    OptionFlags       = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default
                };

                DepthStencilBuffer = new Texture2D(Device, depthBufferDesc);

                var depthStencilViewDesc = new DepthStencilViewDescription
                {
                    ArraySize       = 0,
                    Format          = Format.D32_Float,
                    Dimension       = DepthStencilViewDimension.Texture2D,
                    MipSlice        = 0,
                    Flags           = 0,
                    FirstArraySlice = 0
                };

                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

                // Set up viewport, render target (back buffer on swap chain), and render target view
                // TODO KAM: Do the viewports actually need adjusting here? Probably?
                Viewport = new Viewport(0.0f, 0.0f, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f);
                ImmediateContext.Rasterizer.SetViewports(Viewport);

                base.OnResize(e);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Creates depth stencil texture, view and shader resource with format D24S8
        /// </summary>
        /// <param name="rs"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="format"></param>
        public DepthStencil2D( GraphicsDevice device, DepthFormat format, int width, int height, int samples = 1 )
            : base(device)
        {
            CheckSamplesCount( samples );

            Width		=	width;
            Height		=	height;
            Depth		=	1;
            Format		=	format;
            SampleCount	=	samples;

            var bindFlags	=	BindFlags.DepthStencil;

            if (device.GraphicsProfile==GraphicsProfile.HiDef) {
                bindFlags	|=	BindFlags.ShaderResource;

            } else if (device.GraphicsProfile==GraphicsProfile.Reach) {
                if (samples==1) {
                    bindFlags	|=	BindFlags.ShaderResource;
                }
            }

            var	texDesc	=	new Texture2DDescription();
                texDesc.Width				=	width;
                texDesc.Height				=	height;
                texDesc.ArraySize			=	1;
                texDesc.BindFlags			=	bindFlags;
                texDesc.CpuAccessFlags		=	CpuAccessFlags.None;
                texDesc.Format				=	Converter.ConvertToTex( format );
                texDesc.MipLevels			=	1;
                texDesc.OptionFlags			=	ResourceOptionFlags.None;
                texDesc.SampleDescription	=	new DXGI.SampleDescription(samples, 0);
                texDesc.Usage				=	ResourceUsage.Default;

            var dsvDesc	=	new DepthStencilViewDescription();
                dsvDesc.Dimension			=	samples > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
                dsvDesc.Format				=	Converter.ConvertToDSV( format );
                dsvDesc.Flags				=	DepthStencilViewFlags.None;

            var srvDesc	=	new ShaderResourceViewDescription();
                srvDesc.Dimension			=	samples > 1 ? ShaderResourceViewDimension.Texture2DMultisampled : ShaderResourceViewDimension.Texture2D;
                srvDesc.Format				=	Converter.ConvertToSRV( format );
                srvDesc.Texture2D.MostDetailedMip	=	0;
                srvDesc.Texture2D.MipLevels			=	1;

            tex2D		=	new D3D.Texture2D		( device.Device, texDesc );

            var dsv		=	new DepthStencilView	( device.Device, tex2D,	dsvDesc );

            if (bindFlags.HasFlag( BindFlags.ShaderResource)) {
                SRV		=	new ShaderResourceView	( device.Device, tex2D,	srvDesc );
            }

            surface		=	new DepthStencilSurface	( dsv, format, width, height, samples );
        }
Beispiel #21
0
        void InitDevice()
        {
            // create Direct 3D device
            device    = D3DDevice.CreateDeviceAndSwapChain(renderHost.Handle);
            swapChain = device.SwapChain;

            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer <Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width             = (uint)renderHost.ActualWidth,
                Height            = (uint)renderHost.ActualHeight,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.D32Float,
                SampleDescription = new SampleDescription()
                {
                    Count   = 1,
                    Quality = 0
                },
                BindingOptions = BindingOptions.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format        = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };

            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            // bind the views to the device
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width    = (uint)renderHost.ActualWidth,
                Height   = (uint)renderHost.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };

            device.RS.Viewports = new Viewport[] { vp };
        }
        public override 数管理  数登録インスタンスを生成して返す(EffectVariable variable, エフェクト effect, int semanticIndex)
        {
            var subscriber = new RENDERDEPTHSTENCILTARGET変数();

            int    width, height, depth, mip;
            Format textureFormat, viewFormat, resourceFormat;

            テクスチャのアノテーション解析.解析する(variable, Format.D24_UNorm_S8_UInt, new Vector2(1f, 1f), false, out width, out height, out depth, out mip, out textureFormat, out viewFormat, out resourceFormat);

            // テクスチャの作成
            var tex2DDesc = new Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = textureFormat,
                Height            = height,
                Width             = width,
                MipLevels         = mip,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            subscriber._depthStencilTexture = new Texture2D(RenderContext.Instance.DeviceManager.D3DDevice, tex2DDesc);

            // レンダーリソースビューの作成
            var viewDesc = new DepthStencilViewDescription()
            {
                Format    = viewFormat,
                Dimension = DepthStencilViewDimension.Texture2D,
            };

            subscriber._depthStencilView = new DepthStencilView(RenderContext.Instance.DeviceManager.D3DDevice, subscriber._depthStencilTexture, viewDesc);

            // シェーダリソースビューの作成
            var shaderDesc = new ShaderResourceViewDescription()
            {
                Format    = resourceFormat,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0,
                },
            };

            subscriber._shaderResource = new ShaderResourceView(RenderContext.Instance.DeviceManager.D3DDevice, subscriber._depthStencilTexture, shaderDesc);


            effect.深度ステンシルビューのマップ.Add(variable.Description.Name, subscriber._depthStencilView);

            return(subscriber);
        }
        void CreateDeviceDependentResources()
        {
            SharpDX.Utilities.Dispose(ref DSSRV);
            SharpDX.Utilities.Dispose(ref DSV);
            SharpDX.Utilities.Dispose(ref DS0);
            RTs.ForEach(rt => SharpDX.Utilities.Dispose(ref rt));
            SRVs.ForEach(srv => SharpDX.Utilities.Dispose(ref srv));
            RTVs.ForEach(rtv => SharpDX.Utilities.Dispose(ref rtv));
            RTs.Clear();
            SRVs.Clear();
            RTVs.Clear();
            var texDesc = new Texture2DDescription();

            texDesc.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize         = 1;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Usage             = ResourceUsage.Default;
            texDesc.Width             = width;
            texDesc.Height            = height;
            texDesc.MipLevels         = 1;
            texDesc.SampleDescription = sampleDescription;
            bool isMSAA  = sampleDescription.Count > 1;
            var  rtvDesc = new RenderTargetViewDescription();

            rtvDesc.Dimension          = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;
            var srvDesc = new ShaderResourceViewDescription();

            srvDesc.Format                    = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
            srvDesc.Dimension                 = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels       = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            foreach (var format in RTFormats)
            {
                texDesc.Format = format;
                srvDesc.Format = format;
                rtvDesc.Format = format;
                RTs.Add(new Texture2D(device, texDesc));
                SRVs.Add(new ShaderResourceView(device, RTs.Last(), srvDesc));
                RTVs.Add(new RenderTargetView(device, RTs.Last(), rtvDesc));
            }
            texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.DepthStencil;
            texDesc.Format    = SharpDX.DXGI.Format.R32G8X24_Typeless;
            DS0            = new Texture2D(device, texDesc);
            srvDesc.Format = SharpDX.DXGI.Format.R32_Float_X8X24_Typeless;
            DSSRV          = new ShaderResourceView(device, DS0, srvDesc);
            var dsvDesc = new DepthStencilViewDescription();

            dsvDesc.Flags     = DepthStencilViewFlags.None;
            dsvDesc.Dimension = isMSAA ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
            dsvDesc.Format    = SharpDX.DXGI.Format.D32_Float_S8X24_UInt;
            DSV = new DepthStencilView(device, DS0, dsvDesc);
        }
Beispiel #24
0
            public void OnDeviceInit()
            {
                OnDeviceInitInternal();

                DepthStencilViewDescription desc = new DepthStencilViewDescription();

                desc.Format             = m_dsvFormat;
                desc.Dimension          = DepthStencilViewDimension.Texture2D;
                desc.Texture2D.MipSlice = 0;
                m_dsv           = new DepthStencilView(MyRender11.Device, m_resource, desc);
                m_dsv.DebugName = m_name;
            }
Beispiel #25
0
 public void InitializeDepthStencilViewDescription()
 {
     depthstencilviewdesc = new DepthStencilViewDescription()
     {
         Format    = Format.D24_UNorm_S8_UInt,
         Dimension = DepthStencilViewDimension.Texture2D,
         Texture2D = new DepthStencilViewDescription.Texture2DResource()
         {
             MipSlice = 0
         }
     };
 }
Beispiel #26
0
        public static DepthStencilView CreateDepthStencilView(Device device, Texture2D depthStencil, Format format, DepthStencilViewDimension viewDimension)
        {
            DepthStencilViewDescription dsvd = new DepthStencilViewDescription();

            dsvd.Format             = format;
            dsvd.Flags              = 0;
            dsvd.Dimension          = viewDimension;
            dsvd.Texture2D.MipSlice = 0;
            DepthStencilView dsv = new DepthStencilView(device, depthStencil, dsvd);

            return(dsv);
        }
            private bool CreateCubeMapResources()
            {
                if(textureDesc.Width == faceSize && cubeMap != null && !cubeMap.IsDisposed)
                {
                    return false;
                }
                textureDesc.Width = textureDesc.Height = dsvTextureDesc.Width = dsvTextureDesc.Height = FaceSize;

                RemoveAndDispose(ref cubeMap);
                cubeMap = Collect(new ShaderResourceViewProxy(Device, textureDesc));

                var srvDesc = new ShaderResourceViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = global::SharpDX.Direct3D.ShaderResourceViewDimension.TextureCube,
                    TextureCube = new ShaderResourceViewDescription.TextureCubeResource() { MostDetailedMip = 0, MipLevels = -1 }
                };
                cubeMap.CreateView(srvDesc);

                var rtsDesc = new RenderTargetViewDescription()
                {
                    Format = textureDesc.Format,
                    Dimension = RenderTargetViewDimension.Texture2DArray,
                    Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource() { MipSlice = 0, FirstArraySlice = 0, ArraySize = 1 }
                };

                for (int i = 0; i < 6; ++i)
                {
                    RemoveAndDispose(ref cubeRTVs[i]);
                    rtsDesc.Texture2DArray.FirstArraySlice = i;
                    cubeRTVs[i] = Collect(new RenderTargetView(Device, CubeMap.Resource, rtsDesc));
                }

                RemoveAndDispose(ref cubeDSV);
                cubeDSV = Collect(new ShaderResourceViewProxy(Device, dsvTextureDesc));
                var dsvDesc = new DepthStencilViewDescription()
                {
                    Format = dsvTextureDesc.Format,
                    Dimension = DepthStencilViewDimension.Texture2DArray,
                    Flags = DepthStencilViewFlags.None,
                    Texture2DArray = new DepthStencilViewDescription.Texture2DArrayResource() { MipSlice = 0, FirstArraySlice = 0, ArraySize = 1 }
                };

                for (int i = 0; i < 6; ++i)
                {
                    RemoveAndDispose(ref cubeDSVs[i]);
                    dsvDesc.Texture2DArray.FirstArraySlice = i;
                    cubeDSVs[i] = Collect(new DepthStencilView(Device, cubeDSV.Resource, dsvDesc));
                }

                viewport = new Viewport(0, 0, FaceSize, FaceSize);
                return true;
            }
            public void OnDeviceInit()
            {
                DepthStencilViewDescription desc = new DepthStencilViewDescription();

                desc.Format    = m_format;
                desc.Flags     = DepthStencilViewFlags.None;
                desc.Dimension = DepthStencilViewDimension.Texture2DArray;
                desc.Texture2DArray.ArraySize       = 1;
                desc.Texture2DArray.FirstArraySlice = m_slice;
                desc.Texture2DArray.MipSlice        = m_mipmap;
                m_dsv           = new DepthStencilView(MyRender11.Device, m_owner.Resource, desc);
                m_dsv.DebugName = m_owner.Name;
            }
Beispiel #29
0
        private void CreateDeviceSwapChainContext()
        {
            var description = new SwapChainDescription
            {
                BufferCount       = 1,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = RenderForm.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard,
            };
            Device dev;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out dev, out swapChain);
            device = dev;

            deviceContext = device.ImmediateContext;

            swapchainresource = Resource.FromSwapChain <Texture2D>(swapChain, 0);
            MainRenderTarget  = new RenderTargetView(device, swapchainresource);

            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32_Typeless,
                Height            = RenderForm.ClientSize.Height,
                Width             = RenderForm.ClientSize.Width,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default
            };

            DepthBuffer = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription
            {
                ArraySize       = 1,
                Format          = Format.D32_Float,
                Dimension       = DepthStencilViewDimension.Texture2D,
                MipSlice        = 0,
                Flags           = 0,
                FirstArraySlice = 0
            };

            renderTargetDepthStencil = new DepthStencilView(device, DepthBuffer, dsViewDesc);
        }
        private void BuildDepthBuffer()
        {
            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type            = DescriptorHeapType.DepthStencilView,
                Flags           = DescriptorHeapFlags.None
            };

            DescriptorHeap      descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth         = new ResourceDescription()
            {
                Dimension         = ResourceDimension.Texture2D,
                DepthOrArraySize  = 1,
                MipLevels         = 0,
                Flags             = ResourceFlags.AllowDepthStencil,
                Width             = (int)viewport.Width,
                Height            = (int)viewport.Height,
                Format            = Format.R32_Typeless,
                Layout            = TextureLayout.Unknown,
                SampleDescription = new SampleDescription()
                {
                    Count = 1
                }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format       = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth   = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format    = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;
        }
Beispiel #31
0
        public DX11DepthStencil(DX11RenderContext context, int w, int h, SampleDescription sd, Format format)
        {
            this.context = context;
            var depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = h,
                Width = w,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = sd,
                Usage = ResourceUsage.Default
            };

            this.Resource = new Texture2D(context.Device, depthBufferDesc);

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = 1,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                Dimension = sd.Count == 1 ? ShaderResourceViewDimension.Texture2D : ShaderResourceViewDimension.Texture2DMultisampled,
                MipLevels = 1,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.Resource, srvd);

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                Format = DepthFormatsHelper.GetDepthFormat(format),
                Dimension = sd.Count == 1 ? DepthStencilViewDimension.Texture2D : DepthStencilViewDimension.Texture2DMultisampled,
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            //Read only dsv only supported in dx11 minimum
            if (context.IsFeatureLevel11)
            {
                dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

                this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);
            }

            this.desc = depthBufferDesc;
            this.isowner = true;
        }
        public DX11DepthTextureArray(DX11RenderContext context, int w, int h, int elemcnt, Format format)
        {
            this.context = context;

            this.original = format;

            var texBufferDesc = new Texture2DDescription
            {
                ArraySize = elemcnt,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = DepthFormatsHelper.GetGenericTextureFormat(format),
                Height = h,
                Width = w,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1,0),
                Usage = ResourceUsage.Default,
            };

            this.Resource = new Texture2D(context.Device, texBufferDesc);

            ShaderResourceViewDescription srvd = new ShaderResourceViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Format = DepthFormatsHelper.GetSRVFormat(format),
                MipLevels = 1,
                MostDetailedMip = 0
            };

            this.SRV = new ShaderResourceView(context.Device, this.Resource, srvd);

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize = elemcnt,
                FirstArraySlice = 0,
                Format = DepthFormatsHelper.GetDepthFormat(format),// Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                MipSlice = 0
            };

            this.DSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            dsvd.Flags = DepthStencilViewFlags.ReadOnlyDepth;
            if (format == Format.D24_UNorm_S8_UInt) { dsvd.Flags |= DepthStencilViewFlags.ReadOnlyStencil; }

            this.ReadOnlyDSV = new DepthStencilView(context.Device, this.Resource, dsvd);

            this.desc = texBufferDesc;
        }
Beispiel #33
0
        public static DepthStencilView CreateDepthStencilView(Device device, Texture2D depthStencil, Format format, int arraySlice)
        {
            DepthStencilViewDescription dsvd = new DepthStencilViewDescription();

            dsvd.Format    = format;
            dsvd.Flags     = 0;
            dsvd.Dimension = DepthStencilViewDimension.Texture2DArray;// D3D11_DSV_DIMENSION_TEXTURE2DARRAY;
            dsvd.Texture2DArray.ArraySize       = 1;
            dsvd.Texture2DArray.FirstArraySlice = arraySlice;
            dsvd.Texture2DArray.MipSlice        = 0;
            DepthStencilView dsv = new DepthStencilView(device, depthStencil, dsvd);

            return(dsv);
        }
 private void CreateDepthStencilViews()
 {
     var depthStencilViewDesc = new DepthStencilViewDescription();
     depthStencilViewDesc.Format = Format.D32_Float;
     depthStencilViewDesc.Dimension = DepthStencilViewDimension.Texture2DArray;
     depthStencilViewDesc.ArraySize = 1;
     depthStencilViewDesc.MipSlice = 0;
     for (int i = 0; i < deferredShadingConfiguration.LayerCount; ++i)
     {
         depthStencilViewDesc.FirstArraySlice = i;
         var depthStencilView = new DepthStencilView(device, texture, depthStencilViewDesc);
         depthStencilViews.Add(depthStencilView);
     }
 }
Beispiel #35
0
        public D3DFramebuffer(Device device, D3DTexture2D colorTexture, D3DTexture2D depthTexture, int width, int height)
        {
            _device               = device;
            _colorTextures[0]     = colorTexture;
            _renderTargetViews[0] = new RenderTargetView(device, colorTexture.DeviceTexture);
            DepthStencilViewDescription dsvd = new DepthStencilViewDescription();

            dsvd.Format      = SharpDX.DXGI.Format.D16_UNorm;
            dsvd.Dimension   = DepthStencilViewDimension.Texture2D;
            DepthStencilView = new DepthStencilView(device, depthTexture.DeviceTexture, dsvd);
            DepthTexture     = depthTexture;
            _width           = width;
            _height          = height;
        }
Beispiel #36
0
        public TextureRenderTargetAspect(DxDeviceContext dxDeviceContext, int width, int height)
        {
            _dxDeviceContext = dxDeviceContext;
            _width           = width;
            _height          = height;

            Texture2DDescription rtDesc = new Texture2DDescription();

            rtDesc.Width             = _width;
            rtDesc.Height            = _height;
            rtDesc.MipLevels         = 1;
            rtDesc.ArraySize         = 1;
            rtDesc.Format            = Format.B8G8R8A8_UNorm;
            rtDesc.SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0);
            rtDesc.Usage             = ResourceUsage.Default;
            rtDesc.BindFlags         = BindFlags.RenderTarget;
            rtDesc.CpuAccessFlags    = CpuAccessFlags.None;
            rtDesc.OptionFlags       = ResourceOptionFlags.None;
            _renderTexture           = new Texture2D(dxDeviceContext.Device, rtDesc);
            _renderTargetView        = new RenderTargetView(_dxDeviceContext.Device, _renderTexture);
            _dxDeviceContext.Device.ImmediateContext.ClearRenderTargetView(_renderTargetView, new Color4(System.Drawing.Color.Black));

            rtDesc.Usage          = ResourceUsage.Staging;
            rtDesc.BindFlags      = BindFlags.None;
            rtDesc.CpuAccessFlags = CpuAccessFlags.Read;
            _lockableTexture      = new Texture2D(_dxDeviceContext.Device, rtDesc);

            Texture2DDescription sdDesc = new Texture2DDescription();

            sdDesc.Width             = _width;
            sdDesc.Height            = _height;
            sdDesc.MipLevels         = 1;
            sdDesc.ArraySize         = 1;
            sdDesc.Format            = Format.D24_UNorm_S8_UInt;
            sdDesc.SampleDescription = new SampleDescription(1, 0);
            sdDesc.Usage             = ResourceUsage.Default;
            sdDesc.BindFlags         = BindFlags.DepthStencil;
            sdDesc.CpuAccessFlags    = CpuAccessFlags.None;
            sdDesc.OptionFlags       = ResourceOptionFlags.None;
            _depthStencilTexture     = new Texture2D(_dxDeviceContext.Device, sdDesc);
            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();

            dsvDesc.Format          = sdDesc.Format;
            dsvDesc.Dimension       = DepthStencilViewDimension.Texture2D;
            dsvDesc.FirstArraySlice = 0;
            dsvDesc.ArraySize       = 1;
            _depthStencilView       = new DepthStencilView(_dxDeviceContext.Device, _depthStencilTexture, dsvDesc);

            _viewport = new Viewport(0, 0, _width, _height, 0, 1);
        }
        public DX11SliceDepthStencil(DX11RenderContext context, DX11Texture2D texture, int sliceindex, Format depthformat)
        {
            this.context = context;
            this.parent = texture;

            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize = 1,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                Format = depthformat,
                MipSlice = 0,
                FirstArraySlice = sliceindex
            };

            this.DSV = new DepthStencilView(context.Device, this.parent.Resource, dsvd);
        }
Beispiel #38
0
        public ShadowMap(Device device, int width, int height) {
            _width = width;
            _height = height;

            _viewport = new Viewport(0, 0, _width, _height, 0, 1.0f);

            var texDesc = new Texture2DDescription {
                Width = _width,
                Height = _height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.R24G8_Typeless,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            var depthMap = new Texture2D(device, texDesc) {
                DebugName = "shadowmap depthmap"
            };
            var dsvDesc = new DepthStencilViewDescription {
                Flags = DepthStencilViewFlags.None,
                Format = Format.D24_UNorm_S8_UInt,
                Dimension = DepthStencilViewDimension.Texture2D,
                Texture2D = new DepthStencilViewDescription.Texture2DResource() {
                    MipSlice = 0
                }
            };
            _depthMapDSV = new DepthStencilView(device, depthMap, dsvDesc);

            var srvDesc = new ShaderResourceViewDescription {
                Format = Format.R24_UNorm_X8_Typeless,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource() {
                    MipLevels = texDesc.MipLevels,
                    MostDetailedMip = 0
                }
            };

            DepthMapSRV = new ShaderResourceView(device, depthMap, srvDesc);

            Utilities.Dispose(ref depthMap);

        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref DSSRV);
            RemoveAndDispose(ref DSV);
            RemoveAndDispose(ref DS0);

            RTs.ForEach(rt => RemoveAndDispose(ref rt));
            SRVs.ForEach(srv => RemoveAndDispose(ref srv));
            RTVs.ForEach(rtv => RemoveAndDispose(ref rtv));
            RTs.Clear();
            SRVs.Clear();
            RTVs.Clear();

            var device = DeviceManager.Direct3DDevice;

            bool isMSAA = sampleDescription.Count > 1;

            // Render Target texture description
            var texDesc = new Texture2DDescription();
            texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize = 1;
            texDesc.CpuAccessFlags = CpuAccessFlags.None;
            texDesc.Usage = ResourceUsage.Default;
            texDesc.Width = width;
            texDesc.Height = height;
            texDesc.MipLevels = 1; // No mip levels
            texDesc.SampleDescription = sampleDescription;

            // Render Target View description
            var rtvDesc = new RenderTargetViewDescription();
            rtvDesc.Dimension = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;

            // SRV description for render targets
            var srvDesc = new ShaderResourceViewDescription();
            srvDesc.Dimension = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;

            // Create Render Targets (with SRV and RTV)
            foreach (var format in RTFormats)
            {
                texDesc.Format = format;
                srvDesc.Format = format;
                rtvDesc.Format = format;

                RTs.Add(ToDispose(new Texture2D(device, texDesc)));
                SRVs.Add(ToDispose(new ShaderResourceView(device, RTs.Last(), srvDesc)));
                RTVs.Add(ToDispose(new RenderTargetView(device, RTs.Last(), rtvDesc)));

                RTs.Last().DebugName = String.Format("RT{0}_{1}", RTs.Count, format);
                SRVs.Last().DebugName = String.Format("SRV{0}_{1}", RTs.Count, format);
                RTVs.Last().DebugName = String.Format("RTV{0}_{1}", RTs.Count, format);
            }

            // Create Depth/Stencil
            texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.DepthStencil;
            texDesc.Format = SharpDX.DXGI.Format.R32G8X24_Typeless; // typeless so we can use as shader resource
            DS0 = ToDispose(new Texture2D(device, texDesc));
            DS0.DebugName = "DS0";

            srvDesc.Format = SharpDX.DXGI.Format.R32_Float_X8X24_Typeless;
            DSSRV = ToDispose(new ShaderResourceView(device, DS0, srvDesc));
            DSSRV.DebugName = "DSSRV-DepthStencil";

            // Depth Stencil View
            var dsvDesc = new DepthStencilViewDescription();
            dsvDesc.Flags = DepthStencilViewFlags.None;
            dsvDesc.Dimension = isMSAA ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
            dsvDesc.Format = SharpDX.DXGI.Format.D32_Float_S8X24_UInt;
            dsvDesc.Texture2D.MipSlice = 0;

            DSV = ToDispose(new DepthStencilView(device, DS0, dsvDesc));
            DSV.DebugName = "DSV0";
        }
        public DepthStencilView GetView(int slice, int count)
        {
            DepthStencilViewDescription dsvd = new DepthStencilViewDescription()
            {
                ArraySize = count,
                FirstArraySlice = slice,
                Format = DepthFormatsHelper.GetDepthFormat(this.original),// Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2DArray,
                MipSlice = 0
            };

            return new DepthStencilView(context.Device, this.Resource, dsvd);
        }
        private void BuildDepthBuffer()
        {
            DescriptorHeapDescription descDescriptorHeapDSB = new DescriptorHeapDescription()
            {
                DescriptorCount = 1,
                Type = DescriptorHeapType.DepthStencilView,
                Flags = DescriptorHeapFlags.None
            };

            DescriptorHeap descriptorHeapDSB = device.CreateDescriptorHeap(descDescriptorHeapDSB);
            ResourceDescription descDepth = new ResourceDescription()
            {
                Dimension = ResourceDimension.Texture2D,
                DepthOrArraySize = 1,
                MipLevels = 0,
                Flags = ResourceFlags.AllowDepthStencil,
                Width = (int)viewport.Width,
                Height = (int)viewport.Height,
                Format = Format.R32_Typeless,
                Layout = TextureLayout.Unknown,
                SampleDescription = new SampleDescription() { Count = 1 }
            };

            ClearValue dsvClearValue = new ClearValue()
            {
                Format = Format.D32_Float,
                DepthStencil = new DepthStencilValue()
                {
                    Depth = 1.0f,
                    Stencil = 0
                }
            };

            Resource renderTargetDepth = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, descDepth, ResourceStates.GenericRead, dsvClearValue);

            DepthStencilViewDescription depthDSV = new DepthStencilViewDescription()
            {
                Dimension = DepthStencilViewDimension.Texture2D,
                Format = Format.D32_Float,
                Texture2D = new DepthStencilViewDescription.Texture2DResource()
                {
                    MipSlice = 0
                }
            };

            device.CreateDepthStencilView(renderTargetDepth, depthDSV, descriptorHeapDSB.CPUDescriptorHandleForHeapStart);
            handleDSV = descriptorHeapDSB.CPUDescriptorHandleForHeapStart;
        }
Beispiel #42
0
        public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory();
                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter(0);
                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);
                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description;

                // Release the adapter output.
                monitor.Dispose();

                // Release the adapter.
                adapter.Dispose();

                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm),
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !SystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                Device device;
                SwapChain swapChain;
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device = device;
                SwapChain = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width = configuration.Width,
                    Height = configuration.Height,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode = CullMode.Back,
                    DepthBias = 0,
                    DepthBiasClamp = .0f,
                    IsDepthClipEnabled = true,
                    FillMode = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled = false,
                    IsScissorEnabled = false,
                    SlopeScaledDepthBias = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering.
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation = StencilOperation.Keep,
                        Comparison = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                // Create an alpha enabled blend state description.
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled = true;
                blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                // Create the blend state using the description.
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);

                // Modify the description to create an disabled blend state description.
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;
                // Create the blend state using the description.
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Beispiel #43
0
        // Static functions
        static public TextureObject CreateTexture(Device device, int width, int height, int mips, Format format, bool isDepthStencil, bool needsGpuWrite)
        {
            if (isDepthStencil && format != Format.R32_Typeless && format != Format.R24G8_Typeless)
            {
                throw new Exception("Unsupported depth format");
            }

            TextureObject newTexture = new TextureObject();

            // Variables
            newTexture.m_Width = width;
            newTexture.m_Height = height;
            newTexture.m_TexFormat = format;
            newTexture.m_Mips = mips;

            BindFlags bindFlags = BindFlags.ShaderResource;
            if (isDepthStencil) bindFlags |= BindFlags.DepthStencil;
            if (needsGpuWrite && !isDepthStencil) bindFlags |= BindFlags.RenderTarget;
            if (needsGpuWrite && !isDepthStencil) bindFlags |= BindFlags.UnorderedAccess;

            Texture2DDescription textureDescription = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = bindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = height,
                Width = width,
                MipLevels = mips,
                OptionFlags = (mips > 1 && needsGpuWrite) ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            newTexture.m_TextureObject2D = new Texture2D(device, textureDescription);

            Format srvFormat = format;

            // Special case for depth
            if (isDepthStencil)
            {
                srvFormat = (format == Format.R32_Typeless) ? Format.R32_Float : Format.R24_UNorm_X8_Typeless;
            }

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = srvFormat,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Flags = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels = mips
            };

            newTexture.m_ShaderResourceView = new ShaderResourceView(device, newTexture.m_TextureObject2D, srvViewDesc);

            if (isDepthStencil)
            {
                DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription
                {
                    ArraySize = 0,
                    Format = (format == Format.R32_Typeless) ? Format.D32_Float : Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    MipSlice = 0,
                    Flags = 0,
                    FirstArraySlice = 0
                };

                newTexture.m_DepthStencilView = new DepthStencilView(device, newTexture.m_TextureObject2D, dsViewDesc);
            }

            // No RTV for depth stencil, sorry
            if (needsGpuWrite && !isDepthStencil)
            {
                newTexture.m_RenderTargetView = new RenderTargetView(device, newTexture.m_TextureObject2D);

                UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
                {
                    ArraySize = 0,
                    DepthSliceCount = 1,
                    Dimension = UnorderedAccessViewDimension.Texture2D,
                    ElementCount = 1,
                    FirstArraySlice = 0,
                    FirstDepthSlice = 0,
                    FirstElement = 0,
                    Flags = UnorderedAccessViewBufferFlags.None,
                    Format = format,
                    MipSlice = 0
                };
                newTexture.m_UnorderedAccessView = new UnorderedAccessView(device, newTexture.m_TextureObject2D, uavDesc);
            }

            return newTexture;
        }
Beispiel #44
0
        private void SetViews()
        {
            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width = (uint)directControl.ClientSize.Width,
                Height = (uint)directControl.ClientSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32_FLOAT,
                SampleDescription = new SampleDescription()
                {
                    Count = 1,
                    Quality = 0
                },
                BindFlags = BindFlag.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            //bind the views to the device
            device.OM.SetRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width = (uint)directControl.ClientSize.Width,
                Height = (uint)directControl.ClientSize.Height,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };

            device.RS.SetViewports(new Viewport[] { vp });
        }
Beispiel #45
0
        private DepthStencilView GetDepthStencilView(out bool hasStencil)
        {
            hasStencil = false;
            if (!IsDepthStencil)
                return null;

            // Check that the format is supported
            if (ComputeShaderResourceFormatFromDepthFormat(ViewFormat) == SharpDX.DXGI.Format.Unknown)
                throw new NotSupportedException("Depth stencil format [{0}] not supported".ToFormat(ViewFormat));

            // Setup the HasStencil flag
            hasStencil = IsStencilFormat(ViewFormat);

            // Create a Depth stencil view on this texture2D
            var depthStencilViewDescription = new DepthStencilViewDescription
            {
                Format = ComputeDepthViewFormatFromTextureFormat(ViewFormat),
                Flags = DepthStencilViewFlags.None,
            };

            if (ArraySize > 1)
            {
                depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DArray;
                depthStencilViewDescription.Texture2DArray.ArraySize = ArraySize;
                depthStencilViewDescription.Texture2DArray.FirstArraySlice = 0;
                depthStencilViewDescription.Texture2DArray.MipSlice = 0;
            }
            else
            {
                depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2D;
                depthStencilViewDescription.Texture2D.MipSlice = 0;
            }

            if (MultiSampleLevel > MSAALevel.None)
                depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DMultisampled;

            if (IsDepthStencilReadOnly)
            {
                if (!IsDepthStencilReadOnlySupported(GraphicsDevice))
                    throw new NotSupportedException("Cannot instantiate ReadOnly DepthStencilBuffer. Not supported on this device.");

                // Create a Depth stencil view on this texture2D
                depthStencilViewDescription.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                if (HasStencil)
                    depthStencilViewDescription.Flags |= DepthStencilViewFlags.ReadOnlyStencil;
            }

            return new DepthStencilView(GraphicsDevice.NativeDevice, NativeResource, depthStencilViewDescription);
        }
        internal MyDepthStencil(int width, int height,
            int sampleCount, int sampleQuality)
        {
            m_resolution = new Vector2I(width, height);
            m_samples = new Vector2I(sampleCount, sampleQuality);

            m_depthSubresource = new MyDepthView(this);
            m_stencilSubresource = new MyStencilView(this);

            Texture2DDescription desc = new Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.Format = Depth32F ? Format.R32G8X24_Typeless : Format.R24G8_Typeless;
            desc.ArraySize = 1;
            desc.MipLevels = 1;
            desc.BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource;
            desc.Usage = ResourceUsage.Default;
            desc.CpuAccessFlags = 0;
            desc.SampleDescription.Count = sampleCount;
            desc.SampleDescription.Quality = sampleQuality;
            desc.OptionFlags = 0;
            m_resource = new Texture2D(MyRender11.Device, desc);

            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();
            dsvDesc.Format = Depth32F ? Format.D32_Float_S8X24_UInt : Format.D24_UNorm_S8_UInt;
            if (sampleCount == 1)
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags = DepthStencilViewFlags.None;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags = DepthStencilViewFlags.None;
            }
            m_DSV = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            if (sampleCount == 1)
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
            }
            m_DSV_roDepth = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            if (sampleCount == 1)
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
            }
            m_DSV_roStencil = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
            dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil | DepthStencilViewFlags.ReadOnlyDepth;
            if (sampleCount == 1)
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                dsvDesc.Texture2D.MipSlice = 0;
            }
            else
            {
                dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
            }
            m_DSV_ro = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);

            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
            srvDesc.Format = Depth32F ? Format.R32_Float_X8X24_Typeless : Format.R24_UNorm_X8_Typeless;
            if (sampleCount == 1)
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels = -1;
                srvDesc.Texture2D.MostDetailedMip = 0;
            }
            else
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
            }
            m_SRV_depth = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);

            srvDesc.Format = Depth32F ? Format.X32_Typeless_G8X24_UInt : Format.X24_Typeless_G8_UInt;
            if (sampleCount == 1)
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                srvDesc.Texture2D.MipLevels = -1;
                srvDesc.Texture2D.MostDetailedMip = 0;
            }
            else
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
            }
            m_SRV_stencil = new ShaderResourceView(MyRender11.Device, m_resource, srvDesc);
        }
Beispiel #47
0
        private void InitializeDepthStencil(uint nWidth, uint nHeight)
        {
            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
                                                 {
                                                     Width = nWidth,
                                                     Height = nHeight,
                                                     MipLevels = 1,
                                                     ArraySize = 1,
                                                     Format = Format.D16_UNORM,
                                                     SampleDescription = new SampleDescription()
                                                                             {
                                                                                 Count = 1,
                                                                                 Quality = 0
                                                                             },
                                                     BindFlags = BindFlag.DepthStencil,
                                                 };
            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
                                                                   {
                                                                       Format = descDepth.Format,
                                                                       ViewDimension =
                                                                           DepthStencilViewDimension.
                                                                           Texture2D
                                                                   };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);
        }
Beispiel #48
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample");

            // SwapChain description
            var desc = new SwapChainDescription()
                           {
                               BufferCount = 3,
                               ModeDescription=
                                   new ModeDescription(form.ClientSize.Width, form.ClientSize.Height,
                                                       new Rational(60, 1), Format.R8G8B8A8_UNorm),
                               IsWindowed = true,
                               OutputHandle = form.Handle,
                               SampleDescription = new SampleDescription(1,0),
                               SwapEffect = SwapEffect.Sequential,
                               Usage = Usage.RenderTargetOutput

                           };

            // Create Device and SwapChain
            Device device;
            SwapChain swapChain;
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
            var context = device.ImmediateContext;

            // Ignore all windows events
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            Texture2DDescription depthBufferDesc;
            depthBufferDesc.Width = form.Width;
            depthBufferDesc.Height = form.Height;
            depthBufferDesc.MipLevels = 1;
            depthBufferDesc.ArraySize = 1;
            depthBufferDesc.Format = Format.D24_UNorm_S8_UInt;
            depthBufferDesc.SampleDescription.Count = 1;
            depthBufferDesc.SampleDescription.Quality = 0;
            depthBufferDesc.Usage = ResourceUsage.Default;
            depthBufferDesc.BindFlags = BindFlags.DepthStencil;
            depthBufferDesc.CpuAccessFlags = CpuAccessFlags.None ;
            depthBufferDesc.OptionFlags = ResourceOptionFlags.None;

            Texture2D DepthStencilTexture = new Texture2D(device, depthBufferDesc);

            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription();
            depthStencilViewDesc.Format = Format.D24_UNorm_S8_UInt;
            depthStencilViewDesc.Dimension =  DepthStencilViewDimension.Texture2D;
            depthStencilViewDesc.Texture2D.MipSlice = 0;
            DepthStencilView depthStencilView = new DepthStencilView(device, DepthStencilTexture, depthStencilViewDesc);
            context.OutputMerger.SetTargets(depthStencilView,renderView);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };
            DepthStencilState depthStencilState = new DepthStencilState(device, depthDesc);

            RasterizerStateDescription rasdesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias = 0,
                DepthBiasClamp = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled = true,
                IsMultisampleEnabled =true,
            };
            context.Rasterizer.State = new RasterizerState(device, rasdesc);

            //////////////////////////////

            var flags = (ppsteps |
                aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
                aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
                aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges
                aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
                aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
                (aiPostProcessSteps)0);

            // default model
            var path = @"jeep1.ms3d";

            Importer importer = new Importer();

            //var path = "man.3ds";
            aiScene scene = importer.ReadFile(path, flags);
            String directory = null;
            if (scene != null)
            {
                directory = Path.GetDirectoryName(path);
            }
            else
            {
                MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid.");
                Application.Exit();
            }

            SceneLoader SceneLoader = new SceneLoader();
            List<model> models = new List<model>();
            for (int i = 0; i < scene.mNumMeshes; i++)
            {
                models.Add(SceneLoader.CreateMesh(device, scene.mMeshes[i], scene.mMaterials,directory));
            }

            //////////////////////////////

            // Compile Vertex and Pixel shaders
            var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var effect = new Effect(device, effectByteCode);
            var technique = effect.GetTechniqueByIndex(0);
            var pass = technique.GetPassByIndex(0);

            // Layout from VertexShader input signature
            var passSignature = pass.Description.Signature;

            // Layout from VertexShader input signature
            var layout = new InputLayout(
                device,
                passSignature,
                new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
                    });

            // Prepare All the stages
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.OutputMerger.DepthStencilState = depthStencilState;

            Input input = new Input(form);
            //FreeLook FreeLook = new SharpExamples.FreeLook(input, (float)form.Width / (float)form.Height);
            CameraFirstPerson FreeLook = new CameraFirstPerson(input, 0, 0, Vector3.Zero, form.Width, form.Height);
            //FreeLook.SetEyeTarget(new Vector3(300), Vector3.Zero);
            Clock Clock = new SharpExamples.Clock();
            Clock.Start();

            effect.GetVariableByName("projection").AsMatrix().SetMatrix(FreeLook.Projection);

            // Main loop
            RenderLoop.Run(form, () =>
                                      {
                                          foreach (var item in models)
                                          {
                                                context.InputAssembler.InputLayout = layout;
                                                context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                                                int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture));
                                                context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(item.vertex, SizeInBytes, 0));
                                                context.InputAssembler.SetIndexBuffer(item.indices, Format.R32_UInt, 0);

                                                float elapsed = Clock.Update();
                                                FreeLook.Update(elapsed);

                                                effect.GetVariableByName("view").AsMatrix().SetMatrix(FreeLook.View);
                                                effect.GetVariableByName("World").AsMatrix().SetMatrix(Matrix.Scaling(5));
                                                effect.GetVariableByName("tex0").AsShaderResource().SetResource(item.ShaderResourceView);
                                                context.ClearRenderTargetView(renderView, Colors.Black);
                                                context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0);

                                                for (int i = 0; i < technique.Description.PassCount; ++i)
                                                {
                                                    pass.Apply(context);
                                                    context.DrawIndexed(item.numberIndices, 0, 0);
                                                }
                                                swapChain.Present(0, PresentFlags.None);
                                          }

                                      });

            // Release all resources
            foreach (var item in models)
            {
                item.vertex.Dispose();
                item.indices.Dispose();
                item.ShaderResourceView.Dispose();
            }

            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
Beispiel #49
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RenderTargetCube"/> class.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device.</param>
        /// <param name="size">The width and height of a texture cube face in pixels.</param>
        /// <param name="mipMap"><see langword="true"/> to generate a full mipmap chain; otherwise <see langword="false"/>.</param>
        /// <param name="preferredFormat">The preferred format of the surface.</param>
        /// <param name="preferredDepthFormat">The preferred format of the depth-stencil buffer.</param>
        /// <param name="preferredMultiSampleCount">The preferred number of multisample locations.</param>
        /// <param name="usage">The usage mode of the render target.</param>
        public RenderTargetCube(GraphicsDevice graphicsDevice, int size, bool mipMap, SurfaceFormat preferredFormat, DepthFormat preferredDepthFormat, int preferredMultiSampleCount, RenderTargetUsage usage)
            : base(graphicsDevice, size, mipMap, preferredFormat, true)
        {
            DepthStencilFormat = preferredDepthFormat;
            MultiSampleCount = preferredMultiSampleCount;
            RenderTargetUsage = usage;

#if DIRECTX
            // Create one render target view per cube map face.
            _renderTargetViews = new RenderTargetView[6];
            for (int i = 0; i < _renderTargetViews.Length; i++)
            {
                var renderTargetViewDescription = new RenderTargetViewDescription
                {
                    Dimension = RenderTargetViewDimension.Texture2DArray,
                    Format = SharpDXHelper.ToFormat(preferredFormat),
                    Texture2DArray =
                    {
                        ArraySize = 1,
                        FirstArraySlice = i,
                        MipSlice = 0
                    }
                };

                _renderTargetViews[i] = new RenderTargetView(graphicsDevice._d3dDevice, _texture, renderTargetViewDescription);
            }

            // If we don't need a depth buffer then we're done.
            if (preferredDepthFormat == DepthFormat.None)
                return;

            var sampleDescription = new SampleDescription(1, 0);
            if (preferredMultiSampleCount > 1)
            {
                sampleDescription.Count = preferredMultiSampleCount;
                sampleDescription.Quality = (int)StandardMultisampleQualityLevels.StandardMultisamplePattern;
            }

            var depthStencilDescription = new Texture2DDescription
            {
                Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                ArraySize = 1,
                MipLevels = 1,
                Width = size,
                Height = size,
                SampleDescription = sampleDescription,
                BindFlags = BindFlags.DepthStencil,
            };

            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, depthStencilDescription))
            {
                var depthStencilViewDescription = new DepthStencilViewDescription
                {
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Format = SharpDXHelper.ToFormat(preferredDepthFormat),
                };
                _depthStencilView = new DepthStencilView(graphicsDevice._d3dDevice, depthBuffer, depthStencilViewDescription);
            }
#else
            throw new NotImplementedException();
#endif            
        }
        public void OnInitialise(InitialiseMessage msg)
        {
            // Initialise renderer
            Console.WriteLine("Initialising renderer...");
            rendermsg = new RenderMessage();
            updatemsg = new UpdateMessage();

            // Create the window
            window = new RenderForm("Castle Renderer - 11030062");
            window.Width = 1280;
            window.Height = 720;

            // Add form events
            window.FormClosed += window_FormClosed;

            // Defaults
            ClearColour = new Color4(1.0f, 0.0f, 0.0f, 1.0f);

            // Setup the device
            var description = new SwapChainDescription()
            {
                BufferCount = 1,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = window.Handle,
                IsWindowed = true,
                ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };
            Device tmp;
            var result = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out tmp, out swapchain);
            if (result.IsFailure)
            {
                Console.WriteLine("Failed to create Direct3D11 device (" + result.Code.ToString() + ":" + result.Description + ")");
                return;
            }
            Device = tmp;
            context = Device.ImmediateContext;
            using (var factory = swapchain.GetParent<Factory>())
                factory.SetWindowAssociation(window.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // Check AA stuff
            int q = Device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 8);

            // Setup the viewport
            viewport = new Viewport(0.0f, 0.0f, window.ClientSize.Width, window.ClientSize.Height);
            viewport.MinZ = 0.0f;
            viewport.MaxZ = 1.0f;
            context.Rasterizer.SetViewports(viewport);

            // Setup the backbuffer
            using (var resource = Resource.FromSwapChain<Texture2D>(swapchain, 0))
                rtBackbuffer = new RenderTargetView(Device, resource);

            // Setup depth for backbuffer
            {
                Texture2DDescription texdesc = new Texture2DDescription()
                {
                    ArraySize = 1,
                    BindFlags = BindFlags.DepthStencil,
                    CpuAccessFlags = CpuAccessFlags.None,
                    Format = Format.D32_Float,
                    Width = (int)viewport.Width,
                    Height = (int)viewport.Height,
                    MipLevels = 1,
                    OptionFlags = ResourceOptionFlags.None,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default
                };
                texDepthBuffer = new Texture2D(Device, texdesc);
                DepthStencilViewDescription viewdesc = new DepthStencilViewDescription()
                {
                    ArraySize = 0,
                    Format = Format.D32_Float,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    MipSlice = 0,
                    Flags = 0,
                    FirstArraySlice = 0
                };
                vwDepthBuffer = new DepthStencilView(Device, texDepthBuffer, viewdesc);
            }

            // Setup states
            #region Depth States
            // Setup depth states
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less
                };
                Depth_Enabled = DepthStencilState.FromDescription(Device, desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero,
                    DepthComparison = Comparison.Less
                };
                Depth_Disabled = DepthStencilState.FromDescription(Device, desc);
            }
            {
                DepthStencilStateDescription desc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero,
                    DepthComparison = Comparison.Less
                };
                Depth_ReadOnly = DepthStencilState.FromDescription(Device, desc);
            }
            #endregion
            #region Sampler States
            Sampler_Clamp = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.Anisotropic,
                MinimumLod = 0.0f,
                MaximumLod = float.MaxValue,
                MaximumAnisotropy = 16
            });
            Sampler_Clamp_Point = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.MinMagMipPoint
            });
            Sampler_Clamp_Linear = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                Filter = Filter.MinMagMipLinear
            });
            Sampler_Wrap = SamplerState.FromDescription(Device, new SamplerDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                MinimumLod = 0.0f,
                MaximumLod = float.MaxValue,
                MaximumAnisotropy = 16
            });
            #endregion
            #region Rasterizer States
            Culling_Backface = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.Back,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            Culling_Frontface = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.Front,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            Culling_None = RasterizerState.FromDescription(Device, new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = true,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f
            });
            #endregion
            #region Blend States
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.One;
                desc.RenderTargets[0].DestinationBlend = BlendOption.Zero;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Opaque = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha;
                desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Alpha = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.One;
                desc.RenderTargets[0].DestinationBlend = BlendOption.One;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Add = BlendState.FromDescription(Device, desc);
            }
            {
                BlendStateDescription desc = new BlendStateDescription();
                desc.RenderTargets[0].BlendEnable = true;
                desc.RenderTargets[0].BlendOperation = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlend = BlendOption.DestinationColor;
                desc.RenderTargets[0].DestinationBlend = BlendOption.Zero;
                desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add;
                desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One;
                desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero;
                desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                Blend_Multiply = BlendState.FromDescription(Device, desc);
            }
            #endregion

            // Setup default states
            Depth = Depth_Enabled;
            Culling = Culling_Backface;
            Blend = Blend_Opaque;

            // Setup other objects
            shaderresourcemap = new Dictionary<Resource, ShaderResourceView>();
            resourceviewslots = new ShaderResourceViewData[MaxPixelShaderResourceViewSlots];

            // Send the window created message
            WindowCreatedMessage windowcreatedmsg = new WindowCreatedMessage();
            windowcreatedmsg.Form = window;
            Owner.MessagePool.SendMessage(windowcreatedmsg);

            // Show the form
            window.Show();
        }
Beispiel #51
0
 /// <summary>
 ///   Creates a <see cref = "T:SharpDX.Direct3D11.DepthStencilView" /> for accessing resource data.
 /// </summary>
 /// <param name = "device">The device to use when creating this <see cref = "T:SharpDX.Direct3D11.DepthStencilView" />.</param>
 /// <param name = "resource">The resource that represents the render-target surface. This surface must have been created with the <see cref = "T:SharpDX.Direct3D11.BindFlags">DepthStencil</see> flag.</param>
 /// <param name = "description">A structure describing the <see cref = "T:SharpDX.Direct3D11.DepthStencilView" /> to be created.</param>
 /// <unmanaged>ID3D11Device::CreateDepthStencilView</unmanaged>
 public DepthStencilView(Device device, Resource resource, DepthStencilViewDescription description)
     : base(IntPtr.Zero)
 {
     device.CreateDepthStencilView(resource, description, this);
 }
Beispiel #52
0
        internal static RwTexId CreateShadowmap(int width, int height)
        {
            Texture2DDescription desc = new Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.Format = Format.R24G8_Typeless;
            desc.ArraySize = 1;
            desc.MipLevels = 1;
            desc.BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource;
            desc.Usage = ResourceUsage.Default;
            desc.CpuAccessFlags = 0;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.OptionFlags = 0;

            var handle = new RwTexId { Index = Textures.Allocate() };
            var res = new Texture2D(MyRender11.Device, desc);
            Textures.Data[handle.Index] = new MyRwTextureInfo { Description2D = desc, Resource = res };
            Index.Add(handle);

            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
            srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
            srvDesc.Format = Format.R24_UNorm_X8_Typeless;
            srvDesc.Texture2D.MipLevels = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            Srvs[handle] = new MySrvInfo { Description = srvDesc, View = new ShaderResourceView(MyRender11.Device, res, srvDesc) };

            DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();
            dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
            dsvDesc.Format = Format.D24_UNorm_S8_UInt;
            dsvDesc.Flags = DepthStencilViewFlags.None;
            dsvDesc.Texture2D.MipSlice = 0;
            Dsvs[handle] = new MyDsvInfo { Description = dsvDesc, View = new DepthStencilView(MyRender11.Device, res, dsvDesc) };

            return handle;
        }
Beispiel #53
0
        // ReSharper disable once FunctionComplexityOverflow
        public void Resize(int width, int height, bool bgra)
        {
            if (Texture != null)
                Texture.Dispose();

            if (Native != null)
                Native.Dispose();

            var texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = bgra ? SharpDX.DXGI.Format.B8G8R8A8_UNorm : SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = mContext.Multisampling,
                Usage = ResourceUsage.Default,
                Width = width
            };

            Texture = new Texture2D(mContext.Device, texDesc);

            var rtvd = new RenderTargetViewDescription
            {
                Dimension = RenderTargetViewDimension.Texture2DMultisampled,
                Format = texDesc.Format,

                Texture2DMS = new RenderTargetViewDescription.Texture2DMultisampledResource()
            };

            Native = new RenderTargetView(mContext.Device, Texture, rtvd);

            if (mDepthTexture != null)
                mDepthTexture.Dispose();

            if (mDepthView != null)
                mDepthView.Dispose();

            texDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = mContext.Multisampling,
                Usage = ResourceUsage.Default,
                Width = width
            };

            mDepthTexture = new Texture2D(mContext.Device, texDesc);

            var dsvd = new DepthStencilViewDescription
            {
                Dimension = DepthStencilViewDimension.Texture2DMultisampled,
                Flags = DepthStencilViewFlags.None,
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource()
            };

            mDepthView = new DepthStencilView(mContext.Device, mDepthTexture, dsvd);
        }
Beispiel #54
0
        internal static RwTexId CreateShadowmapArray(int width, int height, int arraySize, 
            Format resourceFormat = Format.R24G8_Typeless, 
            Format depthFormat = Format.D24_UNorm_S8_UInt, 
            Format? viewFormat = Format.R24_UNorm_X8_Typeless, 
            string debugName = null)
        {
            Texture2DDescription desc = new Texture2DDescription();
            desc.Width = width;
            desc.Height = height;
            desc.Format = resourceFormat;
            desc.ArraySize = arraySize;
            desc.MipLevels = 1;
            desc.BindFlags = BindFlags.DepthStencil;
            if (viewFormat.HasValue)
            {
                desc.BindFlags |= BindFlags.ShaderResource;
            }
            desc.Usage = ResourceUsage.Default;
            desc.CpuAccessFlags = 0;
            desc.SampleDescription.Count = 1;
            desc.SampleDescription.Quality = 0;
            desc.OptionFlags = 0;

            var handle = new RwTexId { Index = Textures.Allocate() };
            var res = new Texture2D(MyRender11.Device, desc);
            Textures.Data[handle.Index] = new MyRwTextureInfo { Description2D = desc, Resource = res };
            Index.Add(handle);

            var srvDesc = new ShaderResourceViewDescription();
            if(viewFormat.HasValue)
            {
                srvDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
                srvDesc.Format = viewFormat.Value;
                srvDesc.Texture2DArray.MipLevels = -1;
                srvDesc.Texture2DArray.MostDetailedMip = 0;
                srvDesc.Texture2DArray.ArraySize = arraySize;
                srvDesc.Texture2DArray.FirstArraySlice = 0;
                Srvs[handle] = new MySrvInfo { Description = srvDesc, View = new ShaderResourceView(MyRender11.Device, res, srvDesc) };
            }

            var dsvDesc = new DepthStencilViewDescription();
            dsvDesc.Dimension = DepthStencilViewDimension.Texture2DArray;
            dsvDesc.Format = depthFormat;
            dsvDesc.Flags = DepthStencilViewFlags.None;
            dsvDesc.Texture2DArray.MipSlice = 0;
            dsvDesc.Texture2DArray.ArraySize = 1;

            srvDesc.Dimension = ShaderResourceViewDimension.Texture2DArray;
            srvDesc.Format = viewFormat.Value;
            srvDesc.Texture2DArray.MipLevels = -1;
            srvDesc.Texture2DArray.MostDetailedMip = 0;
            srvDesc.Texture2DArray.ArraySize = 1;
            for (int i = 0; i < arraySize; i++)
            {
                dsvDesc.Texture2DArray.FirstArraySlice = i;

                SubresourceDsvs[new MySubresourceId { Id = handle, Subresource = i }] = new MyDsvInfo
                {
                    Description = dsvDesc,
                    View = new DepthStencilView(MyRender11.Device, res, dsvDesc)
                };

                srvDesc.Texture2DArray.FirstArraySlice = i;

                SubresourceSrvs[new MySubresourceId { Id = handle, Subresource = i }] = new MySrvInfo
                {
                    Description = srvDesc,
                    View = new ShaderResourceView(MyRender11.Device, res, srvDesc)
                };
            }

            return handle;
        }
Beispiel #55
0
        // Static functions
        static public TextureObject CreateCubeTexture(Device device, int width, int height, int mips, Format format, bool isDepthStencil, bool needsGpuWrite)
        {
            if (isDepthStencil && format != Format.R32_Typeless && format != Format.R24G8_Typeless)
            {
                throw new Exception("Unsupported depth format");
            }

            TextureObject newTexture = new TextureObject();

            // Variables
            newTexture.m_Width = width;
            newTexture.m_Height = height;
            newTexture.m_TexFormat = format;
            newTexture.m_Mips = mips;
            newTexture.m_IsCube = true;
            newTexture.m_ArraySize = 6;

            BindFlags bindFlags = BindFlags.ShaderResource;
            if (isDepthStencil) bindFlags |= BindFlags.DepthStencil;
            if (needsGpuWrite && !isDepthStencil) bindFlags |= BindFlags.RenderTarget;
            if (needsGpuWrite && !isDepthStencil) bindFlags |= BindFlags.UnorderedAccess;

            Texture2DDescription textureDescription = new Texture2DDescription
            {
                ArraySize = 6,
                BindFlags = bindFlags,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = format,
                Height = height,
                Width = width,
                MipLevels = mips,
                OptionFlags = ResourceOptionFlags.TextureCube | ((mips > 1 && needsGpuWrite) ? ResourceOptionFlags.GenerateMipMaps : ResourceOptionFlags.None),
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            newTexture.m_TextureObject2D = new Texture2D(device, textureDescription);

            Format srvFormat = format;

            // Special case for depth
            if (isDepthStencil)
            {
                srvFormat = (format == Format.R32_Typeless) ? Format.R32_Float : Format.R24_UNorm_X8_Typeless;
            }

            ShaderResourceViewDescription srvViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 6,
                Format = srvFormat,
                Dimension = ShaderResourceViewDimension.Texture2DArray,
                Flags = 0,
                FirstArraySlice = 0,
                MostDetailedMip = 0,
                MipLevels = mips
            };

            newTexture.m_ShaderResourceView = new ShaderResourceView(device, newTexture.m_TextureObject2D, srvViewDesc);

            newTexture.m_ArrayShaderResourceViews = new ShaderResourceView[6]; 
            for (int i = 0; i < 6; ++ i )
            {
                srvViewDesc.ArraySize = 1;
                srvViewDesc.FirstArraySlice = i;
                newTexture.m_ArrayShaderResourceViews[i] = new ShaderResourceView(device, newTexture.m_TextureObject2D, srvViewDesc);
            }

            if (isDepthStencil)
            {
                DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription
                {
                    ArraySize = 6,
                    Format = (format == Format.R32_Typeless) ? Format.D32_Float : Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2DArray,
                    MipSlice = 0,
                    Flags = 0,
                    FirstArraySlice = 0
                };

                newTexture.m_DepthStencilView = new DepthStencilView(device, newTexture.m_TextureObject2D, dsViewDesc);

                newTexture.m_ArrayDepthStencilViews = new DepthStencilView[6];
                for (int i = 0; i < 6; ++i)
                {
                    dsViewDesc.ArraySize = 1;
                    dsViewDesc.FirstArraySlice = i;
                    newTexture.m_ArrayDepthStencilViews[i] = new DepthStencilView(device, newTexture.m_TextureObject2D, dsViewDesc);
                }
            }

            // No RTV for depth stencil, sorry
            if (needsGpuWrite && !isDepthStencil)
            {
                newTexture.m_RenderTargetView = new RenderTargetView(device, newTexture.m_TextureObject2D);

                RenderTargetViewDescription rtvDesc = new RenderTargetViewDescription
                {
                    ArraySize = 6,
                    Dimension = RenderTargetViewDimension.Texture2DArray,
                    FirstArraySlice = 0,
                    Format = format,
                };

                newTexture.m_ArrayRenderTargetViews = new RenderTargetView[6];
                for (int i = 0; i < 6; ++i)
                {
                    rtvDesc.ArraySize = 1;
                    rtvDesc.FirstArraySlice = i;
                    newTexture.m_ArrayRenderTargetViews[i] = new RenderTargetView(device, newTexture.m_TextureObject2D, rtvDesc);
                }

                UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
                {
                    ArraySize = 6,
                    Dimension = UnorderedAccessViewDimension.Texture2DArray,
                    FirstArraySlice = 0,
                    Format = format,
                };
                newTexture.m_UnorderedAccessView = new UnorderedAccessView(device, newTexture.m_TextureObject2D, uavDesc);

                newTexture.m_ArrayUnorderedAccessViews = new UnorderedAccessView[6];
                for (int i = 0; i < 6; ++i)
                {
                    uavDesc.ArraySize = 1;
                    uavDesc.FirstArraySlice = i;
                    newTexture.m_ArrayUnorderedAccessViews[i] = new UnorderedAccessView(device, newTexture.m_TextureObject2D, uavDesc);
                }
            }

            return newTexture;
        }
        void Window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if(device != null)
            {
                //need to remove the reference to the swapchain's backbuffer to enable ResizeBuffers() call
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(
                    sd.BufferCount,
                    (uint)renderHost.ActualWidth,
                    (uint)renderHost.ActualHeight,
                    sd.BufferDescription.Format,
                    sd.Options);

                using(Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
                {
                    renderTargetView = device.CreateRenderTargetView(pBuffer);
                }

                // Create depth stencil texture
                Texture2DDescription descDepth = new Texture2DDescription()
                {
                    Width = (uint)renderHost.ActualWidth,
                    Height = (uint)renderHost.ActualHeight,
                    MipLevels = 1,
                    ArraySize = 1,
                    Format = Format.D32Float,
                    SampleDescription = new SampleDescription()
                    {
                        Count = 1,
                        Quality = 0
                    },
                    BindingOptions = BindingOptions.DepthStencil,
                };

                depthStencil = device.CreateTexture2D(descDepth);

                // Create the depth stencil view
                DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format = descDepth.Format,
                    ViewDimension = DepthStencilViewDimension.Texture2D
                };
                depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

                // bind the views to the device
                device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[ ] { renderTargetView }, depthStencilView);

                // Setup the viewport
                Viewport vp = new Viewport()
                {
                    Width = (uint)renderHost.ActualWidth,
                    Height = (uint)renderHost.ActualHeight,
                    MinDepth = 0.0f,
                    MaxDepth = 1.0f,
                    TopLeftX = 0,
                    TopLeftY = 0
                };

                device.RS.Viewports = new Viewport[ ] { vp };
            }
        }
Beispiel #57
0
            public void OnDeviceInit()
            {
                Texture2DDescription desc = new Texture2DDescription();
                desc.Width = Size.X;
                desc.Height = Size.Y;
                desc.Format = m_resourceFormat;
                desc.ArraySize = 1;
                desc.MipLevels = 1;
                desc.BindFlags = BindFlags.ShaderResource | BindFlags.DepthStencil;
                desc.Usage = ResourceUsage.Default;
                desc.CpuAccessFlags = 0;
                desc.SampleDescription.Count = m_samplesCount;
                desc.SampleDescription.Quality = m_samplesQuality;
                desc.OptionFlags = 0;
                m_resource = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = Name;

                DepthStencilViewDescription dsvDesc = new DepthStencilViewDescription();
                dsvDesc.Format = m_dsvFormat;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.None;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.None;
                }
                m_dsv = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth;
                }
                m_dsv_roDepth = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                    dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil;
                }
                m_dsv_roStencil = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyStencil | DepthStencilViewFlags.ReadOnlyDepth;
                if (m_samplesCount == 1)
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2D;
                    dsvDesc.Texture2D.MipSlice = 0;
                }
                else
                {
                    dsvDesc.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                }
                m_dsv_ro = new DepthStencilView(MyRender11.Device, m_resource, dsvDesc);

                ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();
                srvDesc.Format = m_srvDepthFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvDepth.OnDeviceInit(this, srvDesc);
                srvDesc.Format = m_srvStencilFormat;
                if (m_samplesCount == 1)
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2D;
                    srvDesc.Texture2D.MipLevels = -1;
                    srvDesc.Texture2D.MostDetailedMip = 0;
                }
                else
                {
                    srvDesc.Dimension = ShaderResourceViewDimension.Texture2DMultisampled;
                }
                m_srvStencil.OnDeviceInit(this, srvDesc);
            }
        void InitDevice()
        {
            // create Direct 3D device
            device = D3DDevice.CreateDeviceAndSwapChain(renderHost.Handle);
            swapChain = device.SwapChain;

            // Create a render target view
            using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
            {
                renderTargetView = device.CreateRenderTargetView(pBuffer);
            }

            // Create depth stencil texture
            Texture2DDescription descDepth = new Texture2DDescription()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32Float,
                SampleDescription = new SampleDescription()
                {
                    Count = 1,
                    Quality = 0
                },
                BindingOptions = BindingOptions.DepthStencil,
            };

            depthStencil = device.CreateTexture2D(descDepth);

            // Create the depth stencil view
            DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription()
            {
                Format = descDepth.Format,
                ViewDimension = DepthStencilViewDimension.Texture2D
            };
            depthStencilView = device.CreateDepthStencilView(depthStencil, depthStencilViewDesc);

            // bind the views to the device
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            // Setup the viewport
            Viewport vp = new Viewport()
            {
                Width = (uint)renderHost.ActualWidth,
                Height = (uint)renderHost.ActualHeight,
                MinDepth = 0.0f,
                MaxDepth = 1.0f,
                TopLeftX = 0,
                TopLeftY = 0
            };
            
            device.RS.Viewports = new Viewport[] { vp };
        }
Beispiel #59
0
        private void CreateRenderTargets()
        {
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0);
            sceneView = new RenderTargetView(Device, backBuffer);

            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R32_Typeless,
                Width = WindowWidth,
                Height = WindowHeight,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };
            Texture2D depthBuffer = new Texture2D(Device, depthBufferDesc);

            DepthStencilViewDescription depthStencilDesc = new DepthStencilViewDescription
            {
                ArraySize = 0,
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0,
                Flags = 0,
                FirstArraySlice = 0
            };
            depthView = new DepthStencilView(Device, depthBuffer, depthStencilDesc);
            ShaderResourceViewDescription depthResViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = Format.R32_Float,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = 1,
                Flags = 0,
                FirstArraySlice = 0
            };
            depthResView = new ShaderResourceView(Device, depthBuffer, depthResViewDesc);

            Texture2DDescription densityBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.R8G8B8A8_UNorm,
                Width = WindowWidth,
                Height = WindowHeight,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };
            Texture2D densityBuffer = new Texture2D(Device, densityBufferDesc);

            RenderTargetViewDescription densityViewDesc = new RenderTargetViewDescription
            {
                ArraySize = 0,
                Format = Format.R8G8B8A8_UNorm,
                Dimension = RenderTargetViewDimension.Texture2D,
                MipSlice = 0,
                FirstArraySlice = 0
            };
            densityView = new RenderTargetView(Device, densityBuffer, densityViewDesc);
            ShaderResourceViewDescription densityResViewDesc = new ShaderResourceViewDescription
            {
                ArraySize = 0,
                Format = Format.R8G8B8A8_UNorm,
                Dimension = ShaderResourceViewDimension.Texture2D,
                MipLevels = 1,
                Flags = 0,
                FirstArraySlice = 0
            };
            densityResView = new ShaderResourceView(Device, densityBuffer, densityResViewDesc);
        }
Beispiel #60
0
        private void EnsureOutputBuffers()
        {
            if (SharedTexture == null ||
                SharedTexture.Description.Width != ClientWidth ||
                SharedTexture.Description.Height != ClientHeight)
            {
                if (SharedTexture != null)
                {
                    SharedTexture.Dispose();
                    SharedTexture = null;
                }

                var colordesc = new Texture2DDescription
                {
                    BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                    Format = Format.B8G8R8A8_UNorm,
                    Width = ClientWidth,
                    Height = ClientHeight,
                    MipLevels = 1,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage = ResourceUsage.Default,
                    OptionFlags = ResourceOptionFlags.Shared, // needed for D3DImage
                    CpuAccessFlags = CpuAccessFlags.None,
                    ArraySize = 1
                };

                if (_dxRenderView != null)
                {
                    _dxRenderView.Dispose();
                    _dxRenderView = null;
                }

                SharedTexture = new Texture2D(_dxDevice, colordesc);

                var descRtv = new RenderTargetViewDescription();
                if (colordesc.SampleDescription.Count > 1)
                    descRtv.Dimension = RenderTargetViewDimension.Texture2DMultisampled;
                else
                    descRtv.Dimension = RenderTargetViewDimension.Texture2D;

                _dxRenderView = new RenderTargetView(_dxDevice, SharedTexture, descRtv);
            }

            if (DepthTexture == null ||
                DepthTexture.Description.Width != ClientWidth ||
                DepthTexture.Description.Height != ClientHeight)
            {
                if (DepthTexture != null)
                {
                    DepthTexture.Dispose();
                    DepthTexture = null;
                }

                var depthDesc = new Texture2DDescription
                                    {
                                        BindFlags = BindFlags.DepthStencil,
                                        Format = Format.D32_Float_S8X24_UInt,
                                        Width = ClientWidth,
                                        Height = ClientHeight,
                                        MipLevels = 1,
                                        SampleDescription = new SampleDescription(1, 0), // not using multisampling
                                        Usage = ResourceUsage.Default,
                                        OptionFlags = ResourceOptionFlags.None,
                                        CpuAccessFlags = CpuAccessFlags.None,
                                        ArraySize = 1
                                    };

                // create depth texture
                DepthTexture = new Texture2D(_dxDevice, depthDesc);

                if (_dxDepthStencilView != null)
                {
                    _dxDepthStencilView.Dispose();
                    _dxDepthStencilView = null;
                }

                var descDsv = new DepthStencilViewDescription();
                descDsv.Format = depthDesc.Format;
                if (depthDesc.SampleDescription.Count > 1)
                {
                    descDsv.Dimension = DepthStencilViewDimension.Texture2DMultisampled;
                }
                else
                {
                    descDsv.Dimension = DepthStencilViewDimension.Texture2D;
                }
                descDsv.MipSlice = 0;

                // create depth/stencil view
                _dxDepthStencilView = new DepthStencilView(_dxDevice, DepthTexture, descDsv);
            }
        }