public void Close()
            {
                deviceReady = false;

                if (screenTexture != null && !screenTexture.IsDisposed)
                {
                    screenTexture.Dispose();
                    screenTexture = null;
                }

                if (screenTarget != null && !screenTarget.IsDisposed)
                {
                    screenTarget.Dispose();
                    screenTarget = null;
                }

                if (duplTexture != null && !duplTexture.IsDisposed)
                {
                    duplTexture.Dispose();
                    duplTexture = null;
                }

                if (deskDupl != null && !deskDupl.IsDisposed)
                {
                    deskDupl.Dispose();
                    deskDupl = null;
                }

                if (cursorInfo != null)
                {
                    cursorInfo.Dispose();
                    cursorInfo = null;
                }
            }
 internal void ReleaseDevices()
 {
     IsRendererSuppressed = true;
     RenderTarget.Dispose();
     Backbuffer.Dispose();
     RenderTargetSurface.Dispose();
     RenderTargetView.Dispose();
     D2DDeviceContext.Dispose();
     D2DDevice.Dispose();
     D2DFactory.Dispose();
     DXGIDevice.Dispose();
     D3DDevice.Dispose();
     D3DDefaultDevice.Dispose();
     SwapChain.Dispose();
     SwapChain           = null;
     RenderTarget        = null;
     RenderTargetSurface = null;
     Backbuffer          = null;
     RenderTargetView    = null;
     D2DDeviceContext    = null;
     D2DFactory          = null;
     D2DDevice           = null;
     DXGIDevice          = null;
     D3DDevice           = null;
     D3DDefaultDevice    = null;
 }
Exemplo n.º 3
0
        /// <summary>
        /// Converts rendered image to bitmap
        /// </summary>
        /// <returns></returns>
        private D2D1.BitmapRenderTarget RenderBitmap()
        {
            using (var textureToBitmap = Texture2D.FromSwapChain <Texture2D>(_swapChain, 0)) {
                using (var surface = textureToBitmap.QueryInterface <Surface>()) {
                    using (D2D1.Factory factory = new D2D1.Factory1()) {
                        var target = new D2D1.RenderTarget(
                            factory,
                            surface,
                            new D2D1.RenderTargetProperties(
                                new D2D1.PixelFormat(Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Ignore)
                                )
                            );

                        D2D1.BitmapRenderTarget tes = null;

                        tes = new D2D1.BitmapRenderTarget(
                            target,
                            D2D1.CompatibleRenderTargetOptions.None,
                            new D2D1.PixelFormat(
                                Format.B8G8R8A8_UNorm,
                                D2D1.AlphaMode.Ignore));

                        target.Dispose();

                        return(tes);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void Dispose()
        {
            Target?.Dispose();
            Bitmap?.Dispose();
#if DEBUG
            _redBrush?.Dispose();
#endif
        }
Exemplo n.º 5
0
        static void Main()
        {
            var form = new RenderForm("KinectLight");
            form.Size = new System.Drawing.Size(1920,1200);

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

            SharpDX.Direct3D10.Device1 device;
            SwapChain swapChain;
            SharpDX.Direct3D10.Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, SharpDX.Direct3D10.FeatureLevel.Level_10_1, out device, out swapChain);

            var d2dFactory = new SharpDX.Direct2D1.Factory();
            var surface = Surface.FromSwapChain(swapChain, 0);

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

            MainGame.Instance.Height = form.ClientSize.Height;
            MainGame.Instance.Width = form.ClientSize.Width;
            GameTime gameTime = new GameTime();

            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{name}",
                new { id = RouteParameter.Optional });

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            RenderLoop.Run(form, () =>
            {
                gameTime.StartFrame();
                MainGame.Instance.Update(gameTime);
                dc.BeginDraw();
                dc.Clear(Colors.White);
                MainGame.Instance.Render(dc);
                var res = dc.EndDraw();
                swapChain.Present(1, PresentFlags.None);
                //Thread.Sleep(1);
            });

            server.Dispose();
            MainGame.Instance.Dispose();
            dc.Dispose();
            surface.Dispose();
            d2dFactory.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
        public void CleanUp(D2D1.RenderTarget target, GDI.Graphics g, Map map)
        {
            target.EndDraw();
            using (var sc = TakeScreenshotGdi(map.Size))
                g.DrawImage(sc, new GDI.Point(0, 0));

            target.Dispose();

            //Monitor.Exit(_syncRoot);
        }
Exemplo n.º 7
0
        public void CleanUp(RenderTarget target, Graphics g, Map map)
        {
            target.EndDraw();
            
            var wicBitmap = (WICBitmap) target.Tag;
            using (var image = ConvertToBitmap(wicBitmap))
                g.DrawImageUnscaled(image, 0, 0);

            wicBitmap.Dispose();
            target.Dispose();
        }
Exemplo n.º 8
0
 private void DisposeDirectXResources()
 {
     _textFormat.Dispose();
     _dwFactory.Dispose();
     _renderTarget.Dispose();
     _renderTargetView.Dispose();
     _d2DFactory.Dispose();
     _swapChain.Dispose();
     _d3DDeviceContext.Dispose();
     _d3DDevice.Dispose();
 }
Exemplo n.º 9
0
        public void Dispose()
        {
            uiInitialized = false;

            uiTexture?.Dispose();
            uiEffect?.Dispose();

            target2d?.Dispose();
            uiPrimitive?.Dispose();

            textFormat?.Dispose();
            textFormatSmall?.Dispose();
            textBrush?.Dispose();
            blueBrush?.Dispose();
        }
Exemplo n.º 10
0
 private void disposeResources()
 {
     if (renderTarget != null)
     {
         renderTarget.Dispose();
     }
     if (swapChain != null)
     {
         swapChain.Dispose();
     }
     if (backbufferView != null)
     {
         backbufferView.Dispose();
     }
     if (backbuffer != null)
     {
         backbuffer.Dispose();
     }
 }
Exemplo n.º 11
0
        public void Dispose()
        {
            if (_canvas != null)
            {
                _canvas.Dispose();
                _canvas = null;
            }

            if (_bitmap != null)
            {
                _bitmap.Dispose();
                _bitmap = null;
            }

            if (_renderTarget != null)
            {
                _renderTarget.Dispose();
                _renderTarget = null;
            }
        }
Exemplo n.º 12
0
 private void DisposeDirect3D()
 {
     lock (_drawLock)
     {
         if (surface != null)
         {
             surface.Dispose();
         }
         if (d2dRenderTarget != null)
         {
             d2dRenderTarget.Dispose();
         }
         if (swapChain != null)
         {
             swapChain.Dispose();
         }
         if (device != null)
         {
             device.Dispose();
         }
     }
 }
Exemplo n.º 13
0
        protected void DisposeDirectXResources()
        {
            PreDestroyDirectXResources();
            SharedBrush.Dispose();
            BackgroundBrush.Dispose();
            ForegroundBrush.Dispose();
            CorrectColorBrush.Dispose();
            WrongColorBrush.Dispose();

            InputTextFormat.Dispose();
            ButtonLabelTextFormat.Dispose();
            SubtitleTextFormat.Dispose();
            CueTextFormat.Dispose();

            DwFactory.Dispose();
            RenderTarget.Dispose();
            RenderTargetView.Dispose();
            D2DFactory.Dispose();
            SwapChain.Dispose();
            D3DDeviceContext.Dispose();
            D3DDevice.Dispose();
        }
Exemplo n.º 14
0
        public IDrawingTarget BeginDraw(Color? clearColor)
        {
            #if NETFX_CORE
            var surface = _texture.QueryInterface<Surface>();
            #else
            var surface = _texture.AsSurface();
            #endif

            var rtProperties = new RenderTargetProperties
            {
                DpiX = 96,
                DpiY = 96,
                Type = RenderTargetType.Default,
                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
            };

            var renderTarget = new RenderTarget(_factory, surface, rtProperties);

            renderTarget.BeginDraw();
            // required to clear the render target
            // not required on all machines, seems to be a driver decision.
            renderTarget.Clear(clearColor != null ? clearColor.Value.import() : (Color4?)null);

            var state = new DrawingState();
            var transform = new DrawingTransform();
            var drawingTarget = new DrawingTarget(state, transform, renderTarget, _width, _height);

            var target = new DrawingTargetSplitter(
                _backend,
                state,
                transform,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                drawingTarget,
                () =>
                    {
                        drawingTarget.Dispose();

                        renderTarget.EndDraw();
                        renderTarget.Dispose();
                        surface.Dispose();
                    });

            var pixelAligner = PixelAligningDrawingTarget.Create(target, target.Dispose, state, transform);
            return pixelAligner;
        }
Exemplo n.º 15
0
        public IDisposable beginDraw(out IDrawingContext context)
        {
            var surface = _texture.AsSurface();

            var rtProperties = new RenderTargetProperties()
            {
                DpiX = 96,
                DpiY = 96,
                Type = RenderTargetType.Default,
                PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied)
            };

            var renderTarget = new RenderTarget(_factory, surface, rtProperties);

            var c = new RenderTargetDrawingContext(renderTarget, _width, _height);
            context = c;

            renderTarget.BeginDraw();

            return new DisposeAction(() =>
                {
                    renderTarget.EndDraw();

                    c.Dispose();
                    renderTarget.Dispose();
                    surface.Dispose();
                });
        }
Exemplo n.º 16
0
        public void Create3dObjects()
        {
            //Create RenderWindow
            RenderWindowInstance = new ModelRenderWindow();
            FormInstance = RenderWindowInstance.CreateWindow(1080,1240,FormStartPosition.CenterScreen);

            //Create SwapChain
            SwapChainCreator = new ModelSwapChainDesc();
            SwapChainD = SwapChainCreator.CreateSwapChain(2, Usage.RenderTargetOutput, FormInstance.Handle, true, 0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm, 1,0,SwapChainFlags.AllowModeSwitch, SwapEffect.Discard);

            //Create Device
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SwapChainD, out GraphicsDevice, out NewSwapChain);

            //Create Back buffer
            BackBuffer = Surface.FromSwapChain(NewSwapChain, 0);

            //Create Factory
            FactoryD2D FactoryInstance = new FactoryD2D();

            //Create RenderTarget
            RenderTargetInstance = new ModelRenderTarget();
            RenderTarget = RenderTargetInstance.CreateRenderTarget(SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Ignore), RenderTargetType.Default, RenderTargetUsage.None, BackBuffer, FactoryInstance);

            RenderLoop.Run(FormInstance, () =>
            {

                RenderTarget.BeginDraw();
                RenderTarget.Transform = Matrix3x2.Identity;
                RenderTarget.Clear(Color.White);

                using (var brush = new SolidColorBrush(RenderTarget, Color.Red))
                {
                    //for (int x = 0; x < RenderTarget.Size.Width; x += 10)
                    //    RenderTarget.DrawLine(new Vector2(x, 0), new Vector2(x, RenderTarget.Size.Height), brush, 0.5f);

                    //for (int y = 0; y < RenderTarget.Size.Height; y += 10)
                    //    RenderTarget.DrawLine(new Vector2(0, y), new Vector2(RenderTarget.Size.Width, y), brush, 0.5f);
                    RenderTarget.DrawLine(new Vector2(300, 10), new Vector2(300, 300), brush,1.5f);
                   // RenderTarget.FillRectangle(new RectangleF(RenderTarget.Size.Width / 2 - 50, RenderTarget.Size.Height / 2 - 50, 100, 100), brush);
                }

              //  RenderTarget.DrawRectangle(
                   // new RectangleF(RenderTarget.Size.Width / 2 - 100, RenderTarget.Size.Height / 2 - 100, 200, 200),
                   // new SolidColorBrush(RenderTarget, Color.CornflowerBlue));

                RenderTarget.EndDraw();

                NewSwapChain.Present(0, PresentFlags.None);
            });

            RenderTarget.Dispose();
            NewSwapChain.Dispose();
            GraphicsDevice.Dispose();
        }
Exemplo n.º 17
0
 public void Dispose()
 {
     _renderTarget.Dispose();
 }
Exemplo n.º 18
0
        private void Resize(Size size)
        {
            Utilities.Dispose(ref _deviceContext);
            Utilities.Dispose(ref _backBuffer);
            Utilities.Dispose(ref _renderView);
            Utilities.Dispose(ref _depthBuffer);
            Utilities.Dispose(ref _depthView);
            var context = Direct2D1Platform.Direct3D11Device.ImmediateContext;

            // Resize the backbuffer
            _swapChain.ResizeBuffers(0, 0, 0, Format.Unknown, SwapChainFlags.None);

            // Get the backbuffer from the swapchain
            _backBuffer = Resource.FromSwapChain <Texture2D>(_swapChain, 0);

            // Renderview on the backbuffer
            _renderView = new RenderTargetView(Direct2D1Platform.Direct3D11Device, _backBuffer);

            // Create the depth buffer
            _depthBuffer = new Texture2D(
                Direct2D1Platform.Direct3D11Device,
                new Texture2DDescription()
            {
                Format            = Format.D32_Float_S8X24_UInt,
                ArraySize         = 1,
                MipLevels         = 1,
                Width             = (int)size.Width,
                Height            = (int)size.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.DepthStencil,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.None
            });

            // Create the depth buffer view
            _depthView = new DepthStencilView(Direct2D1Platform.Direct3D11Device, _depthBuffer);

            // Setup targets and viewport for rendering
            context.Rasterizer.SetViewport(new Viewport(0, 0, (int)size.Width, (int)size.Height, 0.0f, 1.0f));
            context.OutputMerger.SetTargets(_depthView, _renderView);

            // Setup new projection matrix with correct aspect ratio
            _proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, (float)(size.Width / size.Height), 0.1f, 100.0f);

            using (var dxgiBackBuffer = _swapChain.GetBackBuffer <Surface>(0))
            {
                var renderTarget = new SharpDX.Direct2D1.RenderTarget(
                    Direct2D1Platform.Direct2D1Factory,
                    dxgiBackBuffer,
                    new RenderTargetProperties
                {
                    DpiX        = 96,
                    DpiY        = 96,
                    Type        = RenderTargetType.Default,
                    PixelFormat = new PixelFormat(
                        Format.Unknown,
                        AlphaMode.Premultiplied)
                });

                _deviceContext = renderTarget.QueryInterface <DeviceContext>();

                renderTarget.Dispose();
            }
        }
Exemplo n.º 19
0
        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();
        }
Exemplo n.º 20
0
 /// <summary>
 /// Dispose the device.
 /// </summary>
 public void Dispose()
 {
     renderTarget.Dispose();
     renderTarget = null;
 }
Exemplo n.º 21
0
        public void OnResize(int width, int height)
        {
            if (mRealTexture != null)
            {
                mRealTexture.Dispose();
            }
            if (mTmpTexture != null)
            {
                mTmpTexture.Dispose();
            }

            mRealTexture = new SharpDX.Direct3D11.Texture2D(mDevice.Device, new SharpDX.Direct3D11.Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource,
                CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None,
                Format            = Format.B8G8R8A8_UNorm,
                Height            = height,
                Width             = width,
                MipLevels         = 1,
                OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = SharpDX.Direct3D11.ResourceUsage.Default
            });

            using (var resource = mRealTexture.QueryInterface <SharpDX.DXGI.Resource>())
                mTmpTexture = D2DDevice.OpenSharedResource <Texture2D>(resource.SharedHandle);

            if (NativeView != null)
            {
                NativeView.Dispose();
            }
            NativeView = new SharpDX.Direct3D11.ShaderResourceView(mDevice.Device, mRealTexture,
                                                                   new SharpDX.Direct3D11.ShaderResourceViewDescription
            {
                Format    = Format.B8G8R8A8_UNorm,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0
                }
            });

            if (RenderTarget != null)
            {
                RenderTarget.Dispose();
            }
            using (var surface = mTmpTexture.QueryInterface <Surface>())
                RenderTarget = new RenderTarget(Direct2DFactory, surface, new RenderTargetProperties()
                {
                    DpiX        = 0.0f,
                    DpiY        = 0.0f,
                    MinLevel    = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT,
                    PixelFormat = new PixelFormat()
                    {
                        AlphaMode = AlphaMode.Premultiplied, Format = Format.Unknown
                    },
                    Type  = RenderTargetType.Hardware,
                    Usage = RenderTargetUsage.None
                });

            if (mMutex10 != null)
            {
                mMutex10.Dispose();
            }
            if (mMutex11 != null)
            {
                mMutex11.Dispose();
            }

            mMutex10 = mTmpTexture.QueryInterface <KeyedMutex>();
            mMutex11 = mRealTexture.QueryInterface <KeyedMutex>();

            Brushes.Initialize(RenderTarget);
            Fonts.Initialize(DirectWriteFactory);

            Button.Initialize();
            Frame.Initialize();

            // right now the texture is unowned and only a key of 0 will succeed.
            // after releasing it with a specific key said key then can be used for
            // further locking.
            mMutex10.Acquire(0, -1);
            mMutex10.Release(Key11);
        }