public RenderContainer(SwapChainDescription swapChainDescription, RenderControl control) { try { _swapChainDescription = swapChainDescription; using (Factory1 factory = new Factory1()) using (Adapter adapter = factory.GetAdapter(0)) { Device11 = new Dx11ChainedDevice(adapter, _swapChainDescription); Device10 = new Dx10Device(adapter); } GraphicsDevice = new GenericGraphicsDevice(Device11.Device); SpriteBatch = new SpriteBatch(GraphicsDevice); Reset(control.Width, control.Height); control.Resize += OnRenderControlResize; } catch { Dispose(); throw; } }
public static bool Initialise(long adapterLuid) { // Find the adapter matching the luid from the parent process var factory = new DXGI.Factory1(); DXGI.Adapter gameAdapter = null; foreach (var adapter in factory.Adapters) { if (adapter.Description.Luid == adapterLuid) { gameAdapter = adapter; break; } } if (gameAdapter == null) { var foundLuids = string.Join(",", factory.Adapters.Select(adapter => adapter.Description.Luid)); Console.Error.WriteLine($"FATAL: Could not find adapter matching game adapter LUID {adapterLuid}. Found: {foundLuids}."); return(false); } // Use the adapter to build the device we'll use var flags = D3D11.DeviceCreationFlags.BgraSupport; #if DEBUG flags |= D3D11.DeviceCreationFlags.Debug; #endif Device = new D3D11.Device(gameAdapter, flags); return(true); }
public void TestException() { // Device is implicitly created with a DXGI Factory / Adapter var device = new Direct3D11.Device(DriverType.Hardware); // Create another DXGI Factory var factory = new SharpDX.DXGI.Factory1(); try { // This call should raise a DXGI_ERROR_INVALID_CALL: // The reason is the SwapChain must be created with a d3d device that was created with the same factory // Because we were creating the D3D11 device without a DXGI factory, it is associated with another factory. var swapChain = new SwapChain( factory, device, new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = false, ModeDescription = new ModeDescription(1024, 768, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), OutputHandle = IntPtr.Zero, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }); } catch (SharpDXException exception) { Assert.AreEqual(exception.Descriptor.NativeApiCode, "DXGI_ERROR_INVALID_CALL"); } }
public WindowedDirect2dRenderEnvironment(string formName, bool debug) { form = new RenderForm(formName); d3dDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | (debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None)); dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); dxgiFactory = new SharpDX.DXGI.Factory1(); swapChain = new SwapChain(dxgiFactory, dxgiDevice, new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(Format.B8G8R8A8_UNorm), OutputHandle = form.Handle, IsWindowed = true, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }); dxgiSurface = swapChain.GetBackBuffer <Surface>(0); d2dFactory = new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debug ? DebugLevel.Warning : DebugLevel.None); d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None); bitmap = new Bitmap1(d2dContext, dxgiSurface, null); d2dContext.Target = bitmap; }
private static void PlatformInitializeAdapters(out ReadOnlyCollection <GraphicsAdapter> adapters) { var factory = new SharpDX.DXGI.Factory1(); var adapterCount = factory.GetAdapterCount(); var adapterList = new List <GraphicsAdapter>(adapterCount); for (var i = 0; i < adapterCount; i++) { var device = factory.GetAdapter1(i); var monitorCount = device.GetOutputCount(); for (var j = 0; j < monitorCount; j++) { var monitor = device.GetOutput(j); var adapter = CreateAdapter(device, monitor); adapterList.Add(adapter); monitor.Dispose(); } } factory.Dispose(); adapters = new ReadOnlyCollection <GraphicsAdapter>(adapterList); }
public ProjectorFormLoader(String path) { Forms = new List<ProjectorForm>(); // load ensemble.xml string directory = Path.GetDirectoryName(path); var ensemble = ProjectorCameraEnsemble.FromFile(path); // create d3d device var factory = new Factory1(); var adapter = factory.Adapters[0]; // When using DeviceCreationFlags.Debug on Windows 10, ensure that "Graphics Tools" are installed via Settings/System/Apps & features/Manage optional features. // Also, when debugging in VS, "Enable native code debugging" must be selected on the project. var device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None); Object renderLock = new Object(); // create a form for each projector foreach (var projector in ensemble.projectors) { var form = new ProjectorForm(factory, device, renderLock, projector); form.FullScreen = FULLSCREEN_ENABLED; // TODO: fix this so can be called after Show form.Show(); Forms.Add(form); } }
private Adapter1 FindAdapter(long adapterId) { Adapter1 adapter1 = null; using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { if (adapterId > 0) { var adapters = dxgiFactory.Adapters1; for (int i = 0; i < adapters.Length; i++) { var _adapter = adapters[i]; if (_adapter.Description1.Luid == adapterId) { adapter1 = _adapter; continue; } _adapter.Dispose(); } } if (adapter1 == null) { adapter1 = dxgiFactory.GetAdapter1(0); } } return(adapter1); }
public override void Dispose() { if (dx11Device != null) dx11Device.Dispose(); if (dx11Factory != null) dx11Factory.Dispose(); if (dx11Output != null) dx11Output.Dispose(); if (dx11DuplicatedOutput != null) dx11DuplicatedOutput.Dispose(); if (dx11ScreenTexture != null) dx11ScreenTexture.Dispose(); if (dx11ScreenResource != null) dx11ScreenResource.Dispose(); if (dx11ScreenSurface != null) dx11ScreenSurface.Dispose(); if (screenShot != null) screenShot.Dispose(); dx11Device = null; dx11Factory = null; dx11Output = null; dx11DuplicatedOutput = null; dx11ScreenTexture = null; dx11ScreenResource = null; dx11ScreenSurface = null; screenShot = null; bmpData = null; GC.SuppressFinalize(this); }
/// <summary> /// Initializes static members of the <see cref="GraphicsAdapter" /> class. /// </summary> static GraphicsAdapter() { #if DIRECTX11_1 using (var factory = new Factory1()) Initialize(factory.QueryInterface<Factory2>()); #else Initialize(new Factory1()); #endif }
public void TestDXGI() { // Force to load DXGI assembly var factory = new Factory1(); factory.Dispose(); // Look for DXGI descriptor SharpDX.DXGI.ResultCode.DeviceRemoved var descriptor = ResultDescriptor.Find(0x887A0005); Assert.AreEqual(descriptor.NativeApiCode, "DXGI_ERROR_DEVICE_REMOVED"); }
public CompositionEngine() { _dxgiFactory = new SharpDX.DXGI.Factory1(); //_dxgiFactory.Adapters1[0].Description1. //_dxgiFactory = new SharpDX.DXGI.Factory(); //new _wicFactory = new SharpDX.WIC.ImagingFactory(); _d2DFactory = new SharpDX.Direct2D1.Factory(); _dWriteFactory = new SharpDX.DirectWrite.Factory(); }
/// <summary> /// Initializes the GraphicsAdapter. On Desktop and WinRT, this is done statically. /// </summary> public static void Initialize() { if (Adapters == null) { #if DIRECTX11_1 using (var factory = new Factory1()) Initialize(factory.QueryInterface<Factory2>()); #else Initialize(new Factory1()); #endif } }
/// <summary> /// Initializes a new instance of the <see cref="GraphicsAdapter" /> class. /// </summary> /// <param name="defaultFactory">The default factory.</param> /// <param name="adapterOrdinal">The adapter ordinal.</param> internal GraphicsAdapter(Factory1 defaultFactory, int adapterOrdinal) { this.adapterOrdinal = adapterOrdinal; adapter = defaultFactory.GetAdapter1(adapterOrdinal).DisposeBy(this); description = adapter.Description1; //var nativeOutputs = adapter.Outputs; var count = adapter.GetOutputCount(); outputs = new GraphicsOutput[count]; for (var i = 0; i < outputs.Length; i++) outputs[i] = new GraphicsOutput(this, i).DisposeBy(this); }
/// <summary> /// Duplicates the output of the specified monitor on the specified graphics adapter. /// </summary> /// <param name="whichGraphicsCardAdapter">The adapter which contains the desired outputs.</param> /// <param name="whichOutputDevice">The output device to duplicate (i.e. monitor). Begins with zero, which seems to correspond to the primary monitor.</param> public DesktopDuplicator(int whichGraphicsCardAdapter, int whichOutputDevice) { this.mWhichOutputDevice = whichOutputDevice; Adapter1 adapter = null; try { adapter = new Factory1().GetAdapter1(whichGraphicsCardAdapter); } catch (SharpDXException) { throw new DesktopDuplicationException("Could not find the specified graphics card adapter."); } this.mDevice = new Device(adapter); Output output = null; try { output = adapter.GetOutput(whichOutputDevice); } catch (SharpDXException) { throw new DesktopDuplicationException("Could not find the specified output device."); } var output1 = output.QueryInterface<Output1>(); this.mOutputDesc = output.Description; this.mTextureDesc = new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = this.mOutputDesc.DesktopBounds.Width, Height = this.mOutputDesc.DesktopBounds.Height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; try { this.mDeskDupl = output1.DuplicateOutput(mDevice); } catch (SharpDXException ex) { if (ex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code) { throw new DesktopDuplicationException("There is already the maximum number of applications using the Desktop Duplication API running, please close one of the applications and try again."); } } }
public bool InitializeGraphics(Control control) { this.control = control; AttachMouseEventHandler(control); control.Resize += new System.EventHandler(form_Resize); System.Drawing.Size clientSize = control.ClientSize; // Create Device and SwapChain device = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }); factory1 = new SharpDX.DXGI.Factory1(); swapChain = new SwapChain(factory1, device, new SwapChainDescription() { ModeDescription = new ModeDescription(clientSize.Width, clientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = DetectSampleDescription(device, Format.D32_Float_S8X24_UInt), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = control.Handle, IsWindowed = true, SwapEffect = SwapEffect.Discard }); // Ignore all windows events factory1.MakeWindowAssociation(control.Handle, WindowAssociationFlags.IgnoreAll); CreateViewportAndProjection(ref clientSize); string skel_file = Path.Combine(Application.StartupPath, @"resources\skeleton.bin"); skeleton = new hkaSkeleton(); skeleton.Load(skel_file); string anim_file = Path.Combine(Application.StartupPath, @"resources\idle.bin"); anim = new hkaAnimation(); if (anim.Load(anim_file)) { string source_file = Path.ChangeExtension(anim_file, ".hkx"); LoadAnimationSuccessful(source_file); } renderer3d.InitializeGraphics(device, skeleton); renderer3d.CreateDeviceResources(swapChain, ref viewport); renderer2d.CreateDeviceIndependentResources(skeleton); return(true); }
/// <summary> /// Initializes the GraphicsAdapter. On Desktop and WinRT, this is done statically. /// </summary> public static void Initialize() { lock(staticLock) { if (!isInitialized) { #if DIRECTX11_1 using (var factory = new Factory1()) Initialize(factory.QueryInterface<Factory2>()); #else Initialize(new Factory1()); #endif isInitialized = true; } } }
public override void Dispose() { if (dx11Device != null) { dx11Device.Dispose(); } if (dx11Factory != null) { dx11Factory.Dispose(); } if (dx11Output != null) { dx11Output.Dispose(); } if (dx11DuplicatedOutput != null) { dx11DuplicatedOutput.Dispose(); } if (dx11ScreenTexture != null) { dx11ScreenTexture.Dispose(); } if (dx11ScreenResource != null) { dx11ScreenResource.Dispose(); } if (dx11ScreenSurface != null) { dx11ScreenSurface.Dispose(); } if (screenShot != null) { screenShot.Dispose(); } dx11Device = null; dx11Factory = null; dx11Output = null; dx11DuplicatedOutput = null; dx11ScreenTexture = null; dx11ScreenResource = null; dx11ScreenSurface = null; screenShot = null; bmpData = null; GC.SuppressFinalize(this); }
/// <summary> /// Init some variables one times to spend execution time. /// </summary> public DirectX() { try { factory = new Factory1(); adapter = factory.GetAdapter1(numAdapter); device = new Device(adapter); output = adapter.GetOutput(numOutput); output1 = output.QueryInterface<Output1>(); // get screen wize textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left, Height = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; screenTexture = new Texture2D(device, textureDesc); try { duplicatedOutput = output1.DuplicateOutput(device); } catch (SharpDXException e) { if (e.ResultCode.Code == SharpDX.DXGI.ResultCode.Unsupported.Result.Code) { throw new System.ApplicationException("Your system does not support DirectX 11.2 (normally on windows 7). Please use 'Use GDI Capture' option to prevent this error!"); } else { throw e; } } } catch (Exception ex) { throw ex; } }
/// <summary> /// Create the DXGI factory object. /// </summary> private void CreateFactory() { m_dxgiFactory = CommonTools.TryExecute(() => new DXGI.Factory4()); if (m_dxgiFactory == null) { m_dxgiFactory = CommonTools.TryExecute(() => new DXGI.Factory2()); } if (m_dxgiFactory == null) { m_dxgiFactory = CommonTools.TryExecute(() => new DXGI.Factory1()); } if (m_dxgiFactory == null) { throw new SeeingSharpGraphicsException("Unable to create the DXGI Factory object!"); } }
private void InitGrabber() { try { this.pixelFormat = PixelFormat.Format32bppRgb; boundsRect = new System.Drawing.Rectangle(0, 0, WIDTH, HEIGHT); uint numAdapter = 0; // # of graphics card adapter uint numOutput = 0; // # of output device (i.e. monitor) // create device and factory dx11Device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware); dx11Factory = new Factory1(); dx11Output = new Output1(dx11Factory.Adapters1[numAdapter].Outputs[numOutput].NativePointer); // creating CPU-accessible texture resource dx11Texture2Ddescr = new SharpDX.Direct3D11.Texture2DDescription(); dx11Texture2Ddescr.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read; dx11Texture2Ddescr.BindFlags = SharpDX.Direct3D11.BindFlags.None; dx11Texture2Ddescr.Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm; dx11Texture2Ddescr.Height = HEIGHT; dx11Texture2Ddescr.Width = WIDTH; dx11Texture2Ddescr.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; dx11Texture2Ddescr.MipLevels = 1; dx11Texture2Ddescr.ArraySize = 1; dx11Texture2Ddescr.SampleDescription.Count = 1; dx11Texture2Ddescr.SampleDescription.Quality = 0; dx11Texture2Ddescr.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; dx11ScreenTexture = new SharpDX.Direct3D11.Texture2D(dx11Device, dx11Texture2Ddescr); // duplicate output stuff dx11DuplicatedOutput = dx11Output.DuplicateOutput(dx11Device); } catch (SharpDX.SharpDXException dxe) { string error = "Directx 11 initializer error.\n" + dxe.Message; LdpLog.Error(error); MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } catch (Exception ex) { string error = "Directx 11 initializer error.\n" + ex.Message; LdpLog.Error(error); MessageBox.Show(error, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public GxContext(RenderControl window) { mWindow = window; mFactory = new Factory1(); if (mFactory.Adapters1.Length == 0) throw new InvalidOperationException( "Sorry, but DirectX returned that there is no graphics card installed on your system. Please check if all your drivers are up to date!"); Adapter = mFactory.GetAdapter1(0); if (Adapter.Outputs.Length == 0) throw new InvalidOperationException( "Sorry, but DirectX returned that there is no output (monitor) assigned to the graphics card: \"" + Adapter.Description.Description + "\". Please check if your drivers are OK and if your graphics card and monitor show up in the device manager."); mOutput = Adapter.Outputs[0]; }
public WinformsDevice(Factory1 dxgiFactory, WinformsEye eye, CAdapter adapter, ControlWindow primaryWindow, SwapChainDescription primarySwapChainDesc, DeviceInitializationFlags flags, IFileSystem fileSystem) { this.flags = flags; this.eye = eye; this.dxgiFactory = dxgiFactory; this.adapter = adapter; d3dDevice = new Device(adapter.DXGIAdapter, CtSharpDX11.DeviceCreationFlags(flags)); primarySwapChain = new CSwapChain(this, primaryWindow, ref primarySwapChainDesc, pswc => { }, () => !primaryWindow.IsVisible && additionalSwapChains.All(aswc => !aswc.Window.IsVisible)); creator = new CDeviceChildCreator(this); immediateContext = new CDeviceContext(this, d3dDevice.ImmediateContext); additionalSwapChains = new List<CSwapChain>(); }
public DeviceResources(IntPtr windowHandle, int renderResWidth, int renderResHeight, int targetFPS) { Device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug | D3D11.DeviceCreationFlags.DisableGpuTimeout); DeviceContext = Device.ImmediateContext; var backBufferDesc = new DXGI.ModeDescription( renderResWidth, renderResHeight, new DXGI.Rational(targetFPS, 1), DXGI.Format.R8G8B8A8_UNorm ); //var backBufferDesc = new DXGI.ModeDescription() //{ // Width = renderResWidth, // Height = renderResHeight, // RefreshRate = new DXGI.Rational(targetFPS, 1), // Format = DXGI.Format.R8G8B8A8_UNorm //}; var swapChainDesc = new DXGI.SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = sampleDescription, Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = windowHandle, IsWindowed = true }; // Create SwapChain DXGI.Factory factory = new DXGI.Factory1(); SwapChain = new DXGI.SwapChain(factory, Device, swapChainDesc); // Create BackBuffer RTV BackBuffer = SwapChain.GetBackBuffer <D3D11.Texture2D>(0); BackBufferRTV = new D3D11.RenderTargetView(Device, BackBuffer); }
/// <summary> /// Init some variables one times to spend execution time. /// </summary> public DirectX() { try { factory = new Factory1(); adapter = factory.GetAdapter1(numAdapter); device = new Device(adapter); output = adapter.GetOutput(numOutput); output1 = output.QueryInterface<Output1>(); // get screen wize textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Right - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Left, Height = ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Bottom - ((SharpDX.Mathematics.Interop.RawRectangle)output.Description.DesktopBounds).Top, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; screenTexture = new Texture2D(device, textureDesc); duplicatedOutput = output1.DuplicateOutput(device); } catch (Exception ex) { throw ex; } }
/// <summary> /// Initializes all adapters with the specified factory. /// </summary> /// <param name="factory1">The factory1.</param> internal static void Initialize(Factory1 factory1) { if (staticCollector != null) { staticCollector.Dispose(); } staticCollector = new DisposeCollector(); Factory = factory1; staticCollector.Collect(Factory); int countAdapters = Factory.GetAdapterCount1(); var adapters = new List<GraphicsAdapter>(); for (int i = 0; i < countAdapters; i++) { var adapter = new GraphicsAdapter(i); staticCollector.Collect(adapter); adapters.Add(adapter); } Default = adapters[0]; Adapters = adapters.ToArray(); }
public D3D11SwapChain(D3D11GraphicsDevice graphiceDevice, SwapChainInfo swapChainInfo) { _swapChainInfo = swapChainInfo; _factory = new DXGIFactory(); var swapChainDescription = new SwapChainDescription { SwapEffect = swapChainInfo.SwapEffect.ToSharpDX(), BufferCount = 2, Flags = SwapChainFlags.None, IsWindowed = swapChainInfo.IsWindowed, ModeDescription = new ModeDescription(swapChainInfo.Width, swapChainInfo.Height, new Rational(60, 1), Format.R8G8B8A8UNorm.ToSharpDX()), OutputHandle = swapChainInfo.WindowHandle, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput }; _swapChain = new SwapChain(_factory, graphiceDevice, swapChainDescription); using var resource = _swapChain.GetBackBuffer <D3D11Texture2D>(0); TextureView = new D3D11TextureView(graphiceDevice, resource, swapChainInfo.Width, swapChainInfo.Height, 0, false, 1, TextureViewType.RenderTarget); DepthStencilView = CreateDepthStencilView(graphiceDevice, swapChainInfo.Width, swapChainInfo.Height); }
private static Device CreateDevice() { SharpDX.DXGI.Adapter chosenAdapter = null; using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { var adapters = dxgiFactory.Adapters; try { ulong adapterLuid = OpenVR.System.GetOutputDevice(ETextureType.DirectX, IntPtr.Zero); if (adapterLuid != 0) { foreach (var adapter in adapters) { if ((ulong)adapter.Description.Luid == adapterLuid) { chosenAdapter = adapter; } } } if (chosenAdapter == null) { //fallback to the default adapter chosenAdapter = adapters[0]; } var device = new Device(chosenAdapter, debugDevice ? DeviceCreationFlags.Debug : DeviceCreationFlags.None); return(device); } finally { foreach (var adapter in adapters) { adapter.Dispose(); } } } }
/// <summary> /// Initializes a new instance of the <see cref="RenderControl" /> class. /// </summary> public RenderControl() { SwapChainDescription swapCHainDesc = new SwapChainDescription { BufferCount = 2, Usage = Usage.RenderTargetOutput, OutputHandle = Handle, IsWindowed = true, ModeDescription = new ModeDescription( Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.BgraSupport, swapCHainDesc, out _device, out _swapChain); Debug.Assert(_swapChain != null, "_swapChain != null"); // ReSharper disable once AssignNullToNotNullAttribute _backBuffer = Surface.FromSwapChain(_swapChain, 0); Debug.Assert(_backBuffer != null, "_backBuffer != null"); Size2F dpi = DirectXResourceManager.FactoryD2D.DesktopDpi; RenderTarget renderTarget = new RenderTarget( DirectXResourceManager.FactoryD2D, _backBuffer, new RenderTargetProperties { DpiX = dpi.Width, DpiY = dpi.Height, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Ignore), Type = RenderTargetType.Default, Usage = RenderTargetUsage.None }); _renderTargetContainer = RenderTargetContainer.CreateContainer(renderTarget, out _renderTargetRef); using (FactoryDXGI factory = _swapChain.GetParent <FactoryDXGI>()) { Debug.Assert(factory != null, "factory != null"); factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter); } _renderThread = new Thread(RenderLoop) { Name = "Render Thread", IsBackground = true }; }
public void Run() { #region setup resources var mainForm = new RenderForm(); var scDescription = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription( 0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = mainForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; //DeviceCreationFlags.Debug flag below will show debug layer messages in your output window. //Need proper version of windows sdk for it to work, otherwise it will throw an exception. //You also need to right click your project->properties->debug (on the left panel)-> check "enable native code debugging" // Create Device and SwapChain _d3d11.Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, new[] { _d3d.FeatureLevel.Level_12_1 }, scDescription, out d3d11Device, out swapChain); // Ignore all windows events dxgiFactory = swapChain.GetParent <_dxgi.Factory1>(); dxgiFactory.MakeWindowAssociation(mainForm.Handle, WindowAssociationFlags.IgnoreAll); d2dFactory = new _d2d.Factory(); d2dFactory4 = d2dFactory.QueryInterface <_d2d.Factory4>(); dxgiDevice = d3d11Device.QueryInterface <_dxgi.Device>(); d2dDevice3 = new _d2d.Device3(d2dFactory4, dxgiDevice); d2dDeviceContext3 = new _d2d.DeviceContext3(d2dDevice3, DeviceContextOptions.None); #endregion #region create drawing input sourceImage = createD2DBitmap(@"yourFile.png", d2dDeviceContext3); spriteBatch = new SpriteBatch(d2dDeviceContext3); var destinationRects = new RawRectangleF[1]; destinationRects[0] = new RectangleF(100, 50, sourceImage.Size.Width, sourceImage.Size.Height); var sourceRects = new RawRectangle[1]; sourceRects[0] = new RectangleF(0, 0, sourceImage.Size.Width, sourceImage.Size.Height); #endregion #region mainLoop RenderLoop.Run(mainForm, () => { if (d2dTarget != null) { d2dTarget.Dispose(); d2dTarget = null; } using (var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0)) { using (var surface = backBuffer.QueryInterface <Surface>()) { var bmpProperties = new BitmapProperties1( new PixelFormat(Format.R8G8B8A8_UNorm, _d2d.AlphaMode.Premultiplied), dpiX: 96, dpiY: 96, bitmapOptions: BitmapOptions.Target | BitmapOptions.CannotDraw); d2dTarget = new Bitmap1( d2dDeviceContext3, surface, bmpProperties); d2dDeviceContext3.Target = d2dTarget; } } //the key missing piece: cannot use per primitive antialiasing with spritebatch d2dDeviceContext3.AntialiasMode = AntialiasMode.Aliased; d2dDeviceContext3.BeginDraw(); spriteBatch.Clear(); spriteBatch.AddSprites( 1, destinationRects, sourceRects, null, null, destinationRectanglesStride: 0, //0 stride because there is only 1 element sourceRectanglesStride: 0, colorsStride: 0, transformsStride: 0); d2dDeviceContext3.DrawSpriteBatch( spriteBatch: spriteBatch, startIndex: 0, spriteCount: 1, bitmap: sourceImage, interpolationMode: BitmapInterpolationMode.Linear, spriteOptions: SpriteOptions.ClampToSourceRectangle); d2dDeviceContext3.EndDraw(); //first param set to 1 would indicate waitVerticalBlanking swapChain.Present(0, PresentFlags.None); }); #endregion }
public void Init() { logger.Debug("DesktopDuplicationManager::Init(...)"); CaptureMouse = true; this.AllScreensRect = SystemInformation.VirtualScreen; //var rawRect = new RawRectangle //{ // Left = AllScreensRect.Left, // Right = AllScreensRect.Right, // Top = AllScreensRect.Top, // Bottom = AllScreensRect.Bottom, //}; // SetupRegions(rawRect, ) SharpDX.DXGI.Factory1 dxgiFactory = null; Adapter1 adapter = null; Output output = null; try { dxgiFactory = new SharpDX.DXGI.Factory1(); logger.Info(MediaFoundation.DxTool.LogDxAdapters(dxgiFactory.Adapters1)); if (adapter == null) {// первым идет адаптер с которому подключен primary монитор adapter = dxgiFactory.GetAdapter1(0); } AdapterId = adapter.Description.Luid; //logger.Info("Screen source info: " + adapter.Description.Description + " " + output.Description.DeviceName); var deviceCreationFlags = //DeviceCreationFlags.Debug | DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport; device = new Device(adapter, deviceCreationFlags); using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>()) { multiThread.SetMultithreadProtected(true); } if (deskDupls != null) { //... } deskDupls = new List <_DesktopDuplicator>(); foreach (var _output in adapter.Outputs) { var descr = _output.Description; var desktopBounds = descr.DesktopBounds; var desktopRect = new GDI.Rectangle { X = desktopBounds.Left, Y = desktopBounds.Top, Width = desktopBounds.Right - desktopBounds.Left, Height = desktopBounds.Bottom - desktopBounds.Top, }; _DesktopDuplicator deskDupl = new _DesktopDuplicator(device); deskDupl.Init(_output, desktopRect); deskDupl.CaptureMouse = this.CaptureMouse; deskDupls.Add(deskDupl); //var rect = GDI.Rectangle.Intersect(desktopRect, SrcRect); //if (rect.Width > 0 && rect.Height > 0) //{ // logger.Info("Screen source info: " + adapter.Description.Description + " " + descr.DeviceName); // DesktopDuplicator deskDupl = new DesktopDuplicator(device); // deskDupl.Init(_output, SrcRect); // deskDupl.CaptureMouse = this.CaptureMouse; // deskDupls.Add(deskDupl); //} //else //{ // logger.Debug("No common area: " + descr.DeviceName + " " + SrcRect.ToString()); // continue; //} _output.Dispose(); } } finally { if (adapter != null) { adapter.Dispose(); adapter = null; } if (output != null) { output.Dispose(); output = null; } if (dxgiFactory != null) { dxgiFactory.Dispose(); dxgiFactory = null; } } compositionTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = AllScreensRect.Width, Height = AllScreensRect.Height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, }); initialized = true; }
public static Bitmap CaptureScreen() { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 1; // Create DXGI Factory1 var factory = new Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter var device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface<Output1>(); // Width/Height of desktop to capture int width = ((Rectangle)output.Description.DesktopBounds).Width; //width = 1024; int height = ((Rectangle)output.Description.DesktopBounds).Height; //height = 1024; // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; var screenTexture = new Texture2D(device, textureDesc); // Duplicate the output var duplicatedOutput = output1.DuplicateOutput(device); bool captureDone = false; Bitmap bitmap = null; for (int i = 0; !captureDone; i++) { try { SharpDX.DXGI.Resource screenResource; OutputDuplicateFrameInformation duplicateFrameInformation; // Try to get duplicated frame within given time duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource); if (i > 0) { // copy resource into memory that can be accessed by the CPU using (var screenTexture2D = screenResource.QueryInterface<Texture2D>()) device.ImmediateContext.CopyResource(screenTexture2D, screenTexture); // Get the desktop capture texture var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None); // Create Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, width, height); // Copy pixels from screen capture Texture to GDI bitmap var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat); var sourcePtr = mapSource.DataPointer; var destPtr = mapDest.Scan0; for (int y = 0; y < height; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, width * 4); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch); destPtr = IntPtr.Add(destPtr, mapDest.Stride); } // Release source and dest locks bitmap.UnlockBits(mapDest); device.ImmediateContext.UnmapSubresource(screenTexture, 0); // Capture done captureDone = true; } screenResource.Dispose(); duplicatedOutput.ReleaseFrame(); } catch (SharpDXException e) { if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code) { throw e; } } } duplicatedOutput.Dispose(); screenTexture.Dispose(); output1.Dispose(); output.Dispose(); device.Dispose(); adapter.Dispose(); factory.Dispose(); return bitmap; }
public override void Hook() { DebugMessage("Hook: Begin"); // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain if (_d3d10_1VTblAddresses == null) { _d3d10_1VTblAddresses = new List<IntPtr>(); _dxgiSwapChainVTblAddresses = new List<IntPtr>(); DebugMessage("Hook: Before device creation"); using (var factory = new Factory1()) { using ( var device = new Device1(factory.GetAdapter(0), DeviceCreationFlags.None, FeatureLevel.Level_10_1)) { DebugMessage("Hook: Device created"); _d3d10_1VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_1_DEVICE_METHOD_COUNT)); using (var renderForm = new RenderForm()) { using ( var sc = new SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle))) { _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT)); } } } } } // We will capture the backbuffer here DXGISwapChain_PresentHook = new Hook<DXGISwapChain_PresentDelegate>( _dxgiSwapChainVTblAddresses[(int) DXGI.DXGISwapChainVTbl.Present], new DXGISwapChain_PresentDelegate(PresentHook), this); // We will capture target/window resizes here DXGISwapChain_ResizeTargetHook = new Hook<DXGISwapChain_ResizeTargetDelegate>( _dxgiSwapChainVTblAddresses[(int) DXGI.DXGISwapChainVTbl.ResizeTarget], new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook), this); /* * Don't forget that all hooks will start deactivated... * The following ensures that all threads are intercepted: * Note: you must do this for each hook. */ DXGISwapChain_PresentHook.Activate(); DXGISwapChain_ResizeTargetHook.Activate(); Hooks.Add(DXGISwapChain_PresentHook); Hooks.Add(DXGISwapChain_ResizeTargetHook); }
public void Setup(MfVideoArgs inputArgs) { logger.Debug("MfH264Decoder::Setup(...)"); var frameRate = inputArgs.FrameRate; frameDuration = MfTool.TicksPerSecond / frameRate; var width = inputArgs.Width; var height = inputArgs.Height; var bufSize = width * height * 4; var inputFormat = VideoFormatGuids.H264; try { //device = new Device(adapter, DeviceCreationFlags.BgraSupport); if (device == null) { using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { using (var adapter = dxgiFactory.GetAdapter1(0)) { device = new Device(adapter, //DeviceCreationFlags.Debug | DeviceCreationFlags.VideoSupport | DeviceCreationFlags.BgraSupport); using (var multiThread = device.QueryInterface <SharpDX.Direct3D11.Multithread>()) { multiThread.SetMultithreadProtected(true); } } } } var transformFlags = //TransformEnumFlag.Hardware | TransformEnumFlag.SortAndFilter; var inputType = new TRegisterTypeInformation { GuidMajorType = MediaTypeGuids.Video, GuidSubtype = VideoFormatGuids.H264 }; var transformActivators = MediaFactory.FindTransform(TransformCategoryGuids.VideoDecoder, transformFlags, inputType, null); try { foreach (var activator in transformActivators) { //bool isHardware = flags.HasFlag(TransformEnumFlag.Hardware); //bool isAsync = flags.HasFlag(TransformEnumFlag.Asyncmft); string name = activator.Get(TransformAttributeKeys.MftFriendlyNameAttribute); Guid clsid = activator.Get(TransformAttributeKeys.MftTransformClsidAttribute); TransformEnumFlag flags = (TransformEnumFlag)activator.Get(TransformAttributeKeys.TransformFlagsAttribute); bool isAsync = !(flags.HasFlag(TransformEnumFlag.Syncmft)); isAsync |= !!(flags.HasFlag(TransformEnumFlag.Asyncmft)); bool isHardware = !!(flags.HasFlag(TransformEnumFlag.Hardware)); var _flags = Enum.GetValues(typeof(TransformEnumFlag)) .Cast <TransformEnumFlag>() .Where(m => (m != TransformEnumFlag.None && flags.HasFlag(m))); var transformInfo = name + " " + clsid.ToString() + " " + string.Join("|", _flags); logger.Info(transformInfo); //encoder = activator.ActivateObject<Transform>(); //break; //var HardwareUrl = activator.Get(TransformAttributeKeys.MftEnumHardwareUrlAttribute); //logger.Info(HardwareUrl); //var TransformAsync = activator.Get(TransformAttributeKeys.TransformAsync); //logger.Info(TransformAsync); //logger.Info("-------------------------------------"); } } finally { decoder = transformActivators[0].ActivateObject <Transform>(); foreach (var activator in transformActivators) { activator.Dispose(); } } using (var attr = decoder.Attributes) { bool d3dAware = attr.Get(TransformAttributeKeys.D3DAware); bool d3d11Aware = attr.Get(TransformAttributeKeys.D3D11Aware); if (d3d11Aware) { using (DXGIDeviceManager devMan = new DXGIDeviceManager()) { devMan.ResetDevice(device); decoder.ProcessMessage(TMessageType.SetD3DManager, devMan.NativePointer); } } attr.Set(SinkWriterAttributeKeys.LowLatency, true); //attr.Set(MFAttributeKeys.MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT, 1); } int inputStreamCount = -1; int outputStreamsCount = -1; decoder.GetStreamCount(out inputStreamCount, out outputStreamsCount); int[] inputStreamIDs = new int[inputStreamCount]; int[] outputStreamIDs = new int[outputStreamsCount]; bool res = decoder.TryGetStreamIDs(inputStreamIDs, outputStreamIDs); if (res) { inputStreamId = inputStreamIDs[0]; outputStreamId = outputStreamIDs[0]; } else { inputStreamId = 0; outputStreamId = 0; } for (int i = 0; ; i++) { try { decoder.GetInputAvailableType(0, i, out MediaType mediaType); if (mediaType == null) { logger.Warn("NoMoreType"); break; } var formatId = mediaType.Get(MediaTypeAttributeKeys.Subtype); if (formatId == inputFormat) { logger.Debug("inputFormat " + inputFormat); InputMediaType = mediaType; break; } mediaType.Dispose(); mediaType = null; } catch (SharpDX.SharpDXException ex) { if (ex.ResultCode != SharpDX.MediaFoundation.ResultCode.NoMoreTypes) { throw; } } } if (InputMediaType == null) { logger.Warn("Unsuported format: " + MfTool.GetMediaTypeName(inputFormat)); return; } InputMediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video); InputMediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.H264); InputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); InputMediaType.Set(MediaTypeAttributeKeys.FrameRate, frameRate); // InputMediaType.Set(MediaTypeAttributeKeys.PixelAspectRatio, MfTool.PackToLong(1, 1)); InputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); InputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); decoder.SetInputType(inputStreamId, InputMediaType, 0); logger.Info("============== INPUT TYPE=================="); logger.Info(MfTool.LogMediaType(InputMediaType)); //MediaType outputMediaType = null; //for (int i = 0; ; i++) //{ // res = decoder.TryGetOutputAvailableType(outputStreamId, i, out outputMediaType); // if (!res) // { // break; // } // //outputMediaType.Set(MediaTypeAttributeKeys.AvgBitrate, 30000000); // outputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); // outputMediaType.Set(MediaTypeAttributeKeys.FrameRate, MfTool.PackToLong(frameRate, 1)); // //outputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); // //outputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); // decoder.SetOutputType(outputStreamId, outputMediaType, 0); // outputMediaType.Dispose(); // outputMediaType = null; // break; //} OutputMediaType = new MediaType(); OutputMediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video); OutputMediaType.Set(MediaTypeAttributeKeys.Subtype, VideoFormatGuids.NV12); //OutputMediaType.Set(MediaTypeAttributeKeys.AvgBitrate, 30000000); OutputMediaType.Set(MediaTypeAttributeKeys.InterlaceMode, (int)VideoInterlaceMode.Progressive); OutputMediaType.Set(MediaTypeAttributeKeys.FrameSize, MfTool.PackToLong(width, height)); OutputMediaType.Set(MediaTypeAttributeKeys.FrameRate, frameRate); OutputMediaType.Set(MediaTypeAttributeKeys.AllSamplesIndependent, 1); decoder.SetOutputType(outputStreamId, OutputMediaType, 0); logger.Info("============== OUTPUT TYPE=================="); logger.Info(MfTool.LogMediaType(OutputMediaType)); } catch (Exception ex) { logger.Error(ex); Close(); throw; } }
public WinformsEye() { factory = new Factory1(); adapters = Enumerable.Range(0, factory.GetAdapterCount1()).Select(i => new CAdapter(factory.GetAdapter1(i), i)).ToArray(); windows = new List<ControlWindow>(); }
/// <summary> /// Function to return a device object for this video device. /// </summary> /// <returns>The new device object, adapter and factory.</returns> internal Tuple <GI.Factory1, GI.Adapter1, D3D.Device> GetDevice(VideoDeviceType deviceType, DeviceFeatureLevel featureLevel) { GI.Factory1 factory; GI.Adapter1 adapter; D3D.Device device; switch (deviceType) { #if DEBUG case VideoDeviceType.ReferenceRasterizer: device = new D3D.Device(D3DCommon.DriverType.Reference, D3D.DeviceCreationFlags.Debug, D3DCommon.FeatureLevel.Level_11_0) { DebugName = string.Format("{0} D3D11 Device", Name) }; using (var giDevice = device.QueryInterface <GI.Device1>()) { adapter = giDevice.GetParent <GI.Adapter1>(); //giDevice.Adapter; factory = adapter.GetParent <GI.Factory1>(); } break; #endif case VideoDeviceType.Software: // WARP devices can only do SM4_1 or lower. if (featureLevel >= DeviceFeatureLevel.SM5) { featureLevel = DeviceFeatureLevel.SM4_1; } #if DEBUG device = new D3D.Device(D3DCommon.DriverType.Warp, D3D.DeviceCreationFlags.Debug, GetFeatureLevel(featureLevel)) { DebugName = string.Format("{0} D3D11 Device", Name) }; #else device = new D3D.Device(D3DCommon.DriverType.Warp, D3D.DeviceCreationFlags.None, GetFeatureLevel(featureLevel)); #endif using (var giDevice = device.QueryInterface <GI.Device1>()) { adapter = giDevice.GetParent <GI.Adapter1>(); factory = adapter.GetParent <GI.Factory1>(); } break; default: factory = new GI.Factory1(); adapter = factory.GetAdapter1(Index); #if DEBUG device = new D3D.Device(adapter, D3D.DeviceCreationFlags.Debug, GetFeatureLevel(featureLevel)) { DebugName = string.Format("{0} D3D11 Device", Name) }; #else device = new D3D.Device(adapter, D3D.DeviceCreationFlags.None, GetFeatureLevel(HardwareFeatureLevel)); #endif break; } return(new Tuple <GI.Factory1, GI.Adapter1, D3D.Device>(factory, adapter, device)); }
public DemoApplication() { //SharpDX.Configuration.EnableObjectTracking = true; _Form = new RenderForm(); _Timer = new Stopwatch(); _Form.Width = 1280; _Form.Height = 720; _Form.MaximumSize = new System.Drawing.Size(1280, 720); _Form.MinimumSize = new System.Drawing.Size(1280, 720); _Form.MaximizeBox = false; _Form.SizeGripStyle = SizeGripStyle.Hide; _Form.KeyPress += HandleKeyPress; _Form.ClientSizeChanged += HandleClientSizeChanged; _Form.KeyDown += HandleKeyDown; ModeDescription displayMode = new ModeDescription { Width = _Form.ClientSize.Width, Height = _Form.ClientSize.Height, RefreshRate = new Rational(60, 1), Format = Format.R8G8B8A8_UNorm }; SwapChainDescription chainDescription = new SwapChainDescription { ModeDescription = displayMode, SampleDescription = new SampleDescription(1, 0), BufferCount = 2, IsWindowed = true, OutputHandle = _Form.Handle, SwapEffect = SwapEffect.Sequential, Usage = Usage.BackBuffer | Usage.RenderTargetOutput }; _Factory = new Factory1(); int availableAdapters = _Factory.GetAdapterCount1(); if(availableAdapters == 0) { throw new Exception("no adapters are available"); } for(int i = 0; i < availableAdapters; ++i) { #if DEBUG using(Adapter1 dxgiSurfaceAdapter = _Factory.GetAdapter1(i)) { try { Device1.CreateWithSwapChain( dxgiSurfaceAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, chainDescription, out _Device, out _SwapChain); } catch(SharpDXException) { continue; } _Device2D = new Device2D(dxgiSurfaceAdapter); } #else using (Adapter1 dxgiSurfaceAdapter = _Factory.GetAdapter1(i)) { try { Device1.CreateWithSwapChain( dxgiSurfaceAdapter, DeviceCreationFlags.BgraSupport, chainDescription, out _Device, out _SwapChain); } catch(SharpDXException) { continue; } _Device2D = new Device2D(dxgiSurfaceAdapter); } #endif } _Device2D.Diagnostics.Query("Composition", "FrameBatchCount", out _CompositionFrameBatchCount); _Device2D.Diagnostics.Query("Composition", "FrameDuration", out _CompositionFrameDuration); _Device2D.Diagnostics.Query("Painting", "FrameDuration", out _PaintingFrameDuration); _Timer.Start(); _Renderer = new D3D10Renderer(_Device); HandleClientSizeChanged(null, null); _IsResetQueued = true; }
public SharpRender(RenderForm form) { this.form = form; var adapters = new DXGI.Factory1().Adapters; DXGI.Adapter myadapter = null; for (int i = 0; i < adapters.Length; ++i) { Logger.Log(string.Format("Adapter Found: [{0}] " + "{1}\tDeviceId={5}" + "{1}\tLuid={6}" + "{1}\tVendorId={10}" + "{1}\tSubsystemId={9}" + "{1}\tDescription={4}" + "{1}\tRevision={7}" + "{1}\tDedicatedSystemMemory={2}" + "{1}\tDedicatedVideoMemory={3}" + "{1}\tSharedSystemMemory={8}" + "", i, Environment.NewLine, adapters[i].Description.DedicatedSystemMemory, adapters[i].Description.DedicatedVideoMemory, adapters[i].Description.Description, adapters[i].Description.DeviceId, adapters[i].Description.Luid, adapters[i].Description.Revision, adapters[i].Description.SharedSystemMemory, adapters[i].Description.SubsystemId, adapters[i].Description.VendorId)); var outputs = adapters[i].Outputs; for (int j = 0; j < outputs.Length; ++j) { Logger.Log(string.Format("Output Found: [{0},{1}]" + "{2}\tDeviceName={4}" + "{2}\tIsAttachedToDesktop={5}" + "{2}\tMonitorHandle={6}" + "{2}\tDesktopBounds={3}" + "{2}\tRotation={7}" + "", i, j, Environment.NewLine, (Rectangle)outputs[j].Description.DesktopBounds, outputs[j].Description.DeviceName, outputs[j].Description.IsAttachedToDesktop, outputs[j].Description.MonitorHandle, outputs[j].Description.Rotation)); } if (outputs.Length > 0 && myadapter == null) { myadapter = adapters[i]; } } d3device = new Direct3D11.Device( myadapter, Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.Direct3D.DriverType.Hardware, //Direct3D11.DeviceCreationFlags.BgraSupport | //Direct3D11.DeviceCreationFlags.Debug); defDevice = d3device.QueryInterface <Direct3D11.Device1>(); dxgiDevice2 = defDevice.QueryInterface <DXGI.Device2>(); dxgiAdapter = dxgiDevice2.Adapter; dxgiFactory2 = dxgiAdapter.GetParent <DXGI.Factory2>(); var scDescription = new DXGI.SwapChainDescription1() { Width = 0, Height = 0, Format = DXGI.Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 2, Scaling = DXGI.Scaling.None, SwapEffect = DXGI.SwapEffect.FlipSequential }; swapChain = new DXGI.SwapChain1(dxgiFactory2, defDevice, form.Handle, ref scDescription, null, null); d2dDevice = new Direct2D1.Device(dxgiDevice2); d2dContext = new Direct2D1.DeviceContext(d2dDevice, Direct2D1.DeviceContextOptions.None); fac = new Direct2D1.Factory(Direct2D1.FactoryType.SingleThreaded); var dpi = fac.DesktopDpi; var bMProperties = new Direct2D1.BitmapProperties1( new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied), dpi.Width, dpi.Height, Direct2D1.BitmapOptions.CannotDraw | Direct2D1.BitmapOptions.Target); bb = swapChain.GetBackBuffer <DXGI.Surface>(0); target = new Direct2D1.Bitmap1(d2dContext, bb, bMProperties); d2dContext.Target = target; wrFactory = new DirectWrite.Factory(); brush = new Direct2D1.SolidColorBrush(d2dContext, c(Color.White)); }
/// <summary> /// Initializes all adapters with the specified factory. /// </summary> /// <param name="factory1">The factory1.</param> internal static void Initialize(Factory1 factory1) { if (staticCollector != null) { staticCollector.Dispose(); } staticCollector = new DisposeCollector(); defaultFactory = factory1; staticCollector.Collect(defaultFactory); int countAdapters = defaultFactory.GetAdapterCount1(); var adapterList = new List<GraphicsAdapter>(); for (int i = 0; i < countAdapters; i++) { var adapter = new GraphicsAdapter(i); staticCollector.Collect(adapter); adapterList.Add(adapter); } defaultAdapter = adapterList.Count > 0 ? adapterList[0] : null; adapters = adapterList.ToArray(); }
private void InitDXGIFactory() { DXGIFactory = new Factory1(); }
private Adapter1 InitializeAdapter(int adapterIndex) { try { using (var factory = new Factory1()) { return factory.GetAdapter1(adapterIndex); } } catch (SharpDXException) { throw new ScreenException("Unable to initialize the adapter."); } }
public static Dx10Device CreateDefaultAdapter() { using (Factory1 factory = new Factory1()) using (Adapter adapter = factory.GetAdapter(0)) return new Dx10Device(adapter); }
private void Reset() { using (Factory1 DXGIfactory = new Factory1()) { Adapter1 adapter; if (DXGIfactory.Adapters1[0].Outputs.Length == 0) { adapter = DXGIfactory.Adapters1[1]; } else { adapter = DXGIfactory.Adapters1[0]; } Output1 output = adapter.Outputs[0].QueryInterface<Output1>(); this.duplicatedOutput = output.DuplicateOutput(this.device); } }
public RLocalDesktopCapture(int outputDeviceIndex) { // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) int numOutput = outputDeviceIndex; // Create DXGI Factory1 var factory = new SharpDX.DXGI.Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture DisplayWidth = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width; DisplayHeight = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height; int stride = 4 * DisplayWidth; int size = stride * DisplayHeight; FrameBytes = new byte[size]; GCHandle pinned = GCHandle.Alloc(outBytes, GCHandleType.Pinned); outBytesPtr = pinned.AddrOfPinnedObject(); //pinned.Free(); GCHandle pinned2 = GCHandle.Alloc(transcoderOptions, GCHandleType.Pinned); transcoderOptionsPtr = pinned2.AddrOfPinnedObject(); GCHandle pinned3 = GCHandle.Alloc(FrameBytes, GCHandleType.Pinned); frameBytesPtr = pinned3.AddrOfPinnedObject(); // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = DisplayWidth, Height = DisplayHeight, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; screenTexture = new Texture2D(device, textureDesc); // Duplicate the output duplicatedOutput = output1.DuplicateOutput(device); StartWorkTimer(); }
public SC_SharpDX_ScreenCapture(int adapter, int numOutput, SharpDX.Direct3D11.Device device_) { //_textureByteArray[0] = 0; imageptrList = new IntPtr[num_cols * num_rows]; _frameCaptureData = new SC_SharpDX_ScreenFrame(); arrayOfTexture2DFrac = new Texture2D[num_cols * num_rows]; pastearray = new int[num_cols * num_rows]; pastearrayTwo = new int[num_cols * num_rows]; arrayOfBytesTwo = new byte[_textureDescriptionFinal.Width * _textureDescriptionFinal.Height]; _lastShaderResourceViewArray = new ShaderResourceView[num_cols * num_rows]; _ShaderResourceViewArray = new ShaderResourceView[num_cols * num_rows]; _numAdapter = adapter; _numOutput = numOutput; try { using (var _factory = new SharpDX.DXGI.Factory1()) { this._adapter = _factory.GetAdapter1(_numAdapter); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //this._device = new Device(_adapter); //this._device = sccsVD4VE_LightNWithoutVr.SC_Console_DIRECTX._dxDevice.Device; this._device = device_; } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //initializeOutput(); using (var _output = _adapter.GetOutput(_numOutput)) { // Width/Height of desktop to capture //getDesktopBoundaries(); _width = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Width; _height = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Height; _frameCaptureData.width = _width; _frameCaptureData.height = _height; this._output1 = _output.QueryInterface <Output1>(); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //duplicateOutput(); this._outputDuplication = _output1.DuplicateOutput(_device); } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //getTextureDescription(); this._textureDescription = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget Format = Format.B8G8R8A8_UNorm, Width = _width, Height = _height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; this._textureDescriptionFinal = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, Format = Format.B8G8R8A8_UNorm, Width = _width, Height = _height, OptionFlags = ResourceOptionFlags.GenerateMipMaps, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default }; wid = _textureDescriptionFinal.Width / num_cols; hgt = _textureDescriptionFinal.Height / num_rows; /*this._textureDescriptionFinalFrac = new Texture2DDescription * { * CpuAccessFlags = CpuAccessFlags.None, * BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, * Format = Format.B8G8R8A8_UNorm, * Width = wid, * Height = hgt, * OptionFlags = ResourceOptionFlags.GenerateMipMaps, * MipLevels = 1, * ArraySize = 1, * SampleDescription = { Count = 1, Quality = 0 }, * Usage = ResourceUsage.Default * };*/ this._textureDescriptionFinalFrac = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget Format = Format.B8G8R8A8_UNorm, Width = wid, Height = hgt, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; piece = new Bitmap(wid, hgt); gr = Graphics.FromImage(piece); dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); strider = wid * 4; for (int i = 0; i < arrayOfImage.Length; i++) { arrayOfImage[i] = new int[wid * hgt * 4]; } for (int i = 0; i < arrayOfBytes.Length; i++) { arrayOfBytes[i] = new byte[wid * hgt * 4]; } piece = new System.Drawing.Bitmap(wid, hgt); dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); //int num_rows = _textureDescriptionFinal.Height / hgt; //int num_cols = _textureDescriptionFinal.Width / wid; source_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); for (int tex2D = 0; tex2D < 10 * 10; tex2D++) { arrayOfTexture2DFrac[tex2D] = new Texture2D(_device, _textureDescriptionFinalFrac); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } _texture2D = new Texture2D(_device, _textureDescription); _texture2DFinal = new Texture2D(_device, _textureDescriptionFinal); resourceViewDescription = new ShaderResourceViewDescription { Format = _texture2DFinal.Description.Format, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = -1, MostDetailedMip = 0 } }; _bitmap = new System.Drawing.Bitmap(_width, _height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, _width, _height); var bmpData = _bitmap.LockBits(boundsRect, ImageLockMode.ReadOnly, _bitmap.PixelFormat); _bytesTotal = Math.Abs(bmpData.Stride) * _bitmap.Height; _bitmap.UnlockBits(bmpData); _textureByteArray = new byte[_bytesTotal]; /*try * { * * } * catch (SharpDXException ex) * { * Console.WriteLine(ex.ToString()); * return; * }*/ }
/*private void CaptureFrame(object sender, DoWorkEventArgs e) * { * //Bitmap bmp = GetFrame(); * //e.Result = bmp; * }*/ private void Init() { captureWorker = new BackgroundWorker(); captureWorker.DoWork += new DoWorkEventHandler(CaptureFrame); captureWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleCapturedFrame); EncoderWorker = new BackgroundWorker(); EncoderWorker.DoWork += new DoWorkEventHandler(EncodeFrameTask); EncoderWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleEncodedFrame); DecoderWorker = new BackgroundWorker(); DecoderWorker.DoWork += new DoWorkEventHandler(DecodeFrameTask); DecoderWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HandleDecodedFrame); // # of graphics card adapter const int numAdapter = 0; // # of output device (i.e. monitor) const int numOutput = 0; // Create DXGI Factory1 var factory = new SharpDX.DXGI.Factory1(); var adapter = factory.GetAdapter1(numAdapter); // Create device from Adapter device = new Device(adapter); // Get DXGI.Output var output = adapter.GetOutput(numOutput); var output1 = output.QueryInterface <Output1>(); // Width/Height of desktop to capture transcoderOptions.InputWidth = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width; transcoderOptions.InputHeight = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height; outBytes = new byte[GetNumBytesRender()]; GCHandle pinned = GCHandle.Alloc(outBytes, GCHandleType.Pinned); outBytesPtr = pinned.AddrOfPinnedObject(); //pinned.Free(); GCHandle pinned2 = GCHandle.Alloc(transcoderOptions, GCHandleType.Pinned); transcoderOptionsPtr = pinned2.AddrOfPinnedObject(); GCHandle pinned3 = GCHandle.Alloc(frameBytes, GCHandleType.Pinned); frameBytesPtr = pinned3.AddrOfPinnedObject(); this.ClientSize = new Size(1600, 900); // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = DisplayWidth(), Height = DisplayHeight(), OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; screenTexture = new Texture2D(device, textureDesc); // Duplicate the output duplicatedOutput = output1.DuplicateOutput(device); InitializeDeviceResources(); }
public ProjectionMappingSample(string[] args) { // load ensemble.xml string path = args[0]; string directory = Path.GetDirectoryName(path); ensemble = RoomAliveToolkit.ProjectorCameraEnsemble.FromFile(path); // create d3d device var factory = new Factory1(); var adapter = factory.Adapters[0]; // When using DeviceCreationFlags.Debug on Windows 10, ensure that "Graphics Tools" are installed via Settings/System/Apps & features/Manage optional features. // Also, when debugging in VS, "Enable native code debugging" must be selected on the project. device = new SharpDX.Direct3D11.Device(adapter, DeviceCreationFlags.None); // shaders depthAndColorShader = new DepthAndColorShader(device); projectiveTexturingShader = new ProjectiveTexturingShader(device); fromUIntPS = new FromUIntPS(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight); bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight); // create device objects for each camera foreach (var camera in ensemble.cameras) cameraDeviceResources[camera] = new CameraDeviceResource(device, camera, renderLock, directory); // user view depth buffer var userViewDpethBufferDesc = new Texture2DDescription() { Width = userViewTextureWidth, Height = userViewTextureHeight, MipLevels = 1, ArraySize = 1, Format = Format.D32_Float, // necessary? SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None }; var userViewDepthStencil = new Texture2D(device, userViewDpethBufferDesc); userViewDepthStencilView = new DepthStencilView(device, userViewDepthStencil); // create a form for each projector foreach (var projector in ensemble.projectors) { var form = new ProjectorForm(factory, device, renderLock, projector); if (fullScreenEnabled) form.FullScreen = fullScreenEnabled; // TODO: fix this so can be called after Show form.Show(); projectorForms.Add(form); } clock.Start(); if (liveDepthEnabled) { foreach (var cameraDeviceResource in cameraDeviceResources.Values) cameraDeviceResource.StartLive(); } new System.Threading.Thread(RenderLoop).Start(); }
public ScreenDublicator() { Adapter adapter = null; Output output = null; Output1 output1 = null; try { //Адаптер adapter = new Factory1().GetAdapter1(this.ADAPTER); //Устройство this._device = new Device(adapter); output = adapter.GetOutput(this.MONITOR); //Выход output1 = output.QueryInterface<Output1>(); this._outputDesc = output.Description; this._width = this._outputDesc.DesktopBounds.Right - this._outputDesc.DesktopBounds.Left; this._height = this._outputDesc.DesktopBounds.Bottom - this._outputDesc.DesktopBounds.Top; this._textureDesc = new Texture2DDescription() { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = this._width, Height = this._height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; this._outputDublication = output1.DuplicateOutput(this._device); //Текстура this._desktopTexture = new Texture2D(this._device, this._textureDesc); } catch(SharpDXException sdxex) { if (sdxex.ResultCode.Code == SharpDX.DXGI.ResultCode.NotCurrentlyAvailable.Result.Code) { throw new ScreenDublicatorException("Достигнут предел приложений, работающих с API)"); } else { string message = String.Format("Не удалось создать дублирующий выход"); Debug.WriteLine(message + "\n{0}\n{1}", sdxex.Message, sdxex.StackTrace); throw new ScreenDublicatorException(message); } } catch(Exception ex) { string message = String.Format("Ошибка при инициализации объекта\n{0}\n{1}", ex.Message, ex.StackTrace); throw new ScreenDublicatorException(message); } finally { if(adapter != null) { adapter.Dispose(); } if(output != null) { output.Dispose(); } if(output1 != null) { output1.Dispose(); } } }
public D3D11GraphicsDevice(bool validation, PresentationParameters presentationParameters) : base(GraphicsBackend.Direct3D11, presentationParameters) { #if DEBUG SharpDX.Configuration.EnableObjectTracking = true; SharpDX.Configuration.ThrowOnShaderCompileError = false; #endif // Create factory first. using (var dxgifactory = new DXGI.Factory1()) { var adapterCount = dxgifactory.GetAdapterCount1(); for (var i = 0; i < adapterCount; i++) { var adapter = dxgifactory.GetAdapter1(i); var desc = adapter.Description1; // Don't select the Basic Render Driver adapter. if ((desc.Flags & DXGI.AdapterFlags.Software) != DXGI.AdapterFlags.None) { continue; } var creationFlags = DeviceCreationFlags.BgraSupport /* | DeviceCreationFlags.VideoSupport*/; if (validation) { creationFlags |= DeviceCreationFlags.Debug; } try { D3DDevice = new Device(adapter, creationFlags, s_featureLevels); } catch (SharpDXException) { // Remove debug flag not being supported. creationFlags &= ~DeviceCreationFlags.Debug; D3DDevice = new Device(adapter, creationFlags, s_featureLevels); } Features.VendorId = desc.VendorId; Features.DeviceId = desc.DeviceId; Features.DeviceName = desc.Description; Log.Debug($"Direct3D Adapter ({i}): VID:{desc.VendorId}, PID:{desc.DeviceId} - {desc.Description}"); break; } } FeatureLevel = D3DDevice.FeatureLevel; D3DContext = D3DDevice.ImmediateContext; D3DDevice1 = D3DDevice.QueryInterfaceOrNull <Device1>(); if (D3DDevice1 != null) { D3DContext1 = D3DContext.QueryInterface <DeviceContext1>(); D3DAnnotation = D3DContext.QueryInterface <UserDefinedAnnotation>(); } // Detect multithreading D3DDevice1.CheckThreadingSupport(out _supportsConcurrentResources, out _supportsCommandLists); if (_supportsConcurrentResources && _supportsCommandLists) { Features.Multithreading = true; } // Create queue's GraphicsQueue = new D3D11CommandQueue(this); //ImmediateContext = new D3D11CommandContext(this, Device.ImmediateContext1); _mainSwapchain = new D3D11Swapchain(this, presentationParameters); }
public void Run() { var form = new RenderForm("2d and 3d combined...it's like magic"); form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); }; // DirectX DXGI 1.1 factory var factory1 = new Factory1(); // The 1st graphics adapter var adapter1 = factory1.GetAdapter1(0); // --------------------------------------------------------------------------------------------- // Setup direct 3d version 11. It's context will be used to combine the two elements // --------------------------------------------------------------------------------------------- var description = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch }; Device11 device11; SwapChain swapChain; Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created RenderTargetView renderTargetView; using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTargetView = new RenderTargetView(device11, resource); // setting a viewport is required if you want to actually see anything var context = device11.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTargetView); context.Rasterizer.SetViewports(viewport); // // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device. // // The DirectX10 device will be used to render text onto this texture. // DirectX11 will then draw this texture (blended) onto the screen. // The KeyedMutex flag is required in order to share this resource between the two devices. var textureD3D11 = new Texture2D(device11, new Texture2DDescription { Width = form.ClientSize.Width, Height = form.ClientSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }); // --------------------------------------------------------------------------------------------- // Setup a direct 3d version 10.1 adapter // --------------------------------------------------------------------------------------------- var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); // --------------------------------------------------------------------------------------------- // Setup Direct 2d // --------------------------------------------------------------------------------------------- // Direct2D Factory var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information); // Here we bind the texture we've created on our direct3d11 device through the direct3d10 // to the direct 2d render target.... var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>(); var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var surface = textureD3D10.AsSurface(); var rtp = new RenderTargetProperties { MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied) }; var renderTarget2D = new RenderTarget(factory2D, surface, rtp); var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red); // --------------------------------------------------------------------------------------------------- // Setup the rendering data // --------------------------------------------------------------------------------------------------- // Load Effect. This includes both the vertex and pixel shaders. // Also can include more than one technique. ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile( "effectDx11.fx", "fx_5_0", ShaderFlags.EnableStrictness); var effect = new Effect(device11, shaderByteCode); // create triangle vertex data, making sure to rewind the stream afterward var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f))); verticesTriangle.Position = 0; // create the triangle vertex layout and buffer var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements); var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesTriangle.Close(); // create overlay vertex data, making sure to rewind the stream afterward // Top Left of screen is -1, +1 // Bottom Right of screen is +1, -1 var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true); verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f))); verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0))); verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1))); verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1))); verticesText.Position = 0; // create the overlay vertex layout and buffer var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements); var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesText.Close(); // Think of the shared textureD3D10 as an overlay. // The overlay needs to show the 2d content but let the underlying triangle (or whatever) // show thru, which is accomplished by blending. var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; var blendStateTransparent = new BlendState(device11, bsd); // --------------------------------------------------------------------------------------------------- // Create and tesselate an ellipse // --------------------------------------------------------------------------------------------------- var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f); var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f)); // Populate a PathGeometry from Ellipse tessellation var tesselatedGeometry = new PathGeometry(factory2D); _geometrySink = tesselatedGeometry.Open(); // Force RoundLineJoin otherwise the tesselated looks buggy at line joins _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); // Tesselate the ellipse to our TessellationSink ellipse.Tessellate(1, this); _geometrySink.Close(); // --------------------------------------------------------------------------------------------------- // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface // --------------------------------------------------------------------------------------------------- var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>(); var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>(); // --------------------------------------------------------------------------------------------------- // Main rendering loop // --------------------------------------------------------------------------------------------------- bool first = true; RenderLoop .Run(form, () => { if(first) { form.Activate(); first = false; } // clear the render target to black context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray); // Draw the triangle context.InputAssembler.InputLayout = layoutColor; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0)); context.OutputMerger.BlendState = null; var currentTechnique = effect.GetTechniqueByName("Color"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(3, 0); }; // Draw Ellipse on the shared Texture2D device10Mutex.Acquire(0, 100); renderTarget2D.BeginDraw(); renderTarget2D.Clear(Colors.Black); renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush); renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null); renderTarget2D.EndDraw(); device10Mutex.Release(0); // Draw the shared texture2D onto the screen, blending the 2d content in device11Mutex.Acquire(0, 100); var srv = new ShaderResourceView(device11, textureD3D11); effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv); context.InputAssembler.InputLayout = layoutOverlay; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0)); context.OutputMerger.BlendState = blendStateTransparent; currentTechnique = effect.GetTechniqueByName("Overlay"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(4, 0); } srv.Dispose(); device11Mutex.Release(0); swapChain.Present(0, PresentFlags.None); }); // dispose everything vertexBufferColor.Dispose(); vertexBufferOverlay.Dispose(); layoutColor.Dispose(); layoutOverlay.Dispose(); effect.Dispose(); shaderByteCode.Dispose(); renderTarget2D.Dispose(); swapChain.Dispose(); device11.Dispose(); device10.Dispose(); textureD3D10.Dispose(); textureD3D11.Dispose(); factory1.Dispose(); adapter1.Dispose(); sharedResource.Dispose(); factory2D.Dispose(); surface.Dispose(); solidColorBrush.Dispose(); blendStateTransparent.Dispose(); device10Mutex.Dispose(); device11Mutex.Dispose(); }