Beispiel #1
0
        public IndexBuffer(Device device, ushort[] indices)
        {
            if(device == null)
            {
                throw new ArgumentNullException("device");
            }

            if(indices == null)
            {
                throw new ArgumentNullException("indices");
            }

            using(var dataStream = new DataStream(sizeof(UInt16)*indices.Length, true, true))
            {
                dataStream.WriteRange(indices);
                dataStream.Position = 0;

                Buffer = new Buffer(device,
                                    dataStream,
                                    (int) dataStream.Length,
                                    ResourceUsage.Immutable,
                                    BindFlags.IndexBuffer,
                                    CpuAccessFlags.None,
                                    ResourceOptionFlags.None,
                                    0);
            }

            Count = indices.Length;
        }
Beispiel #2
0
        public Postprocess(Game game, string shaderFile, RenderTexture rt = null, string name = null)
        {
            this.game = game;
            this.renderTexture = rt;
            if(name == null)
            {
                this.Name = System.IO.Path.GetFileNameWithoutExtension(shaderFile);
                this.debugName = "Postprocess " + this.Name;
            }
            else
            {
                this.debugName = this.Name = name;
            }
            this.shaderFile = shaderFile;

            var desc = SamplerStateDescription.Default();
            desc.Filter = Filter.MinMagMipPoint;
            defaultSamplerStateDescription = desc;

            LoadShader();
            BuildVertexBuffer();
            ppBuffer = Material.CreateBuffer<LiliumPostprocessData>();

            game.AddObject(this);
        }
Beispiel #3
0
        public Buffer(BufferDescription description)
        {
            _description = description;
            _flags = GetBufferFlagsFromDescription(description);

            _nativeBuffer = new SharpDX.Direct3D11.Buffer(GraphicManager.Device, description);
        }
Beispiel #4
0
        public Buffer(BufferDescription description, BufferFlags flags)
        {
            _description = description;
            _flags = flags;

            _nativeBuffer = new SharpDX.Direct3D11.Buffer(GraphicManager.Device, description);
        }
Beispiel #5
0
        public Rectangle(Renderer renderer, Vector2I screenSize, Vector2I position, Vector2I size, Vector4 color, float depth = 0.0f)
        {
            _shader = renderer.ColorShader;
            Position = position;
            ScreenSize = screenSize;
            Size = size;
            _color = color;
            _changed = true;
            Depth = depth;

            int vertexCount = 4;
            _indexCount = 6;

            _vertices = new VertexDefinition.PositionColor[vertexCount];
            UInt32[] indices = { 0, 1, 2, 0, 3, 1 };

            _vertexBuffer = Buffer.Create(renderer.DirectX.Device, _vertices,
                new BufferDescription
                {
                    Usage = ResourceUsage.Dynamic,
                    SizeInBytes = Utilities.SizeOf<VertexDefinition.PositionColor>() * vertexCount,
                    BindFlags = BindFlags.VertexBuffer,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    OptionFlags = ResourceOptionFlags.None,
                    StructureByteStride = 0
                });

            _indexBuffer = Buffer.Create(renderer.DirectX.Device, BindFlags.IndexBuffer, indices);
        }
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Texture11 texture, SharpDX.Direct3D.PrimitiveTopology primitiveType, float opacity = 1.0f)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);

            }
            renderContext.devContext.InputAssembler.PrimitiveTopology = primitiveType;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);
            SharpDX.Matrix mat = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11;
            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, texture != null, opacity);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);
            if (texture != null)
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, texture.ResourceView);
            }
            else
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, null);
            }
            renderContext.devContext.Draw(count, 0);
        }
        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;
        }
        public StencilShadowRenderer(Game game)
        {
            this.game = game;

            var desc = new MaterialPassDesc();
            desc.ManualConstantBuffers = true;
            desc.ShaderFile = "StencilShadow.hlsl";
            desc.BlendStates.RenderTarget[0].IsBlendEnabled = true;
            desc.BlendStates.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha;
            desc.BlendStates.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha;
            desc.BlendStates.RenderTarget[0].BlendOperation = BlendOperation.Add;
            desc.BlendStates.RenderTarget[0].SourceAlphaBlend = BlendOption.One;
            desc.BlendStates.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            desc.BlendStates.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add;
            desc.BlendStates.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            desc.DepthStencilStates.IsDepthEnabled = true;
            desc.DepthStencilStates.DepthWriteMask = DepthWriteMask.Zero;
            desc.DepthStencilStates.DepthComparison = Comparison.LessEqual;
            desc.DepthStencilStates.IsStencilEnabled = true;
            desc.DepthStencilStates.StencilReadMask = 1;
            desc.DepthStencilStates.StencilWriteMask = 1;
            desc.DepthStencilStates.FrontFace.FailOperation = StencilOperation.Keep;
            desc.DepthStencilStates.FrontFace.DepthFailOperation = StencilOperation.Keep;
            desc.DepthStencilStates.FrontFace.PassOperation = StencilOperation.Replace;
            desc.DepthStencilStates.FrontFace.Comparison = Comparison.NotEqual;
            desc.StencilRef = 1;
            pass = new MaterialPass(game.Device, desc, "StencilShadow");
            buffer = Material.CreateBuffer<ShaderData>();
        }
Beispiel #9
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,
            });
        }
        /****************************************************************************************************
         * 
         ****************************************************************************************************/
        public void UpdateBuffer(DeviceContext context, Matrix world, ICamera camera)
        {
            var view = camera.CreateViewMatrix();
            var projection = camera.CreateProjectionMatrix(Resolution);
            Matrices[0] = Matrix.Transpose(world);
            Matrices[1] = Matrix.Transpose(view);
            Matrices[2] = Matrix.Transpose(projection);
            Matrices[3] = Matrix.Transpose(world * view);
            Matrices[4] = Matrix.Transpose(world * view * projection);
            Matrices[5] = Matrix.Transpose(view * projection);
            Matrices[6] = Matrix.Invert(world);
            Matrices[7] = Matrix.Invert(world * view);
            Matrices[8] = Matrix.Transpose(Matrix.Identity * Matrix.Scaling(LightPosition));
            Matrices[9] = new Matrix(new float[] 
            {
                LerpTime, AbsoluteTime, Resolution.X, Resolution.Y,
                BeatTime, Lead,0,0,
                Nisse0, Nisse1, Nisse2, Nisse3,
                0,0,0,0,
            });
            if (Buffer == null)
            {
                Buffer = new Buffer(context.Device, Matrices.Length * Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            }

            context.UpdateSubresource(Matrices, Buffer);
        }
Beispiel #11
0
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Matrix mat, bool triangleStrip)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);

            }

            renderContext.devContext.InputAssembler.PrimitiveTopology = triangleStrip ? SharpDX.Direct3D.PrimitiveTopology.TriangleStrip : SharpDX.Direct3D.PrimitiveTopology.TriangleList;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);

            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, false);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);

            renderContext.devContext.PixelShader.SetShaderResource(0, null);

            renderContext.devContext.Draw(count, 0);
        }
Beispiel #12
0
        protected void InitializeShaders(string pathVert, string pathPixel)
        {
            ShaderSignature inputSignature;

            using (var vertexShaderByteCode = ShaderBytecode.CompileFromFile(pathVert, "VS", "vs_5_0", ShaderFlags.PackMatrixRowMajor))
            {
                inputSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);
                VertShader     = new VertexShader(device, vertexShaderByteCode);
            }

            using (var pixelShaderByteCode = ShaderBytecode.CompileFromFile(pathPixel, "PS", "ps_5_0", ShaderFlags.PackMatrixRowMajor))
            {
                PixShader = new PixelShader(device, pixelShaderByteCode);
            }

            Layout = new InputLayout(device, inputSignature, InputElem);

            LightBuffer           = new Direct3D11.Buffer(device, Utilities.SizeOf <LightBuf>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            MatrixBuffer          = new Direct3D11.Buffer(device, Utilities.SizeOf <MatrixBuf>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            MaterialBuffer        = new Direct3D11.Buffer(device, Utilities.SizeOf <MaterialBuf>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            ShadowTransformBuffer = new Direct3D11.Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            FlagsBuffer           = new Direct3D11.Buffer(device, Utilities.SizeOf <FlagsBuf>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            var samplerStateDescription = new SamplerStateDescription
            {
                AddressU = TextureAddressMode.Wrap,
                AddressV = TextureAddressMode.Wrap,
                AddressW = TextureAddressMode.Wrap,
                Filter   = Filter.MinMagMipLinear
            };

            Sampler = new SamplerState(device, samplerStateDescription);
        }
Beispiel #13
0
        internal void Init(string name, ref BufferDescription description, IntPtr? initData)
        {
            m_description = description;
            m_elementCount = description.SizeInBytes / Math.Max(1, Description.StructureByteStride);

            try
            {
                m_buffer = new Buffer(MyRender11.Device, initData ?? default(IntPtr), description)
                {
                    DebugName = name,
                };
            }
            catch (SharpDXException e)
            {
                MyRenderProxy.Log.WriteLine("Error during allocation of a directX buffer!");
                LogStuff(e);
                throw;
            }

            try
            {
                AfterBufferInit();
            }
            catch (SharpDXException e)
            {
                MyRenderProxy.Log.WriteLine("Error during creating a view or an unordered access to a directX buffer!");
                LogStuff(e);
                throw;
            }

            IsReleased = false;
        }
Beispiel #14
0
        /// <summary>
        /// Create a buffer containing all GameColors
        /// </summary>
        public static SharpDX.Direct3D11.Buffer CreateGameColorBuffer(Device device)
        {
            int numcolors = GameColorRGB.NUMCOLORS;

            var arr = new int[numcolors];
            for (int i = 0; i < numcolors; ++i)
            {
                var gc = (GameColor)i;
                arr[i] = GameColorRGB.FromGameColor(gc).ToInt32();
            }

            SharpDX.Direct3D11.Buffer colorBuffer;

            using (var stream = DataStream.Create(arr, true, false))
            {
                colorBuffer = new SharpDX.Direct3D11.Buffer(device, stream, new BufferDescription()
                {
                    BindFlags = BindFlags.ShaderResource,
                    CpuAccessFlags = CpuAccessFlags.None,
                    OptionFlags = ResourceOptionFlags.None,
                    SizeInBytes = sizeof(int) * arr.Length,
                    Usage = ResourceUsage.Immutable,
                });
            }

            return colorBuffer;
        }
Beispiel #15
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);
        }
        /// <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;

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

            // v0    v1
            // |-----|
            // | \ A |
            // | B \ |
            // |-----|
            // v3    v2
            quadIndices = ToDispose(Buffer.Create(device, BindFlags.IndexBuffer, new ushort[] {
                0, 1, 2, // A
                2, 3, 0  // B
            }));
        }
Beispiel #17
0
        //Constructor
        internal Geometry(SharpDevice device, ModelGeometry data, bool animated)
        {
            this.Name = data.Name;
            this.Device = device;

            //Data
            List<VertexFormat> vertices = new List<VertexFormat>(data.Vertices);

            List<int> indices = new List<int>(data.Indices);

            VertexCount = vertices.Count;
            IndexCount = indices.Count;

            //Vertex Buffer
            VertexBuffer = SharpDX.Direct3D11.Buffer.Create<VertexFormat>(Device.Device, BindFlags.VertexBuffer, vertices.ToArray());

            //Index Buffer
            IndexBuffer = SharpDX.Direct3D11.Buffer.Create<int>(Device.Device, BindFlags.IndexBuffer, indices.ToArray());

            Material = new Material(data.Material);

            IsAnimated = animated;

            transformBuffer = new Buffer11(Device.Device, Utilities.SizeOf<SkinShaderInformation>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            paletteBuffer = new Buffer11(Device.Device, Utilities.SizeOf<Matrix>() * 256, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
        }
        public static UnorderedAccessView CreateBufferUAV(SharpDX.Direct3D11.Device device, Buffer buffer, UnorderedAccessViewBufferFlags flags = UnorderedAccessViewBufferFlags.None)
        {
            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
            {
                Dimension = UnorderedAccessViewDimension.Buffer,
                Buffer = new UnorderedAccessViewDescription.BufferResource { FirstElement = 0 }
            };
            if ((buffer.Description.OptionFlags & ResourceOptionFlags.BufferAllowRawViews) == ResourceOptionFlags.BufferAllowRawViews)
            {
                // A raw buffer requires R32_Typeless
                uavDesc.Format = Format.R32_Typeless;
                uavDesc.Buffer.Flags = UnorderedAccessViewBufferFlags.Raw | flags;
                uavDesc.Buffer.ElementCount = buffer.Description.SizeInBytes / 4;
            }
            else if ((buffer.Description.OptionFlags & ResourceOptionFlags.BufferStructured) == ResourceOptionFlags.BufferStructured)
            {
                uavDesc.Format = Format.Unknown;
                uavDesc.Buffer.Flags = flags;
                uavDesc.Buffer.ElementCount = buffer.Description.SizeInBytes / buffer.Description.StructureByteStride;
            }
            else
            {
                throw new ArgumentException("Buffer must be raw or structured", "buffer");
            }

            return new UnorderedAccessView(device, buffer, uavDesc);
        }
Beispiel #19
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);
        }
        protected override void CreateDeviceDependentResources()
        {
            base.CreateDeviceDependentResources();

            RemoveAndDispose(ref vertexBuffer);

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

            List<Vertex> vertices = new List<Vertex>();

            vertices.AddRange(new[] {
                new Vertex(0, 0, -4, Vector3.UnitY, Color.Blue),
                new Vertex(0, 0, 4,Vector3.UnitY,  Color.Blue),
                new Vertex(-4, 0, 0, Vector3.UnitY, Color.Red),
                new Vertex(4, 0, 0,Vector3.UnitY,  Color.Red),
            });
            for (var i = -4f; i < -0.09f; i += 0.2f)
            {
                vertices.Add(new Vertex(i, 0, -4, Color.Gray));
                vertices.Add(new Vertex(i, 0, 4, Color.Gray));
                vertices.Add(new Vertex(-i, 0, -4, Color.Gray));
                vertices.Add(new Vertex(-i, 0, 4, Color.Gray));

                vertices.Add(new Vertex(-4, 0, i, Color.Gray));
                vertices.Add(new Vertex(4, 0, i, Color.Gray));
                vertices.Add(new Vertex(-4, 0, -i, Color.Gray));
                vertices.Add(new Vertex(4, 0, -i, Color.Gray));
            }
            vertexCount = vertices.Count;
            vertexBuffer = ToDispose(Buffer.Create(device, BindFlags.VertexBuffer, vertices.ToArray()));
        }
Beispiel #21
0
        public Vector2I UpdateVertexArray(string text, ref VertexDefinition.PositionTextureColor[] vertices, ref Buffer vertexBuffer, Color defaultColor, List<TexturedRectangle> icons, int positionX = 0, int positionY = 0)
        {
            icons.Clear();
            Color color = defaultColor;
            int width = 0;
            int maxWidth = 0;
            int height = Characters.First().Value.height;
            int maxHeight = height;
            for (int i = 0; i < text.Length; i++)
            {
                char letter = text[i];
                if (letter == '\n')
                {
                    maxWidth = Math.Max(maxWidth, width);
                    width = 0;
                    positionX = 0;
                    positionY += height;
                    maxHeight += height;
                    continue;
                }
                if (letter == '[')
                {
                    if (text[i + 1] == '[')
                        continue;
                    string token = text.Substring(i + 1, text.IndexOf(']', i + 1) - (i + 1));
                    if (!ColorParser.TryParse(token, out color))
                    {
                        if (token == "-")
                            color = defaultColor;
                        else if (token == "gold")
                        {
                            icons.Add(new TexturedRectangle(_context,
                                _context.TextureManager.Create("gold.png", "Data/UI/Icons/"), new Vector2I(height, height)));
                            positionX += height + 1;
                            width += height + 1;
                        }
                        else
                            throw new InvalidOperationException("Unexpected token : " + token);
                    }
                    i = text.IndexOf(']', i + 1);
                    continue;
                }
                Character c = Characters[letter];
                Vector4 colorAsVector = color.ToVector4();
                vertices[i * 4] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX, positionY, 0.0f), texture = new Vector2(c.uLeft, c.vTop), color = colorAsVector }; //Top left
                vertices[i * 4 + 1] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX + c.width, positionY + c.height, 0.0f), texture = new Vector2(c.uRight, c.vBottom), color = colorAsVector }; //Right bottom
                vertices[i * 4 + 2] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX, positionY + c.height, 0.0f), texture = new Vector2(c.uLeft, c.vBottom), color = colorAsVector }; //Left bottom
                vertices[i * 4 + 3] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX + c.width, positionY, 0.0f), texture = new Vector2(c.uRight, c.vTop), color = colorAsVector }; //Top right

                positionX += c.width + 1;
                width += c.width + 1;
            }
            DataStream mappedResource;
            _context.DirectX.Device.ImmediateContext.MapSubresource(vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None,
                out mappedResource);
            mappedResource.WriteRange(vertices);
            _context.DirectX.Device.ImmediateContext.UnmapSubresource(vertexBuffer, 0);
            return  new Vector2I(Math.Max(maxWidth, width), maxHeight);
        }
 void IDisposable.Dispose()
 {
     if (Buffer != null)
     {
         Buffer.Dispose();
         Buffer = null;
     }
 }
Beispiel #23
0
 internal void SetConstantBuffer(int slot, Buffer constantBuffer)
 {
     if (constantBuffer == m_constantBuffers[slot])
         return;
     m_constantBuffers[slot] = constantBuffer;
     m_shaderStage.SetConstantBuffer(slot, constantBuffer);
     m_statistics.SetConstantBuffers++;
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Direct3D11 Device</param>
        public BodyJointStatusBuffer(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.buffer = new SharpDX.Direct3D11.Buffer(device, JointBufferDescriptor.DynamicBuffer(new BufferStride(4)));
            this.shaderView = new ShaderResourceView(device, this.buffer);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Direct3D11 Device</param>
        public BodyCameraPositionBuffer(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.buffer = new SharpDX.Direct3D11.Buffer(device, JointBufferDescriptor.CameraSpacePositionBuffer);
            this.shaderView = new ShaderResourceView(device, this.buffer);
        }
        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),
            });

        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Direct3D11 Device</param>
        /// <param name="maxFaceCount">Maximum body count</param>
        public DynamicHdFaceStructuredBuffer(Device device, int maxFaceCount)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            var desc = DescriptorUtils.DynamicStructuredBuffer(new BufferElementCount(maxFaceCount * (int)Microsoft.Kinect.Face.FaceModel.VertexCount), new BufferStride(12));
            this.buffer = new SharpDX.Direct3D11.Buffer(device, desc);
            this.shaderView = new ShaderResourceView(device, this.buffer);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="device">Direct3D11 Device</param>
        public AppendPointCloudBuffer(Device device)
        {
            if (device == null)
                throw new ArgumentNullException("device");

            this.buffer = new SharpDX.Direct3D11.Buffer(device, PointCloudDescriptors.PositionBuffer);
            this.shaderView = new ShaderResourceView(device, this.buffer);
            this.unorderedView = new UnorderedAccessView(device, this.buffer, PointCloudDescriptors.AppendView);
        }
        internal void Clear()
        {
            matTexturesID = MyMaterialProxyId.NULL;
            matConstantsID = -1;

            objectData = new MyObjectData();

            objectBuffer = null;
        }
Beispiel #30
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);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="device">Device</param>
 /// <param name="size">Buffer size</param>
 public SharpOutputBuffer(SharpDevice device, int size)
 {
     Device = device;
     BufferDescription desc = new BufferDescription()
     {
         SizeInBytes = size,
         BindFlags = BindFlags.VertexBuffer | BindFlags.StreamOutput,
         Usage = ResourceUsage.Default,
     };
     _buffer = new Buffer11(Device.Device, desc);
 }
Beispiel #32
0
        //Вынести в наследника
        public bool Initialize(Device dev, Direct3D11.Buffer vertBuffer, bool isShadowMap)
        {
            device       = dev;
            VertexBuffer = vertBuffer;

            InputElem = new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
            };
            InputTypeSize = Utilities.SizeOf <VertexPositionNormalTexture>();

            var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var path     = Path.GetDirectoryName(location) + "\\Shaders\\ShadowMapShaders.hlsl";

            InitializeShaders(path, path);

            return(true);
        }
Beispiel #33
0
 public InOutStructuredBufferManager(Device device, int elementCount)
 {
     Buffer  = new Buffer(device, elementCount * elementSizeInBytes, ResourceUsage.Default, BindFlags.UnorderedAccess | BindFlags.ShaderResource, CpuAccessFlags.None, ResourceOptionFlags.BufferStructured, structureByteStride: elementSizeInBytes);
     InView  = new ShaderResourceView(device, Buffer);
     OutView = new UnorderedAccessView(device, Buffer);
 }
 protected override void FreeResource()
 {
     Buffer?.Dispose();
     Buffer = null;
 }
        /// <summary>
        /// Updates resources associated with a holographic camera's swap chain.
        /// The app does not access the swap chain directly, but it does create
        /// resource views for the back buffer.
        /// </summary>
        public void CreateResourcesForBackBuffer(
            DeviceResources deviceResources,
            HolographicCameraRenderingParameters cameraParameters
            )
        {
            var device = deviceResources.D3DDevice;

            // Get the WinRT object representing the holographic camera's back buffer.
            IDirect3DSurface surface = cameraParameters.Direct3D11BackBuffer;

            // Get a DXGI interface for the holographic camera's back buffer.
            // Holographic cameras do not provide the DXGI swap chain, which is owned
            // by the system. The Direct3D back buffer resource is provided using WinRT
            // interop APIs.
            InteropStatics.IDirect3DDxgiInterfaceAccess surfaceDxgiInterfaceAccess = surface as InteropStatics.IDirect3DDxgiInterfaceAccess;
            IntPtr pResource = surfaceDxgiInterfaceAccess.GetInterface(InteropStatics.ID3D11Resource);

            SharpDX.Direct3D11.Resource resource = SharpDX.Direct3D11.Resource.FromPointer <SharpDX.Direct3D11.Resource>(pResource);
            Marshal.Release(pResource);

            // Get a Direct3D interface for the holographic camera's back buffer.
            Texture2D cameraBackBuffer = resource.QueryInterface <Texture2D>();

            // Determine if the back buffer has changed. If so, ensure that the render target view
            // is for the current back buffer.
            if ((null == d3dBackBuffer) || (d3dBackBuffer.NativePointer != cameraBackBuffer.NativePointer))
            {
                // This can change every frame as the system moves to the next buffer in the
                // swap chain. This mode of operation will occur when certain rendering modes
                // are activated.
                d3dBackBuffer = cameraBackBuffer;

                // Create a render target view of the back buffer.
                // Creating this resource is inexpensive, and is better than keeping track of
                // the back buffers in order to pre-allocate render target views for each one.
                d3dRenderTargetView = this.ToDispose(new RenderTargetView(device, BackBufferTexture2D));

                // Get the DXGI format for the back buffer.
                // This information can be accessed by the app using CameraResources::GetBackBufferDXGIFormat().
                Texture2DDescription backBufferDesc = BackBufferTexture2D.Description;
                dxgiFormat = backBufferDesc.Format;

                // Check for render target size changes.
                Size currentSize = holographicCamera.RenderTargetSize;
                if (d3dRenderTargetSize != currentSize)
                {
                    // Set render target size.
                    d3dRenderTargetSize = HolographicCamera.RenderTargetSize;

                    // A new depth stencil view is also needed.
                    this.RemoveAndDispose(ref d3dDepthStencilView);
                }
            }

            // Refresh depth stencil resources, if needed.
            if (null == DepthStencilView)
            {
                // Create a depth stencil view for use with 3D rendering if needed.
                var depthStencilDesc = new Texture2DDescription
                {
                    Format            = SharpDX.DXGI.Format.D16_UNorm,
                    Width             = (int)RenderTargetSize.Width,
                    Height            = (int)RenderTargetSize.Height,
                    ArraySize         = IsRenderingStereoscopic ? 2 : 1, // Create two textures when rendering in stereo.
                    MipLevels         = 1,                               // Use a single mipmap level.
                    BindFlags         = BindFlags.DepthStencil,
                    SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0)
                };

                using (var depthStencil = new Texture2D(device, depthStencilDesc))
                {
                    var depthStencilViewDesc = new DepthStencilViewDescription();
                    depthStencilViewDesc.Dimension = IsRenderingStereoscopic ? DepthStencilViewDimension.Texture2DArray : DepthStencilViewDimension.Texture2D;
                    depthStencilViewDesc.Texture2DArray.ArraySize = IsRenderingStereoscopic ? 2 : 0;
                    d3dDepthStencilView = this.ToDispose(new DepthStencilView(device, depthStencil, depthStencilViewDesc));
                }
            }

            // Create the constant buffer, if needed.
            if (null == viewProjectionConstantBuffer)
            {
                // Create a constant buffer to store view and projection matrices for the camera.
                ViewProjectionConstantBuffer viewProjectionConstantBufferData = new ViewProjectionConstantBuffer();
                viewProjectionConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                                  device,
                                                                  BindFlags.ConstantBuffer,
                                                                  ref viewProjectionConstantBufferData));
            }
        }
Beispiel #36
0
        public UnitSphere(Device device, byte[] vsbytes, int detail)
        {
            InputLayout = new InputLayout(device, vsbytes, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                //new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
            });



            List <Vector3>            verts   = new List <Vector3>();
            Dictionary <Vector3, int> vdict   = new Dictionary <Vector3, int>();
            List <SphTri>             curtris = new List <SphTri>();
            List <SphTri>             nxttris = new List <SphTri>();

            verts.Add(new Vector3(-1.0f, 0.0f, 0.0f));
            verts.Add(new Vector3(1.0f, 0.0f, 0.0f));
            verts.Add(new Vector3(0.0f, -1.0f, 0.0f));
            verts.Add(new Vector3(0.0f, 1.0f, 0.0f));
            verts.Add(new Vector3(0.0f, 0.0f, -1.0f));
            verts.Add(new Vector3(0.0f, 0.0f, 1.0f));
            curtris.Add(new SphTri(0, 4, 2));
            curtris.Add(new SphTri(4, 1, 2));
            curtris.Add(new SphTri(1, 5, 2));
            curtris.Add(new SphTri(5, 0, 2));
            curtris.Add(new SphTri(4, 0, 3));
            curtris.Add(new SphTri(1, 4, 3));
            curtris.Add(new SphTri(5, 1, 3));
            curtris.Add(new SphTri(0, 5, 3));

            for (int i = 0; i < verts.Count; i++)
            {
                vdict[verts[i]] = i;
            }


            for (int i = 0; i < detail; i++)
            {
                nxttris.Clear();
                foreach (var tri in curtris)
                {
                    Vector3 v1 = verts[tri.v1];
                    Vector3 v2 = verts[tri.v2];
                    Vector3 v3 = verts[tri.v3];
                    Vector3 s1 = Vector3.Normalize(v1 + v2);
                    Vector3 s2 = Vector3.Normalize(v2 + v3);
                    Vector3 s3 = Vector3.Normalize(v3 + v1);
                    int     i1, i2, i3;
                    if (!vdict.TryGetValue(s1, out i1))
                    {
                        i1 = verts.Count;
                        verts.Add(s1);
                        vdict[s1] = i1;
                    }
                    if (!vdict.TryGetValue(s2, out i2))
                    {
                        i2 = verts.Count;
                        verts.Add(s2);
                        vdict[s2] = i2;
                    }
                    if (!vdict.TryGetValue(s3, out i3))
                    {
                        i3 = verts.Count;
                        verts.Add(s3);
                        vdict[s3] = i3;
                    }
                    nxttris.Add(new SphTri(tri.v1, i1, i3));
                    nxttris.Add(new SphTri(tri.v2, i2, i1));
                    nxttris.Add(new SphTri(tri.v3, i3, i2));
                    nxttris.Add(new SphTri(i1, i2, i3));
                }
                var cur = curtris;
                curtris = nxttris;
                nxttris = cur;
            }


            List <Vector4> vdata = new List <Vector4>();

            foreach (var vert in verts)
            {
                vdata.Add(new Vector4(vert, 1.0f));
            }

            List <uint> idata = new List <uint>();

            foreach (var tri in curtris)
            {
                idata.Add((uint)tri.v1);
                idata.Add((uint)tri.v2);
                idata.Add((uint)tri.v3);
            }


            VertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, vdata.ToArray());
            vbbinding    = new VertexBufferBinding(VertexBuffer, 16, 0);

            IndexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, idata.ToArray());
            indexcount  = idata.Count;
        }
Beispiel #37
0
 void InitializeTriangle()
 {
     m_triangleVertexBuffer = D3D11.Buffer.Create <VertexPositionColor>(m_d3d11Device, D3D11.BindFlags.VertexBuffer, m_vertices);
 }
Beispiel #38
0
        static string ProfileBuffer <T>(ref DeviceContext context, ref D3DBuffer buffer, T[] writeData) where T : struct
        {
            string info = "";

            Tuple <string, MapMode> modeList;

            info += "Map-Read Test:\r\n";
            try
            {
                context.MapSubresource(buffer, MapMode.Read, /* wait if busy */ 0, out DataStream readStream);
                info += "  length: " + readStream.Length + "\r\n";
                info += "  read: " + readStream.CanRead + "\r\n";
                info += "  write: " + readStream.CanWrite + "\r\n";
                info += "  seek: " + readStream.CanSeek + "\r\n";
                if (readStream.CanRead)
                {
                    info += "  Content:\r\n";
                    while (readStream.RemainingLength > 0)
                    {
                        info += "  " + (readStream.Length - readStream.RemainingLength) + ":" + readStream.Read <T>().ToString() + "\r\n";
                    }
                }
                context.UnmapSubresource(buffer, 0);
                readStream.Dispose();
            }
            catch (Exception e)
            {
                info += "  exception: " + e.Message + "\r\n";
            }

            info += "Map-Write Test:\r\n";
            try
            {
                bool readBack = false;
                context.MapSubresource(buffer, MapMode.Write, /* wait if busy */ 0, out DataStream writeStream);
                info += "  length: " + writeStream.Length + "\r\n";
                info += "  read: " + writeStream.CanRead + "\r\n";
                info += "  write: " + writeStream.CanWrite + "\r\n";
                info += "  seek: " + writeStream.CanSeek + "\r\n";
                if (writeStream.CanWrite)
                {
                    writeStream.WriteRange <T>(writeData);
                    readBack = true;
                }
                context.UnmapSubresource(buffer, 0);
                writeStream.Dispose();
                if (readBack)
                {
                    context.MapSubresource(buffer, MapMode.Read, 0, out DataStream readStream);
                    if (readStream.CanRead)
                    {
                        info += "  Content After Write:\r\n";
                        while (readStream.RemainingLength > 0)
                        {
                            info += "  " + (readStream.Length - readStream.RemainingLength) + ":" + readStream.Read <T>().ToString() + "\r\n";
                        }
                    }
                    context.UnmapSubresource(buffer, 0);
                    readStream.Dispose();
                }
            }
            catch (Exception e)
            {
                info += "  exception: " + e.Message + "\r\n";
            }

            info += "Map-RW Test:\r\n";
            try
            {
                bool readBack = false;
                context.MapSubresource(buffer, MapMode.ReadWrite, /* wait if busy */ 0, out DataStream writeStream);
                info += "  length: " + writeStream.Length + "\r\n";
                info += "  read: " + writeStream.CanRead + "\r\n";
                info += "  write: " + writeStream.CanWrite + "\r\n";
                info += "  seek: " + writeStream.CanSeek + "\r\n";
                if (writeStream.CanRead)
                {
                    info += "  Read Content:\r\n";
                    while (writeStream.RemainingLength > 0)
                    {
                        info += "  " + (writeStream.Length - writeStream.RemainingLength) + ":" + writeStream.Read <T>().ToString() + "\r\n";
                    }
                }
                if (writeStream.CanWrite)
                {
                    writeStream.WriteRange <T>(writeData);
                    readBack = true;
                }
                context.UnmapSubresource(buffer, 0);
                writeStream.Dispose();
                if (readBack)
                {
                    context.MapSubresource(buffer, MapMode.Read, 0, out DataStream readStream);
                    if (readStream.CanRead)
                    {
                        info += "  Content After Write:\r\n";
                        while (readStream.RemainingLength > 0)
                        {
                            info += "  " + (readStream.Length - readStream.RemainingLength) + ":" + readStream.Read <T>().ToString() + "\r\n";
                        }
                    }
                    context.UnmapSubresource(buffer, 0);
                    readStream.Dispose();
                }
            }
            catch (Exception e)
            {
                info += "  exception: " + e.Message + "\r\n";
            }

            info += "Map-Write-Discard Test:\r\n";
            try
            {
                bool readBack = false;
                context.MapSubresource(buffer, MapMode.WriteDiscard, /* wait if busy */ 0, out DataStream writeStream);
                info += "  length: " + writeStream.Length + "\r\n";
                info += "  read: " + writeStream.CanRead + "\r\n";
                info += "  write: " + writeStream.CanWrite + "\r\n";
                info += "  seek: " + writeStream.CanSeek + "\r\n";
                if (writeStream.CanWrite)
                {
                    writeStream.WriteRange <T>(writeData);
                    readBack = true;
                }
                context.UnmapSubresource(buffer, 0);
                writeStream.Dispose();
                if (readBack)
                {
                    context.MapSubresource(buffer, MapMode.Read, 0, out DataStream readStream);
                    if (readStream.CanRead)
                    {
                        info += "  Content After Write:\r\n";
                        while (readStream.RemainingLength > 0)
                        {
                            info += "  " + (readStream.Length - readStream.RemainingLength) + ":" + readStream.Read <T>().ToString() + "\r\n";
                        }
                    }
                    context.UnmapSubresource(buffer, 0);
                    readStream.Dispose();
                }
            }
            catch (Exception e)
            {
                info += "  exception: " + e.Message + "\r\n";
            }
            return(info);
        }
Beispiel #39
0
 /// <summary>
 /// Updates a buffer using UpdateSubresource.
 /// </summary>
 /// <typeparam name="T">Type of the elements in the buffer.</typeparam>
 /// <param name="context">Context used to update the buffer.</param>
 /// <param name="buffer">Buffer to update.</param>
 /// <param name="newValues">Values to upload into the buffer.</param>
 /// <param name="sourceOffset">Starting index in the new values array to read from.</param>
 /// <param name="count">Number of elements in the values to upload into the buffer.</param>
 /// <param name="destinationOffset">Offset from the beginning of the buffer to store the new values.</param>
 public static unsafe void UpdateBuffer <T>(this DeviceContext context, Buffer buffer, Span <T> newValues, int count, int sourceOffset = 0, int destinationOffset = 0) where T : struct
 {
     ref var raw = ref MemoryMarshal.GetReference(newValues);
Beispiel #40
0
        void CreateMesh()
        {
            var device = _d3dDevice;
            // Compile Vertex and Pixel shaders
            var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0");
            var vertexShader         = new VertexShader(device, vertexShaderByteCode);

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

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

            // Instantiate Vertex buiffer from vertex data
            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[]
            {
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),                       // Front
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),                        // BACK
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),                        // Top
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),                       // Bottom
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),                       // Left
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),                        // Right
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
            });

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

            var context = _d3dDevice.ImmediateContext;

            // Prepare All the stages
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0));
            context.VertexShader.SetConstantBuffer(0, _contantBuffer);
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);
        }
        /// <summary>
        /// Creates device-based resources to store a constant buffer, cube
        /// geometry, and vertex and pixel shaders. In some cases this will also
        /// store a geometry shader.
        /// </summary>
        public async void CreateDeviceDependentResourcesAsync()
        {
            ReleaseDeviceDependentResources();

            usingVprtShaders = deviceResources.D3DDeviceSupportsVprt;

            var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

            // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3::
            // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature
            // we can avoid using a pass-through geometry shader to set the render
            // target array index, thus avoiding any overhead that would be
            // incurred by setting the geometry shader stage.
            var vertexShaderFileName = usingVprtShaders ? "Content\\Shaders\\VPRTVertexShader.cso" : "Content\\Shaders\\VertexShader.cso";

            // Load the compiled vertex shader.
            var vertexShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync(vertexShaderFileName));

            // After the vertex shader file is loaded, create the shader and input layout.
            vertexShader = this.ToDispose(new SharpDX.Direct3D11.VertexShader(
                                              deviceResources.D3DDevice,
                                              vertexShaderByteCode));

            SharpDX.Direct3D11.InputElement[] vertexDesc =
            {
                new SharpDX.Direct3D11.InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float,  0, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
                new SharpDX.Direct3D11.InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float,    12, 0, SharpDX.Direct3D11.InputClassification.PerVertexData, 0),
            };

            inputLayout = this.ToDispose(new SharpDX.Direct3D11.InputLayout(
                                             deviceResources.D3DDevice,
                                             vertexShaderByteCode,
                                             vertexDesc));

            if (!usingVprtShaders)
            {
                // Load the compiled pass-through geometry shader.
                var geometryShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\GeometryShader.cso"));

                // After the pass-through geometry shader file is loaded, create the shader.
                geometryShader = this.ToDispose(new SharpDX.Direct3D11.GeometryShader(
                                                    deviceResources.D3DDevice,
                                                    geometryShaderByteCode));
            }

            // Load the compiled pixel shader.
            var pixelShaderByteCode = await DirectXHelper.ReadDataAsync(await folder.GetFileAsync("Content\\Shaders\\PixelShader.cso"));

            // After the pixel shader file is loaded, create the shader.
            pixelShader = this.ToDispose(new SharpDX.Direct3D11.PixelShader(
                                             deviceResources.D3DDevice,
                                             pixelShaderByteCode));

            var texture = TextureLoader.CreateTexture2DFromBitmap(deviceResources.D3DDevice, TextureLoader.LoadBitmap(new SharpDX.WIC.ImagingFactory2(), _file));

            _textureView = new ShaderResourceView(deviceResources.D3DDevice, texture);

            // Load mesh vertices. Each vertex has a position and a color.
            // Note that the cube size has changed from the default DirectX app
            // template. Windows Holographic is scaled in meters, so to draw the
            // cube at a comfortable size we made the cube width 0.2 m (20 cm).

            TexturedVertex[] vertices =
            {
                new TexturedVertex(new Vector3(0.0f,   0.0f, 0.0f), new Vector2(0, 1)),
                new TexturedVertex(new Vector3(_size,  0.0f, 0.0f), new Vector2(1, 1)),
                new TexturedVertex(new Vector3(_size, _size, 0.0f), new Vector2(1, 0)),
                new TexturedVertex(new Vector3(0.0f,  _size, 0.0f), new Vector2(0, 0)),
            };

            vertexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                              deviceResources.D3DDevice,
                                              SharpDX.Direct3D11.BindFlags.VertexBuffer,
                                              vertices));

            // Load mesh indices. Each trio of indices represents
            // a triangle to be rendered on the screen.
            // For example: 0,2,1 means that the vertices with indexes
            // 0, 2 and 1 from the vertex buffer compose the
            // first triangle of this mesh.
            ushort[] cubeIndices =
            {
                2, 1, 0,
                0, 3, 2,
            };

            indexCount = cubeIndices.Length;

            indexBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                             deviceResources.D3DDevice,
                                             SharpDX.Direct3D11.BindFlags.IndexBuffer,
                                             cubeIndices));

            // Create a constant buffer to store the model matrix.
            modelConstantBuffer = this.ToDispose(SharpDX.Direct3D11.Buffer.Create(
                                                     deviceResources.D3DDevice,
                                                     SharpDX.Direct3D11.BindFlags.ConstantBuffer,
                                                     ref modelConstantBufferData));

            // Once the cube is loaded, the object is ready to be rendered.
            loadingComplete = true;
        }
Beispiel #42
0
 private IndexBuffer(Buffer buffer, Format format)
 {
     _buffer = buffer ?? throw new ArgumentNullException(nameof(buffer));
     Format  = format;
 }
Beispiel #43
0
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "TextureVertexShader", "vs_4_0", ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "TexturePixelShader", "ps_4_0", ShaderFlags.None, EffectFlags.None);
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                PixelShader  = new PixelShader(device, pixelShaderByteCode);
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

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

                SamplerStateDescription 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), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };
                SamplerState = new SamplerState(device, samplerDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
        private bool InitializeShader(Device device, IntPtr windowsHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the Vertex Shader & Pixel Shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "AlphaMapVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                ShaderBytecode pixelShaderByteCode  = ShaderBytecode.CompileFromFile(psFileName, "AlphaMapPixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the Vertex & Pixel Shaders from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                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.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout. Kin dof like a Vertex Declaration.
                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 Matrix buffer that is in the vertex shader.
                BufferDescription matrixBufferDescription = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(),
                    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 SharpDX.Direct3D11.Buffer(device, matrixBufferDescription);

                // Create a texture sampler state description.
                SamplerStateDescription 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), // Black Border.
                    MinimumLod         = 0,
                    MaximumLod         = float.MaxValue
                };

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

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref lambertShader);
            RemoveAndDispose(ref blinnPhongShader);
            RemoveAndDispose(ref phongShader);

            RemoveAndDispose(ref tessellateVertexShader);
            RemoveAndDispose(ref tessellateTriIntegerShader);
            RemoveAndDispose(ref tessellateTriPow2Shader);
            RemoveAndDispose(ref tessellateTriFractionalEvenShader);
            RemoveAndDispose(ref tessellateTriFractionalOddShader);
            RemoveAndDispose(ref tessellateTriDomainShader);

            RemoveAndDispose(ref tessellatePhongDomainShader);

            RemoveAndDispose(ref debugNormals);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);
            RemoveAndDispose(ref perArmatureBuffer);

            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;


            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
                using (var vertexTessBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSPassThruTessellate", "vs_5_0"))
                {
                    vertexShader           = ToDispose(new VertexShader(device, vertexShaderBytecode));
                    tessellateVertexShader = ToDispose(new VertexShader(device, vertexTessBytecode));

                    // Layout from VertexShader input signature
                    vertexLayout = ToDispose(new InputLayout(device,
                                                             vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                             new[]
                    {
                        // "SV_Position" = vertex coordinate in object space
                        new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                        // "NORMAL" = the vertex normal
                        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                        // "COLOR"
                        new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                        // "UV"
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                        // "BLENDINDICES"
                        new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                        // "BLENDWEIGHT"
                        new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                        // "TANGENT"
                        new InputElement("TANGENT", 0, Format.R32G32B32A32_Float, 68, 0),
                    }));
                }

            // Compile and create the pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
                depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
                lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
                phongShader = ToDispose(new PixelShader(device, bytecode));

            #region Tessellation Shaders

            using (var triIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesInteger", "hs_5_0", null))
                using (var triPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesPow2", "hs_5_0", null))
                    using (var triFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalEven", "hs_5_0", null))
                        using (var triFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "HS_TrianglesFractionalOdd", "hs_5_0", null))
                            using (var triDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellateTri.hlsl", "DS_Triangles", "ds_5_0", null))
                            {
                                tessellateTriIntegerShader        = ToDispose(new HullShader(device, triIntegerBytecode));
                                tessellateTriPow2Shader           = ToDispose(new HullShader(device, triPow2Bytecode));
                                tessellateTriFractionalEvenShader = ToDispose(new HullShader(device, triFractionalEvenBytecode));
                                tessellateTriFractionalOddShader  = ToDispose(new HullShader(device, triFractionalOddBytecode));
                                tessellateTriDomainShader         = ToDispose(new DomainShader(device, triDomainShaderBytecode));
                            }

            using (var phongDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePhong.hlsl", "DS_PhongTessellation", "ds_5_0", null))
            {
                tessellatePhongDomainShader = ToDispose(new DomainShader(device, phongDomainShaderBytecode));
            }

            using (var pnTriIntegerBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesInteger", "hs_5_0", null))
                using (var pnTriPow2Bytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesPow2", "hs_5_0", null))
                    using (var pnTriFractionalEvenBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalEven", "hs_5_0", null))
                        using (var pnTriFractionalOddBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "HS_PNTrianglesFractionalOdd", "hs_5_0", null))
                            using (var pnTriDomainShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\TessellatePNTri.hlsl", "DS_PNTriangles", "ds_5_0", null))
                            {
                                pnTriIntegerShader        = ToDispose(new HullShader(device, pnTriIntegerBytecode));
                                pnTriPow2Shader           = ToDispose(new HullShader(device, pnTriPow2Bytecode));
                                pnTriFractionalEvenShader = ToDispose(new HullShader(device, pnTriFractionalEvenBytecode));
                                pnTriFractionalOddShader  = ToDispose(new HullShader(device, pnTriFractionalOddBytecode));
                                pnTriDomainShader         = ToDispose(new DomainShader(device, pnTriDomainShaderBytecode));
                            }

            using (var geomShaderByteCode = HLSLCompiler.CompileFromFile(@"Shaders\GS_DebugNormals.hlsl", "GSMain", "gs_5_0", null))
            {
                debugNormals = ToDispose(new GeometryShader(device, geomShaderByteCode));
            }

            #endregion


            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
                // Configure FrontFace depth/stencil operations
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment
                },
                // Configure BackFace depth/stencil operations
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement
                },
            }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);
            context.VertexShader.SetConstantBuffer(3, perArmatureBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set our hull shader constant buffers
            context.HullShader.SetConstantBuffer(0, perObjectBuffer);
            context.HullShader.SetConstantBuffer(1, perFrameBuffer);

            // Set default Hull Shader
            context.HullShader.Set(tessellateTriIntegerShader);

            context.DomainShader.SetConstantBuffer(0, perObjectBuffer);
            context.DomainShader.SetConstantBuffer(1, perFrameBuffer);
            context.DomainShader.SetConstantBuffer(2, perMaterialBuffer);
            context.DomainShader.Set(tessellateTriDomainShader);

            // Set gemoetry shader buffers
            context.GeometryShader.SetConstantBuffer(0, perObjectBuffer);
            context.GeometryShader.SetConstantBuffer(1, perFrameBuffer);

            // Set our pixel constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the pixel shader to run
            context.PixelShader.Set(blinnPhongShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;

            // No culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.None
            }));
        }
Beispiel #46
0
        public unsafe Dx11RenderingDrawingRoom(Dx11RenderingDevice device, Description description)
        {
            Device           = device;
            TextureView      = ((Dx11RenderingTextureAllocator)(description.TextureAllocator)).TextureView;
            TextureAllocator = description.TextureAllocator;
            Vector2 textureScaling = new Vector2(16777216.0f) / new Vector2(TextureAllocator.Size.X, TextureAllocator.Size.Y);

            RoomGeometry roomGeometry = description.Room.RoomGeometry;

            // Create buffer
            Vector3 worldPos = description.Room.WorldPos + description.Offset;
            int     singleSidedVertexCount = roomGeometry.VertexPositions.Count;
            int     vertexCount            = VertexCount = singleSidedVertexCount + roomGeometry.DoubleSidedTriangleCount * 3;

            if (vertexCount == 0)
            {
                return;
            }
            VertexBufferSize = vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint) + sizeof(ulong) + sizeof(uint));
            fixed(byte *data = new byte[VertexBufferSize])
            {
                Vector3 *positions                = (Vector3 *)(data);
                uint *   colors                   = (uint *)(data + vertexCount * sizeof(Vector3));
                uint *   overlays                 = (uint *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint)));
                ulong *  uvwAndBlendModes         = (ulong *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint)));
                uint *   editorUVAndSectorTexture = (uint *)(data + vertexCount * (sizeof(Vector3) + sizeof(uint) + sizeof(uint) + sizeof(ulong)));

                // Setup vertices
                for (int i = 0; i < singleSidedVertexCount; ++i)
                {
                    positions[i] = roomGeometry.VertexPositions[i] + worldPos;
                }
                for (int i = 0; i < singleSidedVertexCount; ++i)
                {
                    colors[i] = Dx11RenderingDevice.CompressColor(roomGeometry.VertexColors[i]);
                }
                for (int i = 0; i < singleSidedVertexCount; ++i)
                {
                    Vector2 vertexEditorUv = roomGeometry.VertexEditorUVs[i];
                    uint    editorUv       = 0;
                    editorUv |= (uint)((int)vertexEditorUv.X) & 3;
                    editorUv |= ((uint)((int)vertexEditorUv.Y) & 3) << 2;
                    editorUVAndSectorTexture[i] = editorUv;
                }
                {
                    SectorInfo lastSectorInfo    = new SectorInfo(-1, -1, BlockFace.Floor);
                    uint       lastSectorTexture = 0;
                    uint       overlay           = 0;
                    for (int i = 0, triangleCount = singleSidedVertexCount / 3; i < triangleCount; ++i)
                    {
                        SectorInfo currentSectorInfo = roomGeometry.TriangleSectorInfo[i];
                        if (!lastSectorInfo.Equals(currentSectorInfo))
                        {
                            SectorTextureResult result = description.SectorTextureGet(description.Room, currentSectorInfo.Pos.X, currentSectorInfo.Pos.Y, currentSectorInfo.Face);

                            lastSectorInfo    = currentSectorInfo;
                            lastSectorTexture = 0;
                            if (result.SectorTexture != SectorTexture.None)
                            { // Use sector texture
                                lastSectorTexture = 0x40 | (((uint)result.SectorTexture - 1) << 8);
                            }
                            else
                            { // Use sector color
                                lastSectorTexture =
                                    (((uint)(result.Color.X * 255)) << 8) |
                                    (((uint)(result.Color.Y * 255)) << 16) |
                                    (((uint)(result.Color.Z * 255)) << 24);
                            }
                            // Highlight / dim sectors
                            if (result.Highlighted)
                            {
                                lastSectorTexture |= 0x10;
                            }
                            if (result.Dimmed)
                            {
                                lastSectorTexture |= 0x20;
                            }
                            // Indicate selected textured faces
                            if (result.Selected && roomGeometry.TriangleTextureAreas[i].Texture != null)
                            {
                                lastSectorTexture |= 0x80;
                            }

                            // Assign overlay color which will be used in geometry mode if face has service texture (e.g. arrows)
                            overlay = Dx11RenderingDevice.CompressColor(new Vector3(result.Overlay.X, result.Overlay.Y, result.Overlay.Z), (result.Hidden ? 0.4f : 1.0f), false);
                        }
                        editorUVAndSectorTexture[i * 3 + 0] |= lastSectorTexture;
                        editorUVAndSectorTexture[i * 3 + 1] |= lastSectorTexture;
                        editorUVAndSectorTexture[i * 3 + 2] |= lastSectorTexture;

                        overlays[i * 3 + 0] = overlay;
                        overlays[i * 3 + 1] = overlay;
                        overlays[i * 3 + 2] = overlay;
                    }
                }

RetryTexturing:
                ;
                {
                    int doubleSidedVertexIndex = singleSidedVertexCount;
                    for (int i = 0, triangleCount = singleSidedVertexCount / 3; i < triangleCount; ++i)
                    {
                        TextureArea texture = roomGeometry.TriangleTextureAreas[i];

                        if (texture.Texture == null)
                        { // Render as geometry
                            uvwAndBlendModes[i * 3 + 0] = 1ul << 24;
                            uvwAndBlendModes[i * 3 + 1] = 1ul << 24;
                            uvwAndBlendModes[i * 3 + 2] = 1ul << 24;
                        }
                        else if (texture.Texture is TextureInvisible)
                        { // Render as invisible
                            uvwAndBlendModes[i * 3 + 0] = 0ul << 24;
                            uvwAndBlendModes[i * 3 + 1] = 0ul << 24;
                            uvwAndBlendModes[i * 3 + 2] = 0ul << 24;
                        }
                        else
                        {
                            // Render as textured (the texture may turn out to be unavailable)
                            if (texture.Texture.IsUnavailable)
                            { // Texture is unvailable (i.e. file couldn't be loaded.
                                ImageC     image    = Dx11RenderingDevice.TextureUnavailable;
                                VectorInt3 position = TextureAllocator.Get(image);
                                uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                            }
                            else if (texture.TriangleCoordsOutOfBounds)
                            { // Texture is available but coordinates are ouf of bounds
                                ImageC     image    = Dx11RenderingDevice.TextureCoordOutOfBounds;
                                VectorInt3 position = TextureAllocator.Get(image);
                                uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                            }
                            else if (!texture.ParentArea.IsZero && !texture.ParentArea.Intersects(texture.GetRect()))
                            { // Texture is available but coordinates are ouf of bounds
                                ImageC     image    = Dx11RenderingDevice.TextureCoordOutOfBounds;
                                VectorInt3 position = TextureAllocator.Get(image);
                                uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 0]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 1]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, Vector2.Abs(roomGeometry.VertexEditorUVs[i * 3 + 2]) * (image.Size - VectorInt2.One) + new Vector2(0.5f), (uint)texture.BlendMode);
                            }
                            else
                            { // Texture is available
                                VectorInt3 position = TextureAllocator.GetForTriangle(texture);
                                uvwAndBlendModes[i * 3 + 0] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord0, (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 1] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord1, (uint)texture.BlendMode);
                                uvwAndBlendModes[i * 3 + 2] = Dx11RenderingDevice.CompressUvw(position, textureScaling, texture.TexCoord2, (uint)texture.BlendMode);
                            }

                            // Duplicate double sided triangles
                            if (texture.DoubleSided)
                            {
                                positions[doubleSidedVertexIndex]                  = positions[i * 3 + 2];
                                colors[doubleSidedVertexIndex]                     = colors[i * 3 + 2];
                                overlays[doubleSidedVertexIndex]                   = overlays[i * 3 + 2];
                                uvwAndBlendModes[doubleSidedVertexIndex]           = uvwAndBlendModes[i * 3 + 2];
                                editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 2];

                                positions[doubleSidedVertexIndex]                  = positions[i * 3 + 1];
                                colors[doubleSidedVertexIndex]                     = colors[i * 3 + 1];
                                overlays[doubleSidedVertexIndex]                   = overlays[i * 3 + 1];
                                uvwAndBlendModes[doubleSidedVertexIndex]           = uvwAndBlendModes[i * 3 + 1];
                                editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 1];

                                positions[doubleSidedVertexIndex]                  = positions[i * 3 + 0];
                                colors[doubleSidedVertexIndex]                     = colors[i * 3 + 0];
                                overlays[doubleSidedVertexIndex]                   = overlays[i * 3 + 0];
                                uvwAndBlendModes[doubleSidedVertexIndex]           = uvwAndBlendModes[i * 3 + 0];
                                editorUVAndSectorTexture[doubleSidedVertexIndex++] = editorUVAndSectorTexture[i * 3 + 0];
                            }
                        }
                    }
                    if (doubleSidedVertexIndex != vertexCount)
                    {
                        throw new ArgumentException("Double sided triangle count of RoomGeometry is wrong!");
                    }

                    // Retry texturing once at max
                    if (TexturesInvalidated && !TexturesInvalidatedRetried)
                    {
                        TexturesInvalidatedRetried = true;
                        goto RetryTexturing;
                    }
                }

                // Create GPU resources
                VertexBuffer = new Buffer(device.Device, new IntPtr(data),
                                          new BufferDescription(VertexBufferSize, ResourceUsage.Immutable, BindFlags.VertexBuffer,
                                                                CpuAccessFlags.None, ResourceOptionFlags.None, 0));
                VertexBufferBindings = new VertexBufferBinding[] {
                    new VertexBufferBinding(VertexBuffer, sizeof(Vector3), (int)((byte *)positions - data)),
                    new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)colors - data)),
                    new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)overlays - data)),
                    new VertexBufferBinding(VertexBuffer, sizeof(ulong), (int)((byte *)uvwAndBlendModes - data)),
                    new VertexBufferBinding(VertexBuffer, sizeof(uint), (int)((byte *)editorUVAndSectorTexture - data))
                };
                VertexBuffer.SetDebugName("Room " + (description.Room.Name ?? ""));
            }

            TextureAllocator.GarbageCollectionCollectEvent.Add(GarbageCollectTexture);
        }
Beispiel #47
0
        static void Main()
        {
            //SharpDX.RawInput.Device.RegisterDevice(UsagePage.Generic, UsageId.GenericMouse, DeviceFlags.None);
            //SharpDX.RawInput.Device.MouseInput += (sender, args) => textBox.Invoke(new UpdateTextCallback(UpdateMouseText), args);

            SharpDX.RawInput.Device.RegisterDevice(UsagePage.Generic, UsageId.GenericKeyboard, DeviceFlags.None);
            SharpDX.RawInput.Device.KeyboardInput += (sender, args) => UpdateKeyboardText(args);

            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //Init textured cube
            int[] indices = new int[]
            {
                0, 1, 2, 0, 2, 3,
                4, 6, 5, 4, 7, 6,
                8, 9, 10, 8, 10, 11,
                12, 14, 13, 12, 15, 14,
                16, 18, 17, 16, 19, 18,
                20, 21, 22, 20, 22, 23
            };

            TexturedVertex[] vertices = new[]
            {
                ////TOP
                new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 1)),
                new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 1)),
                new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)),
                //BOTTOM
                new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)),
                new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)),
                new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 0)),
                //LEFT
                new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(0, 1)),
                new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(1, 0)),
                new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(1, 1)),
                //RIGHT
                new TexturedVertex(new Vector3(5, -5, 5), new Vector2(1, 1)),
                new TexturedVertex(new Vector3(5, 5, 5), new Vector2(1, 0)),
                new TexturedVertex(new Vector3(5, 5, -5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(5, -5, -5), new Vector2(0, 1)),
                //FRONT
                new TexturedVertex(new Vector3(-5, 5, 5), new Vector2(1, 0)),
                new TexturedVertex(new Vector3(5, 5, 5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(5, -5, 5), new Vector2(0, 1)),
                new TexturedVertex(new Vector3(-5, -5, 5), new Vector2(1, 1)),
                //BACK
                new TexturedVertex(new Vector3(-5, 5, -5), new Vector2(0, 0)),
                new TexturedVertex(new Vector3(5, 5, -5), new Vector2(1, 0)),
                new TexturedVertex(new Vector3(5, -5, -5), new Vector2(1, 1)),
                new TexturedVertex(new Vector3(-5, -5, -5), new Vector2(0, 1))
            };



            //render form
            RenderForm form = new RenderForm();

            form.Text = "SGE Demo";
            SharpFPS fpsCounter = new SharpFPS();


            using (SharpDevice device = new SharpDevice(form))
            {
                //Init Mesh
                //SharpMesh mesh = SharpMesh.Create<TexturedVertex>(device, vertices, indices);

                //Init shader from file
                //SharpShader shader = new SharpShader(device, "../../HLSL.txt",
                //    new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" },
                //    new InputElement[] {
                //        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                //        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0)
                //    });

                SharpShader shader = new SharpShader(device, "../../HLSL.txt",
                                                     new SharpShaderDescription()
                {
                    VertexShaderFunction = "VS", PixelShaderFunction = "PS"
                },
                                                     new InputElement[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
                });

                //Create constant buffer
                Buffer11 buffer = shader.CreateBuffer <Data>();
                //Create texture from file
                ShaderResourceView texture = device.LoadTextureFromFile("../../texture2.bmp");

                fpsCounter.Reset();


                var gm = new GameManager();
                gm.gameObjects.Add(new GameObject()
                {
                    mesh = SharpMesh.CreateFromObj(device, "../../Models/sword/sword.obj")
                });

                gm.gameObjects[0].update = (delta)
                                           =>
                {
                    gm.gameObjects[0].position  = Vector3.Up * (-8 + (float)Math.Sin((float)Environment.TickCount / 500));
                    gm.gameObjects[0].rotation *= Quaternion.RotationYawPitchRoll(0.0002f, 0, 0);
                    return(0);
                };
                gm.gameObjects[0].scale *= 4;

                gm.gameObjects.Add(new GameObject()
                {
                    mesh = SharpMesh.CreateFromObj(device, "../../Models/Sphere/sphere2.obj")
                });

                gm.gameObjects[1].update = (delta)
                                           =>
                {
                    gm.gameObjects[1].position += Vector3.Up * -0.0001f;
                    gm.gameObjects[1].rotation *= Quaternion.RotationYawPitchRoll(-0.0001f, 0, 0);
                    return(0);
                };
                gm.gameObjects[1].scale *= 1;


                //var go = new GameObject();

                //main loop
                RenderLoop.Run(form, () =>
                {
                    //Resizing
                    if (device.MustResize)
                    {
                        device.Resize();
                    }

                    //apply states
                    device.UpdateAllStates();

                    //clear color
                    device.Clear(Color.CornflowerBlue);


                    //apply shader
                    shader.Apply();

                    //apply constant buffer to shader
                    //device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);

                    //set texture
                    //device.DeviceContext.PixelShader.SetShaderResource(0, texture);

                    //set transformation matrix
                    float ratio       = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 0.1F, 1000.0F);
                    Matrix view       = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY);
                    Matrix world      = Matrix.RotationY(Environment.TickCount / 1000.0F);
                    Matrix WVP        = world * view * projection;
                    //device.UpdateData<Matrix>(buffer, WVP);

                    //draw mesh
                    //mesh.Draw();

                    //light direction
                    Vector3 lightDirection = new Vector3(0.5f, 0, -1);
                    lightDirection.Normalize();


                    Data sceneInformation = new Data()
                    {
                        world = world,
                        worldViewProjection = world * view * projection,
                        lightDirection      = new Vector4(lightDirection, 1)
                    };

                    //write data inside constant buffer
                    device.UpdateData <Data>(buffer, sceneInformation);

                    //apply constant buffer to shader



                    //world = Matrix.Transformation(Vector3.Zero, Quaternion.Identity, new Vector3(1.2f, 1.2f, 1.2f), Vector3.Zero, Quaternion.Identity, new Vector3(0, -5, 0));
                    //WVP = world * view * projection;

                    for (int i = 0; i < gm.gameObjects.Count; i++)
                    {
                        gm.gameObjects[i].update(1.0f / fpsCounter.FPS);
                        WVP = gm.gameObjects[i].transform * view * projection;
                        //device.UpdateData<Matrix>(buffer, WVP);

                        sceneInformation.world = gm.gameObjects[i].transform;
                        WVP = sceneInformation.world * view * projection;
                        sceneInformation.worldViewProjection = WVP;
                        device.UpdateData <Data>(buffer, sceneInformation);

                        device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);
                        device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer);

                        //device.DeviceContext.PixelShader.SetShaderResource(0, gm.gameObjects[i].mesh.SubSets[i].DiffuseMap);
                        //gm.gameObjects[i].mesh.Draw();
                        gm.gameObjects[i].mesh.Begin();
                        for (int j = 0; j < gm.gameObjects[i].mesh.SubSets.Count; j++)
                        {
                            device.DeviceContext.PixelShader.SetShaderResource(0, gm.gameObjects[i].mesh.SubSets[j].DiffuseMap);
                            gm.gameObjects[i].mesh.Draw(j);
                        }
                    }

                    //go.position = go.position + Vector3.Up * 0.001f;

                    //go.rotation = go.rotation * Quaternion.RotationYawPitchRoll(0.0001f, 0, 0);

                    //WVP = go.transform * view * projection;

                    //device.UpdateData<Matrix>(buffer, WVP);

                    //mesh.Draw();



                    //begin drawing text
                    device.Font.Begin();

                    //draw string
                    fpsCounter.Update();
                    device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0);
                    device.Font.DrawString(text, 0, 20);

                    //flush text to view
                    device.Font.End();
                    //present
                    device.Present();
                });

                //release resource
                //mesh.Dispose();
                foreach (GameObject go in gm.gameObjects)
                {
                    go.mesh.Dispose();
                }

                buffer.Dispose();
                texture.Dispose();
            }
        }
Beispiel #48
0
        public unsafe RenderingTextureAllocator.GarbageCollectionAdjustDelegate GarbageCollectTexture(RenderingTextureAllocator allocator,
                                                                                                      RenderingTextureAllocator.Map map, HashSet <RenderingTextureAllocator.Map.Entry> inOutUsedTextures)
        {
            TexturesInvalidated = true;
            if (VertexBuffer == null)
            {
                return(null);
            }

            byte[]  data                   = Device.ReadBuffer(VertexBuffer, VertexBufferSize);
            Vector2 textureScaling         = new Vector2(16777216.0f) / new Vector2(TextureAllocator.Size.X, TextureAllocator.Size.Y);
            int     uvwAndBlendModesOffset = VertexBufferBindings[3].Offset;

            // Collect all used textures
            fixed(byte *dataPtr = data)
            {
                ulong *uvwAndBlendModesPtr = (ulong *)(dataPtr + uvwAndBlendModesOffset);

                for (int i = 0; i < VertexCount; ++i)
                {
                    if (uvwAndBlendModesPtr[i] < 0x1000000) // Very small coordinates make no sense, they are used as a placeholder
                    {
                        continue;
                    }
                    var texture = map.Lookup(Dx11RenderingDevice.UncompressUvw(uvwAndBlendModesPtr[i], textureScaling));
                    if (texture == null)
#if DEBUG
                    { throw new ArgumentOutOfRangeException("Texture unrecognized."); }
#else
                    { continue; }
#endif
                    inOutUsedTextures.Add(texture);
                }
            }

            // Provide a methode to update the buffer with new UV coordinates
            return(delegate(RenderingTextureAllocator allocator2, RenderingTextureAllocator.Map map2)
            {
                Vector2 textureScaling2 = new Vector2(16777216.0f) / new Vector2(TextureAllocator.Size.X, TextureAllocator.Size.Y);

                // Update data
                fixed(byte *dataPtr = data)
                {
                    ulong *uvwAndBlendModesPtr = (ulong *)(dataPtr + uvwAndBlendModesOffset);
                    for (int i = 0; i < VertexCount; ++i)
                    {
                        if (uvwAndBlendModesPtr[i] < 0x1000000) // Very small coordinates make no sense, they are used as a placeholder
                        {
                            continue;
                        }
                        var texture = map.Lookup(Dx11RenderingDevice.UncompressUvw(uvwAndBlendModesPtr[i], textureScaling));
                        Vector2 uv;
                        uint highestBits;
                        Dx11RenderingDevice.UncompressUvw(uvwAndBlendModesPtr[i], texture.Pos, textureScaling, out uv, out highestBits);
                        uvwAndBlendModesPtr[i] = Dx11RenderingDevice.CompressUvw(allocator2.Get(texture.Texture), textureScaling2, uv, highestBits);
                    }
                }

                // Upload data
                var oldVertexBuffer = VertexBuffer;
                fixed(byte *dataPtr = data)
                {
                    VertexBuffer = new Buffer(Device.Device, new IntPtr(dataPtr),
                                              new BufferDescription(VertexBufferSize, ResourceUsage.Immutable, BindFlags.VertexBuffer,
                                                                    CpuAccessFlags.None, ResourceOptionFlags.None, 0));
                    oldVertexBuffer.Dispose();
                }

                for (int i = 0; i < VertexBufferBindings.Length; ++i)
                {
                    if (VertexBufferBindings[i].Buffer == oldVertexBuffer)
                    {
                        VertexBufferBindings[i].Buffer = VertexBuffer;
                    }
                }
            });
        }
        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);
        }
Beispiel #50
0
        static void Main()
        {
            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //render form
            RenderForm form = new RenderForm();

            form.Text = "Tutorial 9: Normal Mapping";
            //frame rate counter
            SharpFPS fpsCounter = new SharpFPS();


            using (SharpDevice device = new SharpDevice(form))
            {
                //load font
                SharpBatch font = new SharpBatch(device, "textfont.dds");

                //load model from wavefront obj file
                SharpMesh mesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj");

                //init shader with normal map illumination
                SharpShader shaderNormal = new SharpShader(device, "../../HLSL_normal.txt",
                                                           new SharpShaderDescription()
                {
                    VertexShaderFunction = "VS", PixelShaderFunction = "PS"
                },
                                                           new InputElement[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0),
                    new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0)
                });

                //Init shader with standard illumination
                SharpShader shaderStandard = new SharpShader(device, "../../HLSL_standard.txt",
                                                             new SharpShaderDescription()
                {
                    VertexShaderFunction = "VS", PixelShaderFunction = "PS"
                },
                                                             new InputElement[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0),
                    new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0)
                });

                //init constant buffer
                Buffer11 buffer = shaderNormal.CreateBuffer <Data>();

                //init frame counter
                fpsCounter.Reset();

                //Used for parallax mapping
                float bias = 0.005f;
                //to active normal mapping
                bool normalMap = true;


                form.KeyDown += (sender, e) =>
                {
                    if (e.KeyCode == Keys.A)
                    {
                        bias = 0.005f;
                    }
                    else if (e.KeyCode == Keys.S)
                    {
                        bias = 0;
                    }

                    if (e.KeyCode == Keys.N)
                    {
                        normalMap = true;
                    }
                    if (e.KeyCode == Keys.D)
                    {
                        normalMap = false;
                    }
                };

                //main loop
                RenderLoop.Run(form, () =>
                {
                    //Resizing
                    if (device.MustResize)
                    {
                        device.Resize();
                        font.Resize();
                    }

                    //apply states
                    device.UpdateAllStates();

                    //clear color
                    device.Clear(Color.CornflowerBlue);



                    //set transformation matrix
                    float ratio       = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F);
                    //set camera position and target
                    Vector3 from = new Vector3(0, 70, -150);
                    Vector3 to   = new Vector3(0, 50, 0);

                    Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY);

                    //set world matrix
                    Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F);

                    //light direction
                    Vector3 lightDirection = new Vector3(0.5f, 0, -1);
                    lightDirection.Normalize();


                    Data sceneInformation = new Data()
                    {
                        world = world,
                        worldViewProjection = world * view * projection,
                        lightDirection      = new Vector4(lightDirection, 1),
                        viewDirection       = new Vector4(Vector3.Normalize(from - to), 1),
                        bias = new Vector4(bias, 0, 0, 0)
                    };


                    //apply shader
                    if (normalMap)
                    {
                        shaderNormal.Apply();
                    }
                    else
                    {
                        shaderStandard.Apply();
                    }

                    //write data inside constant buffer
                    device.UpdateData <Data>(buffer, sceneInformation);

                    //apply constant buffer to shader
                    device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);
                    device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer);

                    //draw mesh
                    mesh.Begin();
                    for (int i = 0; i < mesh.SubSets.Count; i++)
                    {
                        device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap);
                        device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap);
                        mesh.Draw(i);
                    }


                    //begin drawing text
                    font.Begin();

                    //draw string
                    fpsCounter.Update();
                    font.DrawString("FPS: " + fpsCounter.FPS, 0, 0, Color.White);

                    //flush text to view
                    font.End();
                    //present
                    device.Present();
                });

                //release resource
                font.Dispose();
                mesh.Dispose();
                buffer.Dispose();
                shaderNormal.Dispose();
                shaderStandard.Dispose();
            }
        }
Beispiel #51
0
 public bool Flag;//for external use
 public GpuVarsBuffer(Device device)
 {
     Size   = System.Runtime.InteropServices.Marshal.SizeOf <T>();                                                                          // (sizeof(T));
     Buffer = new Buffer(device, Size, ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0); // //DXUtility::CreateShaderVarsBuffer(Size, name);
 }
Beispiel #52
0
        static void Main(string[] args)
        {
            //int? i = 10;
            //Console.WriteLine(i.GetType()); // Displays
            //Type type = TypedReference.GetTargetType(__makeref(i));
            //Console.WriteLine((type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)).ToString());
            //Console.ReadLine();
            //return;

            //TreeTest.Run();
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //using (var frm = new Form1())
            //{
            //    Application.Run(frm);
            //}



            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //render form
            RenderForm form = new RenderForm();

            form.Text = "Tutorial 3: Font";
            int count = 0;


            Global.doc = XDocument.Load(@".\\..\\..\\XMLfile1.xml");

            Global.dta = Global.doc.Descendants("lites").Descendants("lite").Select(n => new TreeData()
            {
                row   = (int)n.Attribute("row"),
                ctr   = (int)n.Attribute("cir"),
                col   = (int)n.Attribute("col"),
                ndx   = (int)n.Attribute("ndx"),
                color = Colors[(int)(ColorEnum)Enum.Parse(typeof(ColorEnum), (string)n.Attribute("color"))],
            }).OrderBy(t => t.ndx).ToArray();

            Global.dict = Global.dta.ToDictionary(d => Tuple.Create <int, int>(d.row, d.ctr), d => d);



            int[] indices = Enumerable.Range(0, Global.dta.Count()).ToArray();

            ColoredVertex[] vertices =
                Global.dta.Select(x => new ColoredVertex(new Vector3((x.ctr), -(x.row - 16) * 2, -5),
                                                         new Vector4(x.color.R / 255.0f, x.color.G / 255.0f, x.color.B / 255.0f, 1)
                                                         )).ToArray();

            using (SharpDevice device = new SharpDevice(form))

                //Init Font
                using (SharpBatch font = new SharpBatch(device, "../../textfont.dds"))

                    //Init Mesh
                    using (SharpMesh mesh = SharpMesh.Create <ColoredVertex>(device, vertices, indices))

                        //Create Shader From File and Create Input Layout
                        using (SharpShader shader = new SharpShader(device, "../../HLSL.txt",
                                                                    new SharpShaderDescription()
                        {
                            VertexShaderFunction = "VS", PixelShaderFunction = "PS", GeometryShaderFunction = "GS"
                        },
                                                                    new InputElement[] {
                            new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                            new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0)
                        }))

                            //create constant buffer
                            using (Buffer11 buffer = shader.CreateBuffer <Matrix>())
                            {
                                SharpFPS fpsCounter = new SharpFPS();
                                fpsCounter.Reset();

                                //main loop
                                RenderLoop.Run(form, () =>
                                {
                                    //resize if form was resized
                                    if (device.MustResize)
                                    {
                                        device.Resize();
                                        font.Resize();
                                    }

                                    //apply states
                                    device.UpdateAllStates();

                                    //clear color
                                    device.Clear(Color.Black);

                                    //apply shader
                                    shader.Apply();


                                    //apply constant buffer to shader
                                    device.DeviceContext.GeometryShader.SetConstantBuffer(0, buffer);

                                    //Set matrices
                                    float ratio       = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1, 1000);
                                    Matrix view       = Matrix.LookAtLH(new Vector3(0, 0, -50), new Vector3(0, 0, 0), Vector3.UnitY);
                                    Matrix world      = Matrix.RotationY(0); // (float)Math.PI /2);
                                    Matrix WVP        = world * view * projection;

                                    //update constant buffer
                                    device.UpdateData <Matrix>(buffer, WVP);

                                    //pass constant buffer to shader
                                    //device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);

                                    //draw mesh
                                    mesh.DrawPoints(vertices.Length);


                                    ////Set matrices
                                    //world = Matrix.RotationZ( (float)Math.PI /2);
                                    //WVP = world * view * projection;

                                    ////update constant buffer
                                    //device.UpdateData<Matrix>(buffer, WVP);

                                    //////pass constant buffer to shader
                                    ////device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);

                                    //////apply shader
                                    ////shader.Apply();

                                    ////draw mesh
                                    //mesh.DrawPoints(vertices.Length);


                                    //begin drawing text
                                    device.DeviceContext.GeometryShader.Set(null);



                                    //begin drawing text
                                    font.Begin();

                                    //draw string
                                    //font.DrawString("Hello SharpDX", 0, 0, Color.White);
                                    fpsCounter.Update();
                                    count++;
                                    font.DrawString("FPS: " + fpsCounter.FPS + ":" + count, 0, 0, Color.White);

                                    font.DrawString("Current Time " + DateTime.Now.ToString(), 0, 32, Color.White);

                                    //flush text to view
                                    font.End();

                                    //present
                                    device.Present();
                                });
                            }



            Console.WriteLine("Completed.");
            //Console.ReadLine();
            return;

            Dictionary <string, int> crdtypes = new Dictionary <string, int>(50);

            using (StreamReader rdr = new StreamReader("c:\\temp\\popmoney\\rmaccounts"))
            {
                while (!rdr.EndOfStream)
                {
                    string rcd = rdr.ReadLine();
                    if (rcd.Length != 78)
                    {
                    }
                    Console.WriteLine(rcd.Length.ToString());
                    string typ = rcd.Substring(53, 2);
                    int    lng = rcd.Substring(30, 23).Trim().Length;
                    if (!crdtypes.ContainsKey(rcd))
                    {
                        crdtypes[typ] = 0;
                    }
                    if (crdtypes[typ] < lng)
                    {
                        crdtypes[typ] = lng;
                    }
                }
            }
            foreach (var dict in crdtypes.AsQueryable())
            {
                Console.WriteLine(dict.Key + ":" + dict.Value.ToString());
            }
            Console.ReadLine();
        }
 public VertexBuffer(RenderingDevice device, Buffer buffer, int size)
 {
     Buffer  = buffer;
     Size    = size;
     _device = device;
 }
Beispiel #54
0
        private bool InitializeShader(Device device, IntPtr windowHandler, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full paths
                vsFileName = SystemConfiguration.ShadersFilePath + vsFileName;
                psFileName = SystemConfiguration.ShadersFilePath + psFileName;

                // Compile the vertex shader code.
                var vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "LightVertexShader", SystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                var pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "LightPixelShader", SystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                var inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "TEXCOORD",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    },
                    new InputElement()
                    {
                        SemanticName         = "NORMAL",
                        SemanticIndex        = 0,
                        Format               = Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = InputElement.AppendAligned,
                        Classification       = InputClassification.PerVertexData,
                        InstanceDataStepRate = 0
                    }
                };

                // Create the vertex input the layout.
                Layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), inputElements);

                // Release the vertex and pixel shader buffers, since they are no longer needed.
                vertexShaderByteCode.Dispose();
                pixelShaderByteCode.Dispose();

                // 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         = float.MaxValue
                };

                // Create the texture sampler state.
                SampleState = new SamplerState(device, samplerDesc);

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

                // Setup the description of the camera dynamic constant buffer that is in the vertex shader.
                var cameraBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <CameraBuffer>(),
                    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.
                ConstantCameraBuffer = new Buffer(device, cameraBufferDesc);

                // Setup the description of the light dynamic constant bufffer that is in the pixel shader.
                // Note that ByteWidth alwalys needs to be a multiple of the 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
                var lightBufferDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <LightBuffer>(),
                    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.
                ConstantLightBuffer = new Buffer(device, lightBufferDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            };
        }
Beispiel #55
0
 public void Dispose()
 {
     Buffer.Dispose();
     InView.Dispose();
     OutView.Dispose();
 }
        private bool InitializeShader(Device device, IntPtr windowsHandle, string vsFileName, string psFileName)
        {
            try
            {
                // Setup full pathes
                vsFileName = DSystemConfiguration.ShaderFilePath + vsFileName;
                psFileName = DSystemConfiguration.ShaderFilePath + psFileName;

                // Compile the vertex shader code.
                ShaderBytecode vertexShaderByteCode = ShaderBytecode.CompileFromFile(vsFileName, "DepthVertexShader", DSystemConfiguration.VertexShaderProfile, ShaderFlags.None, EffectFlags.None);
                // Compile the pixel shader code.
                ShaderBytecode pixelShaderByteCode = ShaderBytecode.CompileFromFile(psFileName, "DepthPixelShader", DSystemConfiguration.PixelShaderProfile, ShaderFlags.None, EffectFlags.None);

                // Create the vertex shader from the buffer.
                VertexShader = new VertexShader(device, vertexShaderByteCode);
                // Create the pixel shader from the buffer.
                PixelShader = new PixelShader(device, pixelShaderByteCode);

                // Now setup the layout of the data that goes into the shader.
                // This setup needs to match the VertexType structure in the Model and in the shader.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement()
                    {
                        SemanticName         = "POSITION",
                        SemanticIndex        = 0,
                        Format               = SharpDX.DXGI.Format.R32G32B32_Float,
                        Slot                 = 0,
                        AlignedByteOffset    = 0,
                        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.
                BufferDescription matrixBufDesc = new BufferDescription()
                {
                    Usage               = ResourceUsage.Dynamic,
                    SizeInBytes         = Utilities.SizeOf <DMatrixBuffer>(), // was Matrix
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.Write,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
                ConstantMatrixBuffer = new SharpDX.Direct3D11.Buffer(device, matrixBufDesc);

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error initializing shader. Error is " + ex.Message);
                return(false);
            }
        }
Beispiel #57
0
        static void Main()
        {
            if (!SharpDevice.IsDirectX11Supported())
            {
                System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported");
                return;
            }

            //render form
            RenderForm form = new RenderForm();

            form.Text = "Tutorial 7: Loading Obj File";
            //frame rate counter
            SharpFPS fpsCounter = new SharpFPS();


            using (SharpDevice device = new SharpDevice(form))
            {
                //load model from wavefront obj file
                SharpMesh mesh = SharpMesh.CreateFromObj(device, "../../../Models/car/car.obj");

                //init shader
                SharpShader shader = new SharpShader(device, "../../HLSL.txt",
                                                     new SharpShaderDescription()
                {
                    VertexShaderFunction = "VS", PixelShaderFunction = "PS"
                },
                                                     new InputElement[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
                });

                //init constant buffer
                Buffer11 buffer = shader.CreateBuffer <Data>();

                //init frame counter
                fpsCounter.Reset();

                //main loop
                RenderLoop.Run(form, () =>
                {
                    //Resizing
                    if (device.MustResize)
                    {
                        device.Resize();
                    }

                    //apply states
                    device.UpdateAllStates();

                    //clear color
                    device.Clear(Color.CornflowerBlue);

                    //apply shader
                    shader.Apply();

                    //set transformation matrix
                    float ratio       = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height;
                    Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F);
                    Matrix view       = Matrix.LookAtLH(new Vector3(0, 10, -30), new Vector3(), Vector3.UnitY);
                    Matrix world      = Matrix.RotationY(Environment.TickCount / 1000.0F);

                    //light direction
                    Vector3 lightDirection = new Vector3(0.5f, 0, -1);
                    lightDirection.Normalize();


                    Data sceneInformation = new Data()
                    {
                        world = world,
                        worldViewProjection = world * view * projection,
                        lightDirection      = new Vector4(lightDirection, 1)
                    };

                    //write data inside constant buffer
                    device.UpdateData <Data>(buffer, sceneInformation);

                    //apply constant buffer to shader
                    device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer);
                    device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer);

                    //draw mesh
                    mesh.Begin();
                    for (int i = 0; i < mesh.SubSets.Count; i++)
                    {
                        device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap);
                        mesh.Draw(i);
                    }


                    //begin drawing text
                    device.Font.Begin();

                    //draw string
                    fpsCounter.Update();
                    device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0);

                    //flush text to view
                    device.Font.End();
                    //present
                    device.Present();
                });

                //release resource
                mesh.Dispose();
                buffer.Dispose();
            }
        }
Beispiel #58
0
        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.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                BorderColor        = new Color4(0, 0, 0, 0),
                ComparisonFunction = Comparison.Never,
                Filter             = Filter.Anisotropic,
                MaximumAnisotropy  = 16,
                MaximumLod         = float.MaxValue,
                MinimumLod         = 0,
                MipLodBias         = 0.0f
            }));
        }
Beispiel #59
0
        public override void CreateDeviceResources()
        {
            base.CreateDeviceResources();

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

            // Loads vertex shader bytecode
            var vertexShaderByteCode = NativeFile.ReadAllBytes(path + "\\MiniCube_VS.fxo");

            _vertexShader = new VertexShader(_device, vertexShaderByteCode);

            // Loads pixel shader bytecode
            _pixelShader = new PixelShader(_device, NativeFile.ReadAllBytes(path + "\\MiniCube_PS.fxo"));

            // Layout from VertexShader input signature
            _vertexLayout = new InputLayout(_device, vertexShaderByteCode, new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
            });


            // Instantiate Vertex buffer from vertex data
            var vertices = SharpDX.Direct3D11.Buffer.Create(_device, BindFlags.VertexBuffer, new[]
            {
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),                       // Front
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),                        // BACK
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),                        // Top
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),                       // Bottom
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),                       // Left
                new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),                        // Right
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
            });

            _vertexBufferBinding = new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0);

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

            _clock = new Stopwatch();
            _clock.Start();

            _loadingComplete = true;
        }
    private void ProcessTexturedSurface(int surfaceIdx, string uvSetName, FileInfo file, bool isLinear)
    {
        bool isOrderedTransparent = surfaceProperties.RenderOrder.Contains(surfaceIdx);
        bool isMaxing             = isOrderedTransparent;

        var context = device.ImmediateContext;

        var opacityTexture     = LoadOpacityTexture(file, isLinear);
        var opacityTextureView = new ShaderResourceView(device, opacityTexture);

        // Not sure by, possibly a nvidia bug, but the vertex buffer padding by an extra element is necessary.
        // Otherwise (0,0) gets passed to the vertex shader instead of the last vertex.
        var uvSet    = figure.UvSets[uvSetName];
        var vertices = uvSet.Uvs;
        var vertexBufferSizeInBytes = Vector2.SizeInBytes * (vertices.Length + 1);
        var vertexBuffer            = Buffer.Create(device, BindFlags.VertexBuffer, vertices, vertexBufferSizeInBytes);

        List <int> faceIdxMap      = new List <int>();
        List <int> triangleIndices = new List <int>();

        for (int faceIdx = 0; faceIdx < faceCount; ++faceIdx)
        {
            if (figure.Geometry.SurfaceMap[faceIdx] != surfaceIdx)
            {
                continue;
            }

            faceIdxMap.Add(faceIdx);

            Quad face = figure.DefaultUvSet.Faces[faceIdx];
            triangleIndices.Add(face.Index0);
            triangleIndices.Add(face.Index1);
            triangleIndices.Add(face.Index2);

            if (!face.IsDegeneratedIntoTriangle)
            {
                triangleIndices.Add(face.Index2);
                triangleIndices.Add(face.Index3);
                triangleIndices.Add(face.Index0);
            }
        }

        var indexBuffer = Buffer.Create(device, BindFlags.IndexBuffer, triangleIndices.ToArray());

        var transparencyCounterBufferManager = new InOutStructuredBufferManager <TransparencyCounters>(device, faceIdxMap.Count);

        context.ClearState();

        states.Apply(context);

        context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
        context.InputAssembler.InputLayout       = inputLayout;
        context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, Vector2.SizeInBytes, 0));
        context.InputAssembler.SetIndexBuffer(indexBuffer, Format.R32_UInt, 0);

        context.VertexShader.Set(vertexShader);

        context.Rasterizer.SetViewport(0, 0, opacityTexture.Description.Width, opacityTexture.Description.Height);

        context.PixelShader.Set(isMaxing ? maxingPixelShader : addingPixelShader);
        context.PixelShader.SetShaderResources(0, opacityTextureView);

        context.OutputMerger.SetUnorderedAccessView(0, transparencyCounterBufferManager.OutView);

        context.DrawIndexed(triangleIndices.Count, 0, 0);

        context.ClearState();

        var transparencyCounterStagingBufferManager = new StagingStructuredBufferManager <TransparencyCounters>(device, faceIdxMap.Count);

        transparencyCounterStagingBufferManager.CopyToStagingBuffer(context, transparencyCounterBufferManager.Buffer);
        var array = transparencyCounterStagingBufferManager.FillArrayFromStagingBuffer(context);

        for (int faceIdx = 0; faceIdx < faceIdxMap.Count; ++faceIdx)
        {
            TransparencyCounters transparencyCounter = array[faceIdx];

            if (transparencyCounter.pixelCount > (1 << 24))
            {
                throw new Exception("pixel count overflow");
            }

            float transparency;
            if (isMaxing)
            {
                transparency = (float)transparencyCounter.transparencyCount / 0xff;
            }
            else
            {
                transparency = transparencyCounter.transparencyCount == 0 ? 0 : (float)transparencyCounter.transparencyCount / transparencyCounter.pixelCount / 0xff;
            }
            faceTransparencies[faceIdxMap[faceIdx]] = transparency;
        }

        opacityTextureView.Dispose();
        opacityTexture.Dispose();
        indexBuffer.Dispose();
        vertexBuffer.Dispose();
        transparencyCounterBufferManager.Dispose();
        transparencyCounterStagingBufferManager.Dispose();
    }