private void LoadAssets() { // Create the descriptor heap for the render target view descriptorHeap = device.CreateDescriptorHeap(new DescriptorHeapDescription() { Type = DescriptorHeapType.RenderTargetView, DescriptorCount = 1 }); // Create the main command list commandList = device.CreateCommandList(CommandListType.Direct, commandListAllocator, null); // Get the backbuffer and creates the render target view renderTarget = swapChain.GetBackBuffer <Resource>(0); device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart); // Create the viewport viewPort = new ViewportF(0, 0, width, height); // Create the scissor scissorRectangle = new Rectangle(0, 0, width, height); // Create a fence to wait for next frame fence = device.CreateFence(0, FenceFlags.None); currentFence = 1; // Close command list commandList.Close(); // Create an event handle use for VTBL eventHandle = new AutoResetEvent(false); // Wait the command list to complete WaitForPrevFrame(); }
int SwapChainPresentHook(IntPtr swapChainPtr, ref SharpDX.Rectangle pSourceRect, ref SharpDX.Rectangle pDestRect, IntPtr hDestWindowOverride, IntPtr pDirtyRegion, uint dwFlags) { SwapChain swapChain = (SwapChain)swapChainPtr; if (!IS_FREEING_PRIVATE_DATA) { DoCaptureRenderTarget(swapChain.GetBackBuffer(0).Device, swapChain.GetBackBuffer(0), "SwapChainPresentHook"); } return(Direct3D9SwapChain_PresentHook.Original(swapChainPtr, ref pSourceRect, ref pDestRect, hDestWindowOverride, pDirtyRegion, dwFlags));; }
public void EndFrame() { commandQueue.ExecuteCommandList(commandList); swapChain.Present(1, PresentFlags.None); indexLastSwapBuf = (indexLastSwapBuf + 1) % SwapBufferCount; Utilities.Dispose(ref renderTarget); renderTarget = swapChain.GetBackBuffer <Resource>(indexLastSwapBuf); device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart); WaitForPrevFrame(); }
void CreateBuffers(int width, int height) { using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderTargetView = new RenderTargetView(D3DDevice, backBuffer); } var zBufferTextureDescription = new Texture2DDescription { Format = Format.D16_UNorm, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; using (var zBufferTexture = new Texture2D(D3DDevice, zBufferTextureDescription)) { depthStencilView = new DepthStencilView(D3DDevice, zBufferTexture); } var depthEnabledStencilState = new DepthStencilState(D3DDevice, D3DDepthStencilStateDescriptions.DepthEnabled); var viewport = new SharpDX.Viewport(0, 0, width, height); ImmediateContext.Rasterizer.SetViewport(viewport); ImmediateContext.OutputMerger.SetTargets(depthStencilView, renderTargetView); //no zbuffer and DepthStencil //ImmediateContext.OutputMerger.SetRenderTargets(renderTargetView); //with zbuffer / DepthStencil ImmediateContext.OutputMerger.SetDepthStencilState(depthEnabledStencilState, 0); //var blendStateDesc = new BlendStateDescription(); //blendStateDesc.RenderTarget[0].IsBlendEnabled = true; //blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; //blendStateDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; //blendStateDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; //blendStateDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; //blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; //blendStateDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; //blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; //var blend = new BlendState(Device, blendStateDesc); //var blendFactor = new Color4(0, 0, 0, 0); //Device.ImmediateContext.OutputMerger.SetBlendState(blend, blendFactor, -1); }
public override bool Resize(int width, int height, Format format, Rational?refreshRate = null) { if (!base.Resize(width, height, format, refreshRate)) { return(false); } RemoveAndDispose(ref backBuffer); #if DIRECTX11_2 && (WIN8METRO || WINDOWS_UWP) var swapChainPanel = Description.DeviceWindowHandle as SwapChainPanel; if (swapChainPanel != null && swapChain2 != null) { swapChain2.MatrixTransform = Matrix3x2.Scaling(1f / swapChainPanel.CompositionScaleX, 1f / swapChainPanel.CompositionScaleY); } #endif swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags); // Recreate the back buffer backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer <Direct3D11.Texture2D>(0))); // Reinit the Viewport DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height); return(true); }
protected void InitializeDeviceResources() { var backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescriptor = new SwapChainDescription() { BufferCount = 1, ModeDescription = backBufferDesc, IsWindowed = true, OutputHandle = RenderForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, }; Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, Direct3D11.DeviceCreationFlags.BgraSupport, SwapChainDescriptor, out GameDevice, out SwapChain); DeviceContext = GameDevice.ImmediateContext; Viewport = new Viewport(0, 0, Width, Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(Viewport); Factory = SwapChain.GetParent <SharpDX.DXGI.Factory>(); //factory.MakeWindowAssociation(renderForm.Handle, WindowAssociationFlags.IgnoreAll); BackBufer = SwapChain.GetBackBuffer <Direct3D11.Texture2D>(0); RenderTargetView = new RenderTargetView(GameDevice, BackBufer); }
//startup settings private void InitializeDeviceResources() { //params,FPS,buffer pixel format ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(30, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; //GPU,Special flag,descriptor for swap chain,holders D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); //Getting device context d3dDeviceContext = d3dDevice.ImmediateContext; using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
private void ControlViewport_Load(object sender, EventArgs e) { if (DesignMode) { return; } SwapChainDescription swd = new SwapChainDescription(); swd.BufferCount = 1; swd.Flags = SwapChainFlags.None; swd.IsWindowed = true; swd.ModeDescription.Format = Format.R8G8B8A8_UNorm; swd.ModeDescription.Width = ClientSize.Width; swd.ModeDescription.Height = ClientSize.Height; swd.ModeDescription.RefreshRate = new Rational(60, 1); swd.OutputHandle = Handle; swd.SampleDescription = new SampleDescription(8, 31); swd.SwapEffect = SwapEffect.Discard; swd.Usage = Usage.RenderTargetOutput; swapChain = new SwapChain(Renderer.Current.Factory, Renderer.Current.Device, swd); backBufferTexture = swapChain.GetBackBuffer <Texture2D>(0); backBufferView = new RenderTargetView(Renderer.Current.Device, backBufferTexture); RecreateDepthStencilView(swd); }
private void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); // Descriptor for the swap chain SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; // Create device and swap chain D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; // Create render target view for back buffer using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
private void InitBackbuffer() { BackBuffer = new Texture2D(this, swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0)); DepthStencilBuffer = Factory.CreateRenderTarget2D(DefaultWindow.Width, DefaultWindow.Height, TextureFormat.Depth24Stencil8, false); RenderContext.SetRenderTargetsBackBuffer(); RenderContext.SetViewport(new Viewport(0, 0, DefaultWindow.Width, DefaultWindow.Height, 0, 1)); }
void InitializeDepthStencil(Control control) { var DepthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D24_UNorm_S8_UInt, ArraySize = 1, MipLevels = 1, Width = control.Width, Height = control.Height, SampleDescription = swapChain.Description.SampleDescription, BindFlags = BindFlags.DepthStencil, }); DepthStencilView = new DepthStencilView(device, DepthBuffer, new DepthStencilViewDescription() { Dimension = (swapChain.Description.SampleDescription.Count > 1 || swapChain.Description.SampleDescription.Quality > 0) ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D }); using (Texture2D backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) { renderTargetView = new RenderTargetView(device, backBuffer); } context.OutputMerger.SetTargets(DepthStencilView, renderTargetView); }
protected override void ResizeBackBuffer(int width, int height, PixelFormat format) { // Manually update back buffer texture backBuffer.OnDestroyed(); #if SILICONSTUDIO_PLATFORM_WINDOWS_RUNTIME var swapChainPanel = Description.DeviceWindowHandle.NativeHandle as Windows.UI.Xaml.Controls.SwapChainPanel; if (swapChainPanel != null) { var swapChain2 = swapChain.QueryInterface <SwapChain2>(); if (swapChain2 != null) { swapChain2.MatrixTransform = new RawMatrix3x2 { M11 = 1f / swapChainPanel.CompositionScaleX, M22 = 1f / swapChainPanel.CompositionScaleY }; swapChain2.Dispose(); } } #endif // If format is same as before, using Unknown (None) will keep the current // We do that because on Win10/RT, actual format might be the non-srgb one and we don't want to switch to srgb one by mistake (or need #ifdef) if (format == backBuffer.Format) { format = PixelFormat.None; } swapChain.ResizeBuffers(bufferCount, width, height, (SharpDX.DXGI.Format)format, SwapChainFlags.None); // Get newly created native texture var backBufferTexture = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0); // Put it in our back buffer texture backBuffer.InitializeFrom(backBufferTexture, Description.BackBufferFormat.IsSRgb()); }
/// <summary> /// Инициализирует объекты связанные с графическим устройство - Девайс его контекст и Свапчейн /// </summary> private void InitializeDeviceResources() { //Создаем объектное преставление нашего GPU, его контекст и класс который будет менят местами буфферы в которые рисует наша GPU DX11.Device.CreateWithSwapChain( SharpDX.Direct3D.DriverType.Hardware, DX11.DeviceCreationFlags.None | DX11.DeviceCreationFlags.BgraSupport, new[] { SharpDX.Direct3D.FeatureLevel.Level_11_0 }, new SwapChainDescription() { ModeDescription = new ModeDescription( _renderForm.ClientSize.Width, _renderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(4, 0), Usage = Usage.BackBuffer | Usage.RenderTargetOutput, BufferCount = 2, OutputHandle = _renderForm.Handle, IsWindowed = true, SwapEffect = SwapEffect.Discard, Flags = SwapChainFlags.None }, out _dx11Device, out _swapChain); //Игноровать все события видновс _factory = _swapChain.GetParent <Factory>(); _factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll); // Создаем буффер и вьюшку глубины using (var _depthBuffer = new DX11.Texture2D( _dx11Device, new DX11.Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = _renderForm.ClientSize.Width, Height = _renderForm.ClientSize.Height, SampleDescription = _swapChain.Description.SampleDescription, Usage = DX11.ResourceUsage.Default, BindFlags = DX11.BindFlags.DepthStencil, CpuAccessFlags = DX11.CpuAccessFlags.None, OptionFlags = DX11.ResourceOptionFlags.None })) _depthView = new DX11.DepthStencilView(_dx11Device, _depthBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription() { Dimension = (SwapChain.Description.SampleDescription.Count > 1 || SwapChain.Description.SampleDescription.Quality > 0) ? DX11.DepthStencilViewDimension.Texture2DMultisampled : DX11.DepthStencilViewDimension.Texture2D, Flags = DX11.DepthStencilViewFlags.None }); //Создаем буффер и вьюшку для рисования using (DX11.Texture2D backBuffer = _swapChain.GetBackBuffer <DX11.Texture2D>(0)) _renderView = new DX11.RenderTargetView(_dx11Device, backBuffer); //Создаем контекст нашего GPU _dx11DeviceContext = _dx11Device.ImmediateContext; //Устанавливаем размер конечной картинки _dx11DeviceContext.Rasterizer.SetViewport(0, 0, _renderForm.ClientSize.Width, _renderForm.ClientSize.Height); _dx11DeviceContext.OutputMerger.SetTargets(_depthView, _renderView); }
protected void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true }; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; viewport = new Viewport(0, 0, Width, Height); d3dDeviceContext.Rasterizer.SetViewport(viewport); using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } }
public void NativeLoad(IDXViewPipe videoPipe, VideoFormat videoFormat) { this.timer.Enabled = false; ModeDescription backBufferDesc = new ModeDescription(videoFormat.width, videoFormat.height, new Rational(videoFormat.fps, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = this.Handle, IsWindowed = true }; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out deviceDx11, out swapChain); deviceCtx = deviceDx11.ImmediateContext; backBuffer = swapChain.GetBackBuffer <Texture2D>(0); renderTargetView = new RenderTargetView(deviceDx11, backBuffer); deviceCtx.OutputMerger.SetRenderTargets(renderTargetView); viewPipe = videoPipe; SetBlendInput(); this.timer.Interval = 1000 / videoFormat.fps; this.timer.Enabled = true; //Action action = () => { RenderLoop.Run(this, Draw); }; //this.BeginInvoke(action); }
public WindowedDirect2dRenderEnvironment(string formName, bool debug) { form = new RenderForm(formName); d3dDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | (debug ? DeviceCreationFlags.Debug : DeviceCreationFlags.None)); dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device>(); dxgiFactory = new SharpDX.DXGI.Factory1(); swapChain = new SwapChain(dxgiFactory, dxgiDevice, new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(Format.B8G8R8A8_UNorm), OutputHandle = form.Handle, IsWindowed = true, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }); dxgiSurface = swapChain.GetBackBuffer <Surface>(0); d2dFactory = new SharpDX.Direct2D1.Factory1(FactoryType.SingleThreaded, debug ? DebugLevel.Warning : DebugLevel.None); d2dDevice = new SharpDX.Direct2D1.Device(d2dFactory, dxgiDevice); d2dContext = new SharpDX.Direct2D1.DeviceContext(d2dDevice, DeviceContextOptions.None); bitmap = new Bitmap1(d2dContext, dxgiSurface, null); d2dContext.Target = bitmap; }
protected override void ResizeBackBuffer(int width, int height, PixelFormat format) { // Manually update back buffer texture backBuffer.OnDestroyed(); #if SILICONSTUDIO_PLATFORM_WINDOWS_RUNTIME var swapChainPanel = Description.DeviceWindowHandle.NativeHandle as Windows.UI.Xaml.Controls.SwapChainPanel; if (swapChainPanel != null) { var swapChain2 = swapChain.QueryInterface <SwapChain2>(); if (swapChain2 != null) { swapChain2.MatrixTransform = Matrix3x2.Scaling(1f / swapChainPanel.CompositionScaleX, 1f / swapChainPanel.CompositionScaleY); swapChain2.Dispose(); } } #endif swapChain.ResizeBuffers(bufferCount, width, height, (SharpDX.DXGI.Format)format, SwapChainFlags.None); // Get newly created native texture var backBufferTexture = swapChain.GetBackBuffer <SharpDX.Direct3D11.Texture2D>(0); // Put it in our back buffer texture backBuffer.InitializeFrom(backBufferTexture); }
public RenderState(RenderForm form) { Form = form; var swapDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(Form.ClientSize.Width, Form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = Form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain( DriverType.Hardware, DeviceCreationFlags.Debug, swapDesc, out device, out swapChain); backBuffer = swapChain.GetBackBuffer <Texture2D>(0); renderView = new RenderTargetView(device, backBuffer); context = device.ImmediateContext; context.Rasterizer.SetViewport(new Viewport(0, 0, Form.ClientSize.Width, Form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(renderView); }
private void InitializeDeviceResources() { ModeDescription backBufferDesc = new ModeDescription(Size.X, Size.Y, new Rational(60, 1), Format.R8G8B8A8_UNorm); SwapChainDescription swapChainDesc = new SwapChainDescription() { ModeDescription = backBufferDesc, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, IsWindowed = true, OutputHandle = Form.Handle }; viewport = new Viewport(0, 0, Size.X, Size.Y); D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain); deviceContext = device.ImmediateContext; using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { view = new D3D11.RenderTargetView(device, backBuffer); } deviceContext.OutputMerger.SetRenderTargets(view); deviceContext.Rasterizer.SetViewport(viewport); vertexBuffer = D3D11.Buffer.Create <Vertex>(device, D3D11.BindFlags.VertexBuffer, new Vertex[1]); lastVertexArrayLength = 1; }
/// <summary> /// Creates a new swap chain to use when rendering to this control. /// </summary> private void CreateSwapChain() { if (_control.ClientSize.Width <= 0 || _control.ClientSize.Height <= 0) { return; } // If this is the default swap chain of the DX9Device then // reset the DX9Device instead of creating one. if (_dx9Driver.DX9Device.PresentationParameters.DeviceWindow == _control) { _swapChain = null; return; } bool isPreviousSwapChain = (_dx9Driver.SwapChain == _swapChain); if (_swapChain != null) { _swapChain.Dispose(); } _presentParameters = Direct3D9Driver.CreatePresentParameters(_control, _control.ClientSize.Width, _control.ClientSize.Height, _flags); _swapChain = new SwapChain(_dx9Driver.DX9Device, _presentParameters); if (isPreviousSwapChain == true) { _dx9Driver.SwapChain = _swapChain; _dx9Driver.DX9Device.SetRenderTarget(0, _swapChain.GetBackBuffer(0, BackBufferType.Mono)); } }
public static unsafe Emgu.CV.Image <Bgra, byte> GetImage(this SwapChain swapchain) { var bb = swapchain.GetBackBuffer <Texture2D>(0); SharpDX.Direct3D11.Device dev = bb.Device; var origDesc = bb.Description; // Create Staging texture CPU-accessible var textureDesc = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = origDesc.Width, Height = origDesc.Height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; var screenTexture = new Texture2D(dev, textureDesc); dev.ImmediateContext.CopyResource(bb, screenTexture); var mapSource = dev.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, 0); // Create bitmap var bitmap = new Emgu.CV.Image <Bgra, byte>(origDesc.Width, origDesc.Height); var sourcePtr = mapSource.DataPointer; int height = origDesc.Height; int width = origDesc.Width; int stride = bitmap.MIplImage.WidthStep; var data = bitmap.Data; fixed(byte *pData = data) { IntPtr destPtr = new IntPtr(pData); for (int y = 0; y < height; y++) { // Copy a single line Utilities.CopyMemory(destPtr, sourcePtr, stride); // Advance pointers sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch); destPtr = IntPtr.Add(destPtr, stride); } } dev.ImmediateContext.UnmapSubresource(screenTexture, 0); screenTexture.Dispose(); return(bitmap); }
public override void Present() { try { swapChain.Present((int)PresentInterval, PresentFlags.None); #if SILICONSTUDIO_XENKO_GRAPHICS_API_DIRECT3D12 // Manually swap back buffer backBuffer.NativeResource.Dispose(); backBuffer.InitializeFrom(swapChain.GetBackBuffer <BackBufferResourceType>((++bufferSwapIndex) % bufferCount), Description.BackBufferFormat.IsSRgb()); #endif } catch (SharpDXException sharpDxException) { throw new GraphicsException("Unexpected error on Present", sharpDxException, GraphicsDevice.GraphicsDeviceStatus); } }
private unsafe IntPtr PresentHook(IntPtr swapChainPtr, int syncInterval, PresentFlags flags) { var swapChain = new SwapChain(swapChainPtr); var device = swapChain.GetDevice <Device>(); if (!_initialized) { _windowHandle = swapChain.Description.OutputHandle; ImGui.ImGuiImplDX11Init((void *)device.NativePointer, (void *)device.ImmediateContext.NativePointer); var backBuffer = swapChain.GetBackBuffer <Texture2D>(0); _renderTargetView = new RenderTargetView(device, backBuffer); _initialized = true; backBuffer.Dispose(); } ImGui.ImGuiImplDX11NewFrame(); ImguiHook.NewFrame(); device.ImmediateContext.OutputMerger.SetRenderTargets(_renderTargetView); ImGui.ImGuiImplDX11RenderDrawData(ImGui.GetDrawData()); swapChain.Dispose(); device.Dispose(); return(_presentHook.OriginalFunction(swapChainPtr, syncInterval, flags)); }
public virtual void Render() { try { if (deviceLost) { ReinitializeRenderer(); return; } if (isInitialized && !isRendering && (swapChain != null)) { isRendering = true; using (Surface surface = swapChain.GetBackBuffer(0)) { Device.SetRenderTarget(0, surface); } Light light = this.Device.GetLight(0); light.Direction = camera.Direction; Device.SetLight(0, light); Device.SetTransform(TransformState.View, camera.View); Device.SetTransform(TransformState.Projection, camera.Projection); Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Background, 1.0f, 0); Device.BeginScene(); foreach (var pair in renderObjects) { pair.Value.Render(); } if (mouseDown != MouseButtons.None) { DrawCursor(); DrawAxes(); string camStr = "(" + camera.target.X.ToString("0.##") + ", " + camera.target.Y.ToString("0.##") + ", " + camera.target.Z.ToString("0.##") + ")"; TextFont.DrawString(null, camStr, renderRect, DrawTextFormat.Right | DrawTextFormat.Top, TextColor); } Device.EndScene(); swapChain.Present(Present.None, renderRect, renderRect, renderControl.Handle); isRendering = false; } } catch { isInitialized = false; isRendering = false; ReinitializeRenderer(); isInitialized = true; if (!deviceLost) { Render(); } } }
private void CreateRenderTargetView() { using (Texture2D backBuffer = _swapChain.GetBackBuffer <Texture2D>(0)) { _renderTargetView = new RenderTargetView(_device, backBuffer); } _deviceContext.OutputMerger.SetRenderTargets(_renderTargetView); }
public override void Present() { try { var presentInterval = GraphicsDevice.Tags.Get(ForcedPresentInterval) ?? PresentInterval; swapChain.Present((int)presentInterval, PresentFlags.None); #if STRIDE_GRAPHICS_API_DIRECT3D12 // Manually swap back buffer backBuffer.NativeResource.Dispose(); backBuffer.InitializeFromImpl(swapChain.GetBackBuffer <BackBufferResourceType>((++bufferSwapIndex) % bufferCount), Description.BackBufferFormat.IsSRgb()); #endif } catch (SharpDXException sharpDxException) { var deviceStatus = GraphicsDevice.GraphicsDeviceStatus; throw new GraphicsException($"Unexpected error on Present (device status: {deviceStatus})", sharpDxException, deviceStatus); } }
/// <summary> /// Render scene /// </summary> public void Render() { // record all the commands we need to render the scene into the command list PopulateCommandLists(); // execute the command list commandQueue.ExecuteCommandList(commandList); // swap the back and front buffers swapChain.Present(1, 0); indexLastSwapBuf = (indexLastSwapBuf + 1) % SwapBufferCount; Utilities.Dispose(ref renderTarget); renderTarget = swapChain.GetBackBuffer <Resource>(indexLastSwapBuf); device.CreateRenderTargetView(renderTarget, null, descriptorHeap.CPUDescriptorHandleForHeapStart); // wait and reset EVERYTHING WaitForPrevFrame(); }
private void Resize() { // Dispose all previous allocated resources Canvas.Release(); Utilities.Dispose(ref backBufferView); Utilities.Dispose(ref depthStencilView); if (View.ClientSize.Width == 0 || View.ClientSize.Height == 0) { return; } // Resize the backbuffer swapChain.ResizeBuffers(1, View.ClientSize.Width, View.ClientSize.Height, Format.B8G8R8A8_UNorm, SwapChainFlags.None); // Get the backbuffer from the swapchain var backBufferTexture = swapChain.GetBackBuffer <Texture2D11>(0); //update font Canvas.UpdateResources(backBufferTexture); // Backbuffer backBufferView = new RenderTargetView(NativeDevice, backBufferTexture); backBufferTexture.Dispose(); // Depth buffer var depthStencilTexture = new Texture2D11(NativeDevice, new Texture2DDescription() { Format = Format.D16_UNorm, ArraySize = 1, MipLevels = 1, Width = View.ClientSize.Width, Height = View.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthStencilView = new DepthStencilView(NativeDevice, depthStencilTexture); depthStencilTexture.Dispose(); //SetDefaultTargers(); // Set Default Targets NativeDeviceContext.Rasterizer.SetViewport(0, 0, View.ClientSize.Width, View.ClientSize.Height); NativeDeviceContext.OutputMerger.SetTargets(depthStencilView, backBufferView); // End resize //MustResize = false; }
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = ToDispose(CreateSwapChain()); backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0))); }
protected SwapChainGraphicsPresenter(DirectXDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = ToDispose(CreateSwapChain()); backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer <Texture2D>(0))); backBuffer.DebugName = string.Format("RT2D_Backbuffer"); }
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = ToDispose(CreateSwapChain()); backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer <Direct3D11.Texture2D>(0))); }
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) { PresentInterval = presentationParameters.PresentationInterval; // Initialize the swap chain swapChain = CreateSwapChain(); backBuffer = new Texture(device).InitializeFrom(swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0), Description.BackBufferFormat.IsSRgb()); // Reload should get backbuffer from swapchain as well //backBufferTexture.Reload = graphicsResource => ((Texture)graphicsResource).Recreate(swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture>(0)); }
private void InitializeOculus() { RenderForm form = new RenderForm("OculusWrap SharpDX demo"); Wrap oculus = new Wrap(); Hmd hmd; form.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Window_KeyUp); //form.moused //form.Activate(); //form.Show(); int textureWidth = 0, textureHeight = 0; newTextureArrived = false; //zoom == 2 is not implemented, because the visual quality would be too low. //zoom == 4 will be implemented in the future. if (zoom == 3) { textureWidth = 3328; textureHeight = 1664; } bool success = oculus.Initialize(); if (!success) { System.Windows.Forms.MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) hmd = oculus.Hmd_Create(0); else hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); if (hmd == null) { System.Windows.Forms.MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (hmd.ProductName == string.Empty) System.Windows.Forms.MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OVR.HmdCaps.LowPersistence | OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OVR.TrackingCaps.ovrTrackingCap_Orientation | OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OVR.TrackingCaps.ovrTrackingCap_Position, OVR.TrackingCaps.None); // Create a set of layers to submit. EyeTexture[] eyeTextures = new EyeTexture[2]; OVR.ovrResult result; // Create DirectX drawing device. SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug); // Create DirectX Graphics Interface factory, used to create the swap chain. Factory factory = new Factory(); DeviceContext immediateContext = device.ImmediateContext; // Define the properties of the swap chain. SwapChainDescription swapChainDescription = new SwapChainDescription(); swapChainDescription.BufferCount = 1; swapChainDescription.IsWindowed = true; swapChainDescription.OutputHandle = form.Handle; swapChainDescription.SampleDescription = new SampleDescription(1, 0); swapChainDescription.Usage = Usage.RenderTargetOutput | Usage.ShaderInput; swapChainDescription.SwapEffect = SwapEffect.Sequential; swapChainDescription.Flags = SwapChainFlags.AllowModeSwitch; swapChainDescription.ModeDescription.Width = form.Width; swapChainDescription.ModeDescription.Height = form.Height; swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm; swapChainDescription.ModeDescription.RefreshRate.Numerator = 0; swapChainDescription.ModeDescription.RefreshRate.Denominator = 1; // Create the swap chain. SharpDX.DXGI.SwapChain swapChain = new SwapChain(factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0); RenderTargetView backBufferRenderTargetView = new RenderTargetView(device, backBuffer); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = new Texture2DDescription(); depthBufferDescription.Format = Format.D32_Float; depthBufferDescription.ArraySize = 1; depthBufferDescription.MipLevels = 1; depthBufferDescription.Width = form.Width; depthBufferDescription.Height = form.Height; depthBufferDescription.SampleDescription = new SampleDescription(1, 0); depthBufferDescription.Usage = ResourceUsage.Default; depthBufferDescription.BindFlags = BindFlags.DepthStencil; depthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; depthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer. DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription(); depthStencilStateDescription.IsDepthEnabled = true; depthStencilStateDescription.DepthComparison = Comparison.Less; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; // Create the depth buffer. Texture2D depthBuffer = new Texture2D(device, depthBufferDescription); DepthStencilView depthStencilView = new DepthStencilView(device, depthBuffer); DepthStencilState depthStencilState = new DepthStencilState(device, depthStencilStateDescription); Viewport viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); immediateContext.OutputMerger.SetDepthStencilState(depthStencilState); immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView); immediateContext.Rasterizer.SetViewport(viewport); // 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; } Layers layers = new Layers(); LayerEyeFov layerEyeFov = layers.AddLayerEyeFov(); for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { OVR.EyeType eye = (OVR.EyeType)eyeIndex; EyeTexture eyeTexture = new EyeTexture(); eyeTextures[eyeIndex] = eyeTexture; // Retrieve size and position of the texture for the current eye. eyeTexture.FieldOfView = hmd.DefaultEyeFov[eyeIndex]; eyeTexture.TextureSize = hmd.GetFovTextureSize(eye, hmd.DefaultEyeFov[eyeIndex], 1.0f); eyeTexture.RenderDescription = hmd.GetRenderDesc(eye, hmd.DefaultEyeFov[eyeIndex]); eyeTexture.HmdToEyeViewOffset = eyeTexture.RenderDescription.HmdToEyeViewOffset; eyeTexture.ViewportSize.Position = new OVR.Vector2i(0, 0); eyeTexture.ViewportSize.Size = eyeTexture.TextureSize; eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f); // Define a texture at the size recommended for the eye texture. eyeTexture.Texture2DDescription = new Texture2DDescription(); eyeTexture.Texture2DDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.Texture2DDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.Texture2DDescription.ArraySize = 1; eyeTexture.Texture2DDescription.MipLevels = 1; eyeTexture.Texture2DDescription.Format = Format.R8G8B8A8_UNorm; eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.Texture2DDescription.Usage = ResourceUsage.Default; eyeTexture.Texture2DDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.Texture2DDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; // Convert the SharpDX texture description to the native Direct3D texture description. OVR.D3D11.D3D11_TEXTURE2D_DESC swapTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(eyeTexture.Texture2DDescription); // Create a SwapTextureSet, which will contain the textures to render to, for the current eye. result = hmd.CreateSwapTextureSetD3D11(device.NativePointer, ref swapTextureDescriptionD3D11, out eyeTexture.SwapTextureSet); WriteErrorDetails(oculus, result, "Failed to create swap texture set."); // Create room for each DirectX texture in the SwapTextureSet. eyeTexture.Textures = new Texture2D[eyeTexture.SwapTextureSet.TextureCount]; eyeTexture.RenderTargetViews = new RenderTargetView[eyeTexture.SwapTextureSet.TextureCount]; // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet. for (int textureIndex = 0; textureIndex < eyeTexture.SwapTextureSet.TextureCount; textureIndex++) { // Retrieve the current textureData object. OVR.D3D11.D3D11TextureData textureData = eyeTexture.SwapTextureSet.Textures[textureIndex]; // Create a managed Texture2D, based on the unmanaged texture pointer. eyeTexture.Textures[textureIndex] = new Texture2D(textureData.Texture); // Create a render target view for the current Texture2D. eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]); } // Define the depth buffer, at the size recommended for the eye texture. eyeTexture.DepthBufferDescription = new Texture2DDescription(); eyeTexture.DepthBufferDescription.Format = Format.D32_Float; eyeTexture.DepthBufferDescription.Width = eyeTexture.TextureSize.Width; eyeTexture.DepthBufferDescription.Height = eyeTexture.TextureSize.Height; eyeTexture.DepthBufferDescription.ArraySize = 1; eyeTexture.DepthBufferDescription.MipLevels = 1; eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0); eyeTexture.DepthBufferDescription.Usage = ResourceUsage.Default; eyeTexture.DepthBufferDescription.BindFlags = BindFlags.DepthStencil; eyeTexture.DepthBufferDescription.CpuAccessFlags = CpuAccessFlags.None; eyeTexture.DepthBufferDescription.OptionFlags = ResourceOptionFlags.None; // Create the depth buffer. eyeTexture.DepthBuffer = new Texture2D(device, eyeTexture.DepthBufferDescription); eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer); // Specify the texture to show on the HMD. layerEyeFov.ColorTexture[eyeIndex] = eyeTexture.SwapTextureSet.SwapTextureSetPtr; layerEyeFov.Viewport[eyeIndex].Position = new OVR.Vector2i(0, 0); layerEyeFov.Viewport[eyeIndex].Size = eyeTexture.TextureSize; layerEyeFov.Fov[eyeIndex] = eyeTexture.FieldOfView; layerEyeFov.Header.Flags = OVR.LayerFlags.TextureOriginAtBottomLeft; } // Define the texture used to display the rendered result on the computer monitor. Texture2DDescription mirrorTextureDescription = new Texture2DDescription(); mirrorTextureDescription.Width = form.Width; mirrorTextureDescription.Height = form.Height; mirrorTextureDescription.ArraySize = 1; mirrorTextureDescription.MipLevels = 1; mirrorTextureDescription.Format = Format.R8G8B8A8_UNorm; mirrorTextureDescription.SampleDescription = new SampleDescription(1, 0); mirrorTextureDescription.Usage = ResourceUsage.Default; mirrorTextureDescription.CpuAccessFlags = CpuAccessFlags.None; mirrorTextureDescription.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; SamplerStateDescription samplerStateDescription = new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic }; RasterizerStateDescription rasterizerStateDescription = RasterizerStateDescription.Default(); rasterizerStateDescription.IsFrontCounterClockwise = true; // Convert the SharpDX texture description to the native Direct3D texture description. OVR.D3D11.D3D11_TEXTURE2D_DESC mirrorTextureDescriptionD3D11 = SharpDXHelpers.CreateTexture2DDescription(mirrorTextureDescription); OculusWrap.D3D11.MirrorTexture mirrorTexture; // Create the texture used to display the rendered result on the computer monitor. result = hmd.CreateMirrorTextureD3D11(device.NativePointer, ref mirrorTextureDescriptionD3D11, out mirrorTexture); WriteErrorDetails(oculus, result, "Failed to create mirror texture."); Texture2D mirrorTextureD3D11 = new Texture2D(mirrorTexture.Texture.Texture); #region Vertex and pixel shader // Create vertex shader. ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderMain", "vs_4_0"); VertexShader vertexShader = new VertexShader(device, vertexShaderByteCode); // Create pixel shader. ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderMain", "ps_4_0"); PixelShader pixelShader = new PixelShader(device, pixelShaderByteCode); ShaderSignature shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); Texture2D myTexture = new Texture2D(device, new Texture2DDescription() { Format = Format.R8G8B8A8_UNorm, ArraySize = 1, MipLevels = 1, Width = textureWidth, Height = textureHeight, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }); ShaderResourceView textureView = new ShaderResourceView(device, myTexture); //set sampler for texture SamplerState samplerState = new SamplerState(device, samplerStateDescription); //initialize rasterizer RasterizerState rasterizerState = new RasterizerState(device, rasterizerStateDescription); // Specify that each vertex consists of a single vertex position and color. int[] indices = null; Vertex[] vertices = null; CreateGeometry(out indices, out vertices); InputElement[] inputElements = new InputElement[] { new InputElement("SV_Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0), /*new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0),*/ }; // Define an input layout to be passed to the vertex shader. InputLayout inputLayout = new InputLayout(device, shaderSignature, inputElements); // Create a vertex buffer, containing our 3D model. Buffer vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vertices);//m_vertices); // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader. Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); Buffer indexBuffer = SharpDX.Direct3D11.Buffer.Create(device, BindFlags.IndexBuffer, indices); // Setup the immediate context to use the shaders and model we defined. immediateContext.InputAssembler.InputLayout = inputLayout; immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0)); immediateContext.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0); immediateContext.VertexShader.SetConstantBuffer(0, constantBuffer); immediateContext.VertexShader.Set(vertexShader); immediateContext.PixelShader.Set(pixelShader); immediateContext.PixelShader.SetShaderResource(0, textureView); immediateContext.PixelShader.SetSampler(0, samplerState); #endregion DateTime startTime = DateTime.Now; Vector3 position = new Vector3(0, 0, 0); oculusReady = true; #region Render loop RenderLoop.Run(form, () => { OVR.Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset }; OVR.FrameTiming frameTiming = hmd.GetFrameTiming(0); OVR.TrackingState trackingState = hmd.GetTrackingState(frameTiming.DisplayMidpointSeconds); OVR.Posef[] eyePoses = new OVR.Posef[2]; // Calculate the position and orientation of each eye. oculus.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses); float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds; for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++) { OVR.EyeType eye = (OVR.EyeType)eyeIndex; EyeTexture eyeTexture = eyeTextures[eyeIndex]; layerEyeFov.RenderPose[eyeIndex] = eyePoses[eyeIndex]; // Retrieve the index of the active texture and select the next texture as being active next. int textureIndex = eyeTexture.SwapTextureSet.CurrentIndex++; immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]); immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black); immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport); //added a custom rasterizer immediateContext.Rasterizer.State = rasterizerState; // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction. Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation); Matrix rotationMatrix = Matrix.RotationQuaternion(rotationQuaternion); Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3(); Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3(); Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3(); //use this to get the first rotation to goal Matrix world = Matrix.Scaling(1.0f) /** Matrix.RotationX(timeSinceStart*0.2f) */* Matrix.RotationY(timeSinceStart * 2 / 10f) /** Matrix.RotationZ(timeSinceStart*3/10f)*/; Matrix viewMatrix = Matrix.LookAtRH(viewPosition, viewPosition + lookAt, lookUp); Matrix projectionMatrix = OVR.ovrMatrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 10.0f, OVR.ProjectionModifier.None).ToMatrix(); projectionMatrix.Transpose(); Matrix worldViewProjection = world * viewMatrix * projectionMatrix; worldViewProjection.Transpose(); // Update the transformation matrix. immediateContext.UpdateSubresource(ref worldViewProjection, constantBuffer); // Draw the cube //immediateContext.Draw(vertices.Length/2, 0); immediateContext.DrawIndexed(indices.Length, 0, 0); } hmd.SubmitFrame(0, layers); immediateContext.CopyResource(mirrorTextureD3D11, backBuffer); swapChain.Present(0, PresentFlags.None); if (newTextureArrived == true) { newTextureArrived = false; DataBox map = device.ImmediateContext.MapSubresource(myTexture, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None); //load the BitMapSource with appropriate formating (Format32bppPRGBA) SharpDX.WIC.BitmapSource bitMap = LoadBitmap(new SharpDX.WIC.ImagingFactory(), streamTexture); //string newFile = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\img_merged.jpg"; //SharpDX.WIC.BitmapSource bitMap = LoadBitmapFromFile(new SharpDX.WIC.ImagingFactory(), newFile); int width = bitMap.Size.Width; int height = bitMap.Size.Height; int stride = bitMap.Size.Width * 4; bitMap.CopyPixels(stride, map.DataPointer, height * stride); device.ImmediateContext.UnmapSubresource(myTexture, 0); //bitMap.Dispose(); streamTexture.Seek(0, SeekOrigin.Begin); } }); #endregion // Release all resources inputLayout.Dispose(); constantBuffer.Dispose(); indexBuffer.Dispose(); vertexBuffer.Dispose(); inputLayout.Dispose(); shaderSignature.Dispose(); pixelShader.Dispose(); pixelShaderByteCode.Dispose(); vertexShader.Dispose(); vertexShaderByteCode.Dispose(); mirrorTextureD3D11.Dispose(); layers.Dispose(); eyeTextures[0].Dispose(); eyeTextures[1].Dispose(); immediateContext.ClearState(); immediateContext.Flush(); immediateContext.Dispose(); depthStencilState.Dispose(); depthStencilView.Dispose(); depthBuffer.Dispose(); backBufferRenderTargetView.Dispose(); backBuffer.Dispose(); swapChain.Dispose(); factory.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(); hmd.Dispose(); oculus.Dispose(); }
public override void OnRecreated() { base.OnRecreated(); // Recreate swap chain swapChain = CreateSwapChain(); // Get newly created native texture var backBufferTexture = swapChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0); // Put it in our back buffer texture // TODO: Update new size backBuffer.InitializeFrom(backBufferTexture, Description.BackBufferFormat.IsSRgb()); backBuffer.LifetimeState = GraphicsResourceLifetimeState.Active; }
public bool Initialise(SwapChain swapChain) { return Initialise(swapChain.GetDevice<Device>(), swapChain.GetBackBuffer<Texture2D>(0)); }
/// <summary> /// Creates a new swap chain to use when rendering to this control. /// </summary> private void CreateSwapChain() { if (_control.ClientSize.Width <= 0 || _control.ClientSize.Height <= 0) return; // If this is the default swap chain of the DX9Device then // reset the DX9Device instead of creating one. if (_dx9Driver.DX9Device.PresentationParameters.DeviceWindow == _control) { _swapChain = null; return; } bool isPreviousSwapChain = (_dx9Driver.SwapChain == _swapChain); if (_swapChain != null) _swapChain.Dispose(); _presentParameters = Direct3D9Driver.CreatePresentParameters(_control, _control.ClientSize.Width, _control.ClientSize.Height, _flags); _swapChain = new SwapChain(_dx9Driver.DX9Device, _presentParameters); if (isPreviousSwapChain == true) { _dx9Driver.SwapChain = _swapChain; _dx9Driver.DX9Device.SetRenderTarget(0, _swapChain.GetBackBuffer(0, BackBufferType.Mono)); } }
private void HandleDeviceChangeEnd(object sender, EventArgs e) { var device = _graphicsDeviceManager.GraphicsDevice; var swapChain = (SwapChain)device.Presenter.NativePresenter; var d = swapChain.Description; var d3DDevice = (SharpDX.Direct3D11.Device)device; using (var dxgiDevice = d3DDevice.QueryInterface<Device3>()) { var adapter = dxgiDevice.Adapter; var factory = adapter.GetParent<Factory2>(); var description = new SwapChainDescription1 { Width = d.ModeDescription.Width, Height = d.ModeDescription.Height, Format = d.ModeDescription.Format, Stereo = false, SampleDescription = new SampleDescription(1, 0), Usage = Usage.RenderTargetOutput, BufferCount = 2, SwapEffect = SwapEffect.FlipSequential, Flags = SwapChainFlags.ForegroundLayer, Scaling = Scaling.None, AlphaMode = AlphaMode.Premultiplied }; // create the foreground swap chain for the core window using (var comWindow = new ComObject(Window.NativeWindow)) _foregroundChain = new SwapChain1(factory, (SharpDX.Direct3D11.Device)device, comWindow, ref description); // recreate the foreground render target using (var backBuffer = _foregroundChain.GetBackBuffer<SharpDX.Direct3D11.Texture2D>(0)) _foregroundRenderTarget = RenderTarget2D.New(device, backBuffer); } }
protected HRESULT CreateVideoSamples(IMFMediaType pFormat) { if (pFormat == null) { return MFHelper.MF_E_UNEXPECTED; } HRESULT hr = S_OK; PresentParameters pp; lock (m_ObjectLock) { hr = GetSwapChainPresentParameters(pFormat, out pp); hr.Assert(); if (hr.Failed) { return hr; } // Create the video samples. for (int i = 0; i < PRESENTER_BUFFER_COUNT; i++) { Surface _surface = null; if (m_bUseSwapChain) { // Create a new swap chain. SwapChain pSwapChain = new SwapChain(m_Device, pp); if (pSwapChain == null) { return E_UNEXPECTED; } _surface = pSwapChain.GetBackBuffer(0); if (_surface == null) return E_FAIL; m_Device.ColorFill(_surface, new Color4(Color.Black)); } else { _surface = Surface.CreateRenderTarget(m_Device, pp.BackBufferWidth, pp.BackBufferHeight, pp.BackBufferFormat, pp.Multisample, pp.MultisampleQuality, true); } // Create the video sample from the swap chain. MFSample pVideoSample = new MFSample(); pVideoSample.Target = _surface; hr = (HRESULT)MFHelper.MFCreateVideoSampleFromSurface(Marshal.GetObjectForIUnknown(_surface.ComPointer), out pVideoSample.Sample); // Add it to the list. m_SamplePool.AddSample(pVideoSample); } } return NOERROR; }