Esempio n. 1
0
        /// <summary>
        ///     Enumerates both adapters (video cards) with or without outputs.
        /// </summary>
        /// <param name="adapterId">The index of the adapter to enumerate.</param>
        /// <param name="adapter1">
        ///     The out object as <seealso cref="IDXGIAdapter1" /> interface at the position specified by the Adapter
        ///     parameter. This parameter must not be NULL.
        /// </param>
        /// <returns></returns>
        /// <remarks>
        ///     The set of adapters available in the system is enumerated when the factory is created. Therefore, if you change the
        ///     adapters in a system, you must destroy and recreate the <seealso cref="IDXGIFactory1" /> object. The number of
        ///     adapters adapters in a
        ///     system changes when you add or remove a display card, or dock or undock a laptop.
        ///     When the <seealso cref="EnumAdapters1" /> method succeeds and the adapter interface is filled, the adapters
        ///     reference count will be
        ///     incremented. When you are finished with the adapter interface, be sure to call the Release method to decrement the
        ///     reference count before you destroy the pointer.
        ///     The local adapter with output on which the Desktop primary is displayed is returned first, followed by other
        ///     adapter(s) with outputs, then adapter(s) without outputs.
        ///     The following code example demonstrates how to enumerate adapters using the EnumAdapters1 method.
        ///     <example>
        ///         <code>
        /// uint i = 0;
        /// IDXGIAdapter1 adapter;
        /// List&lt;IDXGIAdapter&gt; adapters = new List&lt;IDXGIAdapter1&gt;
        /// while(factory.EnumAdapters1(i, out adapter) != DXGI_ERROR_NOT_FOUND)
        /// {
        /// adapters.Add(pAdapter);
        /// ++i;
        /// }
        /// </code>
        ///     </example>
        /// </remarks>
        public int EnumAdapters1(uint adapterId, out IDXGIAdapter1 adapter1)
        {
            int result = GetMethodDelegate <EnumAdapters1Delegate>().Invoke(this, adapterId, out IntPtr adapterPtr);

            adapter1 = result == 0 ? new DXGIAdapter1(adapterPtr) : null;
            return(result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EngineAdapterInfo" /> class.
        /// </summary>
        internal EngineAdapterInfo(int adapterIndex, IDXGIAdapter1 adapter)
        {
            this.Outputs      = new List <EngineOutputInfo>();
            this.AdapterIndex = adapterIndex;

            _adapterDescription    = adapter.Description;
            this.IsSoftwareAdapter =
                _adapterDescription.Description == "Microsoft Basic Render Driver" ||
                !string.IsNullOrEmpty(_adapterDescription.Description) && _adapterDescription.Description.Contains("Software") ||
                !string.IsNullOrEmpty(_adapterDescription.Description) && _adapterDescription.Description.Contains("Microsoft Basic Render Driver");
            _d3d11FeatureLevel = D3D11.D3D11.GetSupportedFeatureLevel(adapter);

            //Query for output information
            var lastResult = Result.Ok;
            var actIndex   = 0;

            do
            {
                lastResult = adapter.EnumOutputs(actIndex, out var actOutput);
                if (lastResult.Success)
                {
                    this.Outputs.Add(new EngineOutputInfo(adapterIndex, actIndex, actOutput));
                }
                actIndex++;
            }while (lastResult.Success);
        }
Esempio n. 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D9"/> class.
        /// </summary>
        /// <param name="dxgiAdapter">The target adapter.</param>
        /// <param name="isSoftwareAdapter">Are we in software mode?</param>
        internal DeviceHandlerD3D9(IDXGIAdapter1 dxgiAdapter, bool isSoftwareAdapter)
        {
            try
            {
                // Just needed when on true hardware
                if (!isSoftwareAdapter)
                {
                    //Prepare device creation
                    const D3D9.CreateFlags CREATE_FLAGS = D3D9.CreateFlags.HardwareVertexProcessing |
                                                          D3D9.CreateFlags.PureDevice |
                                                          D3D9.CreateFlags.FpuPreserve |
                                                          D3D9.CreateFlags.Multithreaded;

                    var presentparams = new D3D9.PresentParameters
                    {
                        Windowed             = true,
                        SwapEffect           = D3D9.SwapEffect.Discard,
                        DeviceWindowHandle   = GetDesktopWindow(),
                        PresentationInterval = D3D9.PresentInterval.Default,
                        BackBufferCount      = 1
                    };

                    //Create the device finally
                    var result = Create9Ex(out _direct3DEx);
                    result.CheckError();

                    // Try to find the Direct3D9 adapter that matches given DXGI adapter
                    var adapterIndex = -1;
                    for (var loop = 0; loop < _direct3DEx.AdapterCount; loop++)
                    {
                        var d3d9AdapterInfo = _direct3DEx.GetAdapterIdentifier(loop);
                        if (d3d9AdapterInfo.DeviceId == dxgiAdapter.Description1.DeviceId)
                        {
                            adapterIndex = loop;
                            break;
                        }
                    }

                    // Direct3D 9 is only relevant on the primary device
                    if (adapterIndex < 0)
                    {
                        return;
                    }

                    // Try to create the device
                    _deviceEx = _direct3DEx.CreateDeviceEx(
                        adapterIndex, D3D9.DeviceType.Hardware, IntPtr.Zero,
                        CREATE_FLAGS, presentparams);
                }
            }
            catch (Exception)
            {
                // No direct3d 9 interface support
                SeeingSharpUtil.SafeDispose(ref _direct3DEx);
                SeeingSharpUtil.SafeDispose(ref _deviceEx);
            }
        }
Esempio n. 4
0
        public static DXGI_ADAPTER_DESC1 GetDesc1(this IDXGIAdapter1 adapter)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter));
            }

            adapter.GetDesc1(out var desc).ThrowOnError();
            return(desc);
        }
        private IDXGIAdapter1 GetHardwareAdapter()
        {
            IDXGIAdapter1 adapter  = null;
            IDXGIFactory6 factory6 = Factory.QueryInterfaceOrNull <IDXGIFactory6>();

            if (factory6 != null)
            {
                for (int adapterIndex = 0;
                     factory6.EnumAdapterByGpuPreference(adapterIndex, GpuPreference.HighPerformance, out adapter) != Vortice.DXGI.ResultCode.NotFound;
                     adapterIndex++)
                {
                    AdapterDescription1 desc = adapter.Description1;

                    if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
                    {
                        // Don't select the Basic Render Driver adapter.
                        adapter.Dispose();
                        continue;
                    }

                    return(adapter);
                }


                factory6.Dispose();
            }

            if (adapter == null)
            {
                for (int adapterIndex = 0;
                     Factory.EnumAdapters1(adapterIndex, out adapter) != Vortice.DXGI.ResultCode.NotFound;
                     adapterIndex++)
                {
                    AdapterDescription1 desc = adapter.Description1;

                    if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
                    {
                        // Don't select the Basic Render Driver adapter.
                        adapter.Dispose();
                        continue;
                    }

                    return(adapter);
                }
            }

            return(adapter);
        }
Esempio n. 6
0
        public static int Main()
        {
            int result;

            using (IDXGIFactory1 factory1 = new DXGIFactory1())
            {
                LinkedList <IDXGIAdapter1> adapters = new LinkedList <IDXGIAdapter1>();

                uint adapterId = 0;
                while ((result = factory1.EnumAdapters1(adapterId, out IDXGIAdapter1 currentAdapter)) == 0)
                {
                    adapterId++;
                    result = currentAdapter.GetDesc1(out DXGIAdapterDescription1 adapterDescription);

                    if (result != 0)
                    {
                        foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                        {
                            dxgiAdapter1.Dispose();
                        }

                        return(1);
                    }

                    if ((adapterDescription.Flags & DXGIAdapterFlag.Software) != 0)
                    {
                        currentAdapter.Dispose();
                        continue;
                    }

                    adapters.AddLast(currentAdapter);
                }

                if (adapters.Count == 0)
                {
                    foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                    {
                        dxgiAdapter1.Dispose();
                    }

                    return(2);
                }

                FeatureLevel[] featureLevels =
                {
                    FeatureLevel.Level_12_1,
                    FeatureLevel.Level_12_0,
                    FeatureLevel.Level_11_1,
                    FeatureLevel.Level_11_0,
                    FeatureLevel.Level_10_1,
                    FeatureLevel.Level_10_0,
                    FeatureLevel.Level_9_3,
                    FeatureLevel.Level_9_2,
                    FeatureLevel.Level_9_1
                };

                result = DXGINativeMethods.D3D11CreateDevice
                         (
                    adapters.First.Value,
                    DriverType.Unknown,
                    IntPtr.Zero,
                    0x2,
                    featureLevels,
                    7u,
                    out IUnknown d3d11Device,
                    out FeatureLevel selectedLevel,
                    out IUnknown d3d11DeviceContext
                         );

                if (result != 0)
                {
                    foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                    {
                        dxgiAdapter1.Dispose();
                    }

                    return(3);
                }

                using (d3d11Device)
                {
                    using (IDXGIAdapter1 adapter = adapters.First.Value)
                    {
                        using (d3d11DeviceContext)
                        {
                            result = adapter.EnumOutputs(0, out IDXGIOutput output);

                            if (result != 0)
                            {
                                foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                                {
                                    dxgiAdapter1.Dispose();
                                }

                                return(4);
                            }

                            using (output)
                            {
                                result = output.QueryInterface(typeof(IDXGIOutput1).GUID, out IntPtr output1Ptr);
                                if (result != 0)
                                {
                                    foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                                    {
                                        dxgiAdapter1.Dispose();
                                    }

                                    return(5);
                                }

                                using (IDXGIOutput1 output1 = new DXGIOutput1(output1Ptr))
                                {
                                    result = output1.DuplicateOutput(d3d11Device,
                                                                     out IDXGIOutputDuplication duplicationOutput);

                                    if (result != 0)
                                    {
                                        foreach (IDXGIAdapter1 dxgiAdapter1 in adapters)
                                        {
                                            dxgiAdapter1.Dispose();
                                        }

                                        return(6);
                                    }

                                    duplicationOutput.GetDesc(out DXGIOutDuplDescription duplDescription);

                                    duplicationOutput.ReleaseFrame();
                                    duplicationOutput.Dispose();
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 7
0
    private D3D11GraphicsDevice(Window?window, SizeI size, Format depthStencilFormat = Format.D32_Float)
    {
        Window = window;
        Size   = size;

        Factory = CreateDXGIFactory1 <IDXGIFactory2>();

        using (IDXGIAdapter1 adapter = GetHardwareAdapter())
        {
            DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
#if DEBUG
            if (SdkLayersAvailable())
            {
                creationFlags |= DeviceCreationFlags.Debug;
            }
#endif

            if (D3D11CreateDevice(
                    adapter,
                    DriverType.Unknown,
                    creationFlags,
                    s_featureLevels,
                    out ID3D11Device tempDevice, out FeatureLevel, out ID3D11DeviceContext tempContext).Failure)
            {
                // If the initialization fails, fall back to the WARP device.
                // For more information on WARP, see:
                // http://go.microsoft.com/fwlink/?LinkId=286690
                D3D11CreateDevice(
                    IntPtr.Zero,
                    DriverType.Warp,
                    creationFlags,
                    s_featureLevels,
                    out tempDevice, out FeatureLevel, out tempContext).CheckError();
            }

            Device        = tempDevice.QueryInterface <ID3D11Device1>();
            DeviceContext = tempContext.QueryInterface <ID3D11DeviceContext1>();
            tempContext.Dispose();
            tempDevice.Dispose();
        }

        if (window != null)
        {
            IntPtr hwnd = window.Handle;

            SwapChainDescription1 swapChainDescription = new()
            {
                Width             = window.ClientSize.Width,
                Height            = window.ClientSize.Height,
                Format            = Format.R8G8B8A8_UNorm,
                BufferCount       = FrameCount,
                BufferUsage       = Usage.RenderTargetOutput,
                SampleDescription = SampleDescription.Default,
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipDiscard,
                AlphaMode         = AlphaMode.Ignore
            };

            SwapChainFullscreenDescription fullscreenDescription = new SwapChainFullscreenDescription
            {
                Windowed = true
            };

            SwapChain = Factory.CreateSwapChainForHwnd(Device, hwnd, swapChainDescription, fullscreenDescription);
            Factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAltEnter);

            BackBufferTexture = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            RenderTargetView  = Device.CreateRenderTargetView(BackBufferTexture);
        }
        else
        {
            // Create offscreen texture
            OffscreenTexture = Device.CreateTexture2D(Format.R8G8B8A8_UNorm, Size.Width, Size.Height, 1, 1, null, BindFlags.ShaderResource | BindFlags.RenderTarget);
            RenderTargetView = Device.CreateRenderTargetView(OffscreenTexture);
        }

        if (depthStencilFormat != Format.Unknown)
        {
            DepthStencilTexture = Device.CreateTexture2D(depthStencilFormat, Size.Width, Size.Height, 1, 1, null, BindFlags.DepthStencil);
            DepthStencilView    = Device.CreateDepthStencilView(DepthStencilTexture !, new DepthStencilViewDescription(DepthStencilTexture, DepthStencilViewDimension.Texture2D));
        }

        ReadOnlySpan <VertexPositionColor> triangleVertices = stackalloc VertexPositionColor[]
        {
            new VertexPositionColor(new Vector3(0f, 0.5f, 0.0f), new Color4(1.0f, 0.0f, 0.0f, 1.0f)),
            new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.0f), new Color4(0.0f, 1.0f, 0.0f, 1.0f)),
            new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.0f), new Color4(0.0f, 0.0f, 1.0f, 1.0f))
        };

        bool dynamic = false;
        if (dynamic)
        {
            _vertexBuffer = Device.CreateBuffer(VertexPositionColor.SizeInBytes * 3, BindFlags.VertexBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write);
            MappedSubresource mappedSubresource = DeviceContext.Map(_vertexBuffer, 0, MapMode.WriteDiscard);
            triangleVertices.CopyTo(mappedSubresource.AsSpan <VertexPositionColor>(3));
            DeviceContext.Unmap(_vertexBuffer, 0);
        }
        else
        {
            _vertexBuffer = Device.CreateBuffer(triangleVertices, BindFlags.VertexBuffer);
        }

        InputElementDescription[] inputElementDescs = new[]
        {
            new InputElementDescription("POSITION", 0, Format.R32G32B32_Float, 0, 0),
            new InputElementDescription("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
        };

        Span <byte> vertexShaderByteCode = CompileBytecode("Triangle.hlsl", "VSMain", "vs_4_0");
        Span <byte> pixelShaderByteCode  = CompileBytecode("Triangle.hlsl", "PSMain", "ps_4_0");

        _vertexShader = Device.CreateVertexShader(vertexShaderByteCode);
        _pixelShader  = Device.CreatePixelShader(pixelShaderByteCode);
        _inputLayout  = Device.CreateInputLayout(inputElementDescs, vertexShaderByteCode);
    }
Esempio n. 8
0
        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 D3D11GraphicsDevice(bool validation, Window window)
        {
            Window = window;
            if (CreateDXGIFactory1(out Factory).Failure)
            {
                throw new InvalidOperationException("Cannot create IDXGIFactory1");
            }

            using (IDXGIAdapter1 adapter = GetHardwareAdapter())
            {
                DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;
                if (validation && SdkLayersAvailable())
                {
                    creationFlags |= DeviceCreationFlags.Debug;
                }

                if (D3D11CreateDevice(
                        adapter,
                        DriverType.Unknown,
                        creationFlags,
                        s_featureLevels,
                        out ID3D11Device tempDevice, out FeatureLevel, out ID3D11DeviceContext tempContext).Failure)
                {
                    // If the initialization fails, fall back to the WARP device.
                    // For more information on WARP, see:
                    // http://go.microsoft.com/fwlink/?LinkId=286690
                    D3D11CreateDevice(
                        null,
                        DriverType.Warp,
                        creationFlags,
                        s_featureLevels,
                        out tempDevice, out FeatureLevel, out tempContext).CheckError();
                }

                Device        = tempDevice.QueryInterface <ID3D11Device1>();
                DeviceContext = tempContext.QueryInterface <ID3D11DeviceContext1>();
                tempContext.Dispose();
                tempDevice.Dispose();
            }

            IntPtr hwnd = window.Handle;

            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                Width             = window.Width,
                Height            = window.Height,
                Format            = Format.B8G8R8A8_UNorm,
                BufferCount       = FrameCount,
                Usage             = DXGI.Usage.RenderTargetOutput,
                SampleDescription = new SampleDescription(1, 0),
                Scaling           = Scaling.Stretch,
                SwapEffect        = SwapEffect.FlipDiscard,
                AlphaMode         = AlphaMode.Ignore
            };

            SwapChainFullscreenDescription fullscreenDescription = new SwapChainFullscreenDescription
            {
                Windowed = true
            };


            SwapChain = Factory.CreateSwapChainForHwnd(Device, hwnd, swapChainDescription, fullscreenDescription);
            Factory.MakeWindowAssociation(hwnd, WindowAssociationFlags.IgnoreAltEnter);

            BackBuffer       = SwapChain.GetBuffer <ID3D11Texture2D>(0);
            RenderTargetView = Device.CreateRenderTargetView(BackBuffer);
        }
            public static DesktopDuplicatorInternal CreateDesktopDuplicator(ILogger logger, int adapterIndex, int outputDeviceIndex)
            {
                var dd = new DesktopDuplicatorInternal
                {
                    _outputDeviceIndex = outputDeviceIndex
                };

                var createFactoryResult = DXGI.CreateDXGIFactory1(out IDXGIFactory1 factory);

                if (!createFactoryResult.Success)
                {
                    throw new DesktopDuplicationException("Couldn't create a DXGI Factory.");
                }

                IDXGIAdapter1 adapter = null;
                IDXGIOutput   output  = null;

                try
                {
                    var result = factory.EnumAdapters1(adapterIndex, out adapter);
                    if (result.Failure)
                    {
                        throw new DesktopDuplicationException($"An error occurred attempting to retrieve the adapter at the specified index ({adapterIndex}): {result}");
                    }

                    if (adapter == null)
                    {
                        throw new DesktopDuplicationException($"An adapter was not found at the specified index ({adapterIndex}).");
                    }

                    logger.LogInformation($"Using adapter at index {adapterIndex} - {adapter.Description.Description}");

                    var createD3dDeviceResult = D3D11.D3D11CreateDevice(adapter, DriverType.Unknown, DeviceCreationFlags.None, null, out dd._d3dDevice, out dd._immediateContext);
                    if (!createD3dDeviceResult.Success)
                    {
                        throw new DesktopDuplicationException("Couldn't create a D3D device from the specified adapter.");
                    }

                    using var device = dd._d3dDevice.QueryInterface <IDXGIDevice>();
                    var outputResult = adapter.EnumOutputs(outputDeviceIndex, out output);
                    if (outputResult.Failure)
                    {
                        throw new DesktopDuplicationException($"An error occurred attempting to retrieve the output device at the specified index ({outputDeviceIndex}): {outputResult}");
                    }

                    if (output == null)
                    {
                        throw new DesktopDuplicationException($"An output was not found at the specified index ({outputDeviceIndex}).");
                    }

                    logger.LogInformation($"Using output device on adapter {adapterIndex} at index {outputDeviceIndex}.");

                    var output6 = output.QueryInterface <IDXGIOutput6>();
                    try
                    {
                        // Copy the values to a new rect.
                        var rectTemp = output6.Description.DesktopCoordinates;
                        dd._desktopRect = new RawRect(rectTemp.Left, rectTemp.Top, rectTemp.Right, rectTemp.Bottom);

                        dd._outputDuplication = output6.DuplicateOutput(device);

                        var stagingTexture = new Texture2DDescription()
                        {
                            CpuAccessFlags    = CpuAccessFlags.Read,
                            BindFlags         = BindFlags.None,
                            Format            = dd._outputDuplication.Description.ModeDescription.Format,
                            Width             = Math.Abs(dd._desktopRect.Right - dd._desktopRect.Left),
                            Height            = Math.Abs(dd._desktopRect.Bottom - dd._desktopRect.Top),
                            OptionFlags       = ResourceOptionFlags.None,
                            MipLevels         = 1,
                            ArraySize         = 1,
                            SampleDescription = { Count = 1, Quality = 0 },
                            Usage             = Usage.Staging // << can be read by CPU
                        };

                        // Initialize the Output Duplication -- If this isn't done occassionally an 'Unsupported' result will occur with DuplicationOutput1
                        dd._desktopImageTexture = dd._d3dDevice.CreateTexture2D(stagingTexture);
                    }
                    catch (SharpGenException ex)
                    {
                        if (ex.Descriptor.NativeApiCode == "DXGI_ERROR_UNSUPPORTED")
                        {
                            throw new DesktopDuplicationException("Unsupported desktop mode or scenario.");
                        }
                        else if (ex.Descriptor.NativeApiCode == "DXGI_ERROR_NOT_CURRENTLY_AVAILABLE")
                        {
                            throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again.");
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                finally
                {
                    if (output != null)
                    {
                        output.Dispose();
                    }

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

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

                return(dd);
            }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D11"/> class.
        /// </summary>
        internal DeviceHandlerD3D11(GraphicsDeviceConfiguration deviceConfig, IDXGIAdapter1 dxgiAdapter)
        {
            _dxgiAdapter = dxgiAdapter;

            // Define possible create flags
            var createFlags = D3D11.DeviceCreationFlags.BgraSupport;

            if (deviceConfig.CoreConfiguration.DebugEnabled)
            {
                createFlags |= D3D11.DeviceCreationFlags.Debug;
            }

            // Define all steps on which we try to initialize Direct3D
            var initParameterQueue =
                new List <Tuple <D3D.FeatureLevel, D3D11.DeviceCreationFlags, HardwareDriverLevel> >();

            // Define all tries for hardware initialization
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_1, createFlags, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_0, createFlags, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_10_0, createFlags, HardwareDriverLevel.Direct3D10));

            // Try to create the device, each defined configuration step by step
            foreach (var(actFeatureLevel, actCreateFlags, actDriverLevel) in initParameterQueue)
            {
                try
                {
                    // Try to create the device using current parameters
                    var result = D3D11CreateDevice(
                        dxgiAdapter, D3D.DriverType.Unknown, createFlags,
                        new D3D.FeatureLevel[] { actFeatureLevel }, out var device);
                    if (!result.Success)
                    {
                        continue;
                    }
                    if (device == null)
                    {
                        continue;
                    }

                    try
                    {
                        _device1 = device.QueryInterface <D3D11.ID3D11Device1>();
                        _device3 = SeeingSharpUtil.TryExecute(() => _device1.QueryInterface <D3D11.ID3D11Device3>());

                        if (_device3 != null)
                        {
                            _immediateContext3 = _device3.ImmediateContext3;
                        }
                    }
                    finally
                    {
                        SeeingSharpUtil.SafeDispose(ref device);
                    }

                    // Device successfully created, save all parameters and break this loop
                    _featureLevel    = actFeatureLevel;
                    _creationFlags   = actCreateFlags;
                    this.DriverLevel = actDriverLevel;
                    break;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            // Throw exception on failure
            if (_device1 == null)
            {
                throw new SeeingSharpGraphicsException("Unable to initialize d3d11 device!");
            }

            // Get immediate context from the device
            _immediateContext = _device1.ImmediateContext;
        }
Esempio n. 12
0
        public DeviceD3D11(IDXGIFactory1 factory, bool validation)
        {
            DXGIFactory = factory;
            var adapters = DXGIFactory.EnumAdapters1();

            for (var i = 0; i < adapters.Length; i++)
            {
                var adapter = adapters[0];
                var desc    = adapter.Description1;

                // Don't select the Basic Render Driver adapter.
                if ((desc.Flags & AdapterFlags.Software) != AdapterFlags.None)
                {
                    continue;
                }

                var creationFlags = DeviceCreationFlags.BgraSupport /* | DeviceCreationFlags.VideoSupport*/;

                if (validation)
                {
                    creationFlags |= DeviceCreationFlags.Debug;
                }

                if (D3D11CreateDevice(
                        null,
                        DriverType.Hardware,
                        creationFlags,
                        s_featureLevels,
                        out D3D11Device,
                        out FeatureLevel,
                        out D3D11DeviceContext).Failure)
                {
                    // Remove debug flag not being supported.
                    creationFlags &= ~DeviceCreationFlags.Debug;

                    if (D3D11CreateDevice(null, DriverType.Hardware,
                                          creationFlags, s_featureLevels,
                                          out D3D11Device, out FeatureLevel, out D3D11DeviceContext).Failure)
                    {
                        throw new GraphicsException("Cannot create D3D11 Device");
                    }
                }

                DXGIAdapter = adapter;
                break;
            }

            D3D11Device1 = D3D11Device.QueryInterfaceOrNull <ID3D11Device1>();

            // Detect multithreading
            FeatureDataThreading featureDataThreading = default;

            if (D3D11Device.CheckFeatureSupport(DirectX.Direct3D11.Feature.Threading, ref featureDataThreading))
            {
                SupportsConcurrentResources = featureDataThreading.DriverConcurrentCreates;
                SupportsCommandLists        = featureDataThreading.DriverCommandLists;
            }

            // Init device features.
            InitializeFeatures();

            // Create command queue's.
            _graphicsCommandQueue = new CommandQueueD3D11(this, D3D11DeviceContext);
            _computeCommandQueue  = new CommandQueueD3D11(this, CommandQueueType.Compute);
            _copyCommandQueue     = new CommandQueueD3D11(this, CommandQueueType.Copy);
        }