/*
	VulkanFramework
	by John Ryland
	Copyright (c) 2023
*/

////////////////////////////////////////////////////////////////////////////////////
//	Vulkan Framebuffer

#include "VulkanFramebuffer.h"
#include "VulkanImageBuffer.h"
#include <cassert>

namespace Vulkan {

Framebuffer::Framebuffer()
    : m_owner(nullptr)
    , m_framebuffer(nullptr)
    , m_width(0)
    , m_height(0)
{
}

// virtual
Framebuffer::~Framebuffer()
{
    Destroy();
}

// virtual
void Framebuffer::Initialize(Device*               device,
                             VkRenderPass          renderPass,
                             ImageBuffer*          buffers[],
                             VkImageView           imageViews[],
                             size_t                count)
{
    m_owner = device;

    // Check the attachments all have the same dimensions
    assert(count);
    m_width = buffers[0]->m_width;
    m_height = buffers[0]->m_height;
    for (int i = 1; i < count; ++i)
    {
        m_owner->CheckResult(m_width == buffers[i]->m_width ? VK_SUCCESS : VK_ERROR_UNKNOWN, "framebuffer attachments have mismatching dimensions");
        m_owner->CheckResult(m_height == buffers[i]->m_height ? VK_SUCCESS : VK_ERROR_UNKNOWN, "framebuffer attachments have mismatching dimensions");
    }

    VkFramebufferCreateInfo framebufferInfo {};
    framebufferInfo.sType           = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
    framebufferInfo.renderPass      = renderPass;
    framebufferInfo.attachmentCount = count;
    framebufferInfo.pAttachments    = imageViews;
    framebufferInfo.width           = m_width;
    framebufferInfo.height          = m_height;
    framebufferInfo.layers          = 1;
    m_owner->CheckResult(vkCreateFramebuffer(m_owner->m_device, &framebufferInfo, nullptr, &m_framebuffer), "failed to create framebuffer!");
}

// virtual
void Framebuffer::Destroy()
{
    if (m_framebuffer)
        vkDestroyFramebuffer(m_owner->m_device, m_framebuffer, nullptr);
    m_framebuffer = nullptr;
}

} // Vulkan namespace
