Orange/src/Apps/Tools/CubeTest.cpp

408 lines
12 KiB
C++

#include <Orange/Core/Array.h>
#include <Orange/Core/Vector.h>
#include "Orange/Core/Span.h"
#include <Orange/Core/Result.h>
#include <Orange/Core/FileSystem.h>
#include <Orange/Math/Vector.h>
#include <Orange/Math/Matrix.h>
#include <Orange/Core/Parse.h>
#include <Orange/Core/Variant.h>
#include <Orange/Render/Window.h>
#include <Orange/Render/RenderContext.h>
#include <Orange/Render/Swapchain.h>
#include <vs_Triangle.h>
#include <fs_DebugVertColor.h>
using namespace orange;
struct AABB
{
vec3 min;
vec3 max;
void Extend(vec3 pos)
{
min = Min(pos, min);
max = Max(pos, max);
}
};
enum class MeshVertexType
{
Static,
Skinned,
};
struct StaticVertex
{
vec3 pos;
vec2 uv;
vec3 normal;
vec3 tangent;
bool operator == (const StaticVertex& other) const
{
return pos == other.pos &&
uv == other.uv &&
normal == other.normal &&
tangent == other.tangent;
}
};
struct SkinnedVertex : public StaticVertex
{
static constexpr uint32_t MaxVertexWeights = 4;
bool operator == (const SkinnedVertex& other) const
{
return pos == other.pos &&
uv == other.uv &&
normal == other.normal &&
tangent == other.tangent &&
boneIndices == other.boneIndices &&
boneWeights == other.boneWeights;
}
Array<uint8_t, MaxVertexWeights> boneIndices;
Array<uint8_t, MaxVertexWeights> boneWeights;
};
struct MeshData
{
MeshData(MeshVertexType type)
: vertexType(type)
{
switch(type)
{
case MeshVertexType::Static:
vertices.Construct<Vector<StaticVertex>>();
break;
case MeshVertexType::Skinned:
vertices.Construct<Vector<SkinnedVertex>>();
break;
}
}
Vector<StaticVertex>& GetStaticVertices()
{
Assert(vertexType == MeshVertexType::Static);
return vertices.Get<Vector<StaticVertex>>();
}
Vector<SkinnedVertex>& GetSkinnedVertices()
{
Assert(vertexType == MeshVertexType::Skinned);
return vertices.Get<Vector<SkinnedVertex>>();
}
MeshVertexType vertexType;
Variant<Vector<StaticVertex>, Vector<SkinnedVertex>> vertices;
Vector<uint16_t> indices;
AABB bounds;
};
Result<MeshData> ParseOBJ(StringView buffer)
{
MeshData data{ MeshVertexType::Static };
Vector<vec3> positions;
Vector<vec2> uvs;
Vector<vec3> normals;
const char* obj = buffer.data;
const char* end = buffer.data + buffer.size;
while (obj != end)
{
SmallVector<char, 8> element;
stream::ReadString(obj, end, " #\n", element);
if (element == "v" || element == "vt" || element == "vn")
{
float vtx[3]{};
for (int i = 0; i < 3; i++)
{
stream::ConsumeSpace(obj, end);
if (auto r_float = stream::Parse<float>(obj, end))
vtx[i] = *r_float;
else
return Result<MeshData>::Error();
}
if (element == "v")
positions.EmplaceBack(vtx[0], vtx[1], vtx[2]);
else if (element == "vt")
normals.EmplaceBack(vtx[0], vtx[1], vtx[2]);
else if (element == "vn")
uvs.EmplaceBack(vtx[0], vtx[1]);
}
else if (element == "g" || element == "o")
{
stream::ConsumeSpace(obj, end);
SmallVector<char, 32> name;
stream::ReadString(obj, end, " #\n", name);
name.PushBack('\0');
if (element == "g")
log::info("Group name: %s", name.Data());
else
log::info("Object name: %s", name.Data());
}
else if (element == "f")
{
int32_t indices[3][3]{};
for (int i = 0; i < 3; i++)
{
stream::ConsumeSpace(obj, end);
for (int j = 0; j < 3; j++)
{
indices[i][j] = -1;
if (j == 0 || stream::Consume(obj, end, "/"))
{
if (auto r_int = stream::Parse<uint32_t>(obj, end))
indices[i][j] = *r_int;
}
}
}
for (int i = 0; i < 3; i++)
{
StaticVertex vertex =
{
.pos = indices[i][0] != -1 ? positions[indices[i][0]] : vec3{},
.uv = indices[i][1] != -1 ? uvs [indices[i][1]] : vec2{},
.normal = indices[i][2] != -1 ? normals [indices[i][2]] : vec3{},
};
auto& vertices = data.GetStaticVertices();
size_t vertexIdx = vertices.FindIdx(vertex);
if (vertexIdx == vertices.InvalidIdx)
{
data.bounds.Extend(vertex.pos);
vertexIdx = vertices.PushBack(vertex);
}
Assert(vertexIdx < UINT16_MAX);
data.indices.PushBack(uint16_t(vertexIdx));
}
}
else if (!element.Empty())
{
element.PushBack('\0');
log::info("Unknown element: %s", element.Data());
}
stream::AdvancePast(obj, end, "\n");
};
return Result<MeshData>::Success(data);
}
int main(int argc, char** argv)
{
(void)argc; (void)argv;
auto r_window = Window::Create();
if (!r_window)
return 1;
auto r_renderContext = RenderContext::Create("Cube Test");
if (!r_renderContext)
return 1;
auto r_surface = r_window->CreateSurface(r_renderContext->Instance());
if (!r_surface)
return 1;
auto r_swapchain = Swapchain::Create(*r_renderContext, *r_surface);
if (!r_swapchain)
return 1;
auto r_objData = fs::OpenFileIntoTextBuffer("/home/joshua/chair.obj");
if (!r_objData)
return 1;
auto r_mesh = ParseOBJ(*r_objData);
auto r_vs = r_renderContext->CreateShader(vs_Triangle);
if (!r_vs) return 1;
auto r_fs = r_renderContext->CreateShader(fs_DebugVertColor);
if (!r_fs) return 1;
VkPipelineShaderStageCreateInfo stages[] =
{
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_VERTEX_BIT,
.module = *r_vs,
.pName = "main",
},
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
.stage = VK_SHADER_STAGE_FRAGMENT_BIT,
.module = *r_fs,
.pName = "main",
},
};
Array<VkDynamicState, 2> dynamicStates =
{
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR,
};
VkPipelineDynamicStateCreateInfo dynamicStateInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
.dynamicStateCount = uint32_t(dynamicStates.Size()),
.pDynamicStates = dynamicStates.Data(),
};
VkPipelineVertexInputStateCreateInfo vertexInputInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
.vertexBindingDescriptionCount = 0u,
.pVertexBindingDescriptions = nullptr,
.vertexAttributeDescriptionCount = 0u,
.pVertexAttributeDescriptions = nullptr,
};
VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
.primitiveRestartEnable = VK_FALSE,
};
VkPipelineViewportStateCreateInfo viewportStateInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
.viewportCount = 1,
.scissorCount = 1,
};
VkPipelineRasterizationStateCreateInfo rasterizationInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
.cullMode = VK_CULL_MODE_NONE, //VK_CULL_MODE_BACK_BIT,
.frontFace = VK_FRONT_FACE_CLOCKWISE,
};
VkPipelineMultisampleStateCreateInfo multisampleInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
};
VkPipelineColorBlendAttachmentState attachmentBlendState =
{
.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
};
VkPipelineColorBlendStateCreateInfo colorBlendStateInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
.attachmentCount = 1,
.pAttachments = &attachmentBlendState,
};
VkPipelineLayoutCreateInfo pipelineLayoutInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
};
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
vkCreatePipelineLayout(r_renderContext->Device(), &pipelineLayoutInfo, nullptr, &pipelineLayout);
VkFormat format = r_swapchain->Format();
VkPipelineRenderingCreateInfo renderingInfo =
{
.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
.viewMask = 0u,
.colorAttachmentCount = 1u,
.pColorAttachmentFormats = &format,
};
VkGraphicsPipelineCreateInfo pipelineInfo =
{
.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
.pNext = &renderingInfo,
.stageCount = Size(stages),
.pStages = stages,
.pVertexInputState = &vertexInputInfo,
.pInputAssemblyState = &inputAssemblyInfo,
.pViewportState = &viewportStateInfo,
.pRasterizationState = &rasterizationInfo,
.pMultisampleState = &multisampleInfo,
.pDepthStencilState = nullptr,
.pColorBlendState = &colorBlendStateInfo,
.pDynamicState = &dynamicStateInfo,
.layout = pipelineLayout,
};
VkPipeline pipeline = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(r_renderContext->Device(), VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS)
{
log::err("Blah");
return 1;
}
while (r_window->Update())
{
VkCommandBuffer cmdBuf = r_swapchain->CommandBuffer();
r_renderContext->BeginCommandBuffer(cmdBuf);
{
VkViewport viewport =
{
.x = 0.0f,
.y = 0.0f,
.width = float(r_swapchain->Extent().width),
.height = float(r_swapchain->Extent().height),
.minDepth = 0.0f,
.maxDepth = 1.0f,
};
VkRect2D scissor =
{
.offset = {0u, 0u},
.extent = r_swapchain->Extent(),
};
vkCmdSetViewport(cmdBuf, 0, 1, &viewport);
vkCmdSetScissor(cmdBuf, 0, 1, &scissor);
vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
const VkRenderingAttachmentInfoKHR attachmentInfo =
{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR,
.imageView = r_swapchain->ImageView(),
.imageLayout = VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.clearValue = { .color = { .float32 = { 1.0f, 0.5f, 0.0f, 1.0f } } },
};
const VkRenderingInfo renderInfo =
{
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = { {}, r_swapchain->Extent() },
.layerCount = 1,
.colorAttachmentCount = 1,
.pColorAttachments = &attachmentInfo,
};
vkCmdBeginRendering(cmdBuf, &renderInfo);
vkCmdDraw(cmdBuf, 3, 1, 0, 0);
vkCmdEndRendering(cmdBuf);
}
r_renderContext->EndCommandBuffer(cmdBuf);
r_swapchain->Present();
}
return 0;
}