public D3DBlendState( Device device, bool isBlendEnabled, Blend srcAlpha, Blend destAlpha, BlendFunction alphaBlendFunc, Blend srcColor, Blend destColor, BlendFunction colorBlendFunc, RgbaFloat blendFactor) { _device = device; IsBlendEnabled = isBlendEnabled; SourceAlphaBlend = srcAlpha; DestinationAlphaBlend = destAlpha; AlphaBlendFunction = alphaBlendFunc; SourceColorBlend = srcColor; DestinationColorBlend = destColor; ColorBlendFunction = colorBlendFunc; BlendFactor = blendFactor; var desc = new BlendStateDescription(); desc.RenderTarget[0].SourceAlphaBlend = D3DFormats.VeldridToD3DBlend(SourceAlphaBlend); desc.RenderTarget[0].DestinationAlphaBlend = D3DFormats.VeldridToD3DBlend(DestinationAlphaBlend); desc.RenderTarget[0].AlphaBlendOperation = D3DFormats.VeldridToD3DBlendFunction(AlphaBlendFunction); desc.RenderTarget[0].SourceBlend = D3DFormats.VeldridToD3DBlend(SourceColorBlend); desc.RenderTarget[0].DestinationBlend = D3DFormats.VeldridToD3DBlend(DestinationColorBlend); desc.RenderTarget[0].BlendOperation = D3DFormats.VeldridToD3DBlendFunction(ColorBlendFunction); desc.RenderTarget[0].IsBlendEnabled = isBlendEnabled; desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _deviceBlendState = new SharpDX.Direct3D11.BlendState(_device, desc); }
internal void Clear() { m_deviceContext.ClearState(); m_inputLayout = null; m_primitiveTopology = PrimitiveTopology.Undefined; m_indexBufferRef = null; m_indexBufferFormat = 0; m_indexBufferOffset = 0; for (int i = 0; i < m_vertexBuffers.Length; i++) m_vertexBuffers[i] = null; for (int i = 0; i < m_vertexBuffersStrides.Length; i++) m_vertexBuffersStrides[i] = 0; m_blendState = null; m_stencilRef = 0; m_depthStencilState = null; m_rtvsCount = 0; for (int i = 0; i < m_rtvs.Length; i++) m_rtvs[i] = null; m_dsv = null; m_rasterizerState = null; m_scissorLeftTop = new Vector2I(-1, -1); m_scissorRightBottom = new Vector2I(-1, -1); m_viewport = default(RawViewportF); m_targetBuffer = null; m_targetOffsets = 0; m_statistics.ClearStates++; }
/// <summary> /// Creates a new ApertureComposer instance. /// </summary> /// <param name="device">The graphics device.</param> public ApertureComposer(Device device) { BlendStateDescription description = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; description.RenderTarget[0] = new RenderTargetBlendDescription() { IsBlendEnabled = true, SourceBlend = BlendOption.Zero, DestinationBlend = BlendOption.SourceColor, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.Zero, DestinationAlphaBlend = BlendOption.Zero, AlphaBlendOperation = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.Red, }; blendState = new BlendState(device, description); // Instantiate all layers here layers.Add(new StructuralLayer()); }
public BlendState(bool blendEnabled, BlendOperation blendOperation, BlendOperation alphaBlendOperation, BlendOption sourceBlend, BlendOption destinationBlend, BlendOption sourceAlphhaBlend, BlendOption destinationAlphaBlend) { RenderTargetBlendDescription targetDesc = new RenderTargetBlendDescription() { AlphaBlendOperation = alphaBlendOperation, BlendOperation = blendOperation, DestinationAlphaBlend = destinationAlphaBlend, SourceAlphaBlend = sourceAlphhaBlend, SourceBlend = sourceBlend, DestinationBlend = destinationBlend, IsBlendEnabled = blendEnabled, RenderTargetWriteMask = ColorWriteMaskFlags.All }; BlendStateDescription desc = new BlendStateDescription() { IndependentBlendEnable = false, }; desc.RenderTarget[0] = targetDesc; NativeBlendState = new SharpDX.Direct3D11.BlendState(GraphicManager.Device, desc); }
/// <summary> /// SetupBlendState /// </summary> void SetupBlendState() { var rtbd = new RenderTargetBlendDescription(); bool enabled = true; if (BlendState.DstAlpha == Blend.Zero && BlendState.SrcAlpha == Blend.One && BlendState.DstColor == Blend.Zero && BlendState.SrcColor == Blend.One) { enabled = false; } rtbd.IsBlendEnabled = enabled; rtbd.BlendOperation = Converter.Convert(BlendState.ColorOp); rtbd.AlphaBlendOperation = Converter.Convert(BlendState.AlphaOp); rtbd.RenderTargetWriteMask = (ColorWriteMaskFlags)(int)BlendState.WriteMask; rtbd.DestinationBlend = Converter.Convert(BlendState.DstColor); rtbd.SourceBlend = Converter.Convert(BlendState.SrcColor); rtbd.DestinationAlphaBlend = Converter.Convert(BlendState.DstAlpha); rtbd.SourceAlphaBlend = Converter.Convert(BlendState.SrcAlpha); var bsd = new BlendStateDescription(); bsd.AlphaToCoverageEnable = false; bsd.IndependentBlendEnable = false; bsd.RenderTarget[0] = rtbd; blendFactor = SharpDXHelper.Convert(BlendState.BlendFactor); blendMsaaMask = BlendState.MultiSampleMask; blendState = new D3DBlendState(device.Device, bsd); }
/// <summary> /// Initializes a new instance of the <see cref="BlendState" /> class. /// </summary> /// <param name="device">The device local.</param> /// <param name="description">The description.</param> /// <param name="blendFactor">The blend factor.</param> /// <param name="mask">The mask.</param> private BlendState(DirectXDevice device, BlendStateDescription description, Color4 blendFactor, int mask) : base(device) { this.description = description; BlendFactor = blendFactor; MultiSampleMask = mask; Resource = new SharpDX.Direct3D11.BlendState(device, description); }
private void Dispose(bool disposing) { if (mState != null) { mState.Dispose(); mState = null; } mContext = null; }
internal static void Run(MyBindableResource dst, MyBindableResource src, BlendState bs = null) { RC.SetBS(bs); RC.SetRS(null); RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, dst); RC.BindSRV(0, src); RC.SetPS(m_copyPixelShader); DrawFullscreenQuad(); RC.SetBS(null); }
internal static void RunWithStencil(MyBindableResource destinationResource, MyBindableResource sourceResource, BlendState blendState, DepthStencilState depthStencilState, int stencilMask) { RC.SetDS(depthStencilState, stencilMask); RC.SetBS(blendState); RC.SetRS(null); RC.BindDepthRT(MyGBuffer.Main.DepthStencil, DepthStencilAccess.ReadOnly, destinationResource); RC.BindSRV(0, sourceResource); RC.SetPS(m_copyPixelShader); DrawFullscreenQuad(); RC.SetBS(null); }
internal static void RunWithPixelStencilTest(MyBindableResource dst, MyBindableResource src, BlendState bs = null, bool inverseTest = false) { RC.SetDS(null); RC.SetBS(bs); RC.SetRS(null); RC.BindDepthRT(null, DepthStencilAccess.ReadOnly, dst); RC.BindSRV(0, src); RC.BindSRV(1, MyGBuffer.Main.DepthStencil.Stencil); if (!inverseTest) RC.SetPS(m_stencilTestPixelShader); else RC.SetPS(m_stencilInverseTestPixelShader); DrawFullscreenQuad(); RC.SetBS(null); }
void CreateBlendStates() { var desc = BlendStateDescription.Default(); _blendStateDefault = new BlendState(Device, desc); AutoDispose(_blendStateDefault); desc = BlendStateDescription.Default(); desc.RenderTarget[0].IsBlendEnabled = true; desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; desc.RenderTarget[0].BlendOperation = BlendOperation.Add; desc.RenderTarget[0].SourceBlend = BlendOption.One; desc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _blendStateAlphaBlend = new BlendState(Device, desc); AutoDispose(_blendStateAlphaBlend); }
private void EnableAlphaBlending() { if (blendState != null) { blendState.Dispose(); } // Enable alpha blending // Based on: https://stackoverflow.com/questions/24899337/sharpdx-dx11-alpha-blend blendStateDesc = new D3D11.BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; blendStateDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendStateDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; blendStateDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendState = new D3D11.BlendState(d3dDevice, blendStateDesc); d3dDeviceContext.OutputMerger.SetBlendState(blendState); }
public override bool Init() { if (!base.Init()) { return(false); } //Initialize Wave Physics _awave = new AcceleratedWave(Device, ImmediateContext, "FX/compute.fx", "ProcessVertex"); _awave.Init(200, 200, 0.8f, 0.03f, 6.25f, 0.1f); BuildLandGeometryBuffers(); BuildWavesGeometryBuffers(); BuildBallGeometryBuffers(); BuildFX(); BuildVertexLayout(); FillWavesGeometryBuffer(); //Initialize Alpha Blending D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription(); alphaDesc.RenderTarget[0].IsBlendEnabled = true; alphaDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; alphaDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; alphaDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; alphaDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; _alphaBlend = new D3D11.BlendState(base.Device, alphaDesc); //Setup Ground Texture _groundMap = TextureLoader.CreateTex2DFromFile(Device, "Textures\\grass.jpg"); _groundMapSRV = new D3D11.ShaderResourceView(Device, _groundMap); return(true); }
public void Begin(SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState blendState = null) { _SortMode = sortMode; _BlendFactor = new Color4(1f); if (blendState != null) _BlendState = blendState; _SpriteCacheByResource.Clear(); _ResourceCache.Clear(); var context = GraphicsAdapter.GraphicsDeviceContext; // Save current blend state _PreviousBlendState = context.OutputMerger.GetBlendState(out _PreviousBlendFactor, out _PreviousBlendMask); // Apply our blend state context.OutputMerger.SetBlendState(_BlendState, _BlendFactor); }
internal void SetBlendState(BlendState bs) { if (bs == m_blendState) return; m_blendState = bs; m_deviceContext.OutputMerger.SetBlendState(bs); m_statistics.SetBlendStates++; }
public void Run() { var form = new RenderForm("2d and 3d combined...it's like magic"); form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) form.Close(); }; // DirectX DXGI 1.1 factory var factory1 = new Factory1(); // The 1st graphics adapter var adapter1 = factory1.GetAdapter1(0); // --------------------------------------------------------------------------------------------- // Setup direct 3d version 11. It's context will be used to combine the two elements // --------------------------------------------------------------------------------------------- var description = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch }; Device11 device11; SwapChain swapChain; Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created RenderTargetView renderTargetView; using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0)) renderTargetView = new RenderTargetView(device11, resource); // setting a viewport is required if you want to actually see anything var context = device11.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTargetView); context.Rasterizer.SetViewports(viewport); // // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device. // // The DirectX10 device will be used to render text onto this texture. // DirectX11 will then draw this texture (blended) onto the screen. // The KeyedMutex flag is required in order to share this resource between the two devices. var textureD3D11 = new Texture2D(device11, new Texture2DDescription { Width = form.ClientSize.Width, Height = form.ClientSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }); // --------------------------------------------------------------------------------------------- // Setup a direct 3d version 10.1 adapter // --------------------------------------------------------------------------------------------- var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); // --------------------------------------------------------------------------------------------- // Setup Direct 2d // --------------------------------------------------------------------------------------------- // Direct2D Factory var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information); // Here we bind the texture we've created on our direct3d11 device through the direct3d10 // to the direct 2d render target.... var sharedResource = textureD3D11.QueryInterface<SharpDX.DXGI.Resource>(); var textureD3D10 = device10.OpenSharedResource<SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var surface = textureD3D10.AsSurface(); var rtp = new RenderTargetProperties { MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied) }; var renderTarget2D = new RenderTarget(factory2D, surface, rtp); var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red); // --------------------------------------------------------------------------------------------------- // Setup the rendering data // --------------------------------------------------------------------------------------------------- // Load Effect. This includes both the vertex and pixel shaders. // Also can include more than one technique. ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile( "effectDx11.fx", "fx_5_0", ShaderFlags.EnableStrictness); var effect = new Effect(device11, shaderByteCode); // create triangle vertex data, making sure to rewind the stream afterward var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f),new Color4(1.0f, 0.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f),new Color4(0.0f, 1.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f),new Color4(0.0f, 0.0f, 1.0f, 1.0f))); verticesTriangle.Position = 0; // create the triangle vertex layout and buffer var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements); var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesTriangle.Close(); // create overlay vertex data, making sure to rewind the stream afterward // Top Left of screen is -1, +1 // Bottom Right of screen is +1, -1 var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true); verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0),new Vector2(0, 0f))); verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0),new Vector2(1, 0))); verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0),new Vector2(0, 1))); verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0),new Vector2(1, 1))); verticesText.Position = 0; // create the overlay vertex layout and buffer var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements); var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesText.Close(); // Think of the shared textureD3D10 as an overlay. // The overlay needs to show the 2d content but let the underlying triangle (or whatever) // show thru, which is accomplished by blending. var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; var blendStateTransparent = new BlendState(device11, bsd); // --------------------------------------------------------------------------------------------------- // Create and tesselate an ellipse // --------------------------------------------------------------------------------------------------- var center = new DrawingPointF(form.ClientSize.Width/2.0f, form.ClientSize.Height/2.0f); var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f)); // Populate a PathGeometry from Ellipse tessellation var tesselatedGeometry = new PathGeometry(factory2D); _geometrySink = tesselatedGeometry.Open(); // Force RoundLineJoin otherwise the tesselated looks buggy at line joins _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); // Tesselate the ellipse to our TessellationSink ellipse.Tessellate(1, this); _geometrySink.Close(); // --------------------------------------------------------------------------------------------------- // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface // --------------------------------------------------------------------------------------------------- var device10Mutex = textureD3D10.QueryInterface<KeyedMutex>(); var device11Mutex = textureD3D11.QueryInterface<KeyedMutex>(); // --------------------------------------------------------------------------------------------------- // Main rendering loop // --------------------------------------------------------------------------------------------------- bool first = true; RenderLoop .Run(form, () => { if(first) { form.Activate(); first = false; } // clear the render target to black context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray); // Draw the triangle context.InputAssembler.InputLayout = layoutColor; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0)); context.OutputMerger.BlendState = null; var currentTechnique = effect.GetTechniqueByName("Color"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(3, 0); }; // Draw Ellipse on the shared Texture2D device10Mutex.Acquire(0, 100); renderTarget2D.BeginDraw(); renderTarget2D.Clear(Colors.Black); renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush); renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null); renderTarget2D.EndDraw(); device10Mutex.Release(0); // Draw the shared texture2D onto the screen, blending the 2d content in device11Mutex.Acquire(0, 100); var srv = new ShaderResourceView(device11, textureD3D11); effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv); context.InputAssembler.InputLayout = layoutOverlay; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0)); context.OutputMerger.BlendState = blendStateTransparent; currentTechnique = effect.GetTechniqueByName("Overlay"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(4, 0); } srv.Dispose(); device11Mutex.Release(0); swapChain.Present(0, PresentFlags.None); }); // dispose everything vertexBufferColor.Dispose(); vertexBufferOverlay.Dispose(); layoutColor.Dispose(); layoutOverlay.Dispose(); effect.Dispose(); shaderByteCode.Dispose(); renderTarget2D.Dispose(); swapChain.Dispose(); device11.Dispose(); device10.Dispose(); textureD3D10.Dispose(); textureD3D11.Dispose(); factory1.Dispose(); adapter1.Dispose(); sharedResource.Dispose(); factory2D.Dispose(); surface.Dispose(); solidColorBrush.Dispose(); blendStateTransparent.Dispose(); device10Mutex.Dispose(); device11Mutex.Dispose(); }
public void Initialize() { var direct2Dsettings = new RenderTarget.Configuration.CreationSettings( new Size(_settings.Width, _settings.Height), false, new SampleDescription(1, 0), RenderTarget.Configuration.RenderTargetClearSettings.Default, RenderTarget.Configuration.DepthStencilClearSettings.Default); RenderTargetDirect2D = _deviceManager.RenderTargetManager.CreateDirect2DRenderTarget(direct2Dsettings); _screenQuad = MeshFactory.CreateScreenQuad(_deviceManager.Device); //_screenQuadBinding = new VertexBufferBinding(_screenQuad, 20, 0); _effect = _deviceManager.ShaderCompiler.CreateEffectFromFile(@"..\..\Shaders\staging.fx"); _pass = _effect.GetTechniqueByIndex(0).GetPassByIndex(0); //_elements = new[] // { // new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), // new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), // }; _screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, VertexPositionTexture.InputElements); //_screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, _elements); _shaderResource = _effect.GetVariableByName("source").AsShaderResource(); var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _blendStateTransparent = new BlendState(_deviceManager.Device, bsd); }
private void InitializeInternal(Device device) { Debug.Assert(device != null); var wfDesc = new RasterizerStateDescription { FillMode = FillMode.Wireframe, CullMode = CullMode.Back, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _wireframeRs = new RasterizerState(device, wfDesc); var noCullDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.None, IsFrontCounterClockwise = false, IsDepthClipEnabled = true }; _noCullRs = new RasterizerState(device, noCullDesc); var cullClockwiseDesc = new RasterizerStateDescription { FillMode = FillMode.Solid, CullMode = CullMode.Back, IsFrontCounterClockwise = true, IsDepthClipEnabled = true }; _cullClockwiseRs = new RasterizerState(device, cullClockwiseDesc); var atcDesc = new BlendStateDescription { AlphaToCoverageEnable = true, IndependentBlendEnable = false, }; atcDesc.RenderTarget[0].IsBlendEnabled = false; atcDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _alphaToCoverageBs = new BlendState(device, atcDesc); var transDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; transDesc.RenderTarget[0].IsBlendEnabled = true; transDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBs = new BlendState(device, transDesc); var noRenderTargetWritesDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; noRenderTargetWritesDesc.RenderTarget[0].IsBlendEnabled = false; noRenderTargetWritesDesc.RenderTarget[0].SourceBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; noRenderTargetWritesDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; noRenderTargetWritesDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; noRenderTargetWritesDesc.RenderTarget[0].RenderTargetWriteMask = 0; _noRenderTargetWritesBs = new BlendState(device, noRenderTargetWritesDesc); var mirrorDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Replace, Comparison = Comparison.Always } }; _markMirrorDss = new DepthStencilState(device, mirrorDesc); var drawReflectionDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Keep, Comparison = Comparison.Equal } }; _drawReflectionDss = new DepthStencilState(device, drawReflectionDesc); var noDoubleBlendDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xff, StencilWriteMask = 0xff, FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal }, BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Keep, PassOperation = StencilOperation.Increment, Comparison = Comparison.Equal } }; _noDoubleBlendDss = new DepthStencilState(device, noDoubleBlendDesc); var lessEqualDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false }; _lessEqualDss = new DepthStencilState(device, lessEqualDesc); var equalsDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.LessEqual, }; _equalsDss = new DepthStencilState(device, equalsDesc); var noDepthDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthComparison = Comparison.Always, DepthWriteMask = DepthWriteMask.Zero }; _noDepthDss = new DepthStencilState(device, noDepthDesc); }
protected void OnInitializeDevice() { Form.ClientSize = new Size(_width, _height); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(_width, _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 SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out _device, out _swapChain); _immediateContext = _device.ImmediateContext; outputMerger = _immediateContext.OutputMerger; inputAssembler = _immediateContext.InputAssembler; Factory factory = _swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(Form.Handle, WindowAssociationFlags.None); 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; alphaBlendState = new BlendState(_device, blendStateDesc); }
void DefineBlendState() { var desc = BlendStateDescription.Default(); desc.RenderTarget[0].IsBlendEnabled = true; desc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; desc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTarget[0].BlendOperation = BlendOperation.Add; /* desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; */ default_blend_state = new BlendState(device, desc); }
protected override void CreateDeviceDependentResources() { RemoveAndDispose(ref vertexShader); RemoveAndDispose(ref lightBuffer); RemoveAndDispose(ref RTV); RemoveAndDispose(ref SRV); RemoveAndDispose(ref rsCullBack); RemoveAndDispose(ref rsCullFront); RemoveAndDispose(ref rsWireframe); RemoveAndDispose(ref blendStateAdd); RemoveAndDispose(ref depthLessThan); RemoveAndDispose(ref depthGreaterThan); RemoveAndDispose(ref depthDisabled); RemoveAndDispose(ref perLightBuffer); RemoveAndDispose(ref psAmbientLight); RemoveAndDispose(ref psDirectionalLight); RemoveAndDispose(ref psPointLight); RemoveAndDispose(ref psSpotLight); RemoveAndDispose(ref psDebugLight); RemoveAndDispose(ref perLightBuffer); // Retrieve our SharpDX.Direct3D11.Device1 instance var device = this.DeviceManager.Direct3DDevice; int width, height; SampleDescription sampleDesc; // Retrieve DSV from GBuffer and extract width/height // then create a new read-only DSV using (var depthTexture = gbuffer.DSV.ResourceAs<Texture2D>()) { width = depthTexture.Description.Width; height = depthTexture.Description.Height; sampleDesc = depthTexture.Description.SampleDescription; // Initialize read-only DSV var dsvDesc = gbuffer.DSV.Description; dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil; DSVReadonly = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc)); } // Check if GBuffer is multi-sampled bool isMSAA = sampleDesc.Count > 1; // Initialize the light render target var texDesc = new Texture2DDescription(); texDesc.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget; texDesc.ArraySize = 1; texDesc.CpuAccessFlags = CpuAccessFlags.None; texDesc.Usage = ResourceUsage.Default; texDesc.Width = width; texDesc.Height = height; texDesc.MipLevels = 1; // No mip levels texDesc.SampleDescription = sampleDesc; texDesc.Format = Format.R8G8B8A8_UNorm; lightBuffer = ToDispose(new Texture2D(device, texDesc)); // Render Target View description var rtvDesc = new RenderTargetViewDescription(); rtvDesc.Format = Format.R8G8B8A8_UNorm; rtvDesc.Dimension = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D; rtvDesc.Texture2D.MipSlice = 0; RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc)); // SRV description for render targets var srvDesc = new ShaderResourceViewDescription(); srvDesc.Format = Format.R8G8B8A8_UNorm; srvDesc.Dimension = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D; srvDesc.Texture2D.MipLevels = -1; srvDesc.Texture2D.MostDetailedMip = 0; SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc)); // Initialize additive blend state (assuming single render target) BlendStateDescription bsDesc = new BlendStateDescription(); bsDesc.RenderTarget[0].IsBlendEnabled = true; bsDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One; bsDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; bsDesc.RenderTarget[0].SourceBlend = BlendOption.One; bsDesc.RenderTarget[0].DestinationBlend = BlendOption.One; bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendStateAdd = ToDispose(new BlendState(device, bsDesc)); // Initialize rasterizer states RasterizerStateDescription rsDesc = new RasterizerStateDescription(); rsDesc.FillMode = FillMode.Solid; rsDesc.CullMode = CullMode.Back; rsCullBack = ToDispose(new RasterizerState(device, rsDesc)); rsDesc.CullMode = CullMode.Front; rsCullFront = ToDispose(new RasterizerState(device, rsDesc)); rsDesc.CullMode = CullMode.Front; rsDesc.FillMode = FillMode.Wireframe; rsWireframe = ToDispose(new RasterizerState(device, rsDesc)); // Initialize depth state var dsDesc = new DepthStencilStateDescription(); dsDesc.IsStencilEnabled = false; dsDesc.IsDepthEnabled = true; // Less-than depth comparison dsDesc.DepthComparison = Comparison.Less; depthLessThan = ToDispose(new DepthStencilState(device, dsDesc)); // Greater-than depth comparison dsDesc.DepthComparison = Comparison.Greater; depthGreaterThan = ToDispose(new DepthStencilState(device, dsDesc)); // Depth/stencil testing disabled dsDesc.IsDepthEnabled = false; depthDisabled = ToDispose(new DepthStencilState(device, dsDesc)); // Buffer to light parameters perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); if (isMSAA) { // Compile and create the vertex shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0")) vertexShader = ToDispose(new VertexShader(device, bytecode)); // Compile pixel shaders using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0")) psAmbientLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0")) psDirectionalLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0")) psPointLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0")) psSpotLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0")) psDebugLight = ToDispose(new PixelShader(device, bytecode)); } else { // Compile and create the vertex shader using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0")) vertexShader = ToDispose(new VertexShader(device, bytecode)); // Compile pixel shaders using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0")) psAmbientLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0")) psDirectionalLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0")) psPointLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0")) psSpotLight = ToDispose(new PixelShader(device, bytecode)); using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0")) psDebugLight = ToDispose(new PixelShader(device, bytecode)); } }
internal static void RunWithPixelStencilTest(MyBindableResource dst, MyBindableResource src, BlendState bs = null) { RC.SetDS(null); RC.SetBS(bs); RC.SetRS(null); RC.BindDepthRT(null, DepthStencilAccess.ReadOnly, dst); RC.BindSRV(0, src); RC.BindSRV(1, MyGBuffer.Main.DepthStencil.Stencil); RC.SetPS(m_psPixelStencil); DrawFullscreenQuad(); RC.SetBS(null); }
internal static void RunWithStencil(MyBindableResource dst, MyBindableResource src, BlendState bs = null) { RC.SetDS(MyDepthStencilState.TestOutlineMeshStencil, 0x40); RC.SetBS(bs); RC.SetRS(null); RC.BindDepthRT(MyGBuffer.Main.DepthStencil, DepthStencilAccess.ReadOnly, dst); RC.BindSRV(0, src); RC.SetPS(m_ps); DrawFullscreenQuad(); RC.SetBS(null); }
internal static void Run(MyBindableResource dst, MyBindableResource src, BlendState bs = null) { //RC.SetBS(MyRender.BlendStateAdditive); RC.SetBS(bs); RC.SetRS(null); RC.BindDepthRT(null, DepthStencilAccess.ReadWrite, dst); RC.BindSRV(0, src); RC.SetPS(m_ps); DrawFullscreenQuad(); RC.SetBS(null); }
internal void Clear() { if (m_VBs == null) { m_VBs = new Buffer[8]; m_strides = new int[8]; m_CBs = new Buffer[8]; m_bindings = new SortedDictionary<int, MyBinding>(); m_srvBindings = new SortedSet<Tuple<int, int>>(); m_RTVs = new RenderTargetView[8]; m_SRVs = new ShaderResourceView[8]; m_constantsVersion = new Dictionary<Buffer, int>(); m_constantBindings = new Dictionary<MyStageBinding, Buffer>(); m_srvTableBindings = new Dictionary<MyStageSrvBinding, int>(); m_srvBindings1 = new List<MyStageSrvBinding>(); } m_IB = null; m_inputLayout = null; m_ps = null; m_vs = null; m_gs = null; m_RS = null; m_BS = null; m_DS = null; m_stencilRef = 0; Array.Clear(m_VBs, 0, m_VBs.Length); Array.Clear(m_CBs, 0, m_CBs.Length); m_bindings.Clear(); m_srvBindings.Clear(); m_constantsVersion.Clear(); m_constantBindings.Clear(); m_srvTableBindings.Clear(); m_srvBindings1.Clear(); }
public void InitializeBuffers() { //Create back buffer Texture2D backBuffer = Resource.FromSwapChain<Texture2D>(SwapChain, 0); _renderTargetView = new RenderTargetView(Device, backBuffer); backBuffer.Dispose(); //Create the depth/stencil buffer var depthBufferDesc = new Texture2DDescription { Width = ConfigurationManager.Config.Width, Height = ConfigurationManager.Config.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = ConfigurationManager.Config.AntiAliasing ? new SampleDescription(4, _maxQualityLevel-1) : new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; _depthStencilBuffer = new Texture2D(Device, depthBufferDesc); DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. _depthStencilState = new DepthStencilState(Device, depthStencilDesc); DepthStencilStateDescription depthDisabledStencilDesc = new DepthStencilStateDescription { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; _depthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); // Set the depth stencil state. _isZBufferEnabled = true; DeviceContext.OutputMerger.SetDepthStencilState(_depthStencilState, 1); // Initialize and set up the depth stencil view. DepthStencilViewDescription depthStencilViewDesc; if(ConfigurationManager.Config.AntiAliasing) depthStencilViewDesc = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2DMultisampled, Texture2DMS = new DepthStencilViewDescription.Texture2DMultisampledResource() }; else depthStencilViewDesc = new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, _depthStencilBuffer, depthStencilViewDesc); RenderToTextureDepthStencilView = new DepthStencilView(Device, new Texture2D(Device, new Texture2DDescription { Width = ConfigurationManager.Config.Width, Height = ConfigurationManager.Config.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }), new DepthStencilViewDescription { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, _renderTargetView); // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. _rasterStateSolid = new RasterizerState(Device, rasterDesc); rasterDesc.FillMode = FillMode.Wireframe; _rasterStateWireFrame = new RasterizerState(Device, rasterDesc); // Now set the rasterizer state. DeviceContext.Rasterizer.State = _rasterStateSolid; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, ConfigurationManager.Config.Width, ConfigurationManager.Config.Height, 0, 1); var blendStateDescription = new BlendStateDescription(); blendStateDescription.RenderTarget[0].IsBlendEnabled = true; blendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; blendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; blendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One; blendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; blendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; blendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; // Create the blend state using the description. _alphaEnabledBlendState = new BlendState(Device, blendStateDescription); blendStateDescription.RenderTarget[0].IsBlendEnabled = false; // Create the blend state using the description. _alphaDisabledBlendState = new BlendState(Device, blendStateDescription); }
internal void SetBS(BlendState bs) { if (State.m_BS != bs) { State.m_BS = bs; Context.OutputMerger.SetBlendState(bs); Stats.SetBlendState++; } }
protected override void CreateDeviceDependentResources() { RemoveAndDispose(ref vertexShader); RemoveAndDispose(ref vertexShaderInstanced); RemoveAndDispose(ref geomShader); RemoveAndDispose(ref pixelShader); RemoveAndDispose(ref blendState); RemoveAndDispose(ref linearSampler); RemoveAndDispose(ref perComputeBuffer); RemoveAndDispose(ref perFrame); // Dispose of any loaded particle textures particleTextureSRVs.ForEach(srv => RemoveAndDispose(ref srv)); particleTextureSRVs.Clear(); // Dispose of any compute shaders computeShaders.Select(kv => kv.Value).ToList().ForEach(cs => RemoveAndDispose(ref cs)); computeShaders.Clear(); var device = this.DeviceManager.Direct3DDevice; #region Compile Vertex/Pixel/Geometry shaders // Compile and create the vertex shader using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMain", "vs_5_0")) using (var vsInstance = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMainInstance", "vs_5_0")) // Compile and create the pixel shader using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticlePS.hlsl", "PSMain", "ps_5_0")) // Compile and create the geometry shader using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleGS.hlsl", "PointToQuadGS", "gs_5_0")) { vertexShader = ToDispose(new VertexShader(device, vsBytecode)); vertexShaderInstanced = ToDispose(new VertexShader(device, vsInstance)); pixelShader = ToDispose(new PixelShader(device, psBytecode)); geomShader = ToDispose(new GeometryShader(device, gsBytecode)); } #endregion #region Blend States var blendDesc = new BlendStateDescription() { IndependentBlendEnable = false, AlphaToCoverageEnable = false, }; // Additive blend state that darkens blendDesc.RenderTarget[0] = new RenderTargetBlendDescription { IsBlendEnabled = true, BlendOperation = BlendOperation.Add, AlphaBlendOperation = BlendOperation.Add, SourceBlend = BlendOption.SourceAlpha, DestinationBlend = BlendOption.InverseSourceAlpha, SourceAlphaBlend = BlendOption.One, DestinationAlphaBlend = BlendOption.Zero, RenderTargetWriteMask = ColorWriteMaskFlags.All }; blendState = ToDispose(new BlendState(device, blendDesc)); // Additive blend state that lightens // (needs a dark background) blendDesc.RenderTarget[0].DestinationBlend = BlendOption.One; blendStateLight = ToDispose(new BlendState(device, blendDesc)); #endregion // depth stencil state to disable Z-buffer disableDepthWrite = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription { DepthComparison = Comparison.Less, DepthWriteMask = SharpDX.Direct3D11.DepthWriteMask.Zero, IsDepthEnabled = true, IsStencilEnabled = false })); // Create a linear sampler linearSampler = ToDispose(new SamplerState(device, new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.MinMagMipLinear, // Bilinear MaximumLod = float.MaxValue, MinimumLod = 0, })); // Create the per compute shader constant buffer perComputeBuffer = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleConstants>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); // Create the particle frame buffer perFrame = ToDispose(new Buffer(device, Utilities.SizeOf<ParticleFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0)); particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Particle.png"))); particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Snowflake.png"))); particleTextureSRVs.Add(ToDispose(ShaderResourceView.FromFile(device, "Square.png"))); activeParticleTextureIndex = 0; // Reinitialize particles if > 0 if (this.Constants.MaxParticles > 0) { InitializeParticles(this.Constants.MaxParticles, this.Constants.MaxLifetime); } }
unsafe void InitializeInner(AntiAliasingMode antiAliasingMode) { worldMatrix = Matrix.Identity; textMatrix = Matrix.Identity; device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.None, new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 }); tkDevice = TK.GraphicsDevice.New(device); deviceContext = device.ImmediateContext; deviceContext.Rasterizer.State = device.CreateRasterizerState(); //TODO: replace with precompiled bytecode const string shaderFile = @"..\..\..\GameUtils\Graphics\shaders.fx"; ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "VS", "vs_4_0", ShaderFlags.Debug); ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "PS", "ps_4_0", ShaderFlags.Debug); InitializeShaders(vertexShaderBytecode, pixelShaderBytecode); indexBuffers = new D3D11.Buffer[BufferCount]; vertexBuffers = new D3D11.Buffer[BufferCount]; for (int i = 0, indexBufferSize = IndexBufferStartSize, vertexBufferSize = VertexBufferStartSize; i < BufferCount; i++, indexBufferSize <<= BufferSizeStep, vertexBufferSize <<= BufferSizeStep) { indexBuffers[i] = device.CreateDynamicBuffer(sizeof(int) * indexBufferSize, D3D11.BindFlags.IndexBuffer); vertexBuffers[i] = device.CreateDynamicBuffer(sizeof(Vertex) * vertexBufferSize, D3D11.BindFlags.VertexBuffer); } currentBufferIndex = 0; indexBuffer = indexBuffers[0]; vertexBuffer = vertexBuffers[0]; //indexBuffer = device.CreateDynamicBuffer(sizeof(int) * IndexBufferSize, D3D11.BindFlags.IndexBuffer); //vertexBuffer = device.CreateDynamicBuffer(sizeof(Vertex) * VertexBufferSize, D3D11.BindFlags.VertexBuffer); matrixBuffer = device.CreateConstantBuffer(sizeof(MatrixBuffer)); brushBuffer = device.CreateConstantBuffer(sizeof(Brush.BrushBuffer)); deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0); deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0)); deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; blendState = device.CreateBlendState(); deviceContext.OutputMerger.SetBlendState(blendState); currentWrapMode = WrapMode.Clamp; currentInterpolationMode = InterpolationMode.Linear; samplerState = device.CreateSamplerState(WrapMode.Clamp, InterpolationMode.Linear); deviceContext.PixelShader.SetSampler(0, samplerState); sampleDescription = device.GetMultisamplingLevel(antiAliasingMode); defaultDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Always, D3D11.StencilOperation.Keep, D3D11.StencilOperation.Keep); clipDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Never, D3D11.StencilOperation.Replace, D3D11.StencilOperation.Keep); clippingDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Equal, D3D11.StencilOperation.Keep, D3D11.StencilOperation.Keep); deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState); }
private void SetBlendState() { blendState = new BlendState(Device, BlendStateDescription.Default()); }
public Renderer(Game game, SharpDX.Windows.RenderForm renderForm) { this.game = game; int width = renderForm.ClientSize.Width, height = renderForm.ClientSize.Height; ResolutionX = width; ResolutionY = height; #region 3d device & context D3D11.DeviceCreationFlags creationFlags = D3D11.DeviceCreationFlags.BgraSupport; #if DEBUG creationFlags |= D3D11.DeviceCreationFlags.Debug; #endif DXGI.SwapChainDescription swapChainDesc = new DXGI.SwapChainDescription() { ModeDescription = new DXGI.ModeDescription(width, height, new DXGI.Rational(60, 1), DXGI.Format.R8G8B8A8_UNorm), SampleDescription = new DXGI.SampleDescription(SampleCount, SampleQuality), Usage = DXGI.Usage.RenderTargetOutput, BufferCount = 1, OutputHandle = renderForm.Handle, IsWindowed = true, SwapEffect = DXGI.SwapEffect.Discard }; D3D11.Device device; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, creationFlags, swapChainDesc, out device, out swapChain); Device = device; Context = Device.ImmediateContext; #endregion #region 2d device & context DXGI.Device dxgiDevice = Device.QueryInterface <D3D11.Device1>().QueryInterface <DXGI.Device2>(); D2DDevice = new D2D1.Device(dxgiDevice); D2DContext = new D2D1.DeviceContext(D2DDevice, D2D1.DeviceContextOptions.None); D2DFactory = D2DDevice.Factory; #endregion #region 2d brushes/fonts Brushes = new Dictionary <string, D2D1.Brush>(); Brushes.Add("Red", new D2D1.SolidColorBrush(D2DContext, Color.Red)); Brushes.Add("Green", new D2D1.SolidColorBrush(D2DContext, Color.Green)); Brushes.Add("Blue", new D2D1.SolidColorBrush(D2DContext, Color.Blue)); Brushes.Add("White", new D2D1.SolidColorBrush(D2DContext, Color.White)); Brushes.Add("Black", new D2D1.SolidColorBrush(D2DContext, Color.Black)); Brushes.Add("TransparentWhite", new D2D1.SolidColorBrush(D2DContext, new Color(1, 1, 1, .5f))); Brushes.Add("TransparentBlack", new D2D1.SolidColorBrush(D2DContext, new Color(0, 0, 0, .5f))); Brushes.Add("LightGray", new D2D1.SolidColorBrush(D2DContext, Color.LightGray)); Brushes.Add("OrangeRed", new D2D1.SolidColorBrush(D2DContext, Color.OrangeRed)); Brushes.Add("CornflowerBlue", new D2D1.SolidColorBrush(D2DContext, Color.CornflowerBlue)); Brushes.Add("Yellow", new D2D1.SolidColorBrush(D2DContext, Color.Yellow)); Brushes.Add("Magenta", new D2D1.SolidColorBrush(D2DContext, Color.Magenta)); Brushes.Add("RosyBrown", new D2D1.SolidColorBrush(D2DContext, Color.RosyBrown)); DashStyle = new D2D1.StrokeStyle(D2DFactory, new D2D1.StrokeStyleProperties() { StartCap = D2D1.CapStyle.Flat, DashCap = D2D1.CapStyle.Round, EndCap = D2D1.CapStyle.Flat, DashStyle = D2D1.DashStyle.Custom, DashOffset = 0, LineJoin = D2D1.LineJoin.Round, MiterLimit = 1 }, new float[] { 4f, 4f }); FontFactory = new DWrite.Factory(); SegoeUI24 = new DWrite.TextFormat(FontFactory, "Segoe UI", 24f); SegoeUI14 = new DWrite.TextFormat(FontFactory, "Segoe UI", 14f); Consolas14 = new DWrite.TextFormat(FontFactory, "Consolas", 14f); #endregion #region blend states D3D11.BlendStateDescription opaqueDesc = new D3D11.BlendStateDescription(); opaqueDesc.RenderTarget[0].IsBlendEnabled = false; opaqueDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendStateOpaque = new D3D11.BlendState(Device, opaqueDesc); D3D11.BlendStateDescription alphaDesc = new D3D11.BlendStateDescription(); alphaDesc.RenderTarget[0].IsBlendEnabled = true; alphaDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; alphaDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; alphaDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; alphaDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; alphaDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; alphaDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendStateTransparent = new D3D11.BlendState(Device, alphaDesc); #endregion #region rasterizer states rasterizerStateSolidCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.Back, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeCullBack = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.Back, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateSolidNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.None, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeNoCull = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.None, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateSolidCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Solid, CullMode = D3D11.CullMode.Front, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); rasterizerStateWireframeCullFront = new D3D11.RasterizerState(Device, new D3D11.RasterizerStateDescription() { FillMode = D3D11.FillMode.Wireframe, CullMode = D3D11.CullMode.Front, IsAntialiasedLineEnabled = true, IsDepthClipEnabled = false, IsMultisampleEnabled = true }); #endregion #region depth stencil states depthStencilStateDefault = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthComparison = D3D11.Comparison.Less, DepthWriteMask = D3D11.DepthWriteMask.All }); depthStencilStateNoDepth = new D3D11.DepthStencilState(Device, new D3D11.DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false, DepthComparison = D3D11.Comparison.Less, DepthWriteMask = D3D11.DepthWriteMask.All }); Context.OutputMerger.SetDepthStencilState(depthStencilStateDefault); #endregion #region blank textures D3D11.Texture2D wtex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription() { ArraySize = 1, Width = 1, Height = 1, Format = DXGI.Format.R32G32B32A32_Float, CpuAccessFlags = D3D11.CpuAccessFlags.None, MipLevels = 0, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D11.BindFlags.ShaderResource, OptionFlags = D3D11.ResourceOptionFlags.None }); Context.UpdateSubresource(new Vector4[] { Vector4.One }, wtex); WhiteTextureView = new D3D11.ShaderResourceView(Device, wtex); D3D11.Texture2D btex = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription() { ArraySize = 1, Width = 1, Height = 1, Format = DXGI.Format.R32G32B32A32_Float, CpuAccessFlags = D3D11.CpuAccessFlags.None, MipLevels = 0, Usage = D3D11.ResourceUsage.Default, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D11.BindFlags.ShaderResource, OptionFlags = D3D11.ResourceOptionFlags.None }); Context.UpdateSubresource(new Vector4[] { new Vector4(0, 0, 0, 1) }, btex); BlackTextureView = new D3D11.ShaderResourceView(Device, btex); AnisotropicSampler = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription() { AddressU = D3D11.TextureAddressMode.Wrap, AddressV = D3D11.TextureAddressMode.Wrap, AddressW = D3D11.TextureAddressMode.Wrap, Filter = D3D11.Filter.Anisotropic, }); #endregion #region screen vertex & constants constants = new CameraConstants(); constantBuffer = D3D11.Buffer.Create(Device, D3D11.BindFlags.ConstantBuffer, ref constants); #endregion //swapChain.GetParent<DXGI.Factory>().MakeWindowAssociation(renderForm.Handle, DXGI.WindowAssociationFlags.); Cameras = new List <Camera>(); MainCamera = Camera.CreatePerspective(MathUtil.DegreesToRadians(70), 16 / 9f); ActiveCamera = MainCamera; Cameras.Add(MainCamera); ShadowCamera = Camera.CreateOrthographic(500, 1); ShadowCamera.zNear = 0; ShadowCamera.zFar = 1000; ShadowCamera.CreateResources(Device, 1, 0, 1024, 1024); //Cameras.Add(ShadowCamera); // TODO: Shadow camera has no depth Resize(ResolutionX, ResolutionY); }
public bool Initialize(SystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = SystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter(0); // Get the primary adapter output (monitor). var monitor = adapter.GetOutput(0); // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor). var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); // Now go through all the display modes and find the one that matches the screen width and height. // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled. // Otherwise we use maximum refresh rate. var rational = new Rational(0, 1); if (VerticalSyncEnabled) { foreach (var mode in modes) { if (mode.Width == configuration.Width && mode.Height == configuration.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } // Get the adapter (video card) description. var adapterDescription = adapter.Description; // Store the dedicated video card memory in megabytes. VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; // Convert the name of the video card to a character array and store it. VideoCardDescription = adapterDescription.Description; // Release the adapter output. monitor.Dispose(); // Release the adapter. adapter.Dispose(); // Release the factory. factory.Dispose(); #endregion #region Initialize swap chain and d3d device // Initialize the swap chain description. var swapChainDesc = new SwapChainDescription() { // Set to a single back buffer. BufferCount = 1, // Set the width and height of the back buffer. ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm), // Set the usage of the back buffer. Usage = Usage.RenderTargetOutput, // Set the handle for the window to render to. OutputHandle = windowHandle, // Turn multisampling off. SampleDescription = new SampleDescription(1, 0), // Set to full screen or windowed mode. IsWindowed = !SystemConfiguration.FullScreen, // Don't set the advanced flags. Flags = SwapChainFlags.None, // Discard the back buffer content after presenting. SwapEffect = SwapEffect.Discard }; // Create the swap chain, Direct3D device, and Direct3D device context. Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers // Get the pointer to the back buffer. var backBuffer = Texture2D.FromSwapChain<Texture2D>(SwapChain, 0); // Create the render target view with the back buffer pointer. RenderTargetView = new RenderTargetView(device, backBuffer); // Release pointer to the back buffer as we no longer need it. backBuffer.Dispose(); // Initialize and set up the description of the depth buffer. var depthBufferDesc = new Texture2DDescription() { Width = configuration.Width, Height = configuration.Height, MipLevels = 1, ArraySize = 1, Format = Format.D24_UNorm_S8_UInt, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }; // Create the texture for the depth buffer using the filled out description. DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil // Initialize and set up the description of the stencil state. var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); // Initialize and set up the depth stencil view. var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; // Create the depth stencil view. DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); // Bind the render target view and depth stencil buffer to the output render pipeline. DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State // Setup the raster description which will determine how and what polygon will be drawn. var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the rasterizer state from the description we just filled out. RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(0, 0, configuration.Width, configuration.Height, 0, 1); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4f), ((float)configuration.Width / configuration.Height), SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); // Initialize the world matrix to the identity matrix. WorldMatrix = Matrix.Identity; // Create an orthographic projection matrix for 2D rendering. OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, SystemConfiguration.ScreenNear, SystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. // The difference is that DepthEnable is set to false. // All other parameters are the same as the other depth stencil state. var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, // Stencil operation if pixel front-facing. FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, // Stencil operation if pixel is back-facing. BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; // Create the depth stencil state. DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States // Create an alpha enabled blend state description. var blendStateDesc = new BlendStateDescription(); blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = BlendOption.One; 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; // Create the blend state using the description. AlphaEnableBlendingState = new BlendState(device, blendStateDesc); // Modify the description to create an disabled blend state description. blendStateDesc.RenderTarget[0].IsBlendEnabled = false; // Create the blend state using the description. AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return true; } catch (Exception) { return false; } }
public WavesSimulator(IntPtr hInst) : base(hInst) { //Geometry Related Buffers _ballIB = null; _ballVB = null; _groundVB = null; _groundIB = null; _wavesVB = null; _wavesIB = null; _ballIndexCount = 0; _groundIndexCount = 0; //WVP Matrices _groundWorld = Matrix.Identity; _wavesWorld = Matrix.Translation(0, -2.0f, 0); _ballWorld = Matrix.Translation(-30, 15, 0); _view = Matrix.Identity; _proj = Matrix.Identity; _reflectView = Matrix.Identity; //Rendering Effects Related _fx = null; _fxWVP = null; _tech = null; _fxWorld = null; _fxWIT = null; _fxEyePosW = null; _fxDirLight = null; _fxPointLight = null; _fxSpotLight = null; _fxMaterial = null; _fxDiffuseMap = null; _fxRefractiveMap = null; _fxClipPlane = null; _fxReflectiveMap = null; _fxReflectViewProj = null; _fxUseStructBuf = null; _fxgRefractionPositionMap = null; //Textures and Views refractText = null; refractRenderTargetView = null; refractResourceView = null; reflectRenderTargetView = null; reflectResourceView = null; reflectText = null; positionMapRenderTargetView = null; positionMapResourceView = null; positionMapText = null; _groundMapSRV = null; _groundMap = null; //Input Format _inputLayout = null; //Camera Related _theta = 1.5f * MathF.PI; _phi = 0.1f * MathF.PI; _radius = 200.0f; _lastMousePos = new System.Drawing.Point(0, 0); _eyePosW = new Vector3(); //Shading and Lighting _alphaBlend = null; _dirLight = new DirectionalLight { Ambient = new Color4(0.2f, 0.2f, 0.2f, 1), Diffuse = new Color4(0.5f, 0.5f, 0.5f, 1), Specular = new Color4(0.5f, 0.5f, 0.5f, 1), Direction = new Vector3(0.57735f, -0.57735f, 0.57735f) }; _pointLight = new PointLight { Ambient = new Color4(0.3f, 0.3f, 0.3f, 1), Diffuse = new Color4(0.7f, 0.7f, 0.7f, 1), Specular = new Color4(0.7f, 0.7f, 0.7f, 1), Attenuation = new Vector3(0.1f, 0.1f, 0.1f), Range = 25.0f }; _spotLight = new SpotLight { Ambient = new Color4(0, 0, 0, 0), Diffuse = new Color4(1.0f, 1.0f, 1.0f, 1), Specular = Color.White, Attenuation = new Vector3(1.0f, 0.0f, 0.0f), Spot = 96.0f, Range = 10000.0f }; _landMaterial = new Material { Ambient = new Color4(1f, 1f, 1f, 1.0f), Diffuse = new Color4(1, 1, 1, 1.0f), Specular = new Color4(0.2f, 0.2f, 0.2f, 16.0f), Reflect = new Color4(1.0f, 1f, 1f, 1f) }; _wavesMaterial = new Material { Ambient = new Color4(1, 1, 1, 0.8f), Diffuse = new Color4(0.137f, 0.42f, 0.556f, 1.0f), Specular = new Color4(0.8f, 0.8f, 0.8f, 96.0f), Reflect = new Color4(2f, 1, 1, 1) //R component of Reflect is used for Gama Correction in Effect }; _disposed = false; MainWindowCaption = "Waves Simulator"; }
public void Init(Form form) { ViewportSize = new Size2F(form.Width, form.Height); hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f); ModeDescription backBufferDesc = new ModeDescription(form.Width, form.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 = form.Handle, IsWindowed = true, }; D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain); d3dDeviceContext = d3dDevice.ImmediateContext; d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height); using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0)) { renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer); } D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.RenderTarget[0].IsBlendEnabled = true; blendStateDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendStateDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.One; // blendStateDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.SourceAlpha; //Zero blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha; blendStateDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Maximum; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; blendState = new D3D11.BlendState(d3dDevice, blendStateDesc); Fonts = new Detail.FontCache(this); var layout2d = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0), new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0), }; var layout3d = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0), }; var vertexShaderOutput2d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode2d, "main", "vs_4_0", ShaderFlags.Debug); var vertexShaderOutput3d = ShaderBytecode.Compile(Detail.Shaders.vertexShaderCode3d, "main", "vs_4_0", ShaderFlags.Debug); var pixelShaderOutput = ShaderBytecode.Compile(Detail.Shaders.pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug); Detail.Shaders.VertexShader2D = new D3D11.VertexShader(Device, vertexShaderOutput2d); Detail.Shaders.VertexShader3D = new D3D11.VertexShader(Device, vertexShaderOutput3d); Detail.Shaders.PixelShader = new D3D11.PixelShader(Device, pixelShaderOutput); Detail.Shaders.InputLayout2D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput2d), layout2d); Detail.Shaders.InputLayout3D = new D3D11.InputLayout(Device, ShaderSignature.GetInputSignature(vertexShaderOutput3d), layout3d); IntPtr data = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4); var white = BitConverter.GetBytes(1f); for (int i = 0; i < 4 * 4; i++) { for (int j = 0; j < white.Length; j++) { System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]); } } White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription { Width = 4, Height = 4, ArraySize = 1, BindFlags = D3D11.BindFlags.ShaderResource, Usage = D3D11.ResourceUsage.Dynamic, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Format = Format.R32G32B32A32_Float, MipLevels = 1, OptionFlags = D3D11.ResourceOptionFlags.None, SampleDescription = new DXGI.SampleDescription(1, 0), }, new DataBox[] { new DataBox(data, 4 * 2, 4) }); System.Runtime.InteropServices.Marshal.FreeHGlobal(data); WhiteView = new D3D11.ShaderResourceView(Device, White); samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription() { Filter = D3D11.Filter.MinMagMipLinear, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, BorderColor = new RawColor4(1f, 0f, 1f, 1f), ComparisonFunction = D3D11.Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16 }); transfBuffer = new SharpDX.Direct3D11.Buffer(Device, new D3D11.BufferDescription(sizeof(float) * 4, D3D11.ResourceUsage.Dynamic, D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.Write, D3D11.ResourceOptionFlags.None, sizeof(float))); DataStream stream; DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream); stream.Write(hViewportSize.Width); stream.Write(hViewportSize.Height); DeviceContext.UnmapSubresource(transfBuffer, 0); DeviceContext.VertexShader.SetShader(vertexShader, null, 0); DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer); DeviceContext.PixelShader.SetShader(pixelShader, null, 0); DeviceContext.PixelShader.SetSampler(0, samplerState); DeviceContext.InputAssembler.InputLayout = inputLayout; DeviceContext.OutputMerger.BlendState = blendState; cam = new Camera(this); }
internal void SetBS(BlendState bs, Color4? blendFactor = null) { if (State.m_BS != bs || blendFactor != null) { State.m_BS = bs; Context.OutputMerger.SetBlendState(bs, blendFactor); Stats.SetBlendState++; } }
/// <summary> /// SetupBlendState /// </summary> void SetupBlendState () { var rtbd = new RenderTargetBlendDescription(); bool enabled = true; if ( BlendState.DstAlpha==Blend.Zero && BlendState.SrcAlpha==Blend.One && BlendState.DstColor==Blend.Zero && BlendState.SrcColor==Blend.One ) { enabled = false; } rtbd.IsBlendEnabled = enabled ; rtbd.BlendOperation = Converter.Convert( BlendState.ColorOp ); rtbd.AlphaBlendOperation = Converter.Convert( BlendState.AlphaOp ); rtbd.RenderTargetWriteMask = (ColorWriteMaskFlags)(int)BlendState.WriteMask; rtbd.DestinationBlend = Converter.Convert( BlendState.DstColor ); rtbd.SourceBlend = Converter.Convert( BlendState.SrcColor ); rtbd.DestinationAlphaBlend = Converter.Convert( BlendState.DstAlpha ); rtbd.SourceAlphaBlend = Converter.Convert( BlendState.SrcAlpha ); var bsd = new BlendStateDescription(); bsd.AlphaToCoverageEnable = false; bsd.IndependentBlendEnable = false; bsd.RenderTarget[0] = rtbd; blendFactor = SharpDXHelper.Convert( BlendState.BlendFactor ); blendMsaaMask = BlendState.MultiSampleMask; blendState = new D3DBlendState( device.Device, bsd ); }
private void InitBlendState() { BlendStateDescription _BlendStateDescription = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; _BlendStateDescription.RenderTarget[0].IsBlendEnabled = true; _BlendStateDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; _BlendStateDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; _BlendStateDescription.RenderTarget[0].BlendOperation = BlendOperation.Add; _BlendStateDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One; _BlendStateDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; _BlendStateDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; _BlendStateDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _BlendState = new BlendState(GraphicsAdapter.GraphicsDevice, _BlendStateDescription); }
/// <summary> /// Function to retrieve the D3D state object. /// </summary> /// <param name="stateType">The state type information.</param> /// <returns>The D3D state object.</returns> internal override D3D.DeviceChild GetStateObject(ref GorgonBlendStates stateType) { #if DEBUG #region State Validation Code. if ((stateType.RenderTarget0.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget1.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget2.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget3.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget4.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget5.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget6.AlphaOperation == BlendOperation.Unknown) && (stateType.RenderTarget7.AlphaOperation == BlendOperation.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendOperation.Unknown, "AlphaOperation")); } if ((stateType.RenderTarget0.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget1.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget2.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget3.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget4.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget5.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget6.BlendingOperation == BlendOperation.Unknown) && (stateType.RenderTarget7.BlendingOperation == BlendOperation.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendOperation.Unknown, "BlendingOperation")); } if ((stateType.RenderTarget0.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget1.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget2.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget3.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget4.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget5.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget6.DestinationAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget7.DestinationAlphaBlend == BlendType.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown, "DestinationAlphaBlend")); } if ((stateType.RenderTarget0.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget1.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget2.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget3.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget4.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget5.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget6.DestinationBlend == BlendType.Unknown) && (stateType.RenderTarget7.DestinationBlend == BlendType.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown, "DestinationBlend")); } if ((stateType.RenderTarget0.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget1.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget2.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget3.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget4.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget5.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget6.SourceAlphaBlend == BlendType.Unknown) && (stateType.RenderTarget7.SourceAlphaBlend == BlendType.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown, "SourceAlphaBlend")); } if ((stateType.RenderTarget0.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget1.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget2.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget3.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget4.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget5.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget6.SourceBlend == BlendType.Unknown) && (stateType.RenderTarget7.SourceBlend == BlendType.Unknown)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, BlendType.Unknown, "SourceBlend")); } if ((stateType.RenderTarget0.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget1.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget2.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget3.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget4.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget5.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget6.WriteMask == ColorWriteMaskFlags.None) && (stateType.RenderTarget7.WriteMask == ColorWriteMaskFlags.None)) { throw new GorgonException(GorgonResult.CannotBind, string.Format(Resources.GORGFX_INVALID_ENUM_VALUE, ColorWriteMaskFlags.None, "WriteMask")); } #endregion #endif var desc = new D3D.BlendStateDescription { AlphaToCoverageEnable = stateType.IsAlphaCoverageEnabled, IndependentBlendEnable = stateType.IsIndependentBlendEnabled, }; // Copy render targets. desc.RenderTarget[0] = stateType.RenderTarget0.Convert(); desc.RenderTarget[1] = stateType.RenderTarget1.Convert(); desc.RenderTarget[2] = stateType.RenderTarget2.Convert(); desc.RenderTarget[3] = stateType.RenderTarget3.Convert(); desc.RenderTarget[4] = stateType.RenderTarget4.Convert(); desc.RenderTarget[5] = stateType.RenderTarget5.Convert(); desc.RenderTarget[6] = stateType.RenderTarget6.Convert(); desc.RenderTarget[7] = stateType.RenderTarget7.Convert(); var state = new D3D.BlendState(Graphics.D3DDevice, desc) { DebugName = "Gorgon Blend State #" + StateCacheCount }; return(state); }
/// <summary> /// Creates a ConvolutionEngine instance. /// </summary> /// <param name="device">The graphics device to use.</param> /// <param name="context">The graphics context to use.</param> /// <param name="resolution">The convolution resolution.</param> public ConvolutionEngine(Device device, DeviceContext context, Size resolution) { fft = FastFourierTransform.Create2DComplex(context, resolution.Width, resolution.Height); fft.InverseScale = 1.0f / (float)(resolution.Width * resolution.Height); this.resolution = resolution; FastFourierTransformBufferRequirements bufferReqs = fft.BufferRequirements; precomputed = new FFTBuffer[bufferReqs.PrecomputeBufferCount]; temporaries = new FFTBuffer[bufferReqs.TemporaryBufferCount]; for (int t = 0; t < precomputed.Length; ++t) precomputed[t] = FFTUtils.AllocateBuffer(device, bufferReqs.PrecomputeBufferSizes[t]); for (int t = 0; t < temporaries.Length; ++t) temporaries[t] = FFTUtils.AllocateBuffer(device, bufferReqs.TemporaryBufferSizes[t]); UnorderedAccessView[] precomputedUAV = new UnorderedAccessView[bufferReqs.PrecomputeBufferCount]; for (int t = 0; t < precomputed.Length; ++t) precomputedUAV[t] = precomputed[t].view; UnorderedAccessView[] temporariesUAV = new UnorderedAccessView[bufferReqs.TemporaryBufferCount]; for (int t = 0; t < temporaries.Length; ++t) temporariesUAV[t] = temporaries[t].view; fft.AttachBuffersAndPrecompute(temporariesUAV, precomputedUAV); lBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height); rBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height); tBuf = FFTUtils.AllocateBuffer(device, 2 * resolution.Width * resolution.Height); rConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true); gConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true); bConvolved = new GraphicsResource(device, resolution, Format.R32_Float, true, true); staging = new GraphicsResource(device, new Size(resolution.Width / 2, resolution.Height / 2), Format.R32G32B32A32_Float, true, true); BlendStateDescription description = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; description.RenderTarget[0] = new RenderTargetBlendDescription() { IsBlendEnabled = true, SourceBlend = BlendOption.One, DestinationBlend = BlendOption.One, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.Zero, DestinationAlphaBlend = BlendOption.Zero, AlphaBlendOperation = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.Red | ColorWriteMaskFlags.Green | ColorWriteMaskFlags.Blue, }; blendState = new BlendState(device, description); }
public bool Initialize() { Debug.Assert(!_initialized); #region Shaders string SpriteFX = @"Texture2D SpriteTex; SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = WRAP; AddressV = WRAP; }; struct VertexIn { float3 PosNdc : POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; struct VertexOut { float4 PosNdc : SV_POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; VertexOut VS(VertexIn vin) { VertexOut vout; vout.PosNdc = float4(vin.PosNdc, 1.0f); vout.Tex = vin.Tex; vout.Color = vin.Color; return vout; }; float4 PS(VertexOut pin) : SV_Target { return pin.Color*SpriteTex.Sample(samLinear, pin.Tex); }; technique11 SpriteTech { pass P0 { SetVertexShader( CompileShader( vs_5_0, VS() ) ); SetHullShader( NULL ); SetDomainShader( NULL ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_5_0, PS() ) ); } };"; #endregion _compiledFX = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"); { if (_compiledFX.HasErrors) return false; _effect = new Effect(_device, _compiledFX); { _spriteTech = _effect.GetTechniqueByName("SpriteTech"); _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource(); var pass = _spriteTech.GetPassByIndex(0).Description.Signature; InputElement[] layoutDesc = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, pass, layoutDesc); // Create Vertex Buffer BufferDescription vbd = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _VB = new SharpDX.Direct3D11.Buffer(_device, vbd); // Create and initialise Index Buffer short[] indices = new short[3072]; for (ushort i = 0; i < 512; ++i) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4); indices[i * 6 + 4] = (short)(i * 4 + 2); indices[i * 6 + 5] = (short)(i * 4 + 3); } _indexBuffer = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0])); Marshal.Copy(indices, 0, _indexBuffer, indices.Length); BufferDescription ibd = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _IB = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, ibd); BlendStateDescription transparentDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDesc.RenderTarget[0].IsBlendEnabled = true; transparentDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBS = new BlendState(_device, transparentDesc); } } _initialized = true; return true; }
private void InitializeDeviceResources(DXGI.SwapChain swapChain) { backbufferTexture = swapChain.GetBackBuffer <D3D11.Texture2D>(0); backbufferRTV = new D3D11.RenderTargetView(device, backbufferTexture); width = backbufferTexture.Description.Width; height = backbufferTexture.Description.Height; var depthBufferDesc = new D3D11.Texture2DDescription() { Width = width, Height = height, MipLevels = 1, ArraySize = 1, Format = DXGI.Format.D24_UNorm_S8_UInt, SampleDescription = new DXGI.SampleDescription(1, 0), Usage = D3D11.ResourceUsage.Default, BindFlags = D3D11.BindFlags.DepthStencil, CpuAccessFlags = D3D11.CpuAccessFlags.None, OptionFlags = D3D11.ResourceOptionFlags.None }; using (var depthStencilBufferTexture = new D3D11.Texture2D(device, depthBufferDesc)) { var depthStencilViewDesc = new D3D11.DepthStencilViewDescription() { Format = DXGI.Format.D24_UNorm_S8_UInt, Dimension = D3D11.DepthStencilViewDimension.Texture2D, Texture2D = new D3D11.DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; depthDSV = new D3D11.DepthStencilView(device, depthStencilBufferTexture, depthStencilViewDesc); } var depthStencilDesc = new D3D11.DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = D3D11.DepthWriteMask.All, DepthComparison = D3D11.Comparison.Less, IsStencilEnabled = false, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always }, BackFace = new D3D11.DepthStencilOperationDescription() { FailOperation = D3D11.StencilOperation.Keep, DepthFailOperation = D3D11.StencilOperation.Keep, PassOperation = D3D11.StencilOperation.Keep, Comparison = D3D11.Comparison.Always } }; depthStencilState = new D3D11.DepthStencilState(device, depthStencilDesc); var rasterDesc = new D3D11.RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = D3D11.CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = false, FillMode = D3D11.FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }; /*var blendDesc = new D3D11.BlendStateDescription(); * blendDesc.RenderTarget[0].IsBlendEnabled = true; * blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; * blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; * blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.Zero; * blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; * blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;*/ #if ALPHABLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.InverseSourceAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.Zero; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif #if ADDITIVEBLENDING var blendDesc = new D3D11.BlendStateDescription(); blendDesc.RenderTarget[0].IsBlendEnabled = true; blendDesc.RenderTarget[0].SourceBlend = D3D11.BlendOption.SourceAlpha; blendDesc.RenderTarget[0].DestinationBlend = D3D11.BlendOption.DestinationAlpha; blendDesc.RenderTarget[0].BlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].SourceAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.One; blendDesc.RenderTarget[0].AlphaBlendOperation = D3D11.BlendOperation.Add; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All; #endif // RenderTarget[0].BlendOpSharpDX.Direct3D11.BlendOperation.Add RenderTarget[0].SrcBlendAlphaSharpDX.Direct3D11.BlendOption.One // RenderTarget[0].DestBlendAlphaSharpDX.Direct3D11.BlendOption.Zero RenderTarget[0].BlendOpAlphaSharpDX.Direct3D11.BlendOperation.Add // RenderTarget[0].RenderTargetWriteMaskSharpDX.Direct3D11.ColorWriteMaskFlags.All blendState = new D3D11.BlendState(device, blendDesc); rasterizerState = new D3D11.RasterizerState(device, rasterDesc); }