public WriteableBitmap RenderToWriteableBitmap(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; //new D2D.Device() //new DeviceContext() //new DeviceContext() //var bitmap = new Bitmap1( // _d2DFactory, // width, // height, // pixelFormat, // BitmapCreateCacheOption.CacheOnLoad); var wb = new WriteableBitmap(width, height); return(wb); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Direct2D var renderTargetProperties = new RenderTargetProperties() { PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore) }; var hwndRenderTargetProperties = new HwndRenderTargetProperties() { Hwnd = this.Handle, PixelSize = new Size2(bounds.Width, bounds.Height), PresentOptions = PresentOptions.Immediately, }; renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties); var bitmapProperties = new BitmapProperties() { PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Ignore) }; bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(bounds.Width, bounds.Height), bitmapProperties); textFormat = new TextFormat(directWriteFacrtory, "Arial", FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, 96.0f); textFormat.ParagraphAlignment = ParagraphAlignment.Center; textFormat.TextAlignment = TextAlignment.Center; solidColorBrush = new SolidColorBrush(renderTarget, Color4.White); }
public void Init(Window window) { var factory = new D2D.Factory(); var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Ignore); var renderTargetProperties = new D2D.RenderTargetProperties ( // 默认的行为就是尝试使用硬件优先,否则再使用软件 D2D.RenderTargetType.Default, // 像素格式,对于当前大多数显卡来说,选择 B8G8R8A8 是完全能支持的 // 而且也方便和其他框架,如 WPF 交互 pixelFormat, dpiX: 96, dpiY: 96, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT ); var hwndRenderTargetProperties = new D2D.HwndRenderTargetProperties(); hwndRenderTargetProperties.Hwnd = new WindowInteropHelper(window).Handle; hwndRenderTargetProperties.PixelSize = new Size2((int)window.ActualWidth, (int)window.ActualHeight); var renderTarget = new D2D.WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties); }
public WriteableBitmap RenderToWriteableBitmap(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; //new D2D.Device() //new DeviceContext() //new DeviceContext() //var bitmap = new Bitmap1( // _d2DFactory, // width, // height, // pixelFormat, // BitmapCreateCacheOption.CacheOnLoad); var wb = new WriteableBitmap(width, height); return wb; }
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(); }); }
private RendererDirect2D Create(PxSize size, out WIC.Bitmap wicBitmap) { _bitmap = wicBitmap = new WIC.Bitmap( WicFactory, (int)(size.Width * 1.0f), (int)(size.Height * 1.0f), WIC.PixelFormat.Format32bppPBGRA, WIC.BitmapCreateCacheOption.CacheOnLoad ); wicBitmap.SetResolution(200, 200); var renderProps = new D2D1.RenderTargetProperties( D2D1.RenderTargetType.Default, new D2D1.PixelFormat( DXGI.Format.B8G8R8A8_UNorm, D2D1.AlphaMode.Premultiplied ), 96, 96, D2D1.RenderTargetUsage.None, //GdiCompatible| D2D1.RenderTargetUsage.ForceBitmapRemoting, D2D1.FeatureLevel.Level_DEFAULT ); var wicRenderTarget = new D2D1.WicRenderTarget( D2DFactory, wicBitmap, renderProps ); // {DotsPerInch = new Size2F(600, 600)}; return(new RendererDirect2D(this, wicRenderTarget)); }
void CreateRenderTarget() { var renderProp = new sd.RenderTargetProperties { DpiX = 0, DpiY = 0, MinLevel = sd.FeatureLevel.Level_DEFAULT, Type = sd.RenderTargetType.Default, Usage = sd.RenderTargetUsage.None }; if (drawable != null) { renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, sd.AlphaMode.Premultiplied); var winProp = new sd.HwndRenderTargetProperties { Hwnd = drawable.Control.Handle, PixelSize = drawable.ClientSize.ToDx(), PresentOptions = sd.PresentOptions.Immediately }; Control = new sd.WindowRenderTarget(SDFactory.D2D1Factory, renderProp, winProp); } else if (image != null) { var imageHandler = image.Handler as BitmapHandler; renderProp.PixelFormat = new sd.PixelFormat(SharpDX.DXGI.Format.Unknown, sd.AlphaMode.Unknown); Control = new sd.WicRenderTarget(SDFactory.D2D1Factory, imageHandler.Control, renderProp); } }
public InfoText(SharpDX.Direct3D11.Device device, int width, int height) { _immediateContext = device.ImmediateContext; _rect.Size = new Size2F(width, height); _bitmapSize = width * height * 4; IsEnabled = true; using (var factoryWic = new SharpDX.WIC.ImagingFactory()) { _wicBitmap = new SharpDX.WIC.Bitmap(factoryWic, width, height, _pixelFormat, SharpDX.WIC.BitmapCreateCacheOption.CacheOnLoad); } var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); using (var factory2D = new SharpDX.Direct2D1.Factory()) { _wicRenderTarget = new WicRenderTarget(factory2D, _wicBitmap, renderTargetProperties); _wicRenderTarget.TextAntialiasMode = TextAntialiasMode.Default; } using (var factoryDWrite = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)) { _textFormat = new TextFormat(factoryDWrite, "Tahoma", 20); } Color4 color = new Color4(1, 1, 1, 1); _sceneColorBrush = new SolidColorBrush(_wicRenderTarget, color); _clearColor = color; _clearColor.Alpha = 0; _renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R8G8B8A8_UNorm, Height = height, Width = width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic }); OverlayBufferRes = new ShaderResourceView(device, _renderTexture, new ShaderResourceViewDescription() { Format = _renderTexture.Description.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
public RenderTargetCanvas(DXGI.Surface surface, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null) { if (surface == null) { throw new ArgumentNullException("surface"); } this.factories = factories ?? Direct2DFactories.Shared; Initialize(new D2D1.RenderTarget(this.factories.D2DFactory, surface, properties)); }
public WICBitmapCanvas(WIC.Bitmap bmp, D2D1.RenderTargetProperties properties, Direct2DFactories factories = null) : base(new D2D1.WicRenderTarget((factories ?? Direct2DFactories.Shared).D2DFactory, bmp, properties), factories) { this.Bmp = bmp; this.scale = properties.DpiX / 96.0; var bmpSize = bmp.Size; this.size = new Size(bmpSize.Width / scale, bmpSize.Height / scale); }
public void ConstructRenderAndResource(double width, double height) { float dpiX, dpiY; this.GetDpi(out dpiX, out dpiY); D2D.RenderTargetProperties prop = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied), dpiX, dpiY, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); D3D11.Texture2DDescription desc = new D3D11.Texture2DDescription(); desc.Width = (int)width; desc.Height = (int)height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI.Format.B8G8R8A8_UNorm; desc.SampleDescription = new DXGI.SampleDescription(1, 0); desc.Usage = D3D11.ResourceUsage.Default; desc.BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource; desc.CpuAccessFlags = D3D11.CpuAccessFlags.None; desc.OptionFlags = D3D11.ResourceOptionFlags.Shared; this.d3d11Texture = new D3D11.Texture2D(this.device, desc); this.surface = this.d3d11Texture.QueryInterface <DXGI.Surface>(); DXGI.Resource resource = this.d3d11Texture.QueryInterface <DXGI.Resource>(); IntPtr handel = resource.SharedHandle; D3D9.Texture texture = new D3D9.Texture( this.device9, this.d3d11Texture.Description.Width, this.d3d11Texture.Description.Height, 1, D3D9.Usage.RenderTarget, D3D9.Format.A8R8G8B8, D3D9.Pool.Default, ref handel); this.surface9 = texture.GetSurfaceLevel(0); resource.Dispose(); texture.Dispose(); D2D.BitmapProperties bmpProp = new D2D.BitmapProperties(); bmpProp.DpiX = dpiX; bmpProp.DpiY = dpiY; bmpProp.PixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); this.bmpd2d = new D2D.Bitmap(this.render, this.surface, bmpProp); this.cachedBitMap = new D2D.Bitmap(this.render, new Size2((int)width, (int)height), bmpProp); this.hasCache = false; this.render.Target = this.bmpd2d; this.renderSize = new Size(width, height); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Создание текстуры Direct3D11 для ренденинга /// </summary> //--------------------------------------------------------------------------------------------------------- private void CreateAndBindTargets() { mD3DSurface.SetRenderTarget(null); XDisposer.SafeDispose(ref mD2DRenderTarget); XDisposer.SafeDispose(ref mD3DRenderTarget); XDisposer.SafeDispose(ref XDirect2DManager.mD2DDevice); XDisposer.SafeDispose(ref XDirect2DManager.mD2DFactory); XDisposer.SafeDispose(ref XDirect2DManager.mD2DWriteFactory); XDisposer.SafeDispose(ref XDirect2DManager.mD2DImagingFactory); var width = (Int32)Math.Max(ActualWidth, mWidthRenderTargetDip); var height = (Int32)Math.Max(ActualHeight, mHeightRenderTargetDip); var colordesc = new Direct3D11.Texture2DDescription { BindFlags = Direct3D11.BindFlags.RenderTarget | Direct3D11.BindFlags.ShaderResource, Format = DXGI.Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = Direct3D11.ResourceUsage.Default, OptionFlags = Direct3D11.ResourceOptionFlags.Shared, CpuAccessFlags = Direct3D11.CpuAccessFlags.None, ArraySize = 1 }; // Создаем текстуру Direct3D11 mD3DRenderTarget = new Direct3D11.Texture2D(mD3DDevice, colordesc); var surface = mD3DRenderTarget.QueryInterface <DXGI.Surface>(); // Фабрика ресурсов DirectD2 XDirect2DManager.mD2DFactory = new Direct2D.Factory(); //XNativeD2DFactory.mD2DDevice = new Direct2D.Device(XNativeD2DFactory.mD2DFactory, XNativeD2DFactory.mDXGIDevice); XDirect2DManager.mD2DWriteFactory = new DirectWrite.Factory(DirectWrite.FactoryType.Shared); XDirect2DManager.mD2DImagingFactory = new ImagingFactory(); // Создаем поверхность отображения DirectD2 var render_target_properties = new Direct2D.RenderTargetProperties(new Direct2D.PixelFormat(DXGI.Format.Unknown, Direct2D.AlphaMode.Premultiplied)); render_target_properties.Type = Direct2D.RenderTargetType.Default; render_target_properties.Usage = Direct2D.RenderTargetUsage.None; mD2DRenderTarget = new Direct2D.RenderTarget(XDirect2DManager.mD2DFactory, surface, render_target_properties); mD3DSurface.SetRenderTarget(mD3DRenderTarget); // Определяем область отображения mD3DDevice.ImmediateContext.Rasterizer.SetViewport(0, 0, width, height, 0.0f, 1.0f); // Сохраняем XDirect2DManager.mD2DRenderTarget = mD2DRenderTarget; }
public SurfaceImageSourceCanvas(SurfaceImageSource surfaceImageSource, Rect updateRect, Direct2DFactories factories = null) : base(factories) { sisn = ComObject.As <DXGI.ISurfaceImageSourceNative> (surfaceImageSource); SharpDX.Point offset; var surface = sisn.BeginDraw(updateRect.ToRectangle(), out offset); var dpi = 96.0; var properties = new D2D1.RenderTargetProperties(D2D1.RenderTargetType.Default, new D2D1.PixelFormat(DXGI.Format.Unknown, D2D1.AlphaMode.Unknown), (float)(dpi), (float)(dpi), D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT); Initialize(new D2D1.RenderTarget(this.factories.D2DFactory, surface, properties)); }
private static sd.RenderTargetProperties CreateRenderProperties() { var renderProp = new sd.RenderTargetProperties { DpiX = 0, DpiY = 0, MinLevel = sd.FeatureLevel.Level_DEFAULT, Type = sd.RenderTargetType.Default, Usage = sd.RenderTargetUsage.None }; return(renderProp); }
public Direct2DImageEncoder(int imageWidth, int imageHeight, int imageDpi) { this.imageWidth = imageWidth; this.imageHeight = imageHeight; factoryManager = new Direct2DFactoryManager(); wicBitmap = new SharpDX.WIC.Bitmap(factoryManager.WicFactory, imageWidth, imageHeight, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, AlphaMode.Unknown), imageDpi, imageDpi, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(factoryManager.D2DFactory, wicBitmap, renderTargetProperties); renderTarget.BeginDraw(); renderTarget.Clear(SharpDX.Color.Yellow); }
private static void Main() { var wicFactory = new ImagingFactory(); var d2dFactory = new SharpDX.Direct2D1.Factory(); string filename = "output.jpg"; const int width = 512; const int height = 512; var rectangleGeometry = new RoundedRectangleGeometry(d2dFactory, new RoundedRectangle() { RadiusX = 32, RadiusY = 32, Rect = new RectangleF(128, 128, width - 128, height-128) }); var wicBitmap = new Bitmap(wicFactory, width, height, SharpDX.WIC.PixelFormat.Format32bppBGR, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var d2dRenderTarget = new WicRenderTarget(d2dFactory, wicBitmap, renderTargetProperties); var solidColorBrush = new SolidColorBrush(d2dRenderTarget, Color.White); d2dRenderTarget.BeginDraw(); d2dRenderTarget.Clear(Color.Black); d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null); d2dRenderTarget.EndDraw(); if (File.Exists(filename)) File.Delete(filename); var stream = new WICStream(wicFactory, filename, NativeFileAccess.Write); // Initialize a Jpeg encoder with this stream var encoder = new JpegBitmapEncoder(wicFactory); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); var pixelFormatGuid = SharpDX.WIC.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); System.Diagnostics.Process.Start(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory,filename))); }
public void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(1600, 900, new Rational(60, 1), Format.B8G8R8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = this.Handle, IsWindowed = true }; var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug; //SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); using (SharpDX.Direct3D11.Texture2D backBuffer = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0)) { renderTargetView = new SharpDX.Direct3D11.RenderTargetView(d3dDevice, backBuffer); } System.Drawing.Graphics g = this.CreateGraphics(); SharpDX.Direct2D1.Factory d2dFactory = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, SharpDX.Direct2D1.DebugLevel.None); // Create Direct2D device var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); //d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); //d2dContext.PrimitiveBlend = PrimitiveBlend.SourceOver; BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore), g.DpiX, g.DpiY, BitmapOptions.Target | BitmapOptions.CannotDraw); Surface backBuffer2D = swapChain.GetBackBuffer <Surface>(0); //new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied) SharpDX.Direct2D1.RenderTargetProperties rtp = new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Ignore)); d2dRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, backBuffer2D, rtp); d2dTarget = new Bitmap1(d2dContext, backBuffer2D, properties); d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); }
private static sd.RenderTargetProperties CreateRenderProperties() { var renderProp = new sd.RenderTargetProperties { /* Direct2D rendering engine does not perform DPI virtualization like WPF and Logical pixel size is always 1 * In order to prevent SharpDX from using real screen DPI, we fix the scale ratio to 1 */ DpiX = 96, DpiY = 96, MinLevel = sd.FeatureLevel.Level_DEFAULT, Type = sd.RenderTargetType.Default, Usage = sd.RenderTargetUsage.None }; return(renderProp); }
public async Task <MemoryStream> RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); if (width == 0 || height == 0) { throw new InvalidOperationException("Can't render an empty element. ActualWidth or ActualHeight equal 0. Consider awaiting a WaitForNonZeroSizeAsync() call or invoking Measure()/Arrange() before the call to Render()."); } // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; using (var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad)) { var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat( Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); using (var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }) { await Compose(renderTarget, fe); } // TODO: There is no need to encode the bitmap to PNG - we could just copy the texture pixel buffer to a WriteableBitmap pixel buffer. return(GetBitmapAsStream(wicBitmap)); } }
public RenderTarget Create(Factory factory, Graphics g, Map map) { var hdc = g.GetHdc(); var rtp = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var rt = new DeviceContextRenderTarget(factory, rtp); rt.Tag = hdc; rt.BindDeviceContext(hdc, new SharpDX.Rectangle(0, 0, map.Size.Width, map.Size.Height)); rt.BeginDraw(); return rt; }
private void OnFormLoad(object sender, EventArgs e) { if (_osuModel != null) { LogUtil.LogInfo("Form loads normally."); } else { LogUtil.LogError("Form loads without real-time instance."); return; } Paint += OnPaint; // Initial settings var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); var winProp = new D2D.HwndRenderTargetProperties { Hwnd = Handle, PixelSize = new DX.Size2(ClientSize.Width, ClientSize.Height), PresentOptions = _useVsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately }; var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96, D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT); RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp) { AntialiasMode = D2D.AntialiasMode.PerPrimitive, TextAntialiasMode = D2D.TextAntialiasMode.Grayscale, Transform = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0) }; LayerList = new List <DxLayer> { new BgDxLayer(RenderTarget, _obj, _osuModel), new SongInfoDxLayer(RenderTarget, _obj, _osuModel), new FpsDxLayer(RenderTarget, _obj, _osuModel), //new TestLayer(RenderTarget, _obj, _osuModel), }; _renderTask = new Task[LayerList.Count]; // Avoid artifacts SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); Text = "Osu!Live Player (DX)"; LogUtil.LogInfo("Form loaded."); }
public static void EncodeImage(this d2.Bitmap target, ImageFormat imageFormat, Stream outputStream) { var width = target.PixelSize.Width; var height = target.PixelSize.Height; var wicBitmap = new wic.Bitmap(DXGraphicsService.FactoryImaging, width, height, wic.PixelFormat.Format32bppBGR, wic.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new d2.RenderTargetProperties(d2.RenderTargetType.Default, new d2.PixelFormat(Format.Unknown, d2.AlphaMode.Unknown), 0, 0, d2.RenderTargetUsage.None, d2.FeatureLevel.Level_DEFAULT); var d2DRenderTarget = new d2.WicRenderTarget(target.Factory, wicBitmap, renderTargetProperties); d2DRenderTarget.BeginDraw(); d2DRenderTarget.Clear(global::SharpDX.Color.Transparent); d2DRenderTarget.DrawBitmap(target, 1, d2.BitmapInterpolationMode.Linear); d2DRenderTarget.EndDraw(); var stream = new wic.WICStream(DXGraphicsService.FactoryImaging, outputStream); // Initialize a Jpeg encoder with this stream var encoder = new wic.BitmapEncoder(DXGraphicsService.FactoryImaging, GetImageFormat(imageFormat)); encoder.Initialize(stream); // Create a Frame encoder var bitmapFrameEncode = new wic.BitmapFrameEncode(encoder); bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(width, height); Guid pixelFormatGuid = wic.PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormatGuid); bitmapFrameEncode.WriteSource(wicBitmap); bitmapFrameEncode.Commit(); encoder.Commit(); bitmapFrameEncode.Dispose(); encoder.Dispose(); stream.Dispose(); d2DRenderTarget.Dispose(); wicBitmap.Dispose(); }
public RenderTarget Create(Factory factory, Graphics g, Map map) { var wicBitmap = new WICBitmap(_wicFactory, map.Size.Width, map.Size.Height, SharpDX.WIC.PixelFormat.Format32bppPBGRA, BitmapCreateCacheOption.CacheOnDemand); var rtp = new RenderTargetProperties(RenderTargetType.Default, new D2D1PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var res = new WicRenderTarget(factory, wicBitmap, rtp) {Tag = wicBitmap}; res.BeginDraw(); res.Clear(SharpDX.Color.Transparent); return res; }
public RenderTargetDirect2D CreateDirect2DRenderTarget(RenderTarget.Configuration.CreationSettings settings) { var description = new Texture2DDescription { Width = settings.Dimensions.Width, Height = settings.Dimensions.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = settings.SampleDescription, Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }; var texture2D = new Texture2D(_deviceManager.Device, description); //using var resource = texture2D; { var sharedResource = resource.QueryInterface<SharpDX.DXGI.Resource>(); var textureD3D10 = _deviceManager.Device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var renderTargetProperties = new RenderTargetProperties { MinLevel = FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied) }; var surface = textureD3D10.AsSurface(); var context = new SharpDX.Direct2D1.RenderTarget(_deviceManager.Direct2DFactory, surface, renderTargetProperties) { AntialiasMode = AntialiasMode.PerPrimitive, TextAntialiasMode = TextAntialiasMode.Cleartype }; var renderTargetView11 = new RenderTargetView(_deviceManager.Device, resource); var renderTargetView10 = new SharpDX.Direct3D10.RenderTargetView(_deviceManager.Device10, textureD3D10); var renderTarget2D = new RenderTargetDirect2D(renderTargetView11, renderTargetView10, context, settings); _renderTargets.Add(renderTarget2D); return renderTarget2D; } }
public DXWicContext(int width, int height) { _bitmap = new wic.Bitmap( DXGraphicsService.FactoryImaging, width, height, wic.PixelFormat.Format32bppBGR, wic.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new d2.RenderTargetProperties(d2.RenderTargetType.Default, new d2.PixelFormat(dxgi.Format.Unknown, d2.AlphaMode.Unknown), 0, 0, d2.RenderTargetUsage.None, d2.FeatureLevel.Level_DEFAULT); _renderTarget = new d2.WicRenderTarget(DXGraphicsService.SharedFactory, _bitmap, renderTargetProperties); _renderTarget.BeginDraw(); _canvas = new DXCanvas(_renderTarget); }
public RenderTarget(D2D.Factory factory, IntPtr hwnd, int width, int height) { D2D.RenderTargetProperties renderTargetProperties = new D2D.RenderTargetProperties { }; D2D.HwndRenderTargetProperties hwndProperties = new D2D.HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = new SharpDX.Size2(width, height), PresentOptions = D2D.PresentOptions.Immediately }; _renderTarget = new D2D.WindowRenderTarget( factory, renderTargetProperties, hwndProperties); }
public RenderTargetBitmapImpl( ImagingFactory imagingFactory, Factory d2dFactory, int width, int height) : base(imagingFactory, width, height) { var props = new RenderTargetProperties { DpiX = 96, DpiY = 96, }; _target = new WicRenderTarget( d2dFactory, WicImpl, props); }
public RenderTarget(D2D.Factory factory,IntPtr hwnd, int width, int height) { D2D.RenderTargetProperties renderTargetProperties = new D2D.RenderTargetProperties { }; D2D.HwndRenderTargetProperties hwndProperties = new D2D.HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = new SharpDX.Size2(width, height), PresentOptions = D2D.PresentOptions.Immediately }; _renderTarget = new D2D.WindowRenderTarget( factory, renderTargetProperties, hwndProperties); }
private void LoadTarget(object sender, EventArgs e) { // Initial settings var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); var winProp = new D2D.HwndRenderTargetProperties { Hwnd = Handle, PixelSize = new DX.Size2(ClientSize.Width, ClientSize.Height), PresentOptions = Program.MainSettings.LimitFps ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately }; var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Default, pixelFormat, 96, 96, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp) { AntialiasMode = D2D.AntialiasMode.PerPrimitive, TextAntialiasMode = D2D.TextAntialiasMode.Grayscale, Transform = new Mathe.RawMatrix3x2 { M11 = 1f, M12 = 0f, M21 = 0f, M22 = 1f, M31 = 0, M32 = 0 } }; // Create colors _colorBack = new Mathe.RawColor4(0, 0, 0, 1); LayerList = new Dictionary <string, ILayer>(); LayerList.Add("back", new Background()); if (Program.MainSettings.UseParticle) { LayerList.Add("particle", new Particle(500)); } LayerList.Add("chess", new Chessboard()); // Create brushes _whiteBrush = new D2D.SolidColorBrush(RenderTarget, new Mathe.RawColor4(1, 1, 1, 1)); // Create text formats _textFormat = new DW.TextFormat(FactoryWrite, "Microsoft YaHei", 12); // Avoid artifacts SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); }
public HwndRenderBase(Control control) { var hwndProp = new D2D.HwndRenderTargetProperties { Hwnd = control.Handle, PixelSize = new DX.Size2(control.ClientSize.Width, control.ClientSize.Height), PresentOptions = Vsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately }; var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96, D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT); RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, hwndProp) { AntialiasMode = D2D.AntialiasMode.Aliased, TextAntialiasMode = D2D.TextAntialiasMode.Default, Transform = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0) }; }
private void InitializeGraphics() { factory = new Factory(FactoryType.SingleThreaded, DebugLevel.None); renderTargetProperties = new RenderTargetProperties(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied)); hwndRenderTargetProperties = new HwndRenderTargetProperties(); hwndRenderTargetProperties.Hwnd = this.Handle; hwndRenderTargetProperties.PixelSize = new SharpDX.Size2(Width, Height); hwndRenderTargetProperties.PresentOptions = PresentOptions.None; windowRenderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties); backgroundColor = new RawColor4(BackColor.R, BackColor.G, BackColor.B, BackColor.A); borderColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0.5f, 0.5f, 0.5f, 1)); wayColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0, 0, 1, 0.3f)); currentPositionColor = new SolidColorBrush(windowRenderTarget, new RawColor4(0, 0, 1, 1)); graphicsInitialized = true; }
private void CreateTarget(int width, int height, System.IntPtr hwnd) { RenderTarget?.Dispose(); var hwndProp = new D2D.HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = new DX.Size2(width, height), PresentOptions = Vsync ? D2D.PresentOptions.None : D2D.PresentOptions.Immediately }; var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Hardware, pixelFormat, 96, 96, D2D.RenderTargetUsage.ForceBitmapRemoting, D2D.FeatureLevel.Level_DEFAULT); RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, hwndProp) { AntialiasMode = D2D.AntialiasMode.Aliased, TextAntialiasMode = D2D.TextAntialiasMode.Default, Transform = new Mathe.RawMatrix3x2(1, 0, 0, 1, 0, 0) }; }
/// <summary> /// Initializes a new instance of the <see cref="RenderTarget"/> class. /// </summary> /// <param name="hwnd">The window handle.</param> /// <param name="width">The width of the window.</param> /// <param name="height">The height of the window.</param> public RenderTarget(IntPtr hwnd, double width, double height) { Direct2DFactory = PerspexLocator.Current.GetService<Factory>(); DirectWriteFactory = PerspexLocator.Current.GetService<DwFactory>(); RenderTargetProperties renderTargetProperties = new RenderTargetProperties { }; HwndRenderTargetProperties hwndProperties = new HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = new Size2((int)width, (int)height), PresentOptions = PresentOptions.Immediately, }; _renderTarget = new WindowRenderTarget( Direct2DFactory, renderTargetProperties, hwndProperties); }
private void LoadTarget(object sender, EventArgs e) { var pixelFormat = new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied); var winProp = new D2D.HwndRenderTargetProperties { Hwnd = this.Handle, PixelSize = new DX.Size2(this.ClientSize.Width, this.ClientSize.Height), PresentOptions = D2D.PresentOptions.Immediately }; var renderProp = new D2D.RenderTargetProperties(D2D.RenderTargetType.Default, pixelFormat, 96, 96, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); RenderTarget = new D2D.WindowRenderTarget(Factory, renderProp, winProp) { AntialiasMode = D2D.AntialiasMode.PerPrimitive, TextAntialiasMode = D2D.TextAntialiasMode.Grayscale, Transform = new Mathe.RawMatrix3x2 { M11 = 1, M12 = 0, M21 = 0, M22 = 1, M31 = 0, M32 = 0 } }; // Create colors colorBack = new Mathe.RawColor4(0, 0, 0, 1); // Initialize layers layerClock = new Layer.Clock(this.ClientSize); layerParticle = new Layer.Particles(500, 200); layerBack = new Layer.Background(); // Avoid artifacts this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); }
/// <summary> /// Initializes a new instance of the <see cref="RenderTarget"/> class. /// </summary> /// <param name="hwnd">The window handle.</param> /// <param name="width">The width of the window.</param> /// <param name="height">The height of the window.</param> public RenderTarget(IntPtr hwnd) { _hwnd = hwnd; Direct2DFactory = PerspexLocator.Current.GetService<Factory>(); DirectWriteFactory = PerspexLocator.Current.GetService<DwFactory>(); RenderTargetProperties renderTargetProperties = new RenderTargetProperties { }; HwndRenderTargetProperties hwndProperties = new HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = _savedSize = GetWindowSize(), PresentOptions = PresentOptions.Immediately, }; _renderTarget = new WindowRenderTarget( Direct2DFactory, renderTargetProperties, hwndProperties); }
private void CreateAndBindTargets() { var width = Math.Max((int)ActualWidth, 100); var height = Math.Max((int)ActualHeight, 100); var renderDesc = new D3D11.Texture2DDescription { BindFlags = D3D11.BindFlags.RenderTarget | D3D11.BindFlags.ShaderResource, Format = DXGI.Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = D3D11.ResourceUsage.Default, OptionFlags = D3D11.ResourceOptionFlags.Shared, CpuAccessFlags = D3D11.CpuAccessFlags.None, ArraySize = 1 }; var device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport); var renderTarget = new D3D11.Texture2D(device, renderDesc); var surface = renderTarget.QueryInterface <DXGI.Surface>(); var d2DFactory = new D2D.Factory(); var renderTargetProperties = new D2D.RenderTargetProperties(new D2D.PixelFormat(DXGI.Format.Unknown, D2D.AlphaMode.Premultiplied)); _d2DRenderTarget = new D2D.RenderTarget(d2DFactory, surface, renderTargetProperties); SetRenderTarget(renderTarget); device.ImmediateContext.Rasterizer.SetViewport(0, 0, (int)ActualWidth, (int)ActualHeight); CompositionTarget.Rendering += CompositionTarget_Rendering; }
public Direct2DRenderer(IntPtr hwnd, bool limitFps) { _factory = new Factory(); _fontFactory = new FontFactory(); RECT bounds;//immer 1920x1080. resizing muss durch die Overlay klasse geregelt sein NativeMethods.GetWindowRect(hwnd, out bounds); var targetProperties = new HwndRenderTargetProperties { Hwnd = hwnd, PixelSize = new Size2(bounds.Right - bounds.Left, bounds.Bottom - bounds.Top), PresentOptions = limitFps ? PresentOptions.None : PresentOptions.Immediately //Immediatly -> Zeichnet sofort ohne auf 60fps zu locken. None lockt auf 60fps }; var prop = new RenderTargetProperties(RenderTargetType.Hardware, new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); _device = new WindowRenderTarget(_factory, prop, targetProperties) { TextAntialiasMode = TextAntialiasMode.Cleartype, AntialiasMode = AntialiasMode.PerPrimitive }; }
// // http://stackoverflow.com/questions/9151615/how-does-one-use-a-memory-stream-instead-of-files-when-rendering-direct2d-images // // Identical to above SO question, except that we are rendering to MemoryStream because it was added to the API // private MemoryStream RenderStaticTextToBitmap() { var width = 400; var height = 100; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); var wicBitmap = new Bitmap( wicFactory, width, height, pixelFormat, BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); var renderTarget = new WicRenderTarget( dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = TextAntialiasMode.Cleartype }; renderTarget.BeginDraw(); var textFormat = new TextFormat(dwFactory, "Consolas", 48) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center }; var textBrush = new SharpDX.Direct2D1.SolidColorBrush( renderTarget, SharpDX.Colors.Blue); renderTarget.Clear(Colors.White); renderTarget.DrawText( "Hi, mom!", textFormat, new RectangleF(0, 0, width, height), textBrush); renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream( wicFactory, ms); var encoder = new PngBitmapEncoder(wicFactory); encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return ms; }
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(); }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { // 根据 [Surface sharing between Windows graphics APIs - Win32 apps](https://docs.microsoft.com/en-us/windows/win32/direct3darticles/surface-sharing-between-windows-graphics-apis?WT.mc_id=WD-MVP-5003260 ) 文档 var width = ImageWidth; var height = ImageHeight; // 2021.12.23 不能在 x86 下运行,会炸掉。参阅 https://github.com/dotnet/Silk.NET/issues/731 var texture2DDesc = new D3D11.Texture2DDesc() { BindFlags = (uint)(D3D11.BindFlag.BindRenderTarget | D3D11.BindFlag.BindShaderResource), Format = DXGI.Format.FormatB8G8R8A8Unorm, // 最好使用此格式,否则还需要后续转换 Width = (uint)width, Height = (uint)height, MipLevels = 1, SampleDesc = new DXGI.SampleDesc(1, 0), Usage = D3D11.Usage.UsageDefault, MiscFlags = (uint)D3D11.ResourceMiscFlag.ResourceMiscShared, // The D3D11_RESOURCE_MISC_FLAG cannot be used when creating resources with D3D11_CPU_ACCESS flags. CPUAccessFlags = 0, //(uint) D3D11.CpuAccessFlag.None, ArraySize = 1 }; D3D11.ID3D11Device * pD3D11Device; D3D11.ID3D11DeviceContext *pD3D11DeviceContext; D3DFeatureLevel pD3DFeatureLevel = default; D3D11.D3D11 d3D11 = D3D11.D3D11.GetApi(); var hr = d3D11.CreateDevice((DXGI.IDXGIAdapter *)IntPtr.Zero, D3DDriverType.D3DDriverTypeHardware, Software: 0, Flags: (uint)D3D11.CreateDeviceFlag.CreateDeviceBgraSupport, (D3DFeatureLevel *)IntPtr.Zero, FeatureLevels: 0, // D3DFeatureLevel 的长度 SDKVersion: 7, (D3D11.ID3D11Device * *) & pD3D11Device, // 参阅 [C# 从零开始写 SharpDx 应用 聊聊功能等级](https://blog.lindexi.com/post/C-%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%86%99-SharpDx-%E5%BA%94%E7%94%A8-%E8%81%8A%E8%81%8A%E5%8A%9F%E8%83%BD%E7%AD%89%E7%BA%A7.html ) ref pD3DFeatureLevel, (D3D11.ID3D11DeviceContext * *) & pD3D11DeviceContext ); SilkMarshal.ThrowHResult(hr); Debugger.Launch(); Debugger.Break(); _pD3D11Device = pD3D11Device; _pD3D11DeviceContext = pD3D11DeviceContext; D3D11.ID3D11Texture2D *pD3D11Texture2D; hr = pD3D11Device->CreateTexture2D(ref texture2DDesc, (D3D11.SubresourceData *)IntPtr.Zero, &pD3D11Texture2D); SilkMarshal.ThrowHResult(hr); var renderTarget = pD3D11Texture2D; _pD3D11Texture2D = pD3D11Texture2D; DXGI.IDXGISurface *pDXGISurface; var dxgiSurfaceGuid = DXGI.IDXGISurface.Guid; renderTarget->QueryInterface(ref dxgiSurfaceGuid, (void **)&pDXGISurface); _pDXGISurface = pDXGISurface; var d2DFactory = new D2D.Factory(); var renderTargetProperties = new D2D.RenderTargetProperties(new D2D.PixelFormat(SharpDXDXGI.Format.Unknown, D2D.AlphaMode.Premultiplied)); var surface = new SharpDXDXGI.Surface(new IntPtr((void *)pDXGISurface)); _d2DRenderTarget = new D2D.RenderTarget(d2DFactory, surface, renderTargetProperties); SetRenderTarget(renderTarget); var viewport = new D3D11.Viewport(0, 0, width, height, 0, 1); pD3D11DeviceContext->RSSetViewports(NumViewports: 1, ref viewport); CompositionTarget.Rendering += CompositionTarget_Rendering; }
private void CreateAndBindTargets() { d3DSurface.SetRenderTarget( null ); Disposer.SafeDispose( ref d2DRenderTarget ); Disposer.SafeDispose( ref d2DFactory ); Disposer.SafeDispose( ref renderTarget ); var width = Math.Max((int)ActualWidth , 100); var height = Math.Max((int)ActualHeight, 100); var renderDesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; renderTarget = new Texture2D( device, renderDesc ); var surface = renderTarget.QueryInterface<Surface>(); d2DFactory = new SharpDX.Direct2D1.Factory(); var rtp = new RenderTargetProperties(new PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)); d2DRenderTarget = new RenderTarget( d2DFactory, surface, rtp ); resCache.RenderTarget = d2DRenderTarget; d3DSurface.SetRenderTarget( renderTarget ); device.ImmediateContext.Rasterizer.SetViewport( 0, 0, width, height, 0.0f, 1.0f ); }
protected void Initialize() { // Load all of the factories Factories.LoadFactories(); // Setup the graphics Console.WriteLine("Setup Graphics"); var hwndprop = new HwndRenderTargetProperties(); hwndprop.Hwnd = Handle; hwndprop.PixelSize = new Size2(Constants.Width, Constants.Height); hwndprop.PresentOptions = PresentOptions.Immediately; var rendprop = new RenderTargetProperties(); rendprop.PixelFormat = new PixelFormat(DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied); rendprop.Type = RenderTargetType.Hardware; SetClientSizeCore(Constants.Width, Constants.Height); RenderTarget2D = new WindowRenderTarget(Factories.Factory2D, rendprop, hwndprop); // Tick timer Console.WriteLine("Setup Timer"); stopwatch = new Stopwatch(); stopwatch.Start(); physicsDelayTicks = Stopwatch.Frequency / updatesPerSecond; ticksToMilliFactor = 1.0 / (Stopwatch.Frequency / 1000.0); ticksToPhysicsStepPercentFactor = 1.0 / physicsDelayTicks; lastPhysicsStepTicks = 0.0; // Load all assets and resources Constants.Load(); // Setup the main menu Console.WriteLine("Setup Menu"); GameController.LoadInitialLevel(new LevelMenu()); // Start the loop MainLoop(); }
/// <summary> /// Creates an <see cref="WindowRenderTarget"/>, a render target that renders to a window. /// </summary> /// <remarks> /// When you create a render target and hardware acceleration is available, you allocate resources on the computer's GPU. By creating a render target once and retaining it as long as possible, you gain performance benefits. Your application should create render targets once and hold onto them for the life of the application or until the {{D2DERR_RECREATE_TARGET}} error is received. When you receive this error, you need to recreate the render target (and any resources it created). /// </remarks> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="renderTargetProperties">The rendering mode, pixel format, remoting options, DPI information, and the minimum DirectX support required for hardware rendering. For information about supported pixel formats, see {{Supported Pixel Formats and Alpha Modes}}.</param> /// <param name="hwndProperties">The window handle, initial size (in pixels), and present options.</param> public WindowRenderTarget(Factory factory, RenderTargetProperties renderTargetProperties, HwndRenderTargetProperties hwndProperties) : base(IntPtr.Zero) { factory.CreateHwndRenderTarget(ref renderTargetProperties, ref hwndProperties, this); }
public VRUI(Device device, SharpDX.Toolkit.Graphics.GraphicsDevice gd) { Texture2DDescription uiTextureDescription = new Texture2DDescription() { Width = 1024, Height = 512, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, Usage = ResourceUsage.Default, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.Shared }; uiTexture = new SharpDX.Direct3D11.Texture2D(device, uiTextureDescription); using (DX2D.Factory factory2d = new DX2D.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded, DX2D.DebugLevel.Information)) { DX2D.RenderTargetProperties renderTargetProperties = new DX2D.RenderTargetProperties() { DpiX = 96, DpiY = 96, PixelFormat = new DX2D.PixelFormat(Format.B8G8R8A8_UNorm, DX2D.AlphaMode.Premultiplied), Type = DX2D.RenderTargetType.Hardware, MinLevel = DX2D.FeatureLevel.Level_10, Usage = DX2D.RenderTargetUsage.None }; using (var uiSurface = uiTexture.QueryInterface <Surface>()) target2d = new DX2D.RenderTarget(factory2d, uiSurface, renderTargetProperties) { AntialiasMode = DX2D.AntialiasMode.PerPrimitive }; } // 2D materials uiEffect = new SharpDX.Toolkit.Graphics.BasicEffect(gd) { PreferPerPixelLighting = false, Texture = SharpDX.Toolkit.Graphics.Texture2D.New(gd, uiTexture), TextureEnabled = true, LightingEnabled = false }; BlendStateDescription blendStateDescription = new BlendStateDescription() { AlphaToCoverageEnable = false }; blendStateDescription.RenderTarget[0].IsBlendEnabled = true; blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero; blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; using (var blendState = SharpDX.Toolkit.Graphics.BlendState.New(gd, blendStateDescription)) gd.SetBlendState(blendState); uiPrimitive = SharpDX.Toolkit.Graphics.GeometricPrimitive.Plane.New(gd, 2, 1); using (SharpDX.DirectWrite.Factory factoryDW = new SharpDX.DirectWrite.Factory()) { textFormat = new SharpDX.DirectWrite.TextFormat(factoryDW, "Segoe UI Light", 34f) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center }; textFormatSmall = new SharpDX.DirectWrite.TextFormat(factoryDW, "Segoe UI Light", 20f) { TextAlignment = SharpDX.DirectWrite.TextAlignment.Center, ParagraphAlignment = SharpDX.DirectWrite.ParagraphAlignment.Center }; } textBrush = new SharpDX.Direct2D1.SolidColorBrush(target2d, new Color(1f, 1f, 1f, 1f)); blueBrush = new SharpDX.Direct2D1.SolidColorBrush(target2d, new Color(0, 167, 245, 255)); uiInitialized = true; }
/// <summary> /// Creates a render target that draws to a Windows Graphics Device Interface (GDI) device context. /// </summary> /// <remarks> /// Before you can render with a DC render target, you must use the render target's {{BindDC}} method to associate it with a GDI DC. Do this for each different DC and whenever there is a change in the size of the area you want to draw to.To enable the DC render target to work with GDI, set the render target's DXGI format to <see cref="SharpDX.DXGI.Format.B8G8R8A8_UNorm"/> and alpha mode to <see cref="SharpDX.Direct2D1.AlphaMode.Premultiplied"/> or D2D1_ALPHA_MODE_IGNORE.Your application should create render targets once and hold on to them for the life of the application or until the render target's {{EndDraw}} method returns the {{D2DERR_RECREATE_TARGET}} error. When you receive this error, recreate the render target (and any resources it created). /// </remarks> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="properties">The rendering mode, pixel format, remoting options, DPI information, and the minimum DirectX support required for hardware rendering. To enable the device context (DC) render target to work with GDI, set the DXGI format to <see cref="SharpDX.DXGI.Format.B8G8R8A8_UNorm"/> and the alpha mode to <see cref="SharpDX.Direct2D1.AlphaMode.Premultiplied"/> or D2D1_ALPHA_MODE_IGNORE. For more information about pixel formats, see {{Supported Pixel Formats and Alpha Modes}}.</param> public DeviceContextRenderTarget(Factory factory, RenderTargetProperties properties) : base(IntPtr.Zero) { factory.CreateDCRenderTarget(ref properties, this); }
static Direct2DPanel() { D2DFactory = new D2D.Factory(D2D.FactoryType.SingleThreaded); D2DProps = new D2D.RenderTargetProperties(); }
/// <summary> /// Creates an <see cref="WindowRenderTarget"/>, a render target that renders to a window. /// </summary> /// <remarks> /// When you create a render target and hardware acceleration is available, you allocate resources on the computer's GPU. By creating a render target once and retaining it as long as possible, you gain performance benefits. Your application should create render targets once and hold onto them for the life of the application or until the {{D2DERR_RECREATE_TARGET}} error is received. When you receive this error, you need to recreate the render target (and any resources it created). /// </remarks> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="renderTargetProperties">The rendering mode, pixel format, remoting options, DPI information, and the minimum DirectX support required for hardware rendering. For information about supported pixel formats, see {{Supported Pixel Formats and Alpha Modes}}.</param> /// <param name="hwndProperties">The window handle, initial size (in pixels), and present options.</param> public WindowRenderTarget(Factory factory, RenderTargetProperties renderTargetProperties, HwndRenderTargetProperties hwndProperties) : base(IntPtr.Zero) { factory.CreateHwndRenderTarget(ref renderTargetProperties, hwndProperties, this); }
/// <summary> /// Creates a render target that draws to a DirectX Graphics Infrastructure (DXGI) surface. /// </summary> /// <remarks> /// To write to a Direct3D surface, you obtain an <see cref="SharpDX.DXGI.Surface"/> and pass it to the {{CreateDxgiSurfaceRenderTarget}} method to create a DXGI surface render target; you can then use the DXGI surface render target to draw 2-D content to the DXGI surface. A DXGI surface render target is a type of <see cref="SharpDX.Direct2D1.RenderTarget"/>. Like other Direct2D render targets, you can use it to create resources and issue drawing commands. The DXGI surface render target and the DXGI surface must use the same DXGI format. If you specify the {{DXGI_FORMAT_UNKOWN}} format when you create the render target, it will automatically use the surface's format.The DXGI surface render target does not perform DXGI surface synchronization. To work with Direct2D, the Direct3D device that provides the <see cref="SharpDX.DXGI.Surface"/> must be created with the D3D10_CREATE_DEVICE_BGRA_SUPPORT flag.For more information about creating and using DXGI surface render targets, see the {{Direct2D and Direct3D Interoperability Overview}}.When you create a render target and hardware acceleration is available, you allocate resources on the computer's GPU. By creating a render target once and retaining it as long as possible, you gain performance benefits. Your application should create render targets once and hold onto them for the life of the application or until the render target's {{EndDraw}} method returns the {{D2DERR_RECREATE_TARGET}} error. When you receive this error, you need to recreate the render target (and any resources it created). /// </remarks> /// <param name="factory">an instance of <see cref = "SharpDX.Direct2D1.Factory" /></param> /// <param name="dxgiSurface">The DXGI surface to bind this render target to</param> /// <param name="properties">The rendering mode, pixel format, remoting options, DPI information, and the minimum DirectX support required for hardware rendering. For information about supported pixel formats, see {{Supported Pixel Formats and Alpha Modes}}.</param> public RenderTarget(Factory factory, Surface dxgiSurface, RenderTargetProperties properties) : base(IntPtr.Zero) { factory.CreateDxgiSurfaceRenderTarget(dxgiSurface, ref properties, this); }
/// <summary> /// 使用指定的渲染目标控件创建渲染目标。 /// </summary> /// <param name="control">渲染的目标控件。</param> public void CreateRenderTarget(Control control) { if (SupportD3D) { // 创建 Direct3D SwapChain。 SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format), SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard }; this.swapChain = new SwapChain(dxgiDevice.GetParent<Adapter>().GetParent<DXGIFactory>(), d3DDevice, swapChainDesc); this.backBuffer = Surface.FromSwapChain(this.swapChain, 0); this.targetBitmap = new Bitmap1(this.d2DContext, backBuffer); this.renderTarget = new DeviceContext(this.d2DDevice, DeviceContextOptions.None); ((DeviceContext)this.renderTarget).Target = targetBitmap; } else { // 创建 Direct2D 工厂。 // 渲染参数。 RenderTargetProperties renderProps = new RenderTargetProperties { PixelFormat = D2PixelFormat, Usage = RenderTargetUsage.None, Type = RenderTargetType.Default }; // 渲染目标属性。 HwndRenderTargetProperties hwndProps = new HwndRenderTargetProperties() { Hwnd = control.Handle, PixelSize = new Size2(control.ClientSize.Width, control.ClientSize.Height), PresentOptions = PresentOptions.None }; // 渲染目标。 this.renderTarget = new WindowRenderTarget(d2DFactory, renderProps, hwndProps) { AntialiasMode = AntialiasMode.PerPrimitive }; } }
public SurfaceImageSourceCanvas(SurfaceImageSource surfaceImageSource, Rect updateRect, Direct2DFactories factories = null) : base(factories) { sisn = ComObject.As<DXGI.ISurfaceImageSourceNative> (surfaceImageSource); SharpDX.Point offset; var surface = sisn.BeginDraw (updateRect.ToRectangle (), out offset); var dpi = 96.0; var properties = new D2D1.RenderTargetProperties (D2D1.RenderTargetType.Default, new D2D1.PixelFormat (DXGI.Format.Unknown, D2D1.AlphaMode.Unknown), (float)(dpi), (float)(dpi), D2D1.RenderTargetUsage.None, D2D1.FeatureLevel.Level_DEFAULT); Initialize (new D2D1.RenderTarget (this.factories.D2DFactory, surface, properties)); }
/// <summary> /// Initializes a new instance of the <see cref="WicRenderTarget"/> class from a <see cref="SharpDX.WIC.Bitmap"/>. /// </summary> /// <param name="factory">The factory.</param> /// <param name="wicBitmap">The wic bitmap.</param> /// <param name="renderTargetProperties">The render target properties.</param> public WicRenderTarget(Factory factory, WIC.Bitmap wicBitmap, RenderTargetProperties renderTargetProperties) : base(IntPtr.Zero) { factory.CreateWicBitmapRenderTarget(wicBitmap, ref renderTargetProperties, this); }
private static void ConfigureRenderTarget(out RenderTarget description) { description.Type = RenderTargetType.Hardware; description.PixelFormat = PixelFormat; description.DpiX = 96.0f; description.DpiY = 96.0f; description.Usage = RenderTargetUsage.None; description.MinLevel = FeatureLevel.Level_10; }
private void CreateRenderObjects() { RenderTargetProperties renderTargetProperties = new RenderTargetProperties(); HwndRenderTargetProperties hwRenderTargetProperties = new HwndRenderTargetProperties() { Hwnd = this.Handle, PixelSize = new Size2(ClientSize.Width, ClientSize.Height) }; renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwRenderTargetProperties); renderObjectsCreated = true; OnCreateRenderObjects(EventArgs.Empty); }
public MemoryStream RenderToPngStream(FrameworkElement fe) { var width = (int)Math.Ceiling(fe.ActualWidth); var height = (int)Math.Ceiling(fe.ActualHeight); // pixel format with transparency/alpha channel and RGB values premultiplied by alpha var pixelFormat = WIC.PixelFormat.Format32bppPRGBA; // pixel format without transparency, but one that works with Cleartype antialiasing //var pixelFormat = WicPixelFormat.Format32bppBGR; var wicBitmap = new WIC.Bitmap( this.WicFactory, width, height, pixelFormat, WIC.BitmapCreateCacheOption.CacheOnLoad); var renderTargetProperties = new D2D.RenderTargetProperties( D2D.RenderTargetType.Default, new D2D.PixelFormat(Format.R8G8B8A8_UNorm, D2D.AlphaMode.Premultiplied), //new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), // use this for non-alpha, cleartype antialiased text 0, 0, D2D.RenderTargetUsage.None, D2D.FeatureLevel.Level_DEFAULT); var renderTarget = new D2D.WicRenderTarget( this.D2DFactory, wicBitmap, renderTargetProperties) { //TextAntialiasMode = TextAntialiasMode.Cleartype // this only works with the pixel format with no alpha channel TextAntialiasMode = D2D.TextAntialiasMode.Grayscale // this is the best we can do for bitmaps with alpha channels }; Compose(renderTarget, fe); // TODO: There is no need to encode the bitmap to PNG - we could just copy the texture pixel buffer to a WriteableBitmap pixel buffer. var ms = new MemoryStream(); var stream = new WIC.WICStream( this.WicFactory, ms); var encoder = new WIC.PngBitmapEncoder(WicFactory); encoder.Initialize(stream); var frameEncoder = new WIC.BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); var format = WIC.PixelFormat.Format32bppBGRA; //var format = WicPixelFormat.FormatDontCare; frameEncoder.SetPixelFormat(ref format); frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return(ms); }
public void Init(Output output, GDI.Rectangle srcRect) { logger.Debug("DesktopDuplicator::Init(...) " + srcRect.ToString()); try { var descr = output.Description; RawRectangle screenRect = descr.DesktopBounds; int width = screenRect.Right - screenRect.Left; int height = screenRect.Bottom - screenRect.Top; SetupRegions(screenRect, srcRect); if (descr.DeviceName == "\\\\.\\DISPLAY1") { drawRect = new Rectangle { X = 1920, Y = 0, Width = width, Height = height, }; } else if (descr.DeviceName == "\\\\.\\DISPLAY2") { drawRect = new Rectangle { X = 0, Y = 0, Width = width, Height = height, }; } screenTexture = new Texture2D(device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, }); using (SharpDX.Direct2D1.Factory1 factory2D1 = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.MultiThreaded)) { using (var surf = screenTexture.QueryInterface <Surface>()) { var pixelFormat = new Direct2D.PixelFormat(Format.B8G8R8A8_UNorm, Direct2D.AlphaMode.Premultiplied); var renderTargetProps = new Direct2D.RenderTargetProperties(pixelFormat); screenTarget = new Direct2D.RenderTarget(factory2D1, surf, renderTargetProps); } } using (var output1 = output.QueryInterface <Output1>()) { // Duplicate the output deskDupl = output1.DuplicateOutput(device); } } catch (Exception ex) { logger.Error(ex); Close(); throw; } deviceReady = true; }
/// <summary> /// 初始化绘图有关组件 /// </summary> /// <param name="width">游戏窗口宽度</param> /// <param name="height">游戏窗口高度</param> /// <param name="title">游戏窗口标题</param> private void InitRenderComponent(int width, int height, string title) { WindowSize = new Size2(width, height); var factory = new Factory(FactoryType.SingleThreaded); var hwndRenderTargetProperties = new HwndRenderTargetProperties { Hwnd = Form.Handle, PixelSize = new Size2(Form.Width, Form.Height), PresentOptions = PresentOptions.RetainContents }; var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Ignore); var renderTargetProperties = new RenderTargetProperties( RenderTargetType.Hardware, pixelFormat, 0, 0, RenderTargetUsage.None, FeatureLevel.Level_DEFAULT); renderTarget = new WindowRenderTarget(factory, renderTargetProperties, hwndRenderTargetProperties); }
private void Form1_Load(object sender, EventArgs e) { //Init Direct Draw //Set Rendering properties RenderTargetProperties renderProp = new RenderTargetProperties() { DpiX = 0, DpiY = 0, MinLevel = FeatureLevel.Level_10, PixelFormat = new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied), Type = RenderTargetType.Hardware, Usage = RenderTargetUsage.None }; //set hwnd target properties (permit to attach Direct2D to window) HwndRenderTargetProperties winProp = new HwndRenderTargetProperties() { Hwnd = this.Handle, PixelSize = new DrawingSize(this.ClientSize.Width, this.ClientSize.Height), PresentOptions = PresentOptions.Immediately }; //target creation target = new WindowRenderTarget(factory, renderProp, winProp); //create red and white brushes redBrush = new SharpDX.Direct2D1.SolidColorBrush(target, SharpDX.Color.Red); whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(target, SharpDX.Color.White); //create a linear gradient brush var grad = new LinearGradientBrushProperties() { StartPoint = new DrawingPointF(ClientSize.Width / 2, ClientSize.Height / 2), EndPoint = new DrawingPointF(ClientSize.Width, ClientSize.Height) }; var stopCollection = new GradientStopCollection(target, new GradientStop[] { new GradientStop(){Color=SharpDX.Color.Azure ,Position=0F}, new GradientStop(){Color=SharpDX.Color.Yellow,Position=0.2F}, new GradientStop(){Color=SharpDX.Color.Green,Position=0.4F}, new GradientStop(){Color=SharpDX.Color.Red,Position=1F}, }, ExtendMode.Mirror); gradient = new SharpDX.Direct2D1.LinearGradientBrush(target, grad, stopCollection); //create textformat textFormat = new SharpDX.DirectWrite.TextFormat(factoryWrite, "Arial", 36); //avoid artifacts this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); }