Exemple #1
0
 public Pipeline(Device dev, VkPipelineBindPoint type, PipelineLayout layout, VkPipeline pipeline)
 {
     PipelineType = type;
     Device       = dev;
     Layout       = layout;
     Handle       = pipeline;
 }
Exemple #2
0
 public override void DestroyPipeline(VkPipeline pipeline)
 {
     if (pipeline != null)
     {
         ((SoftwarePipeline)pipeline).Destroy();
     }
 }
Exemple #3
0
        // Called by the parent renderer when the MSAA changes
        internal void Rebuild()
        {
            // Destroy old handle
            Handle?.DestroyPipeline(null);

            // Create new handle
            Handle = CreatePipeline(BuildCache !, Renderer, Subpass, Layout, ShaderProgram);
        }
Exemple #4
0
        public void CmdBindPipeline(VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline)
        {
            if (m_State != CommandBufferState.Recording)
            {
                return;
            }

            m_Commands.Add(new Cmd_BindPipeline(pipelineBindPoint, pipeline));
        }
Exemple #5
0
 public Pipeline(
     Device device,
     RenderPass renderPass,
     VkPipelineLayout layout,
     VkPipeline handle
     )
 {
     _device     = device;
     _renderPass = renderPass;
     _layout     = layout;
     _handle     = handle;
 }
Exemple #6
0
        /// <inheritdoc/>
        protected internal override unsafe void OnDestroyed()
        {
            if (NativePipeline != VkPipeline.Null)
            {
                vkDestroyRenderPass(GraphicsDevice.NativeDevice, NativeRenderPass, null);
                vkDestroyPipeline(GraphicsDevice.NativeDevice, NativePipeline, null);
                vkDestroyPipelineLayout(GraphicsDevice.NativeDevice, NativeLayout, null);

                vkDestroyDescriptorSetLayout(GraphicsDevice.NativeDevice, NativeDescriptorSetLayout, null);

                NativePipeline = VkPipeline.Null;
            }

            base.OnDestroyed();
        }
Exemple #7
0
        public static void SetDebugMarkerName(this VkPipeline obj, Device dev, string name)
        {
            if (!dev.DebugMarkersEnabled)
            {
                return;
            }
            VkDebugMarkerObjectNameInfoEXT dmo = new VkDebugMarkerObjectNameInfoEXT(VkDebugReportObjectTypeEXT.PipelineEXT,
                                                                                    obj.Handle)
            {
                pObjectName = name.Pin()
            };

            Utils.CheckResult(vkDebugMarkerSetObjectNameEXT(dev.VkDev, ref dmo));
            name.Unpin();
        }
Exemple #8
0
        public override VkResult CreateGraphicsPipelines(VkPipelineCache pipelineCache, int createInfoCount, VkGraphicsPipelineCreateInfo[] pCreateInfos, VkPipeline[] pPipelines)
        {
            VkResult result;

            for (int i = 0; i < createInfoCount; i++)
            {
                VkPipeline pipeline = null;
                result = CreateGraphicsPipelines(pCreateInfos[i], out pipeline);
                if (result != VkResult.VK_SUCCESS)
                {
                    return(result);
                }
                pPipelines[i] = pipeline;
            }
            return(VkResult.VK_SUCCESS);
        }
Exemple #9
0
        private VkPipeline CreateGraphicsPipeline(VkDevice device, VkRenderPass renderPass)
        {
            VkPipeline pipeline   = null;
            var        createInfo = new VkGraphicsPipelineCreateInfo()
            {
                inputAssemblyState  = m_inputAssemblyState,
                vertexInputState    = m_vertexInputState,
                pRasterizationState = m_rasterizationState,
                pDepthStencilState  = m_depthStencilState,
                pColorBlendState    = m_colorBlendState,
                pMultisampleState   = m_multisampleState,
                pStages             = m_shaderStages,
                viewportState       = m_viewportState,
                layout     = m_pipelineLayout,
                renderPass = renderPass
            };

            VulkanAPI.vkCreateGraphicsPipelines(device, null, 1, ref createInfo, out pipeline);
            return(pipeline);
        }
Exemple #10
0
        static internal VkPipeline[] CreatePipelinesInternal(Device device, ComputePipelineCreateInfo[] mInfos, VkPipelineCache cache)
        {
            int count            = mInfos.Length;
            var infosMarshalled  = new MarshalledArray <VkComputePipelineCreateInfo>(count);
            var pipelineResults  = new VkPipeline[count];
            var marshalledArrays = new DisposableList <IDisposable>(count);

            for (int i = 0; i < count; i++)
            {
                var mInfo = mInfos[i];
                VkComputePipelineCreateInfo info = new VkComputePipelineCreateInfo();
                info.sType = VkStructureType.ComputePipelineCreateInfo;
                info.flags = mInfo.flags;

                info.stage = mInfo.stage.GetNative(marshalledArrays);

                info.layout = mInfo.layout.Native;
                if (mInfo.basePipelineHandle != null)
                {
                    info.basePipelineHandle = mInfo.basePipelineHandle.Native;
                }
                info.basePipelineIndex = mInfo.basePipelineIndex;

                infosMarshalled[i] = info;
            }

            using (infosMarshalled)
                using (marshalledArrays)
                    using (var pipelinesMarshalled = new PinnedArray <VkPipeline>(pipelineResults)) {
                        var result = device.Commands.createComputePipelines(
                            device.Native, cache,
                            (uint)count, infosMarshalled.Address,
                            device.Instance.AllocationCallbacks, pipelinesMarshalled.Address);

                        if (result != VkResult.Success)
                        {
                            throw new PipelineException(string.Format("Error creating pipeline: {0}", result));
                        }
                        return(pipelineResults);
                    }
        }
        protected override void InitializeFrame()
        {
            _depthStencilBuffer = ToDispose(VulkanImage.DepthStencil(Context, Host.Width, Host.Height));
            var renderPass = CreateRenderPass();

            _renderPass = renderPass;
            ToDispose(new ActionDisposable(() =>
            {
                vkDestroyRenderPass(Context.Device, renderPass, null);
            }));
            var imageViews = CreateImageViews();

            _imageViews = imageViews;
            ToDispose(new ActionDisposable(() =>
            {
                foreach (var imageView in imageViews)
                {
                    vkDestroyImageView(Context.Device, imageView, null);
                }
            }));
            var frameBuffers = CreateFramebuffers();

            _framebuffers = frameBuffers;
            ToDispose(new ActionDisposable(() =>
            {
                foreach (var frameBuffer in frameBuffers)
                {
                    vkDestroyFramebuffer(Context.Device, frameBuffer, null);
                }
            }));
            var pipeline = CreateGraphicsPipeline();

            _pipeline = pipeline;
            ToDispose(new ActionDisposable(() =>
            {
                vkDestroyPipeline(Context.Device, pipeline, null);
            }));
            SetViewProjection();
        }
Exemple #12
0
        /// <summary>
        /// Create a new pipeline with the given description, for use in the given renderer and subpass.
        /// </summary>
        /// <param name="description">The description of the pipeline states to build into the pipeline.</param>
        /// <param name="renderer">The renderer to use the pipeline in.</param>
        /// <param name="subpass">The subpass index within the renderer to use the pipeline in.</param>
        public Pipeline(PipelineDescription description, Renderer renderer, uint subpass)
            : base(ResourceType.Pipeline)
        {
            // Create the pipeline handle
            Handle = CreatePipeline(description, renderer, subpass, out var cache);
            if (renderer.MSAALayout is not null)
            {
                BuildCache = cache;                 // Only save cache if we might rebuild from MSAA change
            }

            // Assign fields
            Layout = description.Shader !.Layout;
            Layout.IncRefCount();
            ShaderProgram = description.Shader.Program;
            ShaderProgram.IncRefCount();
            Renderer = renderer;
            Subpass  = subpass;

            // Assign values
            VertexBindingCount = (uint)cache.VertexBindings.Length;

            // Register to the renderer
            renderer.AddPipeline(this);
        }
Exemple #13
0
 public static extern void CmdBindPipeline(
     VkCommandBuffer commandBuffer,
     VkPipelineBindPoint pipelineBindPoint,
     VkPipeline pipeline
     );
Exemple #14
0
 public static extern void DestroyPipeline(
     VkDevice device,
     VkPipeline pipeline,
     IntPtr pAllocator
     );
Exemple #15
0
 public override VkResult CreateGraphicsPipelines(VkGraphicsPipelineCreateInfo graphicsPipelineCreateInfo, out VkPipeline pipeline)
 {
     pipeline = new DummyGraphicsPipeline(this, graphicsPipelineCreateInfo);
     return(VkResult.VK_SUCCESS);
 }
Exemple #16
0
 public override void DestroyPipeline(VkPipeline pipeline)
 {
     throw new NotImplementedException();
 }
Exemple #17
0
        void CreateGraphicsPipeline()
        {
            VkShaderModule vert = CreateShaderModule(File.ReadAllBytes("vert.spv"));
            VkShaderModule frag = CreateShaderModule(File.ReadAllBytes("frag.spv"));

            InteropString entry = new InteropString("main");

            var vertInfo = new VkPipelineShaderStageCreateInfo();

            vertInfo.sType  = CSGL.Vulkan.VkStructureType.PipelineShaderStageCreateInfo;
            vertInfo.stage  = CSGL.Vulkan.VkShaderStageFlags.VertexBit;
            vertInfo.module = vert;
            vertInfo.pName  = entry.Address;

            var fragInfo = new VkPipelineShaderStageCreateInfo();

            fragInfo.sType  = CSGL.Vulkan.VkStructureType.PipelineShaderStageCreateInfo;
            fragInfo.stage  = CSGL.Vulkan.VkShaderStageFlags.FragmentBit;
            fragInfo.module = frag;
            fragInfo.pName  = entry.Address;

            var shaderStages = new NativeArray <VkPipelineShaderStageCreateInfo>(2);

            shaderStages[0] = vertInfo;
            shaderStages[1] = fragInfo;

            var vertexInputInfo = new VkPipelineVertexInputStateCreateInfo();

            vertexInputInfo.sType = CSGL.Vulkan.VkStructureType.PipelineVertexInputStateCreateInfo;

            var vertexInputNative = new Native <VkPipelineVertexInputStateCreateInfo>(vertexInputInfo);

            var inputAssembly = new VkPipelineInputAssemblyStateCreateInfo();

            inputAssembly.sType    = CSGL.Vulkan.VkStructureType.PipelineInputAssemblyStateCreateInfo;
            inputAssembly.topology = CSGL.Vulkan.VkPrimitiveTopology.TriangleList;

            var inputAssemblyNative = new Native <VkPipelineInputAssemblyStateCreateInfo>(inputAssembly);

            var viewport = new VkViewport();

            viewport.width    = swapchainExtent.width;
            viewport.height   = swapchainExtent.height;
            viewport.minDepth = 0f;
            viewport.maxDepth = 1f;

            var viewportNative = new Native <VkViewport>(viewport);

            var scissor = new VkRect2D();

            scissor.extent = swapchainExtent;

            var scissorNative = new Native <VkRect2D>(scissor);

            var viewportState = new VkPipelineViewportStateCreateInfo();

            viewportState.sType         = CSGL.Vulkan.VkStructureType.PipelineViewportStateCreateInfo;
            viewportState.viewportCount = 1;
            viewportState.pViewports    = viewportNative.Address;
            viewportState.scissorCount  = 1;
            viewportState.pScissors     = scissorNative.Address;

            var viewportStateNative = new Native <VkPipelineViewportStateCreateInfo>(viewportState);

            var rasterizer = new VkPipelineRasterizationStateCreateInfo();

            rasterizer.sType       = CSGL.Vulkan.VkStructureType.PipelineRasterizationStateCreateInfo;
            rasterizer.polygonMode = CSGL.Vulkan.VkPolygonMode.Fill;
            rasterizer.lineWidth   = 1f;
            rasterizer.cullMode    = CSGL.Vulkan.VkCullModeFlags.BackBit;
            rasterizer.frontFace   = CSGL.Vulkan.VkFrontFace.Clockwise;

            var rasterizerNative = new Native <VkPipelineRasterizationStateCreateInfo>(rasterizer);

            var multisampling = new VkPipelineMultisampleStateCreateInfo();

            multisampling.sType = CSGL.Vulkan.VkStructureType.PipelineMultisampleStateCreateInfo;
            multisampling.rasterizationSamples = CSGL.Vulkan.VkSampleCountFlags._1_Bit;
            multisampling.minSampleShading     = 1f;

            var multisamplingNative = new Native <VkPipelineMultisampleStateCreateInfo>(multisampling);

            var colorBlendAttachment = new VkPipelineColorBlendAttachmentState();

            colorBlendAttachment.colorWriteMask = CSGL.Vulkan.VkColorComponentFlags.RBit
                                                  | CSGL.Vulkan.VkColorComponentFlags.GBit
                                                  | CSGL.Vulkan.VkColorComponentFlags.BBit
                                                  | CSGL.Vulkan.VkColorComponentFlags.ABit;
            colorBlendAttachment.srcColorBlendFactor = CSGL.Vulkan.VkBlendFactor.One;
            colorBlendAttachment.dstColorBlendFactor = CSGL.Vulkan.VkBlendFactor.Zero;
            colorBlendAttachment.colorBlendOp        = CSGL.Vulkan.VkBlendOp.Add;
            colorBlendAttachment.srcAlphaBlendFactor = CSGL.Vulkan.VkBlendFactor.One;
            colorBlendAttachment.dstAlphaBlendFactor = CSGL.Vulkan.VkBlendFactor.Zero;
            colorBlendAttachment.alphaBlendOp        = CSGL.Vulkan.VkBlendOp.Add;

            var colorBlendAttachmentNative = new Native <VkPipelineColorBlendAttachmentState>(colorBlendAttachment);

            var colorBlending = new VkPipelineColorBlendStateCreateInfo();

            colorBlending.sType           = CSGL.Vulkan.VkStructureType.PipelineColorBlendStateCreateInfo;
            colorBlending.logicOp         = CSGL.Vulkan.VkLogicOp.Copy;
            colorBlending.attachmentCount = 1;
            colorBlending.pAttachments    = colorBlendAttachmentNative.Address;

            var colorBlendingNative = new Native <VkPipelineColorBlendStateCreateInfo>(colorBlending);

            var pipelineLayoutInfo = new VkPipelineLayoutCreateInfo();

            pipelineLayoutInfo.sType = CSGL.Vulkan.VkStructureType.PipelineLayoutCreateInfo;

            if (pipelineLayout != VkPipelineLayout.Null)
            {
                VK.DestroyPipelineLayout(device, pipelineLayout, alloc);
            }
            var result = VK.CreatePipelineLayout(device, ref pipelineLayoutInfo, alloc, out pipelineLayout);

            var info = new VkGraphicsPipelineCreateInfo();

            info.sType               = CSGL.Vulkan.VkStructureType.GraphicsPipelineCreateInfo;
            info.stageCount          = 2;
            info.pStages             = shaderStages.Address;
            info.pVertexInputState   = vertexInputNative.Address;
            info.pInputAssemblyState = inputAssemblyNative.Address;
            info.pViewportState      = viewportStateNative.Address;
            info.pRasterizationState = rasterizerNative.Address;
            info.pMultisampleState   = multisamplingNative.Address;
            info.pColorBlendState    = colorBlendingNative.Address;
            info.layout              = pipelineLayout;
            info.renderPass          = renderPass;
            info.subpass             = 0;
            info.basePipelineHandle  = VkPipeline.Null;
            info.basePipelineIndex   = -1;

            var infoNative = new Native <VkGraphicsPipelineCreateInfo>(info);
            var temp       = new Native <VkPipeline>();

            if (pipeline != VkPipeline.Null)
            {
                VK.DestroyPipeline(device, pipeline, alloc);
            }

            result   = VK.CreateGraphicsPipelines(device, VkPipelineCache.Null, 1, infoNative.Address, alloc, temp.Address);
            pipeline = temp.Value;

            infoNative.Dispose();
            temp.Dispose();

            entry.Dispose();
            shaderStages.Dispose();
            vertexInputNative.Dispose();
            inputAssemblyNative.Dispose();
            viewportNative.Dispose();
            scissorNative.Dispose();
            viewportStateNative.Dispose();
            rasterizerNative.Dispose();
            multisamplingNative.Dispose();
            colorBlendingNative.Dispose();
            colorBlendAttachmentNative.Dispose();
            VK.DestroyShaderModule(device, vert, alloc);
            VK.DestroyShaderModule(device, frag, alloc);
        }
Exemple #18
0
        public static VkResult vkCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, VkComputePipelineCreateInfo createInfo, out VkPipeline pipeline)
        {
            VkPipeline pinPipeline;
            var        result = vkCreateComputePipelines(device, pipelineCache, 1, &createInfo, null, &pinPipeline);

            pipeline = pinPipeline;
            return(result);
        }
Exemple #19
0
        //[HandleProcessCorruptedStateExceptionsAttribute, SecurityCriticalAttribute]
        private unsafe void Recreate()
        {
            errorDuringCreate = false;

            if (Description.RootSignature == null)
            {
                return;
            }

            VkPipelineShaderStageCreateInfo[] stages;

            // create render pass
            bool hasDepthStencilAttachment = Description.Output.DepthStencilFormat != PixelFormat.None;

            var renderTargetCount = Description.Output.RenderTargetCount;

            var attachmentCount = renderTargetCount;

            if (hasDepthStencilAttachment)
            {
                attachmentCount++;
            }

            var attachments = new VkAttachmentDescription[attachmentCount];
            var colorAttachmentReferences = new VkAttachmentReference[renderTargetCount];

            fixed(PixelFormat *renderTargetFormat = &Description.Output.RenderTargetFormat0)
            fixed(BlendStateRenderTargetDescription * blendDescription = &Description.BlendState.RenderTarget0)
            {
                for (int i = 0; i < renderTargetCount; i++)
                {
                    var currentBlendDesc = Description.BlendState.IndependentBlendEnable ? (blendDescription + i) : blendDescription;

                    attachments[i] = new VkAttachmentDescription
                    {
                        format         = VulkanConvertExtensions.ConvertPixelFormat(*(renderTargetFormat + i)),
                        samples        = VkSampleCountFlags.Count1,
                        loadOp         = currentBlendDesc->BlendEnable ? VkAttachmentLoadOp.Load : VkAttachmentLoadOp.DontCare, // TODO VULKAN: Only if any destination blend?
                        storeOp        = VkAttachmentStoreOp.Store,
                        stencilLoadOp  = VkAttachmentLoadOp.DontCare,
                        stencilStoreOp = VkAttachmentStoreOp.DontCare,
                        initialLayout  = VkImageLayout.ColorAttachmentOptimal,
                        finalLayout    = VkImageLayout.ColorAttachmentOptimal,
                    };

                    colorAttachmentReferences[i] = new VkAttachmentReference
                    {
                        attachment = (uint)i,
                        layout     = VkImageLayout.ColorAttachmentOptimal,
                    };
                }
            }

            if (hasDepthStencilAttachment)
            {
                attachments[attachmentCount - 1] = new VkAttachmentDescription
                {
                    format         = Texture.GetFallbackDepthStencilFormat(GraphicsDevice, VulkanConvertExtensions.ConvertPixelFormat(Description.Output.DepthStencilFormat)),
                    samples        = VkSampleCountFlags.Count1,
                    loadOp         = VkAttachmentLoadOp.Load,     // TODO VULKAN: Only if depth read enabled?
                    storeOp        = VkAttachmentStoreOp.Store,   // TODO VULKAN: Only if depth write enabled?
                    stencilLoadOp  = VkAttachmentLoadOp.DontCare, // TODO VULKAN: Handle stencil
                    stencilStoreOp = VkAttachmentStoreOp.DontCare,
                    initialLayout  = VkImageLayout.DepthStencilAttachmentOptimal,
                    finalLayout    = VkImageLayout.DepthStencilAttachmentOptimal,
                };
            }

            var depthAttachmentReference = new VkAttachmentReference
            {
                attachment = (uint)attachments.Length - 1,
                layout     = VkImageLayout.DepthStencilAttachmentOptimal,
            };

            var subpass = new VkSubpassDescription
            {
                pipelineBindPoint       = VkPipelineBindPoint.Graphics,
                colorAttachmentCount    = (uint)renderTargetCount,
                pColorAttachments       = colorAttachmentReferences.Length > 0 ? (VkAttachmentReference *)Core.Interop.Fixed(colorAttachmentReferences) : null,
                pDepthStencilAttachment = hasDepthStencilAttachment ? &depthAttachmentReference : null,
            };

            var renderPassCreateInfo = new VkRenderPassCreateInfo
            {
                sType           = VkStructureType.RenderPassCreateInfo,
                attachmentCount = (uint)attachmentCount,
                pAttachments    = attachments.Length > 0 ? (VkAttachmentDescription *)Core.Interop.Fixed(attachments) : null,
                subpassCount    = 1,
                pSubpasses      = &subpass,
            };

            // create pipeline layout
            // Remap descriptor set indices to those in the shader. This ordering generated by the ShaderCompiler
            var resourceGroups = Description.EffectBytecode.Reflection.ResourceBindings.Select(x => x.ResourceGroup ?? "Globals").Distinct().ToList();

            ResourceGroupCount = resourceGroups.Count;

            var layouts = Description.RootSignature.EffectDescriptorSetReflection.Layouts;

            // Get binding indices used by the shader
            var destinationBindings = Description.EffectBytecode.Stages
                                      .SelectMany(x => BinarySerialization.Read <ShaderInputBytecode>(x.Data).ResourceBindings)
                                      .GroupBy(x => x.Key, x => x.Value)
                                      .ToDictionary(x => x.Key, x => x.First());

            var maxBindingIndex    = destinationBindings.Max(x => x.Value);
            var destinationEntries = new DescriptorSetLayoutBuilder.Entry[maxBindingIndex + 1];

            DescriptorBindingMapping = new List <DescriptorSetInfo>();

            for (int i = 0; i < resourceGroups.Count; i++)
            {
                var resourceGroupName = resourceGroups[i] == "Globals" ? Description.RootSignature.EffectDescriptorSetReflection.DefaultSetSlot : resourceGroups[i];
                var layoutIndex       = resourceGroups[i] == null ? 0 : layouts.FindIndex(x => x.Name == resourceGroupName);

                // Check if the resource group is used by the shader
                if (layoutIndex == -1)
                {
                    continue;
                }

                var sourceEntries = layouts[layoutIndex].Layout.Entries;

                for (int sourceBinding = 0; sourceBinding < sourceEntries.Count; sourceBinding++)
                {
                    var sourceEntry = sourceEntries[sourceBinding];

                    int destinationBinding;
                    if (destinationBindings.TryGetValue(sourceEntry.Key.Name, out destinationBinding))
                    {
                        destinationEntries[destinationBinding] = sourceEntry;

                        // No need to umpdate immutable samplers
                        if (sourceEntry.Class == EffectParameterClass.Sampler && sourceEntry.ImmutableSampler != null)
                        {
                            continue;
                        }

                        DescriptorBindingMapping.Add(new DescriptorSetInfo
                        {
                            SourceSet          = layoutIndex,
                            SourceBinding      = sourceBinding,
                            DestinationBinding = destinationBinding,
                            DescriptorType     = VulkanConvertExtensions.ConvertDescriptorType(sourceEntry.Class, sourceEntry.Type)
                        });
                    }
                }
            }

            // Create default sampler, used by texture and buffer loads
            destinationEntries[0] = new DescriptorSetLayoutBuilder.Entry
            {
                Class            = EffectParameterClass.Sampler,
                Type             = EffectParameterType.Sampler,
                ImmutableSampler = GraphicsDevice.SamplerStates.PointWrap,
                ArraySize        = 1,
            };

            // Create descriptor set layout
            NativeDescriptorSetLayout = DescriptorSetLayout.CreateNativeDescriptorSetLayout(GraphicsDevice, destinationEntries, out DescriptorTypeCounts);

            // Create pipeline layout
            var nativeDescriptorSetLayout = NativeDescriptorSetLayout;
            var pipelineLayoutCreateInfo  = new VkPipelineLayoutCreateInfo
            {
                sType          = VkStructureType.PipelineLayoutCreateInfo,
                setLayoutCount = 1,
                pSetLayouts    = &nativeDescriptorSetLayout,
            };

            // Create shader stages
            Dictionary <int, string> inputAttributeNames;

            // Note: important to pin this so that stages[x].Name is valid during this whole function
            void *defaultEntryPointData = Core.Interop.Fixed(defaultEntryPoint);

            stages = CreateShaderStages(Description, out inputAttributeNames);

            var inputAttributes     = new VkVertexInputAttributeDescription[Description.InputElements.Length];
            int inputAttributeCount = 0;
            var inputBindings       = new VkVertexInputBindingDescription[inputAttributes.Length];
            int inputBindingCount   = 0;

            for (int inputElementIndex = 0; inputElementIndex < inputAttributes.Length; inputElementIndex++)
            {
                var inputElement = Description.InputElements[inputElementIndex];
                var slotIndex    = inputElement.InputSlot;

                if (inputElement.InstanceDataStepRate > 1)
                {
                    throw new NotImplementedException();
                }

                VkFormat format;
                int      size;
                bool     isCompressed;
                VulkanConvertExtensions.ConvertPixelFormat(inputElement.Format, out format, out size, out isCompressed);

                var location = inputAttributeNames.FirstOrDefault(x => x.Value == inputElement.SemanticName && inputElement.SemanticIndex == 0 || x.Value == inputElement.SemanticName + inputElement.SemanticIndex);
                if (location.Value != null)
                {
                    inputAttributes[inputAttributeCount++] = new VkVertexInputAttributeDescription
                    {
                        format   = format,
                        offset   = (uint)inputElement.AlignedByteOffset,
                        binding  = (uint)inputElement.InputSlot,
                        location = (uint)location.Key
                    };
                }

                inputBindings[slotIndex].binding   = (uint)slotIndex;
                inputBindings[slotIndex].inputRate = inputElement.InputSlotClass == InputClassification.Vertex ? VkVertexInputRate.Vertex : VkVertexInputRate.Instance;

                // TODO VULKAN: This is currently an argument to Draw() overloads.
                if (inputBindings[slotIndex].stride < inputElement.AlignedByteOffset + size)
                {
                    inputBindings[slotIndex].stride = (uint)(inputElement.AlignedByteOffset + size);
                }

                if (inputElement.InputSlot >= inputBindingCount)
                {
                    inputBindingCount = inputElement.InputSlot + 1;
                }
            }

            var inputAssemblyState = new VkPipelineInputAssemblyStateCreateInfo
            {
                sType    = VkStructureType.PipelineInputAssemblyStateCreateInfo,
                topology = VulkanConvertExtensions.ConvertPrimitiveType(Description.PrimitiveType),
                primitiveRestartEnable = VulkanConvertExtensions.ConvertPrimitiveRestart(Description.PrimitiveType) ? (uint)1 : (uint)0,
            };

            // TODO VULKAN: Tessellation and multisampling
            var multisampleState = new VkPipelineMultisampleStateCreateInfo
            {
                sType = VkStructureType.PipelineMultisampleStateCreateInfo,
                rasterizationSamples = VkSampleCountFlags.Count1,
            };

            var rasterizationState = new VkPipelineRasterizationStateCreateInfo
            {
                sType                   = VkStructureType.PipelineRasterizationStateCreateInfo,
                cullMode                = VulkanConvertExtensions.ConvertCullMode(Description.RasterizerState.CullMode),
                frontFace               = Description.RasterizerState.FrontFaceCounterClockwise ? VkFrontFace.CounterClockwise : VkFrontFace.Clockwise,
                polygonMode             = VulkanConvertExtensions.ConvertFillMode(Description.RasterizerState.FillMode),
                depthBiasEnable         = 1, // TODO VULKAN
                depthBiasConstantFactor = Description.RasterizerState.DepthBias,
                depthBiasSlopeFactor    = Description.RasterizerState.SlopeScaleDepthBias,
                depthBiasClamp          = Description.RasterizerState.DepthBiasClamp,
                lineWidth               = 1.0f,
                depthClampEnable        = Description.RasterizerState.DepthClipEnable ? (uint)0 : (uint)1,
                rasterizerDiscardEnable = 0,
            };

            var depthStencilState = new VkPipelineDepthStencilStateCreateInfo
            {
                sType             = VkStructureType.PipelineDepthStencilStateCreateInfo,
                depthTestEnable   = Description.DepthStencilState.DepthBufferEnable ? (uint)1 : (uint)0,
                stencilTestEnable = Description.DepthStencilState.StencilEnable ? (uint)1 : (uint)0,
                depthWriteEnable  = Description.DepthStencilState.DepthBufferWriteEnable ? (uint)1 : (uint)0,

                minDepthBounds = 0.0f,
                maxDepthBounds = 1.0f,
                depthCompareOp = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.DepthBufferFunction),
                front          =
                {
                    compareOp   = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.FrontFace.StencilFunction),
                    depthFailOp = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilDepthBufferFail),
                    failOp      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilFail),
                    passOp      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilPass),
                    compareMask = Description.DepthStencilState.StencilMask,
                    writeMask   = Description.DepthStencilState.StencilWriteMask
                },
                back =
                {
                    compareOp   = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.BackFace.StencilFunction),
                    depthFailOp = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilDepthBufferFail),
                    failOp      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilFail),
                    passOp      = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilPass),
                    compareMask = Description.DepthStencilState.StencilMask,
                    writeMask   = Description.DepthStencilState.StencilWriteMask
                }
            };

            var description = Description.BlendState;

            var colorBlendAttachments = new VkPipelineColorBlendAttachmentState[renderTargetCount];

            var renderTargetBlendState = &description.RenderTarget0;

            for (int i = 0; i < renderTargetCount; i++)
            {
                colorBlendAttachments[i] = new VkPipelineColorBlendAttachmentState
                {
                    blendEnable         = renderTargetBlendState->BlendEnable ? (uint)1 : (uint)0,
                    alphaBlendOp        = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->AlphaBlendFunction),
                    colorBlendOp        = VulkanConvertExtensions.ConvertBlendFunction(renderTargetBlendState->ColorBlendFunction),
                    dstAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaDestinationBlend),
                    dstColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorDestinationBlend),
                    srcAlphaBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->AlphaSourceBlend),
                    srcColorBlendFactor = VulkanConvertExtensions.ConvertBlend(renderTargetBlendState->ColorSourceBlend),
                    colorWriteMask      = VulkanConvertExtensions.ConvertColorWriteChannels(renderTargetBlendState->ColorWriteChannels),
                };

                if (description.IndependentBlendEnable)
                {
                    renderTargetBlendState++;
                }
            }

            var viewportState = new VkPipelineViewportStateCreateInfo
            {
                sType         = VkStructureType.PipelineViewportStateCreateInfo,
                scissorCount  = 1,
                viewportCount = 1,
            };

            fixed(void *dynamicStatesPointer   = dynamicStates.Length == 0?null : dynamicStates,
                  inputAttributesPointer       = inputAttributes.Length == 0?null : inputAttributes,
                  inputBindingsPointer         = inputBindings.Length == 0?null : inputBindings,
                  colorBlendAttachmentsPointer = colorBlendAttachments.Length == 0?null : colorBlendAttachments,
                  stagesPointer = stages.Length == 0?null : stages)
            {
                var vertexInputState = new VkPipelineVertexInputStateCreateInfo
                {
                    sType = VkStructureType.PipelineVertexInputStateCreateInfo,
                    vertexAttributeDescriptionCount = (uint)inputAttributeCount,
                    pVertexAttributeDescriptions    = (Vortice.Vulkan.VkVertexInputAttributeDescription *)inputAttributesPointer,
                    vertexBindingDescriptionCount   = (uint)inputBindingCount,
                    pVertexBindingDescriptions      = (Vortice.Vulkan.VkVertexInputBindingDescription *)inputBindingsPointer,
                };

                var colorBlendState = new VkPipelineColorBlendStateCreateInfo
                {
                    sType           = VkStructureType.PipelineColorBlendStateCreateInfo,
                    attachmentCount = (uint)renderTargetCount,
                    pAttachments    = (Vortice.Vulkan.VkPipelineColorBlendAttachmentState *)colorBlendAttachmentsPointer,
                };

                var dynamicState = new VkPipelineDynamicStateCreateInfo
                {
                    sType             = VkStructureType.PipelineDynamicStateCreateInfo,
                    dynamicStateCount = (uint)dynamicStates.Length,
                    pDynamicStates    = (Vortice.Vulkan.VkDynamicState *)dynamicStatesPointer,
                };

                var createInfo = new VkGraphicsPipelineCreateInfo
                {
                    sType               = VkStructureType.GraphicsPipelineCreateInfo,
                    layout              = NativeLayout,
                    stageCount          = (uint)stages.Length,
                    pVertexInputState   = &vertexInputState,
                    pInputAssemblyState = &inputAssemblyState,
                    pRasterizationState = &rasterizationState,
                    pMultisampleState   = &multisampleState,
                    pDepthStencilState  = &depthStencilState,
                    pColorBlendState    = &colorBlendState,
                    pDynamicState       = &dynamicState,
                    pStages             = (Vortice.Vulkan.VkPipelineShaderStageCreateInfo *)stagesPointer,
                    pViewportState      = &viewportState,
                    renderPass          = NativeRenderPass,
                    subpass             = 0,
                };

                using (GraphicsDevice.QueueLock.ReadLock())
                {
                    vkCreateRenderPass(GraphicsDevice.NativeDevice, &renderPassCreateInfo, null, out NativeRenderPass);
                    vkCreatePipelineLayout(GraphicsDevice.NativeDevice, &pipelineLayoutCreateInfo, null, out NativeLayout);

                    createInfo.layout     = NativeLayout;
                    createInfo.renderPass = NativeRenderPass;

                    try {
                        fixed(VkPipeline *nativePipelinePtr = &NativePipeline)
                        vkCreateGraphicsPipelines(GraphicsDevice.NativeDevice, VkPipelineCache.Null, 1, &createInfo, null, nativePipelinePtr);
                    } catch (Exception e) {
                        errorDuringCreate = true;
                        NativePipeline    = VkPipeline.Null;
                    }
                }
            }

            // Cleanup shader modules
            for (int i = 0; i < stages.Length; i++)
            {
                vkDestroyShaderModule(GraphicsDevice.NativeDevice, stages[i].module, null);
            }
        }
Exemple #20
0
        public void Init(IntPtr hwnd, IntPtr processHandle)
        {
            if (this.isInitialized)
            {
                return;
            }

            this.instance = InitInstance();
            InitDebugCallback(this.instance);
            this.surface          = InitSurface(this.instance, hwnd, processHandle);
            this.vkPhysicalDevice = InitPhysicalDevice(this.instance);
            VkSurfaceFormatKHR surfaceFormat = SelectFormat(this.vkPhysicalDevice, this.surface);

            this.device = CreateDevice(this.vkPhysicalDevice, this.surface);

            this.vkQueue = this.device.GetQueue(0, 0);

            VkSurfaceCapabilitiesKHR surfaceCapabilities;

            //this.vkPhysicalDevice.GetSurfaceCapabilitiesKhr(this.vkSurface, out surfaceCapabilities);
            vkAPI.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(this.vkPhysicalDevice, this.surface, &surfaceCapabilities).Check();

            this.swapchain = CreateSwapchain(this.device, this.surface, surfaceFormat, surfaceCapabilities);

            this.vkImages = this.device.GetSwapchainImages(this.swapchain);

            this.renderPass = CreateRenderPass(this.device, surfaceFormat);

            this.framebuffers = CreateFramebuffers(this.device, this.vkImages, surfaceFormat, this.renderPass, surfaceCapabilities);

            this.vkFence     = this.device.CreateFence();
            this.vkSemaphore = this.device.CreateSemaphore();

            // buffers for vertex data.
            VkBuffer vertexBuffer = CreateBuffer(this.vkPhysicalDevice, this.device, Vertices, VkBufferUsageFlagBits.VertexBuffer, typeof(float));

            VkBuffer indexBuffer = CreateBuffer(this.vkPhysicalDevice, this.device, Indexes, VkBufferUsageFlagBits.IndexBuffer, typeof(short));

            var uniformBufferData = new AreaUniformBuffer(1, 1);

            this.originalWidth  = 1; this.width = this.originalWidth;
            this.originalHeight = 1; this.height = this.originalHeight;

            this.uniformBuffer = CreateBuffer(this.vkPhysicalDevice, this.device, uniformBufferData, VkBufferUsageFlagBits.UniformBuffer, typeof(AreaUniformBuffer));

            this.descriptorSetLayout = CreateDescriptorSetLayout(this.device);

            this.vkPipelineLayout = CreatePipelineLayout(this.device, this.descriptorSetLayout);

            VkPipeline pipeline = CreatePipeline(this.device, surfaceCapabilities, this.renderPass, this.vkPipelineLayout);

            this.descriptorSet = CreateDescriptorSet(this.device, this.descriptorSetLayout);

            UpdateDescriptorSets(this.device, this.uniformBuffer, this.descriptorSet);

            this.commandBuffers = CreateCommandBuffers(
                this.device, this.renderPass, surfaceCapabilities,
                this.vkImages, this.framebuffers, pipeline,
                vertexBuffer, indexBuffer, (uint)Indexes.Length,
                this.vkPipelineLayout, this.descriptorSet);

            this.isInitialized = true;
        }
Exemple #21
0
        void CreateGraphicsPipeline()
        {
            var vert = CreateShaderModule(File.ReadAllBytes("vert.spv"));
            var frag = CreateShaderModule(File.ReadAllBytes("frag.spv"));

            var vertInfo = new VkPipelineShaderStageCreateInfo();

            vertInfo.stage  = VkShaderStageFlags.VertexBit;
            vertInfo.module = vert;
            vertInfo.name   = "main";

            var fragInfo = new VkPipelineShaderStageCreateInfo();

            fragInfo.stage  = VkShaderStageFlags.FragmentBit;
            fragInfo.module = frag;
            fragInfo.name   = "main";

            var shaderStages = new List <VkPipelineShaderStageCreateInfo> {
                vertInfo, fragInfo
            };

            var vertexInputInfo = new VkPipelineVertexInputStateCreateInfo();

            var inputAssembly = new VkPipelineInputAssemblyStateCreateInfo();

            inputAssembly.topology = VkPrimitiveTopology.TriangleList;

            var viewport = new VkViewport();

            viewport.width    = swapchainExtent.width;
            viewport.height   = swapchainExtent.height;
            viewport.minDepth = 0f;
            viewport.maxDepth = 1f;

            var scissor = new VkRect2D();

            scissor.extent = swapchainExtent;

            var viewportState = new VkPipelineViewportStateCreateInfo();

            viewportState.viewports = new List <VkViewport> {
                viewport
            };
            viewportState.scissors = new List <VkRect2D> {
                scissor
            };

            var rasterizer = new VkPipelineRasterizationStateCreateInfo();

            rasterizer.polygonMode = VkPolygonMode.Fill;
            rasterizer.lineWidth   = 1f;
            rasterizer.cullMode    = VkCullModeFlags.BackBit;
            rasterizer.frontFace   = VkFrontFace.Clockwise;

            var multisampling = new VkPipelineMultisampleStateCreateInfo();

            multisampling.rasterizationSamples = VkSampleCountFlags._1_Bit;
            multisampling.minSampleShading     = 1f;

            var colorBlendAttachment = new VkPipelineColorBlendAttachmentState();

            colorBlendAttachment.colorWriteMask = VkColorComponentFlags.RBit
                                                  | VkColorComponentFlags.GBit
                                                  | VkColorComponentFlags.BBit
                                                  | VkColorComponentFlags.ABit;
            colorBlendAttachment.srcColorBlendFactor = VkBlendFactor.One;
            colorBlendAttachment.dstColorBlendFactor = VkBlendFactor.Zero;
            colorBlendAttachment.colorBlendOp        = VkBlendOp.Add;
            colorBlendAttachment.srcAlphaBlendFactor = VkBlendFactor.One;
            colorBlendAttachment.dstAlphaBlendFactor = VkBlendFactor.Zero;
            colorBlendAttachment.alphaBlendOp        = VkBlendOp.Add;

            var colorBlending = new VkPipelineColorBlendStateCreateInfo();

            colorBlending.logicOp     = VkLogicOp.Copy;
            colorBlending.attachments = new List <VkPipelineColorBlendAttachmentState> {
                colorBlendAttachment
            };

            var pipelineLayoutInfo = new VkPipelineLayoutCreateInfo();

            pipelineLayout?.Dispose();

            pipelineLayout = new VkPipelineLayout(device, pipelineLayoutInfo);

            var info = new VkGraphicsPipelineCreateInfo();

            info.stages             = shaderStages;
            info.vertexInputState   = vertexInputInfo;
            info.inputAssemblyState = inputAssembly;
            info.viewportState      = viewportState;
            info.rasterizationState = rasterizer;
            info.multisampleState   = multisampling;
            info.colorBlendState    = colorBlending;
            info.layout             = pipelineLayout;
            info.renderPass         = renderPass;
            info.subpass            = 0;
            info.basePipelineHandle = null;
            info.basePipelineIndex  = -1;

            pipeline?.Dispose();

            pipeline = new VkGraphicsPipeline(device, info, null);

            vert.Dispose();
            frag.Dispose();
        }
Exemple #22
0
        public static void vkDestroyPipeline(VkDevice device, VkPipeline pipeline, VkAllocationCallbacks pAllocator)
        {
            VkPreconditions.CheckNull(device, nameof(device));

            GetDevice(device).DestroyPipeline(pipeline);
        }
 internal GraphicsPipeline(Device device, VkPipeline pipeline)
 {
     Device        = device;
     this.pipeline = pipeline;
 }
        static internal VkPipeline[] CreatePipelinesInternal(Device device, GraphicsPipelineCreateInfo[] mInfos, VkPipelineCache cache)
        {
            int count            = mInfos.Length;
            var infosMarshalled  = new MarshalledArray <VkGraphicsPipelineCreateInfo>(count);
            var pipelineResults  = new VkPipeline[count];
            var marshalledArrays = new DisposableList <IDisposable>(count);

            for (int i = 0; i < count; i++)
            {
                VkGraphicsPipelineCreateInfo info = new VkGraphicsPipelineCreateInfo();
                var mInfo = mInfos[i];

                info.sType = VkStructureType.GraphicsPipelineCreateInfo;
                info.flags = mInfo.flags;

                int stagesCount      = mInfo.stages.Count;
                var stagesMarshalled = new MarshalledArray <VkPipelineShaderStageCreateInfo>(stagesCount);
                for (int j = 0; j < stagesCount; j++)
                {
                    stagesMarshalled[j] = mInfo.stages[j].GetNative(marshalledArrays);
                }

                info.stageCount = (uint)stagesCount;
                info.pStages    = stagesMarshalled.Address;

                marshalledArrays.Add(stagesMarshalled);

                if (mInfo.vertexInputState != null)
                {
                    var m = new Marshalled <VkPipelineVertexInputStateCreateInfo>(mInfo.vertexInputState.GetNative(marshalledArrays));
                    info.pVertexInputState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.inputAssemblyState != null)
                {
                    var m = new Marshalled <VkPipelineInputAssemblyStateCreateInfo>(mInfo.inputAssemblyState.GetNative());
                    info.pInputAssemblyState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.tessellationState != null)
                {
                    var m = new Marshalled <VkPipelineTessellationStateCreateInfo>(mInfo.tessellationState.GetNative());
                    info.pTessellationState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.viewportState != null)
                {
                    var m = new Marshalled <VkPipelineViewportStateCreateInfo>(mInfo.viewportState.GetNative(marshalledArrays));
                    info.pViewportState = m.Address;
                }

                if (mInfo.rasterizationState != null)
                {
                    var m = new Marshalled <VkPipelineRasterizationStateCreateInfo>(mInfo.rasterizationState.GetNative());
                    info.pRasterizationState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.multisampleState != null)
                {
                    var m = new Marshalled <VkPipelineMultisampleStateCreateInfo>(mInfo.multisampleState.GetNative());
                    info.pMultisampleState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.depthStencilState != null)
                {
                    var m = new Marshalled <VkPipelineDepthStencilStateCreateInfo>(mInfo.depthStencilState.GetNative());
                    info.pDepthStencilState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.colorBlendState != null)
                {
                    var m = new Marshalled <VkPipelineColorBlendStateCreateInfo>(mInfo.colorBlendState.GetNative(marshalledArrays));
                    info.pColorBlendState = m.Address;
                    marshalledArrays.Add(m);
                }

                if (mInfo.dynamicState != null)
                {
                    var m = new Marshalled <VkPipelineDynamicStateCreateInfo>(mInfo.dynamicState.GetNative(marshalledArrays));
                    info.pDynamicState = m.Address;
                    marshalledArrays.Add(m);
                }

                info.layout = mInfo.layout.Native;

                if (mInfo.renderPass != null)
                {
                    info.renderPass = mInfo.renderPass.Native;
                }

                info.subpass = mInfo.subpass;
                if (mInfo.basePipelineHandle != null)
                {
                    info.basePipelineHandle = mInfo.basePipelineHandle.Native;
                }
                info.basePipelineIndex = mInfo.basePipelineIndex;

                infosMarshalled[i] = info;
            }

            using (infosMarshalled)
                using (marshalledArrays)
                    using (var pipelinesMarshalled = new PinnedArray <VkPipeline>(pipelineResults)) {
                        var result = device.Commands.createGraphicsPiplines(
                            device.Native, cache,
                            (uint)count, infosMarshalled.Address,
                            device.Instance.AllocationCallbacks, pipelinesMarshalled.Address);

                        if (result != VkResult.Success)
                        {
                            throw new PipelineException(string.Format("Error creating pipeline: {0}", result));
                        }
                        return(pipelineResults);
                    }
        }
Exemple #25
0
        public static void vkCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline)
        {
            VkPreconditions.CheckNull(commandBuffer, nameof(commandBuffer));
            VkPreconditions.CheckNull(pipeline, nameof(pipeline));

            GetCommandBuffer(commandBuffer).CmdBindPipeline(pipelineBindPoint, pipeline);
        }
Exemple #26
0
 public static VkResult vkCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint createInfoCount, VkComputePipelineCreateInfo *createInfos, VkAllocationCallbacks *allocator, out VkPipeline pipelines)
 {
     throw new NotImplementedException();
 }
Exemple #27
0
        private void CreateGraphicsPipeline()
        {
            // Shader stages
            var vertShaderCode = System.IO.File.ReadAllBytes("Shaders/vert.spv");
            var fragShaderCode = System.IO.File.ReadAllBytes("Shaders/frag.spv");

            var vertShaderModule = CreateShaderModule(vertShaderCode);
            var fragShaderModule = CreateShaderModule(fragShaderCode);

            string name      = "main";
            int    byteCount = System.Text.Encoding.UTF8.GetByteCount(name);
            byte * utf8Ptr   = stackalloc byte[byteCount];

            fixed(char *namePtr = name)
            {
                System.Text.Encoding.UTF8.GetBytes(namePtr, name.Length, utf8Ptr, byteCount);
            }

            var vertShaderStageInfo = new VkPipelineShaderStageCreateInfo()
            {
                sType  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                stage  = VkShaderStageFlagBits.VK_SHADER_STAGE_VERTEX_BIT,
                module = vertShaderModule,
                pName  = utf8Ptr,
            };

            var fragShaderStageInfo = new VkPipelineShaderStageCreateInfo()
            {
                sType  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                stage  = VkShaderStageFlagBits.VK_SHADER_STAGE_FRAGMENT_BIT,
                module = fragShaderModule,
                pName  = utf8Ptr,
            };

            var shaderStages = stackalloc VkPipelineShaderStageCreateInfo[] { vertShaderStageInfo, fragShaderStageInfo };

            // VertexInput
            var vertexInputInfo = new VkPipelineVertexInputStateCreateInfo()
            {
                sType = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
                vertexBindingDescriptionCount   = 0,
                pVertexBindingDescriptions      = null,
                vertexAttributeDescriptionCount = 0,
                pVertexAttributeDescriptions    = null,
            };

            var inputAssembly = new VkPipelineInputAssemblyStateCreateInfo()
            {
                sType    = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
                topology = VkPrimitiveTopology.VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
                primitiveRestartEnable = false,
            };

            var viewport = new VkViewport()
            {
                x        = 0f,
                y        = 0f,
                width    = (float)vkSwapChainExtent.width,
                height   = (float)vkSwapChainExtent.height,
                minDepth = 0f,
                maxDepth = 1f,
            };

            var scissor = new VkRect2D()
            {
                offset = new VkOffset2D()
                {
                    x = 0, y = 0
                },
                extent = vkSwapChainExtent,
            };

            var viewportState = new VkPipelineViewportStateCreateInfo()
            {
                sType         = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
                viewportCount = 1,
                pViewports    = &viewport,
                scissorCount  = 1,
                pScissors     = &scissor,
            };

            var rasterizer = new VkPipelineRasterizationStateCreateInfo()
            {
                sType                   = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
                depthClampEnable        = false,
                rasterizerDiscardEnable = false,
                polygonMode             = VkPolygonMode.VK_POLYGON_MODE_FILL,
                lineWidth               = 1f,
                cullMode                = VkCullModeFlagBits.VK_CULL_MODE_BACK_BIT,
                frontFace               = VkFrontFace.VK_FRONT_FACE_CLOCKWISE,
                depthBiasEnable         = false,
                depthBiasConstantFactor = 0f,
                depthBiasClamp          = 0f,
                depthBiasSlopeFactor    = 0f,
            };

            var multisampling = new VkPipelineMultisampleStateCreateInfo()
            {
                sType = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
                sampleShadingEnable   = false,
                rasterizationSamples  = VkSampleCountFlagBits.VK_SAMPLE_COUNT_1_BIT,
                minSampleShading      = 1f,
                pSampleMask           = null,
                alphaToCoverageEnable = false,
                alphaToOneEnable      = false,
            };

            var colorBlendAttachment = new VkPipelineColorBlendAttachmentState()
            {
                colorWriteMask = VkColorComponentFlagBits.VK_COLOR_COMPONENT_R_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_G_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_B_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_A_BIT,
                blendEnable    = false,
            };


            var colorBlending = new VkPipelineColorBlendStateCreateInfo()
            {
                sType            = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
                logicOpEnable    = false,
                logicOp          = VkLogicOp.VK_LOGIC_OP_COPY,
                pAttachments     = &colorBlendAttachment,
                attachmentCount  = 1,
                blendConstants_0 = 0f,
                blendConstants_1 = 0f,
                blendConstants_2 = 0f,
                blendConstants_3 = 0f,
            };

            var pipelineLayoutInfo = new VkPipelineLayoutCreateInfo()
            {
                sType                  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
                setLayoutCount         = 0,
                pushConstantRangeCount = 0,
            };

            VkPipelineLayout newPipelineLayout;
            var result = VulkanNative.vkCreatePipelineLayout(vkDevice, &pipelineLayoutInfo, null, &newPipelineLayout);

            vkPipelineLayout = newPipelineLayout;
            Helpers.CheckErrors(result);

            var pipelineInfo = new VkGraphicsPipelineCreateInfo()
            {
                sType               = VkStructureType.VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
                stageCount          = 2,
                pStages             = shaderStages,
                pVertexInputState   = &vertexInputInfo,
                pInputAssemblyState = &inputAssembly,
                pViewportState      = &viewportState,
                pRasterizationState = &rasterizer,
                pMultisampleState   = &multisampling,
                pDepthStencilState  = null,
                pColorBlendState    = &colorBlending,
                pDynamicState       = null,
                layout              = vkPipelineLayout,
                renderPass          = vkRenderPass,
                subpass             = 0,
                basePipelineHandle  = 0,
                basePipelineIndex   = -1,
            };

            VkPipeline newPipeline;

            result             = VulkanNative.vkCreateGraphicsPipelines(vkDevice, 0, 1, &pipelineInfo, null, &newPipeline);
            vkGraphicsPipeline = newPipeline;
            Helpers.CheckErrors(result);

            VulkanNative.vkDestroyShaderModule(vkDevice, vertShaderModule, null);
            VulkanNative.vkDestroyShaderModule(vkDevice, fragShaderModule, null);
        }
Exemple #28
0
 public static VkResult vkCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, VkComputePipelineCreateInfo createInfo, out VkPipeline pipeline)
 {
     return(vkCreateComputePipelines(device, pipelineCache, 1, &createInfo, null, out pipeline));
 }
Exemple #29
0
        VkCommandBuffer[] CreateCommandBuffers(
            VkDevice device, VkRenderPass renderPass, VkSurfaceCapabilitiesKHR surfaceCapabilities,
            VkImage[] images, VkFramebuffer[] framebuffers, VkPipeline pipeline,
            VkBuffer vertexBuffer, VkBuffer indexBuffer, uint indexLength,
            VkPipelineLayout pipelineLayout, VkDescriptorSet descriptorSet)
        {
            VkCommandBuffer[] buffers;
            {
                VkCommandPool pool;
                {
                    var info = new VkCommandPoolCreateInfo {
                        sType = VkStructureType.CommandPoolCreateInfo
                    };
                    info.flags = VkCommandPoolCreateFlagBits.ResetCommandBuffer;
                    //var commandPool = device.CreateCommandPool(ref poolInfo);
                    vkCreateCommandPool(device, &info, null, &pool).Check();
                }
                {
                    var info = new VkCommandBufferAllocateInfo {
                        sType = VkStructureType.CommandBufferAllocateInfo
                    };
                    info.level              = VkCommandBufferLevel.Primary;
                    info.commandPool        = pool;
                    info.commandBufferCount = (uint)images.Length;
                    //buffers = device.AllocateCommandBuffers(ref info);
                    buffers = new VkCommandBuffer[info.commandBufferCount];
                    fixed(VkCommandBuffer *pointer = buffers)
                    {
                        vkAPI.vkAllocateCommandBuffers(device, &info, pointer).Check();
                    }
                }
            }

            var cmdBeginInfo = new VkCommandBufferBeginInfo {
                sType = VkStructureType.CommandBufferBeginInfo
            };
            var clearValue = new VkClearValue {
                color = new VkClearColorValue(0.9f, 0.87f, 0.75f, 1.0f)
            };
            var begin = new VkRenderPassBeginInfo {
                sType = VkStructureType.RenderPassBeginInfo
            };

            begin.renderPass  = renderPass;
            begin.clearValues = clearValue;
            begin.renderArea  = new VkRect2D {
                extent = surfaceCapabilities.currentExtent
            };
            for (int i = 0; i < images.Length; i++)
            {
                VkCommandBuffer cmds = buffers[i];
                //cmds.Begin(ref cmdBeginInfo);
                vkAPI.vkBeginCommandBuffer(cmds, &cmdBeginInfo).Check();
                begin.framebuffer = framebuffers[i];
                vkAPI.vkCmdBeginRenderPass(cmds, &begin, VkSubpassContents.Inline);
                vkAPI.vkCmdBindDescriptorSets(cmds, VkPipelineBindPoint.Graphics, pipelineLayout,
                                              0, 1, &descriptorSet,
                                              0, null);
                vkAPI.vkCmdBindPipeline(cmds, VkPipelineBindPoint.Graphics, pipeline);
                VkDeviceSize offset = 0;
                vkAPI.vkCmdBindVertexBuffers(cmds, 0, 1, &vertexBuffer, &offset);
                vkAPI.vkCmdBindIndexBuffer(cmds, indexBuffer, offset, VkIndexType.Uint16);
                vkAPI.vkCmdDrawIndexed(cmds, indexLength, 1, 0, 0, 0);
                vkAPI.vkCmdEndRenderPass(cmds);
                vkAPI.vkEndCommandBuffer(cmds).Check();
            }

            begin.Free();

            return(buffers);
        }
Exemple #30
0
        private void createGraphicsPipeline()
        {
            var vertShaderModule = createShaderModule(typeof(Shader_Vert_03));
            var fragShaderModule = createShaderModule(typeof(Shader_Frag_03));

            VkPipelineShaderStageCreateInfo vertShaderStageInfo = new VkPipelineShaderStageCreateInfo();

            vertShaderStageInfo.sType  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
            vertShaderStageInfo.stage  = VkShaderStageFlagBits.VK_SHADER_STAGE_VERTEX_BIT;
            vertShaderStageInfo.module = vertShaderModule;
            vertShaderStageInfo.pName  = "main";

            VkPipelineShaderStageCreateInfo fragShaderStageInfo = new VkPipelineShaderStageCreateInfo();

            fragShaderStageInfo.sType  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
            fragShaderStageInfo.stage  = VkShaderStageFlagBits.VK_SHADER_STAGE_FRAGMENT_BIT;
            fragShaderStageInfo.module = fragShaderModule;
            fragShaderStageInfo.pName  = "main";

            VkPipelineShaderStageCreateInfo[] shaderStages = new VkPipelineShaderStageCreateInfo[2] {
                vertShaderStageInfo, fragShaderStageInfo
            };

            VkPipelineVertexInputStateCreateInfo vertexInputInfo = new VkPipelineVertexInputStateCreateInfo();

            vertexInputInfo.sType = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;

            var bindingDescription    = Vertex.getBindingDescription();
            var attributeDescriptions = Vertex.getAttributeDescriptions();

            vertexInputInfo.vertexBindingDescriptionCount   = 1;
            vertexInputInfo.vertexAttributeDescriptionCount = attributeDescriptions.Length;
            vertexInputInfo.pVertexBindingDescriptions      = new VkVertexInputBindingDescription[] { bindingDescription };
            vertexInputInfo.pVertexAttributeDescriptions    = attributeDescriptions;

            VkPipelineInputAssemblyStateCreateInfo inputAssembly = new VkPipelineInputAssemblyStateCreateInfo();

            inputAssembly.sType    = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
            inputAssembly.topology = VkPrimitiveTopology.VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
            inputAssembly.primitiveRestartEnable = VkBool32.VK_FALSE;

            VkViewport viewport = new VkViewport();

            viewport.x        = 0.0f;
            viewport.y        = 0.0f;
            viewport.width    = (float)swapChainExtent.width;
            viewport.height   = (float)swapChainExtent.height;
            viewport.minDepth = 0.0f;
            viewport.maxDepth = 1.0f;

            VkRect2D scissor = new VkRect2D();

            scissor.offset = new VkOffset2D()
            {
                x = 0, y = 0
            };
            scissor.extent = swapChainExtent;

            VkPipelineViewportStateCreateInfo viewportState = new VkPipelineViewportStateCreateInfo();

            viewportState.sType         = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
            viewportState.viewportCount = 1;
            viewportState.pViewports    = new VkViewport[] { viewport };
            viewportState.scissorCount  = 1;
            viewportState.pSicssors     = new VkRect2D[] { scissor };

            VkPipelineRasterizationStateCreateInfo rasterizer = new VkPipelineRasterizationStateCreateInfo();

            rasterizer.sType                   = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
            rasterizer.depthClampEnable        = VkBool32.VK_FALSE;
            rasterizer.rasterizerDiscardEnable = VkBool32.VK_FALSE;
            rasterizer.polygonMode             = VkPolygonMode.VK_POLYGON_MODE_FILL;
            rasterizer.lineWidth               = 1.0f;
            rasterizer.cullMode                = VkCullModeFlagBits.VK_CULL_MODE_BACK_BIT;
            rasterizer.frontFace               = VkFrontFace.VK_FRONT_FACE_CLOCKWISE;
            rasterizer.depthBiasEnable         = VkBool32.VK_FALSE;

            VkPipelineMultisampleStateCreateInfo multisampling = new VkPipelineMultisampleStateCreateInfo();

            multisampling.sType = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
            multisampling.sampleShadingEnable  = VkBool32.VK_FALSE;
            multisampling.rasterizationSamples = VkSampleCountFlagBits.VK_SAMPLE_COUNT_1_BIT;

            VkPipelineColorBlendAttachmentState colorBlendAttachment = new VkPipelineColorBlendAttachmentState();

            colorBlendAttachment.colorWriteMask = VkColorComponentFlagBits.VK_COLOR_COMPONENT_R_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_G_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_B_BIT | VkColorComponentFlagBits.VK_COLOR_COMPONENT_A_BIT;
            colorBlendAttachment.blendEnable    = VkBool32.VK_FALSE;

            VkPipelineColorBlendStateCreateInfo colorBlending = VkPipelineColorBlendStateCreateInfo.Create();

            colorBlending.sType             = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
            colorBlending.logicOpEnable     = VkBool32.VK_FALSE;
            colorBlending.logicOp           = VkLogicOp.VK_LOGIC_OP_COPY;
            colorBlending.attachmentCount   = 1;
            colorBlending.pAttachments      = new VkPipelineColorBlendAttachmentState[] { colorBlendAttachment };
            colorBlending.blendConstants[0] = 0.0f;
            colorBlending.blendConstants[1] = 0.0f;
            colorBlending.blendConstants[2] = 0.0f;
            colorBlending.blendConstants[3] = 0.0f;

            VkPipelineLayoutCreateInfo pipelineLayoutInfo = new VkPipelineLayoutCreateInfo();

            pipelineLayoutInfo.sType                  = VkStructureType.VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
            pipelineLayoutInfo.setLayoutCount         = 0;
            pipelineLayoutInfo.pushConstantRangeCount = 0;

            VkResult result = Vulkan.vkCreatePipelineLayout(device, pipelineLayoutInfo, null, out pipelineLayout);

            if (result != VkResult.VK_SUCCESS)
            {
                throw Program.Throw("failed to create pipeline layout!");
            }

            VkGraphicsPipelineCreateInfo pipelineInfo = new VkGraphicsPipelineCreateInfo();

            pipelineInfo.sType               = VkStructureType.VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
            pipelineInfo.stageCount          = shaderStages.Length;
            pipelineInfo.pStages             = shaderStages;
            pipelineInfo.pVertexInputState   = vertexInputInfo;
            pipelineInfo.pInputAssemblyState = inputAssembly;
            pipelineInfo.pViewportState      = viewportState;
            pipelineInfo.pRasterizationState = rasterizer;
            pipelineInfo.pMultisampleState   = multisampling;
            pipelineInfo.pColorBlendState    = colorBlending;
            pipelineInfo.layout              = pipelineLayout;
            pipelineInfo.renderPass          = renderPass;
            pipelineInfo.subpass             = 0;
            pipelineInfo.basePipelineHandle  = null;

            VkPipeline[] pipelineResult = new VkPipeline[1];
            result = Vulkan.vkCreateGraphicsPipelines(device, null, 1, new VkGraphicsPipelineCreateInfo[] { pipelineInfo }, null, pipelineResult);
            if (result != VkResult.VK_SUCCESS)
            {
                throw Program.Throw("failed to create graphics pipeline!", result);
            }

            graphicsPipeline = pipelineResult[0];

            Vulkan.vkDestroyShaderModule(device, fragShaderModule, null);
            Vulkan.vkDestroyShaderModule(device, vertShaderModule, null);
        }