public void CreateD3D9TextureFromD3D10Texture(SharpDX.Direct3D10.Texture2D Texture) { DirectXHelpers.SafeDispose(ref shareableTexture9); if (IsShareable(Texture)) { SharpDX.Direct3D9.Format format = TranslateFormat(Texture); if (format == SharpDX.Direct3D9.Format.Unknown) { throw new ArgumentException("Texture format is not compatible with OpenSharedResource"); } IntPtr Handle = GetSharedHandle(Texture); if (Handle == IntPtr.Zero) { throw new ArgumentNullException("Handle"); } shareableTexture9 = new SharpDX.Direct3D9.Texture(sharpDXGraphicsDeviceService9.GraphicsDevice, Texture.Description.Width, Texture.Description.Height, 1, SharpDX.Direct3D9.Usage.RenderTarget, format, SharpDX.Direct3D9.Pool.Default, ref Handle); } else { throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared"); } }
public BitmapDrawingContext(int width, int height) { if (width < 0 || height < 0) throw new Exception("Negative BitmapDrawingContext's area"); _width = width; _height = height; _device = new Device1(DriverType.Hardware, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); var textureDesc = new Texture2DDescription { MipLevels = 1, ArraySize = 1, BindFlags = BindFlags.RenderTarget, CpuAccessFlags = CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, OptionFlags = ResourceOptionFlags.None, Width = _width, Height = _height, Usage = ResourceUsage.Default, SampleDescription = new SampleDescription(1, 0) }; _texture = new Texture2D(_device, textureDesc); _factory = new Factory(FactoryType.SingleThreaded, DebugLevel.None); }
public InfoText(Device device) { this.device = device; outputMerger = device.OutputMerger; font = new Font(device, 20, 0, FontWeight.Normal, 0, false, FontCharacterSet.Default, FontPrecision.Default, FontQuality.ClearTypeNatural, FontPitchAndFamily.DontCare, "tahoma"); renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Height = rect.Height, Width = rect.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }); renderTextureView = new RenderTargetView(device, renderTexture); renderViews = new[] { renderTextureView }; OverlayBufferRes = new ShaderResourceView(device, renderTexture, new ShaderResourceViewDescription() { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
IntPtr GetSharedHandle(SharpDX.Direct3D10.Texture2D Texture) { SharpDX.DXGI.Resource resource = Texture.QueryInterface <SharpDX.DXGI.Resource>(); IntPtr result = resource.SharedHandle; resource.Dispose(); return(result); }
public static IDraw GetDrawer() { var dv = new SharpDX.Direct3D10.Device1(DriverType.Hardware); var df = new SharpDX.Direct2D1.Factory(); var t2d = new SharpDX.Direct3D10.Texture2D(dv, new Texture2DDescription() { Height = 100, Width = 100, MipLevels = 1, Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm }); var rt = new RenderTarget(df, t2d.QueryInterface <SharpDX.DXGI.Surface1>(), new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied))); return(new GetSDXContext(new Renderers.SharpDX.SharpDX_RenderElements(rt))); }
SharpDX.Direct3D9.Format TranslateFormat(SharpDX.Direct3D10.Texture2D Texture) { switch (Texture.Description.Format) { case SharpDX.DXGI.Format.R10G10B10A2_UNorm: return(SharpDX.Direct3D9.Format.A2B10G10R10); case SharpDX.DXGI.Format.R16G16B16A16_Float: return(SharpDX.Direct3D9.Format.A16B16G16R16F); case SharpDX.DXGI.Format.B8G8R8A8_UNorm: return(SharpDX.Direct3D9.Format.A8R8G8B8); default: return(SharpDX.Direct3D9.Format.Unknown); } }
public Direct3D10RenderContext(Window window) { SwapChainDescription desc = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(window.Width, window.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = window.DisplayHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out m_device, out m_swapChain); Factory factory = m_swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(window.DisplayHandle, WindowAssociationFlags.IgnoreAll); m_backBuffer = Resource.FromSwapChain<Texture2D>(m_swapChain, 0); m_backBufferView = new RenderTargetView(m_device, m_backBuffer); }
protected void CreateSizeDependentComponents() { backBuffer = Direct3D.Resource.FromSwapChain <Direct3D.Texture2D>(swapChain, 0); backBufferView = new Direct3D.RenderTargetView(device, backBuffer); factory = new Direct2D1.Factory(); imagingFactory = new ImagingFactory(); using (var surface = backBuffer.QueryInterface <DXGI.Surface>()) { renderTarget = new Direct2D1.RenderTarget(factory, surface, new Direct2D1.RenderTargetProperties(new Direct2D1.PixelFormat(DXGI.Format.Unknown, Direct2D1.AlphaMode.Premultiplied))); } renderTarget.AntialiasMode = Direct2D1.AntialiasMode.PerPrimitive; renderTarget.TextAntialiasMode = Direct2D1.TextAntialiasMode.Cleartype; var imageLoader = ImageLoader as ImageLoader; if (imageLoader != null) { imageLoader.ReloadAll(); } }
private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4( 1.0f,-1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4( 1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.OutputMerger.SetTargets(depthView, renderView); context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
bool IsShareable(SharpDX.Direct3D10.Texture2D Texture) { return((Texture.Description.OptionFlags & SharpDX.Direct3D10.ResourceOptionFlags.Shared) != 0); }
private void Initialize() { // Create the form form = CreateForm(); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription((int)Config.SCREEN_WIDTH, (int)Config.SCREEN_HEIGHT, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; //Create the device and swapchain try { Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); } catch (Exception e) { Device1.CreateWithSwapChain(DriverType.Warp, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); Console.WriteLine("Could not create Hardware drivertype, using Warp instead. \n" + e.ToString()); } // Ignore all Windows events SharpDX.DXGI.Factory factory = swapChain.GetParent<SharpDX.DXGI.Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); backBufferView = new RenderTargetView(device, backBuffer); // Create the rendertarget for the form factory2D = new SharpDX.Direct2D1.Factory(); Surface surface = backBuffer.QueryInterface<Surface>(); renderTarget = new RenderTarget(factory2D, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); renderTarget.AntialiasMode = AntialiasMode.Aliased; // Initialize the global resources used for drawing and writing. Resources.Initialize(renderTarget); runnableComponent.InitBase(); }
private void _initializeGraphics() { Console.Write("Initializing graphic device... "); var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription( _appConfiguration.Width, _appConfiguration.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = !_appConfiguration.FullScreen, OutputHandle = DisplayHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device1.CreateWithSwapChain( DriverType.Hardware, #if DEBUG DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug | DeviceCreationFlags.SingleThreaded, #else DeviceCreationFlags.BgraSupport, #endif desc, out _device, out _swapChain); if (_device == null) throw new SharpDXException("Failed to initialize graphics device."); if (_swapChain == null) throw new SharpDXException("Failed to initialize swap chain."); ToDispose<Device1>(_device); ToDispose<SwapChain>(_swapChain); Factory2D = ToDispose<Factory2D>(new Factory2D()); _factoryDXGI = ToDispose<FactoryDXGI>(_swapChain.GetParent<FactoryDXGI>()); _factoryDXGI.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll); _backBuffer = ToDispose<Texture2D>(Texture2D.FromSwapChain<Texture2D>(_swapChain, 0)); _backBufferRenderTargetView = ToDispose<RenderTargetView>(new RenderTargetView(_device, _backBuffer)); Viewport = new Viewport(0, 0, _appConfiguration.Width, _appConfiguration.Height); using (var surface = _backBuffer.QueryInterface<Surface>()) { RenderTarget2D = ToDispose<RenderTarget>( new RenderTarget(Factory2D, surface, new RenderTargetProperties( new PixelFormat( Format.Unknown, AlphaMode.Premultiplied)))); } RenderTarget2D.AntialiasMode = AntialiasMode.PerPrimitive; _vsync = Config.VSync; ScreenSize = new DrawingSizeF(Viewport.Width, Viewport.Height); Console.WriteLine("done."); }
public void Render(Canvas canvas, Device2D device2D) { Contract.Requires(canvas != null); Contract.Requires(device2D != null); IntPtr sharedHandle = canvas.GetDeviceHandle(device2D); if(sharedHandle != _SharedHandle) { _SharedMutex.SafeDispose(); _DependentView.SafeDispose(); _SharedTexture.SafeDispose(); _SharedMutex = null; _DependentView = null; _SharedTexture = null; if(sharedHandle != IntPtr.Zero) { _SharedTexture = _Device3D.OpenSharedResource<Texture2D>(sharedHandle); _SharedMutex = _SharedTexture.QueryInterface<KeyedMutex>(); _DependentView = new ShaderResourceView(_Device3D, _SharedTexture); _SharedHandle = sharedHandle; } } if(_SharedMutex != null) { _SharedMutex.AcquireSync(); try { if(_SharedTexture != null) { var textureVariable = _Effect.GetVariableByName("tex2D"); Contract.Assert(textureVariable != null); var shaderResource = textureVariable.AsShaderResource(); Contract.Assert(shaderResource != null); shaderResource.SetResource(_DependentView); _EffectPass.Apply(); _Device3D.Draw(_VertexCount, 0); } } finally { _SharedMutex.ReleaseSync(); } } }
void CreateBuffers() { DisposeBuffers(); // New RenderTargetView from the backbuffer using (var bb = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0)) { renderView = new RenderTargetView(_device, bb); renderViews[0] = renderView; } Texture2DDescription gBufferDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; gBufferLight = new Texture2D(_device, gBufferDesc); gBufferLightView = new RenderTargetView(_device, gBufferLight); gBufferNormal = new Texture2D(_device, gBufferDesc); gBufferNormalView = new RenderTargetView(_device, gBufferNormal); gBufferDiffuse = new Texture2D(_device, gBufferDesc); gBufferDiffuseView = new RenderTargetView(_device, gBufferDiffuse); gBufferViews = new RenderTargetView[] { gBufferLightView, gBufferNormalView, gBufferDiffuseView }; ShaderResourceViewDescription gBufferResourceDesc = new ShaderResourceViewDescription() { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; lightBufferRes = new ShaderResourceView(_device, gBufferLight, gBufferResourceDesc); normalBufferRes = new ShaderResourceView(_device, gBufferNormal, gBufferResourceDesc); diffuseBufferRes = new ShaderResourceView(_device, gBufferDiffuse, gBufferResourceDesc); Texture2DDescription depthDesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R32_Typeless, Width = _width, Height = _height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; DepthStencilViewDescription depthViewDesc = new DepthStencilViewDescription() { Dimension = DepthStencilViewDimension.Texture2D, Format = Format.D32_Float, }; ShaderResourceViewDescription resourceDesc = new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }; depthTexture = new Texture2D(_device, depthDesc); depthView = new DepthStencilView(_device, depthTexture, depthViewDesc); depthRes = new ShaderResourceView(_device, depthTexture, resourceDesc); lightDepthTexture = new Texture2D(_device, depthDesc); lightDepthView = new DepthStencilView(_device, lightDepthTexture, depthViewDesc); lightDepthRes = new ShaderResourceView(_device, lightDepthTexture, resourceDesc); lightBufferVar = effect2.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect2.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect2.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect2.GetVariableByName("depthMap").AsShaderResource(); lightDepthMapVar = effect2.GetVariableByName("lightDepthMap").AsShaderResource(); _device.Rasterizer.SetViewports(new Viewport(0, 0, _width, _height)); }
public void OnResize(int width, int height) { if (mRealTexture != null) mRealTexture.Dispose(); if (mTmpTexture != null) mTmpTexture.Dispose(); mRealTexture = new SharpDX.Direct3D11.Texture2D(mDevice.Device, new SharpDX.Direct3D11.Texture2DDescription { ArraySize = 1, BindFlags = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource, CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, Height = height, Width = width, MipLevels = 1, OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex, SampleDescription = new SampleDescription(1, 0), Usage = SharpDX.Direct3D11.ResourceUsage.Default }); using (var resource = mRealTexture.QueryInterface<SharpDX.DXGI.Resource>()) mTmpTexture = D2DDevice.OpenSharedResource<Texture2D>(resource.SharedHandle); if (NativeView != null) NativeView.Dispose(); NativeView = new SharpDX.Direct3D11.ShaderResourceView(mDevice.Device, mRealTexture, new SharpDX.Direct3D11.ShaderResourceViewDescription { Format = Format.B8G8R8A8_UNorm, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource { MipLevels = 1, MostDetailedMip = 0 } }); if (RenderTarget != null) RenderTarget.Dispose(); using (var surface = mTmpTexture.QueryInterface<Surface>()) RenderTarget = new RenderTarget(Direct2DFactory, surface, new RenderTargetProperties() { DpiX = 0.0f, DpiY = 0.0f, MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_DEFAULT, PixelFormat = new PixelFormat() { AlphaMode = AlphaMode.Premultiplied, Format = Format.Unknown }, Type = RenderTargetType.Hardware, Usage = RenderTargetUsage.None }); if (mMutex10 != null) mMutex10.Dispose(); if (mMutex11 != null) mMutex11.Dispose(); mMutex10 = mTmpTexture.QueryInterface<KeyedMutex>(); mMutex11 = mRealTexture.QueryInterface<KeyedMutex>(); Brushes.Initialize(RenderTarget); Fonts.Initialize(DirectWriteFactory); Button.Initialize(); Frame.Initialize(); // right now the texture is unowned and only a key of 0 will succeed. // after releasing it with a specific key said key then can be used for // further locking. mMutex10.Acquire(0, -1); mMutex10.Release(Key11); }
private void CreateAndBindTargets(int sizeX, int sizeY) { _d3dImageSource.SetRenderTargetDX10(null); Disposer.RemoveAndDispose(ref this._renderTargetView); Disposer.RemoveAndDispose(ref this._renderTargetIntermediateView); Disposer.RemoveAndDispose(ref this._renderTargetIntermediateShaderResourceView); Disposer.RemoveAndDispose(ref this._depthStencilView); Disposer.RemoveAndDispose(ref this._renderTarget); Disposer.RemoveAndDispose(ref this._renderTargetIntermediate); Disposer.RemoveAndDispose(ref this._depthStencil); Disposer.RemoveAndDispose(ref this._gammaCorrector); if (sizeX >= 2 && sizeY >= 2) { Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; Texture2DDescription renderTextureDescriptionForD3D9 = new Texture2DDescription { BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.Read, ArraySize = 1 }; Texture2DDescription depthdesc = new Texture2DDescription { BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1, }; this._renderTarget = new Texture2D(this._device, colordesc); this._renderTargetIntermediate = new Texture2D(this._device, colordesc); this._depthStencil = new Texture2D(this._device, depthdesc); this._renderTargetIntermediateView = new RenderTargetView(this._device, this._renderTargetIntermediate); this._renderTargetIntermediateShaderResourceView = new ShaderResourceView(this._device, this._renderTargetIntermediate); this._renderTargetView = new RenderTargetView(this._device, this._renderTarget); this._depthStencilView = new DepthStencilView(this._device, this._depthStencil); this._gammaCorrector = new D3D10GammaCorrector(_device, "Altaxo.CompiledShaders.Effects.GammaCorrector.cso"); this._d3dImageSource.SetRenderTargetDX10(this._renderTarget); } }
private void initD3D() { if (drawForm == null) return; swapChainDesc = new SwapChainDescription { BufferCount = 2, ModeDescription = new ModeDescription { Width = drawForm.Width, Height = drawForm.Height, Format = Format.R8G8B8A8_UNorm, }, Usage = Usage.RenderTargetOutput, }; swapChainDesc.ModeDescription.RefreshRate.Numerator = 60; swapChainDesc.ModeDescription.RefreshRate.Denominator = 1; swapChainDesc.SampleDescription.Quality = 0; swapChainDesc.SampleDescription.Count = 1; swapChainDesc.OutputHandle = drawHandle; swapChainDesc.IsWindowed = true; D3D10.Device.CreateWithSwapChain( D3D10.DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out d3d10Device, out swapChain ); using (Texture2D backBuffer = swapChain.GetBackBuffer<Texture2D>(0)) renderTargetView = new RenderTargetView(d3d10Device, backBuffer); d3d10Device.OutputMerger.SetTargets(renderTargetView); viewport = new Viewport { Width = drawForm.Width, Height = drawForm.Height, MinDepth = 0.0f, MaxDepth = 1.0f, X = 0, Y = 0 }; d3d10Device.Rasterizer.SetViewports(viewport); var zBufferTextureDescription = new Texture2DDescription { Format = Format.D16_UNorm, ArraySize = 1, MipLevels = 1, Width = drawForm.Width, Height = drawForm.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; using (var zBufferTexture = new Texture2D(this.d3d10Device, zBufferTextureDescription)) depthStencilView = new DepthStencilView(this.d3d10Device, zBufferTexture); d3d10Device.OutputMerger.SetTargets(depthStencilView, renderTargetView); depthState = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; depthNonState = new DepthStencilStateDescription() { IsDepthEnabled = false }; d3d10Device.OutputMerger.SetDepthStencilState( new DepthStencilState( d3d10Device, depthState ), 1 ); // Generic font? // Camera? d3d10Device.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; d3d10Device.Rasterizer.State = new RasterizerState(d3d10Device, new RasterizerStateDescription { CullMode = CullMode.Back, FillMode = FillMode.Solid } ); }
private void CreateAndBindTargets() { _d3DSurface.SetRenderTargetDX10(null); Disposer.RemoveAndDispose(ref _renderTargetView); Disposer.RemoveAndDispose(ref _depthStencilView); Disposer.RemoveAndDispose(ref _renderTarget); Disposer.RemoveAndDispose(ref _depthStencil); int width = Math.Max((int)base.ActualWidth, 100); int height = Math.Max((int)base.ActualHeight, 100); Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; Texture2DDescription depthdesc = new Texture2DDescription { BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1, }; _renderTarget = new Texture2D(_device, colordesc); _depthStencil = new Texture2D(_device, depthdesc); _renderTargetView = new RenderTargetView(_device, _renderTarget); _depthStencilView = new DepthStencilView(_device, _depthStencil); _d3DSurface.SetRenderTargetDX10(_renderTarget); }
public void ResizeDevice(int width, int height) { lock (this) { if (width < 0) { throw new ArgumentOutOfRangeException("width", "Value must be positive."); } if (height < 0) { throw new ArgumentOutOfRangeException("height", "Value must be positive."); } if ((width <= this.width) && (height <= this.height)) { return; } DirectXHelpers.SafeDispose(ref this.texture); var texture = CreateTexture(Math.Max(width, this.width), Math.Max(height, this.height), true); this.texture = texture; DirectXHelpers.SafeDispose(ref this.shareableTexture); var shareableTexture = CreateTexture(Math.Max(width, this.width), Math.Max(height, this.height), false); this.shareableTexture = shareableTexture; CreateD3D9TextureFromD3D10Texture(shareableTexture); this.width = texture.Description.Width; this.height = texture.Description.Height; using (SharpDX.DXGI.Surface surface = texture.AsSurface()) { CreateRenderTarget(surface); } if (DeviceResized != null) DeviceResized(this, EventArgs.Empty); } }
public void Export(int sizeX, int sizeY, ID3D10Scene scene, Altaxo.Graph.Gdi.GraphExportOptions options, System.IO.Stream toStream) { var device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0); // try to get the highest MSAA level with the highest quality int sampleCount = 32; int qlevel_sampleCount = 0; for (; sampleCount >= 0; sampleCount /= 2) { if (0 != (qlevel_sampleCount = device.CheckMultisampleQualityLevels(Format.B8G8R8A8_UNorm, sampleCount))) // quality level for sample count break; } Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm_SRgb, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(sampleCount, qlevel_sampleCount - 1), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; Texture2DDescription depthdesc = new Texture2DDescription { BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(sampleCount, qlevel_sampleCount - 1), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1, }; var renderTarget = new Texture2D(device, colordesc); var depthStencil = new Texture2D(device, depthdesc); var renderTargetView = new RenderTargetView(device, renderTarget); var depthStencilView = new DepthStencilView(device, depthStencil); // Rendering device.OutputMerger.SetTargets(depthStencilView, renderTargetView); device.Rasterizer.SetViewports(new Viewport(0, 0, sizeX, sizeY, 0.0f, 1.0f)); Color4 clearColor = new Color4(1, 1, 1, 0); // Transparent if (options.BackgroundBrush != null) { var axoColor = options.BackgroundBrush.Color.Color; clearColor = new Color4(axoColor.ScR, axoColor.ScG, axoColor.ScB, axoColor.ScA); } device.ClearRenderTargetView(renderTargetView, clearColor); device.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); scene.Attach(device, new PointD2D(sizeX, sizeY)); scene.Render(); device.Flush(); Texture2D renderTarget2 = null; if (sampleCount > 1) // if renderTarget is an MSAA render target, we first have to copy it into a non-MSAA render target before we can copy it to a CPU texture and then hope to save it { // create a non-MSAA render target with the same size Texture2DDescription renderTarget2Description = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm_SRgb, Width = sizeX, Height = sizeY, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), // non MSAA Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; renderTarget2 = new Texture2D(device, renderTarget2Description); // create non-MSAA render target device.ResolveSubresource(renderTarget, 0, renderTarget2, 0, renderTarget.Description.Format); // copy from MSAA render target to the non-MSAA render target var h = renderTarget; // exchange renderTarget with renderTarget2 renderTarget = renderTarget2; renderTarget2 = h; } // renderTarget is now a non-MSAA renderTarget Texture2DExtensions.SaveToStream(renderTarget, options.ImageFormat, options.DestinationDpiResolution, toStream); scene.Detach(); Disposer.RemoveAndDispose(ref depthStencilView); Disposer.RemoveAndDispose(ref renderTargetView); Disposer.RemoveAndDispose(ref renderTarget2); Disposer.RemoveAndDispose(ref renderTarget); Disposer.RemoveAndDispose(ref depthStencil); Disposer.RemoveAndDispose(ref device); }
protected override void Initialize(DemoConfiguration demoConfiguration) { // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(demoConfiguration.Width, demoConfiguration.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = DisplayHandle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device1.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, FeatureLevel.Level_10_0, out _device, out _swapChain); // Ignore all windows events Factory factory = _swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(DisplayHandle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer _backBuffer = Texture2D.FromSwapChain<Texture2D>(_swapChain, 0); _backBufferView = new RenderTargetView(_device, _backBuffer); }
Texture2D createTexture(int width, int height, Format format) { var texDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = format, Height = height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Dynamic, Width = width }; Texture2D texture = new Texture2D(Host.Device, texDesc); return (texture); }
private void SetDevice() { this.RenderForm = new RenderForm("SharpDX - Basics") { Width = 1700, Height = 900 }; // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = RenderForm.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain { Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); this.Device = device; this.SwapChain = swapChain; } // Ignore all windows events var factory = SwapChain.GetParent<Factory>(); factory.MakeWindowAssociation(RenderForm.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0); this.RenderTargetView = new RenderTargetView(Device, backBuffer); // Create Constant Buffer var ConstantBuffer = new Buffer(Device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(Device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = RenderForm.ClientSize.Width, Height = RenderForm.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); this.DepthStencilView = new DepthStencilView(Device, depthBuffer); Device.VertexShader.SetConstantBuffer(0, ConstantBuffer); Device.Rasterizer.SetViewports(new Viewport(0, 0, RenderForm.ClientSize.Width, RenderForm.ClientSize.Height, 0.0f, 1.0f)); }
/// <summary> /// Crée le Device DirectX 10 et initialise les resources /// </summary> public void Initialize(int width, int height) { if (width <= 2) throw new ArgumentOutOfRangeException("width"); else if (height <= 2) throw new ArgumentOutOfRangeException("height"); Width = width; Height = height; Clean(); hwndRenderingWindow = new Form(); hwndRenderingWindow.Width = hwndRenderingWindow.Height = 100; var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = hwndRenderingWindow.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain //Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, desc, out device, out swapChain); Factory factory = new Factory(); var adapter = factory.GetAdapter(0); device = new Device(adapter, DeviceCreationFlags.BgraSupport, SharpDX.Direct3D10.FeatureLevel.Level_10_0); swapChain = new SwapChain(factory, device, desc); //device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport, SharpDX.Direct3D10.FeatureLevel.Level_10_0); Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; renderBuffer = new Texture2D(device, colordesc); renderView = new RenderTargetView(device, renderBuffer); LoadRenderShader(); wpfImage = new DX10ImageSource(); wpfImage.SetRenderTargetDX10(renderBuffer); RaisePropertyChanged("WPFImage"); }
/// <summary> /// Converts a height map into a normal map. The (x,y,z) components of each normal are mapped to the (r,g,b) channels of the output texture. /// </summary> /// <param name = "source">The source height map texture.</param> /// <param name = "destination">The destination texture.</param> /// <param name = "flags">One or more flags that control generation of normal maps.</param> /// <param name = "channel">One or more flag specifying the source of height information.</param> /// <param name = "amplitude">Constant value multiplier that increases (or decreases) the values in the normal map. Higher values usually make bumps more visible, lower values usually make bumps less visible.</param> /// <returns>A <see cref = "T:SharpDX.Result" /> object describing the result of the operation.</returns> public static void ComputeNormalMap(Texture2D source, Texture2D destination, NormalMapFlags flags, Channel channel, float amplitude) { D3DX10.ComputeNormalMap(source, flags, channel, amplitude, destination); }
Texture2D createTextureFromFile(string filename) { BitmapImage loadedImage = new BitmapImage(); loadedImage.BeginInit(); loadedImage.CacheOption = BitmapCacheOption.OnLoad; loadedImage.UriSource = new Uri(filename); loadedImage.EndInit(); loadedImage.Freeze(); int stride = loadedImage.PixelWidth * (loadedImage.Format.BitsPerPixel / 8); byte[] pixels = new byte[loadedImage.PixelHeight * stride]; loadedImage.CopyPixels(pixels, stride, 0); pinnedArray = GCHandle.Alloc(pixels, GCHandleType.Pinned); IntPtr pixelPtr = pinnedArray.AddrOfPinnedObject(); DataRectangle data = new DataRectangle(pixelPtr, stride); var texDesc = new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.B8G8R8A8_UNorm, Height = loadedImage.PixelHeight, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, Width = loadedImage.PixelWidth }; Texture2D texture = new Texture2D(Host.Device, texDesc, data); return (texture); }
public void UploadData(Size size, byte[] rgbaData) { Contract.Requires(Check.IsPositive(size.Width)); Contract.Requires(Check.IsPositive(size.Height)); Contract.Requires(rgbaData != null); Contract.Requires( rgbaData.Length >= (Convert.ToInt32(size.Width) * Convert.ToInt32(size.Height)) * 4); int regionWidth = Convert.ToInt32(size.Width); int regionHeight = Convert.ToInt32(size.Height); if(regionWidth != _Description.Width || regionHeight != _Description.Height) { _Description.Width = regionWidth; _Description.Height = regionHeight; _Texture.SafeDispose(); _Texture = new Texture2D(_Device3D, _Description); } DataRectangle data = _Texture.Map(0, MapMode.Write, MapFlags.None); try { int stageSize = data.Pitch * regionHeight; using(var stream = new DataStream(data.DataPointer, stageSize, false, true)) { int stride = regionWidth * 4; int indexTotal = regionHeight * stride; for(int index = 0; index < indexTotal; index += stride) { stream.Write(rgbaData, index, stride); stream.Seek(data.Pitch - stride, SeekOrigin.Current); } } } finally { _Texture.Unmap(0); } }
private void CreateAndBindTargets() { this.D3DSurface.SetRenderTargetDX10(null); Disposer.RemoveAndDispose(ref this.D2DRenderTarget); Disposer.RemoveAndDispose(ref this.D2DFactory); Disposer.RemoveAndDispose(ref this.RenderTarget); int width = Math.Max((int)base.ActualWidth, 100); int height = Math.Max((int)base.ActualHeight, 100); Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; this.RenderTarget = new Texture2D(this.Device, colordesc); Surface surface = this.RenderTarget.QueryInterface<Surface>(); D2DFactory = new SharpDX.Direct2D1.Factory(); var rtp = new RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)); D2DRenderTarget = new RenderTarget(D2DFactory, surface, rtp); this.D3DSurface.SetRenderTargetDX10(this.RenderTarget); OnOnCreateAndBindTargetEnd(this.D2DRenderTarget); Debug.Print("OnOnCreateAndBindTargetEnd"); }
public byte[] extractRawBitmap() { // use a cpu bound resource var textureDesc = new Texture2DDescription { MipLevels = 1, ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, Format = Format.B8G8R8A8_UNorm, OptionFlags = ResourceOptionFlags.None, Width = _width, Height = _height, Usage = ResourceUsage.Default, SampleDescription = new SampleDescription(1, 0) }; using (var cpuTexture = new Texture2D(_device, textureDesc)) { _device.CopyResource(_texture, cpuTexture); var res = new byte[4 * _width * _height]; var data = cpuTexture.Map(0, MapMode.Read, MapFlags.None); try { IntPtr sourcePtr = data.DataPointer; int targetOffset = 0; for (int i = 0; i != _height; ++i) { Marshal.Copy(sourcePtr, res, targetOffset, _width); sourcePtr += data.Pitch; targetOffset += _width; } return res; } finally { cpuTexture.Unmap(0); } } }
/// <summary> /// Saves a texture to a stream as an image. /// </summary> /// <param name="texture">The texture to save.</param> /// <param name="imageFormat">The image format of the saved image.</param> /// <param name="imageResolutionInDpi">The image resolution in dpi.</param> /// <param name="toStream">The stream to save the texture to.</param> public static void SaveToStream(this Texture2D texture, System.Drawing.Imaging.ImageFormat imageFormat, double imageResolutionInDpi, System.IO.Stream toStream) { Texture2D textureCopy = null; ImagingFactory imagingFactory = null; Bitmap bitmap = null; BitmapEncoder bitmapEncoder = null; try { textureCopy = new Texture2D(texture.Device, new Texture2DDescription { Width = (int)texture.Description.Width, Height = (int)texture.Description.Height, MipLevels = 1, ArraySize = 1, Format = texture.Description.Format, Usage = ResourceUsage.Staging, SampleDescription = new SampleDescription(1, 0), BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, OptionFlags = ResourceOptionFlags.None }); texture.Device.CopyResource(texture, textureCopy); DataRectangle dataRectangle = textureCopy.Map(0, MapMode.Read, SharpDX.Direct3D10.MapFlags.None); imagingFactory = new ImagingFactory(); bitmap = new Bitmap( imagingFactory, textureCopy.Description.Width, textureCopy.Description.Height, PixelFormat.Format32bppBGRA, dataRectangle); toStream.Position = 0; if (imageFormat == System.Drawing.Imaging.ImageFormat.Png) bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Bmp) bitmapEncoder = new BmpBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Gif) bitmapEncoder = new GifBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Jpeg) bitmapEncoder = new JpegBitmapEncoder(imagingFactory, toStream); else if (imageFormat == System.Drawing.Imaging.ImageFormat.Tiff) bitmapEncoder = new TiffBitmapEncoder(imagingFactory, toStream); else bitmapEncoder = new PngBitmapEncoder(imagingFactory, toStream); using (var bitmapFrameEncode = new BitmapFrameEncode(bitmapEncoder)) { bitmapFrameEncode.Initialize(); bitmapFrameEncode.SetSize(bitmap.Size.Width, bitmap.Size.Height); var pixelFormat = PixelFormat.FormatDontCare; bitmapFrameEncode.SetPixelFormat(ref pixelFormat); bitmapFrameEncode.SetResolution(imageResolutionInDpi, imageResolutionInDpi); bitmapFrameEncode.WriteSource(bitmap); bitmapFrameEncode.Commit(); bitmapEncoder.Commit(); } } finally { bitmapEncoder?.Dispose(); textureCopy?.Unmap(0); textureCopy?.Dispose(); bitmap?.Dispose(); imagingFactory?.Dispose(); } }
/// <summary> /// Our present hook that will grab a copy of the backbuffer when requested. Note: this supports multi-sampling /// (anti-aliasing) /// </summary> /// <param name="swapChainPtr"></param> /// <param name="syncInterval"></param> /// <param name="flags"></param> /// <returns>The HRESULT of the original method</returns> private int PresentHook(IntPtr swapChainPtr, int syncInterval, PresentFlags flags) { Frame(); var swapChain = (SwapChain) swapChainPtr; { try { #region Screenshot Request if (Request != null) { try { DebugMessage("PresentHook: Request Start"); var startTime = DateTime.Now; using (var texture = Resource.FromSwapChain<Texture2D>(swapChain, 0)) { #region Determine region to capture var regionToCapture = new Rectangle(0, 0, texture.Description.Width, texture.Description.Height); if (Request.RegionToCapture.Width > 0) { regionToCapture = Request.RegionToCapture; } #endregion var theTexture = texture; // If texture is multisampled, then we can use ResolveSubresource to copy it into a non-multisampled texture Texture2D textureResolved = null; if (texture.Description.SampleDescription.Count > 1) { DebugMessage("PresentHook: resolving multi-sampled texture"); // texture is multi-sampled, lets resolve it down to single sample textureResolved = new Texture2D(texture.Device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, Format = texture.Description.Format, Height = texture.Description.Height, Usage = ResourceUsage.Default, Width = texture.Description.Width, ArraySize = 1, SampleDescription = new SampleDescription(1, 0), // Ensure single sample BindFlags = BindFlags.None, MipLevels = 1, OptionFlags = texture.Description.OptionFlags }); // Resolve into textureResolved texture.Device.ResolveSubresource(texture, 0, textureResolved, 0, texture.Description.Format); // Make "theTexture" be the resolved texture theTexture = textureResolved; } // Create destination texture var textureDest = new Texture2D(texture.Device, new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, // CpuAccessFlags.Write | CpuAccessFlags.Read, Format = Format.R8G8B8A8_UNorm, // Supports BMP/PNG Height = regionToCapture.Height, Usage = ResourceUsage.Default, // ResourceUsage.Staging, Width = regionToCapture.Width, ArraySize = 1, //texture.Description.ArraySize, SampleDescription = new SampleDescription(1, 0), // texture.Description.SampleDescription, BindFlags = BindFlags.None, MipLevels = 1, //texture.Description.MipLevels, OptionFlags = texture.Description.OptionFlags }); // Copy the subresource region, we are dealing with a flat 2D texture with no MipMapping, so 0 is the subresource index theTexture.Device.CopySubresourceRegion(theTexture, 0, new ResourceRegion { Top = regionToCapture.Top, Bottom = regionToCapture.Bottom, Left = regionToCapture.Left, Right = regionToCapture.Right, Front = 0, Back = 1 // Must be 1 or only black will be copied }, textureDest, 0, 0, 0, 0); // Note: it would be possible to capture multiple frames and process them in a background thread // Copy to memory and send back to host process on a background thread so that we do not cause any delay in the rendering pipeline var request = Request.Clone(); // this.Request gets set to null, so copy the Request for use in the thread ThreadPool.QueueUserWorkItem(delegate { //FileStream fs = new FileStream(@"c:\temp\temp.bmp", FileMode.Create); //Texture2D.ToStream(testSubResourceCopy, ImageFileFormat.Bmp, fs); var startCopyToSystemMemory = DateTime.Now; using (var ms = new MemoryStream()) { Resource.ToStream(textureDest, ImageFileFormat.Bmp, ms); ms.Position = 0; this.DebugMessage("PresentHook: Copy to System Memory time: " + (DateTime.Now - startCopyToSystemMemory)); var startSendResponse = DateTime.Now; ProcessCapture(ms, request); this.DebugMessage("PresentHook: Send response time: " + (DateTime.Now - startSendResponse)); } // Free the textureDest as we no longer need it. textureDest.Dispose(); textureDest = null; this.DebugMessage("PresentHook: Full Capture time: " + (DateTime.Now - startTime)); }); // Make sure we free up the resolved texture if it was created if (textureResolved != null) { textureResolved.Dispose(); textureResolved = null; } } DebugMessage("PresentHook: Copy BackBuffer time: " + (DateTime.Now - startTime)); DebugMessage("PresentHook: Request End"); } finally { // Prevent the request from being processed a second time Request = null; } } #endregion #region Example: Draw overlay (after screenshot so we don't capture overlay as well) if (Config.ShowOverlay) { using (var texture = Resource.FromSwapChain<Texture2D>(swapChain, 0)) { if (FPS.GetFPS() >= 1) { var fd = new FontDescription { Height = 16, FaceName = "Arial", Italic = false, Width = 0, MipLevels = 1, CharacterSet = FontCharacterSet.Default, OutputPrecision = FontPrecision.Default, Quality = FontQuality.Antialiased, PitchAndFamily = FontPitchAndFamily.Default | FontPitchAndFamily.DontCare, Weight = FontWeight.Bold }; // TODO: do not create font every frame! using (var font = new Font(texture.Device, fd)) { DrawText(font, new Vector2(5, 5), string.Format("{0:N0} fps", FPS.GetFPS()), new Color4(Color.Red.ToColor3())); if (TextDisplay != null && TextDisplay.Display) { DrawText(font, new Vector2(5, 25), TextDisplay.Text, new Color4(Color.Red.ToColor3(), (Math.Abs(1.0f - TextDisplay.Remaining)))); } } } } } #endregion } catch (Exception e) { // If there is an error we do not want to crash the hooked application, so swallow the exception DebugMessage("PresentHook: Exeception: " + e.GetType().FullName + ": " + e.Message); } // As always we need to call the original method, note that EasyHook has already repatched the original method // so calling it here will not cause an endless recursion to this function swapChain.Present(syncInterval, flags); return Result.Ok.Code; } }
public void Dispose() { if (renderTexture != null) { renderTexture.Dispose(); renderTexture = null; } if (renderTextureView != null) { renderTextureView.Dispose(); renderTextureView = null; } }