public override void Init(IntPtr display, IntPtr window, uint samples, bool vsync, bool sRGB) { _display = display; _window = window; _vsync = vsync; FeatureLevel[] features = { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 }; SharpDX.Direct3D11.Device dev11 = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.None, features); _dev = dev11.QueryInterfaceOrNull <SharpDX.Direct3D11.Device1>(); SampleDescription sampleDesc = new SampleDescription(); do { if (_dev.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, (int)samples) > 0) { sampleDesc.Count = (int)samples; sampleDesc.Quality = 0; break; } else { samples >>= 1; } } while (samples > 0); SwapChainDescription1 desc = new SwapChainDescription1(); desc.Width = 0; desc.Height = 0; desc.Format = sRGB ? Format.R8G8B8A8_UNorm_SRgb : Format.R8G8B8A8_UNorm; desc.Scaling = Scaling.None; desc.SampleDescription = sampleDesc; desc.Usage = Usage.RenderTargetOutput; desc.BufferCount = 2; desc.SwapEffect = SwapEffect.FlipSequential; desc.Flags = SwapChainFlags.None; SharpDX.DXGI.Device2 dev = _dev.QueryInterface <SharpDX.DXGI.Device2>(); Adapter adapter = dev.Adapter; Factory2 factory = adapter.GetParent <Factory2>(); if (display == IntPtr.Zero) { GCHandle handle = (GCHandle)window; SharpDX.ComObject coreWindow = new SharpDX.ComObject(handle.Target as object); _swapChain = new SwapChain1(factory, _dev, coreWindow, ref desc); } else { _swapChain = new SwapChain1(factory, _dev, window, ref desc); } _device = new RenderDeviceD3D11(_dev.ImmediateContext.NativePointer, sRGB); }
public RenderController(IntPtr windowHandle) { writeFactory = new SharpDX.DirectWrite.Factory(); SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device ( DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport ); device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); SwapChainDescription1 description = new SwapChainDescription1() { Width = 0, Height = 0, Format = Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, Scaling = Scaling.None, SwapEffect = SwapEffect.FlipSequential, }; swapChain = new SwapChain1(dxgiFactory2, device, windowHandle, ref description); backBuffer = Surface.FromSwapChain(swapChain, 0); d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); properties = new BitmapProperties1 ( new SharpDX.Direct2D1.PixelFormat ( SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied ), 0, 0, BitmapOptions.Target | BitmapOptions.CannotDraw ); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); d2dContext.Target = d2dTarget; canDraw = true; }
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, } })); }
public SharpRender(RenderForm form) { this.form = form; var adapters = new DXGI.Factory1().Adapters; DXGI.Adapter myadapter = null; for (int i = 0; i < adapters.Length; ++i) { Logger.Log(string.Format("Adapter Found: [{0}] " + "{1}\tDeviceId={5}" + "{1}\tLuid={6}" + "{1}\tVendorId={10}" + "{1}\tSubsystemId={9}" + "{1}\tDescription={4}" + "{1}\tRevision={7}" + "{1}\tDedicatedSystemMemory={2}" + "{1}\tDedicatedVideoMemory={3}" + "{1}\tSharedSystemMemory={8}" + "", i, Environment.NewLine, adapters[i].Description.DedicatedSystemMemory, adapters[i].Description.DedicatedVideoMemory, adapters[i].Description.Description, adapters[i].Description.DeviceId, adapters[i].Description.Luid, adapters[i].Description.Revision, adapters[i].Description.SharedSystemMemory, adapters[i].Description.SubsystemId, adapters[i].Description.VendorId)); var outputs = adapters[i].Outputs; for (int j = 0; j < outputs.Length; ++j) { Logger.Log(string.Format("Output Found: [{0},{1}]" + "{2}\tDeviceName={4}" + "{2}\tIsAttachedToDesktop={5}" + "{2}\tMonitorHandle={6}" + "{2}\tDesktopBounds={3}" + "{2}\tRotation={7}" + "", i, j, Environment.NewLine, (Rectangle)outputs[j].Description.DesktopBounds, outputs[j].Description.DeviceName, outputs[j].Description.IsAttachedToDesktop, outputs[j].Description.MonitorHandle, outputs[j].Description.Rotation)); } if (outputs.Length > 0 && myadapter == null) { myadapter = adapters[i]; } } d3device = new Direct3D11.Device( myadapter, Direct3D11.DeviceCreationFlags.BgraSupport); //SharpDX.Direct3D.DriverType.Hardware, //Direct3D11.DeviceCreationFlags.BgraSupport | //Direct3D11.DeviceCreationFlags.Debug); defDevice = d3device.QueryInterface <Direct3D11.Device1>(); dxgiDevice2 = defDevice.QueryInterface <DXGI.Device2>(); dxgiAdapter = dxgiDevice2.Adapter; dxgiFactory2 = dxgiAdapter.GetParent <DXGI.Factory2>(); var scDescription = new DXGI.SwapChainDescription1() { Width = 0, Height = 0, Format = DXGI.Format.B8G8R8A8_UNorm, Stereo = false, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 2, Scaling = DXGI.Scaling.None, SwapEffect = DXGI.SwapEffect.FlipSequential }; swapChain = new DXGI.SwapChain1(dxgiFactory2, defDevice, form.Handle, ref scDescription, null, null); d2dDevice = new Direct2D1.Device(dxgiDevice2); d2dContext = new Direct2D1.DeviceContext(d2dDevice, Direct2D1.DeviceContextOptions.None); fac = new Direct2D1.Factory(Direct2D1.FactoryType.SingleThreaded); var dpi = fac.DesktopDpi; var bMProperties = new Direct2D1.BitmapProperties1( new Direct2D1.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, Direct2D1.AlphaMode.Premultiplied), dpi.Width, dpi.Height, Direct2D1.BitmapOptions.CannotDraw | Direct2D1.BitmapOptions.Target); bb = swapChain.GetBackBuffer <DXGI.Surface>(0); target = new Direct2D1.Bitmap1(d2dContext, bb, bMProperties); d2dContext.Target = target; wrFactory = new DirectWrite.Factory(); brush = new Direct2D1.SolidColorBrush(d2dContext, c(Color.White)); }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public async void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer <Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); // Create the DirectWrite factory objet. SharpDX.DirectWrite.Factory fontFactory = new SharpDX.DirectWrite.Factory(); // Create a TextFormat object that will use the Segoe UI font with a size of 24 DIPs. textFormat = new TextFormat(fontFactory, "Segoe UI", 24.0f); // Create two TextLayout objects for rendering the moving text. textLayout1 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with snapped pixel boundaries.", textFormat, 400.0f, 200.0f); textLayout2 = new TextLayout(fontFactory, "This is an example of a moving TextLayout object with no snapped pixel boundaries.", textFormat, 400.0f, 200.0f); // Vertical offset for the moving text. layoutY = 0.0f; // Create the brushes for the text background and text color. backgroundBrush = new SolidColorBrush(d2dContext, Color.White); textBrush = new SolidColorBrush(d2dContext, Color.Black); }
override protected void Render() { Lock = true; int mainRetry = 5; ClientContext context; do { context = new ClientContext("com.bivrost360.desktopplayer"); Thread.Sleep(50); }while (context == null && mainRetry-- > 0); DisplayConfig displayConfig = null; for (int retry = 0; retry < 12; retry++) { if (abort) { context.Dispose(); Lock = false; return; } displayConfig = context.GetDisplayConfig(); if (displayConfig != null) { int contextRetry = 0; do { context.update(); contextRetry++; if (abort) { context.Dispose(); Lock = false; return; } Thread.Sleep(1); } while (!displayConfig.CheckDisplayStartup() || contextRetry < 300); if (displayConfig.CheckDisplayStartup()) { break; } } } if (displayConfig == null) { context.Dispose(); Lock = false; return; } var numDisplayInputs = displayConfig.GetNumDisplayInputs(); if (numDisplayInputs != 1) { context.Dispose(); Lock = false; return; } var displayDimensions = displayConfig.GetDisplayDimensions(0); var numViewers = displayConfig.GetNumViewers(); if (numViewers != 1) { context.Dispose(); Lock = false; return; } var form = new RenderForm("BIVROST - OSVR"); form.Width = displayDimensions.Width; form.Height = displayDimensions.Height; form.ShowInTaskbar = false; var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(displayDimensions.Width, displayDimensions.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; SwapChain swapChain; // Create DirectX drawing device. //SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }); Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out _device, out swapChain); // Create DirectX Graphics Interface factory, used to create the swap chain. Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); form.FormBorderStyle = FormBorderStyle.None; form.TopMost = true; DeviceContext immediateContext = _device.ImmediateContext; using (SharpDX.DXGI.Device2 dxgiDevice = _device.QueryInterface <SharpDX.DXGI.Device2>()) { //var bounds = dxgiDevice.Adapter.Outputs[1].Description.DesktopBounds; //form.DesktopBounds = new System.Drawing.Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height); //dxgiDevice.Adapter.Outputs.ToList().ForEach(o => //{ // if (o.Description.DeviceName.EndsWith("2")) // { // swapChain.SetFullscreenState(true, o); // } //}); Rectangle bounds; if (Features.IsDebug) { log.Info("OSVR: available screens: " + string.Join("\n", dxgiDevice.Adapter.Outputs.ToList().ConvertAll(o => o.Description.DeviceName + " (" + o.Description.DesktopBounds + ")"))); } if (Logic.Instance.settings.OSVRScreen == ScreenSelection.Autodetect) { // start with last screen Output output = dxgiDevice.Adapter.Outputs[dxgiDevice.Adapter.Outputs.Length - 1]; // but something resembling a HDK 1.4 (1920x1080) will be better foreach (var o in dxgiDevice.Adapter.Outputs) { var b = o.Description.DesktopBounds; if (b.Width == 1920 && b.Height == 1080) { log.Info("OSVR: found a 1920x1080 candidate for a HDK 1.4"); output = o; } } // and something resembling a HDK 2.0 (2160x1200) will be even more better foreach (var o in dxgiDevice.Adapter.Outputs) { var b = o.Description.DesktopBounds; if (b.Width == 2160 && b.Height == 1200) { log.Info("OSVR: found a 2160x1200 candidate for a HDK 2.0"); output = o; } } bounds = output.Description.DesktopBounds; log.Info($"OSVR: guessed output ({bounds})"); } else { int osvrScreen = (int)Logic.Instance.settings.OSVRScreen; if (osvrScreen >= dxgiDevice.Adapter.Outputs.Length) { osvrScreen = dxgiDevice.Adapter.Outputs.Length - 1; } bounds = dxgiDevice.Adapter.Outputs[osvrScreen].Description.DesktopBounds; log.Info($"OSVR: selected output #{osvrScreen} ({bounds})"); } form.DesktopBounds = new System.Drawing.Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height); if (dxgiDevice.Adapter.Outputs.Length <= 1) { Logic.Notify("Only one screen is active. Press Control+S to stop the movie if needed."); } } // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = new Texture2DDescription() { Format = Format.D32_Float, ArraySize = 1, MipLevels = 1, Width = displayDimensions.Width, Height = displayDimensions.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = _device.QueryInterface <SharpDX.DXGI.Device1>()) dxgiDevice.MaximumFrameLatency = 1; using (_gd = SharpDX.Toolkit.Graphics.GraphicsDevice.New(_device)) using (customEffectL = GetCustomEffect(_gd)) using (customEffectR = GetCustomEffect(_gd)) //using (var primitive = GraphicTools.CreateGeometry(_projection, _gd)) using (vrui = new VRUI(_device, _gd)) using (Texture2D depthBuffer = new Texture2D(_device, depthBufferDescription)) using (DepthStencilView depthView = new DepthStencilView(_device, depthBuffer)) using (Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0)) using (RenderTargetView renderView = new RenderTargetView(_device, backBuffer)) { //primitive = GraphicTools.CreateGeometry(Projection, _gd); DateTime startTime = DateTime.Now; Vector3 position = new Vector3(0, 0, -1); #region Render loop DateTime lastTime = DateTime.Now; float deltaTime = 0; immediateContext.OutputMerger.SetTargets(depthView, renderView); form.GotFocus += (s, e) => OnGotFocus(); bool first = true; RenderLoop.Run(form, () => { if (abort) { form.Close(); return; } if (first) { // Start with default background SetDefaultScene(); OnGotFocus(); first = false; } UpdateContentIfRequested(); context.update(); float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds; deltaTime = (float)(DateTime.Now - lastTime).TotalSeconds; lastTime = DateTime.Now; immediateContext.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); immediateContext.ClearRenderTargetView(renderView, Color.Black); uint viewer = 0; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { var numEyes = displayConfig.GetNumEyesForViewer(viewer); var viewerPose = displayConfig.GetViewerPose(viewer); for (byte eye = 0; eye < numEyes; eye++) { uint numSurfaces = displayConfig.GetNumSurfacesForViewerEye(viewer, eye); Pose3 viewerEyePose = displayConfig.GetViewerEyePose(viewer, eye); Matrix44f viewerEyeMatrixf = displayConfig.GetViewerEyeViewMatrixf(viewer, eye, MatrixConventionsFlags.Default); uint surface = 0; OSVR.ClientKit.Viewport viewport = displayConfig.GetRelativeViewportForViewerEyeSurface(viewer, eye, surface); Matrix44f projectionf = displayConfig.GetProjectionMatrixForViewerEyeSurfacef(viewer, eye, surface, 0.001f, 1000.0f, MatrixConventionsFlags.Default); ProjectionClippingPlanes projectionClippingPlanes = displayConfig.GetViewerEyeSurfaceProjectionClippingPlanes(viewer, eye, surface); ViewportF vp = new ViewportF(viewport.Left, viewport.Bottom, viewport.Width, viewport.Height); immediateContext.Rasterizer.SetViewport(vp); Vector3 lookPosition = viewerEyePose.translation.ToVector3(); SharpDX.Quaternion lookRotation = viewerEyePose.rotation.ToQuaternion(); Matrix rotationMatrix = Matrix.RotationQuaternion(lookRotation); Vector3 lookUp = Vector3.Transform(new Vector3(0, 1, 0), rotationMatrix).ToVector3(); Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, -1), rotationMatrix).ToVector3(); Matrix viewMatrix = Matrix.LookAtRH(lookPosition, lookPosition + lookAt, lookUp); Matrix projectionMatrix = projectionf.ToMatrix(); Matrix worldMatrix = Matrix.Translation(lookPosition); Matrix MVP = worldMatrix * viewMatrix * projectionMatrix; customEffectL.Parameters["WorldViewProj"].SetValue(MVP); customEffectR.Parameters["WorldViewProj"].SetValue(MVP); lock (localCritical) { if (eye == 0) { primitive?.Draw(customEffectL); } if (eye == 1) { primitive?.Draw(customEffectR); } } // reset UI position every frame if it is not visible if (vrui.isUIHidden) { vrui.SetWorldPosition(viewMatrix.Forward, lookPosition, true); } if (eye == 0) { lookRotation.Invert(); ProvideLook?.Invoke(lookPosition, lookRotation, OSVRFOV); } vrui.Draw(Media, currentTime, Duration); vrui.Render(deltaTime, viewMatrix, projectionMatrix, lookPosition, ShouldShowVRUI); } } swapChain.Present(0, PresentFlags.None); }); #endregion //debugWindow.Stop(); waitForRendererStop.Set(); //swapChain.SetFullscreenState(false, null); immediateContext.ClearState(); immediateContext.Flush(); immediateContext.Dispose(); swapChain.Dispose(); factory.Dispose(); //swapChain.Dispose(); // Disposing the device, before the hmd, will cause the hmd to fail when disposing. // Disposing the device, after the hmd, will cause the dispose of the device to fail. // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down. // device.Dispose(); base._device.Dispose(); //hmd.Dispose(); //oculus.Dispose(); displayConfig.Dispose(); context.Dispose(); } Lock = false; }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = dxgiFactory2.CreateSwapChainForCoreWindow(device, new ComObject(window), ref description, null); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer <Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); // Create a solid color brush. solidBrush = new 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 LinearGradientBrush(d2dContext, new LinearGradientBrushProperties() { StartPoint = new Vector2(50, 0), EndPoint = new Vector2(450, 0), }, new GradientStopCollection(d2dContext, new GradientStop[] { new GradientStop() { Color = Color.Blue, Position = 0, }, new GradientStop() { Color = Color.Green, Position = 1, } })); // Create a radial gradient brush. // The center is specified in absolute coordinates, too. radialGradientBrush = new RadialGradientBrush(d2dContext, new RadialGradientBrushProperties() { Center = new Vector2(250, 525), RadiusX = 100, RadiusY = 100, }, new GradientStopCollection(d2dContext, new GradientStop[] { new GradientStop() { Color = Color.Yellow, Position = 0, }, new GradientStop() { Color = Color.Red, Position = 1, } })); }
public async static Task <MemoryStream> InterpolateImageMarkup(StorageFile imageFile, StorageFile markupFile) { try { var bitmap = new BitmapImage(); using (var strm = await imageFile.OpenAsync(FileAccessMode.Read)) { bitmap.SetSource(strm); } var width = bitmap.PixelWidth; var height = bitmap.PixelHeight; var pixelFormat = WicPixelFormat.Format32bppBGR; var wicFactory = new ImagingFactory2(); var markupFactory = new ImagingFactory2(); var dddFactory = new SharpDX.Direct2D1.Factory(); var dwFactory = new SharpDX.DirectWrite.Factory(); WicRenderTarget renderTarget; Bitmap wicBitmap; SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); var device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); // d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); using (var bitmapSource = LoadBitmap(wicFactory, imageFile.Path)) { wicBitmap = new Bitmap(wicFactory, bitmapSource, BitmapCreateCacheOption.CacheOnLoad); int pixelWidth = (int)(wicBitmap.Size.Width * DisplayProperties.LogicalDpi / 96.0); int pixelHeight = (int)(wicBitmap.Size.Height * DisplayProperties.LogicalDpi / 96.0); var renderTargetProperties = new RenderTargetProperties(RenderTargetType.Default, new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown), 0, 0, RenderTargetUsage.None, SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT); renderTarget = new WicRenderTarget(dddFactory, wicBitmap, renderTargetProperties) { TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Cleartype }; } renderTarget.BeginDraw(); renderTarget.DrawBitmap(LoadBitmapFromContentFile(wicFactory, markupFile.Path, renderTarget), 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.NearestNeighbor, new SharpDX.RectangleF(30, 50, 100, 80)); //new RectangleF(width - 150, 0, width, height + 25), renderTarget.EndDraw(); var ms = new MemoryStream(); var stream = new WICStream(wicFactory, ms); BitmapEncoder encoder = null; if (imageFile.FileType == ".png") { encoder = new PngBitmapEncoder(wicFactory); } else if (imageFile.FileType == ".jpg") { encoder = new JpegBitmapEncoder(wicFactory); } encoder.Initialize(stream); var frameEncoder = new BitmapFrameEncode(encoder); frameEncoder.Initialize(); frameEncoder.SetSize(width, height); //frameEncoder.piPixelFormat = WicPixelFormat.FormatDontCare; frameEncoder.WriteSource(wicBitmap); frameEncoder.Commit(); encoder.Commit(); frameEncoder.Dispose(); encoder.Dispose(); stream.Dispose(); ms.Position = 0; return(ms); } catch (Exception) { throw; } }
/// <summary> /// Now that we have a CoreWindow object, the DirectX device/context can be created. /// </summary> /// <param name="entryPoint"></param> public void Load(string entryPoint) { // Get the default hardware device and enable debugging. Don't care about the available feature level. // DeviceCreationFlags.BgraSupport must be enabled to allow Direct2D interop. SharpDX.Direct3D11.Device defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport); // Query the default device for the supported device and context interfaces. device = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>(); d3dContext = device.ImmediateContext.QueryInterface <SharpDX.Direct3D11.DeviceContext1>(); // Query for the adapter and more advanced DXGI objects. SharpDX.DXGI.Device2 dxgiDevice2 = device.QueryInterface <SharpDX.DXGI.Device2>(); SharpDX.DXGI.Adapter dxgiAdapter = dxgiDevice2.Adapter; SharpDX.DXGI.Factory2 dxgiFactory2 = dxgiAdapter.GetParent <SharpDX.DXGI.Factory2>(); // Description for our swap chain settings. SwapChainDescription1 description = new SwapChainDescription1() { // 0 means to use automatic buffer sizing. Width = 0, Height = 0, // 32 bit RGBA color. Format = Format.B8G8R8A8_UNorm, // No stereo (3D) display. Stereo = false, // No multisampling. SampleDescription = new SampleDescription(1, 0), // Use the swap chain as a render target. Usage = Usage.RenderTargetOutput, // Enable double buffering to prevent flickering. BufferCount = 2, // No scaling. Scaling = Scaling.None, // Flip between both buffers. SwapEffect = SwapEffect.FlipSequential, }; // Generate a swap chain for our window based on the specified description. swapChain = new SwapChain1(dxgiFactory2, device, new ComObject(window), ref description); // Get the default Direct2D device and create a context. SharpDX.Direct2D1.Device d2dDevice = new SharpDX.Direct2D1.Device(dxgiDevice2); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, SharpDX.Direct2D1.DeviceContextOptions.None); // Specify the properties for the bitmap that we will use as the target of our Direct2D operations. // We want a 32-bit BGRA surface with premultiplied alpha. BitmapProperties1 properties = new BitmapProperties1(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied), DisplayProperties.LogicalDpi, DisplayProperties.LogicalDpi, BitmapOptions.Target | BitmapOptions.CannotDraw); // Get the default surface as a backbuffer and create the Bitmap1 that will hold the Direct2D drawing target. Surface backBuffer = swapChain.GetBackBuffer <Surface>(0); d2dTarget = new Bitmap1(d2dContext, backBuffer, properties); playerBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/player.png"); terrainBitmap = this.LoadBitmapFromContentFile("/Assets/Bitmaps/terrain.png"); terrainBrush = new BitmapBrush1(d2dContext, terrainBitmap, new BitmapBrushProperties1() { ExtendModeX = ExtendMode.Wrap, ExtendModeY = ExtendMode.Wrap, }); }