コード例 #1
0
        public Direct3D11Base(Form form,
            SwapChainDescription swapDesc,
            Adapter adapter = null,
            DriverType type = DriverType.Hardware,
            DeviceCreationFlags flags = DeviceCreationFlags.None,
            FeatureLevel[] levels = null)
        {
            IsDisposed = false;

            try
            {
                _isInitializing = true;

                _form = form;

                _isComposited = DwmApi.IsCompositionEnabled;
                if (_isComposited)
                {
                    DwmApi.EnableMMCSS(true);
                    DwmPresentParameters present = new DwmPresentParameters()
                    {
                        IsQueued = true,
                        BufferCount = 2,
                        RefreshesPerFrame = 1,
                    };
                    DwmApi.SetPresentParameters(form.Handle, ref present);
                }

                if (swapDesc.OutputHandle != IntPtr.Zero) { throw new ArgumentException("Output handle must not be set."); }
                if (swapDesc.Usage != Usage.RenderTargetOutput) { throw new ArgumentException("Usage must be RenderTargetOutput."); }

                swapDesc.OutputHandle = _form.Handle;
                bool setFullscreen = !swapDesc.IsWindowed;
                swapDesc.IsWindowed = true;

                Device.CreateWithSwapChain(adapter, type, DeviceCreationFlags.None, levels, swapDesc, out _device, out _swapChain);
                _swapChain.ResizeTarget(swapDesc.ModeDescription);
                _factory = _swapChain.GetParent<Factory>();
                _factory.SetWindowAssociation(_form.Handle, WindowAssociationFlags.IgnoreAll);

                _form.SizeChanged += SizeChanged_Handler;
                _form.ResizeBegin += ResizeBegin_Handler;
                _form.Resize += Resize_Handler;
                _form.ResizeEnd += ResizeEnd_Handler;
                _form.KeyDown += KeyDown_Handler;

                if (setFullscreen)
                {
                    ChangeMode(true);
                }

                _isInitializing = false;
            }
            catch
            {
                Dispose();
                throw;
            }
        }
コード例 #2
0
ファイル: ShaderDesc.cs プロジェクト: fxbit/FxGraphicsEngine
 public ShaderDesc()
 {
     _EntryPoint = new List<string>();
     _EntryPoint.Add("main");
     _BuildLevel = FeatureLevel.Level_11_0;
     _Flags = ShaderFlags.OptimizationLevel3 | ShaderFlags.Debug;
     _IncludePath = null;
 }
コード例 #3
0
        public void WillReturnCorrectFeatureLevelFromProfile(int major, int minor, int profileMajor, int profileMinor, FeatureLevel expected)
        {
            var profile = new ShaderProfile(ShaderVersion.VertexShader, major, minor, profileMajor, profileMinor);

            var featureLevel = profile.GetFeatureLevel();

            Assert.AreEqual(expected, featureLevel);
        }
コード例 #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderTargetProperties"/> struct.
 /// </summary>
 /// <param name="type">A value that specifies whether the render target should force hardware or software rendering. A value of <see cref="SharpDX.Direct2D1.RenderTargetType.Default"/> specifies that the render target should use hardware rendering if it is available; otherwise, it uses software rendering. Note that WIC bitmap render targets do not support hardware rendering.</param>
 /// <param name="pixelFormat">The pixel format and alpha mode of the render target. You can use the {{D2D1::PixelFormat}} function to create a pixel format that specifies that Direct2D should select the pixel format and alpha mode for you. For a list of pixel formats and alpha modes supported by each render target, see {{Supported Pixel Formats and Alpha Modes}}.</param>
 /// <param name="dpiX">The horizontal DPI of the render target.  To use the default DPI, set dpiX and dpiY to 0. For more information, see the Remarks section. 	</param>
 /// <param name="dpiY">The vertical DPI of the render target. To use the default DPI, set dpiX and dpiY to 0.  For more information, see the Remarks section. 	</param>
 /// <param name="usage">A value that specifies how the render target is remoted and whether it should be GDI-compatible.  Set to <see cref="SharpDX.Direct2D1.RenderTargetUsage.None"/> to create a render target that is not compatible with GDI and uses Direct3D command-stream remoting if it  is available.</param>
 /// <param name="minLevel">A value that specifies the minimum Direct3D feature level required for hardware rendering. If the specified minimum level is not available, the render target uses software rendering if the type  member is set to <see cref="SharpDX.Direct2D1.RenderTargetType.Default"/>; if  type  is set to to D2D1_RENDER_TARGET_TYPE_HARDWARE, render target creation fails. A value of <see cref="SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT"/> indicates that Direct2D should determine whether the Direct3D feature level of the device is adequate. This field is used only when creating <see cref="WindowRenderTarget"/> and <see cref="DeviceContextRenderTarget"/> objects.	</param>  
 public RenderTargetProperties(RenderTargetType type, PixelFormat pixelFormat, float dpiX, float dpiY, RenderTargetUsage usage, FeatureLevel minLevel)
 {
     Type = type;
     PixelFormat = pixelFormat;
     DpiX = dpiX;
     DpiY = dpiY;
     Usage = usage;
     MinLevel = minLevel;
 }
コード例 #5
0
ファイル: Device.cs プロジェクト: Wumpf/ClearSight
        public Device(ref Descriptor desc, FeatureLevel featureLevel = FeatureLevel.Level_12_0)
            : base(ref desc)
        {
            if (desc.DebugDevice)
            {
                var debugInterface = SharpDX.Direct3D12.DebugInterface.Get();
                if (debugInterface != null)
                {
                    debugInterface.EnableDebugLayer();
                }
                else
                {
                    Log.Error("Failed to obtain DX12 debug layer.");
                }
            }

            // Use first adapter that is supported.
            using (SharpDX.DXGI.Factory dxgiFactory = new Factory4())
            {
                for (int adapterIndex = 0;; ++adapterIndex)
                {
                    var adapter = dxgiFactory.GetAdapter(adapterIndex);
                    if (adapter == null)
                    {
                        // TODO: Throw exception
                        return;
                    }

                    try
                    {
                        DeviceD3D12 = new SharpDX.Direct3D12.Device(adapter, (SharpDX.Direct3D.FeatureLevel) featureLevel);
                        Adapter = adapter;
                        break;
                    }

                    catch (Exception)
                    {
                        DeviceD3D12 = null;
                        adapter.Dispose();
                    }
                }
            }

            // Get Resource handle increment sizes.
            descriptorHandleIncrementSize[(int)DescriptorHeap.Descriptor.ResourceDescriptorType.Sampler] = DeviceD3D12.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler);
            descriptorHandleIncrementSize[(int)DescriptorHeap.Descriptor.ResourceDescriptorType.DepthStencil] = DeviceD3D12.GetDescriptorHandleIncrementSize(DescriptorHeapType.DepthStencilView);
            descriptorHandleIncrementSize[(int)DescriptorHeap.Descriptor.ResourceDescriptorType.RenderTarget] = DeviceD3D12.GetDescriptorHandleIncrementSize(DescriptorHeapType.RenderTargetView);
            descriptorHandleIncrementSize[(int)DescriptorHeap.Descriptor.ResourceDescriptorType.ShaderResource] = DeviceD3D12.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView);

            Memory.Enums.InitLookupTables();

            Log.Info("Successfully created a DX12 device with adapter \"{0}\"", Adapter.Description.Description);
        }
コード例 #6
0
 /// <summary>
 /// Initializes a new instance of the SongDisplayController class.
 /// </summary>
 /// <param name="control">The web view that is controlled by this instance. Its IsProcessCreated property must be true.</param>
 /// <param name="features">The desired feature level.</param>
 public SongDisplayController(IWebView control, FeatureLevel features = FeatureLevel.None)
 {
     this.control = control;
     this.features = features;
     this.control.ConsoleMessage += (obj, target) =>
     {
         System.Windows.MessageBox.Show("SongDisplayController encountered JS error in " + target.Source + " (line " +  target.LineNumber + "): " + target.Message);
     };
     // FIXME: sometimes throws exception saying that "bridge" object already exists
     bridge = this.control.CreateGlobalJavascriptObject("bridge");
     bridge.BindAsync("callbackLoaded", (sender, args) => OnSongLoaded());
     bridge["featureLevel"] = new JSValue(JsonConvert.SerializeObject(features));
 }
コード例 #7
0
        /// <summary>
        /// Returns a GraphicsProfile from a FeatureLevel.
        /// </summary>
        /// <returns>associated GraphicsProfile</returns>
        public static FeatureLevel[] ToFeatureLevel(this GraphicsProfile[] profiles)
        {
            if (profiles == null)
            {
                return null;
            }

            var levels = new FeatureLevel[profiles.Length];
            for (int i = 0; i < levels.Length; i++)
            {
                levels[i] = (FeatureLevel) profiles[i];
            }
            return levels;
        }
コード例 #8
0
        private string GetFeatureLevelText(FeatureLevel featureLevel)
        {
            string featureLevelText;

            switch (featureLevel)
            {
            case FeatureLevel.Level_9_1:
                featureLevelText = "9.1";
                break;

            case FeatureLevel.Level_9_2:
                featureLevelText = "9.2";
                break;

            case FeatureLevel.Level_9_3:
                featureLevelText = "9.3";
                break;

            case FeatureLevel.Level_10_0:
                featureLevelText = "10.0";
                break;

            case FeatureLevel.Level_10_1:
                featureLevelText = "10.1";
                break;

            case FeatureLevel.Level_11_0:
                featureLevelText = "11.0";
                break;

            default:
                if ((int)featureLevel > (int)FeatureLevel.Level_11_0)
                {
                    featureLevelText = "11.0+";
                }
                else
                {
                    featureLevelText = "unknown";
                }

                break;
            }

            return(featureLevelText);
        }
コード例 #9
0
        private static Device CreateDeviceWithSwapChain(DriverType driverType, FeatureLevel level,
                                                        SwapChainDescription swapChainDescription,
                                                        out SwapChain swapChain, out CommandQueue queue)
        {
#if DEBUG
            // Enable the D3D12 debug layer.
            // DebugInterface.Get().EnableDebugLayer();
#endif
            using (var factory = new Factory4())
            {
                var adapter = driverType == DriverType.Hardware ? null : factory.GetWarpAdapter();
                var device  = new Device(adapter, level);
                queue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));

                swapChain = new SwapChain(factory, queue, swapChainDescription);
                return(device);
            }
        }
コード例 #10
0
 private GraphicsDeviceInformation CreateGraphicsDeviceInformation(GameGraphicsParameters prefferedParameters,
                                                                   GraphicsAdapter graphicsAdapter,
                                                                   FeatureLevel featureLevel)
 {
     return(new GraphicsDeviceInformation
     {
         Adapter = graphicsAdapter,
         GraphicsProfile = featureLevel,
         PresentationParameters =
         {
             MultiSampleCount     = MSAALevel.None,
             IsFullScreen         = prefferedParameters.IsFullScreen,
             PresentationInterval = prefferedParameters.SynchronizeWithVerticalRetrace ? PresentInterval.One : PresentInterval.Immediate,
             DeviceWindowHandle   = MainWindow.NativeWindow,
             RenderTargetUsage    = Usage.BackBuffer | Usage.RenderTargetOutput
         }
     });
 }
コード例 #11
0
ファイル: D3D12.cs プロジェクト: yinyue200/Vortice.Windows
        /// <summary>
        /// Gets the highest supported hardware feature level of the primary adapter.
        /// </summary>
        /// <param name="adapter">The <see cref="IDXGIAdapter"/>.</param>
        /// <param name="minFeatureLevel">Thje</param>
        /// <returns>The highest supported hardware feature level.</returns>
        public static FeatureLevel GetMaxSupportedFeatureLevel(IDXGIAdapter adapter, FeatureLevel minFeatureLevel = FeatureLevel.Level_11_0)
        {
            ID3D12Device device = null;

            try
            {
                D3D12CreateDevice(adapter, minFeatureLevel, out device);
                return(device.CheckMaxSupportedFeatureLevel(FeatureLevels));
            }
            catch
            {
                return(FeatureLevel.Level_9_1);
            }
            finally
            {
                device?.Dispose();
            }
        }
コード例 #12
0
    /// <summary>
    /// Check if a feature level is supported by a particular adapter.
    /// </summary>
    /// <param name="adapterPtr">The native handle of <see cref="IDXGIAdapter"/>.</param>
    /// <param name="featureLevel">The feature level.</param>
    /// <param name="flags">The <see cref="DeviceCreationFlags"/> flags.</param>
    /// <returns><c>true</c> if the specified adapter is supporting this feature level; otherwise, <c>false</c>.</returns>
    public static unsafe bool IsSupportedFeatureLevel(
        IntPtr adapterPtr,
        FeatureLevel featureLevel,
        DeviceCreationFlags flags = DeviceCreationFlags.None)
    {
        if (adapterPtr == IntPtr.Zero)
        {
            throw new ArgumentNullException(nameof(adapterPtr), "Invalid adapter handle");
        }

        Result result = RawD3D11CreateDeviceNoDeviceAndContext(
            adapterPtr,
            DriverType.Unknown,
            flags,
            new[] { featureLevel },
            out FeatureLevel outputLevel);

        return(result.Success && outputLevel == featureLevel);
    }
コード例 #13
0
        public DeviceContext11(IntPtr handle, DeviceSettings settings)
        {
            Contract.Requires(handle != IntPtr.Zero);
            Contract.Requires(settings != null);

            Settings = settings;
            LogEvent.Engine.Log(settings.ToString());

            eventHandlerList = new EventHandlerList();
            SwapChainDescription swapChainDesc = new SwapChainDescription
                                                     {
                                                         BufferCount = 1,
                                                         IsWindowed = Settings.IsWindowed,
                                                         ModeDescription =
                                                             new ModeDescription{
                                                                 Width = Settings.ScreenWidth,
                                                                 Height = Settings.ScreenHeight,
                                                                 RefreshRate= new Rational(0, 1),
                                                                 Format = Settings.Format,
                                                                 Scaling = DisplayModeScaling.Unspecified,
                                                                 ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified,
                                                             },

                                                         //new Rational(120, 1), Settings.Format),
                                                         OutputHandle = handle,
                                                         SampleDescription = Settings.SampleDescription,
                                                         Flags = SwapChainFlags.AllowModeSwitch,
                                                         SwapEffect = SwapEffect.Discard,
                                                         Usage = Usage.RenderTargetOutput,
                                                     };

            FeatureLevel[] featureLevels = new FeatureLevel[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 };
            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating);
            Device.CreateWithSwapChain(DriverType.Hardware, Settings.CreationFlags, featureLevels, swapChainDesc, out device, out swapChain);

            factory = swapChain.GetParent<Factory>();
            factory.SetWindowAssociation(handle, WindowAssociationFlags.IgnoreAltEnter | WindowAssociationFlags.IgnoreAll);

            immediate = device.ImmediateContext;

            CreateTargets();
            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreated);
        }
コード例 #14
0
        /// <summary>
        /// Check if a feature level is supported by a particular adapter.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <param name="featureLevel">The feature level.</param>
        /// <param name="flags">The <see cref="DeviceCreationFlags"/> flags.</param>
        /// <returns><c>true</c> if the specified adapter is supporting this feature level; otherwise, <c>false</c>.</returns>
        public static unsafe bool IsSupportedFeatureLevel(
            IDXGIAdapter adapter,
            FeatureLevel featureLevel,
            DeviceCreationFlags flags = DeviceCreationFlags.None)
        {
            if (adapter == null)
            {
                throw new ArgumentNullException(nameof(adapter), "Invalid adapter");
            }

            var result = RawD3D11CreateDeviceNoDeviceAndContext(
                adapter,
                DriverType.Unknown,
                flags,
                new[] { featureLevel },
                out var outputLevel);

            return(result.Success && outputLevel == featureLevel);
        }
コード例 #15
0
    public static Result D3D11CreateDevice(IntPtr adapterPtr, DriverType driverType, DeviceCreationFlags flags, FeatureLevel[] featureLevels,
                                           out ID3D11Device device, out FeatureLevel featureLevel, out ID3D11DeviceContext immediateContext)
    {
        Result result = D3D11CreateDevice(adapterPtr, driverType, IntPtr.Zero,
                                          (int)flags,
                                          featureLevels,
                                          (featureLevels != null) ? featureLevels.Length : 0,
                                          SdkVersion,
                                          out device,
                                          out featureLevel,
                                          out immediateContext);

        if (result.Failure)
        {
            return(result);
        }

        return(result);
    }
コード例 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="adapter"></param>
        /// <param name="leftOut"></param>
        /// <param name="rightOut"></param>
        void GetDualHeadAdapter(FeatureLevel fl, out Adapter adapter, out Output leftOut, out Output rightOut)
        {
            using (var factory2 = new Factory()) {
                adapter = factory2.Adapters.FirstOrDefault(a => a.Outputs.Length >= 2 && D3D.Device.IsSupportedFeatureLevel(a, fl));

                if (adapter == null)
                {
                    throw new GraphicsException("No DualHead adapters with Direct3D11 support found.");
                }

                leftOut  = adapter.Outputs[0];
                rightOut = adapter.Outputs[1];

                if (leftOut.Description.DesktopBounds.Left > rightOut.Description.DesktopBounds.Left)
                {
                    Misc.Swap(ref leftOut, ref rightOut);
                }
            }
        }
コード例 #17
0
        public GraphicsDevice(GraphicsAdapter adapter)
        {
            //set the adapter
            Adapter = adapter;


            //creation flag, we use debug flag
            DeviceCreationFlags creationFlags = DeviceCreationFlags.Debug;

            //fetuares level: 11_0, 12_0
            FeatureLevel[] fetuares = new FeatureLevel[2]
            {
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_12_0
            };

            //create device with current adapter
            NativeDevice = new Device(Adapter.Adapter, creationFlags, fetuares);

            NativeDeviceContext = NativeDevice.ImmediateContext;
        }
コード例 #18
0
 private DeviceInformation CreateDeviceInformation(ApplicationGraphicsParameters preferredParameters,
                                                   GraphicsAdapter graphicsAdapter,
                                                   FeatureLevel featureLevel)
 {
     return(new DeviceInformation
     {
         Adapter = graphicsAdapter,
         GraphicsProfile = featureLevel,
         PresentationParameters =
         {
             MultiSampleCount               = (MSAALevel)preferredParameters.PreferredMultiSampleCount,
             IsFullScreen                   = preferredParameters.IsFullScreen,
             PreferredFullScreenOutputIndex = preferredParameters.PreferredFullScreenOutputIndex,
             DepthBufferShaderResource      = preferredParameters.DepthBufferShaderResource,
             PresentationInterval           =
                 preferredParameters.SynchronizeWithVerticalRetrace ? PresentInterval.One : PresentInterval.Immediate,
             DeviceWindowHandle             = MainWindow.NativeWindow,
             RenderTargetUsage              = Usage.BackBuffer | Usage.RenderTargetOutput
         }
     });
 }
コード例 #19
0
        /// <summary>
        /// Creates device resources.
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }
            catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
コード例 #20
0
        public unsafe GraphicsDevice(FeatureLevel minFeatureLevel = FeatureLevel.Level11_0, bool enableDebugLayer = false)
        {
            if (enableDebugLayer)
            {
                Result debugResult = D3D12.D3D12GetDebugInterface(out ID3D12Debug debugInterface);

                if (debugResult.Success)
                {
                    ID3D12Debug1 debug = debugInterface.QueryInterface <ID3D12Debug1>();

                    debug.EnableDebugLayer();
                }
            }

            FeatureLevel = minFeatureLevel < FeatureLevel.Level11_0 ? FeatureLevel.Level11_0 : minFeatureLevel;

            Result result = D3D12.D3D12CreateDevice(null, (Vortice.Direct3D.FeatureLevel)FeatureLevel, out ID3D12Device device);

            if (result.Failure)
            {
                throw new COMException("Device creation failed.", result.Code);
            }

            NativeDevice = device;

            DirectCommandQueue  = new CommandQueue(this, CommandListType.Direct);
            ComputeCommandQueue = new CommandQueue(this, CommandListType.Compute);
            CopyCommandQueue    = new CommandQueue(this, CommandListType.Copy);

            DepthStencilViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView, 1);
            RenderTargetViewAllocator   = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView, 2);
            ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, 4096);
            SamplerAllocator            = new DescriptorAllocator(this, DescriptorHeapType.Sampler, 256);

            ShaderVisibleShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, 4096, DescriptorHeapFlags.ShaderVisible);
            ShaderVisibleSamplerAllocator            = new DescriptorAllocator(this, DescriptorHeapType.Sampler, 256, DescriptorHeapFlags.ShaderVisible);

            CommandList = new CommandList(this, CommandListType.Direct);
            CommandList.Close();
        }
コード例 #21
0
ファイル: D3D11.cs プロジェクト: Ethereal77/Vortice.Windows
        private static Result RawD3D11CreateDeviceNoContext(
            IDXGIAdapter adapter,
            DriverType driverType,
            DeviceCreationFlags flags,
            FeatureLevel[] featureLevels,
            out ID3D11Device device,
            out FeatureLevel featureLevel)
        {
            unsafe
            {
                device = default;
                var adapterPtr = CppObject.ToCallbackPtr <IDXGIAdapter>(adapter);
                fixed(void *featureLevelsPtr = &featureLevels[0])
                fixed(void *featureLevelPtr = &featureLevel)
                {
                    var    devicePtr = IntPtr.Zero;
                    Result result    = D3D11CreateDevice_(
                        (void *)adapterPtr,
                        (int)driverType,
                        null,
                        (int)flags,
                        featureLevels != null && featureLevels.Length > 0 ? featureLevelsPtr : null,
                        featureLevels?.Length ?? 0,
                        SdkVersion,
                        &devicePtr,
                        featureLevelPtr,
                        null);

                    if (result.Success && devicePtr != IntPtr.Zero)
                    {
                        device = new ID3D11Device(devicePtr);
                    }

                    GC.KeepAlive(adapter);
                    return(result);
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// Check if a feature level is supported by a particular adapter.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        /// <param name="featureLevel">The feature level.</param>
        /// <returns><c>true</c> if the specified adapter is supporting this feature level; otherwise, <c>false</c>.</returns>
        public static bool IsSupportedFeatureLevel(IDXGIAdapter adapter, FeatureLevel featureLevel)
        {
            ID3D11Device        device  = null;
            ID3D11DeviceContext context = null;

            try
            {
                var result = D3D11CreateDevice(
                    adapter,
                    DriverType.Unknown,
                    IntPtr.Zero,
                    0,
                    new[] { featureLevel }, 1,
                    SdkVersion,
                    out device, out var outputLevel, out context);
                return(result.Success && outputLevel == featureLevel);
            }
            finally
            {
                context?.Dispose();
                device?.Dispose();
            }
        }
コード例 #23
0
        /// <summary>
        /// Find the display mode that most closely matches the requested display mode.
        /// </summary>
        /// <param name="targetProfiles">The target profile, as available formats are different depending on the feature level..</param>
        /// <param name="mode">The mode.</param>
        /// <returns>Returns the closes display mode.</returns>
        /// <unmanaged>HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice)</unmanaged>
        /// <remarks>Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order.  ScanlineOrdering Scaling Format Resolution RefreshRate  When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and  other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering,  Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because  the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output.  If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified  display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output.   Unspecified fields are lower priority than specified fields and will be resolved later than specified fields.</remarks>
        public DisplayMode FindClosestMatchingDisplayMode(FeatureLevel[] targetProfiles,  DisplayMode mode)
        {
            ModeDescription closestDescription;
            SharpDX.Direct3D11.Device deviceTemp = null;
            try
            {
                deviceTemp = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None, targetProfiles);
            }
            catch(Exception ex) {}

            var descriprtion = new ModeDescription()
                                   {
                                       Width = mode.Width,
                                       Height = mode.Height,
                                       RefreshRate = mode.RefreshRate,
                                       Format = mode.Format,
                                       Scaling = DisplayModeScaling.Unspecified,
                                       ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                                   };
            using (var device = deviceTemp)
                output.GetClosestMatchingMode(device, descriprtion, out closestDescription);

            return DisplayMode.FromDescription(closestDescription);
        }
コード例 #24
0
    public static Result D3D11On12CreateDevice(
        IUnknown d3d12Device,
        DeviceCreationFlags flags,
        FeatureLevel[] featureLevels,
        IUnknown[] commandQueues,
        int nodeMask,
        out ID3D11Device device,
        out ID3D11DeviceContext immediateContext,
        out FeatureLevel chosenFeatureLevel)
    {
        Result result = D3D11On12CreateDevice(d3d12Device,
                                              flags,
                                              featureLevels, featureLevels.Length,
                                              commandQueues, commandQueues.Length,
                                              nodeMask,
                                              out device, out immediateContext, out chosenFeatureLevel);

        if (result.Failure)
        {
            return(result);
        }

        return(result);
    }
コード例 #25
0
 public virtual bool isFeatureLevelSupported(FeatureLevel level)
 {
     if (GetGeometryShaderSource("gs_4_0") == null)
     {
         return true;
     }
     else
     {
         return level >= FeatureLevel.Level_10_0;
     }
 }
コード例 #26
0
 public ID3DDeviceContextState CreateDeviceContextState <T>(CreateDeviceContextStateFlags flags, FeatureLevel[] featureLevels, out FeatureLevel chosenFeatureLevel) where T : ComObject
 {
     return(CreateDeviceContextState(
                flags, featureLevels, featureLevels.Length,
                D3D11.SdkVersion,
                typeof(T).GUID, out chosenFeatureLevel));
 }
コード例 #27
0
ファイル: DXManager.cs プロジェクト: qingliu2018/CodeWalker
        public bool Init(DXForm form, bool autostart = true)
        {
            dxform        = form;
            autoStartLoop = autostart;

            try
            {
                SwapChainDescription scd = new SwapChainDescription()
                {
                    BufferCount     = 2,
                    Flags           = SwapChainFlags.None,
                    IsWindowed      = true,
                    ModeDescription = new ModeDescription(
                        form.Form.ClientSize.Width,
                        form.Form.ClientSize.Height,
                        new Rational(0, 0),
                        Format.R8G8B8A8_UNorm),
                    OutputHandle      = form.Form.Handle,
                    SampleDescription = new SampleDescription(multisamplecount, multisamplequality),
                    SwapEffect        = SwapEffect.Discard,
                    Usage             = Usage.RenderTargetOutput
                };

                FeatureLevel[] levels = new FeatureLevel[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 };

                DeviceCreationFlags flags = DeviceCreationFlags.None;
                //#if DEBUG
                //    flags = DeviceCreationFlags.Debug;
                //#endif
                Device    dev = null;
                SwapChain sc  = null;
                Exception exc = null;

                bool success = false;
                try
                {
                    Device.CreateWithSwapChain(DriverType.Hardware, flags, levels, scd, out dev, out sc);
                    success = true;
                }
                catch (Exception ex) { exc = ex; }

                if (!success)
                {
                    multisamplecount      = 1;
                    multisamplequality    = 0;
                    scd.SampleDescription = new SampleDescription(1, 0); //try no AA
                    try
                    {
                        Device.CreateWithSwapChain(DriverType.Hardware, flags, levels, scd, out dev, out sc);
                        success = true;
                    }
                    catch (Exception ex) { exc = ex; }
                }

                if (!success)
                {
                    var msg = "CodeWalker was unable to initialise the graphics device. Please ensure your system meets the minimum requirements and that your graphics drivers and DirectX are up to date.";
                    if (exc != null)
                    {
                        msg += "\n\nException info: " + exc.ToString();
                    }
                    throw new Exception(msg);
                }

                device    = dev;
                swapchain = sc;


                var factory = swapchain.GetParent <Factory>(); //ignore windows events...
                factory.MakeWindowAssociation(form.Form.Handle, WindowAssociationFlags.IgnoreAll);



                context = device.ImmediateContext;



                CreateRenderBuffers();



                dxform.Form.Load              += Dxform_Load;
                dxform.Form.FormClosing       += Dxform_FormClosing;
                dxform.Form.ClientSizeChanged += Dxform_ClientSizeChanged;
                dxform.Form.ResizeBegin       += DxForm_ResizeBegin;
                dxform.Form.ResizeEnd         += DxForm_ResizeEnd;

                if (autostart)
                {
                    dxform.InitScene(device);
                }

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to initialise DirectX11.\n" + ex.Message, "CodeWalker - Error!");
                return(false);
            }
        }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderTargetProperties"/> struct.
 /// </summary>
 /// <param name="type">A value that specifies whether the render target should force hardware or software rendering. A value of <see cref="SharpDX.Direct2D1.RenderTargetType.Default"/> specifies that the render target should use hardware rendering if it is available; otherwise, it uses software rendering. Note that WIC bitmap render targets do not support hardware rendering.</param>
 /// <param name="pixelFormat">The pixel format and alpha mode of the render target. You can use the {{D2D1::PixelFormat}} function to create a pixel format that specifies that Direct2D should select the pixel format and alpha mode for you. For a list of pixel formats and alpha modes supported by each render target, see {{Supported Pixel Formats and Alpha Modes}}.</param>
 /// <param name="dpiX">The horizontal DPI of the render target.  To use the default DPI, set dpiX and dpiY to 0. For more information, see the Remarks section.     </param>
 /// <param name="dpiY">The vertical DPI of the render target. To use the default DPI, set dpiX and dpiY to 0.  For more information, see the Remarks section.   </param>
 /// <param name="usage">A value that specifies how the render target is remoted and whether it should be GDI-compatible.  Set to <see cref="SharpDX.Direct2D1.RenderTargetUsage.None"/> to create a render target that is not compatible with GDI and uses Direct3D command-stream remoting if it  is available.</param>
 /// <param name="minLevel">A value that specifies the minimum Direct3D feature level required for hardware rendering. If the specified minimum level is not available, the render target uses software rendering if the type  member is set to <see cref="SharpDX.Direct2D1.RenderTargetType.Default"/>; if  type  is set to to D2D1_RENDER_TARGET_TYPE_HARDWARE, render target creation fails. A value of <see cref="SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT"/> indicates that Direct2D should determine whether the Direct3D feature level of the device is adequate. This field is used only when creating <see cref="WindowRenderTarget"/> and <see cref="DeviceContextRenderTarget"/> objects.	</param>
 public RenderTargetProperties(RenderTargetType type, PixelFormat pixelFormat, float dpiX, float dpiY, RenderTargetUsage usage, FeatureLevel minLevel)
 {
     Type        = type;
     PixelFormat = pixelFormat;
     DpiX        = dpiX;
     DpiY        = dpiY;
     Usage       = usage;
     MinLevel    = minLevel;
 }
コード例 #29
0
ファイル: GamePlatform.cs プロジェクト: BrianLunt/SharpDX
 private GraphicsDeviceInformation CreateGraphicsDeviceInformation(GameGraphicsParameters prefferedParameters,
                                                                   GraphicsAdapter graphicsAdapter,
                                                                   FeatureLevel featureLevel)
 {
     return new GraphicsDeviceInformation
            {
                Adapter = graphicsAdapter,
                GraphicsProfile = featureLevel,
                PresentationParameters =
                {
                    MultiSampleCount = MSAALevel.None,
                    IsFullScreen = prefferedParameters.IsFullScreen,
                    PreferredFullScreenOutputIndex = prefferedParameters.PreferredFullScreenOutputIndex,
                    DepthBufferShaderResource = prefferedParameters.DepthBufferShaderResource,
                    PresentationInterval = prefferedParameters.SynchronizeWithVerticalRetrace ? PresentInterval.One : PresentInterval.Immediate,
                    DeviceWindowHandle = MainWindow.NativeWindow,
                    RenderTargetUsage = Usage.BackBuffer | Usage.RenderTargetOutput
                }
            };
 }
コード例 #30
0
        /// <summary>
        /// Configures the Direct3D device, and stores handles to it and the device context.
        /// </summary>
        private void CreateDeviceResources()
        {
            DisposeDeviceAndContext();

            // This flag adds support for surfaces with a different color channel ordering
            // than the API default. It is required for compatibility with Direct2D.
            DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport;

#if DEBUG
            if (DirectXHelper.SdkLayersAvailable())
            {
                // If the project is in a debug build, enable debugging via SDK Layers with this flag.
                creationFlags |= DeviceCreationFlags.Debug;
            }
#endif

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Note that HoloLens supports feature level 11.1. The HoloLens emulator is also capable
            // of running on graphics cards starting with feature level 10.0.
            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
            };

            // Create the Direct3D 11 API device object and a corresponding context.
            try
            {
                if (null != dxgiAdapter)
                {
                    using (var device = new Device(dxgiAdapter, creationFlags, featureLevels))
                    {
                        // Store pointers to the Direct3D 11.1 API device.
                        d3dDevice = this.ToDispose(device.QueryInterface <Device3>());
                    }
                }
                else
                {
                    using (var device = new Device(DriverType.Hardware, creationFlags, featureLevels))
                    {
                        // Store a pointer to the Direct3D device.
                        d3dDevice = this.ToDispose(device.QueryInterface <Device3>());
                    }
                }
            }
            catch
            {
                // If the initialization fails, fall back to the WARP device.
                // For more information on WARP, see:
                // http://go.microsoft.com/fwlink/?LinkId=286690
                using (var device = new Device(DriverType.Warp, creationFlags, featureLevels))
                {
                    d3dDevice = this.ToDispose(device.QueryInterface <Device3>());
                }
            }

            // Cache the feature level of the device that was created.
            d3dFeatureLevel = d3dDevice.FeatureLevel;

            // Store a pointer to the Direct3D immediate context.
            d3dContext = this.ToDispose(d3dDevice.ImmediateContext3);

            // Acquire the DXGI interface for the Direct3D device.
            using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device3>())
            {
                // Wrap the native device using a WinRT interop object.
                IntPtr pUnknown;
                UInt32 hr = InteropStatics.CreateDirect3D11DeviceFromDXGIDevice(dxgiDevice.NativePointer, out pUnknown);
                if (hr == 0)
                {
                    d3dInteropDevice = (IDirect3DDevice)Marshal.GetObjectForIUnknown(pUnknown);
                    Marshal.Release(pUnknown);
                }

                // Store a pointer to the DXGI adapter.
                // This is for the case of no preferred DXGI adapter, or fallback to WARP.
                dxgiAdapter = this.ToDispose(dxgiDevice.Adapter.QueryInterface <SharpDX.DXGI.Adapter3>());
            }

            // Check for device support for the optional feature that allows setting the render target array index from the vertex shader stage.
            var options = d3dDevice.CheckD3D113Features3();
            if (options.VPAndRTArrayIndexFromAnyShaderFeedingRasterizer)
            {
                d3dDeviceSupportsVprt = true;
            }
        }
コード例 #31
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Device1" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
 /// </summary>
 /// <param name = "driverType">The type of device to create.</param>
 /// <param name = "flags">A list of runtime layers to enable.</param>
 /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
 /// <param name="featureLevel">Desired feature level</param>
 /// <param name = "device">When the method completes, contains the created device instance.</param>
 /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
 /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
 public static void CreateWithSwapChain(DriverType driverType, DeviceCreationFlags flags,
                                          SwapChainDescription swapChainDescription, FeatureLevel featureLevel, out Device1 device,
                                          out SwapChain swapChain)
 {
     CreateWithSwapChain(null, driverType, flags, swapChainDescription, featureLevel, out device, out swapChain);
 }
コード例 #32
0
ファイル: Device.cs プロジェクト: TomAtWork/SharpDX
 /// <summary>
 /// Initializes a new instance of the <see cref="Device"/> class.
 /// </summary>
 /// <param name="adapter">The adapter.</param>
 /// <param name="minFeatureLevel">The minimum feature level.</param>
 public Device(Adapter adapter, FeatureLevel minFeatureLevel) : base(IntPtr.Zero)
 {
     CreateDevice(adapter, minFeatureLevel, this);
 }
コード例 #33
0
ファイル: DX11.cs プロジェクト: bgarate/SynergyEngine
        public void Init(IntPtr windowHandle)
        {
            // Factory de interfaces de DirectX
            Factory factory = new Factory();

            // Factory para crear el adaptador a la tarjeta grafica (la primera)
            Adapter adapter = factory.GetAdapter(0);

            // Obtengo la salida a monitor primario del adaptador
            Output monitor = adapter.Outputs[0];

            //Obtengo mis posibilidades de salida que soporto que utilicen el formato R8G8B8A8_UNorm
            ModeDescription[] displayModes = monitor.GetDisplayModeList(swapChainFormat, DisplayModeEnumerationFlags.Interlaced);

            //Si utilizo VSync, busco la taza de refresco para la resolución deseada que soporta el monitor
            Rational refreshRate = new Rational(0, 1);

            //if (VSyncEnabled)
                foreach (ModeDescription mode in displayModes)
                    if (mode.Width == SettingsManager.Current.ScreenSize.Width &&
                        mode.Height == SettingsManager.Current.ScreenSize.Height)
                    {
                        refreshRate = mode.RefreshRate;
                        break;
                    }


            // Obtengo los datos sobre la tarjeta de memoria
            AdapterDescription adapterDescription = adapter.Description;
            VideoCardDescription = adapterDescription.Description;
            VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // En MB

            DebugManager.LogNotice(VideoCardDescription + " con " + VideoCardMemory + " MB dedicados");

            // Creo el device y el devicecontext
            SharpDX.Direct3D11.Device temp_device;

            SharpDX.Direct3D.FeatureLevel[] features = new FeatureLevel[] { // Array de Feature Level soportados
            FeatureLevel.Level_11_0,
            FeatureLevel.Level_10_1,
            FeatureLevel.Level_10_0,
            FeatureLevel.Level_9_3 };

            DeviceCreationFlags creationFlags; // Creo al device en modo debug si estoy en modo debug
            if (DebugManager.DebugMode)
                creationFlags = DeviceCreationFlags.Debug;
            else
                creationFlags = DeviceCreationFlags.None;


            SampleDescription sampleDescription; // Info de MSAA
            sampleDescription = new SampleDescription(1, 0);


            // Creo swapchain
            SwapChain temp_swapchain;

            // Descripcion de SwapChain
            SwapChainDescription swapChainDesc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription = new ModeDescription(SettingsManager.Current.ScreenSize.Width,
                    SettingsManager.Current.ScreenSize.Height,
                    refreshRate, swapChainFormat),
                Usage = Usage.RenderTargetOutput,
                OutputHandle = windowHandle,
                // Multisampling
                SampleDescription = sampleDescription,
                IsWindowed = SettingsManager.Current.IsWindowed,
                // Sin flags avanzados
                Flags = SwapChainFlags.None,
                // Descarto el backbuffer despues de presentarlo
                SwapEffect = SwapEffect.Discard
            };

            SharpDX.Direct3D11.Device.CreateWithSwapChain(adapter, creationFlags, features, swapChainDesc, out temp_device, out temp_swapchain);

            DebugManager.LogNotice("DirectX11 Device creado");

            DXDevice = temp_device;
            DXDeviceContext = DXDevice.ImmediateContext;
            swapChain = temp_swapchain;
            DebugManager.LogNotice("Feature Level utilizado: " + DXDevice.FeatureLevel.ToString());
          

            // Libero la salida, el adaptador y el factory
            monitor.Dispose();
            adapter.Dispose();
            factory.Dispose();

            // Puntero al backbuffer
            Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            // A partir del puntero creo el render target
            renderTargetView = new RenderTargetView(DXDevice, backBuffer);
            // Libero el backBuffer
            backBuffer.Dispose();

            // Descripcion del depth/stencil buffer
            Texture2DDescription depthBufferDesc = new Texture2DDescription()
            {
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D24_UNorm_S8_UInt,
                SampleDescription = sampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            // Creo el depth/stencil buffer a partir de la descripcion
            depthStencilBuffer = new Texture2D(DXDevice, depthBufferDesc);
            // Y creo el depth/stencil view
            depthStencilView = new DepthStencilView(DXDevice, depthStencilBuffer);

            DXDeviceContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            ViewportF viewport = new ViewportF()
            {
                X = 0,
                Y = 0,
                Width = SettingsManager.Current.ScreenSize.Width,
                Height = SettingsManager.Current.ScreenSize.Height,
                MinDepth = 0,
                MaxDepth = 1
            };

            DXDeviceContext.Rasterizer.SetViewport(viewport.X, viewport.Y, viewport.Width, viewport.Height, viewport.MinDepth, viewport.MaxDepth);
            DebugManager.LogNotice("DX11 inicilizado!");

        }
コード例 #34
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="adapter"></param>
		/// <param name="leftOut"></param>
		/// <param name="rightOut"></param>
		void GetDualHeadAdapter ( FeatureLevel fl, out Adapter adapter, out Output leftOut, out Output rightOut )
		{
			using ( var factory2 = new Factory() ) {

				adapter	=	factory2.Adapters.FirstOrDefault( a => a.Outputs.Length>=2 && D3D.Device.IsSupportedFeatureLevel( a, fl ) );

				if (adapter==null) {
					throw new GraphicsException("No DualHead adapters with Direct3D11 support found.");
				}

				leftOut		=	adapter.Outputs[0];
				rightOut	=	adapter.Outputs[1];

				if (leftOut.Description.DesktopBounds.Left > rightOut.Description.DesktopBounds.Left ) {
					Misc.Swap( ref leftOut, ref rightOut );
				}
			}
		}
コード例 #35
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 /// <summary>
 ///   This overload has been deprecated. Use one of the alternatives that does not take both an adapter and a driver type.
 /// </summary>
 internal static void CreateWithSwapChain(Adapter adapter, DriverType driverType, DeviceCreationFlags flags, SwapChainDescription swapChainDescription, FeatureLevel featureLevel, out Device1 device, out SwapChain swapChain)
 {
     D3D10.CreateDeviceAndSwapChain1(adapter, driverType, IntPtr.Zero, flags, featureLevel, D3D10.SdkVersion1,
                                                    ref swapChainDescription, out swapChain, out device);
 }
コード例 #36
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 private void CreateDevice(Adapter adapter, DriverType driverType, DeviceCreationFlags flags, FeatureLevel featureLevel)
 {
     D3D10.CreateDevice1(adapter, driverType, IntPtr.Zero, flags, featureLevel, D3D10.SdkVersion1, this);
 }
コード例 #37
0
 /// <summary>
 /// Returns a GraphicsProfile from a FeatureLevel.
 /// </summary>
 /// <param name="level">The level.</param>
 /// <returns>associated GraphicsProfile</returns>
 public static GraphicsProfile FromFeatureLevel(FeatureLevel level)
 {
     return (GraphicsProfile) level;
 }
コード例 #38
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 /// <summary>
 ///   Constructor for a D3D10.1 Device. See <see cref = "SharpDX.Direct3D10.D3D10.CreateDevice1" /> for more information.
 /// </summary>
 /// <param name = "adapter"></param>
 /// <param name = "flags"></param>
 /// <param name="featureLevel"></param>
 public Device1(Adapter adapter, DeviceCreationFlags flags, FeatureLevel featureLevel) : base(IntPtr.Zero)
 {
     CreateDevice(adapter, DriverType.Hardware, flags, featureLevel);
 }
コード例 #39
0
        public void CreateDirectXSwapChain(Adapter adapter)
        {
            var desc = adapter.Description;

            Debug.WriteLine(desc.Description);
            Debug.WriteLine($"vender = {desc.VendorId:X4}");
            Debug.WriteLine($"Shared Memory: {desc.SharedSystemMemory} bytes");
            Debug.WriteLine($"Video Memory: {desc.DedicatedVideoMemory} bytes");
            Debug.WriteLine($"device: {desc.DeviceId}");

            FeatureLevel[] featureLevels = new FeatureLevel[] {
                FeatureLevel.Level_11_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_10_1,
            };

            D3D11Device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.BgraSupport, featureLevels);

            SwapChainDescription1 swapChainDescription = new SwapChainDescription1()
            {
                // Double buffer.
                BufferCount = 2,
                // BGRA 32bit pixel format.
                Format = Format.B8G8R8A8_UNorm,
                // Unlike in CoreWindow swap chains, the dimensions must be set.
                Height = (int)(ActualHeight),
                Width  = (int)(ActualWidth),
                // Default multisampling.
                SampleDescription = new SampleDescription(1, 0),
                // In case the control is resized, stretch the swap chain accordingly.
                Scaling = Scaling.Stretch,
                // No support for stereo display.
                Stereo = false,
                // Sequential displaying for double buffering.
                SwapEffect = SwapEffect.FlipSequential,
                // This swapchain is going to be used as the back buffer.
                Usage = Usage.BackBuffer | Usage.RenderTargetOutput,
            };

            // 建立SwapChain
            using (SharpDX.DXGI.Device3 dxgiDevice3 = D3D11Device.QueryInterface <SharpDX.DXGI.Device3>()) {
                using (Factory2 dxgiFactory2 = dxgiDevice3.Adapter.GetParent <Factory2>()) {
                    using (SwapChain1 swapChain1 = new SwapChain1(dxgiFactory2, D3D11Device, ref swapChainDescription)) {
                        swapChain = swapChain1.QueryInterface <SwapChain>();
                    }
                }
            }

            // 把Xaml的SwapChainPanel與DirectX的SwapChain連結起來
            using (ISwapChainPanelNative swapChainPanelNative = ComObject.As <ISwapChainPanelNative>(this)) {
                swapChainPanelNative.SwapChain = swapChain;
            }

            backBuffer = SharpDX.Direct3D11.Resource.FromSwapChain <Texture2D>(swapChain, 0);

            var renderTarget = new RenderTargetView(D3D11Device, backBuffer);

            context = D3D11Device.ImmediateContext;
            // Clear Screen to Teel Blue.
            context.ClearRenderTargetView(renderTarget, new Color(0xFF887536));
            swapChain.Present(1, PresentFlags.None);
        }
コード例 #40
0
 private static extern int Orbital_Video_Vulkan_Instance_Init(IntPtr handle, FeatureLevel minimumFeatureLevel);
コード例 #41
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 /// <summary>
 ///   Initializes a new instance of the <see cref = "T:SharpDX.Direct3D10.Device1" /> class along with a new <see cref = "T:SharpDX.DXGI.SwapChain" /> used for rendering.
 /// </summary>
 /// <param name = "adapter">The video adapter on which the device should be created.</param>
 /// <param name = "flags">A list of runtime layers to enable.</param>
 /// <param name = "swapChainDescription">Details used to create the swap chain.</param>
 /// <param name="featureLevel">Desired feature level</param>
 /// <param name = "device">When the method completes, contains the created device instance.</param>
 /// <param name = "swapChain">When the method completes, contains the created swap chain instance.</param>
 /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns>
 public static void CreateWithSwapChain(Adapter adapter, DeviceCreationFlags flags,
                                          SwapChainDescription swapChainDescription, FeatureLevel featureLevel,out Device1 device,
                                          out SwapChain swapChain)
 {
     CreateWithSwapChain(adapter, DriverType.Hardware, flags, swapChainDescription, featureLevel, out device, out swapChain);
 }
コード例 #42
0
ファイル: Device1.cs プロジェクト: numo16/SharpDX
 /// <summary>
 ///   Constructor for a D3D10.1 Device. See <see cref = "SharpDX.Direct3D10.D3D10.CreateDevice1" /> for more information.
 /// </summary>
 /// <param name = "driverType"></param>
 /// <param name = "flags"></param>
 /// <param name="featureLevel"></param>
 public Device1(DriverType driverType, DeviceCreationFlags flags, FeatureLevel featureLevel)
     : base(IntPtr.Zero)
 {
     CreateDevice(null, driverType, flags, featureLevel);
 }
コード例 #43
0
ファイル: DeviceManager.cs プロジェクト: BEEden/Diplomarbeit
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            RemoveAndDispose(ref d3dDevice);
            RemoveAndDispose(ref d3dContext);
            RemoveAndDispose(ref d2dDevice);
            RemoveAndDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;

            // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default
            try
            {
                // Try to create it with Video Support
                // If it is not working, we just use BGRA
                // Force to FeatureLevel.Level_9_1
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            } catch (Exception)
            {
                creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
                using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                    d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            }
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
コード例 #44
0
        static void Main()
        {
            #region Предварительная настройка
            RuntimeTypeModel.Default.Add(typeof(Vector3), false).Add("X", "Y", "Z");
            RuntimeTypeModel.Default.Add(typeof(Matrix), false).Add("M11", "M12", "M13", "M14",
                                                                    "M21", "M22", "M23", "M24",
                                                                    "M31", "M32", "M33", "M34",
                                                                    "M41", "M42", "M43", "M44");
            RuntimeTypeModel.Default.Add(typeof(Quaternion), false).Add("X", "Y", "Z", "W");
            RuntimeTypeModel.Default.Add(typeof(DVector3), false).Add("X", "Y", "Z");
            RuntimeTypeModel.Default.Add(typeof(DMatrix), false).Add("M11", "M12", "M13", "M14",
                                                                     "M21", "M22", "M23", "M24",
                                                                     "M31", "M32", "M33", "M34",
                                                                     "M41", "M42", "M43", "M44");
            RuntimeTypeModel.Default.Add(typeof(DQuaternion), false).Add("X", "Y", "Z", "W");
            Process thisProc = Process.GetCurrentProcess();
            thisProc.PriorityClass = ProcessPriorityClass.High;
            #endregion

            using (StartForm Input_form = new StartForm())
            {
                Application.Run(Input_form);
            }

            featureLevel = Device.GetSupportedFeatureLevel();
            //featureLevel = FeatureLevel.Level_10_0;

            if (Global.Settings.Run && featureLevel >= FeatureLevel.Level_10_0)
            {
                HiTimer = new HiResTimer();
                IntPreTime = HiTimer.Value;

                form = new RenderForm()
                {
                    ClientSize = new System.Drawing.Size(Global.Settings.Width, Global.Settings.Height),
                    Text = "Model Viewer"
                };
                //form.FormBorderStyle = FormBorderStyle.None;
                form.StartPosition = FormStartPosition.CenterScreen;

                InputManager.Init();

                var description = new SwapChainDescription()
                {
                    BufferCount = 2,
                    Usage = Usage.RenderTargetOutput,
                    OutputHandle = form.Handle,
                    IsWindowed = true,
                    ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                    SampleDescription = new SampleDescription(1, 0), //8, 32
                    //Flags = SwapChainFlags.AllowModeSwitch,
                    SwapEffect = SwapEffect.Discard
                };

                FeatureLevel[] f_level = new FeatureLevel[] { (featureLevel > FeatureLevel.Level_10_0) ? FeatureLevel.Level_10_1 : FeatureLevel.Level_10_0 };
                Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, f_level, description, out device, out swapChain);
                // setting a viewport is required if you want to actually see anything
                context = device.ImmediateContext;
                viewport = new Viewport(0, 0, Global.Settings.Width, Global.Settings.Height);
                context.Rasterizer.SetViewports(viewport);

                // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms

                var factory_ = swapChain.GetParent<Factory>();
                    factory_.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

                // handle alt+enter ourselves
                form.KeyDown += FormOnKeyDown;
                // handle form size changes
                form.UserResized += Resize;

                ////Scene inizialize
                MyScene.Inizialize(device, viewport, description, context, swapChain);

                SharpDX.DXGI.Surface surface = Surface.FromSwapChain(swapChain, 0);

                DrawHelper.Init(device);
                DebugDraw.Init(device);
                QuadScreen.Init(device, (int)viewport.Width, (int)viewport.Height);

                MyScene.LoadContent(device);

                swapChain.IsFullScreen = Global.Settings.FullScr;

               // RenderLoop.UseCustomDoEvents = false;
                RenderLoop.Run(form, () =>
                {
                    //RenderLoop.UseCustomDoEvents = false;
                    //Application.DoEvents();
                    TimeUpdate = HiTimer.Tick2Mili(HiTimer.Value - IntPreTime);
                    IntPreTime = HiTimer.Value;

                    InputManager.Update(TimeUpdate);

                    MyScene.Update(TimeUpdate);

                    MyScene.Draw(TimeUpdate, device, context);

                    swapChain.Present(Global.Settings.VSync, PresentFlags.None);

                    TimeGC += TimeUpdate;
                    if (TimeGC > 300)
                    {
                        TimeGC = 0;
                        System.GC.Collect(1);
                    }

                });

                if (swapChain.IsFullScreen) swapChain.IsFullScreen = false;
                //MyScene.Dispose();

                DrawHelper.FreeResource();
                ContentManager.FreeResources();
                InputManager.FreeResource();
                DebugDraw.FreeResource();
                QuadScreen.FreeResource();
                factory_.Dispose();
                swapChain.Dispose();
                device.Dispose();
                context.Dispose();
            }
        }
コード例 #45
0
ファイル: Device.cs プロジェクト: TomAtWork/SharpDX
 private static void CreateDevice(Adapter adapter, FeatureLevel minFeatureLevel, Device instance)
 {
     D3D12.CreateDevice(adapter, minFeatureLevel, Utilities.GetGuidFromType(typeof(Device)), instance).CheckError();
 }
コード例 #46
0
ファイル: Device.cs プロジェクト: maxIsaev/SharpDX
 private static void CreateDevice(Adapter adapter, FeatureLevel minFeatureLevel, Device instance)
 {
     D3D12.CreateDevice(adapter, minFeatureLevel, Utilities.GetGuidFromType(typeof(Device)), instance).CheckError();
 }
コード例 #47
0
ファイル: Game_Device.cs プロジェクト: woncomp/LiliumLab
        void CreateDevice(System.Drawing.Size size, IntPtr hwnd)
        {
            RenderViewSize = size;
            ControlHandle = hwnd;

            //create device and swapchain
            DriverType driverType = DriverType.Hardware;
            DeviceCreationFlags flags = DeviceCreationFlags.None;
            if (Config.DebugMode) flags |= DeviceCreationFlags.Debug;

            FeatureLevel[] levels = new FeatureLevel[] { FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 };

            SwapChainDescription desc = new SwapChainDescription();
            desc.BufferCount = 1;
            desc.Flags = SharpDX.DXGI.SwapChainFlags.None;
            desc.IsWindowed = true;
            desc.ModeDescription = new ModeDescription(RenderViewSize.Width, RenderViewSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            desc.OutputHandle = ControlHandle;
            desc.SampleDescription = new SampleDescription(Config.MSAASampleCount, Config.MSAAQuality);
            desc.SwapEffect = SwapEffect.Discard;
            desc.Usage = Usage.RenderTargetOutput;

            SharpDX.Direct3D11.Device createdDevice;
            SharpDX.DXGI.SwapChain createdSwapChain;
            SharpDX.Direct3D11.Device.CreateWithSwapChain(driverType, flags, levels, desc, out createdDevice, out createdSwapChain);

            // Store references
            this.SwapChain = createdSwapChain;
            this.Device = createdDevice;
            this.DeviceContext = createdDevice.ImmediateContext;

            this.SwapChain.DebugName = "Lilium";
            this.Device.DebugName = "Lilium";
            this.DeviceContext.DebugName = "Lilium";

            // Ignore all windows events
            var factory = SwapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(ControlHandle, WindowAssociationFlags.IgnoreAll);

            ResizeBuffers();

            renderTimer = new Timer();
            renderTimer.Tick += renderTimer_TickUpdate;
            renderTimer.Interval = 1;
            renderTimer.Start();
        }
コード例 #48
0
        /// <summary>
        /// Create the swapchain
        /// </summary>
        /// <param name="windowsHandler">The windows handle.</param>
        protected override void CreateSwapChain(IntPtr windowsHandler)
        {
            // Define the properties of the swap chain.
            this.desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                IsWindowed        = !this.FullScreen,
                OutputHandle      = windowsHandler,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput | Usage.ShaderInput,
                SwapEffect        = SwapEffect.Sequential,
                Flags             = SwapChainFlags.AllowModeSwitch,
                ModeDescription   = new ModeDescription()
                {
                    Width       = this.Width,
                    Height      = this.Height,
                    Format      = Format.R8G8B8A8_UNorm,
                    RefreshRate = new Rational(0, 1)
                }
            };

            FeatureLevel[] supportedLevels = new FeatureLevel[]
            {
                FeatureLevel.Level_11_0,
            };

            DeviceCreationFlags creationFlags;

#if DEBUG
            creationFlags = DeviceCreationFlags.Debug;
#else
            creationFlags = DeviceCreationFlags.None;
#endif

            if (this.HasVideoSupport)
            {
                try
                {
                    // Startup MediaManager
                    MediaManager.Startup();

                    // Create a DXGI Device Manager
                    this.dxgiDeviceManager = new SharpDX.MediaFoundation.DXGIDeviceManager();
                    this.dxgiDeviceManager.ResetDevice(this.device);

                    creationFlags |= DeviceCreationFlags.BgraSupport | DeviceCreationFlags.VideoSupport;
                }
                catch (Exception)
                {
                    this.dxgiDeviceManager = null;

                    // Shutdown MediaManager
                    MediaManager.Shutdown();
                }
            }

            // Create Device and SwapChain
            // SharpDX.DXGI.Factory f = new SharpDX.DXGI.Factory1();
            // SharpDX.DXGI.Adapter a = f.GetAdapter(0);
            SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, supportedLevels, this.desc, out this.device, out this.swapChain);

            // Setup multithread on the Direct3D11 device
            var multithread = this.device.QueryInterface <SharpDX.Direct3D.DeviceMultithread>();
            multithread.SetMultithreadProtected(true);
        }
コード例 #49
0
ファイル: DeviceManager.cs プロジェクト: Maskl/MetroRetro
        /// <summary>
        /// Creates device resources. 
        /// </summary>
        /// <remarks>
        /// This method is called at the initialization of this instance.
        /// </remarks>
        protected virtual void CreateDeviceResources()
        {
            // Dispose previous references and set to null
            SafeDispose(ref d3dDevice);
            SafeDispose(ref d3dContext);
            SafeDispose(ref d2dDevice);
            SafeDispose(ref d2dContext);

            // Allocate new references
            // Enable compatibility with Direct2D
            // Retrieve the Direct3D 11.1 device amd device context
            var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport;
            #if DEBUG
            creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug;
            #endif
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags))
                d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();
            featureLevel = d3dDevice.FeatureLevel;

            // Get Direct3D 11.1 context
            d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());

            // Create Direct2D device
            using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>())
                d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice));

            // Create Direct2D context
            d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None));
        }
コード例 #50
0
        /// <summary>
        /// Creates a swapchain and the device for a forms window.
        /// </summary>
        /// <param name="window_handle"></param>
        /// <param name="feature_level"></param>
        private void CreateDeviceWithSwapChain(IntPtr window_handle, FeatureLevel feature_level)
        {
            SwapChainDescription swap_chain_desc = new SwapChainDescription()
            {
                BufferCount = 1,
                IsWindowed = true,
                ModeDescription = new ModeDescription(_current_width, _current_height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle = _window_handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };

            Device1.CreateWithSwapChain(null, DriverType.Hardware, DeviceCreationFlags.Debug, feature_level,
                                        swap_chain_desc, out _device, out _swapchain);

            Factory factory = _swapchain.GetParent<Factory>();
            //factory.SetWindowAssociation(_window_handle, WindowAssociationFlags.IgnoreAll);
        }
コード例 #51
0
ファイル: Device.cs プロジェクト: maxIsaev/SharpDX
 /// <summary>
 /// Initializes a new instance of the <see cref="Device"/> class.
 /// </summary>
 /// <param name="adapter">The adapter.</param>
 /// <param name="minFeatureLevel">The minimum feature level.</param>
 public Device(Adapter adapter, FeatureLevel minFeatureLevel) : base(IntPtr.Zero)
 {
     CreateDevice(adapter, minFeatureLevel, this);
 }
コード例 #52
0
ファイル: GraphicsAdapter.cs プロジェクト: Nezz/SharpDX
        /// <summary>
        /// Tests to see if the adapter supports the requested profile.
        /// </summary>
        /// <param name="featureLevel">The graphics profile.</param>
        /// <returns>true if the profile is supported</returns>
        public bool IsProfileSupported(FeatureLevel featureLevel)
        {
            // Only way is to instantiate a Direct3D11 device and check the selected
            // feature level
            bool isProfileSupported = false;

            Direct3D11.Device device = null;
            try
            {
                device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None, featureLevel);
                isProfileSupported = featureLevel == device.FeatureLevel;
            }
            catch (SharpDXException) { }
            finally
            {
                if (device != null)
                    device.Dispose();
            }
            return isProfileSupported;
        }
コード例 #53
0
        /// <summary>
        /// Creates Direct3D11 Device, RenderTargetView, DepthStencilView, Viewport
        /// </summary>
        /// <param name="deviceDescription">The device description.</param>
        /// <exception cref="System.Exception"></exception>
        /// <exception cref="System.ComponentModel.InvalidEnumArgumentException">deviceDescription.MultiSampleCount</exception>
        private void Initialize(DeviceDescription deviceDescription)
        {
            FeatureLevel[] levels = new FeatureLevel[] {
                FeatureLevel.Level_10_0,
                FeatureLevel.Level_10_1,
                FeatureLevel.Level_11_0,
                FeatureLevel.Level_11_1,
            };

            d3dDevice = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, levels);

            DXGI.ModeDescription backBufferDesc = new DXGI.ModeDescription()
            {
                Width            = width,
                Height           = height,
                Format           = BackBufferFormat,
                RefreshRate      = new DXGI.Rational(60, 1),
                Scaling          = DXGI.DisplayModeScaling.Unspecified,
                ScanlineOrdering = DXGI.DisplayModeScanlineOrder.Progressive,
            };

            DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription()
            {
                BufferCount     = 1,
                Flags           = DXGI.SwapChainFlags.None,
                IsWindowed      = !deviceDescription.Fullcreen,
                ModeDescription = backBufferDesc,
                OutputHandle    = renderControl.Handle,
                SwapEffect      = deviceDescription.SwapEffect,
                Usage           = DXGI.Usage.RenderTargetOutput,
            };

            switch (deviceDescription.MultiSampleCount)
            {
            case MultiSampleType.MSAA1:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(1, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA2:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(2, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA4:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(4, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA8:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(8, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.MSAA16:
                swapChainDesc.SampleDescription = new DXGI.SampleDescription(16, deviceDescription.MultiSampleQuality);
                break;

            case MultiSampleType.Unknown:
                var samples = SharpDXDevice.CheckMultiSample();
                if (samples == null)
                {
                    throw new Exception(MethodBase.GetCurrentMethod().Name +
                                        " Because the MultiSampleCount parameter is [Unknown], the device could not determine the parameter automatically");
                }
                swapChainDesc.SampleDescription = samples.Last();
                break;

            default:
                throw new System.ComponentModel.InvalidEnumArgumentException("deviceDescription.MultiSampleCount",
                                                                             (int)deviceDescription.MultiSampleCount, typeof(MultiSampleType));
            }

            DXGI.Device  device  = d3dDevice.QueryInterface <DXGI.Device>();
            DXGI.Adapter adapter = device.GetParent <DXGI.Adapter>();
            DXGI.Factory factory = adapter.GetParent <DXGI.Factory>();

            swapChain = new DXGI.SwapChain(factory, d3dDevice, swapChainDesc);

            d3dContext = d3dDevice.ImmediateContext;

            D3D11.RasterizerStateDescription rasterDesc = new D3D11.RasterizerStateDescription()
            {
                CullMode = D3D11.CullMode.Back,
                FillMode = D3D11.FillMode.Solid,
                IsAntialiasedLineEnabled = true,
                IsMultisampleEnabled     = true,
                IsDepthClipEnabled       = true,
            };

            viewport = new Viewport(0, 0, width, height);

            this.SetRasterizerState(rasterDesc);
            d3dRenderTarget = CreateRenderTarget();
            d3dDepthStencil = CreateDepthStencil();
        }
コード例 #54
0
ファイル: DML.cs プロジェクト: manju-summoner/Vortice.Windows
    public static T DMLCreateDevice <T>(ID3D12Device d3d12Device, CreateDeviceFlags createDeviceFlags, FeatureLevel minimumFeatureLevel)
        where T : IDMLDevice
    {
        DMLCreateDevice1(
            d3d12Device,
            createDeviceFlags,
            minimumFeatureLevel,
            typeof(T).GUID,
            out IntPtr nativePtr).CheckError();

        return(MarshallingHelpers.FromPointer <T>(nativePtr) ?? throw new NullReferenceException());
    }
コード例 #55
0
 private static extern int Orbital_Video_D3D12_Instance_Init(IntPtr handle, FeatureLevel minimumFeatureLevel, int extraDebugging);
コード例 #56
0
ファイル: DML.cs プロジェクト: manju-summoner/Vortice.Windows
    public static Result DMLCreateDevice <T>(ID3D12Device d3d12Device, CreateDeviceFlags createDeviceFlags, FeatureLevel minimumFeatureLevel, out T?device)
        where T : IDMLDevice
    {
        Result result = DMLCreateDevice1(
            d3d12Device,
            createDeviceFlags,
            minimumFeatureLevel,
            typeof(T).GUID,
            out IntPtr nativePtr);

        if (result.Failure)
        {
            device = default;
            return(result);
        }

        device = MarshallingHelpers.FromPointer <T>(nativePtr);
        return(result);
    }
コード例 #57
0
ファイル: D3D12Pipeline.cs プロジェクト: liquidboy/X
        private static Device CreateDeviceWithSwapChain(DriverType driverType, FeatureLevel level,
           SwapChainDescription swapChainDescription,
           out SwapChain swapChain, out CommandQueue queue)
        {
#if DEBUG
            // Enable the D3D12 debug layer.
            // DebugInterface.Get().EnableDebugLayer();
#endif
            using (var factory = new Factory4())
            {
                var adapter = driverType == DriverType.Hardware ? null : factory.GetWarpAdapter();
                var device = new Device(adapter, level);
                queue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct));

                swapChain = new SwapChain(factory, queue, swapChainDescription);
                return device;
            }
        }
コード例 #58
0
 /// <summary>
 /// Gets the <see cref="GraphicsDevice"/> for a given <see cref="Adapter"/>
 /// </summary>
 /// <param name="requiredFeatureLevel">The required <see cref="FeatureLevel"/> for device creation</param>
 /// <param name="adapter">The <see cref="Adapter"/> to create the device from, or <see langword="null"/> to use the default adapter</param>
 /// <param name="config">The <see cref="DebugLayerConfiguration"/> for the device, or <see langword="null"/> to use the default</param>
 /// <returns>A <see cref="GraphicsDevice"/></returns>
 public static new GraphicsDevice Create(FeatureLevel requiredFeatureLevel, in Adapter?adapter, DebugLayerConfiguration?config = null)
コード例 #59
0
ファイル: GraphicsAdapter.cs プロジェクト: pH200/SharpDX
 /// <summary>
 /// Tests to see if the adapter supports the requested profile.
 /// </summary>
 /// <param name="featureLevel">The graphics profile.</param>
 /// <returns>true if the profile is supported</returns>
 public bool IsProfileSupported(FeatureLevel featureLevel)
 {
     return Direct3D11.Device.IsSupportedFeatureLevel(this, featureLevel);
 }
コード例 #60
0
        public bool Initialize(out string errorMsg)
        {
            try
            {
                errorMsg = null;

                List <ModeDescription> adapterModes = new List <ModeDescription>();
                _dx11factory = new Factory1();

                using (Adapter1 adapter = _dx11factory.GetAdapter1(0))
                {
                    using (Output output = adapter.Outputs[0])
                    {
                        IsB8G8R8A8_UNormSupport = false;
                        foreach (var mode in output.GetDisplayModeList(Format.B8G8R8A8_UNorm, DisplayModeEnumerationFlags.Interlaced))
                        {
                            IsB8G8R8A8_UNormSupport = true;
                            adapterModes.Add(mode);
                        }

                        MainAdapter = adapter.Description.Description;
                        logger.Info("GPU found : {0}", MainAdapter);
                        //GetResource Level
                        FeatureLevel maxSupportLevel = Device.GetSupportedFeatureLevel(adapter);
                        logger.Info("Maximum supported DirectX11 level = {0}", maxSupportLevel.ToString());

                        if (maxSupportLevel == FeatureLevel.Level_9_1 ||
                            maxSupportLevel == FeatureLevel.Level_9_2 ||
                            maxSupportLevel == FeatureLevel.Level_9_3)
                        {
                            errorMsg = "Your graphical card doesn't support at minimum DirectX 10 feature, current feature : " + maxSupportLevel.ToString();
                            return(false);
                        }

                        int DedicatedGPU = adapter.Description.DedicatedVideoMemory / (1024 * 1024);
                        if (DedicatedGPU < 0)
                        {
                            DedicatedGPU = 0;
                        }
                        int DedicatedSystem = adapter.Description.DedicatedSystemMemory / (1024 * 1024);
                        if (DedicatedSystem < 0)
                        {
                            DedicatedSystem = 0;
                        }
                        int SharedSystem = adapter.Description.SharedSystemMemory / (1024 * 1024);
                        if (SharedSystem < 0)
                        {
                            SharedSystem = 0;
                        }

                        logger.Info("GPU Memory : Dedicated from GPU : {0}MB, Shared : {1}MB, Dedicated from System : {2}MB. Total : {3}MB", DedicatedGPU, DedicatedSystem, SharedSystem, DedicatedGPU + DedicatedSystem + SharedSystem);
                        logger.Info("B8G8R8A8_UNormSupport compatibility = {0}", IsB8G8R8A8_UNormSupport);

#if DEBUG
                        foreach (var mode in adapterModes)
                        {
                            logger.Trace("[{1}:{2}], format : {0}, RefreshRate : {3}hz, Scaling : {4}, ScanlineMode : {5}", mode.Format, mode.Width, mode.Height, (float)mode.RefreshRate.Numerator / mode.RefreshRate.Denominator, mode.Scaling, mode.ScanlineOrdering);
                        }
#endif
                    }
                }

                RefreshResources();

                GetMSAAQualities(Format.B8G8R8A8_UNorm);

                //Remove the some built-in fonctionnality of DXGI
                _dx11factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll | WindowAssociationFlags.IgnoreAltEnter);

                _renderForm.ResizeBegin += _renderForm_ResizeBegin;
                _renderForm.ResizeEnd   += _renderForm_ResizeEnd;
                _renderForm.Resize      += _renderForm_Resize;
                _renderForm.LostFocus   += GameWindow_LostFocus;
                _renderForm.GotFocus    += GameWindow_GotFocus;

                _renderForm.Show();
                _renderForm.Focus();
                _renderForm.TopMost = true;
                HasFocus            = true;
                _renderForm.TopMost = false;

                return(true);
            }
            catch (Exception e)
            {
                errorMsg = e.Message;
                return(false);
            }
        }