예제 #1
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>
        /// <param name="debugEnabled">Is debug mode enabled?</param>
        internal DeviceHandlerD3D9(DXGI.Adapter1 dxgiAdapter, bool isSoftwareAdapter, bool debugEnabled)
        {
            // Update member variables
            m_dxgiAdapter = dxgiAdapter;

            try
            {
                // Just needed when on true hardware
                if (!isSoftwareAdapter)
                {
                    //Prepare device creation
                    D3D9.CreateFlags createFlags =
                        D3D9.CreateFlags.HardwareVertexProcessing |
                        D3D9.CreateFlags.PureDevice |
                        D3D9.CreateFlags.FpuPreserve |
                        D3D9.CreateFlags.Multithreaded;
                    D3D9.PresentParameters presentparams = new D3D9.PresentParameters();
                    presentparams.Windowed             = true;
                    presentparams.SwapEffect           = D3D9.SwapEffect.Discard;
                    presentparams.DeviceWindowHandle   = GetDesktopWindow();
                    presentparams.PresentationInterval = D3D9.PresentInterval.Default;
                    presentparams.BackBufferCount      = 1;

                    //Create the device finally
                    m_direct3DEx = new D3D9.Direct3DEx();

                    // Try to find the Direct3D9 adapter that maches given DXGI adapter
                    m_adapterIndex = -1;
                    for (int loop = 0; loop < m_direct3DEx.AdapterCount; loop++)
                    {
                        var d3d9AdapterInfo = m_direct3DEx.GetAdapterIdentifier(loop);
                        if (d3d9AdapterInfo.DeviceId == m_dxgiAdapter.Description1.DeviceId)
                        {
                            m_adapterIndex = loop;
                            break;
                        }
                    }

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

                    // Try to create the device
                    m_deviceEx = new D3D9.DeviceEx(m_direct3DEx, m_adapterIndex, D3D9.DeviceType.Hardware, IntPtr.Zero, createFlags, presentparams);
                }
                else
                {
                    //Not supported in software mode
                }
            }
            catch (Exception)
            {
                // No direct3d 9 interface support
                GraphicsHelper.SafeDispose(ref m_direct3DEx);
                GraphicsHelper.SafeDispose(ref m_deviceEx);
            }
        }
예제 #2
0
        /// <summary>
        /// Unloads all resources.
        /// </summary>
        internal void UnloadResources()
        {
            m_factory = CommonTools.DisposeObject(m_factory);
            m_adapter = CommonTools.DisposeObject(m_adapter);
#if UNIVERSAL
            m_device = CommonTools.DisposeObject(m_device);
#endif
        }
예제 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EngineDevice"/> class.
        /// </summary>
        internal EngineDevice(GraphicsCore core, GraphicsCoreConfiguration coreConfiguration, DXGI.Adapter1 adapter, bool isSoftwareAdapter, bool debugEnabled)
        {
            m_core              = core;
            m_adapter1          = adapter;
            m_adapterDesc1      = m_adapter1.Description1;
            m_isSoftwareAdapter = isSoftwareAdapter;
            m_debugEnabled      = debugEnabled;
            m_configuration     = new GraphicsDeviceConfiguration(coreConfiguration);

            // Set default antialiasing configurations
            m_sampleDescWithAntialiasing = new DXGI.SampleDescription(1, 0);

            // Initialize all direct3D APIs
            try
            {
#if UNIVERSAL
                m_handlerD3D11 = new DeviceHandlerD3D11(adapter, debugEnabled);
                m_handlerDXGI  = new DeviceHandlerDXGI(adapter, m_handlerD3D11.Device1);
#endif
#if DESKTOP
                m_handlerD3D11 = new DeviceHandlerD3D11(adapter, debugEnabled);
                m_handlerDXGI  = new DeviceHandlerDXGI(adapter, m_handlerD3D11.Device1);
                m_handlerD3D9  = new DeviceHandlerD3D9(adapter, isSoftwareAdapter, debugEnabled);
#endif
            }
            catch (Exception ex)
            {
                m_initializationException = ex;

#if UNIVERSAL
                m_handlerD3D11 = null;
                m_handlerDXGI  = null;
#endif
#if DESKTOP
                m_handlerD3D11 = null;
                m_handlerDXGI  = null;
                m_handlerD3D9  = null;
#endif
            }

            // Set default configuration
            m_configuration.TextureQuality  = !isSoftwareAdapter && m_handlerD3D11.IsDirect3D10OrUpperHardware ? TextureQuality.Hight : TextureQuality.Low;
            m_configuration.GeometryQuality = !isSoftwareAdapter && m_handlerD3D11.IsDirect3D10OrUpperHardware ? GeometryQuality.Hight : GeometryQuality.Low;

            // Initialize handlers for feature support information
            if (m_initializationException == null)
            {
                m_isStandardAntialiasingSupported = CheckIsStandardAntialiasingPossible();
            }

            // Initialize direct2D handler finally
            if (m_handlerD3D11 != null)
            {
                m_handlerD2D            = new DeviceHandlerD2D(m_core, this);
                this.FakeRenderTarget2D = m_handlerD2D.RenderTarget;
            }
        }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerDXGI"/> class.
        /// </summary>
        internal DeviceHandlerDXGI(DXGI.Adapter1 adapter, D3D11.Device device)
        {
#if UNIVERSAL
            m_device = device.QueryInterface <DXGI.Device3>();
#endif
            m_adapter = adapter;

            m_factory = m_adapter.GetParent <DXGI.Factory2>();
        }
예제 #5
0
        internal DXGI.Output GetOutputByOutputInfo(EngineOutputInfo outputInfo)
        {
            int adapterCount = m_dxgiFactory.GetAdapterCount1();

            if (outputInfo.AdapterIndex >= adapterCount)
            {
                throw new SeeingSharpException($"Unable to find adapter with index {outputInfo.AdapterIndex}!");
            }

            using (DXGI.Adapter1 adapter = m_dxgiFactory.GetAdapter1(outputInfo.AdapterIndex))
            {
                int outputCount = adapter.GetOutputCount();
                if (outputInfo.OutputIndex >= outputCount)
                {
                    throw new SeeingSharpException($"Unable to find output with index {outputInfo.OutputIndex} on adapter {outputInfo.AdapterIndex}!");
                }

                return(adapter.GetOutput(outputInfo.OutputIndex));
            }
        }
예제 #6
0
        /// <summary>
        /// Loads all adapter information and builds up all needed view models in a background thread.
        /// </summary>
        private void LoadAdapterInformation()
        {
            m_adapters = new List <EngineAdapterInfo>();

            int adapterCount = m_dxgiFactory.GetAdapterCount1();

            for (int loop = 0; loop < adapterCount; loop++)
            {
                try
                {
                    DXGI.Adapter1 actAdapter = m_dxgiFactory.GetAdapter1(loop);
                    m_adapters.Add(new EngineAdapterInfo(loop, actAdapter));
                }
                catch (Exception)
                {
                    //No exception handling needed here
                    // .. adapter information simply can not be gathered
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EngineAdapterInfo" /> class.
        /// </summary>
        internal EngineAdapterInfo(int adapterIndex, DXGI.Adapter1 adapter)
        {
            m_outputs      = new List <EngineOutputInfo>();
            m_adapter      = adapter;
            m_adapterIndex = adapterIndex;

            m_adapterDescription = adapter.Description;
            m_isSoftware         =
                (m_adapterDescription.Description == "Microsoft Basic Render Driver") ||
                ((!string.IsNullOrEmpty(m_adapterDescription.Description)) && m_adapterDescription.Description.Contains("Software")) ||
                ((!string.IsNullOrEmpty(m_adapterDescription.Description)) && m_adapterDescription.Description.Contains("Microsoft Basic Render Driver"));

            m_d3d11FeatureLevel = D3D11.Device.GetSupportedFeatureLevel(adapter);

            //Query for output information
            DXGI.Output[] outputs = adapter.Outputs;
            for (int loop = 0; loop < outputs.Length; loop++)
            {
                try
                {
                    DXGI.Output actOutput = outputs[loop];
                    try
                    {
                        m_outputs.Add(new EngineOutputInfo(adapterIndex, loop, actOutput));
                    }
                    finally
                    {
                        actOutput.Dispose();
                    }
                }
                catch (Exception)
                {
                    //Query for output information not possible
                    // .. no special handling needed here
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GorgonVideoDevice"/> class.
        /// </summary>
        /// <param name="adapter">DXGI video adapter.</param>
        /// <param name="deviceType">Type of video device.</param>
        /// <param name="index">Index of the device.</param>
        internal GorgonVideoDevice(GI.Adapter1 adapter, VideoDeviceType deviceType, int index)
        {
            VideoDeviceType = deviceType;

            Index = index;
            DedicatedSystemMemory = adapter.Description1.DedicatedSystemMemory;
            DedicatedVideoMemory  = adapter.Description1.DedicatedVideoMemory;
            DeviceID             = adapter.Description1.DeviceId;
            HardwareFeatureLevel = DeviceFeatureLevel.Unsupported;
            UUID               = adapter.Description1.Luid;
            Revision           = adapter.Description1.Revision;
            SharedSystemMemory = adapter.Description1.SharedSystemMemory;
            SubSystemID        = adapter.Description1.SubsystemId;
            VendorID           = adapter.Description1.VendorId;

            switch (deviceType)
            {
            case VideoDeviceType.Software:
                Name = Resources.GORGFX_DEVICE_NAME_WARP;
                HardwareFeatureLevel = SupportedFeatureLevel = DeviceFeatureLevel.SM4_1;
                break;

            case VideoDeviceType.ReferenceRasterizer:
                Name = Resources.GORGFX_DEVICE_NAME_REFRAST;
                HardwareFeatureLevel = SupportedFeatureLevel = DeviceFeatureLevel.SM5;
                break;

            default:
                Name = adapter.Description1.Description;
                EnumerateFeatureLevels(D3D.Device.GetSupportedFeatureLevel(adapter));
                break;
            }


            Outputs = new GorgonNamedObjectReadOnlyCollection <GorgonVideoOutput>(false, new GorgonVideoOutput[] { });
        }
        private static GraphicsAdapter CreateAdapter(SharpDX.DXGI.Adapter1 device, SharpDX.DXGI.Output monitor)
        {
            var adapter = new GraphicsAdapter();

            adapter._adapter = device;

            adapter.DeviceName    = monitor.Description.DeviceName.TrimEnd(new char[] { '\0' });
            adapter.Description   = device.Description1.Description.TrimEnd(new char[] { '\0' });
            adapter.DeviceId      = device.Description1.DeviceId;
            adapter.Revision      = device.Description1.Revision;
            adapter.VendorId      = device.Description1.VendorId;
            adapter.SubSystemId   = device.Description1.SubsystemId;
            adapter.MonitorHandle = monitor.Description.MonitorHandle;

#if WINDOWS_UAP
            var desktopWidth  = monitor.Description.DesktopBounds.Right - monitor.Description.DesktopBounds.Left;
            var desktopHeight = monitor.Description.DesktopBounds.Bottom - monitor.Description.DesktopBounds.Top;
#else
            var desktopWidth  = monitor.Description.DesktopBounds.Width;
            var desktopHeight = monitor.Description.DesktopBounds.Height;
#endif

            var modes = new List <DisplayMode>();

            foreach (var formatTranslation in FormatTranslations)
            {
                SharpDX.DXGI.ModeDescription[] displayModes;

                // This can fail on headless machines, so just assume the desktop size
                // is a valid mode and return that... so at least our unit tests work.
                try
                {
                    displayModes = monitor.GetDisplayModeList(formatTranslation.Key, 0);
                }
                catch (SharpDX.SharpDXException)
                {
                    var mode = new DisplayMode(desktopWidth, desktopHeight, SurfaceFormat.Color);
                    modes.Add(mode);
                    adapter._currentDisplayMode = mode;
                    break;
                }


                foreach (var displayMode in displayModes)
                {
                    var mode = new DisplayMode(displayMode.Width, displayMode.Height, formatTranslation.Value);

                    // Skip duplicate modes with the same width/height/formats.
                    if (modes.Contains(mode))
                    {
                        continue;
                    }

                    modes.Add(mode);

                    if (adapter._currentDisplayMode == null)
                    {
                        if (mode.Width == desktopWidth && mode.Height == desktopHeight && mode.Format == SurfaceFormat.Color)
                        {
                            adapter._currentDisplayMode = mode;
                        }
                    }
                }
            }

            adapter._supportedDisplayModes = new DisplayModeCollection(modes);

            if (adapter._currentDisplayMode == null) //(i.e. desktop mode wasn't found in the available modes)
            {
                adapter._currentDisplayMode = new DisplayMode(desktopWidth, desktopHeight, SurfaceFormat.Color);
            }

            return(adapter);
        }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DeviceHandlerD3D11"/> class.
        /// </summary>
        /// <param name="dxgiAdapter">The tasrget adapter.</param>
        /// <param name="debugEnabled">Is debug mode enabled?</param>
        internal DeviceHandlerD3D11(DXGI.Adapter1 dxgiAdapter, bool debugEnabled)
        {
            m_dxgiAdapter = dxgiAdapter;

            // Define possible create flags
            D3D11.DeviceCreationFlags createFlagsBgra = D3D11.DeviceCreationFlags.BgraSupport;
            D3D11.DeviceCreationFlags createFlags     = D3D11.DeviceCreationFlags.None;
            if (debugEnabled)
            {
                createFlagsBgra |= D3D11.DeviceCreationFlags.Debug;
                createFlags     |= D3D11.DeviceCreationFlags.Debug;
            }

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

            // Define all trys for hardware initialization
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_1, createFlagsBgra, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_11_0, createFlagsBgra, HardwareDriverLevel.Direct3D11));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_10_0, createFlagsBgra, HardwareDriverLevel.Direct3D10));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_3, createFlagsBgra, HardwareDriverLevel.Direct3D9_3));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_2, createFlagsBgra, HardwareDriverLevel.Direct3D9_2));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_1, createFlagsBgra, HardwareDriverLevel.Direct3D9_1));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_10_0, createFlags, HardwareDriverLevel.Direct3D10));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_3, createFlags, HardwareDriverLevel.Direct3D9_3));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_2, createFlags, HardwareDriverLevel.Direct3D9_2));
            initParameterQueue.Add(Tuple.Create(
                                       D3D.FeatureLevel.Level_9_1, createFlags, HardwareDriverLevel.Direct3D9_1));

            // Try to create the device, each defined configuration step by step
            foreach (Tuple <D3D.FeatureLevel, D3D11.DeviceCreationFlags, HardwareDriverLevel> actInitParameters in initParameterQueue)
            {
                D3D.FeatureLevel          featureLevel    = actInitParameters.Item1;
                D3D11.DeviceCreationFlags direct3D11Flags = actInitParameters.Item2;
                HardwareDriverLevel       actDriverLevel  = actInitParameters.Item3;

                try
                {
                    // Try to create the device using current parameters
                    using (D3D11.Device device = new D3D11.Device(dxgiAdapter, direct3D11Flags, featureLevel))
                    {
                        m_device1 = device.QueryInterface <D3D11.Device1>();
                        m_device3 = CommonTools.TryExecute(() => m_device1.QueryInterface <D3D11.Device3>());
                        if (m_device3 != null)
                        {
                            m_immediateContext3 = m_device3.ImmediateContext3;
                        }
                    }

                    // Device successfully created, save all parameters and break this loop
                    m_featureLevel  = featureLevel;
                    m_creationFlags = direct3D11Flags;
                    m_driverLevel   = actDriverLevel;
                    break;
                }
                catch (Exception) { }
            }

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

            // Get immediate context from the device
            m_immediateContext = m_device1.ImmediateContext;
        }
예제 #11
0
        public D3D12GraphicsDevice(bool validation, PresentationParameters presentationParameters)
            : base(GraphicsBackend.Direct3D12, presentationParameters)
        {
#if DEBUG
            SharpDX.Configuration.EnableObjectTracking      = true;
            SharpDX.Configuration.ThrowOnShaderCompileError = false;
#endif

            // Just try to enable debug layer.
            try
            {
                if (validation)
                {
                    // Enable the D3D12 debug layer.
                    DebugInterface.Get().EnableDebugLayer();

                    Validation = true;
                }
            }
            catch (SharpDX.SharpDXException)
            {
                Validation = false;
            }

            // Create factory first.
            DXGIFactory = new DXGI.Factory4(Validation);

            var adapterCount = DXGIFactory.GetAdapterCount1();
            for (var i = 0; i < adapterCount; i++)
            {
                var adapter = DXGIFactory.GetAdapter1(i);
                var desc    = adapter.Description1;

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

                var tempDevice = new Device(adapter, FeatureLevel.Level_11_0);
                tempDevice.Dispose();

                DXGIAdapter = adapter;
            }

            try
            {
                Device = new Device(DXGIAdapter, FeatureLevel.Level_11_0);
            }
            catch (SharpDXException)
            {
                // Create the Direct3D 12 with WARP adapter.
                var warpAdapter = DXGIFactory.GetWarpAdapter();
                Device = new Device(warpAdapter, FeatureLevel.Level_11_0);
            }

            if (Validation)
            {
                var infoQueue = Device.QueryInterfaceOrNull <InfoQueue>();
                if (infoQueue != null)
                {
                    infoQueue.SetBreakOnSeverity(MessageSeverity.Corruption, true);
                    infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true);
                    infoQueue.AddStorageFilterEntries(new InfoQueueFilter
                    {
                        DenyList = new InfoQueueFilterDescription
                        {
                            Ids = new[]
                            {
                                MessageId.MapInvalidNullRange,
                                MessageId.UnmapInvalidNullRange
                            }
                        }
                    });
                    infoQueue.Dispose();
                }
            }

            // Init capabilities.
            FeatureLevel = Device.CheckMaxSupportedFeatureLevel(s_featureLevels);
            var D3D12Options = Device.D3D12Options;

            var dataShaderModel       = Device.CheckShaderModel(ShaderModel.Model60);
            var dataShaderModel1      = Device.CheckShaderModel(ShaderModel.Model61);
            var dataShaderModel2      = Device.CheckShaderModel(ShaderModel.Model62);
            var waveIntrinsicsSupport = default(FeatureDataD3D12Options1);
            Device.CheckFeatureSupport(Feature.D3D12Options1, ref waveIntrinsicsSupport);

            var featureDataRootSignature = new FeatureDataRootSignature
            {
                HighestVersion = RootSignatureVersion.Version11
            };

            if (!Device.CheckFeatureSupport(Feature.RootSignature, ref featureDataRootSignature))
            {
                featureDataRootSignature.HighestVersion = RootSignatureVersion.Version10;
            }

            var gpuVaSupport = Device.GpuVirtualAddressSupport;

            // Create direct command queue.
            GraphicsQueue = new D3D12CommandQueue(this, CommandListType.Direct);

            // Get descriptor heaps size.
            RTVDescriptorSize = Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            DSVDescriptorSize = Device.GetDescriptorHandleIncrementSize(DescriptorHeapType.DepthStencilView);

            // Create main swap chain.
            _mainSwapchain = new D3D12Swapchain(this, presentationParameters);
        }