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(); }); }
public void Compose(D2D.RenderTarget renderTarget, FrameworkElement fe) { renderTarget.BeginDraw(); renderTarget.Clear(new SharpDX.Color(0, 0, 0, 0)); this.Render(renderTarget, fe, fe); renderTarget.EndDraw(); }
void Draw() { if (InvokeRequired) { this.Invoke(new Action(Draw)); return; } lock (_drawLock) { if (!m_Ready) { return; } lock (_drawReqLock) { if (DrawRequests.Count > 0) { d2dRenderTarget.BeginDraw(); foreach (Action <RenderTarget> req in DrawRequests) { req(d2dRenderTarget); } DrawRequestFlushed = true; this.d2dRenderTarget.Flush(); d2dRenderTarget.EndDraw(); } } swapChain.Present(0, PresentFlags.None); } }
public void CleanUp(RenderTarget target, Graphics g, Map map) { target.EndDraw(); var hdc = (IntPtr)target.Tag; g.ReleaseHdc(hdc); }
public static void Render(RenderTarget pRender, float pPercent) { if (Loading) return; pRender.BeginDraw(); currentLevel.Render(pRender, pPercent); pRender.EndDraw(); }
/// <summary> /// Ends a draw operation. /// </summary> public void Dispose() { foreach (var layer in _layerPool) { layer.Dispose(); } _renderTarget.EndDraw(); }
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(); }
private void OnRender() { lock (_renderContextLock) { if (_renderTarget?.IsDisposed ?? true) { return; } _renderTarget.BeginDraw(); _renderTarget.Clear(_backgroundColor); if (_paradigmStarted) // Draw blocks { foreach (var block in _blocks) { if (block.BorderWidth > 0) { _solidColorBrush.Color = _blockBorderColor; _renderTarget.FillRectangle(block.BorderRect, _solidColorBrush); } if (_bitmap != null) { _solidColorBrush.Color = _blockNormalColor; _renderTarget.FillRectangle(block.ContentRect, _solidColorBrush); if (block.Actived) { _renderTarget.DrawBitmap(_bitmap, block.ContentRect, 1, D2D1.BitmapInterpolationMode.Linear); } } else { _solidColorBrush.Color = block.Actived ? _blockActivedColor : _blockNormalColor; _renderTarget.FillRectangle(block.ContentRect, _solidColorBrush); } if (block.Target) { _solidColorBrush.Color = _blockBorderColor; _renderTarget.FillEllipse(block.CenterPointEllipse, _solidColorBrush); } } } else if (!(_displayText?.IsBlank() ?? true)) // Draw text { _solidColorBrush.Color = _fontColor; _renderTarget.DrawText(_displayText, _textFormat, new RawRectangleF(0, 0, Width, Height), _solidColorBrush, D2D1.DrawTextOptions.None); } _renderTarget.EndDraw(); _swapChain.Present(1, DXGI.PresentFlags.None, _presentParameters); } }
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); }
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(); }
/// <summary> /// Finishes Direct2D drawing. /// </summary> public void EndDraw() { if (m_renderTarget2D == null) { return; } if (!m_device.IsUsingFallbackMethodFor2D) { m_renderTarget2D.EndDraw(); // Finish Direct2D drawing m_device.DeviceContextD2D.Target = null; } else { // Finish Direct2D drawing m_renderTarget2D.EndDraw(); } }
internal void Render() { if (!IsRendererSuppressed) { if (RenderTarget != null) { if (!RenderTarget.IsDisposed) { CountFPS(); // === Start count frame time RenderTarget.BeginDraw(); RenderTarget.Clear(SceneManager.CurrentScene.BackgroundColor.RawColor); for (int obj = 0; obj < SceneManager.CurrentScene.GameObjects.Count; obj++) { SceneManager.CurrentScene.GameObjects[obj].GetComponent <IRenderable>().OnRender(RenderFrame); RenderTarget.Transform = Matrix3x2.Identity; } if (Debugging.DrawBounds) { for (int obj = 0; obj < SceneManager.CurrentScene.GameObjects.Count; obj++) { RenderTarget.DrawRectangle(SceneManager.CurrentScene.GameObjects[obj].Transform.DrawingBoundings.RawRectangle, DrawingBoundsBrush); RenderTarget.DrawRectangle(SceneManager.CurrentScene.GameObjects[obj].CollisionBox.ColliderBounds, CollisionBoxesBrush); RenderTarget.Transform = Matrix3x2.Identity; } } RenderTarget.Transform = Matrix3x2.Identity; RenderTarget.EndDraw(); switch (GameWindow.Current.WindowParameters.VSyncMode) { case VSyncMode.Off: SwapChain.Present(0, DXGI.PresentFlags.None); break; case VSyncMode.On: SwapChain.Present(1, DXGI.PresentFlags.None); break; case VSyncMode.Half: SwapChain.Present(2, DXGI.PresentFlags.None); break; } Clock.Restart(); // === End count frame time } } } }
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(); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Подготовка и отображения поверхности /// </summary> //--------------------------------------------------------------------------------------------------------- private void PrepareAndCallRender() { // Does the acttual rendering mD2DRenderTarget.BeginDraw(); Draw(); mD2DRenderTarget.EndDraw(); mD3DDevice.ImmediateContext.Flush(); }
public void Draw(ServiceResult serviceResult, float currentTime, float duration) { if (!uiInitialized) { return; } if (!redraw) { return; } redraw = false; target2d.BeginDraw(); target2d.Clear(new Color4(0, 0, 0, 0.7f)); target2d.DrawLine(new Vector2(0, 1), new Vector2(1024, 1), blueBrush, 2); target2d.DrawLine(new Vector2(0, 511), new Vector2(1024, 511), blueBrush, 2); textFormat.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; if (serviceResult.contentType == ServiceResult.ContentType.video) { target2d.DrawText("now playing:", textFormatSmall, new RectangleF(0, 0, 1024, 100), textBrush); target2d.DrawText(serviceResult.TitleWithFallback, textFormat, new RectangleF(0, 50, 1024, 100), textBrush); var barLength = 1024 - 265; var currentLength = barLength * (currentTime / duration); target2d.DrawLine(new Vector2(128, 384), new Vector2(1024 - 128, 384), textBrush, 6); target2d.DrawLine(new Vector2(128, 384), new Vector2(128 + currentLength, 384), blueBrush, 6); var ellipse = new DX2D.Ellipse(new Vector2(128 + currentLength + 3.5f, 384), 7, 7); target2d.FillEllipse(ellipse, blueBrush); target2d.DrawEllipse(new DX2D.Ellipse(new Vector2(512, 256), 48, 48), textBrush, 2); var dist = 8; var len = 10; target2d.DrawLine(new Vector2(512 - dist, 256 - len), new Vector2(512 - dist, 256 + len), textBrush, 2); target2d.DrawLine(new Vector2(512 + dist, 256 - len), new Vector2(512 + dist, 256 + len), textBrush, 2); textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Trailing; target2d.DrawText((new TimeSpan(0, 0, (int)Math.Floor(duration))).ToString(), textFormatSmall, new Rectangle(1024 - 128 - 150, 384, 150, 50), textBrush); int positionx = (int)(128 + currentLength - 74 / 2); positionx = MathUtil.Clamp(positionx, 128, 1024 - 128 - 74); textFormatSmall.TextAlignment = SharpDX.DirectWrite.TextAlignment.Center; target2d.DrawText((new TimeSpan(0, 0, (int)Math.Floor(currentTime))).ToString(), textFormatSmall, new Rectangle(positionx, 340, 74, 32), textBrush); } target2d.EndDraw(); }
/// <summary> /// Ends a draw operation. /// </summary> public void Dispose() { foreach (var layer in _layerPool) { layer.Dispose(); } try { _renderTarget.EndDraw(); } catch (SharpDXException ex) when((uint)ex.HResult == 0x8899000C) // D2DERR_RECREATE_TARGET { throw new RenderTargetCorruptedException(ex); } }
private void OnRender() { lock (_renderContextLock) { if (RenderTarget?.IsDisposed ?? true) { return; } RenderTarget.BeginDraw(); OnDraw(); RenderTarget.EndDraw(); SwapChain.Present(1, DXGI.PresentFlags.None, _presentParameters); } }
/// <summary> /// Present the device. /// </summary> public void Present() { if (renderTarget != null) { renderTarget.BeginDraw(); for (int i = 0; i < layers.Count; i++) { if (i == 5) { renderTarget.Transform = SharpDX.Matrix.Translation(padding.Left, padding.Top, 0); } renderTarget.DrawBitmap(layers[i].Bitmap, 1, BitmapInterpolationMode.Linear); renderTarget.Transform = SharpDX.Matrix.Identity; } renderTarget.EndDraw(); } }
/// <summary> /// Ends a draw operation. /// </summary> public void Dispose() { foreach (var layer in _layerPool) { layer.Dispose(); } try { _renderTarget.EndDraw(); _swapChain?.Present(1, SharpDX.DXGI.PresentFlags.None); _finishedCallback?.Invoke(); } catch (SharpDXException ex) when((uint)ex.HResult == 0x8899000C) // D2DERR_RECREATE_TARGET { throw new RenderTargetCorruptedException(ex); } }
private void OnRender() { lock (_renderContextLock) { if (_renderTarget?.IsDisposed ?? true) { return; } _renderTarget.BeginDraw(); _renderTarget.Clear(_backgroundColor); if (_paradigmStarted && _trialStarted) // Draw blocks { var borderRect = SharpDXUtils.CenteredRect(Width / 2f, Height / 2f, _paradigm.Config.Gui.ButtonSize); var buttonRect = borderRect.Shrink(Math.Max((float)_paradigm.Config.Gui.ButtonBorder.Width, 0)); var paddings = _paradigm.Config.Gui.ButtonPaddings; var contentRect = buttonRect.Shrink((float)paddings.Left, (float)paddings.Top, (float)paddings.Right, (float)paddings.Bottom); if (_paradigm.Config.Gui.ButtonBorder.Width > 0) { _solidColorBrush.Color = _blockBorderColor; _renderTarget.FillRectangle(borderRect, _solidColorBrush); } _solidColorBrush.Color = _blockNormalColor; _renderTarget.FillRectangle(buttonRect, _solidColorBrush); _solidColorBrush.Color = _foregroundColor; _renderTarget.DrawText(_displayText, _textFormat, contentRect, _solidColorBrush, D2D1.DrawTextOptions.None); } else if (_displayText?.IsNotBlank() ?? false) // Draw text { _solidColorBrush.Color = _foregroundColor; _renderTarget.DrawText(_displayText, _textFormat, new RawRectangleF(0, 0, Width, Height), _solidColorBrush, D2D1.DrawTextOptions.None); } _renderTarget.EndDraw(); _swapChain.Present(1, DXGI.PresentFlags.None, _presentParameters); } }
public void RenderFrame(Action <RenderTarget> renderAction) { mMutex10.Acquire(Key11, -1); try { RenderTarget.BeginDraw(); RenderTarget.Clear(new Color4(0, 0, 0, 0)); if (renderAction != null) { renderAction(RenderTarget); } RenderTarget.EndDraw(); } finally { // we absolutely need to release the old lock and acquire the new one // or the CPU will stall when we return mMutex10.Release(Key11); mMutex11.Acquire(Key11, -1); } }
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; }
private void OnEditViewportDrawPrimitives(Device device, RenderTarget target2D, Rectangle cliprectangle) { UiEncodingWindowSource source = _currentSource; WflContent info = source?.Info; if (info?.Header.TableType != WflHeader.LargeTable) return; int viewportX = _editViewport.X; int viewportY = _editViewport.Y; RectangleF rectangle = new RectangleF {Height = info.Header.LineHeight}; target2D.BeginDraw(); for (int i = 0; i < 256 * 2; i++) { if (i % 256 < 0x20) continue; int x, y; info.GetOffsets(i, out x, out y); x -= viewportX; y -= viewportY; byte before, width, after; info.GetSizes(i, out before, out width, out after); rectangle.X = x; rectangle.Y = y; rectangle.Width = width & 0x7F; if (_charactersControl.CurrentMainIndices.Contains(i)) { target2D.FillRectangle(rectangle, _selectedColorBrush); if (before > 0x7F) { rectangle.Width = (0xFF - before) + 1; rectangle.X = x; } else { rectangle.Width = before; rectangle.X = x - before; } target2D.FillRectangle(rectangle, _spacingColorBrush); if (after > 0x7F) { rectangle.Width = (0xFF - after) + 1; rectangle.X = x + (width & 0x7F) - rectangle.Width; } else { rectangle.Width = after; rectangle.X = x + width & 0x7F; } target2D.FillRectangle(rectangle, _spacingColorBrush); } else if (source.Chars[i % 256] == 0x00) { target2D.FillRectangle(rectangle, _notMappedColorBrush); } else { target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f); } } int squareSize = info.Header.LineSpacing + info.Header.SquareDiff; rectangle.Height = squareSize; rectangle.Width = squareSize; for (int i = 0; i < info.AdditionalTable.Length; i++) { int value = info.AdditionalTable[i]; if (value == 0) continue; rectangle.Y = (value >> 8) * squareSize - viewportY; rectangle.X = (value & 0xFF) * squareSize - viewportX; if (_charactersControl.CurrentAdditionalIndices.Contains(i)) target2D.FillRectangle(rectangle, _selectedColorBrush); else if (source.Chars[i + 256] == 0x00) target2D.FillRectangle(rectangle, _notMappedColorBrush); else target2D.DrawRectangle(rectangle, _gridColorBrush, 1.0f); } target2D.EndDraw(); }
/// <summary> /// Not implemented in interface to more directly manage draw order /// plus it makes it's own begin/end draw calls /// </summary> /// <param name="renderTarget">The Direct2d render target</param> public void Render(RenderTarget renderTarget) { if (_controlLayers.Count == 0) return; renderTarget.BeginDraw(); // Draws in reverse for (var node = _controlLayers.Last; node != null; node = node.Previous) node.Value.Render(renderTarget); renderTarget.EndDraw(); }
public void EndDraw() { renderTarget.EndDraw(); swapChain.Present(0, DXGI.PresentFlags.None); }
public void Render(RenderTarget renderTarget) { if (!_enabled) return; renderTarget.BeginDraw(); renderTarget.Transform = Matrix3x2.Identity; _outputView.Draw(renderTarget); _inputView.Draw(renderTarget); renderTarget.EndDraw(); }
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(); }
public ErrorCode TryGetScreenTexture(out Texture2D texture, int timeout = 0) { texture = null; ErrorCode Result = ErrorCode.Unexpected; if (!deviceReady) { return(ErrorCode.NotReady); } try { SharpDX.DXGI.Resource desktopResource = null; try { var acquireResult = deskDupl.TryAcquireNextFrame(timeout, out OutputDuplicateFrameInformation frameInfo, out desktopResource); if (acquireResult.Failure) { if (acquireResult == SharpDX.DXGI.ResultCode.WaitTimeout) { return(ErrorCode.Ok); } else { logger.Debug("result.Code " + acquireResult.Code); acquireResult.CheckError(); } } if (duplTexture != null) { duplTexture.Dispose(); duplTexture = null; } duplTexture = desktopResource.QueryInterface <Texture2D>(); #region Update regions info //var frameParams = GetFrameParams(frameInfo); /* * var moveRects = frameParams.MoveRects; * foreach (OutputDuplicateMoveRectangle moveRect in moveRects) * { * //... * var srcPoint = moveRect.SourcePoint; * GDI.Point point = new GDI.Point(srcPoint.X, srcPoint.Y); * * var destRect = moveRect.DestinationRect; * int x = destRect.Left; * int y = destRect.Top; * int width = destRect.Right - destRect.Left; * int height = destRect.Bottom - destRect.Top; * GDI.Rectangle rect = new GDI.Rectangle(x, y, width, height); * * logger.Debug("srcPoint " + point.ToString() + " destRect " + rect.ToString()); * } * var dirtyRects = frameParams.DirtyRects; * foreach (RawRectangle dirtyRect in dirtyRects) * { * int x = dirtyRect.Left; * int y = dirtyRect.Top; * int width = dirtyRect.Right - dirtyRect.Left; * int height = dirtyRect.Bottom - dirtyRect.Top; * GDI.Rectangle rect = new GDI.Rectangle(x, y, width, height); * } */ #endregion UpdateMouseInfo(frameInfo); device.ImmediateContext.CopyResource(duplTexture, screenTexture); device.ImmediateContext.Flush(); if (cursorInfo != null && cursorInfo.Visible && CaptureMouse) { screenTarget.BeginDraw(); //screenTarget.Clear(Color.Green); DrawCursor(screenTarget, cursorInfo); screenTarget.EndDraw(); } texture = screenTexture; //texture = duplTexture; Result = 0; } finally { if (desktopResource != null) { deskDupl.ReleaseFrame(); desktopResource.Dispose(); desktopResource = null; } } } catch (SharpDXException ex) { if (ex.ResultCode == SharpDX.DXGI.ResultCode.WaitTimeout) { return(0); } else { if (ex.ResultCode == SharpDX.DXGI.ResultCode.AccessLost || ex.ResultCode == SharpDX.DXGI.ResultCode.AccessDenied || ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceReset || ex.ResultCode == SharpDX.DXGI.ResultCode.DeviceRemoved || ex.HResult == (int)NativeAPIs.HResult.E_ACCESSDENIED) { logger.Warn(ex.Descriptor.ToString()); Result = ErrorCode.AccessDenied; } else { logger.Error(ex); Result = ErrorCode.Unexpected; } } } return(Result); }
/// <summary> /// End drawing session /// </summary> public void End() { _direct2DRenderTarget.EndDraw(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct2D - Direct3D 10 Sample"); // SwapChain description 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 }; // Create Device and SwapChain Device1 device; SwapChain swapChain; Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out device, out swapChain); var d2dFactory = new SharpDX.Direct2D1.Factory(); int width = form.ClientSize.Width; int height = form.ClientSize.Height; var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128 * 2, height-128 * 2) }); // Ignore all windows events Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); Surface surface = backBuffer.QueryInterface<Surface>(); var d2dRenderTarget = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // Main loop RenderLoop.Run(form, () => { d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(Color.Black); solidColorBrush.Color = new Color4(1, 1, 1, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001))); d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null); d2dRenderTarget.EndDraw(); swapChain.Present(0, PresentFlags.None); }); // Release all resources renderView.Dispose(); backBuffer.Dispose(); device.ClearState(); device.Flush(); device.Dispose(); device.Dispose(); swapChain.Dispose(); factory.Dispose(); }
/// <summary> /// Draw a fading bitmap animation on the Render Target (Game Launcher Window). /// </summary> /// <param name="target">Destination render target which is ready to be drawn.</param> /// <param name="bitmapData">Bitmap data.</param> /// <param name="scaleMultiple">Which multiple should be used to scale the bitmap?</param> /// <param name="rect">Which rectangle range on the render target(window) should be drawn by the bitmap?</param> /// <param name="type">Which type of fade should we use to do the animation?</param> /// <param name="isStopDoing"> /// The variable reference of the sign which indicates 'Should we stop fading animation now'. /// <para>Project Rabotora Launcher will <b>instantly finish</b> fading bitmap draw process when drawing fading bitmap and <b>player clicks in the window of Rabotora Launcher</b>.<br /> /// This argument will pass the 'Instant finish' command from caller to animation method.</para> /// <para>If you do not want player finish the animation by clicking in the window, please give a <see langword="bool" /> variable whose value is <b>fixed <see langword="false" /></b> .</para> /// </param> /// <param name="duration">The animation duration of drawing fading bitmap in seconds. Default is <see langword="2.5f" /> .</param> /// <param name="segmentAlpha">How much alpha we should increase/decrease in the every round of inner drawing circulation? (Range: [0, 0.5]; Default is <see langword="0.005f" /> .)</param> /// <param name="isBeginDrawBeforeStart">Should we called <see cref="D2D.RenderTarget.BeginDraw()"/> before starting fading animation? (Default is <see langword="false" /> .)</param> /// <exception cref="ArgumentException" /> public static void DrawFadeBitmap(D2D.RenderTarget target, byte[] bitmapData, RawRectangleF rect, float scaleMultiple, FadeType type, ref bool isStopDoing, float duration = 2.5f, float segmentAlpha = 0.005f, bool isBeginDrawBeforeStart = false) { if (segmentAlpha < 0.0f || segmentAlpha > 0.5f) { throw new ArgumentException("Segment alpha value must in [0.0,0.5].", nameof(segmentAlpha)); } var stream = new MemoryStream(bitmapData); stream.Seek(0, SeekOrigin.Begin); var bitmapWrapper = (Bitmap)Image2.FromStream(stream); bitmapWrapper = bitmapWrapper.ScaleBitmap(scaleMultiple); var bitmap = target.LoadD2DBitmapFromBitmap(bitmapWrapper); if (bitmap != null) { if (isBeginDrawBeforeStart) { target.BeginDraw(); } int waitMS = (int)(duration * 1000 / (1 / segmentAlpha)); if (type == FadeType.FadeIn) { for (float i = 0f; i < 1f; i += segmentAlpha) { if (!isStopDoing) { target.DrawBitmap(bitmap, i, D2D.BitmapInterpolationMode.Linear, rect); target.EndDraw(); target.BeginDraw(); Thread.Sleep(waitMS); } else { target.DrawBitmap(bitmap, 1.0f, D2D.BitmapInterpolationMode.Linear, rect); target.EndDraw(); target.BeginDraw(); break; } } } else { for (float i = 1f; i > 0f; i -= segmentAlpha) { if (!isStopDoing) { target.DrawBitmap(bitmap, i, D2D.BitmapInterpolationMode.Linear, rect); target.EndDraw(); target.BeginDraw(); Thread.Sleep(waitMS); } else { target.DrawBitmap(bitmap, 0.0f, D2D.BitmapInterpolationMode.Linear, rect); target.EndDraw(); target.BeginDraw(); break; } } } } }
public void EndDraw() { _renderTarget.EndDraw(); }
static void Main() { var form = new RenderForm("FUN STUFF PHYSXS"); // SwapChain description 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 }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain); var d2dFactory = new SharpDX.Direct2D1.Factory(); // Ignore all windows events Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); Surface surface = backBuffer.QueryInterface<Surface>(); var d2dRenderTarget = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); var sim = new Simulation(); // Main loop RenderLoop.Run(form, () => { d2dRenderTarget.BeginDraw(); int width = form.ClientSize.Width; int height = form.ClientSize.Height; var simScaleX = sim.SimBounds.MaxX - sim.SimBounds.MinX; var simScaleY = sim.SimBounds.MaxY - sim.SimBounds.MinY; var viewScaleX = sim.ViewBounds.MaxX - sim.ViewBounds.MinX; var viewScaleY = sim.ViewBounds.MaxY - sim.ViewBounds.MinY; d2dRenderTarget.Clear(Color.Black); foreach (Body body in sim.State) { var x = Convert.ToSingle((body.Pos.X - sim.SimBounds.MinX) * width / simScaleX); var y = Convert.ToSingle((body.Pos.Y - sim.SimBounds.MinY) * height / simScaleY); var xRad = Convert.ToSingle((body.Radius) * width / viewScaleX); var yRad = Convert.ToSingle((body.Radius) * height / viewScaleY); var elipse = new EllipseGeometry(d2dFactory, new Ellipse(new Vector2(x, y), xRad, yRad)); d2dRenderTarget.FillGeometry(elipse, solidColorBrush, null); } d2dRenderTarget.EndDraw(); sim.Step(); swapChain.Present(0, PresentFlags.None); }); // Release all resources renderView.Dispose(); backBuffer.Dispose(); device.ImmediateContext.ClearState(); device.ImmediateContext.Flush(); device.Dispose(); device.Dispose(); swapChain.Dispose(); factory.Dispose(); }