Ejemplo n.º 1
0
        ShaderSetDescription CreateShaderSet(string Name)
        {
            ShaderSetDescription ShaderSet = new ShaderSetDescription();

            LoadShader(Name, out ShaderSet.Shaders, out ShaderSet.VertexLayouts);
            return(ShaderSet);
        }
Ejemplo n.º 2
0
        public Pipeline CreateAPipeline(ResourceLayout[] resourceLayouts,
                                        ShaderSetDescription shaderSetDescription,
                                        OutputDescription outputDescription,
                                        BlendStateDescription blendStateDescription,
                                        bool depthTest,
                                        FaceCullMode faceCullMode       = FaceCullMode.None,
                                        PolygonFillMode polygonFillMode = PolygonFillMode.Solid,
                                        FrontFace frontFaceWindingOrder = FrontFace.Clockwise)
        {
            var pipelineDescription = new GraphicsPipelineDescription()
            {
                BlendState        = blendStateDescription,
                DepthStencilState = new DepthStencilStateDescription(
                    depthTestEnabled: depthTest,
                    depthWriteEnabled: depthTest,
                    comparisonKind: ComparisonKind.LessEqual),
                RasterizerState = new RasterizerStateDescription(
                    cullMode: faceCullMode,
                    fillMode: polygonFillMode,
                    frontFace: frontFaceWindingOrder,
                    depthClipEnabled: depthTest,
                    scissorTestEnabled: false
                    ),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = resourceLayouts,
                ShaderSet         = shaderSetDescription,
                Outputs           = outputDescription
            };

            return(_components.Factory.CreateGraphicsPipeline(pipelineDescription));
        }
Ejemplo n.º 3
0
    public ShaderSet(
        ShaderSetStore store,
        Assembly shaderAssembly,
        string shaderName,
        params VertexLayoutDescription[] vertexDescriptors)
    {
        Store = store;

        Id = store.GetNextId();

        var factory = store.GraphicsDevice.ResourceFactory;

        var cacheFile = ShaderCrossCompiler.GetOrCreateCachedShaders(factory, shaderAssembly, shaderName);

        var vertexShader = AddDisposable(factory.CreateShader(cacheFile.VertexShaderDescription));

        vertexShader.Name = $"{shaderName}.vert";

        var fragmentShader = AddDisposable(factory.CreateShader(cacheFile.FragmentShaderDescription));

        fragmentShader.Name = $"{shaderName}.frag";

        Description = new ShaderSetDescription(
            vertexDescriptors,
            new[] { vertexShader, fragmentShader });

        ResourceLayouts = new ResourceLayout[cacheFile.ResourceLayoutDescriptions.Length];
        for (var i = 0; i < cacheFile.ResourceLayoutDescriptions.Length; i++)
        {
            ResourceLayouts[i] = AddDisposable(
                factory.CreateResourceLayout(
                    ref cacheFile.ResourceLayoutDescriptions[i]));
        }
    }
Ejemplo n.º 4
0
        public virtual bool Load(GraphicsDevice graphicsDevice, string vertexShaderFileName, string fragmentShaderFileName)
        {
            _vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription(nameof(Vertex.Position), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription(nameof(Vertex.Normal), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription(nameof(Vertex.TextureCoordinate), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2));

            try
            {
                byte[]            vertexShaderBytes = File.ReadAllBytes(vertexShaderFileName);
                ShaderDescription vertexShaderDesc  = new ShaderDescription(ShaderStages.Vertex, vertexShaderBytes, "main");

                byte[]            fragmentShaderBytes = File.ReadAllBytes(fragmentShaderFileName);
                ShaderDescription fragmentShaderDesc  = new ShaderDescription(ShaderStages.Fragment, fragmentShaderBytes, "main");

                _shaders = graphicsDevice.ResourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc);

                ShaderSet = new ShaderSetDescription(new[] { _vertexLayout }, _shaders);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                Dispose();

                return(false);
            }

            return(true);
        }
Ejemplo n.º 5
0
        private static CachedShaderSet CreateAndCacheShaders(this ResourceFactory resourceFactory, SimpleShaderDescription simpleShaderDescription)
        {
            var vertexLayouts = new VertexLayoutDescription(
                new VertexElementDescription(nameof(Vertex.Position), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription(nameof(Vertex.UV), VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                new VertexElementDescription(nameof(Vertex.VertexGroup), VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt1));

            var vertexCode   = VertexCode;
            var fragmentCode = FragmentCode;

            var shaders = resourceFactory.CreateFromSpirv(
                new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexCode), "main"),
                new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentCode), "main"));

            var shaderSetDescription = new ShaderSetDescription(new[] { vertexLayouts }, shaders);

            var resourceLayout = resourceFactory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                          new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                          new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                          new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                          new ResourceLayoutElementDescription("Transform", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                          new ResourceLayoutElementDescription("Nodes", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                          new ResourceLayoutElementDescription("SurfaceTex", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                          new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            var cachedShaderSet = new CachedShaderSet
            {
                ShaderSetDescription = shaderSetDescription,
                ResourceLayout       = resourceLayout,
            };

            _cachedShaderSets[resourceFactory].Add(simpleShaderDescription, cachedShaderSet);
            return(cachedShaderSet);
        }
Ejemplo n.º 6
0
        public void CreateDeviceResources(GraphicsDevice gd, ResourceFactory factory)
        {
            _gd           = gd;
            _cylinderMesh = _cylinder.ToMesh();
            var result = _cylinderMesh.CreateGraphicResource(gd, factory);

            _VertexBuffer  = result.Item1;
            _IndicesBuffer = result.Item2;
            ///Shader布局
            var curAss = this.GetType().Assembly;

            shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3)
                    )
            },
                new[]
            {
                ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "CylinderVS.spv", gd, curAss),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "CylinderFS.spv", gd, curAss),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Geometry, "CylinderGS.spv", gd, curAss)
            });
        }
Ejemplo n.º 7
0
        public ShaderSet(
            GraphicsDevice graphicsDevice,
            string shaderName,
            GlobalResourceSetIndices globalResourceSetIndices,
            params VertexLayoutDescription[] vertexDescriptors)
        {
            GlobalResourceSetIndices = globalResourceSetIndices;

            Id = NextId++;

#if DEBUG
            const bool debug = true;
#else
            const bool debug = false;
#endif

            GetShaders(
                graphicsDevice.ResourceFactory,
                shaderName,
                debug,
                out var vertexShader,
                out var fragmentShader);

            AddDisposable(vertexShader);
            AddDisposable(fragmentShader);

            vertexShader.Name   = $"{shaderName}.vert";
            fragmentShader.Name = $"{shaderName}.frag";

            Description = new ShaderSetDescription(
                vertexDescriptors,
                new[] { vertexShader, fragmentShader });
        }
Ejemplo n.º 8
0
        public void DeviceCreated(GraphicsDevice device)
        {
            _device    = device;
            _resources = _device.ResourceFactory;

            var vertexShaderDescription   = new ShaderDescription(ShaderStages.Vertex, Encoding.ASCII.GetBytes(_vertexShaderSource), "main");
            var fragmentShaderDescription = new ShaderDescription(ShaderStages.Fragment, Encoding.ASCII.GetBytes(_fragmentShaderSource), "main");
            var shaders = _resources.CreateFromSpirv(vertexShaderDescription, fragmentShaderDescription);

            var shaderSetDescription = new ShaderSetDescription(new VertexLayoutDescription[0], shaders);

            _resourceLayout = _resources.CreateResourceLayout(new ResourceLayoutDescription(new ResourceLayoutElementDescription("Uniforms", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            var sizeOf = (uint)Marshal.SizeOf <ShaderToyUniforms.Uniforms>();

            sizeOf    = ((sizeOf + 15) / 16) * 16;
            _uniforms = _resources.CreateBuffer(new BufferDescription(
                                                    sizeOf, BufferUsage.Dynamic | BufferUsage.UniformBuffer));

            _resourceSet = _resources.CreateResourceSet(new ResourceSetDescription(_resourceLayout, _uniforms));

            _pipeline = _resources.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                              BlendStateDescription.SingleOverrideBlend,
                                                              DepthStencilStateDescription.Disabled,
                                                              RasterizerStateDescription.CullNone,
                                                              PrimitiveTopology.TriangleStrip,
                                                              shaderSetDescription,
                                                              new ResourceLayout[] { _resourceLayout, },
                                                              _device.MainSwapchain.Framebuffer.OutputDescription
                                                              ));

            _cl = _resources.CreateCommandList();
        }
Ejemplo n.º 9
0
        private void Build()
        {
            try
            {
                var vertexShader = _vertexShader.Data;
                var fragShader   = _fragmentShader.Data;

                var resourceFactory = _device.ResourceFactory;

                if (_pipeline != null)
                {
                    _pipeline.Dispose();
                    _pipeline = null;
                }

                ShaderSetDescription shaderSet = new ShaderSetDescription(
                    _vertexInputs.Select(i => _registry.VertexLayouts[i]).ToArray(),
                    resourceFactory.CreateFromSpirv(
                        new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexShader), "main"),
                        new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragShader), "main")));

                _pipeline = resourceFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                       BlendStateDescription.SingleAlphaBlend,
                                                                       DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                       RasterizerStateDescription.Default,
                                                                       PrimitiveTopology.TriangleList,
                                                                       shaderSet,
                                                                       _resourceInputs.Select(l => _registry.ResourceLayouts[l]).ToArray(),
                                                                       _target.OutputDescription));
            }
            catch
            {
                _pipeline = null;
            }
        }
Ejemplo n.º 10
0
        private void CreateResources()
        {
            var rf = GraphicsDevice.ResourceFactory;

            _commandList = rf.CreateCommandList();

            var vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Byte4_Norm),
                new VertexElementDescription("TextureCoordinate", VertexElementSemantic.TextureCoordinate,
                                             VertexElementFormat.Float2));

            _vertexShader   = VeldridHelper.LoadShader(rf, "SpriteShader", ShaderStages.Vertex, "VS");
            _fragmentShader = VeldridHelper.LoadShader(rf, "SpriteShader", ShaderStages.Fragment, "FS");

            _shaderSet = new ShaderSetDescription(
                new[] { vertexLayout },
                new[] { _vertexShader, _fragmentShader });

            _wvpLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
                                                     new ResourceLayoutElementDescription("Wvp", ResourceKind.UniformBuffer, ShaderStages.Vertex)));
            _textureLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
                                                         new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));
            _samplerLayout = rf.CreateResourceLayout(new ResourceLayoutDescription(
                                                         new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            CreateSamplerResourceSets();

            _resourceLayouts = new[] { _wvpLayout, _textureLayout, _samplerLayout };

            _wvpBuffer = rf.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            UpdateWvp();

            _wvpSet = rf.CreateResourceSet(new ResourceSetDescription(_wvpLayout, _wvpBuffer));
        }
Ejemplo n.º 11
0
        public void CreateDeviceObjects(IRendererContext context)
        {
            var c  = (VeldridRendererContext)context;
            var cl = c.CommandList;
            var gd = c.GraphicsDevice;
            var sc = c.SceneContext;

            ResourceFactory factory = gd.ResourceFactory;

            _vb = factory.CreateBuffer(new BufferDescription(Vertices.SizeInBytes(), BufferUsage.VertexBuffer));
            _ib = factory.CreateBuffer(new BufferDescription(Indices.SizeInBytes(), BufferUsage.IndexBuffer));
            _miscUniformBuffer      = factory.CreateBuffer(new BufferDescription(MiscUniformData.SizeInBytes, BufferUsage.UniformBuffer));
            _vb.Name                = "TileMapVertexBuffer";
            _ib.Name                = "TileMapIndexBuffer";
            _miscUniformBuffer.Name = "TileMapMiscBuffer";
            cl.UpdateBuffer(_vb, 0, Vertices);
            cl.UpdateBuffer(_ib, 0, Indices);

            var shaderCache = Resolve <IShaderCache>();

            _shaders = shaderCache.GetShaderPair(gd.ResourceFactory,
                                                 VertexShaderName,
                                                 FragmentShaderName,
                                                 shaderCache.GetGlsl(VertexShaderName),
                                                 shaderCache.GetGlsl(FragmentShaderName));

            var shaderSet = new ShaderSetDescription(new[] { VertexLayout, InstanceLayout }, _shaders);

            _layout         = factory.CreateResourceLayout(PerSpriteLayoutDescription);
            _textureSampler = gd.ResourceFactory.CreateSampler(new SamplerDescription(
                                                                   SamplerAddressMode.Clamp,
                                                                   SamplerAddressMode.Clamp,
                                                                   SamplerAddressMode.Clamp,
                                                                   SamplerFilter.MinPoint_MagPoint_MipPoint,
                                                                   null, 1, 0, 0, 0, SamplerBorderColor.TransparentBlack
                                                                   ));

            var depthStencilMode = gd.IsDepthRangeZeroToOne
                    ? DepthStencilStateDescription.DepthOnlyLessEqual
                    : DepthStencilStateDescription.DepthOnlyGreaterEqual;

            var rasterizerMode = new RasterizerStateDescription(
                FaceCullMode.Front, PolygonFillMode.Solid, FrontFace.Clockwise,
                true, true);

            var pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                depthStencilMode,
                rasterizerMode,
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(new[] { VertexLayout, InstanceLayout },
                                         shaderSet.Shaders,
                                         ShaderHelper.GetSpecializations(gd)),
                new[] { _layout, sc.CommonResourceLayout },
                sc.MainSceneFramebuffer.OutputDescription);

            _pipeline      = factory.CreateGraphicsPipeline(ref pd);
            _pipeline.Name = "P_TileMapRenderer";
            _disposeCollector.Add(_vb, _ib, _layout, _textureSampler, _pipeline);
        }
Ejemplo n.º 12
0
        public void CreateDeviceResources(GraphicsDevice gd, ResourceFactory factory)
        {
            _gd = gd;
            ///至多100个点输入,至多102个indices输入
            _lineVertexBuffer = factory.CreateBuffer(new BufferDescription((uint)(6 * 100), BufferUsage.VertexBuffer));
            //gd.UpdateBuffer(_vertexBuffer, 0, this.Positions);
            _lineIndicesBuffer = factory.CreateBuffer(new BufferDescription((uint)(sizeof(ushort) * 102), BufferUsage.IndexBuffer));
            //gd.UpdateBuffer(_indexBuffer, 0, this.Indices);
            _polylinetyleBuffer = factory.CreateBuffer(new BufferDescription(32, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            gd.UpdateBuffer(_polylinetyleBuffer, 0, new LineVectorStyleUBO(RgbaFloat.Red));


            ResourceLayout styleLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("LineStyle", ResourceKind.UniformBuffer, ShaderStages.Fragment | ShaderStages.Geometry)
                    ));


            var curAss = this.GetType().Assembly;


            //这里position的定义极有可能是vec3,因此传入vec2可能出现问题,具体可以参考vk里的源码
            ShaderSetDescription shaderSetBoundingBox = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3))
            },
                new[]
            {
                ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "DrawLineVS.spv", gd, curAss),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "DrawLineFS.spv", gd, curAss),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Geometry, "DrawLineGS.spv", gd, curAss)
            });


            var rasterizer = RasterizerStateDescription.Default;

            rasterizer.FillMode  = PolygonFillMode.Wireframe;
            rasterizer.FrontFace = FrontFace.CounterClockwise;
            //gpu的lineWidth实际绘制的效果并不好仍然需要GeometryShader来实现更好的效果
            //rasterizer.LineWidth = 8.0f;
            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           rasterizer,
                                                           PrimitiveTopology.LinesAdjacency,
                                                           shaderSetBoundingBox,
                                                           //共享View和prj的buffer
                                                           new ResourceLayout[] { ShareResource.ProjectionResourceLayout, styleLayout },
                                                           gd.MainSwapchain.Framebuffer.OutputDescription));


            //创建一个StyleresourceSet,0是线样式1是面样式
            _styleResourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                              styleLayout,
                                                              _polylinetyleBuffer
                                                              ));
        }
Ejemplo n.º 13
0
        protected unsafe override void CreateResources(ResourceFactory factory)
        {
            _projectionBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBuffer       = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _worldBuffer      = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            _vertexBuffer = factory.CreateBuffer(new BufferDescription((uint)(VertexPositionTexture.SizeInBytes * _vertices.Length), BufferUsage.VertexBuffer));
            GraphicsDevice.UpdateBuffer(_vertexBuffer, 0, _vertices);

            _indexBuffer = factory.CreateBuffer(new BufferDescription(sizeof(ushort) * (uint)_indices.Length, BufferUsage.IndexBuffer));
            GraphicsDevice.UpdateBuffer(_indexBuffer, 0, _indices);

            _surfaceTexture     = _stoneTexData.CreateDeviceTexture(GraphicsDevice, ResourceFactory, TextureUsage.Sampled);
            _surfaceTextureView = factory.CreateTextureView(_surfaceTexture);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main")));

            ResourceLayout projViewLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldTextureLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           RasterizerStateDescription.Default,
                                                           PrimitiveTopology.TriangleList,
                                                           shaderSet,
                                                           new[] { projViewLayout, worldTextureLayout },
                                                           MainSwapchain.Framebuffer.OutputDescription));

            _projViewSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                         projViewLayout,
                                                         _projectionBuffer,
                                                         _viewBuffer));

            _worldTextureSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                             worldTextureLayout,
                                                             _worldBuffer,
                                                             _surfaceTextureView,
                                                             GraphicsDevice.Aniso4xSampler));

            _cl = factory.CreateCommandList();
        }
 public SpriteRenderer(GraphicsDevice device, ResourceFactory factory, Framebuffer framebuffer, ShaderSetDescription shaderSet, BlendStateDescription?blendStateDescription = null)
 {
     this.device      = device;
     this.factory     = factory;
     this.framebuffer = framebuffer;
     this.shaderSet   = shaderSet;
     Initialize(blendStateDescription ?? BlendStateDescription.SingleAlphaBlend);
 }
Ejemplo n.º 15
0
        public BasicMaterial(DrawingContext context, Texture2D texture, bool twoSided = false)
            : base(context)
        {
            // NOTE: Quick solution to draw without culling
            this.TwoSided = twoSided;

            _projectionBuffer = context.ResourceFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBuffer       = context.ResourceFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _worldBuffer      = context.ResourceFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            _surfaceTexture     = texture.CreateDeviceTexture(context.GraphicsDevice, context.ResourceFactory, TextureUsage.Sampled);
            _surfaceTextureView = context.ResourceFactory.CreateTextureView(_surfaceTexture);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4)
                    )
            },
                context.ResourceFactory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main")));

            ResourceLayout projViewLayout = context.ResourceFactory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldTextureLayout = context.ResourceFactory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            _pipeline = context.ResourceFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                           BlendStateDescription.SingleOverrideBlend,
                                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                           twoSided ? RasterizerStateDescription.CullNone : RasterizerStateDescription.Default,
                                                                           PrimitiveTopology.TriangleList,
                                                                           shaderSet,
                                                                           new[] { projViewLayout, worldTextureLayout },
                                                                           context.MainSwapchain.Framebuffer.OutputDescription));

            _projViewSet = context.ResourceFactory.CreateResourceSet(new ResourceSetDescription(
                                                                         projViewLayout,
                                                                         _projectionBuffer,
                                                                         _viewBuffer));

            _worldTextureSet = context.ResourceFactory.CreateResourceSet(new ResourceSetDescription(
                                                                             worldTextureLayout,
                                                                             _worldBuffer,
                                                                             _surfaceTextureView,
                                                                             context.GraphicsDevice.Aniso4xSampler));
        }
        public SpriteRenderer(IGraphicsContext context, Framebuffer framebuffer, BlendStateDescription?blendStateDescription = null)
        {
            this.device      = context.Device;
            this.factory     = context.Factory;
            this.framebuffer = framebuffer;
            var shaders = factory.CreateFromSpirv(Shaders.SpritebatchDefaultVertexShader, Shaders.SpritebatchDefaultFragmentShader);

            this.shaderSet = new ShaderSetDescription(new[] { VertexPosition3ColorTexture.VertexLayout }, shaders);
            Initialize(blendStateDescription ?? BlendStateDescription.SingleAlphaBlend);
        }
Ejemplo n.º 17
0
        private VxContext(GraphicsDevice gd, Sdl2Window window)
        {
            Device  = gd;
            Window  = window;
            Factory = new DisposeCollectorResourceFactory(gd.ResourceFactory);
            _cl     = Factory.CreateCommandList();

            Window.Resized += () =>
            {
                Device.MainSwapchain.Resize((uint)Window.Width, (uint)Window.Height);
                _imguiRenderer.WindowResized(Window.Width, Window.Height);
            };

            ShaderSetDescription meshShaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3))
            },
                ShaderHelpers.LoadSet(Device, Factory, "Model"));

            ResourceLayout viewProjLayout = Factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                             new ResourceLayoutElementDescription("ViewProjection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                             new ResourceLayoutElementDescription("SceneInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment)));
            ResourceLayout worldLayout = Factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                          new ResourceLayoutElementDescription("World", ResourceKind.UniformBuffer, ShaderStages.Vertex)));
            ResourceLayout modelParamsLayout = Factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                                new ResourceLayoutElementDescription("ModelParams", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            GraphicsPipelineDescription meshPipelineDescription = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.DepthOnlyGreaterEqual,
                RasterizerStateDescription.Default,
                PrimitiveTopology.TriangleList,
                meshShaderSet,
                new[] { viewProjLayout, worldLayout, modelParamsLayout },
                Device.MainSwapchain.Framebuffer.OutputDescription);

            _modelPipeline = Factory.CreateGraphicsPipeline(meshPipelineDescription);

            _viewProjectionBuffer = Factory.CreateBufferFor <Matrix4x4>(BufferUsage.Dynamic | BufferUsage.UniformBuffer);
            _sceneInfoBuffer      = Factory.CreateBufferFor <SceneInfo>(BufferUsage.Dynamic | BufferUsage.UniformBuffer);
            _viewProjectionSet    = Factory.CreateResourceSet(new ResourceSetDescription(viewProjLayout, _viewProjectionBuffer, _sceneInfoBuffer));

            _worldBuffer = Factory.CreateBuffer(new BufferDescription(128, BufferUsage.Dynamic | BufferUsage.UniformBuffer));
            _worldSet    = Factory.CreateResourceSet(new ResourceSetDescription(worldLayout, _worldBuffer));

            _modelParamsBuffer = Factory.CreateBufferFor <Vector4>(BufferUsage.Dynamic | BufferUsage.UniformBuffer);
            _modelParamsSet    = Factory.CreateResourceSet(new ResourceSetDescription(modelParamsLayout, _modelParamsBuffer));

            _imguiRenderer = new ImGuiRenderer(Device, Device.MainSwapchain.Framebuffer.OutputDescription, Window.Width, Window.Height);

            _sw = Stopwatch.StartNew();
        }
Ejemplo n.º 18
0
        public void ResourceSet_IncompatibleSet_Fails()
        {
            DeviceBuffer infoBuffer  = RF.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            DeviceBuffer orthoBuffer = RF.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float2),
                    new VertexElementDescription("Color_UInt", VertexElementSemantic.Color, VertexElementFormat.UInt4))
            },
                new Shader[]
            {
                TestShaders.Load(RF, "UIntVertexAttribs", ShaderStages.Vertex, "VS"),
                TestShaders.Load(RF, "UIntVertexAttribs", ShaderStages.Fragment, "FS")
            });

            ResourceLayout layout = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                new ResourceLayoutElementDescription("InfoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                new ResourceLayoutElementDescription("Ortho", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout layout2 = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                 new ResourceLayoutElementDescription("InfoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                 new ResourceLayoutElementDescription("Tex", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));

            ResourceLayout layout3 = RF.CreateResourceLayout(new ResourceLayoutDescription(
                                                                 new ResourceLayoutElementDescription("InfoBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            Texture     tex     = RF.CreateTexture(TextureDescription.Texture2D(16, 16, 1, 1, PixelFormat.R32_G32_B32_A32_Float, TextureUsage.Sampled));
            TextureView texView = RF.CreateTextureView(tex);

            ResourceSet set  = RF.CreateResourceSet(new ResourceSetDescription(layout, infoBuffer, orthoBuffer));
            ResourceSet set2 = RF.CreateResourceSet(new ResourceSetDescription(layout2, infoBuffer, texView));
            ResourceSet set3 = RF.CreateResourceSet(new ResourceSetDescription(layout3, infoBuffer));

            GraphicsPipelineDescription gpd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleOverrideBlend,
                DepthStencilStateDescription.Disabled,
                RasterizerStateDescription.Default,
                PrimitiveTopology.PointList,
                shaderSet,
                layout,
                new OutputDescription(null, new OutputAttachmentDescription(PixelFormat.B8_G8_R8_A8_UNorm)));

            Pipeline pipeline = RF.CreateGraphicsPipeline(ref gpd);

            CommandList cl = RF.CreateCommandList();

            cl.Begin();
            cl.SetPipeline(pipeline);
            cl.SetGraphicsResourceSet(0, set);
            Assert.Throws <VeldridException>(() => cl.SetGraphicsResourceSet(0, set2)); // Wrong type
            Assert.Throws <VeldridException>(() => cl.SetGraphicsResourceSet(0, set3)); // Wrong count
        }
Ejemplo n.º 19
0
        Pipeline BuildPipeline(GraphicsDevice gd, SceneContext sc, SpriteShaderKey key)
        {
            var shaderCache           = Resolve <IShaderCache>();
            var vertexShaderName      = "SpriteSV.vert";
            var fragmentShaderName    = "SpriteSF.frag";
            var vertexShaderContent   = shaderCache.GetGlsl(vertexShaderName);
            var fragmentShaderContent = shaderCache.GetGlsl(fragmentShaderName);

            if (key.UseArrayTexture)
            {
                fragmentShaderName   += ".array";
                fragmentShaderContent =
                    @"#define USE_ARRAY_TEXTURE
" + fragmentShaderContent;
            }

            var shaders = shaderCache.GetShaderPair(
                gd.ResourceFactory,
                vertexShaderName, fragmentShaderName,
                vertexShaderContent, fragmentShaderContent);

            _shaders.AddRange(shaders);
            var shaderSet = new ShaderSetDescription(new[] { VertexLayout, InstanceLayout }, shaders);

            Console.WriteLine($"-- Build SpriteRenderer-- IsDepth0..1: {gd.IsDepthRangeZeroToOne} YInvert: {gd.IsClipSpaceYInverted} UV TopLeft: {gd.IsUvOriginTopLeft}");
            var depthStencilMode =
                key.PerformDepthTest
                ?  gd.IsDepthRangeZeroToOne
                    ? DepthStencilStateDescription.DepthOnlyLessEqual
                    : DepthStencilStateDescription.DepthOnlyGreaterEqual
                : DepthStencilStateDescription.Disabled;

            var rasterizerMode = new RasterizerStateDescription(
                FaceCullMode.None,
                PolygonFillMode.Solid,
                FrontFace.Clockwise,
                key.PerformDepthTest, // depth test
                true);                // scissor test

            var pipelineDescription = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                depthStencilMode,
                rasterizerMode,
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(new[] { VertexLayout, InstanceLayout },
                                         shaderSet.Shaders,
                                         ShaderHelper.GetSpecializations(gd)),
                new[] { _perSpriteResourceLayout, sc.CommonResourceLayout },
                sc.MainSceneFramebuffer.OutputDescription);

            var pipeline = gd.ResourceFactory.CreateGraphicsPipeline(ref pipelineDescription);

            pipeline.Name = $"P_Sprite_{key}";
            return(pipeline);
        }
Ejemplo n.º 20
0
        public void CreateAllDrawingPipelines(ResourceLayout[] resourceLayouts, ShaderSetDescription shaderSetDescription, OutputDescription outputDescription)
        {
            _drawingPipelines = new Dictionary <BlendState, Pipeline>();

            var states = Enum.GetValues(typeof(BlendState));

            foreach (BlendState state in states)
            {
                _drawingPipelines.Add(state, CreateAPipeline(resourceLayouts, shaderSetDescription, outputDescription, _blendStateConverter.Convert(state), true));
            }
        }
Ejemplo n.º 21
0
        public void CreateResources()
        {
            mProjectionBuffer = mFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            mViewBuffer       = mFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            mWorldBuffer      = mFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            ChooseMesh();

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                mFactory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(VertexCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(FragmentCode), "main")));

            ResourceLayout projViewLayout = mFactory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldTextureLayout = mFactory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("WorldBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            mPipeline = mFactory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                            BlendStateDescription.SingleOverrideBlend,
                                                            DepthStencilStateDescription.DepthOnlyLessEqual,
                                                            RasterizerStateDescription.Default,
                                                            PrimitiveTopology.TriangleList,
                                                            shaderSet,
                                                            new[] { projViewLayout, worldTextureLayout },
                                                            mSwapchain.Framebuffer.OutputDescription));

            mProjViewSet = mFactory.CreateResourceSet(new ResourceSetDescription(
                                                          projViewLayout,
                                                          mProjectionBuffer,
                                                          mViewBuffer));

            mWorldTextureSet = mFactory.CreateResourceSet(new ResourceSetDescription(
                                                              worldTextureLayout,
                                                              mWorldBuffer,
                                                              mSurfaceTextureView,
                                                              mGraphicsDevice.Aniso4xSampler));

            mCommandList = mFactory.CreateCommandList();
        }
Ejemplo n.º 22
0
        public void CreateDeviceResources(GraphicsDevice gd, ResourceFactory factory)
        {
            ///创建一个默认的commandlist
            _cl = factory.CreateCommandList();

            //创建一个当前窗体大小的屏幕纹理
            _texture = factory.CreateTexture(TextureDescription.Texture2D((uint)_windowsWidth, (uint)_windowsHeight, 1, 1, PixelFormat.B8_G8_R8_A8_UNorm, TextureUsage.Sampled));
            //创建textureView
            _textureView = factory.CreateTextureView(_texture);

            //Create resourceLayout
            _screenResourceLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)
                    ));

            //create resourceview
            _screenResourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                               _screenResourceLayout,
                                                               _textureView,
                                                               gd.Aniso4xSampler
                                                               ));

            var curAss = this.GetType().Assembly;

            //无顶点布局
            _shaderset = new ShaderSetDescription(
                new VertexLayoutDescription[] { },
                new[]
            {
                ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "FullScreenVS.spv", gd, curAss),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "FullScreenFS.spv", gd, curAss),
            });

            var rasterizer = RasterizerStateDescription.Default;

            rasterizer.FillMode  = PolygonFillMode.Solid;
            rasterizer.FrontFace = FrontFace.CounterClockwise;
            rasterizer.CullMode  = FaceCullMode.Front;
            //创建渲染管道
            _screenPipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                 BlendStateDescription.SingleOverrideBlend,
                                                                 DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                 rasterizer,
                                                                 PrimitiveTopology.TriangleList,
                                                                 _shaderset,
                                                                 //共享View和prj的buffer
                                                                 new ResourceLayout[] { _screenResourceLayout },
                                                                 gd.MainSwapchain.Framebuffer.OutputDescription));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Constructs a new <see cref="GraphicsPipelineDescription"/>.
        /// </summary>
        /// <param name="blendState">A description of the blend state, which controls how color values are blended into each
        /// color target.</param>
        /// <param name="depthStencilStateDescription">A description of the depth stencil state, which controls depth tests,
        /// writing, and comparisons.</param>
        /// <param name="rasterizerState">A description of the rasterizer state, which controls culling, clipping, scissor, and
        /// polygon-fill behavior.</param>
        /// <param name="shaders">An array of <see cref="Shader"/> objects, one for each shader stage which is to be active
        /// in the <see cref="Pipeline"/>. At a minimum, every graphics Pipeline must include a Vertex and Fragment shader. All
        /// other stages are optional, but if either Tessellation stage is present, then the other must also be.</param>
        /// <param name="specializations">An array of <see cref="SpecializationConstant"/> used to override specialization
        /// constants in the created <see cref="Pipeline"/>. Each element in this array describes a single ID-value pair, which
        /// will be matched with the constants specified in each <see cref="Shader"/>.</param>
        /// <param name="resourceLayouts">An array of <see cref="ResourceLayout"/>, which controls the layout of shader resoruces
        /// in the <see cref="Pipeline"/>.</param>
        /// <param name="outputs">A description of the output attachments used by the <see cref="Pipeline"/>.</param>
        public GraphicsPipelineDescription CreateGraphicsPipelineDescription(
            ref VeldridPrimitive primitive,
            BlendStateDescription blendState,
            DepthStencilStateDescription depthStencilStateDescription,
            RasterizerStateDescription rasterizerState,
            Shader[] shaders,
            SpecializationConstant[] specializations,
            ResourceLayout[] resourceLayouts,
            OutputDescription outputs)
        {
            var shaderSetDescription = new ShaderSetDescription(new VertexLayoutDescription[] { primitive.VertexLayout }, shaders, specializations);

            return(new GraphicsPipelineDescription(blendState, depthStencilStateDescription, rasterizerState, primitive.PrimitiveTopology, shaderSetDescription, resourceLayouts, outputs));
        }
Ejemplo n.º 24
0
        public Shader(string path)
        {
            var vertexCode   = File.ReadAllText($"{path}.vert");
            var fragmentCode = File.ReadAllText($"{path}.frag");

            // TODO: Make generic, together with RenderObject
            // Probably requires waiting for Veldrid.SPIRV update
            var shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                Renderer.ResourceFactory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentCode), "main")));

            var matrixDescription = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("MVP", ResourceKind.UniformBuffer, ShaderStages.Vertex));

            var textureDescription = new ResourceLayoutDescription(
                new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly,
                                                     ShaderStages.Fragment),
                new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler,
                                                     ShaderStages.Fragment));

            MatrixLayout = Renderer.ResourceFactory.CreateResourceLayout(matrixDescription);

            TextureLayout = Renderer.ResourceFactory.CreateResourceLayout(textureDescription);

            var pipelineDescription = new GraphicsPipelineDescription
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerState   = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.Clockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = new[] { MatrixLayout, TextureLayout },
                ShaderSet         = shaderSet,
                Outputs           = Renderer.GraphicsDevice.SwapchainFramebuffer.OutputDescription
            };

            Pipeline = Renderer.ResourceFactory.CreateGraphicsPipeline(pipelineDescription);
        }
Ejemplo n.º 25
0
        public static void CreateResources(Game game)
        {
            WorldBuffer = game.Factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));

            var vertexShaderCode   = System.IO.File.ReadAllText("shaders/chunk.vert");
            var fragmentShaderCode = System.IO.File.ReadAllText("shaders/chunk.frag");

            var vertexLayout = new VertexLayoutDescription(
                new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                new VertexElementDescription("MaterialID", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Int1),
                new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                new VertexElementDescription("FaceDirection", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Int1));

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new VertexLayoutDescription[] { vertexLayout },
                game.Factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(vertexShaderCode), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(fragmentShaderCode), "main")));

            ResourceLayout projViewLayout = game.Factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldTextureLayout = game.Factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("WorldBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("DiffuseTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("NormalMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SurfaceSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            Pipeline = game.Factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                               BlendStateDescription.SingleOverrideBlend,
                                                               DepthStencilStateDescription.DepthOnlyLessEqual,
                                                               new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, false),
                                                               //new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Wireframe, FrontFace.Clockwise, true, false),
                                                               PrimitiveTopology.TriangleList,
                                                               shaderSet,
                                                               new[] { projViewLayout, worldTextureLayout },
                                                               game.Swapchain.Framebuffer.OutputDescription));

            WorldTextureSet = game.Factory.CreateResourceSet(new ResourceSetDescription(
                                                                 worldTextureLayout,
                                                                 WorldBuffer,
                                                                 game.BlockDiffuseTextureArray,
                                                                 game.BlockNormalMapArray,
                                                                 game.GraphicsDevice.Aniso4xSampler));
        }
Ejemplo n.º 26
0
        private void UpdateResources(GraphicsDevice device, RenderingContext context)
        {
            var factory = device.ResourceFactory;
            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3))
            },
                factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, Encoding.UTF8.GetBytes(_vertexShader), "main"),
                    new ShaderDescription(ShaderStages.Fragment, Encoding.UTF8.GetBytes(_fragShader), "main")));

            var projViewLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("SceneColours", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("SceneLighting", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleAlphaBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           _noCulling ? RasterizerStateDescription.CullNone : RasterizerStateDescription.Default,
                                                           PrimitiveTopology.TriangleList,
                                                           shaderSet,
                                                           new[] { projViewLayout, context.Renderer.ObjectLayout },
                                                           device.MainSwapchain.Framebuffer.OutputDescription));

            _wireframePipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                    BlendStateDescription.SingleOverrideBlend,
                                                                    DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                    new RasterizerStateDescription(FaceCullMode.None, PolygonFillMode.Wireframe, FrontFace.Clockwise, true, false),
                                                                    PrimitiveTopology.TriangleList,
                                                                    shaderSet,
                                                                    new[] { projViewLayout, context.Renderer.ObjectLayout },
                                                                    device.MainSwapchain.Framebuffer.OutputDescription));

            _projViewSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                         projViewLayout,
                                                         context.Renderer.ProjectionBuffer,
                                                         context.Renderer.ViewBuffer,
                                                         context.Renderer.WireframeColourBuffer,
                                                         context.Renderer.SceneLightingBuffer));
        }
Ejemplo n.º 27
0
        /*
         *
         * Display icons for the visualiser bar
         *
         */

        public static ShaderSetDescription CreateVisBarPointIconShader(GraphicsDevice gd)
        {
            VertexElementDescription VEDpos       = new VertexElementDescription("Coord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2);
            VertexElementDescription VEDcol       = new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4);
            VertexLayoutDescription  vertexLayout = new VertexLayoutDescription(VEDpos, VEDcol);

            byte[]            nodeVertShaderBytes = Encoding.UTF8.GetBytes(Shaders.SPIR_V.SPIRVShaders.vs_visbar_points);
            byte[]            nodeFragShaderBytes = Encoding.UTF8.GetBytes(Shaders.SPIR_V.SPIRVShaders.fs_visbar_points);
            ShaderDescription vertexShaderDesc    = new ShaderDescription(ShaderStages.Vertex, nodeVertShaderBytes, "main");
            ShaderDescription fragmentShaderDesc  = new ShaderDescription(ShaderStages.Fragment, nodeFragShaderBytes, "main");

            ShaderSetDescription shaderSetDesc = new ShaderSetDescription(
                vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                shaders: gd.ResourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc));

            return(shaderSetDesc);
        }
Ejemplo n.º 28
0
        public ShaderSet(
            GraphicsDevice graphicsDevice,
            string shaderName,
            GlobalResourceSetIndices globalResourceSetIndices,
            params VertexLayoutDescription[] vertexDescriptors)
        {
            GlobalResourceSetIndices = globalResourceSetIndices;

            Id = _nextId++;

#if DEBUG
            const bool debug = true;
#else
            const bool debug = false;
#endif

            var assembly = typeof(ShaderSet).Assembly;

            byte[] ReadShader(string shaderType)
            {
                var bytecodeShaderName = $"OpenSage.Assets.Shaders.{shaderName}.{shaderType}.spv";

                using (var shaderStream = assembly.GetManifestResourceStream(bytecodeShaderName))
                {
                    return(shaderStream.ReadAllBytes());
                }
            }

            var vsBytes = ReadShader("vert");
            var fsBytes = ReadShader("frag");

            var shaders = graphicsDevice.ResourceFactory.CreateFromSpirv(
                new ShaderDescription(ShaderStages.Vertex, vsBytes, "main", debug),
                new ShaderDescription(ShaderStages.Fragment, fsBytes, "main", debug),
                new CrossCompileOptions());

            var vertexShader   = AddDisposable(shaders[0]);
            var fragmentShader = AddDisposable(shaders[1]);

            vertexShader.Name   = $"{shaderName}.vert";
            fragmentShader.Name = $"{shaderName}.frag";

            Description = new ShaderSetDescription(
                vertexDescriptors,
                new[] { vertexShader, fragmentShader });
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 创建相关资源
        /// </summary>
        /// <param name="gd"></param>
        /// <param name="factory"></param>
        public void CreateDeviceResources(GraphicsDevice gd, ResourceFactory factory)
        {
            List <Vector3> positions = new List <Vector3>();

            //记录其indices
            // List<ushort> indics = new List<ushort>();
            //填充顶点跟索引
            //详细流程,如果是投影坐标,将其转换成wgs84的经纬度坐标,再使用参考系计算出其真实的地理坐标
            foreach (var coord in _feature.Geometry.Coordinates)
            {
                //将其转换成弧度制,自动贴地
                positions.Add(_shape.ToVector3(new Geodetic3D(MathExtension.ToRadius(coord.X), MathExtension.ToRadius(coord.Y))));
            }
            //三角网化
            var indices = EarClippingOnEllipsoid.Triangulate(positions);

            //三角细分,细分精度为1度
            _mesh         = TriangleMeshSubdivision.Compute(positions, indices.ToArray(), Math.PI / 180);
            _vertexBuffer = factory.CreateBuffer(new BufferDescription((uint)(12 * _mesh.Positions.Count()), BufferUsage.VertexBuffer));
            gd.UpdateBuffer(_vertexBuffer, 0, _mesh.Positions);
            _indexBuffer = factory.CreateBuffer(new BufferDescription((uint)(sizeof(ushort) * _mesh.Indices.Length), BufferUsage.IndexBuffer));
            gd.UpdateBuffer(_indexBuffer, 0, _mesh.Indices);
            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3))
            },
                new[]
            {
                ResourceHelper.LoadEmbbedShader(ShaderStages.Vertex, "GlobeVS.spv", gd),
                ResourceHelper.LoadEmbbedShader(ShaderStages.Fragment, "GlobeFS.spv", gd)
            });

            _pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                           BlendStateDescription.SingleOverrideBlend,
                                                           DepthStencilStateDescription.DepthOnlyLessEqual,
                                                           RasterizerStateDescription.Default,
                                                           PrimitiveTopology.TriangleList,
                                                           shaderSet,
                                                           //共享View和prj的buffer
                                                           new ResourceLayout[] { ShareResource.ProjectionResourceLoyout },
                                                           gd.MainSwapchain.Framebuffer.OutputDescription));
            _cl = factory.CreateCommandList();
        }
Ejemplo n.º 30
0
        /*
         *
         * Picking node points for mousing over instruction verts
         *
         */


        public static ShaderSetDescription CreateNodePickingShaders(GraphicsDevice gd, out DeviceBuffer vertBuffer)
        {
            VertexElementDescription VEDpos       = new VertexElementDescription("PositionBufIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Int1);
            VertexElementDescription VEDcol       = new VertexElementDescription("Color", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float4);
            VertexLayoutDescription  vertexLayout = new VertexLayoutDescription(VEDpos, VEDcol);

            byte[]            vertShaderBytes    = Encoding.UTF8.GetBytes(Shaders.SPIR_V.SPIRVShaders.vspickingglsl);
            byte[]            fragShaderBytes    = Encoding.UTF8.GetBytes(Shaders.SPIR_V.SPIRVShaders.fspickingglsl);
            ShaderDescription vertexShaderDesc   = new ShaderDescription(ShaderStages.Vertex, vertShaderBytes, "main");
            ShaderDescription fragmentShaderDesc = new ShaderDescription(ShaderStages.Fragment, fragShaderBytes, "main");

            ShaderSetDescription shaderSetDesc = new ShaderSetDescription(
                vertexLayouts: new VertexLayoutDescription[] { vertexLayout },
                shaders: gd.ResourceFactory.CreateFromSpirv(vertexShaderDesc, fragmentShaderDesc));

            vertBuffer = VeldridGraphBuffers.TrackedVRAMAlloc(gd, 1, BufferUsage.VertexBuffer, name: "NodePickingShaderVertexBufInitial");
            return(shaderSetDesc);
        }