private void RenderDots() { LoadData(); d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 103, 178)); swapChain.Present(1, PresentFlags.None); vertexBuffer = D3D11.Buffer.Create <Vector3>(d3dDevice, D3D11.BindFlags.VertexBuffer, dots.ToArray()); //Shader Code using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; LoadData(); //DRAW d3dDeviceContext.OutputMerger.SetRenderTargets(renderTargetView); d3dDeviceContext.ClearRenderTargetView(renderTargetView, new SharpDX.Color(32, 166, 178)); d3dDeviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vector3>(), 0)); d3dDeviceContext.Draw(dotsArray.Count(), 0); swapChain.Present(1, PresentFlags.None); }
private void ClearStateImpl() { NativeDeviceContext.ClearState(); for (int i = 0; i < samplerStates.Length; ++i) { samplerStates[i] = null; } for (int i = 0; i < constantBuffers.Length; ++i) { constantBuffers[i] = null; } for (int i = 0; i < unorderedAccessViews.Length; ++i) { unorderedAccessViews[i] = null; } for (int i = 0; i < currentRenderTargetViews.Length; i++) { currentRenderTargetViews[i] = null; } currentEffectInputSignature = null; currentVertexArrayLayout = null; currentInputLayout = null; currentVertexArrayObject = null; CurrentEffect = null; }
private void BuildVertexLayout() { var vertexDesc = VertexPN.GetVertexDescription(); var passDesc = _tech.GetPassByIndex(0).Description; _inputLayout = new D3D11.InputLayout(Device, passDesc.Signature, vertexDesc); }
public IShader LoadVS(string path, Type constantsType = null) { using (var cr = ShaderBytecode.CompileFromFile(path, "main", "vs_5_0", DEBUG_FLAG)) { if (cr.Bytecode == null) { throw new Exception(cr.Message); } var gpuShader = new D3D11.VertexShader(Graphics.Device, cr); var inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new D3D11.InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }; var inputSignature = ShaderSignature.GetInputSignature(cr); var inputLayout = new D3D11.InputLayout(Graphics.Device, inputSignature, inputElements); var shader = new SharpDXShader(Graphics, gpuShader, inputLayout, constantsType); m_Shaders.Add(shader); return(shader); } }
public PhysicsDebugDraw(DeviceManager manager) { device = manager.Direct3DDevice; inputAssembler = device.ImmediateContext.InputAssembler; lineArray = new PositionColored[0]; using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "VSMain", "vs_5_0")) { vertexShader = new VertexShader(device, bc); InputElement[] elements = new InputElement[] { new InputElement("SV_POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; inputLayout = new InputLayout(device, bc, elements); } vertexBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); using (var bc = HLSLCompiler.CompileFromFile(@"Shaders\PhysicsDebug.hlsl", "PSMain", "ps_5_0")) pixelShader = new PixelShader(device, bc); }
public static void BuildAndBindShaders() { D3D11.InputElement[] inputElements = { new D3D11.InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, D3D11.InputClassification.PerVertexData, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32_Float, 12, 0, D3D11.InputClassification.PerVertexData, 0) }; using (var byteCode = ShaderBytecode.CompileFromFile("vertex.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { _inputSignature = ShaderSignature.GetInputOutputSignature(byteCode); _inputLayout = new D3D11.InputLayout(_d3dDevice, _inputSignature, inputElements); _d3dDeviceContext.InputAssembler.InputLayout = _inputLayout; _vertexShader = new D3D11.VertexShader(_d3dDevice, byteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixel.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { _pixelShader = new D3D11.PixelShader(_d3dDevice, pixelShaderByteCode); } _d3dDeviceContext.VertexShader.Set(_vertexShader); _d3dDeviceContext.PixelShader.Set(_pixelShader); _d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; }
internal void Clear() { m_deviceContext.ClearState(); m_inputLayout = null; m_primitiveTopology = PrimitiveTopology.Undefined; m_indexBufferRef = null; m_indexBufferFormat = 0; m_indexBufferOffset = 0; for (int i = 0; i < m_vertexBuffers.Length; i++) m_vertexBuffers[i] = null; for (int i = 0; i < m_vertexBuffersStrides.Length; i++) m_vertexBuffersStrides[i] = 0; m_blendState = null; m_stencilRef = 0; m_depthStencilState = null; m_rtvsCount = 0; for (int i = 0; i < m_rtvs.Length; i++) m_rtvs[i] = null; m_dsv = null; m_rasterizerState = null; m_scissorLeftTop = new Vector2I(-1, -1); m_scissorRightBottom = new Vector2I(-1, -1); m_viewport = default(RawViewportF); m_targetBuffer = null; m_targetOffsets = 0; m_statistics.ClearStates++; }
private void InitializeShaders() { // Compile the vertex shader code using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { // Read input signature from shader code inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); } // Compile the pixel shader code using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } // Set as current vertex and pixel shaders d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; // Create the input layout from the input signature and the input elements inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); // Set input layout to use d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { D3D11.InputLayout layout = Interlocked.Exchange(ref _d3DInputLayout, null); layout?.Dispose(); this.UnregisterDisposable(Graphics); }
protected virtual void Dispose(bool disposing) { if (disposing) { Graphics = null; if (ConstantBuffer != null) { ConstantBuffer.Dispose(); ConstantBuffer = null; } if (InputLayout != null) { InputLayout.Dispose(); InputLayout = null; } if (Shader != null) { Shader.Dispose(); Shader = null; } } }
private void InitScene() { D3D11.InputElement[] inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0) }; using (CompilationResult vsResult = ShaderBytecode.CompileFromFile("vs.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { vs = new D3D11.VertexShader(device, vsResult.Bytecode.Data); vertLayout = new D3D11.InputLayout(device, vsResult.Bytecode, inputElements); } using (CompilationResult psResult = ShaderBytecode.CompileFromFile("ps.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) ps = new D3D11.PixelShader(device, psResult.Bytecode.Data); deviceContext.VertexShader.Set(vs); deviceContext.PixelShader.Set(ps); verts = new RawVector3[] { new RawVector3(0.0f, 0.5f, 0.5f), new RawVector3(0.5f, -0.5f, 0.5f), new RawVector3(-0.5f, -0.5f, 0.5f) }; vertBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.VertexBuffer, verts); deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertBuffer, Utilities.SizeOf <RawVector3>(), 0)); deviceContext.InputAssembler.InputLayout = vertLayout; deviceContext.InputAssembler.PrimitiveTopology = D3D.PrimitiveTopology.TriangleList; }
public void Initialize(Device Device) { _shaderSolution=ROD_core.ShaderBinding.GetCompatibleShader(this); layout = new InputLayout(Device, _shaderSolution.shaders_bytecode[Shaders.VertexShader], mesh._vertexStream.vertexDefinition.GetInputElements()); mesh.Load(Device); material.LoadTextures(Device); sampler = new SamplerState(Device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = new SharpDX.Color4(0,0,0,1), ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = -float.MaxValue, MaximumLod = float.MaxValue }); List<Shaders> actual_shaders = (from sh in _shaderSolution.shaders_bytecode select sh.Key).ToList<Shaders>(); foreach (Shaders sh in actual_shaders) { ShaderReflection _shaderReflection = new ShaderReflection(_shaderSolution.shaders_bytecode[sh]); int buffers_count = _shaderReflection.Description.ConstantBuffers; SharpDX.Direct3D11.Buffer[] _buffers = new SharpDX.Direct3D11.Buffer[buffers_count]; for (int i = 0; i < buffers_count; i++) { ConstantBuffer cb_buffer = _shaderReflection.GetConstantBuffer(i); _buffers[i] = new SharpDX.Direct3D11.Buffer(Device, cb_buffer.Description.Size, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); } _shaderSolution.shaders_buffers[sh] = _buffers; } }
private void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile( Path.Combine(Properties.Resources.ShadersFolder, "vertexShader.hlsl"), "main", "vs_5_0", ShaderFlags.Debug)) { _inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); _vertexShader = new D3D11.VertexShader(_d3DDevice, vertexShaderByteCode.Bytecode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile( Path.Combine(Properties.Resources.ShadersFolder, "pixelShader.hlsl"), "main", "ps_5_0", ShaderFlags.Debug)) { _pixelShader = new D3D11.PixelShader(_d3DDevice, pixelShaderByteCode); } // Set as current vertex and pixel shaders _d3DDeviceContext.VertexShader.Set(_vertexShader); _d3DDeviceContext.PixelShader.Set(_pixelShader); _d3DDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; _inputLayout = new D3D11.InputLayout(_d3DDevice, _inputSignature, _inputElements); _d3DDeviceContext.InputAssembler.InputLayout = _inputLayout; }
public static void InitializeAll(Device device) { EffectPassDescription? passDesc; var e1 = EffectManager11.Instance.GetEffect<BasicEffect11>(); passDesc = e1?.Light1Tech?.GetPassByIndex(0)?.Description; try { if (passDesc?.Signature != null) { _posNorm = new InputLayout(device, passDesc.Value.Signature, InputLayoutDescriptions.PosNorm); } } catch (SharpDXException ex) { Debug.Print(ex.Message); } try { if (passDesc?.Signature != null) { _posNormTex = new InputLayout(device, passDesc.Value.Signature, InputLayoutDescriptions.PosNormTex); } } catch (SharpDXException ex) { Debug.Print(ex.Message); } var e2 = EffectManager11.Instance.GetEffect<SkyboxEffect11>(); passDesc = e2?.SkyTech?.GetPassByIndex(0)?.Description; if (passDesc?.Signature != null) { _pos = new InputLayout(device, passDesc.Value.Signature, InputLayoutDescriptions.Pos); } var e3 = EffectManager11.Instance.GetEffect<NormalMapEffect11>(); passDesc = e3?.Light1Tech?.GetPassByIndex(0)?.Description; if (passDesc?.Signature != null) { _posNormTexTan = new InputLayout(device, passDesc.Value.Signature, InputLayoutDescriptions.PosNormTexTan); } var e4 = EffectManager11.Instance.GetEffect<FireParticleEffect11>(); passDesc = e4?.StreamOutTech?.GetPassByIndex(0)?.Description; if (passDesc?.Signature != null) { _particle = new InputLayout(device, passDesc.Value.Signature, InputLayoutDescriptions.Particle); } }
public MeshFactory(SharpDX11Graphics graphics) { this.device = graphics.Device; this.inputAssembler = device.ImmediateContext.InputAssembler; this.demo = graphics.Demo; instanceDataDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }; InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("WORLD", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 64, 1, InputClassification.PerInstanceData, 1) }; inputLayout = new InputLayout(device, graphics.GetEffectPass().Description.Signature, elements); groundColor = ColorToUint(Color.Green); activeColor = ColorToUint(Color.Orange); passiveColor = ColorToUint(Color.OrangeRed); softBodyColor = ColorToUint(Color.LightBlue); }
private void InitializeShaders() { ConstantBuffer data = new ConstantBuffer(); data.worldViewProjectionMatrix = Matrix.Identity; data.worldMatrix = Matrix.Identity; data.viewProjectionMatrix = Matrix.Identity; data.time = 0.0f; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\MainVS.hlsl", "main", "vs_5_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, include: new StreamInclude())) { Debug.Assert(vertexShaderByteCode.Bytecode != null, vertexShaderByteCode.Message); mainVertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\MainPS.hlsl", "main", "ps_5_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, include: new StreamInclude())) { Debug.Assert(pixelShaderByteCode.Bytecode != null, pixelShaderByteCode.Message); mainPixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
/// <summary> /// Function to convert this input layout into a Direct3D input layout. /// </summary> /// <param name="device">Direct 3D device object.</param> /// <returns>The Direct 3D 11 input layout.</returns> internal D3D.InputLayout Convert(D3D.Device device) { if (D3DLayout != null) { return(D3DLayout); } // If the shader that's linked to this layout is gone, then don't bother with a new layout object. if (Shader.D3DByteCode == null) { return(null); } var elements = new D3D.InputElement[_elements.Length]; for (int i = 0; i < elements.Length; i++) { elements[i] = _elements[i].Convert(); } D3DLayout = new D3D.InputLayout(device, Shader.D3DByteCode, elements) { DebugName = "Gorgon Input Layout '" + Name + "'" }; return(D3DLayout); }
protected override void InitEffects() { var custom = renderTechniquesManager.RenderTechniques["RenderCustom"]; var lines = renderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Lines]; var points = renderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Points]; var text = renderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.BillboardText]; var blinn = renderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Blinn]; RegisterEffect(Properties.Resources._custom, new[] { custom, lines, points, text, blinn}); var customInputLayout = new InputLayout(device, GetEffect(custom).GetTechniqueByName("RenderCustom").GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, InputElement.AppendAligned, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, InputElement.AppendAligned, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, InputElement.AppendAligned, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 1, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), //INSTANCING: die 4 texcoords sind die matrix, die mit jedem buffer reinwandern new InputElement("TEXCOORD", 1, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 2, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 3, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 4, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), }); RegisterLayout(new[] { custom, lines, points, text, blinn}, customInputLayout); var linesInputLayout = new InputLayout(device, GetEffect(lines).GetTechniqueByName(DefaultRenderTechniqueNames.Lines).GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 1, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), //INSTANCING: die 4 texcoords sind die matrix, die mit jedem buffer reinwandern new InputElement("TEXCOORD", 1, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 2, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 3, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("TEXCOORD", 4, Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), }); RegisterLayout(new[]{lines},linesInputLayout); var pointsInputLayout = new InputLayout(device, GetEffect(points).GetTechniqueByName(DefaultRenderTechniqueNames.Points).GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 1, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), }); RegisterLayout(new[] { points }, pointsInputLayout); var textInputLayout = new InputLayout(device, GetEffect(text).GetTechniqueByName(DefaultRenderTechniqueNames.BillboardText).GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0), }); RegisterLayout(new[] { text }, textInputLayout); }
public RenderTechnique(string name, Effect effect, InputLayout layout) { this.Name = name; this.Device = effect.Device; this.Effect = effect; this.EffectTechnique = effect.GetTechniqueByName(this.Name); this.InputLayout = layout; }
public ProjectiveTexturingShader(Device device) { var shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndProjectiveTextureVS.cso")); vertexShader = new VertexShader(device, shaderByteCode); geometryShader = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso"))); pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorPS.cso"))); // depth stencil state var depthStencilStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.LessEqual, IsStencilEnabled = false, }; depthStencilState = new DepthStencilState(device, depthStencilStateDesc); // rasterizer states var rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsDepthClipEnabled = true, IsFrontCounterClockwise = true, IsMultisampleEnabled = true, }; rasterizerState = new RasterizerState(device, rasterizerStateDesc); // constant buffer var constantBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, SizeInBytes = Constants.size, CpuAccessFlags = CpuAccessFlags.Write, StructureByteStride = 0, OptionFlags = 0, }; constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc); // user view sampler state var colorSamplerStateDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Border, AddressV = TextureAddressMode.Border, AddressW = TextureAddressMode.Border, //BorderColor = new SharpDX.Color4(0.5f, 0.5f, 0.5f, 1.0f), BorderColor = new SharpDX.Color4(0, 0, 0, 1.0f), }; colorSamplerState = new SamplerState(device, colorSamplerStateDesc); vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[] { new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0), }); }
internal void SetInputLayout(InputLayout il) { if (il == m_inputLayout) return; m_inputLayout = il; m_deviceContext.InputAssembler.InputLayout = il; m_statistics.SetInputLayout++; }
public VanillaInputLayout(ShaderAsset shader) { InputLayout = new InputLayout(shader.Device, shader.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, 48, 0), }); }
/// <summary> /// Renders this GeometryResource. /// </summary> /// <param name="renderState">Current render state.</param> public void Render(RenderState renderState) { D3D11.DeviceContext deviceContext = renderState.Device.DeviceImmediateContextD3D11; DXGI.Format indexBufferFormat = renderState.Device.SupportsOnly16BitIndexBuffer ? DXGI.Format.R16_UInt : DXGI.Format.R32_UInt; int lastVertexBufferID = -1; int lastIndexBufferID = -1; for (int loop = 0; loop < m_loadedStructures.Length; loop++) { LoadedStructureInfo structureToDraw = m_loadedStructures[loop]; // Apply VertexBuffer if (lastVertexBufferID != structureToDraw.VertexBufferID) { lastVertexBufferID = structureToDraw.VertexBufferID; deviceContext.InputAssembler.InputLayout = structureToDraw.InputLayout; deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(structureToDraw.VertexBuffer, structureToDraw.SizePerVertex, 0)); } // Apply IndexBuffer if (lastIndexBufferID != structureToDraw.IndexBufferID) { deviceContext.InputAssembler.SetIndexBuffer(structureToDraw.IndexBuffer, indexBufferFormat, 0); } // Apply material renderState.ApplyMaterial(structureToDraw.Material); D3D11.InputLayout newInputLayout = null; if (renderState.ForcedMaterial != null) { newInputLayout = renderState.ForcedMaterial.GenerateInputLayout( renderState.Device, StandardVertex.InputElements, MaterialApplyInstancingMode.SingleObject); deviceContext.InputAssembler.InputLayout = newInputLayout; } try { // Draw current rener block deviceContext.DrawIndexed( structureToDraw.IndexCount, structureToDraw.StartIndex, 0); } finally { if (newInputLayout != null) { deviceContext.InputAssembler.InputLayout = null; GraphicsHelper.SafeDispose(ref newInputLayout); } } } }
public Style(String vertexShaderFilename, String pixelShaderFilename, InputElement[] layoutElements, int floatsPerVertex, DeviceManager deviceManager) { var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; // Read pre-compiled shader byte code relative to current directory var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\" + vertexShaderFilename); this.pixelShader = new PixelShader(deviceManager.DeviceDirect3D, NativeFile.ReadAllBytes(path + "\\" + pixelShaderFilename)); this.vertexShader = new VertexShader(deviceManager.DeviceDirect3D, vertexShaderByteCode); // Specify the input layout for the new style this.layout = new InputLayout(deviceManager.DeviceDirect3D, vertexShaderByteCode, layoutElements); this.floatsPerVertex = floatsPerVertex; }
public override Effect Init(EffectDescription description) { base.Init(description); var mode = _demo.SetupModel.Mode; _greetingsRenderTarget = _disposer.Add(new RenderTarget( device: _demo.Device, width: mode.Width, // TODO(mstrandh): Honor setupmodel? height: mode.Height, // TODO(mstrandh): Honor setupmodel? sampleCount: 1, // TODO(mstrandh): Honor setupmodel? sampleQuality: 0, // TODO(mstrandh): Honor setupmodel? format: Format.R8G8B8A8_UNorm // TODO(mstrandh): Honor setupmodel? )); CreateCylinderBuffers(); var texture = _textures[0]; _textureHeight = texture.Texture.Description.Height; _tubeVertexShader = _demo.ShaderManager["greetingsTube.vs.cso"]; _tubePixelShader = _demo.ShaderManager["greetingsTube.ps.cso"]; _tubeInputLayout = _disposer.Add(new InputLayout(_demo.Device, _tubeVertexShader.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0), })); _greetingsTexture = _resourceViews[0]; _renderedCylinderTexture = _greetingsRenderTarget.ShaderResourceView; // Create the depth buffer var depthBuffer = _disposer.Add(new Texture2D(_demo.Device, new Texture2DDescription { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = mode.Width, Height = mode.Height, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None })); // Create the depth buffer view _greetingsDepthView = _disposer.Add(new DepthStencilView(_demo.Device, depthBuffer)); return this; }
internal unsafe void RecordCommands(MyRenderableProxy proxy, MyFoliageStream stream, int voxelMatId, VertexShader vertexShader, InputLayout inputLayout, int materialIndex, int indexCount, int startIndex, int baseVertex) { if (stream.m_stream == VertexBufferId.NULL) return; //var worldMatrix = proxy.WorldMatrix; //worldMatrix.Translation = Vector3D.Zero; //MyObjectData objectData = proxy.ObjectData; //objectData.LocalMatrix = Matrix.Identity; var worldMat = proxy.WorldMatrix; //worldMat.Translation -= MyRender11.Environment.CameraPosition; MyObjectDataCommon objectData = proxy.CommonObjectData; objectData.LocalMatrix = worldMat; MyMapping mapping = MyMapping.MapDiscard(RC, proxy.ObjectBuffer); mapping.WriteAndPosition(ref proxy.VoxelCommonObjectData); mapping.WriteAndPosition(ref objectData); mapping.Unmap(); RC.AllShaderStages.SetConstantBuffer(MyCommon.OBJECT_SLOT, proxy.ObjectBuffer); BindProxyGeometry(proxy, RC); RC.VertexShader.Set(vertexShader); RC.SetInputLayout(inputLayout); int offset = -1; if (!stream.Append) { offset = 0; stream.Append = true; } RC.SetTarget(stream.m_stream.Buffer, offset); RC.AllShaderStages.SetConstantBuffer(MyCommon.FOLIAGE_SLOT, MyCommon.FoliageConstants); float densityFactor = MyVoxelMaterials1.Table[voxelMatId].FoliageDensity * MyRender11.Settings.GrassDensityFactor; float zero = 0; mapping = MyMapping.MapDiscard(RC, MyCommon.FoliageConstants); mapping.WriteAndPosition(ref densityFactor); mapping.WriteAndPosition(ref materialIndex); mapping.WriteAndPosition(ref voxelMatId); mapping.WriteAndPosition(ref zero); mapping.Unmap(); RC.DrawIndexed(indexCount, startIndex, baseVertex); }
private void InitializeEffect() { var vsBytecode = ShaderBytecode.CompileFromFile(string.Format(@"Content\{0}", FileName), "VS_Main", "vs_5_0"); var psBytecode = ShaderBytecode.CompileFromFile(string.Format(@"Content\{0}", FileName), "PS_Main", "ps_5_0"); _pixelShader = new PixelShader(_myGame.GraphicsDevice, psBytecode); _vertexShader = new VertexShader(_myGame.GraphicsDevice, vsBytecode); _layout = new InputLayout(_myGame.GraphicsDevice, ShaderSignature.GetInputSignature(vsBytecode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0) }); }
/*------------------------------------- * CONSTRUCTORS *-----------------------------------*/ public SharpDXShader(SharpDXGraphicsMgr graphics, D3D11.DeviceChild shader, D3D11.InputLayout inputLayout, Type constantsType) { Graphics = graphics; InputLayout = inputLayout; Shader = shader; if (constantsType != null) { ConstantBuffer = CreateConstantBuffer(constantsType); } }
void CreateResources() { // If we have a shader signature, we can store the input layout directly if (EffectInputSignature != null) { InputLayout = GraphicsDevice.InputLayoutManager.GetInputLayout(EffectInputSignature, Layout); } nativeVertexBufferBindings = vertexBufferBindings.Select(x => new SharpDX.Direct3D11.VertexBufferBinding(x.Buffer.NativeBuffer, x.Stride, x.Offset)).ToArray(); if (indexBufferBinding != null) { nativeIndexBuffer = indexBufferBinding.Buffer.NativeBuffer; } }
/// <summary> /// Function to convert this input layout into a Direct3D input layout. /// </summary> private void BuildD3DLayout() { // ReSharper disable once InconsistentNaming var d3dElements = new D3D11.InputElement[_elements.Length]; for (int i = 0; i < _elements.Length; ++i) { d3dElements[i] = _elements[i].D3DInputElement; } _d3DInputLayout = new D3D11.InputLayout(Graphics.D3DDevice, Shader.D3DByteCode.Data, d3dElements) { DebugName = $"{Name} Direct 3D 11 Input Layout" }; }
private void InitializeSharedComponents() { inputLayout = new D3D11.InputLayout(d3dDevice, shaderInputSigVsQuad, shaderInputElements); samplerState = new D3D11.SamplerState(d3dDevice, new D3D11.SamplerStateDescription { AddressU = D3D11.TextureAddressMode.Wrap, AddressV = D3D11.TextureAddressMode.Wrap, AddressW = D3D11.TextureAddressMode.Wrap, MinimumLod = 0, MipLodBias = 0.0f, MaximumLod = float.MaxValue, BorderColor = new SharpDX.Mathematics.Interop.RawColor4(0.0f, 0.0f, 0.0f, 0.0f), Filter = D3D11.Filter.MinMagMipLinear, }); }
public ColorShader(Device device) { var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "ColorVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "ColorPixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); VertexShader = new VertexShader(device, vertexShaderByteCode); PixelShader = new PixelShader(device, pixelShaderByteCode); var inputElements = new InputElement[] { new InputElement { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = ColorShader.Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, // Updated each frame SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), // Contains three matrices BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); }
/// <summary> /// Loads the resource. /// </summary> protected override void LoadResourceInternal(EngineDevice device, ResourceDictionary resources) { m_vertexShader = resources.GetResourceAndEnsureLoaded( KEY_VERTEX_SHADER, () => GraphicsHelper.GetVertexShaderResource(device, "LineRendering", "LineVertexShader")); m_pixelShader = resources.GetResourceAndEnsureLoaded( KEY_PIXEL_SHADER, () => GraphicsHelper.GetPixelShaderResource(device, "LineRendering", "LinePixelShader")); m_constantBuffer = resources.GetResourceAndEnsureLoaded( KEY_CONSTANT_BUFFER, () => new TypeSafeConstantBufferResource <ConstantBufferData>()); m_inputLayout = new D3D11.InputLayout( device.DeviceD3D11_1, m_vertexShader.ShaderBytecode, LineVertex.InputElements); }
public static InputLayout GetLayout(GxContext context, InputElement[] elements, Mesh mesh, ShaderProgram program) { Dictionary<ShaderProgram, InputLayout> meshEntry; InputLayout layout; if (Layouts.TryGetValue(mesh, out meshEntry)) { if (meshEntry.TryGetValue(program, out layout)) return layout; layout = new InputLayout(context.Device, program.VertexShaderCode.Data, elements); meshEntry.Add(program, layout); return layout; } bool hasInstance = false, hasVertex = false; for(var i = 0; i < elements.Length; ++i) { if (hasInstance && hasVertex) break; if(elements[i].Classification == InputClassification.PerInstanceData && hasInstance == false) { elements[i].AlignedByteOffset = 0; hasInstance = true; continue; } if(elements[i].Classification == InputClassification.PerVertexData && hasVertex == false) { elements[i].AlignedByteOffset = 0; hasVertex = true; } } layout = new InputLayout(context.Device, program.VertexShaderCode.Data, elements); meshEntry = new Dictionary<ShaderProgram, InputLayout>() { {program, layout} }; Layouts.Add(mesh, meshEntry); return layout; }
public void Compile() { // Compilo Vertex y Pixel Shaders CompilationResult vertexShaderBytecode = ShaderBytecode.CompileFromFile(_path, _vertexShaderEntryPoint, "vs_4_0", ShaderFlags.None, EffectFlags.None); CompilationResult pixelShaderBytecode = ShaderBytecode.CompileFromFile(_path, _pixelShaderEntryPoint, "ps_4_0", ShaderFlags.None, EffectFlags.None); _vertexShader = new VertexShader(GraphicManager.Device, vertexShaderBytecode); _pixelShader = new PixelShader(GraphicManager.Device, pixelShaderBytecode); Layout = new InputLayout(GraphicManager.Device, ShaderSignature.GetInputSignature(vertexShaderBytecode), VertexDescription.PosNormVertexInput); vertexShaderBytecode.Dispose(); pixelShaderBytecode.Dispose(); _compiled = true; }
protected void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0", ShaderFlags.Debug)) { InputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); VertexShader = new Direct3D11.VertexShader(GameDevice, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0", ShaderFlags.Debug)) { PixelShader = new Direct3D11.PixelShader(GameDevice, pixelShaderByteCode); } DeviceContext.VertexShader.Set(VertexShader); DeviceContext.PixelShader.Set(PixelShader); InputLayoutMain = new InputLayout(GameDevice, InputSignature, inputElements); DeviceContext.InputAssembler.InputLayout = InputLayoutMain; }
public static void Init(SharpDX.Direct3D11.Device device) { vertexShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/VertexShader.hlsl", "vertex", "vs_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null); vertexShader = new VertexShader(device, vertexShaderByteCode, null); vertices = SharpDX.Direct3D11.Buffer.Create<Vertex>(device, BindFlags.VertexBuffer, new Vertex[] { new Vertex(new Vector4(-1f, -1f, 0.5f, 1f), new Vector2(0f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)), new Vertex(new Vector4(-1f, 1f, 0.5f, 1f), new Vector2(0f, 0f)), new Vertex(new Vector4(1f, 1f, 0.5f, 1f), new Vector2(1f, 0f)), new Vertex(new Vector4(1f, -1f, 0.5f, 1f), new Vector2(1f, 1f)) }, 144, ResourceUsage.Default, CpuAccessFlags.None, ResourceOptionFlags.None, 0); layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), Vertex.elements); binding = new VertexBufferBinding(vertices, 24, 0); buffer = new SharpDX.Direct3D11.Buffer(device, 64, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); data.offset = 0f; data.scale = 1f; }
public Shader(Device device, string shaderFile, string vertexTarget, string pixelTraget, InputElement[] layouts) { var shaderString = ShaderBytecode.PreprocessFromFile(shaderFile); using (var bytecode = ShaderBytecode.Compile(shaderString, vertexTarget, "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), layouts); vertShader = new VertexShader(device, bytecode); } using (var bytecode = ShaderBytecode.Compile(shaderString, pixelTraget, "ps_4_0")) { pixShader = new PixelShader(device, bytecode); } OnCleanup += vertShader.Dispose; OnCleanup += pixShader.Dispose; OnCleanup += layout.Dispose; }
private void ReleaseDevice() { // Display D3D11 ref counting info ClearState(); NativeDevice.ImmediateContext.Flush(); NativeDevice.ImmediateContext.Dispose(); if (IsDebugMode) { var deviceDebug = new DeviceDebug(NativeDevice); deviceDebug.ReportLiveDeviceObjects(ReportingLevel.Detail); } currentInputLayout = null; currentEffectInputSignature = null; currentVertexArrayObject = null; currentVertexArrayLayout = null; nativeDevice.Dispose(); }
private void InitializeShaders() { using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("vertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("pixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode); } d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
private void InitializeShader() { //creating shaderbytecode from a file and using it for initializing shader (data, start methode, version to use, flag) using (var vertextShaderByteCode = ShaderBytecode.CompileFromFile("Shader/standardVertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { //get the signature for the input inputSignature = ShaderSignature.GetInputSignature(vertextShaderByteCode); //creating a vertex shader for the device vertexShader = new D3D11.VertexShader(device, vertextShaderByteCode); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shader/standardPixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { //creating a pixel shader for the device pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } //creating the Input Layout (device, signature, inputElements) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); //set the device, to use the shader deviceContext.VertexShader.Set(vertexShader); deviceContext.PixelShader.Set(pixelShader); //set the primitive topology (how to treat the input) deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; //set the device to use the input Layout deviceContext.InputAssembler.InputLayout = inputLayout; deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, Utilities.SizeOf <Vertex>(), 0)); float ratio = (float)Size.X / (float)Size.Y; Matrix ratioMatrix = new Matrix(1 / ratio, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); ratioBuffer = D3D11.Buffer.Create <Matrix>(device, D3D11.BindFlags.ConstantBuffer, ref ratioMatrix); deviceContext.VertexShader.SetConstantBuffer(0, ratioBuffer); Matrix invCamara = camara.GetInvertedCamaraPosition(); camaraBuffer = D3D11.Buffer.Create <Matrix>(device, D3D11.BindFlags.ConstantBuffer, ref invCamara); deviceContext.VertexShader.SetConstantBuffer(1, camaraBuffer); }
void InitializeShaders() { using (var vertexShaderByteCode = D3DCompiler.ShaderBytecode.CompileFromFile("../../src/vertexShader.hlsl", "main", "vs_4_0", D3DCompiler.ShaderFlags.Debug)) { m_inputSignature = D3DCompiler.ShaderSignature.GetInputOutputSignature(vertexShaderByteCode); m_vertexShader = new D3D11.VertexShader(m_d3d11Device, vertexShaderByteCode); } using (var pixelShaderByteCode = D3DCompiler.ShaderBytecode.CompileFromFile("../../src/pixelShader.hlsl", "main", "ps_4_0", D3DCompiler.ShaderFlags.Debug)) { m_pixelShader = new D3D11.PixelShader(m_d3d11Device, pixelShaderByteCode); } m_d3d11DeviceContext.VertexShader.Set(m_vertexShader); m_d3d11DeviceContext.PixelShader.Set(m_pixelShader); m_d3d11DeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; m_inputLayout = new D3D11.InputLayout(m_d3d11Device, m_inputSignature, m_inputElments); m_d3d11DeviceContext.InputAssembler.InputLayout = m_inputLayout; }
public PhysicsDebugDraw(SharpDX11Graphics graphics) { _device = graphics.Device; _inputAssembler = _device.ImmediateContext.InputAssembler; InputElement[] elements = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, graphics.GetDebugDrawPass().Description.Signature, elements); _vertexBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; _vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); }
/// <summary> /// Binds the effect shader to the specified <see cref="Device"/>. /// </summary> /// <param name="device">The device to bind the shader to.</param> /// <returns>If the binding was successful.</returns> public bool Initialize(Device device) { try { matrixBuffer = new Buffer(device, Matrix.SizeInBytes * 3, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0) {DebugName = "Matrix buffer"}; using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Texture.vs", "TextureVertexShader", "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), TextureDrawingVertex.VertexDeclaration) { DebugName = "Color vertex layout" }; vertexShader = new VertexShader(device, bytecode) { DebugName = "Texture vertex shader" }; } using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Texture.ps", "TexturePixelShader", "ps_4_0")) { pixelShader = new PixelShader(device, bytecode) { DebugName = "Texture pixel shader" }; } var samplerDesc = new SamplerStateDescription { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.ComparisonMinMagMipLinear, MaximumAnisotropy = 1, MipLodBias = 0f, MinimumLod = 0, MaximumLod = float.MaxValue, BorderColor = Color.LimeGreen, ComparisonFunction = Comparison.Always }; pixelSampler = new SamplerState(device, samplerDesc); texture = new Texture(); return texture.Initialize(device, "Textures/dirt.dds"); } catch (Exception e) { MessageBox.Show("Shader error: " + e.Message); return false; } }
void InitializeDevice() { // Create Direct3D 11 Device without SwapChain device = new D3D11.Device(DriverType.Hardware, D3D11.DeviceCreationFlags.BgraSupport); deviceContext = device.ImmediateContext; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new D3D11.InputLayout( device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new D3D11.InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = D3D11.Buffer.Create(device, D3D11.BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages deviceContext.InputAssembler.InputLayout = layout; deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertices, 32, 0)); deviceContext.VertexShader.Set(vertexShader); deviceContext.PixelShader.Set(pixelShader); }
private void InitializeShaders() { ConstantBufferCPU data = new ConstantBufferCPU(); data.worldViewProjectionMatrix = Matrix.Identity; data.time = 0.0f; data.padding = Vector3.Zero; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); string textVS = System.IO.File.ReadAllText("Shaders\\MainVS.hlsl"); using (var vertexShaderByteCode = ShaderBytecode.Compile(textVS, "main", "vs_4_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, EffectFlags.None, null, new StreamInclude(), sourceFileName: "Shaders\\MainVS.hlsl")) { if (vertexShaderByteCode.Bytecode == null) { MessageBox.Show(vertexShaderByteCode.Message, "Shader Compilation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(-1); } vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } string textPS = System.IO.File.ReadAllText("Shaders\\MainPS.hlsl"); using (var pixelShaderByteCode = ShaderBytecode.Compile(textPS, "main", "ps_4_0", ShaderFlags.Debug | ShaderFlags.WarningsAreErrors, EffectFlags.None, null, new StreamInclude(), sourceFileName: "Shaders\\MainPS.hlsl")) { if (pixelShaderByteCode.Bytecode == null) { MessageBox.Show(pixelShaderByteCode.Message, "Shader Compilation Error", MessageBoxButtons.OK, MessageBoxIcon.Error); System.Environment.Exit(-1); } pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
public Shader(string file, D3D11.Device device, D3D11.DeviceContext context, params D3D11.InputElement[] inputElements) { if (File.Exists(file + "_vs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_vs.cso")) { Signature = ShaderSignature.GetInputSignature(byteCode); VertexShader = new D3D11.VertexShader(device, byteCode); InputLayout = new D3D11.InputLayout(device, Signature, inputElements); } } if (File.Exists(file + "_ps.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_ps.cso")) PixelShader = new D3D11.PixelShader(device, byteCode); } if (File.Exists(file + "_gs.cso")) { using (var byteCode = ShaderBytecode.FromFile(file + "_gs.cso")) GeometryShader = new D3D11.GeometryShader(device, byteCode); } }
private void InitializeShaders() { using (var vertexShaderCode = ShaderBytecode.CompileFromFile("vertex_shader.hlsl", "main", "vs_4_0", ShaderFlags.Debug)) { inputSignature = ShaderSignature.GetInputSignature(vertexShaderCode); vertexShader = new D3D11.VertexShader(d3dDevice, vertexShaderCode); } using (var pixelShaderCode = ShaderBytecode.CompileFromFile("pixel_shader.hlsl", "main", "ps_4_0", ShaderFlags.Debug)) { pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderCode); } constantBuffer = new D3D11.Buffer(d3dDevice, Utilities.SizeOf <VertexShaderConstants>(), D3D11.ResourceUsage.Default, D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0); d3dDeviceContext.VertexShader.SetConstantBuffer(0, constantBuffer); d3dDeviceContext.VertexShader.Set(vertexShader); d3dDeviceContext.PixelShader.Set(pixelShader); d3dDeviceContext.PixelShader.SetShaderResource(0, textureView); d3dDeviceContext.PixelShader.SetSampler(0, samplerState); d3dDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements); d3dDeviceContext.InputAssembler.InputLayout = inputLayout; }
private void InitializeShaders() { ConstantBuffer data = new ConstantBuffer(); data.parameters = Vector4.Zero; constantBuffer = D3D11.Buffer.Create(device, D3D11.BindFlags.ConstantBuffer, ref data); using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\PostEffectVS.hlsl", "main", "vs_5_0", ShaderFlags.Debug, include: new StreamInclude())) { Debug.Assert(vertexShaderByteCode.Bytecode != null, vertexShaderByteCode.Message); vertexShader = new D3D11.VertexShader(device, vertexShaderByteCode); using (var inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode)) inputLayout = new D3D11.InputLayout(device, inputSignature, inputElements); } using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders\\PostEffectPS.hlsl", "main", "ps_5_0", ShaderFlags.Debug, include: new StreamInclude())) { Debug.Assert(pixelShaderByteCode.Bytecode != null, pixelShaderByteCode.Message); pixelShader = new D3D11.PixelShader(device, pixelShaderByteCode); } }
public BasicEffect(Device device) { // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("BasicEffect.fx", "VS", "vs_4_0"); vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("BasicEffect.fx", "PS", "ps_4_0"); pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXTURECOORD", 0, Format.R32G32_Float, 24, 0) }); // Create Constant Buffer constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); Utilities.Dispose(ref vertexShaderByteCode); Utilities.Dispose(ref pixelShaderByteCode); }
/// <summary> /// Binds the effect shader to the specified <see cref="Device"/>. /// </summary> /// <param name="device">The device to bind the shader to.</param> /// <returns>If the binding was successful.</returns> public bool Initialize(Device device) { try { matrixBuffer = new Buffer(device, Matrix.SizeInBytes * 3, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0) {DebugName = "Matrix buffer"}; using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Color.vs", "ColorVertexShader", "vs_4_0")) { layout = new InputLayout(device, ShaderSignature.GetInputSignature(bytecode), ColorDrawingVertex.VertexDeclaration) { DebugName = "Color vertex layout" }; vertexShader = new VertexShader(device, bytecode) { DebugName = "Color vertex shader" }; } using (var bytecode = ShaderBytecode.CompileFromFile("Shaders/Color.ps", "ColorPixelShader", "ps_4_0")) { pixelShader = new PixelShader(device, bytecode) { DebugName = "Color pixel shader" }; } return true; } catch (Exception e) { MessageBox.Show("Shader error: " + e.Message); return false; } }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32_Float, Slot = 0, AlignedByteOffset = 0, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = 0, Format = Format.R32G32_Float, Slot = 0, AlignedByteOffset = Vertex.AppendAlignedElement, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<MatrixBuffer>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); // Create a texture sampler state description. var samplerDesc = new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, MipLodBias = 0, MaximumAnisotropy = 1, ComparisonFunction = Comparison.Always, BorderColor = new Color4(0, 0, 0, 0), MinimumLod = 0, MaximumLod = 0 }; // Create the texture sampler state. SampleState = new SamplerState(device, samplerDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
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; }
/// <inheritdoc/> public void Initialize(Device device) { this.device = device; // Compile Vertex and Pixel shaders var bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMaxVS", "vs_4_0"); vertexShader = ToDispose(new VertexShader(device, bytecode)); // Layout from VertexShader input signature layout = ToDispose(new InputLayout(device,ShaderSignature.GetInputSignature(bytecode), new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0) })); bytecode.Dispose(); pixelShaderMinMaxBegin = new PixelShader[3]; pixelShaderMinMax = new PixelShader[3]; for (int i = 0; i < 3; i++) { bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMaxBegin" + (i + 1) + "PS", "ps_4_0"); pixelShaderMinMaxBegin[i] = ToDispose(new PixelShader(device, bytecode)); bytecode.Dispose(); bytecode = ShaderBytecode.CompileFromFile("minmax.hlsl", "MipMapMinMax" + (i + 1) + "PS", "ps_4_0"); pixelShaderMinMax[i]= ToDispose(new PixelShader(device, bytecode)); bytecode.Dispose(); } // Instantiate Vertex buiffer from vertex data vertices = ToDispose(Buffer.Create(device,BindFlags.VertexBuffer, new[] { -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, })); sampler = ToDispose(new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipPoint, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, })); // Create result 2D texture to readback by CPU textureReadback = ToDispose(new Texture2D( device, new Texture2DDescription { ArraySize = 1, BindFlags = BindFlags.None, CpuAccessFlags = CpuAccessFlags.Read, Format = Format.R32G32_Float, Width = 1, Height = 1, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Staging })); UpdateMinMaxTextures(); }
/// <summary> /// Prepares a draw call. This method is called before each Draw() method to setup the correct Primitive, InputLayout and VertexBuffers. /// </summary> /// <param name="primitiveType">Type of the primitive.</param> /// <exception cref="System.InvalidOperationException">Cannot GraphicsDevice.Draw*() without an effect being previously applied with Effect.Apply() method</exception> private void PrepareDraw(PrimitiveType primitiveType) { if (CurrentEffect == null) { throw new InvalidOperationException("Cannot GraphicsDevice.Draw*() without an effect being previously applied with Effect.Apply() method"); } // Setup the primitive type PrimitiveType = primitiveType; // If the vertex array object is null, simply set the InputLayout to null if (newVertexArrayObject == null) { if (currentVertexArrayObject != null) { currentVertexArrayObject = null; currentVertexArrayLayout = null; currentEffectInputSignature = null; inputAssembler.InputLayout = currentInputLayout = null; } } else { var newVertexArrayLayout = newVertexArrayObject.Layout; var newEffectInputSignature = CurrentEffect.InputSignature; var oldInputLayout = currentInputLayout; // Apply the VertexArrayObject if (newVertexArrayObject != currentVertexArrayObject) { currentVertexArrayObject = newVertexArrayObject; newVertexArrayObject.Apply(inputAssembler); } // If the input layout of the effect or the vertex buffer has changed, get the associated new input layout if (!ReferenceEquals(newVertexArrayLayout, currentVertexArrayLayout) || !ReferenceEquals(newEffectInputSignature, currentEffectInputSignature)) { currentVertexArrayLayout = newVertexArrayLayout; currentEffectInputSignature = newEffectInputSignature; if (newVertexArrayObject.InputLayout != null && ReferenceEquals(newEffectInputSignature, newVertexArrayObject.EffectInputSignature)) { // Default configuration currentInputLayout = newVertexArrayObject.InputLayout; } else if (ReferenceEquals(newEffectInputSignature, newVertexArrayObject.LastEffectInputSignature)) { // Reuse previous configuration currentInputLayout = newVertexArrayObject.LastInputLayout; } // Slow path if the current VertexArrayObject is not optimized for the particular input (or not used right before) else { currentInputLayout = InputLayoutManager.GetInputLayout(newEffectInputSignature, currentVertexArrayLayout); // Store it in VAO since it will likely be used with same effect later newVertexArrayObject.LastInputLayout = currentInputLayout; newVertexArrayObject.LastEffectInputSignature = newEffectInputSignature; } // Setup the input layout (if it changed) if (currentInputLayout != oldInputLayout) { inputAssembler.InputLayout = currentInputLayout; } } } SetViewportImpl(); }
// Set up the pipeline for drawing a shape then draw it. public void Draw(Shape shape) { // Set pipeline components to suit the shape if necessary. if (currVertexBinding.Buffer != shape.vertexBinding.Buffer) { context.InputAssembler.SetVertexBuffers(0, shape.vertexBinding); currVertexBinding = shape.vertexBinding; } if (currLayout != shape.style.layout) { context.InputAssembler.InputLayout = shape.style.layout; currLayout = shape.style.layout; } if (currTopology != shape.topology) { context.InputAssembler.PrimitiveTopology = shape.topology; currTopology = shape.topology; } if (currVertexShader != shape.style.vertexShader) { context.VertexShader.Set(shape.style.vertexShader); currVertexShader = shape.style.vertexShader; } if (currPixelShader != shape.style.pixelShader) { context.PixelShader.Set(shape.style.pixelShader); currPixelShader = shape.style.pixelShader; } if (currTextureView != shape.textureView) { context.PixelShader.SetShaderResource(0, shape.textureView); currTextureView = shape.textureView; } // Calculate the vertex transformation and update the constant buffer. worldViewProj = world * view * proj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, constantBuffer); // Draw the shape. context.Draw(shape.vertexCount, 0); }
private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName) { try { // Setup full pathes vsFileName = SystemConfiguration.ShadersFilePath + vsFileName; psFileName = SystemConfiguration.ShadersFilePath + psFileName; // Compile the vertex shader code. var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "ColorVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None); // Compile the pixel shader code. var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "ColorPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None); // Create the vertex shader from the buffer. VertexShader = new VertexShader(device, vertexShaderByteCode); // Create the pixel shader from the buffer. PixelShader = new PixelShader(device, pixelShaderByteCode); // Now setup the layout of the data that goes into the shader. // This setup needs to match the VertexType structure in the Model and in the shader. var inputElements = new InputElement[] { new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 }, new InputElement() { SemanticName = "COLOR", SemanticIndex = 0, Format = Format.R32G32B32A32_Float, Slot = 0, AlignedByteOffset = InputElement.AppendAligned, Classification = InputClassification.PerVertexData, InstanceDataStepRate = 0 } }; // Create the vertex input the layout. Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements); // Release the vertex and pixel shader buffers, since they are no longer needed. vertexShaderByteCode.Dispose(); pixelShaderByteCode.Dispose(); // Setup the description of the dynamic matrix constant buffer that is in the vertex shader. var matrixBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, SizeInBytes = Utilities.SizeOf<Matrix>(), BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class. ConstantMatrixBuffer = new Buffer(device, matrixBufferDesc); return true; } catch (Exception ex) { MessageBox.Show("Error initializing shader. Error is " + ex.Message); return false; }; }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events Factory factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "VS", "vs_4_0", ShaderFlags.None, EffectFlags.None); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "PS", "ps_4_0", ShaderFlags.None, EffectFlags.None); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION",0,Format.R32G32B32A32_Float,0,0), new InputElement("COLOR",0,Format.R32G32B32A32_Float,16,0) }); // Write vertex data to a datastream var stream = new DataStream(32*3, true, true); stream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32*3, Usage = ResourceUsage.Default, StructureByteStride = 0 }); stream.Release(); // Prepare All the stages context.InputAssembler.SetInputLayout(layout); context.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); context.Draw(3, 0); swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Release(); vertexShader.Release(); pixelShaderByteCode.Release(); pixelShader.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); context.ClearState(); context.Flush(); device.Release(); context.Release(); swapChain.Release(); factory.Release(); }
private void SwapChainPanel_OnLoaded(object sender, RoutedEventArgs e) { using (var defDevice = new D3D.Device(DriverType.Hardware, D3D.DeviceCreationFlags.Debug)) { _device = defDevice.QueryInterface <D3D.Device3>(); } _context = _device.ImmediateContext3; var pixelScale = DisplayInformation.GetForCurrentView().LogicalDpi / 96.0f; var swapChainDesc = new DXGI.SwapChainDescription1() { AlphaMode = DXGI.AlphaMode.Premultiplied, BufferCount = 2, Flags = DXGI.SwapChainFlags.None, Format = DXGI.Format.B8G8R8A8_UNorm, Width = (int)(panel.RenderSize.Width * pixelScale), Height = (int)(panel.RenderSize.Height * pixelScale), SampleDescription = new DXGI.SampleDescription(1, 0), Scaling = DXGI.Scaling.Stretch, Stereo = false, SwapEffect = DXGI.SwapEffect.FlipSequential, Usage = DXGI.Usage.BackBuffer | DXGI.Usage.RenderTargetOutput }; using (var dxgiDevice = _device.QueryInterface <DXGI.Device3>()) { var factory = dxgiDevice.Adapter.GetParent <DXGI.Factory4>(); using (var tmpSwapChain = new DXGI.SwapChain1(factory, _device, ref swapChainDesc)) { _swapChain = tmpSwapChain.QueryInterface <DXGI.SwapChain3>(); } } using (var nativeObject = ComObject.As <DXGI.ISwapChainPanelNative>(panel)) { nativeObject.SwapChain = _swapChain; } using (var depthBuffer = new D3D.Texture2D(_device, new D3D.Texture2DDescription() { Format = DXGI.Format.D24_UNorm_S8_UInt, ArraySize = 1, MipLevels = 1, Width = swapChainDesc.Width, Height = swapChainDesc.Height, SampleDescription = new DXGI.SampleDescription(1, 0), BindFlags = D3D.BindFlags.DepthStencil, })) { _depthStencilView = new D3D.DepthStencilView(_device, depthBuffer, new D3D.DepthStencilViewDescription() { Dimension = D3D.DepthStencilViewDimension.Texture2D }); } _backBuffer = D3D.Resource.FromSwapChain <D3D.Texture2D>(_swapChain, 0); _renderView = new D3D.RenderTargetView1(_device, _backBuffer); var viewport = new ViewportF(0, 0, (float)panel.RenderSize.Width, (float)panel.RenderSize.Height, 0.0f, 1.0f); _context.Rasterizer.SetViewport(viewport); ShaderBytecode shaderBytecode; using (shaderBytecode = ShaderBytecode.CompileFromFile("shaders.hlsl", "vs", "vs_5_0", ShaderFlags.Debug)) { _vertexShader = new D3D.VertexShader(_device, shaderBytecode); } using (var byteCode = ShaderBytecode.CompileFromFile(@"shaders.hlsl", "ps", "ps_5_0", ShaderFlags.Debug)) { _pixelShader = new D3D.PixelShader(_device, byteCode); } D3D.InputElement[] inputElements = { new D3D.InputElement("POSITION", 0, DXGI.Format.R32G32B32A32_Float, 0, 0), }; _inputLayout = new D3D.InputLayout(_device, shaderBytecode, inputElements); _vertices = new[] { new Vector4(-0.5f, 0.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(0.5f, 0.0f, 0.5f, 1.0f), }; _vertexBuffer = D3D.Buffer.Create(_device, D3D.BindFlags.VertexBuffer, _vertices); _vertexBinding = new D3D.VertexBufferBinding(_vertexBuffer, Utilities.SizeOf <Vector4>(), 0); _constantBuffer = new SharpDX.Direct3D11.Buffer( _device, Utilities.SizeOf <SharpDX.Matrix>(), D3D.ResourceUsage.Default, D3D.BindFlags.ConstantBuffer, D3D.CpuAccessFlags.None, D3D.ResourceOptionFlags.None, 0); _timer = new Stopwatch(); _timer.Start(); CompositionTarget.Rendering += CompositionTarget_Rendering; }
internal Engine_Material(string _shaderFileName, string _imageFileName, bool _includeGeometryShader = false) { #region //Get Instances m_d3d = Engine_Renderer.Instance; #endregion #region //Create InputLayout var inputElements = new D3D11.InputElement[] { new D3D11.InputElement("POSITION", 0, DXGI.Format.R32G32B32_Float, 0, 0), new D3D11.InputElement("TEXCOORD", 0, DXGI.Format.R32G32_Float, D3D11.InputElement.AppendAligned, 0), new D3D11.InputElement("NORMAL", 0, DXGI.Format.R32G32B32_Float, D3D11.InputElement.AppendAligned, 0) }; #endregion #region //Create VertexShader CompilationResult vsResult; using (vsResult = ShaderBytecode.CompileFromFile(_shaderFileName, "VS", "vs_4_0", ShaderFlags.None)) { m_vertexShader = new D3D11.VertexShader(m_d3d.m_device, vsResult.Bytecode.Data); m_inputLayout = new D3D11.InputLayout(m_d3d.m_device, vsResult.Bytecode, inputElements); } #endregion #region //Create PixelShader using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "PS", "ps_4_0", ShaderFlags.None)) m_pixelShader = new D3D11.PixelShader(m_d3d.m_device, psResult.Bytecode.Data); #endregion #region //Create GeometryShader if (_includeGeometryShader) { using (var psResult = ShaderBytecode.CompileFromFile(_shaderFileName, "GS", "gs_4_0", ShaderFlags.None)) m_geometryShader = new D3D11.GeometryShader(m_d3d.m_device, psResult.Bytecode.Data); } #endregion #region //Create ConstantBuffers for Model SPerModelConstantBuffer cbModel = new SPerModelConstantBuffer(); D3D11.BufferDescription bufferDescription = new D3D11.BufferDescription { BindFlags = D3D11.BindFlags.ConstantBuffer, CpuAccessFlags = D3D11.CpuAccessFlags.Write, Usage = D3D11.ResourceUsage.Dynamic, }; m_model = D3D11.Buffer.Create(m_d3d.m_device, D3D11.BindFlags.ConstantBuffer, ref cbModel); #endregion #region //Create Texture and Sampler var texture = Engine_ImgLoader.CreateTexture2DFromBitmap(m_d3d.m_device, Engine_ImgLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), _imageFileName)); m_resourceView = new D3D11.ShaderResourceView(m_d3d.m_device, texture); D3D11.SamplerStateDescription samplerStateDescription = new D3D11.SamplerStateDescription { Filter = D3D11.Filter.Anisotropic, AddressU = D3D11.TextureAddressMode.Clamp, AddressV = D3D11.TextureAddressMode.Clamp, AddressW = D3D11.TextureAddressMode.Clamp, ComparisonFunction = D3D11.Comparison.Always, MaximumAnisotropy = 16, MinimumLod = 0, MaximumLod = float.MaxValue, }; m_sampler = new D3D11.SamplerState(m_d3d.m_device, samplerStateDescription); #endregion }