/// <summary>
        /// Function to add the WARP software device.
        /// </summary>
        /// <param name="index">Index of the device.</param>
        /// <param name="factory">The factory used to query the adapter.</param>
        /// <param name="log">The log interface used to send messages to a debug log.</param>
        /// <returns>The video adapter used for WARP software rendering.</returns>
        private static VideoAdapterInfo GetWARPSoftwareDevice(int index, Factory5 factory, IGorgonLog log)
        {
            D3D11.DeviceCreationFlags flags = D3D11.DeviceCreationFlags.None;

            if (GorgonGraphics.IsDebugEnabled)
            {
                flags = D3D11.DeviceCreationFlags.Debug;
            }

            using (Adapter warp = factory.GetWarpAdapter())
                using (Adapter4 warpAdapter4 = warp.QueryInterface <Adapter4>())
                    using (var D3DDevice = new D3D11.Device(warpAdapter4, flags))
                        using (D3D11.Device5 D3DDevice5 = D3DDevice.QueryInterface <D3D11.Device5>())
                        {
                            FeatureSet?featureSet = GetFeatureLevel(D3DDevice5);

                            if (featureSet == null)
                            {
                                log.Print("WARNING: The WARP software adapter does not support the minimum feature set of 12.0. This device will be excluded.", LoggingLevel.All);
                                return(null);
                            }

                            var result = new VideoAdapterInfo(index, warpAdapter4, featureSet.Value, new Dictionary <string, VideoOutputInfo>(), VideoDeviceType.Software);

                            PrintLog(result, log);

                            return(result);
                        }
        }
Пример #2
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            SharpDX.Direct3D.FeatureLevel[] levels = graphicsProfiles.ToFeatureLevel();
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Create Device D3D11 with feature Level based on profile
            nativeDevice        = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, levels);
            nativeDeviceContext = nativeDevice.ImmediateContext;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }

            InitializeStages();

            // Create the input layout manager
            if (InputLayoutManager == null)
            {
                InputLayoutManager = new InputLayoutManager(this).DisposeBy(this);
            }
        }
Пример #3
0
 public static SharpDX.Direct3D11.DeviceCreationFlags Convert(DotGame.Graphics.DeviceCreationFlags flags)
 {
     SharpDX.Direct3D11.DeviceCreationFlags f = 0;
     if (flags.HasFlag(DotGame.Graphics.DeviceCreationFlags.Debug))
     {
         f |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
     }
     return(f);
 }
Пример #4
0
        /// <summary>
        /// Unloads all resources.
        /// </summary>
        public void UnloadResources()
        {
            m_immediateContext  = CommonTools.DisposeObject(m_immediateContext);
            m_immediateContext3 = CommonTools.DisposeObject(m_immediateContext3);
            m_device1           = CommonTools.DisposeObject(m_device1);
            m_device3           = CommonTools.DisposeObject(m_device3);

            m_creationFlags = D3D11.DeviceCreationFlags.None;
            m_featureLevel  = D3D.FeatureLevel.Level_11_0;
        }
Пример #5
0
		public static SharpDX.Direct3D11.Device Create11(
			Direct3D11.DeviceCreationFlags cFlags = Direct3D11.DeviceCreationFlags.None,
			Direct3D.FeatureLevel minLevel = Direct3D.FeatureLevel.Level_9_1
		)
		{
			using (var dg = new DisposeGroup())
			{
				var level = Direct3D11.Device.GetSupportedFeatureLevel();
				if (level < minLevel)
					return null;
				return new Direct3D11.Device(Direct3D.DriverType.Hardware, cFlags, level);
			}
		}
Пример #6
0
        /// <summary>
        ///   Initializes the device for the specified profile.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through PIX markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Create Direct3D 11 Device with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // Direct3D 12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();

                    nativeDevice = new Device(Adapter.NativeAdapter, creationFlags, level);

                    RequestedProfile = graphicsProfile;
                    break;
                }
                catch
                {
                    if (index == graphicsProfiles.Length - 1)
                    {
                        throw;
                    }
                }
            }

            nativeDeviceContext = nativeDevice.ImmediateContext;

            // We keep one reference so that it doesn't disappear with InternalMainCommandList
            ((IUnknown)nativeDeviceContext).AddReference();
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }
        }
Пример #7
0
        private void InitDevice(int numSamples)
        {
            var width  = m_Window.ClientRectangle.Width;
            var height = m_Window.ClientRectangle.Height;

            var refreshRate = new Rational(60, 1);
            var modeDesc    = new ModeDescription(width, height, refreshRate, Format.R8G8B8A8_UNorm);

            var quality = GetBestQuality(numSamples);

            var swapChainDesc = new SwapChainDescription()
            {
                BufferCount       = 1,
                IsWindowed        = true,
                ModeDescription   = modeDesc,
                SampleDescription = new SampleDescription(numSamples, quality),
                OutputHandle      = Game.Inst.Window.Handle,
                Usage             = Usage.RenderTargetOutput
            };

#if DEBUG
            const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.Debug;
#else
            const D3D11.DeviceCreationFlags DEBUG_FLAG = D3D11.DeviceCreationFlags.None;
#endif

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.SingleThreaded | DEBUG_FLAG, swapChainDesc, out Device, out m_SwapChain);
            m_DeviceContext = Device.ImmediateContext;

            var rsd = new D3D11.RasterizerStateDescription {
                CullMode             = D3D11.CullMode.Back,
                FillMode             = D3D11.FillMode.Solid,
                IsMultisampleEnabled = true,
            };
            var rs = new D3D11.RasterizerState(Device, rsd);
            Device.ImmediateContext.Rasterizer.State = rs;

            var backBuffer = m_SwapChain.GetBackBuffer <D3D11.Texture2D>(0);

            m_DefaultRenderTarget = new SharpDXRenderTarget(this, backBuffer, width, height, new D3D11.RenderTargetView(Device, backBuffer));
            RenderTarget          = m_DefaultRenderTarget;

            m_DeviceContext.Rasterizer.SetViewport(0.0f, 0.0f, width, height);
        }
Пример #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsDevice" /> class using the default GraphicsAdapter
        /// and the Level10 <see cref="GraphicsProfile" />.
        /// </summary>
        /// <param name="device">The device.</param>
        private GraphicsDevice(GraphicsDevice device)
        {
            RootDevice = device;
            Adapter = device.Adapter;
            creationFlags = device.creationFlags;
            Features = device.Features;
            sharedDataPerDevice = device.sharedDataPerDevice;
            InputLayoutManager = device.InputLayoutManager;
            nativeDevice = device.NativeDevice;
            nativeDeviceContext = new SharpDX.Direct3D11.DeviceContext(NativeDevice).DisposeBy(this);
            nativeDeviceProfiler = SharpDX.ComObject.QueryInterfaceOrNull<UserDefinedAnnotation>(nativeDeviceContext.NativePointer);
            isDeferred = true;
            IsDebugMode = device.IsDebugMode;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(device, nativeDeviceContext, "DeferredContext");
            }
            NeedWorkAroundForUpdateSubResource = !Features.HasDriverCommandLists;

            primitiveQuad = new PrimitiveQuad(this).DisposeBy(this);

            InitializeStages();
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphicsDevice" /> class using the default GraphicsAdapter
        /// and the Level10 <see cref="GraphicsProfile" />.
        /// </summary>
        /// <param name="device">The device.</param>
        private GraphicsDevice(GraphicsDevice device)
        {
            RootDevice           = device;
            Adapter              = device.Adapter;
            creationFlags        = device.creationFlags;
            Features             = device.Features;
            sharedDataPerDevice  = device.sharedDataPerDevice;
            InputLayoutManager   = device.InputLayoutManager;
            nativeDevice         = device.NativeDevice;
            nativeDeviceContext  = new SharpDX.Direct3D11.DeviceContext(NativeDevice).DisposeBy(this);
            nativeDeviceProfiler = SharpDX.ComObject.QueryInterfaceOrNull <UserDefinedAnnotation>(nativeDeviceContext.NativePointer);
            isDeferred           = true;
            IsDebugMode          = device.IsDebugMode;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(device, nativeDeviceContext, "DeferredContext");
            }
            NeedWorkAroundForUpdateSubResource = !Features.HasDriverCommandLists;

            primitiveQuad = new PrimitiveQuad(this).DisposeBy(this);

            InitializeStages();
        }
Пример #10
0
        private void InitDevice(int adapterNumber, DeviceCreationFlags deviceCreationFlags)
        {
            Adapter adapter;
            if (adapterNumber < DXGIFactory.GetAdapterCount() - 1)
            {
                adapter = DXGIFactory.GetAdapter(adapterNumber);
            }
            else
            {
                throw new ConfigurationErrorsException(String.Format("Attempt to get adapter {0}, while adapter Count = {1}", adapterNumber, DXGIFactory.GetAdapterCount()));
            }

            //
            // we can force the feature level here.. but atm I'm not using this since it breaks on my laptop.
            SharpDX.Direct3D.FeatureLevel[] featureLevels = { SharpDX.Direct3D.FeatureLevel.Level_11_0 };
            //
            Device = new Device(adapter, deviceCreationFlags, featureLevels);
            Device10 = new Device10(adapter, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_1);

            Context = Device.ImmediateContext;
        }
Пример #11
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Create Device D3D11 with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // D3D12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();

                    // INTEL workaround: it seems Intel driver doesn't support properly feature level 9.x. Fallback to 10.
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (level < SharpDX.Direct3D.FeatureLevel.Level_10_0)
                        {
                            level = SharpDX.Direct3D.FeatureLevel.Level_10_0;
                        }
                    }

                    if (Core.Platform.Type == PlatformType.Windows &&
                        GetModuleHandle("renderdoc.dll") != IntPtr.Zero)
                    {
                        if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0)
                        {
                            level = SharpDX.Direct3D.FeatureLevel.Level_11_0;
                        }
                    }

                    nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, level);

                    // INTEL workaround: force ShaderProfile to be 10+ as well
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (graphicsProfile < GraphicsProfile.Level_10_0 && (!ShaderProfile.HasValue || ShaderProfile.Value < GraphicsProfile.Level_10_0))
                        {
                            ShaderProfile = GraphicsProfile.Level_10_0;
                        }
                    }

                    RequestedProfile = graphicsProfile;
                    break;
                }
                catch (Exception)
                {
                    if (index == graphicsProfiles.Length - 1)
                    {
                        throw;
                    }
                }
            }

            nativeDeviceContext = nativeDevice.ImmediateContext;
            // We keep one reference so that it doesn't disappear with InternalMainCommandList
            ((IUnknown)nativeDeviceContext).AddReference();
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }
        }
        public RendererOptions()
        {
#if DEBUG
            CreationFlags |= D3D11.DeviceCreationFlags.Debug;
#endif
        }
Пример #13
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;
        }
Пример #14
0
        public Renderer(Game game, SharpDX.Windows.RenderForm renderForm)
        {
            this.game = game;
            int width = renderForm.ClientSize.Width, height = renderForm.ClientSize.Height;

            ResolutionX = width; ResolutionY = height;

            #region 3d device & context
            D3D11.DeviceCreationFlags creationFlags = D3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            creationFlags |= D3D11.DeviceCreationFlags.Debug;
            #endif
            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                ModeDescription   = new DXGI.ModeDescription(width, height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm),
                SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality),
                Usage             = DXGI.Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = renderForm.Handle,
                IsWindowed        = true,
                SwapEffect        = DXGI.SwapEffect.Discard
            };
            D3D11.Device device;
            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out device, out swapChain);
            Device  = device;
            Context = Device.ImmediateContext;
            #endregion
            #region 2d device & context
            DXGI.Device dxgiDevice = Device.QueryInterface <D3D11.Device1>().QueryInterface <DXGI.Device2>();
            D2DDevice  = new D2D1.Device(dxgiDevice);
            D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);
            D2DFactory = D2DDevice.Factory;
            #endregion
            #region 2d brushes/fonts
            Brushes = new Dictionary <string, D2D1.Brush>();
            Brushes.Add("Red", new D2D1.SolidColorBrush(D2DContext, Color.Red));
            Brushes.Add("Green", new D2D1.SolidColorBrush(D2DContext, Color.Green));
            Brushes.Add("Blue", new D2D1.SolidColorBrush(D2DContext, Color.Blue));
            Brushes.Add("White", new D2D1.SolidColorBrush(D2DContext, Color.White));
            Brushes.Add("Black", new D2D1.SolidColorBrush(D2DContext, Color.Black));
            Brushes.Add("TransparentWhite", new D2D1.SolidColorBrush(D2DContext, new Color(1, 1, 1, .5f)));
            Brushes.Add("TransparentBlack", new D2D1.SolidColorBrush(D2DContext, new Color(0, 0, 0, .5f)));
            Brushes.Add("LightGray", new D2D1.SolidColorBrush(D2DContext, Color.LightGray));
            Brushes.Add("OrangeRed", new D2D1.SolidColorBrush(D2DContext, Color.OrangeRed));
            Brushes.Add("CornflowerBlue", new D2D1.SolidColorBrush(D2DContext, Color.CornflowerBlue));
            Brushes.Add("Yellow", new D2D1.SolidColorBrush(D2DContext, Color.Yellow));
            Brushes.Add("Magenta", new D2D1.SolidColorBrush(D2DContext, Color.Magenta));
            Brushes.Add("RosyBrown", new D2D1.SolidColorBrush(D2DContext, Color.RosyBrown));

            DashStyle = new D2D1.StrokeStyle(D2DFactory, new D2D1.StrokeStyleProperties()
            {
                StartCap   = D2D1.CapStyle.Flat,
                DashCap    = D2D1.CapStyle.Round,
                EndCap     = D2D1.CapStyle.Flat,
                DashStyle  = D2D1.DashStyle.Custom,
                DashOffset = 0,
                LineJoin   = D2D1.LineJoin.Round,
                MiterLimit = 1
            }, new float[] { 4f, 4f });

            FontFactory = new DWrite.Factory();
            SegoeUI24   = new DWrite.TextFormat(FontFactory, "Segoe UI", 24f);
            SegoeUI14   = new DWrite.TextFormat(FontFactory, "Segoe UI", 14f);
            Consolas14  = new DWrite.TextFormat(FontFactory, "Consolas", 14f);
            #endregion

            #region blend states
            D3D11.BlendStateDescription opaqueDesc = new D3D11.BlendStateDescription();
            opaqueDesc.RenderTarget[0].IsBlendEnabled        = false;
            opaqueDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateOpaque = new D3D11.BlendState(Device, opaqueDesc);

            D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription();
            alphaDesc.RenderTarget[0].IsBlendEnabled        = true;
            alphaDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            alphaDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.InverseSourceAlpha;
            alphaDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.One;
            alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero;
            alphaDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Add;
            alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendStateTransparent = new D3D11.BlendState(Device, alphaDesc);
            #endregion
            #region rasterizer states
            rasterizerStateSolidCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Back,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.None,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateSolidCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Solid,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            rasterizerStateWireframeCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription()
            {
                FillMode = D3D11.FillMode.Wireframe,
                CullMode = D3D11.CullMode.Front,
                IsAntialiasedLineEnabled = true,
                IsDepthClipEnabled       = false,
                IsMultisampleEnabled     = true
            });
            #endregion

            #region depth stencil states
            depthStencilStateDefault = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            depthStencilStateNoDepth = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription()
            {
                IsDepthEnabled   = false,
                IsStencilEnabled = false,
                DepthComparison  = D3D11.Comparison.Less,
                DepthWriteMask   = D3D11.DepthWriteMask.All
            });

            Context.OutputMerger.SetDepthStencilState(depthStencilStateDefault);
            #endregion

            #region blank textures
            D3D11.Texture2D wtex   = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { Vector4.One }, wtex);
            WhiteTextureView = new D3D11.ShaderResourceView(Device, wtex);

            D3D11.Texture2D btex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                Width             = 1,
                Height            = 1,
                Format            = DXGI.Format.R32G32B32A32_Float,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                MipLevels         = 0,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                BindFlags         = D3D11.BindFlags.ShaderResource,
                OptionFlags       = D3D11.ResourceOptionFlags.None
            });
            Context.UpdateSubresource(new Vector4[] { new Vector4(0, 0, 0, 1) }, btex);
            BlackTextureView = new D3D11.ShaderResourceView(Device, btex);

            AnisotropicSampler = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                AddressU = D3D11.TextureAddressMode.Wrap,
                AddressV = D3D11.TextureAddressMode.Wrap,
                AddressW = D3D11.TextureAddressMode.Wrap,
                Filter   = D3D11.Filter.Anisotropic,
            });
            #endregion
            #region screen vertex & constants
            constants      = new CameraConstants();
            constantBuffer = D3D11.Buffer.Create(Device, D3D11.BindFlags.ConstantBuffer, ref constants);
            #endregion
            //swapChain.GetParent<DXGI.Factory>().MakeWindowAssociation(renderForm.Handle, DXGI.WindowAssociationFlags.);

            Cameras      = new List <Camera>();
            MainCamera   = Camera.CreatePerspective(MathUtil.DegreesToRadians(70), 16 / 9f);
            ActiveCamera = MainCamera;
            Cameras.Add(MainCamera);

            ShadowCamera       = Camera.CreateOrthographic(500, 1);
            ShadowCamera.zNear = 0;
            ShadowCamera.zFar  = 1000;
            ShadowCamera.CreateResources(Device, 1, 0, 1024, 1024);
            //Cameras.Add(ShadowCamera);
            // TODO: Shadow camera has no depth

            Resize(ResolutionX, ResolutionY);
        }
Пример #15
0
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            SharpDX.Direct3D.FeatureLevel[] levels = graphicsProfiles.ToFeatureLevel();
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Create Device D3D11 with feature Level based on profile
            nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, levels);
            nativeDeviceContext = nativeDevice.ImmediateContext;
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }

            InitializeStages();

            // Create the input layout manager
            if (InputLayoutManager == null)
                InputLayoutManager = new InputLayoutManager(this).DisposeBy(this);
        }
        /// <summary>
        /// Function to perform an enumeration of the video adapters attached to the system and populate this list.
        /// </summary>
        /// <param name="enumerateWARPDevice"><b>true</b> to enumerate the WARP software device, or <b>false</b> to exclude it.</param>
        /// <param name="log">The log that will capture debug logging messages.</param>
        /// <remarks>
        /// <para>
        /// Use this method to populate a list with information about the video adapters installed in the system.
        /// </para>
        /// <para>
        /// You may include the WARP device, which is a software based device that emulates most of the functionality of a video adapter, by setting the <paramref name="enumerateWARPDevice"/> to <b>true</b>.
        /// </para>
        /// <para>
        /// Gorgon requires a video adapter that is capable of supporting Direct 3D 12.0 at minimum. If no suitable devices are found installed in the computer, then the resulting list will be empty.
        /// </para>
        /// </remarks>
        public static IReadOnlyList <IGorgonVideoAdapterInfo> Enumerate(bool enumerateWARPDevice, IGorgonLog log)
        {
            var devices = new List <IGorgonVideoAdapterInfo>();

            if (log == null)
            {
                log = GorgonLog.NullLog;
            }

            using (var factory2 = new Factory2(GorgonGraphics.IsDebugEnabled))
                using (Factory5 factory5 = factory2.QueryInterface <Factory5>())
                {
                    int adapterCount = factory5.GetAdapterCount1();

                    log.Print("Enumerating video adapters...", LoggingLevel.Simple);

                    // Begin gathering device information.
                    for (int i = 0; i < adapterCount; i++)
                    {
                        // Get the video adapter information.
                        using (Adapter1 adapter1 = factory5.GetAdapter1(i))
                            using (Adapter4 adapter = adapter1.QueryInterface <Adapter4>())
                            {
                                // ReSharper disable BitwiseOperatorOnEnumWithoutFlags
                                if (((adapter.Desc3.Flags & AdapterFlags3.Remote) == AdapterFlags3.Remote) ||
                                    ((adapter.Desc3.Flags & AdapterFlags3.Software) == AdapterFlags3.Software))
                                {
                                    continue;
                                }
                                // ReSharper restore BitwiseOperatorOnEnumWithoutFlags

                                D3D11.DeviceCreationFlags flags = D3D11.DeviceCreationFlags.None;

                                if (GorgonGraphics.IsDebugEnabled)
                                {
                                    flags = D3D11.DeviceCreationFlags.Debug;
                                }

                                // We create a D3D device here to filter out unsupported video modes from the format list.
                                using (var D3DDevice = new D3D11.Device(adapter, flags, D3D.FeatureLevel.Level_12_1, D3D.FeatureLevel.Level_12_0))
                                    using (D3D11.Device5 D3DDevice5 = D3DDevice.QueryInterface <D3D11.Device5>())
                                    {
                                        D3DDevice5.DebugName = "Output enumerator device.";

                                        FeatureSet?featureSet = GetFeatureLevel(D3DDevice5);

                                        // Do not enumerate this device if its feature set is not supported.
                                        if (featureSet == null)
                                        {
                                            log.Print("This video adapter is not supported by Gorgon and will be skipped.", LoggingLevel.Verbose);
                                            continue;
                                        }

                                        Dictionary <string, VideoOutputInfo> outputs = GetOutputs(D3DDevice5, adapter, adapter.GetOutputCount(), log);

                                        if (outputs.Count <= 0)
                                        {
                                            log.Print($"WARNING: Video adapter {adapter.Description1.Description.Replace("\0", string.Empty)} has no outputs. Full screen mode will not be possible.",
                                                      LoggingLevel.Verbose);
                                        }

                                        var videoAdapter = new VideoAdapterInfo(i, adapter, featureSet.Value, outputs, VideoDeviceType.Hardware);

                                        devices.Add(videoAdapter);
                                        PrintLog(videoAdapter, log);
                                    }
                            }
                    }

                    // Get software devices.
                    if (!enumerateWARPDevice)
                    {
                        return(devices);
                    }

                    VideoAdapterInfo device = GetWARPSoftwareDevice(devices.Count, factory5, log);

                    if (device != null)
                    {
                        devices.Add(device);
                    }
                }

            log.Print("Found {0} video adapters.", LoggingLevel.Simple, devices.Count);

            return(devices);
        }
Пример #17
0
        /// <summary>
        /// Initializes the directX devices.
        /// </summary>
        /// <param name="adapterNumber"></param>
        /// <param name="deviceCreationFlags"></param>
        public void Initialize(int adapterNumber = 0, DeviceCreationFlags deviceCreationFlags = DeviceCreationFlags.None)
        {
            InitDXGIFactory();
            InitDirect2DFactory();

            InitDevice(adapterNumber, deviceCreationFlags);
            InitRenderTargetManager();
            InitShaderCompiler();
        }