Exemplo n.º 1
0
        public SharpDX.Direct2D1.Bitmap GetD2DBitmap(SharpDX.Direct2D1.DeviceContext dc)
        {
            BitmapSource src = Frame;

            // PixelFormat settings/conversion
            if (src.Format != System.Windows.Media.PixelFormats.Bgra32)
            {
                // Convert BitmapSource
                FormatConvertedBitmap fcb = new FormatConvertedBitmap();
                fcb.BeginInit();
                fcb.Source            = src;
                fcb.DestinationFormat = PixelFormats.Bgra32;
                fcb.EndInit();
                src = fcb;
            }

            if (src.PixelHeight > _maxImageSize || src.PixelWidth > _maxImageSize)
            {
                double            scale = (src.PixelWidth > src.PixelHeight) ? _maxImageSize / src.PixelWidth : _maxImageSize / src.PixelHeight;
                TransformedBitmap tb    = new TransformedBitmap();
                tb.BeginInit();
                tb.Source    = src;
                tb.Transform = new ScaleTransform(scale, scale);
                tb.EndInit();
                src = tb;
            }

            SharpDX.Direct2D1.Bitmap retval = null;
            GCHandle pinnedArray            = GCHandle.Alloc(null);

            try
            {
                int    stride     = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8;
                int    bufferSize = stride * src.PixelHeight;
                byte[] buffer     = new byte[bufferSize];
                src.CopyPixels(System.Windows.Int32Rect.Empty, buffer, stride, 0);
                pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned);
                using (SharpDX.DataStream datastream = new SharpDX.DataStream(pinnedArray.AddrOfPinnedObject(), bufferSize, true, false))
                {
                    var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height);
                    retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1);
                }
            }
            catch
            {
            }
            finally
            {
                if (pinnedArray.IsAllocated)
                {
                    pinnedArray.Free();
                }
            }
            return(retval);
        }
        /// <inveritdoc/>
        public override void RenderAll()
        {
            SurfaceViewData viewData;

            var regionToDraw = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);

            // Unlike other targets, we can only get the DXGI surface to render to
            // just before rendering.

            SharpDX.Mathematics.Interop.RawPoint rawPoint;

            using (var surface = surfaceImageSourceNative.BeginDraw(regionToDraw, out rawPoint))
            {
                position = rawPoint;

                // Cache DXGI surface in order to avoid recreate all render target view, depth stencil...etc.
                // Is it the right way to do it?
                // It seems that ISurfaceImageSourceNative.BeginDraw is returning 2 different DXGI surfaces
                if (!mapSurfaces.TryGetValue(surface.NativePointer, out viewData))
                {
                    viewData = new SurfaceViewData();
                    mapSurfaces.Add(surface.NativePointer, viewData);

                    // Allocate a new renderTargetView if size is different
                    // Cache the rendertarget dimensions in our helper class for convenient use.
                    viewData.BackBuffer = Collect(surface.QueryInterface <SharpDX.Direct3D11.Texture2D>());
                    {
                        var desc = viewData.BackBuffer.Description;
                        viewData.RenderTargetSize = new Size(desc.Width, desc.Height);
                        viewData.RenderTargetView = Collect(new SharpDX.Direct3D11.RenderTargetView(DeviceManager.DeviceDirect3D, viewData.BackBuffer));
                    }

                    // Create a descriptor for the depth/stencil buffer.
                    // Allocate a 2-D surface as the depth/stencil buffer.
                    // Create a DepthStencil view on this surface to use on bind.
                    // TODO: Recreate a DepthStencilBuffer is inefficient. We should only have one depth buffer. Shared depth buffer?
                    using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(DeviceManager.DeviceDirect3D, new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = (int)viewData.RenderTargetSize.Width,
                        Height = (int)viewData.RenderTargetSize.Height,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
                    }))
                        viewData.DepthStencilView = Collect(new SharpDX.Direct3D11.DepthStencilView(DeviceManager.DeviceDirect3D, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription()
                        {
                            Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D
                        }));

                    // Now we set up the Direct2D render target bitmap linked to the swapchain.
                    // Whenever we render to this bitmap, it will be directly rendered to the
                    // swapchain associated with the window.
                    var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                        new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                        DeviceManager.Dpi,
                        DeviceManager.Dpi,
                        SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

                    // Direct2D needs the dxgi version of the backbuffer surface pointer.
                    // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
                    viewData.BitmapTarget = Collect(new SharpDX.Direct2D1.Bitmap1(DeviceManager.ContextDirect2D, surface, bitmapProperties));

                    // Create a viewport descriptor of the full window size.
                    viewData.Viewport = new SharpDX.ViewportF(position.X, position.Y, (float)viewData.RenderTargetSize.Width - position.X, (float)viewData.RenderTargetSize.Height - position.Y, 0.0f, 1.0f);
                }

                backBuffer         = viewData.BackBuffer;
                renderTargetView   = viewData.RenderTargetView;
                depthStencilView   = viewData.DepthStencilView;
                RenderTargetBounds = new Rect(viewData.Viewport.X, viewData.Viewport.Y, viewData.Viewport.Width, viewData.Viewport.Height);
                bitmapTarget       = viewData.BitmapTarget;

                DeviceManager.ContextDirect2D.Target = viewData.BitmapTarget;

                // Set the current viewport using the descriptor.
                DeviceManager.ContextDirect3D.Rasterizer.SetViewport(viewData.Viewport);

                // Perform the actual rendering of this target
                base.RenderAll();
            }

            surfaceImageSourceNative.EndDraw();
        }
Exemplo n.º 3
0
        protected virtual void CreateSizeDependentResources(TargetBase renderBase)
        {
            var d3dDevice = DeviceManager.DeviceDirect3D;
            var d3dContext = DeviceManager.ContextDirect3D;
            var d2dContext = DeviceManager.ContextDirect2D;

            d2dContext.Target = null;
            SafeDispose(ref renderTargetView);
            SafeDispose(ref depthStencilView);
            SafeDispose(ref bitmapTarget);

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain
                using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
                using (var dxgiAdapter = dxgiDevice2.Adapter)
                using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                {
                    swapChain = ToDispose(CreateSwapChain(dxgiFactory2, d3dDevice, desc));

                    // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                    // latency and ensures that the application will only render after each VSync, minimizing
                    // power consumption.
                    dxgiDevice2.MaximumFrameLatency = 1;
                }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            using (var backBuffer = SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(swapChain, 0))
            {
                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer));

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = backBuffer.Description;
                RenderTargetBounds = new Windows.Foundation.Rect(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D }));

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.Direct3D11.Viewport((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewports(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Exemplo n.º 4
0
        protected virtual void CreateSizeDependentResources(object sender, RenderEventArgs e)
        {
            var  d3dDevice       = DirectX.Direct3D.Device;
            var  d3dContext      = DirectX.Direct3D.Context;
            var  d2dContext      = DirectX.Direct2D.Context;
            bool isStereoEnabled = deviceManager.Settings.IsStereo;

            Cleanup();

            // If the swap chain already exists, resize it.
            if (swapChain != null)
            {
                swapChain.ResizeBuffers(2, Width, Height, SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.DXGI.SwapChainFlags.None);
            }

            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // Creates the swap chain
                using (var dxgiDevice2 = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                        {
                            swapChain = ToDispose(CreateSwapChain(dxgiFactory2, d3dDevice, desc));

                            // Ensure that DXGI does not queue more than one frame at a time. This both reduces
                            // latency and ensures that the application will only render after each VSync, minimizing
                            // power consumption.
                            dxgiDevice2.MaximumFrameLatency = 1;
                        }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            backBuffer = ToDispose(SharpDX.Direct3D11.Texture2D.FromSwapChain <SharpDX.Direct3D11.Texture2D>(swapChain, 0));
            {
                RenderTargetViewDescription rtvDescription = new RenderTargetViewDescription()
                {
                    Dimension      = RenderTargetViewDimension.Texture2DArray,
                    Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                    Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource()
                    {
                        MipSlice = 0, FirstArraySlice = 0, ArraySize = 1
                    }
                };

                // Create a view interface on the rendertarget to use on bind.
                renderTargetView = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer, rtvDescription));

                if (IsStereoEnabled)
                {
                    RenderTargetViewDescription rtvDescriptionRight = new RenderTargetViewDescription()
                    {
                        Dimension      = RenderTargetViewDimension.Texture2DArray,
                        Format         = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                        Texture2DArray = new RenderTargetViewDescription.Texture2DArrayResource()
                        {
                            MipSlice = 0, FirstArraySlice = 1, ArraySize = 1
                        }
                    };

                    renderTargetViewRight = ToDispose(new SharpDX.Direct3D11.RenderTargetView(d3dDevice, BackBuffer, rtvDescriptionRight));
                }

                // Cache the rendertarget dimensions in our helper class for convenient use.
                var backBufferDesc = BackBuffer.Description;
                RenderTargetBounds = new Windows.Foundation.Rect(0, 0, backBufferDesc.Width, backBufferDesc.Height);
            }

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D surface as the depth/stencil buffer.
            // Create a DepthStencil view on this surface to use on bind.
            using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(d3dDevice, new SharpDX.Direct3D11.Texture2DDescription()
            {
                Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = (int)RenderTargetSize.Width,
                Height = (int)RenderTargetSize.Height,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
            }))
                depthStencilView = ToDispose(new SharpDX.Direct3D11.DepthStencilView(d3dDevice, depthBuffer,
                                                                                     new SharpDX.Direct3D11.DepthStencilViewDescription()
                {
                    Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D
                }));

            // Create a viewport descriptor of the full window size.
            var viewport = new SharpDX.ViewportF((float)RenderTargetBounds.X, (float)RenderTargetBounds.Y, (float)RenderTargetBounds.Width, (float)RenderTargetBounds.Height, 0.0f, 1.0f);

            // Set the current viewport using the descriptor.
            d3dContext.Rasterizer.SetViewport(viewport);

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                deviceManager.Dpi,
                deviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            if (IsStereoEnabled)
            {
                using (var dxgiBackBuffer = swapChain.GetBackBuffer <SharpDX.DXGI.Resource1>(0))
                {
                    using (var dxgiSurface = new Surface2(dxgiBackBuffer, 0))
                        bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiSurface, bitmapProperties));
                    using (var dxgiSurface = new Surface2(dxgiBackBuffer, 1))
                        bitmapTargetRight = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiSurface, bitmapProperties));
                }
            }
            else
            {
                using (var dxgiBackBuffer = swapChain.GetBackBuffer <SharpDX.DXGI.Surface2>(0))
                    bitmapTarget = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));
            }
            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
        /// <inveritdoc/>
        public override void RenderAll()
        {
            SurfaceViewData viewData = null;

            var regionToDraw = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight);

            // Unlike other targets, we can only get the DXGI surface to render to
            // just before rendering.
            using (var surface = surfaceImageSourceNative.BeginDraw(regionToDraw, out position))
            {
                // Cache DXGI surface in order to avoid recreate all render target view, depth stencil...etc.
                // Is it the right way to do it?
                // It seems that ISurfaceImageSourceNative.BeginDraw is returning 2 different DXGI surfaces (when the application is in foreground)
                // or different DXGI surfaces (when the application is in background).
                foreach (var surfaceViewData in viewDatas)
                {
                    if (surfaceViewData.SurfacePointer == surface.NativePointer)
                    {
                        viewData = surfaceViewData;
                        break;
                    }
                }

                if (viewData == null)
                {
                    viewData = viewDatas[nextViewDataIndex];
                    nextViewDataIndex = (nextViewDataIndex + 1) % viewDatas.Length;

                    // Make sure that previous was disposed.
                    viewData.Dispose();
                    viewData.SurfacePointer = surface.NativePointer;

                    // Allocate a new renderTargetView if size is different
                    // Cache the rendertarget dimensions in our helper class for convenient use.
                    viewData.BackBuffer = surface.QueryInterface<SharpDX.Direct3D11.Texture2D>();
                    {
                        var desc = viewData.BackBuffer.Description;
                        viewData.RenderTargetSize = new Size(desc.Width, desc.Height);
                        viewData.RenderTargetView = new SharpDX.Direct3D11.RenderTargetView(DeviceManager.DeviceDirect3D, viewData.BackBuffer);
                    }

                    // Create a descriptor for the depth/stencil buffer.
                    // Allocate a 2-D surface as the depth/stencil buffer.
                    // Create a DepthStencil view on this surface to use on bind.
                    // TODO: Recreate a DepthStencilBuffer is inefficient. We should only have one depth buffer. Shared depth buffer?
                    using (var depthBuffer = new SharpDX.Direct3D11.Texture2D(DeviceManager.DeviceDirect3D, new SharpDX.Direct3D11.Texture2DDescription()
                    {
                        Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
                        ArraySize = 1,
                        MipLevels = 1,
                        Width = (int)viewData.RenderTargetSize.Width,
                        Height = (int)viewData.RenderTargetSize.Height,
                        SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                        BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
                    }))
                        viewData.DepthStencilView = new SharpDX.Direct3D11.DepthStencilView(DeviceManager.DeviceDirect3D, depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D });

                    // Now we set up the Direct2D render target bitmap linked to the swapchain. 
                    // Whenever we render to this bitmap, it will be directly rendered to the 
                    // swapchain associated with the window.
                    var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                        new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                        DeviceManager.Dpi,
                        DeviceManager.Dpi,
                        SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

                    // Direct2D needs the dxgi version of the backbuffer surface pointer.
                    // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
                    viewData.BitmapTarget = new SharpDX.Direct2D1.Bitmap1(DeviceManager.ContextDirect2D, surface, bitmapProperties);

                    // Create a viewport descriptor of the full window size.
                    viewData.Viewport = new SharpDX.ViewportF(position.X, position.Y, (float)viewData.RenderTargetSize.Width - position.X, (float)viewData.RenderTargetSize.Height - position.Y, 0.0f, 1.0f);
                }

                backBuffer = viewData.BackBuffer;
                renderTargetView = viewData.RenderTargetView;
                depthStencilView = viewData.DepthStencilView;
                RenderTargetBounds = new Rect(viewData.Viewport.X, viewData.Viewport.Y, viewData.Viewport.Width, viewData.Viewport.Height);
                bitmapTarget = viewData.BitmapTarget;

                DeviceManager.ContextDirect2D.Target = viewData.BitmapTarget;

                // Set the current viewport using the descriptor.
                DeviceManager.ContextDirect3D.Rasterizer.SetViewports(viewData.Viewport);

                // Perform the actual rendering of this target
                base.RenderAll();
            }

            surfaceImageSourceNative.EndDraw();
        }
Exemplo n.º 6
0
        void InitText(SwapChain3 tempSwapChain)
        {
            init       = true;
            device     = tempSwapChain.GetDevice <SharpDX.Direct3D11.Device1>();
            d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>();
            var texture2d = tempSwapChain.GetBackBuffer <Texture2D>(0);

            SharpDX.DXGI.Device2  dxgiDevice2  = device.QueryInterface <SharpDX.DXGI.Device2>();
            SharpDX.DXGI.Adapter  dxgiAdapter  = dxgiDevice2.Adapter;
            SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>();

            SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2);
            d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None);

            SharpDX.Direct2D1.BitmapProperties1 properties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                                  SharpDX.Direct2D1.AlphaMode.Premultiplied),
                96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            Surface backBuffer = tempSwapChain.GetBackBuffer <Surface>(0);

            d2dTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, new Size2(800, 600), properties);

            solidBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Coral);

            // Create a linear gradient brush.
            // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to,
            // NOT the geometry we will apply the brush.
            linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(d2dContext, new SharpDX.Direct2D1.LinearGradientBrushProperties()
            {
                StartPoint = new Vector2(50, 0),
                EndPoint   = new Vector2(450, 0),
            },
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Blue,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Green,
                    Position = 1,
                }
            }));

            SharpDX.Direct2D1.RadialGradientBrushProperties rgb = new SharpDX.Direct2D1.RadialGradientBrushProperties()
            {
                Center  = new Vector2(250, 525),
                RadiusX = 100,
                RadiusY = 100,
            };
            // Create a radial gradient brush.
            // The center is specified in absolute coordinates, too.
            radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(d2dContext, ref rgb
                                                                            ,
                                                                            new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[]
            {
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Yellow,
                    Position = 0,
                },
                new SharpDX.Direct2D1.GradientStop()
                {
                    Color    = Color.Red,
                    Position = 1,
                }
            }));
        }
Exemplo n.º 7
0
 /// <summary>
 /// Creates an <see cref="SharpDX.Direct2D1.Bitmap"/> whose data is shared with another resource.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="surface">An <see cref="SharpDX.DXGI.Surface"/> that contains the data to share with the new ID2D1Bitmap. For more information, see the Remarks section.</param>
 /// <param name="bitmapProperties">The pixel format  and DPI of the bitmap to create . The <see cref="SharpDX.DXGI.Format"/> portion of the pixel format  must match the <see cref="SharpDX.DXGI.Format"/> of data or the method will fail, but the alpha modes don't have to match. To prevent a  mismatch, you can pass NULL or the value obtained from the {{D2D1::PixelFormat}} helper function. The DPI settings do not have to match those of data. If both dpiX and dpiY are  0.0f, the default DPI, 96, is used.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromDxgiSurface([In] IDXGISurface* surface,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap1)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Surface surface, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmapFromDxgiSurface(surface, bitmapProperties, this);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="dataStream">A pointer to the memory location of the image data, or NULL to create an uninitialized bitmap.</param>
 /// <param name="pitch">The byte count of each scanline, which is equal to (the image width in pixels * the number of bytes per pixel) + memory padding. If srcData is NULL, this value is ignored. (Note that pitch is also sometimes called stride.)</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size, DataStream dataStream, int pitch, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : base(IntPtr.Zero)
 {
     deviceContext.CreateBitmap(size, dataStream == null ? IntPtr.Zero : dataStream.PositionPointer, pitch, bitmapProperties, this);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Creates a Direct2D bitmap from a pointer to in-memory source data.
 /// </summary>
 /// <param name="deviceContext">an instance of <see cref = "SharpDX.Direct2D1.RenderTarget" /></param>
 /// <param name="size">The dimension of the bitmap to create in pixels.</param>
 /// <param name="bitmapProperties">The pixel format and dots per inch (DPI) of the bitmap to create.</param>
 /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmap([In] D2D_SIZE_U size,[In, Buffer, Optional] const void* sourceData,[In] unsigned int pitch,[In] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out, Fast] ID2D1Bitmap1** bitmap)</unmanaged>
 public Bitmap1(DeviceContext deviceContext, Size2 size, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
     : this(deviceContext, size, null, 0, bitmapProperties)
 {
 }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a Bitmap from a WIC bitmap.
        /// </summary>
        /// <param name="deviceContext">The render target.</param>
        /// <param name="wicBitmap">The WIC bitmap.</param>
        /// <param name="bitmapProperties">The bitmap properties.</param>
        /// <returns></returns>
        /// <unmanaged>HRESULT ID2D1DeviceContext::CreateBitmapFromWicBitmap([In] IWICBitmapSource* wicBitmapSource,[In, Optional] const D2D1_BITMAP_PROPERTIES1* bitmapProperties,[Out] ID2D1Bitmap1** bitmap)</unmanaged>
        public static Bitmap1 FromWicBitmap(DeviceContext deviceContext, WIC.BitmapSource wicBitmap, SharpDX.Direct2D1.BitmapProperties1 bitmapProperties)
        {
            Bitmap1 bitmap;

            deviceContext.CreateBitmapFromWicBitmap(wicBitmap, bitmapProperties, out bitmap);
            return(bitmap);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Create size dependent resources, in this case the swap chain and render targets
        /// </summary>
        /// <param name="app"></param>
        protected virtual void CreateSizeDependentResources(D3DApplicationBase app)
        {
            // Retrieve references to device and context
            var device  = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;
            // Retrieve Direct2D context (for use with text rendering etc)
            var d2dContext = DeviceManager.Direct2DContext;

            // Before the swapchain can resize all the buffers must be released
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _depthStencilView);
            RemoveAndDispose(ref _depthBuffer);
            RemoveAndDispose(ref _bitmapTarget);
            d2dContext.Target = null;

            #region Initialize Direct3D swap chain and render target

            // If the swap chain already exists, resize it.
            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description1.BufferCount,
                    Width,
                    Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Rather than create a new DXGI Factory we should reuse
                // the one that has been used internally to create the device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // access the adapter used for that device and then create the swap chain
                using (var dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>())
                    using (var dxgiAdapter = dxgiDevice2.Adapter)
                        using (var dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>())
                            using (var output = dxgiAdapter.Outputs.First())
                            {
                                // The CreateSwapChain method is used so we can descend
                                // from this class and implement a swapchain for a desktop
                                // or a Windows 8 AppStore app
                                _swapChain = ToDispose(CreateSwapChain(dxgiFactory2, device, desc));

#if !NETFX_CORE
                                // Retrieve the list of supported display modes
                                DisplayModeList = output.GetDisplayModeList(desc.Format, DisplayModeEnumerationFlags.Scaling);
#endif
                            }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            BackBuffer = ToDispose(Texture2D.FromSwapChain <Texture2D>(_swapChain, 0));
            // Create a view interface on the rendertarget to use on bind.
            RenderTargetView = ToDispose(new RenderTargetView(device, BackBuffer));

            // Cache the rendertarget dimensions in our helper class for convenient use.
            var backBufferDesc = BackBuffer.Description;
            RenderTargetBounds = new SharpDX.Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height);

            // Create a viewport descriptor of the render size.
            this.Viewport = new SharpDX.ViewportF(
                (float)RenderTargetBounds.X,
                (float)RenderTargetBounds.Y,
                (float)RenderTargetBounds.Width,
                (float)RenderTargetBounds.Height,
                0.0f,   // min depth
                1.0f);  // max depth

            // Set the current viewport for the rasterizer.
            context.Rasterizer.SetViewport(Viewport);

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D texture as the depth/stencil buffer.
            // Create a DSV to use on bind.
            this.DepthBuffer = ToDispose(new Texture2D(device, new Texture2DDescription()
            {
                Format            = SharpDX.DXGI.Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = RenderTargetSize.Width,
                Height            = RenderTargetSize.Height,
                SampleDescription = SwapChain.Description.SampleDescription,
                BindFlags         = BindFlags.DepthStencil,
            }));
            this.DepthStencilView = ToDispose(
                new DepthStencilView(
                    device,
                    DepthBuffer,
                    new DepthStencilViewDescription()
            {
                Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D
            }));

            // Set the OutputMerger targets
            context.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            #endregion

            #region Initialize Direct2D render target

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(_swapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <SharpDX.DXGI.Surface>(0))
                BitmapTarget2D = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;

            #endregion
        }
        /// <summary>
        /// Create size dependent resources, in this case the swap chain and render targets
        /// </summary>
        /// <param name="app"></param>
        protected virtual void CreateSizeDependentResources(D3DApplicationBase app)
        {
            // Retrieve references to device and context
            var device = DeviceManager.Direct3DDevice;
            var context = DeviceManager.Direct3DContext;
            // Retrieve Direct2D context (for use with text rendering etc)
            var d2dContext = DeviceManager.Direct2DContext;

            // Before the swapchain can resize all the buffers must be released
            RemoveAndDispose(ref _backBuffer);
            RemoveAndDispose(ref _renderTargetView);
            RemoveAndDispose(ref _depthStencilView);
            RemoveAndDispose(ref _depthBuffer);
            RemoveAndDispose(ref _bitmapTarget);
            d2dContext.Target = null;

            #region Initialize Direct3D swap chain and render target

            // If the swap chain already exists, resize it.
            if (_swapChain != null)
            {
                _swapChain.ResizeBuffers(
                    _swapChain.Description1.BufferCount,
                    Width,
                    Height,
                    _swapChain.Description.ModeDescription.Format,
                    _swapChain.Description.Flags);
            }
            // Otherwise, create a new one.
            else
            {
                // SwapChain description
                var desc = CreateSwapChainDescription();

                // Rather than create a new DXGI Factory we should reuse
                // the one that has been used internally to create the device

                // First, retrieve the underlying DXGI Device from the D3D Device.
                // access the adapter used for that device and then create the swap chain
                using (var dxgiDevice2 = device.QueryInterface<SharpDX.DXGI.Device2>())
                using (var dxgiAdapter = dxgiDevice2.Adapter)
                using (var dxgiFactory2 = dxgiAdapter.GetParent<SharpDX.DXGI.Factory2>())
                using (var output = dxgiAdapter.Outputs.First())
                {
                    // The CreateSwapChain method is used so we can descend
                    // from this class and implement a swapchain for a desktop
                    // or a Windows 8 AppStore app
                    _swapChain = ToDispose(CreateSwapChain(dxgiFactory2, device, desc));

            #if !NETFX_CORE
                    // Retrieve the list of supported display modes
                    DisplayModeList = output.GetDisplayModeList(desc.Format, DisplayModeEnumerationFlags.Scaling);
            #endif
                }
            }

            // Obtain the backbuffer for this window which will be the final 3D rendertarget.
            BackBuffer = ToDispose(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0));
            // Create a view interface on the rendertarget to use on bind.
            RenderTargetView = ToDispose(new RenderTargetView(device, BackBuffer));

            // Cache the rendertarget dimensions in our helper class for convenient use.
            var backBufferDesc = BackBuffer.Description;
            RenderTargetBounds = new SharpDX.Rectangle(0, 0, backBufferDesc.Width, backBufferDesc.Height);

            // Create a viewport descriptor of the render size.
            this.Viewport = new SharpDX.ViewportF(
                (float)RenderTargetBounds.X,
                (float)RenderTargetBounds.Y,
                (float)RenderTargetBounds.Width,
                (float)RenderTargetBounds.Height,
                0.0f,   // min depth
                1.0f);  // max depth

            // Set the current viewport for the rasterizer.
            context.Rasterizer.SetViewport(Viewport);

            // Create a descriptor for the depth/stencil buffer.
            // Allocate a 2-D texture as the depth/stencil buffer.
            // Create a DSV to use on bind.
            this.DepthBuffer = ToDispose(new Texture2D(device, new Texture2DDescription()
                {
                    Format = SharpDX.DXGI.Format.D32_Float_S8X24_UInt,
                    ArraySize = 1,
                    MipLevels = 1,
                    Width = RenderTargetSize.Width,
                    Height = RenderTargetSize.Height,
                    SampleDescription = SwapChain.Description.SampleDescription,
                    BindFlags = BindFlags.DepthStencil,
                }));
            this.DepthStencilView = ToDispose(
                new DepthStencilView(
                    device,
                    DepthBuffer,
                    new DepthStencilViewDescription()
                    {
                        Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D
                    }));

            // Set the OutputMerger targets
            context.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            #endregion

            #region Initialize Direct2D render target

            // Now we set up the Direct2D render target bitmap linked to the swapchain.
            // Whenever we render to this bitmap, it will be directly rendered to the
            // swapchain associated with the window.
            var bitmapProperties = new SharpDX.Direct2D1.BitmapProperties1(
                new SharpDX.Direct2D1.PixelFormat(_swapChain.Description.ModeDescription.Format, SharpDX.Direct2D1.AlphaMode.Premultiplied),
                DeviceManager.Dpi,
                DeviceManager.Dpi,
                SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw);

            // Direct2D needs the dxgi version of the backbuffer surface pointer.
            // Get a D2D surface from the DXGI back buffer to use as the D2D render target.
            using (var dxgiBackBuffer = _swapChain.GetBackBuffer<SharpDX.DXGI.Surface>(0))
                BitmapTarget2D = ToDispose(new SharpDX.Direct2D1.Bitmap1(d2dContext, dxgiBackBuffer, bitmapProperties));

            // So now we can set the Direct2D render target.
            d2dContext.Target = BitmapTarget2D;

            // Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
            d2dContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;

            #endregion
        }