Files
OpenVulkano/openVulkanoCpp/Scene/ObjEncoder.hpp

70 lines
1.9 KiB
C++

/*
* 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/.
*/
#pragma once
#include "Scene/Geometry.hpp"
#include <utility>
#include <string>
#include <sstream>
#include <fmt/core.h>
namespace OpenVulkano::Scene
{
// Returns [objContents, mtlContents]
std::pair<std::string, std::string> GetObjContents(Geometry* geometry, const std::string& texturePath)
{
std::pair<std::string, std::string> result;
bool useTexture = texturePath.size() != 0;
std::stringstream objContent;
objContent << "# OBJ file generated by OpenVulkanoCpp\n";
if (useTexture)
{
std::stringstream mtlContent;
std::string materialName = "Material0";
mtlContent << "newmtl " << materialName << R"(
Ka 1.000 1.000 1.000
Kd 1.000 1.000 1.000
Ks 0.000 0.000 0.000
map_Ka texture.png
map_Kd texture.png
)";
objContent << "mtllib material.mtl\nusemtl " << materialName << "\n";
result.second = mtlContent.str();
}
for (int i = 0; i < geometry->vertexCount; ++i)
{
const auto& v = geometry->vertices[i];
objContent << fmt::format("v {} {} {}\n", v.position.x, v.position.y, v.position.z);
}
for (int i = 0; i < geometry->vertexCount; ++i)
{
const auto& v = geometry->vertices[i];
objContent << fmt::format("vn {} {} {}\n", v.normal.x, v.normal.y, v.normal.z);
}
for (int i = 0; i < geometry->vertexCount; ++i)
{
const auto& v = geometry->vertices[i];
objContent << fmt::format("vt {} {}\n", v.textureCoordinates.x, v.textureCoordinates.y);
}
for (int i = 0; i < geometry->indexCount; i += 3)
{
uint32_t i0 = geometry->GetIndex(i + 0) + 1;
uint32_t i1 = geometry->GetIndex(i + 1) + 1;
uint32_t i2 = geometry->GetIndex(i + 2) + 1;
objContent << fmt::format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n", i0, i1, i2);
}
result.first = objContent.str();
return result;
}
}