private DescriptorSet(GraphicsDevice graphicsDevice, DescriptorPool pool, DescriptorSetLayout desc)
        {
            if (pool.SrvOffset + desc.SrvCount > pool.SrvCount || pool.SamplerOffset + desc.SamplerCount > pool.SamplerCount)
            {
                // Eearly exit if OOM, IsValid should return false (TODO: different mechanism?)
                Device = null;
                BindingOffsets = null;
                Description = null;
                SrvStart = new CpuDescriptorHandle();
                SamplerStart = new CpuDescriptorHandle();
                return;
            }

            Device = graphicsDevice;
            BindingOffsets = desc.BindingOffsets;
            Description = desc;

            // Store start CpuDescriptorHandle
            SrvStart = desc.SrvCount > 0 ? (pool.SrvStart + graphicsDevice.SrvHandleIncrementSize * pool.SrvOffset) : new CpuDescriptorHandle();
            SamplerStart = desc.SamplerCount > 0 ? (pool.SamplerStart + graphicsDevice.SamplerHandleIncrementSize * pool.SamplerOffset) : new CpuDescriptorHandle();

            // Allocation is done, bump offsets
            // TODO D3D12 thread safety?
            pool.SrvOffset += desc.SrvCount;
            pool.SamplerOffset += desc.SamplerCount;
        }
        private DescriptorPool(GraphicsDevice graphicsDevice, DescriptorTypeCount[] counts) : base(graphicsDevice)
        {
            // For now, we put everything together so let's compute total count
            foreach (var count in counts)
            {
                if (count.Type == EffectParameterClass.Sampler)
                    SamplerCount += count.Count;
                else
                    SrvCount += count.Count;
            }

            if (SrvCount > 0)
            {
                SrvHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SrvCount,
                    Flags = DescriptorHeapFlags.None,
                    Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView,
                });
                SrvStart = SrvHeap.CPUDescriptorHandleForHeapStart;
            }

            if (SamplerCount > 0)
            {
                SamplerHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription
                {
                    DescriptorCount = SamplerCount,
                    Flags = DescriptorHeapFlags.None,
                    Type = DescriptorHeapType.Sampler,
                });
                SamplerStart = SamplerHeap.CPUDescriptorHandleForHeapStart;
            }
        }
Beispiel #3
0
        /// <summary>
        /// <p> Sets CPU descriptor handles for the render targets and depth stencil. </p>
        /// </summary>
        /// <param name="numRenderTargetDescriptors"><dd>  <p> The number of entries in the <em>pRenderTargetDescriptors</em> array. </p> </dd></param>
        /// <param name="renderTargetDescriptorsRef"><dd>  <p> Specifies an array of <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structures that describe the CPU descriptor handles that represents the start of the heap of render target descriptors. </p> </dd></param>
        /// <param name="rTsSingleHandleToDescriptorRange"><dd>  <p><strong>True</strong> means the handle passed in is the reference to a contiguous range of <em>NumRenderTargetDescriptors</em> descriptors.  This case is useful if the set of descriptors to bind already happens to be contiguous in memory (so all that?s needed is a handle to the first one).  For example, if  <em>NumRenderTargetDescriptors</em> is 3 then the memory layout is taken as follows:</p><p>In this case the driver dereferences the handle and then increments the memory being pointed to.</p> <p><strong>False</strong> means that the handle is the first of an array of <em>NumRenderTargetDescriptors</em> handles.  The false case allows an application to bind a set of descriptors from different locations at once. Again assuming that <em>NumRenderTargetDescriptors</em> is 3, the memory layout is taken as follows:</p><p>In this case the driver dereferences three handles that are expected to be adjacent to each other in memory.</p> </dd></param>
        /// <param name="depthStencilDescriptorRef"><dd>  <p> A reference to a <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structure that describes the CPU descriptor handle that represents the start of the heap that holds the depth stencil descriptor. </p> </dd></param>
        /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::OMSetRenderTargets']/*"/>
        /// <msdn-id>dn986884</msdn-id>
        /// <unmanaged>void ID3D12GraphicsCommandList::OMSetRenderTargets([In] unsigned int NumRenderTargetDescriptors,[In, Optional] const void* pRenderTargetDescriptors,[In] BOOL RTsSingleHandleToDescriptorRange,[In, Optional] const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor)</unmanaged>
        /// <unmanaged-short>ID3D12GraphicsCommandList::OMSetRenderTargets</unmanaged-short>
        public unsafe void SetRenderTargets(CpuDescriptorHandle?renderTargetDescriptor, SharpDX.Direct3D12.CpuDescriptorHandle?depthStencilDescriptorRef)
        {
            var renderTargetDesc = new CpuDescriptorHandle();

            if (renderTargetDescriptor.HasValue)
            {
                renderTargetDesc = renderTargetDescriptor.Value;
            }
            SetRenderTargets(renderTargetDesc.Ptr != PointerSize.Zero ? 1 : 0, renderTargetDescriptor.HasValue ? new IntPtr(&renderTargetDesc) : IntPtr.Zero, false, depthStencilDescriptorRef);
        }
Beispiel #4
0
        public override void SetDefaultRenderTarget(int width, int height, bool doClearColor)
        {
            SharpDX.Direct3D12.ResourceBarrier barrier = new SharpDX.Direct3D12.ResourceBarrier();
            barrier.Type  = SharpDX.Direct3D12.ResourceBarrierType.Transition;
            barrier.Flags = SharpDX.Direct3D12.ResourceBarrierFlags.None;
            if (_sampleDesc.Count > 1)
            {
                barrier.Transition = new SharpDX.Direct3D12.ResourceTransitionBarrier(_backBuffersAA[_frameIndex],
                                                                                      SharpDX.Direct3D12.ResourceStates.ResolveSource,
                                                                                      SharpDX.Direct3D12.ResourceStates.RenderTarget)
                {
                    Subresource = 0
                };
            }
            else
            {
                barrier.Transition = new SharpDX.Direct3D12.ResourceTransitionBarrier(_backBuffers[_frameIndex],
                                                                                      SharpDX.Direct3D12.ResourceStates.Present,
                                                                                      SharpDX.Direct3D12.ResourceStates.RenderTarget)
                {
                    Subresource = 0
                };
            }
            _commands.ResourceBarrier(barrier);

            SharpDX.Direct3D12.CpuDescriptorHandle rtv = _heapRTV.CPUDescriptorHandleForHeapStart;
            rtv.Ptr += _frameIndex * _sizeRTV;

            if (doClearColor)
            {
                SharpDX.Mathematics.Interop.RawColor4 clearColor = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f);
                _commands.ClearRenderTargetView(rtv, clearColor, 0, null);
            }

            SharpDX.Direct3D12.CpuDescriptorHandle dsv = _heapDSV.CPUDescriptorHandleForHeapStart;
            _commands.ClearDepthStencilView(dsv, SharpDX.Direct3D12.ClearFlags.FlagsStencil, 0.0f, 0, 0, null);
            _commands.SetRenderTargets(1, rtv, dsv);
            _commands.SetViewports(1, _viewport);
        }
        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;
        }
 /// <summary>	
 /// <p> Sets all the elements in a render target to one value. </p>	
 /// </summary>	
 /// <param name="renderTargetView"><dd>  <p> Specifies a <see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/> structure that describes the CPU descriptor handle that represents the start of the heap for the render target to be cleared. </p> </dd></param>	
 /// <param name="colorRGBA"><dd>  <p> A 4-component array that represents the color to fill the render target with. </p> </dd></param>	
 /// <param name="numRects"><dd>  <p> The number of rectangles in the array that the <em>pRects</em> parameter specifies. </p> </dd></param>	
 /// <param name="rectsRef"><dd>  <p> An array of <strong>D3D12_RECT</strong> structures for the rectangles in the resource view to clear. If <strong><c>null</c></strong>, <strong>ClearRenderTargetView</strong> clears the entire resource view. </p> </dd></param>	
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::ClearRenderTargetView']/*"/>	
 /// <msdn-id>dn903842</msdn-id>	
 /// <unmanaged>void ID3D12GraphicsCommandList::ClearRenderTargetView([In] D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView,[In] const SHARPDX_COLOR4* ColorRGBA,[In] unsigned int NumRects,[In, Buffer] const RECT* pRects)</unmanaged>	
 /// <unmanaged-short>ID3D12GraphicsCommandList::ClearRenderTargetView</unmanaged-short>	
 public void ClearRenderTargetView(CpuDescriptorHandle renderTargetView, Mathematics.Interop.RawColor4 colorRGBA)
 {
     ClearRenderTargetView(renderTargetView, colorRGBA, 0, null);
 }
 /// <summary>	
 /// <p> Sets CPU descriptor handles for the render targets and depth stencil. </p>	
 /// </summary>	
 /// <param name="numRenderTargetDescriptors"><dd>  <p> The number of entries in the <em>pRenderTargetDescriptors</em> array. </p> </dd></param>	
 /// <param name="renderTargetDescriptorsRef"><dd>  <p> Specifies an array of <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structures that describe the CPU descriptor handles that represents the start of the heap of render target descriptors. </p> </dd></param>	
 /// <param name="rTsSingleHandleToDescriptorRange"><dd>  <p><strong>True</strong> means the handle passed in is the reference to a contiguous range of <em>NumRenderTargetDescriptors</em> descriptors.  This case is useful if the set of descriptors to bind already happens to be contiguous in memory (so all that?s needed is a handle to the first one).  For example, if  <em>NumRenderTargetDescriptors</em> is 3 then the memory layout is taken as follows:</p><p>In this case the driver dereferences the handle and then increments the memory being pointed to.</p> <p><strong>False</strong> means that the handle is the first of an array of <em>NumRenderTargetDescriptors</em> handles.  The false case allows an application to bind a set of descriptors from different locations at once. Again assuming that <em>NumRenderTargetDescriptors</em> is 3, the memory layout is taken as follows:</p><p>In this case the driver dereferences three handles that are expected to be adjacent to each other in memory.</p> </dd></param>	
 /// <param name="depthStencilDescriptorRef"><dd>  <p> A reference to a <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structure that describes the CPU descriptor handle that represents the start of the heap that holds the depth stencil descriptor. </p> </dd></param>	
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::OMSetRenderTargets']/*"/>	
 /// <msdn-id>dn986884</msdn-id>	
 /// <unmanaged>void ID3D12GraphicsCommandList::OMSetRenderTargets([In] unsigned int NumRenderTargetDescriptors,[In, Optional] const void* pRenderTargetDescriptors,[In] BOOL RTsSingleHandleToDescriptorRange,[In, Optional] const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor)</unmanaged>	
 /// <unmanaged-short>ID3D12GraphicsCommandList::OMSetRenderTargets</unmanaged-short>	
 public unsafe void SetRenderTargets(CpuDescriptorHandle? renderTargetDescriptor, SharpDX.Direct3D12.CpuDescriptorHandle? depthStencilDescriptorRef)
 {
     var renderTargetDesc = new CpuDescriptorHandle();
     if (renderTargetDescriptor.HasValue)
     {
         renderTargetDesc = renderTargetDescriptor.Value;
     }
     SetRenderTargets(renderTargetDesc.Ptr != PointerSize.Zero ? 1 : 0, renderTargetDescriptor.HasValue ? new IntPtr(&renderTargetDesc) : IntPtr.Zero, false, depthStencilDescriptorRef);
 }
 /// <summary>	
 /// <p> Sets CPU descriptor handles for the render targets and depth stencil. </p>	
 /// </summary>	
 /// <param name="numRenderTargetDescriptors"><dd>  <p> The number of entries in the <em>pRenderTargetDescriptors</em> array. </p> </dd></param>	
 /// <param name="renderTargetDescriptorsRef"><dd>  <p> Specifies an array of <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structures that describe the CPU descriptor handles that represents the start of the heap of render target descriptors. </p> </dd></param>	
 /// <param name="rTsSingleHandleToDescriptorRange"><dd>  <p><strong>True</strong> means the handle passed in is the reference to a contiguous range of <em>NumRenderTargetDescriptors</em> descriptors.  This case is useful if the set of descriptors to bind already happens to be contiguous in memory (so all that?s needed is a handle to the first one).  For example, if  <em>NumRenderTargetDescriptors</em> is 3 then the memory layout is taken as follows:</p><p>In this case the driver dereferences the handle and then increments the memory being pointed to.</p> <p><strong>False</strong> means that the handle is the first of an array of <em>NumRenderTargetDescriptors</em> handles.  The false case allows an application to bind a set of descriptors from different locations at once. Again assuming that <em>NumRenderTargetDescriptors</em> is 3, the memory layout is taken as follows:</p><p>In this case the driver dereferences three handles that are expected to be adjacent to each other in memory.</p> </dd></param>	
 /// <param name="depthStencilDescriptorRef"><dd>  <p> A reference to a <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structure that describes the CPU descriptor handle that represents the start of the heap that holds the depth stencil descriptor. </p> </dd></param>	
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::OMSetRenderTargets']/*"/>	
 /// <msdn-id>dn986884</msdn-id>	
 /// <unmanaged>void ID3D12GraphicsCommandList::OMSetRenderTargets([In] unsigned int NumRenderTargetDescriptors,[In, Optional] const void* pRenderTargetDescriptors,[In] BOOL RTsSingleHandleToDescriptorRange,[In, Optional] const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor)</unmanaged>	
 /// <unmanaged-short>ID3D12GraphicsCommandList::OMSetRenderTargets</unmanaged-short>	
 public unsafe void SetRenderTargets(CpuDescriptorHandle[] renderTargetDescriptors, SharpDX.Direct3D12.CpuDescriptorHandle? depthStencilDescriptorRef)
 {
     fixed (void* pRT = renderTargetDescriptors)
         SetRenderTargets(renderTargetDescriptors != null ? renderTargetDescriptors.Length : 0, new IntPtr(pRT), false, depthStencilDescriptorRef);
 }
 /// <summary>	
 /// <p> Sets CPU descriptor handles for the render targets and depth stencil. </p>	
 /// </summary>	
 /// <param name="numRenderTargetDescriptors"><dd>  <p> The number of entries in the <em>pRenderTargetDescriptors</em> array. </p> </dd></param>	
 /// <param name="renderTargetDescriptorsRef"><dd>  <p> Specifies an array of <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structures that describe the CPU descriptor handles that represents the start of the heap of render target descriptors. </p> </dd></param>	
 /// <param name="rTsSingleHandleToDescriptorRange"><dd>  <p><strong>True</strong> means the handle passed in is the reference to a contiguous range of <em>NumRenderTargetDescriptors</em> descriptors.  This case is useful if the set of descriptors to bind already happens to be contiguous in memory (so all that?s needed is a handle to the first one).  For example, if  <em>NumRenderTargetDescriptors</em> is 3 then the memory layout is taken as follows:</p><p>In this case the driver dereferences the handle and then increments the memory being pointed to.</p> <p><strong>False</strong> means that the handle is the first of an array of <em>NumRenderTargetDescriptors</em> handles.  The false case allows an application to bind a set of descriptors from different locations at once. Again assuming that <em>NumRenderTargetDescriptors</em> is 3, the memory layout is taken as follows:</p><p>In this case the driver dereferences three handles that are expected to be adjacent to each other in memory.</p> </dd></param>	
 /// <param name="depthStencilDescriptorRef"><dd>  <p> A reference to a <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structure that describes the CPU descriptor handle that represents the start of the heap that holds the depth stencil descriptor. </p> </dd></param>	
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::OMSetRenderTargets']/*"/>	
 /// <msdn-id>dn986884</msdn-id>	
 /// <unmanaged>void ID3D12GraphicsCommandList::OMSetRenderTargets([In] unsigned int NumRenderTargetDescriptors,[In, Optional] const void* pRenderTargetDescriptors,[In] BOOL RTsSingleHandleToDescriptorRange,[In, Optional] const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor)</unmanaged>	
 /// <unmanaged-short>ID3D12GraphicsCommandList::OMSetRenderTargets</unmanaged-short>	
 public unsafe void SetRenderTargets(int numRenderTargetDescriptors,
     CpuDescriptorHandle renderTargetDescriptors,
     SharpDX.Direct3D12.CpuDescriptorHandle? depthStencilDescriptorRef)
 {
     SetRenderTargets(numRenderTargetDescriptors, new IntPtr(&renderTargetDescriptors), true, depthStencilDescriptorRef);
 }
Beispiel #10
0
 /// <summary>
 /// Binds a depth-stencil buffer and a set of render targets to the output-merger stage. See <see cref="Textures+and+render+targets"/> to learn how to use it.
 /// </summary>
 /// <param name="depthStencilBuffer">The depth stencil buffer.</param>
 /// <param name="renderTargets">The render targets.</param>
 /// <exception cref="System.ArgumentNullException">renderTargetViews</exception>
 private void SetRenderTargetsImpl(Texture depthStencilBuffer, int renderTargetCount, Texture[] renderTargets)
 {
     var renderTargetHandles = new CpuDescriptorHandle[renderTargetCount];
     for (int i = 0; i < renderTargetHandles.Length; ++i)
     {
         renderTargetHandles[i] = renderTargets[i].NativeRenderTargetView;
     }
     NativeCommandList.SetRenderTargets(renderTargetHandles, depthStencilBuffer?.NativeDepthStencilView);
 }
        private void InitializeFromImpl(DataBox[] dataBoxes = null)
        {
            if (ParentTexture != null)
            {
                ParentResource = ParentTexture;
                NativeDeviceChild = ParentTexture.NativeDeviceChild;
            }

            if (NativeDeviceChild == null)
            {
                ResourceDescription nativeDescription;
                switch (Dimension)
                {
                    case TextureDimension.Texture1D:
                        nativeDescription = ConvertToNativeDescription1D();
                        break;
                    case TextureDimension.Texture2D:
                    case TextureDimension.TextureCube:
                        nativeDescription = ConvertToNativeDescription2D();
                        break;
                    case TextureDimension.Texture3D:
                        nativeDescription = ConvertToNativeDescription3D();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                var initialResourceState = ResourceStates.GenericRead;

                var heapType = HeapType.Default;
                var currentResourceState = initialResourceState;
                if (Usage == GraphicsResourceUsage.Staging)
                {
                    if (dataBoxes != null)
                        throw new NotImplementedException();

                    heapType = HeapType.Readback;
                    initialResourceState = ResourceStates.CopyDestination;
                    currentResourceState = ResourceStates.CopyDestination;
                    nativeDescription = ResourceDescription.Buffer(ComputeBufferTotalSize());

                    // TODO: Alloc in readback heap as a buffer
                    //return;
                }

                if (dataBoxes != null && dataBoxes.Length > 0)
                    currentResourceState = ResourceStates.CopyDestination;

                // TODO D3D12 move that to a global allocator in bigger committed resources
                NativeDeviceChild = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, nativeDescription, currentResourceState);
                GraphicsDevice.TextureMemory += (Depth*DepthStride) / (float)0x100000;

                if (dataBoxes != null && dataBoxes.Length > 0)
                {
                    if (Usage == GraphicsResourceUsage.Staging)
                        throw new NotImplementedException("D3D12: Staging textures can't be created with initial data");

                    // Trigger copy
                    var commandList = GraphicsDevice.NativeCopyCommandList;
                    commandList.Reset(GraphicsDevice.NativeCopyCommandAllocator, null);

                    long textureCopySize;
                    var placedSubresources = new PlacedSubResourceFootprint[dataBoxes.Length];
                    var rowCounts = new int[dataBoxes.Length];
                    var rowSizeInBytes = new long[dataBoxes.Length];
                    GraphicsDevice.NativeDevice.GetCopyableFootprints(ref nativeDescription, 0, dataBoxes.Length, 0, placedSubresources, rowCounts, rowSizeInBytes, out textureCopySize);

                    SharpDX.Direct3D12.Resource uploadResource;
                    int uploadOffset;
                    var uploadMemory = GraphicsDevice.AllocateUploadBuffer((int)textureCopySize, out uploadResource, out uploadOffset, TextureSubresourceAlignment);

                    for (int i = 0; i < dataBoxes.Length; ++i)
                    {
                        var databox = dataBoxes[i];
                        var dataPointer = databox.DataPointer;

                        var rowCount = rowCounts[i];
                        var sliceCount = placedSubresources[i].Footprint.Depth;
                        var rowSize = (int)rowSizeInBytes[i];
                        var destRowPitch = placedSubresources[i].Footprint.RowPitch;

                        // Memcpy data
                        for (int z = 0; z < sliceCount; ++z)
                        {
                            var uploadMemoryCurrent = uploadMemory + (int)placedSubresources[i].Offset + z * destRowPitch * rowCount;
                            var dataPointerCurrent = dataPointer + z * databox.SlicePitch;
                            for (int y = 0; y < rowCount; ++y)
                            {
                                Utilities.CopyMemory(uploadMemoryCurrent, dataPointerCurrent, rowSize);
                                uploadMemoryCurrent += destRowPitch;
                                dataPointerCurrent += databox.RowPitch;
                            }
                        }

                        // Adjust upload offset (circular dependency between GetCopyableFootprints and AllocateUploadBuffer)
                        placedSubresources[i].Offset += uploadOffset;

                        commandList.CopyTextureRegion(new TextureCopyLocation(NativeResource, i), 0, 0, 0, new TextureCopyLocation(uploadResource, placedSubresources[i]), null);
                    }

                    commandList.ResourceBarrierTransition(NativeResource, ResourceStates.CopyDestination, initialResourceState);
                    commandList.Close();

                    GraphicsDevice.WaitCopyQueue();
                }

                NativeResourceState = initialResourceState;
            }

            NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel);
            NativeRenderTargetView = GetRenderTargetView(ViewType, ArraySlice, MipLevel);
            NativeDepthStencilView = GetDepthStencilView(out HasStencil);
        }
        private void LoadMesh(CpuDescriptorHandle heapStart)
        {
            SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter = Filter.ComparisonMinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MinimumLod = float.MinValue,
                MaximumLod = float.MaxValue,
                MipLodBias = 0,
                MaximumAnisotropy = 0,
                ComparisonFunction = Comparison.Never

            };
            var heapPosition = heapStart;

            // Load model from obj.
            var importer = new Assimp.AssimpContext();
            var scene = importer.ImportFile(@"../../../Models/lara/lara.obj", PostProcessSteps.GenerateSmoothNormals | PostProcessSteps.FlipUVs | PostProcessSteps.PreTransformVertices);

            Vertex[] vertices = new Vertex[scene.Meshes.Sum(m => m.VertexCount)];
            int[] indices = new int[scene.Meshes.Sum(m => m.FaceCount * 3)];
            faceCounts = new List<int>();

            int vertexOffSet = 0;
            int indexOffSet = 0;
            foreach (var mesh in scene.Meshes)
            {
                var positions = mesh.Vertices;
                var normals = mesh.Normals;
                var texs = mesh.TextureCoordinateChannels[0];
                for (int i = 0; i < mesh.VertexCount; i++)
                {
                    vertices[vertexOffSet + i] = new Vertex()
                    {
                        position = new Vector3(positions[i].X, positions[i].Y, positions[i].Z),
                        normal = new Vector3(normals[i].X, normals[i].Y, normals[i].Z),
                        textureCoordinate = new Vector3(texs[i].X, texs[i].Y, texs[i].Z)
                    };
                }

                var faces = mesh.Faces;
                for (int i = 0; i < mesh.FaceCount; i++)
                {
                    indices[i * 3 + indexOffSet] = (int)faces[i].Indices[0] + vertexOffSet;
                    indices[i * 3 + 1 + indexOffSet] = (int)faces[i].Indices[1] + vertexOffSet;
                    indices[i * 3 + 2 + indexOffSet] = (int)faces[i].Indices[2] + vertexOffSet;
                }

                faceCounts.Add(mesh.FaceCount * 3);
                vertexOffSet += mesh.VertexCount;
                indexOffSet += mesh.FaceCount * 3;

                string textureName = System.IO.Path.GetFileName(scene.Materials[mesh.MaterialIndex].TextureDiffuse.FilePath);
                var texResource = TextureUtilities.CreateTextureFromDDS(device, @"../../../Models/lara/" + textureName);
                textures.Add(texResource);

                int D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING = 5768;
                ShaderResourceViewDescription desc = new ShaderResourceViewDescription
                {
                    Dimension = ShaderResourceViewDimension.Texture2D,
                    Format = texResource.Description.Format,
                    Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
                };
                desc.Texture2D.MipLevels = 1;
                desc.Texture2D.MostDetailedMip = 0;
                desc.Texture2D.ResourceMinLODClamp = 0;

                device.CreateShaderResourceView(texResource, desc, heapStart);
                heapStart += constantBufferDescriptorSize;
            }

            int vertexBufferSize = Utilities.SizeOf(vertices);

            // Note: using upload heaps to transfer static data like vert buffers is not
            // recommended. Every time the GPU needs it, the upload heap will be marshalled
            // over. Please read up on Default Heap usage. An upload heap is used here for
            // code simplicity and because there are very few verts to actually transfer.
            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, vertices, 0, vertices.Length);
            vertexBuffer.Unmap(0);

            // Initialize the vertex buffer view.
            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            //Create Index Buffer
            int indexBufferSize = Utilities.SizeOf(indices);
            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);

            // Copy the triangle data to the vertex buffer.
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, indices, 0, indices.Length);
            indexBuffer.Unmap(0);

            // Initialize the index buffer view.
            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.Format = Format.R32_UInt;
            indexBufferView.SizeInBytes = indexBufferSize;
        }
Beispiel #13
0
 /// <summary>
 /// <p> Sets CPU descriptor handles for the render targets and depth stencil. </p>
 /// </summary>
 /// <param name="numRenderTargetDescriptors"><dd>  <p> The number of entries in the <em>pRenderTargetDescriptors</em> array. </p> </dd></param>
 /// <param name="renderTargetDescriptorsRef"><dd>  <p> Specifies an array of <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structures that describe the CPU descriptor handles that represents the start of the heap of render target descriptors. </p> </dd></param>
 /// <param name="rTsSingleHandleToDescriptorRange"><dd>  <p><strong>True</strong> means the handle passed in is the reference to a contiguous range of <em>NumRenderTargetDescriptors</em> descriptors.  This case is useful if the set of descriptors to bind already happens to be contiguous in memory (so all that?s needed is a handle to the first one).  For example, if  <em>NumRenderTargetDescriptors</em> is 3 then the memory layout is taken as follows:</p><p>In this case the driver dereferences the handle and then increments the memory being pointed to.</p> <p><strong>False</strong> means that the handle is the first of an array of <em>NumRenderTargetDescriptors</em> handles.  The false case allows an application to bind a set of descriptors from different locations at once. Again assuming that <em>NumRenderTargetDescriptors</em> is 3, the memory layout is taken as follows:</p><p>In this case the driver dereferences three handles that are expected to be adjacent to each other in memory.</p> </dd></param>
 /// <param name="depthStencilDescriptorRef"><dd>  <p> A reference to a <strong><see cref="SharpDX.Direct3D12.CpuDescriptorHandle"/></strong> structure that describes the CPU descriptor handle that represents the start of the heap that holds the depth stencil descriptor. </p> </dd></param>
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::OMSetRenderTargets']/*"/>
 /// <msdn-id>dn986884</msdn-id>
 /// <unmanaged>void ID3D12GraphicsCommandList::OMSetRenderTargets([In] unsigned int NumRenderTargetDescriptors,[In, Optional] const void* pRenderTargetDescriptors,[In] BOOL RTsSingleHandleToDescriptorRange,[In, Optional] const D3D12_CPU_DESCRIPTOR_HANDLE* pDepthStencilDescriptor)</unmanaged>
 /// <unmanaged-short>ID3D12GraphicsCommandList::OMSetRenderTargets</unmanaged-short>
 public unsafe void SetRenderTargets(int numRenderTargetDescriptors,
                                     CpuDescriptorHandle renderTargetDescriptors,
                                     SharpDX.Direct3D12.CpuDescriptorHandle?depthStencilDescriptorRef)
 {
     SetRenderTargets(numRenderTargetDescriptors, new IntPtr(&renderTargetDescriptors), true, depthStencilDescriptorRef);
 }
Beispiel #14
0
        void CreateBuffers()
        {
            SharpDX.Direct3D12.CpuDescriptorHandle rtv   = _heapRTV.CPUDescriptorHandleForHeapStart;
            SharpDX.Direct3D12.HeapFlags           flags = SharpDX.Direct3D12.HeapFlags.None;

            _frameIndex = _swapChain.CurrentBackBufferIndex;
            SharpDX.DXGI.SwapChainDescription1 swapChainDesc = _swapChain.Description1;

            // TODO: Check ID3D12Device8 to enable D3D12_HEAP_FLAG_CREATE_NOT_ZEROED

            SharpDX.Direct3D12.ResourceDescription desc = new SharpDX.Direct3D12.ResourceDescription();
            desc.Dimension         = SharpDX.Direct3D12.ResourceDimension.Texture2D;
            desc.Alignment         = 0;
            desc.Width             = swapChainDesc.Width;
            desc.Height            = swapChainDesc.Height;
            desc.DepthOrArraySize  = 1;
            desc.MipLevels         = 1;
            desc.SampleDescription = _sampleDesc;
            desc.Layout            = SharpDX.Direct3D12.TextureLayout.Unknown;

            SharpDX.Direct3D12.HeapProperties heap = new SharpDX.Direct3D12.HeapProperties();
            heap.Type                 = SharpDX.Direct3D12.HeapType.Default;
            heap.CPUPageProperty      = SharpDX.Direct3D12.CpuPageProperty.Unknown;
            heap.MemoryPoolPreference = SharpDX.Direct3D12.MemoryPool.Unknown;
            heap.CreationNodeMask     = 0;
            heap.VisibleNodeMask      = 0;

            SharpDX.Direct3D12.ClearValue clearValue = new SharpDX.Direct3D12.ClearValue();
            clearValue.Format = _format;
            clearValue.Color  = new SharpDX.Mathematics.Interop.RawVector4(0.0f, 0.0f, 0.0f, 0.0f);

            for (int i = 0; i < FrameCount; i++)
            {
                desc.Format = _format;
                desc.Flags  = SharpDX.Direct3D12.ResourceFlags.AllowRenderTarget;

                _backBuffers[i] = _swapChain.GetBackBuffer <SharpDX.Direct3D12.Resource>(i);

                if (_sampleDesc.Count != 1)
                {
                    _backBuffersAA[i] = _dev.CreateCommittedResource(heap, flags, desc, SharpDX.Direct3D12.ResourceStates.ResolveSource, clearValue);
                    _dev.CreateRenderTargetView(_backBuffersAA[i], null, rtv);
                }
                else
                {
                    SharpDX.Direct3D12.RenderTargetViewDescription view = new SharpDX.Direct3D12.RenderTargetViewDescription();
                    view.Format               = _format;
                    view.Dimension            = SharpDX.Direct3D12.RenderTargetViewDimension.Texture2D;
                    view.Texture2D.MipSlice   = 0;
                    view.Texture2D.PlaneSlice = 0;

                    _dev.CreateRenderTargetView(_backBuffers[i], view, rtv);
                }

                rtv.Ptr += _sizeRTV;
            }

            // Stencil buffer
            clearValue.Format               = SharpDX.DXGI.Format.D24_UNorm_S8_UInt;
            clearValue.DepthStencil.Depth   = 0.0f;
            clearValue.DepthStencil.Stencil = 0;

            desc.Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt;
            desc.Flags  = SharpDX.Direct3D12.ResourceFlags.AllowDepthStencil;

            _stencilBuffer = _dev.CreateCommittedResource(heap, flags, desc, SharpDX.Direct3D12.ResourceStates.DepthWrite, clearValue);

            SharpDX.Direct3D12.CpuDescriptorHandle dsv = _heapDSV.CPUDescriptorHandleForHeapStart;
            _dev.CreateDepthStencilView(_stencilBuffer, null, dsv);

            // Viewport
            _viewport[0].TopLeftX = 0.0f;
            _viewport[0].TopLeftY = 0.0f;
            _viewport[0].Width    = desc.Width;
            _viewport[0].Height   = desc.Height;
            _viewport[0].MinDepth = 0.0f;
            _viewport[0].MaxDepth = 1.0f;
        }
        private void LoadAssets()
        {
            // Create the root signature description.
            var rootSignatureDesc = new RootSignatureDescription(

                RootSignatureFlags.AllowInputAssemblerInputLayout,
                // Root Parameters
                new[]
                {
                    new RootParameter(ShaderVisibility.All,
                        new []
                        {
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ShaderResourceView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue,
                                BaseShaderRegister = 0
                            },
                            new DescriptorRange()
                            {
                                RangeType = DescriptorRangeType.ConstantBufferView,
                                DescriptorCount = 1,
                                OffsetInDescriptorsFromTableStart = int.MinValue + 1,
                                BaseShaderRegister = 0
                            }
                        }),
                    new RootParameter(ShaderVisibility.Pixel,
                        new DescriptorRange()
                        {
                            RangeType = DescriptorRangeType.Sampler,
                            DescriptorCount = 1,
                            OffsetInDescriptorsFromTableStart = int.MinValue,
                            BaseShaderRegister = 0
                        }),
                });
                //// Samplers
                //new[]
                //{
                //    new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0)
                //    {
                //        Filter = Filter.MinimumMinMagMipPoint,
                //        AddressUVW = TextureAddressMode.Border,
                //    }
                //});

            rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize());

            // Create the pipeline state, which includes compiling and loading shaders.
            #if DEBUG
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0"));
            #endif

            #if DEBUG
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            #if DEBUG
            //var result = SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug);
            var geometryShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("../../shaders.hlsl"), "GSMain", "gs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug));
            #else
            var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0"));
            #endif

            // Define the vertex input layout.
            var inputElementDescs = new[]
            {
                    new InputElement("POSITION",0,Format.R32G32B32_Float,0,0),
                    new InputElement("TEXCOORD",0,Format.R32G32_Float,12,0)
            };

            // Describe and create the graphics pipeline state object (PSO).
            var psoDesc = new GraphicsPipelineStateDescription()
            {
                InputLayout = new InputLayoutDescription(inputElementDescs),
                RootSignature = rootSignature,
                VertexShader = vertexShader,
                GeometryShader = geometryShader,
                PixelShader = pixelShader,
                RasterizerState = RasterizerStateDescription.Default(),
                BlendState = BlendStateDescription.Default(),
                DepthStencilFormat = SharpDX.DXGI.Format.D32_Float,
                DepthStencilState = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = DepthWriteMask.All,
                    IsStencilEnabled = false
                },
                SampleMask = int.MaxValue,
                PrimitiveTopologyType = PrimitiveTopologyType.Triangle,
                RenderTargetCount = 1,
                Flags = PipelineStateFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                StreamOutput = new StreamOutputDescription()
            };
            psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm;

            pipelineState = device.CreateGraphicsPipelineState(psoDesc);

            commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState);
            commandList.Close();

            // build vertex buffer

            var triangleVertices = new[]
            {
                //TOP
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //BOTTOM
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                //LEFT
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                //RIGHT
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)} ,
                //FRONT
                new Vertex() {Position = new Vector3(-1f , 1f , 1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f , 1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f , 1f) , TexCoord = new Vector2(0f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f , 1f) , TexCoord = new Vector2(1f ,1f)} ,
                //BACK
                new Vertex() {Position = new Vector3(-1f , 1f ,-1f) , TexCoord = new Vector2(0f ,0f)} ,
                new Vertex() {Position = new Vector3(1f , 1f ,-1f) , TexCoord = new Vector2(1f ,0f)} ,
                new Vertex() {Position = new Vector3(1f ,-1f ,-1f) , TexCoord = new Vector2(1f ,1f)} ,
                new Vertex() {Position = new Vector3(-1f ,-1f ,-1f) , TexCoord = new Vector2(0f ,1f)}
            };

            int vertexBufferSize = Utilities.SizeOf(triangleVertices);

            vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead);
            IntPtr pVertexDataBegin = vertexBuffer.Map(0);
            Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length);
            vertexBuffer.Unmap(0);

            vertexBufferView = new VertexBufferView();
            vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress;
            vertexBufferView.StrideInBytes = Utilities.SizeOf<Vertex>();
            vertexBufferView.SizeInBytes = vertexBufferSize;

            // build index buffer

            var triangleIndexes = new uint[]
            {
                0,1,2,
                0,2,3,

                4,6,5,
                4,7,6,

                8,9,10,
                8,10,11,

                12,14,13,
                12,15,14,

                16,18,17,
                16,19,18,

                20,21,22,
                20,22,23
            };

            int indexBufferSize = Utilities.SizeOf(triangleIndexes);

            indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indexBufferSize), ResourceStates.GenericRead);
            IntPtr pIndexDataBegin = indexBuffer.Map(0);
            Utilities.Write(pIndexDataBegin, triangleIndexes, 0, triangleIndexes.Length);
            indexBuffer.Unmap(0);

            indexBufferView = new IndexBufferView();
            indexBufferView.BufferLocation = indexBuffer.GPUVirtualAddress;
            indexBufferView.SizeInBytes = indexBufferSize;
            indexBufferView.Format = Format.R32_UInt;

            // Create the texture.
            // Describe and create a Texture2D.
            var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight, 1, 1, 1, 0, ResourceFlags.None, TextureLayout.Unknown, 0);
            texture = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, textureDesc, ResourceStates.GenericRead, null);

            // Copy data to the intermediate upload heap and then schedule a copy
            // from the upload heap to the Texture2D.
            byte[] textureData = Utilities.ReadStream(new FileStream("../../texture1.dds", FileMode.Open));

            texture.Name = "Texture";

            var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned);
            var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0);
            texture.WriteToSubresource(0, null, ptr, TextureWidth * 4, textureData.Length);
            handle.Free();

            // Describe and create a SRV for the texture.
            var srvDesc = new ShaderResourceViewDescription
            {
                Shader4ComponentMapping = ((((0) & 0x7) |(((1) & 0x7) << 3) |(((2) & 0x7) << (3 * 2)) |(((3) & 0x7) << (3 * 3)) | (1 << (3 * 4)))),

                Format = textureDesc.Format,
                Dimension = ShaderResourceViewDimension.Texture2D,
                Texture2D =
                {
                    MipLevels = 1,
                    MostDetailedMip = 0,
                    PlaneSlice = 0,
                    ResourceMinLODClamp = 0.0f
                },
            };

            device.CreateShaderResourceView(texture, srvDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart);

            SamplerStateDescription samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MaximumAnisotropy = 0,
                MaximumLod = float.MaxValue,
                MinimumLod = -float.MaxValue,
                MipLodBias = 0,
                ComparisonFunction = Comparison.Never
            };

            device.CreateSampler(samplerDesc, samplerViewHeap.CPUDescriptorHandleForHeapStart);

            // build constant buffer

            constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead);

            var cbDesc = new ConstantBufferViewDescription()
            {
                BufferLocation = constantBuffer.GPUVirtualAddress,
                SizeInBytes = (Utilities.SizeOf<ConstantBufferData>() + 255) & ~255
            };
            var srvCbvStep = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateConstantBufferView(cbDesc, srvCbvHeap.CPUDescriptorHandleForHeapStart + srvCbvStep);

            constantBufferData = new ConstantBufferData
            {
                Project = Matrix.Identity
            };

            constantBufferPointer = constantBuffer.Map(0);
            Utilities.Write(constantBufferPointer, ref constantBufferData);

            // build depth buffer

            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;

            fence = device.CreateFence(0, FenceFlags.None);
            fenceValue = 1;
            fenceEvent = new AutoResetEvent(false);
        }
Beispiel #16
0
 /// <summary>
 /// No documentation for Direct3D12
 /// </summary>
 /// <param name="renderTargetView">No documentation.</param>
 /// <param name="colorRGBA">No documentation.</param>
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='ID3D12GraphicsCommandList::ClearRenderTargetView']/*"/>
 /// <unmanaged>void ID3D12GraphicsCommandList::ClearRenderTargetView([In] D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView,[In] const SHARPDX_COLOR4* ColorRGBA,[In] unsigned int NumRects,[In, Buffer] const RECT* pRects)</unmanaged>
 /// <unmanaged-short>ID3D12GraphicsCommandList::ClearRenderTargetView</unmanaged-short>
 public void ClearRenderTargetView(CpuDescriptorHandle renderTargetView, Mathematics.Interop.RawColor4 colorRGBA)
 {
     ClearRenderTargetView(renderTargetView, colorRGBA, 0, null);
 }
        /// <summary>
        /// Gets a <see cref="ShaderResourceView"/> for a particular <see cref="PixelFormat"/>.
        /// </summary>
        /// <param name="viewFormat">The view format.</param>
        /// <returns>A <see cref="ShaderResourceView"/> for the particular view format.</returns>
        /// <remarks>
        /// The buffer must have been declared with <see cref="Graphics.BufferFlags.ShaderResource"/>. 
        /// The ShaderResourceView instance is kept by this buffer and will be disposed when this buffer is disposed.
        /// </remarks>
        internal CpuDescriptorHandle GetShaderResourceView(PixelFormat viewFormat)
        {
            var srv = new CpuDescriptorHandle();
            if ((ViewFlags & BufferFlags.ShaderResource) != 0)
            {
                var description = new ShaderResourceViewDescription
                {
                    Shader4ComponentMapping = 0x00001688,
                    Format = (SharpDX.DXGI.Format)viewFormat,
                    Dimension = SharpDX.Direct3D12.ShaderResourceViewDimension.Buffer,
                    Buffer =
                    {
                        ElementCount = this.ElementCount,
                        FirstElement = 0,
                        Flags = BufferShaderResourceViewFlags.None,
                        StructureByteStride = StructureByteStride,
                    }
                };

                if (((ViewFlags & BufferFlags.RawBuffer) == BufferFlags.RawBuffer))
                    description.Buffer.Flags |= BufferShaderResourceViewFlags.Raw;

                srv = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1);
                NativeDevice.CreateShaderResourceView(NativeResource, description, srv);
            }
            return srv;
        }