/// <summary>
        /// Creates all resources
        /// </summary>
        private void CreateResources(int viewWidth, int viewHeight, DpiScaling dpiScaling, bool forceInit)
        {
            // Calculate the screen size in device independent units
            Size2F scaledScreenSize = new Size2F(
                (float)viewWidth / dpiScaling.ScaleFactorX,
                (float)viewHeight / dpiScaling.ScaleFactorY);

            // Cancel here if the device does not support 2D rendering
            if ((!forceInit) &&
                (!m_device.Supports2D))
            {
                return;
            }

            if (!m_device.IsUsingFallbackMethodFor2D)
            {
                // Create the render target
                using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>())
                {
                    D2D.BitmapProperties1 bitmapProperties = new D2D.BitmapProperties1();
                    bitmapProperties.DpiX          = dpiScaling.DpiX;
                    bitmapProperties.DpiY          = dpiScaling.DpiY;
                    bitmapProperties.BitmapOptions = D2D.BitmapOptions.Target | D2D.BitmapOptions.CannotDraw;
                    bitmapProperties.PixelFormat   = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied);

                    m_renderTargetBitmap = new SharpDX.Direct2D1.Bitmap1(m_device.DeviceContextD2D, dxgiSurface, bitmapProperties);
                    m_renderTarget2D     = m_device.DeviceContextD2D;
                    m_graphics2D         = new Graphics2D(m_device, m_device.DeviceContextD2D, scaledScreenSize);
                }
            }
            else
            {
                using (DXGI.Surface dxgiSurface = m_renderTarget3D.QueryInterface <DXGI.Surface>())
                {
                    m_renderTarget2D = new D2D.RenderTarget(
                        m_device.Core.FactoryD2D,
                        dxgiSurface,
                        new D2D.RenderTargetProperties()
                    {
                        MinLevel    = D2D.FeatureLevel.Level_10,
                        Type        = D2D.RenderTargetType.Default,
                        Usage       = D2D.RenderTargetUsage.ForceBitmapRemoting,
                        PixelFormat = new D2D.PixelFormat(GraphicsHelper.DEFAULT_TEXTURE_FORMAT, D2D.AlphaMode.Premultiplied),
                        DpiX        = dpiScaling.DpiX,
                        DpiY        = dpiScaling.DpiY
                    });
                    m_graphics2D = new Graphics2D(m_device, m_renderTarget2D, scaledScreenSize);
                    return;
                }
            }
        }
Example #2
0
        private void InitializeBackBuffer(D2D.DeviceContext deviceContext, SharpDX.Size2F size)
        {
            this.backBitmap?.Dispose();

            Size2 pixelSize = Helpers.GetPixelSize(size, this.Factory.DesktopDpi);

            var p = new D2D.BitmapProperties1(
                new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                this.Factory.DesktopDpi.Width,
                this.Factory.DesktopDpi.Height,
                D2D.BitmapOptions.Target);

            var desc = new D3D11.Texture2DDescription()
            {
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.Shared,
                Usage             = D3D11.ResourceUsage.Default,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Width             = pixelSize.Width,
                Height            = pixelSize.Height,
            };

            using (var buffer = new D3D11.Texture2D(this.Device, desc))
                using (var surface = buffer.QueryInterface <DXGI.Surface>())
                {
                    this.backBitmap = new D2D.Bitmap1(this.DeviceContext, surface, p);
                }

            this.DeviceContext.Target = this.backBitmap;
        }
Example #3
0
        public virtual void OnRender()
        {
            lock (lockObject)
            {
                if (isVideoStopped)
                {
                    return;
                }

                if (mediaEngineEx != null)
                {
                    long pts;
                    if (mediaEngineEx.OnVideoStreamTick(out pts))
                    {
                        if (OutputVideoTexture != null)
                        {
                            var desc        = OutputVideoTexture.Description;
                            var dxgiSurface = OutputVideoTexture.QueryInterface <SharpDX.DXGI.Surface>();
                            var region      = new SharpDX.Mathematics.Interop.RawRectangle(0, 0, desc.Width, desc.Height);

                            try
                            {
                                // Blit the frame to the supplied rendertarget
                                mediaEngineEx.TransferVideoFrame(dxgiSurface, null, region, null);
                            }
                            catch (Exception)
                            {
                                // This exception can be worked around by using DirectX 9 only (see configuration)
                                Debug.WriteLine("Exception during TransferVideoFrame");
                            }
                        }
                    }
                }
            }
        }
Example #4
0
 private IntPtr GetSharedHandle(D3D11.Texture2D texture)
 {
     using (var resource = texture.QueryInterface <DXGI.Resource>())
     {
         return(resource.SharedHandle);
     }
 }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Получение указателя общего ресурса с текстуры Direct3D11
            /// </summary>
            /// <param name="texture">Текстура Direct3D11</param>
            /// <returns>Указатель на ресурс</returns>
            //---------------------------------------------------------------------------------------------------------
            public static IntPtr GetSharedHandle(Direct3D11.Texture2D texture)
            {
                var resource = texture.QueryInterface <DXGI.Resource>();
                var result   = resource.SharedHandle;

                resource.Dispose();
                return(result);
            }
 /// <summary>
 /// Получает карту битов из текстуры.
 /// </summary>
 /// <param name="texture">Текстура с данными</param>
 /// <param name="renderTarger">Рендер таргет который будет рисовать нашу битмапу</param>
 /// <returns></returns>
 public static SharpDX.Direct2D1.Bitmap GetBitmapFromTexture2D(SharpDX.Direct3D11.Texture2D texture, RenderTarget renderTarger)
 {
     using (var surface = texture.QueryInterface <Surface>())
     {
         var bitmap = new SharpDX.Direct2D1.Bitmap(renderTarger, surface, new SharpDX.Direct2D1.BitmapProperties(new SharpDX.Direct2D1.PixelFormat(
                                                                                                                     Format.R8G8B8A8_UNorm,
                                                                                                                     SharpDX.Direct2D1.AlphaMode.Premultiplied)));
         return(bitmap);
     }
 }
            //---------------------------------------------------------------------------------------------------------
            /// <summary>
            /// Создание текстуры Direct3D11 для ренденинга
            /// </summary>
            //---------------------------------------------------------------------------------------------------------
            private void CreateAndBindTargets()
            {
                mD3DSurface.SetRenderTarget(null);

                XDisposer.SafeDispose(ref mD2DRenderTarget);
                XDisposer.SafeDispose(ref mD3DRenderTarget);

                XDisposer.SafeDispose(ref XDirect2DManager.mD2DDevice);
                XDisposer.SafeDispose(ref XDirect2DManager.mD2DFactory);
                XDisposer.SafeDispose(ref XDirect2DManager.mD2DWriteFactory);
                XDisposer.SafeDispose(ref XDirect2DManager.mD2DImagingFactory);

                var width  = (Int32)Math.Max(ActualWidth, mWidthRenderTargetDip);
                var height = (Int32)Math.Max(ActualHeight, mHeightRenderTargetDip);

                var colordesc = new Direct3D11.Texture2DDescription
                {
                    BindFlags         = Direct3D11.BindFlags.RenderTarget | Direct3D11.BindFlags.ShaderResource,
                    Format            = DXGI.Format.B8G8R8A8_UNorm,
                    Width             = width,
                    Height            = height,
                    MipLevels         = 1,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    Usage             = Direct3D11.ResourceUsage.Default,
                    OptionFlags       = Direct3D11.ResourceOptionFlags.Shared,
                    CpuAccessFlags    = Direct3D11.CpuAccessFlags.None,
                    ArraySize         = 1
                };

                // Создаем текстуру Direct3D11
                mD3DRenderTarget = new Direct3D11.Texture2D(mD3DDevice, colordesc);
                var surface = mD3DRenderTarget.QueryInterface <DXGI.Surface>();

                // Фабрика ресурсов DirectD2
                XDirect2DManager.mD2DFactory = new Direct2D.Factory();
                //XNativeD2DFactory.mD2DDevice = new Direct2D.Device(XNativeD2DFactory.mD2DFactory, XNativeD2DFactory.mDXGIDevice);
                XDirect2DManager.mD2DWriteFactory   = new DirectWrite.Factory(DirectWrite.FactoryType.Shared);
                XDirect2DManager.mD2DImagingFactory = new ImagingFactory();

                // Создаем поверхность отображения DirectD2
                var render_target_properties = new Direct2D.RenderTargetProperties(new Direct2D.PixelFormat(DXGI.Format.Unknown, Direct2D.AlphaMode.Premultiplied));

                render_target_properties.Type  = Direct2D.RenderTargetType.Default;
                render_target_properties.Usage = Direct2D.RenderTargetUsage.None;
                mD2DRenderTarget = new Direct2D.RenderTarget(XDirect2DManager.mD2DFactory, surface, render_target_properties);

                mD3DSurface.SetRenderTarget(mD3DRenderTarget);

                // Определяем область отображения
                mD3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, width, height, 0.0f, 1.0f);

                // Сохраняем
                XDirect2DManager.mD2DRenderTarget = mD2DRenderTarget;
            }
        private void InitializeDevices()
        {
            try
            {
                SwapChainDescription                   = new DXGI.SwapChainDescription();
                SwapChainDescription.BufferCount       = 2;
                SwapChainDescription.SampleDescription = new DXGI.SampleDescription(1, 0);
                SwapChainDescription.SwapEffect        = DXGI.SwapEffect.Discard;
                SwapChainDescription.Usage             = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput;
                SwapChainDescription.IsWindowed        = true;
                SwapChainDescription.ModeDescription   = new DXGI.ModeDescription(GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height, new DXGI.Rational(60, 1), DXGI.Format.B8G8R8A8_UNorm);
                SwapChainDescription.OutputHandle      = GameWindowHandle;

                D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport, featureLevels, SwapChainDescription, out D3DDefaultDevice, out SwapChain);

                DXGI.Factory factory = SwapChain.GetParent <DXGI.Factory>();
                factory.MakeWindowAssociation(GameWindowHandle, DXGI.WindowAssociationFlags.IgnoreAll);

                D3DDevice = D3DDefaultDevice.QueryInterface <D3D11.Device1>();

                Backbuffer       = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(SwapChain, 0);
                RenderTargetView = new D3D11.RenderTargetView(D3DDevice, Backbuffer);
                D3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, GameWindow.Current.WindowParameters.Width, GameWindow.Current.WindowParameters.Height);
                D3DDevice.ImmediateContext.OutputMerger.SetTargets(RenderTargetView);

                DXGIDevice = D3DDevice.QueryInterface <DXGI.Device>();

                D2DFactory       = new D2D1.Factory1(D2D1.FactoryType.MultiThreaded);
                D2DDevice        = new D2D1.Device(D2DFactory, DXGIDevice);
                D2DDeviceContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None);

                RenderTargetSurface        = Backbuffer.QueryInterface <DXGI.Surface>();
                RenderTarget               = new D2D1.RenderTarget(D2DFactory, RenderTargetSurface, new D2D1.RenderTargetProperties(new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Premultiplied)));
                RenderTarget.AntialiasMode = D2D1.AntialiasMode.PerPrimitive;

                // Initialize debug drawings brushes
                DrawingBoundsBrush  = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 1f, 0f));
                CollisionBoxesBrush = new D2D1.SolidColorBrush(RenderTarget, new SharpDX.Color(1f, 0f, 0f));

                RenderFrame = new RenderFrame(RenderTarget);

                Clock = Stopwatch.StartNew();
            }
            catch (Exception ex)
            {
                throw new DeviceInitializationException("Unable to initialize DirectX device!", ex);
            }
        }
Example #9
0
 public SharpDXDevice(Window window)
 {
     this.window = window;
     width = (int)window.ViewportSize.Width;
     height = (int)window.ViewportSize.Height;
     DxDevice.CreateWithSwapChain(DriverType.Hardware,
     #if DEBUG
         DeviceCreationFlags.Debug |
     #endif
         DeviceCreationFlags.BgraSupport,
         CreateSwapChainDescription(), out device, out swapChain);
     direct2DFactory = new D2dFactory();
     backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
     surface = backBuffer.QueryInterface<Surface>();
     RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
     window.ViewportSizeChanged += ResetDeviceToNewViewportSize;
     Screen = new ScreenSpace(window.ViewportSize);
 }
Example #10
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount     = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed        = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect        = DXGI.SwapEffect.Discard,
                    Usage             = DXGI.Usage.RenderTargetOutput,
                    OutputHandle      = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer     = D3D11.Texture2D.FromSwapChain <D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface    = backbuffer.QueryInterface <DXGI.Surface>();

            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
        internal static IDirect3DSurface CreateDirect3DSurfaceFromSharpDXTexture(SharpDX.Direct3D11.Texture2D texture)
        {
            IDirect3DSurface surface = null;

            // Acquire the DXGI interface for the Direct3D surface.
            using (var dxgiSurface = texture.QueryInterface <SharpDX.DXGI.Surface>())
            {
                // Wrap the native device using a WinRT interop object.
                uint hr = CreateDirect3D11SurfaceFromDXGISurface(dxgiSurface.NativePointer, out IntPtr pUnknown);

                if (hr == 0)
                {
                    surface = Marshal.GetObjectForIUnknown(pUnknown) as IDirect3DSurface;
                    Marshal.Release(pUnknown);
                }
            }

            return(surface);
        }
Example #12
0
        private void CreateAndBindTargets()
        {
            var width  = Math.Max((int)ActualWidth, 100);
            var height = Math.Max((int)ActualHeight, 100);

            var renderDesc = new D3D11.Texture2DDescription
            {
                BindFlags         = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource,
                Format            = DXGI.Format.B8G8R8A8_UNorm,
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                SampleDescription = new DXGI.SampleDescription(1, 0),
                Usage             = D3D11.ResourceUsage.Default,
                OptionFlags       = D3D11.ResourceOptionFlags.Shared,
                CpuAccessFlags    = D3D11.CpuAccessFlags.None,
                ArraySize         = 1
            };

            var device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport);

            var renderTarget = new D3D11.Texture2D(device, renderDesc);

            var surface = renderTarget.QueryInterface <DXGI.Surface>();

            var d2DFactory = new D2D.Factory();

            var renderTargetProperties =
                new D2D.RenderTargetProperties(new D2D.PixelFormat(DXGI.Format.Unknown, D2D.AlphaMode.Premultiplied));

            _d2DRenderTarget = new D2D.RenderTarget(d2DFactory, surface, renderTargetProperties);

            SetRenderTarget(renderTarget);

            device.ImmediateContext.Rasterizer.SetViewport(0, 0, (int)ActualWidth, (int)ActualHeight);

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
        public D2D1.RenderTarget Create(D2D1.Factory factory, GDI.Graphics g, Map map)
        {
            //Monitor.Enter(_syncRoot);

            // Dispose the _renderTexture if it is instantiated and not of the required size
            CheckTexture(ref _renderTexture, map.Size);

            // Create a new render texture if one is needed
            if (_renderTexture == null)
            {
                _renderTexture = CreateRenderTargetTexture(_d3d11Device, map.Size.Width, map.Size.Height);
            }

            // Get the surface
            var surface = _renderTexture.QueryInterface <DXGI.Surface>();

            var res = new D2D1.RenderTarget(factory, surface, new D2D1.RenderTargetProperties(
                                                D2D1.RenderTargetType.Hardware, new D2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied),
                                                g.DpiX, g.DpiY, D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT));

            res.BeginDraw();

            return(res);
        }
        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();
        }
Example #15
0
        void EnsureResources(SharpDX.Direct3D11.Device device, Texture2DDescription description, Rectangle captureRegion, ScreenshotRequest request)
        {
            if (_device != null && request.Resize != null && (_resizedRT == null || (_resizedRT.Device.NativePointer != _device.NativePointer || _resizedRT.Description.Width != request.Resize.Value.Width || _resizedRT.Description.Height != request.Resize.Value.Height)))
            {
                // Create/Recreate resources for resizing
                RemoveAndDispose(ref _resizedRT);
                RemoveAndDispose(ref _resizedRTV);
                RemoveAndDispose(ref _saQuad);

                _resizedRT = ToDispose(new Texture2D(_device, new Texture2DDescription() {
                    Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm, // Supports BMP/PNG/etc
                    Height = request.Resize.Value.Height,
                    Width = request.Resize.Value.Width,
                    ArraySize = 1,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                    BindFlags = BindFlags.RenderTarget,
                    MipLevels = 1,
                    Usage = ResourceUsage.Default,
                    OptionFlags = ResourceOptionFlags.None
                }));

                _resizedRTV = ToDispose(new RenderTargetView(_device, _resizedRT));

                _saQuad = ToDispose(new DX11.ScreenAlignedQuadRenderer());
                _saQuad.Initialize(new DX11.DeviceManager(_device));
            }

            // Check if _resolvedRT or _finalRT require creation
            if (_finalRT != null && _finalRT.Device.NativePointer == _device.NativePointer &&
                _finalRT.Description.Height == captureRegion.Height && _finalRT.Description.Width == captureRegion.Width &&
                _resolvedRT != null && _resolvedRT.Description.Height == description.Height && _resolvedRT.Description.Width == description.Width &&
                _resolvedRT.Device.NativePointer == device.NativePointer && _resolvedRT.Description.Format == description.Format
                )
            {
                return;
            }

            RemoveAndDispose(ref _query);
            RemoveAndDispose(ref _resolvedRT);
            RemoveAndDispose(ref _resolvedSharedSRV);
            RemoveAndDispose(ref _finalRT);
            RemoveAndDispose(ref _resolvedRTShared);

            _query = new Query(_device, new QueryDescription()
            {
                Flags = QueryFlags.None,
                Type = QueryType.Event
            });
            _queryIssued = false;

            _resolvedRT = ToDispose(new Texture2D(device, new Texture2DDescription() {
                CpuAccessFlags = CpuAccessFlags.None,
                Format = description.Format, // for multisampled backbuffer, this must be same format
                Height = description.Height,
                Usage = ResourceUsage.Default,
                Width = description.Width,
                ArraySize = 1,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), // Ensure single sample
                BindFlags = BindFlags.ShaderResource,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.SharedKeyedmutex
            }));

            // Retrieve reference to the keyed mutex
            _resolvedRTKeyedMutex = ToDispose(_resolvedRT.QueryInterfaceOrNull<SharpDX.DXGI.KeyedMutex>());

            using (var resource = _resolvedRT.QueryInterface<SharpDX.DXGI.Resource>())
            {
                _resolvedRTShared = ToDispose(_device.OpenSharedResource<Texture2D>(resource.SharedHandle));
                _resolvedRTKeyedMutex_Dev2 = ToDispose(_resolvedRTShared.QueryInterfaceOrNull<SharpDX.DXGI.KeyedMutex>());
            }

            // SRV for use if resizing
            _resolvedSharedSRV = ToDispose(new ShaderResourceView(_device, _resolvedRTShared));

            _finalRT = ToDispose(new Texture2D(_device, new Texture2DDescription()
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                Format = description.Format,
                Height = captureRegion.Height,
                Usage = ResourceUsage.Staging,
                Width = captureRegion.Width,
                ArraySize = 1,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = BindFlags.None,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None
            }));
            _finalRTMapped = false;
        }
Example #16
0
        private void createSwapChain()
        {
            lock (deviceManager.DeviceLock)
            {
                var factory = new DXGI.Factory();

                var description = new DXGI.SwapChainDescription()
                {
                    BufferCount = 1,
                    ModeDescription =
                        new DXGI.ModeDescription(
                            control.ClientSize.Width,
                            control.ClientSize.Height,
                            new DXGI.Rational(60, 1),
                            DXGI.Format.R8G8B8A8_UNorm),
                    IsWindowed = true,
                    SampleDescription = new DXGI.SampleDescription(1, 0),
                    SwapEffect = DXGI.SwapEffect.Discard,
                    Usage = DXGI.Usage.RenderTargetOutput,
                    OutputHandle = control.Handle
                };

                swapChain = new DXGI.SwapChain(factory, deviceContext.Device, description);

                backbuffer = D3D11.Texture2D.FromSwapChain<D3D11.Texture2D>(swapChain, 0);
                backbufferView = new D3D11.RenderTargetView(deviceContext.Device, backbuffer);
            }

            var d2dFactory = deviceManager.Direct2dFactory;
            var surface = backbuffer.QueryInterface<DXGI.Surface>();
            renderTarget = new D2D.RenderTarget(
                d2dFactory,
                surface,
                new D2D.RenderTargetProperties(
                    new D2D.PixelFormat(
                        DXGI.Format.Unknown,
                        D2D.AlphaMode.Premultiplied)));

            renderTarget.AntialiasMode = D2D.AntialiasMode.Aliased;

            createViewport();
        }
Example #17
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            var hr = Direct3DCreate9Ex(D3D_SDK_VERSION, out var direct3D9Ex);

            m_d3dEx = direct3D9Ex;

            var adapterMonitor = direct3D9Ex.GetAdapterMonitor(0);

            m_hWnd = GetDesktopWindow();

            var param = new D3DPRESENT_PARAMETERS
            {
                Windowed = 1,
                Flags    = ((short)D3DPRESENTFLAG.D3DPRESENTFLAG_VIDEO),

                /*
                 * D3DFMT_R8G8B8:表示一个24位像素,从左开始,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_X8R8G8B8:表示一个32位像素,从左开始,8位不用,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_A8R8G8B8:表示一个32位像素,从左开始,8位为ALPHA通道,8位分配给红色,8位分配给绿色,8位分配给蓝色。
                 *
                 * D3DFMT_A16B16G16R16F:表示一个64位浮点像素,从左开始,16位为ALPHA通道,16位分配给蓝色,16位分配给绿色,16位分配给红色。
                 *
                 * D3DFMT_A32B32G32R32F:表示一个128位浮点像素,从左开始,32位为ALPHA通道,32位分配给蓝色,32位分配给绿色,32位分配给红色。
                 */
                //BackBufferFormat = D3DFORMAT.D3DFMT_X8R8G8B8,

                //SwapEffect = D3DSWAPEFFECT.D3DSWAPEFFECT_COPY
                SwapEffect = D3DSWAPEFFECT.D3DSWAPEFFECT_DISCARD,

                hDeviceWindow        = GetDesktopWindow(), // 添加
                PresentationInterval = (int)D3D9.PresentInterval.Default,
            };

            /* The COM pointer to our D3D Device */
            IntPtr dev;

            m_d3dEx.CreateDeviceEx(0, D3DDEVTYPE.D3DDEVTYPE_HAL, m_hWnd,
                                   Direct3D.CreateFlags.D3DCREATE_HARDWARE_VERTEXPROCESSING | Direct3D.CreateFlags.D3DCREATE_MULTITHREADED
                                   | Direct3D.CreateFlags.D3DCREATE_FPU_PRESERVE,
                                   ref param, IntPtr.Zero, out dev);

            m_device = (IDirect3DDevice9)Marshal.GetObjectForIUnknown(dev);
            // 只是减少引用计数而已,现在换成 m_device 了
            Marshal.Release(dev);

            hr = m_device.TestCooperativeLevel();
            var pDevice = dev;

            D3D11.Texture2D d3d11Texture2D = CreateRenderTarget();
            //SetRenderTarget(d3d11Texture2D);

            var format = TranslateFormat(TranslateFormat(d3d11Texture2D));

            var dxgiResource  = d3d11Texture2D.QueryInterface <DXGI.Resource>();
            var pSharedHandle = dxgiResource.SharedHandle;

            hr = m_device.CreateTexture(ImageWidth,
                                        ImageHeight,
                                        1,
                                        1,
                                        format,
                                        0,
                                        out m_privateTexture,
                                        ref pSharedHandle);

            hr = m_privateTexture.GetSurfaceLevel(0, out m_privateSurface);

            var backBuffer = Marshal.GetIUnknownForObject(m_privateSurface);

            var surface        = new D3D9.Surface(backBuffer);
            var queryInterface = surface.QueryInterface <D3D9.Surface>();
            //// 只是减少引用计数而已
            //Marshal.Release(backBuffer);

            //hr = m_device.SetTexture(0, m_privateTexture);

            var texturePtr = Marshal.GetIUnknownForObject(m_privateTexture);

            //Marshal.Release(texturePtr);

            //var byteList = new byte[32 * 10];
            //for (int i = 0; i < byteList.Length; i++)
            //{
            //    byteList[i] = (byte)i;
            //}

            //unsafe
            //{
            //    fixed (void* p = byteList)
            //    {
            //        Buffer.MemoryCopy(p, (void*) texturePtr,0,320);
            //    }
            //}

            //var d2dFactory = new SharpDX.Direct2D1.Factory();

            //Texture2D backBufferTexture2D = new Texture2D(texturePtr);
            //var d2dRenderTarget = new RenderTarget(d2dFactory, new SharpDX.DXGI.Surface(backBuffer),
            //    new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown,AlphaMode.Premultiplied)));

            //d2dRenderTarget.BeginDraw();
            //d2dRenderTarget.Clear(new RawColor4(1,0,0.5f,1));
            //d2dRenderTarget.EndDraw();

            D3DImage.Lock();
            D3DImage.SetBackBuffer(D3DResourceType.IDirect3DSurface9, backBuffer, true);
            D3DImage.Unlock();

            Render();

            string s             = "123";
            var    stringBuilder = new StringBuilder(s);

            stringBuilder.Replace("%", "%25").Replace("#", "%23");
            stringBuilder.Insert(0, "123");
            stringBuilder.Insert("123".Length, "#");
        }
Example #18
0
        private void ResetDeviceToNewViewportSize(Size newSizeInPixel)
        {
            backBuffer.Dispose();
            surface.Dispose();
            RenderTarget.Dispose();

            width = (int)newSizeInPixel.Width;
            height = (int)newSizeInPixel.Height;
            swapChain.ResizeBuffers(BackBufferCount, width, height, BackBufferFormat, SwapChainFlags.None);
            backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);
            surface = backBuffer.QueryInterface<Surface>();
            RenderTarget = new RenderTarget(direct2DFactory, surface, defaultRenderTargetProperties);
            Screen = new ScreenSpace(newSizeInPixel);
        }
Example #19
0
        private void CreateAndBindTargets() {
            d3DSurface.SetRenderTarget( null );

            Disposer.SafeDispose( ref d2DRenderTarget );
            Disposer.SafeDispose( ref d2DFactory );
            Disposer.SafeDispose( ref renderTarget );

            var width  = Math.Max((int)ActualWidth , 100);
            var height = Math.Max((int)ActualHeight, 100);

            var renderDesc = new Texture2DDescription {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Format = Format.B8G8R8A8_UNorm,
                Width = width,
                Height = height,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                OptionFlags = ResourceOptionFlags.Shared,
                CpuAccessFlags = CpuAccessFlags.None,
                ArraySize = 1
            };

            renderTarget = new Texture2D( device, renderDesc );

            var surface = renderTarget.QueryInterface<Surface>();

            d2DFactory = new SharpDX.Direct2D1.Factory();
            var rtp = new RenderTargetProperties(new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            d2DRenderTarget = new RenderTarget( d2DFactory, surface, rtp );
            resCache.RenderTarget = d2DRenderTarget;

            d3DSurface.SetRenderTarget( renderTarget );

            device.ImmediateContext.Rasterizer.SetViewport( 0, 0, width, height, 0.0f, 1.0f );
        }