/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "Scene/SimpleDrawable.hpp"
#include "Scene/Material.hpp"
#include "VulkanGeometry.hpp"
#include "VulkanNode.hpp"
#include "Vulkan/VulkanDrawContext.hpp"
#include "Vulkan/Scene/VulkanUniformBuffer.hpp"
#include "VulkanTexture.hpp"

using namespace OpenVulkano::Scene;

namespace OpenVulkano::Vulkan
{
	void EncodeSimpleDrawable(Drawable* instance, Vulkan::VulkanDrawContext* drawContext)
	{
		SimpleDrawable* drawable = static_cast<SimpleDrawable*>(instance);
		Geometry* mesh = drawable->GetMesh();
		VulkanGeometry* renderGeo = mesh->GetRenderResource();
		if (!renderGeo) renderGeo = drawContext->renderer->GetResourceManager().PrepareGeometry(mesh);
		renderGeo->RecordBind(drawContext->commandBuffer);

		if (drawable->GetBuffer())
		{
			VulkanUniformBuffer* vkBuffer = drawable->GetBuffer()->GetRenderResource();
			if (!vkBuffer)
			{
				vkBuffer = drawContext->renderer->GetResourceManager().PrepareUniformBuffer(drawable->GetBuffer());
			}
			vkBuffer->Record(drawContext);
		}

		if (Material* material = drawable->GetMaterial())
		{
			if (Texture* texture = material->texture)
			{
				VulkanTexture* renderTexture = texture->GetRenderResource();
				if (!renderTexture)
				{
					drawContext->renderer->GetResourceManager().PrepareMaterial(drawable->GetMaterial());
					renderTexture = texture->GetRenderResource();
				}
				renderTexture->Record(drawContext);
			}
		}

		for(Node* node : instance->GetNodes())
		{
			if (!node->IsEnabled()) [[unlikely]] continue;
			drawContext->EncodeNode(node);
			renderGeo->RecordDraw(drawContext->commandBuffer);
		}
	}
}

namespace
{
	void* simpleDrawableVulkanEncoderReg = DrawEncoder::RegisterVulkanEncodeFunction<SimpleDrawable>(&OpenVulkano::Vulkan::EncodeSimpleDrawable);
}