protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexBuffer);
            RemoveAndDispose(ref indexBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture (a DDS cube map)
            textureView = ShaderResourceView.FromFile(device, "CubeMap.dds");

            // Create our sampler state
            samplerState = new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumLod = 9, // Our cube map has 10 mip map levels (0-9)
                MinimumLod = 0,
                MipLodBias = 0.0f
            });

            Vertex[] vertices;
            int[] indices;
            GeometricPrimitives.GenerateSphere(out vertices, out indices, Color.Gray);

            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices));
            vertexBinding = new VertexBufferBinding(vertexBuffer, Utilities.SizeOf<Vertex>(), 0);

            indexBuffer = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, indices));
            totalVertexCount = indices.Length;
        }
Exemple #2
0
        public SibenikMaterial(Device device, TweakBar bar, String name)
            : base(device, bar, name)
        {
            bar.AddColor(Prefix + "diffuse", "Diffuse", name, new Color3(1, 1, 1));
            bar.AddColor(Prefix + "specular", "Specular", name, new Color3(1, 1, 1));
            bar.AddFloat(Prefix + "shininess", "Shininess", name, 1, 256, 64, 0.1, 2);
            bar.AddFloat(Prefix + "brightness", "Brightness", name, 0, 15000, 5, 50, 2);

            pixelShader = Material.CompileShader(device, "sibenik");

            constantBuffer = Material.AllocateMaterialBuffer(device, BufferSize);

            sampler = new SamplerState(device, new SamplerStateDescription()
            {
                ComparisonFunction = Comparison.Always,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                BorderColor = Color4.Black,
                MaximumAnisotropy = 16,
                MaximumLod = 15,
                MinimumLod = 0,
                MipLodBias = 0,
            });
        }
Exemple #3
0
        public WorldTerrainShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TerrainVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TerrainPixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.PositionTexture.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);

            var samplerDescMap = new SamplerStateDescription
            {
                Filter = Filter.MinMagMipPoint,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MipLodBias = 0,
                MaximumAnisotropy = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor = Color.Transparent,
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            };
            SamplerStateMap = new SamplerState(device, samplerDescMap);
        }
Exemple #4
0
        public TextureShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "TexturePixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.PositionTexture.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);

            // Create a texture sampler state description.
            var samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.Anisotropic,
                AddressU = TextureAddressMode.Mirror,
                AddressV = TextureAddressMode.Mirror,
                AddressW = TextureAddressMode.Mirror,
                MipLodBias = 0,
                MaximumAnisotropy = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor = new Color4(1, 1, 1, 1),
                MinimumLod = 0,
                MaximumLod = 0
            };

            // Create the texture sampler state.
            SamplerState = new SamplerState(device, samplerDesc);
        }
Exemple #5
0
        public PathShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "VS", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "PS", "ps_4_0", ShaderFlags);
            var geometryShaderByteCode = ShaderBytecode.CompileFromFile(FileName, "GS", "gs_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);
            GeometryShader = new GeometryShader(device, geometryShaderByteCode);
            Layout = VertexDefinition.Path.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();
            geometryShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);
            ConstantPathDataBuffer = new Buffer(device,
                new BufferDescription
                {
                    Usage = ResourceUsage.Dynamic,
                    SizeInBytes = Utilities.SizeOf<PathData>(),
                    BindFlags = BindFlags.ConstantBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    OptionFlags = ResourceOptionFlags.None,
                    StructureByteStride = 0
                });
            SamplerState = new SamplerState(device, WrapSamplerStateDescription);
        }
Exemple #6
0
        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;
            }
        }
        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),
            });

        }
Exemple #8
0
        public TerrainMinimapShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "MinimapTerrainVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "MinimapTerrainPixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.TerrainVertex.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);
            ConstantSelectionBuffer = new Buffer(device, new BufferDescription
            {
                Usage = ResourceUsage.Dynamic,
                SizeInBytes = Utilities.SizeOf<SelectionBuffer>(),
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                StructureByteStride = 0
            });

            var samplerDescBorder = new SamplerStateDescription
            {
                Filter = Filter.Anisotropic,
                AddressU = TextureAddressMode.MirrorOnce,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MipLodBias = 0,
                MaximumAnisotropy = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor = Color.Transparent,
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            };

            // Create the texture sampler state.
            SamplerStateBorder = new SamplerState(device, samplerDescBorder);

            var samplerDescColor = new SamplerStateDescription
            {
                Filter = Filter.Anisotropic,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MipLodBias = 0,
                MaximumAnisotropy = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor = Color.Transparent,
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            };

            // Create the texture sampler state.
            SamplerStateColor = new SamplerState(device, samplerDescColor);
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref axisLinesVertices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));

            // Create xyz-axis arrows
            // X is Red, Y is Green, Z is Blue
            // The arrows point along the + for each axis
            axisLinesVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[]
            {
            /*  Vertex Position         Texture UV */
                                        // ~45x10
                -1f, 0f, 0f, 1f,        0.1757f, 0.039f, // - x-axis
                1f, 0f, 0f, 1f,         0.1757f, 0.039f,  // + x-axis
                0.9f, -0.05f, 0f, 1f,   0.1757f, 0.039f,// arrow head start
                1f, 0f, 0f, 1f,         0.1757f, 0.039f,
                0.9f, 0.05f, 0f, 1f,    0.1757f, 0.039f,
                1f, 0f, 0f, 1f,         0.1757f, 0.039f,  // arrow head end
                                        // ~135x35
                0f, -1f, 0f, 1f,        0.5273f, 0.136f, // - y-axis
                0f, 1f, 0f, 1f,         0.5273f, 0.136f,  // + y-axis
                -0.05f, 0.9f, 0f, 1f,   0.5273f, 0.136f,// arrow head start
                0f, 1f, 0f, 1f,         0.5273f, 0.136f,
                0.05f, 0.9f, 0f, 1f,    0.5273f, 0.136f,
                0f, 1f, 0f, 1f,         0.5273f, 0.136f,  // arrow head end
                                        // ~220x250
                0f, 0f, -1f, 1f,        0.859f, 0.976f, // - z-axis
                0f, 0f, 1f, 1f,         0.859f, 0.976f,  // + z-axis
                0f, -0.05f, 0.9f, 1f,   0.859f, 0.976f,// arrow head start
                0f, 0f, 1f, 1f,         0.859f, 0.976f,
                0f, 0.05f, 0.9f, 1f,    0.859f, 0.976f,
                0f, 0f, 1f, 1f,         0.859f, 0.976f,  // arrow head end
            }));
            axisLinesBinding = new VertexBufferBinding(axisLinesVertices, Utilities.SizeOf<float>() * 6, 0);
        }
Exemple #10
0
        public LightShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "LightPixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.PositionTextureNormal.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);

            // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
            var lightBufferDesc = new BufferDescription
            {
                Usage = ResourceUsage.Dynamic, // Updated each frame
                SizeInBytes = Utilities.SizeOf<LightBuffer>(), // Contains three matrices
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                StructureByteStride = 0
            };
            ConstantLightBuffer = new Buffer(device, lightBufferDesc);

            // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
            var cameraBufferDesc = new BufferDescription
            {
                Usage = ResourceUsage.Dynamic, // Updated each frame
                SizeInBytes = Utilities.SizeOf<CameraBuffer>(), // Contains three matrices
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                StructureByteStride = 0
            };
            ConstantCameraBuffer = new Buffer(device, cameraBufferDesc);

            // Create a texture sampler state description.
            var samplerDesc = new SamplerStateDescription
            {
                Filter = Filter.Anisotropic,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                MipLodBias = 0,
                MaximumAnisotropy = 16,
                ComparisonFunction = Comparison.Always,
                BorderColor = new Color4(0, 0, 0, 0),
                MinimumLod = 0,
                MaximumLod = 10
            };

            // Create the texture sampler state.
            SamplerState = new SamplerState(device, samplerDesc);
        }
 protected override void InitializeInternal()
 {
     var descr = new SamplerStateDescription
     {
         AddressU = GetTextureAddressMode(Settings.WrapU),
         AddressV = GetTextureAddressMode(Settings.WrapV),
         AddressW = GetTextureAddressMode(Settings.WrapW),
         Filter = GetFilterType(Settings.Filter)
     };
     SamplerState = new SamplerState(DeviceManager.Device, descr);
 }
Exemple #12
0
 public PassThroughFilter(Device device)
 {
     this.pixelShaderByteCode = ShaderBytecode.CompileFromFile("Graphics/PassThrough.hlsl", "pixel", "ps_4_0", ShaderFlags.OptimizationLevel1, EffectFlags.None, null, null);
     this.pixelShader = new PixelShader(device, this.pixelShaderByteCode, null);
     this.sampler = new SamplerState(device, new SamplerStateDescription
     {
         MaximumAnisotropy = 16,
         Filter = SharpDX.Direct3D11.Filter.Anisotropic,
         AddressU = TextureAddressMode.Clamp,
         AddressV = TextureAddressMode.Clamp,
         AddressW = TextureAddressMode.Clamp,
         MinimumLod = 0f,
         MaximumLod = 100f
     });
 }
Exemple #13
0
        public FontShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "FontVertexShader", "vs_4_0", ShaderFlags);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(ShaderFileName, "FontPixelShader", "ps_4_0", ShaderFlags);

            VertexShader = new VertexShader(device, vertexShaderByteCode);
            PixelShader = new PixelShader(device, pixelShaderByteCode);

            Layout = VertexDefinition.PositionTextureColor.GetInputLayout(device, vertexShaderByteCode);

            vertexShaderByteCode.Dispose();
            pixelShaderByteCode.Dispose();

            ConstantMatrixBuffer = new Buffer(device, MatrixBufferDesription);
            SamplerState = new SamplerState(device, WrapSamplerStateDescription);
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref triangleVertices);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a triangle
            triangleVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position, normal, Color, UV */
            // Modified normals to work with Curved PN-Triangles
                new Vertex(new Vector3(0.75f, 0f, -0.001f), Vector3.Normalize(Vector3.UnitZ + Vector3.UnitX - Vector3.UnitY), Color.Black, new Vector2(1.0f, 1.0f)), // Base-right
                new Vertex(new Vector3(-0.75f, 0f, -0.001f),Vector3.Normalize(Vector3.UnitZ - Vector3.UnitX - Vector3.UnitY), Color.Black, new Vector2(0.0f, 1.0f)), // Base-left
                new Vertex(new Vector3(0f, 1.5f, -0.001f), Vector3.Normalize(Vector3.UnitZ + Vector3.UnitY), Color.Black, new Vector2(0.5f, 0.0f)), // Apex
            }));
            triangleBinding = new VertexBufferBinding(triangleVertices, Utilities.SizeOf<Vertex>(), 0);

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture2.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }
Exemple #15
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;
            }
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref vertices);
            RemoveAndDispose(ref textureView);
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Create a vertex to begin the parametric surface
            vertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position */
                new Vertex(new Vector3(0f, 0f, 0f)), // Base-right
            }));
            vertexBinding = new VertexBufferBinding(vertices, Utilities.SizeOf<Vertex>(), 0);

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture2.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }
Exemple #17
0
        public GroundMaterial(Device device, TweakBar bar, String name)
            : base(device, bar, name)
        {
            bar.AddFloat(Prefix + "albedo", "Albedo", name, 0, 100, 30, 0.1, 2);

            pixelShader = Material.CompileShader(device, "ground");

            constantBuffer = Material.AllocateMaterialBuffer(device, BufferSize);

            sampler = new SamplerState(device, new SamplerStateDescription()
            {
                ComparisonFunction = Comparison.Always,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter = Filter.Anisotropic,
                BorderColor = Color4.Black,
                MaximumAnisotropy = 16,
                MaximumLod = 15,
                MinimumLod = 0,
                MipLodBias = 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, "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;
            };
        }
        /// <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();
        }
        // Constructor - Must be initialized before the assets.
        public Pipeline(Program program, String title, int initialWidth, int initialHeight)
        {
            // Set program reference.
            this.program = program;

            // Set dimentions.
            this.width = initialWidth;
            this.height = initialHeight;

            // Create Windows form.
            form = program.ToDispose(new RenderForm(title));
            form.ClientSize = new System.Drawing.Size(width, height);

            // Create SwapChain description
            var desc = new SwapChainDescription()
            {
                BufferCount = 1,
                ModeDescription =
                    new ModeDescription(width, height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput,
            };

            // Create Device, SwapChain and DeviceContext.
            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);
            program.ToDispose(device);
            program.ToDispose(swapChain);
            context = program.ToDispose(device.ImmediateContext);

            // Create the RenderView.
            var backBuffer = program.ToDispose(Texture2D.FromSwapChain<Texture2D>(swapChain, 0));
            renderView = program.ToDispose(new RenderTargetView(device, backBuffer));

            // Create the DepthStencilView.
            var depthBuffer = program.ToDispose(new Texture2D(device, new Texture2DDescription()
            {
                Format = Format.D32_Float_S8X24_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            }));
            depthView = program.ToDispose(new DepthStencilView(device, depthBuffer));

            // Create the texture sampler.
            sampler = program.ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = Colors.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy = 16,
                MipLodBias = 0,
                MinimumLod = 0,
                MaximumLod = 16,
            }));
            context.PixelShader.SetSampler(0, sampler);

            // Initialise the transformation matrices.
            world = Matrix.Identity;
            view = Matrix.Identity;
            proj = Matrix.Identity;
            worldViewProj = Matrix.Identity;

            // Create the Constant Buffer.
            constantBuffer = program.ToDispose(new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            context.VertexShader.SetConstantBuffer(0, constantBuffer);

            // Set the view port.
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));

            // Set the output target.
            context.OutputMerger.SetTargets(depthView, renderView);
        }
        protected override void CreateDeviceDependentResources()
        {
            // Dispose of each vertex and index buffer
            vertexBuffers.ForEach(vb => RemoveAndDispose(ref vb));
            vertexBuffers.Clear();
            indexBuffers.ForEach(ib => RemoveAndDispose(ref ib));
            indexBuffers.Clear();
            textureViews.ForEach(tv => RemoveAndDispose(ref tv));
            textureViews.Clear();
            RemoveAndDispose(ref samplerState);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Initialize vertex buffers
            for (int indx = 0; indx < mesh.VertexBuffers.Count; indx++)
            {
                var vb = mesh.VertexBuffers[indx];
                Vertex[] vertices = new Vertex[vb.Length];
                for (var i = 0; i < vb.Length; i++)
                {
                    // Retrieve skinning information for vertex
                    Common.Mesh.SkinningVertex skin = new Common.Mesh.SkinningVertex();
                    if (mesh.SkinningVertexBuffers.Count > 0)
                        skin = mesh.SkinningVertexBuffers[indx][i];

                    // Create vertex
                    vertices[i] = new Vertex(vb[i].Position, vb[i].Normal, vb[i].Color, vb[i].UV, skin);
                }

                vertexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray())));
                vertexBuffers[vertexBuffers.Count - 1].DebugName = "VertexBuffer_" + indx.ToString();
            }

            // Initialize index buffers
            foreach (var ib in mesh.IndexBuffers)
            {
                indexBuffers.Add(ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, ib)));
                indexBuffers[indexBuffers.Count - 1].DebugName = "IndexBuffer_" + (indexBuffers.Count - 1).ToString();
            }

            // Load textures if a material has any.
            foreach (var m in mesh.Materials)
            {
                for (var i = 0; i < m.Textures.Length; i++)
                {
                    if (System.IO.File.Exists(m.Textures[i]))
                        textureViews.Add(ToDispose(ShaderResourceView.FromFile(device, m.Textures[i])));
                    else
                        textureViews.Add(null);
                }
            }

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));
        }
        public DepthAndColorShader(Device device)
        {
            shaderByteCode = new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorFloatVS.cso"));
            depthAndColorVS = new VertexShader(device, shaderByteCode);
            depthAndColorGS = new GeometryShader(device, new ShaderBytecode(File.ReadAllBytes("Content/DepthAndColorGS.cso")));
            depthAndColorPS = 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 state
            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = true,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = true,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            // color 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);

            //// Kinect depth image
            //var depthImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = depthImageWidth,
            //    Height = depthImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.R16_UInt, // R32_Float
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write,
            //};
            //depthImageTexture = new Texture2D(device, depthImageTextureDesc);
            //depthImageTextureRV = new ShaderResourceView(device, depthImageTexture);

            // filtered depth image
            var filteredDepthImageTextureDesc = new Texture2DDescription()
            {
                Width = Kinect2Calibration.depthImageWidth * 3,
                Height = Kinect2Calibration.depthImageHeight * 3,
                MipLevels = 1,
                ArraySize = 1,
                Format = SharpDX.DXGI.Format.R32G32_Float,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
            };
            filteredDepthImageTexture = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView = new RenderTargetView(device, filteredDepthImageTexture);
            filteredDepthImageSRV = new ShaderResourceView(device, filteredDepthImageTexture);

            filteredDepthImageTexture2 = new Texture2D(device, filteredDepthImageTextureDesc);
            filteredRenderTargetView2 = new RenderTargetView(device, filteredDepthImageTexture2);
            filteredDepthImageSRV2 = new ShaderResourceView(device, filteredDepthImageTexture2);

            //// Kinect color image
            //var colorImageStagingTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 1,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    //Format = SharpDX.DXGI.Format.YUY2
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Dynamic,
            //    BindFlags = BindFlags.ShaderResource,
            //    CpuAccessFlags = CpuAccessFlags.Write
            //};
            //colorImageStagingTexture = new Texture2D(device, colorImageStagingTextureDesc);

            //var colorImageTextureDesc = new Texture2DDescription()
            //{
            //    Width = colorImageWidth,
            //    Height = colorImageHeight,
            //    MipLevels = 0,
            //    ArraySize = 1,
            //    Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
            //    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
            //    Usage = ResourceUsage.Default,
            //    BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget,
            //    CpuAccessFlags = CpuAccessFlags.None,
            //    OptionFlags = ResourceOptionFlags.GenerateMipMaps
            //};
            //colorImageTexture = new Texture2D(device, colorImageTextureDesc);
            //colorImageTextureRV = new ShaderResourceView(device, colorImageTexture);

            // constant buffer
            var constantBufferDesc = new BufferDescription()
            {
                Usage = ResourceUsage.Dynamic,
                BindFlags = BindFlags.ConstantBuffer,
                SizeInBytes = ConstantBuffer.size,
                CpuAccessFlags = CpuAccessFlags.Write,
                StructureByteStride = 0,
                OptionFlags = 0,
            };
            constantBuffer = new SharpDX.Direct3D11.Buffer(device, constantBufferDesc);

            bilateralFilter = new BilateralFilter(device, Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight);

            vertexInputLayout = new InputLayout(device, shaderByteCode.Data, new[]
            {
                new InputElement("SV_POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            });
        }
Exemple #23
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 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
            var factory = swapChain.GetParent<Factory>();
            factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            // New RenderTargetView from the backbuffer
            var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var renderView = new RenderTargetView(device, backBuffer);

            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "VS", "vs_4_0");
            var vertexShader = new VertexShader(device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "PS", "ps_4_0");
            var pixelShader = new PixelShader(device, pixelShaderByteCode);

            // Layout from VertexShader input signature
            var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                    });

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
                                  {
                                      // 3D coordinates              UV Texture coordinates
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f, // Front
                                      -1.0f,  1.0f, -1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 1.0f,

                                      -1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 0.0f, // BACK
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 1.0f,
                                      -1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f, -1.0f,  1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,

                                      -1.0f, 1.0f, -1.0f,  1.0f,     0.0f, 1.0f, // Top
                                      -1.0f, 1.0f,  1.0f,  1.0f,     0.0f, 0.0f,
                                       1.0f, 1.0f,  1.0f,  1.0f,     1.0f, 0.0f,
                                      -1.0f, 1.0f, -1.0f,  1.0f,     0.0f, 1.0f,
                                       1.0f, 1.0f,  1.0f,  1.0f,     1.0f, 0.0f,
                                       1.0f, 1.0f, -1.0f,  1.0f,     1.0f, 1.0f,

                                      -1.0f,-1.0f, -1.0f,  1.0f,     1.0f, 0.0f, // Bottom
                                       1.0f,-1.0f,  1.0f,  1.0f,     0.0f, 1.0f,
                                      -1.0f,-1.0f,  1.0f,  1.0f,     1.0f, 1.0f,
                                      -1.0f,-1.0f, -1.0f,  1.0f,     1.0f, 0.0f,
                                       1.0f,-1.0f, -1.0f,  1.0f,     0.0f, 0.0f,
                                       1.0f,-1.0f,  1.0f,  1.0f,     0.0f, 1.0f,

                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f, // Left
                                      -1.0f, -1.0f,  1.0f, 1.0f,     0.0f, 0.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 1.0f,

                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 0.0f, // Right
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                                       1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 1.0f,
                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                            });

            // Create Constant Buffer
            var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);


            // Create Depth Buffer & View
            var depthBuffer = new Texture2D(device, new Texture2DDescription()
            {
                Format = Format.D32_Float_S8X24_UInt,
                ArraySize = 1,
                MipLevels = 1,
                Width = form.ClientSize.Width,
                Height = form.ClientSize.Height,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            });

            var depthView = new DepthStencilView(device, depthBuffer);

            // Load texture and create sampler
            var texture = Texture2D.FromFile<Texture2D>(device, "GeneticaMortarlessBlocks.jpg");
            var textureView = new ShaderResourceView(device, texture);

            var sampler = new SamplerState(device, new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = Color.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy = 16,
                MipLodBias = 0,
                MinimumLod = 0,
                MaximumLod = 16,
            });


            // Prepare All the stages
            context.InputAssembler.InputLayout = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() + Utilities.SizeOf<Vector2>(), 0));
            context.VertexShader.SetConstantBuffer(0, contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            context.PixelShader.Set(pixelShader);
            context.PixelShader.SetSampler(0, sampler);
            context.PixelShader.SetShaderResource(0, textureView);
            context.OutputMerger.SetTargets(depthView, renderView);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            // Main loop
            RenderLoop.Run(form, () =>
            {
                var time = clock.ElapsedMilliseconds / 1000.0f;

                // Clear views
                context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
                context.ClearRenderTargetView(renderView, Color.Black);

                // Update WorldViewProj Matrix
                var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                worldViewProj.Transpose();
                context.UpdateSubresource(ref worldViewProj, contantBuffer);

                // Draw the cube
                context.Draw(36, 0);

                // Present!
                swapChain.Present(0, PresentFlags.None);
            });

            // Release all resources
            vertexShaderByteCode.Dispose();
            vertexShader.Dispose();
            pixelShaderByteCode.Dispose();
            pixelShader.Dispose();
            vertices.Dispose();
            layout.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            context.ClearState();
            context.Flush();
            device.Dispose();
            context.Dispose();
            swapChain.Dispose();
            factory.Dispose();
        }
        public void Initialize()
        {
            LoadSky(0);

            Texture2DDescription descTex = new Texture2DDescription();
            descTex.ArraySize = 6;
            descTex.Width = Size;
            descTex.Height = Size;
            descTex.Usage = ResourceUsage.Default;
            descTex.CpuAccessFlags = CpuAccessFlags.None;
            descTex.Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm;
            descTex.SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0);
            descTex.MipLevels = MipLevel;
            descTex.BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget;
            descTex.OptionFlags = ResourceOptionFlags.GenerateMipMaps | ResourceOptionFlags.TextureCube;

            //Create the texture and shader view
            CubeTexture = new Texture2D(ModelViewer.Program.device, descTex);
            CubeSRV = new ShaderResourceView(ModelViewer.Program.device, CubeTexture);

            RenderTargetViewDescription RTVD = new RenderTargetViewDescription();
            RTVD.Format = descTex.Format;
            RTVD.Dimension = RenderTargetViewDimension.Texture2DArray;
            RTVD.Texture2DArray.FirstArraySlice = 0;
            RTVD.Texture2DArray.ArraySize = 1;
            RTVD.Texture2DArray.MipSlice = 0;

            CubeRenderTarget = new RenderTargetView[6];

            for (int i = 0; i < 6; i++)
            {
                RTVD.Texture2DArray.FirstArraySlice = i;
                CubeRenderTarget[i] = new RenderTargetView(ModelViewer.Program.device, CubeTexture, RTVD);
            }

            SamplerStateDescription a = new SamplerStateDescription();
            a.AddressU = TextureAddressMode.Clamp;
            a.AddressV = TextureAddressMode.Clamp;
            a.AddressW = TextureAddressMode.Clamp;
            a.Filter = Filter.MinMagMipLinear;
            SSWrapMipLinear = new SamplerState(ModelViewer.Program.device, a);

            MContains = new MeshContainer();
            MContains.BytesPerVertex = 20;
            MContains.FaceCount = 12;
            MContains.VertexsCount = 24;

            Vector3 vExtents = new Vector3(500, 500, 500);

            var vertices = new DataStream(MContains.BytesPerVertex * MContains.VertexsCount, true, true);

            //Back
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 0));
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            //Front
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 0));
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            //Bottom
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 0));
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            //Top
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 0));
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            //Left
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            vertices.Write(new Vector3(-vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 0));
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            vertices.Write(new Vector3(-vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            //Right
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 1));
            vertices.Write(new Vector3(vExtents.X, -vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 1));
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, vExtents.Z));
            vertices.Write(new Vector2(1, 0));
            vertices.Write(new Vector3(vExtents.X, vExtents.Y, -vExtents.Z));
            vertices.Write(new Vector2(0, 0));

            vertices.Position = 0;
            InputElement[] elements11 = new[] {
                new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0) ,
                new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0)};

            MContains.Vertexs = new Buffer(ModelViewer.Program.device, vertices, MContains.BytesPerVertex * MContains.VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            var indices = new DataStream(4 * MContains.FaceCount * 3, true, true);
            for (int x = 0; x < 6; x++)
            {
                indices.Write((int)(x * 4 + 0));
                indices.Write((int)(x * 4 + 1));
                indices.Write((int)(x * 4 + 2));

                indices.Write((int)(x * 4 + 2));
                indices.Write((int)(x * 4 + 3));
                indices.Write((int)(x * 4 + 0));
            }
            indices.Position = 0;

            MContains.Indices = new Buffer(ModelViewer.Program.device, indices, 4 * MContains.FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            MContains.binding = new VertexBufferBinding(MContains.Vertexs, MContains.BytesPerVertex, 0);

            EEEM = ContentManager.LoadEffect("Content/Shaders/SkyBox", elements11);

            // Подготовка константного буффера
            BufferDescription bd = new BufferDescription();
            bd.SizeInBytes = Marshal.SizeOf(typeof(SkyShaderConstants));
            bd.Usage = ResourceUsage.Dynamic;
            bd.BindFlags = BindFlags.ConstantBuffer;
            bd.CpuAccessFlags = CpuAccessFlags.Write;
            bd.OptionFlags = ResourceOptionFlags.None;
            bd.StructureByteStride = 0;

            SkyConstantsBuffer = new Buffer(ModelViewer.Program.device, bd);
            SSC = new SkyShaderConstants();
        }
Exemple #25
0
        public TextureShader(Device device)
        {
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile(VertexShaderFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
            var pixelShaderByteCode = ShaderBytecode.CompileFromFile(PixelShaderFileName, "TexturePixelShader", "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 = "TEXCOORD",
                    SemanticIndex = 0,
                    Format = Format.R32G32_Float,
                    Slot = 0,
                    AlignedByteOffset = TextureShader.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<TextureShader.MatrixBuffer>(), // Contains three matrices
                BindFlags = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags = ResourceOptionFlags.None,
                StructureByteStride = 0
            };
            ConstantMatrixBuffer = new SharpDX.Direct3D11.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.
            SamplerState = new SamplerState(device, samplerDesc);
        }
Exemple #26
0
 private void Update()
 {
     if (UpdateSettings)
     {
         Destroy(ref _TSS);
         _TSS = Tag(new SamplerState(Device3D, TSSD));
         UpdateSettings = false;
     }
 }
Exemple #27
0
        public virtual void Initialize(DeviceManager devices)
        {
            // Remove previous buffer
            RemoveAndDispose(ref constantBuffer);

            // Setup local variables
            var d3dDevice = devices.DeviceDirect3D;
            var d3dContext = devices.ContextDirect3D;

            var path = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;

            // Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCubeTexture_VS.fxo");
            vertexShader = new VertexShader(d3dDevice, vertexShaderByteCode);

            // Loads pixel shader bytecode
            pixelShader = new PixelShader(d3dDevice, NativeFile.ReadAllBytes(path + "\\MiniCubeTexture_PS.fxo"));

            // Layout from VertexShader input signature
            layout = new InputLayout(d3dDevice, vertexShaderByteCode, new[]
                    {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                    });

            // Instantiate Vertex buiffer from vertex data
            var vertices = SharpDX.Direct3D11.Buffer.Create(d3dDevice, BindFlags.VertexBuffer, new[]
                                  {
                                      // 3D coordinates              UV Texture coordinates
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f, // Front
                                      -1.0f,  1.0f, -1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 1.0f,

                                      -1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 0.0f, // BACK
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 1.0f,
                                      -1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f, -1.0f,  1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,

                                      -1.0f, 1.0f, -1.0f,  1.0f,     0.0f, 1.0f, // Top
                                      -1.0f, 1.0f,  1.0f,  1.0f,     0.0f, 0.0f,
                                       1.0f, 1.0f,  1.0f,  1.0f,     1.0f, 0.0f,
                                      -1.0f, 1.0f, -1.0f,  1.0f,     0.0f, 1.0f,
                                       1.0f, 1.0f,  1.0f,  1.0f,     1.0f, 0.0f,
                                       1.0f, 1.0f, -1.0f,  1.0f,     1.0f, 1.0f,

                                      -1.0f,-1.0f, -1.0f,  1.0f,     1.0f, 0.0f, // Bottom
                                       1.0f,-1.0f,  1.0f,  1.0f,     0.0f, 1.0f,
                                      -1.0f,-1.0f,  1.0f,  1.0f,     1.0f, 1.0f,
                                      -1.0f,-1.0f, -1.0f,  1.0f,     1.0f, 0.0f,
                                       1.0f,-1.0f, -1.0f,  1.0f,     0.0f, 0.0f,
                                       1.0f,-1.0f,  1.0f,  1.0f,     0.0f, 1.0f,

                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f, // Left
                                      -1.0f, -1.0f,  1.0f, 1.0f,     0.0f, 0.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f, -1.0f, -1.0f, 1.0f,     0.0f, 1.0f,
                                      -1.0f,  1.0f,  1.0f, 1.0f,     1.0f, 0.0f,
                                      -1.0f,  1.0f, -1.0f, 1.0f,     1.0f, 1.0f,

                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 0.0f, // Right
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                                       1.0f, -1.0f,  1.0f, 1.0f,     1.0f, 1.0f,
                                       1.0f, -1.0f, -1.0f, 1.0f,     1.0f, 0.0f,
                                       1.0f,  1.0f, -1.0f, 1.0f,     0.0f, 0.0f,
                                       1.0f,  1.0f,  1.0f, 1.0f,     0.0f, 1.0f,
                            });

            vertexBufferBinding = new VertexBufferBinding(vertices, sizeof(float) * 6, 0);

            // Create Constant Buffer
            constantBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Load texture and create sampler
            using (var bitmap = TextureLoader.LoadBitmap(devices.WICFactory, "GeneticaMortarlessBlocks.jpg"))
            using (var texture2D = TextureLoader.CreateTexture2DFromBitmap(d3dDevice, bitmap))
                textureView = new ShaderResourceView(d3dDevice, texture2D);

            sampler = new SamplerState(d3dDevice, new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = Color.Black,
                ComparisonFunction = Comparison.Never,
                MaximumAnisotropy = 16,
                MipLodBias = 0,
                MinimumLod =-float.MaxValue,
                MaximumLod = float.MaxValue
            });

            clock = new Stopwatch();
            clock.Start();
        }
        /// <summary>
        /// Create any device dependent resources here.
        /// This method will be called when the device is first
        /// initialized or recreated after being removed or reset.
        /// </summary>
        protected override void CreateDeviceDependentResources()
        {
            // Ensure that if already set the device resources
            // are correctly disposed of before recreating
            RemoveAndDispose(ref quadVertices);
            RemoveAndDispose(ref quadIndices);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            // Load texture
            textureView = ToDispose(ShaderResourceView.FromFile(device, "Texture.png"));

            // Create our sampler state
            samplerState = ToDispose(new SamplerState(device, new SamplerStateDescription()
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                BorderColor = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter = Filter.MinMagMipLinear,
                MaximumAnisotropy = 16,
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
                MipLodBias = 0.0f
            }));

            // Create a quad (two triangles)
            quadVertices = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, new[] {
            /*  Vertex Position         texture UV */
                //0.25f, 0.5f, -0.5f, 1.0f,   0.0f, 0.0f, // Top-left
                //0.75f, 0.5f, -0.5f, 1.0f,   2.0f, 0.0f, // Top-right
                //0.75f, 0.0f, -0.5f, 1.0f,   2.0f, 2.0f, // Base-right
                //0.25f, 0.0f, -0.5f, 1.0f,   0.0f, 2.0f, // Base-left
                -0.75f, 0.75f, 0f, 1.0f,     0.0f, 0.0f, // Top-left
                0.75f, 0.75f, 0f, 1.0f,      2.0f, 0.0f, // Top-right
                0.75f, -0.75f, 0f, 1.0f,     2.0f, 2.0f, // Base-right
                -0.75f, -0.75f, 0f, 1.0f,    0.0f, 2.0f, // Base-left
            }));
            quadBinding = new VertexBufferBinding(quadVertices, Utilities.SizeOf<float>() * 6, 0);

            // v0    v1
            // |-----|
            // | \ A |
            // | B \ |
            // |-----|
            // v3    v2
            quadIndices = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new uint[] {
                0, 1, 2, // A
                2, 3, 0  // B
            }));
        }
Exemple #29
0
        public void Init(Form form)
        {
            ViewportSize  = new Size2F(form.Width, form.Height);
            hViewportSize = new Size2F(form.Width / 2f, form.Height / 2f);

            ModeDescription      backBufferDesc = new ModeDescription(form.Width, form.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm);
            SwapChainDescription swapChainDesc  = new SwapChainDescription()
            {
                ModeDescription   = backBufferDesc,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = Usage.RenderTargetOutput,
                BufferCount       = 1,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
            };

            D3D11.Device.CreateWithSwapChain(DriverType.Hardware, D3D11.DeviceCreationFlags.None, swapChainDesc, out d3dDevice, out swapChain);
            d3dDeviceContext = d3dDevice.ImmediateContext;

            d3dDeviceContext.Rasterizer.SetViewport(0, 0, form.Width, form.Height);
            using (D3D11.Texture2D backBuffer = swapChain.GetBackBuffer <D3D11.Texture2D>(0))
            {
                renderTargetView = new D3D11.RenderTargetView(d3dDevice, backBuffer);
            }

            D3D11.BlendStateDescription blendStateDesc = D3D11.BlendStateDescription.Default();
            blendStateDesc.AlphaToCoverageEnable                 = false;
            blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDesc.RenderTarget[0].SourceBlend           = D3D11.BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend      = D3D11.BlendOption.One;         //
            blendStateDesc.RenderTarget[0].BlendOperation        = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].SourceAlphaBlend      = D3D11.BlendOption.SourceAlpha; //Zero
            blendStateDesc.RenderTarget[0].DestinationAlphaBlend = D3D11.BlendOption.DestinationAlpha;
            blendStateDesc.RenderTarget[0].AlphaBlendOperation   = D3D11.BlendOperation.Maximum;
            blendStateDesc.RenderTarget[0].RenderTargetWriteMask = D3D11.ColorWriteMaskFlags.All;
            blendState = new D3D11.BlendState(d3dDevice, blendStateDesc);

            GeometryBuffer = new GeometryBuffer(this);

            Fonts = new FontCache(this);

            var layout = new D3D11.InputElement[]
            {
                new D3D11.InputElement("POSITION", 0, Format.R32G32_Float, 0, 0),
                new D3D11.InputElement("COLOR", 0, Format.R32G32B32A32_Float, 8, 0),
                new D3D11.InputElement("TEXCOORDS", 0, Format.R32G32_Float, 24, 0),
            };

            var vertexShaderOutput = ShaderBytecode.Compile(vertexShaderCode, "main", "vs_4_0", ShaderFlags.Debug);
            var pixelShaderOutput  = ShaderBytecode.Compile(pixelShaderCode, "main", "ps_4_0", ShaderFlags.Debug);

            vertexShader = new D3D11.VertexShader(Device, vertexShaderOutput);
            pixelShader  = new D3D11.PixelShader(Device, pixelShaderOutput);

            var shaderSignature = ShaderSignature.GetInputSignature(vertexShaderOutput);

            inputLayout = new D3D11.InputLayout(Device, shaderSignature, layout);

            IntPtr data  = System.Runtime.InteropServices.Marshal.AllocHGlobal(4 * 4 * 4);
            var    white = BitConverter.GetBytes(1f);

            for (int i = 0; i < 4 * 4; i++)
            {
                for (int j = 0; j < white.Length; j++)
                {
                    System.Runtime.InteropServices.Marshal.WriteByte(data, i * sizeof(float) + j, white[j]);
                }
            }

            White = new D3D11.Texture2D(Device, new D3D11.Texture2DDescription
            {
                Width             = 4,
                Height            = 4,
                ArraySize         = 1,
                BindFlags         = D3D11.BindFlags.ShaderResource,
                Usage             = D3D11.ResourceUsage.Dynamic,
                CpuAccessFlags    = D3D11.CpuAccessFlags.Write,
                Format            = Format.R32G32B32A32_Float,
                MipLevels         = 1,
                OptionFlags       = D3D11.ResourceOptionFlags.None,
                SampleDescription = new DXGI.SampleDescription(1, 0),
            }, new DataBox[] { new DataBox(data, 4 * 2, 4) });

            System.Runtime.InteropServices.Marshal.FreeHGlobal(data);

            WhiteView = new D3D11.ShaderResourceView(Device, White);

            samplerState = new D3D11.SamplerState(Device, new D3D11.SamplerStateDescription()
            {
                Filter             = D3D11.Filter.MinMagMipLinear,
                AddressU           = D3D11.TextureAddressMode.Clamp,
                AddressV           = D3D11.TextureAddressMode.Clamp,
                AddressW           = D3D11.TextureAddressMode.Clamp,
                BorderColor        = new RawColor4(1f, 0f, 1f, 1f),
                ComparisonFunction = D3D11.Comparison.Never,
                MaximumAnisotropy  = 16,
                MipLodBias         = 0,
                MinimumLod         = 0,
                MaximumLod         = 16
            });

            transfBuffer = new SharpDX.Direct3D11.Buffer(Device,
                                                         new SharpDX.Direct3D11.BufferDescription(sizeof(float) * 4, SharpDX.Direct3D11.ResourceUsage.Dynamic, SharpDX.Direct3D11.BindFlags.ConstantBuffer,
                                                                                                  SharpDX.Direct3D11.CpuAccessFlags.Write, SharpDX.Direct3D11.ResourceOptionFlags.None, sizeof(float)));

            DataStream stream;

            DeviceContext.MapSubresource(transfBuffer, D3D11.MapMode.WriteDiscard, D3D11.MapFlags.None, out stream);

            stream.Write(hViewportSize.Width);
            stream.Write(hViewportSize.Height);

            DeviceContext.UnmapSubresource(transfBuffer, 0);

            DeviceContext.VertexShader.SetShader(vertexShader, null, 0);
            DeviceContext.VertexShader.SetConstantBuffer(0, transfBuffer);
            DeviceContext.PixelShader.SetShader(pixelShader, null, 0);
            DeviceContext.PixelShader.SetSampler(0, samplerState);
            DeviceContext.InputAssembler.InputLayout = inputLayout;
            DeviceContext.OutputMerger.BlendState    = blendState;
        }
Exemple #30
0
        unsafe void InitializeInner(AntiAliasingMode antiAliasingMode)
        {
            worldMatrix = Matrix.Identity;
            textMatrix = Matrix.Identity;

            device = new D3D11.Device(DriverType.Hardware,
                D3D11.DeviceCreationFlags.None,
                new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0, FeatureLevel.Level_10_1, FeatureLevel.Level_10_0 });
            tkDevice = TK.GraphicsDevice.New(device);
            deviceContext = device.ImmediateContext;
            deviceContext.Rasterizer.State = device.CreateRasterizerState();

            //TODO: replace with precompiled bytecode
            const string shaderFile = @"..\..\..\GameUtils\Graphics\shaders.fx";
            ShaderBytecode vertexShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "VS", "vs_4_0", ShaderFlags.Debug);
            ShaderBytecode pixelShaderBytecode = ShaderBytecode.CompileFromFile(shaderFile, "PS", "ps_4_0", ShaderFlags.Debug);
            InitializeShaders(vertexShaderBytecode, pixelShaderBytecode);

            indexBuffers = new D3D11.Buffer[BufferCount];
            vertexBuffers = new D3D11.Buffer[BufferCount];
            for (int i = 0, indexBufferSize = IndexBufferStartSize, vertexBufferSize = VertexBufferStartSize;
                i < BufferCount;
                i++, indexBufferSize <<= BufferSizeStep, vertexBufferSize <<= BufferSizeStep)
            {
                indexBuffers[i] = device.CreateDynamicBuffer(sizeof(int) * indexBufferSize, D3D11.BindFlags.IndexBuffer);
                vertexBuffers[i] = device.CreateDynamicBuffer(sizeof(Vertex) * vertexBufferSize, D3D11.BindFlags.VertexBuffer);
            }
            currentBufferIndex = 0;
            indexBuffer = indexBuffers[0];
            vertexBuffer = vertexBuffers[0];

            //indexBuffer = device.CreateDynamicBuffer(sizeof(int) * IndexBufferSize, D3D11.BindFlags.IndexBuffer);
            //vertexBuffer = device.CreateDynamicBuffer(sizeof(Vertex) * VertexBufferSize, D3D11.BindFlags.VertexBuffer);
            matrixBuffer = device.CreateConstantBuffer(sizeof(MatrixBuffer));
            brushBuffer = device.CreateConstantBuffer(sizeof(Brush.BrushBuffer));

            deviceContext.InputAssembler.SetIndexBuffer(indexBuffer, DXGI.Format.R32_UInt, 0);
            deviceContext.InputAssembler.SetVertexBuffers(0, new D3D11.VertexBufferBinding(vertexBuffer, sizeof(Vertex), 0));
            deviceContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;

            blendState = device.CreateBlendState();
            deviceContext.OutputMerger.SetBlendState(blendState);

            currentWrapMode = WrapMode.Clamp;
            currentInterpolationMode = InterpolationMode.Linear;
            samplerState = device.CreateSamplerState(WrapMode.Clamp, InterpolationMode.Linear);
            deviceContext.PixelShader.SetSampler(0, samplerState);

            sampleDescription = device.GetMultisamplingLevel(antiAliasingMode);

            defaultDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Always,
                D3D11.StencilOperation.Keep,
                D3D11.StencilOperation.Keep);
            clipDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Never,
                D3D11.StencilOperation.Replace,
                D3D11.StencilOperation.Keep);
            clippingDepthStencilState = device.CreateDepthStencilState(D3D11.Comparison.Equal,
                D3D11.StencilOperation.Keep,
                D3D11.StencilOperation.Keep);
            deviceContext.OutputMerger.SetDepthStencilState(defaultDepthStencilState);
        }
Exemple #31
0
        void SetSamplerState(WrapMode wrapMode, InterpolationMode interpolationMode)
        {
            if (wrapMode != currentWrapMode || interpolationMode != currentInterpolationMode)
            {
                D3D11.SamplerState newSamplerState = device.CreateSamplerState(wrapMode, interpolationMode);
                deviceContext.PixelShader.SetSampler(0, newSamplerState);

                samplerState.Dispose();
                samplerState = newSamplerState;
                currentWrapMode = wrapMode;
                currentInterpolationMode = interpolationMode;
            }
        }
Exemple #32
0
        public RectangleGridRendererDX(Tilemap tilemap, Tileset tileset)
        {
            int gridWidth  = tilemap.Width;
            int gridHeight = tilemap.Height;
            // Width and height of each tile in the tileset
            int tileWidth  = tileset.Texture.Width / tileset.RowLength;
            int tileHeight = tileset.Texture.Height / tileset.ColLength;
            // Get the spacing between tiles
            int spacingX = tilemap.SpacingX >= 0 ? tilemap.SpacingX : tileWidth;
            int spacingY = tilemap.SpacingY >= 0 ? tilemap.SpacingY : tileHeight;
            // Calculate the distance from the edge of a pixel to the centre of the pixel as a ratio of the dimensions of the texture
            float halfPixelWidth  = (1 / tileset.Texture.Width) / 2;
            float halfPixelHeight = (1 / tileset.Texture.Height) / 2;

            // Vertices of the rectangle
            // Rectangle drawn as two triangles
            VertexXYUV[] vertices = new VertexXYUV[6 * gridWidth * gridHeight];
            // Loop over rows backwards (top to bottom) s.t. tiles lower down the screen are rendered last
            for (int j = 0; j < gridHeight; j++)
            {
                // Loop over columns from left to right
                for (int i = 0; i < gridWidth; i++)
                {
                    int value = tilemap.TileGrid[i, j];
                    // Check the tile texture is valid for the tileset given
                    if (value >= 0 && value < tileset.NumTiles)
                    {
                        // Calculate the position of the tile in the texture atlas
                        int atlasX = value % tileset.RowLength;
                        int atlasY = value / tileset.ColLength;
                        // Calculate the position co-ordinates for the tile
                        float x0 = i * spacingX + halfPixelWidth;
                        float x1 = i * spacingX + tileWidth - halfPixelWidth;
                        float y0 = j * spacingY + halfPixelHeight;
                        float y1 = j * spacingY + tileHeight - halfPixelHeight;
                        // Calculate the texture co-ordinates for the tile
                        float u0 = (float)atlasX / tileset.RowLength;
                        float u1 = (float)(atlasX + 1) / tileset.RowLength;
                        float v0 = (float)atlasY / tileset.ColLength;
                        float v1 = (float)(atlasY + 1) / tileset.ColLength;
                        // Set the vertex's position and texture co-ordinates
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 0] = new VertexXYUV(new Vector2(x0, y1), new Vector2(u0, v0));
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 1] = new VertexXYUV(new Vector2(x1, y1), new Vector2(u1, v0));
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 2] = new VertexXYUV(new Vector2(x1, y0), new Vector2(u1, v1));
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 3] = new VertexXYUV(new Vector2(x1, y0), new Vector2(u1, v1));
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 4] = new VertexXYUV(new Vector2(x0, y0), new Vector2(u0, v1));
                        vertices[6 * (i + gridWidth * (gridHeight - j - 1)) + 5] = new VertexXYUV(new Vector2(x0, y1), new Vector2(u0, v0));
                    }
                }
            }
            numVertices = vertices.Count();

            // Create a vertex buffer
            vertexBuffer = D3D11.Buffer.Create(d3dDevice, D3D11.BindFlags.VertexBuffer, vertices);

            // Create the vertex and pixel shaders
            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile("EngineAssets/VertexShader.hlsl", "main", "vs_4_0", ShaderFlags.Debug))
            {
                inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                vertexShader   = new D3D11.VertexShader(d3dDevice, vertexShaderByteCode);
            }
            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile("EngineAssets/PixelShader.hlsl", "main", "ps_4_0", ShaderFlags.Debug))
            {
                pixelShader = new D3D11.PixelShader(d3dDevice, pixelShaderByteCode);
            }

            // Array of input elements tell D3D how data is stored in vertex buffer
            inputElements = new D3D11.InputElement[]
            {
                // R32G32_Float tells d3d that a position is a Vector2 of floats
                new D3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32_Float, 0, 0, D3D11.InputClassification.PerVertexData, 0),
                new D3D11.InputElement("TEXTUREUV", 0, SharpDX.DXGI.Format.R32G32_Float, 8, 0, D3D11.InputClassification.PerVertexData, 0)
            };

            // Create the input layout matching the input elements to shader input signature
            inputLayout = new D3D11.InputLayout(d3dDevice, inputSignature, inputElements);

            // Create the sampler used to sample textures in the shaders
            samplerState = new D3D11.SamplerState(d3dDevice,
                                                  new D3D11.SamplerStateDescription
            {
                AddressU = D3D11.TextureAddressMode.Wrap,
                AddressV = D3D11.TextureAddressMode.Wrap,
                AddressW = D3D11.TextureAddressMode.Wrap,
                Filter   = D3D11.Filter.MinMagPointMipLinear
            });

            // Create the world view projection buffer
            worldViewProjBuffer = new SharpDX.Direct3D11.Buffer(d3dDevice, Utilities.SizeOf <Matrix>(), D3D11.ResourceUsage.Default,
                                                                D3D11.BindFlags.ConstantBuffer, D3D11.CpuAccessFlags.None, D3D11.ResourceOptionFlags.None, 0);
        }