Example #1
0
        public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope)
        {
            var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector);

            BonesBuffer = factory.CreateBuffer(new BufferDescription((uint)(Marshal.SizeOf <Matrix4x4>() * MDLConstants.MaxBones), BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            RenderArgumentsBuffer = factory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <StudioRenderArguments>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            TextureDataBuffer = factory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <StudioTextureData>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            _sharedLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                             new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                             new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                             new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                             new ResourceLayoutElementDescription("Bones", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                             new ResourceLayoutElementDescription("RenderArguments", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                             new ResourceLayoutElementDescription("TextureData", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                             new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                             new ResourceLayoutElementDescription("LightingInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            TextureLayout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                             new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));

            var vertexLayouts = new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TextureCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3),
                    new VertexElementDescription("VertexBoneIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt1),
                    new VertexElementDescription("NormalBoneIndex", VertexElementSemantic.TextureCoordinate, VertexElementFormat.UInt1))
            };

            for (var cullMode = CullBack; cullMode < CullModeCount; ++cullMode)
            {
                for (var maskMode = MaskDisabled; maskMode < MaskModeCount; ++maskMode)
                {
                    for (var additiveMode = AdditiveDisabled; additiveMode < AdditiveModeCount; ++additiveMode)
                    {
                        _pipelines[cullMode, maskMode, additiveMode] = CreatePipelines(
                            gd, sc, vertexLayouts, _sharedLayout, TextureLayout, factory,
                            cullMode == CullBack,
                            maskMode == MaskEnabled,
                            additiveMode == AdditiveEnabled);
                    }
                }
            }

            SharedResourceSet = factory.CreateResourceSet(new ResourceSetDescription(
                                                              _sharedLayout,
                                                              sc.ProjectionMatrixBuffer,
                                                              sc.ViewMatrixBuffer,
                                                              sc.WorldAndInverseBuffer,
                                                              BonesBuffer,
                                                              RenderArgumentsBuffer,
                                                              TextureDataBuffer,
                                                              sc.MainSampler,
                                                              sc.LightingInfoBuffer
                                                              ));
        }
Example #2
0
        public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope)
        {
            if ((scope & ResourceScope.Map) == 0)
            {
                return;
            }

            var renderer = sc.Models.GetRenderer <SpriteModelRenderer>();

            var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector);

            (var atlasImage, var vertexBuffers) = SPRResourceUtils.CreateSpriteAtlas(SpriteModel.SpriteFile, gd, disposeFactory, sc.TextureLoader);

            //TODO: disable mipmapping for certain sprites?
            var texture = sc.MapResourceCache.AddTexture2D(gd, disposeFactory, new ImageSharpTexture(atlasImage, true), $"{SpriteModel.Name}_atlas");

            VertexBuffers = vertexBuffers;

            IndexBuffer = SPRResourceUtils.CreateIndexBuffer(gd, disposeFactory);

            RenderColorBuffer = disposeFactory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <Vector4>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            var view = sc.MapResourceCache.GetTextureView(gd.ResourceFactory, texture);

            ResourceSet = disposeFactory.CreateResourceSet(new ResourceSetDescription(
                                                               renderer.Layout,
                                                               sc.ProjectionMatrixBuffer,
                                                               sc.ViewMatrixBuffer,
                                                               sc.WorldAndInverseBuffer,
                                                               view,
                                                               sc.MainSampler,
                                                               sc.LightingInfoBuffer,
                                                               RenderColorBuffer));
        }
Example #3
0
 public void UpdateResourceSet(ResourceSetDescription description)
 {
     if (Set != null)
     {
         Set.Dispose();
     }
     Set = factory.CreateResourceSet(description);
 }
Example #4
0
        public override void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope)
        {
            if ((scope & ResourceScope.Map) == 0)
            {
                return;
            }

            var renderer = sc.Models.GetRenderer <StudioModelRenderer>();

            var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector);

            var vertices = new List <StudioVertex>();
            var indices  = new List <uint>();

            //Construct the meshes for each body part
            var bodyParts = new List <BodyPartData>(StudioModel.StudioFile.BodyParts.Count);

            foreach (var bodyPart in StudioModel.StudioFile.BodyParts)
            {
                bodyParts.Add(StudioResourceUtils.CreateBodyPart(StudioModel.StudioFile, bodyPart, vertices, indices));
            }

            BodyParts = bodyParts.ToArray();

            var verticesArray = vertices.ToArray();
            var indicesArray  = indices.ToArray();

            VertexBuffer = disposeFactory.CreateBuffer(new BufferDescription(verticesArray.SizeInBytes(), BufferUsage.VertexBuffer));

            gd.UpdateBuffer(VertexBuffer, 0, verticesArray);

            IndexBuffer = disposeFactory.CreateBuffer(new BufferDescription(indicesArray.SizeInBytes(), BufferUsage.IndexBuffer));

            gd.UpdateBuffer(IndexBuffer, 0, indicesArray);

            var uploadedTextures = StudioResourceUtils.CreateTextures(StudioModel.Name, StudioModel.StudioFile, gd, sc.TextureLoader, sc.MapResourceCache);

            Textures = new ResourceSet[uploadedTextures.Count];

            for (var i = 0; i < uploadedTextures.Count; ++i)
            {
                var view = sc.MapResourceCache.GetTextureView(gd.ResourceFactory, uploadedTextures[i]);

                Textures[i] = disposeFactory.CreateResourceSet(new ResourceSetDescription(renderer.TextureLayout, view));
            }
        }
        private void CreateResources()
        {
            _factory = new DisposeCollectorResourceFactory(_gd.ResourceFactory);

            _cl = _factory.CreateCommandList();

            _cl.Begin();
            _projectionBuffer = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBuffer       = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _modelBuffer      = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            _projectionBufferForShadowShader = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _viewBufferShadow  = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            _modelBufferShadow = _factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            // TODO: no idea why this buffer requires 48 bytes instead of 32 bytes, padding?
            //_directionLightBuffer = _factory.CreateBuffer(new BufferDescription(48, BufferUsage.UniformBuffer));
            // addition of shadowmatrix, now requires (48+64=) 112 bytes
            _directionLightBuffer = _factory.CreateBuffer(new BufferDescription(112, BufferUsage.UniformBuffer));

            _cl.End();
            _gd.SubmitCommands(_cl);
            _gd.WaitForIdle();

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                    new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3))
            },
                new[]
            {
                LoadShader(_factory, "ColorShader", ShaderStages.Vertex, "VS"),
                LoadShader(_factory, "ColorShader", ShaderStages.Fragment, "FS")
            });

            ShaderSetDescription shaderSetShadow = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.Position, VertexElementFormat.Float3),
                    new VertexElementDescription("Color", VertexElementSemantic.Color, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.Normal, VertexElementFormat.Float3))
            },
                new[]
            {
                LoadShader(_factory, "ShadowShader", ShaderStages.Vertex, "VS"),
                LoadShader(_factory, "ShadowShader", ShaderStages.Fragment, "FS")
            });

            ResourceLayout projectionViewMatricesLightLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                    new ResourceLayoutElementDescription("DirectionalLight", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("ShadowMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                    new ResourceLayoutElementDescription("ShadowMapSampler", ResourceKind.Sampler, ShaderStages.Fragment)
                    ));

            ResourceLayout perObjectLayout = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex)
                    ));

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

            ResourceLayout modelLayoutShadow = _factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("Model", ResourceKind.UniformBuffer, ShaderStages.Vertex)
                    ));

            _pipeline = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                            BlendStateDescription.SingleOverrideBlend,
                                                            DepthStencilStateDescription.DepthOnlyLessEqual,
                                                            RasterizerStateDescription.Default,
                                                            PrimitiveTopology.TriangleList,
                                                            shaderSet,
                                                            new[] { projectionViewMatricesLightLayout, perObjectLayout },
                                                            _gd.SwapchainFramebuffer.OutputDescription));

            TextureDescription desc = TextureDescription.Texture2D(2048, 2048, 1, 1, PixelFormat.D32_Float_S8_UInt, TextureUsage.DepthStencil | TextureUsage.Sampled);

            _shadowMap            = _factory.CreateTexture(desc);
            _shadowMap.Name       = "Shadow Map";
            _shadowMapView        = _factory.CreateTextureView(_shadowMap);
            _shadowMapFramebuffer = _factory.CreateFramebuffer(new FramebufferDescription(
                                                                   new FramebufferAttachmentDescription(_shadowMap, 0), Array.Empty <FramebufferAttachmentDescription>()));


            _pipelineShadow = _factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                  BlendStateDescription.Empty,
                                                                  DepthStencilStateDescription.DepthOnlyLessEqual,
                                                                  RasterizerStateDescription.Default,
                                                                  PrimitiveTopology.TriangleList,
                                                                  shaderSetShadow,
                                                                  new[] { projectionViewMatricesLayoutShadow, modelLayoutShadow },
                                                                  _shadowMapFramebuffer.OutputDescription));

            _projectionViewMatricesLightSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                             projectionViewMatricesLightLayout,
                                                                             _projectionBuffer,
                                                                             _viewBuffer,
                                                                             _directionLightBuffer,
                                                                             _shadowMapView,
                                                                             _gd.PointSampler));

            _perObjectSet = _factory.CreateResourceSet(new ResourceSetDescription(
                                                           perObjectLayout,
                                                           _modelBuffer));

            _projectionViewMatricesSetShadow = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                              projectionViewMatricesLayoutShadow,
                                                                              _projectionBufferForShadowShader,
                                                                              _viewBufferShadow));

            _modelMatrixSetShadow = _factory.CreateResourceSet(new ResourceSetDescription(
                                                                   modelLayoutShadow,
                                                                   _modelBufferShadow));
        }
Example #6
0
        static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine($"ImageTint <image-path> <out>: Tints the image at <image-path> and saves it to <out>.");
                return(1);
            }

            string inPath  = args[0];
            string outPath = args[1];

            // This demo uses WindowState.Hidden to avoid popping up an unnecessary window to the user.

            VeldridStartup.CreateWindowAndGraphicsDevice(
                new WindowCreateInfo
            {
                WindowInitialState = WindowState.Hidden,
            },
                new GraphicsDeviceOptions()
            {
                ResourceBindingModel = ResourceBindingModel.Improved
            },
                out Sdl2Window window,
                out GraphicsDevice gd);

            DisposeCollectorResourceFactory factory = new DisposeCollectorResourceFactory(gd.ResourceFactory);

            ImageSharpTexture inputImage   = new ImageSharpTexture(inPath, false);
            Texture           inputTexture = inputImage.CreateDeviceTexture(gd, factory);
            TextureView       view         = factory.CreateTextureView(inputTexture);

            Texture output = factory.CreateTexture(TextureDescription.Texture2D(
                                                       inputImage.Width,
                                                       inputImage.Height,
                                                       1,
                                                       1,
                                                       PixelFormat.R8_G8_B8_A8_UNorm,
                                                       TextureUsage.RenderTarget));
            Framebuffer framebuffer = factory.CreateFramebuffer(new FramebufferDescription(null, output));

            DeviceBuffer vertexBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.VertexBuffer));

            Vector4[] quadVerts =
            {
                new Vector4(-1,  1, 0, 0),
                new Vector4(1,   1, 1, 0),
                new Vector4(-1, -1, 0, 1),
                new Vector4(1,  -1, 1, 1),
            };
            gd.UpdateBuffer(vertexBuffer, 0, quadVerts);

            ShaderSetDescription shaderSet = new ShaderSetDescription(
                new[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("TextureCoordinates", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            },
                factory.CreateFromSpirv(
                    new ShaderDescription(ShaderStages.Vertex, ReadEmbeddedAssetBytes("TintShader-vertex.glsl"), "main"),
                    new ShaderDescription(ShaderStages.Fragment, ReadEmbeddedAssetBytes("TintShader-fragment.glsl"), "main")));

            ResourceLayout layout = factory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                     new ResourceLayoutElementDescription("Input", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                     new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                                     new ResourceLayoutElementDescription("Tint", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            Pipeline pipeline = factory.CreateGraphicsPipeline(new GraphicsPipelineDescription(
                                                                   BlendStateDescription.SingleOverrideBlend,
                                                                   DepthStencilStateDescription.Disabled,
                                                                   RasterizerStateDescription.Default,
                                                                   PrimitiveTopology.TriangleStrip,
                                                                   shaderSet,
                                                                   layout,
                                                                   framebuffer.OutputDescription));

            DeviceBuffer tintInfoBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));

            gd.UpdateBuffer(
                tintInfoBuffer, 0,
                new TintInfo(
                    new Vector3(1f, 0.2f, 0.1f), // Change this to modify the tint color.
                    0.25f));

            ResourceSet resourceSet = factory.CreateResourceSet(
                new ResourceSetDescription(layout, view, gd.PointSampler, tintInfoBuffer));

            // RenderTarget textures are not CPU-visible, so to get our tinted image back, we need to first copy it into
            // a "staging Texture", which is a Texture that is CPU-visible (it can be Mapped).
            Texture stage = factory.CreateTexture(TextureDescription.Texture2D(
                                                      inputImage.Width,
                                                      inputImage.Height,
                                                      1,
                                                      1,
                                                      PixelFormat.R8_G8_B8_A8_UNorm,
                                                      TextureUsage.Staging));

            CommandList cl = factory.CreateCommandList();

            cl.Begin();
            cl.SetFramebuffer(framebuffer);
            cl.SetFullViewports();
            cl.SetVertexBuffer(0, vertexBuffer);
            cl.SetPipeline(pipeline);
            cl.SetGraphicsResourceSet(0, resourceSet);
            cl.Draw(4, 1, 0, 0);
            cl.CopyTexture(
                output, 0, 0, 0, 0, 0,
                stage, 0, 0, 0, 0, 0,
                stage.Width, stage.Height, 1, 1);
            cl.End();
            gd.SubmitCommands(cl);
            gd.WaitForIdle();

            // When a texture is mapped into a CPU-visible region, it is often not laid out linearly.
            // Instead, it is laid out as a series of rows, which are all spaced out evenly by a "row pitch".
            // This spacing is provided in MappedResource.RowPitch.

            // It is also possible to obtain a "structured view" of a mapped data region, which is what is done below.
            // With a structured view, you can read individual elements from the region.
            // The code below simply iterates over the two-dimensional region and places each texel into a linear buffer.
            // ImageSharp requires the pixel data be contained in a linear buffer.
            MappedResourceView <Rgba32> map = gd.Map <Rgba32>(stage, MapMode.Read);

            // Rgba32 is synonymous with PixelFormat.R8_G8_B8_A8_UNorm.
            Rgba32[] pixelData = new Rgba32[stage.Width * stage.Height];
            for (int y = 0; y < stage.Height; y++)
            {
                for (int x = 0; x < stage.Width; x++)
                {
                    int index = (int)(y * stage.Width + x);
                    pixelData[index] = map[x, y];
                }
            }
            gd.Unmap(stage); // Resources should be Unmapped when the region is no longer used.

            Image <Rgba32> outputImage = Image.LoadPixelData(pixelData, (int)stage.Width, (int)stage.Height);

            outputImage.Save(outPath);

            factory.DisposeCollector.DisposeAll();

            gd.Dispose();
            window.Close();
            return(0);
        }
Example #7
0
 public ResourceSet CreateResourceSet(ResourceSetDescription resourceSetDescription) => _factory.CreateResourceSet(resourceSetDescription);
        public void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, SceneContext sc, ResourceScope scope)
        {
            if ((scope & ResourceScope.Map) == 0)
            {
                return;
            }

            var disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector);

            _sharedLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                    new ResourceLayoutElementDescription("Projection", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                    new ResourceLayoutElementDescription("View", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                    new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                    new ResourceLayoutElementDescription("LightingInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                                                                    new ResourceLayoutElementDescription("LightStyles", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                                                                    new ResourceLayoutElementDescription("RenderColor", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            TextureLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                    new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                    new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            LightmapLayout = disposeFactory.CreateResourceLayout(new ResourceLayoutDescription(
                                                                     new ResourceLayoutElementDescription("Lightmaps", ResourceKind.TextureReadOnly, ShaderStages.Fragment)));

            var vertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TextureCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    new VertexElementDescription("LightmapCoords", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2),
                    //Used for multiple light styles; this is the offset to apply to lightmap X coordinates
                    new VertexElementDescription("LightmapXOffset", VertexElementSemantic.Position, VertexElementFormat.Float1),
                    new VertexElementDescription("StyleIndices", VertexElementSemantic.Position, VertexElementFormat.Int4))
            };

            (var vs, var fs) = sc.MapResourceCache.GetShaders(gd, gd.ResourceFactory, "LightMappedGeneric");

            //Create render mode pipelines
            var rasterizerState = new RasterizerStateDescription(FaceCullMode.Back, PolygonFillMode.Solid, FrontFace.Clockwise, true, true);
            const PrimitiveTopology primitiveTopology = PrimitiveTopology.TriangleList;
            var shaderSets        = new ShaderSetDescription(vertexLayouts, new[] { vs, fs });
            var resourceLayouts   = new ResourceLayout[] { _sharedLayout, TextureLayout, LightmapLayout };
            var outputDescription = sc.MainSceneFramebuffer.OutputDescription;

            var pipelines = new Pipeline[(int)RenderMode.Last + 1];

            var pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleDisabled,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.Normal] = disposeFactory.CreateGraphicsPipeline(ref pd);

            pipelines[(int)RenderMode.TransColor] = disposeFactory.CreateGraphicsPipeline(ref pd);

            pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleAlphaBlend,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.TransTexture] = disposeFactory.CreateGraphicsPipeline(ref pd);

            //Glow uses the same pipeline as texture
            pipelines[(int)RenderMode.Glow] = pipelines[(int)RenderMode.TransTexture];

            pd = new GraphicsPipelineDescription(
                BlendStateDescription.SingleDisabled,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.TransAlpha] = disposeFactory.CreateGraphicsPipeline(ref pd);

            pd = new GraphicsPipelineDescription(
                BlendStates.SingleAdditiveOneOneBlend,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqualRead : DepthStencilStateDescription.DepthOnlyLessEqualRead,
                rasterizerState,
                primitiveTopology,
                shaderSets,
                resourceLayouts,
                outputDescription);

            pipelines[(int)RenderMode.TransAdd] = disposeFactory.CreateGraphicsPipeline(ref pd);

            Pipelines = new RenderModePipelines(pipelines);

            RenderArgumentsBuffer = disposeFactory.CreateBuffer(new BufferDescription((uint)Marshal.SizeOf <BSPRenderArguments>(), BufferUsage.UniformBuffer | BufferUsage.Dynamic));

            _sharedResourceSet = disposeFactory.CreateResourceSet(new ResourceSetDescription(
                                                                      _sharedLayout,
                                                                      sc.ProjectionMatrixBuffer,
                                                                      sc.ViewMatrixBuffer,
                                                                      sc.WorldAndInverseBuffer,
                                                                      sc.LightingInfoBuffer,
                                                                      sc.LightStylesBuffer,
                                                                      RenderArgumentsBuffer));
        }
Example #9
0
        public void CreateDeviceResources(GraphicsDevice gd)
        {
            var factory = new DisposeCollectorResourceFactory(gd.ResourceFactory, disposeCollector);

            vertexBuffer = model.CreateVertexBuffer(gd);
            indexBuffer  = model.CreateIndexBuffer(gd, out indexCount);

            transformationBuffer = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            projectionBuffer     = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));
            viewBuffer           = factory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer));

            texture = textureData.CreateDeviceTexture(gd, factory);
            lightDirectionBuffer = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            lightColorBuffer     = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            shineDamperBuffer    = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));
            reflectivityBuffer   = factory.CreateBuffer(new BufferDescription(16, BufferUsage.UniformBuffer));

            var vertexLayoutDesc = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate),
                    new VertexElementDescription("TexCoord", VertexElementFormat.Float2, VertexElementSemantic.TextureCoordinate),
                    new VertexElementDescription("Normal", VertexElementFormat.Float3, VertexElementSemantic.TextureCoordinate)
                    )
            };

            var transformationResourceLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription[]
            {
                new ResourceLayoutElementDescription("TransformationBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                new ResourceLayoutElementDescription("ProjectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                new ResourceLayoutElementDescription("ViewBuffer", ResourceKind.UniformBuffer, ShaderStages.Vertex)
            }
                    ));

            var textureResourceLayout = factory.CreateResourceLayout(
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription[]
            {
                new ResourceLayoutElementDescription("Texture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("Sampler", ResourceKind.Sampler, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("LightDirectionBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("LightColorBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("ShineDamperBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment),
                new ResourceLayoutElementDescription("ReflectivityBuffer", ResourceKind.UniformBuffer, ShaderStages.Fragment)
            }
                    ));

            transformationResourceSet = factory.CreateResourceSet(
                new ResourceSetDescription(
                    transformationResourceLayout,
                    transformationBuffer,
                    projectionBuffer,
                    viewBuffer));

            textureResourceSet = factory.CreateResourceSet(
                new ResourceSetDescription(
                    textureResourceLayout,
                    texture,
                    gd.Aniso4xSampler,
                    lightDirectionBuffer,
                    lightColorBuffer,
                    shineDamperBuffer,
                    reflectivityBuffer));

            var pipelineDesc = new GraphicsPipelineDescription
            {
                BlendState        = BlendStateDescription.SingleOverrideBlend,
                DepthStencilState = new DepthStencilStateDescription(
                    depthTestEnabled: true,
                    depthWriteEnabled: true,
                    comparisonKind: ComparisonKind.LessEqual
                    ),
                RasterizerState = new RasterizerStateDescription(
                    cullMode: FaceCullMode.Back,
                    fillMode: PolygonFillMode.Solid,
                    frontFace: FrontFace.CounterClockwise,
                    depthClipEnabled: true,
                    scissorTestEnabled: false),
                PrimitiveTopology = PrimitiveTopology.TriangleList,
                ResourceLayouts   = new ResourceLayout[] { transformationResourceLayout, textureResourceLayout },
                ShaderSet         = new ShaderSetDescription(
                    vertexLayouts: vertexLayoutDesc,
                    shaders: new[] { vertexShader, fragmentShader }),
                Outputs = gd.SwapchainFramebuffer.OutputDescription
            };

            pipeline = factory.CreateGraphicsPipeline(pipelineDesc);
        }
Example #10
0
        public unsafe void CreateDeviceObjects(GraphicsDevice gd, CommandList cl, GraphicsSystem sc)
        {
            ResourceFactory disposeFactory = new DisposeCollectorResourceFactory(gd.ResourceFactory, _disposeCollector);

            _vb      = _meshData.CreateVertexBuffer(disposeFactory, cl);
            _vb.Name = _name + "_VB";
            _ib      = _meshData.CreateIndexBuffer(disposeFactory, cl, out _indexCount);
            _ib.Name = _name + "_IB";

            _worldAndInverseBuffer = disposeFactory.CreateBuffer(new BufferDescription(64 * 2, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            if (_materialPropsOwned)
            {
                _materialProps.CreateDeviceObjects(gd, cl, sc);
            }

            if (_textureData != null)
            {
                _texture = StaticResourceCache.GetTexture2D(gd, gd.ResourceFactory, _textureData);
            }
            else
            {
                _texture = disposeFactory.CreateTexture(TextureDescription.Texture2D(1, 1, 1, 1, PixelFormat.R8_G8_B8_A8_UNorm, TextureUsage.Sampled));
                RgbaByte color = RgbaByte.Pink;
                gd.UpdateTexture(_texture, (IntPtr)(&color), 4, 0, 0, 0, 1, 1, 1, 0, 0);
            }

            _textureView = StaticResourceCache.GetTextureView(gd.ResourceFactory, _texture);

            if (_alphaTextureData != null)
            {
                _alphamapTexture = _alphaTextureData.CreateDeviceTexture(gd, disposeFactory);
            }
            else
            {
                _alphamapTexture = StaticResourceCache.GetPinkTexture(gd, gd.ResourceFactory);
            }
            _alphaMapView = StaticResourceCache.GetTextureView(gd.ResourceFactory, _alphamapTexture);

            VertexLayoutDescription[] shadowDepthVertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            };

            (Shader depthVS, Shader depthFS) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "ShadowDepth");

            ResourceLayout projViewCombinedLayout = StaticResourceCache.GetResourceLayout(
                gd.ResourceFactory,
                new ResourceLayoutDescription(
                    new ResourceLayoutElementDescription("ViewProjection", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            ResourceLayout worldLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription(
                                                                                   new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex)));

            GraphicsPipelineDescription depthPD = new GraphicsPipelineDescription(
                BlendStateDescription.Empty,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerStateDescription.Default,
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(shadowDepthVertexLayouts, new[] { depthVS, depthFS }),
                new ResourceLayout[] { projViewCombinedLayout, worldLayout },
                sc.NearShadowMapFramebuffer.OutputDescription);

            _shadowMapPipeline = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref depthPD);

            _shadowMapResourceSets = CreateShadowMapResourceSets(gd.ResourceFactory, disposeFactory, cl, sc, projViewCombinedLayout, worldLayout);

            VertexLayoutDescription[] mainVertexLayouts = new VertexLayoutDescription[]
            {
                new VertexLayoutDescription(
                    new VertexElementDescription("Position", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("Normal", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float3),
                    new VertexElementDescription("TexCoord", VertexElementSemantic.TextureCoordinate, VertexElementFormat.Float2))
            };

            (Shader mainVS, Shader mainFS) = StaticResourceCache.GetShaders(gd, gd.ResourceFactory, "ShadowMain");

            ResourceLayout projViewLayout = StaticResourceCache.GetResourceLayout(
                gd.ResourceFactory,
                StaticResourceCache.ProjViewLayoutDescription);

            ResourceLayout mainSharedLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription(
                                                                                        new ResourceLayoutElementDescription("LightViewProjection1", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("LightViewProjection2", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("LightViewProjection3", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("DepthLimits", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("LightInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("CameraInfo", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("PointLights", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment)));

            ResourceLayout mainPerObjectLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription(
                                                                                           new ResourceLayoutElementDescription("WorldAndInverse", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("MaterialProperties", ResourceKind.UniformBuffer, ShaderStages.Vertex | ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("SurfaceTexture", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("RegularSampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("AlphaMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("AlphaMapSampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("ShadowMapNear", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("ShadowMapMid", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("ShadowMapFar", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                           new ResourceLayoutElementDescription("ShadowMapSampler", ResourceKind.Sampler, ShaderStages.Fragment)));

            ResourceLayout reflectionLayout = StaticResourceCache.GetResourceLayout(gd.ResourceFactory, new ResourceLayoutDescription(
                                                                                        new ResourceLayoutElementDescription("ReflectionMap", ResourceKind.TextureReadOnly, ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("ReflectionSampler", ResourceKind.Sampler, ShaderStages.Fragment),
                                                                                        new ResourceLayoutElementDescription("ReflectionViewProj", ResourceKind.UniformBuffer, ShaderStages.Vertex),
                                                                                        new ResourceLayoutElementDescription("ClipPlaneInfo", ResourceKind.UniformBuffer, ShaderStages.Fragment)));

            GraphicsPipelineDescription mainPD = new GraphicsPipelineDescription(
                _alphamapTexture != null ? BlendStateDescription.SingleAlphaBlend : BlendStateDescription.SingleOverrideBlend,
                gd.IsDepthRangeZeroToOne ? DepthStencilStateDescription.DepthOnlyGreaterEqual : DepthStencilStateDescription.DepthOnlyLessEqual,
                RasterizerStateDescription.Default,
                PrimitiveTopology.TriangleList,
                new ShaderSetDescription(mainVertexLayouts, new[] { mainVS, mainFS }),
                new ResourceLayout[] { projViewLayout, mainSharedLayout, mainPerObjectLayout, reflectionLayout },
                sc.MainSceneFramebuffer.OutputDescription);

            _pipeline      = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref mainPD);
            _pipeline.Name = "MeshRenderer Main Pipeline";
            mainPD.RasterizerState.CullMode = FaceCullMode.Front;
            mainPD.Outputs     = sc.ReflectionFramebuffer.OutputDescription;
            _pipelineFrontCull = StaticResourceCache.GetPipeline(gd.ResourceFactory, ref mainPD);

            _mainProjViewRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(projViewLayout,
                                                                                                                sc.ProjectionMatrixBuffer,
                                                                                                                sc.ViewMatrixBuffer));

            _mainSharedRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(mainSharedLayout,
                                                                                                              sc.LightViewProjectionBuffer0,
                                                                                                              sc.LightViewProjectionBuffer1,
                                                                                                              sc.LightViewProjectionBuffer2,
                                                                                                              sc.DepthLimitsBuffer,
                                                                                                              sc.LightInfoBuffer,
                                                                                                              sc.CameraInfoBuffer,
                                                                                                              sc.PointLightsBuffer));

            _mainPerObjectRS = disposeFactory.CreateResourceSet(new ResourceSetDescription(mainPerObjectLayout,
                                                                                           _worldAndInverseBuffer,
                                                                                           _materialProps.UniformBuffer,
                                                                                           _textureView,
                                                                                           gd.Aniso4xSampler,
                                                                                           _alphaMapView,
                                                                                           gd.LinearSampler,
                                                                                           sc.NearShadowMapView,
                                                                                           sc.MidShadowMapView,
                                                                                           sc.FarShadowMapView,
                                                                                           gd.PointSampler));

            _reflectionRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(reflectionLayout,
                                                                                                              _alphaMapView, // Doesn't really matter -- just don't bind the actual reflection map since it's being rendered to.
                                                                                                              gd.PointSampler,
                                                                                                              sc.ReflectionViewProjBuffer,
                                                                                                              sc.MirrorClipPlaneBuffer));

            _noReflectionRS = StaticResourceCache.GetResourceSet(gd.ResourceFactory, new ResourceSetDescription(reflectionLayout,
                                                                                                                sc.ReflectionColorView,
                                                                                                                gd.PointSampler,
                                                                                                                sc.ReflectionViewProjBuffer,
                                                                                                                sc.NoClipPlaneBuffer));
        }