internal BlendState(GraphicsDevice device, BlendStateDescription blendStateDescription) : base(device) { Description = blendStateDescription; for (int i = 1; i < Description.RenderTargets.Length; ++i) { if (Description.RenderTargets[i].BlendEnable || Description.RenderTargets[i].ColorWriteChannels != ColorWriteChannels.All) throw new NotSupportedException(); } blendEnable = Description.RenderTargets[0].BlendEnable; blendEquationModeColor = ToOpenGL(Description.RenderTargets[0].ColorBlendFunction); blendEquationModeAlpha = ToOpenGL(Description.RenderTargets[0].AlphaBlendFunction); blendFactorSrcColor = ToOpenGL(Description.RenderTargets[0].ColorSourceBlend); blendFactorSrcAlpha = ToOpenGL(Description.RenderTargets[0].AlphaSourceBlend); blendFactorDestColor = (BlendingFactorDest)ToOpenGL(Description.RenderTargets[0].ColorDestinationBlend); blendFactorDestAlpha = (BlendingFactorDest)ToOpenGL(Description.RenderTargets[0].AlphaDestinationBlend); EnabledColors[0] = (Description.RenderTargets[0].ColorWriteChannels & ColorWriteChannels.Red ) != 0; EnabledColors[1] = (Description.RenderTargets[0].ColorWriteChannels & ColorWriteChannels.Green) != 0; EnabledColors[2] = (Description.RenderTargets[0].ColorWriteChannels & ColorWriteChannels.Blue ) != 0; EnabledColors[3] = (Description.RenderTargets[0].ColorWriteChannels & ColorWriteChannels.Alpha) != 0; blendEquationHash = (uint)Description.RenderTargets[0].ColorBlendFunction | ((uint)Description.RenderTargets[0].AlphaBlendFunction << 8); blendFuncHash = (uint)Description.RenderTargets[0].ColorSourceBlend | ((uint)Description.RenderTargets[0].AlphaSourceBlend << 8) | ((uint)Description.RenderTargets[0].ColorDestinationBlend << 16) | ((uint)Description.RenderTargets[0].AlphaDestinationBlend << 24); }
internal unsafe BlendState(BlendStateDescription blendStateDescription, bool hasRenderTarget) { var renderTargets = &blendStateDescription.RenderTarget0; for (int i = 1; i < 8; ++i) { if (renderTargets[i].BlendEnable || renderTargets[i].ColorWriteChannels != ColorWriteChannels.All) throw new NotSupportedException(); } ColorWriteChannels = blendStateDescription.RenderTarget0.ColorWriteChannels; if (!hasRenderTarget) ColorWriteChannels = 0; blendEnable = blendStateDescription.RenderTarget0.BlendEnable; blendEquationModeColor = ToOpenGL(blendStateDescription.RenderTarget0.ColorBlendFunction); blendEquationModeAlpha = ToOpenGL(blendStateDescription.RenderTarget0.AlphaBlendFunction); blendFactorSrcColor = ToOpenGL(blendStateDescription.RenderTarget0.ColorSourceBlend); blendFactorSrcAlpha = ToOpenGL(blendStateDescription.RenderTarget0.AlphaSourceBlend); blendFactorDestColor = (BlendingFactorDest)ToOpenGL(blendStateDescription.RenderTarget0.ColorDestinationBlend); blendFactorDestAlpha = (BlendingFactorDest)ToOpenGL(blendStateDescription.RenderTarget0.AlphaDestinationBlend); blendEquationHash = (uint)blendStateDescription.RenderTarget0.ColorBlendFunction | ((uint)blendStateDescription.RenderTarget0.AlphaBlendFunction << 8); blendFuncHash = (uint)blendStateDescription.RenderTarget0.ColorSourceBlend | ((uint)blendStateDescription.RenderTarget0.AlphaSourceBlend << 8) | ((uint)blendStateDescription.RenderTarget0.ColorDestinationBlend << 16) | ((uint)blendStateDescription.RenderTarget0.AlphaDestinationBlend << 24); }
public void Visit(MaterialGeneratorContext context) { var alpha = Alpha ?? new ComputeFloat(0.5f); var tint = Tint ?? new ComputeColor(Color.White); // Use pre-multiplied alpha to support both additive and alpha blending var blendDesc = new BlendStateDescription(Blend.One, Blend.InverseSourceAlpha); context.Material.HasTransparency = true; context.Parameters.Set(Effect.BlendStateKey, BlendState.NewFake(blendDesc)); var alphaColor = alpha.GenerateShaderSource(context, new MaterialComputeColorKeys(MaterialKeys.DiffuseSpecularAlphaBlendMap, MaterialKeys.DiffuseSpecularAlphaBlendValue, Color.White)); var mixin = new ShaderMixinSource(); mixin.Mixins.Add(new ShaderClassSource("ComputeColorMaterialAlphaBlend")); mixin.AddComposition("color", alphaColor); context.SetStream(MaterialShaderStage.Pixel, AlphaBlendStream.Stream, MaterialStreamType.Float2, mixin); context.SetStream(AlphaBlendColorStream.Stream, tint, MaterialKeys.AlphaBlendColorMap, MaterialKeys.AlphaBlendColorValue, Color.White); if (!context.Tags.Get(HasFinalCallback)) { context.Tags.Set(HasFinalCallback, true); context.AddFinalCallback(MaterialShaderStage.Pixel, AddDiffuseSpecularAlphaBlendColor); } }
/// <summary> /// Initializes a new instance of the <see cref="BlendStateFactory"/> class. /// </summary> /// <param name="device">The device.</param> internal BlendStateFactory(GraphicsDevice device) { var blendDescription = new BlendStateDescription(Blend.One, Blend.Zero); blendDescription.SetDefaults(); Default = BlendState.New(device, blendDescription).DisposeBy(device); Default.Name = "Default"; Additive = BlendState.New(device, new BlendStateDescription(Blend.SourceAlpha, Blend.One)).DisposeBy(device); Additive.Name = "Additive"; AlphaBlend = BlendState.New(device, new BlendStateDescription(Blend.One, Blend.InverseSourceAlpha)).DisposeBy(device); AlphaBlend.Name = "AlphaBlend"; NonPremultiplied = BlendState.New(device, new BlendStateDescription(Blend.SourceAlpha, Blend.InverseSourceAlpha)).DisposeBy(device); NonPremultiplied.Name = "NonPremultiplied"; Opaque = BlendState.New(device, new BlendStateDescription(Blend.One, Blend.Zero)).DisposeBy(device); Opaque.Name = "Opaque"; var colorDisabledDescription = new BlendStateDescription(); colorDisabledDescription.SetDefaults(); colorDisabledDescription.RenderTargets[0].ColorWriteChannels = ColorWriteChannels.None; ColorDisabled = BlendState.New(device, colorDisabledDescription).DisposeBy(device); ColorDisabled.Name = "ColorDisabled"; }
public GrassRendrer(Form1 F) : base(F.Device) { this.P = F; this.CallFrequency = STDCallFrequencys.Always; E3 = new EffectWrapper("Grass_Mesh.fx", D); BlendStateDescription bsd = new BlendStateDescription() { AlphaToCoverageEnable = true, IndependentBlendEnable = false, }; RenderTargetBlendDescription rtbd = new RenderTargetBlendDescription() { BlendEnable = true, BlendOperation = BlendOperation.Add, BlendOperationAlpha = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.All, DestinationBlend = BlendOption.InverseSourceAlpha, SourceBlend = BlendOption.SourceAlpha, SourceBlendAlpha = BlendOption.Zero, DestinationBlendAlpha = BlendOption.One }; bsd.RenderTargets[0] = rtbd; bsd0 = BlendState.FromDescription(D.HadrwareDevice(), bsd); StaticVertex[] vs = new StaticVertex[100]; mBuffer = new DynamicMeshBuffer<StaticVertex>(D, PrimitiveTopology.PointList); mBuffer.Write(vs); }
protected override void InitializeCore() { base.InitializeCore(); sprite3DBatch = new Sprite3DBatch(Context.GraphicsDevice); var blendDesc = new BlendStateDescription(Blend.SourceAlpha, Blend.One) { RenderTarget0 = { BlendEnable = true, ColorBlendFunction = BlendFunction.ReverseSubtract, AlphaBlendFunction = BlendFunction.ReverseSubtract } }; SubBlendState = blendDesc; blendDesc = new BlendStateDescription(Blend.DestinationColor, Blend.InverseSourceAlpha) { RenderTarget0 = { BlendEnable = true, ColorBlendFunction = BlendFunction.Add, AlphaSourceBlend = Blend.Zero, AlphaBlendFunction = BlendFunction.Add } }; MultBlendState = blendDesc; }
private static void SetDefaults(ref BlendStateDescription blendDesc) { for (uint i = 0; i < 8; i++) { blendDesc.SetWriteMask(i, ColorWriteMaskFlags.All); blendDesc.SetBlendEnable(i, true); } }
public BlendStateChangeCommand(RenderTargetBlendDescription bStateDesc) : base(CommandType.BlendStateChange) { CommandAttributes |= CommandAttributes.MonoRendering; Description = bStateDesc; blendStateDescription = new BlendStateDescription(); blendStateDescription.RenderTargets[0] = Description; blendState = BlendState.FromDescription(Game.Context.Device, blendStateDescription); }
/// <summary> /// Clones this instance. /// </summary> /// <returns>A copy of this instance.</returns> /// <remarks> /// Because this structure contains an array, it is not possible to modify it without making an explicit clone method. /// </remarks> public BlendStateDescription Clone() { var description = new BlendStateDescription {AlphaToCoverageEnable = AlphaToCoverageEnable, IndependentBlendEnable = IndependentBlendEnable}; var sourceRenderTargets = RenderTarget; var destRenderTargets = description.RenderTarget; for (int i = 0; i < sourceRenderTargets.Length; i++) destRenderTargets[i] = sourceRenderTargets[i]; return description; }
/// <summary> /// Initializes a new instance of the <see cref="BlendState"/> class. /// </summary> /// <param name="device">The device.</param> /// <param name="name">The name.</param> /// <param name="blendStateDescription">The blend state description.</param> internal BlendState(GraphicsDevice device, BlendStateDescription blendStateDescription) : base(device) { BlendFactor = SiliconStudio.Core.Mathematics.Color4.White; MultiSampleMask = -1; Description = blendStateDescription; CreateNativeDeviceChild(); }
static BlendStates() { var blendDescription = new BlendStateDescription(Blend.One, Blend.Zero); blendDescription.SetDefaults(); Default = blendDescription; var colorDisabledDescription = new BlendStateDescription(); colorDisabledDescription.SetDefaults(); colorDisabledDescription.RenderTarget0.ColorWriteChannels = ColorWriteChannels.None; ColorDisabled = colorDisabledDescription; }
public void SetDefaultBlend() { this.Blend = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, //RenderTargets //RenderTargets = this.SetDefaultRenderBlend() }; this.Blend.RenderTargets[0] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[1] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[2] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[3] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[4] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[5] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[6] = this.SetDefaultRenderBlend(); this.Blend.RenderTargets[7] = this.SetDefaultRenderBlend(); }
public override void VisitFeature(MaterialGeneratorContext context) { var alpha = Alpha ?? new ComputeFloat(1f); var tint = Tint ?? new ComputeColor(Color.White); // Use pre-multiplied alpha to support both additive and alpha blending var blendDesc = new BlendStateDescription(Blend.One, Blend.InverseSourceAlpha); context.Material.HasTransparency = true; context.Parameters.Set(Effect.BlendStateKey, BlendState.NewFake(blendDesc)); context.SetStream(AlphaBlendStream.Stream, alpha, MaterialKeys.DiffuseSpecularAlphaBlendMap, MaterialKeys.DiffuseSpecularAlphaBlendValue, Color.White); context.SetStream(AlphaBlendColorStream.Stream, tint, MaterialKeys.AlphaBlendColorMap, MaterialKeys.AlphaBlendColorValue, Color.White); if (!context.Tags.Get(HasFinalCallback)) { context.Tags.Set(HasFinalCallback, true); context.AddFinalCallback(MaterialShaderStage.Pixel, AddDiffuseSpecularAlphaBlendColor); } }
public static BlendStateDescription BlendDefault() { BlendStateDescription bsDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; bsDesc.RenderTargets[0] = new RenderTargetBlendDescription() { BlendEnable = false, SourceBlend = BlendOption.One, DestinationBlend = BlendOption.Zero, BlendOperation = BlendOperation.Add, SourceBlendAlpha = BlendOption.One, DestinationBlendAlpha = BlendOption.Zero, BlendOperationAlpha = BlendOperation.Add, RenderTargetWriteMask = ColorWriteMaskFlags.All, }; return bsDesc; }
/// <summary> /// Initializes device dependant resources. /// </summary> private void Initialize() { var device = m_directCanvasFactory.DeviceContext.Device; /* Here we create a new sampler for sampling input within * our pixel shader */ var sampDesc = new SamplerDescription(); sampDesc.AddressU = TextureAddressMode.Clamp; sampDesc.AddressV = TextureAddressMode.Clamp; sampDesc.AddressW = TextureAddressMode.Clamp; sampDesc.BorderColor = new Color4(0, 0, 0, 0).InternalColor4; sampDesc.ComparisonFunction = Comparison.Never; sampDesc.Filter = Filter.MinMagMipLinear; sampDesc.MaximumAnisotropy = 10; sampDesc.MaximumLod = float.MaxValue; sampDesc.MinimumLod = 0; sampDesc.MipLodBias = 0; m_linearSamplerState = SamplerState.FromDescription(device, sampDesc); sampDesc.Filter = Filter.MinMagMipPoint; m_pointSamplerState = SamplerState.FromDescription(device, sampDesc); /* Here we have a hard coded blend state. This should be configurable in * the future. Like the composer has */ var blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.DestinationBlend = BlendOption.InverseSourceAlpha; blendDesc.DestinationAlphaBlend = BlendOption.One; blendDesc.SourceBlend = BlendOption.One; blendDesc.SourceAlphaBlend = BlendOption.One; for (uint i = 0; i < 8; i++) { blendDesc.SetWriteMask(i, ColorWriteMaskFlags.All); blendDesc.SetBlendEnable(i, true); } m_alphaBlendState = BlendState.FromDescription(device, blendDesc); }
protected override void OnResourceLoad() { CreatePrimaryRenderTarget(); CreateDepthBuffer(); var dssd = new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; var solidParentOp = new BlendStateDescription(); solidParentOp.SetBlendEnable( 0, false ); solidParentOp.SetWriteMask( 0, ColorWriteMaskFlags.All ); var transParentOp = new BlendStateDescription { AlphaBlendOperation = BlendOperation.Add, BlendOperation = BlendOperation.Add, DestinationAlphaBlend = BlendOption.Zero, DestinationBlend = BlendOption.One, IsAlphaToCoverageEnabled = false, SourceAlphaBlend = BlendOption.Zero, SourceBlend = BlendOption.One, }; transParentOp.SetBlendEnable( 0, true ); transParentOp.SetWriteMask( 0, ColorWriteMaskFlags.All ); transBlendState = BlendState.FromDescription( Context10.Device, transParentOp ); solidBlendState = BlendState.FromDescription( Context10.Device, solidParentOp ); depthStencilState = DepthStencilState.FromDescription( Context10.Device, dssd ); jupiterMesh = new SimpleModel( Context10.Device, "SimpleModel10.fx", "jupiter.SMD", "jupiter.jpg" ); view = Matrix.LookAtLH( new Vector3( 0, 160, 0 ), new Vector3( 0, -128.0f, 0 ), -Vector3.UnitZ ); jupiterMesh.Effect.GetVariableByName( "view" ).AsMatrix().SetMatrix( view ); proj = Matrix.PerspectiveFovLH( 45.0f, WindowWidth / (float)WindowHeight, 1.0f, 1000.0f ); jupiterMesh.Effect.GetVariableByName( "proj" ).AsMatrix().SetMatrix( proj ); }
protected override void InitializeCore() { base.InitializeCore(); sprite3DBatch = new Sprite3DBatch(Context.GraphicsDevice); var blendDesc = new BlendStateDescription(Blend.SourceAlpha, Blend.One); blendDesc.RenderTargets[0].BlendEnable = true; blendDesc.RenderTargets[0].ColorBlendFunction = BlendFunction.ReverseSubtract; blendDesc.RenderTargets[0].AlphaBlendFunction = BlendFunction.ReverseSubtract; SubBlendState = BlendState.New(Context.GraphicsDevice, blendDesc).DisposeBy(Context.GraphicsDevice); SubBlendState.Name = "Subtraction"; blendDesc = new BlendStateDescription(Blend.DestinationColor, Blend.InverseSourceAlpha); blendDesc.RenderTargets[0].BlendEnable = true; blendDesc.RenderTargets[0].ColorBlendFunction = BlendFunction.Add; blendDesc.RenderTargets[0].AlphaSourceBlend = Blend.Zero; blendDesc.RenderTargets[0].AlphaBlendFunction = BlendFunction.Add; MultBlendState = BlendState.New(Context.GraphicsDevice, blendDesc).DisposeBy(Context.GraphicsDevice); MultBlendState.Name = "Multiplication"; }
/// <summary> /// Returns default values for <see cref="BlendStateDescription"/>. /// </summary> /// <remarks> /// See MSDN documentation for default values. /// </remarks> public static BlendStateDescription Default() { var description = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; var renderTargets = description.RenderTarget; for (int i = 0; i < renderTargets.Length; i++) { renderTargets[i].IsBlendEnabled = false; renderTargets[i].SourceBlend = BlendOption.One; renderTargets[i].DestinationBlend = BlendOption.Zero; renderTargets[i].BlendOperation = BlendOperation.Add; renderTargets[i].SourceAlphaBlend = BlendOption.One; renderTargets[i].DestinationAlphaBlend = BlendOption.Zero; renderTargets[i].AlphaBlendOperation = BlendOperation.Add; renderTargets[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; } return description; }
/// <summary> /// Initializes a new instance of the <see cref="BlendState"/> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="blendStateDescription">The blend state description.</param> public static BlendState New(GraphicsDevice graphicsDevice, BlendStateDescription blendStateDescription) { BlendState blendState; lock (graphicsDevice.CachedBlendStates) { if (graphicsDevice.CachedBlendStates.TryGetValue(blendStateDescription, out blendState)) { // TODO: Appropriate destroy blendState.AddReferenceInternal(); } else { // Make a local copy of the render targets (ideally, should be ImmutableArray) var renderTargets = blendStateDescription.RenderTargets; blendStateDescription.RenderTargets = new BlendStateRenderTargetDescription[renderTargets.Length]; for (int i = 0; i < renderTargets.Length; ++i) blendStateDescription.RenderTargets[i] = renderTargets[i]; blendState = new BlendState(graphicsDevice, blendStateDescription); graphicsDevice.CachedBlendStates.Add(blendStateDescription, blendState); } } return blendState; }
public void SetDefaultstate() { // shader pipeline m_D3dDevice.ImmediateContext.InputAssembler.InputLayout = null; m_D3dDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; m_D3dDevice.ImmediateContext.VertexShader.Set(null); m_D3dDevice.ImmediateContext.HullShader.Set(null); m_D3dDevice.ImmediateContext.DomainShader.Set(null); m_D3dDevice.ImmediateContext.GeometryShader.Set(null); m_D3dDevice.ImmediateContext.PixelShader.Set(null); // render state m_D3dDevice.ImmediateContext.Rasterizer.State = RasterizerState.FromDescription(m_D3dDevice, new RasterizerStateDescription() { CullMode = CullMode.Back, FillMode = FillMode.Solid, }); m_D3dDevice.ImmediateContext.OutputMerger.DepthStencilState = DepthStencilState.FromDescription(m_D3dDevice, new DepthStencilStateDescription() { DepthComparison = Comparison.Less, DepthWriteMask = DepthWriteMask.All, IsDepthEnabled = true, IsStencilEnabled = false }); var blendState = new RenderTargetBlendDescription() { BlendEnable = false, BlendOperation = BlendOperation.Add, DestinationBlend = BlendOption.InverseSourceAlpha, SourceBlend = BlendOption.SourceAlpha, RenderTargetWriteMask = ColorWriteMaskFlags.All }; var blendStateDesc = new BlendStateDescription(); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.IndependentBlendEnable = false; blendStateDesc.RenderTargets[0] = blendState; m_D3dDevice.ImmediateContext.OutputMerger.BlendState = BlendState.FromDescription(m_D3dDevice, blendStateDesc); }
// One ModelMeshPart for each unique shader in a W3D_CHUNK_MATERIAL_PASS. private ModelMeshPart CreateModelMeshPart( ContentManager contentManager, uint startIndex, uint indexCount, W3dMesh w3dMesh, FixedFunction.VertexMaterial[] vertexMaterials, FixedFunction.ShadingConfiguration[] shadingConfigurations, uint vertexMaterialID, uint shaderID, uint numTextureStages, uint?textureIndex0, uint?textureIndex1) { var w3dShader = w3dMesh.Shaders[shaderID]; var rasterizerState = RasterizerStateDescriptionUtility.DefaultFrontIsCounterClockwise; rasterizerState.CullMode = w3dMesh.Header.Attributes.HasFlag(W3dMeshFlags.TwoSided) ? FaceCullMode.None : FaceCullMode.Back; var depthState = DepthStencilStateDescription.DepthOnlyLessEqual; depthState.DepthWriteEnabled = w3dShader.DepthMask == W3dShaderDepthMask.WriteEnable; depthState.DepthComparison = w3dShader.DepthCompare.ToComparison(); var blendState = new BlendStateDescription( RgbaFloat.White, new BlendAttachmentDescription( w3dShader.SrcBlend != W3dShaderSrcBlendFunc.One || w3dShader.DestBlend != W3dShaderDestBlendFunc.Zero, w3dShader.SrcBlend.ToBlend(), w3dShader.DestBlend.ToBlend(false), BlendFunction.Add, w3dShader.SrcBlend.ToBlend(), w3dShader.DestBlend.ToBlend(true), BlendFunction.Add)); var effectMaterial = new FixedFunctionMaterial(contentManager, contentManager.EffectLibrary.FixedFunction) { PipelineState = new EffectPipelineState( rasterizerState, depthState, blendState, RenderPipeline.GameOutputDescription) }; var materialConstantsBuffer = AddDisposable(contentManager.GraphicsDevice.CreateStaticBuffer( new FixedFunction.MaterialConstantsType { Material = vertexMaterials[vertexMaterialID], Shading = shadingConfigurations[shaderID], NumTextureStages = numTextureStages }, BufferUsage.UniformBuffer)); effectMaterial.SetMaterialConstants(materialConstantsBuffer); effectMaterial.SetTexture0(CreateTexture(contentManager, w3dMesh, textureIndex0)); effectMaterial.SetTexture1(CreateTexture(contentManager, w3dMesh, textureIndex1)); return(new ModelMeshPart( startIndex, indexCount, effectMaterial)); }
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(TextureLoader.ShaderResourceViewFromFile(device, "Particle.png"))); particleTextureSRVs.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, "Snowflake.png"))); particleTextureSRVs.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, "Square.png"))); activeParticleTextureIndex = 0; // Reinitialize particles if > 0 if (this.Constants.MaxParticles > 0) { InitializeParticles(this.Constants.MaxParticles, this.Constants.MaxLifetime); } }
/// <summary> /// Draws a fullscreen texture using a <see cref="SamplerStateFactory.LinearClamp"/> sampler /// and the texture color multiplied by a custom color. See <see cref="Draw+a+texture"/> to learn how to use it. /// </summary> /// <param name="texture">The texture. Expecting an instance of <see cref="Texture"/>.</param> /// <param name="color">The color.</param> /// <param name="applyEffectStates">The flag to apply effect states.</param> public static void DrawTexture(this GraphicsContext graphicsContext, Texture texture, Color4 color, BlendStateDescription? blendState = null) { graphicsContext.DrawTexture(texture, null, color, blendState); }
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)); } }
private void LoadAssets() { DescriptorRange[] ranges = new DescriptorRange[] { new DescriptorRange() { RangeType = DescriptorRangeType.ConstantBufferView, BaseShaderRegister = 0, OffsetInDescriptorsFromTableStart = int.MinValue, DescriptorCount = 1 } }; RootParameter parameter = new RootParameter(ShaderVisibility.Vertex, ranges); // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, new RootParameter[] { parameter }); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); constantBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(1024 * 64), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = constantBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <ConstantBuffer>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, constantBufferViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. constantBufferPointer = constantBuffer.Map(0); Utilities.Write(constantBufferPointer, ref constantBufferData); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); }
/// <summary> /// Compute the parameters and store them in the material. /// </summary> /// <param name="log">The logger.</param> /// <returns>A boolean stating that the parameters were incorrectly created.</returns> public bool CreateParameterCollectionData(Logger log = null) { Parameters.Clear(); var hasErrors = false; var materialShaderCreator = new MaterialTreeShaderCreator(Material); var shaders = materialShaderCreator.GenerateModelShaders(); if (log != null) { (materialShaderCreator.Logger).CopyTo(log); } foreach (var keyValue in Material.Parameters) { // NOTE: cheap way to activate alpha blending Parameters.Set(keyValue.Key, keyValue.Value); if (keyValue.Key == MaterialParameters.UseTransparent && Material.GetParameter(MaterialParameters.UseTransparent)) { // using non premultiply alpha blending var blendStateDescr = new BlendStateDescription(Blend.SourceAlpha, Blend.InverseSourceAlpha); var blendState = new FakeBlendState(blendStateDescr); Parameters.Set(SiliconStudio.Paradox.Graphics.Effect.BlendStateKey, ContentReference.Create((BlendState)blendState)); // disable face culling // TODO: make this programmable var rasterizerStateDescr = new RasterizerStateDescription(CullMode.None); var rasterizerState = new FakeRasterizerState(rasterizerStateDescr); Parameters.Set(SiliconStudio.Paradox.Graphics.Effect.RasterizerStateKey, ContentReference.Create((RasterizerState)rasterizerState)); // disable depth write var depthStencilStateDescr = new DepthStencilStateDescription(true, false); var depthStencilState = new FakeDepthStencilState(depthStencilStateDescr); Parameters.Set(SiliconStudio.Paradox.Graphics.Effect.DepthStencilStateKey, ContentReference.Create((DepthStencilState)depthStencilState)); } else if (keyValue.Key == MaterialParameters.UseTransparentMask && Material.GetParameter(MaterialParameters.UseTransparentMask)) { // disable face culling // TODO: make this programmable var rasterizerStateDescr = new RasterizerStateDescription(CullMode.None); var rasterizerState = new FakeRasterizerState(rasterizerStateDescr); Parameters.Set(SiliconStudio.Paradox.Graphics.Effect.RasterizerStateKey, ContentReference.Create((RasterizerState)rasterizerState)); // enable depth write var depthStencilStateDescr = new DepthStencilStateDescription(true, true); var depthStencilState = new FakeDepthStencilState(depthStencilStateDescr); Parameters.Set(SiliconStudio.Paradox.Graphics.Effect.DepthStencilStateKey, ContentReference.Create((DepthStencilState)depthStencilState)); } } var textureVisitor = new MaterialTextureVisitor(Material); var allTextures = textureVisitor.GetAllModelTextureValuesWithGenerics(); foreach (var texture in allTextures) { if (texture.TextureReference == null || (texture.TextureReference.Id == Guid.Empty && String.IsNullOrEmpty(texture.TextureReference.Location))) { if (log != null) { log.Error("[Material] Material {0} is missing a texture", materialUrl); } hasErrors = true; } else { Parameters.Set(texture.UsedParameterKey, new ContentReference <Graphics.Texture>(texture.TextureReference.Id, texture.TextureReference.Location)); AddSampler(texture.Sampler); } } var allSamplers = textureVisitor.GetAllSamplerValues(); foreach (var sampler in allSamplers) { AddSampler(sampler); } var parameterVisitor = new MaterialParametersVisitor(Material); var parameters = parameterVisitor.GetParameters(); foreach (var keyValue in parameters) { // The code is separated from the previous code since the key is not generated the same way. if (keyValue.Value is MaterialTextureNode) { var textureNode = (MaterialTextureNode)keyValue.Value; if (textureNode != null) { if (textureNode.TextureReference == null || textureNode.TextureReference.Id == Guid.Empty || String.IsNullOrEmpty(textureNode.TextureReference.Location)) { if (log != null) { log.Error("[Material] Material {0} is missing a texture", materialUrl); } hasErrors = true; } else { Parameters.Set(keyValue.Key, new ContentReference <Graphics.Texture>(textureNode.TextureReference.Id, textureNode.TextureReference.Location)); } } } else if (keyValue.Value is NodeParameterSampler) { var sampler = (NodeParameterSampler)keyValue.Value; if (sampler.SamplerParameterKey == null && keyValue.Key is ParameterKey <SamplerState> ) { sampler.SamplerParameterKey = (ParameterKey <SamplerState>)keyValue.Key; } AddSampler(sampler); } else { Parameters.Set(keyValue.Key, keyValue.Value); } } // NOTE: this can set the shader uniforms and potentially override what was in Material.SharedParameters foreach (var keyValue in shaders) { if (log != null && (keyValue.Key == MaterialParameters.BumpMap || keyValue.Key == MaterialParameters.EmissiveMap || keyValue.Key == MaterialParameters.ReflectionMap)) { log.Warning("[Material] Material {0} contains the key {1} which is not yet handled by the engine.", materialUrl, keyValue.Key); } Parameters.Set(keyValue.Key, keyValue.Value); } return(hasErrors); }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration // Store the vsync setting. VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; // Create a DirectX graphics interface factory. var factory = new Factory1(); // Use the factory to create an adapter for the primary graphics interface (video card). var adapter = factory.GetAdapter1(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.Trim('\0'); // 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) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, // 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 = !DSystemConfiguration.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. SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.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); // Set the depth stencil state. DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); #endregion #region Initialize Output Merger // 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); // Now set the rasterizer state. DeviceContext.Rasterizer.State = RasterState; // Setup a raster description which turns off back face culling. var rasterNoCullDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = .0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsFrontCounterClockwise = false, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; // Create the no culling rasterizer state. RasterStateNoCulling = new RasterizerState(Device, rasterNoCullDesc); #endregion #region Initialize Rasterizer ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); // Setup and create the viewport for rendering. DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices // Setup and create the projection matrix. ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.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, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. Added in Tutorial 11 // 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); } }
/// <summary> /// <p>Create a blend-state object that encapsulates blend state for the output-merger stage.</p> /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="description"><dd> <p>Pointer to a blend-state description (see <strong><see cref="SharpDX.Direct3D11.BlendStateDescription" /></strong>).</p> </dd></param> /// <param name="mask">The mask.</param> /// <returns>A new <see cref="BlendState"/> instance.</returns> /// <msdn-id>ff476500</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateBlendState([In] const D3D11_BLEND_DESC* pBlendStateDesc,[Out, Fast] ID3D11BlendState** ppBlendState)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateBlendState</unmanaged-short> /// <remarks><p>An application can create up to 4096 unique blend-state objects. For each object created, the runtime checks to see if a previous object has the same state. If such a previous object exists, the runtime will return a reference to previous instance instead of creating a duplicate object.</p></remarks> public static BlendState New(GraphicsDevice device, BlendStateDescription description, int mask = -1) { return(new BlendState(device, description, Color.White, mask)); }
/// <summary> /// <p>Create a blend-state object that encapsulates blend state for the output-merger stage.</p> /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="description"><dd> <p>Pointer to a blend-state description (see <strong><see cref="SharpDX.Direct3D11.BlendStateDescription" /></strong>).</p> </dd></param> /// <param name="blendFactor">The blend factor.</param> /// <param name="mask">The mask.</param> /// <returns>A new <see cref="BlendState"/> instance.</returns> /// <msdn-id>ff476500</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateBlendState([In] const D3D11_BLEND_DESC* pBlendStateDesc,[Out, Fast] ID3D11BlendState** ppBlendState)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateBlendState</unmanaged-short> /// <remarks><p>An application can create up to 4096 unique blend-state objects. For each object created, the runtime checks to see if a previous object has the same state. If such a previous object exists, the runtime will return a reference to previous instance instead of creating a duplicate object.</p></remarks> public static BlendState New(GraphicsDevice device, BlendStateDescription description, Color4 blendFactor, int mask = -1) { return(new BlendState(device, description, blendFactor, mask)); }
public void Update(IPluginIO pin, DX11RenderContext context) { Device device = context.Device; DeviceContext ctx = context.CurrentDeviceContext; if (!this.deviceshaderdata.ContainsKey(context)) { this.deviceshaderdata.Add(context, new DX11ShaderData(context)); this.deviceshaderdata[context].SetEffect(this.FShader); } DX11ShaderData shaderdata = this.deviceshaderdata[context]; if (this.shaderupdated) { shaderdata.SetEffect(this.FShader); this.shaderupdated = false; } context.RenderStateStack.Push(new DX11RenderState()); this.OnBeginQuery(context); //Clear shader stages shaderdata.ResetShaderStages(ctx); context.Primitives.ApplyFullTriVS(); foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> rt in this.lastframetargets) { rt.UnLock(); } this.lastframetargets.Clear(); DX11ObjectRenderSettings or = new DX11ObjectRenderSettings(); int wi, he; bool preserve = false; DX11ResourcePoolEntry <DX11RenderTarget2D> preservedtarget = null; for (int i = 0; i < this.spmax; i++) { int passcounter = 0; if (this.FInEnabled[i]) { List <DX11ResourcePoolEntry <DX11RenderTarget2D> > locktargets = new List <DX11ResourcePoolEntry <DX11RenderTarget2D> >(); #region Manage size DX11Texture2D initial; if (this.FIn.PluginIO.IsConnected) { if (this.FInUseDefaultSize[0]) { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[0].X; he = (int)this.FInSize[0].Y; } else { initial = this.FIn[i][context]; if (initial != null) { wi = initial.Width; he = initial.Height; } else { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[0].X; he = (int)this.FInSize[0].Y; } } } else { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[0].X; he = (int)this.FInSize[0].Y; } #endregion DX11RenderSettings r = new DX11RenderSettings(); r.RenderWidth = wi; r.RenderHeight = he; if (this.FInSemantics.PluginIO.IsConnected) { r.CustomSemantics.AddRange(this.FInSemantics.ToArray()); } if (this.FInResSemantics.PluginIO.IsConnected) { r.ResourceSemantics.AddRange(this.FInResSemantics.ToArray()); } this.varmanager.SetGlobalSettings(shaderdata.ShaderInstance, r); this.varmanager.ApplyGlobal(shaderdata.ShaderInstance); DX11Texture2D lastrt = initial; DX11ResourcePoolEntry <DX11RenderTarget2D> lasttmp = null; List <DX11Texture2D> rtlist = new List <DX11Texture2D>(); //Bind Initial (once only is ok) this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "INITIAL", initial); //Go trough all passes EffectTechnique tech = shaderdata.ShaderInstance.Effect.GetTechniqueByIndex(tid); for (int j = 0; j < tech.Description.PassCount; j++) { ImageShaderPass pi = this.varmanager.passes[j]; EffectPass pass = tech.GetPassByIndex(j); if (passcounter > 0) { int pid = j - 1; string pname = "PASSRESULT" + pid; this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, pname, rtlist[pid]); } Format fmt = initial.Format; if (pi.CustomFormat) { fmt = pi.Format; } bool mips = pi.Mips; int w, h; if (j == 0) { h = he; w = wi; } else { h = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? he : lastrt.Height; w = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? wi : lastrt.Width; } if (pi.DoScale) { h = Convert.ToInt32((float)h * pi.Scale); w = Convert.ToInt32((float)w * pi.Scale); h = Math.Max(h, 1); w = Math.Max(w, 1); } //Check format support for render target, and default to rgb8 if not if (!context.IsSupported(FormatSupport.RenderTarget, fmt)) { fmt = Format.R8G8B8A8_UNorm; } //Since device is not capable of telling us BGR not supported if (fmt == Format.B8G8R8A8_UNorm) { fmt = Format.R8G8B8A8_UNorm; } DX11ResourcePoolEntry <DX11RenderTarget2D> elem; if (preservedtarget != null) { elem = preservedtarget; } else { elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0); locktargets.Add(elem); } DX11RenderTarget2D rt = elem.Element; if (this.FDepthIn.PluginIO.IsConnected && pi.UseDepth) { context.RenderTargetStack.Push(this.FDepthIn[0][context], true, elem.Element); } else { context.RenderTargetStack.Push(elem.Element); } if (pi.Clear) { elem.Element.Clear(new Color4(0, 0, 0, 0)); } #region Check for depth/blend preset bool validdepth = false; bool validblend = false; DepthStencilStateDescription ds = new DepthStencilStateDescription(); BlendStateDescription bs = new BlendStateDescription(); if (pi.DepthPreset != "") { try { ds = DX11DepthStencilStates.Instance.GetState(pi.DepthPreset); validdepth = true; } catch { } } if (pi.BlendPreset != "") { try { bs = DX11BlendStates.Instance.GetState(pi.BlendPreset); validblend = true; } catch { } } #endregion if (validdepth || validblend) { DX11RenderState state = new DX11RenderState(); if (validdepth) { state.DepthStencil = ds; } if (validblend) { state.Blend = bs; } context.RenderStateStack.Push(state); } r.RenderWidth = w; r.RenderHeight = h; r.BackBuffer = elem.Element; this.varmanager.ApplyGlobal(shaderdata.ShaderInstance); //Apply settings (note that textures swap is handled later) this.varmanager.ApplyPerObject(context, shaderdata.ShaderInstance, or, i); //Bind last render target this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "PREVIOUS", lastrt); this.BindPassIndexSemantic(shaderdata.ShaderInstance.Effect, "PASSINDEX", j); if (this.FDepthIn.PluginIO.IsConnected) { if (this.FDepthIn[0].Contains(context)) { this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "DEPTHTEXTURE", this.FDepthIn[0][context]); } } //Apply pass and draw quad pass.Apply(ctx); if (pi.ComputeData.Enabled) { pi.ComputeData.Dispatch(context, w, h); context.CleanUpCS(); } else { ctx.ComputeShader.Set(null); context.Primitives.FullScreenTriangle.Draw(); ctx.OutputMerger.SetTargets(this.nullrtvs); } //Generate mips if applicable if (pi.Mips) { ctx.GenerateMips(rt.SRV); } if (!pi.KeepTarget) { preserve = false; rtlist.Add(rt); lastrt = rt; lasttmp = elem; preservedtarget = null; passcounter++; } else { preserve = true; preservedtarget = elem; } context.RenderTargetStack.Pop(); if (validblend || validdepth) { context.RenderStateStack.Pop(); } if (pi.HasState) { context.RenderStateStack.Apply(); } } //Set last render target this.FOut[i][context] = lastrt; //Unlock all resources foreach (DX11ResourcePoolEntry <DX11RenderTarget2D> lt in locktargets) { lt.UnLock(); } //Keep lock on last rt, since don't want it overidden lasttmp.Lock(); //this.lastframetargets. //this.lasttarget = lasttmp; this.lastframetargets.Add(lasttmp); //previousrts[context] = lasttmp.Element; } else { this.FOut[i][context] = this.FIn[i][context]; } } context.RenderStateStack.Pop(); this.OnEndQuery(context); //UnLock previous frame in applicable //if (previoustarget != null) { context.ResourcePool.Unlock(previoustarget); } }
private static void CreateBlendStatesCollection() { BlendStateDescription BlendDescr; //Blender.Enabled BlendDescr = new BlendStateDescription(); BlendDescr.IndependentBlendEnable = false; BlendDescr.AlphaToCoverageEnable = false; for (int i = 0; i < 8; i++) { BlendDescr.RenderTarget[i].IsBlendEnabled = true; BlendDescr.RenderTarget[i].SourceBlend = BlendOption.SourceAlpha; BlendDescr.RenderTarget[i].DestinationBlend = BlendOption.InverseSourceAlpha; BlendDescr.RenderTarget[i].BlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].SourceAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].DestinationAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].AlphaBlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; } Blenders.Enabled = RenderStatesRepo.AddBlendStates(BlendDescr); //Blender.Disabled BlendDescr = new BlendStateDescription(); BlendDescr.IndependentBlendEnable = false; BlendDescr.AlphaToCoverageEnable = false; for (int i = 0; i < 8; i++) { BlendDescr.RenderTarget[i].IsBlendEnabled = false; BlendDescr.RenderTarget[i].SourceBlend = BlendOption.SourceAlpha; BlendDescr.RenderTarget[i].DestinationBlend = BlendOption.InverseSourceAlpha; BlendDescr.RenderTarget[i].BlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].SourceAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].DestinationAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].AlphaBlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; } Blenders.Disabled = RenderStatesRepo.AddBlendStates(BlendDescr); //Blender.Sprite BlendDescr = new BlendStateDescription(); BlendDescr.IndependentBlendEnable = false; BlendDescr.AlphaToCoverageEnable = false; for (int i = 0; i < 8; i++) { BlendDescr.RenderTarget[i].IsBlendEnabled = true; BlendDescr.RenderTarget[i].BlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].AlphaBlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].DestinationBlend = BlendOption.InverseSourceAlpha; BlendDescr.RenderTarget[i].DestinationAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].SourceBlend = BlendOption.One; BlendDescr.RenderTarget[i].SourceAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; } Blenders.Sprite = RenderStatesRepo.AddBlendStates(BlendDescr); //Blender.AlphaToCoverage BlendDescr = new BlendStateDescription(); BlendDescr.IndependentBlendEnable = false; BlendDescr.AlphaToCoverageEnable = true; for (int i = 0; i < 8; i++) { BlendDescr.RenderTarget[i].IsBlendEnabled = false; BlendDescr.RenderTarget[i].SourceBlend = BlendOption.SourceAlpha; BlendDescr.RenderTarget[i].DestinationBlend = BlendOption.InverseSourceAlpha; BlendDescr.RenderTarget[i].BlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].SourceAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].DestinationAlphaBlend = BlendOption.One; BlendDescr.RenderTarget[i].AlphaBlendOperation = BlendOperation.Add; BlendDescr.RenderTarget[i].RenderTargetWriteMask = ColorWriteMaskFlags.All; } Blenders.AlphaToCoverage = RenderStatesRepo.AddBlendStates(BlendDescr); }
public bool Init(IntPtr WindowHandle) { var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); var rational = new Rational(0, 1); if (ToolkitSettings.VSync) { foreach (var mode in modes) { if (mode.Width == ToolkitSettings.Width && mode.Height == ToolkitSettings.Height) { rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator); break; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = adapterDescription.Description.Trim('\0'); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); var swapChainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(ToolkitSettings.Width, ToolkitSettings.Height, rational, Format.R8G8B8A8_UNorm), Usage = Usage.RenderTargetOutput, OutputHandle = WindowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = true, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); m_RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); var depthBufferDesc = new Texture2DDescription() { Width = ToolkitSettings.Width, Height = ToolkitSettings.Height, MipLevels = 0, 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 }; m_depthStencilBuffer = new Texture2D(device, depthBufferDesc); var depthStencilDecs = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always, }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDecs); DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; BlendStateDescription bsd = new BlendStateDescription() { AlphaToCoverageEnable = false,//true, IndependentBlendEnable = false, }; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; //bsDefault = new BlendState(device, bsd); bsd.AlphaToCoverageEnable = true; BlendState bsAlpha = new BlendState(device, bsd); DeviceContext.OutputMerger.BlendState = bsAlpha; m_DepthStencilView = new DepthStencilView(Device, m_depthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(m_DepthStencilView, m_RenderTargetView); m_RSDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = true, CullMode = CullMode.Back, DepthBias = 10, DepthBiasClamp = .0f, IsDepthClipEnabled = false, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, IsMultisampleEnabled = false, IsScissorEnabled = false, SlopeScaledDepthBias = .0f }; m_RSCullSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.None; m_RSSolid = new RasterizerState(Device, m_RSDesc); m_RSDesc.FillMode = FillMode.Wireframe; m_RSWireFrame = new RasterizerState(Device, m_RSDesc); m_RSDesc.CullMode = CullMode.Back; m_RSCullWireFrame = new RasterizerState(Device, m_RSDesc); UpdateRasterizer(); return(true); }
public void OnInitialise(InitialiseMessage msg) { // Initialise renderer Console.WriteLine("Initialising renderer..."); rendermsg = new RenderMessage(); updatemsg = new UpdateMessage(); // Create the window window = new RenderForm("Castle Renderer - 11030062"); window.Width = 1280; window.Height = 720; // Add form events window.FormClosed += window_FormClosed; // Defaults ClearColour = new Color4(1.0f, 0.0f, 0.0f, 1.0f); // Setup the device var description = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = window.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device tmp; var result = Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, description, out tmp, out swapchain); if (result.IsFailure) { Console.WriteLine("Failed to create Direct3D11 device (" + result.Code.ToString() + ":" + result.Description + ")"); return; } Device = tmp; context = Device.ImmediateContext; using (var factory = swapchain.GetParent<Factory>()) factory.SetWindowAssociation(window.Handle, WindowAssociationFlags.IgnoreAltEnter); // Check AA stuff int q = Device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 8); // Setup the viewport viewport = new Viewport(0.0f, 0.0f, window.ClientSize.Width, window.ClientSize.Height); viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; context.Rasterizer.SetViewports(viewport); // Setup the backbuffer using (var resource = Resource.FromSwapChain<Texture2D>(swapchain, 0)) rtBackbuffer = new RenderTargetView(Device, resource); // Setup depth for backbuffer { Texture2DDescription texdesc = new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, Format = Format.D32_Float, Width = (int)viewport.Width, Height = (int)viewport.Height, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }; texDepthBuffer = new Texture2D(Device, texdesc); DepthStencilViewDescription viewdesc = new DepthStencilViewDescription() { ArraySize = 0, Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, MipSlice = 0, Flags = 0, FirstArraySlice = 0 }; vwDepthBuffer = new DepthStencilView(Device, texDepthBuffer, viewdesc); } // Setup states #region Depth States // Setup depth states { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; Depth_Enabled = DepthStencilState.FromDescription(Device, desc); } { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less }; Depth_Disabled = DepthStencilState.FromDescription(Device, desc); } { DepthStencilStateDescription desc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.Zero, DepthComparison = Comparison.Less }; Depth_ReadOnly = DepthStencilState.FromDescription(Device, desc); } #endregion #region Sampler States Sampler_Clamp = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.Anisotropic, MinimumLod = 0.0f, MaximumLod = float.MaxValue, MaximumAnisotropy = 16 }); Sampler_Clamp_Point = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.MinMagMipPoint }); Sampler_Clamp_Linear = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Clamp, AddressV = TextureAddressMode.Clamp, AddressW = TextureAddressMode.Clamp, Filter = Filter.MinMagMipLinear }); Sampler_Wrap = SamplerState.FromDescription(Device, new SamplerDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, MinimumLod = 0.0f, MaximumLod = float.MaxValue, MaximumAnisotropy = 16 }); #endregion #region Rasterizer States Culling_Backface = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.Back, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); Culling_Frontface = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.Front, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); Culling_None = RasterizerState.FromDescription(Device, new RasterizerStateDescription() { CullMode = CullMode.None, DepthBias = 0, DepthBiasClamp = 0.0f, IsDepthClipEnabled = true, FillMode = FillMode.Solid, IsAntialiasedLineEnabled = false, IsFrontCounterclockwise = false, IsMultisampleEnabled = true, IsScissorEnabled = false, SlopeScaledDepthBias = 0.0f }); #endregion #region Blend States { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.One; desc.RenderTargets[0].DestinationBlend = BlendOption.Zero; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Opaque = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; desc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Alpha = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.One; desc.RenderTargets[0].DestinationBlend = BlendOption.One; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Add = BlendState.FromDescription(Device, desc); } { BlendStateDescription desc = new BlendStateDescription(); desc.RenderTargets[0].BlendEnable = true; desc.RenderTargets[0].BlendOperation = BlendOperation.Add; desc.RenderTargets[0].SourceBlend = BlendOption.DestinationColor; desc.RenderTargets[0].DestinationBlend = BlendOption.Zero; desc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; desc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; desc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; desc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; Blend_Multiply = BlendState.FromDescription(Device, desc); } #endregion // Setup default states Depth = Depth_Enabled; Culling = Culling_Backface; Blend = Blend_Opaque; // Setup other objects shaderresourcemap = new Dictionary<Resource, ShaderResourceView>(); resourceviewslots = new ShaderResourceViewData[MaxPixelShaderResourceViewSlots]; // Send the window created message WindowCreatedMessage windowcreatedmsg = new WindowCreatedMessage(); windowcreatedmsg.Form = window; Owner.MessagePool.SendMessage(windowcreatedmsg); // Show the form window.Show(); }
private void Initialize() { var factory = graphicsDevice.ResourceFactory; aspectWidth = 2f / graphicsDevice.SwapchainFramebuffer.Width; aspectHeight = 2f / graphicsDevice.SwapchainFramebuffer.Height; glyphVertexBuffer = factory.CreateBuffer(new BufferDescription(VertexPosition3Coord2.SizeInBytes, BufferUsage.VertexBuffer)); quadVertexBuffer = factory.CreateBuffer(new BufferDescription(VertexPosition2.SizeInBytes * 4, BufferUsage.VertexBuffer)); quadVertices = new VertexPosition2[] { new VertexPosition2(new Vector2(-1, 1)), new VertexPosition2(new Vector2(-1, -1)), new VertexPosition2(new Vector2(1, 1)), new VertexPosition2(new Vector2(1, -1)), }; graphicsDevice.UpdateBuffer(quadVertexBuffer, 0, quadVertices); textVertexPropertiesBuffer = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <TextVertexProperties>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); textFragmentPropertiesBuffer = factory.CreateBuffer(new BufferDescription((uint)Unsafe.SizeOf <TextFragmentProperties>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic)); textVertexProperties = new TextVertexProperties { Transform = new Matrix4x4(), Rectangle = new Vector4(0, 0, 1, 1) }; textFragmentProperties = new TextFragmentProperties { ThicknessAndMode = 0, // TODO support other modes GlyphColor = new Color(0, 0.5f, 1, 1) }; graphicsDevice.UpdateBuffer(textVertexPropertiesBuffer, 0, textVertexProperties); graphicsDevice.UpdateBuffer(textFragmentPropertiesBuffer, 0, textFragmentProperties); var colorFormat = PixelFormat.B8_G8_R8_A8_UNorm; glyphTexture = factory.CreateTexture(TextureDescription.Texture2D(graphicsDevice.SwapchainFramebuffer.Width, graphicsDevice.SwapchainFramebuffer.Height, 1, 1, colorFormat, TextureUsage.RenderTarget | TextureUsage.Sampled)); glyphTextureView = factory.CreateTextureView(glyphTexture); glyphTextureFramebuffer = factory.CreateFramebuffer(new FramebufferDescription(null, glyphTexture)); // HACK workaround issue with texture view caching for shader resources dummyTexture = factory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, colorFormat, TextureUsage.Sampled)); dummyTextureView = factory.CreateTextureView(dummyTexture); var shaderOptions = GetCompileOptions(); CompileShaders(factory, shaderOptions); var textPropertiesLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("TextVertexPropertiesBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex), new ResourceLayoutElementDescription("TextFragmentPropertiesBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment))); var textTextureLayout = factory.CreateResourceLayout( new ResourceLayoutDescription( new ResourceLayoutElementDescription("GlyphTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment), new ResourceLayoutElementDescription("GlyphTextureSampler", ResourceKind.Sampler, ShaderStages.Fragment))); textPropertiesSet = factory.CreateResourceSet(new ResourceSetDescription( textPropertiesLayout, textVertexPropertiesBuffer, textFragmentPropertiesBuffer)); textTextureSet = factory.CreateResourceSet(new ResourceSetDescription( textTextureLayout, glyphTextureView, graphicsDevice.LinearSampler)); // HACK workaround issue with texture view caching for shader resources dummyTextureSet = factory.CreateResourceSet(new ResourceSetDescription( textTextureLayout, dummyTextureView, graphicsDevice.LinearSampler)); var additiveBlendState = new BlendStateDescription(RgbaFloat.White, new BlendAttachmentDescription( blendEnabled: true, sourceColorFactor: BlendFactor.One, destinationColorFactor: BlendFactor.One, colorFunction: BlendFunction.Add, sourceAlphaFactor: BlendFactor.One, destinationAlphaFactor: BlendFactor.One, alphaFunction: BlendFunction.Add)); var pipelineDescription = new GraphicsPipelineDescription( blendState: new BlendStateDescription(RgbaFloat.White, new BlendAttachmentDescription( blendEnabled: true, sourceColorFactor: BlendFactor.Zero, destinationColorFactor: BlendFactor.SourceColor, colorFunction: BlendFunction.Add, sourceAlphaFactor: BlendFactor.Zero, destinationAlphaFactor: BlendFactor.SourceAlpha, alphaFunction: BlendFunction.Add)), depthStencilStateDescription: new DepthStencilStateDescription( depthTestEnabled: true, depthWriteEnabled: true, comparisonKind: ComparisonKind.LessEqual), rasterizerState: new RasterizerStateDescription( cullMode: FaceCullMode.Back, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false), primitiveTopology: PrimitiveTopology.TriangleStrip, shaderSet: new ShaderSetDescription( vertexLayouts: new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, shaders: textShaders, specializations: shaderOptions.Specializations), resourceLayouts: new ResourceLayout[] { textPropertiesLayout, textTextureLayout }, outputs: graphicsDevice.SwapchainFramebuffer.OutputDescription ); outputPipeline = factory.CreateGraphicsPipeline(pipelineDescription); pipelineDescription.BlendState = additiveBlendState; outputColorPipeline = factory.CreateGraphicsPipeline(pipelineDescription); pipelineDescription.Outputs = new OutputDescription(null, new OutputAttachmentDescription(colorFormat)); pipelineDescription.BlendState = additiveBlendState; pipelineDescription.ResourceLayouts = new ResourceLayout[] { textPropertiesLayout }; pipelineDescription.PrimitiveTopology = PrimitiveTopology.TriangleList; pipelineDescription.RasterizerState = new RasterizerStateDescription( cullMode: FaceCullMode.None, fillMode: PolygonFillMode.Solid, frontFace: FrontFace.Clockwise, depthClipEnabled: true, scissorTestEnabled: false); pipelineDescription.ShaderSet = new ShaderSetDescription( vertexLayouts: new[] { new VertexLayoutDescription( new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3), new VertexElementDescription("Coord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2)) }, shaders: glyphShaders, specializations: shaderOptions.Specializations); glyphPipeline = factory.CreateGraphicsPipeline(pipelineDescription); }
public Renderer(Control control) { try { SwapChainDescription description = new SwapChainDescription() { BufferCount = 1, Usage = Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), SampleDescription = new SampleDescription(1, 0), Flags = SwapChainFlags.AllowModeSwitch, SwapEffect = SwapEffect.Discard }; Device device; Device.CreateWithSwapChain(DriverType.Hardware, 0, description, out device, out swapChain); Device = device; } catch (Exception e) { Match m = Regex.Match(e.Message, @"\((.+)\)"); int hexErr = 0; if (m.Groups.Count >= 2) { int.TryParse(m.Groups[1].Value, out hexErr); } Report.ReportLog("Device.CreateWithSwapChain failed: " + e.Message + (hexErr != 0 ? " => x" + hexErr.ToString("X8") : string.Empty)); return; } using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) renderTarget = new RenderTargetView(Device, resource); Texture2DDescription depthStencilDesc = new Texture2DDescription { Width = control.Width, Height = control.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 }; depthStencilBuffer = new Texture2D(Device, depthStencilDesc) { DebugName = "DepthStencilBuffer" }; depthStencilView = new DepthStencilView(Device, depthStencilBuffer); var context = Device.ImmediateContext; context.OutputMerger.SetTargets(depthStencilView, renderTarget); var viewport = new Viewport(0.0f, 0.0f, control.Width, control.Height, 0f, 1f); context.Rasterizer.SetViewports(viewport); // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms using (var factory = swapChain.GetParent <Factory>()) factory.SetWindowAssociation(control.Handle, WindowAssociationFlags.IgnoreAltEnter); /* Device.SetRenderState(RenderState.DiffuseMaterialSource, ColorSource.Material); * Device.SetRenderState(RenderState.EmissiveMaterialSource, ColorSource.Material); * Device.SetRenderState(RenderState.SpecularMaterialSource, ColorSource.Material); * Device.SetRenderState(RenderState.SpecularEnable, true);*/ BlendStateDescription transDesc = new BlendStateDescription { AlphaToCoverageEnable = false, IndependentBlendEnable = false }; transDesc.RenderTargets[0].BlendEnable = true; transDesc.RenderTargets[0].SourceBlend = BlendOption.SourceAlpha; transDesc.RenderTargets[0].DestinationBlend = BlendOption.InverseSourceAlpha; transDesc.RenderTargets[0].BlendOperation = BlendOperation.Add; transDesc.RenderTargets[0].SourceBlendAlpha = BlendOption.One; transDesc.RenderTargets[0].DestinationBlendAlpha = BlendOption.Zero; transDesc.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; transDesc.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; transparentBS = BlendState.FromDescription(Device, transDesc); context.OutputMerger.BlendState = transparentBS; context.OutputMerger.BlendFactor = blendFactor; context.OutputMerger.BlendSampleMask = ~0; /* Device.SetSamplerState(0, SamplerState.MaxAnisotropy, 4); * Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Anisotropic); * Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Anisotropic); * Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear);*/ Lights = new Core.DirectionalLight[1] { new Core.DirectionalLight { Ambient = new Color4(int.Parse((string)Gui.Config["LightAmbientARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)), Diffuse = new Color4(int.Parse((string)Gui.Config["LightDiffuseARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)), Specular = new Color4(int.Parse((string)Gui.Config["LightSpecularARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)), Direction = new Vector3(0.57735f, 0.57735f, 0.57735f) } }; /* TextFont = new SlimDX.Direct3D9.Font(Device, new System.Drawing.Font("Arial", 8)); * TextColor = new Color4(Color.White);*/ showNormals = (bool)Gui.Config["ShowNormals"]; showBones = (bool)Gui.Config["ShowBones"]; string[] mode = Enum.GetNames(typeof(ShowBoneWeights)); for (int i = 0; i < mode.Length; i++) { if (mode[i] == (string)Gui.Config["ShowBoneWeights"]) { showBoneWeights = (ShowBoneWeights)i; break; } } wireframe = (bool)Gui.Config["Wireframe"]; culling = (bool)Gui.Config["Culling"]; Background = Color.FromArgb(int.Parse((string)Gui.Config["RendererBackgroundARGB"], System.Globalization.NumberStyles.AllowHexSpecifier)); camera = new Camera(control); BuildFX(); CursorMesh = new Cursor(Device, LineLayout, PositionColorEffect.ColorTech); AxesMesh = new Axes(Device, LineLayout, PositionColorEffect.ColorTech); RenderControl = control; isInitialized = true; }
/// <summary> /// Registers the specified desc. /// </summary> /// <param name="desc">The desc.</param> /// <returns></returns> public BlendStateProxy Register(BlendStateDescription desc) { return(BlendStatePool.Register(desc) as BlendStateProxy); }
private void BuildPSOs() { // // PSO for opaque objects. // var opaquePsoDesc = new GraphicsPipelineStateDescription { InputLayout = _inputLayout, RootSignature = _rootSignature, VertexShader = _shaders["standardVS"], PixelShader = _shaders["opaquePS"], RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, SampleDescription = new SampleDescription(MsaaCount, MsaaQuality), DepthStencilFormat = DepthStencilFormat }; opaquePsoDesc.RenderTargetFormats[0] = BackBufferFormat; _psos["opaque"] = Device.CreateGraphicsPipelineState(opaquePsoDesc); // // PSO for transparent objects. // GraphicsPipelineStateDescription transparentPsoDesc = opaquePsoDesc.Copy(); var transparencyBlendDesc = new RenderTargetBlendDescription { IsBlendEnabled = true, LogicOpEnable = false, // TODO: API suggestion: Rename to IsLogicOpEnabled similar to IsBlendEnabled. SourceBlend = BlendOption.SourceAlpha, DestinationBlend = BlendOption.InverseSourceAlpha, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.One, DestinationAlphaBlend = BlendOption.Zero, AlphaBlendOperation = BlendOperation.Add, LogicOp = LogicOperation.Noop, RenderTargetWriteMask = ColorWriteMaskFlags.All }; transparentPsoDesc.BlendState.RenderTarget[0] = transparencyBlendDesc; _psos["transparent"] = Device.CreateGraphicsPipelineState(transparentPsoDesc); // // PSO for alpha tested objects. // GraphicsPipelineStateDescription alphaTestedPsoDesc = opaquePsoDesc.Copy(); alphaTestedPsoDesc.PixelShader = _shaders["alphaTestedPS"]; alphaTestedPsoDesc.RasterizerState.CullMode = CullMode.None; _psos["alphaTested"] = Device.CreateGraphicsPipelineState(alphaTestedPsoDesc); }
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); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { _resources = new GraphicsResource[0]; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/SimpleShader.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { new Vertex() { position = new Vector3(-0.5f, -0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(-0.5f, 0.5f, 0.5f), color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, -0.5f, 0.5f), color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, new Vertex() { position = new Vector3(0.5f, 0.5f, 0.5f), color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; }
public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle) { try { #region Environment Configuration VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled; var factory = new Factory1(); var adapter = factory.GetAdapter1(0); var monitor = adapter.GetOutput(0); var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced); 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; } } } var adapterDescription = adapter.Description; VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10; VideoCardDescription = string.Format("VideoCard: {0}", adapterDescription.Description.Trim('\0')); monitor.Dispose(); adapter.Dispose(); factory.Dispose(); #endregion #region Initialize swap chain and d3d device var swapChainDesc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm) { Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified }, Usage = Usage.RenderTargetOutput, OutputHandle = windowHandle, SampleDescription = new SampleDescription(1, 0), IsWindowed = !DSystemConfiguration.FullScreen, Flags = SwapChainFlags.None, SwapEffect = SwapEffect.Discard }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain); Device = device; SwapChain = swapChain; DeviceContext = device.ImmediateContext; #endregion #region Initialize buffers var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0); RenderTargetView = new RenderTargetView(device, backBuffer); backBuffer.Dispose(); 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 }; DepthStencilBuffer = new Texture2D(device, depthBufferDesc); #endregion #region Initialize Depth Enabled Stencil var depthStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthStencilState = new DepthStencilState(Device, depthStencilDesc); #endregion #region Initialize Output Merger DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1); var depthStencilViewDesc = new DepthStencilViewDescription() { Format = Format.D24_UNorm_S8_UInt, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }; DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc); DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView); #endregion #region Initialize Raster State 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 }; RasterState = new RasterizerState(Device, rasterDesc); #endregion #region Initialize Rasterizer DeviceContext.Rasterizer.State = RasterState; ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f); DeviceContext.Rasterizer.SetViewport(ViewPort); #endregion #region Initialize matrices ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); WorldMatrix = Matrix.Identity; OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth); #endregion #region Initialize Depth Disabled Stencil var depthDisabledStencilDesc = new DepthStencilStateDescription() { IsDepthEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less, IsStencilEnabled = true, StencilReadMask = 0xFF, StencilWriteMask = 0xFF, FrontFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Increment, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always }, BackFace = new DepthStencilOperationDescription() { FailOperation = StencilOperation.Keep, DepthFailOperation = StencilOperation.Decrement, PassOperation = StencilOperation.Keep, Comparison = Comparison.Always } }; DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc); #endregion #region Initialize Blend States 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; AlphaEnableBlendingState = new BlendState(device, blendStateDesc); blendStateDesc.RenderTarget[0].IsBlendEnabled = false; AlphaDisableBlendingState = new BlendState(device, blendStateDesc); #endregion return(true); } catch (Exception) { return(false); } }
private void LoadResources() { var imageLayer = m_presenter.Factory.CreateDrawingLayerFromFile(@".\Assets\Nature Mountains photo.jpg"); m_brush = m_presenter.Factory.CreateDrawingLayerBrush(imageLayer); m_brushD3D = m_presenter.Factory.CreateDrawingLayerBrush(m_layer); lastStopwatchValue = Stopwatch.GetTimestamp(); CreateDepthBuffer(); var dssd = new DepthStencilStateDescription { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; var solidParentOp = new BlendStateDescription(); solidParentOp.SetBlendEnable(0, false); solidParentOp.SetWriteMask(0, ColorWriteMaskFlags.All); var transParentOp = new BlendStateDescription { AlphaBlendOperation = BlendOperation.Add, BlendOperation = BlendOperation.Add, DestinationAlphaBlend = BlendOption.Zero, DestinationBlend = BlendOption.One, IsAlphaToCoverageEnabled = false, SourceAlphaBlend = BlendOption.Zero, SourceBlend = BlendOption.One, }; transParentOp.SetBlendEnable(0, true); transParentOp.SetWriteMask(0, ColorWriteMaskFlags.All); transBlendState = BlendState.FromDescription(m_device, transParentOp); solidBlendState = BlendState.FromDescription(m_device, solidParentOp); depthStencilState = DepthStencilState.FromDescription(m_device, dssd); textTex = Texture2D.FromPointer(m_layerText.Texture2DComPointer); jupiterTex = Texture2D.FromFile(m_device, "jupiter.jpg"); jupiterMesh = new SimpleModel(m_device, "SimpleModel10.fx", "jupiter.SMD", jupiterTex); view = Matrix.LookAtLH(new Vector3(0, 160, 0), new Vector3(0, -128.0f, 0), -Vector3.UnitZ); jupiterMesh.Effect.GetVariableByName("view").AsMatrix().SetMatrix(view); proj = Matrix.PerspectiveFovLH(45.0f, m_presenter.Width / (float)m_presenter.Height, 1.0f, 1000.0f); jupiterMesh.Effect.GetVariableByName("proj").AsMatrix().SetMatrix(proj); }
public Dx11RenderingDevice() { logger.Info("Dx11 rendering device creating."); #if DEBUG const DeviceCreationFlags DebugFlags = DeviceCreationFlags.Debug; #else const DeviceCreationFlags DebugFlags = DeviceCreationFlags.None; #endif try { Factory = new Factory(); if (Factory.Adapters.Count() == 0) { MessageBox.Show("Your system have no video adapters. Try to install video adapter.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("There are no valid video adapters in system."); } var adapter = Factory.GetAdapter(0); if (adapter == null) { MessageBox.Show("DirectX wasn't able to acquire video adapter. Try to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("DirectX wasn't able to acquire video adapter."); } if (adapter.Outputs == null || adapter.Outputs.Count() == 0) { MessageBox.Show("There are no video displays connected to your system. Try to connect a display.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw new Exception("No connected displays found."); } Device = new Device(adapter, DebugFlags | DeviceCreationFlags.SingleThreaded, FeatureLevel.Level_10_0); } catch (Exception exc) { switch ((uint)exc.HResult) { case 0x887A0004: MessageBox.Show("Your DirectX version, videocard or drivers are out of date.\nDirectX 11 installation and videocard with DirectX 10 support is required.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case 0x887A002D: MessageBox.Show("Warning: provided build is a debug build.\nPlease install DirectX SDK or request release build from QA team.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case 0x887A0005: case 0x887A0020: MessageBox.Show("There was a serious video system error while initializing Direct3D device.\nTry to restart your system.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: MessageBox.Show("Unknown error while creating Direct3D device!\nShutting down now.", "DirectX error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } throw new Exception("Can't create Direct3D 11 device! Exception: " + exc); } #if DEBUG using (InfoQueue DeviceInfoQueue = Device.QueryInterface <InfoQueue>()) { DeviceInfoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true); } #endif try { Context = Device.ImmediateContext; /*TestShader = new Dx11PipelineState(this, "TestShader", new InputElement[] * { * new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), * new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0) * });*/ TextShader = new Dx11PipelineState(this, "TextShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0) }); SpriteShader = new Dx11PipelineState(this, "SpriteShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("UVW", 0, Format.R32G32_UInt, 0, 1, InputClassification.PerVertexData, 0) }); RoomShader = new Dx11PipelineState(this, "RoomShader", new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 0, 1, InputClassification.PerVertexData, 0), new InputElement("OVERLAY", 0, Format.R8G8B8A8_UNorm, 0, 2, InputClassification.PerVertexData, 0), new InputElement("UVWANDBLENDMODE", 0, Format.R32G32_UInt, 0, 3, InputClassification.PerVertexData, 0), new InputElement("EDITORUVANDSECTORTEXTURE", 0, Format.R32_UInt, 0, 4, InputClassification.PerVertexData, 0) }); RasterizerBackCulling = new RasterizerState(Device, new RasterizerStateDescription { CullMode = CullMode.Back, FillMode = FillMode.Solid, }); SamplerDefault = new SamplerState(Device, new SamplerStateDescription { AddressU = TextureAddressMode.Mirror, AddressV = TextureAddressMode.Mirror, AddressW = TextureAddressMode.Wrap, Filter = Filter.Anisotropic, MaximumAnisotropy = 4, }); SamplerRoundToNearest = new SamplerState(Device, new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.MinMagMipPoint, MaximumAnisotropy = 4, }); { DepthStencilStateDescription desc = DepthStencilStateDescription.Default(); desc.DepthComparison = Comparison.LessEqual; desc.DepthWriteMask = DepthWriteMask.All; desc.IsDepthEnabled = true; desc.IsStencilEnabled = false; DepthStencilDefault = new DepthStencilState(Device, desc); } { DepthStencilStateDescription desc = DepthStencilStateDescription.Default(); desc.DepthComparison = Comparison.Always; desc.DepthWriteMask = DepthWriteMask.Zero; desc.IsDepthEnabled = false; desc.IsStencilEnabled = false; DepthStencilNoZBuffer = new DepthStencilState(Device, desc); } BlendingDisabled = new BlendState(Device, BlendStateDescription.Default()); { BlendStateDescription desc = BlendStateDescription.Default(); desc.RenderTarget[0].IsBlendEnabled = true; desc.RenderTarget[0].SourceBlend = desc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; desc.RenderTarget[0].DestinationBlend = desc.RenderTarget[0].DestinationAlphaBlend = BlendOption.InverseSourceAlpha; desc.RenderTarget[0].BlendOperation = desc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; desc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; BlendingPremultipliedAlpha = new BlendState(Device, desc); } } catch (Exception exc) { throw new Exception("Can't assign needed Direct3D parameters! Exception: " + exc); } // Sector textures bool support16BitTexture = Device.CheckFormatSupport(Format.B5G5R5A1_UNorm).HasFlag(FormatSupport.Texture2D); // For some reason not all DirectX devices support 16 bit textures. string[] sectorTextureNames = Enum.GetNames(typeof(SectorTexture)).Skip(1).ToArray(); GCHandle[] handles = new GCHandle[sectorTextureNames.Length]; try { DataBox[] dataBoxes = new DataBox[sectorTextureNames.Length]; for (int i = 0; i < sectorTextureNames.Length; ++i) { string name = nameof(TombLib) + "." + nameof(Rendering) + ".SectorTextures." + sectorTextureNames[i] + ".png"; using (Stream stream = ThisAssembly.GetManifestResourceStream(name)) { ImageC image = ImageC.FromStream(stream); if ((image.Width != SectorTextureSize) || (image.Height != SectorTextureSize)) { throw new ArgumentOutOfRangeException("The embedded resource '" + name + "' is not of a valid size."); } if (support16BitTexture) { // Compress image data into B5G5R5A1 format to save a bit of GPU memory. (3 MB saved with currently 23 images) ushort[] sectorTextureData = new ushort[SectorTextureSize * SectorTextureSize]; for (int j = 0; j < (SectorTextureSize * SectorTextureSize); ++j) { ColorC Color = image.Get(j); sectorTextureData[j] = (ushort)( ((Color.B >> 3) << 0) | ((Color.G >> 3) << 5) | ((Color.R >> 3) << 10) | ((Color.A >> 7) << 15)); } handles[i] = GCHandle.Alloc(sectorTextureData, GCHandleType.Pinned); dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(ushort) * SectorTextureSize, 0); } else { handles[i] = GCHandle.Alloc(image.ToByteArray(), GCHandleType.Pinned); dataBoxes[i] = new DataBox(handles[i].AddrOfPinnedObject(), sizeof(uint) * SectorTextureSize, 0); } } } SectorTextureArray = new Texture2D(Device, new Texture2DDescription { Width = SectorTextureSize, Height = SectorTextureSize, MipLevels = 1, ArraySize = sectorTextureNames.Length, Format = support16BitTexture ? Format.B5G5R5A1_UNorm : Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }, dataBoxes); } finally { foreach (GCHandle handle in handles) { handle.Free(); } } SectorTextureArrayView = new ShaderResourceView(Device, SectorTextureArray); // Set omni present state ResetState(); logger.Info("Dx11 rendering device created."); }
private void InitalizeGraphics() { if (Window.RenderCanvasHandle == IntPtr.Zero) throw new InvalidOperationException(); SwapChainDescription swapChainDesc = new SwapChainDescription() { BufferCount = 1, Flags = SwapChainFlags.None, IsWindowed = true, OutputHandle = Window.RenderCanvasHandle, SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, ModeDescription = new ModeDescription() { Format = SlimDX.DXGI.Format.R8G8B8A8_UNorm, //Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm, Width = (int)Window.RenderCanvasSize.Width, Height = (int)Window.RenderCanvasSize.Height, RefreshRate = new Rational(60, 1), Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrdering.Unspecified }, SampleDescription = new SampleDescription(1, 0) }; var giFactory = new SlimDX.DXGI.Factory(); var adapter = giFactory.GetAdapter(0); Device device; SwapChain swapChain; Device.CreateWithSwapChain(adapter, DriverType.Hardware, DeviceCreationFlags.Debug, swapChainDesc, out device, out swapChain); _swapChain = swapChain; GraphicsDevice = device; // create a view of our render target, which is the backbuffer of the swap chain we just created using (var resource = SlimDX.Direct3D10.Resource.FromSwapChain<Texture2D>(swapChain, 0)) { _backBuffer = new RenderTargetView(device, resource); } // setting a viewport is required if you want to actually see anything var viewport = new Viewport(0, 0, (int)Window.RenderCanvasSize.Width, (int)Window.RenderCanvasSize.Height); device.OutputMerger.SetTargets(_backBuffer); device.Rasterizer.SetViewports(viewport); CreateDepthStencil(); LoadVisualizationEffect(); // Allocate a large buffer to write the PhysX visualization vertices into // There's more optimized ways of doing this, but for this sample a large buffer will do _userPrimitivesBuffer = new SlimDX.Direct3D10.Buffer(GraphicsDevice, VertexPositionColor.SizeInBytes * 50000, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None); var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); // States var blendDesc = new BlendStateDescription() { SourceBlend = BlendOption.One, DestinationBlend = BlendOption.Zero, BlendOperation = BlendOperation.Add, SourceAlphaBlend = BlendOption.One, DestinationAlphaBlend = BlendOption.Zero, AlphaBlendOperation = BlendOperation.Add }; blendDesc.SetBlendEnable(0, true); _blendState = BlendState.FromDescription(device, blendDesc); var rasterDesc = new RasterizerStateDescription() { IsAntialiasedLineEnabled = false, IsMultisampleEnabled = false, FillMode = FillMode.Solid, CullMode = CullMode.None }; _rasterizerState = RasterizerState.FromDescription(device, rasterDesc); }
/// <summary> /// ブレンディング ステートをセットする /// </summary> /// <param name="d"></param> public void SetBlendDesc(BlendStateDescription d) { m_blendDesc = d.Clone(); }
/// <summary> /// Draws a fullscreen texture using the specified sampler. See <see cref="Draw+a+texture"/> to learn how to use it. /// </summary> /// <param name="texture">The texture. Expecting an instance of <see cref="Texture"/>.</param> /// <param name="sampler">The sampler.</param> /// <param name="applyEffectStates">The flag to apply effect states.</param> public static void DrawTexture(this GraphicsContext graphicsContext, Texture texture, SamplerState sampler, BlendStateDescription? blendState = null) { graphicsContext.DrawTexture(texture, sampler, Color4.White, blendState); }
private void LoadAssets() { // Create the root signature description. var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, // Root Parameters new[] { new RootParameter(ShaderVisibility.Pixel, new DescriptorRange() { RangeType = DescriptorRangeType.ShaderResourceView, DescriptorCount = 1, OffsetInDescriptorsFromTableStart = int.MinValue, BaseShaderRegister = 0 }) }, // Samplers new[] { new StaticSamplerDescription(ShaderVisibility.Pixel, 0, 0) { Filter = Filter.MinimumMinMagMipPoint, AddressUVW = TextureAddressMode.Border, } }); rootSignature = device.CreateRootSignature(0, rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.Compile(SharpDX.IO.NativeFile.ReadAllText("shaders.hlsl"), "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. var inputElementDescs = new [] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). var psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. var triangleVertices = new [] { new Vertex() { Position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), TexCoord = new Vector2(0.5f, 0.0f) }, new Vertex() { Position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), TexCoord = new Vector2(1.0f, 1.0f) }, new Vertex() { Position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), TexCoord = new Vector2(0.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. var pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Create the texture. // Describe and create a Texture2D. var textureDesc = ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight); texture = device.CreateCommittedResource(new HeapProperties(HeapType.Default), HeapFlags.None, textureDesc, ResourceStates.CopyDestination); long uploadBufferSize = GetRequiredIntermediateSize(this.texture, 0, 1); // Create the GPU upload buffer. var textureUploadHeap = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Texture2D(Format.R8G8B8A8_UNorm, TextureWidth, TextureHeight), ResourceStates.GenericRead); // Copy data to the intermediate upload heap and then schedule a copy // from the upload heap to the Texture2D. byte[] textureData = GenerateTextureData(); var handle = GCHandle.Alloc(textureData, GCHandleType.Pinned); var ptr = Marshal.UnsafeAddrOfPinnedArrayElement(textureData, 0); textureUploadHeap.WriteToSubresource(0, null, ptr, TexturePixelSize * TextureWidth, textureData.Length); handle.Free(); commandList.CopyTextureRegion(new TextureCopyLocation(texture, 0), 0, 0, 0, new TextureCopyLocation(textureUploadHeap, 0), null); commandList.ResourceBarrierTransition(this.texture, ResourceStates.CopyDestination, ResourceStates.PixelShaderResource); // Describe and create a SRV for the texture. var srvDesc = new ShaderResourceViewDescription { Shader4ComponentMapping = D3DXUtilities.DefaultComponentMapping(), Format = textureDesc.Format, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = { MipLevels = 1 }, }; device.CreateShaderResourceView(this.texture, srvDesc, shaderRenderViewHeap.CPUDescriptorHandleForHeapStart); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); commandQueue.ExecuteCommandList(commandList); // Create synchronization objects. fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); WaitForPreviousFrame(); //release temp texture textureUploadHeap.Dispose(); }
/// <summary> /// Draws a fullscreen texture using the specified sampler /// and the texture color multiplied by a custom color. See <see cref="Draw+a+texture"/> to learn how to use it. /// </summary> /// <param name="texture">The texture. Expecting an instance of <see cref="Texture"/>.</param> /// <param name="sampler">The sampler.</param> /// <param name="color">The color.</param> /// <param name="applyEffectStates">The flag to apply effect states.</param> public static void DrawTexture(this GraphicsContext graphicsContext, Texture texture, SamplerState sampler, Color4 color, BlendStateDescription? blendState = null) { graphicsContext.CommandList.GraphicsDevice.PrimitiveQuad.Draw(graphicsContext, texture, sampler, color, blendState); }
public void Evaluate(int SpreadMax) { if (this.mode.IsChanged || this.FInState.IsChanged) { this.FOutState.SliceCount = SpreadMax; for (int i = 0; i < SpreadMax; i++) { DX11RenderState rs; if (this.FInState.IsConnected) { rs = this.FInState[i].Clone(); } else { rs = new DX11RenderState(); } BlendStateDescription bs = rs.Blend; RenderTargetBlendDescription target = bs.RenderTargets[0]; //Note: to optimize a little, we do the following : //In any case, if blend is disabled, we enable it as otherwise modes with do nothing //Only exception is replace, if blend is disabled we leave as it is switch (mode[i]) { case AlphaOperationMode.Keep: target.BlendEnable = true; target.BlendOperation = BlendOperation.Add; target.DestinationBlendAlpha = BlendOption.One; target.SourceBlendAlpha = BlendOption.Zero; break; case AlphaOperationMode.Replace: if (target.BlendEnable) { target.BlendOperation = BlendOperation.Add; target.DestinationBlendAlpha = BlendOption.Zero; target.SourceBlendAlpha = BlendOption.One; } break; case AlphaOperationMode.Multiply: target.BlendEnable = true; target.BlendOperation = BlendOperation.Add; target.DestinationBlendAlpha = BlendOption.SourceAlpha; target.SourceBlendAlpha = BlendOption.Zero; break; case AlphaOperationMode.Interpolate: target.BlendEnable = true; target.BlendOperation = BlendOperation.Add; target.DestinationBlendAlpha = BlendOption.InverseSourceAlpha; target.SourceBlendAlpha = BlendOption.SourceAlpha; break; } bs.RenderTargets[0] = target; rs.Blend = bs; this.FOutState[i] = rs; } } }
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); }
internal static Dictionary<BlendStateMode, BlendState> InitializeDefaultBlendStates(Device device) { var blendStates = new Dictionary<BlendStateMode, BlendState>(); /////////////////////////////////////////////////////////////////////////// //// AlphaBlend ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// var blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.One; blendDesc.DestinationAlphaBlend = BlendOption.One; blendDesc.SourceBlend = BlendOption.One; blendDesc.DestinationBlend = BlendOption.InverseSourceAlpha; SetDefaults(ref blendDesc); var blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.AlphaBlend, blendstate); /////////////////////////////////////////////////////////////////////////// //// Subtractive ///////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.ReverseSubtract; blendDesc.AlphaBlendOperation = BlendOperation.ReverseSubtract; blendDesc.SourceAlphaBlend = BlendOption.SourceAlpha; blendDesc.DestinationAlphaBlend = BlendOption.One; blendDesc.SourceBlend = BlendOption.SourceAlpha; blendDesc.DestinationBlend = BlendOption.One; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.Subtractive, blendstate); /////////////////////////////////////////////////////////////////////////// //// Additive ///////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.Zero; blendDesc.DestinationAlphaBlend = BlendOption.Zero; blendDesc.SourceBlend = BlendOption.SourceColor; blendDesc.DestinationBlend = BlendOption.One; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.Additive, blendstate); /////////////////////////////////////////////////////////////////////////// //// Copy ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.SourceAlpha; blendDesc.DestinationAlphaBlend = BlendOption.SourceAlpha; blendDesc.SourceBlend = BlendOption.SourceAlpha; blendDesc.DestinationBlend = BlendOption.Zero; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.Copy, blendstate); /////////////////////////////////////////////////////////////////////////// //// SourceOver ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.One; blendDesc.DestinationAlphaBlend = BlendOption.One; blendDesc.SourceBlend = BlendOption.One; blendDesc.DestinationBlend = BlendOption.InverseSourceAlpha; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.SourceOver, blendstate); /////////////////////////////////////////////////////////////////////////// //// SourceATop ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.DestinationAlpha; blendDesc.DestinationAlphaBlend = BlendOption.DestinationAlpha; blendDesc.SourceBlend = BlendOption.DestinationAlpha; blendDesc.DestinationBlend = BlendOption.InverseSourceAlpha; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.SourceATop, blendstate); /////////////////////////////////////////////////////////////////////////// //// SourceIn ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.DestinationAlpha; blendDesc.DestinationAlphaBlend = BlendOption.Zero; blendDesc.SourceBlend = BlendOption.DestinationAlpha; blendDesc.DestinationBlend = BlendOption.Zero; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.SourceIn, blendstate); /////////////////////////////////////////////////////////////////////////// //// SourceOut ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.InverseDestinationAlpha; blendDesc.DestinationAlphaBlend = BlendOption.Zero; blendDesc.SourceBlend = BlendOption.SourceColor; blendDesc.DestinationBlend = BlendOption.Zero; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.SourceOut, blendstate); /////////////////////////////////////////////////////////////////////////// //// DestinationIn ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.DestinationAlpha; blendDesc.DestinationAlphaBlend = BlendOption.Zero; blendDesc.SourceBlend = BlendOption.Zero; blendDesc.DestinationBlend = BlendOption.SourceAlpha; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.DestinationIn, blendstate); /////////////////////////////////////////////////////////////////////////// //// DestinationOver ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.One; blendDesc.DestinationAlphaBlend = BlendOption.InverseDestinationAlpha; blendDesc.SourceBlend = BlendOption.One; blendDesc.DestinationBlend = BlendOption.One; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.DestinationOver, blendstate); /////////////////////////////////////////////////////////////////////////// //// DestinationOut ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.InverseSourceAlpha; blendDesc.DestinationAlphaBlend = BlendOption.InverseSourceAlpha; blendDesc.SourceBlend = BlendOption.Zero; blendDesc.DestinationBlend = BlendOption.One; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.DestinationOut, blendstate); /////////////////////////////////////////////////////////////////////////// //// DestinationATop ////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// blendDesc = new BlendStateDescription(); blendDesc.IsAlphaToCoverageEnabled = false; blendDesc.BlendOperation = BlendOperation.Add; blendDesc.AlphaBlendOperation = BlendOperation.Add; blendDesc.SourceAlphaBlend = BlendOption.InverseDestinationAlpha; blendDesc.DestinationAlphaBlend = BlendOption.SourceAlpha; blendDesc.SourceBlend = BlendOption.One; blendDesc.DestinationBlend = BlendOption.One; SetDefaults(ref blendDesc); blendstate = BlendState.FromDescription(device, blendDesc); blendStates.Add(BlendStateMode.DestinationATop, blendstate); return blendStates; }
// For FakeBlendState. private BlendState(BlendStateDescription description) { Description = description; }
public void Update(IPluginIO pin, DX11RenderContext context) { Device device = context.Device; DeviceContext ctx = context.CurrentDeviceContext; if (!this.deviceshaderdata.ContainsKey(context)) { this.deviceshaderdata.Add(context, new DX11ShaderData(context)); this.deviceshaderdata[context].SetEffect(this.FShader); } DX11ShaderData shaderdata = this.deviceshaderdata[context]; if (this.shaderupdated) { shaderdata.SetEffect(this.FShader); this.shaderupdated = false; } context.RenderStateStack.Push(new DX11RenderState()); this.OnBeginQuery(context); //Clear shader stages shaderdata.ResetShaderStages(ctx); context.Primitives.ApplyFullTriVS(); foreach (DX11ResourcePoolEntry<DX11RenderTarget2D> rt in this.lastframetargets) { rt.UnLock(); } this.lastframetargets.Clear(); DX11ObjectRenderSettings or = new DX11ObjectRenderSettings(); int wi, he; bool preserve = false; DX11ResourcePoolEntry<DX11RenderTarget2D> preservedtarget = null; for (int i = 0; i < this.spmax; i++) { int passcounter = 0; if (this.FInEnabled[i]) { List<DX11ResourcePoolEntry<DX11RenderTarget2D>> locktargets = new List<DX11ResourcePoolEntry<DX11RenderTarget2D>>(); #region Manage size DX11Texture2D initial; if (this.FIn.PluginIO.IsConnected) { if (this.FInUseDefaultSize[0]) { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[0].X; he = (int)this.FInSize[0].Y; } else { initial = this.FIn[i][context]; if (initial != null) { wi = initial.Width; he = initial.Height; } else { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[i].X; he = (int)this.FInSize[i].Y; } } } else { initial = context.DefaultTextures.WhiteTexture; wi = (int)this.FInSize[i].X; he = (int)this.FInSize[i].Y; } #endregion DX11RenderSettings r = new DX11RenderSettings(); r.RenderWidth = wi; r.RenderHeight = he; if (this.FInSemantics.PluginIO.IsConnected) { r.CustomSemantics.AddRange(this.FInSemantics.ToArray()); } if (this.FInResSemantics.PluginIO.IsConnected) { r.ResourceSemantics.AddRange(this.FInResSemantics.ToArray()); } this.varmanager.SetGlobalSettings(shaderdata.ShaderInstance, r); this.varmanager.ApplyGlobal(shaderdata.ShaderInstance); DX11Texture2D lastrt = initial; DX11ResourcePoolEntry<DX11RenderTarget2D> lasttmp = null; List<DX11Texture2D> rtlist = new List<DX11Texture2D>(); //Bind Initial (once only is ok) this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "INITIAL", initial); //Go trough all passes EffectTechnique tech = shaderdata.ShaderInstance.Effect.GetTechniqueByIndex(tid); for (int j = 0; j < tech.Description.PassCount; j++) { ImageShaderPass pi = this.varmanager.passes[j]; EffectPass pass = tech.GetPassByIndex(j); bool isLastPass = j == tech.Description.PassCount - 1; for (int kiter = 0; kiter < pi.IterationCount; kiter++) { if (passcounter > 0) { for (int pid = 0; pid < passcounter; pid++) { string pname = "PASSRESULT" + pid; this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, pname, rtlist[pid]); } } Format fmt = initial.Format; if (pi.CustomFormat) { fmt = pi.Format; } bool mips = pi.Mips || (isLastPass && FInMipLastPass[i]); int w, h; if (j == 0) { h = he; w = wi; } else { h = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? he : lastrt.Height; w = pi.Reference == ImageShaderPass.eImageScaleReference.Initial ? wi : lastrt.Width; } if (pi.DoScale) { if (pi.Absolute) { w = Convert.ToInt32(pi.ScaleVector.X); h = Convert.ToInt32(pi.ScaleVector.Y); } else { w = Convert.ToInt32((float)w * pi.ScaleVector.X); h = Convert.ToInt32((float)h * pi.ScaleVector.Y); } w = Math.Max(w, 1); h = Math.Max(h, 1); } //Check format support for render target, and default to rgb8 if not if (!context.IsSupported(FormatSupport.RenderTarget, fmt)) { fmt = Format.R8G8B8A8_UNorm; } //Since device is not capable of telling us BGR not supported if (fmt == Format.B8G8R8A8_UNorm) { fmt = Format.R8G8B8A8_UNorm; } DX11ResourcePoolEntry<DX11RenderTarget2D> elem; if (preservedtarget != null) { elem = preservedtarget; } else { elem = context.ResourcePool.LockRenderTarget(w, h, fmt, new SampleDescription(1, 0), mips, 0); locktargets.Add(elem); } DX11RenderTarget2D rt = elem.Element; if (this.FDepthIn.PluginIO.IsConnected && pi.UseDepth) { context.RenderTargetStack.Push(this.FDepthIn[0][context], true, elem.Element); } else { context.RenderTargetStack.Push(elem.Element); } if (pi.Clear) { elem.Element.Clear(new Color4(0, 0, 0, 0)); } #region Check for depth/blend preset bool validdepth = false; bool validblend = false; DepthStencilStateDescription ds = new DepthStencilStateDescription(); BlendStateDescription bs = new BlendStateDescription(); if (pi.DepthPreset != "") { try { ds = DX11DepthStencilStates.Instance.GetState(pi.DepthPreset); validdepth = true; } catch { } } if (pi.BlendPreset != "") { try { bs = DX11BlendStates.Instance.GetState(pi.BlendPreset); validblend = true; } catch { } } #endregion if (validdepth || validblend) { DX11RenderState state = new DX11RenderState(); if (validdepth) { state.DepthStencil = ds; } if (validblend) { state.Blend = bs; } context.RenderStateStack.Push(state); } r.RenderWidth = w; r.RenderHeight = h; r.BackBuffer = elem.Element; this.varmanager.ApplyGlobal(shaderdata.ShaderInstance); //Apply settings (note that textures swap is handled later) this.varmanager.ApplyPerObject(context, shaderdata.ShaderInstance, or, i); //Bind last render target this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "PREVIOUS", lastrt); this.BindPassIndexSemantic(shaderdata.ShaderInstance.Effect, j); this.BindPassIterIndexSemantic(shaderdata.ShaderInstance.Effect, kiter); if (this.FDepthIn.PluginIO.IsConnected) { if (this.FDepthIn[0].Contains(context)) { this.BindTextureSemantic(shaderdata.ShaderInstance.Effect, "DEPTHTEXTURE", this.FDepthIn[0][context]); } } //Apply pass and draw quad pass.Apply(ctx); if (pi.ComputeData.Enabled) { pi.ComputeData.Dispatch(context, w, h); context.CleanUpCS(); } else { ctx.ComputeShader.Set(null); context.Primitives.FullScreenTriangle.Draw(); ctx.OutputMerger.SetTargets(this.nullrtvs); } //Generate mips if applicable if (mips) { ctx.GenerateMips(rt.SRV); } if (!pi.KeepTarget) { preserve = false; rtlist.Add(rt); lastrt = rt; lasttmp = elem; preservedtarget = null; passcounter++; } else { preserve = true; preservedtarget = elem; } context.RenderTargetStack.Pop(); if (validblend || validdepth) { context.RenderStateStack.Pop(); } if (pi.HasState) { context.RenderStateStack.Apply(); } } } //Set last render target this.FOut[i][context] = lastrt; //Unlock all resources foreach (DX11ResourcePoolEntry<DX11RenderTarget2D> lt in locktargets) { lt.UnLock(); } //Keep lock on last rt, since don't want it overidden lasttmp.Lock(); this.lastframetargets.Add(lasttmp); } else { this.FOut[i][context] = this.FIn[i][context]; } } context.RenderStateStack.Pop(); this.OnEndQuery(context); //UnLock previous frame in applicable //if (previoustarget != null) { context.ResourcePool.Unlock(previoustarget); } }
/// <summary> /// Create a new fake blend state for serialization. /// </summary> /// <param name="description">The description of the blend state</param> /// <returns>The fake blend state</returns> public static BlendState NewFake(BlendStateDescription description) { return new BlendState(description); }
public DirectXCanvas() { InitializeComponent(); RenderCanvas = new RenderControl(); RenderForm.Child = RenderCanvas; SwapChainDesc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(RenderCanvas.ClientSize.Width, RenderCanvas.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = RenderCanvas.Handle, SampleDescription = new SampleDescription(4, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, }; SharpDX.Direct3D11.Device device; SwapChain swapChain; SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, SwapChainDesc, out device, out swapChain); SwapChain = swapChain; RenderDevice = device; RenderFactory = SwapChain.GetParent <Factory>(); RenderFactory.MakeWindowAssociation(RenderCanvas.Handle, WindowAssociationFlags.IgnoreAll); RenderDevice.ImmediateContext.Rasterizer.State = new RasterizerState(RenderDevice, RasterizerDesc); WPConstantBuffer = SharpDX.Direct3D11.Buffer.Create(RenderDevice, BindFlags.ConstantBuffer, ref WP); DefaultFragment = LoadFragment(@"Basic.fx", new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 8, 0) }); TextFragment = LoadFragment(@"Text.fx", new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 16, 0) }); Text = new TextManager(this); TextSamplerState = new SamplerState(device, TextSamplerDescription); BlendStateDescription blendDescription = new BlendStateDescription(); blendDescription.RenderTarget[0] = AlphaBlendStateDescription; AlphaBlendState = new BlendState(device, blendDescription); RenderCanvas.Paint += RenderCanvas_Paint; RenderCanvas.Resize += RenderCanvas_Resize; UnitView = SharpDX.Matrix.Scaling(2.0f, -2.0f, 1.0f); UnitView.TranslationVector = new Vector3(-1.0f, 1.0f, 0.0f); OnResize(); }
/// <summary> /// Initializes a new instance of the <see cref="BlendState"/> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="blendStateDescription">The blend state description.</param> internal BlendState(GraphicsDevice graphicsDevice, BlendStateDescription blendStateDescription) { Description = blendStateDescription; }
public MTLPipeline(ref GraphicsPipelineDescription description, MTLGraphicsDevice gd) : base(ref description) { PrimitiveType = MTLFormats.VdToMTLPrimitiveTopology(description.PrimitiveTopology); ResourceLayouts = new MTLResourceLayout[description.ResourceLayouts.Length]; NonVertexBufferCount = 0; for (int i = 0; i < ResourceLayouts.Length; i++) { ResourceLayouts[i] = Util.AssertSubtype <ResourceLayout, MTLResourceLayout>(description.ResourceLayouts[i]); NonVertexBufferCount += ResourceLayouts[i].BufferCount; } ResourceBindingModel = description.ResourceBindingModel ?? gd.ResourceBindingModel; CullMode = MTLFormats.VdToMTLCullMode(description.RasterizerState.CullMode); FrontFace = MTLFormats.VdVoMTLFrontFace(description.RasterizerState.FrontFace); FillMode = MTLFormats.VdToMTLFillMode(description.RasterizerState.FillMode); ScissorTestEnabled = description.RasterizerState.ScissorTestEnabled; MTLRenderPipelineDescriptor mtlDesc = MTLRenderPipelineDescriptor.New(); foreach (Shader shader in description.ShaderSet.Shaders) { MTLShader mtlShader = Util.AssertSubtype <Shader, MTLShader>(shader); MTLFunction specializedFunction; if (mtlShader.HasFunctionConstants) { // Need to create specialized MTLFunction. MTLFunctionConstantValues constantValues = CreateConstantValues(description.ShaderSet.Specializations); specializedFunction = mtlShader.Library.newFunctionWithNameConstantValues(mtlShader.EntryPoint, constantValues); AddSpecializedFunction(specializedFunction); ObjectiveCRuntime.release(constantValues.NativePtr); Debug.Assert(specializedFunction.NativePtr != IntPtr.Zero, "Failed to create specialized MTLFunction"); } else { specializedFunction = mtlShader.Function; } if (shader.Stage == ShaderStages.Vertex) { mtlDesc.vertexFunction = specializedFunction; } else if (shader.Stage == ShaderStages.Fragment) { mtlDesc.fragmentFunction = specializedFunction; } } // Vertex layouts VertexLayoutDescription[] vdVertexLayouts = description.ShaderSet.VertexLayouts; MTLVertexDescriptor vertexDescriptor = mtlDesc.vertexDescriptor; for (uint i = 0; i < vdVertexLayouts.Length; i++) { uint layoutIndex = ResourceBindingModel == ResourceBindingModel.Improved ? NonVertexBufferCount + i : i; MTLVertexBufferLayoutDescriptor mtlLayout = vertexDescriptor.layouts[layoutIndex]; mtlLayout.stride = (UIntPtr)vdVertexLayouts[i].Stride; uint stepRate = vdVertexLayouts[i].InstanceStepRate; mtlLayout.stepFunction = stepRate == 0 ? MTLVertexStepFunction.PerVertex : MTLVertexStepFunction.PerInstance; mtlLayout.stepRate = (UIntPtr)Math.Max(1, stepRate); } uint element = 0; for (uint i = 0; i < vdVertexLayouts.Length; i++) { uint offset = 0; VertexLayoutDescription vdDesc = vdVertexLayouts[i]; for (uint j = 0; j < vdDesc.Elements.Length; j++) { VertexElementDescription elementDesc = vdDesc.Elements[j]; MTLVertexAttributeDescriptor mtlAttribute = vertexDescriptor.attributes[element]; mtlAttribute.bufferIndex = (UIntPtr)(ResourceBindingModel == ResourceBindingModel.Improved ? NonVertexBufferCount + i : i); mtlAttribute.format = MTLFormats.VdToMTLVertexFormat(elementDesc.Format); mtlAttribute.offset = (UIntPtr)offset; offset += FormatHelpers.GetSizeInBytes(elementDesc.Format); element += 1; } } VertexBufferCount = (uint)vdVertexLayouts.Length; // Outputs OutputDescription outputs = description.Outputs; BlendStateDescription blendStateDesc = description.BlendState; BlendColor = blendStateDesc.BlendFactor; if (outputs.SampleCount != TextureSampleCount.Count1) { mtlDesc.sampleCount = (UIntPtr)FormatHelpers.GetSampleCountUInt32(outputs.SampleCount); } if (outputs.DepthAttachment != null) { PixelFormat depthFormat = outputs.DepthAttachment.Value.Format; MTLPixelFormat mtlDepthFormat = MTLFormats.VdToMTLPixelFormat(depthFormat, true); mtlDesc.depthAttachmentPixelFormat = mtlDepthFormat; if ((FormatHelpers.IsStencilFormat(depthFormat))) { HasStencil = true; mtlDesc.stencilAttachmentPixelFormat = mtlDepthFormat; } } for (uint i = 0; i < outputs.ColorAttachments.Length; i++) { BlendAttachmentDescription attachmentBlendDesc = blendStateDesc.AttachmentStates[i]; MTLRenderPipelineColorAttachmentDescriptor colorDesc = mtlDesc.colorAttachments[i]; colorDesc.pixelFormat = MTLFormats.VdToMTLPixelFormat(outputs.ColorAttachments[i].Format, false); colorDesc.blendingEnabled = attachmentBlendDesc.BlendEnabled; colorDesc.alphaBlendOperation = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.AlphaFunction); colorDesc.sourceAlphaBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceAlphaFactor); colorDesc.destinationAlphaBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationAlphaFactor); colorDesc.rgbBlendOperation = MTLFormats.VdToMTLBlendOp(attachmentBlendDesc.ColorFunction); colorDesc.sourceRGBBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.SourceColorFactor); colorDesc.destinationRGBBlendFactor = MTLFormats.VdToMTLBlendFactor(attachmentBlendDesc.DestinationColorFactor); } RenderPipelineState = gd.Device.newRenderPipelineStateWithDescriptor(mtlDesc); ObjectiveCRuntime.release(mtlDesc.NativePtr); if (outputs.DepthAttachment != null) { MTLDepthStencilDescriptor depthDescriptor = MTLUtil.AllocInit <MTLDepthStencilDescriptor>( nameof(MTLDepthStencilDescriptor)); depthDescriptor.depthCompareFunction = MTLFormats.VdToMTLCompareFunction( description.DepthStencilState.DepthComparison); depthDescriptor.depthWriteEnabled = description.DepthStencilState.DepthWriteEnabled; bool stencilEnabled = description.DepthStencilState.StencilTestEnabled; if (stencilEnabled) { StencilReference = description.DepthStencilState.StencilReference; StencilBehaviorDescription vdFrontDesc = description.DepthStencilState.StencilFront; MTLStencilDescriptor front = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor)); front.readMask = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u; front.writeMask = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u; front.depthFailureOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.DepthFail); front.stencilFailureOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Fail); front.depthStencilPassOperation = MTLFormats.VdToMTLStencilOperation(vdFrontDesc.Pass); front.stencilCompareFunction = MTLFormats.VdToMTLCompareFunction(vdFrontDesc.Comparison); depthDescriptor.frontFaceStencil = front; StencilBehaviorDescription vdBackDesc = description.DepthStencilState.StencilBack; MTLStencilDescriptor back = MTLUtil.AllocInit <MTLStencilDescriptor>(nameof(MTLStencilDescriptor)); back.readMask = stencilEnabled ? description.DepthStencilState.StencilReadMask : 0u; back.writeMask = stencilEnabled ? description.DepthStencilState.StencilWriteMask : 0u; back.depthFailureOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.DepthFail); back.stencilFailureOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Fail); back.depthStencilPassOperation = MTLFormats.VdToMTLStencilOperation(vdBackDesc.Pass); back.stencilCompareFunction = MTLFormats.VdToMTLCompareFunction(vdBackDesc.Comparison); depthDescriptor.backFaceStencil = back; ObjectiveCRuntime.release(front.NativePtr); ObjectiveCRuntime.release(back.NativePtr); } DepthStencilState = gd.Device.newDepthStencilStateWithDescriptor(depthDescriptor); ObjectiveCRuntime.release(depthDescriptor.NativePtr); } DepthClipMode = description.DepthStencilState.DepthTestEnabled ? MTLDepthClipMode.Clip : MTLDepthClipMode.Clamp; }
public Boolean Initialize() { Debug.Assert(!this.Initialized, "Ensure not initialized"); 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() ) ); } };"; this.CompiledFX = ShaderBytecode.Compile(spriteFX, "SpriteTech", "fx_5_0"); { if (this.CompiledFX.HasErrors) { return(false); } this.Effect = new Effect(this.Device, this.CompiledFX); { this.SpriteTech = Effect.GetTechniqueByName("SpriteTech"); this.SpriteMap = Effect.GetVariableByName("SpriteTex").AsShaderResource(); using (EffectPass effectPas = this.SpriteTech.GetPassByIndex(0)) { 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) }; this.InputLayout = new InputLayout(this.Device, effectPas.Description.Signature, layoutDesc); } // Create Vertex Buffer BufferDescription vertexBufferDescription = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; this.VertexBuffer = new SharpDX.Direct3D11.Buffer(Device, vertexBufferDescription); // ToDispose() // Create and initialise Index Buffer Int16[] indicies = new Int16[3072]; for (UInt16 index = 0; index < 512; ++index) { indicies[index * 6] = (Int16)(index * 4); indicies[(index * 6) + 1] = (Int16)((index * 4) + 1); indicies[(index * 6) + 2] = (Int16)((index * 4) + 2); indicies[(index * 6) + 3] = (Int16)(index * 4); indicies[(index * 6) + 4] = (Int16)((index * 4) + 2); indicies[(index * 6) + 5] = (Int16)((index * 4) + 3); } this.IndexBuffer = new SafeHGlobal(indicies.Length * Marshal.SizeOf(indicies[0])); Marshal.Copy(indicies, 0, this.IndexBuffer.DangerousGetHandle(), indicies.Length); BufferDescription bufferDescription = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(Int16)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; this.Buffer = new SharpDX.Direct3D11.Buffer(this.Device, this.IndexBuffer.DangerousGetHandle(), bufferDescription); BlendStateDescription transparentDescription = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDescription.RenderTarget[0].IsBlendEnabled = true; transparentDescription.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDescription.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDescription.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDescription.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDescription.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDescription.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDescription.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; this.TransparentBlendState = new BlendState(Device, transparentDescription); // ToDispose() } } this.Initialized = true; return(true); }
public void BuildPSO(Device3 device, GraphicsCommandList commandList) { Projection = Matrix.PerspectiveFovLH((float)Math.PI / 3f, 4f / 3f, 1, 1000); View = Matrix.LookAtLH(new Vector3(10 * (float)Math.Sin(rotation), 5, 10 * (float)Math.Cos(rotation)), Vector3.Zero, Vector3.UnitY); World = Matrix.Translation(-2.5f, -2.5f, -2.5f); DescriptorHeapDescription cbvHeapDesc = new DescriptorHeapDescription() { DescriptorCount = 1, Flags = DescriptorHeapFlags.ShaderVisible, Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView }; _perPassViewHeap = device.CreateDescriptorHeap(cbvHeapDesc); RootParameter[] rootParameters = new RootParameter[] { new RootParameter(ShaderVisibility.All, new RootDescriptor(0, 0), RootParameterType.ConstantBufferView) }; // Create an empty root signature. RootSignatureDescription rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootParameters); _rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("Shaders/Untextured.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. InputElement[] inputElementDescs = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). GraphicsPipelineStateDescription psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = _rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D24_UNorm_S8_UInt, DepthStencilState = DepthStencilStateDescription.Default(), SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; _pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Define the geometry for a triangle. Vertex[] triangleVertices = new Vertex[] { //Front new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(0, 0, 1, 1) }, //Back new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(0, 0, 1, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(0, 0, 1, 1) }, //Left new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(0, 1, 0, 1) }, //Right new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(0, 1, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(0, 1, 0, 1) }, //Top new Vertex() { Position = new Vector3(0, 0, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(0, 0, 5), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 0, 5), Color = new Vector4(1, 0, 0, 1) }, //Bottom new Vertex() { Position = new Vector3(0, 5, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(0, 5, 5), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 0), Color = new Vector4(1, 0, 0, 1) }, new Vertex() { Position = new Vector3(5, 5, 5), Color = new Vector4(1, 0, 0, 1) } }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. _vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = _vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); _vertexBuffer.Unmap(0); _indicies = new int[] { 0, 1, 2, 3, 2, 1, 6, 5, 4, 5, 6, 7, 10, 9, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 18, 17, 16, 17, 18, 19, 20, 21, 22, 23, 22, 21 }; int indBufferSize = Utilities.SizeOf(_indicies); _indexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(indBufferSize), ResourceStates.GenericRead); IntPtr pIndBegin = _indexBuffer.Map(0); Utilities.Write(pIndBegin, _indicies, 0, _indicies.Length); _indexBuffer.Unmap(0); _indexBufferView = new IndexBufferView() { BufferLocation = _indexBuffer.GPUVirtualAddress, Format = Format.R32_UInt, SizeInBytes = indBufferSize }; // Initialize the vertex buffer view. _vertexBufferView = new VertexBufferView { BufferLocation = _vertexBuffer.GPUVirtualAddress, StrideInBytes = Utilities.SizeOf <Vertex>(), SizeInBytes = vertexBufferSize }; _perPassBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(Utilities.SizeOf <PerPass>()), ResourceStates.GenericRead); //// Describe and create a constant buffer view. ConstantBufferViewDescription cbvDesc = new ConstantBufferViewDescription() { BufferLocation = _perPassBuffer.GPUVirtualAddress, SizeInBytes = (Utilities.SizeOf <PerPass>() + 255) & ~255 }; device.CreateConstantBufferView(cbvDesc, _perPassViewHeap.CPUDescriptorHandleForHeapStart); // Initialize and map the constant buffers. We don't unmap this until the // app closes. Keeping things mapped for the lifetime of the resource is okay. _perPassPointer = _perPassBuffer.Map(0); Utilities.Write(_perPassPointer, ref buffer); _resources = new[] { new GraphicsResource() { Resource = _perPassBuffer, Register = 0, type = ResourceType.ConstantBufferView } }; }
private void LoadAssets() { // Create an empty root signature. var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout); rootSignature = device.CreateRootSignature(rootSignatureDesc.Serialize()); // Create the pipeline state, which includes compiling and loading shaders. #if DEBUG var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var vertexShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "VSMain", "vs_5_0")); #endif #if DEBUG var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug)); #else var pixelShader = new ShaderBytecode(SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile("shaders.hlsl", "PSMain", "ps_5_0")); #endif // Define the vertex input layout. var inputElementDescs = new [] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }; // Describe and create the graphics pipeline state object (PSO). var psoDesc = new GraphicsPipelineStateDescription() { InputLayout = new InputLayoutDescription(inputElementDescs), RootSignature = rootSignature, VertexShader = vertexShader, PixelShader = pixelShader, RasterizerState = RasterizerStateDescription.Default(), BlendState = BlendStateDescription.Default(), DepthStencilFormat = SharpDX.DXGI.Format.D32_Float, DepthStencilState = new DepthStencilStateDescription() { IsDepthEnabled = false, IsStencilEnabled = false }, SampleMask = int.MaxValue, PrimitiveTopologyType = PrimitiveTopologyType.Triangle, RenderTargetCount = 1, Flags = PipelineStateFlags.None, SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), StreamOutput = new StreamOutputDescription() }; psoDesc.RenderTargetFormats[0] = SharpDX.DXGI.Format.R8G8B8A8_UNorm; pipelineState = device.CreateGraphicsPipelineState(psoDesc); // Create the command list. commandList = device.CreateCommandList(CommandListType.Direct, commandAllocator, pipelineState); // Command lists are created in the recording state, but there is nothing // to record yet. The main loop expects it to be closed, so close it now. commandList.Close(); // Create the vertex buffer. float aspectRatio = viewport.Width / viewport.Height; // Define the geometry for a triangle. var triangleVertices = new [] { new Vertex() { Position = new Vector3(0.0f, 0.25f * aspectRatio, 0.0f), Color = new Vector4(1.0f, 0.0f, 0.0f, 1.0f) }, new Vertex() { Position = new Vector3(0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 1.0f, 0.0f, 1.0f) }, new Vertex() { Position = new Vector3(-0.25f, -0.25f * aspectRatio, 0.0f), Color = new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }, }; int vertexBufferSize = Utilities.SizeOf(triangleVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. vertexBuffer = device.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(vertexBufferSize), ResourceStates.GenericRead); // Copy the triangle data to the vertex buffer. IntPtr pVertexDataBegin = vertexBuffer.Map(0); Utilities.Write(pVertexDataBegin, triangleVertices, 0, triangleVertices.Length); vertexBuffer.Unmap(0); // Initialize the vertex buffer view. vertexBufferView = new VertexBufferView(); vertexBufferView.BufferLocation = vertexBuffer.GPUVirtualAddress; vertexBufferView.StrideInBytes = Utilities.SizeOf <Vertex>(); vertexBufferView.SizeInBytes = vertexBufferSize; // Create and record the bundle. bundle = device.CreateCommandList(0, CommandListType.Bundle, bundleAllocator, pipelineState); bundle.SetGraphicsRootSignature(rootSignature); bundle.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; bundle.SetVertexBuffer(0, vertexBufferView); bundle.DrawInstanced(3, 1, 0, 0); bundle.Close(); // Create synchronization objects. { fence = device.CreateFence(0, FenceFlags.None); fenceValue = 1; // Create an event handle to use for frame synchronization. fenceEvent = new AutoResetEvent(false); } }
public static void Initialize(Device device) { { var blendStateDescription = new BlendStateDescription(); blendStateDescription.RenderTargets[0].BlendEnable = false; blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; blendStateDescription.RenderTargets[1].BlendEnable = false; blendStateDescription.RenderTargets[1].RenderTargetWriteMask = ColorWriteMaskFlags.None; blendStateDescription.RenderTargets[2].BlendEnable = false; blendStateDescription.RenderTargets[2].RenderTargetWriteMask = ColorWriteMaskFlags.None; blendStateDescription.RenderTargets[3].BlendEnable = false; blendStateDescription.RenderTargets[3].RenderTargetWriteMask = ColorWriteMaskFlags.None; m_BlendStates[(int)BlendType.None] = BlendState.FromDescription(device, blendStateDescription); blendStateDescription.RenderTargets[0].BlendEnable = true; blendStateDescription.RenderTargets[0].BlendOperation = BlendOperation.Add; blendStateDescription.RenderTargets[0].BlendOperationAlpha = BlendOperation.Add; blendStateDescription.RenderTargets[0].DestinationBlend = BlendOption.One; blendStateDescription.RenderTargets[0].DestinationBlendAlpha = BlendOption.One; blendStateDescription.RenderTargets[0].SourceBlend = BlendOption.One; blendStateDescription.RenderTargets[0].SourceBlendAlpha = BlendOption.One; blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; m_BlendStates[(int)BlendType.Additive] = BlendState.FromDescription(device, blendStateDescription); } { var depthStencilStateDescription = new DepthStencilStateDescription(); depthStencilStateDescription.DepthComparison = Comparison.Always; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; depthStencilStateDescription.IsDepthEnabled = false; depthStencilStateDescription.IsStencilEnabled = false; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; m_DepthStencilStates[(int)DepthConfigurationType.NoDepth] = DepthStencilState.FromDescription(device, depthStencilStateDescription); depthStencilStateDescription.DepthComparison = Comparison.LessEqual; depthStencilStateDescription.DepthWriteMask = DepthWriteMask.All; depthStencilStateDescription.IsDepthEnabled = true; m_DepthStencilStates[(int)DepthConfigurationType.DepthWriteCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription); depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero; m_DepthStencilStates[(int)DepthConfigurationType.DepthCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription); } { var rasterizerStateDescription = new RasterizerStateDescription(); rasterizerStateDescription.DepthBias = 0; rasterizerStateDescription.DepthBiasClamp = 0; rasterizerStateDescription.FillMode = FillMode.Solid; rasterizerStateDescription.IsAntialiasedLineEnabled = false; rasterizerStateDescription.IsDepthClipEnabled = true; rasterizerStateDescription.IsMultisampleEnabled = false; rasterizerStateDescription.IsScissorEnabled = false; rasterizerStateDescription.SlopeScaledDepthBias = 0; rasterizerStateDescription.CullMode = CullMode.None; m_RasterizerStates[(int)RasterizerStateType.CullNone] = RasterizerState.FromDescription(device, rasterizerStateDescription); rasterizerStateDescription.CullMode = CullMode.Front; m_RasterizerStates[(int)RasterizerStateType.CullFront] = RasterizerState.FromDescription(device, rasterizerStateDescription); rasterizerStateDescription.CullMode = CullMode.Back; m_RasterizerStates[(int)RasterizerStateType.CullBack] = RasterizerState.FromDescription(device, rasterizerStateDescription); } }