/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { var imageBrush = new ImageBrush(); imageBrush.ImageSource = _sisWrapper; rectangle.Fill = imageBrush; _sisWrapper.BeginDraw(); var context = new SharpDX.Direct2D1.DeviceContext(new IntPtr(_sisWrapper.GetDeviceContext())); context.Clear(new SharpDX.Color4(0.4f, 0.3f, 0.15f, 1.0f)); var random = new Random(); for (int i = 0; i < 20; ++i) { var brush = new SharpDX.Direct2D1.SolidColorBrush(context, new SharpDX.Color4( (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), 1.0f)); var left = (float)(250.0f * random.NextDouble()); var top = (float)(250.0f * random.NextDouble()); context.FillRectangle(new SharpDX.RectangleF( left, top, left + 50.0f, top + 50.0f), brush); } _sisWrapper.EndDraw(); }
private void _drawDesktopOutline(SharpDX.Direct2D1.DeviceContext d2dContext) { //BORDER d2dContext.Transform = Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale); d2dContext.DrawRectangle( _layoutDeviceScreenSize, _generalLightGrayColor, 3 ); //WIDTH d2dContext.Transform = Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale); d2dContext.FillRectangle( new RectangleF(0, -30, 100, 30), _generalLightGrayColor ); d2dContext.Transform = Matrix.Translation(10, 0, 0) * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale); d2dContext.DrawText(_layoutDetail.Width.ToString(), _generalTextFormat, new RectangleF(0, -30, 100, 30), _generalLightWhiteColor); ////HEIGHT double angleRadians = 90 * Math.PI / 180; //90 degrees d2dContext.Transform = Matrix.RotationZ((float)angleRadians) * Matrix.Identity * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale); d2dContext.FillRectangle( new RectangleF(0, 0, 100, 30), _generalLightGrayColor ); d2dContext.Transform = Matrix.RotationZ((float)angleRadians) * Matrix.Translation(0, 10, 0) * Matrix.Translation(_globalTranslation) * Matrix.Scaling(_globalScale); d2dContext.DrawText(_layoutDetail.Height.ToString(), _generalTextFormat, new RectangleF(0, 0, 100, 30), _generalLightWhiteColor); }
private void _drawSelectedTile(SharpDX.Direct2D1.DeviceContext d2dContext) { if (_selectedRect != null) { var strokeStyle_dashed = new SharpDX.Direct2D1.StrokeStyle(d2dContext.Factory, new SharpDX.Direct2D1.StrokeStyleProperties() { DashOffset = (offsetSelectedDash / 5), DashStyle = SharpDX.Direct2D1.DashStyle.Dash }); ////drown out the shadow of the tile //d2dContext.DrawRectangle( // new RectangleF(_selectedRect.Rectangle.X - 2, _selectedRect.Rectangle.Y - 2, _selectedRect.Rectangle.Width + 4, _selectedRect.Rectangle.Height + 4), // new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.White), // 4 // ); //draw an animated dash around border of tile d2dContext.DrawRectangle( new RectangleF(_selectedRect.Rectangle.X - 2, _selectedRect.Rectangle.Y - 2, _selectedRect.Rectangle.Width + 4, _selectedRect.Rectangle.Height + 4), new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Yellow), 4, strokeStyle_dashed); //_drawTiles(_selectedRect.UniqueId); offsetSelectedDash++; if (offsetSelectedDash > 100) { offsetSelectedDash = 0; } } }
/// <summary> /// Creates device resources. /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateDeviceResources() { // Dispose previous references and set to null SafeDispose(ref d3dDevice); SafeDispose(ref d3dContext); SafeDispose(ref d2dDevice); SafeDispose(ref d2dContext); // Allocate new references // Enable compatibility with Direct2D // Retrieve the Direct3D 11.1 device amd device context var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; #if DEBUG creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug; #endif using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); featureLevel = d3dDevice.FeatureLevel; // Get Direct3D 11.1 context d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>()) d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); // Create Direct2D context d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); }
public void SetHWND(IntPtr hWnd, int w, int h) { if (_hWnd == hWnd) { return; } Dispose(); _hWnd = hWnd; // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(w, h, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = hWnd, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain( SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.Debug | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); // Ignore all windows events using (var factory = swapChain.GetParent <Factory>()) { factory.MakeWindowAssociation(hWnd, WindowAssociationFlags.IgnoreAll); } Device = device; Context = Device.ImmediateContext; SwapChain = new DXGISwapChain(swapChain); // D2D using (var dxgi = Device.QueryInterface <Device2>()) { D2DDevice = new SharpDX.Direct2D1.Device(dxgi); D2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(D2DDevice, SharpDX.Direct2D1.DeviceContextOptions.None); } using (var factroy = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded)) { Dpi = factroy.DesktopDpi; } }
public SharpDX.Direct2D1.Bitmap GetD2DBitmap(SharpDX.Direct2D1.DeviceContext dc) { BitmapSource src = Frame; // PixelFormat settings/conversion if (src.Format != System.Windows.Media.PixelFormats.Bgra32) { // Convert BitmapSource FormatConvertedBitmap fcb = new FormatConvertedBitmap(); fcb.BeginInit(); fcb.Source = src; fcb.DestinationFormat = PixelFormats.Bgra32; fcb.EndInit(); src = fcb; } if (src.PixelHeight > _maxImageSize || src.PixelWidth > _maxImageSize) { double scale = (src.PixelWidth > src.PixelHeight) ? _maxImageSize / src.PixelWidth : _maxImageSize / src.PixelHeight; TransformedBitmap tb = new TransformedBitmap(); tb.BeginInit(); tb.Source = src; tb.Transform = new ScaleTransform(scale, scale); tb.EndInit(); src = tb; } SharpDX.Direct2D1.Bitmap retval = null; GCHandle pinnedArray = GCHandle.Alloc(null); try { int stride = src.PixelWidth * (src.Format.BitsPerPixel + 7) / 8; int bufferSize = stride * src.PixelHeight; byte[] buffer = new byte[bufferSize]; src.CopyPixels(System.Windows.Int32Rect.Empty, buffer, stride, 0); pinnedArray = GCHandle.Alloc(buffer, GCHandleType.Pinned); using (SharpDX.DataStream datastream = new SharpDX.DataStream(pinnedArray.AddrOfPinnedObject(), bufferSize, true, false)) { var bmpProps1 = new SharpDX.Direct2D1.BitmapProperties1(dc.PixelFormat, dc.Factory.DesktopDpi.Width, dc.Factory.DesktopDpi.Height); retval = new SharpDX.Direct2D1.Bitmap1(dc, new SharpDX.Size2(src.PixelWidth, src.PixelHeight), datastream, stride, bmpProps1); } } catch { } finally { if (pinnedArray.IsAllocated) { pinnedArray.Free(); } } return(retval); }
/// <summary> /// Creates device resources. /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateDeviceResources() { // Dispose previous references and set to null if (d3dDevice != null) { RemoveAndDispose(ref d3dDevice); } if (d3dContext != null) { RemoveAndDispose(ref d3dContext); } if (d2dDevice != null) { RemoveAndDispose(ref d2dDevice); } if (d2dContext != null) { RemoveAndDispose(ref d2dContext); } // Allocate new references // Enable compatibility with Direct2D // Retrieve the Direct3D 11.1 device amd device context var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default try { // Try to create it with Video Support // If it is not working, we just use BGRA // Force to FeatureLevel.Level_9_1 using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); } catch (Exception) { creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); } featureLevel = d3dDevice.FeatureLevel; // Get Direct3D 11.1 context d3dContext = Collect(d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>()) d2dDevice = Collect(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); // Create Direct2D context d2dContext = Collect(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); }
public PointerData(SharpDX.Direct2D1.DeviceContext context, uint id, PointerDeviceType type, Point p) { this.PointerId = id; this.DeviceType = type; this.Pointers = new List <Point>(); this.Pointers.Add(p); Random rnd = new Random(); // Colors of lines. presents in RGBA (a random value between 0.5 ~ 1.0) color = new Color4(rnd.NextFloat(0.5f, 1), rnd.NextFloat(0.5f, 1), rnd.NextFloat(0.5f, 1), 1); }
/// <summary> /// Create device manager objects /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateInstance() { // Dispose previous references and set to null RemoveAndDispose(ref d3dDevice); RemoveAndDispose(ref d3dContext); RemoveAndDispose(ref d2dDevice); RemoveAndDispose(ref d2dContext); RemoveAndDispose(ref d2dFactory); RemoveAndDispose(ref dwriteFactory); RemoveAndDispose(ref wicFactory); #region Create Direct3D 11.1 device and retrieve device context // BGRA performs better especially with Direct2D software render targets var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; #if DEBUG // Enble D3D device debug layer creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug; #endif // Retrieve the Direct3D 11.1 device and device context using (var device = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags, D3DFeatureLevel)) { d3dDevice = ToDispose(device.QueryInterface <Device1>()); } // Get Direct3D 11.1 immediate context d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface <DeviceContext1>()); #endregion #region Create Direct2D device and context #if DEBUG var debugLevel = SharpDX.Direct2D1.DebugLevel.Information; #endif // Allocate new references d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel)); dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)); wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>()) { d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); } // Create Direct2D context d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); #endregion }
private void _drawDebuggingInfo(SharpDX.Direct2D1.DeviceContext d2dContext) { if (_gt != null) { d2dContext.Transform = Matrix.Identity; d2dContext.DrawText("TotalGameTime (s) : " + _gt.TotalGameTime.TotalSeconds.ToString(), _debugTextFormat, _debugLine1, _generalRedColor); d2dContext.DrawText("FrameCount : " + _gt.FrameCount.ToString(), _debugTextFormat, _debugLine2, _generalRedColor); d2dContext.DrawText("ElapsedGameTime (s) : " + _gt.ElapsedGameTime.TotalSeconds.ToString(), _debugTextFormat, _debugLine3, _generalRedColor); d2dContext.DrawText("IsRunningSlowly : " + _gt.IsRunningSlowly.ToString(), _debugTextFormat, _debugLine4, _generalRedColor); d2dContext.DrawText("FPS : " + (_gt.FrameCount / _gt.TotalGameTime.TotalSeconds).ToString(), _debugTextFormat, _debugLine5, _generalRedColor); } }
/// <summary> /// Direct2D has no ConicGradient implementation so fall back to a solid colour brush based on /// the first gradient stop. /// </summary> public SolidColorBrushImpl(IConicGradientBrush brush, SharpDX.Direct2D1.DeviceContext target) { PlatformBrush = new SharpDX.Direct2D1.SolidColorBrush( target, brush?.GradientStops[0].Color.ToDirect2D() ?? new SharpDX.Mathematics.Interop.RawColor4(), new SharpDX.Direct2D1.BrushProperties { Opacity = brush != null ? (float)brush.Opacity : 1.0f, Transform = target.Transform } ); }
public void Draw(SharpDX.Direct2D1.DeviceContext context, RectangleF rect) { if (_brush == null) { _brush = new SharpDX.Direct2D1.SolidColorBrush(context, Color4.White); } context.Clear(Color4.Black); context.Transform = Matrix3x2.Identity; DrawText(context, rect, $"Draw: {count++}", "Verdana", 24, TextAlignment.Trailing, ParagraphAlignment.Near); //device.D2DDeviceContext.FillEllipse(new Ellipse(new Vector2(_rect.MouseX, _rect.MouseY), 50.0f, 50.0f), _brush); }
void DrawText(SharpDX.Direct2D1.DeviceContext context, RectangleF rect, string text, string font, int size, TextAlignment alignment, ParagraphAlignment pAlignment) { if (_format == null) { using (var factory = new Factory()) { _format = new TextFormat(factory, font, size); _format.TextAlignment = alignment; _format.ParagraphAlignment = pAlignment; } } context.DrawText(text, _format, rect, _brush); }
D3D11Device(SharpDX.Direct3D11.Device device) { Device = device; Context = Device.ImmediateContext; // D2D DXGIDevice = Device.QueryInterface <Device2>(); D2DDevice = new SharpDX.Direct2D1.Device(DXGIDevice); D2DDeviceContext = new SharpDX.Direct2D1.DeviceContext(D2DDevice, SharpDX.Direct2D1.DeviceContextOptions.None); using (var factroy = new SharpDX.Direct2D1.Factory(SharpDX.Direct2D1.FactoryType.SingleThreaded)) { Dpi = factroy.DesktopDpi; } }
/// <summary> /// Initializes a new instance of the <see cref="TextureResourceManager"/> class. /// </summary> /// <param name="gameEngine">The game engine.</param> public TextureResourceManager(IGameEngine gameEngine, SharpDX.Direct2D1.DeviceContext d2dContext) : base(gameEngine) { if (gameEngine == null) { throw new ArgumentNullException(nameof(gameEngine)); } if (d2dContext == null) { throw new ArgumentNullException(nameof(d2dContext)); } _d2dContext = d2dContext; _imagingFactory = new ImagingFactory(); _tileSetTextures = new Dictionary <int, SharpDX.Direct2D1.Bitmap>(); }
/// <summary> /// Called from parent when it closes to ensure this asset closes properly and leaves /// not possible memory leaks /// </summary> public void Unload() { WindowLayoutService.OnWindowLayoutRaised -= WindowLayoutService_OnWindowLayoutRaised; _root = null; _rootParent = null; _clearRenderTree(); ClearAssets(); _clock = null; _gt = null; _tweener = null; _deviceManager = null; _d2dContext = null; if (_stagingBitmap != null) { _stagingBitmap.Dispose(); _stagingBitmap = null; } if (_stagingBitmapSourceEffect != null) { _stagingBitmapSourceEffect.Dispose(); _stagingBitmapSourceEffect = null; } if (_stagingTexture2D != null) { _stagingTexture2D.Dispose(); _stagingTexture2D = null; } _pathD2DConverter = null; //_graphicsDevice.Dispose(); //_graphicsDevice = null; }
public DUIDeviceContext(IntPtr handle) { this.d3d11Device = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); this.dxgiDevice = d3d11Device.QueryInterface <SharpDX.Direct3D11.Device1>().QueryInterface <SharpDX.DXGI.Device>(); this.d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice); this.deviceContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // 创建 DXGI SwapChain。 SharpDX.DXGI.SwapChainDescription swapChainDescription = new SharpDX.DXGI.SwapChainDescription() { BufferCount = 1, Usage = SharpDX.DXGI.Usage.RenderTargetOutput, OutputHandle = handle, IsWindowed = true, // 这里宽度和高度都是 0,表示自动获取。 ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.B8G8R8A8_UNorm), SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), SwapEffect = SharpDX.DXGI.SwapEffect.Discard }; this.swapChain = new SharpDX.DXGI.SwapChain(dxgiDevice.GetParent <SharpDX.DXGI.Adapter>().GetParent <SharpDX.DXGI.Factory>(), d3d11Device, swapChainDescription); this.swapChainBuffer = SharpDX.DXGI.Surface.FromSwapChain(this.swapChain, 0); this.targetBitmap = new SharpDX.Direct2D1.Bitmap1(this.deviceContext, this.swapChainBuffer); this.deviceContext.Target = targetBitmap; }
private void OnLoaded(object sender, RoutedEventArgs e) { ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.TranslateInertia | ManipulationModes.Scale; tileBackground.ImageSource = "Assets/bgline.JPG"; onePointWait.Visibility = Visibility.Collapsed; twoPointWait.Visibility = Visibility.Collapsed; double val = -Math.PI / 2; foreach (UIElement child in colorSelect.Children) { child.SetValue(Canvas.LeftProperty, Math.Cos(val) * 70); child.SetValue(Canvas.TopProperty, Math.Sin(val) * 70); val += Math.PI / 5; } var debugLevel = SharpDX.Direct2D1.DebugLevel.None; d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel); var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; using (var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); d3dContext = d3dDevice.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); using (dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>()) d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); DisplayProperties.LogicalDpiChanged += LogicalDpiChanged; }
/// <summary> /// Initializes a new instance of the <see cref="SpriteResourceManager"/> class. /// </summary> /// <param name="gameEngine">The game engine.</param> public SpriteResourceManager(IGameEngine gameEngine, SharpDX.Direct2D1.DeviceContext d2dContext) : base(gameEngine) { if (gameEngine == null) { throw new ArgumentNullException(nameof(gameEngine)); } if (d2dContext == null) { throw new ArgumentNullException(nameof(d2dContext)); } _d2dContext = d2dContext; _imagingFactory = new ImagingFactory(); _spriteTextures = new Dictionary <int, SharpDX.Direct2D1.Bitmap>(); _animationRects = new Dictionary <int, Dictionary <int, RawRectangleF[]> >(); var imagePath = Path.Combine(_resourceService.GetResourcePath <Sprite>(), "notfound.png"); using (var decoder = new BitmapDecoder(_imagingFactory, imagePath, DecodeOptions.CacheOnDemand)) { using (var formatConverter = new FormatConverter(_imagingFactory)) { formatConverter.Initialize( decoder.GetFrame(0), PixelFormat.Format32bppPBGRA, BitmapDitherType.DualSpiral8x8, null, 0.0, BitmapPaletteType.Custom); _notFound = SharpDX.Direct2D1.Bitmap1.FromWicBitmap(_d2dContext, formatConverter); } } }
public void Initialize(CommonDX.DeviceManager deviceManager) { _deviceManager = deviceManager; _d2dContext = deviceManager.ContextDirect2D; _generalGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Gray); _generalRedColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Red); _generalLightGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.LightGray); _generalLightWhiteColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.White); _generalTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 16f); _debugTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 20f); _layoutDetail = new LayoutDetail() { Width = this.State.DrawingSurfaceWidth, Height = this.State.DrawingSurfaceHeight }; _layoutDeviceScreenSize = new RectangleF(0, 0, (float)_layoutDetail.Width, (float)_layoutDetail.Height); _appWidth = (float)_layoutDetail.Width + 5; _appHeight = (float)_layoutDetail.Height; _updateScaleTranslate(1.0f); ////_drawTiles(0); if (State.DefaultBackgroundUri != string.Empty) { _clearRenderTree(); _changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, State.DefaultBackgroundFolder, State.DefaultBackgroundUri, "", Color.White, 0.7f, "", false); } //GestureService.OnGestureRaised += (o,a) => { // CustomGestureArgs gestureArgs = (CustomGestureArgs)a; // //NumberFramesToRender += 3; // if (gestureArgs.ManipulationStartedArgs != null) // { // _isInertialTranslationStaging = false; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationInertiaStartingArgs != null) // { // _isInertialTranslationStaging = true; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationUpdatedArgs != null) // { // if(_isInertialTranslationStaging) // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Velocities.Linear.X); // else // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Cumulative.Translation.X); // } // else if (gestureArgs.ManipulationCompletedArgs != null) // { // if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale < 1) // { // if (_globalScale.X != 0.9f) { _updateBackgroundTweener(1.0f, 0.9f, 1.2f); SendInformationNotification("zoom level at 90%", 3); } // //_updateScaleTranslate(0.9f); // } // else if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale > 1) // { // if (_globalScale.X != 1.0f) { _updateBackgroundTweener(0.9f, 1.0f, 1.2f); SendInformationNotification("zoom level at 100%", 3); } // //_updateScaleTranslate(1.0f); // } // _globalCameraTranslation = _globalCameraTranslation + _globalCameraTranslationStaging; // _globalCameraTranslationStaging = Vector3.Zero; // _isInertialTranslationStaging = false; // } // else if (gestureArgs.TappedEventArgs != null) // { // var x = gestureArgs.TappedEventArgs.Position.X - _globalCameraTranslation.X; // var y = gestureArgs.TappedEventArgs.Position.Y - _globalCameraTranslation.Y; // var found = _doTilesHitTest((float)x, (float)y); // if (found != null && found.Count > 0) // { // _selectedRect = found[0]; // } // else _selectedRect = null; // } //}; WindowLayoutService.OnWindowLayoutRaised += WindowLayoutService_OnWindowLayoutRaised; }
/// <summary> /// Creates device resources. /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateDeviceResources() { // Dispose previous references and set to null SafeDispose(ref d3dDevice); SafeDispose(ref d3dContext); SafeDispose(ref d2dDevice); SafeDispose(ref d2dContext); // Allocate new references // Enable compatibility with Direct2D // Retrieve the Direct3D 11.1 device amd device context var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; #if DEBUG creationFlags |= SharpDX.Direct3D11.DeviceCreationFlags.Debug; #endif using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); featureLevel = d3dDevice.FeatureLevel; // Get Direct3D 11.1 context d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); // Create Direct2D context d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); }
/// <summary> /// <p>Creates a new Direct2D device context associated with a DXGI surface. </p> /// </summary> /// <param name = "dxgiSurface"><dd> <p>The DXGI surface the Direct2D device context is associated with.</p> </dd></param> /// <param name = "creationProperties"><dd> <p>The properties to apply to the Direct2D device context.</p> </dd></param> /// <param name = "d2dDeviceContext"><dd> <p>When this function returns, contains the address of a reference to a Direct2D device context.</p> </dd></param> /// <returns><p>The function returns an <strong><see cref = "SharpDX.Result"/></strong>. Possible values include, but are not limited to, those in the following table.</p><table> <tr><th><see cref = "SharpDX.Result"/></th><th>Description</th></tr> <tr><td><see cref = "SharpDX.Result.Ok"/></td><td>No error occurred.</td></tr> <tr><td>E_OUTOFMEMORY</td><td>Direct2D could not allocate sufficient memory to complete the call.</td></tr> <tr><td>E_INVALIDARG</td><td>An invalid value was passed to the method.</td></tr> </table><p>?</p></returns> /// <remarks> /// <p>This function will also create a new <strong><see cref = "SharpDX.Direct2D1.Factory1"/></strong> that can be retrieved through <strong>ID2D1Resource::GetFactory</strong>.</p><p>This function will also create a new <strong><see cref = "SharpDX.Direct2D1.Device"/></strong> that can be retrieved through <strong>ID2D1DeviceContext::GetDevice</strong>.</p><p>The DXGI device will be specified implicitly through <em>dxgiSurface</em>.</p><p>If <em>creationProperties</em> are not specified, the Direct2D device will inherit its threading mode from the DXGI device implied by <em>dxgiSurface</em> and debug tracing will not be enabled.</p> /// </remarks> /// <doc-id>hh404273</doc-id> /// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out, Fast] ID2D1DeviceContext** d2dDeviceContext)</unmanaged> /// <unmanaged-short>D2D1CreateDeviceContext</unmanaged-short> public static unsafe void CreateDeviceContext(SharpDX.DXGI.Surface dxgiSurface, SharpDX.Direct2D1.CreationProperties?creationProperties, SharpDX.Direct2D1.DeviceContext d2dDeviceContext) { System.IntPtr dxgiSurface_ = System.IntPtr.Zero; SharpDX.Direct2D1.CreationProperties creationProperties_; System.IntPtr d2dDeviceContext_ = System.IntPtr.Zero; SharpDX.Result __result__; dxgiSurface_ = SharpDX.CppObject.ToCallbackPtr <SharpDX.DXGI.Surface>(dxgiSurface); if (creationProperties != null) creationProperties_ = creationProperties.Value; }
/* DEVICE MANAGER METHODS */ /// <summary> /// Initialize resources and trigger an initialization event for all registered listeners /// </summary> public void Initialize(Tesseract gameEngine) { // Release any pre-exisitng references ReleaseResources(); // Retrieve the Direct3D 11.1 device using (var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, FeatureLevel)) { Device3D = ToDispose(device.QueryInterface<Device1>()); } // Get the Direct3D 11.1 context Context3D = ToDispose(Device3D.ImmediateContext.QueryInterface<DeviceContext1>()); // Create the remaining references Factory2D = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded)); FactoryDW = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)); FactoryWIC = ToDispose(new SharpDX.WIC.ImagingFactory2()); // Create the Direct2D device using (var device = Device3D.QueryInterface<SharpDX.DXGI.Device>()) { Device2D = ToDispose(new SharpDX.Direct2D1.Device(Factory2D, device)); } // Create the Direct2D context Context2D = ToDispose(new SharpDX.Direct2D1.DeviceContext(Device2D, SharpDX.Direct2D1.DeviceContextOptions.None)); }
/// <summary> /// Creates device resources. /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateDeviceResources() { // Dispose previous references and set to null RemoveAndDispose(ref d3dDevice); RemoveAndDispose(ref d3dContext); RemoveAndDispose(ref d2dDevice); RemoveAndDispose(ref d2dContext); // Allocate new references // Enable compatibility with Direct2D // Retrieve the Direct3D 11.1 device amd device context var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport | SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; // Decomment this line to have Debug. Unfortunately, debug is sometimes crashing applications, so it is disable by default try { // Try to create it with Video Support // If it is not working, we just use BGRA // Force to FeatureLevel.Level_9_1 using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); } catch (Exception) { creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); } featureLevel = d3dDevice.FeatureLevel; // Get Direct3D 11.1 context d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); // Create Direct2D context d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); }
/// <summary> /// <p>Creates a new Direct2D device context associated with a DXGI surface. </p> /// </summary> /// <param name="dxgiSurface"><dd> <p>The DXGI surface the Direct2D device context is associated with.</p> </dd></param> /// <param name="creationProperties"><dd> <p>The properties to apply to the Direct2D device context.</p> </dd></param> /// <param name="d2dDeviceContext"><dd> <p>When this function returns, contains the address of a reference to a Direct2D device context.</p> </dd></param> /// <returns><p>The function returns an <strong><see cref="SharpDX.Result"/></strong>. Possible values include, but are not limited to, those in the following table.</p><table> <tr><th><see cref="SharpDX.Result"/></th><th>Description</th></tr> <tr><td><see cref="SharpDX.Result.Ok"/></td><td>No error occurred.</td></tr> <tr><td>E_OUTOFMEMORY</td><td>Direct2D could not allocate sufficient memory to complete the call.</td></tr> <tr><td>E_INVALIDARG</td><td>An invalid value was passed to the method.</td></tr> </table><p>?</p></returns> /// <remarks> /// <p>This function will also create a new <strong><see cref="SharpDX.Direct2D1.Factory1"/></strong> that can be retrieved through <strong><see cref="SharpDX.Direct2D1.Resource.GetFactory"/></strong>.</p><p>This function will also create a new <strong><see cref="SharpDX.Direct2D1.Device"/></strong> that can be retrieved through <strong><see cref="SharpDX.Direct2D1.DeviceContext.GetDevice"/></strong>.</p><p>The DXGI device will be specified implicitly through <em>dxgiSurface</em>.</p><p>The created device context will have exactly the same behavior as if <strong>ID2D1DeviceContext::SetTargetSurface</strong> were called with the corresponding surface.</p><p>If <em>creationProperties</em> are not specified, the Direct2D device will inherit its threading mode from the DXGI device implied by <em>dxgiSurface</em> and debug tracing will not be enabled.</p><p><strong>Windows Phone 8.1:</strong> This API is supported.</p> /// </remarks> /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='D2D1CreateDeviceContext']/*"/> /// <msdn-id>hh404273</msdn-id> /// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out, Fast] ID2D1DeviceContext** d2dDeviceContext)</unmanaged> /// <unmanaged-short>D2D1CreateDeviceContext</unmanaged-short> public static void CreateDeviceContext(SharpDX.DXGI.Surface dxgiSurface, SharpDX.Direct2D1.CreationProperties?creationProperties, SharpDX.Direct2D1.DeviceContext d2dDeviceContext) { unsafe { SharpDX.Direct2D1.CreationProperties creationProperties_; if (creationProperties.HasValue) { creationProperties_ = creationProperties.Value; } IntPtr d2dDeviceContext_ = IntPtr.Zero; SharpDX.Result __result__; __result__ = D2D1CreateDeviceContext_((void *)((dxgiSurface == null)?IntPtr.Zero:dxgiSurface.NativePointer), (creationProperties.HasValue)?&creationProperties_:(void *)IntPtr.Zero, &d2dDeviceContext_); ((SharpDX.Direct2D1.DeviceContext)d2dDeviceContext).NativePointer = d2dDeviceContext_; __result__.CheckError(); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect color sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface <SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); KinectBody[] bodyFrame = null; KinectSensorBodyFrameProvider bodyProvider = new KinectSensorBodyFrameProvider(sensor); bool doQuit = false; bool doUpload = false; ColorRGBAFrameData currentData = null; DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device); KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); provider.FrameReceived += (sender, args) => { currentData = args.FrameData; doUpload = true; }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; FaceFrameResult frameResult = null; SingleFaceProcessor faceProcessor = new SingleFaceProcessor(sensor); faceProcessor.FaceResultAcquired += (sender, args) => { frameResult = args.FrameResult; }; Func <PointF, Vector2> map = new Func <PointF, Vector2>((p) => { float x = p.X / 1920.0f * (float)swapChain.Width; float y = p.Y / 1080.0f * (float)swapChain.Height; return(new Vector2(x, y)); }); Func <float, float, Vector2> mapxy = new Func <float, float, Vector2>((px, py) => { float x = px / 1920.0f * (float)swapChain.Width; float y = py / 1080.0f * (float)swapChain.Height; return(new Vector2(x, y)); }); bodyProvider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; var body = bodyFrame.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { faceProcessor.AssignBody(body); } else { faceProcessor.Suspend(); } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } if (doUpload) { colorTexture.Copy(context, currentData); } context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorTexture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); if (frameResult != null) { context2d.BeginDraw(); var colorBound = frameResult.FaceBoundingBoxInColorSpace; RectangleF rect = new RectangleF(); Vector2 topLeft = mapxy(colorBound.Left, colorBound.Top); Vector2 bottomRight = mapxy(colorBound.Right, colorBound.Bottom); rect.Top = topLeft.Y; rect.Bottom = bottomRight.Y; rect.Left = topLeft.X; rect.Right = bottomRight.X; context2d.DrawRectangle(rect, whiteBrush, 3.0f); foreach (PointF point in frameResult.FacePointsInColorSpace.Values) { var ellipse = new SharpDX.Direct2D1.Ellipse() { Point = map(point), RadiusX = 5, RadiusY = 5 }; context2d.FillEllipse(ellipse, whiteBrush); } context2d.EndDraw(); } swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorTexture.Dispose(); provider.Dispose(); bodyProvider.Dispose(); faceProcessor.Dispose(); whiteBrush.Dispose(); context2d.Dispose(); sensor.Close(); }
void InitText(SwapChain3 tempSwapChain) { init = true; device = tempSwapChain.GetDevice <SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); var texture2d = tempSwapChain.GetBackBuffer <Texture2D>(0); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); SharpDX.Direct2D1.BitmapProperties1 properties = new SharpDX.Direct2D1.BitmapProperties1( new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), 96, 96, SharpDX.Direct2D1.BitmapOptions.Target | SharpDX.Direct2D1.BitmapOptions.CannotDraw); Surface backBuffer = tempSwapChain.GetBackBuffer <Surface>(0); d2dTarget = new SharpDX.Direct2D1.Bitmap1(d2dContext, new Size2(800, 600), properties); solidBrush = new SharpDX.Direct2D1.SolidColorBrush(d2dContext, Color.Coral); // Create a linear gradient brush. // Note that the StartPoint and EndPoint values are set as absolute coordinates of the surface you are drawing to, // NOT the geometry we will apply the brush. linearGradientBrush = new SharpDX.Direct2D1.LinearGradientBrush(d2dContext, new SharpDX.Direct2D1.LinearGradientBrushProperties() { StartPoint = new Vector2(50, 0), EndPoint = new Vector2(450, 0), }, new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[] { new SharpDX.Direct2D1.GradientStop() { Color = Color.Blue, Position = 0, }, new SharpDX.Direct2D1.GradientStop() { Color = Color.Green, Position = 1, } })); SharpDX.Direct2D1.RadialGradientBrushProperties rgb = new SharpDX.Direct2D1.RadialGradientBrushProperties() { Center = new Vector2(250, 525), RadiusX = 100, RadiusY = 100, }; // Create a radial gradient brush. // The center is specified in absolute coordinates, too. radialGradientBrush = new SharpDX.Direct2D1.RadialGradientBrush(d2dContext, ref rgb , new SharpDX.Direct2D1.GradientStopCollection(d2dContext, new SharpDX.Direct2D1.GradientStop[] { new SharpDX.Direct2D1.GradientStop() { Color = Color.Yellow, Position = 0, }, new SharpDX.Direct2D1.GradientStop() { Color = Color.Red, Position = 1, } })); }
private void OnLoaded(object sender, RoutedEventArgs e) { ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.TranslateInertia | ManipulationModes.Scale; tileBackground.ImageSource = "Assets/bgline.JPG"; onePointWait.Visibility = Visibility.Collapsed; twoPointWait.Visibility = Visibility.Collapsed; double val = -Math.PI / 2; foreach (UIElement child in colorSelect.Children) { child.SetValue(Canvas.LeftProperty, Math.Cos(val) * 70); child.SetValue(Canvas.TopProperty, Math.Sin(val) * 70); val += Math.PI / 5; } var debugLevel = SharpDX.Direct2D1.DebugLevel.None; d2dFactory = new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel); var creationFlags = SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport; using (var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags)) d3dDevice = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>(); d3dContext = d3dDevice.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>(); using (dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>()) d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); DisplayProperties.LogicalDpiChanged += LogicalDpiChanged; }
public object Convert(object value, Type targetType, object parameter, string language) { MyChildRenderItem.RenderDataStruct Item = (MyChildRenderItem.RenderDataStruct)value; if (Item.FontSize != AppSettings.dFontSize) { Item.sizeFunc(); //cannot react this late Item = (MyChildRenderItem.RenderDataStruct)value; } int pixelWidth = (int)Item.Width, pixelHeight = (int)Item.Height; SurfaceImageSource newSource = new SurfaceImageSource(pixelWidth, pixelHeight, false); //SharpDX.Direct3D11.Device D3DDev = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.DXGI.Device DXDev = D3DDev.QueryInterface<SharpDX.DXGI.Device>(); #if WINDOWS_PHONE_APP || !STORETOOLKIT SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNativeWithD2D>(newSource); #else SharpDX.DXGI.ISurfaceImageSourceNative surfaceImageSourceNative = SharpDX.ComObject.As<SharpDX.DXGI.ISurfaceImageSourceNative>(newSource); #endif SharpDX.Rectangle rt = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight); #if WINDOWS_PHONE_APP || !STORETOOLKIT SharpDX.Point pt; IntPtr obj; surfaceImageSourceNative.Device = TextShaping.Dev2D; surfaceImageSourceNative.BeginDraw(rt, new Guid("e8f7fe7a-191c-466d-ad95-975678bda998"), out obj, out pt); //d2d1_1.h SharpDX.Direct2D1.DeviceContext devcxt = SharpDX.ComObject.As<SharpDX.Direct2D1.DeviceContext>(obj); #else SharpDX.DrawingPoint pt; surfaceImageSourceNative.Device = TextShaping.DXDev; SharpDX.DXGI.Surface surf = surfaceImageSourceNative.BeginDraw(rt, out pt); SharpDX.Direct2D1.DeviceContext devcxt = new SharpDX.Direct2D1.DeviceContext(surf); //SharpDX.Direct2D1.Bitmap1 bmp = new SharpDX.Direct2D1.Bitmap1(devcxt, surf, new SharpDX.Direct2D1.BitmapProperties1() { DpiX = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiX, DpiY = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawDpiY, PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), BitmapOptions = SharpDX.Direct2D1.BitmapOptions.CannotDraw | SharpDX.Direct2D1.BitmapOptions.Target }); //devcxt.Target = bmp; devcxt.BeginDraw(); #endif devcxt.Clear(new SharpDX.Color4(Windows.UI.Colors.White.R / 255.0f, Windows.UI.Colors.White.G / 255.0f, Windows.UI.Colors.White.B / 255.0f, Windows.UI.Colors.Transparent.A / 255.0f)); SharpDX.Direct2D1.Layer lyr = new SharpDX.Direct2D1.Layer(devcxt); //SharpDX.RectangleF.Infinite devcxt.PushLayer(new SharpDX.Direct2D1.LayerParameters1(new SharpDX.RectangleF(float.NegativeInfinity, float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity), null, SharpDX.Direct2D1.AntialiasMode.PerPrimitive, SharpDX.Matrix3x2.Identity, 1.0f, null, SharpDX.Direct2D1.LayerOptions1.None), lyr); devcxt.PushAxisAlignedClip(new SharpDX.RectangleF(pt.X, pt.Y, pt.X + pixelWidth, pt.Y + pixelHeight), SharpDX.Direct2D1.AntialiasMode.PerPrimitive); devcxt.Transform = SharpDX.Matrix3x2.Translation(pt.X, pt.Y); SharpDX.DirectWrite.GlyphRun gr = new SharpDX.DirectWrite.GlyphRun(); gr.FontFace = TextShaping.DWFontFace; gr.FontSize = (float)TopLevelFontSize; gr.BidiLevel = -1; int curlen = 0; for (int ct = 0; ct < Item.ItemRuns.Count(); ct++) { int newlen = curlen + Item.ItemRuns[ct].ItemText.Length; gr.Indices = Item.indices.Skip(Item.clusters[curlen]).TakeWhile((indice, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); gr.Offsets = Item.offsets.Skip(Item.clusters[curlen]).TakeWhile((offset, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); gr.Advances = Item.advances.Skip(Item.clusters[curlen]).TakeWhile((advance, idx) => ct == Item.ItemRuns.Count() - 1 || idx < Item.clusters[newlen]).ToArray(); if (Item.ItemRuns[ct].ItemText[0] == XMLRender.ArabicData.ArabicEndOfAyah) gr.Advances[0] = 0; SharpDX.Direct2D1.SolidColorBrush brsh = new SharpDX.Direct2D1.SolidColorBrush(devcxt, new SharpDX.Color4(XMLRender.Utility.ColorR(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorG(Item.ItemRuns[ct].Clr) / 255.0f, XMLRender.Utility.ColorB(Item.ItemRuns[ct].Clr) / 255.0f, 0xFF / 255.0f)); devcxt.DrawGlyphRun(new SharpDX.Vector2((float) pt.X + (float)pixelWidth + Item.offsets[0].AdvanceOffset - (Item.clusters[curlen] == 0 ? 0 : Item.advances.Take(Item.clusters[curlen]).Sum()), Item.BaseLine), gr, brsh, SharpDX.Direct2D1.MeasuringMode.Natural); brsh.Dispose(); curlen = newlen; } devcxt.Transform = SharpDX.Matrix3x2.Identity; devcxt.PopAxisAlignedClip(); devcxt.PopLayer(); #if WINDOWS_PHONE_APP || !STORETOOLKIT gr.Dispose(); #else gr.FontFace = null; #endif #if WINDOWS_PHONE_APP || !STORETOOLKIT #else devcxt.EndDraw(); devcxt.Target = null; //bmp.Dispose(); #endif devcxt.Dispose(); #if WINDOWS_PHONE_APP || !STORETOOLKIT #else surf.Dispose(); #endif surfaceImageSourceNative.EndDraw(); surfaceImageSourceNative.Device = null; surfaceImageSourceNative.Dispose(); //DXDev.Dispose(); //D3DDev.Dispose(); return newSource; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect simple pilot sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface<SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var textFormat = new SharpDX.DirectWrite.TextFormat(device.DWriteFactory, "Arial", 16.0f); var blackBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.Black); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); bool doQuit = false; KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); DynamicColorRGBATextureProcessor colorProcessor = new DynamicColorRGBATextureProcessor(provider, device); KinectPilotProcessor pilot = KinectPilotProcessor.Default; KinectSensorBodyFrameProvider bodyFrameProvider = new KinectSensorBodyFrameProvider(sensor); bodyFrameProvider.FrameReceived += (sender, args) => { var body = args.FrameData.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { pilot.Process(body.GetJointTable()); } }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } colorProcessor.Update(context); context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorProcessor.Texture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); context2d.BeginDraw(); var rect = new SharpDX.RectangleF(0, 0, 200, 130); context2d.FillRectangle(rect, blackBrush); context2d.DrawText("Elevation: " + pilot.Elevation, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Y: " + pilot.SteeringY, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Z: " + pilot.SterringZ, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Push: " + pilot.Push, textFormat, rect, whiteBrush); context2d.EndDraw(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorProcessor.Dispose(); provider.Dispose(); sensor.Close(); }
public void Initialize(CommonDX.DeviceManager deviceManager) { _deviceManager = deviceManager; _d2dContext = deviceManager.ContextDirect2D; _generalGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Gray); _generalRedColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.Red); _generalLightGrayColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.LightGray); _generalLightWhiteColor = new SharpDX.Direct2D1.SolidColorBrush(_deviceManager.ContextDirect2D, Color.White); _generalTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 16f); _debugTextFormat = new SharpDX.DirectWrite.TextFormat( _deviceManager.FactoryDirectWrite, "Segoe UI", SharpDX.DirectWrite.FontWeight.Light, SharpDX.DirectWrite.FontStyle.Normal, SharpDX.DirectWrite.FontStretch.Normal, 20f); _layoutDetail = new LayoutDetail() { Width = this.State.DrawingSurfaceWidth, Height = this.State.DrawingSurfaceHeight }; _layoutDeviceScreenSize = new RectangleF(0, 0, (float)_layoutDetail.Width, (float)_layoutDetail.Height); _appWidth = (float)_layoutDetail.Width + 5; _appHeight = (float)_layoutDetail.Height; _updateScaleTranslate(1.0f); ////_drawTiles(0); if (State.DefaultBackgroundUri != string.Empty) { _clearRenderTree(); _changeBackgroundImpl(1, _appWidth, _appHeight, 0, 0, State.DefaultBackgroundFolder, State.DefaultBackgroundUri, "", Color.White, 0.7f, "", false); } //GestureService.OnGestureRaised += (o,a) => { // CustomGestureArgs gestureArgs = (CustomGestureArgs)a; // //NumberFramesToRender += 3; // if (gestureArgs.ManipulationStartedArgs != null) // { // _isInertialTranslationStaging = false; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationInertiaStartingArgs != null) // { // _isInertialTranslationStaging = true; // _globalCameraTranslationStaging = _globalCameraTranslation; // } // else if (gestureArgs.ManipulationUpdatedArgs != null) // { // if(_isInertialTranslationStaging) // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Velocities.Linear.X); // else // _updateCameraTranslationStaging((float)gestureArgs.ManipulationUpdatedArgs.Cumulative.Translation.X); // } // else if (gestureArgs.ManipulationCompletedArgs != null) // { // if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale < 1) // { // if (_globalScale.X != 0.9f) { _updateBackgroundTweener(1.0f, 0.9f, 1.2f); SendInformationNotification("zoom level at 90%", 3); } // //_updateScaleTranslate(0.9f); // } // else if (gestureArgs.ManipulationCompletedArgs.Cumulative.Scale > 1) // { // if (_globalScale.X != 1.0f) { _updateBackgroundTweener(0.9f, 1.0f, 1.2f); SendInformationNotification("zoom level at 100%", 3); } // //_updateScaleTranslate(1.0f); // } // _globalCameraTranslation = _globalCameraTranslation + _globalCameraTranslationStaging; // _globalCameraTranslationStaging = Vector3.Zero; // _isInertialTranslationStaging = false; // } // else if (gestureArgs.TappedEventArgs != null) // { // var x = gestureArgs.TappedEventArgs.Position.X - _globalCameraTranslation.X; // var y = gestureArgs.TappedEventArgs.Position.Y - _globalCameraTranslation.Y; // var found = _doTilesHitTest((float)x, (float)y); // if (found != null && found.Count > 0) // { // _selectedRect = found[0]; // } // else _selectedRect = null; // } //}; WindowLayoutService.OnWindowLayoutRaised += WindowLayoutService_OnWindowLayoutRaised; }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect color sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface<SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); KinectBody[] bodyFrame = null; KinectSensorBodyFrameProvider bodyProvider = new KinectSensorBodyFrameProvider(sensor); bool doQuit = false; bool doUpload = false; ColorRGBAFrameData currentData = null; DynamicColorRGBATexture colorTexture = new DynamicColorRGBATexture(device); KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); provider.FrameReceived += (sender, args) => { currentData = args.FrameData; doUpload = true; }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; FaceFrameResult frameResult = null; SingleFaceProcessor faceProcessor = new SingleFaceProcessor(sensor); faceProcessor.FaceResultAcquired += (sender, args) => { frameResult = args.FrameResult; }; Func<PointF, Vector2> map = new Func<PointF, Vector2>((p) => { float x = p.X / 1920.0f * (float)swapChain.Width; float y = p.Y / 1080.0f * (float)swapChain.Height; return new Vector2(x,y); }); Func<float,float, Vector2> mapxy = new Func<float,float, Vector2>((px,py) => { float x = px / 1920.0f * (float)swapChain.Width; float y = py / 1080.0f * (float)swapChain.Height; return new Vector2(x,y); }); bodyProvider.FrameReceived += (sender, args) => { bodyFrame = args.FrameData; var body = bodyFrame.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { faceProcessor.AssignBody(body); } else { faceProcessor.Suspend(); } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } if (doUpload) { colorTexture.Copy(context, currentData); } context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorTexture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); if (frameResult != null) { context2d.BeginDraw(); var colorBound = frameResult.FaceBoundingBoxInColorSpace; RectangleF rect = new RectangleF(); Vector2 topLeft = mapxy(colorBound.Left, colorBound.Top); Vector2 bottomRight = mapxy(colorBound.Right, colorBound.Bottom); rect.Top = topLeft.Y; rect.Bottom = bottomRight.Y; rect.Left = topLeft.X; rect.Right = bottomRight.X; context2d.DrawRectangle(rect, whiteBrush, 3.0f); foreach (PointF point in frameResult.FacePointsInColorSpace.Values) { var ellipse = new SharpDX.Direct2D1.Ellipse() { Point = map(point), RadiusX = 5, RadiusY = 5 }; context2d.FillEllipse(ellipse, whiteBrush); } context2d.EndDraw(); } swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorTexture.Dispose(); provider.Dispose(); bodyProvider.Dispose(); faceProcessor.Dispose(); whiteBrush.Dispose(); context2d.Dispose(); sensor.Close(); }
/// <summary> /// Called from parent when it closes to ensure this asset closes properly and leaves /// not possible memory leaks /// </summary> public void Unload() { WindowLayoutService.OnWindowLayoutRaised -= WindowLayoutService_OnWindowLayoutRaised; _root = null; _rootParent = null; _clearRenderTree(); ClearAssets(); _clock = null; _gt = null; _tweener = null; _deviceManager = null; _d2dContext = null; if (_stagingBitmap != null) { _stagingBitmap.Dispose(); _stagingBitmap = null; } if (_stagingBitmapSourceEffect != null) { _stagingBitmapSourceEffect.Dispose(); _stagingBitmapSourceEffect = null; } if (_stagingTexture2D != null) { _stagingTexture2D.Dispose(); _stagingTexture2D = null; } _pathD2DConverter = null; //_graphicsDevice.Dispose(); //_graphicsDevice = null; }
/// <summary> /// Creates device manager objects /// </summary> /// <remarks> /// This method is called at the initialization of this instance. /// </remarks> protected virtual void CreateInstances() { // Dispose previous references and set to null RemoveAndDispose(ref d3dDevice); RemoveAndDispose(ref d3dContext); RemoveAndDispose(ref d2dDevice); RemoveAndDispose(ref d2dContext); RemoveAndDispose(ref d2dFactory); RemoveAndDispose(ref dwriteFactory); RemoveAndDispose(ref wicFactory); #region Create Direct3D 11.1 device and retrieve device context // Bgra performs better especially with Direct2D software // render targets var creationFlags = DeviceCreationFlags.BgraSupport; #if DEBUG // Enable D3D device debug layer creationFlags |= DeviceCreationFlags.Debug; #endif // Retrieve the Direct3D 11.1 device and device context using (var device = new Device(DriverType.Hardware, creationFlags, Direct3DFeatureLevels)) { d3dDevice = ToDispose(device.QueryInterface<Device1>()); } // Get Direct3D 11.1 context d3dContext = ToDispose(d3dDevice.ImmediateContext.QueryInterface<DeviceContext1>()); #endregion #region Create Direct2D device and context #if DEBUG var debugLevel = SharpDX.Direct2D1.DebugLevel.Information; #else var debugLevel = SharpDX.Direct2D1.DebugLevel.None; #endif // Allocate new references d2dFactory = ToDispose(new SharpDX.Direct2D1.Factory1(SharpDX.Direct2D1.FactoryType.SingleThreaded, debugLevel)); dwriteFactory = ToDispose(new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared)); wicFactory = ToDispose(new SharpDX.WIC.ImagingFactory2()); // Create Direct2D device using (var dxgiDevice = d3dDevice.QueryInterface<SharpDX.DXGI.Device>()) { d2dDevice = ToDispose(new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice)); } // Create Direct2D context d2dContext = ToDispose(new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None)); #endregion }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); RenderForm form = new RenderForm("Kinect simple pilot sample"); RenderDevice device = new RenderDevice(SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport); RenderContext context = new RenderContext(device); DX11SwapChain swapChain = DX11SwapChain.FromHandle(device, form.Handle); //Allow to draw using direct2d on top of swapchain var context2d = new SharpDX.Direct2D1.DeviceContext(swapChain.Texture.QueryInterface <SharpDX.DXGI.Surface>()); //Call release on texture since queryinterface does an addref Marshal.Release(swapChain.Texture.NativePointer); var textFormat = new SharpDX.DirectWrite.TextFormat(device.DWriteFactory, "Arial", 16.0f); var blackBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.Black); var whiteBrush = new SharpDX.Direct2D1.SolidColorBrush(context2d, SharpDX.Color.White); KinectSensor sensor = KinectSensor.GetDefault(); sensor.Open(); bool doQuit = false; KinectSensorColorRGBAFrameProvider provider = new KinectSensorColorRGBAFrameProvider(sensor); DynamicColorRGBATextureProcessor colorProcessor = new DynamicColorRGBATextureProcessor(provider, device); KinectPilotProcessor pilot = KinectPilotProcessor.Default; KinectSensorBodyFrameProvider bodyFrameProvider = new KinectSensorBodyFrameProvider(sensor); bodyFrameProvider.FrameReceived += (sender, args) => { var body = args.FrameData.TrackedOnly().ClosestBodies().FirstOrDefault(); if (body != null) { pilot.Process(body.GetJointTable()); } }; form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { doQuit = true; } }; RenderLoop.Run(form, () => { if (doQuit) { form.Dispose(); return; } colorProcessor.Update(context); context.RenderTargetStack.Push(swapChain); device.Primitives.ApplyFullTri(context, colorProcessor.Texture.ShaderView); device.Primitives.FullScreenTriangle.Draw(context); context.RenderTargetStack.Pop(); context2d.BeginDraw(); var rect = new SharpDX.RectangleF(0, 0, 200, 130); context2d.FillRectangle(rect, blackBrush); context2d.DrawText("Elevation: " + pilot.Elevation, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Y: " + pilot.SteeringY, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Steering Z: " + pilot.SterringZ, textFormat, rect, whiteBrush); rect.Top += 30; context2d.DrawText("Push: " + pilot.Push, textFormat, rect, whiteBrush); context2d.EndDraw(); swapChain.Present(0, SharpDX.DXGI.PresentFlags.None); }); swapChain.Dispose(); context.Dispose(); device.Dispose(); colorProcessor.Dispose(); provider.Dispose(); sensor.Close(); }