Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceTransitionBarrier"/> struct.
 /// </summary>
 /// <param name="resource">The <see cref="ID3D12Resource"/>.</param>
 /// <param name="stateBefore">The state before.</param>
 /// <param name="stateAfter">The state after.</param>
 /// <param name="subresource">The subresource.</param>
 /// <exception cref="System.ArgumentNullException">resource</exception>
 public ResourceTransitionBarrier(ID3D12Resource resource, ResourceStates stateBefore, ResourceStates stateAfter, int subresource = D3D12.ResourceBarrierAllSubResources)
 {
     ResourcePointer = resource.NativePointer;
     Subresource     = subresource;
     StateBefore     = stateBefore;
     StateAfter      = stateAfter;
 }
Beispiel #2
0
        internal Texture InitializeFrom(ID3D12Resource resource, TextureDescription description)
        {
            NativeResource = resource;
            Description    = description;

            if (description.Flags.HasFlag(TextureFlags.DepthStencil))
            {
                NativeDepthStencilView = CreateDepthStencilView();
            }

            if (description.Flags.HasFlag(TextureFlags.RenderTarget))
            {
                NativeRenderTargetView = CreateRenderTargetView();
            }

            if (description.Flags.HasFlag(TextureFlags.ShaderResource))
            {
                NativeShaderResourceView = CreateShaderResourceView();
            }

            if (description.Flags.HasFlag(TextureFlags.UnorderedAccess))
            {
                NativeUnorderedAccessView = CreateUnorderedAccessView();
            }

            return(this);
        }
        public void CreateAccelerationStructures()
        {
            acs = new AccelerationStructures();

            long mTlasSize = 0;

            ID3D12Resource[] mpVertexBuffer = new ID3D12Resource[2];
            mpVertexBuffer[0] = acs.CreateTriangleVB(mpDevice);
            mpVertexBuffer[1] = acs.CreatePlaneVB(mpDevice);

            // The first bottom-level buffer is for the plane and the triangle
            int[] vertexCount = new int[] { 3, 6 }; // Triangle has 3 vertices, plane has 6
            AccelerationStructureBuffers[] bottomLevelBuffers = new AccelerationStructureBuffers[2];
            bottomLevelBuffers[0] = acs.CreateBottomLevelAS(mpDevice, mpCmdList, mpVertexBuffer, vertexCount, 2);
            mpBottomLevelAS       = new ID3D12Resource[2];
            mpBottomLevelAS[0]    = bottomLevelBuffers[0].pResult;

            // The second bottom-level buffer is for the triangle only
            bottomLevelBuffers[1] = acs.CreateBottomLevelAS(mpDevice, mpCmdList, mpVertexBuffer, vertexCount, 1);
            mpBottomLevelAS[1]    = bottomLevelBuffers[1].pResult;

            // Create the TLAS
            AccelerationStructureBuffers topLevelBuffers = acs.CreateTopLevelAS(mpDevice, mpCmdList, mpBottomLevelAS, ref mTlasSize);

            // The tutorial doesn't have any resource lifetime management, so we flush and sync here. This is not required by the DXR spec - you can submit the list whenever you like as long as you take care of the resources lifetime.
            mFenceValue = context.SubmitCommandList(mpCmdList, mpCmdQueue, mpFence, mFenceValue);
            mpFence.SetEventOnCompletion(mFenceValue, mFenceEvent);
            mFenceEvent.WaitOne();
            int bufferIndex = mpSwapChain.GetCurrentBackBufferIndex();

            mpCmdList.Reset(mFrameObjects[0].pCmdAllocator, null);

            // Store the AS buffers. The rest of the buffers will be released once we exit the function
            mpTopLevelAS = topLevelBuffers.pResult;
        }
 public unsafe void UpdateTileMappings(
     ID3D12Resource resource,
     ReadOnlySpan <TiledResourceCoordinate> resourceRegionStartCoordinates,
     ReadOnlySpan <TileRegionSize> resourceRegionSizes,
     ID3D12Heap heap,
     ReadOnlySpan <TileRangeFlags> rangeFlags,
     ReadOnlySpan <int> heapRangeStartOffsets,
     ReadOnlySpan <int> rangeTileCounts,
     TileMappingFlags flags = TileMappingFlags.None)
 {
     fixed(TiledResourceCoordinate *pResourceRegionStartCoordinates = resourceRegionStartCoordinates)
     fixed(TileRegionSize * pResourceRegionSizes = resourceRegionSizes)
     fixed(TileRangeFlags * pRangeFlags          = rangeFlags)
     fixed(int *pHeapRangeStartOffsets           = heapRangeStartOffsets)
     fixed(int *pRangeTileCounts = rangeTileCounts)
     UpdateTileMappings(resource,
                        resourceRegionStartCoordinates.Length,
                        pResourceRegionStartCoordinates,
                        pResourceRegionSizes,
                        heap,
                        rangeFlags.Length,
                        pRangeFlags,
                        pHeapRangeStartOffsets,
                        pRangeTileCounts,
                        flags);
 }
Beispiel #5
0
        internal Texture InitializeFrom(ID3D12Resource resource, bool isShaderResource = false)
        {
            resource.GetHeapProperties(out HeapProperties heapProperties, out _);

            TextureDescription description = ConvertFromNativeDescription(resource.Description, (GraphicsHeapType)heapProperties.Type, isShaderResource);

            return(InitializeFrom(resource, description));
        }
Beispiel #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceAliasingBarrier"/> struct.
        /// </summary>
        /// <param name="resourceBefore">The resource before.</param>
        /// <param name="resourceAfter">The resource after.</param>
        /// <exception cref="System.ArgumentNullException">resourceBefore</exception>
        public ResourceAliasingBarrier(ID3D12Resource resourceBefore, ID3D12Resource resourceAfter)
        {
            Guard.NotNull(resourceBefore, nameof(resourceBefore));
            Guard.NotNull(resourceAfter, nameof(resourceAfter));

            ResourceBeforePointer = resourceBefore.NativePointer;
            ResourceAfterPointer  = resourceAfter.NativePointer;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceTransitionBarrier"/> struct.
 /// </summary>
 /// <param name="resource">The <see cref="ID3D12Resource"/>.</param>
 /// <param name="stateBefore">The state before.</param>
 /// <param name="stateAfter">The state after.</param>
 /// <param name="subresource">The subresource.</param>
 /// <exception cref="System.ArgumentNullException">resource</exception>
 public ResourceTransitionBarrier(ID3D12Resource resource, ResourceStates stateBefore, ResourceStates stateAfter, int subresource = -1)
 {
     Guard.NotNull(resource, nameof(resource));
     ResourcePointer = resource.NativePointer;
     Subresource     = subresource;
     StateBefore     = stateBefore;
     StateAfter      = stateAfter;
     Subresource     = subresource;
 }
Beispiel #8
0
 public void Dispose()
 {
     resource?.Dispose();
     resource = null;
     renderTargetView?.Dispose();
     renderTargetView = null;
     depthStencilView?.Dispose();
     depthStencilView = null;
 }
Beispiel #9
0
 public void DestroyResource(ID3D12Resource res)
 {
     if (res != null)
     {
         delayDestroy.Enqueue(new ResourceDelayDestroy {
             resource = res, destroyFrame = executeCount
         });
     }
 }
Beispiel #10
0
 private void InsertTransitionResourceBarriers(ID3D12Resource swapChainBuffer, ResourceStates[] before, ResourceStates[] after)
 {
     ResourceBarrier[] barriers = new ResourceBarrier[before.Length];
     for (int i = 0; i < barriers.Length; i++)
     {
         var transition = new ResourceTransitionBarrier(swapChainBuffer, before[i], after[i], ResourceBarrier.AllSubResources);
         barriers[i] = new ResourceBarrier(transition, ResourceBarrierFlags.None);
     }
     commandList.ResourceBarrier(barriers);
 }
Beispiel #11
0
 public void Dispose()
 {
     foreach (var vtbuf in vtBuffers)
     {
         vtbuf.Value.Dispose();
     }
     vtBuffers.Clear();
     indexBuffer?.Release();
     indexBuffer = null;
 }
Beispiel #12
0
 /// <summary>
 /// Discards a resource.
 /// </summary>
 /// <param name="resource">The resource to discard.</param>
 /// <param name="firstSubresource">Index of the first subresource in the resource to discard.</param>
 /// <param name="numSubresources">The number of subresources in the resource to discard.</param>
 public void DiscardResource(ID3D12Resource resource, int firstSubresource, int numSubresources)
 {
     DiscardResource(resource, new DiscardRegion
     {
         NumRects         = 0,
         PRects           = IntPtr.Zero,
         FirstSubresource = firstSubresource,
         NumSubresources  = numSubresources
     });
 }
        public AccelerationStructureBuffers CreatePrimitiveBottomLevelAS(ID3D12Device5 pDevice, ID3D12GraphicsCommandList4 pCmdList)
        {
            this.CreatePrimitive(PrimitiveType.Sphere, pDevice, out ID3D12Resource primitiveVertexBuffer, out uint primitiveVertexCount, out ID3D12Resource primitiveIndexBuffer, out uint primitiveIndexCount);
            this.VertexBuffer = primitiveVertexBuffer;
            this.VertexCount  = primitiveVertexCount;
            this.IndexBuffer  = primitiveIndexBuffer;
            this.IndexCount   = primitiveIndexCount;

            return(this.CreateBottomLevelAS(pDevice, pCmdList, primitiveVertexBuffer, primitiveVertexCount, primitiveIndexBuffer, primitiveIndexCount));
        }
Beispiel #14
0
        public unsafe void CreateShaderTable()
        {
            /** The shader-table layout is as follows:
             *  Entry 0 - Ray-gen program
             *  Entry 1 - Miss program
             *  Entry 2 - Hit program
             *  All entries in the shader-table must have the same size, so we will choose it base on the largest required entry.
             *  The ray-gen program requires the largest entry - sizeof(program identifier) + 8 bytes for a descriptor-table.
             *  The entry size must be aligned up to D3D12_RAYTRACING_SHADER_RECORD_BYTE_ALIGNMENT
             */

            // Calculate the size and create the buffer
            mShaderTableEntrySize  = D3D12ShaderIdentifierSizeInBytes;
            mShaderTableEntrySize += 8; // the ray-gen's descriptor table
            mShaderTableEntrySize  = align_to(D3D12RaytracingShaderRecordByteAlignment, mShaderTableEntrySize);
            uint shaderTableSize = mShaderTableEntrySize * 4;

            // For simplicity, we create the shader.table on the upload heap. You can also create it on the default heap
            mpShaderTable = this.acs.CreateBuffer(mpDevice, shaderTableSize, ResourceFlags.None, ResourceStates.GenericRead, AccelerationStructures.kUploadHeapProps);

            // Map the buffer
            IntPtr pData;

            pData = mpShaderTable.Map(0, null);

            ID3D12StateObjectProperties pRtsoProps;

            pRtsoProps = mpPipelineState.QueryInterface <ID3D12StateObjectProperties>();

            // Entry 0 - ray-gen program ID and descriptor data
            Unsafe.CopyBlock((void *)pData, (void *)pRtsoProps.GetShaderIdentifier(RTPipeline.kRayGenShader), D3D12ShaderIdentifierSizeInBytes);

            ulong heapStart = (ulong)mpSrvUavHeap.GetGPUDescriptorHandleForHeapStart().Ptr;

            Unsafe.Write <ulong>((pData + (int)D3D12ShaderIdentifierSizeInBytes).ToPointer(), heapStart);

            // This is where we need to set the descriptor data for the ray-gen shader. We'll get to it in the next tutorial

            // Entry 1 - miss program
            pData += (int)mShaderTableEntrySize; // +1 skips ray-gen
            Unsafe.CopyBlock((void *)pData, (void *)pRtsoProps.GetShaderIdentifier(RTPipeline.kMissShader), D3D12ShaderIdentifierSizeInBytes);

            // Entry 2 - miss program
            pData += (int)mShaderTableEntrySize; // +1 skips ray-gen
            Unsafe.CopyBlock((void *)pData, (void *)pRtsoProps.GetShaderIdentifier(RTPipeline.kShadowMiss), D3D12ShaderIdentifierSizeInBytes);

            // Entry 3 - hit program
            pData += (int)mShaderTableEntrySize; // +1 skips miss entries
            Unsafe.CopyBlock((void *)pData, (void *)pRtsoProps.GetShaderIdentifier(RTPipeline.kHitGroup), D3D12ShaderIdentifierSizeInBytes);
            heapStart = (ulong)mpSrvUavHeap.GetGPUDescriptorHandleForHeapStart().Ptr;
            Unsafe.Write <ulong>((pData + (int)D3D12ShaderIdentifierSizeInBytes).ToPointer(), heapStart);

            // Unmap
            mpShaderTable.Unmap(0, null);
        }
Beispiel #15
0
        public static ulong UpdateSubresources(
            ID3D12GraphicsCommandList pCmdList,
            ID3D12Resource pDestinationResource,
            ID3D12Resource pIntermediate,
            int FirstSubresource,
            int NumSubresources,
            ulong RequiredSize,
            Span <PlacedSubresourceFootPrint> pLayouts,
            Span <int> pNumRows,
            Span <ulong> pRowSizesInBytes,
            Span <SubresourceData> pSrcData)
        {
            var IntermediateDesc = pIntermediate.Description;
            var DestinationDesc  = pDestinationResource.Description;

            if (IntermediateDesc.Dimension != ResourceDimension.Buffer ||
                IntermediateDesc.Width < RequiredSize + pLayouts[0].Offset ||
                (DestinationDesc.Dimension == ResourceDimension.Buffer &&
                 (FirstSubresource != 0 || NumSubresources != 1)))
            {
                return(0);
            }

            int sum = 0;

            for (int i = pRowSizesInBytes.Length - 1; i < pRowSizesInBytes.Length; i++)
            {
                sum = Math.Max((int)pLayouts[i].Offset + pLayouts[i].Footprint.RowPitch * pNumRows[i] * pLayouts[i].Footprint.Depth, sum);
            }

            Span <byte> pData = pIntermediate.Map <byte>(0, sum);

            for (int i = 0; i < NumSubresources; ++i)
            {
                MemcpySubresource((ulong)pLayouts[i].Footprint.RowPitch, (uint)pLayouts[i].Footprint.RowPitch * (uint)pNumRows[i],
                                  pData.Slice((int)pLayouts[i].Offset), pSrcData[i], (int)pRowSizesInBytes[i], pNumRows[i], pLayouts[i].Footprint.Depth);
            }
            pIntermediate.Unmap(0, null);

            if (DestinationDesc.Dimension == ResourceDimension.Buffer)
            {
                pCmdList.CopyBufferRegion(
                    pDestinationResource, 0, pIntermediate, pLayouts[0].Offset, (ulong)pLayouts[0].Footprint.Width);
            }
            else
            {
                for (int i = 0; i < NumSubresources; ++i)
                {
                    TextureCopyLocation Dst = new TextureCopyLocation(pDestinationResource, i + FirstSubresource);
                    TextureCopyLocation Src = new TextureCopyLocation(pIntermediate, pLayouts[i]);
                    pCmdList.CopyTextureRegion(Dst, 0, 0, 0, Src, null);
                }
            }
            return(RequiredSize);
        }
        public AccelerationStructureBuffers CreatePrimitiveBottomLevelAS(ID3D12Device5 pDevice, ID3D12GraphicsCommandList4 pCmdList)
        {
            this.LoadGLTF("GLTF/DamagedHelmet.glb", pDevice, out ID3D12Resource primitiveVertexBuffer, out uint primitiveVertexCount, out ID3D12Resource primitiveIndexBuffer, out uint primitiveIndexCount);
            //this.LoadGLTF("GLTF/Box.glb", pDevice, out ID3D12Resource primitiveVertexBuffer, out uint primitiveVertexCount, out ID3D12Resource primitiveIndexBuffer, out uint primitiveIndexCount);
            this.VertexBuffer = primitiveVertexBuffer;
            this.VertexCount  = primitiveVertexCount;
            this.IndexBuffer  = primitiveIndexBuffer;
            this.IndexCount   = primitiveIndexCount;

            return(this.CreateBottomLevelAS(pDevice, pCmdList, primitiveVertexBuffer, primitiveVertexCount, primitiveIndexBuffer, primitiveIndexCount));
        }
Beispiel #17
0
        public void UploadMesh(Mesh mesh, Span <byte> vertex, Span <byte> index, int stride, Format indexFormat)
        {
            graphicsDevice.DestroyResource(mesh.vertex);
            graphicsDevice.DestroyResource(mesh.index);
            mesh.sizeInByte      = vertex.Length;
            mesh.stride          = stride;
            mesh.indexFormat     = indexFormat;
            mesh.indexCount      = index.Length / (indexFormat == Format.R32_UInt ? 4 : 2);
            mesh.indexSizeInByte = index.Length;

            ID3D12Resource resourceUpload1 = graphicsDevice.device.CreateCommittedResource <ID3D12Resource>(
                HeapProperties.UploadHeapProperties,
                HeapFlags.None,
                ResourceDescription.Buffer((ulong)vertex.Length),
                ResourceStates.GenericRead);

            graphicsDevice.DestroyResource(resourceUpload1);

            ID3D12Resource resourceUpload2 = graphicsDevice.device.CreateCommittedResource <ID3D12Resource>(
                HeapProperties.UploadHeapProperties,
                HeapFlags.None,
                ResourceDescription.Buffer((ulong)index.Length),
                ResourceStates.GenericRead);

            graphicsDevice.DestroyResource(resourceUpload2);

            mesh.vertex = graphicsDevice.device.CreateCommittedResource <ID3D12Resource>(
                HeapProperties.DefaultHeapProperties,
                HeapFlags.None,
                ResourceDescription.Buffer((ulong)vertex.Length),
                ResourceStates.CopyDestination);

            mesh.index = graphicsDevice.device.CreateCommittedResource <ID3D12Resource>(
                HeapProperties.DefaultHeapProperties,
                HeapFlags.None,
                ResourceDescription.Buffer((ulong)index.Length),
                ResourceStates.CopyDestination);
            unsafe
            {
                var ptr = resourceUpload1.Map(0);
                vertex.CopyTo(new Span <byte>(ptr.ToPointer(), vertex.Length));
                resourceUpload1.Unmap(0);

                ptr = resourceUpload2.Map(0);
                index.CopyTo(new Span <byte>(ptr.ToPointer(), index.Length));
                resourceUpload2.Unmap(0);
            }
            commandList.CopyBufferRegion(mesh.vertex, 0, resourceUpload1, 0, (ulong)vertex.Length);
            commandList.CopyBufferRegion(mesh.index, 0, resourceUpload2, 0, (ulong)index.Length);
            commandList.ResourceBarrierTransition(mesh.vertex, ResourceStates.CopyDestination, ResourceStates.GenericRead);
            commandList.ResourceBarrierTransition(mesh.index, ResourceStates.CopyDestination, ResourceStates.GenericRead);
        }
Beispiel #18
0
        public unsafe void ResourceBarrierTransition(
            ID3D12Resource resource,
            ResourceStates stateBefore,
            ResourceStates stateAfter,
            int subresource            = D3D12.ResourceBarrierAllSubResources,
            ResourceBarrierFlags flags = ResourceBarrierFlags.None)
        {
            var barrier = new ResourceBarrier(
                new ResourceTransitionBarrier(resource, stateBefore, stateAfter, subresource),
                flags);

            ResourceBarrier(1, new IntPtr(&barrier));
        }
Beispiel #19
0
 /// <summary>
 /// Discards a resource.
 /// </summary>
 /// <param name="resource">The resource to discard.</param>
 /// <param name="rectCount">The number of rects to discard in rects.</param>
 /// <param name="rects">An array of  rectangles in the resource to discard. If null, DiscardResource discards the entire resource.</param>
 /// <param name="firstSubresource">Index of the first subresource in the resource to discard.</param>
 /// <param name="numSubresources">The number of subresources in the resource to discard.</param>
 public unsafe void DiscardResource(ID3D12Resource resource, int rectCount, RawRect[] rects, int firstSubresource, int numSubresources)
 {
     fixed(void *rectsPtr = &rects[0])
     {
         DiscardResource(resource, new DiscardRegion
         {
             NumRects         = rectCount,
             PRects           = (IntPtr)rectsPtr,
             FirstSubresource = firstSubresource,
             NumSubresources  = numSubresources
         });
     }
 }
Beispiel #20
0
        IntPtr Upload(ID3D12GraphicsCommandList commandList, int size, ID3D12Resource target, int offset)
        {
            if (currentPosition + size > this.size)
            {
                currentPosition = 0;
            }
            IntPtr result = mapped + currentPosition;

            commandList.CopyBufferRegion(target, (ulong)offset, resource, (ulong)currentPosition, (ulong)size);
            currentPosition = ((currentPosition + size + 255) & ~255) % this.size;

            return(result);
        }
        internal Texture InitializeFrom(ID3D12Resource resource, bool isSRgb = false)
        {
            resource.GetHeapProperties(out HeapProperties heapProperties, out _);

            TextureDescription description = ConvertFromNativeDescription(resource.Description, (GraphicsHeapType)heapProperties.Type);

            if (isSRgb)
            {
                description.Format = description.Format.ToSRgb();
            }

            return(InitializeFrom(resource, description));
        }
Beispiel #22
0
 /// <summary>
 /// Copy a region of a multisampled or compressed resource into a non-multisampled or non-compressed resource.
 /// </summary>
 /// <param name="dstResource">Destination resource.</param>
 /// <param name="dstSubresource">A zero-based index that identifies the destination subresource. Use <see cref="ID3D12Resource.CalculateSubResourceIndex(int, int, int, int, int)"/> to calculate the subresource index if the parent resource is complex.</param>
 /// <param name="dstX">The X coordinate of the left-most edge of the destination region. The width of the destination region is the same as the width of the source rect.</param>
 /// <param name="dstY">The Y coordinate of the top-most edge of the destination region. The height of the destination region is the same as the height of the source rect.</param>
 /// <param name="srcResource">Source resource. Must be multisampled or compressed.</param>
 /// <param name="srcSubresource">A zero-based index that identifies the source subresource.</param>
 /// <param name="format">A <see cref="Format"/> that specifies how the source and destination resource formats are consolidated.</param>
 /// <param name="resolveMode">Specifies the operation used to resolve the source samples.</param>
 public void ResolveSubresourceRegion(
     ID3D12Resource dstResource,
     int dstSubresource,
     int dstX, int dstY,
     ID3D12Resource srcResource,
     int srcSubresource,
     Format format,
     ResolveMode resolveMode = ResolveMode.Decompress)
 {
     ResolveSubresourceRegion_(
         dstResource, dstSubresource, dstX, dstY,
         srcResource, srcSubresource, null,
         format, resolveMode);
 }
Beispiel #23
0
        public CpuDescriptorHandle CreateRTV(ID3D12Device5 pDevice, ID3D12Resource pResource, ID3D12DescriptorHeap pHeap, ref uint usedHeapEntries, Format format)
        {
            RenderTargetViewDescription desc = new RenderTargetViewDescription();

            desc.ViewDimension      = RenderTargetViewDimension.Texture2D;
            desc.Format             = format;
            desc.Texture2D          = new Texture2DRenderTargetView();
            desc.Texture2D.MipSlice = 0;
            CpuDescriptorHandle rtvHandle = pHeap.GetCPUDescriptorHandleForHeapStart();

            rtvHandle.Ptr += usedHeapEntries * pDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            usedHeapEntries++;
            pDevice.CreateRenderTargetView(pResource, desc, rtvHandle);
            return(rtvHandle);
        }
Beispiel #24
0
        public unsafe void SetData <T>(Span <T> data) where T : unmanaged
        {
            if (NativeResource is null)
            {
                throw new InvalidOperationException();
            }

            ID3D12Resource uploadResource = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, NativeResource.Description, ResourceStates.CopyDestination);

            using Texture textureUploadBuffer = new Texture(GraphicsDevice).InitializeFrom(uploadResource);

            textureUploadBuffer.NativeResource !.WriteToSubresource(0, data, Width * 4, Width * Height * 4);

            using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);

            copyCommandList.CopyResource(textureUploadBuffer, this);
            copyCommandList.Flush(true);
        }
Beispiel #25
0
        public ID3D12Resource CreateTriangleVB(ID3D12Device5 pDevice)
        {
            Vector3[] vertices = new Vector3[]
            {
                new Vector3(0, 1, 0),
                new Vector3(0.866f, -0.5f, 0),
                new Vector3(-0.866f, -0.5f, 0),
            };

            // For simplicity, we create the vertex buffer on the upload heap, but that's not required
            ID3D12Resource pBuffer = CreateBuffer(pDevice, (uint)(Unsafe.SizeOf <Vector3>() * vertices.Length), ResourceFlags.None, ResourceStates.GenericRead, kUploadHeapProps);
            IntPtr         pData   = pBuffer.Map(0, null);

            Helpers.MemCpy(pData, vertices, (uint)(Unsafe.SizeOf <Vector3>() * vertices.Length));
            pBuffer.Unmap(0, null);

            return(pBuffer);
        }
Beispiel #26
0
        private CpuDescriptorHandle CreateRenderTargetView(ID3D12Device device, ID3D12Resource swapChainBuffer, ID3D12DescriptorHeap heap,
                                                           ref uint usedEntries, Format format)
        {
            RenderTargetViewDescription viewDesc = new RenderTargetViewDescription();

            viewDesc.ViewDimension      = RenderTargetViewDimension.Texture2D;
            viewDesc.Format             = format;
            viewDesc.Texture2D          = new Texture2DRenderTargetView();
            viewDesc.Texture2D.MipSlice = 0;

            CpuDescriptorHandle handle = heap.GetCPUDescriptorHandleForHeapStart();

            handle.Ptr += usedEntries * device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            usedEntries++;

            device.CreateRenderTargetView(swapChainBuffer, viewDesc, handle);
            return(handle);
        }
        public ID3D12Resource CreateBuffer(ID3D12Device5 pDevice, uint size, ResourceFlags flags, ResourceStates initState, HeapProperties heapProps)
        {
            ResourceDescription bufDesc = new ResourceDescription();

            bufDesc.Alignment         = 0;
            bufDesc.DepthOrArraySize  = 1;
            bufDesc.Dimension         = ResourceDimension.Buffer;
            bufDesc.Flags             = flags;
            bufDesc.Format            = Format.Unknown;
            bufDesc.Height            = 1;
            bufDesc.Layout            = TextureLayout.RowMajor;
            bufDesc.MipLevels         = 1;
            bufDesc.SampleDescription = new SampleDescription(1, 0);
            bufDesc.Width             = size;

            ID3D12Resource pBuffer = pDevice.CreateCommittedResource(heapProps, HeapFlags.None, bufDesc, initState, null);

            return(pBuffer);
        }
        public void CreateAccelerationStructures()
        {
            acs = new AccelerationStructures();

            AccelerationStructureBuffers bottomLevelBuffers = acs.CreateBottomLevelAS(mpDevice, mpCmdList);
            AccelerationStructureBuffers topLevelBuffers    = acs.CreateTopLevelAS(mpDevice, mpCmdList, bottomLevelBuffers.pResult, ref mTlasSize);

            // The tutorial doesn't have any resource lifetime management, so we flush and sync here. This is not required by the DXR spec - you can submit the list whenever you like as long as you take care of the resources lifetime.
            mFenceValue = context.SubmitCommandList(mpCmdList, mpCmdQueue, mpFence, mFenceValue);
            mpFence.SetEventOnCompletion(mFenceValue, mFenceEvent);
            mFenceEvent.WaitOne();
            int bufferIndex = mpSwapChain.GetCurrentBackBufferIndex();

            mpCmdList.Reset(mFrameObjects[0].pCmdAllocator, null);

            // Store the AS buffers. The rest of the buffers will be released once we exit the function
            mpTopLevelAS    = topLevelBuffers.pResult;
            mpBottomLevelAS = bottomLevelBuffers.pResult;
        }
Beispiel #29
0
        public Texture InitializeFrom(TextureDescription description)
        {
            ResourceStates resourceStates = ResourceStates.Common;

            if (description.HeapType == GraphicsHeapType.Upload)
            {
                resourceStates = ResourceStates.GenericRead;
            }
            else if (description.HeapType == GraphicsHeapType.Readback)
            {
                resourceStates = ResourceStates.CopyDestination;
            }

            ID3D12Resource resource = GraphicsDevice.NativeDevice.CreateCommittedResource(
                new HeapProperties((HeapType)description.HeapType), HeapFlags.None,
                ConvertToNativeDescription(description), resourceStates);

            return(InitializeFrom(resource, description));
        }
Beispiel #30
0
        private void CreateShaderResources()
        {
            HeapProperties heapProperties = new HeapProperties(HeapType.Default, CpuPageProperty.Unknown, MemoryPool.Unknown, 0, 0);

            // Create the output resource. The dimensions and format should match the swap-chain
            ResourceDescription resDesc = new ResourceDescription();

            resDesc.Alignment               = 0;
            resDesc.DepthOrArraySize        = 1;
            resDesc.Dimension               = ResourceDimension.Texture2D;
            resDesc.Flags                   = ResourceFlags.AllowUnorderedAccess;
            resDesc.Format                  = Format.R8G8B8A8_UNorm;
            resDesc.Width                   = Window.Width;
            resDesc.Height                  = Window.Height;
            resDesc.Layout                  = TextureLayout.Unknown;
            resDesc.MipLevels               = 1;
            resDesc.SampleDescription       = new SampleDescription();
            resDesc.SampleDescription.Count = 1;

            outputResource = device.CreateCommittedResource(heapProperties, HeapFlags.None, resDesc, ResourceStates.CopySource, null);

            // Create an SRV/UAV descriptor heap. Need 2 entries - 1 SRV for the scene and 1 UAV for the output
            srvUavHeap = CreateDescriptorHeap(device, 2, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, true);

            // Create the UAV. Based on the root signature we created it should be the first entry
            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription();

            uavDesc.ViewDimension = UnorderedAccessViewDimension.Texture2D;
            device.CreateUnorderedAccessView(outputResource, null, uavDesc, srvUavHeap.GetCPUDescriptorHandleForHeapStart());

            // Create the TLAS SRV right after the UAV. Note that we are using a different SRV desc here
            ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription();

            srvDesc.ViewDimension                            = ShaderResourceViewDimension.RaytracingAccelerationStructure;
            srvDesc.Shader4ComponentMapping                  = 5768; // D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING
            srvDesc.RaytracingAccelerationStructure          = new RaytracingAccelerationStructureShaderResourceView();
            srvDesc.RaytracingAccelerationStructure.Location = topLevelAS.GPUVirtualAddress;

            CpuDescriptorHandle srvHandle = srvUavHeap.GetCPUDescriptorHandleForHeapStart();

            srvHandle.Ptr += device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);
            device.CreateShaderResourceView(null, srvDesc, srvHandle);
        }