private ID3D12CommandQueue CreateCommandQueue(ID3D12Device device) { var desc = new CommandQueueDescription(); desc.Type = CommandListType.Direct; desc.Flags = CommandQueueFlags.None; return(device.CreateCommandQueue(desc)); }
private ID3D12DescriptorHeap CreateDescriptorHeap(ID3D12Device device, int count, DescriptorHeapType type, bool shaderVisible) { DescriptorHeapDescription desc = new DescriptorHeapDescription(); desc.DescriptorCount = count; desc.Flags = shaderVisible ? DescriptorHeapFlags.ShaderVisible : DescriptorHeapFlags.None; desc.Type = type; return(device.CreateDescriptorHeap(desc)); }
public unsafe void Init(ID3D12Device device, int size) { this.size = (size + 255) & ~255; ThrowIfFailed(device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer((ulong)size), ResourceStates.GenericRead, out resource)); void *ptr1 = null; resource.Map(0, &ptr1); mapped = new IntPtr(ptr1); }
public static T DMLCreateDevice <T>(ID3D12Device d3d12Device, CreateDeviceFlags createDeviceFlags, FeatureLevel minimumFeatureLevel) where T : IDMLDevice { DMLCreateDevice1( d3d12Device, createDeviceFlags, minimumFeatureLevel, typeof(T).GUID, out IntPtr nativePtr).CheckError(); return(MarshallingHelpers.FromPointer <T>(nativePtr) ?? throw new NullReferenceException()); }
/// <summary> /// Creates a new <see cref="DescriptorAllocator"/> instance with the specified parameters /// </summary> /// <param name="device">The <see cref="ID3D12Device"/> instance to use</param> public DescriptorAllocator(ID3D12Device device) { DescriptorSize = device.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); DescriptorHeapDescription descriptorHeapDescription = new DescriptorHeapDescription { DescriptorCount = DescriptorsPerHeap, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; DescriptorHeap = device.CreateDescriptorHeap(descriptorHeapDescription); _RemainingHandles = DescriptorsPerHeap; _CurrentCpuHandle = DescriptorHeap.GetCPUDescriptorHandleForHeapStart(); _CurrentGpuHandle = DescriptorHeap.GetGPUDescriptorHandleForHeapStart(); }
internal CpuDescriptorHandle GetRenderTargetView(ID3D12Device device, int mipLevel, int faceIndex) { if (renderTargetView == null) { ThrowIfFailed(device.CreateDescriptorHeap(new DescriptorHeapDescription(DescriptorHeapType.RenderTargetView, 1), out renderTargetView)); device.CreateRenderTargetView(resource, new RenderTargetViewDescription() { Texture2DArray = new Texture2DArrayRenderTargetView() { MipSlice = mipLevel, ArraySize = 1, FirstArraySlice = faceIndex, } }, renderTargetView.GetCPUDescriptorHandleForHeapStart()); } return(renderTargetView.GetCPUDescriptorHandleForHeapStart()); }
public static Result DMLCreateDevice <T>(ID3D12Device d3d12Device, CreateDeviceFlags createDeviceFlags, out T?device) where T : IDMLDevice { Result result = DMLCreateDevice( d3d12Device, createDeviceFlags, typeof(T).GUID, out IntPtr nativePtr); if (result.Failure) { device = default; return(result); } device = MarshallingHelpers.FromPointer <T>(nativePtr); return(result); }
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); }
/// <summary> /// Checks if given DirectX12 backend is supported. /// </summary> /// <returns>True if supported, false otherwise.</returns> public static bool IsSupported() { if (s_isSupported.HasValue) { return(s_isSupported.Value); } if (Platform.PlatformType != PlatformType.Windows && Platform.PlatformType != PlatformType.UWP && Platform.PlatformType != PlatformType.XboxOne) { s_isSupported = false; return(false); } if (CreateDXGIFactory1(out IDXGIFactory1 tempDXGIFactory1).Failure) { s_isSupported = false; return(false); } var adapters = tempDXGIFactory1.EnumAdapters1(); for (var i = 0; i < adapters.Length; i++) { var adapter = adapters[i]; var desc = adapter.Description1; // Don't select the Basic Render Driver adapter. if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None) { continue; } if (ID3D12Device.IsSupported(adapter, FeatureLevel.Level_11_0)) { s_isSupported = true; return(true); } } s_isSupported = true; return(true); }
/// <summary> /// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/> /// </summary> /// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param> /// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param> public GraphicsDevice(ID3D12Device device, AdapterDescription description) { NativeDevice = device; Description = description; WavefrontSize = 64; NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute)); NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy)); NativeDirectCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)); ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute); CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy); DirectAllocatorPool = new CommandAllocatorPool(this, CommandListType.Direct); NativeComputeFence = NativeDevice.CreateFence(0); NativeCopyFence = NativeDevice.CreateFence(0); NativeDirectFence = NativeDevice.CreateFence(0); ShaderResourceViewAllocator = new DescriptorAllocator(this); }
/// <summary> /// Creates a new <see cref="GraphicsDevice"/> instance for the input <see cref="ID3D12Device"/> /// </summary> /// <param name="device">The <see cref="ID3D12Device"/> to use for the new <see cref="GraphicsDevice"/> instance</param> /// <param name="description">The available info for the new <see cref="GraphicsDevice"/> instance</param> public GraphicsDevice(ID3D12Device device, AdapterDescription description) { NativeDevice = device; Name = description.Description; MemorySize = description.DedicatedVideoMemory; ComputeUnits = device.Options1.TotalLaneCount; WavefrontSize = device.Options1.WaveLaneCountMin; NativeComputeCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Compute)); NativeCopyCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Copy)); NativeDirectCommandQueue = NativeDevice.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)); ComputeAllocatorPool = new CommandAllocatorPool(this, CommandListType.Compute); CopyAllocatorPool = new CommandAllocatorPool(this, CommandListType.Copy); DirectAllocatorPool = new CommandAllocatorPool(this, CommandListType.Direct); NativeComputeFence = NativeDevice.CreateFence(0); NativeCopyFence = NativeDevice.CreateFence(0); NativeDirectFence = NativeDevice.CreateFence(0); ShaderResourceViewAllocator = new DescriptorAllocator(NativeDevice); }
public static ulong UpdateSubresources( ID3D12GraphicsCommandList pCmdList, ID3D12Resource pDestinationResource, ID3D12Resource pIntermediate, ulong IntermediateOffset, int FirstSubresource, int NumSubresources, Span <SubresourceData> pSrcData) { Span <PlacedSubresourceFootPrint> pLayouts = stackalloc PlacedSubresourceFootPrint[NumSubresources]; Span <ulong> pRowSizesInBytes = stackalloc ulong[NumSubresources]; Span <int> pNumRows = stackalloc int[NumSubresources]; var Desc = pDestinationResource.Description; ID3D12Device pDevice = null; pDestinationResource.GetDevice(out pDevice); pDevice.GetCopyableFootprints(Desc, (int)FirstSubresource, (int)NumSubresources, IntermediateOffset, pLayouts, pNumRows, pRowSizesInBytes, out ulong RequiredSize); pDevice.Release(); ulong Result = UpdateSubresources(pCmdList, pDestinationResource, pIntermediate, FirstSubresource, NumSubresources, RequiredSize, pLayouts, pNumRows, pRowSizesInBytes, pSrcData); return(Result); }
public D3D12GraphicsDevice(IDXGIFactory4 factory) { DXGIFactory = factory; var adapters = DXGIFactory.EnumAdapters1(); for (var i = 0; i < adapters.Length; i++) { var adapter = adapters[i]; var desc = adapter.Description1; // Don't select the Basic Render Driver adapter. if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None) { continue; } if (D3D12CreateDevice(adapter, FeatureLevel.Level_11_0, out var device).Success) { DXGIAdapter = adapter; D3D12Device = device; } } if (D3D12Device == null) { // Create the Direct3D 12 with WARP adapter. DXGIAdapter = DXGIFactory.GetWarpAdapter <IDXGIAdapter1>(); if (D3D12CreateDevice(DXGIAdapter, FeatureLevel.Level_11_0, out D3D12Device).Failure) { throw new GraphicsException("Cannot create D3D12 device"); } } if (Validation) { var infoQueue = D3D12Device.QueryInterfaceOrNull <ID3D12InfoQueue>(); if (infoQueue != null) { #if DEBUG infoQueue.SetBreakOnSeverity(MessageSeverity.Corruption, true); infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true); #endif infoQueue.AddStorageFilterEntries(new DirectX.Direct3D12.Debug.InfoQueueFilter { DenyList = new DirectX.Direct3D12.Debug.InfoQueueFilterDescription { Ids = new[] { MessageId.ClearRenderTargetViewMismatchingClearValue, // These happen when capturing with VS diagnostics MessageId.MapInvalidNullRange, MessageId.UnmapInvalidNullRange, } } }); infoQueue.Dispose(); } } // Init device features. InitializeFeatures(); // Create command queue's. _graphicsCommandQueue = new CommandQueueD3D12(this, CommandQueueType.Graphics); _computeCommandQueue = new CommandQueueD3D12(this, CommandQueueType.Compute); _copyCommandQueue = new CommandQueueD3D12(this, CommandQueueType.Copy); // Create main graphics command queue. GraphicsQueue = D3D12Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)); GraphicsQueue.SetName("Main GraphicsQueue"); // Create ImmediateContext. for (int i = 0; i < RenderLatency; i++) { _deferredReleases[i] = new List <IUnknown>(); } // Create the frame fence _frameFence = new FenceD3D12(this, 0); // Create descriptor allocators for (var i = 0; i < (int)DescriptorHeapType.Count; i++) { _descriptorAllocator[i] = new DescriptorAllocator(this, (DescriptorHeapType)i); } }
public static void Main() { using ID3D12Device device = D3D12CreateDevice <ID3D12Device>(null, FeatureLevel.Level_12_1); using IDStorageFactory factory = DStorageGetFactory <IDStorageFactory>(); string fileToLoad = "Test.txt"; Result result = factory.OpenFile(fileToLoad, out IDStorageFile? file); if (result.Failure) { Console.WriteLine($"The file '{fileToLoad}' could not be opened. HRESULT={result}"); //ShowHelpText(); return; } ByHandleFileInformation info = file !.FileInformation; uint fileSize = info.FileSizeLow; // Create a DirectStorage queue which will be used to load data into a buffer on the GPU. QueueDesc queueDesc = new QueueDesc { Capacity = MaxQueueCapacity, Priority = Priority.Normal, SourceType = RequestSourceType.File, Device = device }; using IDStorageQueue queue = factory.CreateQueue(queueDesc); // Create the ID3D12Resource buffer which will be populated with the file's contents HeapProperties bufferHeapProps = new HeapProperties(HeapType.Default); ResourceDescription bufferDesc = ResourceDescription.Buffer(fileSize); using ID3D12Resource bufferResource = device.CreateCommittedResource( bufferHeapProps, HeapFlags.None, bufferDesc, ResourceStates.Common ); // Enqueue a request to read the file contents into a destination D3D12 buffer resource. // Note: The example request below is performing a single read of the entire file contents. Request request = new Request(); request.Options.SourceType = RequestSourceType.File; request.Options.DestinationType = RequestDestinationType.Buffer; request.Source.File.Source = file; request.Source.File.Offset = 0; request.Source.File.Size = fileSize; request.UncompressedSize = fileSize; request.Destination.Buffer.Resource = bufferResource; request.Destination.Buffer.Offset = 0; request.Destination.Buffer.Size = request.Source.File.Size; queue.EnqueueRequest(request); // Configure a fence to be signaled when the request is completed using ID3D12Fence fence = device.CreateFence(); using AutoResetEvent fenceEvent = new AutoResetEvent(false); ulong fenceValue = 1; fence.SetEventOnCompletion(fenceValue, fenceEvent).CheckError(); queue.EnqueueSignal(fence, fenceValue); // Tell DirectStorage to start executing all queued items. queue.Submit(); // Wait for the submitted work to complete Console.WriteLine("Waiting for the DirectStorage request to complete..."); fenceEvent.WaitOne(); // Check the status array for errors. // If an error was detected the first failure record // can be retrieved to get more details. ErrorRecord errorRecord = queue.RetrieveErrorRecord(); if (errorRecord.FirstFailure.HResult.Failure) { // // errorRecord.FailureCount - The number of failed requests in the queue since the last // RetrieveErrorRecord call. // errorRecord.FirstFailure - Detailed record about the first failed command in the enqueue order. // Console.WriteLine($"The DirectStorage request failed! HRESULT={errorRecord.FirstFailure.HResult}"); } else { Console.WriteLine("The DirectStorage request completed successfully!"); } }
public byte GetPlaneCount(ID3D12Device device) { return(device.GetFormatPlaneCount(Format)); }
public static IDMLDevice DMLCreateDevice(ID3D12Device d3d12Device, CreateDeviceFlags createDeviceFlags) { DMLCreateDevice(d3d12Device, createDeviceFlags, typeof(IDMLDevice).GUID, out IntPtr nativePtr).CheckError(); return(new(nativePtr)); }
public static bool IsSupported() { return(ID3D12Device.IsSupported(null, Vortice.DirectX.Direct3D.FeatureLevel.Level_11_0)); }
public int Subresources(ID3D12Device pDevice) { return(MipLevels * ArraySize * GetPlaneCount(pDevice)); }
public static bool IsSupported() { return(ID3D12Device.IsSupported(null, FeatureLevel.Level_11_0)); }
protected Application(bool useDirect3D12) { _wndProc = ProcessWindowMessage; var wndClassEx = new WNDCLASSEX { Size = Unsafe.SizeOf <WNDCLASSEX>(), Styles = WindowClassStyles.CS_HREDRAW | WindowClassStyles.CS_VREDRAW | WindowClassStyles.CS_OWNDC, WindowProc = _wndProc, InstanceHandle = HInstance, CursorHandle = LoadCursor(IntPtr.Zero, SystemCursor.IDC_ARROW), BackgroundBrushHandle = IntPtr.Zero, IconHandle = IntPtr.Zero, ClassName = WndClassName, }; var atom = RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new InvalidOperationException( $"Failed to register window class. Error: {Marshal.GetLastWin32Error()}" ); } Window = new Window("Vortice", 800, 600); if (useDirect3D12 && !ID3D12Device.IsSupported(null, FeatureLevel.Level_11_0)) { useDirect3D12 = false; } var debugFactory = false; #if DEBUG if (useDirect3D12) { if (D3D12GetDebugInterface <ID3D12Debug>(out var debug).Success) { debug.EnableDebugLayer(); debugFactory = true; } } #endif if (useDirect3D12) { if (CreateDXGIFactory2(debugFactory, out IDXGIFactory4 dxgiFactory4).Failure) { throw new InvalidOperationException("Cannot create IDXGIFactory4"); } _dxgiFactory = dxgiFactory4; } else { if (CreateDXGIFactory2(debugFactory, out _dxgiFactory).Failure) { throw new InvalidOperationException("Cannot create IDXGIFactory4"); } } if (useDirect3D12) { Debug.Assert(D3D12CreateDevice(null, FeatureLevel.Level_11_0, out _d3d12Device).Success); _d3d12CommandQueue = _d3d12Device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct, CommandQueuePriority.Normal)); } else { var featureLevels = new FeatureLevel[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 }; Debug.Assert(ID3D11Device.TryCreate( null, DriverType.Hardware, DeviceCreationFlags.BgraSupport, featureLevels, out _d3d11Device, out _d3d11DeviceContext).Success); } var swapChainDesc = new SwapChainDescription1 { BufferCount = FrameCount, Width = Window.Width, Height = Window.Height, Format = Format.B8G8R8A8_UNorm, Usage = Vortice.Usage.RenderTargetOutput, SwapEffect = SwapEffect.FlipDiscard, SampleDescription = new SampleDescription(1, 0) }; SwapChain = DXGIFactory.CreateSwapChainForHwnd(_d3d12CommandQueue, Window.Handle, swapChainDesc); DXGIFactory.MakeWindowAssociation(Window.Handle, WindowAssociationFlags.IgnoreAltEnter); if (useDirect3D12) { SwapChain3 = SwapChain.QueryInterface <IDXGISwapChain3>(); _frameIndex = SwapChain3.GetCurrentBackBufferIndex(); } _rtvHeap = _d3d12Device.CreateDescriptorHeap(new DescriptorHeapDescription(DescriptorHeapType.RenderTargetView, FrameCount)); _rtvDescriptorSize = _d3d12Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView); // Create frame resources. { var rtvHandle = _rtvHeap.GetCPUDescriptorHandleForHeapStart(); // Create a RTV for each frame. _renderTargets = new ID3D12Resource[FrameCount]; for (var i = 0; i < FrameCount; i++) { _renderTargets[i] = SwapChain.GetBuffer <ID3D12Resource>(i); _d3d12Device.CreateRenderTargetView(_renderTargets[i], null, rtvHandle); rtvHandle += _rtvDescriptorSize; } } _commandAllocator = _d3d12Device.CreateCommandAllocator(CommandListType.Direct); _commandList = _d3d12Device.CreateCommandList(CommandListType.Direct, _commandAllocator); _commandList.Close(); // Create synchronization objects. _d3d12Fence = _d3d12Device.CreateFence(0); _fenceValue = 1; _fenceEvent = new AutoResetEvent(false); }