Ejemplo n.º 1
0
        public override void Activate()
        {
            if (state != ActivableState.Activated)
            {
                List <VkSubpassDescription> spDescs = new List <VkSubpassDescription> ();
                foreach (SubPass sp in subpasses)
                {
                    spDescs.Add(sp.SubpassDescription);
                }

                VkRenderPassCreateInfo renderPassInfo = VkRenderPassCreateInfo.New();
                renderPassInfo.attachmentCount = (uint)attachments.Count;
                renderPassInfo.pAttachments    = attachments.Pin();
                renderPassInfo.subpassCount    = (uint)spDescs.Count;
                renderPassInfo.pSubpasses      = spDescs.Pin();
                renderPassInfo.dependencyCount = (uint)dependencies.Count;
                renderPassInfo.pDependencies   = dependencies.Pin();

                handle = Dev.CreateRenderPass(renderPassInfo);

                foreach (SubPass sp in subpasses)
                {
                    sp.UnpinLists();
                }

                attachments.Unpin();
                spDescs.Unpin();
                dependencies.Unpin();
            }
            base.Activate();
        }
Ejemplo n.º 2
0
        internal void CreateRenderPass()
        {
            VkFormat ColorFormat = NativeDevice.NativeSwapChain.VkColorFormat;


            VkAttachmentDescription colorAttachment = new VkAttachmentDescription()
            {
                format         = ColorFormat,
                samples        = VkSampleCountFlags.Count1,
                loadOp         = VkAttachmentLoadOp.Clear,
                storeOp        = VkAttachmentStoreOp.Store,
                stencilLoadOp  = VkAttachmentLoadOp.DontCare,
                stencilStoreOp = VkAttachmentStoreOp.DontCare,
                initialLayout  = VkImageLayout.Undefined,
                finalLayout    = VkImageLayout.PresentSrcKHR,
            };


            VkAttachmentReference colorAttachmentRef = new VkAttachmentReference()
            {
                attachment = 0,
                layout     = VkImageLayout.ColorAttachmentOptimal,
            };


            VkSubpassDescription subpass = new VkSubpassDescription()
            {
                pipelineBindPoint    = VkPipelineBindPoint.Graphics,
                colorAttachmentCount = 1,
                pColorAttachments    = &colorAttachmentRef,
            };


            VkSubpassDependency dependency = new VkSubpassDependency()
            {
                srcSubpass    = SubpassExternal,
                dstSubpass    = 0,
                srcStageMask  = VkPipelineStageFlags.ColorAttachmentOutput,
                srcAccessMask = 0,
                dstStageMask  = VkPipelineStageFlags.ColorAttachmentOutput,
                dstAccessMask = VkAccessFlags.ColorAttachmentRead | VkAccessFlags.ColorAttachmentWrite,
            };


            VkRenderPassCreateInfo renderPassCI = new VkRenderPassCreateInfo()
            {
                sType           = VkStructureType.RenderPassCreateInfo,
                attachmentCount = 1,
                pAttachments    = &colorAttachment,
                subpassCount    = 1,
                pSubpasses      = &subpass,
                dependencyCount = 1,
                pDependencies   = &dependency,
            };



            vkCreateRenderPass(NativeDevice.Device, ref renderPassCI, null, out var RenderPass);
            NativeRenderPass = RenderPass;
        }
Ejemplo n.º 3
0
        public static VkResult vkCreateFramebuffer(
            VkDevice device,
            VkRenderPass renderPass,
            ReadOnlySpan <VkImageView> attachments,
            uint width,
            uint height,
            uint layers,
            out VkFramebuffer framebuffer)
        {
            fixed(VkImageView *attachmentsPtr = attachments)
            {
                VkFramebufferCreateInfo createInfo = new VkFramebufferCreateInfo
                {
                    sType           = VkStructureType.FramebufferCreateInfo,
                    renderPass      = renderPass,
                    attachmentCount = (uint)attachments.Length,
                    pAttachments    = attachmentsPtr,
                    width           = width,
                    height          = height,
                    layers          = layers
                };

                return(vkCreateFramebuffer(device, &createInfo, null, out framebuffer));
            }
        }
Ejemplo n.º 4
0
        private void CreateRenderPass()
        {
            var colorAttachment = new VkAttachmentDescription()
            {
                format         = vkSwapChainImageFormat,
                samples        = VkSampleCountFlagBits.VK_SAMPLE_COUNT_1_BIT,
                loadOp         = VkAttachmentLoadOp.VK_ATTACHMENT_LOAD_OP_CLEAR,
                storeOp        = VkAttachmentStoreOp.VK_ATTACHMENT_STORE_OP_STORE,
                stencilLoadOp  = VkAttachmentLoadOp.VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                stencilStoreOp = VkAttachmentStoreOp.VK_ATTACHMENT_STORE_OP_DONT_CARE,
                initialLayout  = VkImageLayout.VK_IMAGE_LAYOUT_UNDEFINED,
                finalLayout    = VkImageLayout.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
            };

            var colorAttachmentRef = new VkAttachmentReference()
            {
                attachment = 0,
                layout     = VkImageLayout.VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            };

            var subpass = new VkSubpassDescription()
            {
                pipelineBindPoint    = VkPipelineBindPoint.VK_PIPELINE_BIND_POINT_GRAPHICS,
                colorAttachmentCount = 1,
                pColorAttachments    = &colorAttachmentRef,
            };

            var dependency = new VkSubpassDependency()
            {
                srcSubpass    = VK_SUBPASS_EXTERNAL,
                srcStageMask  = VkPipelineStageFlagBits.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                srcAccessMask = 0,

                dstSubpass    = 0,
                dstStageMask  = VkPipelineStageFlagBits.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                dstAccessMask = VkAccessFlagBits.VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
            };

            var renderPassInfo = new VkRenderPassCreateInfo()
            {
                sType           = VkStructureType.VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
                attachmentCount = 1,
                pAttachments    = &colorAttachment,
                subpassCount    = 1,
                pSubpasses      = &subpass,
                dependencyCount = 1,
                pDependencies   = &dependency,
            };

            VkRenderPass newRenderPass;
            var          result = VulkanNative.vkCreateRenderPass(vkDevice, &renderPassInfo, null, &newRenderPass);

            vkRenderPass = newRenderPass;
            Helpers.CheckErrors(result);
        }
Ejemplo n.º 5
0
        private void BeginCurrentRenderPass()
        {
            Debug.Assert(_activeRenderPass == VkRenderPass.Null);

            VkRenderPassBeginInfo renderPassBI = VkRenderPassBeginInfo.New();

            renderPassBI.framebuffer = _currentFramebuffer.CurrentFramebuffer;
            renderPassBI.renderPass  = _currentFramebuffer.RenderPass;
            renderPassBI.renderArea  = new VkRect2D(_currentFramebuffer.Width, _currentFramebuffer.Height);
            vkCmdBeginRenderPass(_cb, ref renderPassBI, VkSubpassContents.Inline);
            _activeRenderPass = _currentFramebuffer.RenderPass;
        }
Ejemplo n.º 6
0
        public static VkGraphicsPipelineCreateInfo pipelineCreateInfo(
            VkPipelineLayout layout,
            VkRenderPass renderPass,
            VkPipelineCreateFlags flags = 0)
        {
            VkGraphicsPipelineCreateInfo pipelineCreateInfo = VkGraphicsPipelineCreateInfo.New();

            pipelineCreateInfo.layout             = layout;
            pipelineCreateInfo.renderPass         = renderPass;
            pipelineCreateInfo.flags              = flags;
            pipelineCreateInfo.basePipelineIndex  = -1;
            pipelineCreateInfo.basePipelineHandle = new VkPipeline();
            return(pipelineCreateInfo);
        }
Ejemplo n.º 7
0
        void CreateRenderPass()
        {
            var colorAttachment = new VkAttachmentDescription();

            colorAttachment.format         = swapchainImageFormat;
            colorAttachment.samples        = VkSampleCountFlags._1_Bit;
            colorAttachment.loadOp         = VkAttachmentLoadOp.Clear;
            colorAttachment.storeOp        = VkAttachmentStoreOp.Store;
            colorAttachment.stencilLoadOp  = VkAttachmentLoadOp.DontCare;
            colorAttachment.stencilStoreOp = VkAttachmentStoreOp.DontCare;
            colorAttachment.initialLayout  = VkImageLayout.Undefined;
            colorAttachment.finalLayout    = VkImageLayout.PresentSrcKhr;

            var colorAttachmentRef = new VkAttachmentReference();

            colorAttachmentRef.attachment = 0;
            colorAttachmentRef.layout     = VkImageLayout.ColorAttachmentOptimal;

            var subpass = new VkSubpassDescription();

            subpass.pipelineBindPoint = VkPipelineBindPoint.Graphics;
            subpass.colorAttachments  = new List <VkAttachmentReference> {
                colorAttachmentRef
            };

            var dependency = new VkSubpassDependency();

            dependency.srcSubpass    = -1; //VK_SUBPASS_EXTERNAL
            dependency.dstSubpass    = 0;
            dependency.srcStageMask  = VkPipelineStageFlags.BottomOfPipeBit;
            dependency.srcAccessMask = VkAccessFlags.MemoryReadBit;
            dependency.dstStageMask  = VkPipelineStageFlags.ColorAttachmentOutputBit;
            dependency.dstAccessMask = VkAccessFlags.ColorAttachmentReadBit
                                       | VkAccessFlags.ColorAttachmentWriteBit;

            var info = new VkRenderPassCreateInfo();

            info.attachments = new List <VkAttachmentDescription> {
                colorAttachment
            };
            info.subpasses = new List <VkSubpassDescription> {
                subpass
            };
            info.dependencies = new List <VkSubpassDependency> {
                dependency
            };

            renderPass?.Dispose();
            renderPass = new VkRenderPass(device, info);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        private void EndCurrentRenderPass()
        {
            Debug.Assert(_activeRenderPass != VkRenderPass.Null);
            vkCmdEndRenderPass(_cb);
            _activeRenderPass = VkRenderPass.Null;

            // Place a barrier between RenderPasses, so that color / depth outputs
            // can be read in subsequent passes.
            vkCmdPipelineBarrier(
                _cb,
                VkPipelineStageFlags.BottomOfPipe,
                VkPipelineStageFlags.TopOfPipe,
                VkDependencyFlags.None,
                0,
                null,
                0,
                null,
                0,
                null);
        }
Ejemplo n.º 10
0
        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();
        }
Ejemplo n.º 11
0
        static VkFramebuffer CreateFramebuffer(VkDevice device, VkRenderPass pass, VkImageView imageView, VkImageView depthImageView)
        {
            VkImageView[] imageViews = new VkImageView[] {
                imageView,
                depthImageView
            };

            VkFramebufferCreateInfo createInfo = VkFramebufferCreateInfo.New();

            createInfo.renderPass      = pass;
            createInfo.attachmentCount = (uint)imageViews.Length;

            fixed(VkImageView *ptr = imageViews)
            createInfo.pAttachments = ptr;

            createInfo.width  = (uint)width;
            createInfo.height = (uint)height;
            createInfo.layers = 1;

            VkFramebuffer framebuffer = VkFramebuffer.Null;

            Assert(vkCreateFramebuffer(device, &createInfo, null, &framebuffer));
            return(framebuffer);
        }
Ejemplo n.º 12
0
        public static VkResult vkCreateRenderPass(VkDevice device, VkRenderPassCreateInfo renderPassInfo, VkAllocationCallbacks pAllocator, out VkRenderPass renderPass)
        {
            VkPreconditions.CheckNull(device, nameof(device));

            return(GetDevice(device).CreateRenderPass(renderPassInfo, out renderPass));
        }
Ejemplo n.º 13
0
        public Framebuffer(VkDevice Device, int Width, int Height)
        {
            _Device           = Device;
            _Width            = Width;
            _Height           = Height;
            _FrameBufferColor = _Device.CreateImage(VkImageCreateFlag.NONE,
                                                    VkFormat.VK_FORMAT_B8G8R8A8_SRGB,
                                                    Width, Height,
                                                    1, 1,
                                                    VkSampleCountFlag.VK_SAMPLE_COUNT_1,
                                                    VkImageTiling.VK_IMAGE_TILING_OPTIMAL,
                                                    VkImageUsageFlag.VK_IMAGE_USAGE_COLOR_ATTACHMENT,
                                                    VkSharingMode.VK_SHARING_MODE_EXCLUSIVE,
                                                    null,
                                                    VkImageLayout.VK_IMAGE_LAYOUT_UNDEFINED);

            _ImageSize = _FrameBufferColor.MemoryRequirements.size;


            // We will back this image with Device Accessible Memomy so we can map it an copy
            // the content from the Host.
            // To do so we need to find the right memory type first.
            VkMemoryType deviceMemory = new VkMemoryType();

            foreach (VkMemoryType memoryType in _FrameBufferColor.MemoryRequirements.memoryTypes)
            {
                // Pick the first memory type that can be mapped into host memory
                if ((memoryType.propertyFlags & VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_DEVICE_LOCAL) != 0)
                {
                    deviceMemory = memoryType;
                    break;
                }
            }

            VkDeviceMemory FrameBufferMemory = _Device.AllocateMemory(_FrameBufferColor.MemoryRequirements.size, deviceMemory);

            _FrameBufferColor.BindMemory(FrameBufferMemory, 0);

            // Allocate the host visible memory to transfer the framebuffer
            _TransferBuffer = _Device.CreateBuffer(0, _FrameBufferColor.MemoryRequirements.size, VkBufferUsageFlag.VK_BUFFER_USAGE_TRANSFER_DST, VkSharingMode.VK_SHARING_MODE_EXCLUSIVE, new VkQueueFamilyProperties[] { _Device.Queues[0].Family });

            // We will use a host visible buffer so we can map it an copy
            // the content from the Host.
            // To do so we need to find the right memory type first.
            VkMemoryType hostMemory = new VkMemoryType();

            foreach (VkMemoryType memoryType in _TransferBuffer.MemoryRequirements.memoryTypes)
            {
                // Pick the first memory type that can be mapped into host memory
                if ((memoryType.propertyFlags & VkMemoryPropertyFlags.VK_MEMORY_PROPERTY_HOST_VISIBLE) != 0)
                {
                    hostMemory = memoryType;
                    break;
                }
            }

            VkDeviceMemory TransferBufferMemory = _Device.AllocateMemory(_ImageSize, hostMemory);

            _TransferBuffer.BindMemory(TransferBufferMemory, 0);
            _TransferBufferPtr = TransferBufferMemory.Map(0, _ImageSize, VkMemoryMapFlag.NONE);


            VkImageView imageView = _FrameBufferColor.CreateImageView(VkImageViewType.VK_IMAGE_VIEW_TYPE_2D, new VkImageSubresourceRange()
            {
                aspectMask = VkImageAspectFlag.VK_IMAGE_ASPECT_COLOR_BIT, baseArrayLayer = 0, baseMipLevel = 0, layerCount = 1, levelCount = 1
            });


            VkAttachmentDescription colorAttachment = new VkAttachmentDescription();

            colorAttachment.format         = _FrameBufferColor.Format;
            colorAttachment.samples        = VkSampleCountFlag.VK_SAMPLE_COUNT_1;
            colorAttachment.loadOp         = VkAttachmentLoadOp.VK_ATTACHMENT_LOAD_OP_CLEAR;
            colorAttachment.storeOp        = VkAttachmentStoreOp.VK_ATTACHMENT_STORE_OP_STORE;
            colorAttachment.stencilLoadOp  = VkAttachmentLoadOp.VK_ATTACHMENT_LOAD_OP_DONT_CARE;
            colorAttachment.stencilStoreOp = VkAttachmentStoreOp.VK_ATTACHMENT_STORE_OP_DONT_CARE;
            colorAttachment.initialLayout  = VkImageLayout.VK_IMAGE_LAYOUT_UNDEFINED;
            colorAttachment.finalLayout    = VkImageLayout.VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

            VkAttachmentReference colorAttachmentReference = new VkAttachmentReference();

            colorAttachmentReference.attachment = 0;
            colorAttachmentReference.layout     = VkImageLayout.VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

            VkSubpassDescription subpass = new VkSubpassDescription();

            subpass.pipelineBindPoint      = VkPipelineBindPoint.VK_PIPELINE_BIND_POINT_GRAPHICS;
            subpass.colorAttachments       = new VkAttachmentReference[] { colorAttachmentReference };
            subpass.depthStencilAttachment = null;
            subpass.inputAttachments       = null;
            subpass.preserveAttachments    = null;
            subpass.resolveAttachments     = null;

            VkSubpassDependency dependency = new VkSubpassDependency();

            dependency.srcSubpass    = VkSubpassDependency.VK_SUBPASS_EXTERNAL;
            dependency.dstSubpass    = 0;
            dependency.srcStageMask  = VkPipelineStageFlag.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT;
            dependency.srcAccessMask = 0;
            dependency.dstStageMask  = VkPipelineStageFlag.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT;
            dependency.dstAccessMask = VkAccessFlag.VK_ACCESS_COLOR_ATTACHMENT_READ | VkAccessFlag.VK_ACCESS_COLOR_ATTACHMENT_WRITE;

            _RenderPass = _Device.CreateRenderPass(new VkAttachmentDescription[] { colorAttachment },
                                                   new VkSubpassDescription[] { subpass },
                                                   new VkSubpassDependency[] { dependency });

            _Framebuffer = _Device.CreateFramebuffer(_RenderPass, new VkImageView[] { imageView }, (uint)Width, (uint)Height, 1);
        }
Ejemplo n.º 14
0
 private void EndCurrentRenderPass()
 {
     Debug.Assert(_activeRenderPass != VkRenderPass.Null);
     vkCmdEndRenderPass(_cb);
     _activeRenderPass = VkRenderPass.Null;
 }
Ejemplo n.º 15
0
        public static void vkDestroyRenderPass(VkDevice device, VkRenderPass renderPass, VkAllocationCallbacks pAllocator)
        {
            VkPreconditions.CheckNull(device, nameof(device));

            GetDevice(device).DestroyRenderPass(renderPass);
        }
Ejemplo n.º 16
0
 public static extern void DestroyRenderPass(
     VkDevice device,
     VkRenderPass renderPass,
     IntPtr pAllocator
     );
Ejemplo n.º 17
0
 public static extern void GetRenderAreaGranularity(
     VkDevice device,
     VkRenderPass renderPass,
     out VkExtent2D pGranularity
     );
Ejemplo n.º 18
0
 public static VkResult vkCreateFramebuffer(
     VkDevice device,
     VkRenderPass renderPass,
     ReadOnlySpan <VkImageView> attachments,
     in Size extent,
Ejemplo n.º 19
0
 public static extern VkResult CreateRenderPass(
     VkDevice device,
     ref VkRenderPassCreateInfo pCreateInfo,
     IntPtr pAllocator,
     out VkRenderPass pRenderPass
     );
Ejemplo n.º 20
0
 public RenderPass(Device dev, VkRenderPass handle)
 {
     Device = dev;
     Handle = handle;
 }
Ejemplo n.º 21
0
        VkPipeline CreatePipeline(VkDevice device, VkSurfaceCapabilitiesKHR surfaceCapabilities,
                                  VkRenderPass renderPass, VkPipelineLayout pipelineLayout)
        {
            //VkShaderModule vertexShaderModule = device.CreateShaderModule(LoadResource(@"Shaders\shader.vert.spv"));
            VkShaderModule vsModule;
            {
                var info = new VkShaderModuleCreateInfo {
                    sType = VkStructureType.ShaderModuleCreateInfo
                };
                byte[] bytes = LoadResource(@"Shaders\shader.vert.spv");
                info.code = bytes;
                //vkAPI.vkCreateShaderModule(device, bytes);
                vkAPI.vkCreateShaderModule(device, &info, null, &vsModule).Check();
                info.Free();
            }
            //VkShaderModule fragmentShaderModule = device.CreateShaderModule(LoadResource(@"Shaders\shader.frag.spv"));
            VkShaderModule fsModule;
            {
                var info = new VkShaderModuleCreateInfo {
                    sType = VkStructureType.ShaderModuleCreateInfo
                };
                byte[] bytes = LoadResource(@"Shaders\shader.frag.spv");
                info.code = bytes;
                //vkAPI.vkCreateShaderModule(device, bytes);
                vkAPI.vkCreateShaderModule(device, &info, null, &fsModule).Check();
                info.Free();
            }
            var shaderStages = new VkPipelineShaderStageCreateInfo[2];
            {
                shaderStages[0].sType  = VkStructureType.PipelineShaderStageCreateInfo;
                shaderStages[0].stage  = VkShaderStageFlagBits.Vertex;
                shaderStages[0].module = vsModule;
                //"main".Set(ref shaderStages[0].pName);
                shaderStages[0].pName  = "main";
                shaderStages[1].sType  = VkStructureType.PipelineShaderStageCreateInfo;
                shaderStages[1].stage  = VkShaderStageFlagBits.Fragment;
                shaderStages[1].module = fsModule;
                //"main".Set(ref shaderStages[1].pName);
                shaderStages[1].pName = "main";
            }
            var viewport = new VkPipelineViewportStateCreateInfo {
                sType = VkStructureType.PipelineViewportStateCreateInfo
            };

            viewport.viewports = new VkViewport(surfaceCapabilities.currentExtent, 0.0f, 1.0f);
            viewport.scissors  = new VkRect2D(surfaceCapabilities.currentExtent);

            var multisample = new VkPipelineMultisampleStateCreateInfo {
                sType = VkStructureType.PipelineMultisampleStateCreateInfo
            };

            multisample.rasterizationSamples = VkSampleCountFlagBits._1;

            var colorBlend = new VkPipelineColorBlendStateCreateInfo {
                sType = VkStructureType.PipelineColorBlendStateCreateInfo
            };

            colorBlend.logicOp = VkLogicOp.Copy;
            var blend = new VkPipelineColorBlendAttachmentState(
                colorWriteMask: VkColorComponentFlagBits.R | VkColorComponentFlagBits.G
                | VkColorComponentFlagBits.B | VkColorComponentFlagBits.A,
                blendEnable: false);

            colorBlend.attachments = blend;

            var rasterization = new VkPipelineRasterizationStateCreateInfo {
                sType = VkStructureType.PipelineRasterizationStateCreateInfo
            };

            rasterization.polygonMode = VkPolygonMode.Fill;
            rasterization.cullMode    = VkCullModeFlagBits.None;
            rasterization.frontFace   = VkFrontFace.Clockwise;
            rasterization.lineWidth   = 1.0f;

            var inputAssem = new VkPipelineInputAssemblyStateCreateInfo {
                sType = VkStructureType.PipelineInputAssemblyStateCreateInfo
            };

            inputAssem.topology = VkPrimitiveTopology.TriangleList;

            var input = new VkPipelineVertexInputStateCreateInfo {
                sType = VkStructureType.PipelineVertexInputStateCreateInfo
            };

            // static readonly float[] Vertices = { .. }
            input.vertexBindingDescriptions = new VkVertexInputBindingDescription(
                binding: 0,
                stride: 2 * sizeof(float),
                inputRate: VkVertexInputRate.Vertex);
            // layout(location = 0) in vec2 inPos;
            input.vertexAttributeDescriptions = new VkVertexInputAttributeDescription(
                location: 0,
                binding: 0,
                format: VkFormat.R32g32Sfloat,
                offset: 0);

            //VkPipelineCache cache = device.CreatePipelineCache(ref cacheInfo);
            VkPipelineCache cache;
            {
                var info = VkPipelineCacheCreateInfo.Alloc();
                vkAPI.vkCreatePipelineCache(device, info, null, &cache).Check();
                Marshal.FreeHGlobal((IntPtr)info);
            }
            //var infos = new VkGraphicsPipelineCreateInfo[] { pipelineCreateInfo };
            //return device.CreateGraphicsPipelines(ref cache, infos);
            VkPipeline pipeline;

            {
                var info = new VkGraphicsPipelineCreateInfo {
                    sType = VkStructureType.GraphicsPipelineCreateInfo
                };
                info.layout              = pipelineLayout;
                info.pViewportState      = &viewport;
                info.stages              = shaderStages;
                info.pMultisampleState   = &multisample;
                info.pColorBlendState    = &colorBlend;
                info.pRasterizationState = &rasterization;
                info.pInputAssemblyState = &inputAssem;
                info.pVertexInputState   = &input;
                info.renderPass          = renderPass;
                vkAPI.vkCreateGraphicsPipelines(device, cache, 1, &info, null, &pipeline).Check();
                info.Free();
            }

            shaderStages[0].Free();
            shaderStages[1].Free();
            viewport.Free();
            colorBlend.Free();
            input.Free();

            return(pipeline);
        }
Ejemplo n.º 22
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;
        }
Ejemplo n.º 23
0
 public abstract VkResult CreateRenderPass(VkRenderPassCreateInfo renderPassInfo, out VkRenderPass renderPass);
Ejemplo n.º 24
0
 public RenderPass(GraphicsDevice device)
 {
     vkRenderPass = default;
     this.device  = device;
 }
Ejemplo n.º 25
0
        private void BeginCurrentRenderPass()
        {
            Debug.Assert(_activeRenderPass == VkRenderPass.Null);
            Debug.Assert(_currentFramebuffer != null);
            _currentFramebufferEverActive = true;

            uint attachmentCount    = _currentFramebuffer.AttachmentCount;
            bool haveAnyAttachments = _currentFramebuffer.ColorTargets.Count > 0 || _currentFramebuffer.DepthTarget != null;
            bool haveAllClearValues = _depthClearValue.HasValue || _currentFramebuffer.DepthTarget == null;
            bool haveAnyClearValues = _depthClearValue.HasValue;

            for (int i = 0; i < _currentFramebuffer.ColorTargets.Count; i++)
            {
                if (!_validColorClearValues[i])
                {
                    haveAllClearValues = false;
                    haveAnyClearValues = true;
                }
                else
                {
                    haveAnyClearValues = true;
                }
            }

            VkRenderPassBeginInfo renderPassBI = VkRenderPassBeginInfo.New();

            renderPassBI.renderArea  = new VkRect2D(_currentFramebuffer.RenderableWidth, _currentFramebuffer.RenderableHeight);
            renderPassBI.framebuffer = _currentFramebuffer.CurrentFramebuffer;

            if (!haveAnyAttachments || !haveAllClearValues)
            {
                renderPassBI.renderPass = _newFramebuffer
                    ? _currentFramebuffer.RenderPassNoClear_Init
                    : _currentFramebuffer.RenderPassNoClear_Load;
                vkCmdBeginRenderPass(_cb, ref renderPassBI, VkSubpassContents.Inline);
                _activeRenderPass = renderPassBI.renderPass;

                if (haveAnyClearValues)
                {
                    if (_depthClearValue.HasValue)
                    {
                        ClearDepthStencil(_depthClearValue.Value.depthStencil.depth, (byte)_depthClearValue.Value.depthStencil.stencil);
                        _depthClearValue = null;
                    }

                    for (uint i = 0; i < _currentFramebuffer.ColorTargets.Count; i++)
                    {
                        if (_validColorClearValues[i])
                        {
                            _validColorClearValues[i] = false;
                            VkClearValue vkClearValue = _clearValues[i];
                            RgbaFloat    clearColor   = new RgbaFloat(
                                vkClearValue.color.float32_0,
                                vkClearValue.color.float32_1,
                                vkClearValue.color.float32_2,
                                vkClearValue.color.float32_3);
                            ClearColorTarget(i, clearColor);
                        }
                    }
                }
            }
            else
            {
                // We have clear values for every attachment.
                renderPassBI.renderPass = _currentFramebuffer.RenderPassClear;
                fixed(VkClearValue *clearValuesPtr = &_clearValues[0])
                {
                    renderPassBI.clearValueCount = attachmentCount;
                    renderPassBI.pClearValues    = clearValuesPtr;
                    if (_depthClearValue.HasValue)
                    {
                        _clearValues[_currentFramebuffer.ColorTargets.Count] = _depthClearValue.Value;
                        _depthClearValue = null;
                    }
                    vkCmdBeginRenderPass(_cb, ref renderPassBI, VkSubpassContents.Inline);
                    _activeRenderPass = _currentFramebuffer.RenderPassClear;
                    Util.ClearArray(_validColorClearValues);
                }
            }

            _newFramebuffer = false;
        }
Ejemplo n.º 26
0
 public override void DestroyRenderPass(VkRenderPass renderPass)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 27
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);
        }
Ejemplo n.º 28
0
 public override VkResult CreateRenderPass(VkRenderPassCreateInfo renderPassInfo, out VkRenderPass renderPass)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 29
0
        protected VkFramebuffer[] CreateFramebuffers(VkDevice device, VkImage[] images,
                                                     VkSurfaceFormatKHR surfaceFormat, VkRenderPass renderPass,
                                                     VkSurfaceCapabilitiesKHR surfaceCapabilities)
        {
            var displayViews = new VkImageView[images.Length];
            var viewInfo     = new VkImageViewCreateInfo {
                sType = VkStructureType.ImageViewCreateInfo
            };

            viewInfo.viewType   = VkImageViewType._2d;
            viewInfo.format     = surfaceFormat.format;
            viewInfo.components = new VkComponentMapping {
                r = VkComponentSwizzle.R,
                g = VkComponentSwizzle.G,
                b = VkComponentSwizzle.B,
                a = VkComponentSwizzle.A
            };
            viewInfo.subresourceRange = new VkImageSubresourceRange {
                aspectMask = VkImageAspectFlagBits.Color,
                levelCount = 1,
                layerCount = 1
            };
            for (int i = 0; i < images.Length; i++)
            {
                viewInfo.image = images[i];
                //displayViews[i] = device.CreateImageView(ref info);
                VkImageView view;
                vkAPI.vkCreateImageView(device, &viewInfo, null, &view).Check();
                displayViews[i] = view;
            }

            var framebuffers = new VkFramebuffer[images.Length];
            var fbInfo       = new VkFramebufferCreateInfo {
                sType = VkStructureType.FramebufferCreateInfo
            };

            fbInfo.layers     = 1;
            fbInfo.renderPass = renderPass;
            fbInfo.width      = surfaceCapabilities.currentExtent.width;
            fbInfo.height     = surfaceCapabilities.currentExtent.height;
            for (int i = 0; i < images.Length; i++)
            {
                fbInfo.attachments = displayViews[i];
                //framebuffers[i] = device.CreateFramebuffer(ref info);
                VkFramebuffer framebuffer;
                vkAPI.vkCreateFramebuffer(device, &fbInfo, null, &framebuffer).Check();
                framebuffers[i] = framebuffer;
            }

            fbInfo.Free();

            return(framebuffers);
        }
Ejemplo n.º 30
0
        private void BeginCurrentRenderPass()
        {
            Debug.Assert(_activeRenderPass == VkRenderPass.Null);
            Debug.Assert(_currentFramebuffer != null);
            _currentFramebufferEverActive = true;

            uint attachmentCount    = _currentFramebuffer.AttachmentCount;
            bool haveAnyAttachments = _framebuffer.ColorTargets.Count > 0 || _framebuffer.DepthTarget != null;
            bool haveAllClearValues = _depthClearValue.HasValue || _framebuffer.DepthTarget == null;
            bool haveAnyClearValues = _depthClearValue.HasValue;

            for (int i = 0; i < _currentFramebuffer.ColorTargets.Count; i++)
            {
                if (!_validColorClearValues[i])
                {
                    haveAllClearValues = false;
                    haveAnyClearValues = true;
                }
                else
                {
                    haveAnyClearValues = true;
                }
            }

            VkRenderPassBeginInfo renderPassBI = VkRenderPassBeginInfo.New();

            renderPassBI.renderArea  = new VkRect2D(_currentFramebuffer.RenderableWidth, _currentFramebuffer.RenderableHeight);
            renderPassBI.framebuffer = _currentFramebuffer.CurrentFramebuffer;

            if (!haveAnyAttachments || !haveAllClearValues)
            {
                renderPassBI.renderPass = _currentFramebuffer.RenderPassNoClear;
                vkCmdBeginRenderPass(_cb, ref renderPassBI, VkSubpassContents.Inline);
                _activeRenderPass = _currentFramebuffer.RenderPassNoClear;

                if (haveAnyClearValues)
                {
                    if (_depthClearValue.HasValue)
                    {
                        ClearDepthStencil(_depthClearValue.Value.depthStencil.depth, (byte)_depthClearValue.Value.depthStencil.stencil);
                        _depthClearValue = null;
                    }

                    for (uint i = 0; i < _currentFramebuffer.ColorTargets.Count; i++)
                    {
                        if (_validColorClearValues[i])
                        {
                            _validColorClearValues[i] = false;
                            VkClearValue vkClearValue = _clearValues[i];
                            RgbaFloat    clearColor   = new RgbaFloat(
                                vkClearValue.color.float32_0,
                                vkClearValue.color.float32_1,
                                vkClearValue.color.float32_2,
                                vkClearValue.color.float32_3);
                            ClearColorTarget(i, clearColor);
                        }
                    }
                }
            }
            else
            {
                // We have clear values for every attachment.
                renderPassBI.renderPass = _currentFramebuffer.RenderPassClear;
                fixed(VkClearValue *clearValuesPtr = &_clearValues[0])
                {
                    renderPassBI.clearValueCount = attachmentCount;
                    renderPassBI.pClearValues    = clearValuesPtr;
                    if (_depthClearValue.HasValue)
                    {
                        _clearValues[_currentFramebuffer.ColorTargets.Count] = _depthClearValue.Value;
                    }
                    vkCmdBeginRenderPass(_cb, ref renderPassBI, VkSubpassContents.Inline);
                    _activeRenderPass = _currentFramebuffer.RenderPassClear;
                    Util.ClearArray(_validColorClearValues);
                }
            }

            // Set new image layouts
            foreach (FramebufferAttachment colorTarget in _currentFramebuffer.ColorTargets)
            {
                VkTexture     vkTex  = Util.AssertSubtype <Texture, VkTexture>(colorTarget.Target);
                VkImageLayout layout = (vkTex.Usage & TextureUsage.Sampled) != 0
                    ? VkImageLayout.ShaderReadOnlyOptimal
                    : VkImageLayout.ColorAttachmentOptimal;
                vkTex.SetImageLayout(colorTarget.ArrayLayer, layout);
            }

            if (_currentFramebuffer.DepthTarget != null)
            {
                VkTexture     vkDepthTex = Util.AssertSubtype <Texture, VkTexture>(_currentFramebuffer.DepthTarget.Value.Target);
                VkImageLayout layout     = (vkDepthTex.Usage & TextureUsage.Sampled) != 0
                    ? VkImageLayout.ShaderReadOnlyOptimal
                    : VkImageLayout.DepthStencilAttachmentOptimal;

                vkDepthTex.SetImageLayout(_currentFramebuffer.DepthTarget.Value.ArrayLayer, layout);
            }
        }